src/Controller/DefaultController.php line 50

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