src/Controller/Front/HomeController.php line 565

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