src/Manager/CartManager.php line 123

Open in your IDE?
  1. <?php
  2. namespace App\Manager;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use App\Entity\Cart;
  5. use App\Service\Mailer;
  6. use App\Manager\CustomerManager;
  7. use App\Entity\Product;
  8. use App\Entity\Coupon;
  9. class CartManager {
  10.     
  11.     private $em;
  12.     private $mailer;
  13.     private $customerMgr;
  14.     private $priceMgr;
  15.     private $session;
  16.     private $translator;
  17.     public function __construct(\Symfony\Component\HttpFoundation\Session\SessionInterface $sessionEntityManagerInterface $emMailer $mailerCustomerManager $customerMgr, \Symfony\Contracts\Translation\TranslatorInterface $translator)
  18.     {
  19.         $this->em $em;
  20.         $this->mailer $mailer;
  21.         $this->customerMgr $customerMgr;
  22.         $this->session $session;
  23.         $this->translator $translator;
  24.     }
  25.     
  26.     public function getCustomer()
  27.     {
  28.         return $this->customerMgr->getCustomer();
  29.     }
  30.     
  31.     public function isExpert()
  32.     {
  33.         return $this->customerMgr->isExpert();
  34.     }
  35.     
  36.     public function getPriceContext()
  37.     {
  38.         return $this->customerMgr->getPriceContext();
  39.     }
  40.     
  41.     public function getCartByCustomerId($cid)
  42.     {
  43.         $customer $this->em->getRepository('App:Customer')->find($cid);
  44.         if($customer){
  45.             return $this->getCartByCustomer($customer);
  46.         }
  47.         return null;
  48.     }
  49.     
  50.     public function getCartByCustomer($customer)
  51.     {
  52.         return $this->em->getRepository('App:Cart')->findOneByCustomer($customer);
  53.     }
  54.     
  55.     public function remindCustomer(Cart $cart)
  56.     {
  57.         $this->markCartAsReminded($cart);
  58.         return $this->mailer->remindCart($cart);
  59.     }
  60.     
  61.     protected function markCartAsReminded(Cart $cart)
  62.     {
  63. //        $items = $cart->getItems();
  64. //        if(!empty($items)){
  65. //            foreach ($items as $item){
  66. //                $item->setReminded(new \DateTime);
  67. //                $this->em->persist($item);
  68. //            }
  69. //            $this->em->flush();
  70. //        }
  71.         return true;
  72.     }
  73.     
  74.     public function getLastUnremindedCarts()
  75.     {
  76.         $carts = [];
  77.         $customerIds $this->getLastUnremindedCustomerIds();
  78.         if(!empty($customerIds)){
  79.             foreach ($customerIds as $cid){
  80.                 $cart $this->getCartByCustomerId($cid);
  81.                 if($cart)
  82.                     $carts[] = $cart;
  83.             }
  84.         }
  85.         return $carts;
  86.     }
  87.     
  88.     public function getLastUnremindedCustomerIds() {
  89.         $yesterday = new \DateTime();
  90.         $yesterday->modify('-1 day');
  91.         $conn $this->em->getConnection();
  92.         $stmt $conn->prepare('SELECT distinct(customers_id) FROM customers_basket where customers_basket_reminded is null and `customers_basket_date_added`=\''.$yesterday->format('Ymd').'\'');
  93.         $stmt->execute();
  94.         $customerIds = [];
  95.         $lines $stmt->fetchAll();
  96.         foreach($lines as $row){
  97.             $customerIds[] = $row['customers_id'];
  98.         }
  99.         return $customerIds;
  100.     }
  101.     
  102.     public function getLastCarts($sinceNbDays=180) {
  103.         $yesterday = new \DateTime();
  104.         $yesterday->modify('-'.$sinceNbDays.' day');
  105.         $conn $this->em->getConnection();
  106.         $stmt $conn->prepare('SELECT distinct(customers_id) FROM customers_basket where `customers_basket_date_added`>=\''.$yesterday->format('Ymd').'\'');
  107.         $stmt->execute();
  108.         $carts = [];
  109.         $lines $stmt->fetchAll();
  110.         foreach($lines as $row){
  111.             $cart $this->getCartByCustomerId($row['customers_id']);
  112.             if($cart)
  113.                 $carts[] = $cart;
  114.         }
  115.         return $carts;
  116.     }
  117.     public function getCartSession()
  118.     {
  119.         return $this->session->get('cart',$this->getEmptyCart());
  120.     }
  121.     
  122.     private function getEmptyCart()
  123.     {
  124.         return ['products'=>[],'id'=>null,'createdAt'=>(new \DateTime())->format('Y-m-d H:i:s'),'updatedAt'=>'0000-00-00 00:00:00''coupons'=>[]];
  125.     }
  126.     
  127.     public function getGifts()
  128.     {
  129.         return $this->em->getRepository('App:Product')->getGifts();
  130.     }
  131.     
  132.     public function fillCartFromSession(&$cart)
  133.     {
  134.         $cart->setItems([]);
  135.         $cartSession $this->getCartSession();
  136.         if(empty($cartSession['products']))
  137.             return;
  138.         foreach($cartSession['products'] as $item){
  139.             $product $this->em->getRepository('App:Product')->find($item['product']['id']);
  140.             if(!empty($product))
  141.                 $cart->addItem(
  142.                     $product,
  143.                     $item['qty']
  144.                 );
  145.         }
  146.     }
  147.     
  148.     public function getCart($reload=false) : Cart
  149.     {
  150.         $customer $this->customerMgr->getCustomer();
  151.         $cartSession $this->getCartSession();
  152.         $cart null;
  153.         $fillFromSession false;
  154.         $priceGroup $this->customerMgr->getPriceContext();
  155.         if($customer){
  156.             $cart $this->em->getRepository('App:Cart')->findOneBy([
  157.                 'customer' => $customer->getId(),
  158.                 'priceGroup' => $priceGroup,
  159.             ]);
  160.             if($cart)
  161.                 $cart->setCustomer($customer);
  162.         }else if(!empty($cartSession['id'])){
  163.             $cart $this->em->getRepository('App:Cart')->find($cartSession['id']);
  164.         }
  165.         if(empty($cart)){
  166.             $cart = new Cart();
  167.             $cart->setPriceGroup($priceGroup);
  168.             if($customer){
  169.                 $cart->setCustomer($customer);
  170.             }
  171.         }
  172.         if(!isset($cartSession['coupons'])){
  173.             $cartSession['coupons'] = [];
  174.         }
  175.         foreach($cartSession['coupons'] as $c){
  176.             $coupon $this->em->getRepository(\App\Entity\Coupon::class)->find($c['id']);
  177.             if(!empty($coupon))
  178.                 $cart->addCoupon($coupon);
  179.         }
  180.         $this->cart $cart;
  181.         return $this->cart;
  182.     }
  183.     public function add(Product $product,$qty,$actionType=null,$genericProductId=null,$categoryId=null,$force=false)
  184.     {
  185.         if(!$this->customerMgr->isLogged()){
  186.             return [
  187.                 'success'=>false,
  188.                 'error'=>'',
  189.                 'requestQty'=>$qty,
  190.                 'totalQty'=>$qty
  191.             ];
  192.         }
  193.         $cart $this->getCart();
  194.         if($cart->hasProduct($product)){
  195.             $qtyUpdate $cart->getItemQuantityByProduct($product)+$qty;
  196.             if($qtyUpdate<=0){
  197.                 return $this->remove($product);
  198.             }
  199.             return $this->update($product$qtyUpdate);
  200.         }
  201.         if($product->isGift()){
  202.             $qty 1;
  203.         }
  204.         $cart->addItem($product,$qty);
  205.         $checkQuantity $this->checkQuantityForProduct($product$qty$force);
  206.         if($checkQuantity === true){
  207.             return $this->save($cart);
  208.         }else{
  209.             return [
  210.                 'success'=>false,
  211.                 'error'=>$checkQuantity,
  212.                 'requestQty'=>$qty,
  213.                 'totalQty'=>$qty
  214.             ];
  215.         }
  216.         return [
  217.             'success'=>false,
  218.             'error'=>'',
  219.             'requestQty'=>$qty,
  220.             'totalQty'=>$qty
  221.         ];
  222.     }
  223.     
  224.     public function update(Product $product,$qty)
  225.     {
  226.         $cart $this->getCart();
  227.         if(empty($cart)){
  228.             $cart = [];
  229.         }
  230.         if(!$cart->hasProduct($product)){
  231.             return $this->add($product$qtynullnullnull$force);
  232.         }
  233.         if($qty<=0){
  234.             return $this->remove($product);
  235.         }
  236.         if($product->isGift()){
  237.             $qty 1;
  238.         }
  239.         $cart->updateItem($product,$qty);
  240.         $cart $this->save($cart);
  241.         return $cart;
  242.     }
  243.     
  244.     public function qtyInCart(Product $product)
  245.     {
  246.         $cart $this->getCart();
  247.         if(empty($cart))
  248.             return 0;
  249.         return $cart->getItemQuantityByProduct($product);
  250.     }
  251.     
  252.     public function setAddress(\App\Entity\Address $address$type) {
  253.         $cart $this->getCart();
  254.         if($type == 'shipping'){
  255.             $cart->setShippingAddress($address);
  256.         }else if($type == 'billing'){
  257.             $cart->setBillingAddress($address);
  258.         }else{
  259.             throw new \Exception("Type d'adresse inconnu (".$type.")");
  260.         }
  261.         return $this->save($cart);
  262.     }
  263.     
  264.     public function setCarrier(\App\Entity\Carrier $carrier) {
  265.         $cart $this->getCart();
  266.         $cart->setCarrier($carrier);
  267.         return $this->save($cart);
  268.     }
  269.     
  270.     public function checkQuantityForProduct(Product $product$qty$force){
  271.         return $product->getQuantity()>=$qty;
  272.     }
  273.     
  274.     public function checkCartDisponibility(Cart $cart) {
  275. //        $output = [
  276. //            'products' => [],
  277. //            'message' => ''
  278. //        ];
  279. //        foreach($cart->getItems() as $item){
  280. //            $product = $item->getProduct();
  281. //            if(!$item->getProduct()->isAvailable()){
  282. //                $cart->removeItem($product);
  283. //                $output['products'][] = $product;
  284. //            }
  285. //        }
  286. //        if(!empty($output['products'])){
  287. //            $this->save($cart);
  288. //            return false;
  289. //        }
  290.         return true;
  291.     }
  292.     
  293.     public function remove(Product $product)
  294.     {
  295.         $cart $this->getCart();
  296.         if(empty($cart)){
  297.             return false;
  298.         }
  299.         $item $cart->getItemByProduct($product);
  300.         if($item){
  301.             $this->em->remove($item);
  302.             $this->em->flush();
  303.             $cart $this->save($cart);
  304.         }
  305.         return $this->save($cart);
  306.     }
  307.     
  308.     public function empty()
  309.     {
  310.         $cart $this->getCart();
  311.         $this->em->remove($cart);
  312.         $this->em->flush();
  313.         $this->session->remove('cart');
  314.     }
  315.             
  316.     public function save(Cart $cart)
  317.     {
  318.         $customer $this->customerMgr->getCustomer();
  319.         $cartId $cart->getId();
  320.         $items $cart->getItems();
  321.         if($customer){
  322.             if(empty($cartId))
  323.                 $cart->setCustomer($customer);
  324.         }
  325.         if(empty($items)){
  326.             $this->em->remove($cart);
  327.         }else{
  328.             $this->em->persist($cart);
  329.         }
  330.         $this->em->flush();
  331.         $this->session->set('cart',$cart->toArray());
  332.         $this->cart $cart;
  333.         return $this->cart;
  334.     }
  335.     
  336.     public function assignCartToCustomer($cartIdCustomer $customer)
  337.     {
  338.         // utilisation d'une requête SQL pour empecher l'ecrasement de la date de mise à jour.
  339.         $conn $this->em->getConnection();
  340.         $conn->executeQuery("update Cart set CustomerId=".$customer->getId()." where Id=:id",['id'=>$cartId]);
  341.     }
  342.     
  343.     
  344.     public function checkCartItems(Cart $cart) {
  345.         // Available
  346.         $refs = [];
  347.         foreach($cart->getItems() as $item){
  348.             $product $item->getProduct();
  349.             if(!$item->getProduct()->isAvailable() || $item->getProduct()->isStopped()){
  350.                 $cart->removeItem($product);
  351.                 $refs[] = $product->getReference();
  352.             }
  353.         }
  354.         if(!empty($refs)){
  355.             $this->session->getFlashBag()->add('error'$this->translator->trans('Les articles suivants ne sont plus disponibles à la vente : ') . ' ' implode(', ',$refs));
  356.             $this->save($cart);
  357.             return false;
  358.         }
  359.         $refs = [];
  360.         foreach($cart->getItems() as $item){
  361.             $product $item->getProduct();
  362.             if($item->getProduct()->getQuantity() < $item->getQuantity()){
  363.                 $refs[] = $product->getReference();
  364.             }
  365.         }
  366.         if(!empty($refs)){
  367.             $this->session->getFlashBag()->add('error'$this->translator->trans('La quantité demandée pour les articles suivants n\'est pas disponible  : ') . ' ' implode(', ',$refs));
  368.             $this->save($cart);
  369.             return false;
  370.         }
  371.         $refs = [];
  372.         $country $this->customerMgr->getCustomerCountry();
  373.         foreach($cart->getItems() as $item){
  374.             $product $item->getProduct();
  375.             if(!$item->getProduct()->isAvailableForCountry($country)){
  376.                 $cart->removeItem($product);
  377.                 $refs[] = $product->getReference();
  378.             }
  379.         }
  380.         if(!empty($refs)){
  381.             $this->session->getFlashBag()->add('error'$this->translator->trans('Les articles suivants ne sont pas disponibles à la vente pour votre zone géographique : ') . ' ' implode(', ',$refs));
  382.             $this->save($cart);
  383.             return false;
  384.         }
  385.         return true;
  386.     }
  387.     
  388.     public function checkShippingRate(Cart $cart) {
  389.         
  390.         $shippingRate $cart->getShippingRate();
  391.         return empty($shippingRate) ? false true;
  392.     }
  393.     
  394.     public function checkDropShipping(Cart $cart) {
  395.         if($cart->getCarrier()->getCode() != 'dropshipping')
  396.             return true;
  397.         return $cart->getBillingAddress()->getId() != $cart->getShippingAddress()->getId();
  398.     }
  399.     
  400.     public function addCoupon(Coupon $coupon) {
  401.         $cart $this->getCart();
  402.         $result $cart->addCoupon($coupon);
  403.         if($result === true){
  404.             return $this->save($cart);
  405.         }
  406.         return $result;
  407.     }
  408.     
  409. }