src/Controller/Order/OrderController.php line 542

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controller\Order;
  4. use FOS\RestBundle\View\View;
  5. use Sylius\Bundle\ResourceBundle\Controller\RequestConfiguration;
  6. use Sylius\Bundle\ResourceBundle\Controller\ResourceController;
  7. use Sylius\Component\Order\Context\CartContextInterface;
  8. use Sylius\Component\Order\Model\OrderInterface;
  9. use Sylius\Component\Order\Repository\OrderRepositoryInterface;
  10. use Sylius\Component\Order\SyliusCartEvents;
  11. use Sylius\Component\Resource\ResourceActions;
  12. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  13. use Symfony\Component\EventDispatcher\GenericEvent;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpKernel\Exception\HttpException;
  17. use Webmozart\Assert\Assert;
  18. use SM\Factory\FactoryInterface;
  19. use Twig\Environment;
  20. use Symfony\Component\HttpFoundation\JsonResponse;
  21. use App\Services\WSColissimoService;
  22. use App\Services\WSShop2ShopService;
  23. use App\Entity\SiteShop;
  24. use App\Entity\SiteCommentOrder;
  25. use App\Form\Type\SiteCommentOrderType;
  26. use App\Controller\CartController;
  27. use App\Entity\Addressing\Address;
  28. use Symfony\Component\Process\Process;
  29. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  30. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  31. // use Sylius\Bundle\CoreBundle\Controller\OrderController as BaseOrderController;
  32. use Sylius\Bundle\OrderBundle\Controller\OrderController as BaseOrderController;
  33. use Symfony\Component\Messenger\MessageBusInterface;
  34. use App\Message\ValidateOrder;
  35. use Sylius\Component\Channel\Context\ChannelContextInterface;
  36. use App\Form\Type\SiteCodePromotionType;
  37. use Sylius\Bundle\AdminBundle\EmailManager\OrderEmailManagerInterface;
  38. use Sylius\Component\Mailer\Sender\SenderInterface;
  39. use App\Services\PPMCErpSynchroService;
  40. use Sylius\Component\Core\Model\AdjustmentInterface;
  41. use App\Entity\SiteApel;
  42. use Monolog\Logger;
  43. use App\Entity\SiteProductNoStock;
  44. use Sylius\Component\Inventory\Checker\AvailabilityChecker;
  45. use DateTime;
  46. use Carbon\Carbon;
  47. use phpDocumentor\Reflection\Types\Integer;
  48. class OrderController extends BaseOrderController
  49. {
  50.     public function summaryAction(Request $request$tokenValue null): Response
  51.     {
  52.         
  53.         // echo 'coucou';dump($form);
  54.         // exit();
  55.         $this->payLog($request$tokenValue);
  56.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  57.         
  58.         
  59.         // On arrive sur le panier après un paiement annulé ou refusé
  60.         if (empty($tokenValue) == false) {
  61.             $citelisLink $request->getSession()->get('citelis_link'null);
  62.             if (empty($citelisLink)) {
  63.                 $customer $this->get('sylius.context.customer')->getCustomer();
  64.                 $cart $this->get('sylius.repository.order')->findOneBy([
  65.                     'tokenValue' => $tokenValue,
  66.                     'customer' => $customer,
  67.                     'state' => 'new'
  68.                 ]);
  69.     
  70.                 // dump($cart);exit
  71.                 if (empty($cart) == false && $cart->getPaymentState() == 'awaiting_payment') {
  72.                     $orderSM $this->get('sm.factory')->get($cart'sylius_order_checkout');
  73.                     if ($orderSM->can('reset')) {
  74.                         $orderSM->apply('reset');
  75.                     }
  76.                 }
  77.     
  78.                 // Redirection sur la même page tout en conservant 
  79.                 // les messages flashes
  80.                 // dump($request);
  81.                 foreach ($request->getSession()->getFlashBag() as $type => $message) {
  82.                     $this->getSession()->add($type$message);
  83.                 }
  84.                 return $this->redirectHandler->redirectToRoute(
  85.                     $configuration,
  86.                     'sylius_shop_cart_summary'
  87.                 );
  88.             }
  89.             else {
  90.                 $request->getSession()->getFlashBag()->clear();
  91.                 $request->getSession()->getFlashBag()->add(
  92.                     'info',
  93.                     "Le lien a bien été envoyé"
  94.                 );
  95.                 $request->getSession()->remove('citelis_link');
  96.                 return $this->redirectHandler->redirectToRoute(
  97.                     $configuration,
  98.                     'sylius_shop_homepage'
  99.                 );
  100.                 // foreach ($request->getSession()->getFlashBag() as $type => $message) {
  101.                     // $this->getSession()->add($type, $message);
  102.                 // }
  103.             }
  104.         }
  105.         
  106.         // dump($request);
  107.         $cart $this->getCurrentCart();
  108.         if (null !== $cart->getId()) {
  109.             $cart $this->getOrderRepository()->findCartById($cart->getId());
  110.             if(strpos($request->getPathInfo(), 'cart') !== false) {
  111.                 //On supprime la carte cadeau
  112.                 foreach($cart->getPayments() as $payment) {
  113.                     $details $payment->getDetails();
  114.                     if(array_key_exists('giftCardCode'$details)) {
  115.                         $cart->removePayment($payment);
  116.                     }
  117.                 }
  118.     
  119.                 $adjustements $cart->getAdjustments();
  120.                 foreach($adjustements as $adjustement) {
  121.                     $details $adjustement->getDetails();
  122.                     if($adjustement->getType() == AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT && array_key_exists('giftCardCode'$details)) {
  123.                         $adjustement->unlock();
  124.                     }
  125.                 }
  126.                 $cart->removeAdjustments(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
  127.                 $cartManager $this->container->get('sylius.manager.order');
  128.                 $cartManager->persist($cart);
  129.                 $cartManager->flush();
  130.             }
  131.         }
  132.         if (!$configuration->isHtmlRequest()) {
  133.             return $this->viewHandler->handle($configurationView::create($cart));
  134.         }
  135.         $form $this->resourceFormFactory->create($configuration$cart);
  136.         // $isFine = CartController::stockVerification($cart, $request);
  137.         $this->applyReducedPricesToCart$this->container->get('sylius.context.channel')->getChannel(), $cart$this->container->get('doctrine.orm.entity_manager'));
  138.         $amount 0;
  139.         $total 0;
  140.         $diff 0;
  141.         $progress 0;
  142.         $cdts $this->container->get('sylius.repository.promotion')->findOneByCode('FREE_DELIVERY')->getRules();
  143.         foreach($cdts as $cdt){
  144.            
  145.             if( $cdt->getType() == 'item_total'){
  146.                 $amount $cdt->getConfiguration()['ppmc']['amount'];
  147.                 $total $cart->getItemsTotal();   
  148.                 $diff $amount-$total;   
  149.                 $progress $total $amount 100;        
  150.             }
  151.         } 
  152.         // Emballage cadeau
  153.         // 1) Il y a les produits pour "J'emballge moi-même"
  154.         // 2) Il y a les produits pour "Prêt à offrir"
  155.         // Ce ne sont pas les même !
  156.         $giftWrapMyself $this->container->get('sylius.repository.product_variant')->findGiftWrapMyself(
  157.             $this->container->get('sylius.context.channel')->getChannel(),
  158.             $this->container->get('sylius.context.locale')->getLocaleCode()
  159.         );
  160.         $giftWrapPPMC $this->container->get('sylius.repository.product_variant')->findGiftWrapPPMC(
  161.             $this->container->get('sylius.context.channel')->getChannel(),
  162.             $this->container->get('sylius.context.locale')->getLocaleCode()
  163.         );
  164.         // Produits dans "Un petit truc en plus"
  165.         // Des accessoires cheveux 
  166.         // de nouvelles collections uniquement
  167.         // 7 produits max aleatoire
  168.         // et 1 chouchou aléatoire peu importe la collection
  169.         $moreVariants $this->container->get('sylius.repository.product_variant')
  170.         ->findVariantsForCartPageIWantThisToo(
  171.             $this->container->get('sylius.context.channel')->getChannel(),
  172.             $this->container->get('sylius.context.locale')->getLocaleCode()
  173.         );
  174.         $cart->formCodePromo $this->createForm(SiteCodePromotionType::class);
  175.         $cart->formCodePromo->handleRequest($request);        
  176.         $cart->formCodePromo $cart->formCodePromo->createView();
  177.         //On vérifie les adresses du client au cas où, et on met une adresse par défaut
  178.         $customer $this->get('sylius.context.customer')->getCustomer();
  179.         if(!empty($customer) && empty($customer->getEmail())) {
  180.             $this->container->get('doctrine')->getManager()->initializeObject($customer);
  181.         }
  182.         if(!empty($customer) && empty($customer->getDefaultAddress())) {
  183.             $addresses $customer->getAddresses();
  184.             $this->container->get('doctrine')->getManager()->initializeObject($addresses);
  185.             if(!empty($addresses)) {
  186.                 foreach($addresses as $address) {
  187.                     // dump($address->getCompany());
  188.                     if($address->getCompany() == null || !str_contains($address->getCompany(), 'Boutique')) {
  189.                         $customer->setDefaultAddress($address);
  190.                         $customerManager $this->container->get('sylius.manager.customer');
  191.                         $customerManager->persist($customer);
  192.                         $customerManager->flush();
  193.                         break;
  194.                     }
  195.                 }
  196.             }
  197.         }    
  198.         
  199.         if(!empty($customer) && $cart->getBillingAddress() == null) {
  200.             $defaultAddress $customer->getDefaultAddress();
  201.             $this->container->get('doctrine')->getManager()->initializeObject($defaultAddress);
  202.             if (null !== $defaultAddress) {
  203.                 // dump($defaultAddress);
  204.                 $clonedAddress = clone $defaultAddress;
  205.                 $clonedAddress->setCustomer(null);
  206.                 $cart->setBillingAddress($clonedAddress);
  207.                 if($cart->getShippingAddress() == null) {
  208.                     $clonedAddress = clone $clonedAddress;
  209.                     $cart->setShippingAddress($clonedAddress);
  210.                 }
  211.                 $cartManager $this->container->get('sylius.manager.order');
  212.                 $cartManager->persist($cart);
  213.                 $cartManager->flush();
  214.             }
  215.         }
  216.         //On set le mode de livraison email si uniquement carte cadeau
  217.         $onlyCadeau true;
  218.         foreach($cart->getItems() as $item) {
  219.             if($item->getVariant()->getCode() != PPMCErpSynchroService::KDO_VARIANT_CODE) {
  220.                 $onlyCadeau false;
  221.                 break;
  222.             }
  223.         }    
  224.         if($onlyCadeau && !empty($cart->getId()) && !empty($cart->getItems())) {
  225.             //On a que des cartes cadeaux
  226.             $shippingMethod $this->container->get('sylius.repository.shipping_method')->createQueryBuilder('s')
  227.             ->where('s.code LIKE :code')
  228.             ->setParameter('code''EMAIL')
  229.             ->getQuery()
  230.             ->getOneOrNullResult();
  231.             
  232.             if(!empty($shippingMethod)) {
  233.                 if($cart->getShipments()->first()){
  234.                     $cart->getShipments()->first()->setMethod($shippingMethod);
  235.                 }
  236.                 $adjustements $cart->getAdjustments();
  237.                 foreach($adjustements as $adjustement) {
  238.                     $details $adjustement->getDetails();
  239.                     if($adjustement->getType() == AdjustmentInterface::SHIPPING_ADJUSTMENT) {
  240.                         $adjustement->unlock();
  241.                     }
  242.                 }
  243.                 $cart->removeAdjustments(AdjustmentInterface::SHIPPING_ADJUSTMENT);
  244.                 $cartManager $this->container->get('sylius.manager.order');
  245.                 $cartManager->persist($cart);
  246.                 $cartManager->flush();
  247.             }
  248.         }
  249.         //On surpprime les produits plus dispo
  250.         // $availabilityChecker = new AvailabilityChecker(false);
  251.                 
  252.         $removeProducts false;
  253.         if(!empty($cart->getItems())) {
  254.             $em $this->container->get('doctrine')->getManager();
  255.             $siteProductNoStockRepo $em->getRepository(SiteProductNoStock::class);
  256.             foreach($cart->getItems() as $item) {
  257.                 
  258.                 // if($cart->getId() == 91814){
  259.                 //     dump($item);
  260.                 // }
  261.                 $available = (($item->getVariant()->getOnHand()-($item->getVariant()->getItemMin() - 1)) > $item->getQuantity());
  262.                 // dump($item->getVariant());
  263.                 // if($_SERVER['HTTP_X_FORWARDED_FOR'] == '91.168.137.186') {
  264.                     // dump($item->getVariant()->getOnHand());
  265.                     // dump($item->getVariant()->getItemMin());
  266.                     // dump($item->getQuantity());
  267.                 //     dump($item->getVariant()->getItemMin());
  268.                 // }
  269.                 if(!$available) {
  270.                     $this->get('session')->getFlashBag()->add('error''Le produit : '.$item->getVariantName().' n\'est plus disponible, il a été enlevé de votre panier');
  271.                     $this->container->get('sylius.order_modifier')->removeFromOrder($cart$item);
  272.                     $removeProducts true;   
  273.                     
  274.                     $siteProductNoStockRepo $em->getRepository(SiteProductNoStock::class);
  275.                     $siteProductsNoStockExist $siteProductNoStockRepo->findBy(
  276.                         [
  277.                             'productVariant' => $item->getVariant(),
  278.                             'order' => $cart,
  279.                         ]
  280.                     );   
  281.                     if(count($siteProductsNoStockExist) == 0){ 
  282.                         $siteProductsNoStock = new SiteProductNoStock();
  283.                         $siteProductsNoStock->setOrder($cart);
  284.                         $siteProductsNoStock->setProductvariant($item->getVariant());
  285.                         $siteProductsNoStock->setCreatedAt(new DateTime());
  286.                         $em->persist($siteProductsNoStock);
  287.                         $em->flush();
  288.                     }    
  289.                 
  290.                 }
  291.             }
  292.             if($removeProducts) {
  293.                 $cartManager $this->container->get('sylius.manager.order');
  294.                 $cartManager->persist($cart);
  295.                 $cartManager->flush();
  296.                 $this->applyReducedPricesToCart$this->container->get('sylius.context.channel')->getChannel(), $cart$this->container->get('doctrine.orm.entity_manager'));
  297.             }
  298.         }
  299.             dump($cart);
  300.         $siteProductsNoStock = array();
  301.         if (null !== $cart->getId()) {
  302.             $em $this->container->get('doctrine')->getManager();
  303.             $siteProductNoStockRepo $em->getRepository(SiteProductNoStock::class);
  304.             $siteProductsNoStock $siteProductNoStockRepo->findBy(
  305.                 ['order' => $cart->getId()]
  306.             ); 
  307.         }
  308.         return $this->render(
  309.             $configuration->getTemplate('summary.html'),
  310.             [
  311.                 'cart' => $cart,
  312.                 'form' => $form->createView(),
  313.                 'amount' => $amount,
  314.                 'total' => $total,
  315.                 'diff' => $diff,
  316.                 'progress' => $progress,
  317.                 'giftWrapMyself' => $giftWrapMyself,
  318.                 'giftWrapPPMC' => $giftWrapPPMC,
  319.                 'moreVariants' => $moreVariants,
  320.                 'siteProductsNoStock' => $siteProductsNoStock
  321.             ]
  322.         );
  323.     }
  324.     // public function getBusMessage(MessageBusInterface $bus) {
  325.     //     return $bus;
  326.     // }
  327.     public function summaryAjaxAction(Request $request$id): Response
  328.     {
  329.         // dump($request->getPathInfo());
  330.         // // $bus = new MessageBusInterface();
  331.         // dump($bus);
  332.         // exit();
  333.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  334.         $cart $this->getCurrentCart();
  335.         if (null !== $cart->getId()) {
  336.             $cart $this->getOrderRepository()->findCartById($cart->getId());
  337.         }
  338.         if (!$configuration->isHtmlRequest()) {
  339.             return $this->viewHandler->handle($configurationView::create($cart));
  340.         }
  341.         $form $this->resourceFormFactory->create($configuration$cart);
  342.         $repository $this->container->get('sylius.repository.order_item');
  343.         $orderItem $repository->findOneByIdAndCartId($id$cart->getId());
  344.    
  345.         if (!empty($orderItem)) {
  346.             $quantity min(99max(0intval($request->request->get('quantity'1))));
  347.             if($quantity == 0){
  348.                 $this->container->get('sylius.order_modifier')->removeFromOrder($cart$orderItem);
  349.             }else{
  350.                 if($quantity 10){
  351.                     $quantity 10;
  352.                 }
  353.                 $this->container->get('sylius.order_item_quantity_modifier')->modify($orderItem$quantity);
  354.             }
  355.             foreach($cart->getPayments() as $payment) {
  356.                 $details $payment->getDetails();
  357.                 if(array_key_exists('giftCardCode'$details)) {
  358.                     $cart->removePayment($payment);
  359.                 }
  360.             }
  361.     
  362.             $adjustements $cart->getAdjustments();
  363.             foreach($adjustements as $adjustement) {
  364.                 $details $adjustement->getDetails();
  365.                 if($adjustement->getType() == AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT && array_key_exists('giftCardCode'$details)) {
  366.                     $adjustement->unlock();
  367.                 }
  368.             }
  369.             $cart->removeAdjustments(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
  370.             // Recalcul des promotions
  371.             $this->container->get('sylius.order_processing.order_processor')->process($cart);
  372.             $cartManager $this->container->get('sylius.manager.order');
  373.             $cartManager->persist($cart);
  374.             $cartManager->flush();
  375.         }
  376.         
  377.         // $isFine = CartController::stockVerification($cart, $request);
  378.         $this->applyReducedPricesToCart$this->container->get('sylius.context.channel')->getChannel(), $cart$this->container->get('doctrine.orm.entity_manager'));
  379.         // if(strpos($request->getPathInfo(), 'select_shipping') !== false) {
  380.             //On supprime la carte cadeau
  381.             
  382.         // }
  383.         $amount 0;
  384.         $total 0;
  385.         $diff 0;
  386.         $progress 0;
  387.         $cdts $this->container->get('sylius.repository.promotion')->findOneByCode('FREE_DELIVERY')->getRules();
  388.         foreach($cdts as $cdt){
  389.            
  390.             if( $cdt->getType() == 'item_total'){
  391.                 $amount $cdt->getConfiguration()['ppmc']['amount'];
  392.                 $total $cart->getItemsTotal();   
  393.                 $diff $amount-$total;   
  394.                 $progress $total $amount 100;        
  395.             }
  396.         }   
  397.         return new JsonResponse([
  398.             'livraison' => $this->renderView(
  399.                 '@SyliusShop/Webapic/panier/pagepanier-right-livraison.html.twig',
  400.                 [
  401.                     'cart' => $cart,
  402.                     'form' => $form->createView(),
  403.                     'amount' => $amount,
  404.                     'total' => $total,
  405.                     'diff' => $diff,
  406.                     'progress' => $progress,
  407.                 ]
  408.             ),
  409.             'total' => $this->renderView(
  410.                 '@SyliusShop/Cart/Summary/_totals.html.twig',
  411.                 [
  412.                     'cart' => $cart,
  413.                     'form' => $form->createView(),
  414.                     'amount' => $amount,
  415.                     'total' => $total,
  416.                     'diff' => $diff,
  417.                     'progress' => $progress,
  418.                 ]
  419.             ),
  420.             'widgettop' =>$this->renderView('@SyliusShop/Cart/_widget.html.twig', [
  421.                 'cart' => $cart,
  422.             ]),
  423.             'items' => $this->renderView(
  424.                 '@SyliusShop/Cart/Summary/_items.html.twig',
  425.                 [
  426.                     'cart' => $cart,
  427.                     'form' => $form->createView(),
  428.                 ]
  429.             ),
  430.             // 'isFine' => true
  431.             // 'isFine' => $isFine
  432.         ]); 
  433.     }
  434.     public function widgetAction(Request $request): Response
  435.     {
  436.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  437.         $cart $this->getCurrentCart();
  438.         if (!$configuration->isHtmlRequest()) {
  439.             return $this->viewHandler->handle($configurationView::create($cart));
  440.         }
  441.         return $this->render(
  442.             $configuration->getTemplate('summary.html'),
  443.             [
  444.                 'cart' => $cart,
  445.             ]
  446.         );
  447.     }
  448.     public function updateAction(Request $request): Response
  449.     {
  450.         // exit();
  451.         //
  452.         // echo 'maj du cart';
  453.         // Cas d'un paiement annulé ou refusé
  454.         $tokenValue $request->query->get('tokenValue'null);
  455.         $paylinetoken $request->query->get('paylinetoken'null);
  456.         dump($this->metadata);
  457.         
  458.         if (empty($tokenValue) == false && empty($paylinetoken) == false) {
  459.             $cart $this->getOrderRepository()->findOneBy([
  460.                 'tokenValue' => $tokenValue
  461.             ]);
  462.             if (empty($cart) == false) {
  463.                 $orderSM $this->getSMFactory()->get($cart'sylius_order_checkout');
  464.                 if ($orderSM->can('reset')) {
  465.                     $orderSM->apply('reset');
  466.                 }
  467.             }
  468.         }
  469.         elseif(empty($tokenValue) == false) {
  470.             $cart $this->getOrderRepository()->findOneBy([
  471.                 'tokenValue' => $tokenValue
  472.             ]);
  473.             if (empty($cart) == false) {
  474.                 $orderSM $this->getSMFactory()->get($cart'sylius_order_checkout');
  475.                 if ($orderSM->can('reset')) {
  476.                     $orderSM->apply('reset');
  477.                 }
  478.             }
  479.             // dump($tokenValue);
  480.         }
  481.         dump($this->metadata);
  482.         dump($request);
  483.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  484.         dump($configuration);
  485.         $this->isGrantedOr403($configurationResourceActions::UPDATE);
  486.         try {
  487.             $resource $this->findOr404($configuration);
  488.         }
  489.         catch (NotFoundHttpException $exception) {
  490.             if($request->getSession()->get('sylius_order_id')) {
  491.                 $order $this->getOrderRepository()->findOneBy([
  492.                     'id' => $request->getSession()->get('sylius_order_id')
  493.                 ]);
  494.                 $order->setState('cart');
  495.                 $order->setCheckoutState('cart');
  496.                 $order->setPaymentState('cart');
  497.                 $order->setShippingState('cart');
  498.                 foreach($order->getPayments() as $payment) {
  499.                     $payment->setState('cart');
  500.                 }
  501.                 $payments $order->getPayments();
  502.                 if (count($payments) > 1) {
  503.                     $first true;
  504.                     foreach ($payments as $payment) {
  505.                         if ($first) {
  506.                             $first false;
  507.                             continue;
  508.                         }
  509.                         $order->removePayment($payment);
  510.                     }
  511.                 }
  512.                 // dump($order);
  513.                 //On supprime les cartes cadeaux
  514.                 // $order->getPayments()->first()->setState('cart');
  515.                 $this->getOrderRepository()->add($order);
  516.                 // $order->setShippingAdress(null);
  517.                 // $order->setBillingAddress(null);
  518.                 //
  519.                 return $this->redirectToRoute('sylius_shop_cart_summary');
  520.             }
  521.             else {
  522.                 throw new NotFoundHttpException(sprintf('The "%s" has not been found'$this->metadata->getHumanizedName()));
  523.             }
  524.         }
  525.         //On vérifie si on a une carte cadeau et on supprime si on est sur le choix shipping
  526.         $order=$resource;
  527.         if(strpos($request->getPathInfo(), 'select_shipping') !== false) {
  528.             //On supprime la carte cadeau
  529.             foreach($order->getPayments() as $payment) {
  530.                 $details $payment->getDetails();
  531.                 if(array_key_exists('giftCardCode'$details)) {
  532.                     $order->removePayment($payment);
  533.                 }
  534.             }
  535.             $adjustements $order->getAdjustments();
  536.             foreach($adjustements as $adjustement) {
  537.                 $details $adjustement->getDetails();
  538.                 if($adjustement->getType() == AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT && array_key_exists('giftCardCode'$details)) {
  539.                     $adjustement->unlock();
  540.                 }
  541.             }
  542.             $order->removeAdjustments(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
  543.         }
  544.         // if($_SERVER['HTTP_X_FORWARDED_FOR'] == '130.93.57.197') {
  545.             // $shippingMethodsResolver = $this->container->get('sylius.shipping_method_eligibility_checker');
  546.             
  547.             $shipment $order->getShipments()->first();
  548.             if(empty($shipment)) {
  549.                 //Cas d'erreur pas de transporteur sur le panier, ça peut arriver avec certains problèmes d'adresses
  550.                 $shippingMethod $this->container->get('sylius.repository.shipping_method')->findOneByCode('RETRAIT_EN_MAGASIN_1');
  551.                 // dump($shippingMethod);
  552.                 $shipment $this->container->get('sylius.factory.shipment')->createNew();
  553.                 $shipment->setMethod($shippingMethod);
  554.                 $shipment->setState('cart');
  555.                 // $shipment->setTracking($row->getShipments()[0]->getTracking());
  556.                 // $shipment->setCreatedAt(Carbon::createFromFormat('Y-m-d H:i:s', $row->getShipments()[0]->getCreatedAt())->toDateTime());
  557.                 // $shipment->setUpdatedAt(Carbon::createFromFormat('Y-m-d H:i:s', $row->getShipments()[0]->getUpdatedAt())->toDateTime());
  558.                 $order->addShipment($shipment);
  559.             }
  560.             $shippingMethodsResolver $this->container->get('sylius.shipping_methods_resolver');
  561.             $availableShippingMethods $shippingMethodsResolver->getSupportedMethods($order->getShipments()->first());
  562.             $forceChange true;
  563.             foreach($availableShippingMethods as $availableShippingMethod) {
  564.                 if($availableShippingMethod->getId() == $order->getShipments()->first()->getMethod()->getId()) {
  565.                     $forceChange false;
  566.                 }
  567.             }
  568.             if($forceChange) {
  569.                 //On change la méthode car celle propsoée n'est aps disponible dans le pays
  570.                 $shipment $order->getShipments()->first();
  571.                 $shipment->setMethod($availableShippingMethods[0]);
  572.                 $shipment->setState('cart');
  573.                 $order->addShipment($shipment);
  574.             }
  575.             // dump($forceChange);
  576.             // $shippingMethods =  $this->container->get('sylius.repository.shipping_method')->findBy([
  577.             //     'enabled' => 1
  578.             // ]);
  579.             // foreach($shippingMethods as $shippingMethod) {
  580.             //     if($shippingMethodsResolver->getSupportedMethods) {
  581.             //     }
  582.             // }
  583.             // dump();
  584.             
  585.             // dump($shipments);
  586.         // }
  587.         // if($_SERVER['HTTP_X_FORWARDED_FOR'] == '130.93.57.197') {
  588.         //     dump($order);
  589.         //     exit();
  590.         // }
  591.         //On surpprime les produits plus dispo
  592.         $removeProducts false;
  593.         if(!empty($order->getItems())) {
  594.             foreach($order->getItems() as $item) {
  595.                 // itemMin
  596.                 $available = (($item->getVariant()->getOnHand()-($item->getVariant()->getItemMin() - 1)) > $item->getQuantity());
  597.                 
  598.                 if(!$available) {
  599.                     $this->get('session')->getFlashBag()->add('error''Le produit : '.$item->getVariantName().' n\'est plus disponible, il a été enlevé de votre panier');
  600.                     $this->container->get('sylius.order_modifier')->removeFromOrder($order$item);
  601.                     $removeProducts true;
  602.                 }
  603.             }
  604.             if($removeProducts) {
  605.                 $cartManager $this->container->get('sylius.manager.order');
  606.                 $cartManager->persist($order);
  607.                 $cartManager->flush();
  608.                 $this->applyReducedPricesToCart$this->container->get('sylius.context.channel')->getChannel(), $order$this->container->get('doctrine.orm.entity_manager'));
  609.             }
  610.         }
  611.         
  612.         $this->getOrderRepository()->add($order);
  613.         
  614.         dump($configuration);
  615.         dump($order);
  616.         $form $this->resourceFormFactory->create($configuration$order);
  617.         
  618.         // dump($form->get('address'));
  619.         // $form->remove('address');
  620.         // $form->remove('second');
  621.         $form->handleRequest($request);
  622.         //On reload les sh
  623.         dump($form);
  624.         dump($order);
  625.         if (
  626.             in_array($request->getMethod(), ['POST''PUT''PATCH'], true)
  627.             && $form->isSubmitted()
  628.             && $form->isValid()
  629.         ) {
  630.             // try {
  631.             //     $form->remove('address');
  632.             // }        
  633.             // catch (\Exception $exception) {
  634.     
  635.             // }
  636.             $resource $form->getData();
  637.             
  638.             /** @var ResourceControllerEvent $event */
  639.             $event $this->eventDispatcher->dispatchPreEvent(ResourceActions::UPDATE$configuration$resource);
  640.             if ($event->isStopped() && !$configuration->isHtmlRequest()) {
  641.                 throw new HttpException($event->getErrorCode(), $event->getMessage());
  642.             }
  643.             if ($event->isStopped()) {
  644.                 $this->flashHelper->addFlashFromEvent($configuration$event);
  645.                 $eventResponse $event->getResponse();
  646.                 if (null !== $eventResponse) {
  647.                     return $eventResponse;
  648.                 }
  649.                 return $this->redirectHandler->redirectToResource($configuration$resource);
  650.             }
  651.             try {
  652.                 $this->resourceUpdateHandler->handle($resource$configuration$this->manager);
  653.             } catch (UpdateHandlingException $exception) {
  654.                 if (!$configuration->isHtmlRequest()) {
  655.                     return $this->createRestView($configuration$form$exception->getApiResponseCode());
  656.                 }
  657.                 $this->flashHelper->addErrorFlash($configuration$exception->getFlash());
  658.                 return $this->redirectHandler->redirectToReferer($configuration);
  659.             }
  660.             if ($configuration->isHtmlRequest()) {
  661.                 $this->flashHelper->addSuccessFlash($configurationResourceActions::UPDATE$resource);
  662.             }
  663.             // dump($configuration);
  664.             $postEvent $this->eventDispatcher->dispatchPostEvent(ResourceActions::UPDATE$configuration$resource);
  665.             // dump($postEvent);
  666.             if (!$configuration->isHtmlRequest()) {
  667.                 // dump($postEvent);
  668.                 if ($configuration->getParameters()->get('return_content'false)) {
  669.                     // dump($postEvent);
  670.                     return $this->createRestView($configuration$resourceResponse::HTTP_OK);
  671.                 }
  672.                 return $this->createRestView($configurationnullResponse::HTTP_NO_CONTENT);
  673.             }
  674.             // dump($postEvent);
  675.             $postEventResponse $postEvent->getResponse();
  676.             // dump($postEventResponse);
  677.             if (null !== $postEventResponse) {
  678.                 return $postEventResponse;
  679.             }
  680.             // dump(3);
  681.             return $this->redirectHandler->redirectToResource($configuration$resource);
  682.         }
  683.         if (!$configuration->isHtmlRequest()) {
  684.             return $this->createRestView($configuration$formResponse::HTTP_BAD_REQUEST);
  685.         }
  686.         $initializeEvent $this->eventDispatcher->dispatchInitializeEvent(ResourceActions::UPDATE$configuration$resource);
  687.         $initializeEventResponse $initializeEvent->getResponse();
  688.         if (null !== $initializeEventResponse) {
  689.             return $initializeEventResponse;
  690.         }
  691.         return $this->render($configuration->getTemplate(ResourceActions::UPDATE '.html'), [
  692.             'configuration' => $configuration,
  693.             'metadata' => $this->metadata,
  694.             'resource' => $resource,
  695.             $this->metadata->getName() => $resource,
  696.             'form' => $form->createView(),
  697.         ]);
  698.     }
  699.     public function thankYouAction(
  700.         Request $request,
  701.         MessageBusInterface $bus,  
  702.         CartController $cartController,
  703.         ChannelContextInterface $channelCtx,
  704.         OrderEmailManagerInterface $orderEmailManager,
  705.         SenderInterface $sender,
  706.     ): Response
  707.     {
  708.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  709.         $orderTokenValue $request->query->get('token_value'null);
  710.         $orderId $request->getSession()->get('sylius_order_id'null);
  711.         // dump($orderTokenValue);
  712.         // dump($orderId);
  713.         // dump($request->getSession());
  714.         // exit();
  715.         // Il y a un token dans la requête, on récupère la commande
  716.         // via ce token
  717.         if (empty($orderTokenValue) == false) {
  718.             $order $this->repository->findOneByTokenValue($orderTokenValue);
  719.             
  720.             if (empty($order) == true) {
  721.                 // La commande n'existe pas avec ce token
  722.                 return $this->redirectHandler->redirectToRoute(
  723.                     $configuration,
  724.                     'sylius_shop_cart_summary',
  725.                     []
  726.                 );
  727.             }
  728.         }
  729.         // La commande est dans la session, on redirige vers la même page 
  730.         // mais avec le "tokenValue"
  731.         if (empty($orderId) == false) {
  732.             $request->getSession()->remove('sylius_order_id');
  733.             $order $this->repository->find($orderId);
  734.             if (empty($order) == true) {
  735.                 // La commande n'existe plus du tout, on redirige sur le panier vide
  736.                 return $this->redirectHandler->redirectToRoute(
  737.                     $configuration,
  738.                     'sylius_shop_cart_summary',
  739.                     []
  740.                 );
  741.             }
  742.             // dump($order);
  743.             // dump($order->getTokenValue());
  744.             // dump( $request->attributes->get('_route'));
  745.             // dump($this->redirectHandler->);
  746.             // La commande existe, on redirige vers la page "thankYou" mais avec le tokenValue
  747.             return $this->redirectHandler->redirectToRoute(
  748.                 $configuration,
  749.                 $request->attributes->get('_route'),
  750.                 ['token_value' => $order->getTokenValue()]
  751.             );
  752.         }
  753.         Assert::notNull($order);
  754.         // dump($order);
  755.         // exit();
  756.         $form $this->createForm(SiteCommentOrderType::class);
  757.         $form->handleRequest($request);
  758.         $repoOrderComment $this->container->get('doctrine.orm.entity_manager')->getRepository(SiteCommentOrder::class);
  759.         $repoOrderComment $repoOrderComment->findOneBy(['idorder' => $order->getId()]);
  760.         // $commentExist = 0;
  761.         // if (!empty($repoOrderComment)) {
  762.         //     $commentExist = 1;
  763.         // }
  764.         if (
  765.             in_array($request->getMethod(), ['POST''PUT''PATCH'], true)
  766.             && $form->isSubmitted()
  767.             && $form->isValid()
  768.         ) {
  769.             $data $form->getData();
  770.            
  771.             if(!empty($data->getComment())){
  772.                 // $repoOrderComment = $this->container->get('doctrine.orm.entity_manager')->getRepository(SiteCommentOrder::class);
  773.                 
  774.                 if (!empty($repoOrderComment)) {
  775.                     $repoOrderComment->setComment($data->getComment());
  776.                 }else{
  777.                     $orderComment = new SiteCommentOrder();
  778.                     $orderComment->setIdorder($order->getId());
  779.                     $orderComment->setComment($data->getComment());
  780.                     $em $this->getDoctrine()->getManager();
  781.                     $em->persist($orderComment);
  782.                     $em->flush();
  783.                 }
  784.                 // $bus->dispatch(new ValidateOrder($order->getId(), true));
  785.                 $this->get('session')->getFlashBag()->add('success''Message envoyé !');
  786.             }else{
  787.                 $this->get('session')->getFlashBag()->add('error''Votre message est vide !');
  788.             }
  789.         }
  790.         // $bus = $this->get('sylius.bus.message');
  791.         // MessageBusInterface $bus)
  792.         $this->get('session')->getFlashBag()->clear();
  793.         
  794.         //On vient supprimer les adjustements liés aux eventuelles cartes cadeaux (facilité pour tunnel d'achat) 
  795.         $adjustements $order->getAdjustmentsRecursively();
  796.         foreach($adjustements as $adjustement) {
  797.             $details $adjustement->getDetails();
  798.             if($adjustement->getType() == AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT && array_key_exists('giftCardCode'$details)) {
  799.                 $adjustement->unlock();
  800.             }
  801.         }
  802.         $order->removeAdjustments(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
  803.         $orderManager $this->container->get('sylius.manager.order');
  804.         $orderManager->persist($order);
  805.         $orderManager->flush();
  806.         $bus->dispatch(new ValidateOrder($order->getId()));
  807.          //bug bizarre on a un nouveau pânier apres la creation de la commande
  808.         $cart $this->container->get('sylius.context.cart')->getCart();       
  809.         $cartItems $cart->getItems();
  810.         foreach ($cartItems as $cartRow) {
  811.             // dump($cartRow);
  812.             $this->container->get('sylius.order_modifier')->removeFromOrder($cart$cartRow);
  813.         }
  814.         
  815.         // $channel = $channelCtx->getChannel();
  816.         // $cartController->applyReducedPricesToCart($channel, $cart);
  817.         $cartManager $this->container->get('sylius.manager.order');
  818.         $cartManager->persist($cart);
  819.         $cartManager->flush();
  820.         //Email envoyé dans sync order désormais
  821.         // $orderEmailManager->sendConfirmationEmail($order);
  822.         
  823.         foreach($order->getPayments() as $paiement){
  824.             //SI PAIEMENT BANCAIRE
  825.             if($paiement->getMethod()->getId() == 3){
  826.                 $vars = array(
  827.                     'order' => $order,
  828.                     'localeCode' =>  $this->container->get('sylius.context.locale')->getLocaleCode()
  829.                 );
  830.                 $sender->send('orderpending', [$order->getCustomer()->getUser()->getEmail()], $vars);
  831.             }
  832.         }
  833.         // dump( $configuration->getParameters()->get('template'));
  834.         
  835.         return $this->render(
  836.             $configuration->getParameters()->get('template'),
  837.             [
  838.                 'order' => $order,
  839.                 'form' => $form->createView(),
  840.                 // 'commentExist' => $commentExist
  841.             ],
  842.         );
  843.     }
  844.     public function tokenSoColissimo(WSColissimoService $wsColissimo)
  845.     {
  846.         return new JsonResponse($wsColissimo->getTokenColissimo());
  847.     }
  848.     public function deliveryShop()
  849.     {
  850.        
  851.         $shopRepository $this->container->get('doctrine.orm.entity_manager')->getRepository(SiteShop::class);
  852.         $shops $shopRepository->createQueryBuilder('a')
  853.         ->where('a.enabled = 1')
  854.         ->orderBy('a.postalCode''ASC')
  855.         ->getQuery()
  856.         ->getResult();
  857.         return $this->render('order/block-delivery-shops.html.twig', [
  858.             'shops' => $shops
  859.         ]);
  860.     }
  861.     public function updateCartDelivery(Request $requestPPMCErpSynchroService $ppmcErpSynchroService)
  862.     {
  863.         $cart $this->getCurrentCart();   
  864.         $shippingMethods $this->container->get('sylius.repository.shipping_method')->createQueryBuilder('s')
  865.         ->where('s.code LIKE :code')
  866.         ->setParameter('code'$request->get('shippingMethod'))
  867.         ->getQuery()
  868.         ->getResult();
  869.         if(!empty($shippingMethods)) {
  870.             $shippingMethod $shippingMethods[0];
  871.             // $cart->getShipments()->first()->setState('ready');
  872.             $cart->getShipments()->first()->setMethod($shippingMethod);
  873.             $cart->setOrderPickupShop(null);
  874.             $cart->setOrderPickupSoColissimo(null);
  875.             $cart->setOrderPickupName(null);
  876.             if($request->get('identifiant')) {
  877.                 $cart->setOrderPickupSoColissimo($request->get('identifiant'));
  878.                 $cart->setOrderPickupName($request->get('nom'));
  879.             }
  880.             else if($request->get('idPickupShop')) {
  881.                 $cart->setOrderPickupShop($request->get('idPickupShop'));
  882.                 $cart->setOrderPickupName($request->get('pickupName'));
  883.             }
  884.             $cartManager $this->container->get('sylius.manager.order');
  885.             $cartManager->persist($cart);
  886.             $cartManager->flush();
  887.         }
  888.     
  889.         // dump($shippingMethod);
  890.         // $shippingMethod = $container->get('sylius.repository.shipping_method')->findOneById(
  891.         //     $generixRow->getShipments()[0]->getMethodId()
  892.         // );
  893.         // $order->setShippingState('cart');
  894.         // echo $request->get('shippingMethod');
  895.         return new JsonResponse('success');
  896.     }
  897.     protected function redirectToCartSummary(RequestConfiguration $configuration): Response
  898.     {
  899.         if (null === $configuration->getParameters()->get('redirect')) {
  900.             return $this->redirectHandler->redirectToRoute($configuration$this->getCartSummaryRoute());
  901.         }
  902.         return $this->redirectHandler->redirectToRoute($configuration$configuration->getParameters()->get('redirect'));
  903.     }
  904.     protected function getCartSummaryRoute(): string
  905.     {
  906.         return 'sylius_cart_summary';
  907.     }
  908.     protected function getCurrentCart(): OrderInterface
  909.     {
  910.         return $this->getContext()->getCart();
  911.     }
  912.     protected function getContext(): CartContextInterface
  913.     {
  914.         return $this->get('sylius.context.cart');
  915.     }
  916.     protected function getOrderRepository(): OrderRepositoryInterface
  917.     {
  918.         return $this->get('sylius.repository.order');
  919.     }
  920.     protected function getSMFactory()
  921.     {
  922.         return $this->container->get('sm.factory');
  923.     }
  924.     protected function getEventDispatcher(): EventDispatcherInterface
  925.     {
  926.         return $this->container->get('event_dispatcher');
  927.     }
  928.     /**
  929.      * @return mixed
  930.      *
  931.      * @deprecated This function will be removed in Sylius 2.0, since Symfony 5.4, use explicit input sources instead
  932.      * based on Symfony\Component\HttpFoundation\Request::get
  933.      */
  934.     private function getParameterFromRequest(Request $requeststring $key)
  935.     {
  936.         if ($request !== $result $request->attributes->get($key$request)) {
  937.             return $result;
  938.         }
  939.         if ($request->query->has($key)) {
  940.             return $request->query->all()[$key];
  941.         }
  942.         if ($request->request->has($key)) {
  943.             return $request->request->all()[$key];
  944.         }
  945.         return null;
  946.     }
  947.     public function paiementkdoShop(Request $requestPPMCErpSynchroService $ppmcErpSynchroService)
  948.     {
  949.         $cart $this->getCurrentCart();   
  950.         $giftCard $ppmcErpSynchroService->checkGiftCard(
  951.             $request->get('code'),
  952.             $request->get('key')
  953.         );
  954.         if($request->get('use')) {
  955.             if($giftCard->getAmount()) {
  956.                 $giftAmout = (int)($giftCard->getAmount()*100);
  957.                 if($cart->getTotal() < $giftAmout) {
  958.                     $giftAmout $cart->getTotal();
  959.                 }
  960.                 else {
  961.                     foreach($cart->getPayments() as $payment) {
  962.                         if($payment->getState() == 'cart') {
  963.                             $payment->setAmount($payment->getAmount()-$giftAmout);
  964.                             break;
  965.                         }
  966.                     }
  967.                 }
  968.                 // echo $giftAmout;
  969.                 //On ajoute une ligne de paiement
  970.                 $payment $this->container->get('sylius.factory.payment')->createNew();
  971.                 $payment->setCurrencyCode('EUR');
  972.                 $payment->setDetails([
  973.                     "giftCardCode" => $request->get('code'),
  974.                     "giftCardKey" => $request->get('key')
  975.                 ]);
  976.                 $payment->setMethod($this->container->get('sylius.repository.payment_method')->findOneByCode('KDO'));
  977.                 $payment->setAmount($giftAmout);
  978.                 $payment->setState('completed');
  979.                 $cart->addPayment($payment);
  980.                 //On ajoute un adjsutment pour les prochgains calculs du reste à payer
  981.                 $adjustment $this->container->get('sylius.factory.adjustment')->createNew();
  982.                 $adjustment->setType(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
  983.                 $adjustment->setAmount(-$giftAmout);
  984.                 $adjustment->setNeutral(false);
  985.                 $adjustment->setLabel('Carte cadeau : '.$request->get('code'));
  986.                 $adjustment->setDetails([
  987.                     "giftCardCode" => $request->get('code')
  988.                 ]);
  989.                 $cart->addAdjustment($adjustment);
  990.                 $adjustment->lock();
  991.                 $cartManager $this->container->get('sylius.manager.order');
  992.         
  993.                 $cartManager->persist($cart);
  994.                 $cartManager->flush();
  995.                 $this->container->get('doctrine.orm.entity_manager')->refresh($cart);
  996.             }
  997.         }
  998.         return new JsonResponse([
  999.             "amount"     => $giftCard->getAmount(),
  1000.             "error"        =>    $giftCard->getError()
  1001.         ]);
  1002.     }
  1003.     public function deliveryApel(Request $requestPPMCErpSynchroService $ppmcErpSynchroService)
  1004.     {
  1005.         $em $this->get('doctrine')->getManager();
  1006.         if ($request->isMethod('POST')) {
  1007.             $error "";
  1008.             $success "";
  1009.             
  1010.             $cart $this->getCurrentCart();   
  1011.         
  1012.             $nom $request->get('nom');
  1013.             $prenom $request->get('prenom');
  1014.             $classe $request->get('classe');
  1015.             $idecole $request->get('idecole');
  1016.             if(!empty($nom) && !empty($prenom) && !empty($classe) && !empty($idecole)){
  1017.                 $apelData = array(
  1018.                     'nom' => $nom,
  1019.                     'prenom' => $prenom,
  1020.                     'classe' => $classe,
  1021.                     'idecole' => $idecole,
  1022.                 );
  1023.                 $ecole $em->getRepository(SiteApel::class)->find($idecole);
  1024.                 $cart->setApel(json_encode($apelData));       
  1025.                 $cartManager $this->container->get('sylius.manager.order');
  1026.                 $cartManager->persist($cart);
  1027.                 $cartManager->flush();
  1028.                 $this->container->get('doctrine.orm.entity_manager')->refresh($cart);
  1029.                 $success "Les informations sont sauvegardées";
  1030.             }else{
  1031.                 $error "Veuillez saisir toutes les informations et choisir une école";
  1032.                 return new JsonResponse([
  1033.                     "error"        =>    $error,
  1034.                 ]);
  1035.             }
  1036.                 // $cart->setOrderPickupShop(null);
  1037.             return new JsonResponse([
  1038.                 "success"    =>    $success,
  1039.                 "info"        =>    'Ecole '.$ecole->getName().' - '.$nom.' '.$prenom.' en classe de '.$classe,
  1040.             ]);
  1041.         }else{
  1042.            
  1043.             // $apels = $em->getRepository(SiteApel::class)->findAll();
  1044.             $shopRepository $em->getRepository(SiteApel::class);
  1045.             $apels $shopRepository->createQueryBuilder('a')
  1046.             ->where('a.enabled = 1')
  1047.             ->orderBy('a.postalCode''ASC')
  1048.             ->getQuery()
  1049.             ->getResult();
  1050.             $listapels = array();
  1051.             if(count($apels) > 0){
  1052.                 foreach($apels as $key => $apel){
  1053.                     // $listapels[] = $apel;
  1054.                    
  1055.                     if( ( empty($apel->getDateStart()) || empty($apel->getDateEnd()))
  1056.                     || ( time() > $apel->getDateStart()->getTimestamp() && time() < $apel->getDateEnd()->getTimestamp() )
  1057.                     ){
  1058.                         // $listapels[$key]['lat'] = $apel->getLat();
  1059.                         // $listapels[$key]['long'] = $apel->getLon();
  1060.                         // $listapels[$key]['id'] = $apel->getId();
  1061.                         // $listapels[$key]['desc'] = $apel->getName()." - ".$apel->getCity();
  1062.                         $apeljson = array();
  1063.                         $apeljson['lat'] = $apel->getLat();
  1064.                         $apeljson['long'] = $apel->getLon();
  1065.                         $apeljson['id'] = $apel->getId();
  1066.                         $apeljson['desc'] = $apel->getName()." - ".$apel->getCity();
  1067.                         $listapels[] = $apeljson;
  1068.                     }
  1069.                    
  1070.                 }
  1071.             }
  1072.             
  1073.     
  1074.             return new JsonResponse(
  1075.                 $listapels
  1076.             );
  1077.         }
  1078.     }
  1079.     public function submitCoupon(Request $request)
  1080.     {
  1081.         $formCodePromo $this->createForm(SiteCodePromotionType::class);
  1082.         $formCodePromo->handleRequest($request);       
  1083.        
  1084.         $cart $this->getCurrentCart();    
  1085.         if(isset($_GET['codepromo'])){
  1086.             $codepromo '0';
  1087.         }else{
  1088.             $codepromo $request->request->get("app_site_codepromotion");
  1089.             $codepromo $codepromo['codePromo'];
  1090.         }
  1091.         
  1092.            
  1093.         $cart->setCodePromo$codepromo);                     
  1094.         $cartManager $this->container->get('sylius.manager.order');
  1095.         $cartManager->persist($cart);
  1096.         $cartManager->flush();
  1097.         $this->applyReducedPricesToCart$this->container->get('sylius.context.channel')->getChannel(), $cart$this->container->get('doctrine.orm.entity_manager'));
  1098.         if($cart->getCodePromoValid() == 1){
  1099.             $this->addFlash('success''Votre coupon est appliqué'.$request->request->get("app_site_codepromotion['codePromo']"));
  1100.         }else{
  1101.             if( $codepromo == 0){
  1102.                 $this->addFlash('error''Coupon supprimé');
  1103.             }else{
  1104.                 $this->addFlash('error''Ce coupon n\'existe pas');
  1105.             }
  1106.             
  1107.         }
  1108.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  1109.         return $this->redirectHandler->redirectToRoute(
  1110.             $configuration,
  1111.             'sylius_shop_cart_summary',
  1112.             []
  1113.         );
  1114.     }   
  1115.     public function applyReducedPricesToCart($channel$cart$em): void
  1116.     {
  1117.         
  1118.         // if (count($cart->getItems()) <= 0) {
  1119.         //     return;
  1120.         // }
  1121.        
  1122.         $process = new Process(['/usr/bin/php'$this->container->get('kernel')->getProjectDir().'/bin/console',  'ppmc:valorize-cart''--cartId='.$cart->getId()]);
  1123.         $process->setTimeout(4);
  1124.         try {
  1125.             $process->start();
  1126.             $process->wait();
  1127.             $em->refresh($cart);
  1128.         
  1129.             $cartItems $cart->getItems();
  1130.             foreach ($cartItems as $cartRow) {
  1131.                 $em->refresh($cartRow);
  1132.             }
  1133.         } catch (ProcessTimedOutException $exception) {
  1134.             // echo 'bofbof';
  1135.         }
  1136.     }
  1137.     public function commentAdminAction(Request $request)
  1138.     {
  1139.         
  1140.         // dump($order);
  1141.        
  1142.         $siteCommentOrder $this->getDoctrine()
  1143.         ->getRepository(SiteCommentOrder::class)
  1144.         ->findOneBy(
  1145.             [
  1146.                 'idorder' => $request->query->get('order')
  1147.             ]
  1148.         );
  1149.         $comment '';
  1150.         if($siteCommentOrder){
  1151.             $comment $siteCommentOrder->getComment();
  1152.         }
  1153.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  1154.         
  1155.         return $this->render(
  1156.             $configuration->getTemplate('admin/order/comment.html'),
  1157.             [
  1158.                 'comment' => $comment,
  1159.             ]
  1160.         );
  1161.     }
  1162.     protected function payLog(Request $request$token) {
  1163.         $cart $this->container->get('sylius.context.cart')->getCart();
  1164.         $data = (array) $request->request->all();
  1165.         $log "Cart id - ".$cart->getId();
  1166.         // $log .= print_r();;
  1167.         $logger $this->get('monolog.logger.paydebug');
  1168.         // $logger = new Logger('paydebug');
  1169.         $logger->debug($log);
  1170.         $logger->debug(print_r($datatrue));
  1171.         // 
  1172.         // dump($data);
  1173.     
  1174.     public function productNoStockAction(Request $request$id): Response
  1175.     {
  1176.        
  1177.         $cart $this->container->get('sylius.context.cart')->getCart();
  1178.         
  1179.         if (null !== $cart->getId()) {
  1180.             $em $this->container->get('doctrine')->getManager();
  1181.             $siteProductNoStockRepo $em->getRepository(SiteProductNoStock::class);
  1182.             $siteProductsNoStock $siteProductNoStockRepo->findOneBy(
  1183.                 ['order' => $cart->getId(), 'productVariant' => $id]
  1184.             ); 
  1185.             if($siteProductsNoStock){
  1186.                 $em->remove($siteProductsNoStock);
  1187.                 // $em->persist($siteProductNoStockRepo);
  1188.                 $em->flush();
  1189.             }
  1190.             dump($siteProductsNoStock);
  1191.         } 
  1192.         return new JsonResponse('success');
  1193.     }
  1194.     public function orderAgainAction(Request $request$tokenValue null) {
  1195.         $customer $this->get('sylius.context.customer')->getCustomer();
  1196.         if($tokenValue != null && !empty($customer)) {
  1197.             //On charge la commande
  1198.             $order $this->get('sylius.repository.order')->findOneBy([
  1199.                 'tokenValue' => $tokenValue,
  1200.                 'customer' => $customer
  1201.             ]);
  1202.             if (empty($order) == false && $order->getState() != 'cart') {
  1203.                 //On duplique 
  1204.                 $defaultChannel $this->container->get('sylius.repository.channel')->findAll()[0];
  1205.                 $newCart $this->container->get('sylius.factory.order')->createNew();
  1206.                 $newCart->setChannel($defaultChannel);
  1207.                 $newCart->setCurrencyCode('EUR');
  1208.                 $newCart->setCreatedByGuest(false);
  1209.                 $newCart->setCustomer($customer);
  1210.                 $newCart->setLocaleCode($order->getLocaleCode());
  1211.                 
  1212.                 $defaultAddress $customer->getDefaultAddress();
  1213.                 $this->container->get('doctrine')->getManager()->initializeObject($defaultAddress);
  1214.                 if (null !== $defaultAddress) {
  1215.                     // dump($defaultAddress);
  1216.                     $clonedAddress = clone $defaultAddress;
  1217.                     $clonedAddress->setCustomer(null);
  1218.                     $newCart->setBillingAddress($clonedAddress);
  1219.                     $clonedAddress = clone $clonedAddress;
  1220.                     $newCart->setShippingAddress($clonedAddress);
  1221.                 }
  1222.                 $shippingMethod $this->container->get('sylius.repository.shipping_method')->findOneByCode('RETRAIT_EN_MAGASIN_1');
  1223.                 $shipment $this->container->get('sylius.factory.shipment')->createNew();
  1224.                 $shipment->setMethod($shippingMethod);
  1225.                 $shipment->setState('cart');
  1226.                 $newCart->addShipment($shipment);
  1227.                 $payment $this->container->get('sylius.factory.payment')->createNew();
  1228.                 $payment->setCurrencyCode('EUR');
  1229.                 $payment->setDetails([]);
  1230.                 $payment->setMethod($order->getPayments()->first()->getMethod());
  1231.                 $payment->setAmount($order->getPayments()->first()->getAmount());
  1232.                 $payment->setState('cart');
  1233.                 $newCart->addPayment($payment);
  1234.                 
  1235.                 foreach($order->getItems() as $item) {
  1236.                     $newItem $this->container->get('sylius.factory.order_item')->createNew();
  1237.                     $newItem->setVariantName($item->getVariantName());
  1238.                     $newItem->setImmutable(true);
  1239.                     $newItem->setUnitPrice($item->getUnitPrice());
  1240.                     $newItem->setOriginalUnitPrice($item->getOriginalUnitPrice());
  1241.                     $newItem->setVariant($item->getVariant());
  1242.                     $newItem->setConditioning($item->getConditioning());
  1243.                     $newItem->setConditioningValue($item->getConditioningValue());
  1244.                     $this->container->get('sylius.order_item_quantity_modifier')->modify($newItem$item->getQuantity());
  1245.                     $newCart->addItem($newItem);
  1246.                 }
  1247.                     
  1248.                 $this->container->get('sylius.repository.order')->add($newCart);
  1249.                 $this->get('session')->set('_sylius.cart.ppmc'$newCart->getId());
  1250.                 
  1251.                 $this->applyReducedPricesToCart($this->container->get('sylius.context.channel')->getChannel(), $newCart$this->container->get('doctrine.orm.entity_manager'));
  1252.             }
  1253.         }
  1254.         return $this->redirectToRoute('sylius_shop_cart_summary');
  1255.     }
  1256.     public function confirmDeliveryAddress(Request $request)
  1257.     {
  1258.         $em $this->get('doctrine')->getManager();
  1259.         if ($request->isMethod('POST')) {
  1260.             $error "";
  1261.             $success "";
  1262.             
  1263.             $cart $this->getCurrentCart();   
  1264.         
  1265.             $nom $request->get('nom');
  1266.             $prenom $request->get('prenom');
  1267.             $telephone $request->get('telephone');
  1268.            
  1269.             if(!empty($nom) && !empty($prenom) && !empty($telephone) ){
  1270.                 $apelData = array(
  1271.                     'nom' => $nom,
  1272.                     'prenom' => $prenom,
  1273.                     'telephone' => $telephone,
  1274.                 );
  1275.                 dump($cart);
  1276.                 dump($prenom);
  1277.                 // $address = $em->getRepository(Address::class)->find($idecole);
  1278.                 $cart->getShippingAddress()->setFirstName($prenom);
  1279.                 $cart->getShippingAddress()->setLastName($nom);
  1280.                 $cart->getShippingAddress()->setPhoneNumber($telephone);
  1281.                 // $ecole = $em->getRepository(SiteApel::class)->find($idecole);
  1282.                 // $cart->setApel(json_encode($apelData));       
  1283.                 $cartManager $this->container->get('sylius.manager.order');
  1284.                 $cartManager->persist($cart);
  1285.                 $cartManager->flush();
  1286.                 $this->container->get('doctrine.orm.entity_manager')->refresh($cart);
  1287.                 $success "Les informations sont sauvegardées";
  1288.             }else{
  1289.                 $error "Veuillez saisir toutes les informations de livraison";
  1290.                 return new JsonResponse([
  1291.                     "error"        =>    $error,
  1292.                 ]);
  1293.             }
  1294.                 // $cart->setOrderPickupShop(null);
  1295.             return new JsonResponse([
  1296.                 "success"    =>    $success,
  1297.              ]);
  1298.         }
  1299.     }
  1300.     public function addAddressDelivery(Request $request) {
  1301.         $checkout $request->get('checkout');
  1302.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  1303.         $customer $this->get('sylius.context.customer')->getCustomer();
  1304.         $address $this->container->get('sylius.factory.address')->createNew();
  1305.         $address->setFirstName($checkout['address']['shippingAddress']['firstName']);
  1306.         $address->setLastName($checkout['address']['shippingAddress']['lastName']);
  1307.         $address->setPhoneNumber($checkout['address']['shippingAddress']['phoneNumber']);
  1308.         $address->setCountryCode($checkout['address']['shippingAddress']['countryCode']);
  1309.         $address->setCity($checkout['address']['shippingAddress']['city']);
  1310.         $address->setStreet($checkout['address']['shippingAddress']['street']);
  1311.         $address->setPostcode($checkout['address']['shippingAddress']['postcode']);
  1312.         $address->setStreetComplementary($checkout['address']['shippingAddress']['streetComplementary']);
  1313.         $address->setCustomer($customer);
  1314.         $addressManager $this->container->get('sylius.manager.address');
  1315.         $addressManager->persist($address);
  1316.         $addressManager->flush();
  1317.         $customer->setDefaultAddress($address);
  1318.         $customerManager $this->container->get('sylius.manager.customer');
  1319.         $customerManager->persist($customer);
  1320.         $customerManager->flush();
  1321.         $cart $this->getCurrentCart();   
  1322.         if(!empty($customer) && $cart->getBillingAddress() == null) {
  1323.             $clonedAddress = clone $address;
  1324.             $clonedAddress->setCustomer(null);
  1325.             $cart->setBillingAddress($clonedAddress);
  1326.             if($cart->getShippingAddress() == null) {
  1327.                 $clonedAddress = clone $address;
  1328.                 $clonedAddress->setCustomer(null);
  1329.                 $cart->setShippingAddress($clonedAddress);
  1330.             }
  1331.             $cartManager $this->container->get('sylius.manager.order');
  1332.             $cartManager->persist($cart);
  1333.             $cartManager->flush();
  1334.         }
  1335.         
  1336.         return $this->redirectHandler->redirectToRoute(
  1337.             $configuration,
  1338.             'bitbag_sylius_one_page_checkout_shop_checkout'
  1339.         );
  1340.     }
  1341.     public function selectCountryDelivery(Request $request) {
  1342.         // dump($request);
  1343.         $cart $this->getCurrentCart();   
  1344.         $cart->getShippingAddress()->setCountryCode($request->get('countryCode'));
  1345.         
  1346.         // Reset les shipments
  1347.         $shipments $cart->getShipments();
  1348.         foreach ($shipments as $shipment) {
  1349.             $cart->removeShipment($shipment);
  1350.         }
  1351.         
  1352.         $cartManager $this->container->get('sylius.manager.order');
  1353.         $cartManager->persist($cart);
  1354.         $cartManager->flush();
  1355.         return new JsonResponse([
  1356.             "success"    =>    'ok',
  1357.         ]);
  1358.     }
  1359.     public function selectAddressDelivery(Request $request) {
  1360.         // dump($request);
  1361.         $id $request->get('id');
  1362.         $cart $this->getCurrentCart();   
  1363.         $cart->setSelectedShippingAddressId($request->get('id'));
  1364.         $cartManager $this->container->get('sylius.manager.order');
  1365.         $cartManager->persist($cart);
  1366.         $cartManager->flush();
  1367.         return new JsonResponse([
  1368.             "success"    =>    'ok',
  1369.         ]);
  1370.     }
  1371.     public function getShop2ShopPoints(Request $requestWSShop2ShopService $wSShop2ShopService) {
  1372.         // dump($request);
  1373.         $points $wSShop2ShopService->getPickupPoints($request->get('address'), $request->get('postcode'), $request->get('city'));
  1374.         return new JsonResponse([
  1375.             "points"    =>    $points,
  1376.         ]);
  1377.     }
  1378.     public function setShop2ShopOrderPoint(Request $requestPPMCErpSynchroService $ppmcErpSynchroService) {
  1379.         // dump($request->request->all());
  1380.         $ppmcErpSynchroService->checkPointRelais($request->request->all());
  1381.         // $points = $wSShop2ShopService->getPickupPoints($request->get('postcode'), $request->get('city'));
  1382.         return new JsonResponse([
  1383.             "success"    =>    'ok',
  1384.         ]);
  1385.     }
  1386.     public function paymentStatusAction(Request $request$id) {
  1387.         $customer $this->container->get('sylius.context.customer')->getCustomer();
  1388.         $orders $this->container->get('sylius.repository.order')->findBy([
  1389.             'customer' => $customer
  1390.         ]);
  1391.         foreach($orders as $order) {
  1392.             if(count($order->getPayments()) == 0) {
  1393.                 continue;
  1394.             }
  1395.             if($order->getPayments()->first()->getId() == $id) {
  1396.                 return new JsonResponse([
  1397.                     "success"    =>    $order->getPayments()->first()->getState(),
  1398.                 ]);
  1399.                 // dump($order->getPayments()->first());
  1400.             }
  1401.         }
  1402.     
  1403.         
  1404.         return new JsonResponse([
  1405.             "success"    =>    'error',
  1406.         ]);
  1407.     }
  1408.     public function paymentLinkAction(Request $request$tokenValue) {
  1409.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  1410.         $resource $this->findOr404($configuration);
  1411.         $form $this->resourceFormFactory->create($configuration$resource);
  1412.         return $this->render('bundles/BitBagSyliusOnePageCheckoutPlugin/checkout_payonly.html.twig', [
  1413.             'order' => $resource,
  1414.             'form' => $form->createView(),
  1415.         ]);
  1416.     }
  1417.     public function paymentLinkChoosePaymentAction(Request $request$tokenValue) {
  1418.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  1419.         $resource $this->findOr404($configuration);
  1420.         dump($request->get('checkout')['select_payment']['payments']);
  1421.         $resource->getPayments()->first()->setMethod($this->container->get('sylius.repository.payment_method')->findOneByCode($request->get('checkout')['select_payment']['payments'][0]['method']));
  1422.         // dump($request->request->all());
  1423.         
  1424.         $orderManager $this->container->get('sylius.manager.order');
  1425.         $orderManager->persist($resource);
  1426.         $orderManager->flush();
  1427.         return $this->render('bundles/BitBagSyliusOnePageCheckoutPlugin/_checkout_submitted.html.twig', [
  1428.             'order' => $resource
  1429.         ]);
  1430.     }
  1431.     public function paymentLinkCheckoutCompleteAction(Request $request$tokenValueFactoryInterface $stateMachineFactory) {
  1432.         $configuration $this->requestConfigurationFactory->create($this->metadata$request);
  1433.         $resource $this->findOr404($configuration);
  1434.         // $stateMachine = $stateMachineFactory->get($resource, $request->attributes->get('_sylius')['state_machine']['graph']);
  1435.         // dump($stateMachine);
  1436.         // $this->redirect($this->generateUrl($configuration['redirect']['route'], ['tokenValue' => $resource->getTokenValue()]));
  1437.         // return $this->redirectHandler->redirectToReferer($configuration);
  1438.         // $resource-getREdi
  1439.         // dump($configuration->getParameters()->get('redirect'));
  1440.         return $this->redirectHandler->redirectToRoute($configuration$configuration->getParameters()->get('redirect')['route'], ['tokenValue' => $resource->getTokenValue()]);
  1441.         // dump($configuration);
  1442.         // $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
  1443.         // $resource = $this->findOr404($configuration);
  1444.         // $resource->setState('completed');
  1445.         // $orderManager = $this->container->get('sylius.manager.order');
  1446.         // $orderManager->persist($resource);
  1447.         // $orderManager->flush();
  1448.         // return $this->render('bundles/BitBagSyliusOnePageCheckoutPlugin/_checkout_submitted.html.twig', [
  1449.         //     'order' => $resource
  1450.         // ]);
  1451.         // return new JsonResponse([
  1452.         //     "success"    =>    'success',
  1453.         // ]);
  1454.     }
  1455. }