src/Controller/DefaultController.php line 44

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