src/Controller/DefaultController.php line 49

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