src/Controller/OrderController.php line 727

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Customer;
  4. use App\Entity\Office;
  5. use App\Entity\Order;
  6. use App\Entity\OrderItem;
  7. use App\Entity\Product;
  8. use App\Entity\User;
  9. use App\Repository\Customer as CustomerRepository;
  10. use App\Repository\Order as OrderRepository;
  11. use App\Service\TempFileUploader;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use Psr\Log\LoggerInterface;
  14. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  15. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  16. use Symfony\Component\HttpFoundation\JsonResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  20. use Symfony\Component\HttpKernel\KernelInterface;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  23. use Symfony\Component\Serializer\SerializerInterface;
  24. use Symfony\Contracts\Translation\TranslatorInterface;
  25. class OrderController extends AbstractController
  26. {
  27.     #[
  28.         Route(
  29.             name'api_order_sums',
  30.             path'/api/orders-sums',
  31.             methods: ['GET'],
  32.             defaults: [
  33.                 '_api_resource_class' => Order::class,
  34.                 '_api_collection_operation_name' => 'getSums',
  35.             ]
  36.         )
  37.     ]
  38.     public function sumsAction(?array $data): ?array
  39.     {
  40.         return $data;
  41.     }
  42.     #[
  43.         Route(
  44.             name'api_order_post',
  45.             path'/api/orders',
  46.             methods: ['POST'],
  47.             defaults: [
  48.                 '_api_resource_class' => Order::class,
  49.                 '_api_collection_operation_name' => 'post',
  50.             ]
  51.         )
  52.     ]
  53.     public function postAction(Order $dataLoggerInterface $loggerTranslatorInterface $translator): Order
  54.     {
  55.         $logger->info($translator->trans('New order saved.', [], 'logger'), ['data' => $data]);
  56.         return $data;
  57.     }
  58.     #[
  59.         Route(
  60.             name'api_order_put',
  61.             path'/api/orders/{id}',
  62.             requirements: ['id' => "\d+"],
  63.             methods: ['PUT'],
  64.             defaults: [
  65.                 '_api_resource_class' => Order::class,
  66.                 '_api_item_operation_name' => 'put',
  67.             ]
  68.         )
  69.     ]
  70.     public function putAction(Order $dataLoggerInterface $loggerTranslatorInterface $translator): Order
  71.     {
  72.         $logger->info($translator->trans('Order updated.', [], 'logger'), ['data' => $data]);
  73.         return $data;
  74.     }
  75.     #[
  76.         Route(
  77.             name'api_order_delete',
  78.             path'/api/orders/{id}',
  79.             requirements: ['id' => "\d+"],
  80.             methods: ['DELETE'],
  81.             defaults: [
  82.                 '_api_resource_class' => Order::class,
  83.                 '_api_item_operation_name' => 'delete',
  84.             ]
  85.         )
  86.     ]
  87.     public function deleteAction(Order $dataLoggerInterface $loggerTranslatorInterface $translator): void
  88.     {
  89.         $logger->info($translator->trans('Order deleted', [], 'logger'), ['data' => $data]);
  90.     }
  91.     #[
  92.         Route(
  93.             name'order_import',
  94.             path'/api-helper/orders/import',
  95.             methods: ['POST']
  96.         )
  97.     ]
  98.     public function importAction(
  99.         Request $request,
  100.         TempFileUploader $uploader
  101.     ): JsonResponse {
  102.         $file $request->files->get('files');
  103.         $workFile $uploader->getTargetDirectory().'/'.$uploader->upload($file);
  104.         file_put_contents($workFile$this->convert(file_get_contents($workFile)));
  105.         $cols = [];
  106.         $rows = [];
  107.         if (false !== ($handle fopen($workFile'r'))) {
  108.             $iter 0;
  109.             while (false !== ($row fgetcsv($handle1000';'))) {
  110.                 if (=== $iter) {
  111.                     $cols array_flip($row);
  112.                 } else {
  113.                     $rows[] = [
  114.                         'invoiceId' => preg_replace("/\s/i"''$row[$cols['SZLASORSZ']]),
  115.                         'invoiceType' => $row[$cols['SZTNEV']],
  116.                         'customerName' => $row[$cols['PARTNEV']],
  117.                         'invoiceDate' => str_replace('.''-'$row[$cols['SZLADATUM']]),
  118.                         'fulfillmentDeadline' => str_replace('.''-'$row[$cols['TELJDATUM']]),
  119.                         'paymentDeadline' => str_replace('.''-'$row[$cols['FIZHDATUM']]),
  120.                         'paymentMethodName' => $row[$cols['FMNEV']],
  121.                         'paymentMethodId' => intval($row[$cols['FMAZON']]),
  122.                         'net' => floatval($row[$cols['SUMNETTO']]),
  123.                         'tax' => floatval($row[$cols['SUMAFA']]),
  124.                         'gross' => floatval($row[$cols['SUMBRUTTO']]),
  125.                         'currency' => $row[$cols['DVZNEM']],
  126.                         'invoiceBookId' => intval($row[$cols['SZTAZON']]),
  127.                         'originalInvoiceId' => preg_replace("/\s/i"''$row[$cols['ESZLASORSZ']]),
  128.                         'notice' => $row[$cols['MEGJEGYZES']],
  129.                         'cashInvoice' => 'IGAZ' === $row[$cols['KPSZAMLA']],
  130.                         'partazon' => intval($row[$cols['PARTAZON']]),
  131.                     ];
  132.                 }
  133.                 ++$iter;
  134.             }
  135.             file_put_contents($uploader->getTargetDirectory().'/order-rows-tmp.json'json_encode($rows));
  136.         }
  137.         $uploader->unlink();
  138.         return $this->json([
  139.             'success' => true,
  140.             'count' => count($rows),
  141.             'remaining' => count($rows),
  142.         ]);
  143.     }
  144.     #[
  145.         Route(
  146.             name'order_import_iteration',
  147.             path'/api-helper/orders/import-iteration',
  148.             methods: ['GET']
  149.         )
  150.     ]
  151.     public function importIterationAction(
  152.         Request $request,
  153.         TempFileUploader $uploader,
  154.         EntityManagerInterface $em
  155.     ): JsonResponse {
  156.         $ordersTmpFile $uploader->getTargetDirectory().'/order-rows-tmp.json';
  157.         $rows json_decode(file_get_contents($ordersTmpFile), true);
  158.         $batch 60;
  159.         $iter 0;
  160.         $orderRepo $em->getRepository(Order::class);
  161.         $customerRepo $em->getRepository(Customer::class);
  162.         $userRepo $em->getRepository(User::class);
  163.         $selectedOfficeid $request->get('office');
  164.         $defaultOffice $em
  165.             ->getRepository(Office::class)
  166.             ->find($selectedOfficeid);
  167.         /** @var User $authUser */
  168.         if (!$defaultOffice && ($authUser $this->getUser())) {
  169.             $defaultOffice $authUser->getOffice();
  170.         }
  171.         while ($batch && !empty($rows)) {
  172.             ++$iter;
  173.             --$batch;
  174.             $row array_shift($rows);
  175.             $user false;
  176.             $userMatches = [];
  177.             if (=== preg_match('~^([0-9]+)([H|T|B|I])\s([\-0-9]+)~'$row['notice'], $userMatches)) {
  178.                 $user $userRepo->find($userMatches[1]);
  179.             }
  180.             $office $defaultOffice;
  181.             if ($user) {
  182.                 $office $user->getOffice();
  183.             }
  184.             $finder = ['office' => $office->getId()];
  185.             $order false;
  186.             if ($row['invoiceId']) {
  187.                 // we can find exact order
  188.                 $order $orderRepo->findOneBy($finder + ['invoiceId' => $row['invoiceId']]);
  189.                 if ($order) {
  190.                     // order exists, skip
  191.                     continue;
  192.                 }
  193.             }
  194.             $order = new Order();
  195.             if ($user) {
  196.                 $order->setUser($user);
  197.             }
  198.             if (!empty($userMatches)) {
  199.                 $order->setSaleType($userMatches[2]);
  200.             }
  201.             /** @var Customer $customer */
  202.             $customer false;
  203.             if ($row['partazon']) {
  204.                 // we have partazon, maybe we can find exact customer
  205.                 $customer $customerRepo->findOneBy($finder + ['partazon' => $row['partazon']]);
  206.             }
  207.             if (!isset($customer) || !$customer) {
  208.                 // try to find by name
  209.                 $customer $customerRepo->findOneBy($finder + ['name' => $row['customerName']]);
  210.             }
  211.             if ($customer) {
  212.                 $order->setCustomer($customer);
  213.                 if (isset($userMatches[3])) {
  214.                     $customer->setLoyaltyPoints($customer->getLoyaltyPoints() + intval($userMatches[3]));
  215.                     $em->persist($customer);
  216.                 }
  217.             }
  218.             if (!empty($row['originalInvoiceId'])) {
  219.                 $order->setOriginalInvoiceId($row['originalInvoiceId']); // ESZLASORSZ
  220.                 $qb $em->createQueryBuilder();
  221.                 $query $qb->select('o')
  222.                             ->from(Order::class, 'o')
  223.                             ->where(
  224.                                 $qb->expr()->andX(
  225.                                     $qb->expr()->eq('o.office'$office->getId()),
  226.                                     $qb->expr()->like('o.invoiceId'$qb->expr()->literal($row['originalInvoiceId']))
  227.                                 )
  228.                             )
  229.                             ->getQuery();
  230.                 $originalOrder $query->getSingleResult();
  231.                 if ($originalOrder) {
  232.                     $order->setOriginalOrder($originalOrder);
  233.                 }
  234.             }
  235.             $order
  236.                 ->setOffice($office)
  237.                 ->setInvoiceId($row['invoiceId']) // SZLASORSZ
  238.                 ->setInvoiceType($row['invoiceType']) // SZTNEV
  239.                 ->setCustomerName($row['customerName']) // PARTNEV
  240.                 ->setInvoiceDate(new \DateTime($row['invoiceDate'])) // SZLADATUM
  241.                 ->setFulfillmentDeadline(new \DateTime($row['fulfillmentDeadline'])) // TELJDATUM
  242.                 ->setPaymentDeadline(new \DateTime($row['paymentDeadline'])) // FIZHDATUM
  243.                 ->setPaymentMethodName($row['paymentMethodName']) // FMNEV
  244.                 ->setPaymentMethodId($row['paymentMethodId']) // FMAZON
  245.                 ->setNet($row['net']) // SUMNETTO
  246.                 ->setTax($row['tax']) // SUMAFA
  247.                 ->setGross($row['gross']) // SUMBRUTTO
  248.                 ->setCurrency($row['currency']) // DVZNEM
  249.                 ->setInvoiceBookId($row['invoiceBookId']) // SZTAZON
  250.                 ->setNotice($row['notice']) // MEGJEGYZES
  251.                 ->setCashInvoice($row['cashInvoice']) // KPSZAMLA
  252.             ;
  253.             $em->persist($order);
  254.             $em->flush();
  255.         }
  256.         if (!empty($rows)) {
  257.             file_put_contents($ordersTmpFilejson_encode($rows));
  258.         } else {
  259.             unlink($ordersTmpFile);
  260.         }
  261.         return $this->json([
  262.             'success' => true,
  263.             'processed' => $iter,
  264.             'remaining' => count($rows),
  265.         ]);
  266.     }
  267.     #[
  268.         Route(
  269.             name'order_import_all',
  270.             path'/api-helper/orders/import-all',
  271.             methods: ['POST']
  272.         )
  273.     ]
  274.     public function importAllAction(
  275.         Request $request,
  276.         TempFileUploader $uploader
  277.     ): JsonResponse {
  278.         $files $request->files->get('files');
  279.         $workFileNames $uploader->upload($files);
  280.         $ordersFile '';
  281.         $itemsFile '';
  282.         foreach ($workFileNames as $fileName) {
  283.             $workFile $uploader->getTargetDirectory().'/'.$fileName;
  284.             file_put_contents($workFile$this->convert(file_get_contents($workFile)));
  285.             if (false !== ($handle fopen($workFile'r'))) {
  286.                 if (false !== ($row fgetcsv($handle1000';'))) {
  287.                     $cols array_flip($row);
  288.                     if (isset($cols['CIKKAZON'])) {
  289.                         $itemsFile $workFile;
  290.                     } else {
  291.                         $ordersFile $workFile;
  292.                     }
  293.                 }
  294.                 fclose($handle);
  295.             }
  296.         }
  297.         $cols = [];
  298.         $rows = [];
  299.         if (false !== ($handle fopen($ordersFile'r'))) {
  300.             $iter 0;
  301.             while (false !== ($row fgetcsv($handle1000';'))) {
  302.                 if (=== $iter) {
  303.                     $cols array_flip($row);
  304.                 } else {
  305.                     $rows[preg_replace("/\s/i"''$row[$cols['SZLASORSZ']])] = [
  306.                         'invoiceId' => preg_replace("/\s/i"''$row[$cols['SZLASORSZ']]),
  307.                         'invoiceType' => $row[$cols['SZTNEV']],
  308.                         'customerName' => $row[$cols['PARTNEV']],
  309.                         'invoiceDate' => str_replace('.''-'$row[$cols['SZLADATUM']]),
  310.                         'fulfillmentDeadline' => str_replace('.''-'$row[$cols['TELJDATUM']]),
  311.                         'paymentDeadline' => str_replace('.''-'$row[$cols['FIZHDATUM']]),
  312.                         'paymentMethodName' => $row[$cols['FMNEV']],
  313.                         'paymentMethodId' => intval($row[$cols['FMAZON']]),
  314.                         'net' => floatval($row[$cols['SUMNETTO']]),
  315.                         'tax' => floatval($row[$cols['SUMAFA']]),
  316.                         'gross' => floatval($row[$cols['SUMBRUTTO']]),
  317.                         'currency' => $row[$cols['DVZNEM']],
  318.                         'invoiceBookId' => intval($row[$cols['SZTAZON']]),
  319.                         'originalInvoiceId' => preg_replace("/\s/i"''$row[$cols['ESZLASORSZ']]),
  320.                         'notice' => $row[$cols['MEGJEGYZES']],
  321.                         'cashInvoice' => 'IGAZ' === $row[$cols['KPSZAMLA']],
  322.                         'partazon' => intval($row[$cols['PARTAZON']]),
  323.                     ];
  324.                 }
  325.                 ++$iter;
  326.             }
  327.             fclose($handle);
  328.         }
  329.         if (!empty($rows) && false !== ($handle fopen($itemsFile'r'))) {
  330.             $iter 0;
  331.             while (false !== ($row fgetcsv($handle1000';'))) {
  332.                 if (=== $iter) {
  333.                     $cols array_flip($row);
  334.                 } else {
  335.                     $invoiceId preg_replace("/\s/i"''$row[$cols['SZLASORSZ']]);
  336.                     if (isset($rows[$invoiceId])) {
  337.                         if (!isset($rows[$invoiceId]['items'])) {
  338.                             $rows[$invoiceId]['items'] = [];
  339.                         }
  340.                         $rows[$invoiceId]['items'][] = [
  341.                             'sku' => $row[$cols['SZTETCSZAM']],
  342.                             'cikkazon' => $row[$cols['CIKKAZON']],
  343.                             'name' => $row[$cols['SZTETNEV']],
  344.                             'quantity' => intval($row[$cols['MENNY']]),
  345.                             'unit' => $row[$cols['MEEGYSEG']],
  346.                             'unitPrice' => $row[$cols['EGYSEGAR']],
  347.                             'price' => intval($row[$cols['NEAR']]),
  348.                             'grossPrice' => intval($row[$cols['BRAR']]),
  349.                             'currency' => $row[$cols['DVZNEM']],
  350.                             'taxRate' => intval($row[$cols['AFASZLK']]),
  351.                             'orderItemId' => intval($row[$cols['SZTETAZON']]),
  352.                         ];
  353.                     }
  354.                 }
  355.                 ++$iter;
  356.             }
  357.         }
  358.         if (!empty($rows)) {
  359.             file_put_contents($uploader->getTargetDirectory().'/order-rows-tmp.json'json_encode($rows));
  360.         }
  361.         $uploader->unlink();
  362.         return $this->json([
  363.             'success' => true,
  364.             'count' => count($rows),
  365.             'remaining' => count($rows),
  366.         ]);
  367.     }
  368.     #[
  369.         Route(
  370.             name'order_import_all_iteration',
  371.             path'/api-helper/orders/import-all-iteration',
  372.             methods: ['GET']
  373.         )
  374.     ]
  375.     public function importAllIterationAction(
  376.         Request $request,
  377.         TempFileUploader $uploader,
  378.         EntityManagerInterface $em
  379.     ): JsonResponse {
  380.         $ordersTmpFile $uploader->getTargetDirectory().'/order-rows-tmp.json';
  381.         $rows json_decode(file_get_contents($ordersTmpFile), true);
  382.         $batch count($rows) < 20 count($rows) : 20;
  383.         $iter 0;
  384.         $orderRepo $em->getRepository(Order::class);
  385.         /** @var CustomerRepository $customerRepo */
  386.         $customerRepo $em->getRepository(Customer::class);
  387.         $userRepo $em->getRepository(User::class);
  388.         $orderItemRepo $em->getRepository(OrderItem::class);
  389.         $productRepo $em->getRepository(Product::class);
  390.         $selectedOfficeid $request->get('office');
  391.         $defaultOffice $em
  392.             ->getRepository(Office::class)
  393.             ->find($selectedOfficeid);
  394.         /** @var User $authUser */
  395.         if (!$defaultOffice && ($authUser $this->getUser())) {
  396.             $defaultOffice $authUser->getOffice();
  397.         }
  398.         $missingCustomers = [];
  399.         while ($batch && !empty($rows)) {
  400.             ++$iter;
  401.             --$batch;
  402.             $row array_shift($rows);
  403.             $user false;
  404.             $userMatches = [];
  405.             if (=== preg_match('~([0-9]+)[\s]*([H|T|B|I])[\s]*([\-0-9]+)?~'$row['notice'], $userMatches)) {
  406.                 $user $userRepo->find(intval($userMatches[1]));
  407.             }
  408.             $office $defaultOffice;
  409.             if ($user) {
  410.                 $office $user->getOffice() ?? $defaultOffice;
  411.             }
  412.             $finder = ['office' => $office->getId()];
  413.             $order false;
  414.             if ($row['invoiceId']) {
  415.                 // we can find exact order
  416.                 $order $orderRepo->findOneBy($finder + ['invoiceId' => $row['invoiceId']]);
  417.                 if ($order) {
  418.                     // order exists, skip
  419.                     continue;
  420.                 }
  421.             }
  422.             $order = new Order();
  423.             if ($user) {
  424.                 $order->setUser($user);
  425.             }
  426.             if (!empty($userMatches)) {
  427.                 $order->setSaleType($userMatches[2]);
  428.             }
  429.             $customer false;
  430.             if ($row['partazon']) {
  431.                 // we have partazon, maybe we can find exact customer
  432.                 $customer $customerRepo->findOneBy($finder + ['partazon' => $row['partazon']]);
  433.             }
  434.             if (!$customer && !== $office->getId()) {
  435.                 // if not in office #1, look for customer in all office
  436.                 $customer $customerRepo->findNotInFirstOffice($row['partazon']);
  437.             }
  438.             // if (!isset($customer) || !$customer) {
  439.             //     // try to find by name
  440.             //     $customer = $customerRepo->findOneBy($finder + ['name' => $row['customerName']]);
  441.             // }
  442.             // if (!$customer && $office->getId() > 2) {
  443.             //     // try to small offices' customers in office with id 2
  444.             //     $customer = $customerRepo->findOneBy(['office' => 2, 'partazon' => $row['partazon']]);
  445.             //     if (!$customer) {
  446.             //         // try to find by name
  447.             //         $customer = $customerRepo->findOneBy(['office' => 2, 'name' => $row['customerName']]);
  448.             //     }
  449.             // }
  450.             if (!$customer) {
  451.                 // if there's no customer, who is ordered? :)
  452.                 $missingCustomers[] = [
  453.                     'invoiceId' => $row['invoiceId'],
  454.                     'partazon' => $row['partazon'] ?? '',
  455.                     'name' => $row['customerName'],
  456.                 ];
  457.                 continue;
  458.             }
  459.             if (isset($userMatches[3])) {
  460.                 $customer->setLoyaltyPoints($customer->getLoyaltyPoints() + intval($userMatches[3]));
  461.                 $em->persist($customer);
  462.             }
  463.             if ($customer->getOffice()->getId() !== $office->getId()) {
  464.                 $customer->setOffice($office);
  465.                 $em->persist($customer);
  466.             }
  467.             if ($user && $customer) {
  468.                 $customer->setUser($user);
  469.                 $em->persist($customer);
  470.             }
  471.             if ($customer) {
  472.                 $order->setCustomer($customer);
  473.             }
  474.             if (!empty($row['originalInvoiceId'])) {
  475.                 $order->setOriginalInvoiceId($row['originalInvoiceId']); // ESZLASORSZ
  476.                 $qb $em->createQueryBuilder();
  477.                 $query $qb->select('o')
  478.                             ->from(Order::class, 'o')
  479.                             ->where(
  480.                                 $qb->expr()->andX(
  481.                                     $qb->expr()->eq('o.office'$office->getId()),
  482.                                     $qb->expr()->like('o.invoiceId'$qb->expr()->literal($row['originalInvoiceId']))
  483.                                 )
  484.                             )
  485.                             ->getQuery();
  486.                 $originalOrder $query->getOneOrNullResult();
  487.                 if ($originalOrder) {
  488.                     $order->setOriginalOrder($originalOrder);
  489.                 }
  490.             }
  491.             $order
  492.                 ->setOffice($office)
  493.                 ->setInvoiceId($row['invoiceId']) // SZLASORSZ
  494.                 ->setInvoiceType($row['invoiceType']) // SZTNEV
  495.                 ->setCustomerName($row['customerName']) // PARTNEV
  496.                 ->setInvoiceDate(new \DateTime($row['invoiceDate'])) // SZLADATUM
  497.                 ->setFulfillmentDeadline(new \DateTime($row['fulfillmentDeadline'])) // TELJDATUM
  498.                 ->setPaymentDeadline(new \DateTime($row['paymentDeadline'])) // FIZHDATUM
  499.                 ->setPaymentMethodName($row['paymentMethodName']) // FMNEV
  500.                 ->setPaymentMethodId($row['paymentMethodId']) // FMAZON
  501.                 ->setNet($row['net']) // SUMNETTO
  502.                 ->setTax($row['tax']) // SUMAFA
  503.                 ->setGross($row['gross']) // SUMBRUTTO
  504.                 ->setCurrency($row['currency']) // DVZNEM
  505.                 ->setInvoiceBookId($row['invoiceBookId']) // SZTAZON
  506.                 ->setNotice($row['notice']) // MEGJEGYZES
  507.                 ->setCashInvoice($row['cashInvoice']) // KPSZAMLA
  508.             ;
  509.             $em->persist($order);
  510.             // ITEMS ITERATION
  511.             $loyaltyPoints 0;
  512.             foreach ($row['items'] as $item) {
  513.                 $orderItem $orderItemRepo->findOneBy([
  514.                     'orderItemId' => $item['orderItemId'],
  515.                     'order' => $order,
  516.                 ]);
  517.                 if ($orderItem) {
  518.                     // item already processed
  519.                     continue;
  520.                 }
  521.                 $orderItem = new OrderItem();
  522.                 $orderItem
  523.                     ->setOrder($order)
  524.                     ->setSku($item['sku'])
  525.                     ->setCikkazon($item['cikkazon'])
  526.                     ->setName($item['name'])
  527.                     ->setQuantity($item['quantity'])
  528.                     ->setUnit($item['unit'])
  529.                     ->setUnitPrice($item['unitPrice'])
  530.                     ->setPrice($item['price'])
  531.                     ->setGrossPrice($item['grossPrice'])
  532.                     ->setCurrency($item['currency'])
  533.                     ->setTaxRate($item['taxRate'])
  534.                     ->setOrderItemId($item['orderItemId'])
  535.                 ;
  536.                 $em->persist($orderItem);
  537.                 // calculate loyalty points
  538.                 $loyaltySkuExcludes = [
  539.                     // '123-284', // catalogue
  540.                     '002-1'// shipping
  541.                     '001-8'// shipping
  542.                     '123-20'// shipping
  543.                 ];
  544.                 if (!in_array($orderItem->getSku(), $loyaltySkuExcludes)) {
  545.                     $loyaltyPoints += 0.005 $orderItem->getGrossPrice();
  546.                 }
  547.                 // have to substract quantity from product stock
  548.                 $product $productRepo->findOneBy(['sku' => $item['sku']]);
  549.                 if ($product) {
  550.                     $product->setStock($product->getStock() - $item['quantity']);
  551.                     $em->persist($product);
  552.                 }
  553.             }
  554.             if (!= $loyaltyPoints) {
  555.                 $sign intval($loyaltyPoints abs($loyaltyPoints));
  556.             } else {
  557.                 $sign 1;
  558.             }
  559.             $loyaltyPoints $sign intval(ceil(abs($loyaltyPoints))) + $customer->getLoyaltyPoints();
  560.             $customer->setLoyaltyPoints($loyaltyPoints $loyaltyPoints);
  561.             $em->persist($customer);
  562.             if (=== $iter 10) {
  563.                 $em->flush();
  564.             }
  565.         }
  566.         $em->flush();
  567.         if (!empty($rows)) {
  568.             file_put_contents($ordersTmpFilejson_encode($rows));
  569.         } else {
  570.             unlink($ordersTmpFile);
  571.         }
  572.         return $this->json([
  573.             'success' => true,
  574.             'processed' => $iter,
  575.             'remaining' => count($rows),
  576.             'missingCustomers' => $missingCustomers,
  577.         ]);
  578.     }
  579.     protected function convert(array|string $strstring $to 'UTF-8'string|array|null $from 'ISO-8859-2'): array|string|false
  580.     {
  581.         return mb_convert_encoding($str$to$from);
  582.     }
  583.     #[
  584.         Route(
  585.             name'order_get_income',
  586.             path'/api-helper/orders/get-income',
  587.             methods: ['GET']
  588.         )
  589.     ]
  590.     public function getIncome(
  591.         Request $request,
  592.         EntityManagerInterface $em,
  593.         AuthorizationCheckerInterface $authChecker
  594.     ): JsonResponse {
  595.         /** @var OrderRepository $orderRepo */
  596.         $orderRepo $em->getRepository(Order::class);
  597.         /** @var User $user */
  598.         $user $this->getUser();
  599.         if (!$authChecker->isGranted('ROLE_CLERK')) {
  600.             $userId $user->getId();
  601.         } else {
  602.             $userId $request->get('user_id''');
  603.         }
  604.         $iDateParam $request->get('invoiceDate', []);
  605.         return $this->json($orderRepo->findIncome(
  606.             $request->get('office_id'$user->getOffice()->getId()),
  607.             isset($iDateParam['after']) ? $iDateParam['after'] : '',
  608.             isset($iDateParam['before']) ? $iDateParam['before'] : '',
  609.             $userId,
  610.             $request->get('customer_id'''),
  611.             $request->get('saleType''')
  612.         ));
  613.     }
  614.     #[
  615.         Route(
  616.             name'order_get_income_by_users',
  617.             path'/api-helper/orders/get-income-by-users',
  618.             methods: ['GET']
  619.         )
  620.     ]
  621.     public function getIncomeByUsers(
  622.         Request $request,
  623.         EntityManagerInterface $em,
  624.         AuthorizationCheckerInterface $authChecker
  625.     ): JsonResponse {
  626.         /** @var OrderRepository $orderRepo */
  627.         $orderRepo $em->getRepository(Order::class);
  628.         /** @var User $user */
  629.         $user $this->getUser();
  630.         if (!$authChecker->isGranted('ROLE_CLERK')) {
  631.             $userId $user->getId();
  632.         } else {
  633.             $userId $request->get('user_id''');
  634.         }
  635.         $iDateParam $request->get('invoiceDate', []);
  636.         return $this->json($orderRepo->findIncomeByUsers(
  637.             $request->get('office_id'$user->getOffice()->getId()),
  638.             isset($iDateParam['after']) ? $iDateParam['after'] : '',
  639.             isset($iDateParam['before']) ? $iDateParam['before'] : '',
  640.             $userId,
  641.             $request->get('customer_id'''),
  642.             $request->get('saleType''')
  643.         ));
  644.     }
  645.     #[
  646.         Route(
  647.             name'order_get_income_by_customers',
  648.             path'/api-helper/orders/get-income-by-customers',
  649.             methods: ['GET']
  650.         )
  651.     ]
  652.     public function getIncomeByCustomers(
  653.         Request $request,
  654.         EntityManagerInterface $em,
  655.         AuthorizationCheckerInterface $authChecker,
  656.         SerializerInterface $serializer
  657.     ): JsonResponse {
  658.         /** @var OrderRepository $orderRepo */
  659.         $orderRepo $em->getRepository(Order::class);
  660.         /** @var User $user */
  661.         $user $this->getUser();
  662.         if (!$authChecker->isGranted('ROLE_CLERK')) {
  663.             $userId $user->getId();
  664.         } else {
  665.             $userId $request->get('user_id''');
  666.         }
  667.         $iDateParam $request->get('invoiceDate', []);
  668.         $page $request->get('page'1);
  669.         $itemsPerPage $request->get('itemsPerPage'40);
  670.         $ordering $request->get('order', []);
  671.         $data $serializer->serialize($orderRepo->findIncomeByCustomers(
  672.             $request->get('office_id'$user->getOffice()->getId()),
  673.             isset($iDateParam['after']) ? $iDateParam['after'] : '',
  674.             isset($iDateParam['before']) ? $iDateParam['before'] : '',
  675.             $userId,
  676.             $request->get('customer_id'''),
  677.             $request->get('saleType'''),
  678.             $page,
  679.             $itemsPerPage,
  680.             $ordering
  681.         ), 'json', ['groups' => ['order:getIncomeByCustomers']]);
  682.         return new JsonResponse($data200, [], true);
  683.     }
  684.     #[
  685.         Route(
  686.             name'order_income_by_customers_export_iterate',
  687.             path'/api/orders/income-by-customers-export-iterate',
  688.             methods: ['GET']
  689.         )
  690.     ]
  691.     public function incomeByCustomersExportIterateAction(
  692.         Request $request,
  693.         KernelInterface $kernel,
  694.         EntityManagerInterface $em,
  695.         AuthorizationCheckerInterface $authChecker
  696.     ): JsonResponse {
  697.         ini_set('max_execution_time'300); // 5 minutes
  698.         $tmpFileDir $kernel->getProjectDir().'/var/tmp-files/';
  699.         if (!is_dir($tmpFileDir)) {
  700.             mkdir($tmpFileDir0777true);
  701.         }
  702.         /** @var User $user */
  703.         $user $this->getUser();
  704.         if (!$authChecker->isGranted('ROLE_CLERK')) {
  705.             $userId $user->getId();
  706.         } else {
  707.             $userId $request->get('user_id''');
  708.         }
  709.         $iDateParam $request->get('invoiceDate', []);
  710.         $ordering $request->get('order', []);
  711.         $page $request->get('page'1);
  712.         $itemsPerPage intval($request->get('itemsPerPage'500));
  713.         $officeId $request->get('office_id'$user->getOffice()->getId());
  714.         $fileName $request->get('fileName'md5(uniqid().json_encode([
  715.             $officeId,
  716.             isset($iDateParam['after']) ? $iDateParam['after'] : '',
  717.             isset($iDateParam['before']) ? $iDateParam['before'] : '',
  718.             $userId,
  719.             $request->get('customer_id'''),
  720.             $request->get('saleType'''),
  721.             $page,
  722.             $itemsPerPage,
  723.             $ordering,
  724.         ])));
  725.         $tmpFile "{$tmpFileDir}/{$fileName}.csv";
  726.         if (!file_exists($tmpFile)) {
  727.             file_put_contents(
  728.                 $tmpFile,
  729.                 $this->buildRow(['id''partazon''name''phone''isActive''zip''city''address''sellerId''sellerName''ordersCount''cartNetValue''giftNetValue''totalNetValue''cartGrossValue''giftGrossValue''totalGrossValue'])
  730.             );
  731.         }
  732.         /** @var OrderRepository $orderRepo */
  733.         $orderRepo $em->getRepository(Order::class);
  734.         $data $orderRepo->findIncomeByCustomers(
  735.             $officeId,
  736.             isset($iDateParam['after']) ? $iDateParam['after'] : '',
  737.             isset($iDateParam['before']) ? $iDateParam['before'] : '',
  738.             $userId,
  739.             $request->get('customer_id'''),
  740.             $request->get('saleType'''),
  741.             $page,
  742.             $itemsPerPage,
  743.             $ordering
  744.         );
  745.         /** @var Customer $item */
  746.         foreach ($data['items'] as $item) {
  747.             file_put_contents(
  748.                 $tmpFile,
  749.                 $this->buildRow([
  750.                     $item['id'],
  751.                     $item['customer']->getPartazon(),
  752.                     $item['customer']->getName(),
  753.                     $item['customer']->getPhone(),
  754.                     $item['customer']->getIsActive() ? '1' '0',
  755.                     $item['customer']->getZip(),
  756.                     $item['customer']->getCity(),
  757.                     $item['customer']->getAddress(),
  758.                     $item['customer']->getUser() ? $item['customer']->getUser()->getId() : '',
  759.                     $item['customer']->getUser() ? $item['customer']->getUser()->getName() : '',
  760.                     $item['ordersCount'],
  761.                     $item['sumNet'] + ($item['giftNet'] ?? 0),
  762.                     ($item['giftNet'] ?? 0),
  763.                     $item['sumNet'],
  764.                     $item['sumGross'] + ($item['giftGross'] ?? 0),
  765.                     ($item['giftGross'] ?? 0),
  766.                     $item['sumGross'],
  767.                 ]),
  768.                 FILE_APPEND
  769.             );
  770.         }
  771.         return $this->json([
  772.             'page' => ($page 1),
  773.             'itemsPerPage' => $itemsPerPage,
  774.             'fileName' => $fileName,
  775.             'remaining' => max($data['totalItems'] - $page $itemsPerPage /*- count($data['items'])*/0),
  776.         ]);
  777.     }
  778.     #[
  779.         Route(
  780.             name'order_income_by_customers_export',
  781.             path'/api/orders/income-by-customers-export',
  782.             methods: ['GET']
  783.         )
  784.     ]
  785.     public function incomeByCustomersExportAction(
  786.         Request $request,
  787.         KernelInterface $kernel
  788.     ): BinaryFileResponse {
  789.         $tmpFileDir $kernel->getProjectDir().'/var/tmp-files/';
  790.         $fileName $request->get('fileName');
  791.         $tmpFile "{$tmpFileDir}/{$fileName}.csv";
  792.         $response = new BinaryFileResponse($tmpFile);
  793.         $response->headers->set('Content-Type''text/csv');
  794.         $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT'orders-income-by-customers.csv')
  795.                  ->deleteFileAfterSend();
  796.         return $response;
  797.     }
  798.     protected function buildRow(array $rowstring $delimiter ','string $enclosure '"'): string|false
  799.     {
  800.         // output up to 5MB is kept in memory, if it becomes bigger
  801.         // it will automatically be written to a temporary file
  802.         $csv fopen('php://temp/maxmemory:'.(1024 1024), 'r+');
  803.         fputcsv($csv$row$delimiter$enclosure);
  804.         rewind($csv);
  805.         return stream_get_contents($csv);
  806.     }
  807. }