src/Controller/TunnelGiftController.php line 118
<?php
namespace App\Controller;
use App\Entity\Country;
use App\Entity\GiftCode;
use App\Entity\PaymentMethod;
use App\Entity\PromoCode;
use App\Entity\ReminderUser;
use App\Entity\User;
use App\Entity\UserGiftPayment;
use App\Helper\FacebookSAPI;
use App\Helper\GeoPlugin;
use App\Helper\IpToCountry;
use App\Service\MailchimpAPI;
use App\Service\MailingTransac;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Bundle\SecurityBundle\Security;
#[Route('/{_locale}')]
class TunnelGiftController extends AbstractController
{
private $doctrine;
private $entityManager;
public function __construct(ManagerRegistry $doctrine)
{
$this->doctrine = $doctrine;
$this->entityManager = $this->doctrine->getManager();
}
public static function generateGiftCode($doctrine, UserGiftPayment $payment)
{
$em = $doctrine->getManager();
$paymentMethod = $payment->getPayment();
$codes = $doctrine->getRepository(GiftCode::class)->getUniqueCode($paymentMethod->getQuantite(),$paymentMethod->getMontant(),'achatCadeau');
while($code = array_shift($codes))
{
$payment->addGiftCode($code);
$em->persist($code);
}
$em->flush();
}
protected function getCurrency($country_code){
switch($country_code){
case 'CA':
$currency = '$CAN';
break;
case 'CH':
$currency = "CHF";
break;
case 'MA':
$currency = "MAD";
break;
default:
$currency = "€";
break;
}
return $currency;
}
protected function getUserIsoCode($request, $session)
{
$ipAddress = $request->getClientIp();
if ($session->get('country_iso',null) == null) {
try {
$geo = new GeoPlugin();
$geo->locate($ipAddress);
$countryCode = $geo->countryCode;
if($countryCode == null)
$countryCode = 'FR';
} catch (\Exception $e) {
$countryCode = 'FR';
}
$session->set('country_iso', $countryCode);
} else {
$countryCode = $session->get('country_iso',null);
}
return $countryCode;
}
#[Route('/cadeau/offrir.html', name: 'tunnel_gift_register')]
public function offrir(Request $request): Response
{
$session = $request->getSession();
if ($request->getMethod() == 'POST')
{
if($formule = $request->request->get('subscription',null))
{
$session->set('formule', $formule);
return $this->redirectToRoute('front_gift_facturation');
}
}
TunnelController::detectCountry($request);
TunnelController::setPromoCode($request, $session, $this->doctrine);
$reduction = false;TunnelController::getReduction($session, $this->doctrine);
$url_promo_code = false;$session->get('url_promo_code',false);
$promoCode = false;$session->get('promo_code',false);
$displayReduction = $reduction !== false;
$country_code = $session->get('payment_code');
$currency = $this->getCurrency($country_code);
$prices = $this->doctrine->getRepository(PaymentMethod::class)->getGiftPrices($country_code,$reduction,$url_promo_code);
$formule = $session->get('formule', 'choice2');
$wordsNb = 3500;//$this->doctrine->getRepository(Word::class)->getRoundedCount();
return $this->renderForm('tunnel_gift/choose.html.twig', [
'prices' => $prices,
'currency' => $currency,
'choice' => $formule,
'displayReduction' => $displayReduction,
'codeReduction' => $promoCode,
'montantReduction' => floor($reduction),
'wordsNb' => $wordsNb,
'isPromoUrl' => $url_promo_code
]);
}
#[Route('/cadeau/facturation.html', name: 'front_gift_facturation')]
public function facturation(Request $request): Response
{
$session = $request->getSession();
/** @var User $user */
$user = new User(); //on crée un user vide pour récupérer les informations
/** @var User $currentUser */
$currentUser = $this->getUser();
if($currentUser)
{
$user->setFirstName($currentUser->getFirstName());
$user->setLastName($currentUser->getLastName());
$user->setEmail($currentUser->getEmail());
$user->setAddress($currentUser->getAddress());
$user->setZipCode($currentUser->getZipCode());
$user->setCity($currentUser->getCity());
$user->setEcountry($currentUser->getEcountry());
$country = $user->getEcountry();
if($country == null)
$country = 68;
else
$country = $country->getId();
} else {
$user->setFirstName($session->get('firstName', ""));
$user->setLastName($session->get('lastName', ""));
$user->setEmail($session->get('email', ""));
$user->setAddress($session->get('address', ""));
$user->setZipCode($session->get('zipCode', ""));
$user->setCity($session->get('city', ""));
$user->setEcountry($session->get('country', null));
$country = $session->get('country', "");
if($country == "")
$country = 68;
}
$defaultCountry = $this->doctrine->getRepository(Country::class)->findOneByIsoCode($country);
if(!$defaultCountry)
$defaultCountry = $this->doctrine->getRepository(Country::class)->findOneByCanonicalName('france-metropolitaine');
$user->setECountry($defaultCountry);
$form = $this->createFormBuilder($user, ['validation_groups' => ['facturation'], 'translation_domain' => 'tunnel'])
->add('firstname', TextType::class, ['label' => 'Nom'])
->add('lastname', TextType::class, ['label' => 'Prénom'])
->add('email', EmailType::class)
->add('address', TextType::class, ['label' => 'Adresse'])
->add('zipCode', TextType::class, ['label' => 'Code postal'])
->add('city', TextType::class, ['label' => 'Ville'])
->add('ecountry', EntityType::class, ['class' => Country::class, 'label' => 'Pays', 'choice_label' => 'canonicalName', 'choice_translation_domain' => 'countries'])
->add('save', SubmitType::class, ['label' => 'Continuer'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$user = $form->getData();
$session->set('lastName', $user->getLastName());
$session->set('firstName', $user->getFirstName());
$session->set('email', $user->getEmail());
$session->set('address', $user->getAddress());
$session->set('city', $user->getCity());
$session->set('zipCode', $user->getZipCode());
$session->set('country', $user->getEcountry()->getId());
return $this->redirectToRoute('front_gift_payment');
}
return $this->renderForm('tunnel_gift/billing.html.twig', [
'form' => $form
]);
}
#[Route('/cadeau/paiement.html', name: 'front_gift_payment')]
public function paiement(Request $request): Response
{
$session = $request->getSession();
$type = 'cb';
if($request->getMethod() == 'POST')
{
$type = $request->get('type','cb');
}
$currentChoice = $session->get('formule', null);
if($currentChoice == null)
{
return $this->redirectToRoute('default_price');
}
$payment_id = $this->doctrine->getRepository(PaymentMethod::class)->getChoiceGift($currentChoice,$session);
$paymentMethod = $this->doctrine->getRepository(PaymentMethod::class)->findOneById($payment_id);
if($paymentMethod != null && $paymentMethod->getType() == PaymentMethod::TYPE_CODECADEAU)
{
$prixBase = $prix = $paymentMethod->getValeur();
$reduction = TunnelController::getReduction($session, $this->doctrine);
$url_promo_code = $session->get('url_promo_code',false);
$prix = TunnelController::getPriceReduction($paymentMethod,$prix,$reduction,$url_promo_code);
if(!$url_promo_code || ($url_promo_code && $paymentMethod->getMontant() != 1)){
$displayReduction = $reduction !== false;
}else{
$displayReduction = false;
}
$montant = $paymentMethod->getMontant();
$prixMois = round($prix / $montant, 2, PHP_ROUND_HALF_DOWN);
$prix = number_format($prix, 2, ',', ' ');
$prixBase = number_format($prixBase, 2, ',', ' ');
$prixMois = number_format($prixMois, 2, ',', ' ');
$currency = IpToCountry::getCurrency($session);
$time = $paymentMethod->getMontant();
$country = $this->doctrine->getRepository(Country::class)->findOneById($session->get('country'));
if($country == null)
$country = $this->doctrine->getRepository(Country::class)->findOneByCanonicalName('france-metropolitaine');
return $this->render('tunnel_gift/payment.html.twig', [
'nom' => $session->get('lastName'),
'prenom' => $session->get('firstName'),
'adresse' => $session->get('address'),
'ville' => $session->get('city'),
'zipCode' => $session->get('zipCode'),
'pays' => $country,
'email' => $session->get('email'),
'paymentMethod' => $session->get('formule'),
'paymentType' => $paymentMethod->getType(),
'paymentDuration' => $montant,
'currency' => $currency,
'prix' => $prix,
'prixBase' => $prixBase,
'prixMois' => $prixMois,
'time' => $time,
'displayReduction' => $displayReduction,
'type' => $type,
]);
}
}
#[Route('/cadeau/delayed_payment.html', name: 'gift_delayed_payment')]
public function delayed_payment(Request $request): Response
{
$session = $request->getSession();
/** @var User $user */
$user = $this->getUser();
$formule = $request->request->get('formule',0);
$isTransfer = $request->request->get('transfer',null) != null;
$type = $request->get('type',0);
$currentChoice = $session->get('formule', null);
$payment_id = $this->doctrine->getRepository(PaymentMethod::class)->getChoiceGift($currentChoice,$session);
$paymentMethod = $this->doctrine->getRepository(PaymentMethod::class)->findOneById($payment_id);
if($paymentMethod != null && $paymentMethod->getType() == PaymentMethod::TYPE_CODECADEAU)
{
switch ($type){
case "cheque":
$route = 'gift_subscription_check';
break;
case "virement":
$route = 'gift_subscription_transfer';
break;
}
$time = '' . time() . '';
$sReference = base_convert($time, 10, 36) . '#' . random_int(1, 9999);
$sMontant = $paymentMethod->getValeur();
$reduction = TunnelController::getReduction($session, $this->doctrine);
$displayReduction = $reduction !== false;
$url_promo_code = $session->get('url_promo_code',false);
$sMontant = TunnelController::getPriceReduction($paymentMethod,$sMontant,$reduction,$url_promo_code);
$payment = self::createPayment($this->doctrine,$session,$user,$request->getLocale(),$sReference);
$payment->setMontant($sMontant);
$payment->setMontantReel($sMontant/$paymentMethod->getBaseReel());
$payment->setPayment($paymentMethod);
$payment->setReference($sReference);
$payment->setType($type);
$this->entityManager->flush();
$country_code = $session->get('payment_code');
$currency = $this->getCurrency($country_code);
self::resetSession($session);
return $this->render('tunnel_gift/form_cheque.html.twig', [
'montant' => $sMontant,
'time' => $paymentMethod->getMontant(),
'reference' => $sReference,
'route' => $route,
'currency' => $currency
]);
}
return new Response("error");
}
#[Route('/cadeau/virement-bancaire.html', name: 'gift_subscription_transfer')]
public function sendBankTransfer(Request $request, MailingTransac $mailer): Response
{
$session = $request->getSession();
$montant = $request->get('montant',0);
$currency = $request->get('currency',0);
$reference = $request->get('reference',"");
$time = intval($request->get('time',0));
$montant = number_format($montant,2);
$montant = str_replace(".", ",", $montant);
$mail = $session->get('email', null);
if($mail){
$mailer->sendBankTransferMail($mail,$montant,$currency,$reference,$time,'gift');
}
return $this->render('tunnel_gift/sendBankTransfer.html.twig', [
'montant' => $montant,
'reference' => $reference,
'time' => $time,
'currency' => $currency,
]);
}
#[Route('/cadeau/envoi-cheque.html', name: 'gift_subscription_check')]
public function sendCheck(Request $request, MailingTransac $mailer): Response
{
$session = $request->getSession();
$montant = $request->get('montant',0);
$currency = $request->get('currency',0);
$reference = $request->get('reference',"");
$time = intval($request->get('time',0));
$montant = number_format($montant,2);
$montant = str_replace(".", ",", $montant);
$mail = $session->get('email', null);
if($mail){
$mailer->sendChequeMail($mail,$montant,$currency,$reference,$time,'gift');
}
return $this->render('tunnel_gift/sendCheque.html.twig', [
'montant' => $montant,
'reference' => $reference,
'time' => $time,
'currency' => $currency,
]);
}
static function createPayment($doctrine,$session,$user,$locale,$sReference)
{
$em = $doctrine->getManager();
$payment = new UserGiftPayment();
$payment->setFirstName($session->get('firstName'));
$payment->setLastName($session->get('lastName'));
$payment->setAddress($session->get('address'));
$payment->setZipCode($session->get('zipCode'));
$payment->setCity($session->get('city'));
$payment->setEmail($session->get('email'));
$payment->setLocale($locale);
$payment->setIsCredit(false);
$country = $doctrine->getRepository(Country::class)->findOneById($session->get('country'));
if($country == null)
$country = $doctrine->getRepository(Country::class)->findOneByCanonicalName('france-metropolitaine');
$payment->setECountry($country);
$payment->setCountry("");
$payment->setEmail($session->get('email'));
if($user != null)
$payment->setUser($user);
$payment->setWaitingPayment(true);
$payment->setReference($sReference);
$pk = md5($session->get('firstName') . $session->get('lastName') . $session->get('address') . $sReference);
$payment->setPrivateKey($pk);
$code = $doctrine->getRepository(PromoCode::class)->getPromoCode($session->get('promo_code',null));
$payment->setPromoCode($code);
$em->persist($payment);
return $payment;
}
#[Route('/cadeau/detail.html', name: 'gift_detail')]
public function showDetailGift(Request $request): Response
{
$id = $request->get('id',0);
$userPayment = $this->doctrine->getRepository(UserGiftPayment::class)->findOneBy(array("privateKey" => $id));
if($userPayment != null){
$request->setLocale($userPayment->getLocale());
$request->attributes->set('_locale', $userPayment->getLocale());
return $this->render('tunnel_gift/detail.html.twig', [
"payment" => $userPayment
]);
}else{
return $this->render('tunnel_gift/detail.html.twig', [
"payment" => null
]);
}
}
#[Route('/cadeau/print.html', name: 'gift_print')]
public function sendPrintGift(Request $request): Response
{
$id = $request->get('id',0);
$userPayment = $this->doctrine->getRepository(UserGiftPayment::class)->findOneBy(array("privateKey" => $id));
if($userPayment != null){
$request->setLocale($userPayment->getLocale());
$request->attributes->set('_locale', $userPayment->getLocale());
$giftCodes = $userPayment->getGiftCodes();
if($giftCodes->count() > 0)
$giftCode = $giftCodes[0];
return $this->render('tunnel_gift/print.html.twig', [
"payment" => $userPayment,
"locale" => $userPayment->getLocale(),
"code" => $giftCode
]);
}else{
return $this->render('tunnel_gift/detail.html.twig', [
"payment" => null
]);
}
}
#[Route('/cadeau.html', name: 'gift_code_html')]
#[Route('/cadeau', name: 'gift_code')]
public function register(Request $request, UserPasswordHasherInterface $passwordHasher, MailchimpAPI $mailchimp, Security $security): Response
{
$session = $request->getSession();
$user = $this->getUser();
//$user = $this->getUser();
if($user instanceof User)
{
//on passe la phase registration
return $this->redirectToRoute('gift_activate');
}
$user = new User(); //on crée un user vide pour récupérer les informations
$codeOk = null;
$form = $this->createFormBuilder($user, ['validation_groups' => ['registration', 'giftCode'], 'translation_domain' => 'tunnel'])
->add('username', TextType::class, ['label' => 'Choisissez un pseudo'])
->add('email', RepeatedType::class, [
'type' => EmailType::class,
'required' => true,
'first_options' => ['label' => 'Entrez votre e-mail'],
'second_options' => ['label' => 'Répétez votre e-mail'],
])
->add('plainPassword', PasswordType::class, ['attr' => ['class' => 'w-75'], 'label' => 'Choisissez un mot de passe'])
->add('code', TextType::class, ['label' => 'Entre ton code-abo :'])
->add('submit', SubmitType::class, ['label' => 'Continuer'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$user = $form->getData();
$codeOk = false;
$code = $this->doctrine->getRepository(GiftCode::class)->getCodeByFull($user->getCode());
if($code != null && $code->isOk())
{
$codeOk = true;
}
if($codeOk)
{
$email = $user->getEmail();
$password = $user->getPlainPassword();
//hasher le password
$hashedPassword = $passwordHasher->hashPassword(
$user,
$password
);
$user->setPassword($hashedPassword);
$user->setLocale($request->getLocale());
$session = $request->getSession();
$countryCode = $this->getUserIsoCode($request, $session);
$defaultCountry = $this->doctrine->getRepository(Country::class)->findOneByIsoCode($countryCode);
if(!$defaultCountry || $countryCode == "FR")
$defaultCountry = $this->doctrine->getRepository(Country::class)->findOneByCanonicalName('france-metropolitaine');
//$currentUser->setSiteUrl(IpToCountry::getExtension($session));
$user->setEcountry($defaultCountry);
$user->addRole(User::ROLE_GIFT);
$user->setMailConfirmedAt(new \DateTimeImmutable());
$user->setSubscriptionDate(new \DateTimeImmutable());
$newDate = new \DateTimeImmutable('now');
$newDate = $newDate->modify('+'.($code->getMontant()).' month');
//Now set the new expiration date
$user->setSubscriptionExpireAt($newDate);
$code->setUtilisation($code->getUtilisation() - 1);
$this->entityManager->persist($user);
$this->entityManager->flush();
$session = $request->getSession();
$session->set('user_data_id',$user->getId());
//FB API !
//$event_id = $this->sendFBMsgRegister($user);
//$session->set('reg_event_id',$event_id);
$this->doctrine->getRepository(ReminderUser::class)->addEmail($user->getEmail(),$user->getUsername(), $request->getLocale());
$mailchimp->addUser($user);
$security->login($user, 'security.authenticator.form_login.main');
return $this->redirectToRoute('user_homepage');
}
}
return $this->renderForm('tunnel_gift/register.html.twig', [
'form' => $form,
'codeOk' => $codeOk
]);
}
public function checkGiftCode($code) {
if(preg_match("#[^-]+-[^-]+-[^-]+-[^-]+#",$code))
{
return true;
}else{
return false;
}
}
#[Route('/cadeau/activate.html', name: 'gift_activate')]
public function activate(Request $request): Response
{
return $this->renderForm('tunnel_gift/activate.html.twig', [
'form' => $form
]);
}
#[Route('/cadeau/confirmation.html', name: 'gift_activate')]
public function confirmation(Request $request): Response
{
return $this->render('tunnel_gift/confirmation.html.twig', [
]);
}
#[Route('/cadeau/abonnement-cb-reussi.html', name: 'gift_subscription_cb')]
#[Route('/cadeau/abonnement-reussi.html', name: 'gift_subscription_confirmed')]
#[Route('/cadeau/abonnement-paypal-reussi.html', name: 'gift_subscription_paypal')]
public function showConfirmSubscription(Request $request): Response
{
return $this->render('tunnel_gift/subscriptionConfirmed.html.twig', [
]);
}
static function resetSession()
{
/*$request = $this->container->get('request');
$session = $request->getSession();
$session->set('formule', 'choice2');
$session->set('occasion', 1);
$session->set('presentation', 1);
$session->set('destinataire', null);
$session->set('expediteur', null);
$session->set('message', null);
$session->set('lastName', null);
$session->set('firstName', null);
$session->set('email', null);
$session->set('address', null);
$session->set('city', null);
$session->set('zipCode', null);
$session->set('country', null);*/
}
}