src/Controller/DefaultController.php line 48

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