src/Controller/OrderController.php line 1274

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Cart;
  4. use App\Entity\Company;
  5. use App\Entity\Grade;
  6. use App\Entity\Imei;
  7. use App\Entity\Order;
  8. use App\Entity\Product;
  9. use App\Entity\Shop;
  10. use App\Entity\Status;
  11. use App\Entity\User;
  12. use App\Form\CompanyType;
  13. use App\Form\OrderCommentType;
  14. use App\Form\OrderCouponType;
  15. use App\Form\OrderDeliveryType;
  16. use App\Form\OrderSummaryType;
  17. use App\Form\OrderType;
  18. use App\Repository\AddressRepository;
  19. use App\Repository\CartRepository;
  20. use App\Repository\CompanyRepository;
  21. use App\Repository\CouponRepository;
  22. use App\Repository\DeliveryRepository;
  23. use App\Repository\GradeRepository;
  24. use App\Repository\ImeiRepository;
  25. use App\Repository\OptionRepository;
  26. use App\Repository\OrderRepository;
  27. use App\Repository\ProductRepository;
  28. use App\Repository\ShopRepository;
  29. use App\Repository\StatusRepository;
  30. use App\Repository\UserRepository;
  31. use App\Service\DeliveryService;
  32. use App\Service\OptionService;
  33. use App\Service\PriceService;
  34. use App\Service\ShopService;
  35. use Doctrine\Persistence\ManagerRegistry;
  36. use Knp\Bundle\SnappyBundle\KnpSnappyBundle;
  37. use Knp\Component\Pager\PaginatorInterface;
  38. use Knp\Snappy\GeneratorInterface;
  39. use Knp\Snappy\Pdf;
  40. use Psr\Log\LoggerInterface;
  41. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  42. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  43. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  44. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  45. use Symfony\Component\HttpFoundation\JsonResponse;
  46. use Symfony\Component\HttpFoundation\ParameterBag;
  47. use Symfony\Component\HttpFoundation\Request;
  48. use Symfony\Component\HttpFoundation\Response;
  49. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  50. use Symfony\Component\Mailer\Mailer;
  51. use Symfony\Component\Mailer\MailerInterface;
  52. use Symfony\Component\Messenger\MessageBusInterface;
  53. use Symfony\Component\Mime\Address;
  54. use Symfony\Component\Mime\Mail;
  55. use Symfony\Component\Mime\Part\DataPart;
  56. use Symfony\Component\Mime\Part\File;
  57. use Symfony\Component\Routing\Annotation\Route;
  58. use Symfony\Component\String\Slugger\SluggerInterface;
  59. use Symfony\Contracts\HttpClient\HttpClientInterface;
  60. /**
  61.  * @Route("/{_locale<%app.supported_locales%>}/order")
  62.  */
  63. class OrderController extends AbstractController
  64. {
  65.     private $doctrine;
  66.     private $bak2life_api_url;
  67.     private $bak2life_api_key;
  68.     private $mailer_sender;
  69.     private $bak2_api_url;
  70.     private $bak2_mp_buyer_id;
  71.     public function __construct(ParameterBagInterface $params)
  72.     {
  73.         $this->bak2life_api_url $params->get('app.bak2life_api_url');
  74.         $this->bak2_api_url $params->get('app.bak2_api_url');
  75.         $this->bak2_mp_buyer_id $params->get('app.bak2_mp_buyer_id');
  76.         $this->mailer_sender $params->get('app.mailer_sender');
  77.     }
  78.     /**
  79.      * @Route("/", name="app_order_index", methods={"GET"})
  80.      */
  81.     public function index(OrderRepository $orderRepositoryShopRepository $shopRepository,  PaginatorInterface $paginatorRequest $request): Response
  82.     {
  83.         $user $this->getUser();
  84.         $shop $user->getShop();
  85.         $tOrders=$orderRepository->findBy(['shop'=>$shop->getId()]);
  86.         foreach($tOrders as $o) {
  87.             $o->setActive(1);
  88.             $orderRepository->add($o);
  89.         }
  90.         if ($this->isGranted('ROLE_SUPER_ADMIN')) {
  91.             //$orders = $orderRepository->findAll();
  92.             $query=$orderRepository->findAllDql();
  93.             $orders $paginator->paginate(
  94.                 $query/* query NOT result */
  95.                 $request->query->getInt('page'1), /*page number*/
  96.                 30 /*limit per page*/
  97.             );
  98.         } else if ($this->isGranted('ROLE_ADMIN')) {
  99.             $query=$orderRepository->findByDql(['shop'=>$shop->getId()]);
  100.             $orders $paginator->paginate(
  101.                 $query/* query NOT result */
  102.                 $request->query->getInt('page'1), /*page number*/
  103.                 30 /*limit per page*/
  104.             );
  105.         } else {
  106.             $query=$orderRepository->findByDql(['user'=>$this->getUser()->getId()]);
  107.             $orders $paginator->paginate(
  108.                 $query/* query NOT result */
  109.                 $request->query->getInt('page'1), /*page number*/
  110.                 30 /*limit per page*/
  111.             );
  112.         }
  113.         return $this->render('order/index.html.twig', [
  114.             'orders' => $orders,
  115.         ]);
  116.     }
  117.     /**
  118.      * @Route("/new", name="app_order_new", methods={"GET", "POST"})
  119.      */
  120.     public function new(Request $requestOrderRepository $orderRepository): Response
  121.     {
  122.         $order = new Order();
  123.         $order->setActive(1);
  124.         $form $this->createForm(OrderType::class, $order);
  125.         $form->handleRequest($request);
  126.         $user $this->getUser();
  127.         $shop=$user->getShop();
  128.         if ($form->isSubmitted() && $form->isValid()) {
  129.             $order->setActive(1);
  130.             $orderRepository->add($order);
  131.             return $this->redirectToRoute('app_order_index', [], Response::HTTP_SEE_OTHER);
  132.         }
  133.         return $this->renderForm('order/new.html.twig', [
  134.             'order' => $order,
  135.             'form' => $form,
  136.             'shop'=>$shop,
  137.             'user'=>$user
  138.         ]);
  139.     }
  140.     /**
  141.      * @Route("/{id}", name="app_order_show", methods={"GET"})
  142.      */
  143.     public function show(Order $orderOptionService $optionService): Response
  144.     {
  145.         $user=$order->getUser();
  146.         $shop=$user->getShop();
  147.         if ($user == $this->getUser() || $this->isGranted('ROLE_ADMIN')) {
  148.             return $this->render('order/show.html.twig', [
  149.                 'order' => $order,
  150.                 'shop'=>$shop,
  151.                 'user'=>$user,
  152.                 'cartOptions'=>$optionService->getCartOptions($order)
  153.             ]);
  154.         }
  155.         return $this->redirectToRoute('app_order_index', [], Response::HTTP_SEE_OTHER);
  156.     }
  157.     /**
  158.      * @Route("/{id}/edit", name="app_order_edit", methods={"GET", "POST"})
  159.      */
  160.     public function edit(Request $requestOrder $orderOrderRepository $orderRepositoryOptionService $optionServiceSluggerInterface $slugger): Response
  161.     {
  162.         $user $order->getUser();
  163.         $shop $user->getShop();
  164.         $form $this->createForm(OrderType::class, $order, array('shop'=>$shop'user'=>$user));
  165.         $form->handleRequest($request);
  166.         $invoiceDirectory=$this->getParameter('kernel.project_dir').'/private/users/'.$order->getUser()->getId().'/invoices/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd');
  167.         //$invoiceDirectory=$this->getParameter('kernel.project_dir').'/private/users/'.$order->getUser()->getId().'/invoices/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$filename;
  168.         if ($form->isSubmitted() && $form->isValid()) {
  169.             $invoiceFile $form->get('invoice')->getData();
  170.             if($invoiceFile) {
  171.                 $originalFilename pathinfo($invoiceFile->getClientOriginalName(), PATHINFO_FILENAME);
  172.                 // this is needed to safely include the file name as part of the URL
  173.                 $safeFilename $slugger->slug($originalFilename);
  174.                 $newFilename $safeFilename.'-'.uniqid().'.'.$invoiceFile->guessExtension();
  175.                 // Move the file to the directory where brochures are stored
  176.                 try {
  177.                     //$invoiceFile->move($invoiceDirectory."/".$shop->getId()."/".$order->getDate()->format('Ymd'), $newFilename);
  178.                     $invoiceFile->move($invoiceDirectory$newFilename);
  179.                 } catch (FileException $e) {
  180.                     // ... handle exception if something happens during file upload
  181.                 }
  182.                 // updates the 'brochureFilename' property to store the PDF file name
  183.                 // instead of its contents
  184.                 $order->setInvoiceFilename($newFilename);
  185.             }
  186.             $orderRepository->add($order);
  187.             return $this->redirectToRoute('app_order_edit', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
  188.         }
  189.         return $this->renderForm('order/edit.html.twig', [
  190.             'order' => $order,
  191.             'form' => $form,
  192.             'shop'=>$shop,
  193.             'user'=>$user,
  194.             'cartOptions'=>$optionService->getCartOptions($order)
  195.         ]);
  196.     }
  197.     /**
  198.      * @Route("/{id}/summary", name="app_order_summary", methods={"GET","POST"})
  199.      */
  200.     public function summary(Request $requestOrder $orderOrderRepository $orderRepositoryOptionService $optionService): Response
  201.     {
  202.         $shop=$order->getShop();
  203.         $user=$order->getUser();
  204.         if(!$order->getDeliveryAddress() || !$order->getInvoiceAddress()) {
  205.             $this->addFlash('error''Missing address');
  206.             return $this->redirectToRoute('app_order_delivery', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
  207.         }
  208.         $form $this->createForm(OrderSummaryType::class, $order, array('shop'=>$shop'user'=>$user));
  209.         $form->handleRequest($request);
  210.         if ($form->isSubmitted() && $form->isValid()) {
  211.             $orderRepository->add($order);
  212.             return $this->redirectToRoute('app_order_confirm', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
  213.         }
  214.         return $this->renderForm('order/summary.html.twig', [
  215.             'order' => $order,
  216.             'form' => $form,
  217.             'shop'=>$shop,
  218.             'user'=>$user,
  219.             'cartOptions'=>$optionService->getCartOptions($order)
  220.         ]);
  221. /*
  222.         if ($order->getUser() == $this->getUser() || $this->isGranted('ROLE_ADMIN')) {
  223.             $shop=$order->getShop();
  224.             if($order->getCoupon()) {
  225.                 $couponName = trim(strtoupper(preg_replace('/\s+/', '', $order->getCoupon())));
  226.                 if($coupon=$couponRepository->findOneByName($couponName, $order->getShop())) {
  227.                     $order->setDiscount($coupon);
  228.                     //echo $order->getDiscount();
  229.                 }
  230.             }
  231.             return $this->render('order/summary.html.twig', [
  232.                 'order' => $order,
  233.                 'shop'=>$shop
  234.             ]);
  235.         }
  236.         return $this->redirectToRoute('app_order_index', [], Response::HTTP_SEE_OTHER);
  237. */
  238. }
  239.     /**
  240.      * @Route("/{id}/comments", name="app_order_comments", methods={"GET", "POST"})
  241.      */
  242.     public function comments(Request $requestOrder $orderOrderRepository $orderRepository): Response
  243.     {
  244.         $user=$this->getUser();
  245.         $shop $order->getShop();
  246.         $form $this->createForm(OrderCommentType::class, $order,['shop'=>$order->getShop()]);
  247.         $form->handleRequest($request);
  248.         if ($form->isSubmitted() && $form->isValid()) {
  249.             $orderRepository->add($order);
  250.             return $this->redirectToRoute('app_order_delivery', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
  251.         }
  252.         return $this->renderForm('order/comments.html.twig', [
  253.             'order'=>$order,
  254.             'form'=>$form
  255.         ]);
  256.     }
  257.     /**
  258.      * @Route("/{id}/delivery", name="app_order_delivery", methods={"GET", "POST"})
  259.      */
  260.     public function delivery(Request $requestOrder $orderOrderRepository $orderRepositoryUserRepository $userRepositoryShopService $shopService): Response
  261.     {
  262.         $user=$this->getUser();
  263.         $shop $order->getShop();
  264.         if($user->getCompany()) {
  265.             if($companyAddress=$user->getCompany()->getAddress()) {
  266.                 $user->addAddress($companyAddress);
  267.                 $userRepository->add($user);
  268.             }
  269.             if($childrenCompanies $user->getCompany()->getChildrenCompanies()) {
  270.                 foreach($childrenCompanies as $co) {
  271.                     if($co->getAddress()) {
  272.                         $user->addAddress($co->getAddress());
  273.                     }
  274.                 }
  275.                 $userRepository->add($user);
  276.             }
  277.         }
  278.         if($shopService->hasSetting($shop'invoice-parent')) {
  279.             if($parentCompany $user->getCompany()->getParent()) {
  280.                 $order->setInvoiceAddress($parentCompany->getAddress());
  281.                 $orderRepository->add($order);
  282.             }
  283.         }
  284.         $form $this->createForm(OrderDeliveryType::class, $order,['user'=>$user,'shop'=>$shop]);
  285.         $form->handleRequest($request);
  286.         if ($form->isSubmitted() && $form->isValid()) {
  287.             $orderRepository->add($order);
  288.             return $this->redirectToRoute('app_order_delivery', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
  289.         }
  290.         return $this->renderForm('order/delivery.html.twig', [
  291.             'order'=>$order,
  292.             'form'=>$form
  293.         ]);
  294.     }
  295.     /**
  296.      * @Route("/{id}/checkout", name="app_order_checkout", methods={"GET", "POST"})
  297.      */
  298.     public function checkout(Request $requestOrder $orderOrderRepository $orderRepositoryAddressRepository $addressRepositoryDeliveryRepository $deliveryRepositoryDeliveryService $deliveryServiceImeiRepository $imeiRepositoryUserRepository $userRepositoryCouponRepository $couponRepositoryMessageBusInterface $bus): Response
  299.     {
  300.         $em $this->getDoctrine()->getManager();
  301.         $user $this->getUser();
  302.         $shop $user->getShop();
  303.         $isPos $shop->getSetting('is-point-of-sale');
  304.         if(count($order->getCarts())<=0) {
  305.             return $this->redirectToRoute('app_cart_index', [], Response::HTTP_SEE_OTHER);
  306.         }
  307.         $availableImeis=array();
  308.         $allImeis=$imeiRepository->findInStock($shop);
  309.         foreach($allImeis as $imei) {
  310.             $availableImeis[]=array(
  311.                 'imei'=>$imei,
  312.                 'model'=>$imei->getProduct()->getModel()->getId(),
  313.                 'color'=>$imei->getProduct()->getColor()->getId(),
  314.                 'grade'=>$imei->getProduct()->getGrade()->getId()
  315.             );
  316.         }
  317.         //$form = $this->createForm(OrderType::class, $order, array('IsPos'=>$isPos,'user'=>$user,'shop'=>$shop,'imeis'=>$availableImeis));
  318.         $form $this->createForm(OrderDeliveryType::class, $order,['user'=>$user,'shop'=>$shop]);
  319.         $form->handleRequest($request);
  320.         if($isPos) {
  321.             $imeis=array();
  322.             $totalQty=0;
  323.             foreach($order->getCarts() as $cart) {
  324.                 $totalQty+=$cart->getQty();
  325.                 foreach($cart->getImei() as $imei) {
  326.                     $imeis[]= $imei->getImei();
  327.                 }
  328.             }
  329.         }
  330.         //$order->setDeliveryHt($this->getDeliveryPrice($order, $deliveryRepository));
  331.         $order->setDeliveryHt($deliveryService->getDeliveryPriceHT($order,$deliveryRepository));
  332.         if ($form->isSubmitted() && $form->isValid()) {
  333.             $order->setDeliveryHt(0);
  334.             if($order->getDeliveryAddress()) {
  335.                 $country=$order->getDeliveryAddress()->getCountry();
  336.                 if(in_array($country,array('Martinique','Guadeloupe','Guyane','Reunion'))) {
  337.                     $order->setDeliveryHt(3000);
  338.                 }
  339.                 else {
  340.                     if($deliveries=$deliveryRepository->findBy(array('shop'=>$order->getShop()->getId()))) {
  341.                         $deliveryHt=$this->getDeliveryPrice($order$deliveryRepository);
  342.                         $order->setDeliveryHt($deliveryHt);
  343.                     }
  344.                 }
  345.             }
  346.             $em->persist($order);
  347.             if($isPos) {
  348.                 if($newInvoiceAddress $form->get('newInvoiceAddress')->getData()['__name__']) {
  349.                     $invoiceAddress=$this->setAddress($newInvoiceAddress$order->getInvoiceAddress());
  350.                     $order->setInvoiceAddress($invoiceAddress);
  351.                     $order->setDeliveryAddress($invoiceAddress);
  352.                 }
  353.                 /*
  354.                 if($newDeliveryAddress = $form->get('newDeliveryAddress')->getData()['__name__']) {
  355.                     $deliveryAddress=$this->setAddress($newDeliveryAddress, $order->getDeliveryAddress());
  356.                     $order->setDeliveryAddress($deliveryAddress);
  357.                 }
  358.                 */
  359.             }
  360.             if($order->getUser()->getShop()->getName()=='AFPA') {
  361.                 if(!$existingUser=$userRepository->findOneByEmail($order->getInvoiceAddress()->getEmail())) {
  362.                     //$order->setUser($existingUser);
  363.                     $tmpUser=$order->getUser();
  364.                     $tmpUser->setEmail($order->getInvoiceAddress()->getEmail());
  365.                     $tmpUser->setFirstname($order->getInvoiceAddress()->getFirstname());
  366.                     $tmpUser->setLastname($order->getInvoiceAddress()->getLastname());
  367.                     $userRepository->add($tmpUser);
  368.                 }
  369.             }
  370.             if($order->getCoupon()) {
  371.                 $couponName trim(strtoupper(preg_replace('/\s+/'''$order->getCoupon())));
  372.                 if($coupon=$couponRepository->findOneByName($couponName$order->getShop())) {
  373.                     $order->setDiscount($coupon);
  374.                     //echo $order->getDiscount();
  375.                 }
  376.             }
  377.             $order->setReference($order->generateReference());
  378.             $orderRepository->add($order);
  379.             //echo $order->getDeliveryHt();
  380.             if($isPos && (count($imeis)<$totalQty || count($imeis)>$totalQty)) {
  381.                 $this->addFlash('error''Error in IMEIS selection');
  382.                 return $this->redirectToRoute('app_order_checkout', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
  383.             }
  384.             if(!$order->getDeliveryAddress() || !$order->getInvoiceAddress()) {
  385.                 return $this->redirectToRoute('app_order_delivery', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
  386.             }
  387.             $totalQty=0;
  388.             $totalAmount=0;
  389.             foreach($order->getCarts() as $cart) {
  390.                 $totalQty+=$cart->getQty();
  391.                 $totalAmount+=$cart->getQty()*$cart->getPrice();
  392.                 foreach($cart->getImei() as $imei) {
  393.                     $imei->setCart($cart);
  394.                     $imeiRepository->add($imei);
  395.                 }
  396.             }
  397.             //$order->setAmountTotal($totalAmount);
  398.             $orderRepository->add($order);
  399.             return $this->redirectToRoute('app_order_summary', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
  400.         }
  401. else {
  402.     die('no');
  403. }
  404.         if($order->getReference()=='') {
  405.             $order->setReference($order->generateReference());
  406.             $orderRepository->add($order);
  407.         }
  408.         return $this->renderForm('order/edit.html.twig', [
  409.             'order' => $order,
  410.             'form' => $form,
  411.             'user'=>$user,
  412.             'shop'=>$shop
  413.         ]);
  414.     }
  415.     /**
  416.      * @Route("/addoption", name="app_order_add_option", methods={"POST","GET"})
  417.      */
  418.     public function addoption(Request $requestOptionRepository $optionRepositoryPriceService $priceService): Response {
  419.         $em $this->getDoctrine()->getManager();
  420.         $optionId=$request->request->get('option');
  421.         $user =  $this->getUser();
  422.         if($order=$em->getRepository(Order::class)->findOneBy(array('user'=>$user,'status'=>10))) {
  423.             $carts=$order->getCarts();
  424.             $totalAmount=0;
  425.             foreach($carts as $cart) {
  426.                 $totalAmount+=$cart->getPrice()*$cart->getQty();
  427.                 foreach($cart->getOptions() as $o) {
  428.                     $totalAmount+=$cart->getQty()*$o->getPrice();
  429.                 }
  430.             }
  431.             if($option $optionRepository->find($optionId)) {
  432.                 foreach($order->getOptions() as $o) {
  433.                     $order->removeOption($o);
  434.                 }
  435.                 $order->addOption($option);
  436.                 $em->persist($order);
  437.                 $em->flush();
  438.                 $priceService->getPrices($ordertrue);
  439.                 return new JsonResponse(array(
  440.                     'reload'=>true
  441.                 ));
  442.             }
  443.             else {
  444.                 if($optionId==0) {
  445.                     foreach($order->getOptions() as $o) {
  446.                         $order->removeOption($o);
  447.                     }
  448.                     //$order->setOptionPrice(0);
  449.                     $em->persist($order);
  450.                     $em->flush();
  451.                     $priceService->getPrices($ordertrue);
  452.                     return new JsonResponse(array(
  453.                         'reload'=>true
  454.                     ));
  455.                 }
  456.             }
  457.         }
  458.         $priceService->getPrices($ordertrue);
  459.         return new JsonResponse(array(
  460.             'result'=>'no'
  461.         ));
  462.     }
  463.     /**
  464.      * @Route("/{id}/resend", name="app_order_resend_email", methods={"GET"})
  465.      */
  466.     public function resendEmail(Order $orderOptionService $optionServiceMailerInterface $mailerParameterBagInterface $params): Response
  467.     {
  468.         $this->sendConfirmationEmail($order$mailer$params);
  469.         return $this->render('order/show.html.twig', [
  470.             'order' => $order,
  471.             'cartOptions'=>$optionService->getCartOptions($order)
  472.         ]);
  473.         return $this->redirectToRoute('app_order_show', ['id' => $order->getId()], Response::HTTP_SEE_OTHER);
  474.     }
  475.     /**
  476.      * @Route("/{id}/confirm", name="app_order_confirm", methods={"GET","POST"})
  477.      */
  478.     public function confirm(Request $requestOrder $orderOrderRepository $orderRepositoryProductRepository $productRepositoryGradeRepository $gradeRepositoryCartRepository $cartRepositoryImeiRepository $imeiRepositoryStatusRepository $statusRepositoryManagerRegistry $doctrineHttpClientInterface $clientMailerInterface $mailerLoggerInterface $loggerShopService $shopServicePriceService $priceServiceParameterBagInterface $params): Response
  479.     {
  480.         if($order->getUser()!=$this->getUser() || $order->getStatus()->getId()!=10 || $order->getConfirm()) {
  481.             return $this->redirectToRoute('app_order_index', [], Response::HTTP_SEE_OTHER);
  482.         }
  483.         if ($pendingOrder $orderRepository->findOneBy(array('user' => $this->getUser(), 'status' => 10'confirm' => 0'id' => $order->getId()))) {
  484.             $shop=$order->getShop();
  485.             $vat $shopService->getSetting($shop'vat');
  486.             //$vat = 20;
  487.             /*
  488.             if($shop->getCountry()=='es') {
  489.                 $vat=21;
  490.             }*/
  491.             $carts $order->getCarts();
  492.             $totalProduct 0;
  493.             $amountHt 0;
  494.             $totalDeliveryHt 0;
  495.             $amountTotal 0;
  496.             $totalDelivery 0;
  497.             $discount=0;
  498.             foreach ($carts as $cart) {
  499.                 $stock $cart->getStock();
  500.                 $sourceGrades $stock->getSourceGrade();
  501.                 foreach (explode(','$sourceGrades) as $sourceGrade) {
  502.                     if ($grade $gradeRepository->findOneByName($sourceGrade)) {
  503.                         if ($product $productRepository->findOneBy(array('channel'=>$this->getUser()->getShop()->getChannel(),'grade' => $grade'model' => $stock->getModel(), 'color' => $stock->getColor()))) {
  504.                             $cart->setSku($product->getSku());
  505.                             $cartRepository->add($cart);
  506.                             break;
  507.                         }
  508.                     }
  509.                 }
  510.                 $amountHt += (int)$cart->getQty() * $cart->getPrice();
  511.                 //echo $amountHt."<br/>";
  512.                 $totalProduct += (int)$cart->getQty();
  513.             }
  514.             if($order->getOptions()) {
  515.                 foreach($order->getOptions() as $option) {
  516.                     $amountHt+=($amountHt*((int)$option->getPrice())/100);
  517.                     //echo $amountHt."<br/>";
  518.                 }
  519.             }
  520.             if($order->getDiscount()) {
  521.                 $amountHt=$amountHt-$order->getDiscount();
  522.             }
  523.             $tAmountTotal $amountHt ;
  524.             if($order->getDeliveryHt()) {
  525.                 $tAmountTotal=$amountHt$order->getDeliveryHt();
  526.             }
  527.             $amountTotal = ($vat $tAmountTotal) / 100 $tAmountTotal ;
  528.             //$amountTotal = ($vat * $amountHt) / 100 + $amountHt ;
  529.             $priceService->getPrices($ordertrue);
  530. /*
  531.             $order->setTotalProduct($totalProduct);
  532.             $order->setAmountHt($amountHt);
  533.             $order->setAmountTotal($amountTotal);
  534. */
  535.             $order->setReference($order->generateReference());
  536.             $orderRepository->add($order);
  537.             $hasError true;
  538.             $response null;
  539.             $message "";
  540.             $datas $this->getPostOrderData($order$imeiRepository);
  541.             $logger->info(json_encode($datas));
  542.             if($shop->getSetting('stripe')) {
  543.                //die('stripe');
  544.                 return $this->renderForm('checkout/stripe.html.twig', [
  545.                     'order' => $order,
  546.                     'shop'=>$shop
  547.                 ]);
  548.             }
  549.             else if(!$order->getShop()->getSetting('post-to-b2l')) {
  550.                 $status $statusRepository->find(11); //posted
  551.                 $hasError false;
  552.                 $order->setStatus($status);
  553.                 $orderRepository->add($order);
  554.                 $this->sendConfirmationEmail($order$mailer$params);
  555.             }
  556.             else {
  557.                 if ($response $this->postOrder($datas)) {
  558.                     if (isset($response->orderId)) {
  559.                         $status $statusRepository->find(11);//posted
  560.                         $hasError false;
  561.                         $order->setB2lId($response->orderId);
  562.                         $order->setStatus($status);
  563.                         $orderRepository->add($order);
  564.                             $this->sendConfirmationEmail($order$mailer$params);
  565.                         //$this->moveColis($order);
  566.                     } else {
  567.                         //echo "eee";
  568.                         //var_dump($response);
  569.                         $logger->info($response);
  570.                         if (is_string($response)) {
  571.                             //var_dump($response);
  572.                             $message $response;
  573.                         }
  574.                     }
  575.                 } else {
  576.                     $hasError true;
  577.                     echo json_encode($datas);
  578.                     $message "no curl response";
  579.                 }
  580.             }
  581.         } else {
  582.             $hasError true;
  583.             $message "already processed";
  584.         }
  585.         return $this->render('order/confirm.html.twig', [
  586.             'order' => $order,
  587.             'error' => $hasError,
  588.             'message' => $message
  589.         ]);
  590.     }
  591.     /**
  592.      * @Route("/{id}/paid", name="app_order_paid", methods={"GET","POST"})
  593.      */
  594.     public function paid(Request $requestOrder $orderOrderRepository $orderRepositoryStatusRepository $statusRepositoryMailerInterface $mailerParameterBagInterface $params ): Response
  595.     {
  596.         $user $this->getUser();
  597.         if($order $orderRepository->findOneBy(array('user' => $user'status' => 10'confirm' => 0'id' => $order->getId()))) {
  598.             $shop $order->getShop();
  599.             $status $statusRepository->find(2); //Paiement accepté
  600.             $hasError false;
  601.             $order->setStatus($status);
  602.             if($shop->getCountry()=='es') {
  603.                 $stripeSecretKey $params->get("app.stripe_secret_key_es");
  604.             }
  605.             else {
  606.                 $stripeSecretKey $params->get("app.stripe_secret_key");
  607.             }
  608.             $stripe = new \Stripe\StripeClient($stripeSecretKey);
  609.             if($stripe_session $stripe->checkout->sessions->retrieve(
  610.                 $request->get('session_id'),
  611.                 []
  612.             )) {
  613.                 $order->setPayment("stripe");
  614.                 $order->setPaymentReference($stripe_session->payment_intent);
  615.             }
  616.             $orderRepository->add($order);
  617.             $this->sendConfirmationEmail($order$mailer$params);
  618.             return $this->renderForm('order/paid.html.twig', [
  619.                 'order' => $order,
  620.                 'shop' => $shop
  621.             ]);
  622.         }
  623.         else {
  624.             die('payment error');
  625.         }
  626.     }
  627.     /**
  628.      * @Route("/{id}", name="app_order_delete", methods={"POST"})
  629.      */
  630.     public function delete(Request $requestOrder $orderOrderRepository $orderRepository): Response
  631.     {
  632.         if ($this->isCsrfTokenValid('delete' $order->getId(), $request->request->get('_token'))) {
  633.             $order->setActive(0);
  634.             $orderRepository->add($order);
  635.             //$orderRepository->remove($order);
  636.         }
  637.         return $this->redirectToRoute('app_order_index', [], Response::HTTP_SEE_OTHER);
  638.     }
  639.     private function getPostOrderData($order$imeiRepository)
  640.     {
  641.         $isPos=$this->getUser()->getShop()->getSetting('is-point-of-sale');
  642.         $datetime = new \DateTime('now');
  643.         $date $datetime->format('Y-m-d\TH:i:s');
  644.         $reference $order->getReference();
  645.         $privateKey "eee";
  646.         $carts $order->getCarts();
  647.         $products = array();
  648.         foreach ($carts as $cart) {
  649.             $imeis=array();
  650.             $imeisCollection=$imeiRepository->findByCart($cart);
  651.             foreach($imeisCollection as $imei) {
  652.                 $imeis[]=$imei->getImei();
  653.             }
  654.             $products[] = array(
  655.                 'reference' => $cart->getSku(),
  656.                 'main_ref' => $cart->getStock()->getModel()->getMainReference(),
  657.                 "price" => $cart->getPrice() / 100 + ($cart->getPrice()*02) / 100,
  658.                 'qty' => $cart->getQty(),
  659.                 "imeis"=>implode(",",$imeis),
  660.                 'availability' => $cart->getStock()->getQty(),
  661.                 //'color'=>$cart->getStock()->getColor(),
  662.                 'name' => $cart->getStock()->getModel()->getName(),
  663.                 'manufacturer' => $cart->getStock()->getModel()->getManufacturer()->getName(),
  664.                 'attributes' => array(
  665.                     'color' => $cart->getStock()->getColor()->getName(),
  666.                 )
  667.             );
  668.             /*
  669.                         $products[] = array(
  670.                             "reference" =>$cart->getSku(),
  671.                             "name"=>$cart->getModel()->getName(),
  672.                             "main_ref"=>$cart->getSku(),
  673.                             "price" => $cart->getPrice(),
  674.                             "qty" => $cart->getQty()
  675.                         );
  676.             */
  677.         }
  678.         $invoiceAddress $order->getInvoiceAddress();
  679.         $deliveryAddress $order->getDeliveryAddress();
  680.         $invoiceEmail $deliveryAddress->getEmail();
  681.         $parentUser=null;
  682.         if(!$this->getUser()->getShop()->getSetting('is-point-of-sale')) {
  683.             if ($this->getUser()->getParent() && !$isPos) {
  684.                 $parentUser $this->getUser()->getParent();
  685.                 $invoiceEmail $parentUser->getEmail();
  686.                 $company $parentUser->getCompany();
  687.                 $invoiceAddress $parentUser->getCompany()->getAddress();
  688.             }
  689.         }
  690.         $privateKey "2y10DBkKsebmrm6fh5uDHR7eQeJtHQitSUeSpLnQmkyXLyR3og4nSy";
  691.         $str $privateKey "+" $reference "+" $date "+" $invoiceEmail;
  692.         foreach ($products as $product) {
  693.             $str .= "+" $product['reference'] . "+" $product['qty'];
  694.         }
  695.         $hash md5($str);
  696.         $datas = [
  697.             "hash" => $hash,
  698.             "reference" => $reference,
  699.             "date" => $date,
  700.             "carrier" => "DHL".(!$this->getUser()->getShop()->getSetting('is-point-of-sale')?' B2B':' Gratuit'),
  701.             "id_shop" => $this->getUser()->getShop()->getSetting('is-point-of-sale')?1:2,
  702.             "payment_method"=>$order->getPayment(),
  703.             "billing_address" => [
  704.                 //"alias"=>$parentUser->getCompany()->getName(),
  705.                 "company" => $parentUser?$parentUser->getCompany()->getName():$invoiceAddress->getName(),
  706.                 "firstname" => $parentUser?$parentUser->getFirstname():$invoiceAddress->getFirstname(),
  707.                 "lastname" => $parentUser?$parentUser->getLastname():$invoiceAddress->getLastname(),
  708.                 "email" => $invoiceEmail,
  709.                 "address1" => $invoiceAddress->getAddress(),
  710.                 "address2" => "",
  711.                 "postcode" => $invoiceAddress->getZip(),
  712.                 "city" => $invoiceAddress->getCity(),
  713.                 "phone" => $invoiceAddress->getPhone(),
  714.                 "country" => substr(strtoupper($deliveryAddress->getCountry()), 02),
  715.                 "vat_number" => $parentUser?$parentUser->getCompany()->getVat():''
  716.             ],
  717.             "shipping_address" => [
  718.                 "alias" => $deliveryAddress->getName(),
  719.                 "company" => $deliveryAddress->getName(),
  720.                 "firstname" => $isPos?$deliveryAddress->getFirstname():$order->getUser()->getFirstname(),
  721.                 "lastname" => $isPos?$deliveryAddress->getLastname():$order->getUser()->getLastname(),
  722.                 "address1" => $deliveryAddress->getAddress(),
  723.                 "address2" => "",
  724.                 "postcode" => $deliveryAddress->getZip(),
  725.                 "city" => $deliveryAddress->getCity(),
  726.                 "phone" => $deliveryAddress->getPhone(),
  727.                 "country" => substr(strtoupper($deliveryAddress->getCountry()), 02)
  728.             ],
  729.             "cart" => [
  730.                 "products" => $products
  731.             ]
  732.         ];
  733.         return $datas;
  734.     }
  735.     private function postOrder($datas)
  736.     {
  737.         $this->bak2life_api_key $this->getUser()->getShop()->getApikey();
  738.         $url $this->bak2life_api_url "?order=1";
  739.         $curl curl_init();
  740.         curl_setopt_array($curl, array(
  741.             CURLOPT_URL => $url,
  742.             CURLOPT_RETURNTRANSFER => true,
  743.             CURLOPT_ENCODING => "",
  744.             CURLOPT_MAXREDIRS => 10,
  745.             CURLOPT_TIMEOUT => 30,
  746.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  747.             CURLOPT_CUSTOMREQUEST => "POST",
  748.             CURLOPT_USERPWD => $this->bak2life_api_key ":",
  749.             CURLOPT_HTTPHEADER => array(
  750.                 "cache-control: no-cache",
  751.                 'Content-Type:application/json'
  752.             ),
  753.             CURLOPT_POSTFIELDS => json_encode($datas),
  754.         ));
  755.         //$mailMessage['response']=$response;
  756.         $err curl_error($curl);
  757.         if ($err) {
  758.             return array('error' => $err);
  759.             // mail($dest,'sync order kustee curcl error', json_encode($mailMessage));
  760.         } else {
  761.             $response curl_exec($curl);
  762.             curl_close($curl);
  763.             $return json_decode($response);
  764.             if (isset($return->success)) {
  765.                 $responseArray json_decode($return->success);
  766.                 return $responseArray;
  767.             }
  768.             mail($this->mailer_sender'error'json_encode($datas));
  769.             return $return;
  770.         }
  771.     }
  772.     /**
  773.      * @Route("/{id}/invoice", name="app_order_download_invoice", methods={"GET"})
  774.      */
  775.     public function downloadInvoice(Order $order): Response {
  776.         $this->bak2life_api_key $this->getUser()->getShop()->getApikey();
  777.         $url $this->bak2life_api_url "?invoice=1&reference=".$order->getBak2Reference();
  778.         $curl curl_init();
  779.         curl_setopt_array($curl, array(
  780.             CURLOPT_URL => $url,
  781.             CURLOPT_RETURNTRANSFER => true,
  782.             CURLOPT_ENCODING => "",
  783.             CURLOPT_MAXREDIRS => 10,
  784.             CURLOPT_TIMEOUT => 30,
  785.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  786.             CURLOPT_CUSTOMREQUEST => "POST",
  787.             CURLOPT_USERPWD => $this->bak2life_api_key ":",
  788.             CURLOPT_HTTPHEADER => array(
  789.                 "cache-control: no-cache",
  790.                 'Content-Type:application/json'
  791.             )
  792.         ));
  793.         $err curl_error($curl);
  794.         if ($err) {
  795.             return array('error' => $err);
  796.             // mail($dest,'sync order kustee curcl error', json_encode($mailMessage));
  797.         } else {
  798.             $response curl_exec($curl);
  799.             curl_close($curl);
  800.             header('Content-type: application/pdf');
  801.             echo $response;
  802.             die();
  803.         }
  804.         return $this->redirectToRoute('app_order_index', [], Response::HTTP_SEE_OTHER);
  805.     }
  806.     public function syncOrders($em)
  807.     {
  808.         $shops $em->getRepository(Shop::class)->findAll();
  809.         foreach($shops as $shop) {
  810.             if($this->bak2life_api_key=$shop->getApiKey()) {
  811.                 echo $shop->getName()."\n";
  812.                 $orders $em->getRepository(Order::class)->findAllNotIn('status', array(567810), null);
  813.                 foreach ($orders as $order) {
  814.                     $url $this->bak2life_api_url "?sync=1&reference=" $order->getReference();
  815.                     //echo $url;
  816.                     $curl curl_init();
  817.                     curl_setopt_array($curl, array(
  818.                         CURLOPT_URL => $url,
  819.                         CURLOPT_RETURNTRANSFER => true,
  820.                         CURLOPT_ENCODING => "",
  821.                         CURLOPT_MAXREDIRS => 10,
  822.                         CURLOPT_TIMEOUT => 30,
  823.                         CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  824.                         CURLOPT_CUSTOMREQUEST => "GET",
  825.                         CURLOPT_USERPWD => $this->bak2life_api_key ":",
  826.                         CURLOPT_HTTPHEADER => array(
  827.                             "cache-control: no-cache",
  828.                             'Content-Type:application/json'
  829.                         ),
  830.                         //CURLOPT_POSTFIELDS => json_encode($orderToPost),
  831.                     ));
  832.                     $response curl_exec($curl);
  833.                     //var_dump($response);
  834.                     $mailMessage['response'] = $response;
  835.                     $err curl_error($curl);
  836.                     if ($err) {
  837.                         //echo $response;
  838.                         echo "cURL Error---- #:" $err;
  839.                         mail($this->dest'sync order kustee curcl error'json_encode($mailMessage));
  840.                     } else {
  841.                         $b2lOrder json_decode($response);
  842.                         if (isset($b2lOrder->reference)) {
  843.                             $order->setBak2Reference($b2lOrder->reference);
  844.                             $order->setShippingNumber($b2lOrder->shipping_number);
  845.                             if ($status $em->getRepository(Status::class)->findOneByB2lId($b2lOrder->current_state)) {
  846.                                 $order->setStatus($status);
  847.                             }
  848.                             $em->persist($order);
  849.                         }
  850.                     }
  851.                     $this->moveColis($order$em);
  852.                 }
  853.                 $em->flush();
  854.             }
  855.         }
  856.         //$this->bak2life_api_key = $this->getUser()->getShop()->getApikey();
  857.         return 'ok';
  858.     }
  859.     private function sendConfirmationEmail(Order $orderMailerInterface $mailerParameterBagInterface $params)
  860.     {
  861.         $isPos=$this->getUser()->getShop()->getSetting('is-point-of-sale');
  862.         $b2Order=$this->getUser()->getShop()->getSetting('post-to-b2l');
  863.         $bcc = array($this->mailer_sender);
  864.         //$subject = '[' . $order->getUser()->getCompany() . '] '.$b2Order==1?"Confirmation de commande":"Demande d'offre";
  865.         $subject '[' $order->getUser()->getCompany() . ']  Confirmation de commande';
  866.         if($order->getStatus()->getId()==2) {
  867.             $subject '[' $order->getUser()->getCompany() . ']  Confirmation de commande';
  868.         }
  869.         if ($parentUser $order->getUser()->getParent()) {
  870.             $subject '[' $order->getUser()->getParent()->getCompany() . '][' $order->getUser()->getCompany() . '] Confirmation de commande';
  871.         }
  872.         $destinationEmail=$order->getUser()->getEmail();
  873.         if($order->getInvoiceAddress()->getEmail()!='') {
  874.             $destinationEmail=$order->getInvoiceAddress()->getEmail();
  875.         }
  876.         if($mailCopy=$this->getUser()->getShop()->getMailCopy()) {
  877.             $bcc=array_merge($bcc,explode(',',$mailCopy));
  878.         }
  879.         if($isPos) {
  880.             $destinationEmail=$this->getUser()->getEmail();//$order->getInvoiceAddress()->getEmail();
  881.             $subject '[' $order->getUser()->getCompany() . '] Confirmation de commande';
  882.         }
  883.         //attachment
  884.         $filename=$order->getReference().".pdf";
  885.         $filePath=$params->get('kernel.project_dir').'/private/users/'.$order->getUser()->getId().'/orders/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$filename;
  886.         if(!file_exists($filePath)) {
  887.             $this->createPdf($order$filePath$params);
  888.         }
  889.         $email = (new TemplatedEmail())
  890.             ->from($this->mailer_sender)
  891.             ->to($destinationEmail)
  892.             ->bcc(...$bcc)
  893.             ->subject($subject)
  894.             // path of the Twig template to render
  895.             ->htmlTemplate('emails/order/confirm.html.twig')
  896.             ->attachFromPath($filePath)
  897.             // pass variables (name => value) to the template
  898.             ->context([
  899.                 'order' => $order,
  900.                 'shop'=>$order->getShop()
  901.             ]);
  902.         if ($parentUser $order->getUser()->getParent()) {
  903.             $email->addBcc($parentUser->getEmail());
  904.         }
  905.         try {
  906.             $mailer->send($email);
  907.         } catch (TransportExceptionInterface $e) {
  908.             // some error prevented the email sending; display an
  909.             // error message or try to resend the message
  910.             echo "<pre>";
  911.             var_dump($e);
  912.             echo "</pre>";
  913.         }
  914.         //$bcc = $this->mailer_sender;
  915.         $email = (new TemplatedEmail())
  916.             ->from($this->mailer_sender)
  917.             ->to($this->mailer_sender)
  918.             ->bcc(...$bcc)
  919.             ->subject($subject)
  920.             // path of the Twig template to render
  921.             ->htmlTemplate('emails/order/inform.html.twig')
  922.             ->attachFromPath($filePath)
  923.             // pass variables (name => value) to the template
  924.             ->context([
  925.                 'order' => $order,
  926.                 //'cartOptions'=>$optionService->getCartOptions($order),
  927.                 'shop'=>$order->getShop()
  928.             ]);
  929.         if ($parentUser $order->getUser()->getParent()) {
  930.             $email->addCc($parentUser->getEmail());
  931.         }
  932.         if($order->getUser()->getCompany()) {
  933.             if ($parentCompany $order->getUser()->getCompany()->getParent()) {
  934.                 foreach($parentCompany->getUsers() as $parentUser) {
  935.                     $email->addCc($parentUser->getEmail());
  936.                 }
  937.             }
  938.         }
  939.         try {
  940.             $mailer->send($email);
  941.         } catch (TransportExceptionInterface $e) {
  942.             // some error prevented the email sending; display an
  943.             // error message or try to resend the message
  944.             echo "<pre>cc-";
  945.             var_dump($e);
  946.             echo "</pre>";
  947.         }
  948.     }
  949.     private function setAddress($newAddress$address null) {
  950.         if(!$address) {
  951.             $address = new \App\Entity\Address();
  952.         }
  953.         if(!$name=$newAddress->getName()) {
  954.             $name=$newAddress->getFirstname()." ".$newAddress->getLastname();
  955.         }
  956.         $address->setName($name);
  957.         $address->setFirstname($newAddress->getFirstname());
  958.         $address->setLastname($newAddress->getLastname());
  959.         $address->setAddress($newAddress->getAddress());
  960.         $address->setZip($newAddress->getZip());
  961.         $address->setCity($newAddress->getCity());
  962.         $address->setCountry($newAddress->getCountry());
  963.         $address->setPhone($newAddress->getPhone());
  964.         $address->setEmail($newAddress->getEmail());
  965.         return $address;
  966.     }
  967.     private function moveColis($order,$em) {
  968.         $imeiRepository $em->getRepository(Imei::class);
  969.         $buyerId=$this->bak2_mp_buyer_id;
  970.         $currentColis=array();
  971.        // echo $this->bak2_api_url . "/tempStock.php?action=getColisByBuyerId&buyerId=" . $buyerId;
  972.         if($allColis=file_get_contents($this->bak2_api_url "/tempStock.php?action=getColisByBuyerId&buyerId=" $buyerId)) {
  973.             //echo $this->bak2_api_url . "/tempStock.php?action=getColisByBuyerId&buyerId=" . $buyerId;
  974.             $allColis=json_decode($allColis);
  975.             foreach($allColis as $colis) {
  976.                 if(!isset($currentColis[$colis->outGrade])) {
  977.                     $currentColis[$colis->outGrade]=$colis->colisId;
  978.                 }
  979.             }
  980.         }
  981.         foreach($order->getCarts() as $cart) {
  982.             if($imeis=$cart->getImei()) {
  983.                 foreach($imeis as $imei) {
  984.                     if(!$imei->getSync()) {
  985.                         $outGrade $cart->getStock()->getSourceGrade();
  986.                         //echo $outGrade;
  987.                         if($imeiMoved=file_get_contents($this->bak2_api_url "/tempStock.php?action=moveImeiToColis&imei=" $imei->getImei()."&colisId=".$currentColis[$outGrade])) {
  988.                             $imeiMoved=json_decode($imeiMoved);
  989.                             //echo intval((string)$imeiMoved->colisId);
  990.                             if($currentColis[$outGrade]==$imeiMoved->colisId) {
  991.                                 $imei->setSync(true);
  992.                                 $imeiRepository->add($imei);
  993.                             }
  994.                         }
  995.                     }
  996.                 }
  997.             }
  998.         }
  999.         $em->flush();
  1000.         //$productContent = file_get_contents($this->bak2_api_url . "/tempStock.php?action=getProductByColis&imei=" . $imei);
  1001.     }
  1002.     private function getDeliveryPrice($order,DeliveryRepository $deliveryRepository) {
  1003.         $cats=array();
  1004.         $deliveryHt=0;
  1005.         foreach($order->getCarts() as $cart) {
  1006.             $categoryId=$cart->getStock()->getModel()->getCategory()->getId();
  1007.             if(!isset($cats[$categoryId])) {
  1008.                 $cats[$categoryId]=0;
  1009.             }
  1010.             $cats[$categoryId]+=(int)$cart->getQty();
  1011.             //echo $cart->getStock()->getModel()->getCategory();
  1012.         }
  1013.         foreach($cats as $cat=>$qty) {
  1014.             if($deliveries=$deliveryRepository->findBy(array('category'=>$cat,'fromUnit'=>$qty,'shop'=>$order->getShop()->getId()))) {
  1015.                 $deliveryHt+=(int)$deliveries[0]->getPrice()*$qty;
  1016.             }
  1017.         }
  1018.         return $deliveryHt;
  1019.     }
  1020.     public function priceSummary(Request $requestOrder $orderstring $nextStepbool $couponPriceService $priceServiceOrderRepository $orderRepositoryCouponRepository $couponRepository) {
  1021.         $prices=$priceService->getPrices($order);
  1022.         if(!$couponRepository->findBy(['shop'=>$order->getShop()])) {
  1023.             $coupon=false;
  1024.         }
  1025.         $couponForm $this->createForm(OrderCouponType::class, $order,[
  1026.             'action'=>$this->generateUrl('app_order_coupon',['id'=>$order->getId()])
  1027.         ]);
  1028.         return $this->renderForm('order/price.html.twig', [
  1029.             'order'=>$order,
  1030.             'prices'=>$prices,
  1031.             'nextStep'=>$nextStep,
  1032.             'coupon'=>$coupon,
  1033.             'couponForm'=>$couponForm
  1034.         ]);
  1035.     }
  1036.     /**
  1037.      * @Route("/{id}/pdf/invoice", name="app_order_pdf_invoice", methods={"GET"})
  1038.      */
  1039.     public function pdfInvoice(Order $orderParameterBagInterface $parameterBag) {
  1040.         $user=$this->getUser();
  1041.         if($order->getUser()->getId()!=$user->getId() || !$this->isGranted('ROLE_ADMIN')) {
  1042.             if($order->getInvoiceFilename()!='') {
  1043.                 $filename=$order->getInvoiceFilename();
  1044.                 $filePath=$parameterBag->get('kernel.project_dir').'/private/users/'.$order->getUser()->getId().'/invoices/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$filename;
  1045.                 $headers = array('Content-Type'     => 'application/pdf',
  1046.                     'Content-Disposition' => 'inline; filename="file1.pdf"');
  1047.                 return new Response(file_get_contents($filePath), 200$headers);
  1048.                 //return $this->redirect('/uploads/invoices/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$order->getInvoiceFilename());
  1049.             }
  1050.             return $this->redirectToRoute('app_order_edit',['id'=>$order->getId()]);
  1051.         }
  1052.         return $this->redirectToRoute('app_order_show',['id'=>$order->getId()]);
  1053.     }
  1054.     /**
  1055.      * @Route("/{id}/pdf/order", name="app_order_pdf_order", methods={"GET"})
  1056.      */
  1057.     public function pdfOrder(Order $orderParameterBagInterface $parameterBag) {
  1058.         $user=$this->getUser();
  1059.         if($order->getUser()->getId()!=$user->getId() || !$this->isGranted('ROLE_ADMIN')) {
  1060.         $filename=$order->getReference().".pdf";
  1061.         //$filePath=$parameterBag->get('kernel.project_dir').'/public/uploads/orders/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$filename;
  1062.         $filePath=$parameterBag->get('kernel.project_dir').'/private/users/'.$order->getUser()->getId().'/orders/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$filename;
  1063.         if(!file_exists($filePath)) {
  1064.             $this->createPdf($order$filePath$parameterBag);
  1065.         }
  1066.         $headers = array('Content-Type'     => 'application/pdf',
  1067.             'Content-Disposition' => 'inline; filename="file1.pdf"');
  1068.         return new Response(file_get_contents($filePath), 200$headers);
  1069.         }
  1070.         return $this->redirectToRoute('app_order_show',['id'=>$order->getId()]);
  1071.        // return $this->redirect('/uploads/orders/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$filename);
  1072.     }
  1073.         /**
  1074.      * @Route("/{id}/coupon", name="app_order_coupon", methods={"GET", "POST"})
  1075.      */
  1076.     public function coupon(Request $requestOrder $orderOrderRepository $orderRepository) {
  1077.         $couponForm $this->createForm(OrderCouponType::class, $order,[
  1078.             'action'=>$this->generateUrl('app_order_coupon',['id'=>$order->getId()])
  1079.         ]);
  1080.         $couponForm->handleRequest($request);
  1081.         if($couponForm->isSubmitted() && $couponForm->isValid()) {
  1082.             $orderRepository->add($order);
  1083.         }
  1084.         return $this->redirectToRoute('app_cart_index', [], Response::HTTP_SEE_OTHER);
  1085.     }
  1086.     private function createPdf($order$filepath$parameterBag) {
  1087.         $company=null;
  1088.         $parentCompany=null;
  1089.         if($order->getUser()->getCompany()) {
  1090.             if($company=$order->getUser()->getCompany()) {
  1091.                 if($company->getParent()) {
  1092.                     $parentCompany=$company->getParent();
  1093.                 }
  1094.             }
  1095.         }
  1096.         $template='order/pdf.html.twig';
  1097.         if(file_exists($parameterBag->get('kernel.project_dir')."/private/shops/".$order->getShop()->getId()."/templates/order.html.twig")) {
  1098.             $template="shops/".$order->getShop()->getId()."/templates/order.html.twig";
  1099.         }
  1100.         $knpSnappyPdf=new Pdf($parameterBag->get('app.wkhtmltopdf'));
  1101.         $knpSnappyPdf->setTemporaryFolder($parameterBag->get('kernel.project_dir')."/tmp");
  1102.         $knpSnappyPdf->setOptions([
  1103.             'enable-local-file-access' => true,
  1104.             'keep-relative-links' => true,
  1105.             'disable-smart-shrinking' => true,
  1106.             'margin-top'=>"20mm",
  1107.             'margin-right'=>"20mm",
  1108.             'margin-bottom'=>"20mm",
  1109.             'margin-left'=>"20mm",
  1110.         ]);
  1111.         $html=$this->renderView(
  1112.             $template,
  1113.             array(
  1114.                 'order'  => $order,
  1115.                 'company'=>$company,
  1116.                 'parentCompany'=>$parentCompany
  1117.             )
  1118.         );
  1119.         $knpSnappyPdf->generateFromHtml(
  1120.             $html,
  1121.             $filepath
  1122.         );
  1123.     }
  1124. }