src/Controller/TrPanierController.php line 164

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Dto\CommandeKitRequest;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use App\Entity\TrPanier;
  8. use App\Form\TrPanierType;
  9. use App\Repository\TrPanierRepository;
  10. use App\Repository\TrCoeurRepository;
  11. use App\Entity\TrCoeur;
  12. use App\Entity\KitPromotionnel;
  13. use App\Entity\TrClient;
  14. use App\Exception\CommandeKitNotFoundException;
  15. use App\Exception\CommandeKitValidationException;
  16. use App\Entity\TrProduits;
  17. use App\Form\TrProduitsType;
  18. use App\Repository\TrProduitsRepository;
  19. use App\Service\Cart\CartService;
  20. use Doctrine\ORM\EntityManagerInterface;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use symfony\component\Form\FormBuilderInterface;
  23. use Symfony\Component\String\Slugger\SluggerInterface;
  24. use Symfony\Component\DependencyInjection\Loader\Configurator\form;
  25. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  26. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  27. use Psr\Log\LoggerInterface;
  28. use App\Service\CommandeKitService;
  29. class TrPanierController extends AbstractController
  30. {
  31.     private $logger;
  32.     public function __construct(LoggerInterface $logger)
  33.     {
  34.         $this->logger = $logger;
  35.     }
  36.     /**
  37.      * @Route("/tr/panier", name="TrPanier_news")
  38.      * @Route("/tr/panier/{id}/edit", name="TrPanier_modification")
  39.      */
  40.     public function form(TrPanier $Panier = null, request $request, EntityManagerInterface $manager, SessionInterface $session, SluggerInterface $slugger)
  41.     {
  42.         if (!$Panier) {
  43.             $Panier = new TrPanier();
  44.         }
  45.         $form = $this->createForm(TrPanierType::class, $Panier);
  46.         $form->handleRequest($request);
  47.         if ($form->isSubmitted() && $form->isValid()) {
  48.             $manager->persist($Panier);
  49.             $manager->flush();
  50.             /**@var FlashBag */
  51.             $flashBag = $session->getBag('flashes');
  52.             $flashBag->add('success', "Action effectuée avec succès!");
  53.             return $this->redirectToRoute('TrPanier_afficher');
  54.         }
  55.         $title = "Créer un Panier";
  56.         $Soustitle = "Liste des Paniers";
  57.         $Nom_Table = "Les Paniers";
  58.         $Explication_Nom_Table = "Cette Table affiche la liste des Paniers.";
  59.         $Titre_Principal = "Paniers";
  60.         return $this->render('tr_panier/Panier.html.twig', [
  61.             'form' => $form->createView(),
  62.             'edit' => $Panier->getId() !== null,
  63.             'title' => $title,
  64.             'Soustitle' => $Soustitle,
  65.             'Nom_Table' => $Nom_Table,
  66.             'Explication_Nom_Table' => $Explication_Nom_Table,
  67.             'Active_href' => 'Active_Panier',
  68.             'Parametre' => 'Parametre_metier',
  69.             'Titre_Principal' => $Titre_Principal,
  70.         ]);
  71.     }
  72.     /* Supprimer*/
  73.     /**
  74.      * @Route("/tr/panier/{id}/delete", name="TrPanier_delete")
  75.      */
  76.     public function supprimer(TrPanier $Panier, request $request, EntityManagerInterface $manager, SessionInterface $session)
  77.     {
  78.         $donnees = $this->getDoctrine()->getManager();
  79.         $donnees->remove($Panier);
  80.         $donnees->flush();
  81.         /**@var FlashBag */
  82.         $flashBag = $session->getBag('flashes');
  83.         $flashBag->add('success', "Action effectuée avec succès!");
  84.         return $this->redirectToRoute('TrPanier_afficher');
  85.     }
  86.     /* Affichage*/
  87.     /**
  88.      * @Route("/tr/panier/affichage", name="TrPanier_afficher")
  89.      */
  90.     public function afficher(EntityManagerInterface $manager, request $request)
  91.     {
  92.         $title = "Affichage des Paniers";
  93.         $repository = $manager->getRepository(TrPanier::class);
  94.         $Paniers = $repository->findAll();
  95.         $title = "Créer un Panier";
  96.         $Soustitle = "Liste des Paniers";
  97.         $Nom_Table = "Les Paniers";
  98.         $Explication_Nom_Table = "Cette Table affiche la liste des Paniers.";
  99.         $Titre_Principal = "Paniers";
  100.         return $this->render('tr_panier/index.html.twig', [
  101.             'Paniers' => $Paniers,
  102.             'title' => $title,
  103.             'Soustitle' => $Soustitle,
  104.             'Nom_Table' => $Nom_Table,
  105.             'Explication_Nom_Table' => $Explication_Nom_Table,
  106.             'Active_href' => 'Active_Panier',
  107.             'Parametre' => 'Parametre_metier',
  108.             'Titre_Principal' => $Titre_Principal,
  109.         ]);
  110.     }
  111.     /**
  112.      * @Route("/tr/panier/Ajout/{id}", name="TrPanier_add")
  113.      */
  114.     public function Add($id, CartService $cartService)
  115.     {
  116.         $cartService->add($id);
  117.         return $this->redirectToRoute('panier_index');
  118.     }
  119.     /**
  120.      * @Route("/tr/panier/Addition/{id}", name="TrPanier_Addition")
  121.      */
  122.     public function Addition($id, CartService $cartService)
  123.     {
  124.         $cartService->add($id);
  125.         return $this->redirectToRoute('Bussness');
  126.     }
  127.     /**
  128.      * @Route("/tr/panier/subtraction/{id}", name="TrPanier_subtraction")
  129.      */
  130.     public function subtraction($id, CartService $cartService)
  131.     {
  132.         $cartService->subtraction($id);
  133.         return $this->redirectToRoute('panier_index');
  134.     }
  135.     /**
  136.      * @Route("/tr/panier/Initial", name="panier_index")
  137.      */
  138.     public function index(CartService $cartService)
  139.     {
  140.         $title = "Créer un Panier";
  141.         $Soustitle = "Liste des Paniers";
  142.         $Nom_Table = "Les Paniers";
  143.         $Explication_Nom_Table = "Cette Table affiche la liste des Paniers.";
  144.         $Titre_Principal = "Paniers";
  145.         return $this->render('bussness/Panier.html.twig', [
  146.             'items' => $cartService->getFullCart(),
  147.             'kitItems' => $cartService->getFullKitCart(),
  148.             'Nombre_items' => $cartService->getQuantite(),
  149.             'productTotal' => $cartService->getProductsTotal(),
  150.             'kitTotal' => $cartService->getKitsTotal(),
  151.             'title' => $title,
  152.             'Soustitle' => $Soustitle,
  153.             'Nom_Table' => $Nom_Table,
  154.             'Explication_Nom_Table' => $Explication_Nom_Table,
  155.             'Titre_Principal' => $Titre_Principal,
  156.             'total' => $cartService->getTotal(),
  157.             'quantite' => $cartService->getQuantite(),
  158.             'totalcoeur' => count($cartService->getCoeur()),
  159.             'google_maps_api_key' => $this->getParameter('google_maps_api_key'),
  160.         ]);
  161.     }
  162.     /**
  163.      * @Route("/tr/panier/remove/{id}", name="panier_remove")
  164.      */
  165.     public function remove($id, CartService $cartService)
  166.     {
  167.         $cartService->remove($id);
  168.         return $this->redirectToRoute('panier_index');
  169.     }
  170.     /**
  171.      * @Route("/tr/panier/kits/add/{id}", name="TrPanierKit_add")
  172.      */
  173.     public function addKit($id, CartService $cartService, SessionInterface $session): Response
  174.     {
  175.         if (!$cartService->addKit((int) $id)) {
  176.             $session->getBag('flashes')->add('danger', 'Ce kit n est plus disponible.');
  177.         } else {
  178.             $session->getBag('flashes')->add('success', 'Kit promotionnel ajoute au panier.');
  179.         }
  180.         return $this->redirectToRoute('panier_index');
  181.     }
  182.     /**
  183.      * @Route("/tr/panier/kits/addition/{id}", name="TrPanierKit_Addition")
  184.      */
  185.     public function addKitFromFront($id, CartService $cartService, Request $request, SessionInterface $session): Response
  186.     {
  187.         if (!$cartService->addKit((int) $id)) {
  188.             $session->getBag('flashes')->add('danger', 'Ce kit n est plus disponible.');
  189.         } else {
  190.             $session->getBag('flashes')->add('success', 'Kit promotionnel ajoute au panier.');
  191.         }
  192.         $referer = $request->headers->get('referer');
  193.         if ($referer) {
  194.             return $this->redirect($referer);
  195.         }
  196.         return $this->redirectToRoute('Bussness');
  197.     }
  198.     /**
  199.      * @Route("/tr/panier/kits/subtraction/{id}", name="TrPanierKit_subtraction")
  200.      */
  201.     public function subtractionKit($id, CartService $cartService): Response
  202.     {
  203.         $cartService->subtractionKit((int) $id);
  204.         return $this->redirectToRoute('panier_index');
  205.     }
  206.     /**
  207.      * @Route("/tr/panier/kits/remove/{id}", name="TrPanierKit_remove")
  208.      */
  209.     public function removeKit($id, CartService $cartService): Response
  210.     {
  211.         $cartService->removeKit((int) $id);
  212.         return $this->redirectToRoute('panier_index');
  213.     }
  214.     /**
  215.      * @Route("/tr/panier/kits/interet", name="TrPanierKit_interest", methods={"POST"})
  216.      */
  217.     public function registerKitInterest(
  218.         Request $request,
  219.         CartService $cartService,
  220.         SessionInterface $session,
  221.         CommandeKitService $commandeKitService,
  222.         EntityManagerInterface $entityManager
  223.     ): Response
  224.     {
  225.         $kitItems = $cartService->getFullKitCart();
  226.         if (0 === count($kitItems)) {
  227.             $session->getBag('flashes')->add('danger', 'Aucun kit disponible dans votre panier.');
  228.             return $this->redirectToRoute('panier_index');
  229.         }
  230.         $errors = $cartService->validateKitCart();
  231.         if ([] !== $errors) {
  232.             foreach ($errors as $error) {
  233.                 $session->getBag('flashes')->add('danger', $error);
  234.             }
  235.             return $this->redirectToRoute('panier_index');
  236.         }
  237.         $contactName = trim((string) $request->request->get('contact_name'));
  238.         $contactPhone = trim((string) $request->request->get('contact_phone'));
  239.         $commentaire = trim((string) $request->request->get('commentaire'));
  240.         if ($this->getUser()) {
  241.             if ('' === $contactName) {
  242.                 $contactName = method_exists($this->getUser(), 'getFulName') ? (string) $this->getUser()->getFulName() : $contactName;
  243.             }
  244.             if ('' === $contactPhone && method_exists($this->getUser(), 'getEmail')) {
  245.                 $client = $entityManager->getRepository(TrClient::class)->findOneBy([
  246.                     'email' => (string) $this->getUser()->getEmail(),
  247.                 ]);
  248.                 if ($client instanceof TrClient && null !== $client->getTelephone()) {
  249.                     $contactPhone = trim((string) $client->getTelephone());
  250.                 }
  251.             }
  252.         }
  253.         if ('' === $contactName || '' === $contactPhone) {
  254.             $session->getBag('flashes')->add('danger', 'Nom et telephone sont obligatoires pour demander un kit.');
  255.             return $this->redirectToRoute('panier_index');
  256.         }
  257.         $payload = [];
  258.         $createdCommandIds = [];
  259.         foreach ($kitItems as $item) {
  260.             $payload[] = [
  261.                 'kit_id' => $item['kit']->getId(),
  262.                 'kit_nom' => $item['kit']->getNom(),
  263.                 'prix_kit' => $item['kit']->getPrixKit(),
  264.                 'quantite' => $item['quantity'],
  265.                 'items' => array_map(static function ($kitItem) {
  266.                     return [
  267.                         'produit' => null !== $kitItem->getProduit() ? $kitItem->getProduit()->getLIBELLE() : null,
  268.                         'quantite' => $kitItem->getQuantite(),
  269.                     ];
  270.                 }, $item['kit']->getItems()->toArray()),
  271.             ];
  272.             try {
  273.                 $commandeKit = $commandeKitService->createFromRequest(CommandeKitRequest::fromArray([
  274.                     'kit_id' => $item['kit']->getId(),
  275.                     'telephone' => $contactPhone,
  276.                     'nom' => $contactName,
  277.                     'quantite' => (int) $item['quantity'],
  278.                     'commentaire' => $commentaire,
  279.                 ]));
  280.                 $createdCommandIds[] = $commandeKit->getId();
  281.             } catch (CommandeKitNotFoundException $e) {
  282.                 $this->logger->warning('Kit introuvable lors de l enregistrement depuis le panier.', [
  283.                     'kit_id' => $item['kit']->getId(),
  284.                     'error' => $e->getMessage(),
  285.                 ]);
  286.                 $session->getBag('flashes')->add('danger', 'Un des kits selectionnes n est plus disponible.');
  287.                 return $this->redirectToRoute('panier_index');
  288.             } catch (CommandeKitValidationException $e) {
  289.                 $this->logger->warning('Validation bloquante lors de l enregistrement d une commande kit.', [
  290.                     'kit_id' => $item['kit']->getId(),
  291.                     'errors' => $e->getErrors(),
  292.                 ]);
  293.                 $session->getBag('flashes')->add('danger', 'La demande de kit n a pas pu etre enregistree. Verifiez les informations saisies.');
  294.                 return $this->redirectToRoute('panier_index');
  295.             } catch (\Throwable $e) {
  296.                 $this->logger->error('Erreur technique lors de l enregistrement d une demande de kit depuis le panier.', [
  297.                     'kit_id' => $item['kit']->getId(),
  298.                     'error' => $e->getMessage(),
  299.                 ]);
  300.                 $session->getBag('flashes')->add('danger', 'Une erreur technique est survenue lors de l enregistrement de votre demande de kit.');
  301.                 return $this->redirectToRoute('panier_index');
  302.             }
  303.         }
  304.         $this->logger->info('Demandes de kits promotionnels enregistrees depuis le panier.', [
  305.             'customer_name' => $contactName,
  306.             'customer_phone' => $contactPhone,
  307.             'customer_email' => $this->getUser() && method_exists($this->getUser(), 'getEmail') ? $this->getUser()->getEmail() : null,
  308.             'commentaire' => $commentaire,
  309.             'kits' => $payload,
  310.             'commande_ids' => $createdCommandIds,
  311.         ]);
  312.         $cartService->clearKitCart();
  313.         $session->getBag('flashes')->add('success', 'Votre demande pour les kits a bien ete enregistree. Notre equipe vous contactera.');
  314.         return $this->redirectToRoute('panier_index');
  315.     }
  316. }