src/Controller/DefaultController.php line 728

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