src/Controller/Account/CartController.php line 67

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Account;
  3. use App\Form\Type\PaymentType;
  4. use App\Service\SquareDolpo\Tools as SquareTools;
  5. use CoreShop\Bundle\CoreBundle\Checkout\Step\CustomerAddressCheckoutStep;
  6. use CoreShop\Bundle\CoreBundle\Checkout\Step\CustomerCheckoutStep;
  7. use CoreShop\Bundle\CoreBundle\Checkout\Step\GuestAddressCheckoutStep;
  8. use CoreShop\Bundle\CoreBundle\Form\Type\GuestRegistrationType;
  9. use CoreShop\Bundle\CoreBundle\Form\Type\Order\PaymentType as RevisePaymentType;
  10. use CoreShop\Bundle\FrontendBundle\Controller\CartController as CoreShopCartController;
  11. use CoreShop\Bundle\FrontendBundle\TemplateConfigurator\TemplateConfiguratorInterface;
  12. use CoreShop\Bundle\OrderBundle\DTO\AddToCartInterface;
  13. use CoreShop\Bundle\OrderBundle\Factory\AddToCartFactoryInterface;
  14. use CoreShop\Bundle\OrderBundle\Form\Type\CartType;
  15. use CoreShop\Bundle\OrderBundle\Form\Type\ShippingCalculatorType;
  16. use CoreShop\Bundle\WorkflowBundle\Manager\StateMachineManagerInterface;
  17. use CoreShop\Component\Address\Model\AddressInterface;
  18. use CoreShop\Component\Core\Model\CustomerInterface;
  19. use CoreShop\Component\Core\Order\Modifier\CartItemQuantityModifier;
  20. use CoreShop\Component\Customer\Context\CustomerContextInterface;
  21. use CoreShop\Component\Order\Cart\CartModifierInterface;
  22. use CoreShop\Component\Order\Checkout\CheckoutException;
  23. use CoreShop\Component\Order\Checkout\CheckoutManagerFactoryInterface;
  24. use CoreShop\Component\Order\CheckoutEvents;
  25. use CoreShop\Component\Order\Context\CartContextInterface;
  26. use CoreShop\Component\Order\Event\CheckoutEvent;
  27. use CoreShop\Component\Order\InvoiceStates;
  28. use CoreShop\Component\Order\Manager\CartManagerInterface;
  29. use CoreShop\Component\Order\Model\OrderInterface;
  30. use CoreShop\Component\Order\Model\OrderItemInterface;
  31. use CoreShop\Component\Order\Model\PurchasableInterface;
  32. use CoreShop\Component\Order\OrderSaleTransitions;
  33. use CoreShop\Component\Order\Transformer\OrderDocumentTransformerInterface;
  34. use CoreShop\Component\Payment\Model\PaymentInterface;
  35. use CoreShop\Component\Payment\Repository\PaymentRepositoryInterface;
  36. use CoreShop\Component\Resource\Factory\FactoryInterface;
  37. use CoreShop\Component\Resource\Factory\PimcoreFactoryInterface;
  38. use CoreShop\Component\Shipping\Calculator\TaxedShippingCalculatorInterface;
  39. use CoreShop\Component\Shipping\Resolver\CarriersResolverInterface;
  40. use CoreShop\Component\Tracking\Tracker\TrackerInterface;
  41. use Pimcore;
  42. use Pimcore\Bundle\NumberSequenceGeneratorBundle\Generator;
  43. use Pimcore\Log\ApplicationLogger;
  44. use Pimcore\Model\DataObject\CoreShopOrder;
  45. use Pimcore\Model\DataObject\CoreShopOrderInvoice;
  46. use Pimcore\Model\DataObject\CoreShopOrderItem;
  47. use Pimcore\Model\DataObject\InventoryItem;
  48. use Pimcore\Model\DataObject\OnixProduct;
  49. use Pimcore\Model\DataObject\Service;
  50. use Symfony\Component\EventDispatcher\GenericEvent;
  51. use Symfony\Component\Form\ClickableInterface;
  52. use Symfony\Component\Form\FormFactoryInterface;
  53. use Symfony\Component\HttpFoundation\JsonResponse;
  54. use Symfony\Component\HttpFoundation\Request;
  55. use Symfony\Component\HttpFoundation\Response;
  56. use Symfony\Component\HttpFoundation\Session\Session;
  57. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  58. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  59. use App\Service\DolpoSupplyChainService;
  60. use Symfony\Component\Serializer\SerializerInterface;
  61. use Symfony\Component\Routing\Annotation\Route;
  62. use Webmozart\Assert\Assert;
  63. class CartController extends CoreShopCartController
  64. {
  65.     public function __construct(
  66.         public CartItemQuantityModifier $quantityModifer,
  67.         public AddToCartFactoryInterface $cartContext,
  68.         public TemplateConfiguratorInterface $templateConfigurator,
  69.         protected CustomerAddressCheckoutStep $customerAddressCheckoutStep,
  70.         protected GuestAddressCheckoutStep $guestAddressCheckoutStep,
  71.         protected CustomerCheckoutStep $customerCheckoutStep,
  72.         protected CheckoutManagerFactoryInterface $checkoutManagerFactory,
  73.         private FactoryInterface $customerFactory,
  74.         private string $websiteUrl,
  75.         private SerializerInterface $serializer,
  76.     ) {
  77.         $this->setTemplateConfigurator($templateConfigurator);
  78.     }
  79.     #[Route(path: '/panier/', name: 'basket')]
  80.     public function basketReactAction(Request $request): Response
  81.     {
  82.         // Remove from robots index
  83.         header('X-Robots-Tag: noindex, nofollow', true);
  84.         $cart = $this->getCart();
  85.         $normalizedCart = $this->serializer->normalize($cart, 'json', [
  86.             'groups' => ['cs_order', 'cs_order_item', 'onix_product', 'cs_address', 'cs_country'],
  87.         ]);
  88.         $customer = $this->getCustomer();
  89.         $isLogged = false;
  90.         if (!$customer instanceof CustomerInterface && $cart->getCustomer() instanceof CustomerInterface) {
  91.             $customer = $cart->getCustomer();
  92.         }
  93.         if ($customer instanceof CustomerInterface && null !== $customer->getUser()) {
  94.             $isLogged = true;
  95.         }
  96.         $normalizedCustomer = null;
  97.         if ($customer instanceof CustomerInterface) {
  98.             $normalizedCustomer = $this->serializer->normalize($customer, 'json', [
  99.                 'groups' => ['cs_customer', 'cs_address', 'cs_country', 'cs_user'],
  100.             ]);
  101.         }
  102.         return $this->render('basket/basket_react.html.twig', [
  103.             'websiteUrl' => $this->websiteUrl,
  104.             'squareSandbox'     => ($_ENV['SQUARE_SANDBOX'] == 'true') ? 1 : 0,
  105.             'squareAppId'       => $_ENV['SQUARE_APP_ID'],
  106.             'squareLocationId'  => $_ENV['SQUARE_LOCATION_ID'],
  107.             'initialCartData'   => $normalizedCart,
  108.             'initialCustomerData' => [
  109.                 'customer' => $normalizedCustomer,
  110.                 'is_logged' => $isLogged,
  111.             ],
  112.             'requestforbasket'  => true
  113.         ]);
  114.     }
  115.     public function widgetAction(Request $request): Response
  116.     {
  117.          return $this->render('basket/_widget.html.twig', [
  118.              'cart' => $this->getCart(),
  119.          ]);
  120.         
  121.         //  return $this->render('basket/_widget_react.html.twig', [
  122.         //     'websiteUrl' => $this->websiteUrl,
  123.         // ]);
  124.     }
  125.     public function addProductAction(Request $request, SessionInterface $session): Response
  126.     {
  127.         //return $this->addItemAction($request);
  128.         // Remove from robots index
  129.         header('X-Robots-Tag: noindex, nofollow', true);
  130.         $this->denyAccessUnlessGranted('CORESHOP_CART');
  131.         $this->denyAccessUnlessGranted('CORESHOP_CART_ADD_ITEM');
  132.         $redirect = $this->getParameterFromRequest($request, '_redirect', $this->generateUrl('basket'));
  133.         if (0 !== strlen($request->get('firstname', ''))) {
  134.             //Honeypot
  135.             return $this->redirect($redirect);
  136.         }
  137.         $product = OnixProduct::getById($this->getParameterFromRequest($request, 'product'));
  138.         $referrer = $request->headers->get('referer');
  139.         $session->set('cart_prev', $referrer);
  140.         if (!$product instanceof PurchasableInterface) {
  141.             if ($request->isXmlHttpRequest()) {
  142.                 return new JsonResponse([
  143.                     'success' => false,
  144.                 ]);
  145.             }
  146.             return $this->redirect($redirect);
  147.         }
  148.         $engName = $product->getName('en');
  149.         if(empty($engName)){
  150.             $product->setName($product->getName('fr'),'en');
  151.         }
  152.         if(empty($engName)){
  153.             $product->setName($product->getLongTitle(),'en');
  154.         }
  155.         $cartItem = Pimcore::getContainer()->get('coreshop.factory.order_item')->createWithPurchasable($product);
  156.         $this->quantityModifer->modify($cartItem, 1);
  157.         $addToCart = $this->cartContext->createWithCartAndCartItem($this->getCart(), $cartItem);
  158.         $this->getCartModifier()->addToList($addToCart->getCart(), $addToCart->getCartItem());
  159.         $this->getCartManager()->persistCart($this->getCart());
  160.         $product = $addToCart->getCartItem()->getProduct();
  161.         $product->getPrice()->setValue($product->getPrice()->getValue() * 1000);
  162.         Pimcore::getContainer()->get(TrackerInterface::class)->trackCartAdd(
  163.             $addToCart->getCart(),
  164.             $addToCart->getCartItem()->getProduct(),
  165.             $addToCart->getCartItem()->getQuantity(),
  166.         );
  167.         // p_r($cartItem->getItemPriceNet());
  168.         // p_r($addToCart);
  169.         // p_r($cartItem);
  170.         // exit;
  171.         $this->addFlash('success', Pimcore::getContainer()->get('translator')->trans('coreshop.ui.item_added'));
  172.         // Dispatch event after add to cart
  173.         $event = new GenericEvent($this->getCart());
  174.         Pimcore::getContainer()->get('event_dispatcher')->dispatch($event, 'cart.post.additem');
  175.         if ($request->isXmlHttpRequest()) {
  176.             return new JsonResponse([
  177.                 'success' => true,
  178.             ]);
  179.         }
  180.         return $this->redirect($redirect);
  181.     }
  182.     protected function getCustomer(): ?CustomerInterface
  183.     {
  184.         try {
  185.             /**
  186.              * @var CustomerInterface $customer
  187.              */
  188.             $customer = Pimcore::getContainer()->get(CustomerContextInterface::class)->getCustomer();
  189.             return $customer;
  190.         } catch (\Exception) {
  191.             // fail silently
  192.         }
  193.         return null;
  194.     }
  195.     /*
  196.      * Fonction encore appelée avec REACT une fois le paiement Square ok
  197.      */
  198.     public function thanksWithTokenAction(Request $request, Generator $generator, DolpoSupplyChainService $dolpoSupplyService): Response
  199.     {
  200.         $logger = ApplicationLogger::getInstance();
  201.         $items = [];
  202.         $token=$request->attributes->get('token');
  203.         // Retrieve the order based on the token from the request
  204.         $order = Pimcore::getContainer()->get('coreshop.repository.order')->findOneBy([
  205.             'token' => $token
  206.         ]);
  207.         
  208.         if (null === $order) {
  209.             throw new NotFoundHttpException('Order with the specified token does not exist.');
  210.         }
  211.         if ($request->query->has('paymentId')) {
  212.             $paymentObject = $paymentRepository->find($request->query->get('paymentId'));
  213.             if ($paymentObject instanceof PaymentInterface) {
  214.                 $payment = $paymentObject;
  215.             }
  216.         }
  217.     
  218.         // Logging setup
  219.         $logfile = '../var/log/logs_square.txt';
  220.         $this->logToFile($logfile, "thanksWithTokenAction check\nPaymentState: " . $order->getPaymentState());
  221.     
  222.         $paymentState = $order->getPaymentState();
  223.         $applicationLog = "Order: " . $order->getOrderNumber() . "\nPaymentState: " . $paymentState . "\n";
  224.         
  225.         $isPaid = ($paymentState === \CoreShop\Component\Order\OrderPaymentStates::STATE_PAID);
  226.         return new JsonResponse(['isPaid'=>$isPaid, 
  227.             'paymentState'=>isset($payment) ? $payment->getState() : null, 
  228.             'orderPaymentState'=>$paymentState,
  229.             'orderToken'=>$token
  230.         ]);
  231.     }
  232.     /**
  233.      * Log messages to a file.
  234.      */
  235.     private function logToFile(string $logfile, string $message): void
  236.     {
  237.         if (!file_exists($logfile)) {
  238.             file_put_contents($logfile, '');
  239.         }
  240.     
  241.         $currentLogContent = file_get_contents($logfile);
  242.         $currentLogContent .= $message . "\r\n";
  243.         file_put_contents($logfile, $currentLogContent);
  244.     }
  245.     
  246.     
  247.     public function thanksAction(Request $request): Response
  248.     {
  249.         // $this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ORDERS');
  250.         $orderId = $this->getParameterFromRequest($request, 'orderId', null);
  251.         $invocieId = 0;
  252.         $invoiceListing = CoreShopOrderInvoice::getByOrder(['id' => $orderId, 'type' => 'object']);
  253.         $invoice = $invoiceListing->load();
  254.         if (!empty($invoice)) {
  255.             $invocieId = $invoice[0]->getId();
  256.         }
  257.         $customer = $this->getCustomer();
  258.         $viewUrl = '/compte/commande/track/'.$orderId;
  259.         $isGuest = $customer && null === $customer->getUser();
  260.         if($isGuest || !$customer) {
  261.             $viewUrl = '/compte/commande/track/'.$orderId;
  262.         }
  263.         return $this->render('basket/thanks.html.twig', [
  264.             'profilePage' => true,
  265.             'invocieId'=>$invocieId,
  266.             'orderId' =>$orderId,
  267.             'viewUrl' =>$viewUrl,
  268.         ]);
  269.     }
  270.     public function ordersTrackingAction(Request $request): Response
  271.     {
  272.         // $this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ORDERS');
  273.         $orderId = $this->getParameterFromRequest($request, 'orderId', null);
  274.         $customer = $this->getCustomer();
  275.         return $this->render('account/order_tracking_guest.html.twig', [
  276.             'customer' => $customer,
  277.             'profilePage' => true,
  278.             'order' => CoreShopOrder::getById($orderId),
  279.         ]);
  280.     }
  281.     private function getPaymentRepository(): PaymentRepositoryInterface
  282.     {
  283.         return Pimcore::getContainer()->get('coreshop.repository.payment');
  284.     }
  285.     protected function getFormFactory(): FormFactoryInterface
  286.     {
  287.         return Pimcore::getContainer()->get('form.factory');
  288.     }
  289.     // Ex : https://dolpo.fr/fr/shop/orderrevise/ntoi6tOUuQ?paymentId=81
  290.     /*
  291.      * Fonction encore appelée avec REACT une fois le paiement Square ok
  292.      */
  293.     public function orderReviseAction(Request $request, Generator $generator): Response
  294.     {
  295.         $paymentRepository = Pimcore::getContainer()->get('coreshop.repository.payment');
  296.         $token = $this->getParameterFromRequest($request, 'token');
  297.         $payment = null;
  298.         /** @var OrderInterface $order */
  299.         $order = Pimcore::getContainer()->get('coreshop.repository.order')->findOneBy(['token' => $token]);
  300.         if (null === $order) {
  301.             throw new NotFoundHttpException(sprintf('Order does not exist.'));
  302.         }
  303.         if ($request->query->has('paymentId')) {
  304.             $paymentObject = $paymentRepository->find($request->query->get('paymentId'));
  305.             if ($paymentObject instanceof PaymentInterface) {
  306.                 $payment = $paymentObject;
  307.             }
  308.         }
  309.         // Logging setup
  310.         $logfile = '../var/log/logs_square.txt';
  311.         $this->logToFile($logfile, "orderRevise check\nPaymentState: " . $order->getPaymentState());
  312.     
  313.         $paymentState = $order->getPaymentState();
  314.         $applicationLog = "Order: " . $order->getOrderNumber() . "\nPaymentState: " . $paymentState . "\n";
  315.         $isPaid = ($paymentState === \CoreShop\Component\Order\OrderPaymentStates::STATE_PAID);
  316.         return new JsonResponse(['isPaid'=>$isPaid, 
  317.         'paymentState'=>isset($payment) ? $payment->getState() : null, 
  318.         'orderPaymentState'=>$paymentState,
  319.         'orderToken'=>$token]);
  320.     }
  321.     protected function getCart(): OrderInterface
  322.     {
  323.         return $this->getCartContext()->getCart();
  324.     }
  325.     private function getInvoiceFactory(): PimcoreFactoryInterface
  326.     {
  327.         return Pimcore::getContainer()->get('coreshop.factory.order_invoice');
  328.     }
  329.     private function getOrderToInvoiceTransformer(): OrderDocumentTransformerInterface
  330.     {
  331.         return Pimcore::getContainer()->get('coreshop.order.transformer.order_to_invoice');
  332.     }
  333.     protected function getCartContext(): CartContextInterface
  334.     {
  335.         return Pimcore::getContainer()->get(CartContextInterface::class);
  336.     }
  337.     protected function getCartModifier(): CartModifierInterface
  338.     {
  339.         return Pimcore::getContainer()->get(CartModifierInterface::class);
  340.     }
  341.     protected function getCartManager(): CartManagerInterface
  342.     {
  343.         return Pimcore::getContainer()->get(CartManagerInterface::class);
  344.     }
  345. }