src/Controller/Order/OrderController.php line 493

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