src/Controller/Front/CartController.php line 81

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Front;
  3. use App\Entity\Address;
  4. use App\Entity\Category;
  5. use App\Entity\Comment;
  6. use App\Entity\Delivery;
  7. use App\Entity\Document;
  8. use App\Entity\DocumentDeclinationProduit;
  9. use App\Entity\DocumentProduit;
  10. use App\Entity\Produit;
  11. use App\Entity\ProduitDeclinationValue;
  12. use App\Entity\Promotion;
  13. use App\Entity\Stock;
  14. use App\Entity\User;
  15. use App\Mail\Mail;
  16. use App\Repository\DeclinationRepository;
  17. use App\Repository\DeliveryRepository;
  18. use App\Repository\DocumentRepository;
  19. use App\Repository\ProduitRepository;
  20. use App\Repository\PromotionRepository;
  21. use App\Repository\ResourceRepository;
  22. use App\Repository\SupplierRepository;
  23. use App\Repository\TvaRepository;
  24. use App\Repository\UserRepository;
  25. use App\Service\RightService;
  26. use Doctrine\DBAL\Exception;
  27. use Doctrine\ORM\EntityManagerInterface;
  28. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  29. use Symfony\Component\HttpFoundation\JsonResponse;
  30. use Symfony\Component\HttpFoundation\Request;
  31. use Symfony\Component\HttpFoundation\RequestStack;
  32. use Symfony\Component\HttpFoundation\Response;
  33. use Symfony\Component\Messenger\MessageBusInterface;
  34. use Symfony\Component\Messenger\Stamp\DelayStamp;
  35. use Symfony\Component\Routing\Annotation\Route;
  36. use App\Service\ActivityService;
  37. use App\Repository\ProduitDeclinationValueRepository;
  38. class CartController extends AbstractController
  39. {
  40.     /** @var EntityManagerInterface */
  41.     private $em;
  42.     private $tvaRepository;
  43.     private $deliveryRepository;
  44.     private $produitRepository;
  45.     private $produitDeclinationValueRepository;
  46.     private $documentRepository;
  47.     private $resourceRepository;
  48.     private $activityService;
  49.     private $declinationRepository;
  50.     private $promotionRepository;
  51.     public function __construct(EntityManagerInterface $manager,
  52.                                 TvaRepository $tvaRepository,
  53.                                 ProduitRepository $produitRepository,
  54.                                 ProduitDeclinationValueRepository $produitDeclinationValueRepository,
  55.                                 DeliveryRepository $deliveryRepository,
  56.                                 DocumentRepository $documentRepository,
  57.                                 ResourceRepository $resourceRepository,
  58.                                 ActivityService $activityService,
  59.                                 DeclinationRepository $declinationRepository,
  60.                                 PromotionRepository $promotionRepository
  61.                                 )
  62.     {
  63.         $this->em $manager;
  64.         $this->tvaRepository $tvaRepository;
  65.         $this->deliveryRepository $deliveryRepository;
  66.         $this->produitRepository $produitRepository;
  67.         $this->produitDeclinationValueRepository $produitDeclinationValueRepository;
  68.         $this->documentRepository $documentRepository;
  69.         $this->resourceRepository $resourceRepository;
  70.         $this->activityService $activityService;
  71.         $this->declinationRepository $declinationRepository;
  72.         $this->promotionRepository $promotionRepository;
  73.     }
  74.     /**
  75.      * @Route("/cart", name="cart_new",options={"expose"=true}, methods={"GET"})
  76.      */
  77.     public function index(): Response
  78.     {
  79.         /*$sql = 'select * from category limit 6';
  80.         $stmt = $this->em->getConnection()->prepare($sql);
  81.         $categories = $stmt->executeQuery()->fetchAllAssociative();*/
  82.         //$categories = $this->em->getRepository(Category::class)->findAll();
  83.         $delivery $this->em->getRepository(Delivery::class)->findOneBy(array('isSelected' => 1));
  84.         return $this->render('front/cart/index.html.twig', [
  85.             //'categories' => $categories,
  86.             'delivery' => $delivery,
  87.         ]);
  88.     }
  89.     /**
  90.      * @Route("/api/promo-code", name="promo_code", options={"expose"=true}, methods={"POST"})
  91.      */
  92.     public function promoAPI(Request $request): Response {
  93.         //$code = $request->query->get('code');
  94.         $code $request->request->get('code');
  95.         $total $request->request->get('total');
  96.         if(!$code){
  97.             $response = [
  98.                 'res' => 'ERROR',
  99.                 'message' => 'Veuillez saisir un code promo.',
  100.             ];
  101.             return new jsonResponse($response);
  102.         }
  103.         $promotion $this->em->getRepository(Promotion::class)->findOneBy(array('code' => $code));
  104.         if(!$promotion){
  105.             $response = [
  106.                 'res' => 'ERROR',
  107.                 'message' => 'Code promo invalide.',
  108.             ];
  109.             return new jsonResponse($response);
  110.         }
  111.         $date = new \DateTime('now');
  112.         if ($promotion->getStartAt() > $date || $promotion->getEndAt() < $date) {
  113.             $response = [
  114.                 'res' => 'ERROR',
  115.                 'message' => 'Code promo expiré.',
  116.             ];
  117.             return new jsonResponse($response);
  118.         }
  119.         // Vérification de quantité si déja saisie
  120.         if (($promotion->getTotalQuantity() > && $promotion->getQuntityUser() > 0) && $promotion->getQuntityUser() >= $promotion->getTotalQuantity()) {
  121.             $response = [
  122.                 'res' => 'ERROR',
  123.                 'message' => "Code promo atteint nombre maximum d'utilisations.",
  124.             ];
  125.             return new jsonResponse($response);
  126.         }
  127.         // Si total de panier inférieur au remise on l'applique pas
  128.         if ($promotion->getDiscountType() == 'amount' && $promotion->getDiscountValue() > $total) {
  129.             $response = [
  130.                 'res' => 'ERROR',
  131.                 'message' => 'Il vous manque ' number_format(($promotion->getDiscountValue() - $total), 3'.'' ') . ' TND pour appliquer ce code promo',
  132.             ];
  133.             return new jsonResponse($response);
  134.         }
  135.         $response = [
  136.             'res' => 'OK',
  137.             'data' => $promotion,
  138.             'message' => 'Code promo appliqué avec succès.',
  139.         ];
  140.         return new jsonResponse($response);
  141.     }
  142.     /**
  143.      * @Route("/api/verify-client", name="verify_client", options={"expose"=true}, methods={"POST"})
  144.      */
  145.     public function verifyClientAPI(Request $request): Response {
  146.         //$code = $request->query->get('code');
  147.         // Récupérer les donnés coté navigateur
  148.         $client json_decode($request->request->get('client'), true);
  149.         if (!$client['telephone']) {
  150.             $response = [
  151.                 'res' => 'ERROR',
  152.                 'message' => 'Saisir votre numéro de téléphone.',
  153.             ];
  154.             return new jsonResponse($response);
  155.         }
  156.         /*if (!$client['gouvernorat']) {
  157.             $response = [
  158.                 'res' => 'ERROR',
  159.                 'message' => 'Sélectionner votre gouvernorat.',
  160.             ];
  161.             return new jsonResponse($response);
  162.         }
  163.         if (!$client['adresse']) {
  164.             $response = [
  165.                 'res' => 'ERROR',
  166.                 'message' => 'Saisir votre adresse de livraison.',
  167.             ];
  168.             return new jsonResponse($response);
  169.         }*/
  170.         // Si le client connecté de type admin alors bloquer la commande
  171.         if ($this->getUser() && $this->getUser()->getType() != 'client') {
  172.             $response = [
  173.                 'res' => 'ERROR',
  174.                 'message' => 'Vous ne pouvez passer une commande web à travers un compte admin.',
  175.             ];
  176.             return new jsonResponse($response);
  177.         }
  178.         // Vérifier l'existance de client dans la base
  179.         $user $this->em->getRepository(User::class)->findOneBy(array('phone' => str_replace(' '''$client['telephone'])));
  180.         if (!$user) {   // le client n'existe pas dans la base de données.
  181.             $response = [
  182.                 'res' => 'OK',
  183.                 'data' => false,
  184.                 'message' => 'Nouveau client.',
  185.             ];
  186.             return new jsonResponse($response);
  187.         }
  188.         $response = [
  189.             'res' => 'OK',
  190.             'data' => true,
  191.             'message' => 'Client déjà existant.',
  192.         ];
  193.         return new jsonResponse($response);
  194.     }
  195.     /**
  196.      * @Route("/checkout-new", name="checkout_new",options={"expose"=true}, methods={"GET"})
  197.      */
  198.     public function checkout(): Response
  199.     {
  200.         $delivery $this->em->getRepository(Delivery::class)->findOneBy(array('isSelected' => 1));
  201.         // Read the JSON file of regions
  202.         $path $this->getParameter('kernel.project_dir') . '/public' '/front/assets/json/tunisia.json';
  203.         $json file_get_contents($path);
  204.         // Decode the JSON file
  205.         $regions json_decode($jsontrue);
  206.         //dd($regions);
  207.         return $this->render('front/cart/checkout.html.twig', [
  208.             'delivery' => $delivery,
  209.             'regions' => $regions
  210.         ]);
  211.     }
  212.     /**
  213.      * @Route("/api/verify-stock/{idDec}/{qty}", name="verify_stock", options={"expose"=true}, methods={"GET"})
  214.      */
  215.     public function verifyStockAPI(Request $request$idDec$qty): Response
  216.     {
  217.         // Récupérer les données coté navigateur
  218.         $produitDecllination $this->produitDeclinationValueRepository->find($idDec);
  219.         // Calcul de stock
  220.         $quantity 0;
  221.         foreach ($produitDecllination->getStocks() as $stock)
  222.             $quantity $quantity + ($stock->getQtAvailable() - $stock->getQtReserved());
  223.         $response = [
  224.             'res' => 'OK',
  225.             'stock' => $quantity,
  226.             'message' => 'Stock récupéré.',
  227.         ];
  228.         return new jsonResponse($response);
  229.     }
  230.     /**
  231.      * @Route("/api/commande-new", name="new_commande", methods={"POST"}, options={"expose"=true})
  232.      */
  233.     public function newCommande(Request $requestMessageBusInterface $bus): Response
  234.     {
  235.         //$rights = $this->rightService->getAllRights($this->getUser());
  236.         // Récupérer les donnés coté client
  237.         $client json_decode($request->request->get('client'), true);
  238.         $cart json_decode($request->request->get('cart'), true);
  239.         $remise json_decode($request->request->get('remise'), true);
  240.         $delivery json_decode($request->request->get('delivery'), true);
  241.         // Vérifier l'existence de client dans la base
  242.         $userByPhone $this->em->getRepository(User::class)->findOneBy(array('phone' => str_replace(' '''$client['telephone'])));
  243.         // Vérifier téléphone et username si nouveau client
  244.         if (!$this->getUser()) {
  245.             if ($userByPhone) {
  246.                 $response = [
  247.                     'res' => 'ERROR',
  248.                     'message' => "Numéro de téléphone déja utilisé.",
  249.                 ];
  250.             }
  251.         }
  252.         // Contrôle saisie des informations client si nouveau client
  253.         if (!$this->getUser() && !$userByPhone) {
  254. /*            if (!$client['nom']) {
  255.                 $response = [
  256.                     'res' => 'ERROR',
  257.                     'message' => 'Saisir votre nom.',
  258.                 ];
  259.                 return new jsonResponse($response);
  260.             }*/
  261.             /*if (!$client['prenom']) {
  262.                 $response = [
  263.                     'res' => 'ERROR',
  264.                     'message' => 'Saisir votre prénom.',
  265.                 ];
  266.                 return new jsonResponse($response);
  267.             }*/
  268.             if (!$client['telephone']) {
  269.                 $response = [
  270.                     'res' => 'ERROR',
  271.                     'message' => 'Saisir votre numéro de téléphone.',
  272.                 ];
  273.                 return new jsonResponse($response);
  274.             }
  275.            /* if (!$client['gouvernorat']) {
  276.                 $response = [
  277.                     'res' => 'ERROR',
  278.                     'message' => 'Sélectionner votre gouvernorat.',
  279.                 ];
  280.                 return new jsonResponse($response);
  281.             }
  282.             if (!$client['adresse']) {
  283.                 $response = [
  284.                     'res' => 'ERROR',
  285.                     'message' => 'Saisir votre adresse de livraison.',
  286.                 ];
  287.                 return new jsonResponse($response);
  288.             }*/
  289.             if ($client['email'])
  290.                 if ($client['email'] && !filter_var($client['email'], FILTER_VALIDATE_EMAIL)) {
  291.                     $response = [
  292.                         'res' => 'ERROR',
  293.                         'message' => 'Adresse mail non valide.',
  294.                     ];
  295.                     return new jsonResponse($response);
  296.                 } else {
  297.                     $userByEmail $this->em->getRepository(User::class)->findOneBy(array('email' => $client['email']));
  298.                     if ($userByEmail) {
  299.                         $response = [
  300.                             'res' => 'ERROR',
  301.                             'message' => "E-mail déja utilisé.",
  302.                         ];
  303.                         return new jsonResponse($response);
  304.                     }
  305.                 }
  306.         }
  307.         // Vérifcation de code promo si on a
  308.         $date = new \DateTime('now');
  309.         $promotionServer null;
  310.         if ($remise['id']) {
  311.             $promotionServer $this->promotionRepository->find($remise['id']);
  312.             if ($promotionServer) {
  313.                 if (!$promotionServer->isValid()) {
  314.                     $response = [
  315.                         'res' => 'ERROR',
  316.                         'message' => 'Code promo expiré.',
  317.                     ];
  318.                     return new jsonResponse($response);
  319.                 }
  320.                 // Vérifier la remise si sa quantité est définie
  321.                 if (($promotionServer->getQuntityUser() > && $promotionServer->getTotalQuantity() > 0) && $promotionServer->getQuntityUser() >= $promotionServer->getTotalQuantity()) {
  322.                     $response = [
  323.                         'res' => 'ERROR',
  324.                         'message' => "Code promo atteint le nombre maximum d'utilisations.",
  325.                     ];
  326.                     return new jsonResponse($response);
  327.                 }
  328.             }
  329.         }
  330.         // Vérifier si les produits commandés existe en stock et recalculer le total et le total ht
  331.         $total 0;
  332.         $totalHt 0;
  333.         $cartServer = [];
  334.         // Vérification des declinaisons et stock et calcul de total panier
  335.         foreach ($cart as $item) {
  336.             $produitDecllination $this->produitDeclinationValueRepository->find($item['id']);
  337.             if (!$produitDecllination) {
  338.                 $response = [
  339.                     'res' => 'ERROR',
  340.                     'message' => 'Le produit ' $item['name'] . ' est en rupture de stock.',
  341.                 ];
  342.                 return new jsonResponse($response);
  343.             }
  344.             if($produitDecllination){
  345.                 // Vérifier si on a de stock restant pour ce
  346.                 $stock $produitDecllination->getStocks()[0];
  347.                 if(!$stock){
  348.                     $response = [
  349.                         'res' => 'ERROR',
  350.                         'message' => 'Le produit '.$item['name'].' est en rupture de stock.',
  351.                     ];
  352.                     return new jsonResponse($response);
  353.                 }
  354.                 // Si le stock disponible est égale à 0
  355.                 if ($stock->getQtAvailable() - $stock->getQtReserved() <= 0) {
  356.                     $response = [
  357.                         'res' => 'ERROR',
  358.                         'message' => 'Le produit ' $item['name'] . ' est en rupture de stock.',
  359.                     ];
  360.                     return new jsonResponse($response);
  361.                 }
  362.                 // Si le stock diponible est > 0 mais n'est pas suffisant
  363.                 if(($item['qty'] > ($stock->getQtAvailable() - $stock->getQtReserved())) && (($stock->getQtAvailable()-$stock->getQtReserved()) > 0)){
  364.                     $response = [
  365.                         'res' => 'ERROR',
  366.                         'message' => 'Il ne reste que '.($stock->getQtAvailable()-$stock->getQtReserved()).' unités pour le produit '.$item['name'].'.',
  367.                     ];
  368.                     return new jsonResponse($response);
  369.                 };
  370.                 // Le produit existe et le stock est suffisant
  371.                 if($produitDecllination){
  372.                     array_push($cartServer$produitDecllination);
  373.                     // Calcul de prix si le produit est en promotion
  374.                     $promotion $produitDecllination->getProduit()->getPromotion();
  375.                     $decPrice $produitDecllination->getProduit()->getPriceTtc();
  376.                     $decPriceHt $produitDecllination->getProduit()->getPriceHt();
  377.                     if ($promotion) {
  378.                         if ($promotion->isValid()) {
  379.                             $decPrice = ($promotion->getDiscountType() == 'percent') ? $decPrice - ((($decPrice 100) * $promotion->getDiscountValue()))
  380.                                 : $decPrice $promotion->getDiscountValue();
  381.                             $decPriceHt = ($promotion->getDiscountType() == 'percent') ? $decPriceHt - ((($decPriceHt 100) * $promotion->getDiscountValue()))
  382.                                 : $decPriceHt $promotion->getDiscountValue();
  383.                         }
  384.                     }
  385.                     $total += $item['qty'] * floatval($decPrice);
  386.                     $totalHt += $item['qty'] * floatval($decPriceHt);
  387.                 }
  388.             }
  389.         }
  390.         // Calcule de montant de remise
  391.         $montantRemise 0;
  392.         if($promotionServer){
  393.             // Si total de panier inférieur à la remise on ne l'applique pas
  394.             if ($promotionServer->getDiscountType() == 'amount' && $promotionServer->getDiscountValue() > $total){
  395.                 $response = [
  396.                     'res' => 'ERROR',
  397.                     'message' => 'Il vous manque '.number_format(($promotionServer->getDiscountValue() - $total), 3'.'' ').' pour appliquer ce code promo',
  398.                 ];
  399.                 return new jsonResponse($response);
  400.             }
  401.             // Calcul de montant de remise
  402.             switch ($promotionServer->getDiscountType()){
  403.                 case 'amount':
  404.                     $montantRemise $promotionServer->getDiscountValue();
  405.                     break;
  406.                 case 'percent':
  407.                     $montantRemise $total*$promotionServer->getDiscountValue()/100;
  408.                     break;
  409.             }
  410.         }
  411.         // Suspend auto commit : début de la transaction
  412.         $this->em->getConnection()->beginTransaction();
  413.         try {
  414.             $user $this->getUser() ?? $userByPhone ?? null;
  415.             if (!$user) {  // Création de nouveau utilisateur
  416.                 $user = new User();
  417.                 $user->setType('client');
  418.                 $user->setUsermane(($client['nom']?$client['nom']:"Foulen") . ' ' . ($client['prenom']?$client['prenom']:"ben foulen"));
  419.                 $user->setFirstName($client['nom']?$client['nom']:"Foulen");
  420.                 $user->setLastName($client['prenom']?$client['prenom']:"ben foulen");
  421.                 $user->setCivility($client['civilite']);
  422.                 $user->setPhone(str_replace(' '''$client['telephone']));
  423.                 if ($client['email']) $user->setEmail($client['email']);
  424.                 $user->setAdress($client['adresse']);
  425.                 $user->setCreatedAt($date);
  426.                 if($client['adresse2'])$user->setSecondAdress($client['adresse2']);
  427.                 $user->setCountry('Tunisia');
  428.                 $user->setRegion($client['gouvernorat']);
  429.                 if($client['ville'])$user->setCity($client['ville']);
  430.                 if($client['codePostale'])$user->setZip($client['codePostale']);
  431.                 // Enregistrer le nouveau utilisateur
  432.                 $this->em->persist($user);
  433.             }
  434.             /*if( ! $user->getMultiAddress()->count() ){
  435.                 $adress = new Address();
  436.                 $adress->setAddress($client['adresse']);
  437.                 $adress->setCity($client['ville']);
  438.                 $adress->setZip($client['codePostale']);
  439.                 $adress->setRegion($client['gouvernorat']);
  440.                 $adress->setCountry('Tunisia');
  441.                 $this->em->persist($adress);
  442.                 $user->addMultiAddress($adress);
  443.             }*/
  444.             if(empty($user->getAdress()))$user->setAdress($client['adresse']);
  445.             if(empty($user->getRegion()))$user->setRegion($client['gouvernorat']);
  446.             if(empty($user->getZip()))$user->setZip($client['codePostale']);
  447.             if(empty($user->getCountry()))  $user->setCountry('Tunisia');
  448.             // Enregistrer la commande
  449.             $document = new Document();
  450.             //$date = new \DateTime('now');
  451.             $type 'commande';
  452.             $document->setType($type);
  453.             $document->setCategory('client');
  454.             $document->setCreatedAt(new \DateTime('now'));
  455.             $document->setEndAt($date->add(new \DateInterval('P30D')));
  456.             $document->setAdress($client['adresse'].' '.$client['codePostale'].' '.$client['ville'].' '.$client['gouvernorat']);
  457.             $document->setPaymentMethod('especes');
  458.             $document->setStatus('En attente');
  459.             $document->setConditionDocument('Aucun');
  460.             $document->setInternalNbr('BDC-' date('dmY') . '-' rand(1000099999));
  461.             $document->setClient($user);
  462.             $document->setUser($user);
  463.             //if ($request->isMethod('POST')) {
  464.             //dd($request);
  465.             $message 'Le client ' $user->getFirstName() . ' ajouter un bon commande ' $document->getInternalNbr();
  466.             $this->activityService->addActivity('info'$message$document$user'document');
  467.             //if ($request->get('form_document')) {
  468.             //$data = $request->get('form_document');
  469.             //if ($remie['discount'] == "") $data['discount'] = 0;
  470.             //$dateDelivery = ($data['deliveryAt'] && $data['deliveryAt'] != '' && $data['deliveryAt'] != null)?
  471.             //    new \DateTime($data['deliveryAt']): null;
  472.             // Livraison
  473.             $deliveryServer $this->deliveryRepository->find($delivery['id']);
  474.             $document
  475.                 ->setObject('Commande site web n°: ' $document->getInternalNbr())
  476.                 ->setTotalAmountHt($totalHt)
  477.                 // Code promo appliqué
  478.                 ->setPromotion($promotionServer $promotionServer null)
  479.                 //->setParcelTrackingNbr($data['parcelTrackingNbr'])
  480.                 //->setPaymentMethod($data['paymentMethod'])
  481.                 //->setPaymentDeadline($data['paymentDeadline'])
  482.                 ->setDiscount($promotionServer $promotionServer->getDiscountValue() : null)
  483.                 ->setDiscountType($promotionServer $promotionServer->getDiscountType() : null)
  484.                 ->setAdvancePayment(0);
  485.             //->setAdvancePaymentType($data['advancePaymentType'])
  486.             //->setPackagesNbr($data['packagesNbr'])
  487.             //->setUrlTracking($data['urlTracking'])
  488.             //->setDeliveryAt($dateDelivery)
  489.             //->setNote($client['commentaire'] ?$client['commentaire'] :null);
  490.             // Incrémenter l'usage de code promo
  491.             if ($promotionServer && $promotionServer->getQuntityUser() > && $promotionServer->getTotalQuantity() > 0) {
  492.                 if ($promotionServer->getQuntityUser() >= $promotionServer->getTotalQuantity()) {
  493.                     $response = [
  494.                         'res' => 'ERROR',
  495.                         'message' => "Code promo atteint le nombre de maximum d'utilisations.",
  496.                     ];
  497.                     return new jsonResponse($response);
  498.                 }
  499.                 $promotionServer->setQuntityUser($promotionServer->getQuntityUser() + 1);
  500.                 $this->em->persist($promotionServer);
  501.             }
  502.             // Ressource
  503.             $resource $this->resourceRepository->find(6); // Site Web
  504.             $document->setResource($resource);
  505.             // Livraison
  506.             $max = isset($_ENV['FREE_DELIVERY_AMOUNT']) ? floatval($_ENV['FREE_DELIVERY_AMOUNT']) : 0;
  507.             if ($deliveryServer) {
  508.                 $document->setDelivery($deliveryServer)
  509.                     ->setDeliveryPrice($deliveryServer->getPrice());
  510.                 // Si le seuil de livraison gratuite est atteint
  511.                 if ($max && $total $montantRemise >= $max) {
  512.                     $document->setDeliveryDiscount(100)
  513.                         ->setDeliveryDiscountType('percent')
  514.                         //->setDeliveryTotal($deliveryServer->getTotalPrice())
  515.                         ->setDeliveryTotal($deliveryServer->getPrice())
  516.                         ->setDeliveryPrice(0);
  517.                 } else {
  518.                     //$document->setDeliveryTotal($deliveryServer->getTotalPrice())
  519.                     $document->setDeliveryTotal($deliveryServer->getPrice())
  520.                     ->setDeliveryPrice($deliveryServer->getPrice());
  521.                 }
  522.             };
  523.             // Livraison gratuite
  524.             // $montantLivraisonGratuite = 200;
  525.             $deliveryPrice 0;
  526.             if (!$deliveryServer || ($deliveryServer && $max && $total $montantRemise >= $max)){
  527.                 $document->setIsFreeDelivery(true);
  528.             }
  529.             else{
  530.                 $document->setIsFreeDelivery(false);
  531.                 $deliveryPrice $deliveryServer->getPrice();
  532.             }
  533.             // total ttc
  534.             // On ajoute le prix de livraison au total ttc
  535.             $document->setTotalAmountTtc($total $montantRemise $deliveryPrice);
  536.             // On applique la tva 19%
  537.             //$tvaDelivery = $this->tvaRepository->find(2);
  538.             //$document->setDeliveryTva(null);
  539.             //Ajout de commentaire
  540.             if ($client['commentaire']) {
  541.                     //foreach ($data['comment'] as $item) {
  542.                     $comment = new Comment();
  543.                     $comment->setCreateAt(new \DateTime('now'));
  544.                     $comment->setDescription($client['commentaire'])
  545.                         ->setUser($user);
  546.                     $this->em->persist($comment);
  547.                     $document->addComment($comment);
  548.                     //$document->addDocumentComment($comment);
  549.                     //}
  550.                 }
  551.                     $this->em->persist($document);
  552.                     // Enregistrement des produits commandés
  553.                     if ($cartServer) {
  554.                         foreach ($cartServer as $key => $item) {
  555.                             $entity = new DocumentDeclinationProduit();
  556.                             $entity->setType('produitDeclination');
  557.                             if ($item->getID()) {
  558.                                 //$produitDecllination = $this->produitDeclinationValueRepository->find($item['id']);
  559.                                 $entity->setProduitDeclinationValue($item);
  560.                                 // Ajouter la quantité réservé dans le stoack
  561.                                 $stock $item->getStocks()[0];
  562.                                 if ($stock) {
  563.                                     $message 'Ajouter au quantité réserver ' . ($stock->getQtReserved() + $cart[$key]['qty']) . 'au declinaison' $stock->getDeclinationProduit()->getReference();
  564.                                     $this->activityService->addActivity('info'$message$stock$user'stock');
  565.                                     $stock->setQtReserved($stock->getQtReserved() + $cart[$key]['qty']);
  566.                                 }
  567.                                 // Set unité
  568.                                 $entity->setUnite($produitDecllination->getProduit()->getUnit());
  569.                             }
  570.                             // Calcul de prix
  571.                             $productPrice $item->getProduit()->getPriceTtc();
  572.                             $discountPrice 0;
  573.                             // Vérifier si le produit est en promotion et la promotion est valide
  574.                             $promotion $item->getProduit()->getPromotion();
  575.                             if ($promotion && $promotion->isValid()) {
  576.                                 $productPrice = ($promotion->getDiscountType() == 'percent') ? $productPrice - ((($productPrice 100) * $promotion->getDiscountValue()))
  577.                                     : $productPrice $promotion->getDiscountValue();
  578.                                 $discountPrice = ($promotion->getDiscountType() == 'percent') ? (($productPrice 100) * $promotion->getDiscountValue())
  579.                                     : $promotion->getDiscountValue();
  580.                             }
  581.                             $entity->setReference($item->getReference())
  582.                                 ->setDiscount(($promotion && $promotion->isValid()) ? $promotion->getDiscountValue() : 0)
  583.                                 ->setDiscountType($promotion && $promotion->isValid() ? $promotion->getDiscountType() : 'amount')
  584.                                 ->setPriceHt($item->getProduit()->getPriceTtc())  // Prix original sans remise
  585.                                 ->setQuantity($cart[$key]['qty'])
  586.                                 ->setCreatedAt(new \DateTime('now'))
  587.                                 ->setTotalAmount(floatval($productPrice) * $cart[$key]['qty']); // Total avec prix avec remise
  588.                             if ($item->getDescription()) $entity->setDescription($item->getDescription());
  589.                             // Affecter la tva de chaque produit (default 0%)
  590.                             $tva = ($item->getProduit()->getTva()) ? $item->getProduit()->getTva() : $this->tvaRepository->findOneBy(["id" => 1]);
  591.                             // Appliquer le Tva de chaque produit
  592.                             $entity->setTva($tva);
  593.                             //$entity->setDocument($document);
  594.                             // Fix le problème détails commande dans email
  595.                             $document->addDocumentDeclinationProduit($entity);
  596.                             $this->em->persist($entity);
  597.                         }
  598.                     }
  599.             //}
  600.             $this->em->flush();
  601.             // Envoi mail
  602.             if (isset($_ENV['MAILER_DSN']) && isset($_ENV['MAILER_MAIL'])) {
  603.                 if ($document->getClient()->getEmail() && filter_var($document->getClient()->getEmail(), FILTER_VALIDATE_EMAIL)) {
  604.                     $bus->dispatch(new Mail('front/mail/order.html.twig'$document), [new DelayStamp(10000)]);
  605.                 }
  606.             };
  607.             //}
  608.             // Try and commit the transaction
  609.             $this->em->getConnection()->commit();
  610.         } catch(Exception $e) {
  611.             // Rollback the failed transaction
  612.             $this->em->getConnection()->rollBack();
  613.             throw $e;
  614.         }
  615.         $response = [
  616.             'res' => 'OK',
  617.             'data' => $document->getInternalNbr(),
  618.             'message' => 'Votre commande a été enregistré avec succès.',
  619.         ];
  620.         return new jsonResponse($response);
  621.     }
  622.     // Fonction pour afficher la page de Commande crée avec succès
  623.     /**
  624.      * @Route("/recap", name="recap", options={"expose"=true}, methods={"GET"})
  625.      */
  626.     public function orderRecap(Request $request,DocumentRepository $documentRepository): Response
  627.     {
  628.         // Récupérer référence de la commande
  629.         //$idCommande = $request->query->get('idCommande');
  630.         $id $request->query->get('id');
  631.         //$document = $this->em->getRepository(Document::class)->findOneBy(array('internalNbr' => $idCommande));
  632.        // dd(sha1($document->getInternalNbr()));
  633.         $document =   $documentRepository->findBySha1($id);
  634.         // Récupérer les catégories
  635.         //$categories = $this->em->getRepository(Category::class)->findAll();
  636.         $max = isset($_ENV['FREE_DELIVERY_AMOUNT']) ? floatval($_ENV['FREE_DELIVERY_AMOUNT']) : 0;
  637.         return $this->render('front/cart/recapCommande.html.twig', [
  638.             'document' => $document,
  639.             'max' => $max
  640.         ]);
  641.     }
  642. }