<?php
namespace App\Controller\Account;
use App\Form\Type\PaymentType;
use App\Service\SquareDolpo\Tools as SquareTools;
use CoreShop\Bundle\CoreBundle\Checkout\Step\CustomerAddressCheckoutStep;
use CoreShop\Bundle\CoreBundle\Checkout\Step\CustomerCheckoutStep;
use CoreShop\Bundle\CoreBundle\Checkout\Step\GuestAddressCheckoutStep;
use CoreShop\Bundle\CoreBundle\Form\Type\GuestRegistrationType;
use CoreShop\Bundle\CoreBundle\Form\Type\Order\PaymentType as RevisePaymentType;
use CoreShop\Bundle\FrontendBundle\Controller\CartController as CoreShopCartController;
use CoreShop\Bundle\FrontendBundle\TemplateConfigurator\TemplateConfiguratorInterface;
use CoreShop\Bundle\OrderBundle\DTO\AddToCartInterface;
use CoreShop\Bundle\OrderBundle\Factory\AddToCartFactoryInterface;
use CoreShop\Bundle\OrderBundle\Form\Type\CartType;
use CoreShop\Bundle\OrderBundle\Form\Type\ShippingCalculatorType;
use CoreShop\Bundle\WorkflowBundle\Manager\StateMachineManagerInterface;
use CoreShop\Component\Address\Model\AddressInterface;
use CoreShop\Component\Core\Model\CustomerInterface;
use CoreShop\Component\Core\Order\Modifier\CartItemQuantityModifier;
use CoreShop\Component\Customer\Context\CustomerContextInterface;
use CoreShop\Component\Order\Cart\CartModifierInterface;
use CoreShop\Component\Order\Checkout\CheckoutException;
use CoreShop\Component\Order\Checkout\CheckoutManagerFactoryInterface;
use CoreShop\Component\Order\CheckoutEvents;
use CoreShop\Component\Order\Context\CartContextInterface;
use CoreShop\Component\Order\Event\CheckoutEvent;
use CoreShop\Component\Order\InvoiceStates;
use CoreShop\Component\Order\Manager\CartManagerInterface;
use CoreShop\Component\Order\Model\OrderInterface;
use CoreShop\Component\Order\Model\OrderItemInterface;
use CoreShop\Component\Order\Model\PurchasableInterface;
use CoreShop\Component\Order\OrderSaleTransitions;
use CoreShop\Component\Order\Transformer\OrderDocumentTransformerInterface;
use CoreShop\Component\Payment\Model\PaymentInterface;
use CoreShop\Component\Payment\Repository\PaymentRepositoryInterface;
use CoreShop\Component\Resource\Factory\FactoryInterface;
use CoreShop\Component\Resource\Factory\PimcoreFactoryInterface;
use CoreShop\Component\Shipping\Calculator\TaxedShippingCalculatorInterface;
use CoreShop\Component\Shipping\Resolver\CarriersResolverInterface;
use CoreShop\Component\Tracking\Tracker\TrackerInterface;
use Pimcore;
use Pimcore\Bundle\NumberSequenceGeneratorBundle\Generator;
use Pimcore\Log\ApplicationLogger;
use Pimcore\Model\DataObject\CoreShopOrder;
use Pimcore\Model\DataObject\CoreShopOrderInvoice;
use Pimcore\Model\DataObject\CoreShopOrderItem;
use Pimcore\Model\DataObject\InventoryItem;
use Pimcore\Model\DataObject\OnixProduct;
use Pimcore\Model\DataObject\Service;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Form\ClickableInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use App\Service\DolpoSupplyChainService;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Webmozart\Assert\Assert;
class CartController extends CoreShopCartController
{
public function __construct(
public CartItemQuantityModifier $quantityModifer,
public AddToCartFactoryInterface $cartContext,
public TemplateConfiguratorInterface $templateConfigurator,
protected CustomerAddressCheckoutStep $customerAddressCheckoutStep,
protected GuestAddressCheckoutStep $guestAddressCheckoutStep,
protected CustomerCheckoutStep $customerCheckoutStep,
protected CheckoutManagerFactoryInterface $checkoutManagerFactory,
private FactoryInterface $customerFactory,
private string $websiteUrl,
private SerializerInterface $serializer,
) {
$this->setTemplateConfigurator($templateConfigurator);
}
#[Route(path: '/panier/', name: 'basket')]
public function basketReactAction(Request $request): Response
{
// Remove from robots index
header('X-Robots-Tag: noindex, nofollow', true);
$cart = $this->getCart();
$normalizedCart = $this->serializer->normalize($cart, 'json', [
'groups' => ['cs_order', 'cs_order_item', 'onix_product', 'cs_address', 'cs_country'],
]);
$customer = $this->getCustomer();
$isLogged = false;
if (!$customer instanceof CustomerInterface && $cart->getCustomer() instanceof CustomerInterface) {
$customer = $cart->getCustomer();
}
if ($customer instanceof CustomerInterface && null !== $customer->getUser()) {
$isLogged = true;
}
$normalizedCustomer = null;
if ($customer instanceof CustomerInterface) {
$normalizedCustomer = $this->serializer->normalize($customer, 'json', [
'groups' => ['cs_customer', 'cs_address', 'cs_country', 'cs_user'],
]);
}
return $this->render('basket/basket_react.html.twig', [
'websiteUrl' => $this->websiteUrl,
'squareSandbox' => ($_ENV['SQUARE_SANDBOX'] == 'true') ? 1 : 0,
'squareAppId' => $_ENV['SQUARE_APP_ID'],
'squareLocationId' => $_ENV['SQUARE_LOCATION_ID'],
'initialCartData' => $normalizedCart,
'initialCustomerData' => [
'customer' => $normalizedCustomer,
'is_logged' => $isLogged,
],
'requestforbasket' => true
]);
}
public function widgetAction(Request $request): Response
{
return $this->render('basket/_widget.html.twig', [
'cart' => $this->getCart(),
]);
// return $this->render('basket/_widget_react.html.twig', [
// 'websiteUrl' => $this->websiteUrl,
// ]);
}
public function addProductAction(Request $request, SessionInterface $session): Response
{
//return $this->addItemAction($request);
// Remove from robots index
header('X-Robots-Tag: noindex, nofollow', true);
$this->denyAccessUnlessGranted('CORESHOP_CART');
$this->denyAccessUnlessGranted('CORESHOP_CART_ADD_ITEM');
$redirect = $this->getParameterFromRequest($request, '_redirect', $this->generateUrl('basket'));
if (0 !== strlen($request->get('firstname', ''))) {
//Honeypot
return $this->redirect($redirect);
}
$product = OnixProduct::getById($this->getParameterFromRequest($request, 'product'));
$referrer = $request->headers->get('referer');
$session->set('cart_prev', $referrer);
if (!$product instanceof PurchasableInterface) {
if ($request->isXmlHttpRequest()) {
return new JsonResponse([
'success' => false,
]);
}
return $this->redirect($redirect);
}
$engName = $product->getName('en');
if(empty($engName)){
$product->setName($product->getName('fr'),'en');
}
if(empty($engName)){
$product->setName($product->getLongTitle(),'en');
}
$cartItem = Pimcore::getContainer()->get('coreshop.factory.order_item')->createWithPurchasable($product);
$this->quantityModifer->modify($cartItem, 1);
$addToCart = $this->cartContext->createWithCartAndCartItem($this->getCart(), $cartItem);
$this->getCartModifier()->addToList($addToCart->getCart(), $addToCart->getCartItem());
$this->getCartManager()->persistCart($this->getCart());
$product = $addToCart->getCartItem()->getProduct();
$product->getPrice()->setValue($product->getPrice()->getValue() * 1000);
Pimcore::getContainer()->get(TrackerInterface::class)->trackCartAdd(
$addToCart->getCart(),
$addToCart->getCartItem()->getProduct(),
$addToCart->getCartItem()->getQuantity(),
);
// p_r($cartItem->getItemPriceNet());
// p_r($addToCart);
// p_r($cartItem);
// exit;
$this->addFlash('success', Pimcore::getContainer()->get('translator')->trans('coreshop.ui.item_added'));
// Dispatch event after add to cart
$event = new GenericEvent($this->getCart());
Pimcore::getContainer()->get('event_dispatcher')->dispatch($event, 'cart.post.additem');
if ($request->isXmlHttpRequest()) {
return new JsonResponse([
'success' => true,
]);
}
return $this->redirect($redirect);
}
protected function getCustomer(): ?CustomerInterface
{
try {
/**
* @var CustomerInterface $customer
*/
$customer = Pimcore::getContainer()->get(CustomerContextInterface::class)->getCustomer();
return $customer;
} catch (\Exception) {
// fail silently
}
return null;
}
/*
* Fonction encore appelée avec REACT une fois le paiement Square ok
*/
public function thanksWithTokenAction(Request $request, Generator $generator, DolpoSupplyChainService $dolpoSupplyService): Response
{
$logger = ApplicationLogger::getInstance();
$items = [];
$token=$request->attributes->get('token');
// Retrieve the order based on the token from the request
$order = Pimcore::getContainer()->get('coreshop.repository.order')->findOneBy([
'token' => $token
]);
if (null === $order) {
throw new NotFoundHttpException('Order with the specified token does not exist.');
}
if ($request->query->has('paymentId')) {
$paymentObject = $paymentRepository->find($request->query->get('paymentId'));
if ($paymentObject instanceof PaymentInterface) {
$payment = $paymentObject;
}
}
// Logging setup
$logfile = '../var/log/logs_square.txt';
$this->logToFile($logfile, "thanksWithTokenAction check\nPaymentState: " . $order->getPaymentState());
$paymentState = $order->getPaymentState();
$applicationLog = "Order: " . $order->getOrderNumber() . "\nPaymentState: " . $paymentState . "\n";
$isPaid = ($paymentState === \CoreShop\Component\Order\OrderPaymentStates::STATE_PAID);
return new JsonResponse(['isPaid'=>$isPaid,
'paymentState'=>isset($payment) ? $payment->getState() : null,
'orderPaymentState'=>$paymentState,
'orderToken'=>$token
]);
}
/**
* Log messages to a file.
*/
private function logToFile(string $logfile, string $message): void
{
if (!file_exists($logfile)) {
file_put_contents($logfile, '');
}
$currentLogContent = file_get_contents($logfile);
$currentLogContent .= $message . "\r\n";
file_put_contents($logfile, $currentLogContent);
}
public function thanksAction(Request $request): Response
{
// $this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ORDERS');
$orderId = $this->getParameterFromRequest($request, 'orderId', null);
$invocieId = 0;
$invoiceListing = CoreShopOrderInvoice::getByOrder(['id' => $orderId, 'type' => 'object']);
$invoice = $invoiceListing->load();
if (!empty($invoice)) {
$invocieId = $invoice[0]->getId();
}
$customer = $this->getCustomer();
$viewUrl = '/compte/commande/track/'.$orderId;
$isGuest = $customer && null === $customer->getUser();
if($isGuest || !$customer) {
$viewUrl = '/compte/commande/track/'.$orderId;
}
return $this->render('basket/thanks.html.twig', [
'profilePage' => true,
'invocieId'=>$invocieId,
'orderId' =>$orderId,
'viewUrl' =>$viewUrl,
]);
}
public function ordersTrackingAction(Request $request): Response
{
// $this->denyAccessUnlessGranted('CORESHOP_CUSTOMER_PROFILE_ORDERS');
$orderId = $this->getParameterFromRequest($request, 'orderId', null);
$customer = $this->getCustomer();
return $this->render('account/order_tracking_guest.html.twig', [
'customer' => $customer,
'profilePage' => true,
'order' => CoreShopOrder::getById($orderId),
]);
}
private function getPaymentRepository(): PaymentRepositoryInterface
{
return Pimcore::getContainer()->get('coreshop.repository.payment');
}
protected function getFormFactory(): FormFactoryInterface
{
return Pimcore::getContainer()->get('form.factory');
}
// Ex : https://dolpo.fr/fr/shop/orderrevise/ntoi6tOUuQ?paymentId=81
/*
* Fonction encore appelée avec REACT une fois le paiement Square ok
*/
public function orderReviseAction(Request $request, Generator $generator): Response
{
$paymentRepository = Pimcore::getContainer()->get('coreshop.repository.payment');
$token = $this->getParameterFromRequest($request, 'token');
$payment = null;
/** @var OrderInterface $order */
$order = Pimcore::getContainer()->get('coreshop.repository.order')->findOneBy(['token' => $token]);
if (null === $order) {
throw new NotFoundHttpException(sprintf('Order does not exist.'));
}
if ($request->query->has('paymentId')) {
$paymentObject = $paymentRepository->find($request->query->get('paymentId'));
if ($paymentObject instanceof PaymentInterface) {
$payment = $paymentObject;
}
}
// Logging setup
$logfile = '../var/log/logs_square.txt';
$this->logToFile($logfile, "orderRevise check\nPaymentState: " . $order->getPaymentState());
$paymentState = $order->getPaymentState();
$applicationLog = "Order: " . $order->getOrderNumber() . "\nPaymentState: " . $paymentState . "\n";
$isPaid = ($paymentState === \CoreShop\Component\Order\OrderPaymentStates::STATE_PAID);
return new JsonResponse(['isPaid'=>$isPaid,
'paymentState'=>isset($payment) ? $payment->getState() : null,
'orderPaymentState'=>$paymentState,
'orderToken'=>$token]);
}
protected function getCart(): OrderInterface
{
return $this->getCartContext()->getCart();
}
private function getInvoiceFactory(): PimcoreFactoryInterface
{
return Pimcore::getContainer()->get('coreshop.factory.order_invoice');
}
private function getOrderToInvoiceTransformer(): OrderDocumentTransformerInterface
{
return Pimcore::getContainer()->get('coreshop.order.transformer.order_to_invoice');
}
protected function getCartContext(): CartContextInterface
{
return Pimcore::getContainer()->get(CartContextInterface::class);
}
protected function getCartModifier(): CartModifierInterface
{
return Pimcore::getContainer()->get(CartModifierInterface::class);
}
protected function getCartManager(): CartManagerInterface
{
return Pimcore::getContainer()->get(CartManagerInterface::class);
}
}