<?php
namespace App\Controller;
use App\Entity\Order;
use App\Entity\OrderProduct;
use App\Entity\Product;
use App\Repository\OrderRepository;
use App\Repository\ProductRepository;
use App\Repository\SonataUserUserRepository;
use App\Services\ApiConsumer;
use App\Utils\EAS256CBC;
use App\Utils\SeoUtils;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Annotation\Route;
class DefaultController extends AbstractController
{
protected readonly SeoUtils $seoUtils;
protected ApiConsumer $apiConsumer;
protected EntityManagerInterface $em;
private static string $default_task = '5178';
public function __construct(SeoUtils $seoUtils, ApiConsumer $apiConsumer, EntityManagerInterface $em)
{
$this->seoUtils = $seoUtils;
$this->apiConsumer = $apiConsumer;
$this->em = $em;
}
/**
* @Route("/{reactRouting}", name="homepage", requirements={"reactRouting"=".+"}, defaults={"reactRouting": null}, priority=-10)
*/
public function indexAction(Request $request): Response
{
return $this->render('default/index.html.twig');
}
/**
* @Route("/data/batch.json", name="data_batch")
* @Route("/data/batch_json", name="data_batch2")
*/
public function dataBatchAction(Request $request, OrderRepository $orderRepository): \Symfony\Component\HttpFoundation\JsonResponse
{
$id = $request->query->get('id');
$session = $request->getSession();
$order = $orderRepository->findOneBy(['ws_id' => (int)$id]);
$tracking = $this->apiConsumer->getImportsTasksTracking($order->getId(), $order->getWsId(), $session->get('user_password_hash'));
$data[] =
[
"id" => $order->getId(),
"idWeb" => $order->getId(),
"batchId" => $order->getWsId(),
"Cliente" => '',
"Estado" => $tracking->estado,
"detalleDeCarga" => '0000',
"FechaDeCarga" => $tracking->start_process,
"FechaDeProceso" => $tracking->end_process,
"FechaFinProceso" => $tracking->end_process,
"detalle" => $id,
];
return $this->json($data);
}
/**
* @Route("/data/homeWork.json", name="data_homeWork")
* @Route("/data/homeWork_json", name="data_homeWork2")
*/
public function dataHomeWorkAction(Request $request): \Symfony\Component\HttpFoundation\JsonResponse
{
$id = $request->query->get('id');
$session = $request->getSession();
$tasks_ws = $this->getTasksFormat($request, $id);
$fields = [];
foreach ($tasks_ws as $tasks_w) {
$fields[] = $this->correctWorks($tasks_w, true);
}
$field_last = array_pop($fields);
$data = [];
$data[] =
[
"id" => $id,
"IdWork" => $id,
"name" => '',
"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,
"exampleFile" => $id ? $this->generateUrl('download_example', ['task_id' => $id]) : '',
"exampleFileXls" => $id ? $this->generateUrl('download_example_xls', ['task_id' => $id]) : '',
"example" => [],
];
return $this->json($data);
}
private function correctWorks($word, $ucfirst = false): string
{
$result = match ($word) {
'lot' => 'lote',
'hold' => 'Tratamiento',
default => $word,
};
return $ucfirst ? ucfirst($result) : $result;
}
/**
* @Route("/data/fileTranfer.json", name="data_file_tranfer")
* @Route("/data/fileTranfer_json", name="data_file_tranfer2")
*/
public function dataFileTransferAction(Request $request, OrderRepository $orderRepository): \Symfony\Component\HttpFoundation\JsonResponse
{
$id = $request->query->get('id');
$session = $request->getSession();
$works_ws = $this->apiConsumer->getImportsTasksList($id, $session->get('user_password_hash'));
$orders_ws = $this->apiConsumer->getPedidoSeguimiento($id, $session->get('user_password_hash'));
$orders = [];
$statuss = [];
foreach ($orders_ws as $order_ws) {
$order = $orderRepository->findOneBy(['ws_id' => $order_ws->ob_oid]);
if ($order != null) {
$data_merge = [
'web_id' => $order->getId(),
'create_at' => $order->getCreateAt()->format('Y-m-d H:i:s'),
'file' => $order->getFileName() ?? '',
'user' => $order->getUser()->getUsername(),
'client' => $order->getUser()->getUsername(),
];
$orders[] = array_merge((array)$order_ws, $data_merge);
$statuss[] = [
'id' => $order->getId(),
'name' => $order_ws->Estado
];
}
}
$works = [];
foreach ($works_ws as $work) {
$works[] = [
'id' => $work->Id_Tarea,
'IdWork' => $work->Id_Tarea,
'name' => $work->Descripcion,
];
}
$order_list = [];
foreach ($orders as $order) {
$order = (object)$order;
$order_list[] =
[
"id" => $order->web_id,
"idWeb" => $order->web_id,
"BatchId" => $order->ob_oid,
"Carga" => $order->create_at,
"Archivo" => $order->file,
"Usuario" => $order->user,
"Cliente" => $order->client,
"Estado" => $order->Estado,
"detalleDeCarga" => $order->Cita,
"FechaDeCarga" => $order->Fecha_Cita,
"FechaDeProceso" => $order->Fecha_Cita,
"detalle" => 'None',
];
}
$data = [
[
'stateList' => $statuss,
'orderList' => $order_list,
'homework' => $works,
]
];
return $this->json($data);
}
/**
* @param Request $request
* @param ProductRepository $productRepository
* @param SonataUserUserRepository $userRepository
* @param OrderRepository $orderRepository
* @return JsonResponse
* @Route("/intranet/process_order", name="process_order")
*/
public function processOrdenAction(Request $request, ProductRepository $productRepository, SonataUserUserRepository $userRepository, OrderRepository $orderRepository)
{
$session = $request->getSession();
$p = $request->request;
$data = json_decode($p->get('orderData'));
$data = $data->data ?? null;
$user_pass_hash = $session->get('user_password_hash');
$response = [
"status" => 'error',
"message" => 'No se pudo procesar el pedido',
];
$user = $userRepository->findOneBy(['user_pass_hash' => $user_pass_hash]);
if ($data) {
$order = new Order();
$order->setUser($user);
$order->setAccountId($data->accountId);
$order->setTasks(self::$default_task);
$errors = [];
if (!$data->info->name) {
$errors['name'] = 'El nombre es obligatorio';
}
if (!$data->info->phone) {
$errors['phone'] = 'El teléfono es obligatorio';
}
if (!$data->info->address) {
$errors['phone'] = 'La direcciĂłn es obligatoria';
}
if (!$data->info->city) {
$errors['city'] = 'La ciudad es obligatoria';
}
if (count($errors) < 0) {
$response = [
"status" => 'error',
"message" => 'Debes completar todos los campos obligatorios',
"errors" => $errors,
];
return $this->json($response);
}
$order->setContactName($data->info->name);
$order->setContactPhone($data->info->phone);
$order->setContactAddress($data->info->address);
$order->setContactCity($data->info->city);
$this->em->persist($order);
$this->em->flush();
foreach ($data->list as $item) {
$product = $productRepository->findOneBy(['product_id' => $item->id]);
if (!$product) {
$product = new Product();
$product->setProductId($item->id);
$product->setName($item->name);
$product->setPackaging($item->packagingType);
$this->em->persist($product);
$this->em->flush();
}
$order_prod = new OrderProduct();
$order_prod->setOrder($order);
$order_prod->setProduct($product);
$order_prod->setBatch($item->selectBatch);
$order_prod->setQuantity($item->total);
$this->em->persist($order_prod);
$this->em->flush();
}
$send = $this->sendFileBase64($request, $order, false);
if ($send) {
$response = [
"status" => 'success',
"message" => 'Pedido recibido correctamente',
];
}
}
return $this->json($response);
}
/**
* @param Request $request
* @return JsonResponse
* @Route("/intranet/process_order_file", name="process_order_file")
*/
public function processOrdenFileAction(Request $request, ProductRepository $productRepository, SonataUserUserRepository $userRepository, OrderRepository $orderRepository)
{
$session = $request->getSession();
$user_pass_hash = $session->get('user_password_hash');
$account_id = $request->request->get('accountId');
$id_home_work = $request->request->get('idHomeWork');
$file = $request->files->get('file');
$products = $this->apiConsumer->getclientInv($account_id, $session->get('user_password_hash'));
$allowedMimeTypes = [
'text/plain', // .txt
'application/vnd.ms-excel', // .xls (antiguo formato de Excel)
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
];
$mimeType = $file->getMimeType();
if (!in_array($mimeType, $allowedMimeTypes)) {
$response = [
"status" => 'error',
"message" => 'El archivo debe ser en formato TXT o Excel',
];
return $this->json($response);
}
if ($mimeType == 'text/plain') {
$lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
} else {
$spreadsheet = IOFactory::load($file->getPathname());
$sheet = $spreadsheet->getActiveSheet();
$lines = [];
foreach ($sheet->getRowIterator() as $row) {
$rowData = [];
foreach ($row->getCellIterator() as $cell) {
$rowData[] = $cell->getValue();
}
$lines[] = $rowData;
}
}
$user = $userRepository->findOneBy(['user_pass_hash' => $user_pass_hash]);
$order = new Order();
$order->setUser($user);
$order->setAccountId($account_id);
$order->setTasks($id_home_work);
$order->setFileName($file->getClientOriginalName());
$this->em->persist($order);
$this->em->flush();
foreach ($lines as $line) {
if ($mimeType == 'text/plain') {
$columns = explode("\t", $line); // Dividir la lĂnea en columnas
} else {
$columns = $line;
}
$fields = [];
$tasks_format = $this->getTasksFormat($request, $id_home_work);
foreach ($columns as $key => $field) {
$fields[$tasks_format[$key]] = $field;
}
$product = $productRepository->findOneBy(['product_id' => $fields['producto']]);
if (!$product) {
$prod_ws = array_filter($products, function ($item) use ($fields) {
return $item->producto_cod === $fields['producto'];
});
$prod_ws = $prod_ws[0];
$product = new Product();
$product->setProductId($prod_ws->producto_cod);
$product->setName($prod_ws->desc_prod);
$product->setPackaging($prod_ws->unim);
$this->em->persist($product);
$this->em->flush();
}
$order_prod = new OrderProduct();
$order_prod->setOrder($order);
$order_prod->setProduct($product);
$order_prod->setQuantity((int)$fields['cantidad']);
$order_prod->setHold($fields['hold']);
$order_prod->setAddress($fields['DirecciĂłn']);
$order_prod->setCity($fields['Ciudad']);
$this->em->persist($order_prod);
$this->em->flush();
}
$base64 = base64_encode(file_get_contents($file->getPathname()));
$send = $this->sendFileBase64($request, $order, $id_home_work, $mimeType == 'text/plain' ? $base64 : false);
if ($send) {
$response = [
"status" => 'success',
"message" => 'Pedido recibido correctamente',
];
} else {
$response = [
"status" => 'error',
"message" => 'No se pudo procesar el pedido',
];
}
return $this->json($response);
}
public function sendFileBase64($request, Order $order, $task = false, $base64 = false)
{
$session = $request->getSession();
$user_pass_hash = $session->get('user_password_hash');
$products = $this->em->getRepository(OrderProduct::class)->findBy(['order' => $order->getId()]);
$web_task_id = self::$default_task;
$web_task_detail = [
'cod_cliente',
'producto_cod',
'Lote',
'Cant_Solicitada',
'DirecciĂłn',
'NroReferencia',
];
if ($base64) {
$file_64 = $base64;
} else {
$data = [];
foreach ($products as $prod) {
$tmp = [];
foreach ($task === false ? $web_task_detail : $this->getTasksFormat($request, $task) as $field) {
$tmp[] = $this->resolverFieldName($prod, $field);
}
$data[] = $tmp;
}
$content = "";
foreach ($data as $row) {
$content .= implode("\t", $row) . "\n";
}
$file_64 = base64_encode($content);
}
$send = $this->apiConsumer->getImportsTasksFile($user_pass_hash, $task === false ? '76796070-0' : $order->getAccountId(), $order->getId(), $task === false ? $web_task_id : $task, $file_64);
if ($send) {
$order->setStatus('Enviado');
$order->setWsId($send);
$this->em->persist($order);
$this->em->flush();
return true;
} else {
return false;
}
}
/**
* @Route("/data/product.json", name="data_products")
*/
public function dataProductsAction(Request $request): \Symfony\Component\HttpFoundation\JsonResponse
{
$id = $request->query->get('id');
$session = $request->getSession();
$products = $this->apiConsumer->getclientInv($id, $session->get('user_password_hash'));
$data = [];
$data_tmp = [];
foreach ($products as $product) {
if (rtrim($product->Tratamiento) == '') {
$data_tmp[$product->producto_cod][] =
[
"producto_cod" => $product->producto_cod,
"desc_prod" => $product->desc_prod,
"Unim" => $product->Unim,
'Lote' => $product->Lote,
'Disponible' => $product->Disponible,
'Tratamiento' => $product->Tratamiento,
];
}
}
foreach ($data_tmp as $product) {
$data_lote = [];
$total_lote = [];
foreach ($product as $lote) {
$data_lote[] = [
'batch' => $lote['Lote'],
'quantity' => $lote['Disponible'],
];
$total_lote[] = (int)$lote['Disponible'];
}
$data[] =
[
"id" => $product[0]['producto_cod'],
"name" => $product[0]['desc_prod'],
"stored" => array_sum($total_lote),
"packagingType" => $product[0]['Unim'],
"packagingQuantity" => null,
'batch' => $data_lote
];
}
return $this->json($data);
}
/**
* @Route("/data/inventory.json", name="data_inventory")
* @Route("/data/inventory_json", name="data_inventory2")
*/
public function dataInventoryAction(Request $request): \Symfony\Component\HttpFoundation\JsonResponse
{
$id = $request->query->get('id');
$session = $request->getSession();
$products = $this->apiConsumer->getclientInv($id, $session->get('user_password_hash'));
$prod = [];
foreach ($products as $product) {
$prod[] =
[
"id" => $product->producto_cod,
"name" => $product->desc_prod,
"stored" => $product->Total,
"packagingType" => $product->Unim,
"batch" => $product->Lote,
"Treatment" => $product->Tratamiento,
];
}
$data = [
[
'file' => $this->generateUrl('download_inventory', ['id' => $id]),
'data' => $prod,
]
];
return $this->json($data);
}
/**
* @Route("/download/inventory", name="download_inventory")
*/
public function downloadInventoryAction(Request $request): StreamedResponse
{
$id = $request->query->get('id');
$session = $request->getSession();
$products = $this->apiConsumer->getclientInv($id, $session->get('user_password_hash'));
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'ID Producto');
$sheet->setCellValue('B1', 'Nombre');
$sheet->setCellValue('C1', 'Lote');
$sheet->setCellValue('D1', 'Tratamiento');
$sheet->setCellValue('E1', 'Disponible');
$sheet->setCellValue('F1', 'Reservado');
$sheet->setCellValue('G1', 'En despacho');
$sheet->setCellValue('H1', 'En PreparaciĂłn');
$sheet->setCellValue('I1', 'Merma');
$sheet->setCellValue('J1', 'Total');
$sheet->setCellValue('K1', 'Embalaje');
$row = 2;
foreach ($products as $item) {
$sheet->setCellValue('A' . $row, $item->producto_cod);
$sheet->setCellValue('B' . $row, $item->desc_prod);
$sheet->setCellValue('C' . $row, $item->Lote);
$sheet->setCellValue('D' . $row, $item->Tratamiento);
$sheet->setCellValue('E' . $row, $item->Disponible);
$sheet->setCellValue('F' . $row, $item->Reservado);
$sheet->setCellValue('G' . $row, $item->En_Despacho);
$sheet->setCellValue('H' . $row, $item->En_PreparaciĂłn);
$sheet->setCellValue('I' . $row, $item->Merma);
$sheet->setCellValue('J' . $row, $item->Total);
$sheet->setCellValue('K' . $row, $item->Unim);
$row++;
}
$response = new StreamedResponse(function () use ($spreadsheet) {
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
});
// Configurar las cabeceras de la respuesta
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment;filename="inventario_' . date('d/m/Y H:i:s') . '.xlsx"');
$response->headers->set('Cache-Control', 'max-age=0');
return $response;
}
/**
* @Route("/data/account.json", name="data_account")
*/
public function dataAccountAction(Request $request): \Symfony\Component\HttpFoundation\JsonResponse
{
$session = $request->getSession();
$accounts = $this->apiConsumer->getclientList($session->get('user_password_hash'));
$data = [];
foreach ($accounts as $account) {
$data[] =
[
"id" => $account->cod_cliente,
"account" => $account->cliente_nombre,
];
}
return $this->json($data);
}
/**
* @Route("/data/user.json", name="data_users")
* @Route("/data/users_json", name="data_user2")
*/
public function dataUserAction(Request $request, SonataUserUserRepository $userRepository)
{
$session = $request->getSession();
$user = $userRepository->findOneBy(['user_pass_hash' => $session->get('user_password_hash')]);
$account = $this->apiConsumer->getclientList($session->get('user_password_hash'))[0] ?? null;
$validate = $this->apiConsumer->getClienteValidar($session->get('user_password_hash'))[0] ?? null;
$data =
[
"id" => $user->getId(),
"name" => $validate->Modulo_Name,
"token" => $session->get('user_password_hash'),
"year" => 1900,
"bill" => true,
"accountId" => $account->cod_cliente,
"userMsj" => "",
"adminMsj" => "",
"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.'),
'exampleFile' => '',
'example' => [
$this->getTasksFormat($request, null, true)
]
];
return $this->json($data);
}
private function getTasks($cod_client, $user_pass_hash)
{
// return $this->apiConsumer->getImportsTasksFormats('5178', $user_pass_hash) ?? null;
return $this->apiConsumer->getImportsTasksList($cod_client, $user_pass_hash)[0] ?? null;
}
private function getTasksFormat(Request $request, $task_id = null, $ucfirst = false): array
{
$session = $request->getSession();
$user_pass_hash = $session->get('user_password_hash');
if ($task_id == null) {
$task_id = self::$default_task;
}
$tasks_format = $this->apiConsumer->getImportsTasksFormats($task_id, $user_pass_hash) ?? null;
$tasks_ar = [];
foreach ($tasks_format as $item) {
$tasks_ar[(int)$item->Posicion - 1] = $ucfirst ? ucfirst($item->Descripcion) : $item->Descripcion;
}
ksort($tasks_ar);
return $tasks_ar;
}
private function resolverFieldName(OrderProduct $product, $field): bool|int|string|null
{
return match (ltrim($field)) {
'fecha' => date('d/m/Y'),
'cod_cliente' => $product->getOrder()->getAccountId(),
'hold' => $product->getHold(),
'Ciudad' => $product->getCity(),
'producto', 'producto_cod' => $product->getProduct()->getProductId(),
'cantidad', 'Cant_Solicitada' => $product->getQuantity(),
'lot', 'Lote' => $product->getBatch() != 0 ? $product->getBatch() : '*',
'DirecciĂłn' => $product->getOrder()->getContactAddress() ?: $product->getAddress(),
'NroReferencia' => $product->getOrder()->getId(),
default => false,
};
}
private function setFieldName(OrderProduct $product, $field)
{
switch ($field) {
case'fecha':
return date('d/m/Y');
case'producto':
return $product->getProduct()->getProductId();
case'cantidad':
return $product->getQuantity();
case'lot':
return '*';
default;
}
}
#[Route('/download-example/{task_id}', name: 'download_example')]
public function downloadExampleTxt(Request $request, $task_id): Response
{
$session = $request->getSession();
// $tasks_ws = $this->apiConsumer->getImportsTasksFormats($task_id, $session->get('user_password_hash'));
$tasks_ws = $this->getTasksFormat($request, $task_id);
$fields = [];
foreach ($tasks_ws as $tasks_w) {
$fields[] = $this->correctWorks($tasks_w, true);
}
$content = "";
foreach ([$fields] as $row) {
$content .= implode("\t", $row) . "\n";
}
// Crear la respuesta con encabezados adecuados
$response = new Response($content);
$response->headers->set('Content-Type', 'text/plain');
$response->headers->set('Content-Disposition', 'attachment; filename="ejemplo_pedido.txt"');
$response->headers->set('Content-Length', strlen($content));
return $response;
}
#[Route('/download-example-xls/{task_id}', name: 'download_example_xls')]
public function downloadExampleXls(Request $request, $task_id): Response
{
$session = $request->getSession();
// $tasks_ws = $this->apiConsumer->getImportsTasksFormats($task_id, $session->get('user_password_hash'));
$tasks_ws = $this->getTasksFormat($request, $task_id);
$fields = [];
foreach ($tasks_ws as $tasks_w) {
$fields[] = $this->correctWorks($tasks_w, true);
}
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$letras = range('A', 'Z');
foreach ($fields as $index => $field) {
$sheet->setCellValue($letras[$index] . '1', $field);
}
$response = new StreamedResponse(function () use ($spreadsheet) {
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
});
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment;filename="ejemplo_archivo' . '.xlsx"');
$response->headers->set('Cache-Control', 'max-age=0');
return $response;
}
/**
* @Route("/data/tracing.json", name="data_tracing")
* @Route("/data/tracing_json", name="data_tracing2")
*/
public function dataTracingAction(Request $request, OrderRepository $orderRepository): \Symfony\Component\HttpFoundation\JsonResponse
{
$session = $request->getSession();
$hash = $session->get('user_password_hash');
$id_client = $request->query->get('id');
$tracing = $this->apiConsumer->getPedidoSeguimiento($id_client, $hash);
$data = [];
foreach ($tracing as $item) {
$data[] =
[
"id" => $item->ob_oid,
"date" => $item->Crea_date,
"orderId" => $item->ob_oid,
"create_date" => $item->Crea_date,
"status" => $item->Estado,
"guide_number" => $item->num_guia_despacho,
"cita" => $item->Cita,
"fecha_cita" => $item->Fecha_Cita,
];
}
return $this->json($data);
}
/**
* @Route("/data/order.json", name="data_order")
* @Route("/data/order_json", name="data_order2")
*/
public function dataOrderAction(Request $request, OrderRepository $orderRepository): \Symfony\Component\HttpFoundation\JsonResponse
{
$session = $request->getSession();
$hash = $session->get('user_password_hash');
$order_id = $request->query->get('id');
$branch_id = $request->query->get('branchId');
$orders = $orderRepository->findOneBy(['ws_id' => $order_id]);
$tracings = $this->apiConsumer->getPedidoSeguimiento($branch_id, $hash);
$tracings_prods = $this->apiConsumer->getPedidoSeguimientoDetalle($branch_id, $order_id, $hash);
$products = [];
if ($tracings_prods) {
foreach ($tracings_prods as $product) {
$products[] = [
'id' => $product->producto_cod,
'name' => $product->desc_prod,
'quantity' => (int)$product->Cant_Solicitada,
'quantity_processed' => (int)$product->Cant_en_Proceso,
'quantity_dispatched' => (int)$product->Cant_Despachada,
'batch' => $product->Lote ?: 'Sin lote',
'status' => $product->Estado,
];
}
}
$data_ws = [];
foreach ($tracings as $tracing) {
// if ($tracing->ob_oid == $order_id) {
$data_ws = [
'Crea_date' => $tracing->Crea_date,
'ob_oid' => $tracing->ob_oid,
'Tipo' => $tracing->Tipo,
'num_guia_despacho' => $tracing->num_guia_despacho,
'Productos' => $tracing->Productos,
'Lineas' => $tracing->Lineas,
'Cant_Solicitada' => $tracing->Cant_Solicitada,
'Cant_Despachada' => $tracing->Cant_Despachada,
'Estado' => $tracing->Estado,
'Cita' => $tracing->Cita,
'Fecha_Cita' => $tracing->Fecha_Cita,
'Hora_Cita' => $tracing->Hora_Cita,
'Boleto' => $tracing->Boleto,
'Hora_Presentacion' => $tracing->Hora_Presentacion,
'Hora_Ingreso' => $tracing->Hora_Ingreso,
'Hora_Salida' => $tracing->Hora_Salida,
];
// }
}
$data = [];
$data[] =
[
"id" => $data_ws['ob_oid'],
"date" => $data_ws['Crea_date'],
"Tipo" => $data_ws['Tipo'],
"num_guia_despacho" => $data_ws['num_guia_despacho'],
"Productos" => $data_ws['Productos'],
"Lineas" => $data_ws['Lineas'],
"Cant_Solicitada" => $data_ws['Cant_Solicitada'],
"Cant_Despachada" => $data_ws['Cant_Despachada'],
"Cita" => $data_ws['Cita'],
"Fecha_Cita" => $data_ws['Fecha_Cita'],
"Hora_Cita" => $data_ws['Hora_Cita'],
"status" => $data_ws['Estado'],
"statusMsg" => $data_ws['Estado'],
"products" => $products,
];
return $this->json($data);
}
/**
* @Route("/data/bill.json", name="data_bill")
* @Route("/data/bill_json", name="data_bill2")
*/
public function dataBillAction(Request $request): \Symfony\Component\HttpFoundation\JsonResponse
{
$session = $request->getSession();
$id_client = $request->query->get('id');
$bills = $this->apiConsumer->getFacturaResumen($session->get('user_password_hash'));
$data = [];
foreach ($bills as $item) {
$fecha = new \DateTime($item->F_Emis);
$data[] =
[
"id" => $item->Factura,
"date" => $fecha->format('d/m/Y'),
// "n_credito" => $item->N_Credito ,
"nota_venta" => $item->NotaVenta,
"cotizacion" => $item->cotizacion,
"f_impt" => $item->F_Impt,
"f_emis" => $item->F_Emis,
"f_venc" => $item->F_Venc,
"rut_recep" => $item->RutRecep,
"id_erp" => $item->id_erp,
"rzn_soc_recep" => $item->RznSocRecep,
"lineas" => $item->Lineas,
"cve_des" => $item->CveDes,
"venta_item" => $this->moneyFormat($item->Venta_Item),
"desc" => $this->moneyFormat($item->Desc),
"mnt_exe" => $this->moneyFormat($item->MntExe),
"neto" => $this->moneyFormat($item->Neto),
"iva" => $this->moneyFormat($item->IVA),
"total" => $this->moneyFormat($item->Total),
"pendiente" => $this->moneyFormat($item->Pendiente),
"estado" => $item->Estado,
"dias_vencido" => $item->Dias_Vencido,
"file" => $this->generateUrl('data_bill_pdf', ['folio' => $item->Factura]),
];
}
usort($data, function ($a, $b) {
$dateA = DateTime::createFromFormat('d/m/Y', $a['date']);
$dateB = DateTime::createFromFormat('d/m/Y', $b['date']);
return $dateB <=> $dateA; // Orden ascendente
});
return $this->json($data);
}
private function moneyFormat($value)
{
return '$' . number_format((int)$value, 0, null, '.');
}
/**
* @Route("/data/bill_pdf/{folio}", name="data_bill_pdf")
*/
public function getFacturaFile(Request $request, $folio)
{
$session = $request->getSession();
$id_client = $request->query->get('id');
$id_client = $request->query->get('id');
$pdf_64 = $this->apiConsumer->getFacturaPDF($session->get('user_password_hash'), $folio);
$pdfContent = base64_decode($pdf_64);
if ($pdfContent === false) {
return new Response("Error al decodificar el PDF.", Response::HTTP_INTERNAL_SERVER_ERROR);
}
// Retornar el PDF directamente en la respuesta HTTP
return new Response($pdfContent, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="factura-' . $folio . '.pdf"',
]);
}
/**
* @Route("/data/report.json", name="data_report")
* @Route("/data/report_json", name="data_report2")
*/
public function dataReportAction(Request $request): \Symfony\Component\HttpFoundation\JsonResponse
{
$session = $request->getSession();
$id_client = $request->query->get('id');
$report = $this->apiConsumer->getPowerBIList($session->get('user_password_hash'));
$data = [];
foreach ($report as $item) {
$data[] =
[
"id_registro" => $item->id_registro,
"create_date" => $item->crea_date,
"create_oper" => $item->crea_oper,
"id_usuario" => $item->id_usuario,
"Descripc" => $item->Descripc,
"Estado" => $item->Estado,
"URLs" => $item->URLs,
"OrderBy" => $item->OrdenBy,
"Intervalo" => $item->Intervalo,
"URLsParametro" => $item->URLsParametro,
];
}
return $this->json($data);
}
}