src/Controller/CartB2CController.php line 98

Open in your IDE?
  1. <?php
  2. /**
  3.  * Pimcore
  4.  *
  5.  * This source file is available under two different licenses:
  6.  * - GNU General Public License version 3 (GPLv3)
  7.  * - Pimcore Enterprise License (PEL)
  8.  * Full copyright and license information is available in
  9.  * LICENSE.md which is distributed with this source code.
  10.  *
  11.  *  @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  12.  *  @license    http://www.pimcore.org/license     GPLv3 and PEL
  13.  */
  14. namespace App\Controller;
  15. use App\Model\Product\AbstractProduct;
  16. use App\Website\Navigation\BreadcrumbHelperService;
  17. use Pimcore\Bundle\EcommerceFrameworkBundle\CartManager\CartInterface;
  18. use Pimcore\Bundle\EcommerceFrameworkBundle\Exception\VoucherServiceException;
  19. use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
  20. use Pimcore\Bundle\EcommerceFrameworkBundle\Model\CheckoutableInterface;
  21. use Pimcore\Bundle\EcommerceFrameworkBundle\Model\ProductInterface;
  22. use Pimcore\Controller\FrontendController;
  23. use App\Controller\BaseB2CController;
  24. use Pimcore\Translation\Translator;
  25. use Symfony\Component\HttpFoundation\RedirectResponse;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\Routing\Annotation\Route;
  29. use Symfony\Component\HttpFoundation\JsonResponse;
  30. use Pimcore\Model\DataObject;
  31. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  32. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  33. use FrontendPermissionToolkitBundle\Service;
  34. use Symfony\Component\Security\Core\User\UserInterface;
  35. use App\Form\LoginFormType;
  36. class CartB2CController extends BaseB2CController
  37. {
  38.     const DEFAULT_CART_NAME 'cart_b2c';
  39.     /**
  40.      * @var Factory
  41.      */
  42.     protected $factory;
  43.     protected $service;
  44.     private $session;
  45.     public function __construct(Factory $factory,EventDispatcherInterface $eventDispatcher,UserInterface $user null,SessionInterface $session)
  46.     {        
  47.         $this->factory $factory
  48.         $this->service = new Service($eventDispatcher);
  49.         $this->session $session;
  50.     }
  51.     /**
  52.      * @return CartInterface
  53.      */
  54.     protected function getCart()
  55.     {
  56.         $cartManager $this->factory->getCartManager();
  57.         //p_r(session_id());
  58.         return $cartManager->getOrCreateCartByName(self::DEFAULT_CART_NAME);
  59.     }
  60.     /**
  61.      * @Route("/b2c/cart/remove", name="b2c-shop-remove-cart")
  62.      *
  63.      * @param Request $request
  64.      * @param Factory $ecommerceFactory
  65.      *
  66.      * @return RedirectResponse
  67.      *
  68.      * @throws \Exception
  69.      */
  70.     public function removeCartAction(Request $request)
  71.     {
  72.         $cart $this->getCart();
  73.         $cart->delete();
  74.         //p_r(get_class_methods($cart));exit;
  75.         return $this->redirectToRoute('b2c-shop-cart-detail');
  76.     }
  77.     /**
  78.      * @Route("/b2c/cart/add-to-cart", name="b2c-shop-add-to-cart")
  79.      *
  80.      * @param Request $request
  81.      * @param Factory $ecommerceFactory
  82.      *
  83.      * @return RedirectResponse
  84.      *
  85.      * @throws \Exception
  86.      */
  87.     public function addToCartAction(Request $requestFactory $ecommerceFactoryUserInterface $user null)
  88.     {
  89.         $result = [];
  90.         $itemsInCart = [];
  91.         $id $request->get('id');
  92.         $qty $request->get('qty',1);
  93.         $addProduct AbstractProduct::getById($id);
  94.         if (null === $addProduct) {
  95.             throw new \Exception('Product not found');
  96.         }           
  97.         $cart $this->getCart();
  98.         $items $cart->getItems();
  99.         $isAvailable false;
  100.         if($items){            
  101.             foreach ($items as $item) {                
  102.                 $product $item->getProduct();                
  103.                 if ($product->getId() == $addProduct->getId()) {
  104.                     $isAvailable=true;                                    
  105.                     $cart->updateItem($addProduct->getId(), $product$qtytrue);
  106.                 }
  107.             }            
  108.         }  
  109.         if($isAvailable == false){
  110.             $cart->addItem($addProduct$qty);
  111.         }  
  112.        // p_r($cart);exit;
  113.         $cart->save(); 
  114.                
  115.         
  116.         if($user == null){
  117.             $this->storeCartInSessions();
  118.         }        
  119.         // $trackingManager = $ecommerceFactory->getTrackingManager();
  120.         // $trackingManager->trackCartProductActionAdd($cart, $addProduct);
  121.         // $trackingManager->forwardTrackedCodesAsFlashMessage();        
  122.        
  123.         $result['success'] = true;
  124.         $result['totalCount'] = count($cart->getItems());
  125.         $response = new JsonResponse($result);
  126.         return $response;       
  127.     }
  128.     /**
  129.      * @Route("/b2c/cart", name="b2c-shop-cart-detail")
  130.      *
  131.      * @param Request $request
  132.      * @param BreadcrumbHelperService $breadcrumbHelperService
  133.      * @param Factory $ecommerceFactory
  134.      *
  135.      * @return Response
  136.      */
  137.     public function cartListingAction(Request $requestBreadcrumbHelperService $breadcrumbHelperServiceFactory $ecommerceFactory,SessionInterface $sessionUserInterface $user null)
  138.     {       
  139.         $orderType "";
  140.                
  141.         $cart $this->getCart();        
  142.        
  143.         $userObject $user
  144.         
  145.         $branch = ($user)?$user->getPartner():null;
  146.         //$hqBranch = \Pimcore\Model\DataObject\Partners::getByCustSupp(346,true);        
  147.         if ($request->getMethod() == Request::METHOD_POST) {
  148.             $items $request->get('items');
  149.             foreach ($items as $itemKey => $quantity) {
  150.                 $product AbstractProduct::getById($itemKey);
  151.                 if ($product instanceof CheckoutableInterface) {
  152.                     $cart->updateItem($itemKey$product$quantitytrue);
  153.                 }
  154.             }
  155.             $cart->save();
  156.             $trackingManager $ecommerceFactory->getTrackingManager();
  157.             $trackingManager->trackCartUpdate($cart);
  158.         }
  159.        if($cart->getCheckoutData('destinationBranch')){
  160.             $destinationBRanch unserialize($cart->getCheckoutData('destinationBranch'));                  
  161.             $orderType $cart->getCheckoutData('orderType');            
  162.         }
  163.         $breadcrumbHelperService->enrichCartPage();
  164.         $params array_merge($request->request->all(), $request->query->all());
  165.         $formData = [];
  166.         $error = [];
  167.         $form $this->createForm(LoginFormType::class, $formData, [
  168.             'action' => $this->generateUrl('account-login'),
  169.         ]);
  170.         //store referer in session to get redirected after login
  171.         if (!$request->get('no-referer-redirect')) {
  172.             $session->set('_security.demo_frontend.target_path'$request->headers->get('referer'));
  173.         }                   
  174.         
  175.         if ($cart->isEmpty()) {
  176.             return $this->render('cart_b2c/cart_empty.html.twig'array_merge($params, ['cart' => $cart]));
  177.         } else {
  178.             return $this->render('cart_b2c/cart_listing_updated.html.twig'array_merge($params, ['cart' => $cart,'branch'=>$branch,'form' => $form->createView(),'error' => $error]));
  179.         }
  180.     }
  181.     /**
  182.      * @Route("/b2c/cart/remove-from-cart", name="b2c-shop-remove-from-cart")
  183.      *
  184.      * @param Request $request
  185.      * @param Factory $ecommerceFactory
  186.      *
  187.      * @return RedirectResponse
  188.      */
  189.     public function removeFromCartAction(Request $requestFactory $ecommerceFactory)
  190.     {
  191.         $id $request->get('id');
  192.         $checkout $request->get('checkout',false);
  193.         $product AbstractProduct::getById($id);
  194.      
  195.         $cart $this->getCart();
  196.         $cart->removeItem($id);
  197.         $cart->save();
  198.         
  199.         $this->storeCartInSessions();
  200.         if ($product instanceof ProductInterface) {
  201.             $trackingManager $ecommerceFactory->getTrackingManager();
  202.             $trackingManager->trackCartProductActionRemove($cart$product);
  203.             $trackingManager->forwardTrackedCodesAsFlashMessage();
  204.         }
  205.         if($checkout){            
  206.             return $this->redirectToRoute('b2c-shop-checkout-completed');
  207.         }else{
  208.             return $this->redirectToRoute('b2c-shop-cart-detail');
  209.         }
  210.     }
  211.     /**
  212.      * @Route("/b2c/cart/apply-voucher", name="b2c-shop-cart-apply-voucher")
  213.      *
  214.      * @param Request $request
  215.      * @param Translator $translator
  216.      * @param Factory $ecommerceFactory
  217.      *
  218.      * @return RedirectResponse
  219.      *
  220.      * @throws \Exception
  221.      */
  222.     public function applyVoucherAction(Request $requestTranslator $translatorFactory $ecommerceFactory)
  223.     {
  224.         if ($token strip_tags($request->get('voucher-code'))) {
  225.             $cart $this->getCart();
  226.             try {
  227.                 $success $cart->addVoucherToken($token);
  228.                 if ($success) {
  229.                     $this->addFlash('success'$translator->trans('cart.voucher-code-added'));
  230.                     $trackingManager $ecommerceFactory->getTrackingManager();
  231.                     $trackingManager->trackCartUpdate($cart);
  232.                 } else {
  233.                     $this->addFlash('danger'$translator->trans('cart.voucher-code-could-not-be-added'));
  234.                 }
  235.             } catch (VoucherServiceException $e) {
  236.                 $this->addFlash('danger'$translator->trans('cart.error-voucher-code-' $e->getCode()));
  237.             }
  238.         } else {
  239.             $this->addFlash('danger'$translator->trans('cart.empty-voucher-code'));
  240.         }
  241.         return $this->redirectToRoute('b2c-shop-cart-detail');
  242.     }
  243.     /**
  244.      * @Route("/b2c/cart/remove-voucher", name="b2c-shop-cart-remove-voucher")
  245.      *
  246.      * @param Request $request
  247.      * @param Translator $translator
  248.      * @param Factory $ecommerceFactory
  249.      *
  250.      * @return RedirectResponse
  251.      */
  252.     public function removeVoucherAction(Request $requestTranslator $translatorFactory $ecommerceFactory)
  253.     {
  254.         if ($token strip_tags($request->get('voucher-code'))) {
  255.             $cart $this->getCart();
  256.             try {
  257.                 $cart->removeVoucherToken($token);
  258.                 $this->addFlash('success'$translator->trans('cart.voucher-code-removed'));
  259.                 $trackingManager $ecommerceFactory->getTrackingManager();
  260.                 $trackingManager->trackCartUpdate($cart);
  261.             } catch (VoucherServiceException $e) {
  262.                 $this->addFlash('danger'$translator->trans('cart.error-voucher-code-' $e->getCode()));
  263.             }
  264.         } else {
  265.             $this->addFlash('danger'$translator->trans('cart.empty-voucher-code'));
  266.         }
  267.         return $this->redirectToRoute('b2c-shop-cart-detail');
  268.     }
  269.     private function checkPermission(){
  270.         $userObject \Pimcore::getContainer()->get('security.token_storage')->getToken()->getUser();  
  271.         $allow false;            
  272.         if($userObject){
  273.             if($this->service->isAllowed($userObject"draft_create") || $this->service->isAllowed($userObject"booking_create") || $this->service->isAllowed($userObject"order_create")) {
  274.                 $allow true;   
  275.             }
  276.         }
  277.         return $allow;
  278.     }
  279.     public function retainCartFromSessions(){
  280.         $cart $this->getCart();
  281.         $items $cart->getItems();
  282.         $itemsInCart = ($this->session->get('current_cart'))?$this->session->get('current_cart'):[]; 
  283.                
  284.         if(!empty($itemsInCart)){
  285.                        
  286.             // if(!empty($items)){
  287.             //     foreach($items as $item){
  288.             //         $cart->addItem($item->getProduct(), $item->getCount());
  289.             //     }
  290.             // }
  291.             
  292.             foreach($itemsInCart as $item){
  293.                 $addProduct $item['product'];              
  294.                 $cart->addItem($addProduct$item['qty']);
  295.             }
  296.             $cart->save();
  297.             $this->session->set('current_cart',[]); 
  298.         } 
  299.     }
  300.     private function storeCartInSessions(){
  301.         $itemsInCart = [];
  302.         $cart $this->getCart();
  303.         $items=$cart->getItems();
  304.         if(!empty($items)){
  305.             foreach($items as $item){
  306.                 $addProduct $item->getProduct();
  307.                 $itemsInCart[$addProduct->getId()]['product'] = $addProduct;
  308.                 //p_r($item);exit;
  309.                 $itemsInCart[$addProduct->getId()]['qty'] = $item->getCount(); 
  310.             }
  311.         }
  312.         $this->session->set('current_cart',$itemsInCart); 
  313.     }
  314. }