<?php
declare(strict_types=1);
namespace App\Controller\Order;
use FOS\RestBundle\View\View;
use Sylius\Bundle\ResourceBundle\Controller\RequestConfiguration;
use Sylius\Bundle\ResourceBundle\Controller\ResourceController;
use Sylius\Component\Order\Context\CartContextInterface;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Order\Repository\OrderRepositoryInterface;
use Sylius\Component\Order\SyliusCartEvents;
use Sylius\Component\Resource\ResourceActions;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Webmozart\Assert\Assert;
use SM\Factory\FactoryInterface;
use Twig\Environment;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Services\WSColissimoService;
use App\Services\WSShop2ShopService;
use App\Entity\SiteShop;
use App\Entity\SiteCommentOrder;
use App\Form\Type\SiteCommentOrderType;
use App\Controller\CartController;
use App\Entity\Addressing\Address;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
// use Sylius\Bundle\CoreBundle\Controller\OrderController as BaseOrderController;
use Sylius\Bundle\OrderBundle\Controller\OrderController as BaseOrderController;
use Symfony\Component\Messenger\MessageBusInterface;
use App\Message\ValidateOrder;
use Sylius\Component\Channel\Context\ChannelContextInterface;
use App\Form\Type\SiteCodePromotionType;
use Sylius\Bundle\AdminBundle\EmailManager\OrderEmailManagerInterface;
use Sylius\Component\Mailer\Sender\SenderInterface;
use App\Services\PPMCErpSynchroService;
use Sylius\Component\Core\Model\AdjustmentInterface;
use App\Entity\SiteApel;
use Monolog\Logger;
use App\Entity\SiteProductNoStock;
use Sylius\Component\Inventory\Checker\AvailabilityChecker;
use DateTime;
use Carbon\Carbon;
use phpDocumentor\Reflection\Types\Integer;
class OrderController extends BaseOrderController
{
public function summaryAction(Request $request, $tokenValue = null): Response
{
// echo 'coucou';dump($form);
// exit();
$this->payLog($request, $tokenValue);
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
// On arrive sur le panier après un paiement annulé ou refusé
if (empty($tokenValue) == false) {
$citelisLink = $request->getSession()->get('citelis_link', null);
if (empty($citelisLink)) {
$customer = $this->get('sylius.context.customer')->getCustomer();
$cart = $this->get('sylius.repository.order')->findOneBy([
'tokenValue' => $tokenValue,
'customer' => $customer,
'state' => 'new'
]);
// dump($cart);exit
if (empty($cart) == false && $cart->getPaymentState() == 'awaiting_payment') {
$orderSM = $this->get('sm.factory')->get($cart, 'sylius_order_checkout');
if ($orderSM->can('reset')) {
$orderSM->apply('reset');
}
}
// Redirection sur la même page tout en conservant
// les messages flashes
// dump($request);
foreach ($request->getSession()->getFlashBag() as $type => $message) {
$this->getSession()->add($type, $message);
}
return $this->redirectHandler->redirectToRoute(
$configuration,
'sylius_shop_cart_summary'
);
}
else {
$request->getSession()->getFlashBag()->clear();
$request->getSession()->getFlashBag()->add(
'info',
"Le lien a bien été envoyé"
);
$request->getSession()->remove('citelis_link');
return $this->redirectHandler->redirectToRoute(
$configuration,
'sylius_shop_homepage'
);
// foreach ($request->getSession()->getFlashBag() as $type => $message) {
// $this->getSession()->add($type, $message);
// }
}
}
// dump($request);
$cart = $this->getCurrentCart();
if (null !== $cart->getId()) {
$cart = $this->getOrderRepository()->findCartById($cart->getId());
if(strpos($request->getPathInfo(), 'cart') !== false) {
//On supprime la carte cadeau
foreach($cart->getPayments() as $payment) {
$details = $payment->getDetails();
if(array_key_exists('giftCardCode', $details)) {
$cart->removePayment($payment);
}
}
$adjustements = $cart->getAdjustments();
foreach($adjustements as $adjustement) {
$details = $adjustement->getDetails();
if($adjustement->getType() == AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT && array_key_exists('giftCardCode', $details)) {
$adjustement->unlock();
}
}
$cart->removeAdjustments(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
}
}
if (!$configuration->isHtmlRequest()) {
return $this->viewHandler->handle($configuration, View::create($cart));
}
$form = $this->resourceFormFactory->create($configuration, $cart);
// $isFine = CartController::stockVerification($cart, $request);
$this->applyReducedPricesToCart( $this->container->get('sylius.context.channel')->getChannel(), $cart, $this->container->get('doctrine.orm.entity_manager'));
$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;
}
}
// Emballage cadeau
// 1) Il y a les produits pour "J'emballge moi-même"
// 2) Il y a les produits pour "Prêt à offrir"
// Ce ne sont pas les même !
$giftWrapMyself = $this->container->get('sylius.repository.product_variant')->findGiftWrapMyself(
$this->container->get('sylius.context.channel')->getChannel(),
$this->container->get('sylius.context.locale')->getLocaleCode()
);
$giftWrapPPMC = $this->container->get('sylius.repository.product_variant')->findGiftWrapPPMC(
$this->container->get('sylius.context.channel')->getChannel(),
$this->container->get('sylius.context.locale')->getLocaleCode()
);
// Produits dans "Un petit truc en plus"
// 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()
);
$cart->formCodePromo = $this->createForm(SiteCodePromotionType::class);
$cart->formCodePromo->handleRequest($request);
$cart->formCodePromo = $cart->formCodePromo->createView();
//On vérifie les adresses du client au cas où, et on met une adresse par défaut
$customer = $this->get('sylius.context.customer')->getCustomer();
if(!empty($customer) && empty($customer->getEmail())) {
$this->container->get('doctrine')->getManager()->initializeObject($customer);
}
if(!empty($customer) && empty($customer->getDefaultAddress())) {
$addresses = $customer->getAddresses();
$this->container->get('doctrine')->getManager()->initializeObject($addresses);
if(!empty($addresses)) {
foreach($addresses as $address) {
// dump($address->getCompany());
if($address->getCompany() == null || !str_contains($address->getCompany(), 'Boutique')) {
$customer->setDefaultAddress($address);
$customerManager = $this->container->get('sylius.manager.customer');
$customerManager->persist($customer);
$customerManager->flush();
break;
}
}
}
}
if(!empty($customer) && $cart->getBillingAddress() == null) {
$defaultAddress = $customer->getDefaultAddress();
$this->container->get('doctrine')->getManager()->initializeObject($defaultAddress);
if (null !== $defaultAddress) {
// dump($defaultAddress);
$clonedAddress = clone $defaultAddress;
$clonedAddress->setCustomer(null);
$cart->setBillingAddress($clonedAddress);
if($cart->getShippingAddress() == null) {
$clonedAddress = clone $clonedAddress;
$cart->setShippingAddress($clonedAddress);
}
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
}
}
//On set le mode de livraison email si uniquement carte cadeau
$onlyCadeau = true;
foreach($cart->getItems() as $item) {
if($item->getVariant()->getCode() != PPMCErpSynchroService::KDO_VARIANT_CODE) {
$onlyCadeau = false;
break;
}
}
if($onlyCadeau && !empty($cart->getId()) && !empty($cart->getItems())) {
//On a que des cartes cadeaux
$shippingMethod = $this->container->get('sylius.repository.shipping_method')->createQueryBuilder('s')
->where('s.code LIKE :code')
->setParameter('code', 'EMAIL')
->getQuery()
->getOneOrNullResult();
if(!empty($shippingMethod)) {
if($cart->getShipments()->first()){
$cart->getShipments()->first()->setMethod($shippingMethod);
}
$adjustements = $cart->getAdjustments();
foreach($adjustements as $adjustement) {
$details = $adjustement->getDetails();
if($adjustement->getType() == AdjustmentInterface::SHIPPING_ADJUSTMENT) {
$adjustement->unlock();
}
}
$cart->removeAdjustments(AdjustmentInterface::SHIPPING_ADJUSTMENT);
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
}
}
//On surpprime les produits plus dispo
// $availabilityChecker = new AvailabilityChecker(false);
$removeProducts = false;
if(!empty($cart->getItems())) {
$em = $this->container->get('doctrine')->getManager();
$siteProductNoStockRepo = $em->getRepository(SiteProductNoStock::class);
foreach($cart->getItems() as $item) {
// if($cart->getId() == 91814){
// dump($item);
// }
$available = (($item->getVariant()->getOnHand()-($item->getVariant()->getItemMin() - 1)) > $item->getQuantity());
// dump($item->getVariant());
// if($_SERVER['HTTP_X_FORWARDED_FOR'] == '91.168.137.186') {
// dump($item->getVariant()->getOnHand());
// dump($item->getVariant()->getItemMin());
// dump($item->getQuantity());
// dump($item->getVariant()->getItemMin());
// }
if(!$available) {
$this->get('session')->getFlashBag()->add('error', 'Le produit : '.$item->getVariantName().' n\'est plus disponible, il a été enlevé de votre panier');
$this->container->get('sylius.order_modifier')->removeFromOrder($cart, $item);
$removeProducts = true;
$siteProductNoStockRepo = $em->getRepository(SiteProductNoStock::class);
$siteProductsNoStockExist = $siteProductNoStockRepo->findBy(
[
'productVariant' => $item->getVariant(),
'order' => $cart,
]
);
if(count($siteProductsNoStockExist) == 0){
$siteProductsNoStock = new SiteProductNoStock();
$siteProductsNoStock->setOrder($cart);
$siteProductsNoStock->setProductvariant($item->getVariant());
$siteProductsNoStock->setCreatedAt(new DateTime());
$em->persist($siteProductsNoStock);
$em->flush();
}
}
}
if($removeProducts) {
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
$this->applyReducedPricesToCart( $this->container->get('sylius.context.channel')->getChannel(), $cart, $this->container->get('doctrine.orm.entity_manager'));
}
}
dump($cart);
$siteProductsNoStock = array();
if (null !== $cart->getId()) {
$em = $this->container->get('doctrine')->getManager();
$siteProductNoStockRepo = $em->getRepository(SiteProductNoStock::class);
$siteProductsNoStock = $siteProductNoStockRepo->findBy(
['order' => $cart->getId()]
);
}
return $this->render(
$configuration->getTemplate('summary.html'),
[
'cart' => $cart,
'form' => $form->createView(),
'amount' => $amount,
'total' => $total,
'diff' => $diff,
'progress' => $progress,
'giftWrapMyself' => $giftWrapMyself,
'giftWrapPPMC' => $giftWrapPPMC,
'moreVariants' => $moreVariants,
'siteProductsNoStock' => $siteProductsNoStock
]
);
}
// public function getBusMessage(MessageBusInterface $bus) {
// return $bus;
// }
public function summaryAjaxAction(Request $request, $id): Response
{
// dump($request->getPathInfo());
// // $bus = new MessageBusInterface();
// dump($bus);
// exit();
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$cart = $this->getCurrentCart();
if (null !== $cart->getId()) {
$cart = $this->getOrderRepository()->findCartById($cart->getId());
}
if (!$configuration->isHtmlRequest()) {
return $this->viewHandler->handle($configuration, View::create($cart));
}
$form = $this->resourceFormFactory->create($configuration, $cart);
$repository = $this->container->get('sylius.repository.order_item');
$orderItem = $repository->findOneByIdAndCartId($id, $cart->getId());
if (!empty($orderItem)) {
$quantity = min(99, max(0, intval($request->request->get('quantity', 1))));
if($quantity == 0){
$this->container->get('sylius.order_modifier')->removeFromOrder($cart, $orderItem);
}else{
if($quantity > 10){
$quantity = 10;
}
$this->container->get('sylius.order_item_quantity_modifier')->modify($orderItem, $quantity);
}
foreach($cart->getPayments() as $payment) {
$details = $payment->getDetails();
if(array_key_exists('giftCardCode', $details)) {
$cart->removePayment($payment);
}
}
$adjustements = $cart->getAdjustments();
foreach($adjustements as $adjustement) {
$details = $adjustement->getDetails();
if($adjustement->getType() == AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT && array_key_exists('giftCardCode', $details)) {
$adjustement->unlock();
}
}
$cart->removeAdjustments(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
// Recalcul des promotions
$this->container->get('sylius.order_processing.order_processor')->process($cart);
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
}
// $isFine = CartController::stockVerification($cart, $request);
$this->applyReducedPricesToCart( $this->container->get('sylius.context.channel')->getChannel(), $cart, $this->container->get('doctrine.orm.entity_manager'));
// if(strpos($request->getPathInfo(), 'select_shipping') !== false) {
//On supprime la carte cadeau
// }
$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;
}
}
return new JsonResponse([
'livraison' => $this->renderView(
'@SyliusShop/Webapic/panier/pagepanier-right-livraison.html.twig',
[
'cart' => $cart,
'form' => $form->createView(),
'amount' => $amount,
'total' => $total,
'diff' => $diff,
'progress' => $progress,
]
),
'total' => $this->renderView(
'@SyliusShop/Cart/Summary/_totals.html.twig',
[
'cart' => $cart,
'form' => $form->createView(),
'amount' => $amount,
'total' => $total,
'diff' => $diff,
'progress' => $progress,
]
),
'widgettop' =>$this->renderView('@SyliusShop/Cart/_widget.html.twig', [
'cart' => $cart,
]),
'items' => $this->renderView(
'@SyliusShop/Cart/Summary/_items.html.twig',
[
'cart' => $cart,
'form' => $form->createView(),
]
),
// 'isFine' => true
// 'isFine' => $isFine
]);
}
public function widgetAction(Request $request): Response
{
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$cart = $this->getCurrentCart();
if (!$configuration->isHtmlRequest()) {
return $this->viewHandler->handle($configuration, View::create($cart));
}
return $this->render(
$configuration->getTemplate('summary.html'),
[
'cart' => $cart,
]
);
}
public function updateAction(Request $request): Response
{
// exit();
//
// echo 'maj du cart';
// Cas d'un paiement annulé ou refusé
$tokenValue = $request->query->get('tokenValue', null);
$paylinetoken = $request->query->get('paylinetoken', null);
dump($this->metadata);
if (empty($tokenValue) == false && empty($paylinetoken) == false) {
$cart = $this->getOrderRepository()->findOneBy([
'tokenValue' => $tokenValue
]);
if (empty($cart) == false) {
$orderSM = $this->getSMFactory()->get($cart, 'sylius_order_checkout');
if ($orderSM->can('reset')) {
$orderSM->apply('reset');
}
}
}
elseif(empty($tokenValue) == false) {
$cart = $this->getOrderRepository()->findOneBy([
'tokenValue' => $tokenValue
]);
if (empty($cart) == false) {
$orderSM = $this->getSMFactory()->get($cart, 'sylius_order_checkout');
if ($orderSM->can('reset')) {
$orderSM->apply('reset');
}
}
// dump($tokenValue);
}
dump($this->metadata);
dump($request);
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
dump($configuration);
$this->isGrantedOr403($configuration, ResourceActions::UPDATE);
try {
$resource = $this->findOr404($configuration);
}
catch (NotFoundHttpException $exception) {
if($request->getSession()->get('sylius_order_id')) {
$order = $this->getOrderRepository()->findOneBy([
'id' => $request->getSession()->get('sylius_order_id')
]);
$order->setState('cart');
$order->setCheckoutState('cart');
$order->setPaymentState('cart');
$order->setShippingState('cart');
foreach($order->getPayments() as $payment) {
$payment->setState('cart');
}
$payments = $order->getPayments();
if (count($payments) > 1) {
$first = true;
foreach ($payments as $payment) {
if ($first) {
$first = false;
continue;
}
$order->removePayment($payment);
}
}
// dump($order);
//On supprime les cartes cadeaux
// $order->getPayments()->first()->setState('cart');
$this->getOrderRepository()->add($order);
// $order->setShippingAdress(null);
// $order->setBillingAddress(null);
//
return $this->redirectToRoute('sylius_shop_cart_summary');
}
else {
throw new NotFoundHttpException(sprintf('The "%s" has not been found', $this->metadata->getHumanizedName()));
}
}
//On vérifie si on a une carte cadeau et on supprime si on est sur le choix shipping
$order=$resource;
if(strpos($request->getPathInfo(), 'select_shipping') !== false) {
//On supprime la carte cadeau
foreach($order->getPayments() as $payment) {
$details = $payment->getDetails();
if(array_key_exists('giftCardCode', $details)) {
$order->removePayment($payment);
}
}
$adjustements = $order->getAdjustments();
foreach($adjustements as $adjustement) {
$details = $adjustement->getDetails();
if($adjustement->getType() == AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT && array_key_exists('giftCardCode', $details)) {
$adjustement->unlock();
}
}
$order->removeAdjustments(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
}
// if($_SERVER['HTTP_X_FORWARDED_FOR'] == '130.93.57.197') {
// $shippingMethodsResolver = $this->container->get('sylius.shipping_method_eligibility_checker');
$shipment = $order->getShipments()->first();
if(empty($shipment)) {
//Cas d'erreur pas de transporteur sur le panier, ça peut arriver avec certains problèmes d'adresses
$shippingMethod = $this->container->get('sylius.repository.shipping_method')->findOneByCode('RETRAIT_EN_MAGASIN_1');
// dump($shippingMethod);
$shipment = $this->container->get('sylius.factory.shipment')->createNew();
$shipment->setMethod($shippingMethod);
$shipment->setState('cart');
// $shipment->setTracking($row->getShipments()[0]->getTracking());
// $shipment->setCreatedAt(Carbon::createFromFormat('Y-m-d H:i:s', $row->getShipments()[0]->getCreatedAt())->toDateTime());
// $shipment->setUpdatedAt(Carbon::createFromFormat('Y-m-d H:i:s', $row->getShipments()[0]->getUpdatedAt())->toDateTime());
$order->addShipment($shipment);
}
$shippingMethodsResolver = $this->container->get('sylius.shipping_methods_resolver');
$availableShippingMethods = $shippingMethodsResolver->getSupportedMethods($order->getShipments()->first());
$forceChange = true;
foreach($availableShippingMethods as $availableShippingMethod) {
if($availableShippingMethod->getId() == $order->getShipments()->first()->getMethod()->getId()) {
$forceChange = false;
}
}
if($forceChange) {
//On change la méthode car celle propsoée n'est aps disponible dans le pays
$shipment = $order->getShipments()->first();
$shipment->setMethod($availableShippingMethods[0]);
$shipment->setState('cart');
$order->addShipment($shipment);
}
// dump($forceChange);
// $shippingMethods = $this->container->get('sylius.repository.shipping_method')->findBy([
// 'enabled' => 1
// ]);
// foreach($shippingMethods as $shippingMethod) {
// if($shippingMethodsResolver->getSupportedMethods) {
// }
// }
// dump();
// dump($shipments);
// }
// if($_SERVER['HTTP_X_FORWARDED_FOR'] == '130.93.57.197') {
// dump($order);
// exit();
// }
//On surpprime les produits plus dispo
$removeProducts = false;
if(!empty($order->getItems())) {
foreach($order->getItems() as $item) {
// itemMin
$available = (($item->getVariant()->getOnHand()-($item->getVariant()->getItemMin() - 1)) > $item->getQuantity());
if(!$available) {
$this->get('session')->getFlashBag()->add('error', 'Le produit : '.$item->getVariantName().' n\'est plus disponible, il a été enlevé de votre panier');
$this->container->get('sylius.order_modifier')->removeFromOrder($order, $item);
$removeProducts = true;
}
}
if($removeProducts) {
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($order);
$cartManager->flush();
$this->applyReducedPricesToCart( $this->container->get('sylius.context.channel')->getChannel(), $order, $this->container->get('doctrine.orm.entity_manager'));
}
}
$this->getOrderRepository()->add($order);
dump($configuration);
dump($order);
$form = $this->resourceFormFactory->create($configuration, $order);
// dump($form->get('address'));
// $form->remove('address');
// $form->remove('second');
$form->handleRequest($request);
//On reload les sh
dump($form);
dump($order);
if (
in_array($request->getMethod(), ['POST', 'PUT', 'PATCH'], true)
&& $form->isSubmitted()
&& $form->isValid()
) {
// try {
// $form->remove('address');
// }
// catch (\Exception $exception) {
// }
$resource = $form->getData();
/** @var ResourceControllerEvent $event */
$event = $this->eventDispatcher->dispatchPreEvent(ResourceActions::UPDATE, $configuration, $resource);
if ($event->isStopped() && !$configuration->isHtmlRequest()) {
throw new HttpException($event->getErrorCode(), $event->getMessage());
}
if ($event->isStopped()) {
$this->flashHelper->addFlashFromEvent($configuration, $event);
$eventResponse = $event->getResponse();
if (null !== $eventResponse) {
return $eventResponse;
}
return $this->redirectHandler->redirectToResource($configuration, $resource);
}
try {
$this->resourceUpdateHandler->handle($resource, $configuration, $this->manager);
} catch (UpdateHandlingException $exception) {
if (!$configuration->isHtmlRequest()) {
return $this->createRestView($configuration, $form, $exception->getApiResponseCode());
}
$this->flashHelper->addErrorFlash($configuration, $exception->getFlash());
return $this->redirectHandler->redirectToReferer($configuration);
}
if ($configuration->isHtmlRequest()) {
$this->flashHelper->addSuccessFlash($configuration, ResourceActions::UPDATE, $resource);
}
// dump($configuration);
$postEvent = $this->eventDispatcher->dispatchPostEvent(ResourceActions::UPDATE, $configuration, $resource);
// dump($postEvent);
if (!$configuration->isHtmlRequest()) {
// dump($postEvent);
if ($configuration->getParameters()->get('return_content', false)) {
// dump($postEvent);
return $this->createRestView($configuration, $resource, Response::HTTP_OK);
}
return $this->createRestView($configuration, null, Response::HTTP_NO_CONTENT);
}
// dump($postEvent);
$postEventResponse = $postEvent->getResponse();
// dump($postEventResponse);
if (null !== $postEventResponse) {
return $postEventResponse;
}
// dump(3);
return $this->redirectHandler->redirectToResource($configuration, $resource);
}
if (!$configuration->isHtmlRequest()) {
return $this->createRestView($configuration, $form, Response::HTTP_BAD_REQUEST);
}
$initializeEvent = $this->eventDispatcher->dispatchInitializeEvent(ResourceActions::UPDATE, $configuration, $resource);
$initializeEventResponse = $initializeEvent->getResponse();
if (null !== $initializeEventResponse) {
return $initializeEventResponse;
}
return $this->render($configuration->getTemplate(ResourceActions::UPDATE . '.html'), [
'configuration' => $configuration,
'metadata' => $this->metadata,
'resource' => $resource,
$this->metadata->getName() => $resource,
'form' => $form->createView(),
]);
}
public function thankYouAction(
Request $request,
MessageBusInterface $bus,
CartController $cartController,
ChannelContextInterface $channelCtx,
OrderEmailManagerInterface $orderEmailManager,
SenderInterface $sender,
): Response
{
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$orderTokenValue = $request->query->get('token_value', null);
$orderId = $request->getSession()->get('sylius_order_id', null);
// dump($orderTokenValue);
// dump($orderId);
// dump($request->getSession());
// exit();
// Il y a un token dans la requête, on récupère la commande
// via ce token
if (empty($orderTokenValue) == false) {
$order = $this->repository->findOneByTokenValue($orderTokenValue);
if (empty($order) == true) {
// La commande n'existe pas avec ce token
return $this->redirectHandler->redirectToRoute(
$configuration,
'sylius_shop_cart_summary',
[]
);
}
}
// La commande est dans la session, on redirige vers la même page
// mais avec le "tokenValue"
if (empty($orderId) == false) {
$request->getSession()->remove('sylius_order_id');
$order = $this->repository->find($orderId);
if (empty($order) == true) {
// La commande n'existe plus du tout, on redirige sur le panier vide
return $this->redirectHandler->redirectToRoute(
$configuration,
'sylius_shop_cart_summary',
[]
);
}
// dump($order);
// dump($order->getTokenValue());
// dump( $request->attributes->get('_route'));
// dump($this->redirectHandler->);
// La commande existe, on redirige vers la page "thankYou" mais avec le tokenValue
return $this->redirectHandler->redirectToRoute(
$configuration,
$request->attributes->get('_route'),
['token_value' => $order->getTokenValue()]
);
}
Assert::notNull($order);
// dump($order);
// exit();
$form = $this->createForm(SiteCommentOrderType::class);
$form->handleRequest($request);
$repoOrderComment = $this->container->get('doctrine.orm.entity_manager')->getRepository(SiteCommentOrder::class);
$repoOrderComment = $repoOrderComment->findOneBy(['idorder' => $order->getId()]);
// $commentExist = 0;
// if (!empty($repoOrderComment)) {
// $commentExist = 1;
// }
if (
in_array($request->getMethod(), ['POST', 'PUT', 'PATCH'], true)
&& $form->isSubmitted()
&& $form->isValid()
) {
$data = $form->getData();
if(!empty($data->getComment())){
// $repoOrderComment = $this->container->get('doctrine.orm.entity_manager')->getRepository(SiteCommentOrder::class);
if (!empty($repoOrderComment)) {
$repoOrderComment->setComment($data->getComment());
}else{
$orderComment = new SiteCommentOrder();
$orderComment->setIdorder($order->getId());
$orderComment->setComment($data->getComment());
$em = $this->getDoctrine()->getManager();
$em->persist($orderComment);
$em->flush();
}
// $bus->dispatch(new ValidateOrder($order->getId(), true));
$this->get('session')->getFlashBag()->add('success', 'Message envoyé !');
}else{
$this->get('session')->getFlashBag()->add('error', 'Votre message est vide !');
}
}
// $bus = $this->get('sylius.bus.message');
// MessageBusInterface $bus)
$this->get('session')->getFlashBag()->clear();
//On vient supprimer les adjustements liés aux eventuelles cartes cadeaux (facilité pour tunnel d'achat)
$adjustements = $order->getAdjustmentsRecursively();
foreach($adjustements as $adjustement) {
$details = $adjustement->getDetails();
if($adjustement->getType() == AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT && array_key_exists('giftCardCode', $details)) {
$adjustement->unlock();
}
}
$order->removeAdjustments(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
$orderManager = $this->container->get('sylius.manager.order');
$orderManager->persist($order);
$orderManager->flush();
$bus->dispatch(new ValidateOrder($order->getId()));
//bug bizarre on a un nouveau pânier apres la creation de la commande
$cart = $this->container->get('sylius.context.cart')->getCart();
$cartItems = $cart->getItems();
foreach ($cartItems as $cartRow) {
// dump($cartRow);
$this->container->get('sylius.order_modifier')->removeFromOrder($cart, $cartRow);
}
// $channel = $channelCtx->getChannel();
// $cartController->applyReducedPricesToCart($channel, $cart);
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
//Email envoyé dans sync order désormais
// $orderEmailManager->sendConfirmationEmail($order);
foreach($order->getPayments() as $paiement){
//SI PAIEMENT BANCAIRE
if($paiement->getMethod()->getId() == 3){
$vars = array(
'order' => $order,
'localeCode' => $this->container->get('sylius.context.locale')->getLocaleCode()
);
$sender->send('orderpending', [$order->getCustomer()->getUser()->getEmail()], $vars);
}
}
// dump( $configuration->getParameters()->get('template'));
return $this->render(
$configuration->getParameters()->get('template'),
[
'order' => $order,
'form' => $form->createView(),
// 'commentExist' => $commentExist
],
);
}
public function tokenSoColissimo(WSColissimoService $wsColissimo)
{
return new JsonResponse($wsColissimo->getTokenColissimo());
}
public function deliveryShop()
{
$shopRepository = $this->container->get('doctrine.orm.entity_manager')->getRepository(SiteShop::class);
$shops = $shopRepository->createQueryBuilder('a')
->where('a.enabled = 1')
->orderBy('a.postalCode', 'ASC')
->getQuery()
->getResult();
return $this->render('order/block-delivery-shops.html.twig', [
'shops' => $shops
]);
}
public function updateCartDelivery(Request $request, PPMCErpSynchroService $ppmcErpSynchroService)
{
$cart = $this->getCurrentCart();
$shippingMethods = $this->container->get('sylius.repository.shipping_method')->createQueryBuilder('s')
->where('s.code LIKE :code')
->setParameter('code', $request->get('shippingMethod'))
->getQuery()
->getResult();
if(!empty($shippingMethods)) {
$shippingMethod = $shippingMethods[0];
// $cart->getShipments()->first()->setState('ready');
$cart->getShipments()->first()->setMethod($shippingMethod);
$cart->setOrderPickupShop(null);
$cart->setOrderPickupSoColissimo(null);
$cart->setOrderPickupName(null);
if($request->get('identifiant')) {
$cart->setOrderPickupSoColissimo($request->get('identifiant'));
$cart->setOrderPickupName($request->get('nom'));
}
else if($request->get('idPickupShop')) {
$cart->setOrderPickupShop($request->get('idPickupShop'));
$cart->setOrderPickupName($request->get('pickupName'));
}
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
}
// dump($shippingMethod);
// $shippingMethod = $container->get('sylius.repository.shipping_method')->findOneById(
// $generixRow->getShipments()[0]->getMethodId()
// );
// $order->setShippingState('cart');
// echo $request->get('shippingMethod');
return new JsonResponse('success');
}
protected function redirectToCartSummary(RequestConfiguration $configuration): Response
{
if (null === $configuration->getParameters()->get('redirect')) {
return $this->redirectHandler->redirectToRoute($configuration, $this->getCartSummaryRoute());
}
return $this->redirectHandler->redirectToRoute($configuration, $configuration->getParameters()->get('redirect'));
}
protected function getCartSummaryRoute(): string
{
return 'sylius_cart_summary';
}
protected function getCurrentCart(): OrderInterface
{
return $this->getContext()->getCart();
}
protected function getContext(): CartContextInterface
{
return $this->get('sylius.context.cart');
}
protected function getOrderRepository(): OrderRepositoryInterface
{
return $this->get('sylius.repository.order');
}
protected function getSMFactory()
{
return $this->container->get('sm.factory');
}
protected function getEventDispatcher(): EventDispatcherInterface
{
return $this->container->get('event_dispatcher');
}
/**
* @return mixed
*
* @deprecated This function will be removed in Sylius 2.0, since Symfony 5.4, use explicit input sources instead
* based on Symfony\Component\HttpFoundation\Request::get
*/
private function getParameterFromRequest(Request $request, string $key)
{
if ($request !== $result = $request->attributes->get($key, $request)) {
return $result;
}
if ($request->query->has($key)) {
return $request->query->all()[$key];
}
if ($request->request->has($key)) {
return $request->request->all()[$key];
}
return null;
}
public function paiementkdoShop(Request $request, PPMCErpSynchroService $ppmcErpSynchroService)
{
$cart = $this->getCurrentCart();
$giftCard = $ppmcErpSynchroService->checkGiftCard(
$request->get('code'),
$request->get('key')
);
if($request->get('use')) {
if($giftCard->getAmount()) {
$giftAmout = (int)($giftCard->getAmount()*100);
if($cart->getTotal() < $giftAmout) {
$giftAmout = $cart->getTotal();
}
else {
foreach($cart->getPayments() as $payment) {
if($payment->getState() == 'cart') {
$payment->setAmount($payment->getAmount()-$giftAmout);
break;
}
}
}
// echo $giftAmout;
//On ajoute une ligne de paiement
$payment = $this->container->get('sylius.factory.payment')->createNew();
$payment->setCurrencyCode('EUR');
$payment->setDetails([
"giftCardCode" => $request->get('code'),
"giftCardKey" => $request->get('key')
]);
$payment->setMethod($this->container->get('sylius.repository.payment_method')->findOneByCode('KDO'));
$payment->setAmount($giftAmout);
$payment->setState('completed');
$cart->addPayment($payment);
//On ajoute un adjsutment pour les prochgains calculs du reste à payer
$adjustment = $this->container->get('sylius.factory.adjustment')->createNew();
$adjustment->setType(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
$adjustment->setAmount(-$giftAmout);
$adjustment->setNeutral(false);
$adjustment->setLabel('Carte cadeau : '.$request->get('code'));
$adjustment->setDetails([
"giftCardCode" => $request->get('code')
]);
$cart->addAdjustment($adjustment);
$adjustment->lock();
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
$this->container->get('doctrine.orm.entity_manager')->refresh($cart);
}
}
return new JsonResponse([
"amount" => $giftCard->getAmount(),
"error" => $giftCard->getError()
]);
}
public function deliveryApel(Request $request, PPMCErpSynchroService $ppmcErpSynchroService)
{
$em = $this->get('doctrine')->getManager();
if ($request->isMethod('POST')) {
$error = "";
$success = "";
$cart = $this->getCurrentCart();
$nom = $request->get('nom');
$prenom = $request->get('prenom');
$classe = $request->get('classe');
$idecole = $request->get('idecole');
if(!empty($nom) && !empty($prenom) && !empty($classe) && !empty($idecole)){
$apelData = array(
'nom' => $nom,
'prenom' => $prenom,
'classe' => $classe,
'idecole' => $idecole,
);
$ecole = $em->getRepository(SiteApel::class)->find($idecole);
$cart->setApel(json_encode($apelData));
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
$this->container->get('doctrine.orm.entity_manager')->refresh($cart);
$success = "Les informations sont sauvegardées";
}else{
$error = "Veuillez saisir toutes les informations et choisir une école";
return new JsonResponse([
"error" => $error,
]);
}
// $cart->setOrderPickupShop(null);
return new JsonResponse([
"success" => $success,
"info" => 'Ecole '.$ecole->getName().' - '.$nom.' '.$prenom.' en classe de '.$classe,
]);
}else{
// $apels = $em->getRepository(SiteApel::class)->findAll();
$shopRepository = $em->getRepository(SiteApel::class);
$apels = $shopRepository->createQueryBuilder('a')
->where('a.enabled = 1')
->orderBy('a.postalCode', 'ASC')
->getQuery()
->getResult();
$listapels = array();
if(count($apels) > 0){
foreach($apels as $key => $apel){
// $listapels[] = $apel;
if( ( empty($apel->getDateStart()) || empty($apel->getDateEnd()))
|| ( time() > $apel->getDateStart()->getTimestamp() && time() < $apel->getDateEnd()->getTimestamp() )
){
// $listapels[$key]['lat'] = $apel->getLat();
// $listapels[$key]['long'] = $apel->getLon();
// $listapels[$key]['id'] = $apel->getId();
// $listapels[$key]['desc'] = $apel->getName()." - ".$apel->getCity();
$apeljson = array();
$apeljson['lat'] = $apel->getLat();
$apeljson['long'] = $apel->getLon();
$apeljson['id'] = $apel->getId();
$apeljson['desc'] = $apel->getName()." - ".$apel->getCity();
$listapels[] = $apeljson;
}
}
}
return new JsonResponse(
$listapels
);
}
}
public function submitCoupon(Request $request)
{
$formCodePromo = $this->createForm(SiteCodePromotionType::class);
$formCodePromo->handleRequest($request);
$cart = $this->getCurrentCart();
if(isset($_GET['codepromo'])){
$codepromo = '0';
}else{
$codepromo = $request->request->get("app_site_codepromotion");
$codepromo = $codepromo['codePromo'];
}
$cart->setCodePromo( $codepromo);
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
$this->applyReducedPricesToCart( $this->container->get('sylius.context.channel')->getChannel(), $cart, $this->container->get('doctrine.orm.entity_manager'));
if($cart->getCodePromoValid() == 1){
$this->addFlash('success', 'Votre coupon est appliqué'.$request->request->get("app_site_codepromotion['codePromo']"));
}else{
if( $codepromo == 0){
$this->addFlash('error', 'Coupon supprimé');
}else{
$this->addFlash('error', 'Ce coupon n\'existe pas');
}
}
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
return $this->redirectHandler->redirectToRoute(
$configuration,
'sylius_shop_cart_summary',
[]
);
}
public function applyReducedPricesToCart($channel, $cart, $em): void
{
// if (count($cart->getItems()) <= 0) {
// return;
// }
$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();
$em->refresh($cart);
$cartItems = $cart->getItems();
foreach ($cartItems as $cartRow) {
$em->refresh($cartRow);
}
} catch (ProcessTimedOutException $exception) {
// echo 'bofbof';
}
}
public function commentAdminAction(Request $request)
{
// dump($order);
$siteCommentOrder = $this->getDoctrine()
->getRepository(SiteCommentOrder::class)
->findOneBy(
[
'idorder' => $request->query->get('order')
]
);
$comment = '';
if($siteCommentOrder){
$comment = $siteCommentOrder->getComment();
}
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
return $this->render(
$configuration->getTemplate('admin/order/comment.html'),
[
'comment' => $comment,
]
);
}
protected function payLog(Request $request, $token) {
$cart = $this->container->get('sylius.context.cart')->getCart();
$data = (array) $request->request->all();
$log = "Cart id - ".$cart->getId();
// $log .= print_r();;
$logger = $this->get('monolog.logger.paydebug');
// $logger = new Logger('paydebug');
$logger->debug($log);
$logger->debug(print_r($data, true));
//
// dump($data);
}
public function productNoStockAction(Request $request, $id): Response
{
$cart = $this->container->get('sylius.context.cart')->getCart();
if (null !== $cart->getId()) {
$em = $this->container->get('doctrine')->getManager();
$siteProductNoStockRepo = $em->getRepository(SiteProductNoStock::class);
$siteProductsNoStock = $siteProductNoStockRepo->findOneBy(
['order' => $cart->getId(), 'productVariant' => $id]
);
if($siteProductsNoStock){
$em->remove($siteProductsNoStock);
// $em->persist($siteProductNoStockRepo);
$em->flush();
}
dump($siteProductsNoStock);
}
return new JsonResponse('success');
}
public function orderAgainAction(Request $request, $tokenValue = null) {
$customer = $this->get('sylius.context.customer')->getCustomer();
if($tokenValue != null && !empty($customer)) {
//On charge la commande
$order = $this->get('sylius.repository.order')->findOneBy([
'tokenValue' => $tokenValue,
'customer' => $customer
]);
if (empty($order) == false && $order->getState() != 'cart') {
//On duplique
$defaultChannel = $this->container->get('sylius.repository.channel')->findAll()[0];
$newCart = $this->container->get('sylius.factory.order')->createNew();
$newCart->setChannel($defaultChannel);
$newCart->setCurrencyCode('EUR');
$newCart->setCreatedByGuest(false);
$newCart->setCustomer($customer);
$newCart->setLocaleCode($order->getLocaleCode());
$defaultAddress = $customer->getDefaultAddress();
$this->container->get('doctrine')->getManager()->initializeObject($defaultAddress);
if (null !== $defaultAddress) {
// dump($defaultAddress);
$clonedAddress = clone $defaultAddress;
$clonedAddress->setCustomer(null);
$newCart->setBillingAddress($clonedAddress);
$clonedAddress = clone $clonedAddress;
$newCart->setShippingAddress($clonedAddress);
}
$shippingMethod = $this->container->get('sylius.repository.shipping_method')->findOneByCode('RETRAIT_EN_MAGASIN_1');
$shipment = $this->container->get('sylius.factory.shipment')->createNew();
$shipment->setMethod($shippingMethod);
$shipment->setState('cart');
$newCart->addShipment($shipment);
$payment = $this->container->get('sylius.factory.payment')->createNew();
$payment->setCurrencyCode('EUR');
$payment->setDetails([]);
$payment->setMethod($order->getPayments()->first()->getMethod());
$payment->setAmount($order->getPayments()->first()->getAmount());
$payment->setState('cart');
$newCart->addPayment($payment);
foreach($order->getItems() as $item) {
$newItem = $this->container->get('sylius.factory.order_item')->createNew();
$newItem->setVariantName($item->getVariantName());
$newItem->setImmutable(true);
$newItem->setUnitPrice($item->getUnitPrice());
$newItem->setOriginalUnitPrice($item->getOriginalUnitPrice());
$newItem->setVariant($item->getVariant());
$newItem->setConditioning($item->getConditioning());
$newItem->setConditioningValue($item->getConditioningValue());
$this->container->get('sylius.order_item_quantity_modifier')->modify($newItem, $item->getQuantity());
$newCart->addItem($newItem);
}
$this->container->get('sylius.repository.order')->add($newCart);
$this->get('session')->set('_sylius.cart.ppmc', $newCart->getId());
$this->applyReducedPricesToCart($this->container->get('sylius.context.channel')->getChannel(), $newCart, $this->container->get('doctrine.orm.entity_manager'));
}
}
return $this->redirectToRoute('sylius_shop_cart_summary');
}
public function confirmDeliveryAddress(Request $request)
{
$em = $this->get('doctrine')->getManager();
if ($request->isMethod('POST')) {
$error = "";
$success = "";
$cart = $this->getCurrentCart();
$nom = $request->get('nom');
$prenom = $request->get('prenom');
$telephone = $request->get('telephone');
if(!empty($nom) && !empty($prenom) && !empty($telephone) ){
$apelData = array(
'nom' => $nom,
'prenom' => $prenom,
'telephone' => $telephone,
);
dump($cart);
dump($prenom);
// $address = $em->getRepository(Address::class)->find($idecole);
$cart->getShippingAddress()->setFirstName($prenom);
$cart->getShippingAddress()->setLastName($nom);
$cart->getShippingAddress()->setPhoneNumber($telephone);
// $ecole = $em->getRepository(SiteApel::class)->find($idecole);
// $cart->setApel(json_encode($apelData));
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
$this->container->get('doctrine.orm.entity_manager')->refresh($cart);
$success = "Les informations sont sauvegardées";
}else{
$error = "Veuillez saisir toutes les informations de livraison";
return new JsonResponse([
"error" => $error,
]);
}
// $cart->setOrderPickupShop(null);
return new JsonResponse([
"success" => $success,
]);
}
}
public function addAddressDelivery(Request $request) {
$checkout = $request->get('checkout');
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$customer = $this->get('sylius.context.customer')->getCustomer();
$address = $this->container->get('sylius.factory.address')->createNew();
$address->setFirstName($checkout['address']['shippingAddress']['firstName']);
$address->setLastName($checkout['address']['shippingAddress']['lastName']);
$address->setPhoneNumber($checkout['address']['shippingAddress']['phoneNumber']);
$address->setCountryCode($checkout['address']['shippingAddress']['countryCode']);
$address->setCity($checkout['address']['shippingAddress']['city']);
$address->setStreet($checkout['address']['shippingAddress']['street']);
$address->setPostcode($checkout['address']['shippingAddress']['postcode']);
$address->setStreetComplementary($checkout['address']['shippingAddress']['streetComplementary']);
$address->setCustomer($customer);
$addressManager = $this->container->get('sylius.manager.address');
$addressManager->persist($address);
$addressManager->flush();
$customer->setDefaultAddress($address);
$customerManager = $this->container->get('sylius.manager.customer');
$customerManager->persist($customer);
$customerManager->flush();
$cart = $this->getCurrentCart();
if(!empty($customer) && $cart->getBillingAddress() == null) {
$clonedAddress = clone $address;
$clonedAddress->setCustomer(null);
$cart->setBillingAddress($clonedAddress);
if($cart->getShippingAddress() == null) {
$clonedAddress = clone $address;
$clonedAddress->setCustomer(null);
$cart->setShippingAddress($clonedAddress);
}
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
}
return $this->redirectHandler->redirectToRoute(
$configuration,
'bitbag_sylius_one_page_checkout_shop_checkout'
);
}
public function selectCountryDelivery(Request $request) {
// dump($request);
$cart = $this->getCurrentCart();
$cart->getShippingAddress()->setCountryCode($request->get('countryCode'));
// Reset les shipments
$shipments = $cart->getShipments();
foreach ($shipments as $shipment) {
$cart->removeShipment($shipment);
}
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
return new JsonResponse([
"success" => 'ok',
]);
}
public function selectAddressDelivery(Request $request) {
// dump($request);
$id = $request->get('id');
$cart = $this->getCurrentCart();
$cart->setSelectedShippingAddressId($request->get('id'));
$cartManager = $this->container->get('sylius.manager.order');
$cartManager->persist($cart);
$cartManager->flush();
return new JsonResponse([
"success" => 'ok',
]);
}
public function getShop2ShopPoints(Request $request, WSShop2ShopService $wSShop2ShopService) {
// dump($request);
$points = $wSShop2ShopService->getPickupPoints($request->get('address'), $request->get('postcode'), $request->get('city'));
return new JsonResponse([
"points" => $points,
]);
}
public function setShop2ShopOrderPoint(Request $request, PPMCErpSynchroService $ppmcErpSynchroService) {
// dump($request->request->all());
$ppmcErpSynchroService->checkPointRelais($request->request->all());
// $points = $wSShop2ShopService->getPickupPoints($request->get('postcode'), $request->get('city'));
return new JsonResponse([
"success" => 'ok',
]);
}
public function paymentStatusAction(Request $request, $id) {
$customer = $this->container->get('sylius.context.customer')->getCustomer();
$orders = $this->container->get('sylius.repository.order')->findBy([
'customer' => $customer
]);
foreach($orders as $order) {
if(count($order->getPayments()) == 0) {
continue;
}
if($order->getPayments()->first()->getId() == $id) {
return new JsonResponse([
"success" => $order->getPayments()->first()->getState(),
]);
// dump($order->getPayments()->first());
}
}
return new JsonResponse([
"success" => 'error',
]);
}
public function paymentLinkAction(Request $request, $tokenValue) {
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$resource = $this->findOr404($configuration);
$form = $this->resourceFormFactory->create($configuration, $resource);
return $this->render('bundles/BitBagSyliusOnePageCheckoutPlugin/checkout_payonly.html.twig', [
'order' => $resource,
'form' => $form->createView(),
]);
}
public function paymentLinkChoosePaymentAction(Request $request, $tokenValue) {
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$resource = $this->findOr404($configuration);
dump($request->get('checkout')['select_payment']['payments']);
$resource->getPayments()->first()->setMethod($this->container->get('sylius.repository.payment_method')->findOneByCode($request->get('checkout')['select_payment']['payments'][0]['method']));
// dump($request->request->all());
$orderManager = $this->container->get('sylius.manager.order');
$orderManager->persist($resource);
$orderManager->flush();
return $this->render('bundles/BitBagSyliusOnePageCheckoutPlugin/_checkout_submitted.html.twig', [
'order' => $resource
]);
}
public function paymentLinkCheckoutCompleteAction(Request $request, $tokenValue, FactoryInterface $stateMachineFactory) {
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$resource = $this->findOr404($configuration);
// $stateMachine = $stateMachineFactory->get($resource, $request->attributes->get('_sylius')['state_machine']['graph']);
// dump($stateMachine);
// $this->redirect($this->generateUrl($configuration['redirect']['route'], ['tokenValue' => $resource->getTokenValue()]));
// return $this->redirectHandler->redirectToReferer($configuration);
// $resource-getREdi
// dump($configuration->getParameters()->get('redirect'));
return $this->redirectHandler->redirectToRoute($configuration, $configuration->getParameters()->get('redirect')['route'], ['tokenValue' => $resource->getTokenValue()]);
// dump($configuration);
// $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
// $resource = $this->findOr404($configuration);
// $resource->setState('completed');
// $orderManager = $this->container->get('sylius.manager.order');
// $orderManager->persist($resource);
// $orderManager->flush();
// return $this->render('bundles/BitBagSyliusOnePageCheckoutPlugin/_checkout_submitted.html.twig', [
// 'order' => $resource
// ]);
// return new JsonResponse([
// "success" => 'success',
// ]);
}
}