src/Controller/DefaultController.php line 48

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\HomeSlider;
  4. use App\Entity\Order;
  5. use App\Entity\OrderProduct;
  6. use App\Entity\Product;
  7. use App\Repository\HomePageRepository;
  8. use App\Repository\HomeSliderRepository;
  9. use App\Repository\OrderRepository;
  10. use App\Repository\ProductRepository;
  11. use App\Repository\SonataUserUserRepository;
  12. use App\Services\ApiConsumer;
  13. use App\Twig\Extension\MediaExtension;
  14. use App\Utils\EAS256CBC;
  15. use App\Utils\SeoUtils;
  16. use DateTime;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. use PhpOffice\PhpSpreadsheet\IOFactory;
  19. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  20. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  21. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  22. use Symfony\Component\HttpFoundation\JsonResponse;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use Symfony\Component\HttpFoundation\Response;
  25. use Symfony\Component\HttpFoundation\StreamedResponse;
  26. use Symfony\Component\Routing\Annotation\Route;
  27. class DefaultController extends AbstractController
  28. {
  29.     protected readonly SeoUtils $seoUtils;
  30.     protected ApiConsumer            $apiConsumer;
  31.     protected EntityManagerInterface $em;
  32.     private static string            $default_task '5178';
  33.     public function __construct(SeoUtils $seoUtilsApiConsumer $apiConsumerEntityManagerInterface $em)
  34.     {
  35.         $this->seoUtils    $seoUtils;
  36.         $this->apiConsumer $apiConsumer;
  37.         $this->em          $em;
  38.     }
  39.     /**
  40.      * @Route("/{reactRouting}", name="homepage", requirements={"reactRouting"=".+"}, defaults={"reactRouting": null}, priority=-10)
  41.      */
  42.     public function indexAction(Request $request): Response
  43.     {
  44.         return $this->render('default/index.html.twig');
  45.     }
  46.     /**
  47.      * @Route("/data/Initial.json", name="data_home2")
  48.      */
  49.     public function dataHomeAction(Request $requestHomePageRepository $homePageRepositoryMediaExtension $media): \Symfony\Component\HttpFoundation\JsonResponse
  50.     {
  51.         $page $homePageRepository->findOneBy([]);
  52.         $data[] = [
  53.             'bannerPrimary' => [
  54.                 'id'         => 1,
  55.                 'imgDesktop' => $media->media($page->getBannerPrimaryDesktop()),
  56.                 'imgMobile'  => $media->media($page->getBannerPrimaryMobile()),
  57.                 'link'       => $page->getBannerPrimaryLink(),
  58.             ],
  59.             'bannerSecondary' => [
  60.                 'id'         => 2,
  61.                 'imgDesktop' => $media->media($page->getBannerSecondaryDesktop()),
  62.                 'imgMobile'  => $media->media($page->getBannerSecondaryMobile()),
  63.                 'link'       => $page->getBannerSecondaryLink(),
  64.             ],
  65.             'bannerTertiary' => [
  66.                 'id'         => 3,
  67.                 'imgDesktop' => $media->media($page->getBannerTertiaryDesktop()),
  68.                 'imgMobile'  => $media->media($page->getBannerTertiaryMobile()),
  69.                 'link'       => $page->getBannerTertiaryLink(),
  70.             ],
  71.             'slides' => array_values(array_map(
  72.                                          fn(HomeSlider $item) => [
  73.                                              'id'        => $item->getId(),
  74.                                              'imgDesktop' => $media->media($item->getSlideDesktop()),
  75.                                              'imgMobile'  => $media->media($item->getBannerMobile()),
  76.                                              'link'       => $item->getLink(),
  77.                                          ],
  78.                                          array_filter(iterator_to_array($page->getSliders()), fn($item) => $item->isPublic())
  79.                                      )),
  80.         ];
  81.         return $this->json($data);
  82.     }
  83.     /**
  84.      * @Route("/data/batch.json", name="data_batch")
  85.      * @Route("/data/batch_json", name="data_batch2")
  86.      */
  87.     public function dataBatchAction(Request $requestOrderRepository $orderRepository): \Symfony\Component\HttpFoundation\JsonResponse
  88.     {
  89.         $id $request->query->get('id');
  90.         $session $request->getSession();
  91.         $order $orderRepository->findOneBy(['ws_id' => (int)$id]);
  92.         $tracking $this->apiConsumer->getImportsTasksTracking($order->getId(), $order->getWsId(), $session->get('user_password_hash'));
  93.         $data[] =
  94.             [
  95.                 "id"              => $order->getId(),
  96.                 "idWeb"           => $order->getId(),
  97.                 "batchId"         => $order->getWsId(),
  98.                 "Cliente"         => '',
  99.                 "Estado"          => $tracking->estado,
  100.                 "detalleDeCarga"  => '0000',
  101.                 "FechaDeCarga"    => $tracking->start_process,
  102.                 "FechaDeProceso"  => $tracking->end_process,
  103.                 "FechaFinProceso" => $tracking->end_process,
  104.                 "detalle"         => $id,
  105.             ];
  106.         return $this->json($data);
  107.     }
  108.     /**
  109.      * @Route("/data/homeWork.json", name="data_homeWork")
  110.      * @Route("/data/homeWork_json", name="data_homeWork2")
  111.      */
  112.     public function dataHomeWorkAction(Request $request): \Symfony\Component\HttpFoundation\JsonResponse
  113.     {
  114.         $id $request->query->get('id');
  115.         $session $request->getSession();
  116.         $tasks_ws $this->getTasksFormat($request$id);
  117.         $fields = [];
  118.         foreach ($tasks_ws as $tasks_w) {
  119.             $fields[] = $this->correctWorks($tasks_wtrue);
  120.         }
  121.         $field_last array_pop($fields);
  122.         $data = [];
  123.         $data[] =
  124.             [
  125.                 "id"             => $id,
  126.                 "IdWork"         => $id,
  127.                 "name"           => '',
  128.                 "modalContent"   => "Para armar el archivo de texto, crea filas con los datos separados por tabuladores y cada registro en una nueva lĂ­nea, en el siguiente orden: " implode(", "$fields) . ' y ' $field_last,
  129.                 "exampleFile"    => $id $this->generateUrl('download_example', ['task_id' => $id]) : '',
  130.                 "exampleFileXls" => $id $this->generateUrl('download_example_xls', ['task_id' => $id]) : '',
  131.                 "example"        => [],
  132.             ];
  133.         return $this->json($data);
  134.     }
  135.     private function correctWorks($word$ucfirst false): string
  136.     {
  137.         $result = match ($word) {
  138.             'lot' => 'lote',
  139.             'hold' => 'Tratamiento',
  140.             default => $word,
  141.         };
  142.         return $ucfirst ucfirst($result) : $result;
  143.     }
  144.     /**
  145.      * @Route("/data/fileTranfer.json", name="data_file_tranfer")
  146.      * @Route("/data/fileTranfer_json", name="data_file_tranfer2")
  147.      */
  148.     public function dataFileTransferAction(Request $requestOrderRepository $orderRepository): \Symfony\Component\HttpFoundation\JsonResponse
  149.     {
  150.         $id $request->query->get('id');
  151.         $session $request->getSession();
  152.         $works_ws  $this->apiConsumer->getImportsTasksList($id$session->get('user_password_hash'));
  153.         $orders_ws $this->apiConsumer->getPedidoSeguimiento($id$session->get('user_password_hash'));
  154.         $orders  = [];
  155.         $statuss = [];
  156.         foreach ($orders_ws as $order_ws) {
  157.             $order $orderRepository->findOneBy(['ws_id' => $order_ws->ob_oid]);
  158.             if ($order != null) {
  159.                 $data_merge = [
  160.                     'web_id'    => $order->getId(),
  161.                     'create_at' => $order->getCreateAt()->format('Y-m-d H:i:s'),
  162.                     'file'      => $order->getFileName() ?? '',
  163.                     'user'      => $order->getUser()->getUsername(),
  164.                     'client'    => $order->getUser()->getUsername(),
  165.                 ];
  166.                 $orders[]   = array_merge((array)$order_ws$data_merge);
  167.                 $statuss[]  = [
  168.                     'id'   => $order->getId(),
  169.                     'name' => $order_ws->Estado
  170.                 ];
  171.             }
  172.         }
  173.         $works = [];
  174.         foreach ($works_ws as $work) {
  175.             $works[] = [
  176.                 'id'     => $work->Id_Tarea,
  177.                 'IdWork' => $work->Id_Tarea,
  178.                 'name'   => $work->Descripcion,
  179.             ];
  180.         }
  181.         $order_list = [];
  182.         foreach ($orders as $order) {
  183.             $order        = (object)$order;
  184.             $order_list[] =
  185.                 [
  186.                     "id"             => $order->web_id,
  187.                     "idWeb"          => $order->web_id,
  188.                     "BatchId"        => $order->ob_oid,
  189.                     "Carga"          => $order->create_at,
  190.                     "Archivo"        => $order->file,
  191.                     "Usuario"        => $order->user,
  192.                     "Cliente"        => $order->client,
  193.                     "Estado"         => $order->Estado,
  194.                     "detalleDeCarga" => $order->Cita,
  195.                     "FechaDeCarga"   => $order->Fecha_Cita,
  196.                     "FechaDeProceso" => $order->Fecha_Cita,
  197.                     "detalle"        => 'None',
  198.                 ];
  199.         }
  200.         $data = [
  201.             [
  202.                 'stateList' => $statuss,
  203.                 'orderList' => $order_list,
  204.                 'homework'  => $works,
  205.             ]
  206.         ];
  207.         return $this->json($data);
  208.     }
  209.     /**
  210.      * @param Request                  $request
  211.      * @param ProductRepository        $productRepository
  212.      * @param SonataUserUserRepository $userRepository
  213.      * @param OrderRepository          $orderRepository
  214.      * @return JsonResponse
  215.      * @Route("/intranet/process_order", name="process_order")
  216.      */
  217.     public function processOrdenAction(Request $requestProductRepository $productRepositorySonataUserUserRepository $userRepositoryOrderRepository $orderRepository)
  218.     {
  219.         $session        $request->getSession();
  220.         $p              $request->request;
  221.         $data           json_decode($p->get('orderData'));
  222.         $data           $data->data ?? null;
  223.         $user_pass_hash $session->get('user_password_hash');
  224.         $response = [
  225.             "status"  => 'error',
  226.             "message" => 'No se pudo procesar el pedido',
  227.         ];
  228.         $user $userRepository->findOneBy(['user_pass_hash' => $user_pass_hash]);
  229.         if ($data) {
  230.             $order = new Order();
  231.             $order->setUser($user);
  232.             $order->setAccountId($data->accountId);
  233.             $order->setTasks(self::$default_task);
  234.             $errors = [];
  235.             if (!$data->info->name) {
  236.                 $errors['name'] = 'El nombre es obligatorio';
  237.             }
  238.             if (!$data->info->phone) {
  239.                 $errors['phone'] = 'El telĂ©fono es obligatorio';
  240.             }
  241.             if (!$data->info->address) {
  242.                 $errors['phone'] = 'La direcciĂłn es obligatoria';
  243.             }
  244.             if (!$data->info->city) {
  245.                 $errors['city'] = 'La ciudad es obligatoria';
  246.             }
  247.             if (count($errors) < 0) {
  248.                 $response = [
  249.                     "status"  => 'error',
  250.                     "message" => 'Debes completar todos los campos obligatorios',
  251.                     "errors"  => $errors,
  252.                 ];
  253.                 return $this->json($response);
  254.             }
  255.             $order->setContactName($data->info->name);
  256.             $order->setContactPhone($data->info->phone);
  257.             $order->setContactAddress($data->info->address);
  258.             $order->setContactCity($data->info->city);
  259.             $this->em->persist($order);
  260.             $this->em->flush();
  261.             foreach ($data->list as $item) {
  262.                 $product $productRepository->findOneBy(['product_id' => $item->id]);
  263.                 if (!$product) {
  264.                     $product = new Product();
  265.                     $product->setProductId($item->id);
  266.                     $product->setName($item->name);
  267.                     $product->setPackaging($item->packagingType);
  268.                     $this->em->persist($product);
  269.                     $this->em->flush();
  270.                 }
  271.                 $order_prod = new OrderProduct();
  272.                 $order_prod->setOrder($order);
  273.                 $order_prod->setProduct($product);
  274.                 $order_prod->setBatch($item->selectBatch);
  275.                 $order_prod->setQuantity($item->total);
  276.                 $this->em->persist($order_prod);
  277.                 $this->em->flush();
  278.             }
  279.             $send $this->sendFileBase64($request$orderfalse);
  280.             if ($send) {
  281.                 $response = [
  282.                     "status"  => 'success',
  283.                     "message" => 'Pedido recibido correctamente',
  284.                 ];
  285.             }
  286.         }
  287.         return $this->json($response);
  288.     }
  289.     /**
  290.      * @param Request $request
  291.      * @return JsonResponse
  292.      * @Route("/intranet/process_order_file", name="process_order_file")
  293.      */
  294.     public function processOrdenFileAction(Request $requestProductRepository $productRepositorySonataUserUserRepository $userRepositoryOrderRepository $orderRepository)
  295.     {
  296.         $session        $request->getSession();
  297.         $user_pass_hash $session->get('user_password_hash');
  298.         $account_id     $request->request->get('accountId');
  299.         $id_home_work   $request->request->get('idHomeWork');
  300.         
  301.         $file $request->files->get('file');
  302. //        $products = $this->apiConsumer->getclientInv($account_id, $session->get('user_password_hash'));
  303.         $allowedMimeTypes = [
  304.             'text/plain',                 // .txt
  305.             'application/vnd.ms-excel',   // .xls (antiguo formato de Excel)
  306.             'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'// .xlsx
  307.         ];
  308.         $mimeType $file->getMimeType();
  309.         if (!in_array($mimeType$allowedMimeTypes)) {
  310.             $response = [
  311.                 "status"  => 'error',
  312.                 "message" => 'El archivo debe ser en formato TXT o Excel',
  313.             ];
  314.             return $this->json($response);
  315.         }
  316.         if ($mimeType == 'text/plain') {
  317.             $lines file($fileFILE_IGNORE_NEW_LINES FILE_SKIP_EMPTY_LINES);
  318.         } else {
  319.             $spreadsheet IOFactory::load($file->getPathname());
  320.             $sheet       $spreadsheet->getActiveSheet();
  321.             $lines       = [];
  322.             foreach ($sheet->getRowIterator() as $row) {
  323.                 $rowData = [];
  324.                 foreach ($row->getCellIterator() as $cell) {
  325.                     $rowData[] = $cell->getValue();
  326.                 }
  327.                 // Solo agregar la fila si tiene al menos un valor no vacĂ­o
  328.                 if (!empty(array_filter($rowData, function($cell) {
  329.                     return trim($cell) !== '';
  330.                 }))) {
  331.                     $lines[] = $rowData;
  332.                 }
  333.             }
  334.         }
  335.         $user $userRepository->findOneBy(['user_pass_hash' => $user_pass_hash]);
  336.         $order = new Order();
  337.         $order->setUser($user);
  338.         $order->setAccountId($account_id);
  339.         $order->setTasks($id_home_work);
  340.         $order->setFileName($file->getClientOriginalName());
  341.         $this->em->persist($order);
  342.         $this->em->flush();
  343.         /*foreach ($lines as $line) {
  344.             if ($mimeType == 'text/plain') {
  345.                 $columns = explode("\t", $line); // Dividir la lĂ­nea en columnas
  346.             } else {
  347.                 $columns = $line;
  348.             }
  349.             $fields       = [];
  350.             $tasks_format = $this->getTasksFormat($request, $id_home_work);
  351.             foreach ($columns as $key => $field) {
  352.                 if (isset($tasks_format[$key])) {
  353.                     $fields[$tasks_format[$key]] = trim($field);
  354.                 }
  355.             }
  356.             
  357. //            dump($fields);
  358.             $product = $productRepository->findOneBy(['product_id' => $fields['producto']]);
  359.             
  360.             if (!$product) {
  361.                 $prod_ws = array_filter($products, function ($item) use ($fields) {
  362.                     return trim($item->producto_cod) === trim($fields['producto']);
  363.                 });
  364.                 if (!isset($prod_ws[0])) {
  365. //                    dump("No se encontrĂł el producto con cĂłdigo: " . $fields['producto']);
  366.                     continue;
  367.                 }
  368.                 $prod_ws = $prod_ws[0];
  369.                 $product = new Product();
  370.                 $product->setProductId($prod_ws->producto_cod);
  371.                 $product->setName($prod_ws->desc_prod);
  372.                 $product->setPackaging($prod_ws->Unim);
  373.                 $this->em->persist($product);
  374.                 $this->em->flush();
  375.             }
  376.             // Validar que los campos requeridos existan
  377.             if (!isset($fields['cantidad']) || !isset($fields['hold']) || !isset($fields['DirecciĂłn']) || !isset($fields['Ciudad'])) {
  378.                 continue;
  379.             }
  380.             $order_prod = new OrderProduct();
  381.             $order_prod->setOrder($order);
  382.             $order_prod->setProduct($product);
  383.             $order_prod->setQuantity((int)$fields['cantidad']);
  384.             $order_prod->setHold($fields['hold']);
  385.             $order_prod->setAddress($fields['DirecciĂłn']);
  386.             $order_prod->setCity($fields['Ciudad']);
  387.             $this->em->persist($order_prod);
  388.             $this->em->flush();
  389.             
  390. //            dump($order_prod);
  391.         }*/
  392.         if ($mimeType == 'text/plain') {
  393.             $base64 base64_encode(file_get_contents($file->getPathname()));
  394.         }else{
  395.             $content '';
  396.             foreach ($lines as $line) {
  397.                 $content .= implode("\t"$line) . "\n";
  398.             }
  399.             $base64 base64_encode($content);
  400.         }
  401.         $send $this->sendFileBase64($request$order$id_home_work$base64/*$mimeType == 'text/plain' ? $base64 : false*/);
  402.         if ($send) {
  403.             $response = [
  404.                 "status"  => 'success',
  405.                 "message" => 'Pedido recibido correctamente',
  406.             ];
  407.         } else {
  408.             $response = [
  409.                 "status"  => 'error',
  410.                 "message" => 'No se pudo procesar el pedido',
  411.             ];
  412.         }
  413.         return $this->json($response);
  414.     }
  415.     public function sendFileBase64($requestOrder $order$task false$base64 false)
  416.     {
  417.         $session        $request->getSession();
  418.         $user_pass_hash $session->get('user_password_hash');
  419.         $products $this->em->getRepository(OrderProduct::class)->findBy(['order' => $order->getId()]);
  420.         $web_task_id     self::$default_task;
  421.         $web_task_detail = [
  422.             'cod_cliente',
  423.             'producto_cod',
  424.             'Lote',
  425.             'Cant_Solicitada',
  426.             'DirecciĂłn',
  427.             'NroReferencia',
  428.         ];
  429.         if ($base64) {
  430.             $file_64 $base64;
  431.         } else {
  432.             $data = [];
  433.             foreach ($products as $prod) {
  434.                 $tmp = [];
  435.                 foreach ($task === false $web_task_detail $this->getTasksFormat($request$task) as $field) {
  436.                     $tmp[] = $this->resolverFieldName($prod$field);
  437.                 }
  438.                 $data[] = $tmp;
  439.             }
  440.             $content "";
  441.             foreach ($data as $row) {
  442.                 $content .= implode("\t"$row) . "\n";
  443.             }
  444.             $file_64 base64_encode($content);
  445.         }
  446.         $send $this->apiConsumer->getImportsTasksFile($user_pass_hash$task === false '76796070-0' $order->getAccountId(), $order->getId(), $task === false $web_task_id $task$file_64);
  447.         if ($send) {
  448.             $order->setStatus('Enviado');
  449.             $order->setWsId($send);
  450.             $this->em->persist($order);
  451.             $this->em->flush();
  452.             return true;
  453.         } else {
  454.             return false;
  455.         }
  456.     }
  457.     /**
  458.      * @Route("/data/product.json", name="data_products")
  459.      */
  460.     public function dataProductsAction(Request $request): \Symfony\Component\HttpFoundation\JsonResponse
  461.     {
  462.         $id $request->query->get('id');
  463.         $session $request->getSession();
  464.         $products $this->apiConsumer->getclientInv($id$session->get('user_password_hash'));
  465.         $data     = [];
  466.         $data_tmp = [];
  467.         foreach ($products as $product) {
  468.             if (rtrim($product->Tratamiento) == '') {
  469.                 $data_tmp[$product->producto_cod][] =
  470.                     [
  471.                         "producto_cod" => $product->producto_cod,
  472.                         "desc_prod"    => $product->desc_prod,
  473.                         "Unim"         => $product->Unim,
  474.                         'Lote'         => $product->Lote,
  475.                         'Disponible'   => $product->Disponible,
  476.                         'Tratamiento'  => $product->Tratamiento,
  477.                     ];
  478.             }
  479.         }
  480.         foreach ($data_tmp as $product) {
  481.             $data_lote  = [];
  482.             $total_lote = [];
  483.             foreach ($product as $lote) {
  484.                 $data_lote[]  = [
  485.                     'batch'    => $lote['Lote'],
  486.                     'quantity' => $lote['Disponible'],
  487.                 ];
  488.                 $total_lote[] = (int)$lote['Disponible'];
  489.             }
  490.             $data[] =
  491.                 [
  492.                     "id"                => $product[0]['producto_cod'],
  493.                     "name"              => $product[0]['desc_prod'],
  494.                     "stored"            => array_sum($total_lote),
  495.                     "packagingType"     => $product[0]['Unim'],
  496.                     "packagingQuantity" => null,
  497.                     'batch'             => $data_lote
  498.                 ];
  499.         }
  500.         return $this->json($data);
  501.     }
  502.     /**
  503.      * @Route("/data/inventory.json", name="data_inventory")
  504.      * @Route("/data/inventory_json", name="data_inventory2")
  505.      */
  506.     public function dataInventoryAction(Request $request): \Symfony\Component\HttpFoundation\JsonResponse
  507.     {
  508.         $id $request->query->get('id');
  509.         $session $request->getSession();
  510.         $products $this->apiConsumer->getclientInv($id$session->get('user_password_hash'));
  511.         $prod = [];
  512.         foreach ($products as $product) {
  513.             $prod[] =
  514.                 [
  515.                     "id"            => $product->producto_cod,
  516.                     "name"          => $product->desc_prod,
  517.                     "stored"        => $product->Total,
  518.                     "packagingType" => $product->Unim,
  519.                     "batch"         => $product->Lote,
  520.                     "Treatment"     => $product->Tratamiento,
  521.                 ];
  522.         }
  523.         $data = [
  524.             [
  525.                 'file' => $this->generateUrl('download_inventory', ['id' => $id]),
  526.                 'data' => $prod,
  527.             ]
  528.         ];
  529.         return $this->json($data);
  530.     }
  531.     /**
  532.      * @Route("/download/inventory", name="download_inventory")
  533.      */
  534.     public function downloadInventoryAction(Request $request): StreamedResponse
  535.     {
  536.         $id $request->query->get('id');
  537.         $session $request->getSession();
  538.         $products $this->apiConsumer->getclientInv($id$session->get('user_password_hash'));
  539.         $spreadsheet = new Spreadsheet();
  540.         $sheet       $spreadsheet->getActiveSheet();
  541.         $sheet->setCellValue('A1''ID Producto');
  542.         $sheet->setCellValue('B1''Nombre');
  543.         $sheet->setCellValue('C1''Lote');
  544.         $sheet->setCellValue('D1''Tratamiento');
  545.         $sheet->setCellValue('E1''Disponible');
  546.         $sheet->setCellValue('F1''Reservado');
  547.         $sheet->setCellValue('G1''En despacho');
  548.         $sheet->setCellValue('H1''En PreparaciĂłn');
  549.         $sheet->setCellValue('I1''Merma');
  550.         $sheet->setCellValue('J1''Total');
  551.         $sheet->setCellValue('K1''Embalaje');
  552.         $row 2;
  553.         foreach ($products as $item) {
  554.             $sheet->setCellValue('A' $row$item->producto_cod);
  555.             $sheet->setCellValue('B' $row$item->desc_prod);
  556.             $sheet->setCellValue('C' $row$item->Lote);
  557.             $sheet->setCellValue('D' $row$item->Tratamiento);
  558.             $sheet->setCellValue('E' $row$item->Disponible);
  559.             $sheet->setCellValue('F' $row$item->Reservado);
  560.             $sheet->setCellValue('G' $row$item->En_Despacho);
  561.             $sheet->setCellValue('H' $row$item->En_PreparaciĂłn);
  562.             $sheet->setCellValue('I' $row$item->Merma);
  563.             $sheet->setCellValue('J' $row$item->Total);
  564.             $sheet->setCellValue('K' $row$item->Unim);
  565.             $row++;
  566.         }
  567.         $response = new StreamedResponse(function () use ($spreadsheet) {
  568.             $writer = new Xlsx($spreadsheet);
  569.             $writer->save('php://output');
  570.         });
  571.         // Configurar las cabeceras de la respuesta
  572.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  573.         $response->headers->set('Content-Disposition''attachment;filename="inventario_' date('d/m/Y H:i:s') . '.xlsx"');
  574.         $response->headers->set('Cache-Control''max-age=0');
  575.         return $response;
  576.     }
  577.     /**
  578.      * @Route("/data/account.json", name="data_account")
  579.      */
  580.     public function dataAccountAction(Request $request): \Symfony\Component\HttpFoundation\JsonResponse
  581.     {
  582.         $session $request->getSession();
  583.         $accounts $this->apiConsumer->getclientList($session->get('user_password_hash'));
  584.         $data = [];
  585.         foreach ($accounts as $account) {
  586.             $data[] =
  587.                 [
  588.                     "id"      => $account->cod_cliente,
  589.                     "account" => $account->cliente_nombre,
  590.                 ];
  591.         }
  592.         return $this->json($data);
  593.     }
  594.     /**
  595.      * @Route("/data/user.json", name="data_users")
  596.      * @Route("/data/users_json", name="data_user2")
  597.      */
  598.     public function dataUserAction(Request $requestSonataUserUserRepository $userRepository)
  599.     {
  600.         $session $request->getSession();
  601.         $user $userRepository->findOneBy(['user_pass_hash' => $session->get('user_password_hash')]);
  602.         $account $this->apiConsumer->getclientList($session->get('user_password_hash'))[0] ?? null;
  603. //        $validate = $this->apiConsumer->getClienteValidar($session->get('user_password_hash'))[0] ?? null;
  604.         $data =
  605.             [
  606.                 "id"           => $user->getId(),
  607.                 "name"         => /*$validate->Modulo_Name*/'',
  608.                 "token"        => $session->get('user_password_hash'),
  609.                 "year"         => 1900,
  610.                 "bill"         => true,
  611.                 "accountId"    => $account->cod_cliente,
  612.                 "userMsj"      => "",
  613.                 "adminMsj"     => "",
  614.                 "modalContent" => ('Para armar el archivo de texto, crea filas con los datos separados por tabuladores y cada registro en una nueva lĂ­nea, en el siguiente orden: CĂłdigo de Cliente, CĂłdigo de Producto, Fecha, CĂłdigo, Cantidad y Tipo de embalaje.'),
  615.                 'exampleFile'  => '',
  616.                 'example'      => [
  617.                     $this->getTasksFormat($requestnulltrue)
  618.                 ]
  619.             ];
  620.         return $this->json($data);
  621.     }
  622.     private function getTasks($cod_client$user_pass_hash)
  623.     {
  624. //        return $this->apiConsumer->getImportsTasksFormats('5178', $user_pass_hash) ?? null;
  625.         return $this->apiConsumer->getImportsTasksList($cod_client$user_pass_hash)[0] ?? null;
  626.     }
  627.     private function getTasksFormat(Request $request$task_id null$ucfirst false): array
  628.     {
  629.         $session        $request->getSession();
  630.         $user_pass_hash $session->get('user_password_hash');
  631.         if ($task_id == null) {
  632.             $task_id self::$default_task;
  633.         }
  634.         $tasks_format $this->apiConsumer->getImportsTasksFormats($task_id$user_pass_hash) ?? null;
  635.         $tasks_ar = [];
  636.         foreach ($tasks_format as $item) {
  637.             $tasks_ar[(int)$item->Posicion 1] = $ucfirst ucfirst($item->Descripcion) : $item->Descripcion;
  638.         }
  639.         ksort($tasks_ar);
  640.         return $tasks_ar;
  641.     }
  642.     private function resolverFieldName(OrderProduct $product$field): bool|int|string|null
  643.     {
  644.         return match (ltrim($field)) {
  645.             'fecha' => date('d/m/Y'),
  646.             'cod_cliente' => $product->getOrder()->getAccountId(),
  647.             'hold' => $product->getHold(),
  648.             'Ciudad' => $product->getCity(),
  649.             'producto''producto_cod' => $product->getProduct()->getProductId(),
  650.             'cantidad''Cant_Solicitada' => $product->getQuantity(),
  651.             'lot''Lote' => $product->getBatch() != $product->getBatch() : '*',
  652.             'DirecciĂłn' => $product->getOrder()->getContactAddress() ?: $product->getAddress(),
  653.             'NroReferencia' => $product->getOrder()->getId(),
  654.             default => false,
  655.         };
  656.     }
  657.     private function setFieldName(OrderProduct $product$field)
  658.     {
  659.         switch ($field) {
  660.             case'fecha':
  661.                 return date('d/m/Y');
  662.             case'producto':
  663.                 return $product->getProduct()->getProductId();
  664.             case'cantidad':
  665.                 return $product->getQuantity();
  666.             case'lot':
  667.                 return '*';
  668.             default;
  669.         }
  670.     }
  671.     #[Route('/download-example/{task_id}'name'download_example')]
  672.     public function downloadExampleTxt(Request $request$task_id): Response
  673.     {
  674.         $session $request->getSession();
  675. //        $tasks_ws = $this->apiConsumer->getImportsTasksFormats($task_id, $session->get('user_password_hash'));
  676.         $tasks_ws $this->getTasksFormat($request$task_id);
  677.         $fields = [];
  678.         foreach ($tasks_ws as $tasks_w) {
  679.             $fields[] = $this->correctWorks($tasks_wtrue);
  680.         }
  681.         $content "";
  682.         foreach ([$fields] as $row) {
  683.             $content .= implode("\t"$row) . "\n";
  684.         }
  685.         // Crear la respuesta con encabezados adecuados
  686.         $response = new Response($content);
  687.         $response->headers->set('Content-Type''text/plain');
  688.         $response->headers->set('Content-Disposition''attachment; filename="ejemplo_pedido.txt"');
  689.         $response->headers->set('Content-Length'strlen($content));
  690.         return $response;
  691.     }
  692.     #[Route('/download-example-xls/{task_id}'name'download_example_xls')]
  693.     public function downloadExampleXls(Request $request$task_id): Response
  694.     {
  695.         $session $request->getSession();
  696. //        $tasks_ws = $this->apiConsumer->getImportsTasksFormats($task_id, $session->get('user_password_hash'));
  697.         $tasks_ws $this->getTasksFormat($request$task_id);
  698.         $fields = [];
  699.         foreach ($tasks_ws as $tasks_w) {
  700.             $fields[] = $this->correctWorks($tasks_wtrue);
  701.         }
  702.         $spreadsheet = new Spreadsheet();
  703.         $sheet       $spreadsheet->getActiveSheet();
  704.         $letras range('A''Z');
  705.         foreach ($fields as $index => $field) {
  706.             $sheet->setCellValue($letras[$index] . '1'$field);
  707.         }
  708.         $response = new StreamedResponse(function () use ($spreadsheet) {
  709.             $writer = new Xlsx($spreadsheet);
  710.             $writer->save('php://output');
  711.         });
  712.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  713.         $response->headers->set('Content-Disposition''attachment;filename="ejemplo_archivo' '.xlsx"');
  714.         $response->headers->set('Cache-Control''max-age=0');
  715.         return $response;
  716.     }
  717.     /**
  718.      * @Route("/data/tracing.json", name="data_tracing")
  719.      * @Route("/data/tracing_json", name="data_tracing2")
  720.      */
  721.     public function dataTracingAction(Request $requestOrderRepository $orderRepository): \Symfony\Component\HttpFoundation\JsonResponse
  722.     {
  723.         $session $request->getSession();
  724.         $hash $session->get('user_password_hash');
  725.         $id_client $request->query->get('id');
  726.         $tracing $this->apiConsumer->getPedidoSeguimiento($id_client$hash);
  727.         $data = [];
  728.         foreach ($tracing as $item) {
  729.             $data[] =
  730.                 [
  731.                     "id"           => $item->ob_oid,
  732.                     "date"         => $item->Crea_date,
  733.                     "orderId"      => $item->ob_oid,
  734.                     "create_date"  => $item->Crea_date,
  735.                     "status"       => $item->Estado,
  736.                     "guide_number" => $item->num_guia_despacho,
  737.                     "cita"         => $item->Cita,
  738.                     "fecha_cita"   => $item->Fecha_Cita,
  739.                 ];
  740.         }
  741.         return $this->json($data);
  742.     }
  743.     /**
  744.      * @Route("/data/order.json", name="data_order")
  745.      * @Route("/data/order_json", name="data_order2")
  746.      */
  747.     public function dataOrderAction(Request $requestOrderRepository $orderRepository): \Symfony\Component\HttpFoundation\JsonResponse
  748.     {
  749.         $session $request->getSession();
  750.         $hash $session->get('user_password_hash');
  751.         $order_id  $request->query->get('id');
  752.         $branch_id $request->query->get('branchId');
  753.         $orders $orderRepository->findOneBy(['ws_id' => $order_id]);
  754.         $tracings $this->apiConsumer->getPedidoSeguimiento($branch_id$hash);
  755.         $tracings_prods $this->apiConsumer->getPedidoSeguimientoDetalle($branch_id$order_id$hash);
  756.         $products = [];
  757.         if ($tracings_prods) {
  758.             foreach ($tracings_prods as $product) {
  759.                 $products[] = [
  760.                     'id'                  => $product->producto_cod,
  761.                     'name'                => $product->desc_prod,
  762.                     'quantity'            => (int)$product->Cant_Solicitada,
  763.                     'quantity_processed'  => (int)$product->Cant_en_Proceso,
  764.                     'quantity_dispatched' => (int)$product->Cant_Despachada,
  765.                     'batch'               => $product->Lote ?: 'Sin lote',
  766.                     'status'              => $product->Estado,
  767.                 ];
  768.             }
  769.         }
  770.         $data_ws = [];
  771.         foreach ($tracings as $tracing) {
  772. //            if ($tracing->ob_oid == $order_id) {
  773.                 $data_ws = [
  774.                     'Crea_date'         => $tracing->Crea_date,
  775.                     'ob_oid'            => $tracing->ob_oid,
  776.                     'Tipo'              => $tracing->Tipo,
  777.                     'num_guia_despacho' => $tracing->num_guia_despacho,
  778.                     'Productos'         => $tracing->Productos,
  779.                     'Lineas'            => $tracing->Lineas,
  780.                     'Cant_Solicitada'   => $tracing->Cant_Solicitada,
  781.                     'Cant_Despachada'   => $tracing->Cant_Despachada,
  782.                     'Estado'            => $tracing->Estado,
  783.                     'Cita'              => $tracing->Cita,
  784.                     'Fecha_Cita'        => $tracing->Fecha_Cita,
  785.                     'Hora_Cita'         => $tracing->Hora_Cita,
  786.                     'Boleto'            => $tracing->Boleto,
  787.                     'Hora_Presentacion' => $tracing->Hora_Presentacion,
  788.                     'Hora_Ingreso'      => $tracing->Hora_Ingreso,
  789.                     'Hora_Salida'       => $tracing->Hora_Salida,
  790.                 ];
  791. //            }
  792.         }
  793.         $data = [];
  794.         $data[] =
  795.             [
  796.                 "id"                => $data_ws['ob_oid'],
  797.                 "date"              => $data_ws['Crea_date'],
  798.                 "Tipo"              => $data_ws['Tipo'],
  799.                 "num_guia_despacho" => $data_ws['num_guia_despacho'],
  800.                 "Productos"         => $data_ws['Productos'],
  801.                 "Lineas"            => $data_ws['Lineas'],
  802.                 "Cant_Solicitada"   => $data_ws['Cant_Solicitada'],
  803.                 "Cant_Despachada"   => $data_ws['Cant_Despachada'],
  804.                 "Cita"              => $data_ws['Cita'],
  805.                 "Fecha_Cita"        => $data_ws['Fecha_Cita'],
  806.                 "Hora_Cita"         => $data_ws['Hora_Cita'],
  807.                 "status"            => $data_ws['Estado'],
  808.                 "statusMsg"         => $data_ws['Estado'],
  809.                 "products"          => $products,
  810.             ];
  811.         return $this->json($data);
  812.     }
  813.     /**
  814.      * @Route("/data/bill.json", name="data_bill")
  815.      * @Route("/data/bill_json", name="data_bill2")
  816.      */
  817.     public function dataBillAction(Request $request): \Symfony\Component\HttpFoundation\JsonResponse
  818.     {
  819.         $session $request->getSession();
  820.         $id_client $request->query->get('id');
  821.         $bills $this->apiConsumer->getFacturaResumen($session->get('user_password_hash'));
  822.         $data = [];
  823.         foreach ($bills as $item) {
  824.             $fecha = new \DateTime($item->F_Emis);
  825.             $data[] =
  826.                 [
  827.                     "id"            => $item->Factura,
  828.                     "date"          => $fecha->format('d/m/Y'),
  829.                     //                    "n_credito"     => $item->N_Credito ,
  830.                     "nota_venta"    => $item->NotaVenta,
  831.                     "cotizacion"    => $item->cotizacion,
  832.                     "f_impt"        => $item->F_Impt,
  833.                     "f_emis"        => $item->F_Emis,
  834.                     "f_venc"        => $item->F_Venc,
  835.                     "rut_recep"     => $item->RutRecep,
  836.                     "id_erp"        => $item->id_erp,
  837.                     "rzn_soc_recep" => $item->RznSocRecep,
  838.                     "lineas"        => $item->Lineas,
  839.                     "cve_des"       => $item->CveDes,
  840.                     "venta_item"    => $this->moneyFormat($item->Venta_Item),
  841.                     "desc"          => $this->moneyFormat($item->Desc),
  842.                     "mnt_exe"       => $this->moneyFormat($item->MntExe),
  843.                     "neto"          => $this->moneyFormat($item->Neto),
  844.                     "iva"           => $this->moneyFormat($item->IVA),
  845.                     "total"         => $this->moneyFormat($item->Total),
  846.                     "pendiente"     => $this->moneyFormat($item->Pendiente),
  847.                     "estado"        => $item->Estado,
  848.                     "dias_vencido"  => $item->Dias_Vencido,
  849.                     "file"          => $this->generateUrl('data_bill_pdf', ['folio' => $item->Factura]),
  850.                 ];
  851.         }
  852.         usort($data, function ($a$b) {
  853.             $dateA DateTime::createFromFormat('d/m/Y'$a['date']);
  854.             $dateB DateTime::createFromFormat('d/m/Y'$b['date']);
  855.             return $dateB <=> $dateA// Orden ascendente
  856.         });
  857.         return $this->json($data);
  858.     }
  859.     private function moneyFormat($value)
  860.     {
  861.         return '$' number_format((int)$value0null'.');
  862.     }
  863.     /**
  864.      * @Route("/data/bill_pdf/{folio}", name="data_bill_pdf")
  865.      */
  866.     public function getFacturaFile(Request $request$folio)
  867.     {
  868.         $session $request->getSession();
  869.         $id_client $request->query->get('id');
  870.         $id_client $request->query->get('id');
  871.         $pdf_64 $this->apiConsumer->getFacturaPDF($session->get('user_password_hash'), $folio);
  872.         $pdfContent base64_decode($pdf_64);
  873.         if ($pdfContent === false) {
  874.             return new Response("Error al decodificar el PDF."Response::HTTP_INTERNAL_SERVER_ERROR);
  875.         }
  876.         // Retornar el PDF directamente en la respuesta HTTP
  877.         return new Response($pdfContent200, [
  878.             'Content-Type'        => 'application/pdf',
  879.             'Content-Disposition' => 'inline; filename="factura-' $folio '.pdf"',
  880.         ]);
  881.     }
  882.     /**
  883.      * @Route("/data/report.json", name="data_report")
  884.      * @Route("/data/report_json", name="data_report2")
  885.      */
  886.     public function dataReportAction(Request $request): \Symfony\Component\HttpFoundation\JsonResponse
  887.     {
  888.         $session $request->getSession();
  889.         $id_client $request->query->get('id');
  890.         $report $this->apiConsumer->getPowerBIList($session->get('user_password_hash'));
  891.         $data = [];
  892.         foreach ($report as $item) {
  893.             $data[] =
  894.                 [
  895.                     "id_registro"   => $item->id_registro,
  896.                     "create_date"   => $item->crea_date,
  897.                     "create_oper"   => $item->crea_oper,
  898.                     "id_usuario"    => $item->id_usuario,
  899.                     "Descripc"      => $item->Descripc,
  900.                     "Estado"        => $item->Estado,
  901.                     "URLs"          => $item->URLs,
  902.                     "OrderBy"       => $item->OrdenBy,
  903.                     "Intervalo"     => $item->Intervalo,
  904.                     "URLsParametro" => $item->URLsParametro,
  905.                 ];
  906.         }
  907.         return $this->json($data);
  908.     }
  909. }