src/Controller/OrderController.php line 115

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Company;
  4. use App\Entity\File\Contract;
  5. use App\Entity\File\DigiSign;
  6. use App\Entity\File\File;
  7. use App\Entity\File\Signi;
  8. use App\Entity\File\SimpleFile;
  9. use App\Entity\Order;
  10. use App\Entity\OrderEshop;
  11. use App\Entity\Product;
  12. use App\Entity\User;
  13. use App\Exception\FulltextSearchNullResults;
  14. use App\Form\Filter\OrderFilterType;
  15. use App\Form\OrderType;
  16. use App\Helper\EnumsHelper;
  17. use App\Model\FileModel;
  18. use App\Model\RewardLineModel;
  19. use App\Model\RewardModel;
  20. use App\Model\UserModel;
  21. use App\Repository\FileRepository;
  22. use App\Repository\OrderRepository;
  23. use App\Repository\ProductRepository;
  24. use App\Repository\UserRepository;
  25. use App\Security\Voter\OrderVoter;
  26. use App\Services\GalosoftAdamna;
  27. use App\Services\GalosoftDigiSign;
  28. use App\Services\GalosoftDigiSignGenerator;
  29. use App\Services\GalosoftMailerInterface;
  30. use App\Services\GalosoftNotifications;
  31. use App\Services\GalosoftPdfGenerator;
  32. use App\Services\GalosoftRaynet;
  33. use App\Services\GalosoftSigni;
  34. use App\Services\GalosoftSigniGenerator;
  35. use App\Services\GalosoftValuablePaperGenerator;
  36. use App\Services\OrderFilter;
  37. use Doctrine\ORM\EntityManagerInterface;
  38. use Knp\Component\Pager\PaginatorInterface;
  39. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  40. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  41. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  42. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  43. use Symfony\Component\HttpFoundation\JsonResponse;
  44. use Symfony\Component\HttpFoundation\Request;
  45. use Symfony\Component\HttpFoundation\Response;
  46. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  47. use Symfony\Component\HttpFoundation\Session\Session;
  48. use Symfony\Component\HttpFoundation\StreamedResponse;
  49. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  50. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  51. use Symfony\Component\Routing\Annotation\Route;
  52. /**
  53.  *
  54.  */
  55. class OrderController extends AbstractController
  56. {
  57.     /**
  58.      * @isGranted("ROLE_MERCHANT")
  59.      * @Route("/order", name="app_order_index", methods={"GET", "POST"})
  60.      */
  61.     public function index(FileRepository $repository,
  62.                           OrderRepository $orderRepository,
  63.                           Request $request,
  64.                           PaginatorInterface $paginator,
  65.                           GalosoftSigni $galosoftSigni,
  66.                           Session $session,
  67.                           EntityManagerInterface $entityManager,
  68.                           OrderFilter $orderFilter,
  69.                           UserModel $userModel,
  70.                           \Symfony\Component\Security\Core\Security $security
  71.     ): Response
  72.     {
  73.         // clear filter
  74.         if($orderFilter->clearFilter($session$request) == true){
  75.             return $this->redirect($this->generateUrl('app_order_index'));
  76.         }
  77.         // ulozeni strankovace
  78.         $paginationSettings $orderFilter->storePaginationSettings($session$request);
  79.         // predvyplneni formulare filtrace
  80.         $data $orderFilter->loadPrefilledData($session$entityManager);
  81.         $formFilter $this->createForm(OrderFilterType::class, $data, [
  82.             'action' => $this->generateUrl('app_order_index'),
  83.             'method' => 'post',
  84.             'request' => $request,
  85.         ]);
  86.         // ulozim filtr do session
  87.         $orderFilter->storeFilter($formFilter$request$session);
  88.         // aplikace filtru na query builder
  89.         $queryBuilder $orderRepository->createQueryBuilder('o');
  90.         try {
  91.             $orders $orderFilter->applyFilter($session$request$queryBuilder$paginator);
  92.         }catch (FulltextSearchNullResults $e){
  93.             $orders = [];
  94.         }
  95.         return $this->render('order/index.html.twig', [
  96.             'orders' => $orders,
  97.             'filter' => $formFilter->createView(),
  98.             'ordering' => $paginationSettings['ordering'],
  99.             'pageSize' => $paginationSettings['pageSize'],
  100.             'isOnlyMetalist' => $orderRepository->isOnlyMetalist()
  101.         ]);
  102.     }
  103.     /**
  104.      * @Route("/order/export/{type}", name="app_order_export", methods={"GET"})
  105.      */
  106.     public function export(
  107.         OrderRepository $orderRepository,
  108.         Session $session,
  109.         Request $request,
  110.         OrderFilter $orderFilter
  111.     ){
  112.         $queryBuilder $orderRepository->createQueryBuilder('o');
  113.         $orders $orderFilter->applyFilter($session$request$queryBuilder);
  114.         $outputBuffer fopen("php://temp"'w');
  115.         $header = [
  116.             "ID",
  117.             "Datum podpisu",
  118.             "Datum úhrady",
  119.             "Datum odeslání",
  120.             "Datum doručeno",
  121.             "Produkt",
  122.             "Společnost",
  123.             "Jméno",
  124.             "Příjmení",
  125.             "T.P. - Ulice",
  126.             "T.P. - Město",
  127.             "T.P. - PSČ",
  128.             "K.A. - Ulice",
  129.             "K.A. - Město",
  130.             "K.A. - PSČ",
  131.             "Email",
  132.             "Telefon",
  133.             "Částka",
  134.             "Měna",
  135.             "Kód zástupce",
  136.             "Jméno zástupce",
  137.             "Email zástupce"
  138.         ];
  139.         fputcsv($outputBuffer$header);
  140.         $sum 0;
  141.         /** @var Order $order */
  142.         foreach($orders->getQuery()->getResult() as $order) {
  143.             $row = [
  144.                 $order->getId(),
  145.                 ($order->getSignedDate() instanceof \DateTime $order->getSignedDate()->format('Y-m-d') : ""),
  146.                 ($order->getPaidDate() instanceof \DateTime $order->getPaidDate()->format('Y-m-d') : ""),
  147.                 ($order->getSentDate() instanceof \DateTime $order->getSentDate()->format('Y-m-d') : ""),
  148.                 ($order->getVpDeliveryDate() instanceof \DateTime $order->getVpDeliveryDate()->format('Y-m-d') : ""),
  149.                 ($order->getProduct() instanceof Product) ? $order->getProduct()->getName() : '-',
  150.                 ($order->getCompany() instanceof Company) ? $order->getCompany()->getName() : '-',
  151.                 ($this->isGranted(OrderVoter::NOT_ANONYMIZE$order) ? $order->getName() : ""),
  152.                 ($this->isGranted(OrderVoter::NOT_ANONYMIZE$order) ? $order->getSurname() : ""),
  153.                 ($this->isGranted(OrderVoter::NOT_ANONYMIZE$order) ? $order->getStreet() : ""),
  154.                 ($this->isGranted(OrderVoter::NOT_ANONYMIZE$order) ? $order->getTown() : ""),
  155.                 ($this->isGranted(OrderVoter::NOT_ANONYMIZE$order) ? $order->getPostal() : ""),
  156.                 ($this->isGranted(OrderVoter::NOT_ANONYMIZE$order) ? $order->getStreet2() : ""),
  157.                 ($this->isGranted(OrderVoter::NOT_ANONYMIZE$order) ? $order->getTown2() : ""),
  158.                 ($this->isGranted(OrderVoter::NOT_ANONYMIZE$order) ? $order->getPostal2() : ""),
  159.                 ($this->isGranted(OrderVoter::NOT_ANONYMIZE$order) ? $order->getEmail() : ""),
  160.                 ($this->isGranted(OrderVoter::NOT_ANONYMIZE$order) ? $order->getPhone() : ""),
  161.                 $order->getProductPriceTotal(),
  162.                 ($order->getProduct() instanceof Product) ? $order->getProduct()->getCurrency() : '-',
  163.                 ($this->isGranted(OrderVoter::NOT_ANONYMIZE$order) ? $order->getMerchantCode() : ""),
  164.                 ($this->isGranted(OrderVoter::NOT_ANONYMIZE$order) ? ($order->getMerchant() instanceof User $order->getMerchant()->getName() . " " $order->getMerchant()->getSurname() : '') : ""),
  165.                 ($this->isGranted(OrderVoter::NOT_ANONYMIZE$order) ? ($order->getMerchant() instanceof User $order->getMerchant()->getEmail() : '') : "")
  166.             ];
  167.             $sum $sum + (float)$order->getProductPriceTotal();
  168.             fputcsv($outputBuffer$row);
  169.         }
  170.         $footer = ["CELKEM"""""""""""""""""""""""""""""""""$sum""""""""];
  171.         fputcsv($outputBuffer$footer);
  172.         rewind($outputBuffer);
  173.         $response = new Response(stream_get_contents($outputBuffer));
  174.         fclose($outputBuffer);
  175.         $response->headers->set('Content-Type''text/csv');
  176.         $response->headers->set('Content-Disposition''attachment; filename="EFS_'.date('Ymd').'.csv"');
  177.         return $response;
  178.     }
  179.     /**
  180.      * @IsGranted("ROLE_ADMIN")
  181.      *
  182.      * @Route("/order/report/{type}", name="app_order_report", methods={"GET"})
  183.      */
  184.     public function report(
  185.         OrderRepository $orderRepository,
  186.         Session $session,
  187.         Request $request,
  188.         OrderFilter $orderFilter,
  189.         RewardModel $rewardModel
  190.     ){
  191.         $queryBuilder $orderRepository->createQueryBuilder('o');
  192.         $orders $orderFilter->applyFilter($session$request$queryBuilder);
  193.         $rewards $rewardModel->byOrderList($orders->getQuery()->getResult());
  194.         $outputBuffer fopen("php://temp"'w');
  195.         $header = [
  196.             "Jméno",
  197.             "Objednávka",
  198.             "Produkt",
  199.             "Celkem",
  200.             "Odměna %",
  201.             "Odměna Kč",
  202.             "Vztah"
  203.         ];
  204.         fputcsv($outputBuffer$header);
  205.         /** @var RewardLineModel $reward */
  206.         foreach($rewards as $reward) {
  207.             $row $reward->toArray();
  208.             fputcsv($outputBuffer$row);
  209.         }
  210.         rewind($outputBuffer);
  211.         $response = new Response(stream_get_contents($outputBuffer));
  212.         fclose($outputBuffer);
  213.         $response->headers->set('Content-Type''text/csv');
  214.         $response->headers->set('Content-Disposition''attachment; filename="EFS_report_'.date('Ymd').'.csv"');
  215.         return $response;
  216.     }
  217.     /**
  218.      * @Route("/order/new", name="app_order_new", methods={"GET", "POST"})
  219.      */
  220.     public function new(Request $requestOrderRepository $orderRepository): Response
  221.     {
  222.         $order = new Order();
  223.         $currentPersonType $order->getPersonType();
  224.         if(is_null($currentPersonType)){
  225.             $order->setPersonType('FO');
  226.         }
  227.         $options = [
  228.             'action' => $this->generateUrl('app_order_new_process'),
  229.             'method' => 'post',
  230.             'logged_user' => $this->getUser()
  231.         ];
  232.         $form $this->createForm(OrderType::class, $order$options);
  233.         $form->handleRequest($request);
  234.         return $this->render('order/new.html.twig', [
  235.             'form' => $form->createView(),
  236.             'product' => $order->getProduct(),
  237.             'reloadUrl' => $this->generateUrl('app_order_new')
  238.         ]);
  239.     }
  240.     /**
  241.      * @Route("/order/{hash}/preview", name="app_order_preview")
  242.      */
  243.     public function previewPdf(
  244.         Request $request,
  245.         $hash,
  246.         OrderRepository $orderRepository,
  247.         EntityManagerInterface $entityManager,
  248.         GalosoftPdfGenerator $pdfGenerator
  249.     ){
  250.         $order $orderRepository->findOneBy(['hash' => $hash]);
  251.         if(!$order){
  252.             throw new NotFoundHttpException('Objednávka nenalezena');
  253.         }
  254.         $pdf $pdfGenerator->generatePdf($orderfalse);
  255.         $response = new StreamedResponse(function() use ($pdf) {
  256.             $outputStream fopen('php://output''wb');
  257.             $fileStream fopen($pdf->getUrlDel(), 'r+');
  258.             stream_copy_to_stream($fileStream$outputStream);
  259.         });
  260.         $response->headers->set('Content-Type'$pdf->getMime());
  261.         return $response;
  262.     }
  263.     /**
  264.      * @Route("/order/{order}", name="app_order_detail", requirements={"order"="\d+"})
  265.      */
  266.     public function detail(Order $orderUserModel $userModel\Symfony\Component\Security\Core\Security $security): Response
  267.     {
  268.         $this->denyAccessUnlessGranted(OrderVoter::NOT_ANONYMIZE$order);
  269.         return $this->render('order/view.html.twig', [
  270.             'order' => $order,
  271.             'isOrderMetalist' => $order instanceof OrderEshop
  272.         ]);
  273.     }
  274.     /**
  275.      * @Route("/order/{order}/sequence-number", name="app_order_save_sequence_number", requirements={"order"="\d+"})
  276.      */
  277.     public function saveSequenceNumber(
  278.         Request $request,
  279.         Order $order,
  280.         EntityManagerInterface $entityManager
  281.     ): Response
  282.     {
  283.         try {
  284.             //TODO: Add checking access for admin only
  285.             //$this->denyAccessUnlessGranted(OrderVoter::VIEW, $order);
  286.             $sequenceNumber $request->get('sequenceNumber'null);
  287.             if (!is_null($sequenceNumber)) {
  288.                 $order->setSequenceNumber($sequenceNumber);
  289.                 $entityManager->flush();
  290.             }
  291.             return $this->json(['status' => 'success']);
  292.         } catch (\Exception $exception) {
  293.             return $this->json(['status' => 'error''message' => $exception->getMessage()]);
  294.         }
  295.     }
  296.     /**
  297.      * @Route("/order/{order}/valuable-paper/generate", name="app_order_valuable_paper_generate", requirements={"order"="\d+"})
  298.      */
  299.     public function generateValuablePaper(
  300.         Request $request,
  301.         Order $order,
  302.         EntityManagerInterface $entityManager,
  303.         GalosoftValuablePaperGenerator $galosoftValuablePaperGenerator
  304.     ): Response
  305.     {
  306.         try {
  307.             //TODO: Add checking access for admin only
  308.             //$this->denyAccessUnlessGranted(OrderVoter::VIEW, $order);
  309.             // generate and save valuable paper
  310.             $galosoftValuablePaperGenerator->generatePdf($order);
  311.             // generate and save valuable paper
  312.             $galosoftValuablePaperGenerator->generatePdf($ordertrueGalosoftValuablePaperGenerator::TYPE_PDF_VALUABLE_PROTOCOL);
  313.             return $this->forward(OrderController::class . '::detail', [
  314.                 'order' => $order->getId()
  315.             ]);
  316.         } catch (\Exception $exception) {
  317.             return $this->json(['status' => 'error''message' => $exception->getMessage()]);
  318.         }
  319.     }
  320.     /**
  321.      * @Route("/order/{order}/edit", name="app_order_edit", requirements={"order"="\d+"})
  322.      */
  323.     public function show(Order $order): Response
  324.     {
  325.         $this->denyAccessUnlessGranted(OrderVoter::EDIT$order);
  326.         $form $this->createForm(OrderType::class, $order, [
  327.             'action' => $this->generateUrl('app_order_edit_process', ['order' => $order->getId()]),
  328.             'method' => 'post',
  329.             'edit_entity' => true,
  330.             'logged_user' => $this->getUser()
  331.         ]);
  332.         return $this->render('order/new.html.twig', [
  333.             'form' => $form->createView(),
  334.             'product' => $order->getProduct(),
  335.             'reloadUrl' => $this->generateUrl('app_order_new')
  336.         ]);
  337.     }
  338.     /**
  339.      * To complete data from api
  340.      *
  341.      * @Route("/dokonceni-objednavky/{hash}", name="app_order_complete")
  342.      */
  343.     public function complete(Request $request$hashOrderRepository $orderRepositoryProductRepository $productRepository): Response
  344.     {
  345.         $order $orderRepository->findOneBy(['hash' => $hash]);
  346.         $now = new \DateTime('now');
  347.         if(!$order || $now $order->getApiValidTill()){
  348.             return $this->render('errors/404.html.twig',
  349.             [
  350.                 'title' => 'Ouha! Objednávku se nepodařilo najít!',
  351.                 'description' => 'Požadovaná objednávka nebyla nalezena nebo expirovala její platnost. <br /> Pokud máte dotazy ozvěte se nám prosím na email <a href="objednavky@efsgroup.cz">objednavky@efsgroup.cz</a>.'
  352.             ]);
  353.         }
  354.         $currentPersonType $order->getPersonType();
  355.         if(is_null($currentPersonType)){
  356.             $order->setPersonType('FO');
  357.         }
  358.         if(isset($request->get('order')['product'])
  359.             && (int)$request->get('order')['product'] != $order->getProduct()->getId()
  360.         ){
  361.             // pri zmene produktu, aby se spravne renderoval formular tj. dependece atd. vlozim do objednavky novy
  362.             // produkt jiz ted a ne az skrze handlerequest
  363.             $formSentProduct $productRepository->findOneBy(['id' => $request->get('order')['product']]);
  364.             if(false == is_null($formSentProduct)){
  365.                 $order->setProduct($formSentProduct);
  366.                 // array data from request
  367.                 $requestOrder $request->get('order');
  368.                 $requestOrder['company'] = $formSentProduct->getCompany()->getId();
  369.                 $request->request->set('order'$requestOrder);
  370.             }
  371.             //$order->setCompany($formSentProduct->getCompany());
  372.         }
  373.         $form $this->createForm(OrderType::class, $order, [
  374.             'action' => $this->generateUrl('app_order_edit_process', ['order' => $order->getId()]),
  375.             'method' => 'post',
  376.             'edit_entity' => true,
  377.             'api_call' => true,
  378.             'api_complete' => true,
  379.             'logged_user' => $this->getUser()
  380.         ]);
  381.         $form->handleRequest($request);
  382.         return $this->render('order/new.html.twig', [
  383.             'form' => $form->createView(),
  384.             'completeOrder' => true,
  385.             'product' => $order->getProduct(),
  386.             'reloadUrl' => $this->generateUrl('app_order_complete', ['hash' => $hash]),
  387.         ]);
  388.     }
  389.     /**
  390.      * @Route("/order/new/process", name="app_order_new_process", methods={"POST"})
  391.      * @Route("/order/{order}/edit/process", name="app_order_edit_process", methods={"POST"})
  392.      */
  393.     public function saveProcess(
  394.         Request $request,
  395.         OrderRepository $orderRepository,
  396.         Order $order null,
  397.         GalosoftPdfGenerator $pdfGenerator,
  398.         GalosoftSigniGenerator $signiGenerator,
  399.         GalosoftSigni $signi,
  400.         EntityManagerInterface $entityManager,
  401.         UserPasswordHasherInterface $userPasswordHasher,
  402.         GalosoftMailerInterface $galosoftMailer,
  403.         UserRepository $userRepository,
  404.         GalosoftRaynet $galosoftRaynet,
  405.         GalosoftDigiSignGenerator $digiSignGenerator,
  406.         GalosoftDigiSign $digiSign,
  407.         GalosoftAdamna $galosoftAdamna
  408.     ): Response
  409.     {
  410.         $orderEnt is_null($order) ? new Order() : $order;
  411.         $orderData $request->request->get('order');
  412.         if(isset($orderData['api_call']) && $orderData['api_call'] == "1") {
  413.             $orderOriginal = clone $order;
  414.         }
  415.         $form $this->createForm(OrderType::class, $orderEnt, [
  416.             'edit_entity' => is_null($order) === false,
  417.             'allow_extra_fields' => true,
  418.             'logged_user' => $this->getUser()
  419.         ]);
  420.         // vratim do puvodni podoby disabled data
  421.         if(isset($orderData['api_call']) && $orderData['api_call'] == "1") {
  422.             $orderEnt->setUser($orderOriginal->getUser())
  423.                 ->setMerchant($orderOriginal->getMerchant())
  424.                 ->setMerchantCode($orderOriginal->getMerchantCode())
  425.                 ->setCompany($orderOriginal->getCompany());
  426.         }
  427.         $form->handleRequest($request);
  428.         if ($form->isSubmitted() && $form->isValid()) {
  429.             $genSigni = @isset($request->request->get('order', [])['generateSigni']) ? @$request->request->get('order', [])['generateSigni'] : false;
  430.             $genPdf = @isset($request->request->get('order', [])['generatePdf']) ? @$request->request->get('order', [])['generatePdf'] : false;
  431.             $genDigiSign = @isset($request->request->get('order', [])['generateDigiSign']) ? @$request->request->get('order', [])['generateDigiSign'] : false;
  432.             $pdfPreview true// vzdycky generujeme pdf pro nahled
  433.             $genRaynet $orderEnt->getProduct()->isGeneratorRaynet();
  434.             $genAdamna $orderEnt->getProduct()->isUseAdamna();
  435.             $what '';
  436.             if((boolean)$genPdf == true){
  437.                 $what .= 'p';
  438.             }
  439.             if((boolean)$genSigni == true){
  440.                 $what .= 's';
  441.             }
  442.             if((boolean)$genDigiSign == true){
  443.                 $what .= 'd';
  444.             }
  445.             if((boolean)$genRaynet == true){
  446.                 $what .= 'r';
  447.             }
  448.             if((boolean)$genAdamna == true){
  449.                 $what .= 'a';
  450.             }
  451.             $targetUrl $this->generateUrl('app_order_index');
  452.             if(isset($orderData['api_call']) && $orderData['api_call'] == "1") {
  453.                 $orderEnt->setWhatGenerated($what);
  454.                 $orderEnt->setReinvest((bool)$orderData['reinvest']);
  455.                 $targetUrl $this->generateUrl('app_order_thankyou', [
  456.                     'hash' => $orderEnt->getHash()
  457.                 ]);
  458.             }
  459.             try {
  460.                 if($orderEnt->getUser() == null){
  461.                     $alreadyStored $userRepository->findOneBy(['email' => $orderEnt->getEmail()]);
  462.                     if(is_null($alreadyStored)) {
  463.                         $user = new User();
  464.                         $user->setEmail($orderEnt->getEmail())
  465.                             ->setActive(false)
  466.                             ->setIsVerified(false)
  467.                             ->setRoles(['ROLE_CUSTOMER'])
  468.                             ->setName($orderEnt->getName())
  469.                             ->setSurname($orderEnt->getSurname())
  470.                             ->setPassword($userPasswordHasher->hashPassword(
  471.                                 $user,
  472.                                 substr(md5(rand(10000999999999)), 08)
  473.                             ));
  474.                         $entityManager->persist($user);
  475.                     }else{
  476.                         $user $alreadyStored;
  477.                     }
  478.                     $orderEnt->setUser($user);
  479.                 }
  480.                 $orderRepository->store($orderEnttrue);
  481.                 if((boolean)$pdfPreview === true && $genPdf == false && $genSigni == false && $genDigiSign == false){
  482.                     return $this->json([
  483.                         'status' => 'success',
  484.                         'previewUrl' => $this->generateUrl('app_order_preview', [
  485.                             'hash' => $order->getHash()
  486.                         ])
  487.                     ]);
  488.                 }
  489.                 if ((boolean)$genPdf === true) {
  490.                     $pdf $pdfGenerator->generatePdf($orderEnt);
  491.                     $pdfData base64_encode(file_get_contents($pdf->getUrlDel()));
  492.                     $filename str_replace(['.docx''.json'], ''$pdf->getName()). ".pdf";
  493.                     if($request->get('preview'null) == "1"){
  494.                         // jedna se o preview, vracim pdfko
  495.                         return $this->json([
  496.                             'status' => 'success',
  497.                             'previewUrl' => $this->generateUrl('app_order_preview', [
  498.                                 'hash' => $order->getHash()
  499.                             ])
  500.                         ]);
  501.                     }
  502.                     if(isset($orderData['api_call']) && $orderData['api_call'] == "1") {
  503.                         // posilame soubor na email - pouze v pripade ze se jedna o prichod z emailu - tj. api_call == 1
  504.                         $galosoftMailer->send([
  505.                             "template_id" => "d-a0b8f951e1af4fa4b73e5682fd2cc5b2",
  506.                             "from" => array(
  507.                                 "name" => "EFS",
  508.                                 "email" => "info@efsgroup.cz"
  509.                             ),
  510.                             "personalizations" => array(
  511.                                 array(
  512.                                     "dynamic_template_data" => [
  513.                                         "product" => $order->getProduct()->getName(),
  514.                                         "company" => $order->getProduct()->getCompany()->getName()
  515.                                     ],
  516.                                     "to" => array(
  517.                                         array(
  518.                                             "email" => $orderEnt->getEmail()
  519.                                         ),
  520.                                     )
  521.                                 )
  522.                             ),
  523.                             "attachments" => [
  524.                                 [
  525.                                     "content" => $pdfData,
  526.                                     "type" => $pdf->getMime(),
  527.                                     "filename" => $filename
  528.                                 ]
  529.                           ]
  530.                         ]);
  531.                     }
  532.                 }
  533.                 if ((boolean)$genSigni === true && $orderEnt->getProduct()->isGeneratorSigni()) {
  534.                     $signiContract $signiGenerator->generateSigni($orderEntfalse);
  535.                     $result $signi->signContract($signiContract);
  536.                     if($result !== false) {
  537.                         $entityManager->flush();
  538.                     }else{
  539.                         throw new \Exception("Chyba při komunikaci se Signi.com");
  540.                     }
  541.                 }
  542.                 if ((boolean)$genDigiSign === true) {
  543.                     /** @var DigiSign $digiSignContract - Vygeneruje pdf, nasledne vytvorime obalku a posleme do digisignu */
  544.                     $digiSignContract $digiSignGenerator->generateDigiSign($orderEntfalse);
  545.                     $result $digiSign->send($digiSignContract->getEnvelopeId());
  546.                     if($result !== false && $result['title'] != 'Validation Failed') {
  547.                         $entityManager->flush();
  548.                     }else{
  549.                         throw new \Exception("Chyba při komunikaci se Digisign.org (".$result['detail'].")");
  550.                     }
  551.                 }
  552.                 if ((boolean)$genRaynet === true) {
  553.                     $result $galosoftRaynet->sendContract($orderEnt);
  554.                     if($result instanceof \stdClass && $result->success != 'true'){
  555.                         throw new \Exception($result->message);
  556.                     }
  557.                 }
  558.                 if ((boolean)$genAdamna === true) {
  559.                     $result $galosoftAdamna->sendContract($orderEnt);
  560.                     if($result instanceof \stdClass && $result->status != 'true'){
  561.                         throw new \Exception($result->message);
  562.                     }
  563.                 }
  564.                 $entityManager->flush();
  565.                 return $this->json([
  566.                     'status' => 'success',
  567.                     'target_url' => $targetUrl
  568.                 ]);
  569.             } catch (\Exception $exception) {
  570.                 return $this->json([
  571.                     'status' => 'error',
  572.                     'msg' => $exception->getMessage()
  573.                 ]);
  574.             }
  575.         } else {
  576.             return $this->json([
  577.                 'status' => 'error',
  578.                 'msg' => (string)$form->getErrors(truefalse)
  579.             ]);
  580.         }
  581.     }
  582.     /**
  583.      * @Route("/dokonceni-objednavky/{hash}/dekujeme", name="app_order_thankyou", methods={"GET"})
  584.      */
  585.     public function thankyou($hashOrderRepository $orderRepository)
  586.     {
  587.         $order $orderRepository->findOneBy(['hash' => $hash]);
  588.         if(!$order){
  589.             throw new NotFoundHttpException('Objednávka nenalezena');
  590.         }
  591.         $what $order->getWhatGenerated();
  592.         return $this->render('order/thankyou.html.twig', [
  593.             'what' => $what
  594.         ]);
  595.     }
  596.     /**
  597.      * @Route("/order/{order}/delete", name="app_order_delete", methods={"POST"}, requirements={"order"="\d+"})
  598.      */
  599.     public function delete(Request $request,
  600.                         Order $order,
  601.                         OrderRepository $orderRepository,
  602.                         FileRepository $fileRepository,
  603.                         EntityManagerInterface $entityManager
  604.     ): Response
  605.     {
  606.         try {
  607.             $this->denyAccessUnlessGranted(OrderVoter::DELETE$order);
  608.             $files $order->getFiles();
  609.             foreach ($files as $file){
  610.                 $fileRepository->remove($file);
  611.             }
  612.             $orderRepository->remove($ordertrue);
  613.             $entityManager->flush();
  614.             return $this->json([
  615.                 'status' => 'success'
  616.             ]);
  617.         } catch (\Exception $e) {
  618.             return $this->json([
  619.                 'status' => 'error',
  620.                 'msg' => $e->getMessage()
  621.             ]);
  622.         }
  623.     }
  624.     /**
  625.      * @Route("/order/{order}/state/{state}/date/{datechange}/{onoff}/", name="app_change_order_state", methods={"POST", "GET"}, requirements={"order"="\d+", "state"="inprogress|paid|sent|signed|paid2|vpDelivery"})
  626.      */
  627.     public function changeState(Order $order$state$datechange$onoffEntityManagerInterface $entityManager): Response
  628.     {
  629.         try {
  630.             if($datechange == 'now'){
  631.                 $date = new \DateTime('now');
  632.             }else {
  633.                 $date \DateTime::createFromFormat('d.m.Y'$datechange);
  634.             }
  635.             if(filter_var($onoffFILTER_VALIDATE_BOOLEAN) == false){
  636.                 $date null;
  637.             }
  638.             switch ($state){
  639.                 case "inprogress":
  640.                     $order->setInProgress(filter_var($onoffFILTER_VALIDATE_BOOLEAN))
  641.                         ->setInProgressDate($date);
  642.                     break;
  643.                 case "paid":
  644.                     $order->setPaid(filter_var($onoffFILTER_VALIDATE_BOOLEAN))
  645.                         ->setPaidDate($date);
  646.                     break;
  647.                 case "paid2":
  648.                     $order->setPaid2(filter_var($onoffFILTER_VALIDATE_BOOLEAN))
  649.                         ->setPaidDate2($date);
  650.                     break;
  651.                 case "signed":
  652.                     $order->setSigned(filter_var($onoffFILTER_VALIDATE_BOOLEAN));
  653.                     $order->setSignedDate($date);
  654.                     break;
  655.                 case "vpDelivery":
  656.                     $order->setVpDelivery(filter_var($onoffFILTER_VALIDATE_BOOLEAN));
  657.                     $order->setVpDeliveryDate($date);
  658.                     break;
  659.                 case "sent":
  660.                     $order->setSent(filter_var($onoffFILTER_VALIDATE_BOOLEAN))
  661.                         ->setSentDate($date);
  662.                     break;
  663.                 default:
  664.                     throw new \Exception('Nepovoleny stav');
  665.             }
  666.             $entityManager->flush();
  667.             return $this->json([
  668.                 'status' => 'success'
  669.             ]);
  670.         } catch (\Exception $e) {
  671.             return $this->json([
  672.                 'status' => 'error',
  673.                 'msg' => $e->getMessage()
  674.             ]);
  675.         }
  676.     }
  677.     /**
  678.      * @Route("/order/{order}/{file}/delete", name="app_order_file_delete", methods={"GET"}, requirements={"file"="\d+", "order"="\d+"})
  679.      */
  680.     public function deleteFile(
  681.         Request $request,
  682.         Order $order,
  683.         File $file,
  684.         FileRepository $fileRepository
  685.     ): Response
  686.     {
  687.         try {
  688.             $this->denyAccessUnlessGranted(OrderVoter::DELETE$order);
  689.             $fileRepository->remove($filetrue);
  690.             return $this->render('order/view.html.twig', [
  691.                 'order' => $order,
  692.                 'isOrderMetalist' => $order instanceof OrderEshop
  693.             ]);
  694.         } catch (\Exception $e) {
  695.             return new JsonResponse(['statue' => 'error''msg' => $e->getMessage()]);
  696.         }
  697.     }
  698.     /**
  699.      * @Route("/order/download/digisign/{digiSign}/{output}", name="app_order_file_download_digisign", requirements={"digiSign"="\d+","output"="combined|only_log"})
  700.      * @param DigiSign $digiSign
  701.      */
  702.     public function downloadDigiSign($digiSign$outputGalosoftDigiSign $galosoftDigiSignFileRepository $fileRepository)
  703.     {
  704.         $digiSignFile $fileRepository->findOneBy(['id' => $digiSign]);
  705.         if(!$digiSignFile){
  706.             exit('Chyba aplikace');
  707.         }
  708.         $galosoftDigiSign->authenticate($digiSignFile->getProduct());
  709.         $data $galosoftDigiSign->download($digiSignFile->getEnvelopeId(), $output);
  710.         // Vytvořte odpověď prohlížeče jako PDF soubor
  711.         $response = new Response($data);
  712.         $response->headers->set('Content-Type''application/pdf');
  713.         $response->headers->set('Content-Disposition''attachment; filename="'.$digiSignFile->getName().'.pdf"'); // Nastavte název souboru
  714.         // Odpověď odeslat
  715.         return $response;
  716.     }
  717.     /**
  718.      * @Route("/order/download/signi/{signi}", name="app_order_file_download_signi", requirements={"signi"="\d+"})
  719.      * @param Signi $signi
  720.      */
  721.     public function downloadSigni(Signi $signiGalosoftSigni $galosoftSigni)
  722.     {
  723.         // TODO: Check rights or is owner
  724.         $filePath $galosoftSigni->downloadSigniContract($signi);
  725.         $pdfData file_get_contents($filePath);
  726.         $response = new Response($pdfData200, [
  727.             'Content-Length' => strlen($pdfData),
  728.             'Content-type' => 'application/pdf',
  729.             'Content-Transfer-Encoding' => 'binary'
  730.         ]);
  731.         $filename str_replace(['.docx''.json'], ''$signi->getName()). ".pdf";
  732.         $filenameFallback preg_replace(
  733.             '#^.*\.#',
  734.             md5($filename) . '.'$filename
  735.         );
  736.         $disposition $response->headers->makeDisposition(
  737.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  738.             $filename,
  739.             $filenameFallback
  740.         );
  741.         $response->headers->set('Content-Disposition'$disposition);
  742.         return $response;
  743.     }
  744.     /**
  745.      * @Route("/order/download/signicl/{signi}", name="app_order_file_download_signi_cl", requirements={"signi"="\d+"})
  746.      * @param Signi $signi
  747.      */
  748.     public function downloadSigniControlList(Signi $signiGalosoftSigni $galosoftSigni)
  749.     {
  750.         // TODO: Check rights or is owner
  751.         $filePath $galosoftSigni->downloadControlList($signi);
  752.         $pdfData file_get_contents($filePath);
  753.         $response = new Response($pdfData200, [
  754.             'Content-Length' => strlen($pdfData),
  755.             'Content-type' => 'application/pdf',
  756.             'Content-Transfer-Encoding' => 'binary'
  757.         ]);
  758.         $order $signi->getOrderEnt();
  759.         preg_match("/v\.([0-9]+)\.docx/"$signi->getName(), $parsedVersion);
  760.         $version = isset($parsedVersion[1]) ?  " v." .$parsedVersion[1] : "";
  761.         $filename "Kontrolní list digitálního podpisu ke smlouvě č." $order->getId() . $version".pdf";
  762.         $filenameFallback preg_replace(
  763.             '#^.*\.#',
  764.             md5($filename) . '.'$filename
  765.         );
  766.         $disposition $response->headers->makeDisposition(
  767.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  768.             $filename,
  769.             $filenameFallback
  770.         );
  771.         $response->headers->set('Content-Disposition'$disposition);
  772.         return $response;
  773.     }
  774.     /**
  775.      * @Route("/order/{id}/uploadchunk/", name="app_order_uploadefilechunk")
  776.      * @param Request $request
  777.      * @return string
  778.      */
  779.     public function uploadChunkFile(Request $requestOrder $orderFileModel $fileModel){
  780.         try {
  781.             $fileModel->uploadChunkFile($request$order);
  782.             return new JsonResponse(array(
  783.                 "success" => true
  784.             ));
  785.         } catch (Exception $e) {
  786.             return new JsonResponse(array(
  787.                 "success" => false,
  788.                 "error" => $e->getMessage()
  789.             ));
  790.         }
  791.     }
  792.     /**
  793.      * @Route("/order/{id}/upload/", name="app_order_uploadefile")
  794.      * @param Request $request
  795.      * @return string
  796.      */
  797.     public function uploadeFile(
  798.         Request $request,
  799.         EntityManagerInterface $em,
  800.         Order $order,
  801.         FileModel $fileModel,
  802.         GalosoftNotifications $galosoftNotifications
  803.     ){
  804.         try {
  805.             $result $fileModel->uploadOrderFile($request$order);
  806.             $simpleFile = new SimpleFile();
  807.             $simpleFile->setName($result['fileName'])
  808.                 ->setMime($result['mimeType'])
  809.                 ->setUrl($result['url'])
  810.                 ->setUrlDel($result['urlDel'])
  811.                 ->setSize($result['size'])
  812.                 ->setOrderEnt($order)
  813.                 ->setProduct($order->getProduct())
  814.                 ->setVersion('1.0')
  815.             ;
  816.             $em->persist($simpleFile);
  817.             $em->flush();
  818.             //$galosoftNotifications->manualUpload($order);
  819.             if(is_string($result['cmd'])){
  820.                 $cmd $result['cmd'];
  821.             }else{
  822.                 $cmd implode(" "$result['cmd']);
  823.             }
  824.             return $this->json([
  825.                 "success" => true,
  826.                 "origName" => $result['origName'],
  827.                 "slug" => $result['slug'],
  828.                 "name" => $result['name'],
  829.                 "type" => $result['type'],
  830.                 "cmd" => $cmd,
  831.                 "out" => $result['out']
  832.             ]);
  833.         }catch (\Exception $exception){
  834.             return $this->json([
  835.                 "success" => false,
  836.                 "error" => $exception->getMessage(),
  837.                 "preventRetry" => false
  838.             ]);
  839.         }
  840.     }
  841.     /**
  842.      * @Route("/order/download/file/{file}", name="app_order_file_download", requirements={"file"="\d+"})
  843.      * @param File $file
  844.      */
  845.     public function downloadFile(File $file)
  846.     {
  847.         $fileData file_get_contents($file->getUrlDel());
  848.         $response = new Response($fileData200, [
  849.             'Content-Length' => strlen($fileData),
  850.             'Content-type' => $file->getMime(),
  851.             'Content-Transfer-Encoding' => 'binary'
  852.         ]);
  853.         $filename $file->getName();
  854.         $filenameFallback preg_replace(
  855.             '#^.*\.#',
  856.             md5($filename) . '.'$filename
  857.         );
  858.         $disposition $response->headers->makeDisposition(
  859.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  860.             $filename,
  861.             $filenameFallback
  862.         );
  863.         $response->headers->set('Content-Disposition'$disposition);
  864.         return $response;
  865.     }
  866.     /**
  867.      * @Route("/order/download/pdf/{file}", name="app_order_file_download_file", requirements={"file"="\d+"})
  868.      * @param File $file
  869.      */
  870.     public function downloadPdf(File $fileGalosoftSigni $galosoftSigni)
  871.     {
  872.         // TODO: Check rights or is owner
  873.         $pdfData file_get_contents($file->getUrlDel());
  874.         $response = new Response($pdfData200, [
  875.             'Content-Length' => strlen($pdfData),
  876.             'Content-type' => 'application/pdf',
  877.             'Content-Transfer-Encoding' => 'binary'
  878.         ]);
  879.         $filename str_replace(['.docx''.json'], ''$file->getName()) . ".pdf";
  880.         $filenameFallback preg_replace(
  881.             '#^.*\.#',
  882.             md5($filename) . '.'$filename
  883.         );
  884.         $disposition $response->headers->makeDisposition(
  885.             ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  886.             $filename,
  887.             $filenameFallback
  888.         );
  889.         $response->headers->set('Content-Disposition'$disposition);
  890.         return $response;
  891.     }
  892. }