src/Controller/DefaultController.php line 729

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