Añadidas mejoras propuestas por Manolo a la importacion de RAMA

This commit is contained in:
Ignacio Martinez Navajas
2025-05-05 20:13:59 +02:00
parent bf146d4024
commit 10b5ae911a
2 changed files with 53 additions and 21 deletions

View File

@ -3,6 +3,7 @@ namespace App\Controllers\Importadores;
use App\Controllers\BaseResourceController; use App\Controllers\BaseResourceController;
use App\Entities\Catalogo\CatalogoLibroEntity; use App\Entities\Catalogo\CatalogoLibroEntity;
use App\Models\Presupuestos\PresupuestoModel;
use App\Models\Catalogo\CatalogoLibroModel; use App\Models\Catalogo\CatalogoLibroModel;
use App\Controllers\Presupuestos\Presupuestocliente; use App\Controllers\Presupuestos\Presupuestocliente;
use App\Services\PresupuestoService; use App\Services\PresupuestoService;
@ -58,37 +59,51 @@ class ImportadorCatalogo extends BaseResourceController
{ {
$json = $this->request->getJSON(); $json = $this->request->getJSON();
if (!$json || !isset($json->fila[0])) { // Validación inicial del JSON y del ISBN
if (!$json || !isset($json->fila[0]) || empty(trim($json->fila[0]))) {
return $this->response->setJSON([ return $this->response->setJSON([
'apto' => false, 'apto' => false,
'reason' => 'Datos inválidos' 'reason' => 'ISBN no proporcionado o datos inválidos'
]); ]);
} }
$input = trim($json->fila[0]); // Asumimos que 'input' es el primer campo de la fila $input = trim($json->fila[0]); // ISBN
$refCliente = isset($json->fila[1]) ? trim($json->fila[1]) : null;
if (empty($input)) { // Validar formato del refCliente (esperado: idpedido-idlinea)
if (empty($refCliente) || strpos($refCliente, '-') === false) {
return $this->response->setJSON([ return $this->response->setJSON([
'apto' => false, 'apto' => false,
'reason' => 'ISBN no proporiconado' 'reason' => 'Ref. cliente inválido'
]);
}
// 1. Comprobar duplicado en tabla de presupuestos
$presupuestoModel = new PresupuestoModel(); // Usa el modelo real que corresponda
$yaExiste = $presupuestoModel->where('referencia_cliente', $refCliente)->first();
if ($yaExiste) {
return $this->response->setJSON([
'apto' => false,
'reason' => 'Referencia ya importada'
]); ]);
} }
$catalogoModel = new CatalogoLibroModel(); $catalogoModel = new CatalogoLibroModel();
// 1. Buscar por ISBN exacto // 2. Buscar por ISBN exacto
$libroPorIsbn = $catalogoModel->where('isbn', $input)->first(); $libroPorIsbn = $catalogoModel->where('isbn', $input)->first();
if ($libroPorIsbn) { if ($libroPorIsbn) {
return $this->response->setJSON([ return $this->response->setJSON([
'apto' => true 'apto' => true
]); ]);
} }
// 2. Buscar por EAN sin guiones // 3. Buscar por EAN sin guiones
$eanLimpio = str_replace('-', '', $input); $eanLimpio = str_replace('-', '', $input);
$libroPorEan = $catalogoModel
$libroPorEan = $catalogoModel->where('REPLACE(ean, "-", "")', $eanLimpio)->first(); ->where('REPLACE(ean, "-", "")', $eanLimpio, false) // false para evitar escapado automático
->first();
if ($libroPorEan) { if ($libroPorEan) {
return $this->response->setJSON([ return $this->response->setJSON([
@ -96,7 +111,7 @@ class ImportadorCatalogo extends BaseResourceController
]); ]);
} }
// No encontrado // 4. No encontrado
return $this->response->setJSON([ return $this->response->setJSON([
'apto' => false, 'apto' => false,
'reason' => 'No encontrado en catálogo' 'reason' => 'No encontrado en catálogo'
@ -105,6 +120,7 @@ class ImportadorCatalogo extends BaseResourceController
public function importarFila() public function importarFila()
{ {
$json = $this->request->getJSON(); $json = $this->request->getJSON();
@ -248,11 +264,11 @@ class ImportadorCatalogo extends BaseResourceController
'entrega_taller' => 1, 'entrega_taller' => 1,
]; ];
return $this->response->setJSON([ /*return $this->response->setJSON([
'success' => true, 'success' => true,
'message' => 'Libro encontrado y preparado para importar.', 'message' => 'Libro encontrado y preparado para importar.',
'data' => $dataToImport 'data' => $dataToImport
]); ]);*/
// Procedemos a intentar guardar el presupuesto // Procedemos a intentar guardar el presupuesto

View File

@ -57,7 +57,8 @@ document.addEventListener('DOMContentLoaded', function () {
headerMap[name.toLowerCase()] = idx; headerMap[name.toLowerCase()] = idx;
}); });
const missing = TABLE_COLUMNS.filter(col => !(col in headerMap)); const requiredColumns = ["idpedido", ...TABLE_COLUMNS];
const missing = requiredColumns.filter(col => !(col in headerMap));
if (missing.length > 0) { if (missing.length > 0) {
Swal.fire({ Swal.fire({
title: 'Error', title: 'Error',
@ -73,7 +74,19 @@ document.addEventListener('DOMContentLoaded', function () {
const rows = []; const rows = [];
for (let i = 1; i < data.length; i++) { for (let i = 1; i < data.length; i++) {
const rowData = TABLE_COLUMNS.map(col => data[i][headerMap[col]] ?? ''); // Leer columnas necesarias desde Excel
const input = data[i][headerMap["input"]] ?? '';
const idlinea = data[i][headerMap["idlinea"]] ?? '';
const idpedido = data[i][headerMap["idpedido"]] ?? ''; // aunque no esté en TABLE_COLUMNS, lo usamos aquí
const descripcion = data[i][headerMap["descripcion"]] ?? '';
const cnt_pedida = data[i][headerMap["cnt_pedida"]] ?? '';
const precio_compra = data[i][headerMap["precio_compra"]] ?? '';
// Componer Ref. Cliente
const refCliente = `${idpedido}-${idlinea}`;
// Solo mostramos las columnas necesarias (como en el orden de DataTable HTML)
const rowData = [input, refCliente, descripcion, cnt_pedida, precio_compra];
// Llamar backend para validar la fila // Llamar backend para validar la fila
const result = await validarFila(rowData); const result = await validarFila(rowData);
@ -163,7 +176,8 @@ document.addEventListener('DOMContentLoaded', function () {
// Actualizar campo "Notas" con el enlace // Actualizar campo "Notas" con el enlace
if (skUrl) { if (skUrl) {
const notasHtml = `<a href="${skUrl}" target="_blank" class="btn btn-sm btn-secondary">Ver presupuesto</a>`; const skId = result.data?.sk_id ?? '';
const notasHtml = `<a href="${skUrl}" target="_blank" class="btn btn-sm btn-secondary">Ver presupuesto (${skId})</a>`;
// La columna de notas es la posición 6 (índice 6) // La columna de notas es la posición 6 (índice 6)
rowData[6] = notasHtml; rowData[6] = notasHtml;
dataTable.row($row).data(rowData).draw(false); // Redibujar la fila SIN perder scroll ni filtros dataTable.row($row).data(rowData).draw(false); // Redibujar la fila SIN perder scroll ni filtros
@ -176,7 +190,7 @@ document.addEventListener('DOMContentLoaded', function () {
if (result.price_warning) { if (result.price_warning) {
html = skUrl ? `La fila se importó exitosamente, pero el precio se ha ajustado debajo de costes.<br><br><a href="${skUrl}" target="_blank" class="btn btn-primary mt-2">Ver presupuesto</a>` html = skUrl ? `La fila se importó exitosamente, pero el precio se ha ajustado debajo de costes.<br><br><a href="${skUrl}" target="_blank" class="btn btn-primary mt-2">Ver presupuesto</a>`
: 'La fila se importó exitosamente, pero el precio se ha ajustado debajo de costes.'; : 'La fila se importó exitosamente, pero el precio se ha ajustado debajo de costes.';
icon = 'warning'; icon = 'warning';
} }
@ -284,10 +298,12 @@ document.addEventListener('DOMContentLoaded', function () {
idsNoAjustados.push(result.data.sk_id); idsNoAjustados.push(result.data.sk_id);
} }
const skId = result.data?.sk_id ?? '';
if (skUrl) { if (skUrl) {
fila.rowData[6] = `<a href="${skUrl}" target="_blank" class="btn btn-sm btn-primary">Ver presupuesto</a>`; fila.rowData[6] = `<a href="${skUrl}" target="_blank" class="btn btn-sm btn-primary">Ver presupuesto (${skId})</a>`;
} else { } else {
fila.rowData[6] = `<span class="badge bg-success">Importado</span>`; fila.rowData[6] = `<span class="badge bg-success">Importado (${skId})</span>`;
} }
} else { } else {
fila.rowData[6] = `<span class="badge bg-danger">${result.message ?? 'Error desconocido'}</span>`; fila.rowData[6] = `<span class="badge bg-danger">${result.message ?? 'Error desconocido'}</span>`;