src/Controller/CartController.php line 161

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\BaseController;
  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\Model\Utility;
  36. class CartController extends BaseController
  37. {
  38.     const DEFAULT_CART_NAME 'cart';
  39.     /**
  40.      * @var Factory
  41.      */
  42.     protected $factory;
  43.     protected $service;
  44.     public function __construct(Factory $factory,EventDispatcherInterface $eventDispatcher,UserInterface $user null)
  45.     {
  46.         $this->factory $factory;
  47.         $this->service = new Service($eventDispatcher);
  48.         if(!$this->checkPermission())
  49.         {
  50.             throw new \Exception("Permission denied");
  51.         }
  52.     }
  53.     /**
  54.      * @return CartInterface
  55.      */
  56.     protected function getCart()
  57.     {
  58.         $cartManager $this->factory->getCartManager();
  59.         return $cartManager->getOrCreateCartByName(self::DEFAULT_CART_NAME);
  60.     }
  61.     /**
  62.      * @Route("/cart/remove", name="shop-remove-cart")
  63.      *
  64.      * @param Request $request
  65.      * @param Factory $ecommerceFactory
  66.      *
  67.      * @return RedirectResponse
  68.      *
  69.      * @throws \Exception
  70.      */
  71.     public function removeCartAction(Request $request)
  72.     {
  73.         $cart $this->getCart();
  74.         $cart->delete();
  75.         //p_r(get_class_methods($cart));exit;
  76.         return $this->redirectToRoute('shop-cart-detail');
  77.     }
  78.     /**
  79.      * @Route("/cart/add-to-cart", name="shop-add-to-cart")
  80.      *
  81.      * @param Request $request
  82.      * @param Factory $ecommerceFactory
  83.      *
  84.      * @return RedirectResponse
  85.      *
  86.      * @throws \Exception
  87.      */
  88.     public function addToCartAction(Request $requestFactory $ecommerceFactory,UserInterface $user null)
  89.     {
  90.         if($user->getPartner()->getIsMecstoreHQ()){
  91.             throw new \Exception("Permission denied");
  92.         }
  93.         $result = [];
  94.         $id $request->get('id');
  95.         $addProduct AbstractProduct::getById($id);
  96.         $qty $request->get('qty',$addProduct->getMinimumSaleQty());
  97.         if (null === $addProduct) {
  98.             throw new \Exception('Product not found');
  99.         }
  100.         // if ($addProduct->getStockAvailability() < $qty) {
  101.         //     $result['success'] = false;
  102.         //     $result['totalCount'] = "You cannot add more than available stock";
  103.         //     $response = new JsonResponse($result);
  104.         //     return $response;
  105.         // }
  106.         $cart $this->getCart();
  107.         $items $cart->getItems();
  108.         $isAvailable false;
  109.         if($items){
  110.             foreach ($items as $item) {
  111.                 $product $item->getProduct();
  112.                 if ($product->getId() == $addProduct->getId()) {
  113.                     $isAvailable=true;
  114.                     $cart->updateItem($addProduct->getId(), $product$qtytrue);
  115.                 }
  116.             }
  117.         }
  118.         if($isAvailable == false){
  119.             $cart->addItem($addProduct$qty);
  120.         }
  121.         $cart->save();
  122.         // $trackingManager = $ecommerceFactory->getTrackingManager();
  123.         // $trackingManager->trackCartProductActionAdd($cart, $addProduct);
  124.         // $trackingManager->forwardTrackedCodesAsFlashMessage();
  125.         $result['success'] = true;
  126.         $result['totalCount'] = count($cart->getItems());
  127.         $response = new JsonResponse($result);
  128.         return $response;
  129.     }
  130.     /**
  131.      * @Route("/cart", name="shop-cart-detail")
  132.      *
  133.      * @param Request $request
  134.      * @param BreadcrumbHelperService $breadcrumbHelperService
  135.      * @param Factory $ecommerceFactory
  136.      *
  137.      * @return Response
  138.      */
  139.     public function cartListingAction(Request $requestBreadcrumbHelperService $breadcrumbHelperServiceFactory $ecommerceFactory,SessionInterface $sessionUserInterface $user null)
  140.     {
  141.         if($request->get('cartnamedraft')) {
  142.             $bozza \Pimcore\Model\DataObject::getById($request->get('cartnamedraft'));
  143.             if($bozza){
  144.                 $bozza->setHiddenOrder(false);
  145.                 $bozza->save();
  146.             }
  147.         }
  148.         $orderType "";
  149.         $cart $this->getCart();
  150.         $userObject $user;
  151.       //  p_r($userObject->getBranch()->getPartner());exit;
  152.         // Branches
  153.         $availableBranches $this->getBranches($session,$user);
  154.         if(empty($availableBranches))
  155.         {
  156.             throw new \Exception("Permission denied");
  157.         }
  158.       //  p_r($availableBranches);
  159.         // Branches
  160.         $branches = new DataObject\Partners\Listing();
  161.         $branches->setCondition('oo_id IN ('.implode(",",$availableBranches).')');
  162.         $branches $branches->load();
  163.         $customerAddresses = new DataObject\CustomerAddress\Listing();
  164.         $customerAddresses->setCondition('user__id = ?',[$user->getId()]);
  165.         $customerAddresses $customerAddresses->load();
  166.         $hqBranch \Pimcore\Model\DataObject\Partners::getByIsMecstoreHQ(1,true);
  167.         if ($request->getMethod() == Request::METHOD_POST) {
  168.             $items $request->get('items');
  169.             foreach ($items as $itemKey => $quantity) {
  170.                 $product AbstractProduct::getById($itemKey);
  171.                 if ($product instanceof CheckoutableInterface) {
  172.                     $cart->updateItem($itemKey$product$quantitytrue);
  173.                 }
  174.             }
  175.             $cart->save();
  176.             $trackingManager $ecommerceFactory->getTrackingManager();
  177.             $trackingManager->trackCartUpdate($cart);
  178.         }
  179.         $cartItems $cart->getItems();
  180.         $itemsForRecalculation = [];
  181.         if($cartItems){
  182.             foreach($cartItems as $cartItem){
  183.                 $itemsForRecalculation[] = $cartItem->getProduct()->getItem();
  184.             }
  185.         }
  186.         if($itemsForRecalculation){
  187.             $recalculatedCart Utility::getOrders($itemsForRecalculation,$user->getPartner()->getCustSupp());
  188.         }
  189.        if($cart->getCheckoutData('destinationBranch')){
  190.             $destinationBRanch unserialize($cart->getCheckoutData('destinationBranch'));
  191.             $orderType $cart->getCheckoutData('orderType');
  192.         }
  193.         $breadcrumbHelperService->enrichCartPage();
  194.         $params array_merge($request->request->all(), $request->query->all());
  195.         if ($cart->isEmpty()) {
  196.             return $this->render('cart/cart_empty.html.twig'array_merge($params, ['cart' => $cart,'orderType'=>$orderType,'session']));
  197.         } else {
  198.             return $this->render('cart/cart_listing.html.twig'array_merge($params, ['cart' => $cart,'orderType'=>$orderType,'branches'=>$branches,'hqBranch'=>$hqBranch,'addresses'=>$customerAddresses]));
  199.         }
  200.     }
  201.     /**
  202.      * @Route("/cart/remove-from-cart", name="shop-remove-from-cart")
  203.      *
  204.      * @param Request $request
  205.      * @param Factory $ecommerceFactory
  206.      *
  207.      * @return RedirectResponse
  208.      */
  209.     public function removeFromCartAction(Request $requestFactory $ecommerceFactory)
  210.     {
  211.         $id $request->get('id');
  212.         $checkout $request->get('checkout',false);
  213.         $product AbstractProduct::getById($id);
  214.         $cart $this->getCart();
  215.         $cart->removeItem($id);
  216.         $cart->save();
  217.         if ($product instanceof ProductInterface) {
  218.             $trackingManager $ecommerceFactory->getTrackingManager();
  219.             $trackingManager->trackCartProductActionRemove($cart$product);
  220.             $trackingManager->forwardTrackedCodesAsFlashMessage();
  221.         }
  222.         if($checkout){
  223.             return $this->redirectToRoute('shop-checkout-completed');
  224.         }else{
  225.             return $this->redirectToRoute('shop-cart-detail');
  226.         }
  227.     }
  228.     /**
  229.      * @Route("/cart/apply-voucher", name="shop-cart-apply-voucher")
  230.      *
  231.      * @param Request $request
  232.      * @param Translator $translator
  233.      * @param Factory $ecommerceFactory
  234.      *
  235.      * @return RedirectResponse
  236.      *
  237.      * @throws \Exception
  238.      */
  239.     public function applyVoucherAction(Request $requestTranslator $translatorFactory $ecommerceFactory)
  240.     {
  241.         if ($token strip_tags($request->get('voucher-code'))) {
  242.             $cart $this->getCart();
  243.             try {
  244.                 $success $cart->addVoucherToken($token);
  245.                 if ($success) {
  246.                     $this->addFlash('success'$translator->trans('cart.voucher-code-added'));
  247.                     $trackingManager $ecommerceFactory->getTrackingManager();
  248.                     $trackingManager->trackCartUpdate($cart);
  249.                 } else {
  250.                     $this->addFlash('danger'$translator->trans('cart.voucher-code-could-not-be-added'));
  251.                 }
  252.             } catch (VoucherServiceException $e) {
  253.                 $this->addFlash('danger'$translator->trans('cart.error-voucher-code-' $e->getCode()));
  254.             }
  255.         } else {
  256.             $this->addFlash('danger'$translator->trans('cart.empty-voucher-code'));
  257.         }
  258.         return $this->redirectToRoute('shop-cart-detail');
  259.     }
  260.     /**
  261.      * @Route("/cart/remove-voucher", name="shop-cart-remove-voucher")
  262.      *
  263.      * @param Request $request
  264.      * @param Translator $translator
  265.      * @param Factory $ecommerceFactory
  266.      *
  267.      * @return RedirectResponse
  268.      */
  269.     public function removeVoucherAction(Request $requestTranslator $translatorFactory $ecommerceFactory)
  270.     {
  271.         if ($token strip_tags($request->get('voucher-code'))) {
  272.             $cart $this->getCart();
  273.             try {
  274.                 $cart->removeVoucherToken($token);
  275.                 $this->addFlash('success'$translator->trans('cart.voucher-code-removed'));
  276.                 $trackingManager $ecommerceFactory->getTrackingManager();
  277.                 $trackingManager->trackCartUpdate($cart);
  278.             } catch (VoucherServiceException $e) {
  279.                 $this->addFlash('danger'$translator->trans('cart.error-voucher-code-' $e->getCode()));
  280.             }
  281.         } else {
  282.             $this->addFlash('danger'$translator->trans('cart.empty-voucher-code'));
  283.         }
  284.         return $this->redirectToRoute('shop-cart-detail');
  285.     }
  286.     private function checkPermission(){
  287.         $userObject \Pimcore::getContainer()->get('security.token_storage')->getToken()->getUser();
  288.         $allow false;
  289.         if($userObject){
  290.             if($this->service->isAllowed($userObject"draft_create") || $this->service->isAllowed($userObject"booking_create") || $this->service->isAllowed($userObject"order_create")) {
  291.                 $allow true;
  292.             }
  293.             if($userObject->getPartner()->getIsMecstoreHQ()){
  294.                 $allow false;
  295.             }
  296.         }
  297.         return $allow;
  298.     }
  299. }