src/Controller/CartController.php line 2346

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\CompanyAssociation;
  4. use App\Entity\ProductAdjustment;
  5. use Doctrine\ORM\Mapping\ClassMetadataInfo;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\JsonResponse;
  10. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  13. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  14. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  15. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
  16. use Doctrine\ORM\EntityManagerInterface;
  17. use Doctrine\ORM\Query\ResultSetMapping;
  18. use App\Entity\Company;
  19. use App\Entity\Product;
  20. use App\Entity\Cart;
  21. use App\Entity\CartCoupon;
  22. use App\Entity\CartProduct;
  23. use App\Entity\CartCheckout;
  24. use App\Entity\ProductSponsored;
  25. use App\Entity\ProductSponsoredCategory;
  26. use App\Entity\Pricing;
  27. use App\Entity\City;
  28. use App\Entity\Region;
  29. use App\Entity\User;
  30. use App\Entity\UserShippingLocation;
  31. use App\Entity\CustomOrder;
  32. use App\Entity\MaturinOrder;
  33. use App\Entity\RecurringOrder;
  34. use App\Entity\DeliveryMethod;
  35. use App\Entity\DeliveryRoute;
  36. use App\Entity\Subscription;
  37. use App\Form\CartType;
  38. use App\Form\CartCheckoutType;
  39. use App\Form\CustomOrderType;
  40. use App\Service\UserService;
  41. use App\Service\PaymentService;
  42. use App\Service\DistributorService;
  43. use App\Service\CompanyService;
  44. use App\Service\TwigGlobalVariables;
  45. use DateTime;
  46. class CartController extends AbstractController
  47. {
  48.     private $session;
  49.     public function __construct(SessionInterface $session)
  50.     {
  51.         $this->session $session;
  52.     }
  53.     /**
  54.      * @route("/api/product/payment/add/{id}",
  55.      *      name="addProductAtPayment")
  56.      */
  57.     public function addProductAtPayment(Product $productUserService $userServ)
  58.     {
  59.         $em $this->getDoctrine()->getManager();
  60.         $this->addToCart($product1$userServ$em);
  61.         return $this->redirectToRoute('cartPayment');
  62.     }
  63.     /**
  64.      * @route("/api/product/cart/add/{id}",
  65.      *      name="addProductAtCart")
  66.      */
  67.     public function addProductAtCart(Product $productUserService $userServEntityManagerInterface $em)
  68.     {
  69.         $em $this->getDoctrine()->getManager();
  70.         $this->addToCart($product1$userServ$em);
  71.         return $this->redirectToRoute('viewCart');
  72.     }
  73.     /**
  74.      * @route("/maintenance/fix/recalculateTaxesOfAllPaidsCarts",
  75.      *      name="calculateCartTaxes")
  76.      */
  77.     public function calculateCartTaxes(PaymentService $paymentServ){
  78.         $em $this->getDoctrine()->getManager();
  79.         $carts $em->getRepository(Cart::class)->findAllPaid();
  80.         foreach($carts as $cart){
  81.             //Coupong is included by default see CartProduct.php method getTotal
  82.             $taxes $paymentServ->calculateTaxes($cart->getTotalProductsTaxable(), $cart->getShippingAddress()->getProvince());
  83.             $cart->setTaxesProductsCalculations($taxes);
  84.             $cart->setTaxesProducts($taxes['totalTax']);
  85.             //Taxes shipping if by solex
  86.             $taxes $paymentServ->calculateTaxes($cart->getShippingMaturinCost(), $cart->getShippingAddress()->getProvince());
  87.             $cart->setTaxesShippingMaturinCalculations($taxes);
  88.             $cart->setTaxesShippingMaturin($taxes['totalTax']);
  89.             //@TODO Calculate Shipping Company
  90.             $taxes $paymentServ->calculateTaxes($cart->getShippingCompanyCost(), $cart->getShippingAddress()->getProvince());
  91.             $cart->setTaxesShippingCompanyCalculations($taxes);
  92.             $cart->setTaxesShippingCompany($taxes['totalTax']);
  93.             // taxes packing
  94.             $taxes $paymentServ->calculateTaxes($cart->getPackingCost(), $cart->getShippingAddress()->getProvince());
  95.             $cart->setTaxesPackingCalculations($taxes);
  96.             $cart->setTaxesPacking($taxes['totalTax']);
  97.             $em->persist($cart);
  98.         }
  99.         $em->flush();
  100.         return new Response('Done');
  101.     }
  102.     /**
  103.      * @route({
  104.      *          "fr": "/core/convert/cart",
  105.      *          "en": "/core/convert/cart"
  106.      *      },
  107.      *      name="convertCart")
  108.      */
  109.     public function convertCart(UserService $userServ){
  110.         // $userServ->sendEmail('test subject', 'test html', false, 'stephanejourney@gmail.com');
  111.         //Disable
  112.         return false;
  113.         //
  114.         //
  115.         // $em = $this->getDoctrine()->getManager();
  116.         // $carts = $em->getRepository(Cart::class)->findAll();
  117.         // foreach($carts as $cart){
  118.         //     if(count($cart->getMaturinOrders()) < 1 && count($cart->getCustomOrders()) < 1){
  119.         //         /*
  120.         //          * Here we split and populate different Orders
  121.         //          * those orders are what the Company will see and be billed on
  122.         //          */
  123.         //         $customOrders = array();
  124.         //         $maturinOrders = array();
  125.         //
  126.         //         foreach($cart->getProducts() as $p){
  127.         //             if($p->getProduct()->isShippedByMaturin()){
  128.         //
  129.         //                 //Let's reduce the quantity of all products while at it only if it's not a JIT product
  130.         //                 if(!$p->getProduct()->getIsJustInTime())
  131.         //                     $p->getProduct()->setQtyReadyToShip($p->getProduct()->getQtyReadyToShip() - $p->getQuantity());
  132.         //
  133.         //                 $em->persist($p->getProduct());
  134.         //
  135.         //                 $cId = $p->getProduct()->getCompany()->getId();
  136.         //                 if(empty($maturinOrders[$cId])){
  137.         //                     $maturinOrders[$cId] = new MaturinOrder();
  138.         //                     $maturinOrders[$cId]->setFromCart($cart);
  139.         //                     $maturinOrders[$cId]->setCompany($p->getProduct()->getCompany());
  140.         //                 }
  141.         //                 $maturinOrders[$cId]->addItem($p);
  142.         //
  143.         //             }else{
  144.         //                 /*
  145.         //                  * For now all orders from custom Delivery as sent into the CustomOrder Entity for easier managing
  146.         //                  * We regroup them by producer
  147.         //                  */
  148.         //                 $cId = $p->getProduct()->getCompany()->getId();
  149.         //                 if(empty($customOrders[$cId])){
  150.         //                     $customOrders[$cId] = new CustomOrder();
  151.         //                     $customOrders[$cId]->setFromCart($cart);
  152.         //                     $customOrders[$cId]->setCompany($p->getProduct()->getCompany());
  153.         //                 }
  154.         //                 $customOrders[$cId]->addItem($p);
  155.         //             }
  156.         //         }
  157.         //
  158.         //         //Now le's save all the Maturin Orders
  159.         //         foreach($maturinOrders as $c){
  160.         //             $em->persist($c);
  161.         //         }
  162.         //
  163.         //         //Now le's save all the customOrders
  164.         //         foreach($customOrders as $c){
  165.         //             $em->persist($c);
  166.         //         }
  167.         //     }
  168.         // }
  169.         // $em->flush();
  170.         //
  171.         // //$form = $this->createForm(ProductReplenishmentType::class, $replenishment);
  172.         // return new Response('Cart Converted');
  173.     }
  174.     /**
  175.      * @Route({
  176.      *          "fr": "/acheteur/commande/annuler/{orderNo}",
  177.      *          "en": "/buyer/order/cancel/{orderNo}/"
  178.      *      }, name="cancelOrder",
  179.      *      options = { "expose" = true },
  180.      *  )
  181.      * @Security("has_role('ROLE_USER')")
  182.      * @Entity("cart", expr="repository.findOneByOrderNo(orderNo)")
  183.      */
  184.     public function cancelOrder(Cart $cartUserService $userServPaymentService $paymentServ){
  185.         $twigData = array();
  186.         $user $userServ->getUser();
  187.         if($cart->getUser() != $user){
  188.             $this->addFlash('error'"Vous n'avez pas accès a cette commande");
  189.             return $this->redirectToRoute('dashboard');
  190.         }
  191.         //Extra safety
  192.         if(!$cart->showRefundButtonToUser()){
  193.             $this->addFlash('error'"Cette commande n'est pas remboursable");
  194.             return $this->redirectToRoute('listOrders');
  195.         }
  196.         if($paymentServ->refundCart($carttrue))
  197.             $this->addFlash('success'"Cette commande a été annulé et remboursé!");
  198.         else
  199.             $this->addFlash('error'"Cette commande n'a pas été remboursé");
  200.         return $this->redirectToRoute('listOrders');
  201.     }
  202.     /**
  203.      * @Route({
  204.      *          "fr": "/acheteur/commande/voir/{orderNo}/{freshSale}",
  205.      *          "en": "/buyer/order/see/{orderNo}/{freshSale}"
  206.      *      }, name="viewOrder",
  207.      *      options = { "expose" = true },
  208.      *      defaults = {
  209.      *          "freshSale" = false
  210.      *      }
  211.      *  )
  212.      * @Security("has_role('ROLE_USER')")
  213.      * @Template("admin/user/orderView.html.twig")
  214.      * @Entity("cart", expr="repository.findOneByOrderNo(orderNo)")
  215.      */
  216.     public function viewOrder(Cart $cart$freshSaleUserService $userServ){
  217.         $twigData = array();
  218.         $user $userServ->getUser();
  219.         if($cart->getUser() != $user){
  220.             $this->addFlash('error'"Vous n'avez pas accès a cette commande");
  221.             return $this->redirectToRoute('dashboard');
  222.         }
  223.         $twigData['order'] = $cart;
  224.         $twigData['freshSale']= $freshSale;
  225.         return $twigData;
  226.     }
  227.      /**
  228.      * @Route({
  229.      *          "fr": "/acheteur/precommande/voir/{orderNo}/{freshSale}",
  230.      *          "en": "/buyer/preorder/see/{orderNo}/{freshSale}"
  231.      *      }, name="viewPreOrder",
  232.      *      options = { "expose" = true },
  233.      *      defaults = {
  234.      *          "freshSale" = false
  235.      *      }
  236.      *  )
  237.      * @Security("has_role('ROLE_USER')")
  238.      * @Template("admin/user/preOrderView.html.twig")
  239.      * @Entity("cart", expr="repository.findOneByOrderNo(orderNo)")
  240.      */
  241.     public function viewPreOrder(Cart $cart$freshSaleUserService $userServ){
  242.       $twigData = array();
  243.       $user $userServ->getUser();
  244.       if($cart->getUser() != $user){
  245.           $this->addFlash('error'"Vous n'avez pas accès a cette commande");
  246.           return $this->redirectToRoute('dashboard');
  247.       }
  248.       $twigData['order'] = $cart;
  249.       $twigData['freshSale']= $freshSale;
  250.       return $twigData;
  251.   }
  252.     /**
  253.      * @Route({
  254.      *          "fr": "/vendeur/commandes/liste/{id}",
  255.      *          "en": "/seller/orders/list/{id}",
  256.      *      },
  257.      *      defaults={
  258.      *          "id" = false
  259.      *      },
  260.      *      name="companyOrders")
  261.      *
  262.      * @Security("has_role('ROLE_ADMIN')")
  263.      * @Template("admin/company/ordersList.html.twig")
  264.      */
  265.     public function companyOrders(Company $company=nullCompanyService $companyServEntityManagerInterface $emUserService $userServ){
  266.         $twigData = array();
  267.         if(empty($company)){
  268.             $user $userServ->getUser();
  269.             $companies $user->getCompanies();
  270.             if(count($companies) > 1){
  271.                 $this->addFlash('error'"Vous avez plusieur boutiques, pour accéder a l'inventaire via le menu");
  272.                 return $this->redirectToRoute('dashboard');
  273.             }else{
  274.                 $company $companies->get(0);
  275.             }
  276.         }
  277.         if(!$companyServ->allowedToModify($company)){
  278.             $this->addFlash('error'"Vous n'avez pas accès a cette commpagnie");
  279.             return $this->redirectToRoute('dashboard');
  280.         }
  281.         $twigData['orders'] = $company->getCustomOrders();
  282.         $twigData['company'] = $company;
  283.         $twigData['reservedOrders'] = $em->getRepository(CartProduct::class)->findReservedProductsForCompany($company);
  284.         $twigData['preOrder'] = $em->getRepository(CartProduct::class)->findPreOrderProductForCompany($company);
  285.         return $twigData;
  286.     }
  287.       /**
  288.      * @Route({
  289.      *          "fr": "/vendeur/preCommandes/liste/{id}",
  290.      *          "en": "/seller/preOrders/list/{id}",
  291.      *      },
  292.      *      defaults={
  293.      *          "id" = false
  294.      *      },
  295.      *      name="preCompanyOrders")
  296.      *
  297.      * @Security("has_role('ROLE_ADMIN')")
  298.      * @Template("admin/company/preOrdersList.html.twig")
  299.      */
  300.     public function preCompanyOrders(Company $company=nullCompanyService $companyServEntityManagerInterface $emUserService $userServ){
  301.       $twigData = array();
  302.       if(empty($company)){
  303.           $user $userServ->getUser();
  304.           $companies $user->getCompanies();
  305.           if(count($companies) > 1){
  306.               $this->addFlash('error'"Vous avez plusieur boutiques, pour accéder a l'inventaire via le menu");
  307.               return $this->redirectToRoute('dashboard');
  308.           }else{
  309.               $company $companies->get(0);
  310.           }
  311.       }
  312.       if(!$companyServ->allowedToModify($company)){
  313.           $this->addFlash('error'"Vous n'avez pas accès a cette commpagnie");
  314.           return $this->redirectToRoute('dashboard');
  315.       }
  316.       $twigData['orders'] = $company->getCustomOrders();
  317.       $twigData['company'] = $company;
  318.       $twigData['preOrder'] = $em->getRepository(CartProduct::class)->findPreOrderProductForCompany($company);
  319.       return $twigData;
  320.   }
  321.     /**
  322.      * @Route({
  323.      *          "fr": "/vendeur/commandes/maturin/{orderNo}",
  324.      *          "en": "/seller/orders/maturin/{orderNo}"
  325.      *      }, name="viewMaturinOrder")
  326.      * @Security("has_role('ROLE_USER')")
  327.      * @Template("admin/company/viewMaturinOrder.html.twig")
  328.      * @Entity("MaturinOrder", expr="repository.findOneByOrderNo(orderNo)")
  329.      */
  330.     public function viewMaturinOrder (MaturinOrder $orderUserService $userServRequest $requestCompanyService $companyServ){
  331.         //@SECuritY
  332.         if(!$companyServ->allowedToModify($order->getCompany())){
  333.             $this->addFlash('error'"Vous n'avez pas d'accès à cette compagnie.");
  334.             return $this->redirectToRoute('dashboard');
  335.         }
  336.         $twigData = array();
  337.         $twigData['order'] = $order;
  338.         return $twigData;
  339.     }
  340.     /**
  341.      * @Route({
  342.      *          "fr": "/vendeur/commandes/independante/{orderNo}",
  343.      *          "en": "/seller/orders/independant/{orderNo}"
  344.      *      }, name="viewCustomOrder")
  345.      * @Security("has_role('ROLE_USER')")
  346.      * @Template("admin/company/viewCustomOrder.html.twig")
  347.      * @Entity("CustomOrder", expr="repository.findOneByOrderNo(orderNo)")
  348.      */
  349.     public function viewCustomOrder (CustomOrder $orderUserService $userServRequest $requestCompanyService $companyServ){
  350.         //@SECuritY
  351.         if(!$companyServ->allowedToModify($order->getCompany())){
  352.             $this->addFlash('error'"Vous n'avez pas d'accès à cette compagnie.");
  353.             return $this->redirectToRoute('dashboard');
  354.         }
  355.         $twigData = array();
  356.         $twigData['order'] = $order;
  357.         $form $this->createForm(CustomOrderType::class, $order);
  358.         $twigData['form'] = $form->createView();
  359.         $form->handleRequest($request);
  360.         if($form->isSubmitted() && $form->isValid()){
  361.             $order->setIsShipped(true);
  362.             $em $this->getDoctrine()->getManager();
  363.             $em->persist($order);
  364.             $em->flush();
  365.             //Send email to the customer
  366.             if ($order->getCompany()->getAssociations()->count() == 0){
  367.                 $email $this
  368.                     ->get('twig')
  369.                     ->render('emails/tracking.html.twig', [
  370.                         'order' => $order,
  371.                         'user' => $order->getFromCart()->getUser()
  372.                     ]);
  373.                 $userServ->sendEmail('Votre livraison est en route'$emailfalse$order->getFromCart()->getUser()->getEmail());
  374.             }
  375.             return $this->redirectToRoute('companyOrders', array('id' => $order->getCompany()->getId()));
  376.         }
  377.         return $twigData;
  378.     }
  379.     /**
  380.      * @Route({
  381.      *          "fr": "/acheteur/commande/encore/{orderNo}",
  382.      *          "en": "/buyer/order/again/{orderNo}"
  383.      *      }, name="orderAgain")
  384.      * @Security("has_role('ROLE_USER')")
  385.      */
  386.     public function orderAgain(Cart $cartUserService $userServ){
  387.         $em $this->getDoctrine()->getManager();
  388.         $user $userServ->getUser();
  389.         //Cloning give issue doing it manually
  390.         $newCart = new Cart();
  391.         foreach($cart->getProducts() as $p){
  392.             if($p->getProduct()->isSalable()){
  393.                 $np = new CartProduct();
  394.                 $np->setQuantity($p->getQuantity());
  395.                 $np->setProduct($p->getProduct());
  396.                 $newCart->addProduct($np);
  397.             }
  398.         }
  399.         $newCart->setUser($user);
  400.         $newCart->setShippingAddress($cart->getShippingAddress());
  401.         $user->addCart($newCart);
  402.         $em->persist($newCart);
  403.         $em->persist($user);
  404.         $em->flush();
  405.         return $this->redirectToRoute('viewCart');
  406.     }
  407.     /**
  408.      * @Route({
  409.      *          "fr": "/acheteur/commandes",
  410.      *          "en": "/buyer/orders"
  411.      *      }, name="listOrders")
  412.      * @Security("has_role('ROLE_USER')")
  413.      * @Template("admin/ordersList.html.twig")
  414.      */
  415.     public function listOrders(UserService $userServ){
  416.         $twigData = array();
  417.         $user $userServ->getUser();
  418.         $twigData['orders'] = $user->getPaidOrders();
  419.         $twigData['pickUpOrders']=$user->getPaidPickUpOrders();
  420.         return $twigData;
  421.     }
  422.   /**
  423.      * @Route({
  424.      *          "fr": "/acheteur/precommandes",
  425.      *          "en": "/buyer/preorders"
  426.      *      }, name="preListOrders")
  427.      * @Security("has_role('ROLE_USER')")
  428.      * @Template("admin/preOrdersList.html.twig")
  429.      */
  430.     public function preListOrders(UserService $userServ){
  431.       $twigData = array();
  432.       $user $userServ->getUser();
  433.       $em $this->getDoctrine()->getManager();
  434.       $twigData['listPreOrders'] = $em->getRepository(Cart::class)->findBy(['user'=>$user->getId()],['deliveryChoiceDate' => 'ASC']);
  435.       $twigData['orders'] = $user->getPaidOrders();
  436.       $twigData['pickUpOrders']=$user->getPaidPickUpOrders();
  437.       return $twigData;
  438.   }
  439.     /* === moved this to the cart entity === @ 2021/03/16 */
  440.     /*
  441.      * Calculate all the fees and all from Cart
  442.      */
  443.     // public function calculateFees(Cart $cart, PaymentService $paymentServ){
  444.     //     $em = $this->getDoctrine()->getManager();
  445.     //
  446.     //     //@NOTE Legacy, those are not used anymore
  447.     //     //Ok let's start with the Maturin Fees and taxes
  448.     //     $cart->setMaturinFee(round($cart->getTotalProducts(false , false) * 0.1, 2));
  449.     //     $cart->setTaxesMaturin($paymentServ->calculateTaxes($cart->getMaturinFee(), $cart->getShippingAddress()->getProvince(), true));
  450.     //     // End Legacy
  451.     //
  452.     //     foreach($cart->getProducts() as $item){
  453.     //         $item->setPricePaidProduct($item->getTotal(false));
  454.     //     }
  455.     //
  456.     //     //Coupon is included by default see CartProduct.php method getTotal
  457.     //     $taxes = $paymentServ->calculateTaxes($cart->getTotalProductsTaxable(), $cart->getShippingAddress()->getProvince());
  458.     //     $cart->setTaxesProductsCalculations($taxes);
  459.     //     $cart->setTaxesProducts($taxes['totalTax']);
  460.     //
  461.     //     //Taxes shipping if by solex
  462.     //     $taxes = $paymentServ->calculateTaxes($cart->getShippingMaturinCost(), $cart->getShippingAddress()->getProvince());
  463.     //     $cart->setTaxesShippingMaturinCalculations($taxes);
  464.     //     $cart->setTaxesShippingMaturin($taxes['totalTax']);
  465.     //
  466.     //     //@TODO Calculate Shipping Company
  467.     //     $taxes = $paymentServ->calculateTaxes($cart->getShippingCompanyCost(), $cart->getShippingAddress()->getProvince());
  468.     //     $cart->setTaxesShippingCompanyCalculations($taxes);
  469.     //     $cart->setTaxesShippingCompany($taxes['totalTax']);
  470.     //
  471.     //     // taxes packing
  472.     //     $taxes = $paymentServ->calculateTaxes($cart->getPackingCost(), $cart->getShippingAddress()->getProvince());
  473.     //     $cart->setTaxesPackingCalculations($taxes);
  474.     //     $cart->setTaxesPacking($taxes['totalTax']);
  475.     //
  476.     //     //Estimating Payment Cost
  477.     //
  478.     //     $em->persist($cart);
  479.     //     $em->flush();
  480.     //
  481.     // }
  482.     /**
  483.      * @Route({
  484.      *          "fr": "/payer",
  485.      *          "en": "/payment"
  486.      *      }, name="cartPayment")
  487.      * @Security("has_role('ROLE_USER')")
  488.      * @Template("frontend/payment.html.twig")
  489.      */
  490.     public function cartPayment(Request $requestPaymentService $paymentServUserService $userServUrlGeneratorInterface $routerDistributorService $distributorServ,TwigGlobalVariables $twigGlobalVariablesService){
  491.         $twigData = array();
  492.         $twigData['hideSideMenu'] = true;
  493.         // $twigData['loader']= true;
  494.         $twigData['suggestedProducts']= $userServ->findProductsToSuggest();
  495.         $em $this->getDoctrine()->getManager();
  496.         $cart $userServ->getCart();
  497.         // dump($cart->getPickUpAddress());
  498.         // if(empty($cart->getShippingAddress()) && empty($cart->getPickUpAddress())){
  499.         //     $this->addFlash('error', "Nous avons d'abord besoin d'une adresse de livraison'");
  500.         //     return $this->redirectToRoute('checkout');
  501.         // }
  502.        
  503.         /*
  504.          * Called when there is a Shipping Method change
  505.          * But not a payment
  506.          */
  507.         if(!$request->request->has('stripeToken') && !$request->request->has('use-previous-card')){
  508.             // if(!$cart->hasMaturinShipping()){
  509.               if($cart->hasMaturinShipping()){
  510.               $twigData['shippingMaturin'] = $distributorServ->getEstimateShipping($cart);
  511.             }
  512.             //Update the Shipping cost
  513.             if(!empty($twigData['shippingMaturin'])){
  514.               $maturinShipping current($twigData['shippingMaturin']);
  515.             } else {
  516.               $maturinShipping false;
  517.             }
  518.            
  519.             $found false;
  520.             if($maturinShipping){
  521.                 foreach($twigData['shippingMaturin'] as $s){
  522.                     if($s->serviceName == $request->request->get('shippingService') && $s->carrierName == $request->request->get('shippingCarrier')){
  523.                         $found true;
  524.                         $cart->setShippingMaturinCost($s->estimatedCost);
  525.                         $cart->setShippingMaturinCarrierName($s->carrierName);
  526.                         $cart->setShippingMaturinServiceName($s->serviceName);
  527.                         $cart->setShippingMaturinServiceId($s->serviceId);
  528.                         if ($cart->getPreOrderNow()){
  529.                           $dateDeliveryChoice $cart->getDeliveryChoiceDate();
  530.                           $cart->setShippingMaturinEstimatedDate($dateDeliveryChoice);
  531.                         } else {
  532.                         $estimatedCartDate $twigGlobalVariablesService->getEstimationShippingForMaturinProducts($cart);
  533.                        //$cart->setShippingMaturinEstimatedDate(new \DateTime($s->estimatedDate));
  534.                         $cart->setShippingMaturinEstimatedDate($estimatedCartDate);
  535.                         }
  536.                         $twigData['currentShipping'] = $s;
  537.                         break;
  538.                     }
  539.                 }
  540.                 if(!($request->request->has('maturinShipping') && $found)){
  541.                     $cart->setShippingMaturinCost($maturinShipping->estimatedCost);
  542.                     $cart->setShippingMaturinCarrierName($maturinShipping->carrierName);
  543.                     $cart->setShippingMaturinServiceName($maturinShipping->serviceName);
  544.                     $cart->setShippingMaturinServiceId($maturinShipping->serviceId);
  545.                     if ($cart->getPreOrderNow()){
  546.                       $dateDeliveryChoice $cart->getDeliveryChoiceDate();
  547.                       $cart->setShippingMaturinEstimatedDate($dateDeliveryChoice);
  548.                     } else {
  549.                     //// old estimate not working anymore for delivery date we change it to new estimation route
  550.                     $estimatedCartDate $twigGlobalVariablesService->getEstimationShippingRouteForMaturinProducts($cart);
  551.                     $maturinShipping->estimatedDate $estimatedCartDate["date"];
  552.                     $cart->setShippingMaturinEstimatedDate($maturinShipping->estimatedDate);
  553.                     }
  554.                     //$cart->setShippingMaturinEstimatedDate(new \DateTime($maturinShipping->estimatedDate));
  555.                     $twigData['currentShipping'] = $maturinShipping;
  556.                 }
  557.                 $em->persist($cart);
  558.                 $em->flush();
  559.             }else{
  560.                 if($cart->hasMaturinShipping()){
  561.                     //Should be an error with the shipping
  562.                     //In theory the flash should show the error to user
  563.                     //so we redirect to shipping address
  564.                     $twigData['noGo'] = true;
  565.                     return $this->redirectToRoute('checkout');
  566.                 }
  567.             }
  568.         }
  569.         $shippingAddress $cart->getShippingAddress();
  570.         //We need a shipping address for the taxes
  571.         if($shippingAddress) {
  572.             $cart->calculateFees();
  573.             $em->persist($cart);
  574.             $em->flush();
  575.         }
  576.         $PuroTest null;
  577.         if ($shippingAddress){
  578.           $getMethodLivraisons $em->getRepository(DeliveryRoute::class)->findBy(['name' => $cart->getShippingAddress()->getArrayOfDeliveryRoutes()]);
  579.           foreach ($getMethodLivraisons as $getMethodLivraison) {
  580.             if ($getMethodLivraison->getType() == 'maturin')
  581.             $PuroTest 'maturin';
  582.           }
  583.         }
  584.         $twigData['puroConfirm'] = $PuroTest;
  585.         /*
  586.          * If payment is ready
  587.          */
  588.         if($request->request->has('stripeToken') || $request->request->has('use-previous-card')){
  589.             if(!empty($request->request->get('stripeToken')))
  590.                 $cart->setStripeToken($request->request->get('stripeToken'));
  591.                 
  592.                 if($request->request->get('NoteFromBuyer')){
  593.               $noteFromBuyer $request->request->get('NoteFromBuyer'); 
  594.               if (strlen($noteFromBuyer) <= 100){
  595.                 $patternNoteFromBuyer '/([0-9|#][\x{20E3}])|[\x{00ae}|\x{00a9}|\x{203C}|\x{2047}|\x{2048}|\x{2049}|\x{3030}|\x{303D}|\x{2139}|\x{2122}|\x{3297}|\x{3299}][\x{FE00}-\x{FEFF}]?|[\x{2190}-\x{21FF}][\x{FE00}-\x{FEFF}]?|[\x{2300}-\x{23FF}][\x{FE00}-\x{FEFF}]?|[\x{2460}-\x{24FF}][\x{FE00}-\x{FEFF}]?|[\x{25A0}-\x{25FF}][\x{FE00}-\x{FEFF}]?|[\x{2600}-\x{27BF}][\x{FE00}-\x{FEFF}]?|[\x{2900}-\x{297F}][\x{FE00}-\x{FEFF}]?|[\x{2B00}-\x{2BF0}][\x{FE00}-\x{FEFF}]?|[\x{1F000}-\x{1F6FF}][\x{FE00}-\x{FEFF}]?/u';
  596.                 if(preg_match($patternNoteFromBuyer,
  597.                   $noteFromBuyer
  598.                 )){
  599.                    $noteFromBuyer preg_replace($patternNoteFromBuyer
  600.                   ''
  601.                   $noteFromBuyer);
  602.                 }
  603.                 $cart->setNoteFromBuyer($noteFromBuyer);
  604.               }else{
  605.                 $this->addFlash('error'"Veuillez ne pas dépasser les 100 characteres dans votre messages au livreur.");
  606.                 return $this->redirectToRoute('checkout');
  607.               }
  608.             }
  609.             //Let's save if the signature was asked for the shipping
  610.             // todo move from here
  611.             $signature $request->request->get('signature-required');
  612.             if($signature)
  613.                 $cart->setShippingSignatureRequired(true);
  614.             else
  615.                 $cart->setShippingSignatureRequired(false);
  616.                
  617.             $em->persist($cart);
  618.             $em->flush();
  619.   /*---------------------------- en dessous insert la condition si champs preorder true alors envoi dans container preorders ---------------------------------------------*/
  620.              if($paymentServ->payCart($cart)) {
  621.                 $user $userServ->getUser();
  622.                 $locale $request->getSession()->get('_locale');
  623.                 if(empty($locale))
  624.                     $locale 'fr';
  625.                 //if ($cart->getPreOrderNow() != true){
  626.                   $newRoute $router->generate'viewOrder', array ('_locale' => $locale'orderNo' => $cart->getOrderNo()));
  627.                   $userServ->addNotification('success''Votre commande''A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>');
  628.                   $this->addFlash('success'"Votre commande a été passée avec succès");
  629.                /* }else{
  630.                   $newRoute = $router->generate( 'viewPreOrder', array ('_locale' => $locale, 'orderNo' => $cart->getOrderNo()));
  631.                   $userServ->addNotification('success', 'Votre commande', 'A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>');
  632.                   $this->addFlash('success', "Votre commande a été passée avec succès");
  633.                 }*/
  634.                 $emailBody $this->get('twig')->render('emails/order.html.twig', [
  635.                     'cart' => $cart,
  636.                     'user' => $cart->getUser()
  637.                 ]);
  638.                 $replyTo = [];
  639.                 foreach ($cart->getProducts() as $cartProduct) {
  640.                     if (($association $cartProduct->getAddedWhenBeingInAssociation()) != null)
  641.                     {
  642.                         foreach ($association->getAdminUsers() as $adminUser){
  643.                             $replyTo[]=$adminUser->getEmail();
  644.                         }
  645.                         foreach ($association->getUsersAddingCompanies() as $adminUser){
  646.                             $replyTo[]=$adminUser->getEmail();
  647.                         }
  648.                     }
  649.                   }
  650.                 $replyTo count($replyTo) == false array_unique($replyTo);
  651.                 $userServ->sendEmail(
  652.                     'Confirmation de votre commande #'.$cart->getOrderNo(),
  653.                     $emailBody,
  654.                     false,
  655.                     $cart->getUser()->getEmail(), falsenull$replyTo
  656.                 );
  657.                 //This happen if the cart contain JIT product OR the shipping estimate didn'T worked
  658.                 if(!$cart->getPreOrderNow()){
  659.                   if(!$cart->getIsOnHold()){
  660.                       //We are ready let's send the order
  661.                       if($cart->hasMaturinShipping() && !$distributorServ->sendOrders($cart)){
  662.                           $userServ->sendEmail('Maturin: Error Orders''Error with Cart ID (hasMaturinShipping):'.$cart->getId(), 'Error with the Cart ID:'.$cart->getId() , 'entrepot@maturin.ca');
  663.                       }else if($cart->isMaturinPickUp() && !$distributorServ->sendOrders($cart)){
  664.                         $userServ->sendEmail('Maturin: Error Orders''Error with Cart ID (isMaturinPickUp):'.$cart->getId(), 'Error with the Cart ID:'.$cart->getId() , 'entrepot@maturin.ca');
  665.                       }
  666.                   }
  667.                 }
  668.                 /*
  669.                  * Let's see if it's the user first order
  670.                  * In this case, and he got a referrer we give him a coupon
  671.                  */
  672.                 if($user->isFirstOrder() && !empty($user->getReferredBy())){
  673.                     $coupon = new CartCoupon();
  674.                     $coupon->setOneTimeOnly(true);
  675.                     $coupon->setType(0);
  676.                     $coupon->setAmount(10);
  677.                     $coupon->setCode('C-'.uniqid());
  678.                     $coupon->setForUser($user->getReferredBy());
  679.                     $coupon->setDateFrom(new \DateTime());
  680.                     $coupon->setDateTo(new \DateTime("+1 year"));
  681.                     $em->persist($coupon);
  682.                 }
  683.                 //If it's a gift order let's remove the amount on it
  684.                 if(!empty($cart->getUsedCoupon()) && $cart->getUsedCoupon()->getIsGiftCertificate()){
  685.                     $coupon $cart->getUsedCoupon();
  686.                     $cart->setAmountSavedByCoupon($cart->getCouponSavings());
  687.                     $coupon $coupon->setAmount($coupon->getAmount() - $cart->getTotal(false));
  688.                     $em->persist($cart);
  689.                     $em->persist($coupon);
  690.                 }
  691.                 $em->flush();
  692.                 if ($shippingAddress) {
  693.                   $cityName $shippingAddress->getCity();
  694.                   $province $shippingAddress->getProvince();
  695.                   if ($cityName && $province) {
  696.                     //$city = $em->getRepository(City::class)->findLikeName($cityName);
  697.                     $city $em->getRepository(City::class)->findLikeNameAndProvince($cityName,$province);
  698.                     if (empty($city)) {
  699.                       // $cart->setIsOnHold(true);
  700.                       $em->persist($cart);
  701.                       $em->flush();
  702.                       $userServ->sendEmail(
  703.                           'Ville invalide pour la commande #'.$cart->getOrderNo(),
  704.                           'Ville invalide ['.$cityName.'] pour la commande #'.$cart->getOrderNo(),
  705.                           false,
  706.                           "info@maturin.ca"falsenull"info@maturin.ca"
  707.                       );
  708.                     }
  709.                   }
  710.                 }
  711.                 return $this->redirectToRoute('viewOrder', array('orderNo' => $cart->getOrderNo(), 'freshSale' => true));
  712.             } else {
  713.                 $this->addFlash('error''Le paiement a echoué. Veuillez vérifier que votre carte est valide ou notre support.');
  714.                 return $this->redirectToRoute('cartPayment');
  715.             }
  716.             /*
  717.                 $userServ->addNotification('error', 'Votre commande', 'Une erreur est survenue, veuillez contacter notre support.');
  718.                 //$this->addFlash('error', "Une erreur est survenue avec votre commande");
  719.             }
  720.              */
  721.         }
  722.         return $twigData;
  723.     }
  724.     /**
  725.      * @Route({
  726.      *          "fr": "/livraison-groupe-payer",
  727.      *          "en": "/bulk-shipping-payment"
  728.      *      }, name="bulkship_payment")
  729.      * @Security("has_role('ROLE_USER')")
  730.      * @Template("frontend/bulkship.payment.html.twig")
  731.      */
  732.     public function bulkship_payment(UrlGeneratorInterface $routerUserService $userServRequest $requestPaymentService $paymentServDistributorService $distributorServ,TwigGlobalVariables $twigGlobalVariablesService) {
  733.       $twigData = array();
  734.       $twigData['hideSideMenu'] = true;
  735.       $twigData['loader']= true;
  736.       $em $this->getDoctrine()->getManager();
  737.       $user $userServ->getUser();
  738.       $userCart $userServ->getCart();
  739.       /*
  740.        * If payment is ready
  741.        */
  742.       if($request->request->has('stripeToken') || $request->request->has('use-previous-card')) {
  743.           $carts = [];
  744.           $_carts $em->getRepository(Cart::class)->findBy(['isBulkOrder' => true'isPaid' => false'user' => $user]);
  745.           foreach($_carts as $cart) {
  746.             $carts[] = $cart;
  747.           }
  748.           $signature $request->request->get('signature-required');
  749.           $userCart $userServ->getCart();
  750.           $cartCoupon $userCart->getUsedCoupon();
  751.           foreach($carts as $cart) {
  752.             if(!empty($request->request->get('stripeToken'))) {
  753.               $cart->setStripeToken($request->request->get('stripeToken'));
  754.             }
  755.             if($signature) {
  756.               $cart->setShippingSignatureRequired(true);
  757.             } else {
  758.               $cart->setShippingSignatureRequired(false);
  759.             }
  760.             if ($cartCoupon) {
  761.               $cart->setUsedCoupon($cartCoupon);
  762.             }
  763.             // if($request->request->get('NoteFromBuyer')){
  764.             //   $cart->setNoteFromBuyer($request->request->get('NoteFromBuyer'));
  765.             // }
  766.             $cart->setPreOrderNow(false);
  767.             $cart->setPreOrder(false);
  768.             $cart->setDeliveryChoiceDate(null);
  769.         
  770.           $em->persist($cart);
  771.           $em->flush();
  772.             
  773.             $em->persist($cart);
  774.             $em->flush();
  775.           }
  776.           if($paymentServ->payBulkCarts($carts)){
  777.               $locale $request->getSession()->get('_locale');
  778.               if(empty($locale))
  779.                   $locale 'fr';
  780.               $newRoute $router->generate'listOrders' );
  781.               $userServ->addNotification('success''Votre commande''A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>');
  782.               $this->addFlash('success'"Votre commande a été passée avec succès");
  783.               $replyTo = [];
  784.               foreach($carts as $cart) {
  785.                 foreach ($cart->getProducts() as $cartProduct) {
  786.                   if (($association $cartProduct->getAddedWhenBeingInAssociation()) != null)
  787.                   {
  788.                     foreach ($association->getAdminUsers() as $adminUser){
  789.                       $replyTo[]=$adminUser->getEmail();
  790.                     }
  791.                     foreach ($association->getUsersAddingCompanies() as $adminUser){
  792.                       $replyTo[]=$adminUser->getEmail();
  793.                     }
  794.                   }
  795.                 }
  796.                 //This happen if the cart contain JIT product OR the shipping estimate didn'T worked
  797.                 if(!$cart->getPreOrderNow()){
  798.                   if(!$cart->getIsOnHold()){
  799.                   //We are ready let's send the order
  800.                   if($cart->hasMaturinShipping() && !$distributorServ->sendOrders($cart)){
  801.                     $userServ->sendEmail('Maturin: Error Orders''Error with Cart ID:'.$cart->getId(), 'Error with the Cart ID:'.$cart->getId() , 'entrepot@maturin.ca');
  802.                   }else if($cart->isMaturinPickUp() && !$distributorServ->sendOrders($cart)){
  803.                     $userServ->sendEmail('Maturin: Error Orders''Error with Cart ID:'.$cart->getId(), 'Error with the Cart ID:'.$cart->getId() , 'entrepot@maturin.ca');
  804.                   }
  805.                 }
  806.               }
  807.                 if(!empty($cart->getUsedCoupon()) && $cart->getUsedCoupon()->getIsGiftCertificate()){
  808.                     $coupon $cart->getUsedCoupon();
  809.                     $cart->setAmountSavedByCoupon($cart->getCouponSavings());
  810.                     $coupon $coupon->setAmount($coupon->getAmount() - $cart->getTotal(false));
  811.                     $em->persist($cart);
  812.                     $em->persist($coupon);
  813.                     $em->flush();
  814.                 }
  815.               }
  816.               $emailBody $this->get('twig')->render('emails/order.bulk.html.twig', [
  817.                 'carts' => $carts,
  818.                 'user' => $userServ->getUser()
  819.               ]);
  820.               $replyTo count($replyTo) == false array_unique($replyTo);
  821.               $userServ->sendEmail(
  822.                 'Confirmation de vos commandes',
  823.                 $emailBody,
  824.                 false,
  825.                 $userServ->getUser()->getEmail(), falsenull$replyTo
  826.               );
  827.               // /*
  828.               //  * Let's see if it's the user first order
  829.               //  * In this case, and he got a referrer we give him a coupon
  830.               //  */
  831.               // if($user->isFirstOrder() && !empty($user->getReferredBy())){
  832.               //     $coupon = new CartCoupon();
  833.               //     $coupon->setOneTimeOnly(true);
  834.               //     $coupon->setType(0);
  835.               //     $coupon->setAmount(10);
  836.               //     $coupon->setCode('C-'.uniqid());
  837.               //     $coupon->setForUser($user->getReferredBy());
  838.               //     $coupon->setDateFrom(new \DateTime());
  839.               //     $coupon->setDateTo(new \DateTime("+1 year"));
  840.               //     $em->persist($coupon);
  841.               // }
  842.               //
  843.               // //If it's a gift order let's remove the amount on it
  844.               $em->remove($userCart);
  845.               $em->flush();
  846.               return $this->redirectToRoute('listOrders');
  847.           } else {
  848.               $this->addFlash('error''Le paiement a echoué. Veuillez vérifier que votre carte est valide ou notre support.');
  849.               return $this->redirectToRoute('bulkship_payment');
  850.           }
  851.       } else {
  852.         /* remove previous carts with unpaid bulk orders */
  853.         $carts $em->getRepository(Cart::class)->findBy(['isBulkOrder' => true'isPaid' => false'user' => $user]);
  854.         foreach($carts as $cart) {
  855.           $em->remove($cart);
  856.           $em->flush();
  857.         }
  858.         $new_carts = [];
  859.         $cart $userServ->getCart();
  860.         $warn_qty_adjust false;
  861.         foreach($cart->getProducts() as $p) {
  862.           $product_id $p->getProduct()->getId();
  863.           $qty_left $p->getProduct()->getQtyReadyToShip();
  864.           $session_imported_rows $this->session->get('IMPORTED_ROWS_'.$product_id);
  865.           if (!empty($session_imported_rows)) {
  866.             $session_imported_rows json_decode($session_imported_rowstrue);
  867.           }
  868.           foreach($session_imported_rows as $row) {
  869.             $qty $row["quantity"];
  870.             if ($qty $qty_left) {
  871.               $qty $qty_left;
  872.               $warn_qty_adjust true;
  873.             }
  874.             $qty_left $qty_left $qty;
  875.             if ($qty 0) {
  876.               if (!isset($new_carts[$row["id"]])) {
  877.                 $new_carts[$row["id"]] = new Cart();
  878.                 $new_carts[$row["id"]]->setUser($user);
  879.                 $UserShippingLocation $em->getRepository(UserShippingLocation::class)->findOneBy([
  880.                   "email" => $row["contact_col_email"],
  881.                   "name" => $row["contact_col_fullname"],
  882.                   "user" => $user,
  883.                 ]);
  884.                 if (empty($UserShippingLocation)) {
  885.                   $UserShippingLocation = new UserShippingLocation();
  886.                 }
  887.                 $UserShippingLocation->setName($row["contact_col_fullname"]);
  888.                 $UserShippingLocation->setPhone($row["contact_col_phone"]);
  889.                 $UserShippingLocation->setEmail($row["contact_col_email"]);
  890.                 $UserShippingLocation->setCivicNumber($row["contact_col_civicnb"]);
  891.                 $UserShippingLocation->setStreetName($row["contact_col_streetname"]);
  892.                 $UserShippingLocation->setUnit($row["contact_col_appartment"]);
  893.                 $UserShippingLocation->setCity($row["contact_col_city"]);
  894.                 $UserShippingLocation->setProvince($row["contact_col_province"]);
  895.                 $zipCode trim(str_replace("-",""str_replace(" """$row["contact_col_zipcode"])));
  896.                 $UserShippingLocation->setZipCode($zipCode);
  897.                 $UserShippingLocation->setUser($user);
  898.                 $em->persist($UserShippingLocation);
  899.                 $em->flush();
  900.                 $new_carts[$row["id"]]->setShippingAddress($UserShippingLocation);
  901.                 $new_carts[$row["id"]]->setIsBulkOrder(true);
  902.               }
  903.               $new_carts[$row["id"]]->setShippingSignatureRequired(false);
  904.               if (isset($row["signreq"])) {
  905.                 if ($row["signreq"]) {
  906.                   $new_carts[$row["id"]]->setShippingSignatureRequired(true);
  907.                 }
  908.               }
  909.               if($p->getProduct()->isSalable()) {
  910.                 $np = new CartProduct();
  911.                 $np->setProduct($p->getProduct());
  912.                 $np->setRecurringFrequency($p->getRecurringFrequency());
  913.                 $np->setQuantity($qty);
  914.                 $new_carts[$row["id"]]->addProduct($np);
  915.               }
  916.             }
  917.           }
  918.         }
  919.         if ($warn_qty_adjust) {
  920.           $this->addFlash('warning'"Les quantité ont été ajustées en fonction de l'inventaire.");
  921.         }
  922.         foreach($new_carts as $newCartId => $newCart) {
  923.           if($newCart->hasMaturinShipping())
  924.             $twigData['shippingMaturin'] = $distributorServ->getEstimateShipping($newCart);
  925.           //Update the Shipping cost
  926.           $maturinShipping false;
  927.           if (!empty($twigData['shippingMaturin'])) {
  928.             $maturinShipping current($twigData['shippingMaturin']);
  929.           }
  930.           $found false;
  931.           $currentShipping false;
  932.           if($maturinShipping){
  933.             $newCart->setShippingMaturinCost($maturinShipping->estimatedCost);
  934.             $newCart->setShippingMaturinCarrierName($maturinShipping->carrierName);
  935.             $newCart->setShippingMaturinServiceName($maturinShipping->serviceName);
  936.             $newCart->setShippingMaturinServiceId($maturinShipping->serviceId);
  937.             $estimatedCartDate $twigGlobalVariablesService->getEstimationShippingRouteForMaturinProducts($newCart);
  938.             $maturinShipping->estimatedDate $estimatedCartDate["date"];
  939.             $newCart->setShippingMaturinEstimatedDate($maturinShipping->estimatedDate);
  940.             $currentShipping $maturinShipping;
  941.           }
  942.           $em->persist($newCart);
  943.           $em->flush();
  944.           $cartId $newCart->getId();
  945.           if($newCart->getShippingAddress()) {
  946.             $newCart->calculateFees();
  947.             $em->persist($newCart);
  948.             $em->flush();
  949.           }
  950.           $twigData["carts"][] = [
  951.             'cart' => $newCart,
  952.             'currentShipping' => $currentShipping,
  953.             'shippingMaturin' => $twigData['shippingMaturin'],
  954.           ];
  955.         }
  956.       }
  957.       return $twigData;
  958.     }
  959.     /**
  960.      * @Route({
  961.      *          "fr": "/livraison-groupe",
  962.      *          "en": "/bulk-shipping"
  963.      *      }, name="bulkship")
  964.      * @Security("has_role('ROLE_USER')")
  965.      * @Template("frontend/bulkship.cart.html.twig")
  966.      */
  967.     public function bulkship(UserService $userServRequest $request) {
  968.       $twigData = array();
  969.       $twigData['hideSideMenu'] = true;
  970.       $twigData['loader']= true;
  971.       $em $this->getDoctrine()->getManager();
  972.       $cart $userServ->getCart();
  973.         $cart->setPreOrderNow(false);
  974.         $cart->setPreOrder(false);
  975.         $cart->setDeliveryChoiceDate(null);
  976.     
  977.       $em->persist($cart);
  978.       $em->flush();
  979.       $twigData["products"] = [];
  980.       $products $cart->getProducts();
  981.       foreach($products as $product) {
  982.         $twigData["products"][$product->getProduct()->getId()] = [
  983.           "cart_product" => $product,
  984.           "ship_to" => [],
  985.           "default_ship_to" => [$cart->getShippingAddress()],
  986.           "default_ship_to_email" => $userServ->getUser()->getEmail(),
  987.           "rows_to_import" => [],
  988.           "row_to_test_import" => [],
  989.           "imported_filename" => "",
  990.           "multiple_ship_to" => false,
  991.           "file_upload_error" => false,
  992.           "file_upload_success" => false,
  993.         ];
  994.         $session_imported_rows $this->session->get('IMPORTED_ROWS_'.$product->getProduct()->getId());
  995.         if (!empty($session_imported_rows)) {
  996.           $twigData["products"][$product->getProduct()->getId()]["ship_to"] = json_decode($session_imported_rowstrue);
  997.           $twigData["products"][$product->getProduct()->getId()]["multiple_ship_to"] = true;
  998.         }
  999.       }
  1000.       $user $userServ->getUser();
  1001.       $em $this->getDoctrine()->getManager();
  1002.       if ($request->isMethod('post')) {
  1003.        
  1004.           $posts $request->request->all();
  1005.           if ($posts["action"] == "delete_form_address") {
  1006.             $product_id $posts["product_id"];
  1007.             $contact_email $posts["contact_email"];
  1008.             foreach($twigData["products"][$product_id]["ship_to"] as $idx=>$ship_to) {
  1009.               if ($ship_to["contact_col_email"] == $contact_email) {
  1010.                 unset($twigData["products"][$product_id]["ship_to"][$idx]);
  1011.                 $imported_rows $twigData["products"][$product_id]["ship_to"];
  1012.                 $this->session->set('IMPORTED_ROWS_'.$product_idjson_encode($imported_rows));
  1013.               }
  1014.             }
  1015.           }
  1016.           if ($posts["action"] == "add_new_address") {
  1017.             $product_id $posts["product_id"];
  1018.             $ship_to = [];
  1019.             $ship_to["quantity"] = 1;
  1020.             $ship_to["contact_col_email"] = $posts["cart_checkout"]["newAddress"]["email"];
  1021.             $ship_to["contact_col_fullname"] = $posts["cart_checkout"]["newAddress"]["name"];
  1022.             $ship_to["contact_col_phone"] = $posts["cart_checkout"]["newAddress"]["phone"];
  1023.             $ship_to["contact_col_civicnb"] = $posts["cart_checkout"]["newAddress"]["civicNumber"];
  1024.             $ship_to["contact_col_streetname"] = $posts["cart_checkout"]["newAddress"]["streetName"];
  1025.             $ship_to["contact_col_appartment"] = $posts["cart_checkout"]["newAddress"]["unit"];
  1026.             $ship_to["contact_col_city"] = $posts["cart_checkout"]["newAddress"]["city"];
  1027.             $ship_to["contact_col_province"] = $posts["cart_checkout"]["newAddress"]["province"];
  1028.             $ship_to["contact_col_zipcode"] = $posts["cart_checkout"]["newAddress"]["zipCode"];
  1029.             $ship_to["contact_col_zipcode"] = str_replace(" """$ship_to["contact_col_zipcode"]);
  1030.             $ship_to["contact_col_zipcode"] = str_replace("-"""$ship_to["contact_col_zipcode"]);
  1031.             $ship_to["id"] = md5(
  1032.               mb_strtolower($ship_to["contact_col_civicnb"].$ship_to["contact_col_streetname"].$ship_to["contact_col_appartment"].$ship_to["contact_col_zipcode"])
  1033.             );
  1034.             if (filter_var($ship_to["contact_col_email"], FILTER_VALIDATE_EMAIL)) {
  1035.               $twigData["products"][$product_id]["ship_to"][] = $ship_to;
  1036.               $imported_rows $twigData["products"][$product_id]["ship_to"];
  1037.               $this->session->set('IMPORTED_ROWS_'.$product_idjson_encode($imported_rows));
  1038.             } else {
  1039.               $twigData["products"][$product_id]['file_upload_error'] = "Le courriel a un format non valide.";
  1040.             }
  1041.           }
  1042.           if ($posts["action"] == "process_ship_to") {
  1043.             $errors false;
  1044.             $payload json_decode($posts["payload"], true);
  1045.             foreach($twigData["products"] as $product_id => $product) {
  1046.               if ($payload[$product_id]["multiple_ship_to"]) {
  1047.                 if (empty($product["ship_to"])) {
  1048.                   $twigData["products"][$product_id]['file_upload_error'] = "Veuillez importer des destinataires dans votre commande.";
  1049.                   $errors true;
  1050.                 } else {
  1051.                   foreach($product["ship_to"] as $_idx => $ship_to) {
  1052.                     $qty $payload[$product_id]["ship_to"][$ship_to["contact_col_email"]]["qty"];
  1053.                     $signreq false;
  1054.                     if (isset($payload[$product_id]["ship_to"][$ship_to["contact_col_email"]]["signreq"])) {
  1055.                       $signreq $payload[$product_id]["ship_to"][$ship_to["contact_col_email"]]["signreq"];
  1056.                     }
  1057.                     $twigData["products"][$product_id]["ship_to"][$_idx]["quantity"] = $qty;
  1058.                     $twigData["products"][$product_id]["ship_to"][$_idx]["signreq"] = $signreq;
  1059.                   }
  1060.                   $imported_rows $twigData["products"][$product_id]["ship_to"];
  1061.                   $this->session->set('IMPORTED_ROWS_'.$product_idjson_encode($imported_rows));
  1062.                 }
  1063.               } else {
  1064.                 $ship_to = [];
  1065.                 $ship_to["quantity"] = $product["cart_product"]->getQuantity();
  1066.                 $ship_to["contact_col_email"] = $twigData["products"][$product_id]["default_ship_to_email"];
  1067.                 $ship_to["contact_col_fullname"] = $twigData["products"][$product_id]["default_ship_to"][0]->getName();
  1068.                 $ship_to["contact_col_phone"] = $twigData["products"][$product_id]["default_ship_to"][0]->getPhone();
  1069.                 $ship_to["contact_col_civicnb"] = $twigData["products"][$product_id]["default_ship_to"][0]->getCivicNumber();
  1070.                 $ship_to["contact_col_streetname"] = $twigData["products"][$product_id]["default_ship_to"][0]->getStreetName();
  1071.                 $ship_to["contact_col_appartment"] = $twigData["products"][$product_id]["default_ship_to"][0]->getUnit();
  1072.                 $ship_to["contact_col_city"] = $twigData["products"][$product_id]["default_ship_to"][0]->getCity();
  1073.                 $ship_to["contact_col_province"] = $twigData["products"][$product_id]["default_ship_to"][0]->getProvince();
  1074.                 $ship_to["contact_col_zipcode"] = $twigData["products"][$product_id]["default_ship_to"][0]->getZipCode();
  1075.                 $ship_to["contact_col_zipcode"] = str_replace(" """$ship_to["contact_col_zipcode"]);
  1076.                 $ship_to["contact_col_zipcode"] = str_replace("-"""$ship_to["contact_col_zipcode"]);
  1077.                 $ship_to["id"] = md5(
  1078.                   mb_strtolower($ship_to["contact_col_civicnb"].$ship_to["contact_col_streetname"].$ship_to["contact_col_appartment"].$ship_to["contact_col_zipcode"])
  1079.                 );
  1080.                 $imported_rows = [$ship_to];
  1081.                 $this->session->set('IMPORTED_ROWS_'.$product_idjson_encode($imported_rows));
  1082.               }
  1083.             }
  1084.             if (!$errors) {
  1085.               return $this->redirectToRoute("bulkship_payment");
  1086.             }
  1087.           }
  1088.           if ($posts["action"] == "empty_ship_to") {
  1089.             $imported_rows = [];
  1090.             $twigData["products"][$posts["product_id"]]["ship_to"] = $imported_rows;
  1091.             $twigData["products"][$posts["product_id"]]["multiple_ship_to"] = true;
  1092.             $this->session->set('IMPORTED_ROWS_'.$posts["product_id"], json_encode($imported_rows));
  1093.           }
  1094.           if ($posts["action"] == "import_data") {
  1095.             $configuration = [
  1096.               "contact_col_fullname" => $posts["contact_col_fullname"],
  1097.               "contact_col_phone" => $posts["contact_col_phone"],
  1098.               "contact_col_email" => $posts["contact_col_email"],
  1099.               "contact_col_civicnb" => $posts["contact_col_civicnb"],
  1100.               "contact_col_streetname" => $posts["contact_col_streetname"],
  1101.               "contact_col_appartment" => $posts["contact_col_appartment"],
  1102.               "contact_col_city" => $posts["contact_col_city"],
  1103.               "contact_col_province" => $posts["contact_col_province"],
  1104.               "contact_col_zipcode" => $posts["contact_col_zipcode"],
  1105.             ];
  1106.             $ignore_file_header false;
  1107.             if (isset($posts["ignore_file_header"])) {
  1108.               $ignore_file_header $posts["ignore_file_header"];
  1109.             }
  1110.             $session_file_rows_to_be_imported $this->session->get('ROWS_TO_BE_IMPORTED_'.$posts["product_id"]);
  1111.             $rows json_decode($session_file_rows_to_be_importedtrue);
  1112.             $imported_rows = [];
  1113.             $cart_quantity $twigData["products"][$posts["product_id"]]["cart_product"]->getQuantity();
  1114.             foreach($rows as $idx => $row) {
  1115.               if ($idx == && $ignore_file_header == "on") {
  1116.                 continue;
  1117.               }
  1118.               $imported_row = [];
  1119.               foreach($configuration as $config_key => $config_value) {
  1120.                 // strip NON-BREAKING WHITE-SPACES
  1121.                 $row[$config_value] = trim(trim($row[$config_value]),chr(0xC2).chr(0xA0));
  1122.                 if ($config_key == "contact_col_zipcode") {
  1123.                   $row[$config_value] = str_replace(" """$row[$config_value]);
  1124.                   $row[$config_value] = str_replace("-"""$row[$config_value]);
  1125.                 }
  1126.                 if ($config_key == "contact_col_fullname") {
  1127.                   $fullname $row[$config_value];
  1128.                   $fullname explode(" "$fullname);
  1129.                   $fullname_capitalized '';
  1130.                   foreach($fullname as $name) {
  1131.                     $fullname_capitalized .= mb_strtoupper(substr($name01)).substr($name1).' ';
  1132.                   }
  1133.                   $row[$config_value] = $fullname_capitalized;
  1134.                 }
  1135.                 if ($config_key == "contact_col_province") {
  1136.                   /*
  1137.                   'Alberta'=> 'AB',
  1138.                   'Colombie-Britannique' => 'BC',
  1139.                   'Île-du-Prince-Édouard' => 'PE',
  1140.                   'Manitoba' => 'MB',
  1141.                   'Nouveau-Brunswick' => 'NB',
  1142.                   'Nouvelle-Écosse' => 'NS',
  1143.                   'Nunavut' => 'NU',
  1144.                   'Ontario' => 'ON',
  1145.                   'Québec' => 'QC',
  1146.                   'Saskatchewan' => 'SK',
  1147.                   'Terre-Neuve-et-Labrador' => 'NL',
  1148.                   'Territoires du Nord-Ouest' => 'NT',
  1149.                   'Yukon' => 'YT'
  1150.                   */
  1151.                   $province $row[$config_value];
  1152.                   $chars = array(
  1153.                     // Decompositions for Latin-1 Supplement
  1154.                     chr(195).chr(128) => 'A'chr(195).chr(129) => 'A',
  1155.                     chr(195).chr(130) => 'A'chr(195).chr(131) => 'A',
  1156.                     chr(195).chr(132) => 'A'chr(195).chr(133) => 'A',
  1157.                     chr(195).chr(135) => 'C'chr(195).chr(136) => 'E',
  1158.                     chr(195).chr(137) => 'E'chr(195).chr(138) => 'E',
  1159.                     chr(195).chr(139) => 'E'chr(195).chr(140) => 'I',
  1160.                     chr(195).chr(141) => 'I'chr(195).chr(142) => 'I',
  1161.                     chr(195).chr(143) => 'I'chr(195).chr(145) => 'N',
  1162.                     chr(195).chr(146) => 'O'chr(195).chr(147) => 'O',
  1163.                     chr(195).chr(148) => 'O'chr(195).chr(149) => 'O',
  1164.                     chr(195).chr(150) => 'O'chr(195).chr(153) => 'U',
  1165.                     chr(195).chr(154) => 'U'chr(195).chr(155) => 'U',
  1166.                     chr(195).chr(156) => 'U'chr(195).chr(157) => 'Y',
  1167.                     chr(195).chr(159) => 's'chr(195).chr(160) => 'a',
  1168.                     chr(195).chr(161) => 'a'chr(195).chr(162) => 'a',
  1169.                     chr(195).chr(163) => 'a'chr(195).chr(164) => 'a',
  1170.                     chr(195).chr(165) => 'a'chr(195).chr(167) => 'c',
  1171.                     chr(195).chr(168) => 'e'chr(195).chr(169) => 'e',
  1172.                     chr(195).chr(170) => 'e'chr(195).chr(171) => 'e',
  1173.                     chr(195).chr(172) => 'i'chr(195).chr(173) => 'i',
  1174.                     chr(195).chr(174) => 'i'chr(195).chr(175) => 'i',
  1175.                     chr(195).chr(177) => 'n'chr(195).chr(178) => 'o',
  1176.                     chr(195).chr(179) => 'o'chr(195).chr(180) => 'o',
  1177.                     chr(195).chr(181) => 'o'chr(195).chr(182) => 'o',
  1178.                     chr(195).chr(182) => 'o'chr(195).chr(185) => 'u',
  1179.                     chr(195).chr(186) => 'u'chr(195).chr(187) => 'u',
  1180.                     chr(195).chr(188) => 'u'chr(195).chr(189) => 'y',
  1181.                     chr(195).chr(191) => 'y',
  1182.                     // Decompositions for Latin Extended-A
  1183.                     chr(196).chr(128) => 'A'chr(196).chr(129) => 'a',
  1184.                     chr(196).chr(130) => 'A'chr(196).chr(131) => 'a',
  1185.                     chr(196).chr(132) => 'A'chr(196).chr(133) => 'a',
  1186.                     chr(196).chr(134) => 'C'chr(196).chr(135) => 'c',
  1187.                     chr(196).chr(136) => 'C'chr(196).chr(137) => 'c',
  1188.                     chr(196).chr(138) => 'C'chr(196).chr(139) => 'c',
  1189.                     chr(196).chr(140) => 'C'chr(196).chr(141) => 'c',
  1190.                     chr(196).chr(142) => 'D'chr(196).chr(143) => 'd',
  1191.                     chr(196).chr(144) => 'D'chr(196).chr(145) => 'd',
  1192.                     chr(196).chr(146) => 'E'chr(196).chr(147) => 'e',
  1193.                     chr(196).chr(148) => 'E'chr(196).chr(149) => 'e',
  1194.                     chr(196).chr(150) => 'E'chr(196).chr(151) => 'e',
  1195.                     chr(196).chr(152) => 'E'chr(196).chr(153) => 'e',
  1196.                     chr(196).chr(154) => 'E'chr(196).chr(155) => 'e',
  1197.                     chr(196).chr(156) => 'G'chr(196).chr(157) => 'g',
  1198.                     chr(196).chr(158) => 'G'chr(196).chr(159) => 'g',
  1199.                     chr(196).chr(160) => 'G'chr(196).chr(161) => 'g',
  1200.                     chr(196).chr(162) => 'G'chr(196).chr(163) => 'g',
  1201.                     chr(196).chr(164) => 'H'chr(196).chr(165) => 'h',
  1202.                     chr(196).chr(166) => 'H'chr(196).chr(167) => 'h',
  1203.                     chr(196).chr(168) => 'I'chr(196).chr(169) => 'i',
  1204.                     chr(196).chr(170) => 'I'chr(196).chr(171) => 'i',
  1205.                     chr(196).chr(172) => 'I'chr(196).chr(173) => 'i',
  1206.                     chr(196).chr(174) => 'I'chr(196).chr(175) => 'i',
  1207.                     chr(196).chr(176) => 'I'chr(196).chr(177) => 'i',
  1208.                     chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
  1209.                     chr(196).chr(180) => 'J'chr(196).chr(181) => 'j',
  1210.                     chr(196).chr(182) => 'K'chr(196).chr(183) => 'k',
  1211.                     chr(196).chr(184) => 'k'chr(196).chr(185) => 'L',
  1212.                     chr(196).chr(186) => 'l'chr(196).chr(187) => 'L',
  1213.                     chr(196).chr(188) => 'l'chr(196).chr(189) => 'L',
  1214.                     chr(196).chr(190) => 'l'chr(196).chr(191) => 'L',
  1215.                     chr(197).chr(128) => 'l'chr(197).chr(129) => 'L',
  1216.                     chr(197).chr(130) => 'l'chr(197).chr(131) => 'N',
  1217.                     chr(197).chr(132) => 'n'chr(197).chr(133) => 'N',
  1218.                     chr(197).chr(134) => 'n'chr(197).chr(135) => 'N',
  1219.                     chr(197).chr(136) => 'n'chr(197).chr(137) => 'N',
  1220.                     chr(197).chr(138) => 'n'chr(197).chr(139) => 'N',
  1221.                     chr(197).chr(140) => 'O'chr(197).chr(141) => 'o',
  1222.                     chr(197).chr(142) => 'O'chr(197).chr(143) => 'o',
  1223.                     chr(197).chr(144) => 'O'chr(197).chr(145) => 'o',
  1224.                     chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
  1225.                     chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
  1226.                     chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
  1227.                     chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
  1228.                     chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
  1229.                     chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
  1230.                     chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
  1231.                     chr(197).chr(160) => 'S'chr(197).chr(161) => 's',
  1232.                     chr(197).chr(162) => 'T'chr(197).chr(163) => 't',
  1233.                     chr(197).chr(164) => 'T'chr(197).chr(165) => 't',
  1234.                     chr(197).chr(166) => 'T'chr(197).chr(167) => 't',
  1235.                     chr(197).chr(168) => 'U'chr(197).chr(169) => 'u',
  1236.                     chr(197).chr(170) => 'U'chr(197).chr(171) => 'u',
  1237.                     chr(197).chr(172) => 'U'chr(197).chr(173) => 'u',
  1238.                     chr(197).chr(174) => 'U'chr(197).chr(175) => 'u',
  1239.                     chr(197).chr(176) => 'U'chr(197).chr(177) => 'u',
  1240.                     chr(197).chr(178) => 'U'chr(197).chr(179) => 'u',
  1241.                     chr(197).chr(180) => 'W'chr(197).chr(181) => 'w',
  1242.                     chr(197).chr(182) => 'Y'chr(197).chr(183) => 'y',
  1243.                     chr(197).chr(184) => 'Y'chr(197).chr(185) => 'Z',
  1244.                     chr(197).chr(186) => 'z'chr(197).chr(187) => 'Z',
  1245.                     chr(197).chr(188) => 'z'chr(197).chr(189) => 'Z',
  1246.                     chr(197).chr(190) => 'z'chr(197).chr(191) => 's'
  1247.                   );
  1248.                   $province strtr($province$chars);
  1249.                   $province str_replace("-"""$province);
  1250.                   $province str_replace(" """$province);
  1251.                   if (
  1252.                     mb_strtolower($province) == "alberta" ||
  1253.                     mb_strtolower($province) == "ab"
  1254.                   ) {
  1255.                     $province "AB";
  1256.                   }
  1257.                   if (
  1258.                     mb_strtolower($province) == "colombiebritannique" ||
  1259.                     mb_strtolower($province) == "britishcolumbia" ||
  1260.                     mb_strtolower($province) == "bc"
  1261.                   ) {
  1262.                     $province "BC";
  1263.                   }
  1264.                   if (
  1265.                     mb_strtolower($province) == "ileduprinceedouard" ||
  1266.                     mb_strtolower($province) == "pe"
  1267.                   ) {
  1268.                     $province "PE";
  1269.                   }
  1270.                   if (
  1271.                     mb_strtolower($province) == "manitoba" ||
  1272.                     mb_strtolower($province) == "mb"
  1273.                   ) {
  1274.                     $province "MB";
  1275.                   }
  1276.                   if (
  1277.                     mb_strtolower($province) == "nouveaubrunswick" ||
  1278.                     mb_strtolower($province) == "newbrunswick" ||
  1279.                     mb_strtolower($province) == "nb"
  1280.                   ) {
  1281.                     $province "NB";
  1282.                   }
  1283.                   if (
  1284.                     mb_strtolower($province) == "nouvelleecosse" ||
  1285.                     mb_strtolower($province) == "novascotia" ||
  1286.                     mb_strtolower($province) == "ne" ||
  1287.                     mb_strtolower($province) == "ns"
  1288.                   ) {
  1289.                     $province "NS";
  1290.                   }
  1291.                   if (
  1292.                     mb_strtolower($province) == "nunavut" ||
  1293.                     mb_strtolower($province) == "nu"
  1294.                   ) {
  1295.                     $province "NU";
  1296.                   }
  1297.                   if (
  1298.                     mb_strtolower($province) == "ontario" ||
  1299.                     mb_strtolower($province) == "on"
  1300.                   ) {
  1301.                     $province "ON";
  1302.                   }
  1303.                   if (
  1304.                     mb_strtolower($province) == "quebec" ||
  1305.                     mb_strtolower($province) == "que" ||
  1306.                     mb_strtolower($province) == "qc"
  1307.                   ) {
  1308.                     $province "QC";
  1309.                   }
  1310.                   if (
  1311.                     mb_strtolower($province) == "saskatchewan" ||
  1312.                     mb_strtolower($province) == "sk"
  1313.                   ) {
  1314.                     $province "SK";
  1315.                   }
  1316.                   if (
  1317.                     mb_strtolower($province) == "territoiresdunordouest" ||
  1318.                     mb_strtolower($province) == "northwestterritories" ||
  1319.                     mb_strtolower($province) == "nt"
  1320.                   ) {
  1321.                     $province "NT";
  1322.                   }
  1323.                   if (
  1324.                     mb_strtolower($province) == "yukon" ||
  1325.                     mb_strtolower($province) == "yt"
  1326.                   ) {
  1327.                     $province "YT";
  1328.                   }
  1329.                   $row[$config_value] = $province;
  1330.                 }
  1331.                 $imported_row[$config_key] = $row[$config_value];
  1332.               }
  1333.               $imported_row["contact_col_email"] = trim(trim($imported_row["contact_col_email"]),chr(0xC2).chr(0xA0));
  1334.               if (filter_var($imported_row["contact_col_email"], FILTER_VALIDATE_EMAIL)) {
  1335.                 $imported_row["id"] = md5(
  1336.                   mb_strtolower($imported_row["contact_col_civicnb"].$imported_row["contact_col_streetname"].$imported_row["contact_col_appartment"].$imported_row["contact_col_zipcode"])
  1337.                 );
  1338.                 $imported_row["quantity"] = 1;
  1339.                 $imported_rows[] = $imported_row;
  1340.               } else {
  1341.                 $imported_rows = [];
  1342.                 $twigData["products"][$posts["product_id"]]['file_upload_error'] = "La colonne des courriels contient des courriels qui ont un format non valide. Veuillez vérifier la configuration du fichier.";
  1343.                 break;
  1344.               }
  1345.             }
  1346.             $twigData["products"][$posts["product_id"]]["ship_to"] = $imported_rows;
  1347.             $twigData["products"][$posts["product_id"]]["multiple_ship_to"] = true;
  1348.             $this->session->set('IMPORTED_ROWS_'.$posts["product_id"], json_encode($imported_rows));
  1349.           }
  1350.           if ($posts["action"] == "import_shipping_addresses") {
  1351.             $tmpfile $_FILES["fileToUpload"]["tmp_name"];
  1352.             if (file_exists($tmpfile)) {
  1353.               $filename basename($_FILES["fileToUpload"]["name"]);
  1354.               $path_parts pathinfo($filename);
  1355.               if (!isset($path_parts['extension'])) {
  1356.                 $twigData["products"][$posts["product_id"]]['file_upload_error'] = "Le fichier n'est pas supporté. Veuillez importer un fichier CSV ou Excel (.xls ou .xslx) seulement.";
  1357.               } else {
  1358.                 $extension $path_parts['extension'];
  1359.                 if (strtolower($extension) == "xls" || strtolower($extension) == "xlsx" || strtolower($extension) == "csv") {
  1360.                   $rows = [];
  1361.                   if (strtolower($extension) == "xls") {
  1362.                     $xls = \SimpleXLS::parse($tmpfile);
  1363.                     if ($xls) {
  1364.                       $rows $xls->rows();
  1365.                     } else {
  1366.                       $twigData["products"][$posts["product_id"]]['file_upload_error'] = "Une erreur est survenue, impossible d'interpréter ce document.";
  1367.                     }
  1368.                   }
  1369.                   if (strtolower($extension) == "xlsx") {
  1370.                     $xlsx = \SimpleXLSX::parse($tmpfile);
  1371.                     if ($xlsx) {
  1372.                       $rows $xlsx->rows();
  1373.                     } else {
  1374.                       $twigData["products"][$posts["product_id"]]['file_upload_error'] = "Une erreur est survenue, impossible d'interpréter ce document.";
  1375.                     }
  1376.                   }
  1377.                   if (strtolower($extension) == "csv") {
  1378.                     ini_set('auto_detect_line_endings',TRUE);
  1379.                     if (($handle fopen($tmpfile"r")) !== FALSE) {
  1380.                       while (($data fgetcsv($handle0",")) !== FALSE) {
  1381.                         if (count($data) > 1) {
  1382.                           $rows[] = $data;
  1383.                         }
  1384.                       }
  1385.                       fclose($handle);
  1386.                     }
  1387.                     if (empty($rows)) {
  1388.                       if (($handle fopen($tmpfile"r")) !== FALSE) {
  1389.                         while (($data fgetcsv($handle0";")) !== FALSE) {
  1390.                           if (count($data) > 1) {
  1391.                             $rows[] = $data;
  1392.                           }
  1393.                         }
  1394.                         fclose($handle);
  1395.                       }
  1396.                     }
  1397.                     ini_set('auto_detect_line_endings',FALSE);
  1398.                   }
  1399.                   if (!empty($rows)) {
  1400.                     $twigData["products"][$posts["product_id"]]["imported_filename"] = $filename;
  1401.                     $twigData["products"][$posts["product_id"]]["row_to_test_import"] = $rows[0];
  1402.                     $this->session->set('ROWS_TO_BE_IMPORTED_'.$posts["product_id"], json_encode($rows));
  1403.                   }
  1404.                   $twigData["products"][$posts["product_id"]]['file_upload_success'] = "Le fichier a été reçu. Veuillez configurer les colonnes à importer.";
  1405.                 } else {
  1406.                   $twigData["products"][$posts["product_id"]]['file_upload_error'] = "Le fichier n'est pas supporté. Veuillez importer un fichier CSV ou Excel seulement.";
  1407.                 }
  1408.               }
  1409.               unlink($tmpfile);
  1410.             } else {
  1411.               $twigData["products"][$posts["product_id"]]['file_upload_error'] = "Veuillez importer un fichier CSV ou Excel seulement.";
  1412.             }
  1413.         
  1414.           }
  1415.       }
  1416.       
  1417.       try {
  1418.         $payload = [];
  1419.         foreach($twigData["products"] as $product_id => $product) {
  1420.           $payload[$product_id]["multiple_ship_to"] = $product["multiple_ship_to"];
  1421.           if (!empty($product["ship_to"])) {
  1422.             foreach($product["ship_to"] as $address) {
  1423.               $payload[$product_id]["ship_to"][$address["contact_col_email"]]["qty"] = $address["quantity"];
  1424.             }
  1425.           }
  1426.         }
  1427.         $twigData["ship_to_form_payload"] = json_encode($payload);
  1428.       } catch (\Exception $e) {
  1429.           $this->userServ->sendEmail('ERROR: importDataMultipleAdress () failed!''<p>ERROR: importDataMultipleAdress() failed!</p><p>Impossible to import adress from the form or the file</p><hr/>'.$e->getMessage(), false'entrepot@maturin.ca');
  1430.           $this->addFlash('error'"Une erreur est survenu lors du chargement veuillez vérifier les informations rentrer ou contacter notre support.");
  1431.           return $this->redirectToRoute("bulkship");
  1432.       }
  1433.       return $twigData;
  1434.     }
  1435.     /**
  1436.      * @Route({
  1437.      *          "fr": "/deliveryEstimateAjax",
  1438.      *          "en": "/deliveryEstimateAjax"
  1439.      *      }, name="deliveryEstimateAjax")
  1440.      * @Security("has_role('ROLE_USER')")
  1441.      */
  1442.     public function deliveryEstimateAjax(Request $requestEntityManagerInterface $emUserService $userServ,TwigGlobalVariables $twigGlobalVariables) {
  1443.       $shippingAddressId trim($request->get("shippingAddressId"));
  1444.       $newAddressProvince trim($request->get("newAddressProvince"));
  1445.       $shippingAddressCity trim($request->get("shippingAddressCity"));
  1446.       $user $userServ->getUser();
  1447.       $cart $userServ->getCart();
  1448.       $city false;
  1449.  
  1450.       if ($shippingAddressId 0) {
  1451.           $shippingAddress $em->getRepository(UserShippingLocation::class)->findOneBy(['id'=>$shippingAddressId]);
  1452.          
  1453.           if ($shippingAddress) {
  1454.             $city $shippingAddress->getCity();
  1455.             $newAddressProvince $shippingAddress->getProvince();
  1456.           }
  1457.       }else{
  1458.           $shippingAddress $em->getRepository(City::class)->findBy(['id'=>$shippingAddressCity]);
  1459.           foreach ($shippingAddress as $shippingAddressName) {
  1460.             $city $shippingAddressName->getName();
  1461.             $newAddressProvince $shippingAddressName->getProvince();
  1462.           }
  1463.       }
  1464.       if ( $newAddressProvince == "QC" || $newAddressProvince == "ON") {
  1465.        
  1466.     } else {
  1467.         $city $shippingAddressCity;
  1468.     }
  1469.    
  1470.       $dow false;
  1471.       $nameRoute null;
  1472.       $idRoute null;
  1473.       if ($city) {
  1474.         $city trim($city);
  1475.         $cityEntity $em->getRepository(City::class)->findLikeNameAndProvince($city$newAddressProvince);
  1476.         $route $twigGlobalVariables->getEstimationShippingRouteForMaturinProducts($cart$city);
  1477.         $dateRoute $route['date']->format('d F Y');
  1478.         if ($cityEntity) {
  1479.           $cityEntity current($cityEntity);
  1480.           $cityDeliveryRoutes $cityEntity->getDeliveryRoutes();
  1481.           foreach($cityDeliveryRoutes as $route) {
  1482.             if ($route->getType() == "maturin") {
  1483.               $nameRoute $route->getName();
  1484.               $idRoute $route->getId();
  1485.               if ($route->getMonday()) {
  1486.                 $dow 1;
  1487.               }
  1488.               if ($route->getTuesday()) {
  1489.                 $dow 2;
  1490.               }
  1491.               if ($route->getWednesday()) {
  1492.                 $dow 3;
  1493.               }
  1494.               if ($route->getThursday()) {
  1495.                 $dow 4;
  1496.               }
  1497.               if ($route->getFriday()) {
  1498.                 $dow 5;
  1499.               }
  1500.               if ($route->getSaturday()) {
  1501.                 $dow 6;
  1502.               }
  1503.               if ($route->getSunday()) {
  1504.                 $dow 0;
  1505.               }
  1506.             }
  1507.           }
  1508.         }
  1509.       }
  1510.       die(json_encode([
  1511.         'dow' => $dow,
  1512.         'city' => $city,
  1513.         'route' => $dateRoute,
  1514.         'nameRoute' => $nameRoute,
  1515.         'idRoute' => $idRoute
  1516.       ]));
  1517.     }
  1518.     /**
  1519.      * @Route({
  1520.      *          "fr": "/newDeliveryEstimateAjax",
  1521.      *          "en": "/newDeliveryEstimateAjax"
  1522.      *      }, name="newDeliveryEstimateAjax")
  1523.      * @Security("has_role('ROLE_USER')")
  1524.      */
  1525.     public function newDeliveryEstimateAjax(Request $requestEntityManagerInterface $emUserService $userServ,TwigGlobalVariables $twigGlobalVariables) {
  1526.       $cart $userServ->getCart();
  1527.       if ($cart->getShippingAddress()){
  1528.         $shippingAddressId $cart->getShippingAddress()->getId();
  1529.         $shippingAddressCity $cart->getShippingAddress()->getCity();
  1530.         $shippingAddressCity$cart->getShippingAddress()->getProvince();;
  1531.       }
  1532.       $user $userServ->getUser();
  1533.       $cart $userServ->getCart();
  1534.       $city false;
  1535.  
  1536.       if ($shippingAddressId 0) {
  1537.           $shippingAddress $em->getRepository(UserShippingLocation::class)->findOneBy(['id'=>$shippingAddressId]);
  1538.          
  1539.           if ($shippingAddress) {
  1540.             $city $shippingAddress->getCity();
  1541.             $newAddressProvince $shippingAddress->getProvince();
  1542.           }
  1543.       }else{
  1544.           $shippingAddress $em->getRepository(City::class)->findBy(['id'=>$shippingAddressCity]);
  1545.           foreach ($shippingAddress as $shippingAddressName) {
  1546.             $city $shippingAddressName->getName();
  1547.             $newAddressProvince $shippingAddressName->getProvince();
  1548.           }
  1549.       }
  1550.       if ( $newAddressProvince == "QC" || $newAddressProvince == "ON") {
  1551.        
  1552.     } else {
  1553.         $city $shippingAddressCity;
  1554.     }
  1555.    
  1556.       $dow false;
  1557.       $nameRoute null;
  1558.       $idRoute null;
  1559.       if ($city) {
  1560.         $city trim($city);
  1561.         $cityEntity $em->getRepository(City::class)->findLikeNameAndProvince($city$newAddressProvince);
  1562.         $route $twigGlobalVariables->getEstimationShippingRouteForMaturinProducts($cart$city);
  1563.         $dateRoute $route['date']->format('d F Y');
  1564.         if ($cityEntity) {
  1565.           $cityEntity current($cityEntity);
  1566.           $cityDeliveryRoutes $cityEntity->getDeliveryRoutes();
  1567.           foreach($cityDeliveryRoutes as $route) {
  1568.             if ($route->getType() == "maturin") {
  1569.               $nameRoute $route->getName();
  1570.               $idRoute $route->getId();
  1571.               if ($route->getMonday()) {
  1572.                 $dow 1;
  1573.               }
  1574.               if ($route->getTuesday()) {
  1575.                 $dow 2;
  1576.               }
  1577.               if ($route->getWednesday()) {
  1578.                 $dow 3;
  1579.               }
  1580.               if ($route->getThursday()) {
  1581.                 $dow 4;
  1582.               }
  1583.               if ($route->getFriday()) {
  1584.                 $dow 5;
  1585.               }
  1586.               if ($route->getSaturday()) {
  1587.                 $dow 6;
  1588.               }
  1589.               if ($route->getSunday()) {
  1590.                 $dow 0;
  1591.               }
  1592.             }
  1593.           }
  1594.         }
  1595.       }
  1596.       die(json_encode([
  1597.         'dow' => $dow,
  1598.         'city' => $city,
  1599.         'route' => $dateRoute,
  1600.         'nameRoute' => $nameRoute,
  1601.         'idRoute' => $idRoute
  1602.       ]));
  1603.     }
  1604.     /**
  1605.      * @Route({
  1606.      *          "fr": "/livraison",
  1607.      *          "en": "/delivery"
  1608.      *      }, name="checkout")
  1609.      * @Security("has_role('ROLE_USER')")
  1610.      * @Template("frontend/checkout.html.twig")
  1611.      */
  1612.     public function checkout(UserService $userServRequest $request,TwigGlobalVariables $twigGlobalVariables){
  1613.       
  1614.       $twigData = array();
  1615.         $twigData['hideSideMenu'] = true;
  1616.         $twigData['loader']= true;
  1617.         $cart $userServ->getCart();
  1618.         $cart->getProducts();
  1619.         $em $this->getDoctrine()->getManager();
  1620.        
  1621.         $twigData["products"] = [];
  1622.         $products $cart->getProducts();
  1623.         foreach($products as $product) {
  1624.           $twigData["products"][$product->getProduct()->getId()] = [
  1625.             "cart_product" => $product,
  1626.             "ship_to" => [],
  1627.             "default_ship_to" => [$cart->getShippingAddress()],
  1628.             "default_ship_to_email" => $userServ->getUser()->getEmail(),
  1629.             "rows_to_import" => [],
  1630.             "row_to_test_import" => [],
  1631.             "imported_filename" => "",
  1632.             "multiple_ship_to" => false,
  1633.             "file_upload_error" => false,
  1634.             "file_upload_success" => false,
  1635.           ];
  1636.           $session_imported_rows $this->session->get('IMPORTED_ROWS_'.$product->getProduct()->getId());
  1637.           if (!empty($session_imported_rows)) {
  1638.             $twigData["products"][$product->getProduct()->getId()]["ship_to"] = json_decode($session_imported_rowstrue);
  1639.             $twigData["products"][$product->getProduct()->getId()]["multiple_ship_to"] = true;
  1640.           }
  1641.         }
  1642.         $payload = [];
  1643.         foreach($twigData["products"] as $product_id => $product) {
  1644.           $payload[$product_id]["multiple_ship_to"] = $product["multiple_ship_to"];
  1645.           if (!empty($product["ship_to"])) {
  1646.             foreach($product["ship_to"] as $address) {
  1647.               $payload[$product_id]["ship_to"][$address["contact_col_email"]]["qty"] = $address["quantity"];
  1648.             }
  1649.           }
  1650.         }
  1651.         $twigData["ship_to_form_payload"] = json_encode($payload);
  1652.         $twigData["pickupLocation"] = $twigGlobalVariables->getGlobalPickUpLocations();
  1653.         $twigData['checkout'] = $cart;
  1654.         $twigData['activeSubscriptions'] = $userServ->getUser()->getActiveSubscriptions();
  1655.         $contains_alcohol false;
  1656.         $contains_puro_exclusion false;
  1657.         $cold_products false;
  1658.         $products = [];
  1659.         foreach($cart->getProducts() as $cp) {
  1660.           $product $cp->getProduct();
  1661.           if($product->getIsBoxOfProducts()) {
  1662.             foreach($product->getProductsInBox() as $mp) {
  1663.               $products[] = $mp->getProduct();
  1664.               if ($mp->getProduct()->getPuroExclusion()) {
  1665.                 $contains_puro_exclusion true;
  1666.               }
  1667.             }
  1668.           } else {
  1669.             $products[] = $product;
  1670.             if ($product->getPuroExclusion()) {
  1671.               $contains_puro_exclusion true;
  1672.             }
  1673.             if ($product->getId() == 6472) {
  1674.               $contains_puro_exclusion true;
  1675.             }
  1676.           }
  1677.         }
  1678.         $estimationDateToTake $cart->getShippingMaturinEstimatedDate();
  1679.         foreach($products as $product) {
  1680.           if ($product->getIsCold()) {
  1681.             $cold_products true;
  1682.           }
  1683.           if ($product->getIsAlcohol()) {
  1684.             $contains_alcohol true;
  1685.           }
  1686.         }
  1687.         $twigData['contains_alcohol'] = $contains_alcohol;
  1688.         
  1689.         if ($request->getMethod() == 'POST'){
  1690.       //  if($request->get("action") == "proceed_to_payment"){
  1691.             $em $this->getDoctrine()->getManager();
  1692.             $customDeliveryDate $request->get("livraisonDate");
  1693.             if ( $request->get('DeliveryCheck') == "on" && !empty($customDeliveryDate)) {
  1694.               // dump($request->request->get("livraisonDate"))
  1695.               $months = [
  1696.                 'janvier' => 'january',
  1697.                 'février' => 'february',
  1698.                 'mars' => 'march',
  1699.                 'avril' => 'april',
  1700.                 'mai' => 'may',
  1701.                 'juin' => 'june',
  1702.                 'juillet' => 'july',
  1703.                 'août' => 'august',
  1704.                 'septembre' => 'september',
  1705.                 'octobre' => 'october',
  1706.                 'novembre' => 'november',
  1707.                 'décembre' => 'december'
  1708.               ];
  1709.               $customDeliveryDate explode(" "$customDeliveryDate)[1]. " " .$months[explode(" "$customDeliveryDate)[2]]. " "explode(" "$customDeliveryDate)[3];
  1710.               $requestDate = new \DateTime(date("Y-m-d"strtotime($customDeliveryDate)));
  1711.               $date = new \DateTime('now');
  1712.               $date->modify('+8 days');
  1713.               if ($requestDate->format('Y-m-d') > $date->format('Y-m-d')){
  1714.                 $cart->setDeliveryChoiceDate($requestDate);
  1715.                 $cart->setPreOrder(true);
  1716.                 $cart->setPreOrderNow(true);
  1717.               }else{
  1718.                 $cart->setDeliveryChoiceDate($requestDate);
  1719.                 $cart->setPreOrder(true);
  1720.               }
  1721.             } else {
  1722.                 $cart->setPreOrder(false);
  1723.                 $cart->setPreOrderNow(false);
  1724.                 $cart->setDeliveryChoiceDate(null);
  1725.             }
  1726.             $forceRedirect=false;
  1727.             $claudia $em->getRepository(User::class)->findOneBy(["email" => "corpo@maturin.ca"])->getEmail();
  1728.             if ($this->getUser() && $this->getUser()->getEmail() == $claudia){
  1729.             }else{
  1730.             // si il n'y a pas de date de livraison choisi = pas de précommandes donc calcul normal
  1731.            if ($cart->getPreOrder() != false){
  1732.                 //Check if all Maturin product has quantit
  1733.               
  1734.             $limit_date = new Datetime('+ 7 days');
  1735.               foreach($cart->getProducts() as $p){
  1736.                 if ($p->getRecurringFrequency() > && $cart->getDeliveryChoiceDate() >= $limit_date) {
  1737.                     $this->addFlash('error'"Vous ne pouvez pas précommander un abonnement. Veuillez passer votre abonnement en dehors de votre précommande.");
  1738.                     return $this->redirectToRoute('viewCart');
  1739.                 }
  1740.               }
  1741.             }
  1742.           }
  1743.           if ($request->get("action_shipping") == "domicile"){
  1744.             try{
  1745.             if($request->get("checkoutAddressSelection") == "none"){
  1746.                 $newadresseAutocomplete $request->request->get('newAddress_autocomplete');
  1747.              
  1748.                 $pattern '/\d+/';
  1749.                 preg_match($pattern$newadresseAutocomplete$civicnumber);
  1750.                 $pattern strlen($civicnumber[0]);
  1751.                 $streetname substr($newadresseAutocomplete$pattern);
  1752.                 $arrayAutocomplete explode(', 'trim($streetname));
  1753.               
  1754.                   $newAddress_civicnumber $civicnumber[0];
  1755.                   $newAddress_streetname $arrayAutocomplete[0];
  1756.                   $newAddress_phone $request->request->get('newAddress_phone');
  1757.                   $newAddress_province $request->request->get('adresse_province');
  1758.                   $newAddress_zipcode =  $request->request->get('newAddress_zipcode');
  1759.                   $adresse_unit $request->request->get('newAddress_unit');
  1760.                   $newAddress_city $request->request->get('adresse_city');
  1761.                   $newAdresse_name =  $request->request->get('newAddress_name');
  1762.           
  1763.                   $findTheCity $em->getRepository(City::class)->findBy(["name"=>$newAddress_city]);
  1764.       
  1765.                   if ($findTheCity == null && $newAddress_province == "QC"){
  1766.                     $findTheCity = new City();
  1767.                     $findTheCity->setName(trim($newAddress_city));
  1768.                     $findTheCity->setMrc(trim($newAddress_city));
  1769.                     $findTheCity->setProvince(trim($newAddress_province));
  1770.                     $findTheRegion $em->getRepository(Region::class)->findBy(["name"=>'defaut']);
  1771.                     $findTheCity->setRegion($findTheRegion[0]);
  1772.                     $em->persist($findTheCity);
  1773.                     $em->flush();
  1774.                     $charlie $em->getRepository(User::class)->findOneBy(["email" => "charlie@maturin.ca"])->getEmail();
  1775.                     $userServ->sendEmail('Une nouvelle ville a été ajouté''<p>La ville ,' $newAddress_city ' a été ajouté dans la base de données par ' $this->getUser()->getEmail() . '</p>'false$charlie);
  1776.                   }
  1777.           
  1778.                   $UserShippingLocation = new UserShippingLocation();
  1779.                 
  1780.                   $UserShippingLocation->setName($newAdresse_name);
  1781.                     // ajout de condition format et correspond au type de data attendu 
  1782.                   $UserShippingLocation->setPhone($newAddress_phone);
  1783.                   $UserShippingLocation->setCivicNumber($newAddress_civicnumber);
  1784.                   $UserShippingLocation->setStreetName($newAddress_streetname);
  1785.                   $UserShippingLocation->setUnit($adresse_unit);
  1786.                   $UserShippingLocation->setCity($newAddress_city);
  1787.                   $UserShippingLocation->setZipCode($newAddress_zipcode);
  1788.                   $UserShippingLocation->setProvince($newAddress_province);
  1789.                   $UserShippingLocation->setUser($this->getUser());
  1790.                   $UserShippingLocation->setEmail($this->getUser()->getEmail());
  1791.                   $em->persist($UserShippingLocation);
  1792.                   $cart->setShippingAddress($UserShippingLocation);
  1793.                   $em->persist($cart);
  1794.                   $em->flush();
  1795.             } else {
  1796.               $shippingAddressId $request->get("checkoutAddressSelection");
  1797.               $addr $em->getRepository(UserShippingLocation::class)->findOneBy(["id"=>$shippingAddressId]);
  1798.               $addr->setEmail($this->getUser()->getEmail());
  1799.               $cart->setShippingAddress($addr);
  1800.               $em->persist($cart);
  1801.               $em->flush();
  1802.             }
  1803.           }catch(\Exception $e){
  1804.             // $this->userServ->sendEmail('ERROR: errorChackoutErrorData() failed!', '<p>ERROR: errorChackoutErrorData() failed!</p><p>Error during save data in database !</p><hr/>'.$e->getMessage(), false, 'entrepot@maturin.ca');
  1805.             $this->addFlash('error'"Votre adresse comporte une erreur vérifier vos informations");
  1806.             return $this->redirectToRoute('checkout');
  1807.           }
  1808.         }
  1809.             /*
  1810.               prevent user from using invalid city names
  1811.             */
  1812.             $addr $cart->getShippingAddress();
  1813.             if ($request->get('pickupScheduleCheckbox') != "cueillette" ) {
  1814.               if ($addr){
  1815.                 if($addr->getProvince() == 'QC' || $addr->getProvince() == 'ON'){
  1816.                   if (!$addr->isCityValid()) {
  1817.                     $this->addFlash('error'"Votre adresse de livraison n'est pas valide, veuillez vérifier le nom de la ville.");
  1818.                     return $this->redirectToRoute('checkout');
  1819.                   }
  1820.                 }
  1821.               }elseif(!$addr){
  1822.                   $shippingAddressId $request->get("checkoutAddressSelection");
  1823.                   $addr $em->getRepository(UserShippingLocation::class)->findOneBy(["id"=>$shippingAddressId]);
  1824.                   $cart->setShippingAddress($addr);
  1825.                   $em->persist($cart);
  1826.                   $em->flush();
  1827.               }
  1828.            }
  1829.             if ($contains_alcohol && $request->get("18YearsOld") != "on") {
  1830.               $this->addFlash('error'"Vous devez certifier que vous avez 18 ans et plus car cette commande contient des produits alcoolisés.");
  1831.               return $this->redirectToRoute('checkout');
  1832.             }
  1833.             $redirect true;
  1834.             $route_is_puro_nocold false;
  1835.             $maturin_type_route_found false;
  1836.             $shippingAddress $cart->getShippingAddress();
  1837.             if (!$shippingAddress && $request->get('pickupScheduleCheckbox') != "cueillette") {
  1838.          
  1839.               $this->addFlash('error'"Votre adresse de livraison n'est pas valide, veuillez vérifier vos informations.");
  1840.               return $this->redirectToRoute('checkout');
  1841.             }
  1842.             if ($shippingAddress) {
  1843.               $cityName $shippingAddress->getCity();
  1844.               $province $shippingAddress->getProvince();
  1845.               //$city = $em->getRepository(City::class)->findLikeName($cityName);
  1846.               $city $em->getRepository(City::class)->findLikeNameAndProvince($cityName,$province);
  1847.               if (empty($city)) {
  1848.                 $maturin_type_route_found true;
  1849.               } else {
  1850.                 $city $city[0];
  1851.               }
  1852.               if ($city) {
  1853.                 $routes $city->getDeliveryRoutes();
  1854.                 foreach($routes as $route) {
  1855.                   if (
  1856.                     $route->getType() == "maturin" && $route->getName() != "Pas de frais"
  1857.                   ) {
  1858.                     $maturin_type_route_found true;
  1859.                   }
  1860.                   if ($route->getName() == "Pas de frais") {
  1861.                     $route_is_puro_nocold true;
  1862.                   }
  1863.                 }
  1864.               }
  1865.             }
  1866.             $redirect_params = [];
  1867.             if ($contains_puro_exclusion && !$maturin_type_route_found) {
  1868.               // $this->addFlash('error', "Il est impossible de livrer un produit à cette adresse car il contient de l'alcool.");
  1869.               $redirect_params["alert_nodelivery_puro"] = "true";
  1870.             }
  1871.             if ($contains_alcohol && !$maturin_type_route_found) {
  1872.               // $this->addFlash('error', "Il est impossible de livrer un produit à cette adresse car il contient de l'alcool.");
  1873.               $redirect_params["alert_nodelivery_alcohol"] = "true";
  1874.             }
  1875.             if ($route_is_puro_nocold && $cold_products && !$maturin_type_route_found) {
  1876.               // $this->addFlash('error', "Il est impossible de livrer un produit à cette adresse car il doit rester frais durant la livraison.");
  1877.               $redirect_params["alert_nodelivery_cold"] = "true";
  1878.             }
  1879.             if (!empty($redirect_params) and $request->get('pickupScheduleCheckbox') != "cueillette" ) {
  1880.               return $this->redirectToRoute('viewCart'$redirect_params);
  1881.             }
  1882.             //Lets start with the coupon see if it's valid
  1883.             $coupon $request->get("coupon");
  1884.             if(!empty($coupon) ){
  1885.               $cartCoupon $em->getRepository(CartCoupon::class)->findOneValidByCode($coupon);
  1886.               $couponSearchTuango false;
  1887.               $couponSearchTuango =  $this->CouponTuango($coupon);
  1888.               $couponCabane false;
  1889.               $couponCabane =  $this->CouponCabaneMaturin($coupon);
  1890.               if ($couponSearchTuango != false || $couponCabane != false){
  1891.                 $cartCoupon $em->getRepository(CartCoupon::class)->findOneValidByCode($coupon);
  1892.               }
  1893.                 if(empty($cartCoupon)){
  1894.                   if ($couponSearchTuango == false && $couponCabane == false){
  1895.                     $this->addFlash('error'"Merci de vérifier votre code coupon ou associez-le au bon produit");
  1896.                     return $this->redirectToRoute('checkout');
  1897.                   }
  1898.                 }else{
  1899.                     //If coupon is a onetimeonly and was already used
  1900.                     if($cartCoupon->getOneTimeOnly()){
  1901.                         if($cartCoupon->getUsedByUsers()->contains($userServ->getUser())){
  1902.                             $this->addFlash('error'"Vous avez déja utilisé ce coupon");
  1903.                             return $this->redirectToRoute('checkout');
  1904.                         }
  1905.                     }
  1906.                     //Check if any money left
  1907.                     if($cartCoupon->getIsGiftCertificate() && $cartCoupon->getAmount() <= ){
  1908.                         $this->addFlash('error'"Ce coupon a un solde restant de 0$");
  1909.                         return $this->redirectToRoute('checkout');
  1910.                     }
  1911.                     $cart->setUsedCoupon($cartCoupon);
  1912.                     //$user = $userServ->getUser();
  1913.                     //$user->addCouponUsed($cartCoupon);
  1914.                     //$em->persist($user);
  1915.                 }
  1916.             }else{
  1917.               //$user->removeCouponUsed($cartCoupon);
  1918.               $cart->setUsedCoupon(null);
  1919.             }
  1920.             // picking and packing
  1921.             foreach ($cart->getProducts() as $cp){
  1922.                 if ($request->get('pickupScheduleCheckbox') == "cueillette" ) {
  1923.                   $customDeliveryDate $request->get("pickupSchedule");
  1924.                   if (!empty($customDeliveryDate)) {
  1925.                     // dump($request->request->get("livraisonDate"))
  1926.                     $months = [
  1927.                       'janvier' => 'january',
  1928.                       'février' => 'february',
  1929.                       'mars' => 'march',
  1930.                       'avril' => 'april',
  1931.                       'mai' => 'may',
  1932.                       'juin' => 'june',
  1933.                       'juillet' => 'july',
  1934.                       'août' => 'august',
  1935.                       'septembre' => 'september',
  1936.                       'octobre' => 'october',
  1937.                       'novembre' => 'november',
  1938.                       'décembre' => 'december'
  1939.                     ];
  1940.       
  1941.                     $customDeliveryDate explode(" "$customDeliveryDate)[1]. " " .$months[explode(" "$customDeliveryDate)[2]]. " "explode(" "$customDeliveryDate)[3];
  1942.                     $requestDate = new \DateTime(date("Y-m-d"strtotime($customDeliveryDate)));
  1943.       
  1944.                     $date = new \DateTime('now');
  1945.                     $date->modify('+8 days');
  1946.       
  1947.                     if ($requestDate->format('Y-m-d') > $date->format('Y-m-d')){
  1948.                       $cart->setDeliveryChoiceDate($requestDate);
  1949.                       $cart->setPreOrder(true);
  1950.                       $cart->setPreOrderNow(true);
  1951.                     }else{
  1952.                       $cart->setDeliveryChoiceDate($requestDate);
  1953.                       $cart->setPreOrder(true);
  1954.                     }
  1955.                   } else {
  1956.                       $cart->setPreOrder(false);
  1957.                       $cart->setPreOrderNow(false);
  1958.                       $cart->setDeliveryChoiceDate(null);
  1959.                   }
  1960.                   if(!$cp->getProduct()->isShippedByMaturin()){
  1961.                     $this->addFlash('error'"Le produit ".$cp->getProduct()->getName()." n'est pas disponible pour une cueillette vous devez l'enlever de votre panier afin de procéder");
  1962.                     return $this->redirectToRoute('viewCart');
  1963.                   }
  1964.                   $pickUpSchedule $request->get('pickupSchedule');
  1965.                   if (empty($pickUpSchedule)) {
  1966.                     $this->addFlash('error'"Il faut spécifier une date et un temps de cueillette.");
  1967.                     return $this->redirectToRoute('checkout');
  1968.                   }
  1969.                   $pickUpAdress $request->get('pickupLocation');
  1970.                   $pickupLocationId $request->get('pickupLocations');
  1971.                   $dm = new DeliveryMethod();
  1972.                   $dm->setAverageDays(1);
  1973.                   $dm->setIsAPickup(true);
  1974.                   $dm->setServiceId(9999);
  1975.                   $dm->setFixedPrice(0);
  1976.                   $dm->setValid(true);
  1977.                   $dm->setPickupSchedule($pickUpSchedule);
  1978.                   $dm->setPickupAddress($pickUpAdress);
  1979.                   $dm->setPickupLocationId($pickupLocationId);
  1980.                   $cp->setCompanyDeliveryMethod($dm);
  1981.                   $em->persist($dm);
  1982.                   $em->persist($cp);
  1983.                 }else {
  1984.                   $dm $cp->getCompanyDeliveryMethod();
  1985.                   if($cp->getAddedWhenBeingInAssociation()){
  1986.                     if($cp->getAddedWhenBeingInAssociation()->getVariableValueByCodeName('orders.canPickUp')){
  1987.                       $dm = new DeliveryMethod();
  1988.                       $dm->setAverageDays(1);
  1989.                       $dm->setIsAPickup(true);
  1990.                       $dm->setServiceId(9999);
  1991.                       $dm->setFixedPrice(0);
  1992.                       $dm->setValid(true);
  1993.                       $cp->setCompanyDeliveryMethod($dm);
  1994.                       $em->persist($dm);
  1995.                       $em->persist($cp);
  1996.                       $em->flush();
  1997.                     }
  1998.                   }
  1999.                   if ($cp->getIsAPickup()){
  2000.                     $dm $cp->getCompanyDeliveryMethod();
  2001.                     if(!empty($cp->getCompanyDeliveryMethod()->getId())){
  2002.                       $idPickUp $cp->getCompanyDeliveryMethod()->getId();
  2003.                       $entityManager $this->getDoctrine()->getManager();
  2004.                       $PickUpRetake $entityManager->getRepository(DeliveryMethod::class)->find($cp->getId());
  2005.                       $cp->setCompanyDeliveryMethod(null);
  2006.                       $entityManager->persist($cp);
  2007.                       $entityManager->flush();
  2008.                   }else{
  2009.                     // if($request->hasPreviousSession('pickupSchedule')) {
  2010.                       $dm->setAverageDays(2);
  2011.                       $dm->setPickupSchedule($request->get('pickupSchedule'));
  2012.                       $address$cp->getAddedWhenBeingInAssociation()->getVariableValueByCodeName('orders.pickUpAdress');
  2013.                       $dm->setPickupAddress($address);
  2014.                     // }
  2015.                   }
  2016.                     $withPacking $request->hasPreviousSession('withPacking')
  2017.                     && $request->get('withPacking') == 'true';
  2018.                     $dm->setWithPacking($withPacking);
  2019.                     $em->persist($dm);
  2020.                   }
  2021.                 }
  2022.                 $newAddress_phone $request->request->get('pickup_phone');
  2023.                 $newAdresse_name =  $request->request->get('pickup_name');
  2024.                 if($cart->getPickupAddress() != null){
  2025.                   $UserInformation $this->getUser();
  2026.                   if (!empty($newAddress_phone)){
  2027.                     $UserInformation->setPhone($newAddress_phone);
  2028.                   }else{
  2029.                     $this->addFlash('error'"Veuillez noter votre numéro de téléphone");
  2030.                     return $this->redirectToRoute('checkout');
  2031.                   }
  2032.                     $UserInformation->setFirstname($newAdresse_name);
  2033.                   $em->persist($UserInformation);
  2034.                   $em->flush();
  2035.                 }
  2036.             }
  2037.             $cart->resetCalculations();
  2038.             $em->persist($cart);
  2039.             $em->flush();
  2040.             if ($request->get('action_bulkshipping') == "on" && $request->get('pickupScheduleCheckbox') != "cueillette" ) {
  2041.               return $this->redirectToRoute('bulkship');
  2042.             }
  2043.             if($redirect) {
  2044.               return $this->redirectToRoute('cartPayment');
  2045.             }
  2046.         }
  2047.         
  2048.         // We set the coupon if users has a valid one
  2049.         
  2050.         $couponMarketing$this->session->get('coupon_marketing');
  2051.         $twigData['couponMarketing']=false;
  2052.         if($couponMarketing){
  2053.           $cartCoupon $em->getRepository(CartCoupon::class)->findOneValidByCode($couponMarketing);
  2054.           if(!empty($cartCoupon)){
  2055.             $twigData['couponMaketing']=$cartCoupon;
  2056.           }
  2057.         }
  2058.         $userCouponList=[];
  2059.         $tempCouponLists$em->getRepository(CartCoupon::class)->findAllUserCoupons($userServ->getUser()->getId());
  2060.         // we only get not used coupon by the user
  2061.         foreach ($tempCouponLists as $cartCoupon ) {
  2062.           if($cartCoupon->getOneTimeOnly()){
  2063.             if($cartCoupon->getUsedByUsers()->contains($userServ->getUser()))
  2064.                 continue;
  2065.             else
  2066.               array_push($userCouponList,$cartCoupon);
  2067.           }else
  2068.             array_push($userCouponList,$cartCoupon);
  2069.         }
  2070.         $twigData['couponLists'] = $userCouponList;
  2071.         
  2072.         return $twigData;
  2073.     }
  2074.     /**
  2075.      * @Route({
  2076.      *          "fr": "/panier",
  2077.      *          "en": "/cart"
  2078.      *      }, name="viewCart")
  2079.      * @Template("frontend/cart.html.twig")
  2080.      */
  2081.     public function viewCart(UserService $userServRequest $request){
  2082.         $twigData = array();
  2083.         $twigData['loader'] = true;
  2084.         $twigData['suggestedProducts']= $userServ->findProductsToSuggest();
  2085.         $cart $userServ->getCart();
  2086.         $cart->setUsedCoupon(null);
  2087.         $cart->setDeliveryChoiceDate(null);
  2088.         $cart->setPreOrder(false);
  2089.         $cart->setNoteFromBuyer(null);
  2090.         $cart->setPreOrderNow(false);
  2091.         $cart->setDateCreated(new \DateTime(), new \DateTimeZone('America/New_York'));
  2092.         $cart->setDatePayment(new \DateTime(), new \DateTimeZone('America/New_York'));
  2093.         $em $this->getDoctrine()->getManager();
  2094.         //To avoid a lot of bug occuring when the user go back and forth from Payment to card we reset the cart
  2095.         $cart->resetCalculations();
  2096.         $cartForm$this->createForm(CartType::class, $cart);
  2097.         $cartForm->handleRequest($request);
  2098.         if ($request->get("alert_nodelivery_puro") == "true") {
  2099.           $twigData['alert_nodelivery_puro'] = "true";
  2100.         }
  2101.         if ($request->get("alert_nodelivery_cold") == "true") {
  2102.           $twigData['alert_nodelivery_cold'] = "true";
  2103.         }
  2104.         if ($request->get("alert_nodelivery_alcohol") == "true") {
  2105.           $twigData['alert_nodelivery_alcohol'] = "true";
  2106.         }
  2107.         $claudia $em->getRepository(User::class)->findOneBy(["email" => "corpo@maturin.ca"])->getEmail();
  2108.         /* Fix a bug that sometime having product erased they come back */
  2109.         if($cartForm->get('update')->isClicked()){
  2110.           if ($this->getUser() && $this->getUser()->getEmail() == $claudia){
  2111.           }else{
  2112.             $forceRedirect=false;
  2113.             foreach($cart->getProducts() as $p){
  2114.               if (!$p->getProduct()->getIsBoxOfProducts()){
  2115.             // getQuantityMaxProd valable que en preOrder pour augmenter les ventes en période de fetes, permet au producteur d'anticiper 
  2116.             // et de vendre plusque quantité hebdomadaire
  2117.             //If the quantity we have in stock is lower than the one the customer wants
  2118.             $getQtyReadyToShip $p->getProduct()->getQtyReadyToShip();
  2119.                 if ($getQtyReadyToShip) {
  2120.                   if ($p->getProduct()->getQuantityMaxProd() > 0){
  2121.                     $getQtyComing $p->getProduct()->getQuantityMaxProd();
  2122.                   }else{
  2123.                     $getQtyComing 0;
  2124.                   }
  2125.                 $qtyMaximumToSell $getQtyReadyToShip $getQtyComing;
  2126.                if($qtyMaximumToSell $p->getQuantity()) {
  2127.                 if($qtyMaximumToSell == 0){
  2128.                   $this->addFlash('error'"Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier");
  2129.                   $em->remove($p);
  2130.                   $em->flush();
  2131.                   $forceRedirect=true;
  2132.                   continue;
  2133.                 }else{
  2134.                   $this->addFlash('error'"La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire");
  2135.                   $p->setQuantity($getQtyReadyToShip);
  2136.                   $em->persist($p);
  2137.                   $em->flush();
  2138.                   $forceRedirect=true;
  2139.                   continue;
  2140.                 }
  2141.                   }
  2142.                 }
  2143.               }
  2144.           // If the jit product pass the weekly  qty to sell
  2145.             if($p->getProduct()->getIsJustInTime() && !$p->getProduct()->getIsBoxOfProducts()){
  2146.               $qtyWeeklySoldForProduct $em->getRepository(CartProduct::class)->findWeeklyAlreadySoldForProductJit($p->getProduct()->getId());
  2147.               if (!$qtyWeeklySoldForProduct) {
  2148.                 $qtyWeeklySoldForProduct 0;
  2149.               }
  2150.               $getQtyReadyToShip $p->getProduct()->getQtyReadyToShip();
  2151.              
  2152.               if ($getQtyReadyToShip) {
  2153.                 if($qtyWeeklySoldForProduct $p->getQuantity() > $getQtyReadyToShip ) {
  2154.                   if ($p->getQuantity() <= $qtyWeeklySoldForProduct){
  2155.                     $p->setQuantity($p->getQuantity());
  2156.                     $em->persist($p);
  2157.                     $em->flush();
  2158.                     $forceRedirect=true;
  2159.                     continue;
  2160.                   }else{
  2161.                     $this->addFlash('error'"La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire");
  2162.                     $p->setQuantity($getQtyReadyToShip);
  2163.                     $em->persist($p);
  2164.                     $em->flush();
  2165.                     $forceRedirect=true;
  2166.                     continue;
  2167.                   }
  2168.                 }
  2169.               }
  2170.             }
  2171.             if ($p->getProduct()->getIsBoxOfProducts()){
  2172.               $getAllProducts $p->getProduct()->getProductsInBox();
  2173.               foreach ($getAllProducts  as $getAllProduct) {
  2174.                 $getQuantityforBox $p->getQuantity() * $getAllProduct->getQuantity();
  2175.                 if ($getQuantityforBox $p->getProduct()->getQtyReadyToShip()){
  2176.                   $quantityBoxLeft intval(floor($p->getProduct()->getQtyReadyToShip() / $getAllProduct->getQuantity()));
  2177.                   if ($quantityBoxLeft $p->getQuantity()){
  2178.                     $this->addFlash('error'"La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire");
  2179.                     $p->setQuantity($quantityBoxLeft);
  2180.                     $em->persist($p);
  2181.                     $em->flush();
  2182.                     $forceRedirect=true;
  2183.                   }
  2184.                 }
  2185.               }
  2186.             }
  2187.           }
  2188.           if($forceRedirect)
  2189.           {
  2190.             return $this->redirectToRoute('viewCart');
  2191.           }
  2192.         }
  2193.             $em->persist($cart);
  2194.             $em->flush();
  2195.       }
  2196.         // //add by default dth reusable box 
  2197.         // $reusableBox = $request->request->get("reusableBox");
  2198.         // if($cartForm->get('submit')->isClicked()){
  2199.         //   if ($reusableBox == "addBox" && $this->getUser() && !$this->getUser()->getHasReusableBox() && !$cart->containReusableBox() && $cart->containMaturinRoute()){
  2200.         //     $productBoxReusable = $em->getRepository(Product::class)->findOneBy(['id'=> 6472]);
  2201.         //     $this->addToCart($productBoxReusable, 1, $userServ, $em);
  2202.         //   }        
  2203.         // }
  2204.         
  2205.         if($cartForm->isSubmitted() && $cartForm->isValid()){
  2206.                      
  2207.           if ($this->getUser() && $this->getUser()->getEmail() == $claudia){
  2208.           }else{
  2209.             $forceRedirect=false;
  2210.            
  2211.               foreach($cart->getProducts() as $p){
  2212.                 if (!$p->getProduct()->getIsBoxOfProducts()){
  2213.                 // getQuantityMaxProd valable pour augmenter les ventes en période de fetes, permet au producteur d'anticiper ou claudia de commander plus de volume 
  2214.               // et de vendre plusque quantité hebdomadaire
  2215.             //If the quantity we have in stock is lower than the one the customer wants
  2216.                $getQtyReadyToShip $p->getProduct()->getQtyReadyToShip();
  2217.                 if ($getQtyReadyToShip) {
  2218.                     if ($p->getProduct()->getQuantityMaxProd() > 0){
  2219.                       $getQtyComing $p->getProduct()->getQuantityMaxProd();
  2220.                     }else{
  2221.                       $getQtyComing 0;
  2222.                     }
  2223.                       $qtyMaximumToSell $getQtyReadyToShip $getQtyComing;
  2224.                   if($qtyMaximumToSell $p->getQuantity()) {
  2225.                     if($qtyMaximumToSell == 0){
  2226.                       $this->addFlash('error'"Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier");
  2227.                       $em->remove($p);
  2228.                       $em->flush();
  2229.                       $forceRedirect=true;
  2230.                       continue;
  2231.                     }else{
  2232.                       $this->addFlash('error'"La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire");
  2233.                       $p->setQuantity($getQtyReadyToShip);
  2234.                       $em->persist($p);
  2235.                       $em->flush();
  2236.                       $forceRedirect=true;
  2237.                       continue;
  2238.                     }
  2239.                 }
  2240.               }
  2241.             }
  2242.           
  2243.                 // If the jit product pass the weekly  qty to sell
  2244.                 if($p->getProduct()->getIsJustInTime() && !$p->getProduct()->getIsBoxOfProducts()){
  2245.                   $qtyWeeklySoldForProduct $em->getRepository(CartProduct::class)->findWeeklyAlreadySoldForProductJit($p->getProduct()->getId());
  2246.                   if (!$qtyWeeklySoldForProduct) {
  2247.                     $qtyWeeklySoldForProduct 0;
  2248.                   }
  2249.                   $getQtyReadyToShip $p->getProduct()->getQtyReadyToShip();
  2250.                   if ($getQtyReadyToShip) {
  2251.                     if($qtyWeeklySoldForProduct $p->getQuantity() >= $getQtyReadyToShip ) {
  2252.                       if ($p->getQuantity() <= $qtyWeeklySoldForProduct){
  2253.                         $p->setQuantity($p->getQuantity());
  2254.                         $em->persist($p);
  2255.                         $em->flush();
  2256.                        
  2257.                         continue;
  2258.                       }else{
  2259.                         $this->addFlash('error'"La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire");
  2260.                         $p->setQuantity($getQtyReadyToShip);
  2261.                         $em->persist($p);
  2262.                         $em->flush();
  2263.                         $forceRedirect=true;
  2264.                         continue;
  2265.                       }
  2266.                     }
  2267.                   }
  2268.                 }
  2269.                 if ($p->getProduct()->getIsBoxOfProducts()){
  2270.                   $getAllProducts $p->getProduct()->getProductsInBox();
  2271.                   foreach ($getAllProducts  as $getAllProduct) {
  2272.                     $getQuantityforBox $p->getQuantity() * $getAllProduct->getQuantity();
  2273.                     if ($getQuantityforBox $p->getProduct()->getQtyReadyToShip()){
  2274.                       $quantityBoxLeft intval(floor($p->getProduct()->getQtyReadyToShip() / $getAllProduct->getQuantity()));
  2275.                       if ($quantityBoxLeft $p->getQuantity()){
  2276.                         $this->addFlash('error'"La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire");
  2277.                         $p->setQuantity($quantityBoxLeft);
  2278.                         $em->persist($p);
  2279.                         $em->flush();
  2280.                         $forceRedirect=true;
  2281.                       }
  2282.                     }
  2283.                   }
  2284.                 }
  2285.               }
  2286.               if($forceRedirect)
  2287.               {
  2288.                 return $this->redirectToRoute('viewCart');
  2289.               }
  2290.           //bloque si commande de produit Naya (bouteille d'eau) + que 10
  2291.           foreach($cart->getProducts() as $p){
  2292.           if($p->getQuantity() >= 10 && $p->getProduct()->getCompany()->getId() == 525 && $p->getProduct()->isShippedByMaturin() == true){
  2293.             $this->addFlash('error''Désolé vous ne pouvez pas commander plus de 10 produits de la compagnie Naya');
  2294.             return $this->redirectToRoute('viewCart');
  2295.           }
  2296.           // $requestDate = $request->request->get("livraisonDate");
  2297.           // $livDate = new \DateTime($requestDate);
  2298.           //   $cart->setDeliveryChoiceDate($livDate);
  2299.         }
  2300.             $em->persist($cart);
  2301.             $em->flush();
  2302.           
  2303.           }
  2304.             try {
  2305.                 //Erase all cart products with 0 quantity
  2306.                 foreach($cart->getProducts() as $p){
  2307.                     if($p->getQuantity() <= 0){
  2308.                         $cart->removeProduct($p);
  2309.                         $em->remove($p);
  2310.                     }
  2311.                 }
  2312.                 //If Shipping was selected mean the user is going back and forth
  2313.                 //so let's force a recalculate
  2314.                 if($cart->getShippingAddress()){
  2315.                     $cart->calculateFees();
  2316.                 }
  2317.                 // save cart changes
  2318.                 $em->persist($cart);
  2319.                 $em->flush();
  2320.                 if(!$cartForm->get('update')->isClicked()){
  2321.                     if($userServ->getUser()){
  2322.                         if($cartForm->has('recurring')){
  2323.                             $recurring $cartForm->get('recurring')->getData();
  2324.                             //User asked to add this to this recurring order
  2325.                             if($recurring){
  2326.                                 $rCart $recurring->getCart();
  2327.                                 foreach($cart->getProducts() as $p){
  2328.                                     $p->setIsRecurringOneTimeOnly(true);
  2329.                                     $cart->removeProduct($p);
  2330.                                     $rCart->addProduct($p);
  2331.                                     $em->persist($p);
  2332.                                 }
  2333.                                 $em->persist($cart);
  2334.                                 $em->persist($rCart);
  2335.                                 $em->flush();
  2336.                                 $this->addFlash('success''Vos produits on été ajouté à cette commande récurrente.');
  2337.                                 return $this->redirectToRoute('recurringOrderEntry', array('id' => $recurring->getId()));
  2338.                             }
  2339.                         }
  2340.                         return $this->redirectToRoute('checkout', array('id' => $cart->getId()));
  2341.                     }else
  2342.                         return $this->redirectToRoute('fos_user_security_login');
  2343.                 }else{
  2344.                     $this->addFlash('success''Votre panier a été modifié avec succès.');
  2345.                     return $this->redirectToRoute('viewCart');
  2346.                 }
  2347.             }
  2348.             catch (\Exception $e ){
  2349.                 /*
  2350.                 var_dump($e->getMessage());
  2351.                 die();
  2352.                  // */
  2353.                 $this->addFlash('error''Une erreur est survenu, veuillez contacter notre support.');
  2354.             }
  2355.          
  2356.         }
  2357.         $twigData['form'] = $cartForm->createView();
  2358.         $twigData['cart']=$cart;
  2359.         $twigData['hideSideMenu'] = true;
  2360.         if ($this->getUser() && $this->getUser()->getEmail() == $claudia){
  2361.         }else{
  2362.       
  2363.           
  2364.         //Check if all Maturin product has quantity
  2365.         $forceRedirect=false;
  2366.         foreach($cart->getProducts() as $p){
  2367.             //If the product was put unavailable since
  2368.             if(!$p->getProduct()->getAvailable() || !$p->getProduct()->isSalable()){
  2369.                 $this->addFlash('error'"Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier");
  2370.                 $em->remove($p);
  2371.                 $em->flush();
  2372.                 $forceRedirect=true;
  2373.                 continue;
  2374.             }
  2375.             if($p->isShippedByMaturin()){
  2376.                 //Check if they are all valid Solex product
  2377.                 // if(empty($p->getProduct()->getSolexId()) && !$p->getProduct()->getHasMultipleProducts()){
  2378.                 //     $this->addFlash('error', "Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier");
  2379.                 //     $em->remove($p);
  2380.                 //     $em->flush();
  2381.                 //     $forceRedirect=true;
  2382.                 //     continue;
  2383.                 // }
  2384.                 // //If the quantity we have in stock is lower than the one the customer wants
  2385.                 // $getQtyReadyToShip = $p->getProduct()->getQtyReadyToShip();
  2386.                 // if ($getQtyReadyToShip) {
  2387.                 //   if($getQtyReadyToShip < $p->getQuantity()) {
  2388.                 //     if($getQtyReadyToShip == 0){
  2389.                 //       $this->addFlash('error', "Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier");
  2390.                 //       $em->remove($p);
  2391.                 //       $em->flush();
  2392.                 //       $forceRedirect=true;
  2393.                 //       continue;
  2394.                 //     }else{
  2395.                 //       $this->addFlash('error', "La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire");
  2396.                 //       $p->setQuantity($getQtyReadyToShip);
  2397.                 //       $em->persist($p);
  2398.                 //       $em->flush();
  2399.                 //       $forceRedirect=true;
  2400.                 //       continue;
  2401.                 //     }
  2402.                 //   }
  2403.                 // }
  2404.                 // // If the jit product pass the weekly  qty to sell
  2405.                 // if($p->getProduct()->getIsJustInTime()){
  2406.                 //   $qtyWeeklySoldForProduct = $em->getRepository(CartProduct::class)->findWeeklyAlreadySoldForProductJit($p->getProduct()->getId());
  2407.                 //   if (!$qtyWeeklySoldForProduct) {
  2408.                 //     $qtyWeeklySoldForProduct = 0;
  2409.                 //   }
  2410.                 //   $getQtyReadyToShip = $p->getProduct()->getQtyReadyToShip();
  2411.                 //   if ($getQtyReadyToShip) {
  2412.                 //     if($qtyWeeklySoldForProduct + $p->getQuantity() > $getQtyReadyToShip ) {
  2413.                 //       $this->addFlash('error', "Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier");
  2414.                 //       $em->remove($p);
  2415.                 //       $em->flush();
  2416.                 //       $forceRedirect=true;
  2417.                 //       continue;
  2418.                 //     }
  2419.                 //   }
  2420.                 // }
  2421.             }else{
  2422.                 if(empty($p->getValidDeliveryMethods())){
  2423.                     $this->addFlash('error'"Le produit ".$p->getProduct()->getName()." n'a aucune livraison disponible");
  2424.                     $twigData['noGo']= true;
  2425.                 }
  2426.             }
  2427.         }
  2428.         if($forceRedirect)
  2429.             return $this->redirectToRoute('viewCart');
  2430.       }
  2431.         //Let's check if the cart is legit
  2432.         if($cart->getTotalProductsMaturinDeliveryOnly() < 25 && $cart->getHasMaturinDeliveryProducts()) {
  2433.           $this->addFlash('warning'"Le montant minimal d'achat est de 25$");
  2434.           $twigData['noGo']=true;
  2435.         }
  2436.         
  2437.         return $twigData;
  2438.     }
  2439.     /**
  2440.      * @Route(
  2441.      *      "/API/cart/add/{id}/{quantity}/{subscribeType}",
  2442.      *      name="addToCart",
  2443.      *      options = { "expose" = true },
  2444.      *      defaults = {
  2445.      *          "quantity" = 1,
  2446.      *          "subscribeType" = false
  2447.      *      }
  2448.      *  )
  2449.      */
  2450.     public function addToCart(Product $product$quantityUserService $userServEntityManagerInterface $em$subscribeType=false)
  2451.     {
  2452.         $response = new JsonResponse();
  2453.         $cart $userServ->getCart();
  2454.         //$cart->setUser($userServ->getUser());
  2455.         $cartItem false;
  2456.         foreach($cart->getProducts() as $key => $p ){
  2457.             if($p->getProduct()->getId() == $product->getId()){
  2458.                 $cartItem $cart->getProducts()->get($key);
  2459.                 break;
  2460.             }
  2461.         }
  2462.         if($cartItem){
  2463.             $qty = ($cartItem->getQuantity()) + 1;
  2464.             $cartItem->setQuantity($qty);
  2465.             $cart->getProducts()->set($key$cartItem);
  2466.         }else{
  2467.             $cartItem = new CartProduct();
  2468.             $cartItem->setProduct($product);
  2469.             $cartItem->setQuantity($quantity);
  2470.             $cart->addProduct($cartItem);
  2471.         }
  2472.         if($subscribeType){
  2473.             $cartItem->setRecurringFrequency($subscribeType);
  2474.         }
  2475.         //If browsing a association
  2476.         //And this project is in a association
  2477.         $testAssociation $userServ->getAssociationUserIsBrowsing();
  2478.         if($testAssociation && $product->getCompany()->getAssociations()->contains($testAssociation)){
  2479.             $cartItem->setAddedWhenBeingInAssociation($testAssociation);
  2480.             if($testAssociation->getVariableValueByCodeName('orders.canPickUp')){
  2481.                 $dm = new DeliveryMethod();
  2482.                 $dm->setAverageDays(1);
  2483.                 $dm->setIsAPickup(true);
  2484.                 $dm->setServiceId(9999);
  2485.                 $dm->setFixedPrice(0);
  2486.                 $dm->setValid(true);
  2487.                 $testSchedule $testAssociation->getVariableValueByCodeName('orders.pickUpSchedule');
  2488.                 if($testSchedule)
  2489.                     $dm->setPickupSchedule($testSchedule);
  2490.                 $testAddress$testAssociation->getVariableValueByCodeName('orders.pickUpAdress');
  2491.                 if($testAddress)
  2492.                     $dm->setPickupAddress($testAddress);
  2493.                 $cartItem->setCompanyDeliveryMethod($dm);
  2494.                 $em->persist($dm);
  2495.             }
  2496.         }
  2497.         $em->persist($cartItem);
  2498.         $em->persist($cart);
  2499.         $em->flush();
  2500.         $response->setData(array(
  2501.             'success' => true,
  2502.             'totalCart' => number_format($cart->getSubTotalToPay(falsefalse),2).'$'
  2503.         ));
  2504.         return $response;
  2505.     }
  2506.     /**
  2507.      * @Route({
  2508.      *      "fr": "/livraison/ville/ajax_search/{province}",
  2509.      *      "en": "/delivery/city/ajax_search"
  2510.      *      },
  2511.      *      name="cityAdressAJAXSearch"
  2512.      * )
  2513.      *
  2514.      */
  2515.     public function cityAdressAJAXSearch(UserService $userServRequest $requestEntityManagerInterface $em,$province) {
  2516.       $search_query $request->get("term");
  2517.       if (empty($search_query)) {
  2518.         die(json_encode(["results"=>[]]));
  2519.       }
  2520.       $stringCut explode('-'$search_query);
  2521.       if (count($stringCut) > 1){
  2522.         $search_query "%".str_replace(" ""%"trim($stringCut[1]))."%";
  2523.        }else{
  2524.         $search_query "%".str_replace(" ""%"trim($search_query))."%";
  2525.        }
  2526.     
  2527.       $search_results $em->getRepository(City::class)->searchByName($search_query);
  2528.       // $search_results = $em->getRepository(City::class)->searchByNameAndProvince($search_query,$province);
  2529.       $results = [];
  2530.       foreach($search_results as $result) {
  2531.         $results[] = ["id"=>$result->getId(), "text"=>$result->getName()];
  2532.       }
  2533.       die(json_encode(["results"=>$results]));
  2534.     }
  2535.     public function CouponTuango($coupon) {
  2536.       $user $this->getUser();
  2537.       $couponTuango false;
  2538.       $fileTuango $this->getParameter('GiftCouponTuango');
  2539.       $file fopen($fileTuango"rw");
  2540.       while (!feof($file) ) {
  2541.         $lines[] = fgetcsv($file1500" ");
  2542.       }
  2543.      
  2544.       foreach ($lines as $line => $val) {
  2545.         // dump($val);
  2546.         $searchValue in_array($coupon$val);
  2547.           if($searchValue == true){
  2548.             $couponTuango true;
  2549.           }
  2550.         }
  2551.       
  2552.       fclose($file);
  2553.       $em $this->getDoctrine()->getManager();
  2554.       $cartCoupon $em->getRepository(CartCoupon::class)->findBy(["code" => $coupon]);
  2555.       
  2556.      
  2557.         // dump($cartCoupon);
  2558.       if ($couponTuango == true && empty($cartCoupon)){
  2559.         // dump('entrer');
  2560.       $AddCoupon = new CartCoupon();
  2561.       $AddCoupon->setOneTimeOnly(1);
  2562.       $AddCoupon->setType(2);
  2563.       $AddCoupon->setAmount(80);
  2564.       $AddCoupon->setCode($coupon);
  2565.       $AddCoupon->setDateFrom(new \DateTime());
  2566.       $AddCoupon->setDateTo(new \DateTime("+1 month"));
  2567.       $AddCoupon->setForUser($this->getUser());
  2568.       $em->persist($AddCoupon);
  2569.       $em->flush();
  2570.       return true;
  2571.       
  2572.     }else{
  2573.       return false;
  2574.     }
  2575.       
  2576.       
  2577.     }
  2578.     public function CouponCabaneMaturin($coupon) {
  2579.       $user $this->getUser();
  2580.       $cart $user->getCart();
  2581.       // $cart->getProducts();
  2582.       $couponOption1 false;
  2583.       $couponOption2 false;
  2584.       $couponOption3 false;
  2585.       $option1 $this->getParameter('GiftCabaneOption1');
  2586.       $option2 $this->getParameter('GiftCabaneOption2');
  2587.       $option3 $this->getParameter('GiftCabaneOption3');
  2588.       $fileOption1 fopen($option1"rw");
  2589.       $fileOption2 fopen($option2"rw");
  2590.       $fileOption3 fopen($option3"rw");
  2591.       //send all of them in array
  2592.       while (!feof($fileOption1) ) {
  2593.         $linesOption1[] = fgetcsv($fileOption1150" ");
  2594.       }
  2595.       while (!feof($fileOption2) ) {
  2596.         $linesOption2[] = fgetcsv($fileOption2150" ");
  2597.       }
  2598.       while (!feof($fileOption3) ) {
  2599.         $linesOption3[] = fgetcsv($fileOption3150" ");
  2600.       }
  2601.      // check in array option1
  2602.       foreach ($linesOption1 as $lineOption1 => $val) {
  2603.         $searchValue in_array($coupon$val);
  2604.           if($searchValue == true){
  2605.             $couponOption1 true;
  2606.           }
  2607.       }
  2608.       // check in array option2
  2609.       foreach ($linesOption2 as $lineOption2 => $val) {
  2610.         // dump($val);
  2611.         $searchValue in_array($coupon$val);
  2612.           if($searchValue == true){
  2613.             $couponOption2 true;
  2614.           }
  2615.       }
  2616.       // check in array option3
  2617.       foreach ($linesOption3 as $lineOption3 => $val) {
  2618.         // dump($val);
  2619.         $searchValue in_array($coupon$val);
  2620.           if($searchValue == true){
  2621.             $couponOption3 true;
  2622.           }
  2623.       }
  2624.       // close files 
  2625.       fclose($fileOption1);
  2626.       fclose($fileOption2);
  2627.       fclose($fileOption3);
  2628.       //search if coupon already exist 
  2629.       $em $this->getDoctrine()->getManager();
  2630.       $cartCoupon $em->getRepository(CartCoupon::class)->findBy(["code" => $coupon]);
  2631.       //if not exist add it in BD 
  2632.       $applyOption=0;
  2633.       // check if product cabane a sucres is in cart
  2634.       foreach ($cart->getProducts() as $ProductIncart){
  2635.         if ($ProductIncart->getProduct()->getId() == 9287){
  2636.           $applyOption $ProductIncart->getProduct()->getId();
  2637.         }elseif ($ProductIncart->getProduct()->getId() == 9288) {
  2638.           $applyOption $ProductIncart->getProduct()->getId();
  2639.         }elseif ($ProductIncart->getProduct()->getId() == 9289) {
  2640.           $applyOption $ProductIncart->getProduct()->getId();
  2641.         }
  2642.       }
  2643.  
  2644.     if (empty($cartCoupon)){
  2645.         //first otpion 75$ == cabane 2-4pers (100$) free
  2646.         if ($couponOption1 == true && $applyOption == 9287){
  2647.           
  2648.         $AddCoupon = new CartCoupon();
  2649.         $AddCoupon->setOneTimeOnly(1);
  2650.         $AddCoupon->setType(2);
  2651.         $AddCoupon->setAmount(100);
  2652.         $AddCoupon->setCode($coupon);
  2653.         $AddCoupon->setDateFrom(new \DateTime());
  2654.         $AddCoupon->setDateTo(new \DateTime("+1 month"));
  2655.         $AddCoupon->setForUser($this->getUser());
  2656.         $em->persist($AddCoupon);
  2657.         $em->flush();
  2658.        
  2659.         return true;
  2660.         
  2661.         //first otpion 110$ == cabane 4-6pers (155$) free
  2662.       }elseif ($couponOption2 == true && $applyOption == 9288){
  2663.     
  2664.         $AddCoupon = new CartCoupon();
  2665.         $AddCoupon->setOneTimeOnly(1);
  2666.         $AddCoupon->setType(2);
  2667.         $AddCoupon->setAmount(155);
  2668.         $AddCoupon->setCode($coupon);
  2669.         $AddCoupon->setDateFrom(new \DateTime());
  2670.         $AddCoupon->setDateTo(new \DateTime("+1 month"));
  2671.         $AddCoupon->setForUser($this->getUser());
  2672.         $em->persist($AddCoupon);
  2673.         $em->flush();
  2674.         return true;
  2675.         //first otpion 110$ == cabane 4-6pers (225$) free
  2676.       }elseif ($couponOption3 == true && $applyOption == 9289){
  2677.           
  2678.         $AddCoupon = new CartCoupon();
  2679.         $AddCoupon->setOneTimeOnly(1);
  2680.         $AddCoupon->setType(2);
  2681.         $AddCoupon->setAmount(225);
  2682.         $AddCoupon->setCode($coupon);
  2683.         $AddCoupon->setDateFrom(new \DateTime());
  2684.         $AddCoupon->setDateTo(new \DateTime("+1 month"));
  2685.         $AddCoupon->setForUser($this->getUser());
  2686.         $em->persist($AddCoupon);
  2687.         $em->flush();
  2688.         return true;
  2689.         
  2690.       }else {
  2691.         return false;
  2692.       }
  2693.   }
  2694.   return false;
  2695.     }
  2696.  /**
  2697.      * @Route({
  2698.      *          "fr": "/subscriptionVersproduit/{id}",
  2699.      *          "en": "/subscriptionToProduct/{id}",
  2700.      *      },
  2701.      *      name="subscriptionToProduct")
  2702.      *
  2703.      */
  2704.     public function addSubscriptionslikeproduct(Request $requestUserService $userServ$id){
  2705.     $em $this->getDoctrine()->getManager();
  2706.     $productId $request->request->get('productId');
  2707.     $subscriptionId $request->request->get('subscriptionId');;
  2708.   
  2709.     $subscriptions $em->getRepository(Subscription::class)->findBy(["id"=>$subscriptionId]);
  2710.     $cart $userServ->getCart();
  2711.     foreach ($subscriptions as $subscription) {
  2712.       $quantity $subscription->getQuantity();
  2713.       $getSubscritpionProducts $em->getRepository(Product::class)->findBy(["id"=>$productId]);
  2714.       foreach ($getSubscritpionProducts as $getSubscritpionProduct) {
  2715.         $this->addToCart($getSubscritpionProduct$quantity$userServ$em);
  2716.       }
  2717.   //Let's see if we join it with a subscription
  2718.   if ($subscription) {
  2719.     $cart->setSendWithSubscription($subscription);
  2720.     $found false;
  2721.     foreach($cart->getProducts() as $cp){
  2722.     if($cp->getProduct() == $getSubscritpionProduct){
  2723.       $found true;
  2724.             $cp->setOverwriteSubscription(true);
  2725.            }
  2726.       }
  2727.              if(!$found){
  2728.                //Check if product in the cart
  2729.                $cp = new CartProduct();
  2730.                $cp->setQuantity($quantity);
  2731.                $cp->setProduct($getSubscritpionProduct);
  2732.                $cp->setOverwriteSubscription(true);
  2733.                $cart->addProduct($cp);
  2734.                $em->persist($cart);
  2735.                $em->persist($cp);
  2736.               $em->flush();
  2737.             }
  2738.    }
  2739.     }
  2740.     $this->addFlash('success''Ce produit a été ajouté a votre panier');
  2741.     return $this->redirectToRoute('viewCart'); 
  2742.    }
  2743.  /**
  2744.      * @Route({
  2745.      *          "fr": "/SauvegardeNouvelleAddresse/",
  2746.      *          "en": "/SaveNewAdress/",
  2747.      *      },
  2748.      *      name="SaveNewAdress")
  2749.      *
  2750.      */
  2751.     public function SaveNewAdress(Request $requestUserService $userServ){
  2752.     $em $this->getDoctrine()->getManager();
  2753.     $cart $userServ->getCart();
  2754.     if ($request->request->get('adresse_autocomplete')){
  2755.       $newadresseAutocomplete $request->request->get('adresse_autocomplete');
  2756.     }else{
  2757.       $newadresseAutocomplete $request->request->get('adresse_manuel');
  2758.     }
  2759.   
  2760.     $pattern '/\d+/';
  2761.     preg_match($pattern$newadresseAutocomplete$civicnumber);
  2762.     
  2763.     $pattern strlen($civicnumber[0]);
  2764.     $streetname substr($newadresseAutocomplete$pattern);
  2765.     $arrayAutocomplete explode(', 'trim($streetname));
  2766.     
  2767.         $newAddress_civicnumber $civicnumber[0];
  2768.         $newAddress_streetname $arrayAutocomplete[0];
  2769.         $newAddress_phone $request->request->get('adresse_phone');
  2770.         $newAddress_province $request->request->get('adresse_province');
  2771.         $newAddress_zipcode =  $request->request->get('adresse_zipcode');
  2772.         $adresse_unit $request->request->get('adresse_unit');
  2773.         $newAddress_city $request->request->get('adresse_city');
  2774.         $newAdresse_name =  $request->request->get('adresse_name');
  2775.         $findTheCity $em->getRepository(City::class)->findBy(["name"=>$newAddress_city]);
  2776.       
  2777.         if ($findTheCity == null){
  2778.           $findTheCity = new City();
  2779.           $findTheCity->setName(trim($newAddress_city));
  2780.           $findTheCity->setMrc(trim($newAddress_city));
  2781.           $findTheCity->setProvince(trim($newAddress_province));
  2782.           $findTheRegion $em->getRepository(Region::class)->findBy(["name"=>'defaut']);
  2783.           $findTheCity->setRegion($findTheRegion[0]);
  2784.           $em->persist($findTheCity);
  2785.           $em->flush();
  2786.           $charlie $em->getRepository(User::class)->findOneBy(["email" => "charlie@maturin.ca"])->getEmail();
  2787.           $userServ->sendEmail('Une nouvelle ville a été ajouté''<p>La ville ,' $newAddress_city ' a été ajouté dans la base de données</p>'false$charlie);
  2788.         }
  2789.         $user $userServ->getUser();
  2790.         $UserShippingLocation = new UserShippingLocation();
  2791.       
  2792.         $UserShippingLocation->setName($newAdresse_name);
  2793.           // ajout de condition format et correspond au type de data attendu 
  2794.         $UserShippingLocation->setPhone($newAddress_phone);
  2795.         $UserShippingLocation->setCivicNumber($newAddress_civicnumber);
  2796.         $UserShippingLocation->setStreetName($newAddress_streetname);
  2797.         $UserShippingLocation->setUnit($adresse_unit);
  2798.         $UserShippingLocation->setCity($newAddress_city);
  2799.         $UserShippingLocation->setZipCode($newAddress_zipcode);
  2800.         $UserShippingLocation->setProvince($newAddress_province);
  2801.         $UserShippingLocation->setUser($user);
  2802.         $UserShippingLocation->setEmail($this->getUser()->getEmail());
  2803.         
  2804.         $em->persist($UserShippingLocation);
  2805.         $cart->setShippingAddress($UserShippingLocation);
  2806.         $em->persist($cart);
  2807.         $em->flush();
  2808.     $this->addFlash('success''Votre adresse a été ajouté avec succes');
  2809.     return $this->redirectToRoute('checkout'); 
  2810.    }
  2811.    /**
  2812.      * @Route({
  2813.      *          "fr": "/PaymentChoice/maturinRecolte",
  2814.      *          "en": "/PaymentChoice/maturinRecolte",
  2815.      *      },
  2816.      *      name="PaymentChoice")
  2817.      *
  2818.      * @Security("has_role('ROLE_ADMIN')")
  2819.      * @Template("/frontend/newPayment.html.twig")
  2820.      */
  2821.     public function PaymentChoice(Request $requestUserService $userServPaymentService $paymentServDistributorService $distributorServ,  TwigGlobalVariables $twigGlobalVariablesService){
  2822.       $em $this->getDoctrine()->getManager();
  2823.       $user $userServ->getuser();
  2824.       $cart $user->getCart();
  2825.       $twigData =[];
  2826.       $twigData['cards']= null;
  2827.       if(!$request->request->has('stripeToken') && !$request->request->has('use-previous-card')){
  2828.         // if(!$cart->hasMaturinShipping()){
  2829.           if($cart->hasMaturinShipping()){
  2830.           $twigData['shippingMaturin'] = $distributorServ->getEstimateShipping($cart);
  2831.         }
  2832.         //Update the Shipping cost
  2833.         if(!empty($twigData['shippingMaturin'])){
  2834.           $maturinShipping current($twigData['shippingMaturin']);
  2835.         } else {
  2836.           $maturinShipping false;
  2837.         }
  2838.        
  2839.         $found false;
  2840.         if($maturinShipping){
  2841.             foreach($twigData['shippingMaturin'] as $s){
  2842.                 if($s->serviceName == $request->request->get('shippingService') && $s->carrierName == $request->request->get('shippingCarrier')){
  2843.                     $found true;
  2844.                     $cart->setShippingMaturinCost($s->estimatedCost);
  2845.                     $cart->setShippingMaturinCarrierName($s->carrierName);
  2846.                     $cart->setShippingMaturinServiceName($s->serviceName);
  2847.                     $cart->setShippingMaturinServiceId($s->serviceId);
  2848.                     $estimatedCartDate $twigGlobalVariablesService->getEstimationShippingForMaturinProducts($cart);
  2849.                    //$cart->setShippingMaturinEstimatedDate(new \DateTime($s->estimatedDate));
  2850.                     $cart->setShippingMaturinEstimatedDate($estimatedCartDate);
  2851.                     $twigData['currentShipping'] = $s;
  2852.                     break;
  2853.                 }
  2854.               }
  2855.               if(!($request->request->has('maturinShipping') && $found)){
  2856.                   $cart->setShippingMaturinCost($maturinShipping->estimatedCost);
  2857.                   $cart->setShippingMaturinCarrierName($maturinShipping->carrierName);
  2858.                   $cart->setShippingMaturinServiceName($maturinShipping->serviceName);
  2859.                   $cart->setShippingMaturinServiceId($maturinShipping->serviceId);
  2860.                   //// old estimate not working anymore for delivery date we change it to new estimation route
  2861.                   $estimatedCartDate $twigGlobalVariablesService->getEstimationShippingRouteForMaturinProducts($cart);
  2862.                   $maturinShipping->estimatedDate $estimatedCartDate["date"];
  2863.                   $cart->setShippingMaturinEstimatedDate($maturinShipping->estimatedDate);
  2864.                 
  2865.                   //$cart->setShippingMaturinEstimatedDate(new \DateTime($maturinShipping->estimatedDate));
  2866.                   $twigData['currentShipping'] = $maturinShipping;
  2867.               }
  2868.               $em->persist($cart);
  2869.               $em->flush();
  2870.             }else{
  2871.                 if($cart->hasMaturinShipping()){
  2872.                     //Should be an error with the shipping
  2873.                     //In theory the flash should show the error to user
  2874.                     //so we redirect to shipping address
  2875.                     $twigData['noGo'] = true;
  2876.                     return $this->redirectToRoute('checkout');
  2877.                 }
  2878.             }
  2879.         }
  2880.         $shippingAddress $cart->getShippingAddress();
  2881.         //We need a shipping address for the taxes
  2882.         if($shippingAddress) {
  2883.             $cart->calculateFees();
  2884.             $em->persist($cart);
  2885.             $em->flush();
  2886.         }
  2887.         $PuroTest null;
  2888.         if ($shippingAddress){
  2889.           $getMethodLivraisons $em->getRepository(DeliveryRoute::class)->findBy(['name' => $cart->getShippingAddress()->getArrayOfDeliveryRoutes()]);
  2890.           foreach ($getMethodLivraisons as $getMethodLivraison) {
  2891.             if ($getMethodLivraison->getType() == 'maturin')
  2892.             $PuroTest 'maturin';
  2893.           }
  2894.         }
  2895.         $twigData['puroConfirm'] = $PuroTest;
  2896.       
  2897.       $twigData['hideSideMenu'] = true;
  2898.       if ($user->getStripeAccountId()){
  2899.         $acct = \Stripe\Customer::retrieve($user->getStripeAccountId());
  2900.         for ($i=0$i count($acct->sources->data) ; $i++) { 
  2901.           if ($acct->default_source == $acct->sources->data[$i]->id){
  2902.             $default_source true;
  2903.           }else{
  2904.             $default_source false;
  2905.           }
  2906.           $twigData['cards'][] = array (
  2907.                   'card_id' => $acct->sources->data[$i]->id,
  2908.                   'default_source' => $default_source,
  2909.                   'last4' => $acct->sources->data[$i]->last4,
  2910.                   'exp_month' => $acct->sources->data[$i]->exp_month,
  2911.                   'exp_year' => $acct->sources->data[$i]->exp_year);
  2912.         }
  2913.       }
  2914.       
  2915.       if ($this->getUser() && $this->getUser()->getIsBetaTester()){
  2916.         if($request->isMethod('post') && empty($request->request->get('validePayment'))){
  2917.           //  dump('ok12');
  2918.           // dd($request);
  2919.             if(!empty($request->request->get('stripeToken'))){
  2920.               $cart->setStripeToken($request->request->get('stripeToken'));
  2921.             }
  2922.             //First time paying, let's create him a account
  2923.             if(empty($user->getStripeAccountId())){
  2924.               if (empty($cart->getStripeToken()))
  2925.                   throw new \Exception("The Token was not generated correctly");
  2926.               $customer = \Stripe\Customer::create([
  2927.                   'source' => $cart->getStripeToken(),
  2928.                   'email' => $user->getEmail(),
  2929.               ]);
  2930.               $user->setPaymentLast4digits(current($customer->sources->data)->last4);
  2931.               $user->setStripeAccountId($customer->id);
  2932.               $em->persist($user);
  2933.             }elseif(!empty($cart->getStripeToken()) || !empty($request->request->get('stripeToken'))){
  2934.           
  2935.               $acct->sources->create(array("source" => $request->request->get('stripeToken')));
  2936.              
  2937.               $user->setPaymentLast4digits(current($customer->sources->data)->last4);
  2938.             }
  2939.             $em->persist($user);
  2940.           $em->flush();
  2941.           
  2942.           return $this->redirectToRoute('PaymentChoice');
  2943.         }elseif($request->isMethod('post') && $request->request->get('validePayment') == "Soumettre") {
  2944.           $default_source null;
  2945.           $default_source $request->request->get('default_source');
  2946.           //It appear we need to update it
  2947.           if($default_source != null){
  2948.             // Set the new card as the customers default card
  2949.             $acct->default_source $twigData['cards'][$default_source]['card_id'];
  2950.             $acct->save();
  2951.           }else{
  2952.             $this->addFlash('error''Il faut enregistrer une carte');
  2953.             return $this->redirectToRoute('PaymentChoice');
  2954.           }
  2955.           //Lets start with the coupon see if it's valid
  2956.         $coupon $request->get("coupon");
  2957.         if(!empty($coupon) ){
  2958.           $cartCoupon $em->getRepository(CartCoupon::class)->findOneValidByCode($coupon);
  2959.           $couponSearchTuango false;
  2960.           $couponSearchTuango =  $this->CouponTuango($coupon);
  2961.           $couponCabane false;
  2962.           $couponCabane =  $this->CouponCabaneMaturin($coupon);
  2963.           if ($couponSearchTuango != false || $couponCabane != false){
  2964.             $cartCoupon $em->getRepository(CartCoupon::class)->findOneValidByCode($coupon);
  2965.           }
  2966.             if(empty($cartCoupon)){
  2967.               if ($couponSearchTuango == false && $couponCabane == false){
  2968.                 $this->addFlash('error'"Merci de vérifier votre code coupon ou associez-le au bon produit");
  2969.                 return $this->redirectToRoute('checkout');
  2970.               }
  2971.             }else{
  2972.                 //If coupon is a onetimeonly and was already used
  2973.                 if($cartCoupon->getOneTimeOnly()){
  2974.                     if($cartCoupon->getUsedByUsers()->contains($userServ->getUser())){
  2975.                         $this->addFlash('error'"Vous avez déja utilisé ce coupon");
  2976.                         return $this->redirectToRoute('checkout');
  2977.                     }
  2978.                 }
  2979.                 //Check if any money left
  2980.                 if($cartCoupon->getIsGiftCertificate() && $cartCoupon->getAmount() <= ){
  2981.                     $this->addFlash('error'"Ce coupon a un solde restant de 0$");
  2982.                     return $this->redirectToRoute('checkout');
  2983.                 }
  2984.                 $cart->setUsedCoupon($cartCoupon);
  2985.                 //$user = $userServ->getUser();
  2986.                 //$user->addCouponUsed($cartCoupon);
  2987.                 //$em->persist($user);
  2988.             }
  2989.         }else{
  2990.           //$user->removeCouponUsed($cartCoupon);
  2991.           $cart->setUsedCoupon(null);
  2992.         }
  2993.         $em->persist($cart);
  2994.         $em->flush();
  2995.           return $this->redirectToRoute('RecapPayment');
  2996.         }
  2997.       }else{
  2998.         return $this->redirectToRoute('viewCart');
  2999.     }
  3000.     // We set the coupon if users has a valid one
  3001.         
  3002.     $couponMarketing$this->session->get('coupon_marketing');
  3003.     $twigData['couponMarketing']=false;
  3004.     if($couponMarketing){
  3005.       $cartCoupon $em->getRepository(CartCoupon::class)->findOneValidByCode($couponMarketing);
  3006.       if(!empty($cartCoupon)){
  3007.         $twigData['couponMaketing']=$cartCoupon;
  3008.       }
  3009.     }
  3010.     $userCouponList=[];
  3011.     $tempCouponLists$em->getRepository(CartCoupon::class)->findAllUserCoupons($userServ->getUser()->getId());
  3012.     // we only get not used coupon by the user
  3013.     foreach ($tempCouponLists as $cartCoupon ) {
  3014.       if($cartCoupon->getOneTimeOnly()){
  3015.         if($cartCoupon->getUsedByUsers()->contains($userServ->getUser()))
  3016.             continue;
  3017.         else
  3018.           array_push($userCouponList,$cartCoupon);
  3019.       }else
  3020.         array_push($userCouponList,$cartCoupon);
  3021.     }
  3022.     $twigData['couponLists'] = $userCouponList;
  3023.       return $twigData;
  3024.   }
  3025.  /**
  3026.      * @Route({
  3027.      *          "fr": "/nouveauPanier/maturinRecolte",
  3028.      *          "en": "/NewCart/maturinRecolte"
  3029.      *      }, name="NewViewCart")
  3030.      * @Template("frontend/RecolteCart.html.twig")
  3031.      */
  3032.     public function NewViewCart(UserService $userServRequest $requestTwigGlobalVariables $twigGlobalVariablesService){
  3033.       $twigData = array();
  3034.       $em $this->getDoctrine()->getManager();
  3035.       $twigData['loader'] = true;
  3036.       $twigData['suggestedProducts']= $userServ->findProductsToSuggest();
  3037.       if ($this->getUser() && $this->getUser()->getIsBetaTester()){
  3038.       $user$userServ->getuser();
  3039.       $userPaidOrders=false;
  3040.       if($user){
  3041.         $userPaidOrders $user->getAllCartsProducts();
  3042.       }
  3043.         $cart $userServ->getCart();
  3044.         $cart->setUsedCoupon(null);
  3045.         $cart->setDeliveryChoiceDate(null);
  3046.         $cart->setPreOrder(false);
  3047.         $cart->setNoteFromBuyer(null);
  3048.         $cart->setPreOrderNow(false);
  3049.         $cart->setDateCreated(new \DateTime(), new \DateTimeZone('America/New_York'));
  3050.         $cart->setDatePayment(new \DateTime(), new \DateTimeZone('America/New_York'));
  3051.        
  3052.         $forceRedirect=false;
  3053.         $route=[];
  3054.             foreach($cart->getProducts() as $p){
  3055.                 if (!empty($route)){
  3056.                   if ($twigGlobalVariablesService->getEstimationShippingRoute($p->getProduct())['date']->format('Y-m-d') != $route['estimationDelivery']->format('Y-m-d') ){
  3057.                       $route[] = array(
  3058.                         'estimationDelivery' => $twigGlobalVariablesService->getEstimationShippingRoute($p->getProduct())['date']->format('Y-m-d')
  3059.                     );
  3060.                   }
  3061.                 }else{
  3062.                   $route = array(
  3063.                     'estimationDelivery' => $twigGlobalVariablesService->getEstimationShippingRoute($p->getProduct())['date']
  3064.                );
  3065.                } 
  3066.             }
  3067.             sort($route);
  3068.             $twigData['estimationDeliveryDate'] = $route;    
  3069.             
  3070.         //To avoid a lot of bug occuring when the user go back and forth from Payment to card we reset the cart
  3071.         $cart->resetCalculations();
  3072.       $twigData['userPaidOrders']= $userPaidOrders;
  3073.       $cartForm$this->createForm(CartType::class, $cart);
  3074.       $cartForm->handleRequest($request);
  3075.       if ($request->get("alert_nodelivery_puro") == "true") {
  3076.         $twigData['alert_nodelivery_puro'] = "true";
  3077.       }
  3078.       if ($request->get("alert_nodelivery_cold") == "true") {
  3079.         $twigData['alert_nodelivery_cold'] = "true";
  3080.       }
  3081.       if ($request->get("alert_nodelivery_alcohol") == "true") {
  3082.         $twigData['alert_nodelivery_alcohol'] = "true";
  3083.       }
  3084.      
  3085.       $SponsoredItems = [];
  3086.         $sponsored_products_per_category_limit 4;
  3087.         $ProductSponsoredCategories $em->getRepository(ProductSponsoredCategory::class)->findAllFrontPage();
  3088.        
  3089.         foreach($ProductSponsoredCategories as $psc) {
  3090.           $category $psc->getCategory();
  3091.           $Products = [];
  3092.           $_SponsoredProducts $em->getRepository(ProductSponsored::class)->findInSponsoredLimit($psc$sponsored_products_per_category_limit);
  3093.           foreach($_SponsoredProducts as $SponsoredProduct) {
  3094.             $_product $SponsoredProduct->getProduct();     
  3095.             $Products[] = $_product;
  3096.             
  3097.           } 
  3098.           
  3099.          
  3100.           if ($category && count($Products) < $sponsored_products_per_category_limit) {
  3101.             $ExtraSponsoredProducts $em->getRepository(Product::class)->getProductsFromCategoryForFrontpage(
  3102.               $category$sponsored_products_per_category_limit
  3103.             );
  3104.             foreach($ExtraSponsoredProducts as $ExtraSponsoredProduct) {
  3105.               $Products[] = $ExtraSponsoredProduct;
  3106.             }
  3107.           }
  3108.          
  3109.           // Remove duplicate products
  3110.           $_Products = [];
  3111.           foreach($Products as $Product) {
  3112.             $_Products[$Product->getId()] = $Product;
  3113.           }
  3114.           $Products $_Products;
  3115.           shuffle($Products);
  3116.           $SponsoredItems[] = array(
  3117.             "SponsoredCategory" => $psc,
  3118.             "Products" => $Products
  3119.           );
  3120.         }
  3121.        
  3122.         $twigData['SponsoredItems'] = $SponsoredItems;
  3123.       // //add by default dth reusable box 
  3124.       // $reusableBox = $request->request->get("reusableBox");
  3125.       // if($cartForm->get('submit')->isClicked()){
  3126.       //   if ($reusableBox == "addBox" && $this->getUser() && !$this->getUser()->getHasReusableBox() && !$cart->containReusableBox() && $cart->containMaturinRoute()){
  3127.       //     $productBoxReusable = $em->getRepository(Product::class)->findOneBy(['id'=> 6472]);
  3128.       //     $this->addToCart($productBoxReusable, 1, $userServ, $em);
  3129.       //   }        
  3130.       // }
  3131.       
  3132.         //bloque si commande de produit Naya (bouteille d'eau) + que 10
  3133.         foreach($cart->getProducts() as $p){
  3134.           if($p->getQuantity() >= 10 && $p->getProduct()->getCompany()->getId() == 525 && $p->getProduct()->isShippedByMaturin() == true){
  3135.             $this->addFlash('error''Désolé vous ne pouvez pas commander plus de 10 produits de la compagnie Naya');
  3136.             return $this->redirectToRoute('viewCart');
  3137.           }
  3138.         } 
  3139.         
  3140.           if($request->isMethod('post') && $request->request->get('cart_submit') == 'cart_submit'){
  3141.             foreach($cart->getProducts() as $p){
  3142.               if (!$p->getProduct()->getIsBoxOfProducts()){
  3143.                 // getQuantityMaxProd valable pour augmenter les ventes en période de fetes, permet au producteur d'anticiper ou claudia de commander plus de volume 
  3144.               // et de vendre plusque quantité hebdomadaire
  3145.             //If the quantity we have in stock is lower than the one the customer wants
  3146.               $getQtyReadyToShip $p->getProduct()->getQtyReadyToShip();
  3147.                 if ($getQtyReadyToShip) {
  3148.                     if ($p->getProduct()->getQuantityMaxProd() > 0){
  3149.                       $getQtyComing $p->getProduct()->getQuantityMaxProd();
  3150.                     }else{
  3151.                       $getQtyComing 0;
  3152.                     }
  3153.                       $qtyMaximumToSell $getQtyReadyToShip $getQtyComing;
  3154.                   if($qtyMaximumToSell $p->getQuantity()) {
  3155.                     if($qtyMaximumToSell == 0){
  3156.                       $this->addFlash('error'"Le produit ".$p->getProduct()->getName()." n'est plus disponible et a été enlevé de votre panier");
  3157.                       $em->remove($p);
  3158.                       $em->flush();
  3159.                       $forceRedirect=true;
  3160.                       continue;
  3161.                     }else{
  3162.                       $this->addFlash('error'"La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire");
  3163.                       $p->setQuantity($getQtyReadyToShip);
  3164.                       $em->persist($p);
  3165.                       $em->flush();
  3166.                       $forceRedirect=true;
  3167.                       continue;
  3168.                     }
  3169.                 }
  3170.               }
  3171.             }
  3172.           
  3173.             // If the jit product pass the weekly  qty to sell
  3174.             if($p->getProduct()->getIsJustInTime() && !$p->getProduct()->getIsBoxOfProducts()){
  3175.               $qtyWeeklySoldForProduct $em->getRepository(CartProduct::class)->findWeeklyAlreadySoldForProductJit($p->getProduct()->getId());
  3176.               if (!$qtyWeeklySoldForProduct) {
  3177.                 $qtyWeeklySoldForProduct 0;
  3178.               }
  3179.               $getQtyReadyToShip $p->getProduct()->getQtyReadyToShip();
  3180.               if ($getQtyReadyToShip) {
  3181.                 if($qtyWeeklySoldForProduct $p->getQuantity() >= $getQtyReadyToShip ) {
  3182.                   if ($p->getQuantity() <= $qtyWeeklySoldForProduct){
  3183.                     $p->setQuantity($p->getQuantity());
  3184.                     $em->persist($p);
  3185.                     $em->flush();
  3186.                    
  3187.                     continue;
  3188.                   }else{
  3189.                     $this->addFlash('error'"La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire");
  3190.                     $p->setQuantity($getQtyReadyToShip);
  3191.                     $em->persist($p);
  3192.                     $em->flush();
  3193.                     $forceRedirect=true;
  3194.                     continue;
  3195.                   }
  3196.                 }
  3197.               }
  3198.             }
  3199.             if ($p->getProduct()->getIsBoxOfProducts()){
  3200.               $getAllProducts $p->getProduct()->getProductsInBox();
  3201.               foreach ($getAllProducts  as $getAllProduct) {
  3202.                 $getQuantityforBox $p->getQuantity() * $getAllProduct->getQuantity();
  3203.                 if ($getQuantityforBox $p->getProduct()->getQtyReadyToShip()){
  3204.                   $quantityBoxLeft intval(floor($p->getProduct()->getQtyReadyToShip() / $getAllProduct->getQuantity()));
  3205.                   if ($quantityBoxLeft $p->getQuantity()){
  3206.                     $this->addFlash('error'"La quantité du produit ".$p->getProduct()->getName()." à été modifié pour ce qui nous reste en inventaire");
  3207.                     $p->setQuantity($quantityBoxLeft);
  3208.                     $em->persist($p);
  3209.                     $em->flush();
  3210.                     $forceRedirect=true;
  3211.                   }
  3212.                 }
  3213.               }
  3214.             }
  3215.           }
  3216.       if($forceRedirect)
  3217.       {
  3218.         return $this->redirectToRoute('NewViewCart');
  3219.       }
  3220.       
  3221.             $p->setQuantity($p->getQuantity());
  3222.             $em->persist($p);
  3223.             $em->flush();
  3224.             return $this->redirectToRoute('adresse');
  3225.           }
  3226.       $twigData['form'] = $cartForm->createView();
  3227.       $twigData['cart']= $cart;
  3228.       $twigData['hideSideMenu'] = true;
  3229.       //Let's check if the cart is legit
  3230.       if($cart->getTotalProductsMaturinDeliveryOnly() < 25 && $cart->getHasMaturinDeliveryProducts()) {
  3231.         $this->addFlash('warning'"Le montant minimal d'achat est de 25$");
  3232.         $twigData['noGo']=true;
  3233.       }
  3234.     }else{
  3235.       return $this->redirectToRoute('viewCart');
  3236.   }
  3237.       return $twigData;
  3238.   }
  3239.    /**
  3240.      * @Route({
  3241.      *          "fr": "/adresse/maturinRecolte",
  3242.      *          "en": "/adresse/maturinRecolte"
  3243.      *      }, name="adresse")
  3244.      * @Security("has_role('ROLE_USER')")
  3245.      * @Template("frontend/newAdresse.html.twig")
  3246.      */
  3247.     public function adresse(UserService $userServRequest $request,TwigGlobalVariables $twigGlobalVariablesDistributorService $distributorServ,TwigGlobalVariables $twigGlobalVariablesService){
  3248.       
  3249.       $twigData = array();
  3250.         $twigData['hideSideMenu'] = true;
  3251.         $twigData['loader']= true;
  3252.         $cart $userServ->getCart();
  3253.         $em $this->getDoctrine()->getManager();
  3254.         if ($this->getUser() && $this->getUser()->getIsBetaTester()){
  3255.         $redirect true;
  3256.         $route_is_puro_nocold false;
  3257.         $maturin_type_route_found false;
  3258.         $shippingAddress $cart->getShippingAddress();
  3259.         // if(!$cart->hasMaturinShipping()){
  3260.           // if($cart->hasMaturinShipping()){
  3261.           //   $twigData['shippingMaturin'] = $distributorServ->getEstimateShipping($cart);
  3262.           // }
  3263.           //Update the Shipping cost
  3264.           if(!empty($twigData['shippingMaturin'])){
  3265.             $maturinShipping current($twigData['shippingMaturin']);
  3266.           } else {
  3267.             $maturinShipping false;
  3268.           }
  3269.         
  3270.           $found false;
  3271.           if($maturinShipping){
  3272.               foreach($twigData['shippingMaturin'] as $s){
  3273.                   if($s->serviceName == $request->request->get('shippingService') && $s->carrierName == $request->request->get('shippingCarrier')){
  3274.                       $found true;
  3275.                       $cart->setShippingMaturinCost($s->estimatedCost);
  3276.                       $cart->setShippingMaturinCarrierName($s->carrierName);
  3277.                       $cart->setShippingMaturinServiceName($s->serviceName);
  3278.                       $cart->setShippingMaturinServiceId($s->serviceId);
  3279.                       $estimatedCartDate $twigGlobalVariablesService->getEstimationShippingForMaturinProducts($cart);
  3280.                      //$cart->setShippingMaturinEstimatedDate(new \DateTime($s->estimatedDate));
  3281.                       $cart->setShippingMaturinEstimatedDate($estimatedCartDate);
  3282.                    
  3283.                       $twigData['currentShipping'] = $s;
  3284.                       break;
  3285.                   }
  3286.               }
  3287.               if(!($request->request->has('maturinShipping') && $found)){
  3288.                   $cart->setShippingMaturinCost($maturinShipping->estimatedCost);
  3289.                   $cart->setShippingMaturinCarrierName($maturinShipping->carrierName);
  3290.                   $cart->setShippingMaturinServiceName($maturinShipping->serviceName);
  3291.                   $cart->setShippingMaturinServiceId($maturinShipping->serviceId);
  3292.             
  3293.                   //// old estimate not working anymore for delivery date we change it to new estimation route
  3294.                   $estimatedCartDate $twigGlobalVariablesService->getEstimationShippingRouteForMaturinProducts($cart);
  3295.                   $maturinShipping->estimatedDate $estimatedCartDate["date"];
  3296.                   $cart->setShippingMaturinEstimatedDate($maturinShipping->estimatedDate);
  3297.                   //$cart->setShippingMaturinEstimatedDate(new \DateTime($maturinShipping->estimatedDate));
  3298.                   $twigData['currentShipping'] = $maturinShipping;
  3299.               }
  3300.               $em->persist($cart);
  3301.               $em->flush();
  3302.             }
  3303.        
  3304.         if ($request->get('action') == 'proceed_to_payment') {
  3305.           if ($request->request->get('action_shipping') == 'domicile'){
  3306.               if ($request->request->get("checkoutAddressSelection") != 'none'){
  3307.                 $shippingAddressId $request->get("checkoutAddressSelection");
  3308.                 $addr $em->getRepository(UserShippingLocation::class)->findOneBy(["id"=>$shippingAddressId]);
  3309.                 $cart->setShippingAddress($addr);
  3310.                 $em->persist($cart);
  3311.                 $em->flush();
  3312.               }else{
  3313.                   $newadresseAutocomplete $request->request->get('newAddress_autocomplete');
  3314.                 if (!empty($newadresseAutocomplete)){
  3315.                  
  3316.                 $pattern '/\d+/';
  3317.                 preg_match($pattern$newadresseAutocomplete$civicnumber);
  3318.             
  3319.                 $pattern strlen($civicnumber[0]);
  3320.                 $streetname substr($newadresseAutocomplete$pattern);
  3321.             
  3322.                 $arrayAutocomplete explode(', 'trim($streetname));
  3323.               
  3324.                   $newAddress_civicnumber $civicnumber[0];
  3325.                   $newAddress_streetname $arrayAutocomplete[0];
  3326.                   $newAddress_phone $request->request->get('newAddress_phone');
  3327.                   $newAddress_province $request->request->get('adresse_province');
  3328.                   $newAddress_zipcode =  $request->request->get('newAddress_zipcode');
  3329.                   $adresse_unit $request->request->get('newAddress_unit');
  3330.                   $newAddress_city $request->request->get('adresse_city');
  3331.                   $newAdresse_name =  $request->request->get('newAddress_name');
  3332.           
  3333.                   $findTheCity $em->getRepository(City::class)->findBy(["name"=>$newAddress_city]);
  3334.                 
  3335.                   if ($findTheCity == null){
  3336.                     $findTheCity = new City();
  3337.           
  3338.                     $findTheCity->setName(trim($newAddress_city));
  3339.                     $findTheCity->setMrc(trim($newAddress_city));
  3340.                     $findTheCity->setProvince(trim($newAddress_province));
  3341.           
  3342.                     $findTheRegion $em->getRepository(Region::class)->findBy(["name"=>'defaut']);
  3343.                     $findTheCity->setRegion($findTheRegion[0]);
  3344.           
  3345.                     $em->persist($findTheCity);
  3346.                     $em->flush();
  3347.           
  3348.                     $charlie $em->getRepository(User::class)->findOneBy(["email" => "charlie@maturin.ca"])->getEmail();
  3349.                     $userServ->sendEmail('Une nouvelle ville a été ajouté''<p>La ville ,' $newAddress_city ' a été ajouté dans la base de données</p>'false$charlie);
  3350.                   }
  3351.                   $user $userServ->getUser();
  3352.           
  3353.                   $UserShippingLocation = new UserShippingLocation();
  3354.                 
  3355.                   $UserShippingLocation->setName($newAdresse_name);
  3356.                     // ajout de condition format et correspond au type de data attendu 
  3357.                   $UserShippingLocation->setPhone($newAddress_phone);
  3358.                   $UserShippingLocation->setCivicNumber($newAddress_civicnumber);
  3359.                   $UserShippingLocation->setStreetName($newAddress_streetname);
  3360.                   $UserShippingLocation->setUnit($adresse_unit);
  3361.                   $UserShippingLocation->setCity($newAddress_city);
  3362.                   $UserShippingLocation->setZipCode($newAddress_zipcode);
  3363.                   $UserShippingLocation->setProvince($newAddress_province);
  3364.                   $UserShippingLocation->setUser($user);
  3365.                   $UserShippingLocation->setEmail($this->getUser()->getEmail());
  3366.                   
  3367.                   $em->persist($UserShippingLocation);
  3368.                   $cart->setShippingAddress($UserShippingLocation);
  3369.                   $em->persist($cart);
  3370.                   $em->flush();
  3371.                   $this->addFlash('success''Votre adresse a été ajouté avec succes');
  3372.                 }else{
  3373.                   $this->addFlash('error','Veillez a remplir tous les champs adresse');
  3374.                   return $this->redirectToRoute('adresse');
  3375.                 }
  3376.                 }
  3377.                 
  3378.                 foreach($cart->getProducts() as $cp) {
  3379.                   $dm $cp->getCompanyDeliveryMethod();
  3380.                   if($cp->getAddedWhenBeingInAssociation()){
  3381.                     if($cp->getAddedWhenBeingInAssociation()->getVariableValueByCodeName('orders.canPickUp')){
  3382.                       $dm = new DeliveryMethod();
  3383.                       $dm->setAverageDays(1);
  3384.                       $dm->setIsAPickup(true);
  3385.                       $dm->setServiceId(9999);
  3386.                       $dm->setFixedPrice(0);
  3387.                       $dm->setValid(true);
  3388.                       $cp->setCompanyDeliveryMethod($dm);
  3389.                       $em->persist($dm);
  3390.                       $em->persist($cp);
  3391.                       $em->flush();
  3392.                     }
  3393.                   }
  3394.                   if ($cp->getIsAPickup()){
  3395.                     $dm $cp->getCompanyDeliveryMethod();
  3396.                     if(!empty($cp->getCompanyDeliveryMethod()->getId())){
  3397.                       $idPickUp $cp->getCompanyDeliveryMethod()->getId();
  3398.                       $entityManager $this->getDoctrine()->getManager();
  3399.                       $PickUpRetake $entityManager->getRepository(DeliveryMethod::class)->find($cp->getId());
  3400.                       $cp->setCompanyDeliveryMethod(null);
  3401.                       $entityManager->persist($cp);
  3402.                       $entityManager->flush();
  3403.                   }else{
  3404.                     // if($request->hasPreviousSession('pickupSchedule')) {
  3405.                       $dm->setAverageDays(2);
  3406.                       $dm->setPickupSchedule($request->get('pickupSchedule'));
  3407.                       $address$cp->getAddedWhenBeingInAssociation()->getVariableValueByCodeName('orders.pickUpAdress');
  3408.                       $dm->setPickupAddress($address);
  3409.                     // }
  3410.                   }
  3411.                 
  3412.                     $withPacking $request->hasPreviousSession('withPacking')
  3413.                     && $request->get('withPacking') == 'true';
  3414.                     $dm->setWithPacking($withPacking);
  3415.                     $em->persist($dm);
  3416.                 }
  3417.                   }
  3418.               }elseif ($request->request->get('pickupScheduleCheckbox') == 'cueillette'){
  3419.             // if ( $request->get('DeliveryCheck') == "on" && !empty($customDeliveryDate)) {
  3420.             //   // dump($request->request->get("livraisonDate"))
  3421.             //   $months = [
  3422.             //     'janvier' => 'january',
  3423.             //     'février' => 'february',
  3424.             //     'mars' => 'march',
  3425.             //     'avril' => 'april',
  3426.             //     'mai' => 'may',
  3427.             //     'juin' => 'june',
  3428.             //     'juillet' => 'july',
  3429.             //     'août' => 'august',
  3430.             //     'septembre' => 'september',
  3431.             //     'octobre' => 'october',
  3432.             //     'novembre' => 'november',
  3433.             //     'décembre' => 'december'
  3434.             //   ];
  3435.             //   $customDeliveryDate = explode(" ", $customDeliveryDate)[1]. " " .$months[explode(" ", $customDeliveryDate)[2]]. " ". explode(" ", $customDeliveryDate)[3];
  3436.             //   $requestDate = new \DateTime(date("Y-m-d", strtotime($customDeliveryDate)));
  3437.             //   $date = new \DateTime('now');
  3438.             //   $date->modify('+8 days');
  3439.             //   if ($requestDate->format('Y-m-d') > $date->format('Y-m-d')){
  3440.             //     $cart->setDeliveryChoiceDate($requestDate);
  3441.             //     $cart->setPreOrder(true);
  3442.             //     $cart->setPreOrderNow(true);
  3443.             //   }else{
  3444.             //     $cart->setDeliveryChoiceDate($requestDate);
  3445.             //     $cart->setPreOrder(true);
  3446.             //   }
  3447.             // } else {
  3448.             //     $cart->setPreOrder(false);
  3449.             //     $cart->setPreOrderNow(false);
  3450.             //     $cart->setDeliveryChoiceDate(null);
  3451.             // }
  3452.                 $pickUpSchedule $request->get('pickupSchedule');
  3453.                 if (empty($pickUpSchedule)) {
  3454.                   $this->addFlash('error'"Il faut spécifier une date et un temps de cueillette.");
  3455.                   return $this->redirectToRoute('adresse');
  3456.                 }
  3457.                 $pickUpAdress $request->get('pickupLocation');
  3458.                 $pickupLocationId $request->get('pickupLocations');
  3459.                 $newAddress_phone $request->request->get('pickup_phone');
  3460.                 $newAdresse_name =  $request->request->get('pickup_name');
  3461.                 if($cart->getPickupAddress() != null){
  3462.                   $UserInformation $this->getUser();
  3463.                     $UserInformation->setPhone($newAddress_phone);
  3464.                     $UserInformation->setFirstname($newAdresse_name);
  3465.                   $em->persist($UserInformation);
  3466.                   $em->flush();
  3467.                 }
  3468.                 foreach($cart->getProducts() as $cp) {
  3469.                   $dm = new DeliveryMethod();
  3470.                   $dm->setAverageDays(1);
  3471.                   $dm->setIsAPickup(true);
  3472.                   $dm->setServiceId(9999);
  3473.                   $dm->setFixedPrice(0);
  3474.                   $dm->setValid(true);
  3475.                   $dm->setPickupSchedule($pickUpSchedule);
  3476.                   $dm->setPickupAddress($pickUpAdress);
  3477.                   $dm->setPickupLocationId($pickupLocationId);
  3478.                   $cp->setCompanyDeliveryMethod($dm);
  3479.                   $em->persist($dm);
  3480.                   $em->persist($cp);
  3481.                 }
  3482.               }
  3483.               $estimationDateToTake $cart->getShippingMaturinEstimatedDate();
  3484.               $contains_alcohol false;
  3485.               $contains_puro_exclusion false;
  3486.               $cold_products false;
  3487.               $products = [];
  3488.       
  3489.               foreach($cart->getProducts() as $cp) {
  3490.                 $product $cp->getProduct();
  3491.       
  3492.                 if($product->getIsBoxOfProducts()) {
  3493.                   foreach($product->getProductsInBox() as $mp) {
  3494.                     $products[] = $mp->getProduct();
  3495.                     if ($mp->getProduct()->getPuroExclusion()) {
  3496.                       $contains_puro_exclusion true;
  3497.                     }
  3498.                   }
  3499.                 } else {
  3500.                   $products[] = $product;
  3501.                   if ($product->getPuroExclusion()) {
  3502.                     $contains_puro_exclusion true;
  3503.                   }
  3504.                 }
  3505.                 if ($product->getIsCold()) {
  3506.                   $cold_products true;
  3507.                 }
  3508.       
  3509.                 if ($product->getIsAlcohol()) {
  3510.                   $contains_alcohol true;
  3511.                 }
  3512.               }
  3513.               $twigData['contains_alcohol'] = $contains_alcohol;
  3514.               if ($cart->getShippingAddress() && $request->request->get('action_shipping') == 'domicile'){
  3515.                 $cityName $cart->getShippingAddress()->getCity();
  3516.                 $province $cart->getShippingAddress()->getProvince();
  3517.               }elseif($cart->getPickUpAddress() && $request->request->get('pickupScheduleCheckbox') == 'cueillette'){
  3518.                 $completeAdresse $cart->getPickUpAddress();
  3519.                 $arrayAdresse explode(','$completeAdresse);
  3520.                 $cityName trim($arrayAdresse[1]);
  3521.                 $province trim($arrayAdresse[2]);
  3522.               }
  3523.               $city $em->getRepository(City::class)->findLikeNameAndProvince($cityName,$province);
  3524.               if ($city) {
  3525.                 $routes $city[0]->getDeliveryRoutes();
  3526.                 foreach($routes as $route) {
  3527.                   if (
  3528.                     $route->getType() == "maturin" && $route->getName() != "Pas de frais"
  3529.                   ) {
  3530.                     $maturin_type_route_found true;
  3531.                   }
  3532.                   if ($route->getName() == "Pas de frais") {
  3533.                     $route_is_puro_nocold true;
  3534.                   }
  3535.                 }
  3536.               }
  3537.     
  3538.           $redirect_params = [];
  3539.           if ($contains_puro_exclusion && !$maturin_type_route_found) {
  3540.             // $this->addFlash('error', "Il est impossible de livrer un produit à cette adresse car il contient de l'alcool.");
  3541.             $redirect_params["alert_nodelivery_puro"] = "true";
  3542.           }
  3543.           if ($contains_alcohol && !$maturin_type_route_found) {
  3544.             // $this->addFlash('error', "Il est impossible de livrer un produit à cette adresse car il contient de l'alcool.");
  3545.             $redirect_params["alert_nodelivery_alcohol"] = "true";
  3546.           }
  3547.           if ($route_is_puro_nocold && $cold_products && !$maturin_type_route_found) {
  3548.             // $this->addFlash('error', "Il est impossible de livrer un produit à cette adresse car il doit rester frais durant la livraison.");
  3549.             $redirect_params["alert_nodelivery_cold"] = "true";
  3550.           }
  3551.           if (!empty($redirect_params) and $request->get('pickupScheduleCheckbox') != "cueillette" ) {
  3552.             return $this->redirectToRoute('NewViewCart'$redirect_params);
  3553.           }
  3554.           if($cart->getShippingAddress()){
  3555.             $cart->calculateFees();
  3556.         }
  3557.         // save cart changes
  3558.         $em->persist($cart);
  3559.         $em->flush();
  3560.         return $this->redirectToRoute('PaymentChoice'); 
  3561.       }
  3562.     }else{
  3563.       return $this->redirectToRoute('viewCart');
  3564.   }
  3565.         return $twigData;
  3566.     }
  3567.      /**
  3568.      * @Route({
  3569.      *          "fr": "/nouveauPaiement/maturinRecolte",
  3570.      *          "en": "/newPayment/maturinRecolte"
  3571.      *      }, name="RecapPayment")
  3572.      * @Security("has_role('ROLE_USER')")
  3573.      * @Template("frontend/newEndCheckoutPage.html.twig")
  3574.      */
  3575.     public function RecapPayment(Request $requestPaymentService $paymentServUserService $userServUrlGeneratorInterface $routerDistributorService $distributorServ,TwigGlobalVariables $twigGlobalVariablesService){
  3576.       $twigData = array();
  3577.       $twigData['hideSideMenu'] = true;
  3578.       // $twigData['loader']= true;
  3579.       $em $this->getDoctrine()->getManager();
  3580.       $cart $userServ->getCart();
  3581.       $user $userServ->getUser();
  3582.       // dump($cart->getPickUpAddress());
  3583.       // if(empty($cart->getShippingAddress()) && empty($cart->getPickUpAddress())){
  3584.       //     $this->addFlash('error', "Nous avons d'abord besoin d'une adresse de livraison'");
  3585.       //     return $this->redirectToRoute('checkout');
  3586.       // }
  3587.       if ($this->getUser() && $this->getUser()->getIsBetaTester() && count($cart->getProducts()) >0){
  3588.       $forceRedirect=false;
  3589.       $route=[];
  3590.             foreach($cart->getProducts() as $p){
  3591.               if (!empty($route)){
  3592.                 if ($twigGlobalVariablesService->getEstimationShippingRoute($p->getProduct())['date']->format('Y-m-d') != $route['estimationDelivery']->format('Y-m-d') ){
  3593.                     $route[] = array(
  3594.                       'estimationDelivery' => $twigGlobalVariablesService->getEstimationShippingRoute($p->getProduct())['date']->format('Y-m-d')
  3595.                   );
  3596.                 }
  3597.               }else{
  3598.                 $route = array(
  3599.                   'estimationDelivery' => $twigGlobalVariablesService->getEstimationShippingRoute($p->getProduct())['date']
  3600.                 );
  3601.               } 
  3602.             }
  3603.       sort($route);
  3604.       $twigData['estimationDeliveryDate'] = $route;
  3605.       /*
  3606.        * Called when there is a Shipping Method change
  3607.        * But not a payment
  3608.        */
  3609.       if(!$request->request->has('stripeToken') && !$request->request->has('use-previous-card')){
  3610.           // if(!$cart->hasMaturinShipping()){
  3611.             if($cart->hasMaturinShipping()){
  3612.             $twigData['shippingMaturin'] = $distributorServ->getEstimateShipping($cart);
  3613.           }
  3614.           //Update the Shipping cost
  3615.           if(!empty($twigData['shippingMaturin'])){
  3616.             $maturinShipping current($twigData['shippingMaturin']);
  3617.           } else {
  3618.             $maturinShipping false;
  3619.           }
  3620.           $found false;
  3621.       }
  3622.       
  3623.       $shippingAddress $cart->getShippingAddress();
  3624.       //We need a shipping address for the taxes
  3625.       if($shippingAddress) {
  3626.           $cart->calculateFees();
  3627.           $em->persist($cart);
  3628.           $em->flush();
  3629.       }
  3630.       $PuroTest null;
  3631.       if ($shippingAddress){
  3632.         $getMethodLivraisons $em->getRepository(DeliveryRoute::class)->findBy(['name' => $cart->getShippingAddress()->getArrayOfDeliveryRoutes()]);
  3633.         foreach ($getMethodLivraisons as $getMethodLivraison) {
  3634.           if ($getMethodLivraison->getType() == 'maturin')
  3635.           $PuroTest 'maturin';
  3636.         }
  3637.       }
  3638.       $twigData['puroConfirm'] = $PuroTest;
  3639.       /*
  3640.        * If payment is ready
  3641.        */
  3642.       if($request->isMethod('post') && $request->request->get('pay_cart')){
  3643.           if(!empty($request->request->get('stripeToken')))
  3644.               $cart->setStripeToken($request->request->get('stripeToken'));
  3645.               
  3646.               if ($cart->getUsedCoupon() == null){
  3647.                 //Lets start with the coupon see if it's valid
  3648.                   $coupon $request->get("coupon");
  3649.                   if(!empty($coupon) ){
  3650.                     $cartCoupon $em->getRepository(CartCoupon::class)->findOneValidByCode($coupon);
  3651.                     $couponSearchTuango false;
  3652.                     $couponSearchTuango =  $this->CouponTuango($coupon);
  3653.                     $couponCabane false;
  3654.                     $couponCabane =  $this->CouponCabaneMaturin($coupon);
  3655.                     if ($couponSearchTuango != false || $couponCabane != false){
  3656.                       $cartCoupon $em->getRepository(CartCoupon::class)->findOneValidByCode($coupon);
  3657.                     }
  3658.                       if(empty($cartCoupon)){
  3659.                         if ($couponSearchTuango == false && $couponCabane == false){
  3660.                           $this->addFlash('error'"Merci de vérifier votre code coupon ou associez-le au bon produit");
  3661.                           return $this->redirectToRoute('checkout');
  3662.                         }
  3663.                       }else{
  3664.                           //If coupon is a onetimeonly and was already used
  3665.                           if($cartCoupon->getOneTimeOnly()){
  3666.                               if($cartCoupon->getUsedByUsers()->contains($userServ->getUser())){
  3667.                                   $this->addFlash('error'"Vous avez déja utilisé ce coupon");
  3668.                                   return $this->redirectToRoute('checkout');
  3669.                               }
  3670.                           }
  3671.                           //Check if any money left
  3672.                           if($cartCoupon->getIsGiftCertificate() && $cartCoupon->getAmount() <= ){
  3673.                               $this->addFlash('error'"Ce coupon a un solde restant de 0$");
  3674.                               return $this->redirectToRoute('checkout');
  3675.                           }
  3676.                           $cart->setUsedCoupon($cartCoupon);
  3677.                           //$user = $userServ->getUser();
  3678.                           //$user->addCouponUsed($cartCoupon);
  3679.                           //$em->persist($user);
  3680.                       }
  3681.                   }else{
  3682.                     //$user->removeCouponUsed($cartCoupon);
  3683.                     $cart->setUsedCoupon(null);
  3684.                   }
  3685.               }
  3686.               $em->persist($cart);
  3687.               $em->flush();
  3688.           // if($request->request->get('NoteFromBuyer')){
  3689.           //   $noteFromBuyer = $request->request->get('NoteFromBuyer'); 
  3690.           //   if (strlen($noteFromBuyer) <= 100){
  3691.           //     $patternNoteFromBuyer = '/([0-9|#][\x{20E3}])|[\x{00ae}|\x{00a9}|\x{203C}|\x{2047}|\x{2048}|\x{2049}|\x{3030}|\x{303D}|\x{2139}|\x{2122}|\x{3297}|\x{3299}][\x{FE00}-\x{FEFF}]?|[\x{2190}-\x{21FF}][\x{FE00}-\x{FEFF}]?|[\x{2300}-\x{23FF}][\x{FE00}-\x{FEFF}]?|[\x{2460}-\x{24FF}][\x{FE00}-\x{FEFF}]?|[\x{25A0}-\x{25FF}][\x{FE00}-\x{FEFF}]?|[\x{2600}-\x{27BF}][\x{FE00}-\x{FEFF}]?|[\x{2900}-\x{297F}][\x{FE00}-\x{FEFF}]?|[\x{2B00}-\x{2BF0}][\x{FE00}-\x{FEFF}]?|[\x{1F000}-\x{1F6FF}][\x{FE00}-\x{FEFF}]?/u';
  3692.           //     if(preg_match($patternNoteFromBuyer,
  3693.           //       $noteFromBuyer
  3694.           //     )){
  3695.           //        $noteFromBuyer = preg_replace($patternNoteFromBuyer, 
  3696.           //       '', 
  3697.           //       $noteFromBuyer);
  3698.           //     }
  3699.           //     $cart->setNoteFromBuyer($noteFromBuyer);
  3700.           //   }else{
  3701.           //     $this->addFlash('error', "Veuillez ne pas dépasser les 100 characteres dans votre messages au livreur.");
  3702.           //     return $this->redirectToRoute('checkout');
  3703.           //   }
  3704.           // }
  3705.           //Let's save if the signature was asked for the shipping
  3706.           if (!empty($request->request->get('date_first_order'))){
  3707.             $date_first_order $request->request->get('date_first_order');
  3708.           }else{
  3709.             $date_first_order $cart->getShippingMaturinEstimatedDate();
  3710.           }
  3711.           if (!empty($request->request->get('date_second_order'))){
  3712.             $date_second_order $request->request->get('date_second_order');
  3713.           }else{
  3714.             $date_second_order $cart->getShippingMaturinEstimatedDate();
  3715.           }
  3716.            if($date_first_order && $date_second_order && $date_first_order != $date_second_order){
  3717.             $dates[]= $date_first_order;
  3718.             $dates[]= $date_second_order;
  3719.             $i=0;
  3720.             foreach ($dates as $date) {
  3721.               $customDeliveryDate $date;
  3722.               $months = [
  3723.                  'janvier' => 'january',
  3724.                  'février' => 'february',
  3725.                  'mars' => 'march',
  3726.                  'avril' => 'april',
  3727.                  'mai' => 'may',
  3728.                  'juin' => 'june',
  3729.                  'juillet' => 'july',
  3730.                  'août' => 'august',
  3731.                  'septembre' => 'september',
  3732.                  'octobre' => 'october',
  3733.                  'novembre' => 'november',
  3734.                  'décembre' => 'december'
  3735.                ];
  3736.                $customDeliveryDate explode(" "$customDeliveryDate)[1]. " " .$months[explode(" "$customDeliveryDate)[2]]. " "explode(" "$customDeliveryDate)[3];
  3737.                $requestDate = new \DateTime(date("Y-m-d"strtotime($customDeliveryDate)));
  3738.                $date = new \DateTime('now');
  3739.                $date->modify('+8 days');
  3740.                if ($requestDate->format('Y-m-d') > $date->format('Y-m-d')){
  3741.                  $cart->setDeliveryChoiceDate($requestDate);
  3742.                  $cart->setPreOrder(true);
  3743.                  $cart->setPreOrderNow(true);
  3744.                }else{
  3745.                  $cart->setDeliveryChoiceDate($requestDate);
  3746.                  $cart->setPreOrder(true);
  3747.                }
  3748.                 $separateCart = new Cart();
  3749.                 $separateCart->setDateCreated($cart->getDateCreated());
  3750.                 $separateCart->setDatePayment(new \Datetime('now'));
  3751.                 $separateCart->setUser($user);
  3752.                 $separateCart->setShippingAddress($cart->getShippingAddress());
  3753.                 $separateCart->setDateCreated($cart->getDateCreated());
  3754.                 $separateCart->setDateCreated($cart->getDateCreated());
  3755.                 if($cart->hasMaturinShipping()){
  3756.                           $separateCart->setShippingMaturinCost($cart->getShippingMaturinCost());
  3757.                           $separateCart->setShippingMaturinCarrierName($cart->getShippingMaturinCarrierName());
  3758.                           $separateCart->setShippingMaturinServiceName($cart->getShippingMaturinServiceName());
  3759.                           $separateCart->setShippingMaturinServiceId($cart->getShippingMaturinServiceId());
  3760.                           $separateCart->setShippingMaturinEstimatedDate($cart->getShippingMaturinEstimatedDate());
  3761.                   }
  3762.         
  3763.                     if ($i == 1){
  3764.                       foreach ($cart->getProducts() as $cartProduct ) {
  3765.                         if ($cartProduct->getProduct()->getIsJustInTime()){
  3766.                           $separateCart->setIsOnHold(true);
  3767.                           $cartProduct->setProduct($cartProduct->getProduct());
  3768.                           $separateCart->addProduct($cartProduct);
  3769.                           dump('ok');
  3770.                         }
  3771.                       }
  3772.                     }else{
  3773.                       foreach ($cart->getProducts() as $cartProduct) {
  3774.                         if(!$cartProduct->getProduct()->getIsJustInTime()){
  3775.                           $separateCart->setIsOnHold(false);
  3776.                           $cartProduct->setProduct($cartProduct->getProduct());
  3777.                           $separateCart->addProduct($cartProduct);
  3778.                         }
  3779.                     }
  3780.                   }
  3781.                   $em->persist($cartProduct);
  3782.                   $separateCart->setDeliveryChoiceDate($cart->getDeliveryChoiceDate());
  3783.                   $separateCart->setPreOrder($cart->getPreOrder());
  3784.                   $separateCart->setPreOrderNow($cart->getPreOrderNow());
  3785.                   $separateCart->setUsedCoupon($cart->getUsedCoupon());
  3786.                   $em->persist($separateCart);
  3787.                   $em->flush();
  3788.              
  3789.                   if($paymentServ->payCart($separateCart)) {
  3790.                     $locale $request->getSession()->get('_locale');
  3791.                     if(empty($locale))
  3792.                         $locale 'fr';
  3793.     
  3794.                     //if ($cart->getPreOrderNow() != true){
  3795.                       $newRoute $router->generate'viewOrder', array ('_locale' => $locale'orderNo' => $separateCart->getOrderNo()));
  3796.     
  3797.                       $userServ->addNotification('success''Votre commande''A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>');
  3798.                       $this->addFlash('success'"Votre commande a été passée avec succès");
  3799.                   /* }else{
  3800.                       $newRoute = $router->generate( 'viewPreOrder', array ('_locale' => $locale, 'orderNo' => $cart->getOrderNo()));
  3801.     
  3802.                       $userServ->addNotification('success', 'Votre commande', 'A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>');
  3803.                       $this->addFlash('success', "Votre commande a été passée avec succès");
  3804.                     }*/
  3805.     
  3806.                     $emailBody $this->get('twig')->render('emails/order.html.twig', [
  3807.                         'cart' => $separateCart,
  3808.                         'user' => $separateCart->getUser()
  3809.                     ]);
  3810.     
  3811.                     $replyTo = [];
  3812.                     foreach ($separateCart->getProducts() as $cartProduct) {
  3813.                         if (($association $cartProduct->getAddedWhenBeingInAssociation()) != null)
  3814.                         {
  3815.                             foreach ($association->getAdminUsers() as $adminUser){
  3816.                                 $replyTo[]=$adminUser->getEmail();
  3817.                             }
  3818.                             foreach ($association->getUsersAddingCompanies() as $adminUser){
  3819.                                 $replyTo[]=$adminUser->getEmail();
  3820.                             }
  3821.                         }
  3822.                       }
  3823.     
  3824.                     $replyTo count($replyTo) == false array_unique($replyTo);
  3825.     
  3826.                     $userServ->sendEmail(
  3827.                         'Confirmation de votre commande #'.$cart->getOrderNo(),
  3828.                         $emailBody,
  3829.                         false,
  3830.                         $separateCart->getUser()->getEmail(), falsenull$replyTo
  3831.                     );
  3832.     
  3833.                     //This happen if the cart contain JIT product OR the shipping estimate didn'T worked
  3834.                     if(!$separateCart->getPreOrderNow()){
  3835.                       if(!$separateCart->getIsOnHold()){
  3836.                           //We are ready let's send the order
  3837.                           if($separateCart->hasMaturinShipping() && !$distributorServ->sendOrders($separateCart)){
  3838.                               $userServ->sendEmail('Maturin: Error Orders''Error with Cart ID (hasMaturinShipping):'.$separateCart->getId(), 'Error with the Cart ID:'.$separateCart->getId() , 'entrepot@maturin.ca');
  3839.                           }else if($separateCart->isMaturinPickUp() && !$distributorServ->sendOrders($separateCart)){
  3840.                             $userServ->sendEmail('Maturin: Error Orders''Error with Cart ID (isMaturinPickUp):'.$separateCart->getId(), 'Error with the Cart ID:'.$separateCart->getId() , 'entrepot@maturin.ca');
  3841.                           }
  3842.                       }
  3843.                     }
  3844.                   
  3845.                       $em->persist($separateCart);
  3846.                       $em->flush();
  3847.                     /*
  3848.                     * Let's see if it's the user first order
  3849.                     * In this case, and he got a referrer we give him a coupon
  3850.                     */
  3851.                     if($user->isFirstOrder() && !empty($user->getReferredBy())){
  3852.                         $coupon = new CartCoupon();
  3853.                         $coupon->setOneTimeOnly(true);
  3854.                         $coupon->setType(0);
  3855.                         $coupon->setAmount(10);
  3856.                         $coupon->setCode('C-'.uniqid());
  3857.                         $coupon->setForUser($user->getReferredBy());
  3858.                         $coupon->setDateFrom(new \DateTime());
  3859.                         $coupon->setDateTo(new \DateTime("+1 year"));
  3860.                         $em->persist($coupon);
  3861.                     }
  3862.     
  3863.                     //If it's a gift order let's remove the amount on it
  3864.                     if(!empty($separateCart->getUsedCoupon()) && $separateCart->getUsedCoupon()->getIsGiftCertificate()){
  3865.                         $coupon $separateCart->getUsedCoupon();
  3866.                         $separateCart->setAmountSavedByCoupon($separateCart->getCouponSavings());
  3867.                         $coupon $coupon->setAmount($coupon->getAmount() - $separateCart->getTotal(false));
  3868.     
  3869.                         $em->persist($separateCart);
  3870.                         $em->persist($coupon);
  3871.                     }
  3872.     
  3873.                     $em->flush();
  3874.     
  3875.                     if ($shippingAddress) {
  3876.                       $cityName $shippingAddress->getCity();
  3877.                       $province $shippingAddress->getProvince();
  3878.                       if ($cityName && $province) {
  3879.                         //$city = $em->getRepository(City::class)->findLikeName($cityName);
  3880.                         $city $em->getRepository(City::class)->findLikeNameAndProvince($cityName,$province);
  3881.                         if (empty($city)) {
  3882.                           // $cart->setIsOnHold(true);
  3883.                           $em->persist($separateCart);
  3884.                           $em->flush();
  3885.                           $userServ->sendEmail(
  3886.                               'Ville invalide pour la commande #'.$cart->getOrderNo(),
  3887.                               'Ville invalide ['.$cityName.'] pour la commande #'.$cart->getOrderNo(),
  3888.                               false,
  3889.                               "info@maturin.ca"falsenull"info@maturin.ca"
  3890.                           );
  3891.                         }
  3892.                       }
  3893.                     }
  3894.     
  3895.                 } else {
  3896.                   
  3897.                     $this->addFlash('error''Le paiement a echoué. Veuillez vérifier que votre carte est valide ou notre support.');
  3898.                     return $this->redirectToRoute('cartPayment');
  3899.                 }
  3900.               $i++;
  3901.             // $carts[]=$separateCart;
  3902.           }
  3903.           return $this->redirectToRoute('viewOrder', array('orderNo' => $separateCart->getOrderNo(), 'freshSale' => true));
  3904.           // foreach ($carts as $separateCart) {
  3905.               
  3906.           // }         
  3907.            }else{
  3908.               // todo move from here
  3909.               $signature $request->request->get('signature-required');
  3910.               if($signature)
  3911.                   $cart->setShippingSignatureRequired(true);
  3912.               else
  3913.                   $cart->setShippingSignatureRequired(false);
  3914.                 
  3915.               $em->persist($cart);
  3916.               $em->flush();
  3917.               /*---------------------------- en dessous insert la condition si champs preorder true alors envoi dans container preorders ---------------------------------------------*/
  3918.               if($paymentServ->payCart($cart)) {
  3919.                 // if ( $request->get('DeliveryCheck') == "on" && !empty($customDeliveryDate)) {
  3920.                 //   // dump($request->request->get("livraisonDate"))
  3921.                 //   $months = [
  3922.                 //     'janvier' => 'january',
  3923.                 //     'février' => 'february',
  3924.                 //     'mars' => 'march',
  3925.                 //     'avril' => 'april',
  3926.                 //     'mai' => 'may',
  3927.                 //     'juin' => 'june',
  3928.                 //     'juillet' => 'july',
  3929.                 //     'août' => 'august',
  3930.                 //     'septembre' => 'september',
  3931.                 //     'octobre' => 'october',
  3932.                 //     'novembre' => 'november',
  3933.                 //     'décembre' => 'december'
  3934.                 //   ];
  3935.                 //   $customDeliveryDate = explode(" ", $customDeliveryDate)[1]. " " .$months[explode(" ", $customDeliveryDate)[2]]. " ". explode(" ", $customDeliveryDate)[3];
  3936.                 //   $requestDate = new \DateTime(date("Y-m-d", strtotime($customDeliveryDate)));
  3937.                 //   $date = new \DateTime('now');
  3938.                 //   $date->modify('+8 days');
  3939.                 //   if ($requestDate->format('Y-m-d') > $date->format('Y-m-d')){
  3940.                 //     $cart->setDeliveryChoiceDate($requestDate);
  3941.                 //     $cart->setPreOrder(true);
  3942.                 //     $cart->setPreOrderNow(true);
  3943.                 //   }else{
  3944.                 //     $cart->setDeliveryChoiceDate($requestDate);
  3945.                 //     $cart->setPreOrder(true);
  3946.                 //   }
  3947.                 // } else {
  3948.                 //     $cart->setPreOrder(false);
  3949.                 //     $cart->setPreOrderNow(false);
  3950.                 //     $cart->setDeliveryChoiceDate(null);
  3951.                 // }
  3952.                  
  3953.                   $locale $request->getSession()->get('_locale');
  3954.                   if(empty($locale))
  3955.                       $locale 'fr';
  3956.                   //if ($cart->getPreOrderNow() != true){
  3957.                     $newRoute $router->generate'viewOrder', array ('_locale' => $locale'orderNo' => $cart->getOrderNo()));
  3958.                     $userServ->addNotification('success''Votre commande''A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>');
  3959.                     $this->addFlash('success'"Votre commande a été passée avec succès");
  3960.                 /* }else{
  3961.                     $newRoute = $router->generate( 'viewPreOrder', array ('_locale' => $locale, 'orderNo' => $cart->getOrderNo()));
  3962.                     $userServ->addNotification('success', 'Votre commande', 'A été payé avec succès vous pouvez la consulter <a href="'.$newRoute.'">ici</a>');
  3963.                     $this->addFlash('success', "Votre commande a été passée avec succès");
  3964.                   }*/
  3965.                   $emailBody $this->get('twig')->render('emails/order.html.twig', [
  3966.                       'cart' => $cart,
  3967.                       'user' => $cart->getUser()
  3968.                   ]);
  3969.                   $replyTo = [];
  3970.                   foreach ($cart->getProducts() as $cartProduct) {
  3971.                       if (($association $cartProduct->getAddedWhenBeingInAssociation()) != null)
  3972.                       {
  3973.                           foreach ($association->getAdminUsers() as $adminUser){
  3974.                               $replyTo[]=$adminUser->getEmail();
  3975.                           }
  3976.                           foreach ($association->getUsersAddingCompanies() as $adminUser){
  3977.                               $replyTo[]=$adminUser->getEmail();
  3978.                           }
  3979.                       }
  3980.                     }
  3981.                   $replyTo count($replyTo) == false array_unique($replyTo);
  3982.                   $userServ->sendEmail(
  3983.                       'Confirmation de votre commande #'.$cart->getOrderNo(),
  3984.                       $emailBody,
  3985.                       false,
  3986.                       $cart->getUser()->getEmail(), falsenull$replyTo
  3987.                   );
  3988.                   //This happen if the cart contain JIT product OR the shipping estimate didn'T worked
  3989.                   if(!$cart->getPreOrderNow()){
  3990.                     if(!$cart->getIsOnHold()){
  3991.                         //We are ready let's send the order
  3992.                         if($cart->hasMaturinShipping() && !$distributorServ->sendOrders($cart)){
  3993.                             $userServ->sendEmail('Maturin: Error Orders''Error with Cart ID (hasMaturinShipping):'.$cart->getId(), 'Error with the Cart ID:'.$cart->getId() , 'entrepot@maturin.ca');
  3994.                         }else if($cart->isMaturinPickUp() && !$distributorServ->sendOrders($cart)){
  3995.                           $userServ->sendEmail('Maturin: Error Orders''Error with Cart ID (isMaturinPickUp):'.$cart->getId(), 'Error with the Cart ID:'.$cart->getId() , 'entrepot@maturin.ca');
  3996.                         }
  3997.                     }
  3998.                   }
  3999.                 
  4000.                     $em->persist($cart);
  4001.                     $em->flush();
  4002.                   /*
  4003.                   * Let's see if it's the user first order
  4004.                   * In this case, and he got a referrer we give him a coupon
  4005.                   */
  4006.                   if($user->isFirstOrder() && !empty($user->getReferredBy())){
  4007.                       $coupon = new CartCoupon();
  4008.                       $coupon->setOneTimeOnly(true);
  4009.                       $coupon->setType(0);
  4010.                       $coupon->setAmount(10);
  4011.                       $coupon->setCode('C-'.uniqid());
  4012.                       $coupon->setForUser($user->getReferredBy());
  4013.                       $coupon->setDateFrom(new \DateTime());
  4014.                       $coupon->setDateTo(new \DateTime("+1 year"));
  4015.                       $em->persist($coupon);
  4016.                   }
  4017.                   //If it's a gift order let's remove the amount on it
  4018.                   if(!empty($cart->getUsedCoupon()) && $cart->getUsedCoupon()->getIsGiftCertificate()){
  4019.                       $coupon $cart->getUsedCoupon();
  4020.                       $cart->setAmountSavedByCoupon($cart->getCouponSavings());
  4021.                       $coupon $coupon->setAmount($coupon->getAmount() - $cart->getTotal(false));
  4022.                       $em->persist($cart);
  4023.                       $em->persist($coupon);
  4024.                   }
  4025.                   $em->flush();
  4026.                   if ($shippingAddress) {
  4027.                     $cityName $shippingAddress->getCity();
  4028.                     $province $shippingAddress->getProvince();
  4029.                     if ($cityName && $province) {
  4030.                       //$city = $em->getRepository(City::class)->findLikeName($cityName);
  4031.                       $city $em->getRepository(City::class)->findLikeNameAndProvince($cityName,$province);
  4032.                       if (empty($city)) {
  4033.                         // $cart->setIsOnHold(true);
  4034.                         $em->persist($cart);
  4035.                         $em->flush();
  4036.                         $userServ->sendEmail(
  4037.                             'Ville invalide pour la commande #'.$cart->getOrderNo(),
  4038.                             'Ville invalide ['.$cityName.'] pour la commande #'.$cart->getOrderNo(),
  4039.                             false,
  4040.                             "info@maturin.ca"falsenull"info@maturin.ca"
  4041.                         );
  4042.                       }
  4043.                     }
  4044.                   }
  4045.                   return $this->redirectToRoute('viewOrder', array('orderNo' => $cart->getOrderNo(), 'freshSale' => true));
  4046.               } else {
  4047.                 
  4048.                   $this->addFlash('error''Le paiement a echoué. Veuillez vérifier que votre carte est valide ou notre support.');
  4049.                   return $this->redirectToRoute('cartPayment');
  4050.               }
  4051.            }
  4052.       }
  4053.       // We set the coupon if users has a valid one
  4054.           $couponMarketing$this->session->get('coupon_marketing');
  4055.           $twigData['couponMarketing']=false;
  4056.           if($couponMarketing){
  4057.             $cartCoupon $em->getRepository(CartCoupon::class)->findOneValidByCode($couponMarketing);
  4058.             if(!empty($cartCoupon)){
  4059.               $twigData['couponMaketing']=$cartCoupon;
  4060.             }
  4061.           }
  4062.           $userCouponList=[];
  4063.           $tempCouponLists$em->getRepository(CartCoupon::class)->findAllUserCoupons($userServ->getUser()->getId());
  4064.           // we only get not used coupon by the user
  4065.           foreach ($tempCouponLists as $cartCoupon ) {
  4066.             if($cartCoupon->getOneTimeOnly()){
  4067.               if($cartCoupon->getUsedByUsers()->contains($userServ->getUser()))
  4068.                   continue;
  4069.               else
  4070.                 array_push($userCouponList,$cartCoupon);
  4071.             }else
  4072.               array_push($userCouponList,$cartCoupon);
  4073.           }
  4074.           $twigData['couponLists'] = $userCouponList;
  4075.         
  4076.       return $twigData;
  4077.     }else{
  4078.       $this->addFlash('warning''Vous devez ajouter des produits');
  4079.       return $this->redirectToRoute('NewViewCart');
  4080.     }
  4081.      
  4082.   }
  4083. }