<?php
declare(strict_types=1);
namespace App\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sylius\Component\Product\Repository\ProductVariantRepositoryInterface;
use Sylius\Component\Channel\Context\ChannelContextInterface;
use App\Services\PPMCErpSynchroService;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Carbon\Carbon;
use Symfony\Component\Messenger\MessageBusInterface;
use App\Message\SyncCustomer;
// use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class CartController /*extends AbstractController*/
{
protected $twigEnvironment;
protected $container;
protected $productVariantRepository;
protected $ppmcErpSynchroService;
protected $bus;
public function __construct(
Environment $twigEnvironment,
ContainerInterface $container,
ProductVariantRepositoryInterface $productVariantRepository,
PPMCErpSynchroService $ppmcErpSynchroService,
MessageBusInterface $bus
){
$this->twigEnvironment = $twigEnvironment;
$this->container = $container;
$this->productVariantRepository = $productVariantRepository;
$this->ppmcErpSynchroService = $ppmcErpSynchroService;
$this->bus = $bus;
}
public function popupAction(Request $request): Response
{
// $this->payLog($request, "");
$cart = $this->container->get('sylius.context.cart')->getCart();
$amount = 0;
$total = 0;
$diff = 0;
$progress = 0;
$cdts = $this->container->get('sylius.repository.promotion')->findOneByCode('FREE_DELIVERY')->getRules();
foreach ($cdts as $cdt){
if ($cdt->getType() == 'item_total') {
$amount = $cdt->getConfiguration()['ppmc']['amount'];
$total = $cart->getItemsTotal();
$diff = $amount-$total;
$progress = $total / $amount * 100;
}
}
// Produits dans "Je craque aussi pour"
// Des accessoires cheveux
// de nouvelles collections uniquement
// 7 produits max aleatoire
// et 1 chouchou aléatoire peu importe la collection
$moreVariants = $this->container->get('sylius.repository.product_variant')
->findVariantsForCartPageIWantThisToo(
$this->container->get('sylius.context.channel')->getChannel(),
$this->container->get('sylius.context.locale')->getLocaleCode()
);
//On vinet associé une adresse si la personne est connectée
// if(null != $cart->getCustomer() && null != $cart->getCustomer()->getId() && $cart->getBillingAddress() == null) {
// // dump($cart->getCustomer());
// $addresses = $cart->getCustomer()->getAddresses();
// $this->container->get('doctrine')->getManager()->initializeObject($addresses);
// dump($addresses);
// // $cart->setBillingAddress($cart->getCustomer()->getAddresses()[0]);
// // $cart->setShippingAddress($cart->getCustomer()->getAddresses()[0]);
// // $cartManager = $this->container->get('sylius.manager.order');
// // $cartManager->persist($cart);
// // $cartManager->flush();
// }
// $this->container->get('doctrine')->getManager()->initializeObject($cart);
// dump($cart);
return new Response(
$this->twigEnvironment->render('@SyliusShop/Webapic/panier.html.twig', [
'cart' => $cart,
'amount' => $amount,
'total' => $total,
'diff' => $diff,
'progress' => $progress,
'moreVariants' => $moreVariants
])
);
}
public function addToCartAjax(ChannelContextInterface $channelCtx, Request $request)
{
// POST :
// data[<id product variant>] = <quantity>
// data[<id product variant>] = <quantity>
// etc.
$data = (array) $request->request->all();
if (empty($data) == true) {
return new JsonResponse([
'success' => true
]);
}
// Selectionne le canal pour calculer le prix
$channel = $channelCtx->getChannel();
//gestion champ carte kdo
$kdoFields = [];
if(isset($data['kdo_mail'])) {
$kdoFields['kdo_mail'] = $data['kdo_mail'];
$kdoFields['kdo_lastname'] = $data['kdo_lastname'];
$kdoFields['kdo_firstname'] = $data['kdo_firstname'];
$kdoFields['kdo_message'] = $data['kdo_message'];
unset($data['kdo_mail']);
unset($data['kdo_lastname']);
unset($data['kdo_firstname']);
unset($data['kdo_message']);
}
// Ajout au panier
$cart = $this->container->get('sylius.context.cart')->getCart();
foreach ($data as $variantId => $quantity) {
$quantity = round(floatval($quantity), 1);
$variant = $this->productVariantRepository->findOneById($variantId);
if (is_null($variant) == false && $quantity > 0) {
if($variant->countItemStock() <= 0 || $variant->getIsBlocked()){
// if($variant->getOnHand() - $variant->getOnHold() <= 5){
return new JsonResponse([
'stock' => 0
]);
}
$orderItem = $this->container->get('sylius.repository.order_item')->findOneBy([
'variant' => $variant,
'order' => $cart
]);
if (!empty($orderItem) && $variant->getProduct()->getConditioning() != 'per_meter_each_0_5_meter' && $variant->getProduct()->getConditioning() != 'card_kdo_per_euros_each_10_euros') {
$quantity = $orderItem->getQuantity() + $quantity;
if($quantity > 10){
$quantity = 10;
}
$this->container->get('sylius.order_item_quantity_modifier')->modify($orderItem, (int) $quantity);
}else{
// if(!empty($orderItem) && $variant->getProduct()->getConditioning() == 'per_meter_each_0_5_meter'){
// // $this->container->get('sylius.order_modifier')->removeFromOrder($cart, $orderItem);
// // $this->container->get('sylius.order_item_quantity_modifier')->modify($orderItem, 0);
// }
if($variant->getProduct()->getConditioning() == 'per_meter_each_0_5_meter') {
if($quantity > 10){
$quantity = 10;
}
}
$this->addOrderItemToCart($channel, $cart, $variant, $quantity, null, $kdoFields);
}
}
}
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
$isFine = true;
// $isFine =$this->stockVerification($cart, $request);
// Valorisation du panier côté Generix
$this->applyReducedPricesToCart($channel, $cart);
$cart = $this->container->get('sylius.context.cart')->getCart();
// dump($cart);
$amount = 0;
$total = 0;
$diff = 0;
$progress = 0;
$cdts = $this->container->get('sylius.repository.promotion')->findOneByCode('FREE_DELIVERY')->getRules();
foreach($cdts as $cdt){
if( $cdt->getType() == 'item_total'){
$amount = $cdt->getConfiguration()['ppmc']['amount'];
$total = $cart->getItemsTotal();
$diff = $amount-$total;
$progress = $total / $amount * 100;
}
}
$fromPagepanier = $request->query->get('pagepanier', '');
if(!empty($fromPagepanier)){
return new JsonResponse([
'produits' => $this->twigEnvironment->render('@SyliusShop/Webapic/panier/pagepanier-produits.html.twig', [
'cart' => $cart,
]),
'total' => $this->twigEnvironment->render('@SyliusShop/Cart/Summary/_totals.html.twig', [
'cart' => $cart,
]),
'livraison' => $this->twigEnvironment->render('@SyliusShop/Webapic/panier/panier-livraison.html.twig', [
'cart' => $cart,
'amount' => $amount,
'total' => $total,
'diff' => $diff,
'progress' => $progress,
]),
'widgettop' => $this->twigEnvironment->render('@SyliusShop/Cart/_widget.html.twig', [
'cart' => $cart,
]),
// 'isFine' => true
'isFine' => $isFine
]);
}
return new JsonResponse([
'produits' => $this->twigEnvironment->render('@SyliusShop/Webapic/panier/panier-produits.html.twig', [
'cart' => $cart,
]),
'total' => $this->twigEnvironment->render('@SyliusShop/Webapic/panier/panier-total.html.twig', [
'cart' => $cart,
]),
'top' => $this->twigEnvironment->render('@SyliusShop/Webapic/panier/panier-top.html.twig', [
'cart' => $cart,
]),
'livraison' => $this->twigEnvironment->render('@SyliusShop/Webapic/panier/panier-livraison.html.twig', [
'cart' => $cart,
'amount' => $amount,
'total' => $total,
'diff' => $diff,
'progress' => $progress,
]),
'widgettop' => $this->twigEnvironment->render('@SyliusShop/Cart/_widget.html.twig', [
'cart' => $cart,
]),
// 'isFine' => true
'isFine' => $isFine
]);
}
public function updateCartAction(ChannelContextInterface $channelCtx, Request $request, $id)
{
$cart = $this->container->get('sylius.context.cart')->getCart();
$repository = $this->container->get('sylius.repository.order_item');
$orderItem = $repository->findOneByIdAndCartId($id, $cart->getId());
// dump($orderItem);
if (!empty($orderItem)) {
$quantity = min(99, max(0, intval($request->request->get('quantity', 1))));
if($quantity > 10){
$quantity = 10;
}
if($quantity == 0){
$this->container->get('sylius.order_modifier')->removeFromOrder($cart, $orderItem);
}else{
$this->container->get('sylius.order_item_quantity_modifier')->modify($orderItem, $quantity);
}
$this->container->get('sylius.order_item_quantity_modifier')->modify($orderItem, $quantity);
}else{
$orderItem = $this->container->get('sylius.factory.order_item')->createNew();
$orderItem->setVariant($this->productVariantRepository->find($id));
$this->container->get('sylius.order_item_quantity_modifier')->modify($orderItem, 1);
$this->container->get('sylius.order_modifier')->addToOrder($cart, $orderItem);
$cart->addItem($orderItem);
}
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
// echo 'coucou';
// dump($orderItem);
// exit();
// Selectionne le canal pour calculer le prix
$channel = $channelCtx->getChannel();
$isFine = true;
// $isFine =$this->stockVerification($cart, $request);
// Valorisation du panier côté Generix
$this->applyReducedPricesToCart($channel, $cart);
$cart = $this->container->get('sylius.repository.order')->findOneBy([
'id' => $cart->getId()
]);
// $this->container->get('sylius.context.cart')->getCart();
// $this->container->get('sylius.context.cart')->setCart($cart);
// $cartManager = $this->container->get('sylius.manager.order');
// $cartManager->persist($cart);
// $cartManager->flush();
// $cart = $this->container->get('sylius.context.cart')->getCart();
$amount = 0;
$total = 0;
$diff = 0;
$progress = 0;
$cdts = $this->container->get('sylius.repository.promotion')->findOneByCode('FREE_DELIVERY')->getRules();
foreach($cdts as $cdt){
if( $cdt->getType() == 'item_total'){
$amount = $cdt->getConfiguration()['ppmc']['amount'];
$total = $cart->getItemsTotal();
$diff = $amount-$total;
$progress = $total / $amount * 100;
}
}
if($request->request->get('pagepanier')){
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
if (!$configuration->isHtmlRequest()) {
return $this->viewHandler->handle($configuration, View::create($cart));
}
$form = $this->resourceFormFactory->create($configuration, $cart);
return new JsonResponse([
'pagepaniertotal' => $this->twigEnvironment->render('@SyliusShop/Webapic/panier/pagepanier-right.html.twig', [
'cart' => $cart,
'form' => $form->createView(),
'amount' => $amount,
'total' => $total,
'diff' => $diff,
'progress' => $progress,
]),
]);
}else{
return new JsonResponse([
'produits' => $this->twigEnvironment->render('@SyliusShop/Webapic/panier/panier-produits.html.twig', [
'cart' => $cart,
]),
'total' => $this->twigEnvironment->render('@SyliusShop/Webapic/panier/panier-total.html.twig', [
'cart' => $cart,
]),
'top' => $this->twigEnvironment->render('@SyliusShop/Webapic/panier/panier-top.html.twig', [
'cart' => $cart,
]),
'livraison' => $this->twigEnvironment->render('@SyliusShop/Webapic/panier/panier-livraison.html.twig', [
'cart' => $cart,
'amount' => $amount,
'total' => $total,
'diff' => $diff,
'progress' => $progress,
]),
'widgettop' => $this->twigEnvironment->render('@SyliusShop/Cart/_widget.html.twig', [
'cart' => $cart,
]),
// 'isFine' => true
'isFine' => $isFine
]);
}
}
public function meaAction(Request $request): Response
{
return new Response(
$this->twigEnvironment->render('@SyliusShop/Webapic/panier/mea.html.twig', [
// 'cart' => $cart
])
);
}
private function addOrderItemToCart($channel, $cart, $variant, $quantity, ?int $customPrice = null, ?array $kdoFields): void
{
if($variant->getIsBlocked()) {
return;
}
if ($variant->getProduct()->getConditioning() == 'per_meter_each_0_5_meter') {
// Ajout d'un tissu au mètre (0,5m etc)
// On ajoute une ligne à chaque fois avec une quantité de "1"
$basePrice = is_null($customPrice) ? $variant->getChannelPricingForChannel($channel)->getPrice() : $customPrice;
$price = (int) round($basePrice * $quantity, 0);
$orderItem = $this->container->get('sylius.factory.order_item')->createNew();
$orderItem->setVariant($variant);
$orderItem->setVariantName($variant->getName() . ' - ' . $quantity . 'm');
$orderItem->setOriginalUnitPrice($price);
$orderItem->setUnitPrice($price);
$orderItem->setImmutable(true);
$orderItem->setConditioning($variant->getProduct()->getConditioning());
$orderItem->setConditioningValue($quantity);
$this->container->get('sylius.order_item_quantity_modifier')->modify($orderItem, 1);
$this->container->get('sylius.order_modifier')->addToOrder($cart, $orderItem);
} else if ($variant->getProduct()->getConditioning() == 'card_kdo_per_euros_each_10_euros' && !empty($kdoFields)) {
// Ajout d'une carte cadeau
// On ajoute une ligne à chaque fois avec une quantité de "1"
$basePrice = is_null($customPrice) ? $variant->getChannelPricingForChannel($channel)->getPrice() : $customPrice;
$price = (int) round($basePrice * $quantity, 0);
// dump($cart);
// dump($variant);
// dump($quantity);
// dump($price);
// exit();
$orderItem = $this->container->get('sylius.factory.order_item')->createNew();
$orderItem->setVariant($variant);
$orderItem->setVariantName($variant->getName() . ' - ' . $quantity . '€');
$orderItem->setOriginalUnitPrice((int) round($quantity * 100, 0));
$orderItem->setUnitPrice((int) round($quantity * 100, 0));
$orderItem->setImmutable(true);
$orderItem->setConditioning($variant->getProduct()->getConditioning());
$orderItem->setConditioningValue($quantity);
$orderItem->setKdoEmail($kdoFields['kdo_mail']);
$orderItem->setKdoLastname($kdoFields['kdo_lastname']);
$orderItem->setKdoFirstname($kdoFields['kdo_firstname']);
$orderItem->setKdoMessage($kdoFields['kdo_message']);
$this->container->get('sylius.order_item_quantity_modifier')->modify($orderItem, 1);
$this->container->get('sylius.order_modifier')->addToOrder($cart, $orderItem);
} else {
$quantity = intval($quantity);
$orderItem = $this->container->get('sylius.repository.order_item')->findOneBy([
'variant' => $variant,
'order' => $cart
]);
// dump($orderItem);
if (empty($orderItem) == true) {
$orderItem = $this->container->get('sylius.factory.order_item')->createNew();
$orderItem->setVariant($variant);
if (is_null($customPrice) == false) {
$orderItem->setOriginalUnitPrice($customPrice);
$orderItem->setUnitPrice($customPrice);
$orderItem->setImmutable(true);
}
if(($orderItem->getQuantity() + $quantity) > 10){
$this->container->get('sylius.order_item_quantity_modifier')->modify($orderItem, 10);
}else{
$this->container->get('sylius.order_item_quantity_modifier')->modify($orderItem, $orderItem->getQuantity() + $quantity);
}
$this->container->get('sylius.order_modifier')->addToOrder($cart, $orderItem);
} else {
if (is_null($customPrice) == false) {
$orderItem->setOriginalUnitPrice($customPrice);
$orderItem->setUnitPrice($customPrice);
$orderItem->setImmutable(true);
}
$this->container->get('sylius.order_item_quantity_modifier')->modify($orderItem, $orderItem->getQuantity() + $quantity);
}
}
}
public function applyReducedPricesToCart($channel, $cart): void
{
if (isset($_GET['frommail']) ) {
return;
}
// echo $webPath = $this->container->get('kernel')->getProjectDir();
$process = new Process(['/usr/bin/php', $this->container->get('kernel')->getProjectDir().'/bin/console', 'ppmc:valorize-cart', '--cartId='.$cart->getId()]);
$process->setTimeout(4);
try {
$process->start();
$process->wait();
// echo $process->getOutput();
$em = $this->container->get('doctrine.orm.entity_manager');
$em->refresh($cart);
$cartItems = $cart->getItems();
foreach ($cartItems as $cartRow) {
$em->refresh($cartRow);
}
} catch (ProcessTimedOutException $exception) {
// echo 'bofbof';
}
}
public function convertFideliteAction(
Request $request): JsonResponse
{
$customer = $this->container->get('sylius.context.customer')->getCustomer();
$this->bus->dispatch(new SyncCustomer((int)$customer->getId()));
$fidelity = $request->query->get('fidelity', 0);
$cart = $this->container->get('sylius.context.cart')->getCart();
$cart->setHasLoyalty($fidelity);
// $this->applyReducedPricesToCart($channel, $cart);
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
return new JsonResponse([
'success' => true
]);
}
public static function stockVerification($cart, $request): bool
{
$isFine = true;
$cartItems = $cart->getItems();
foreach ($cartItems as $cartRow) {
// si panier > 30mn et stock insuffisant
if($cart->getCompteur() == 0){
if(!$cartRow->canAddItem()){
$isFine = false;
$quantity = $cartRow->nbItemStock();
if($quantity == 0){
$this->container->get('sylius.order_modifier')->removeFromOrder($cart, $cartRow);
$request->getSession()->getFlashBag()->add(
'error',
"Le produit ".$cartRow->getVariant()->getName()." n'est plus disponible "
);
}else{
$this->container->get('sylius.order_item_quantity_modifier')->modify($cartRow, $quantity);
$request->getSession()->getFlashBag()->add(
'info',
"Le produit ".$cartRow->getVariant()->getName()." n'est plus disponible dans la quantité demandée "
);
}
$this->container->get('sylius.order_processing.order_processor')->process($cart);
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
}
}
}
return $isFine;
}
public function addMessageToCart(Request $request) {
$cart = $this->container->get('sylius.context.cart')->getCart();
$data = (array) $request->request->all();
if(!empty($data['message'])) {
$cart->setGiftMessage($data['message']);
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
}
return new JsonResponse([
'success' => true
]);
}
}