src/Controller/Front/HomeController.php line 98

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Front;
  3. use App\Entity\{ServiceDevisArticleWhyChooseUsAboutUsUserClientDevisTravelReasonDevisLuggageDevisBudgetDevisEquipmentDevisVehicleDetailsDevisAttachment}; 
  4. use App\Form\{DevisTypeClientTypeClientDevisType};
  5. use App\Repository\{HomepageRepositoryServiceRepository};
  6. use App\Service\{AccessClientServiceDistanceCalculatorTransporteurProcheAddressInfoService};
  7. use Doctrine\Common\Collections\ArrayCollection;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use Knp\Component\Pager\PaginatorInterface;
  15. use Symfony\Component\Security\Core\Security;
  16. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  17. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  18. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  19. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  20. use Symfony\Component\HttpFoundation\File\UploadedFile;
  21. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  22. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  23. use Symfony\Component\Form\FormError;
  24. class HomeController extends AbstractController
  25. {
  26.     private $distanceCalculator;
  27.     private $transporteurProche;
  28.     private $tokenStorage;
  29.     public function __construct(
  30.         DistanceCalculator $distanceCalculator
  31.         TransporteurProche $transporteurProche,
  32.         TokenStorageInterface $tokenStorage
  33.     )
  34.     {
  35.         $this->distanceCalculator $distanceCalculator;
  36.         $this->transporteurProche $transporteurProche;
  37.         $this->tokenStorage $tokenStorage;
  38.     }
  39.     /**
  40.      * @Route("/", name="app_client_home")
  41.      */
  42.     public function homepage(
  43.         AccessClientService $accessClientService
  44.         HomepageRepository $homepageRepository
  45.         ServiceRepository $serviceRepository,
  46.         EntityManagerInterface $entityManager
  47.     ): Response
  48.     {
  49.         $accessClientService->handleAccessControl();
  50.         
  51.         $homepage $homepageRepository->find(1);
  52.         $services $serviceRepository->getCategories('ASC')->getResult();
  53.         $lastArticles $entityManager->getRepository(Article::class)->findBy(['status' => true], ['id' => 'DESC'], 30);
  54.         $whyChooseUs $entityManager->getRepository(WhyChooseUs::class)->findOneBy([], ['id' => 'DESC']);
  55.         $aboutUs $entityManager->getRepository(AboutUs::class)->findOneBySlug('notre-histoire');
  56.         return $this->render('front/home/index.html.twig', [
  57.             'homepage' => $homepage,
  58.             'services' => $services,
  59.             'lastArticles' => $lastArticles,
  60.             'whyChooseUs' => $whyChooseUs,
  61.             'aboutUs' => $aboutUs
  62.         ]);
  63.     }
  64.     /**
  65.      * @Route("/service/{slug}", name="app_client_service")
  66.      */
  67.     public function service(
  68.         AccessClientService $accessClientService
  69.         string $slug
  70.         Request $request
  71.         EntityManagerInterface $entityManager
  72.         PaginatorInterface $paginator
  73.         SessionInterface $session
  74.     )
  75.     {
  76.         $accessClientService->handleAccessControl();
  77.         
  78.         $service $entityManager->getRepository(Service::class)->findOneBy(['slug' => $slug]);
  79.         if (!$service) {
  80.             throw new NotFoundHttpException('Le service demandé n\'existe pas.');
  81.         }
  82.         $language $request->getLocale();
  83.         $session->remove('login_info_slug');
  84.                 
  85.         $services $entityManager->getRepository(Service::class)->getServices($service->getId());
  86.         switch ($slug) {
  87.             case 'vtc-minibus':
  88.             case 'autocar':
  89.                 $devis $session->get('devis', new Devis());
  90.                 $form $this->createForm(DevisType::class, $devis, ['step' => 'step1']);
  91.                 $form->handleRequest($request);
  92.                 if ($form->isSubmitted() && $form->isValid()) {
  93.                     $typeOfTrip $form->get('typeOfTrip')->getData();
  94.                     $session->set('typeOfTrip'$typeOfTrip);
  95.                     
  96.                     $startAddress $form->get('departureAddress')->getData();
  97.                     $endAddress $form->get('arrivalAddress')->getData();
  98.                     $distanceAndDurationAndRouteNational $this->distanceCalculator->calculDistance($startAddress$endAddress$language);
  99.                     $distance $distanceAndDurationAndRouteNational['distance'] ?? null;
  100.                     $startLocation $distanceAndDurationAndRouteNational['start_location'] ?? ['lat' => null'lng' => null];
  101.                     $endLocation $distanceAndDurationAndRouteNational['end_location'] ?? ['lat' => null'lng' => null];
  102.                     
  103.                     if ($typeOfTrip === 'Aller simple') {
  104.                         $devis->setReturnDate(null);
  105.                         $devis->setReturnTime(null);
  106.                         $devis->setDistance($distance);
  107.                         $devis->setDistancePerTrip(null);
  108.                     } else if ($typeOfTrip === 'Aller-Retour') {
  109.                         $devis->setReturnDate(null);
  110.                         if ($distance) {
  111.                             $totalDistance = (floatval(str_replace(',''.'explode(' '$distance)[0]))) * 2;
  112.                             $distanceFormatted number_format($totalDistance2',''.') . " km";
  113.                             $devis->setDistance($distanceFormatted);
  114.                             $devis->setDistancePerTrip($distance);
  115.                         }
  116.                     } else if ($typeOfTrip === 'Séjours') {
  117.                         if ($distance) {
  118.                             $totalDistance = (floatval(str_replace(',''.'explode(' '$distance)[0]))) * 2;
  119.                             $distanceFormatted number_format($totalDistance2',''.') . " km";
  120.                             $devis->setDistance($distanceFormatted);
  121.                             $devis->setDistancePerTrip($distance);
  122.                         }
  123.                     }
  124.                     $devis->setStartLatitude($startLocation['lat']);
  125.                     $devis->setStartLongitude($startLocation['lng']);
  126.                     $devis->setEndLatitude($endLocation['lat']);
  127.                     $devis->setEndLongitude($endLocation['lng']);
  128.                     $devis->setService($service);
  129.                     $devis->setCreatedAtValue();
  130.                     $session->set('devis'$devis);
  131.                     return $this->redirectToRoute('app_client_service_route_description', ['slug' => $slug]);
  132.                 } 
  133.                 return $this->render('front/service/vtc_autocar.html.twig', [
  134.                     'devis' => $devis,
  135.                     'entity' => $service,
  136.                     'services' => $services,
  137.                     'form' => $form->createView()
  138.                 ]);
  139.             
  140.             case 'ambulance':
  141.                 return $this->render('front/service/ambulance.html.twig', [
  142.                     'entity' => $service,
  143.                 ]);
  144.             case 'taxi':
  145.                 return $this->render('front/service/taxi.html.twig', [
  146.                     'entity' => $service,
  147.                 ]);
  148.     
  149.             case 'covoiturage':
  150.                 return $this->render('front/service/covoiturage.html.twig', [
  151.                     'entity' => $service,
  152.                 ]);
  153.             default:
  154.                 throw new NotFoundHttpException('Type de service invalide.');
  155.         }
  156.     }
  157.     /**
  158.      * @Route("/service/{slug}/route-description", name="app_client_service_route_description")
  159.      */
  160.     public function serviceOptions(
  161.         AccessClientService $accessClientService
  162.         string $slug
  163.         SessionInterface $session
  164.         Request $request
  165.         EntityManagerInterface $entityManager
  166.     )
  167.     {
  168.         $accessClientService->handleAccessControl();
  169.         $service $entityManager->getRepository(Service::class)->findOneBy(['slug' => $slug]);
  170.         if (!$service) {
  171.             throw new NotFoundHttpException('Le service demandé n\'existe pas.');
  172.         }
  173.         $allowedForQuote = ['vtc-minibus''autocar'];
  174.         if (!in_array($slug$allowedForQuote)) {
  175.             return $this->redirectToRoute('app_client_service', ['slug' => $slug]);
  176.         }
  177.         $devis $session->get('devis');
  178.         if (!$devis) {
  179.             return $this->redirectToRoute('app_client_service', ['slug' => $slug]);
  180.         }
  181.         $session->remove('login_info_slug');
  182.         $travelReason $devis->getDevisTravelReason();
  183.         if ($travelReason && !$entityManager->contains($travelReason)) {
  184.             $devisTravelReason $entityManager->getRepository(DevisTravelReason::class)->find($travelReason->getId());
  185.             if ($devisTravelReason) {
  186.                 $devis->setDevisTravelReason($devisTravelReason);
  187.             }
  188.         }
  189.         $luggage $devis->getDevisLuggage();
  190.         if ($luggage && !$entityManager->contains($luggage)) {
  191.             $devisLuggage $entityManager->getRepository(DevisLuggage::class)->find($luggage->getId());
  192.             if ($devisLuggage) {
  193.                 $devis->setDevisLuggage($devisLuggage);
  194.             }
  195.         }
  196.         $budget $devis->getDevisBudget();
  197.         if ($budget && !$entityManager->contains($budget)) {
  198.             $devisBudget $entityManager->getRepository(DevisBudget::class)->find($budget->getId());
  199.             if ($devisBudget) {
  200.                 $devis->setDevisBudget($devisBudget);
  201.             }
  202.         }
  203.         $selectedEquipments $devis->getDevisEquipment();
  204.         $managedEquipments = new ArrayCollection();
  205.         foreach ($selectedEquipments as $equipment) {
  206.             $existingEquipment $entityManager->getRepository(DevisEquipment::class)
  207.                 ->findOneBy(['name' => $equipment->getName()]);
  208.             if ($existingEquipment) {
  209.                 $managedEquipments->add($existingEquipment);
  210.             } 
  211.         }
  212.         $devis->setDevisEquipment($managedEquipments->toArray());
  213.         $form $this->createForm(DevisType::class, $devis, ['step' => 'step2']);
  214.         $form->handleRequest($request);
  215.                         
  216.         if ($form->isSubmitted() && $form->isValid()) {            
  217.             $needVehicleOnSite $form->get('needVehicleOnSite')->getData();
  218.             $session->set('needVehicleOnSite'$needVehicleOnSite);
  219.             if ($needVehicleOnSite == "Non") {
  220.                 $devis->getVehicleDetails()->clear();
  221.             }
  222.             $addPdfDocument $form->get('addPdfDocument')->getData();
  223.             $session->set('addPdfDocument'$addPdfDocument);
  224.             if ($addPdfDocument == "Non") {
  225.                 $devis->getAttachments()->clear();
  226.             } 
  227.             $attachment $form->get('attachments')->getData();
  228.             foreach ($attachment as $devisAttachment) {
  229.                 $attachFile $devisAttachment->getAttachFile();
  230.                 if ($attachFile instanceof UploadedFile) {
  231.                     $newFilename uniqid() . '.' $attachFile->guessExtension();
  232.                     $uploadDir $this->getParameter('kernel.project_dir') . '/public/uploads/files/tmp/';
  233.                     $attachFile->move($uploadDir$newFilename);
  234.                     $fileSizeInBytes $attachFile->getSize();
  235.                     $fileSizeInKB round($fileSizeInBytes 10242);  
  236.                     $fileSizeInMB round($fileSizeInKB 10242);
  237.                     $sizeForSession = ($fileSizeInMB >= 1) ? $fileSizeInMB ' MB' $fileSizeInKB ' KB';
  238.                     
  239.                     $devisAttachment->setFileName($newFilename);
  240.                     $devisAttachment->setSize($sizeForSession);
  241.                     $devis->addAttachment($devisAttachment);  
  242.                 }                
  243.             }
  244.             $session->set('devis'$devis);
  245.             return $this->redirectToRoute('app_client_service_login_info', ['slug' => $slug]);
  246.         } 
  247.         return $this->render('front/service/step2/route_description.html.twig', [
  248.             'service' => $service,
  249.             'devis' => $devis,
  250.             'form' => $form->createView()
  251.         ]);
  252.     }
  253.     /**
  254.      * @Route("/service/{slug}/login-info", name="app_client_service_login_info")
  255.      */
  256.     public function loginInfo(
  257.         AccessClientService $accessClientService
  258.         AddressInfoService $addressInfoService,
  259.         string $slug
  260.         SessionInterface $session
  261.         Request $request
  262.         EntityManagerInterface $entityManager,
  263.         Security $security,
  264.         AuthenticationUtils $authenticationUtils,
  265.         UserPasswordEncoderInterface $passwordEncoder
  266.     ) {
  267.         $accessClientService->handleAccessControl();
  268.         $service $entityManager->getRepository(Service::class)->findOneBy(['slug' => $slug]);
  269.         if (!$service) {
  270.             throw new NotFoundHttpException('Le service demandé n\'existe pas.');
  271.         }
  272.         
  273.         $allowedForQuote = ['vtc-minibus''autocar'];
  274.         if (!in_array($slug$allowedForQuote)) {
  275.             return $this->redirectToRoute('app_client_service', ['slug' => $slug]);
  276.         }
  277.         $devis $session->get('devis');
  278.         if (!$devis) {
  279.             return $this->redirectToRoute('app_client_service', ['slug' => $slug]);
  280.         }
  281.         
  282.         if ($security->isGranted('IS_AUTHENTICATED_FULLY')) {
  283.             if ($session->has('login_info_slug')) {
  284.                 $session->remove('login_info_slug'); 
  285.             }
  286.             if ($session->has('register_info_slug')) {
  287.                 $session->remove('register_info_slug'); 
  288.             }
  289.             $user $this->getUser();   
  290.             $client $user->getClient();
  291.             if (!$client) {
  292.                 throw new NotFoundHttpException('Aucun client trouvé pour cet utilisateur ' $user->getFirstname());
  293.             }
  294.             $form $this->createForm(ClientDevisType::class, $client);
  295.             $form->handleRequest($request);
  296.             if ($form->isSubmitted() && $form->isValid()) {
  297.                 $civility $form->get('user')->get('civility')->getData();
  298.                 $lastname $form->get('user')->get('lastname')->getData();
  299.                 $firstname $form->get('user')->get('firstname')->getData();
  300.                 $address $form->get('address')->getData();
  301.                 $posteZip $form->get('postalCode')->getData();
  302.                 $ville $form->get('city')->getData();
  303.                 
  304.                 if ($civility === 'Monsieur' || $civility === 'Madame') {
  305.                     $client->setEntrepriseName(null);  
  306.                     $client->setSiret(null);        
  307.                 } 
  308.                 $user->setLastname($lastname);
  309.                 $user->setFirstname($firstname);
  310.                 $user->setUpdatedAtValue();
  311.                 $user->preUpdate();
  312.                 
  313.                 $addressInfo $addressInfoService->getAddressInfo($address);
  314.         
  315.                 if ($addressInfo !== null) {
  316.                     $postalCode $addressInfo['postal_code'];
  317.                     $city $addressInfo['city'];
  318.                     $longitude $addressInfo['longitude'];
  319.                     $latitude $addressInfo['latitude'];
  320.                 } else {
  321.                     $postalCode null;
  322.                     $city null;
  323.                     $longitude null;
  324.                     $latitude null;
  325.                 }
  326.                 if ($postalCode !== null && $posteZip !== $postalCode) {
  327.                     $client->setPostalCode($postalCode);
  328.                 }
  329.                 if ($city !== null && $ville !== $city) {
  330.                     $client->setCity($city);
  331.                 }
  332.                 if ($longitude !== null) {
  333.                     $client->setLongitude($longitude);
  334.                 }
  335.                 if ($latitude !== null) {
  336.                     $client->setLatitude($latitude);
  337.                 }
  338.                     
  339.                 $entityManager->persist($user);
  340.                 $entityManager->persist($client);
  341.                 $entityManager->flush();
  342.                 
  343.                 return $this->redirectToRoute('app_client_service_summary', ['slug' => $slug]);
  344.             }
  345.             return $this->render('front/service/step3/login_info.html.twig', [
  346.                 'service' => $service,
  347.                 'devis' => $devis,
  348.                 'slug' => $slug,
  349.                 'client' => $client,
  350.                 'user' => $user,
  351.                 'form' => $form->createView()
  352.             ]);
  353.         } 
  354.         else {
  355.             if (!$session->has('login_info_slug')) {
  356.                 $session->set('login_info_slug'$slug); 
  357.             }
  358.             if (!$session->has('register_info_slug')) {
  359.                 $session->set('register_info_slug'$slug); 
  360.             }
  361.             
  362.             $error $authenticationUtils->getLastAuthenticationError();
  363.             $lastUsername $authenticationUtils->getLastUsername();
  364.             
  365.             $user = new User();
  366.             $client = new Client();
  367.             
  368.             $form $this->createForm(ClientType::class, $client, [
  369.                 'action' => $this->generateUrl('app_front_register')
  370.             ]);
  371.             $form->handleRequest($request);
  372.                 
  373.             return $this->render('front/service/step3/login_info.html.twig', [
  374.                 'service' => $service,
  375.                 'devis' => $devis,
  376.                 'last_username' => $lastUsername,
  377.                 'error' => $error,
  378.                 'slug' => $slug,
  379.                 'form' => $form->createView()
  380.             ]);
  381.         }
  382.     }
  383.     /**
  384.      * @Route("/service/{slug}/summary", name="app_client_service_summary")
  385.      */
  386.     public function summary(
  387.         AccessClientService $accessClientService
  388.         string $slug
  389.         Request $request,
  390.         SessionInterface $session
  391.         EntityManagerInterface $entityManager,
  392.         Security $security
  393.     ) {
  394.         $accessClientService->handleAccessControl();
  395.         $service $entityManager->getRepository(Service::class)->findOneBy(['slug' => $slug]);
  396.         if (!$service) {
  397.             throw new NotFoundHttpException('Le service demandé n\'existe pas.');
  398.         }
  399.         $allowedForQuote = ['vtc-minibus''autocar'];
  400.         if (!in_array($slug$allowedForQuote)) {
  401.             return $this->redirectToRoute('app_client_service', ['slug' => $slug]);
  402.         }                                                            
  403.         $devis $session->get('devis');
  404.         if (!$devis) {
  405.             return $this->redirectToRoute('app_client_service', ['slug' => $slug]);
  406.         }
  407.         $devis->setService($service);
  408.         $travelReason $devis->getDevisTravelReason();
  409.         if ($travelReason && !$entityManager->contains($travelReason)) {
  410.             $devisTravelReason $entityManager->getRepository(DevisTravelReason::class)->find($travelReason->getId());
  411.             if ($devisTravelReason) {
  412.                 $devis->setDevisTravelReason($devisTravelReason);
  413.             }
  414.         }
  415.         $luggage $devis->getDevisLuggage();
  416.         if ($luggage && !$entityManager->contains($luggage)) {
  417.             $devisLuggage $entityManager->getRepository(DevisLuggage::class)->find($luggage->getId());
  418.             if ($devisLuggage) {
  419.                 $devis->setDevisLuggage($devisLuggage);
  420.             }
  421.         }
  422.         $budget $devis->getDevisBudget();
  423.         if ($budget && !$entityManager->contains($budget)) {
  424.             $devisBudget $entityManager->getRepository(DevisBudget::class)->find($budget->getId());
  425.             if ($devisBudget) {
  426.                 $devis->setDevisBudget($devisBudget);
  427.             }
  428.         }
  429.         $form $this->createForm(DevisType::class, $devis, ['step' => 'step3']);
  430.         $form->handleRequest($request);
  431.         if ($form->isSubmitted() && $form->isValid()) {
  432.             if (
  433.                 !$devis->isMiseEnAvance() && 
  434.                 !$devis->isRemonteEnTeteDeListe() && 
  435.                 !$devis->isDemandeUrgente()
  436.             ) {
  437.                 $this->addFlash('danger''Avertissement ! Veuillez sélectionner au moins une option.');
  438.                 return $this->redirectToRoute('app_client_service_summary', ['slug' => $slug]);
  439.             }
  440.             $totalCost 0;
  441.             if ($devis->isMiseEnAvance()) {
  442.                 $totalCost += 6;
  443.             }
  444.             if ($devis->isRemonteEnTeteDeListe()) {
  445.                 $totalCost += 8;
  446.             }
  447.             if ($devis->isDemandeUrgente()) {
  448.                 $totalCost += 3;
  449.             }
  450.             $user $security->getUser();
  451.             if ($user->getCreditBalance() >= $totalCost) {
  452.                 $user->debitCredits($totalCost);
  453.                 
  454.                 $devisAttachment $devis->getAttachments();
  455.                 if ($devisAttachment) {
  456.                     foreach ($devisAttachment as $attachment) {                        
  457.                         $finalPath $this->getParameter('kernel.project_dir') . '/public/uploads/files/devis/attachments/';
  458.                         $sourcePath $this->getParameter('kernel.project_dir') . '/public/uploads/files/tmp/' $attachment->getFileName();
  459.                         if (!file_exists($finalPath $attachment->getFileName())) {
  460.                             if (file_exists($sourcePath)) {
  461.                                 rename($sourcePath$finalPath $attachment->getFileName());
  462.                             } else {
  463.                                 $this->addFlash('danger''Veuillez rajouter le fichier, il est manquant ou ...');
  464.                                 return $this->redirectToRoute('app_client_service_summary', ['slug' => $slug]);
  465.                             }
  466.                         }
  467.                         $attachment->setDevis($devis);
  468.                         $entityManager->persist($attachment);
  469.                     }
  470.                 }
  471.                 foreach ($devis->getDevisEquipment() as $equipment) {
  472.                     $existingEquipment $entityManager->getRepository(DevisEquipment::class)->findOneBy(['name' => $equipment->getName()]);
  473.                     if ($existingEquipment) {
  474.                         $devis->removeDevisEquipment($equipment); 
  475.                         $devis->addDevisEquipment($existingEquipment); 
  476.                     }
  477.                 }
  478.                 $devis->setUser($user);
  479.                 $entityManager->persist($devis);
  480.                 $entityManager->flush();
  481.                 $session->remove('typeOfTrip');
  482.                 $session->remove('needVehicleOnSite');
  483.                 $session->remove('addPdfDocument');
  484.                 $session->remove('uploaded_files');
  485.                 $session->remove('devis');
  486.                 $this->addFlash('success''Succès ! Votre demande de devis a été validée.');
  487.                 return $this->redirectToRoute('app_client_devis_pending');
  488.             } else {
  489.                 $this->addFlash('danger''Avertissement ! Vous n\'avez pas assez de crédit, rechargez votre portefeuille.');
  490.                 return $this->redirectToRoute('app_client_service_summary', ['slug' => $slug]);
  491.             }
  492.         }
  493.         
  494.         return $this->render('front/service/step4/recapitulatif.html.twig', [
  495.             'service' => $service,
  496.             'devis' => $devis,
  497.             'form' => $form->createView(),
  498.             'stripe_public_key' => $this->getParameter('stripe_public_key')
  499.         ]);
  500.     }
  501. }