<?php
/**
* Pimcore
*
* This source file is available under two different licenses:
* - GNU General Public License version 3 (GPLv3)
* - Pimcore Enterprise License (PEL)
* Full copyright and license information is available in
* LICENSE.md which is distributed with this source code.
*
* @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license GPLv3 and PEL
*/
namespace App\Controller;
use App\Model\Product\AbstractProduct;
use App\Website\Navigation\BreadcrumbHelperService;
use Pimcore\Bundle\EcommerceFrameworkBundle\CartManager\CartInterface;
use Pimcore\Bundle\EcommerceFrameworkBundle\Exception\VoucherServiceException;
use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
use Pimcore\Bundle\EcommerceFrameworkBundle\Model\CheckoutableInterface;
use Pimcore\Bundle\EcommerceFrameworkBundle\Model\ProductInterface;
use Pimcore\Controller\FrontendController;
use App\Controller\BaseB2CController;
use Pimcore\Translation\Translator;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Pimcore\Model\DataObject;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use FrontendPermissionToolkitBundle\Service;
use Symfony\Component\Security\Core\User\UserInterface;
use App\Form\LoginFormType;
class CartB2CController extends BaseB2CController
{
const DEFAULT_CART_NAME = 'cart_b2c';
/**
* @var Factory
*/
protected $factory;
protected $service;
private $session;
public function __construct(Factory $factory,EventDispatcherInterface $eventDispatcher,UserInterface $user = null,SessionInterface $session)
{
$this->factory = $factory;
$this->service = new Service($eventDispatcher);
$this->session = $session;
}
/**
* @return CartInterface
*/
protected function getCart()
{
$cartManager = $this->factory->getCartManager();
//p_r(session_id());
return $cartManager->getOrCreateCartByName(self::DEFAULT_CART_NAME);
}
/**
* @Route("/b2c/cart/remove", name="b2c-shop-remove-cart")
*
* @param Request $request
* @param Factory $ecommerceFactory
*
* @return RedirectResponse
*
* @throws \Exception
*/
public function removeCartAction(Request $request)
{
$cart = $this->getCart();
$cart->delete();
//p_r(get_class_methods($cart));exit;
return $this->redirectToRoute('b2c-shop-cart-detail');
}
/**
* @Route("/b2c/cart/add-to-cart", name="b2c-shop-add-to-cart")
*
* @param Request $request
* @param Factory $ecommerceFactory
*
* @return RedirectResponse
*
* @throws \Exception
*/
public function addToCartAction(Request $request, Factory $ecommerceFactory, UserInterface $user = null)
{
$result = [];
$itemsInCart = [];
$id = $request->get('id');
$qty = $request->get('qty',1);
$addProduct = AbstractProduct::getById($id);
if (null === $addProduct) {
throw new \Exception('Product not found');
}
$cart = $this->getCart();
$items = $cart->getItems();
$isAvailable = false;
if($items){
foreach ($items as $item) {
$product = $item->getProduct();
if ($product->getId() == $addProduct->getId()) {
$isAvailable=true;
$cart->updateItem($addProduct->getId(), $product, $qty, true);
}
}
}
if($isAvailable == false){
$cart->addItem($addProduct, $qty);
}
// p_r($cart);exit;
$cart->save();
if($user == null){
$this->storeCartInSessions();
}
// $trackingManager = $ecommerceFactory->getTrackingManager();
// $trackingManager->trackCartProductActionAdd($cart, $addProduct);
// $trackingManager->forwardTrackedCodesAsFlashMessage();
$result['success'] = true;
$result['totalCount'] = count($cart->getItems());
$response = new JsonResponse($result);
return $response;
}
/**
* @Route("/b2c/cart", name="b2c-shop-cart-detail")
*
* @param Request $request
* @param BreadcrumbHelperService $breadcrumbHelperService
* @param Factory $ecommerceFactory
*
* @return Response
*/
public function cartListingAction(Request $request, BreadcrumbHelperService $breadcrumbHelperService, Factory $ecommerceFactory,SessionInterface $session, UserInterface $user = null)
{
$orderType = "";
$cart = $this->getCart();
$userObject = $user;
$branch = ($user)?$user->getPartner():null;
//$hqBranch = \Pimcore\Model\DataObject\Partners::getByCustSupp(346,true);
if ($request->getMethod() == Request::METHOD_POST) {
$items = $request->get('items');
foreach ($items as $itemKey => $quantity) {
$product = AbstractProduct::getById($itemKey);
if ($product instanceof CheckoutableInterface) {
$cart->updateItem($itemKey, $product, $quantity, true);
}
}
$cart->save();
$trackingManager = $ecommerceFactory->getTrackingManager();
$trackingManager->trackCartUpdate($cart);
}
if($cart->getCheckoutData('destinationBranch')){
$destinationBRanch = unserialize($cart->getCheckoutData('destinationBranch'));
$orderType = $cart->getCheckoutData('orderType');
}
$breadcrumbHelperService->enrichCartPage();
$params = array_merge($request->request->all(), $request->query->all());
$formData = [];
$error = [];
$form = $this->createForm(LoginFormType::class, $formData, [
'action' => $this->generateUrl('account-login'),
]);
//store referer in session to get redirected after login
if (!$request->get('no-referer-redirect')) {
$session->set('_security.demo_frontend.target_path', $request->headers->get('referer'));
}
if ($cart->isEmpty()) {
return $this->render('cart_b2c/cart_empty.html.twig', array_merge($params, ['cart' => $cart]));
} else {
return $this->render('cart_b2c/cart_listing_updated.html.twig', array_merge($params, ['cart' => $cart,'branch'=>$branch,'form' => $form->createView(),'error' => $error]));
}
}
/**
* @Route("/b2c/cart/remove-from-cart", name="b2c-shop-remove-from-cart")
*
* @param Request $request
* @param Factory $ecommerceFactory
*
* @return RedirectResponse
*/
public function removeFromCartAction(Request $request, Factory $ecommerceFactory)
{
$id = $request->get('id');
$checkout = $request->get('checkout',false);
$product = AbstractProduct::getById($id);
$cart = $this->getCart();
$cart->removeItem($id);
$cart->save();
$this->storeCartInSessions();
if ($product instanceof ProductInterface) {
$trackingManager = $ecommerceFactory->getTrackingManager();
$trackingManager->trackCartProductActionRemove($cart, $product);
$trackingManager->forwardTrackedCodesAsFlashMessage();
}
if($checkout){
return $this->redirectToRoute('b2c-shop-checkout-completed');
}else{
return $this->redirectToRoute('b2c-shop-cart-detail');
}
}
/**
* @Route("/b2c/cart/apply-voucher", name="b2c-shop-cart-apply-voucher")
*
* @param Request $request
* @param Translator $translator
* @param Factory $ecommerceFactory
*
* @return RedirectResponse
*
* @throws \Exception
*/
public function applyVoucherAction(Request $request, Translator $translator, Factory $ecommerceFactory)
{
if ($token = strip_tags($request->get('voucher-code'))) {
$cart = $this->getCart();
try {
$success = $cart->addVoucherToken($token);
if ($success) {
$this->addFlash('success', $translator->trans('cart.voucher-code-added'));
$trackingManager = $ecommerceFactory->getTrackingManager();
$trackingManager->trackCartUpdate($cart);
} else {
$this->addFlash('danger', $translator->trans('cart.voucher-code-could-not-be-added'));
}
} catch (VoucherServiceException $e) {
$this->addFlash('danger', $translator->trans('cart.error-voucher-code-' . $e->getCode()));
}
} else {
$this->addFlash('danger', $translator->trans('cart.empty-voucher-code'));
}
return $this->redirectToRoute('b2c-shop-cart-detail');
}
/**
* @Route("/b2c/cart/remove-voucher", name="b2c-shop-cart-remove-voucher")
*
* @param Request $request
* @param Translator $translator
* @param Factory $ecommerceFactory
*
* @return RedirectResponse
*/
public function removeVoucherAction(Request $request, Translator $translator, Factory $ecommerceFactory)
{
if ($token = strip_tags($request->get('voucher-code'))) {
$cart = $this->getCart();
try {
$cart->removeVoucherToken($token);
$this->addFlash('success', $translator->trans('cart.voucher-code-removed'));
$trackingManager = $ecommerceFactory->getTrackingManager();
$trackingManager->trackCartUpdate($cart);
} catch (VoucherServiceException $e) {
$this->addFlash('danger', $translator->trans('cart.error-voucher-code-' . $e->getCode()));
}
} else {
$this->addFlash('danger', $translator->trans('cart.empty-voucher-code'));
}
return $this->redirectToRoute('b2c-shop-cart-detail');
}
private function checkPermission(){
$userObject = \Pimcore::getContainer()->get('security.token_storage')->getToken()->getUser();
$allow = false;
if($userObject){
if($this->service->isAllowed($userObject, "draft_create") || $this->service->isAllowed($userObject, "booking_create") || $this->service->isAllowed($userObject, "order_create")) {
$allow = true;
}
}
return $allow;
}
public function retainCartFromSessions(){
$cart = $this->getCart();
$items = $cart->getItems();
$itemsInCart = ($this->session->get('current_cart'))?$this->session->get('current_cart'):[];
if(!empty($itemsInCart)){
// if(!empty($items)){
// foreach($items as $item){
// $cart->addItem($item->getProduct(), $item->getCount());
// }
// }
foreach($itemsInCart as $item){
$addProduct = $item['product'];
$cart->addItem($addProduct, $item['qty']);
}
$cart->save();
$this->session->set('current_cart',[]);
}
}
private function storeCartInSessions(){
$itemsInCart = [];
$cart = $this->getCart();
$items=$cart->getItems();
if(!empty($items)){
foreach($items as $item){
$addProduct = $item->getProduct();
$itemsInCart[$addProduct->getId()]['product'] = $addProduct;
//p_r($item);exit;
$itemsInCart[$addProduct->getId()]['qty'] = $item->getCount();
}
}
$this->session->set('current_cart',$itemsInCart);
}
}