src/Controller/Front/CommandController.php line 179

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Front;
  3. use App\Entity\AppFee;
  4. use App\Entity\Command;
  5. use App\Entity\CommandPack;
  6. use App\Entity\CommandProduct;
  7. use App\Entity\Product;
  8. use App\Entity\ProductOption;
  9. use App\Entity\Transfert;
  10. use App\Form\BrowserInfoType;
  11. use App\Form\ConfirmAdresseUserType;
  12. use App\Form\ValidPromoCodeType;
  13. use App\Repository\AdminPromoRepository;
  14. use App\Repository\CommandProductRepository;
  15. use App\Repository\CommandRepository;
  16. use App\Repository\CompanyRepository;
  17. use App\Repository\PackRepository;
  18. use App\Repository\ProductOptionRepository;
  19. use App\Repository\ProductRepository;
  20. use App\Repository\TransporteurWeightPriceRepository;
  21. use App\Services\Filter;
  22. use App\Services\Mail;
  23. use App\Services\MangoPayService;
  24. use App\Services\StripeClient;
  25. use App\Services\StripeConnectService;
  26. use DateTime;
  27. use DateTimeImmutable;
  28. use Doctrine\ORM\EntityManagerInterface;
  29. use Dompdf\Dompdf;
  30. use Dompdf\Options;
  31. use MangoPay\BrowserInfo;
  32. use MangoPay\Libraries\ResponseException;
  33. use MangoPay\PayInRecurringRegistration;
  34. use MangoPay\TransactionStatus;
  35. use Stripe\Charge;
  36. use Stripe\Stripe;
  37. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  38. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  39. use Symfony\Component\HttpFoundation\Request;
  40. use Symfony\Component\HttpFoundation\Response;
  41. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  42. use Symfony\Component\Routing\Annotation\Route;
  43. use Symfony\Component\Validator\Constraints\NotBlank;
  44. use Symfony\Contracts\HttpClient\HttpClientInterface;
  45. class CommandController extends AbstractController
  46. {
  47.     /**
  48.      * @var EntityManagerInterface
  49.      */
  50.     private $em;
  51.     /**
  52.      * @var HttpClientInterface
  53.      */
  54.     private $client;
  55.     public function __construct(EntityManagerInterface $emHttpClientInterface $client)
  56.     {
  57.         $this->em $em;
  58.         $this->client $client;
  59.     }
  60.     /**
  61.      * @Route("/mon-panier", name="front_my_basket")
  62.      */
  63.     public function basket(Request $requestSessionInterface $sessionProductRepository $productRepositoryPackRepository $packRepository)
  64.     {
  65.         $products $session->get('products');
  66.         $form $this->createForm(ValidPromoCodeType::class)->handleRequest($request);
  67.         $allProducts = [];
  68.         if (!empty($products)) {
  69.             foreach ($products as $productId) {
  70.                 if (!empty($productId['options_fairepar']) && $productId['options_fairepar'] != null) {
  71.                     $product $productRepository->find($productId['productId']);
  72.                     $quantity $productId['quantity'];
  73.                     $optionsf $productId['options_fairepar'];
  74.                     $allProducts[] = [
  75.                         'productId' => $product->getId(),
  76.                         'product' => $product,
  77.                         'quantity' => $quantity,
  78.                         'options_farep' => $optionsf,
  79.                         'promo' => null,
  80.                     ];
  81.                 } else {
  82.                     $product $productRepository->find($productId['productId']);
  83.                     $quantity $productId['quantity'];
  84.                     // $quantityOpt = $productId['qtyOption'];
  85.                     $size $productId['size'];
  86.                     $color $productId['color'];
  87.                     // $optionsArray = [];
  88.                     // if (!empty($productId['options'])) {
  89.                     //     foreach ($productId['options'] as $optionId => $price) {
  90.                     //         $optionsArray[] = $optionId;
  91.                     //     }
  92.                     // }
  93.                     // $optionsQtyArray = [];
  94.                     // if (!empty($productId['qtyOption'])) {
  95.                     //     foreach ($productId['qtyOption'] as $optionIdQty => $qtyO) {
  96.                     //         $optionsQtyArray[] = $optionIdQty;
  97.                     //     }
  98.                     // }
  99.                     //dd($products,$productId['options'],$productId['qtyOption']);
  100.                     $allProducts[] = [
  101.                         'productId' => $product->getId(),
  102.                         'product' => $product,
  103.                         'quantity' => $quantity,
  104.                         'size' => $size,
  105.                         'color' => $color,
  106.                         'options' => $productId['options'],
  107.                         'promo' => null,
  108.                         // 'qtyOption' => $quantityOpt
  109.                     ];
  110.                 }
  111.             }
  112.         }
  113.         // dd($products,$allProducts);
  114.         if ($session->get('packs')) {
  115.             $pack $packRepository->findOneBy(['id' => $session->get('packs')]);
  116.         } else {
  117.             $pack null;
  118.         }
  119.         $isMessagePromo false;
  120.         if ($form->isSubmitted() && $form->isValid()) {
  121.             $codePromo $form->get('codePromo')->getData();
  122.             foreach ($allProducts as $key => $arrayProduct) {
  123.                 /** @var Product $product */
  124.                 //    dd($key, $arrayProduct);
  125.                 $product $arrayProduct['product'];
  126.                 if ($arrayProduct['options_farep'] != null) {
  127.                     $productOpt $arrayProduct['options'];
  128.                     //dd($productOpt);
  129.                     $newArrayProduct $arrayProduct;
  130.                     if ($codePromo === $product->getCodePromo()) {
  131.                         //dd($newArrayProduct);
  132.                         $newArrayProduct['promo'] = $product->getCodePromoEuro();
  133.                         $newArrayProduct['options'] = $productOpt;
  134.                         unset($allProducts[$key]);
  135.                         $allProducts[] = $newArrayProduct;
  136.                         $isMessagePromo true;
  137.                     }
  138.                 } else {
  139.                     $productOpt $arrayProduct['options'];
  140.                     //dd($productOpt);
  141.                     $newArrayProduct $arrayProduct;
  142.                     if ($codePromo === $product->getCodePromo()) {
  143.                         //dd($newArrayProduct);
  144.                         $newArrayProduct['promo'] = $product->getCodePromoEuro();
  145.                         $newArrayProduct['options'] = $productOpt;
  146.                         unset($allProducts[$key]);
  147.                         $allProducts[] = $newArrayProduct;
  148.                         $isMessagePromo true;
  149.                     }
  150.                 }
  151.             }
  152.             $session->set('products'$allProducts);
  153.         }
  154.         return $this->render('front/command/basket.html.twig', [
  155.             'products' => $allProducts,
  156.             'pack' => $pack,
  157.             'form' => $form->createView(),
  158.             'isMessagePromo' => $isMessagePromo
  159.         ]);
  160.     }
  161.     /**
  162.      * @Route("/get-option/{id}", name="get_option")
  163.      */
  164.     public function getOption(SessionInterface $sessionProductOptionRepository $productOptionRepositoryProduct $productFilter $filtre$id): Response
  165.     {
  166.         $modifOption $filtre->getProductOptionByProduit($product);
  167.         $qtoption $session->get('products');
  168.         $qte = [];
  169.         foreach ($qtoption as $qt) {
  170.             if ($qt['productId'] == $id) {
  171.                 $qte["qty"] = $qt['qtyOption'];
  172.             }
  173.         }
  174.         $data[] = $modifOption;
  175.         $data[] = $qte;
  176.         $data[] = $id;
  177.         return $this->json($data200, [], ['groups' => 'post:read']);
  178.     }
  179.     /**
  180.      * @Route("/mon-panier/suppression-article/{id}", name="front_my_basket_remove_product")
  181.      */
  182.     public function removeProductToBasket(Product $productSessionInterface $session)
  183.     {
  184.         $allProducts $session->get('products');
  185.         foreach ($session->get('products') as $key => $productSession) {
  186.             if (array_search($product->getId(), $productSession)) {
  187.                 unset($allProducts[$key]);
  188.                 $session->set('products'$allProducts);
  189.             }
  190.         }
  191.         return $this->redirectToRoute('front_my_basket');
  192.     }
  193.     /**
  194.      * @Route("/commande/livraison", name="front_command_livraison")
  195.      */
  196.     public function livraison(SessionInterface $sessionPackRepository $packRepositoryProductRepository $productRepository)
  197.     {
  198.         if (!$this->getUser()) {
  199.             $session->set('commandInCurse'true);
  200.             return $this->redirectToRoute('app_login');
  201.         }
  202.         $products $session->get('products');
  203.         $packs $session->get('packs');
  204.         if ($session->get('packs')) {
  205.             $pack $packRepository->findOneBy(['id' => $session->get('packs')]);
  206.         } else {
  207.             $pack null;
  208.         }
  209.         $allProducts = [];
  210.         if (!empty($products)) {
  211.             foreach ($products as $productId) {
  212.                 $optionsArray = [];
  213.                 if (!empty($productId['options'])) {
  214.                     foreach ($productId['options'] as $optionId => $price) {
  215.                         $optionsArray[] = $optionId;
  216.                     }
  217.                 }
  218.                 $optionFeraparArray = [];
  219.                 if (!empty($productId['options_fairepar'])) {
  220.                     for ($i 0$i sizeof($productId['options_fairepar']); $i++) {
  221.                         $optionFeraparArray[] = $productId['options_fairepar']['option_' $i];
  222.                     }
  223.                 }
  224.                 $product $productRepository->find($productId['productId']);
  225.                 $isService false;
  226.                 foreach ($product->getSubCategories() as $subcategory) {
  227.                     if ($subcategory->getIsService()) {
  228.                         $isService true;
  229.                     }
  230.                 }
  231.                 $quantity $productId['quantity'];
  232.                 $size $productId['size'];
  233.                 $color $productId['color'];
  234.                 $promo $productId['promo'] ?? null;
  235.                 $allProducts[] = [
  236.                     'id' => $product->getId(),
  237.                     'product' => $product,
  238.                     'quantity' => $quantity,
  239.                     'size' => $size,
  240.                     'color' => $color,
  241.                     'isService' => $isService,
  242.                     'pack' => null,
  243.                     'options' => $productId['options'],
  244.                     'options_fairepar' => $optionFeraparArray,
  245.                     'promo' => $promo,
  246.                     'transporteurs' => $product->getTransporteurs()
  247.                 ];
  248.             }
  249.         }
  250.         if (!empty($packs)) {
  251.             $pack $packRepository->find($packs);
  252.             foreach ($pack->getProductPercents() as $productPercent) {
  253.                 $allProducts[] = [
  254.                     'product' => $productPercent->getProduct(),
  255.                     'quantity' => null ?? 1,
  256.                     'size' => null,
  257.                     'color' => null,
  258.                     'pack' => $pack->getName()
  259.                 ];
  260.             }
  261.         }
  262.         return $this->render('front/command/livraison.html.twig', [
  263.             'products' => $allProducts,
  264.             'pack' => $pack
  265.         ]);
  266.     }
  267.     /**
  268.      * @Route("/commande/validation", name="front_command_validation")
  269.      */
  270.     public function validateCommand(
  271.         SessionInterface $session,
  272.         Request $request,
  273.         ProductOptionRepository $productOptionRepository,
  274.         ProductRepository $productRepository,
  275.         PackRepository $packRepository,
  276.         TransporteurWeightPriceRepository $transporteurWeightPriceRepository,
  277.         AdminPromoRepository $adminPromoRepository
  278.     ) {
  279.         $products $session->get('products');
  280.         if ($request->get('livraison')) {
  281.             $session->set('livraison'$request->get('livraison'));
  282.         }
  283.         if ($request->get('address') && $request->get('address') != "") {
  284.             $session->set('address'$request->get('address'));
  285.             /** @var User $user */
  286.             $user $this->getUser();
  287.             $address explode(','$request->get('address'));
  288.             $user->setLivraisonAdress($address[0]);
  289.             $user->setLivraisonZipCode($address[1]);
  290.             $user->setLivraisonCity($address[2]);
  291.         }
  292.         $isLivraison false;
  293.         $isService false;
  294.         $isFairepart false;
  295.         if (!empty($products)) {
  296.             foreach ($products as $productId) {
  297.                 $product $productRepository->find($productId['productId']);
  298.                 foreach ($product->getSubCategories() as $subCategory) {
  299.                     if ($subCategory->getIsService()) {
  300.                         $isService true;
  301.                     }
  302.                     if ($subCategory->getIsSuivi()) {
  303.                         $isLivraison true;
  304.                     }
  305.                     if ($subCategory->getIsFairepart()) {
  306.                         $isFairepart true;
  307.                     }
  308.                 }
  309.             }
  310.         }
  311.         $form $this->createForm(ConfirmAdresseUserType::class, $this->getUser(), ['isLivraison' => $isLivraison'isService' => $isService])->handleRequest($request);
  312.         if ($form->isSubmitted() && $form->isValid()) {
  313.             $newCommand = new Command();
  314.             $newCommand->setClient($this->getUser());
  315.             $newCommand->setRelaypoint($session->get('address'));
  316.             $totalAmount 0;
  317.             $totalFraisLivraison 0;
  318.             if (!empty($products)) {
  319.                 foreach ($products as $productId) {
  320.                     $product $productRepository->find($productId['productId']);
  321.                     $quantity $productId['quantity'];
  322.                     $newCommandProduct = new CommandProduct();
  323.                     $newCommandProduct->setProduct($product);
  324.                     $newCommandProduct->setCommand($newCommand);
  325.                     $newCommandProduct->setQuantity($quantity);
  326.                     if ($productId['size']) {
  327.                         $newCommandProduct->setSize($productId['size']);
  328.                     }
  329.                     if ($productId['color']) {
  330.                         $newCommandProduct->setColor($productId['color']);
  331.                     }
  332.                     if (array_key_exists('promo'$productId)) {
  333.                         $newCommandProduct->setPromo($productId['promo']);
  334.                     }
  335.                     $arrayLivraisons $session->get('livraison');
  336.                     if ($arrayLivraisons && array_key_exists($product->getId(), $arrayLivraisons)) {
  337.                         $transporteur $transporteurWeightPriceRepository->find($arrayLivraisons[$product->getId()]['transporteur']);
  338.                         $weightInInt str_replace('g'''$transporteur->getWeight());
  339.                         $weightInInt = (int) str_replace('kg'''$weightInInt);
  340.                         $totalWeightProducts $weightInInt $quantity;
  341.                         $arrayLivraisonMode = [
  342.                             'idTransporteur' => $transporteur->getTransporteur()->getId(),
  343.                             'idTransporteurWeight' => $transporteur->getId(),
  344.                             'totalWeight' => $totalWeightProducts,
  345.                         ];
  346.                         $newCommandProduct->setLivraisonMode($arrayLivraisonMode);
  347.                         $totalFraisLivraison $totalFraisLivraison $transporteur->getPrice();
  348.                         $newCommandProduct->setLivraisonPrice($transporteur->getPrice());
  349.                     }
  350.                     $priceOptions 0;
  351.                     if ($isFairepart) {
  352.                         if (!empty($productId['options_fairepar'])) {
  353.                             $arrayOptions = [];
  354.                             for ($j 0$j sizeof($productId['options_fairepar']); $j++) {
  355.                                 $arrayOptions[] = $productId['options_fairepar']['option_' $j];
  356.                                 $operation $productId['options_fairepar']['option_' $j]['quantite'] * $productId['options_fairepar']['option_' $j]['price'];
  357.                                 $priceOptions $priceOptions $operation;
  358.                             }
  359.                             $newCommandProduct->setOptionfarepart($arrayOptions);
  360.                         }
  361.                     }
  362.                     if (!empty($productId['options'])) {
  363.                         $arrayOptions = [];
  364.                         foreach ($productId['options'] as $key => $optiond) {
  365.                             $optionProduct $productOptionRepository->find($key);
  366.                             $priceOptions 0;
  367.                             $group = [];
  368.                             foreach ($optiond as $vale) {
  369.                                 $priceOptions $priceOptions $optionProduct->getPrice();
  370.                                 $operation $vale["prix"] * ($vale["qte"] ? $vale["qte"] : 1);
  371.                                 $priceOptions $priceOptions $operation;
  372.                                 $group[$vale["valeur"]] = [
  373.                                     'price' => $vale["prix"],
  374.                                     'qty' => $vale["qte"] ? $vale["qte"] : 1
  375.                                 ];
  376.                             }
  377.                             $arrayOptions[] = [
  378.                                 'id' => $optionProduct->getId(),
  379.                                 'name' => $optionProduct->getName(),
  380.                                 'group' => $group
  381.                             ];
  382.                         }
  383.                         $newCommandProduct->setOptions($arrayOptions);
  384.                     }
  385.                     $newCommand->addCommandProduct($newCommandProduct);
  386.                     $totalAmount $totalAmount + (($product->getPrice() - $newCommandProduct->getPromo()) * $quantity) + $priceOptions;
  387.                     $this->em->persist($newCommandProduct);
  388.                 }
  389.             }
  390.             if ($session->get('packs')) {
  391.                 $pack $packRepository->find($session->get('packs'));
  392.                 $commandPack = new CommandPack();
  393.                 $commandPack->setPack($pack);
  394.                 $commandPack->setCommand($newCommand);
  395.                 $newCommand->addCommandPack($commandPack);
  396.                 $this->em->persist($commandPack);
  397.                 $totalAmount $totalAmount $pack->getPrice();
  398.             }
  399.             $today = new DateTimeImmutable();
  400.             $appFees 0;
  401.             $adminPromo $adminPromoRepository->findOneByPeriod($today);
  402.             if ($adminPromo != null) {
  403.                 $appFees = ($totalAmount floatval($adminPromo->getValue())) / 100;
  404.             } else {
  405.                 $appFees = ($totalAmount 10) / 100;
  406.             }
  407.             $newCommand->setTotalAmount($totalAmount $totalFraisLivraison $appFees);
  408.             $newCommand->setTotalFraisLivraison($totalFraisLivraison);
  409.             $appFee = new AppFee();
  410.             $appFee->setValue($appFees);
  411.             $appFee->setCommand($newCommand);
  412.             $appFee->setPaid(false);
  413.             $this->em->persist($appFee);
  414.             $this->em->persist($newCommand);
  415.             $this->em->flush();
  416.             return $this->redirectToRoute('front_command_paiement_type');
  417.         }
  418.         return $this->render('front/command/validate_commande.html.twig', [
  419.             'form' => $form->createView(),
  420.             'isLivraison' => $isLivraison,
  421.             'isService' => $isService,
  422.             'isFairepart' => $isFairepart
  423.         ]);
  424.     }
  425.     /**
  426.      * @Route("/commande/paiement/type", name="front_command_paiement_type")
  427.      */
  428.     public function paymentType(Request $requestSessionInterface $sessionCommandRepository $commandRepositoryCommandProductRepository $commandProduct)
  429.     {
  430.         //$prodSession = $session->get('products');
  431.         if (!$this->getUser()) {
  432.             $session->set('commandInCurse'true);
  433.             return $this->redirectToRoute('app_login');
  434.         }
  435.         if ($request->isMethod('POST')) {
  436.             $data json_decode($request->getContent(), true);
  437.             $session->set('paymentType'$data);
  438.             $urlGenerator =  $this->generateUrl('front_command_stripe_payment');
  439.             return $this->json([
  440.                 'status' => 'ok',
  441.                 'data' => $urlGenerator
  442.             ]);
  443.         }
  444.         /** @var Command|null $lastCommandUser */
  445.         $lastCommandUser $commandRepository->getLastPackUser($this->getUser());
  446.         $commandProductUser $commandProduct->getCommandProductsByCommandUser($lastCommandUser);
  447.         return $this->render('front/command/paymentType.html.twig', [
  448.             'commandProduit' => $commandProductUser,
  449.             'command' => $lastCommandUser,
  450.             'commandSize' => $lastCommandUser->getCommandPacks()->count() + $lastCommandUser->getCommandProducts()->count()
  451.         ]);
  452.     }
  453.     /**
  454.      * @Route("/commande/paiement", name="front_command_paiement")
  455.      */
  456.     public function payment(Request $requestSessionInterface $sessionCommandRepository $commandRepositoryMangoPayService $mangoPayServiceCommandProductRepository $commandProduct)
  457.     {
  458.         if (!$this->getUser()) {
  459.             $session->set('commandInCurse'true);
  460.             return $this->redirectToRoute('app_login');
  461.         }
  462.         /** @var Command|null $lastCommandUser */
  463.         $lastCommandUser $commandRepository->getLastPackUser($this->getUser());
  464.         $cardRegistration $mangoPayService->createCardRegistration($this->getUser());
  465.         //dd($cardRegistration);
  466.         $session->set('cardRegistrationId'$cardRegistration->Id);
  467.         $session->set('commandId'$lastCommandUser->getId());
  468.         if ($request->isMethod('POST')) {
  469.             foreach ($lastCommandUser->getCommandProducts() as $commandProduct) {
  470.                 $quantityCommanded $commandProduct->getQuantity();
  471.                 $productQuantity $commandProduct->getProduct()->getQuantity();
  472.                 $commandProduct->getProduct()->setQuantity($productQuantity $quantityCommanded);
  473.             }
  474.             $this->em->flush();
  475.             $session->set('confirmPayment'$this->getUser()->getId());
  476.             return $this->redirectToRoute('front_payment_process');
  477.         }
  478.         //Payment process link
  479.         $paymentProcessUrl $_ENV['COMMAND_PAYMENT_URL'];
  480.         $mongopayContro $_ENV['MONGOPAY_CONTROLER'];
  481.         $clientId $_ENV['CLIENT_ID'];
  482.         $commandProductUser $commandProduct->getCommandProductsByCommandUser($lastCommandUser);
  483.         return $this->render('front/command/payment.html.twig', [
  484.             'commandProduit' => $commandProductUser,
  485.             'command' => $lastCommandUser,
  486.             'cardRegistration' => $cardRegistration,
  487.             'paymentProcessUrl' => $paymentProcessUrl,
  488.             'mongopayContrUrl' => $mongopayContro,
  489.             'clientId' => $clientId
  490.         ]);
  491.     }
  492.     /**
  493.      * @Route("/payment/process", name="front_payment_process", methods={"POST"})
  494.      */
  495.     public function paymentProcess(SessionInterface $sessionMangoPayService $mangoPayServiceCommandRepository $commandRepository)
  496.     {
  497.         $request Request::createFromGlobals();
  498.         $browserInfo = new BrowserInfo();
  499.         $form $this->createForm(BrowserInfoType::class, $browserInfo)->submit(json_decode($request->getContent(), true));
  500.         if (!$form->isValid()) {
  501.             $this->json([
  502.                 "status" => "failed",
  503.                 "msg"    => "invalid data"
  504.             ]);
  505.         }
  506.         $browserInfo->AcceptHeader $request->headers->get('Accept');
  507.         $session->set("browserInfo"$browserInfo);
  508.         $session->set("ipAddress"$request->getClientIp());
  509.         $lastCommandUser $commandRepository->getLastPackUser($this->getUser());
  510.         $updatedCard $mangoPayService->getCardRegistration($session->get('cardRegistrationId'));
  511.         $paymentType $session->get("paymentType");
  512.         $payIn $paymentType["type"] == "RECURRING_PAYMENT"
  513.             $mangoPayService->createRecurringPay($updatedCard$lastCommandUser)
  514.             : $mangoPayService->createPayIn($updatedCard$lastCommandUser);
  515.         return $this->json([
  516.             "status" => "success",
  517.             "data"   => $payIn->Status == "FAILED"
  518.                 $this->generateUrl('front_payment_redirect_process')
  519.                 : (($payIn->Status ==  TransactionStatus::Created && $payIn->ExecutionDetails->SecureModeNeeded)
  520.                     ? $payIn->ExecutionDetails->SecureModeRedirectURL
  521.                     $payIn->ExecutionDetails->SecureModeReturnURL
  522.                 )
  523.         ]);
  524.     }
  525.     /**
  526.      * @Route("/redirect-payment/process", name="front_payment_redirect_process")
  527.      */
  528.     public function redirectPaymentProcess(SessionInterface $sessionMail $mailCommandRepository $commandRepositoryMangoPayService $mangoPayService)
  529.     {
  530.         if (!$session->get('commandId') || !$session->get('payInId')) {
  531.             $this->addFlash('danger''Echec du paiement, veuillez retenter ultérieurement.');
  532.             return $this->redirectToRoute('front_command_paiement');
  533.         }
  534.         $payIn $mangoPayService->getPayIn($session->get('payInId'));
  535.         if ($payIn && $payIn->Status !== 'SUCCEEDED') {
  536.             $session->remove("walletClientId");
  537.             $this->addFlash('danger''Echec du paiement, Le paiement n’a pas été validé.');
  538.             return $this->redirectToRoute('front_command_paiement');
  539.         }
  540.         $command $commandRepository->find($session->get('commandId'));
  541.         if ($command->getPaymentType() == "RECURRING_PAYMENT") {
  542.             $payIn $mangoPayService->getPayInRecurringRegistration($command->getCommandNumber());
  543.         } else {
  544.             $tranferedFundBuyerToSeller $mangoPayService->transfertFundWalledBuyerToSeller($command$payIn);
  545.             if ($tranferedFundBuyerToSeller instanceof ResponseException) {
  546.                 $message $tranferedFundBuyerToSeller->GetErrorDetails()->Message;
  547.                 $this->addFlash('danger''Echec du paiement: ' $message);
  548.                 return $this->redirectToRoute('front_command_paiement');
  549.             }
  550.         }
  551.         $command->setLastPayAt(new \DateTime());
  552.         $command->setStatus($payIn->Status);
  553.         $this->em->flush();
  554.         $session->set('confirmPayment'$this->getUser()->getId());
  555.         $mail->ConfirmationPaiementClient($this->getUser(), $command$this->createInvoicePdf($command));
  556.         $arrayCompanies = [];
  557.         foreach ($command->getCommandProducts() as $commandProduct) {
  558.             array_push($arrayCompanies$commandProduct->getProduct()->getCompany());
  559.         }
  560.         $mail->confirmationCommandCompany($arrayCompanies);
  561.         //mise à jour de la quantité totale de produits
  562.         $lastCommandUser $commandRepository->getLastPackUser($this->getUser());
  563.         foreach ($lastCommandUser->getCommandProducts() as $commandProduct) {
  564.             $quantityCommanded $commandProduct->getQuantity();
  565.             $productQuantity $commandProduct->getProduct()->getQuantity();
  566.             $commandProduct->getProduct()->setQuantity($productQuantity $quantityCommanded);
  567.             $this->em->persist($commandProduct->getProduct());
  568.         }
  569.         $this->em->flush();
  570.         return $this->redirectToRoute('front_command_paiement_confirm');
  571.     }
  572.     /**
  573.      * @Route("/commande/paiement/confirmation", name="front_command_paiement_confirm")
  574.      */
  575.     public function confirmPaymentProduct(SessionInterface $session)
  576.     {
  577.         if (!$session->get('confirmPayment') || $session->get('confirmPayment') !== $this->getUser()->getId()) {
  578.             return $this->redirectToRoute('front_my_basket');
  579.         }
  580.         $session->remove('confirmPayment');
  581.         $session->remove('products');
  582.         $session->remove('packs');
  583.         $session->remove('cardRegistrationId');
  584.         $session->remove('payInId');
  585.         $session->remove('paymentType');
  586.         $session->remove('weddingdate');
  587.         $session->remove('address');
  588.         return $this->render('front/command/confirm_command.html.twig');
  589.     }
  590.     /**
  591.      * @Route("/commande/stripe/paiement", name="front_command_stripe_payment")
  592.      */
  593.     public function stripePayment(StripeConnectService $stripeConnectServiceSessionInterface $sessionCommandRepository $commandRepository): Response
  594.     {
  595.         if (!$this->getUser()) {
  596.             $session->set('commandInCurse'true);
  597.             return $this->redirectToRoute('app_login');
  598.         }
  599.         /** @var Command|null $lastCommandUser */
  600.         $lastCommandUser $commandRepository->getLastPackUser($this->getUser());
  601.         $line_items = [];
  602.         $transfer_group 'ORDER' $lastCommandUser->getId();
  603.         $success_url $this->generateUrl('front_command_stripe_success', [], 0);
  604.         $cancel_url $this->generateUrl('front_command_stripe_cancel', [], 0);
  605.         $session->set('commandId'$lastCommandUser->getId());
  606.         $session->set('transfer_group'$transfer_group);
  607.         $commandProductTotalPrice 0;
  608.         foreach ($lastCommandUser->getCommandProducts() as $commandProduct) {
  609.             // A mettre après le checkout
  610.             $quantityCommanded $commandProduct->getQuantity();
  611.             $productQuantity $commandProduct->getProduct()->getQuantity();
  612.             $commandProduct->getProduct()->setQuantity($productQuantity $quantityCommanded);
  613.             $this->em->persist($commandProduct->getProduct());
  614.             $this->em->flush();
  615.             $commandProductTotalPrice += $commandProduct->getProduct()->getPrice() * $quantityCommanded;
  616.             array_push($line_items, [
  617.                 'price_data' => [
  618.                     'currency' => 'eur',
  619.                     'product_data' => [
  620.                         'name' => $commandProduct->getProduct()->getName(),
  621.                     ],
  622.                     'unit_amount' => $commandProduct->getProduct()->getPrice() * 100// amount in cents
  623.                 ],
  624.                 'quantity' => $quantityCommanded,
  625.             ]);
  626.         }
  627.         $appFeeTotalPrice 0;
  628.         foreach ($lastCommandUser->getAppFees() as $appFee) {
  629.             array_push($line_items, [
  630.                 'price_data' => [
  631.                     'currency' => 'eur',
  632.                     'product_data' => [
  633.                         'name' => 'Commission Hobiin commande n° ' $lastCommandUser->getId(),
  634.                     ],
  635.                     'unit_amount' => $appFee->getValue() * 100 // amount in cents
  636.                 ],
  637.                 'quantity' => 1,
  638.             ]);
  639.             $appFeeTotalPrice += $appFee->getValue();
  640.         }
  641.         if ($lastCommandUser->getTotalFraisLivraison() > 0) {
  642.             array_push($line_items, [
  643.                 'price_data' => [
  644.                     'currency' => 'eur',
  645.                     'product_data' => [
  646.                         'name' => 'Frais de livraison commande n° ' $lastCommandUser->getId(),
  647.                     ],
  648.                     'unit_amount' => $lastCommandUser->getTotalFraisLivraison() * 100 // amount in cents
  649.                 ],
  650.                 'quantity' => 1,
  651.             ]);
  652.         }
  653.             
  654.         $session $stripeConnectService->createCheckoutSessionForProductCommands($lastCommandUser$line_items$transfer_group$success_url$cancel_url);
  655.         return $this->redirect($session->url);
  656.     }
  657.     /**
  658.      * @Route("/command/stripe/success", name="front_command_stripe_success")
  659.      */
  660.     public function stripeSuccess(Request $requestSessionInterface $sessionCommandRepository $commandRepositoryMail $mailStripeConnectService $stripeConnectService): Response
  661.     {
  662.         $command $commandRepository->find(intval($session->get('commandId')));
  663.         $checkoutSessionId $request->get('session_id'); // Recuperates checkout session ID
  664.         $checkoutSession $stripeConnectService->retrieveCheckoutSession($checkoutSessionId); // Recuperates checkout
  665.         if (!$checkoutSession) {
  666.             return new Response('error : Checkout session not found'404);
  667.         }
  668.         $paymentIntentId $checkoutSession->payment_intent// Recuperates payment intent ID
  669.         $paymentIntent $stripeConnectService->retrievePaymentIntent($paymentIntentId); // Recuperates payment intent
  670.         if (!$paymentIntent) {
  671.             return new Response('error : Payment intent not found'404);
  672.         }
  673.         $paymentIntentChargeId $paymentIntent->latest_charge// Recuperates latest charge ID
  674.         if (!$paymentIntentChargeId) {
  675.             return new Response('error : Payment intent charge not found'404);
  676.         }
  677.         $latestCharge $stripeConnectService->retrieveLatestCharge($paymentIntentChargeId); // Recuperates latest charge
  678.         foreach ($command->getCommandProducts() as $commandProduct) {
  679.             $transfer null;
  680.             $quantityCommanded $commandProduct->getQuantity();
  681.             $singleproductPrice $commandProduct->getProduct()->getPrice() * 100// Amount in cents
  682.             try {
  683.                 $transfer $stripeConnectService->createTransfer(
  684.                     $singleproductPrice $quantityCommanded// Amount in cents
  685.                     $commandProduct->getProduct()->getCompany()->getStripeAccountId(), // Connected account ID
  686.                     $latestCharge->id// Charge ID
  687.                     'eur'// Currency
  688.                     'Paiement de la commande ' $command->getId() // Description
  689.                 );
  690.             } catch (\Throwable $th) {
  691.                 $this->addFlash('danger''Echec du paiement: ' $th->getMessage());
  692.             }
  693.             if ($transfer != null) {
  694.                 $hobiin_transfer = (new Transfert)
  695.                     ->setStripeTransferId($transfer->id)
  696.                     ->setCommand($commandProduct->getCommand());
  697.                 $commandProduct->setPayinId($checkoutSession->latest_charge);
  698.                 $command->setChargeId($checkoutSession->id);
  699.                 $command->setCommandNumber($checkoutSession->id);
  700.                 $command->setStatus('succeeded');
  701.                 $this->em->persist($hobiin_transfer);
  702.                 $this->em->persist($commandProduct);
  703.             }
  704.         }
  705.         foreach ($command->getAppFees() as $appFee) {
  706.             if ($checkoutSession->status === 'complete') {
  707.                 $appFee->setPaid(true);
  708.             } else {
  709.                 $appFee->setPaid(false);
  710.             }
  711.             $this->em->persist($appFee);
  712.         }
  713.         $this->em->flush();
  714.         $session->remove('products');
  715.         $session->remove('transfer_group');
  716.         $session->remove('packs');
  717.         $session->remove('commandId');
  718.         $session->remove('session_id');
  719.         $this->addFlash('success''Paiement réussi!');
  720.         return $this->redirectToRoute('front_client_space_command_list');
  721.     }
  722.     /**
  723.      * @Route("/command/stripe/cancel", name="front_command_stripe_cancel")
  724.      */
  725.     public function stripeCancel(SessionInterface $sessionCommandRepository $commandRepository): Response
  726.     {
  727.         $session->remove('products');
  728.         $session->remove('transfer_group');
  729.         $session->remove('packs');
  730.         $session->remove('commandId');
  731.         $session->remove('session_id');
  732.         $this->addFlash('warning''Paiement annulé!');
  733.         return $this->redirectToRoute('front_client_space_command_list');
  734.     }
  735.     public function createInvoicePdf(Command $command)
  736.     {
  737.         // Configure Dompdf according to your needs
  738.         $pdfOptions = new Options();
  739.         $pdfOptions->set('defaultFont''Arial');
  740.         $pdfOptions->isRemoteEnabled(true);
  741.         $pdfOptions->isHtml5ParserEnabled(true);
  742.         // Instantiate Dompdf with our options
  743.         $dompdf = new Dompdf($pdfOptions);
  744.         // Retrieve the HTML generated in our twig file
  745.         $html $this->renderView('front/email/confirmation_paiement_test.html.twig'compact('command'));
  746.         // Load HTML to Dompdf
  747.         $dompdf->loadHtml($html);
  748.         // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
  749.         $dompdf->setPaper('A4''portrait');
  750.         // Render the HTML as PDF
  751.         $dompdf->render();
  752.         // Store PDF Binary Data
  753.         $output $dompdf->output();
  754.         // In this case, we want to write the file in the public directory
  755.         $publicDirectory $this->getParameter('kernel.project_dir') . '/public';
  756.         // e.g /var/www/project/public/mypdf.pdf
  757.         $pdfFilepath =  $publicDirectory '/mypdf.pdf';
  758.         // Write file to the desired path
  759.         file_put_contents($pdfFilepath$output);
  760.         return $pdfFilepath;
  761.     }
  762.     /**
  763.      * @Route("/panierpdf", name="pdf_generate")
  764.      */
  765.     public function createBasketPdf(SessionInterface $sessionProductRepository $productRepositoryPackRepository $packRepositoryFilter $filter)
  766.     {
  767.         $product $session->get('products', []);
  768.         //  dd($product);
  769.         $prduit = [];
  770.         foreach ($product as $key => $prod) {
  771.             // for ($i=0; $i < sizeof($product); $i++) { 
  772.             if (isset($prod['options_fairepar'])) {
  773.                 $options = [];
  774.                 foreach ($prod['options_fairepar'] as $key => $value) {
  775.                     $options[] = [
  776.                         "id" => $value["idoption"],
  777.                         "nom" => $value["nomoption"],
  778.                         "qte" => $value["quantite"],
  779.                         "price" => $value["price"]
  780.                     ];
  781.                 }
  782.                 $prduit[] = [
  783.                     "productId" => $prod["productId"],
  784.                     "quantity" => $prod["quantity"],
  785.                     "options" => $options $options null
  786.                 ];
  787.             } else {
  788.                 //     $options=[];
  789.                 if (isset($prod['options'])) {
  790.                     $options = [];
  791.                     foreach ($prod['options'] as $key => $value) {
  792.                         $produitoption $filter->getProductOption($key);
  793.                         $produitoption->setQuantite([$value]);
  794.                         $options[] = [
  795.                             "id" => $produitoption->getId(),
  796.                             "nom" => $produitoption->getName(),
  797.                             "qte" => $produitoption->getQuantite()[0],
  798.                             "price" => $produitoption->getPrice()
  799.                         ];
  800.                     }
  801.                     $prduit[] = [
  802.                         "productId" => $prod["productId"],
  803.                         "quantity" => $prod["quantity"],
  804.                         "options" => $options $options null
  805.                     ];
  806.                 } else {
  807.                     $options null;
  808.                     $prduit[] = [
  809.                         "productId" => $prod["productId"],
  810.                         "quantity" => $prod["quantity"],
  811.                         "options" => $options
  812.                     ];
  813.                 }
  814.             }
  815.         }
  816.         //    dd($prduit);
  817.         if ($session->get('packs')) {
  818.             $pack $packRepository->findOneBy(['id' => $session->get('packs')]);
  819.         } else {
  820.             $pack null;
  821.         }
  822.         // dd($prduit);
  823.         // $session->set('products', $allProducts);
  824.         // Configure Dompdf according to your needs
  825.         $pdfOptions = new Options();
  826.         $pdfOptions->set('defaultFont''Arial');
  827.         // Instantiate Dompdf with our options
  828.         $dompdf = new Dompdf($pdfOptions);
  829.         // Retrieve the HTML generated in our twig file
  830.         $html $this->renderView('front/command/basketPdf.html.twig', [
  831.             'products' => $prduit,
  832.             'pack' => $pack,
  833.             // 'form' => $form->createView(),
  834.             //'isMessagePromo' => $isMessagePromo
  835.         ]);
  836.         // Load HTML to Dompdf
  837.         $dompdf->loadHtml($html);
  838.         // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
  839.         $dompdf->setPaper('A4''portrait');
  840.         // Render the HTML as PDF
  841.         $dompdf->render();
  842.         // Output the generated PDF to Browser (force download)
  843.         $dompdf->stream("panierpdf.pdf", [
  844.             "Attachment" => true
  845.         ]);
  846.         return new Response();
  847.     }
  848. }