/* ════════════════════════════════════════════════════════════ FACTURACIÓN — módulo dentro de Envasado y Empaque ──────────────────────────────────────────────────────────── 5 sub-pestañas: Inventario · Catálogo · Nueva factura · Historial · Trazabilidad. Sigue el mismo patrón de guardado en la nube que el resto de la app (callApi + API_URL pasados como props desde App). Decisión de formato para plantillas/importación: CSV plano (sin librerías externas) en vez de XLSX vía SheetJS — es más simple, no agrega dependencias nuevas y cubre el caso de uso (código, nombre, lote, cantidad / presentación, código, nombre, CPE, vencimiento, peso neto). Si en el futuro hace falta soportar archivos .xlsx reales, SheetJS ya está disponible en backorden/index.php con la misma versión de CDN permitida. ════════════════════════════════════════════════════════════ */ const { useState: fctUseState, useEffect: fctUseEffect, useRef: fctUseRef, useMemo: fctUseMemo } = React; const FACT_PRESENTACIONES = ['Galón', 'Cuñete 5GL', 'Cuñete 4GL', 'Cuñete 2GL', 'Cuartico', 'Litro', '4 Litros', 'Otro']; const FACT_STOCK_BAJO = 50; // umbral "Bajo" (ajustable); 0 = Agotado // Equivalencia en litros de cada presentación (galones venezolanos ≈ 3.785 L), // para poder inferirla a partir del peso neto que devuelve SENCAMER cuando // viene en litros. Con 8% de tolerancia porque el peso real de un envase // varía un poco entre marcas/lotes. const FACT_PRES_LITROS = { 'Galón': 3.785, 'Cuñete 5GL': 18.925, 'Cuñete 4GL': 15.14, 'Cuñete 2GL': 7.57, 'Cuartico': 0.946, 'Litro': 1, '4 Litros': 4 }; function factInferPresentacion(pesoNeto, unidad) { const u = String(unidad || '').trim().toUpperCase(); if (!['L', 'LT', 'LTS', 'LITRO', 'LITROS'].includes(u)) return ''; const litros = Number(pesoNeto); if (!litros || litros <= 0) return ''; let best = '', bestDiff = Infinity; Object.entries(FACT_PRES_LITROS).forEach(([nombre, ref]) => { const diff = Math.abs(litros - ref) / ref; if (diff < bestDiff) { bestDiff = diff; best = nombre; } }); return bestDiff <= 0.08 ? best : ''; } const factUid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7); // Fecha de hoy según el reloj calibrado contra el servidor (todayStr de // components.jsx, exportado en window). Solo si no existe se usa el reloj local. const factToday = () => { try { if (typeof window !== 'undefined' && typeof window.todayStr === 'function') return window.todayStr(); } catch (_) {} const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; }; const factNum = (n) => Number(n || 0).toLocaleString('es-VE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); // Escapa TODO dato interpolado en HTML (texto y atributos, incluidas comillas). const factEsc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); // Número tolerante a decimales con coma: "3,78" → 3.78; "1.234,56" → 1234.56; // "1,234.56" → 1234.56. Vacío → null; no numérico → NaN. function factParseNumber(v) { if (typeof v === 'number') return Number.isFinite(v) ? v : NaN; let s = String(v == null ? '' : v).trim().replace(/\s+/g, ''); if (s === '') return null; const hasC = s.includes(','), hasD = s.includes('.'); if (hasC && hasD) { // el último separador es el decimal; el otro es de miles if (s.lastIndexOf(',') > s.lastIndexOf('.')) s = s.replace(/\./g, '').replace(',', '.'); else s = s.replace(/,/g, ''); } else if (hasC) { s = s.split(',').length === 2 ? s.replace(',', '.') : s.replace(/,/g, ''); } if (!/^[+-]?(\d+\.?\d*|\.\d+)$/.test(s)) return NaN; const n = Number(s); return Number.isFinite(n) ? n : NaN; } // Fecha YYYY-MM-DD (acepta también DD/MM/YYYY y la convierte); '' si no es válida. function factNormDate(v) { const s = String(v == null ? '' : v).trim(); let y, m, d, mt; if ((mt = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})/))) { y = +mt[1]; m = +mt[2]; d = +mt[3]; } else if ((mt = s.match(/^(\d{1,2})[\/-](\d{1,2})[\/-](\d{4})$/))) { d = +mt[1]; m = +mt[2]; y = +mt[3]; } else return ''; const dt = new Date(Date.UTC(y, m - 1, d)); if (dt.getUTCFullYear() !== y || dt.getUTCMonth() !== m - 1 || dt.getUTCDate() !== d) return ''; return `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`; } // Mensaje legible para un error del servidor (ApiError de app.jsx: status/message/data). function factErrMsg(err, fallback) { let blob = ''; try { blob = `${err?.message || ''} ${JSON.stringify(err?.data || '')}`; } catch (_) { blob = String(err?.message || ''); } if (/delete_key_invalid/i.test(blob)) return 'Clave de eliminación incorrecta. No se eliminó nada.'; if (/delete_key_not_configured/i.test(blob)) return 'No se eliminó: un administrador debe crear primero la clave de eliminación (Usuarios).'; if (err?.status === 403) return 'No tienes permiso para esta operación (o la clave de seguridad es incorrecta).'; if (err?.status === 401) return 'La sesión expiró. Vuelve a iniciar sesión.'; const m = (err?.data && (err.data.error || err.data.message)) || err?.message; return m ? `${fallback ? fallback + ': ' : ''}${m}` : (fallback || 'Error del servidor'); } // ── CSV mínimo (sin librerías) ────────────────────────────── function factToCSV(headers, rows) { const esc = (v) => { const s = v == null ? '' : String(v); return /[",;\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; }; const lines = [headers.map(esc).join(',')]; rows.forEach(r => lines.push(headers.map(h => esc(r[h])).join(','))); return lines.join('\r\n'); } // Devuelve una matriz (primera fila = encabezados tal cual). Acepta , o ; (autodetectado) y comillas. function factParseCSVMatrix(text) { const lines = String(text || '').replace(/^\uFEFF/, '').split(/\r?\n/).filter(l => l.trim() !== ''); if (!lines.length) return []; // El delimitador se decide UNA vez por archivo según el encabezado (; si hay // más ; que , — típico de Excel en español); así "3,78" sin comillas en un // archivo con ; se conserva como decimal en vez de partirse en dos celdas. const head = lines[0].replace(/"[^"]*"/g, ''); const delim = (head.split(';').length - 1) > (head.split(',').length - 1) ? ';' : ','; const splitLine = (line) => { const out = []; let cur = ''; let inQ = false; for (let i = 0; i < line.length; i++) { const c = line[i]; if (inQ) { if (c === '"') { if (line[i + 1] === '"') { cur += '"'; i++; } else inQ = false; } else cur += c; } else { if (c === '"') inQ = true; else if (c === delim) { out.push(cur); cur = ''; } else cur += c; } } out.push(cur); return out.map(s => s.trim()); }; return lines.map(splitLine); } // Filas como objetos con encabezados en minúsculas y sin acentos ("Código" → "codigo"). function factParseCSV(text) { const matrix = factParseCSVMatrix(text); if (!matrix.length) return []; const headers = matrix[0].map(h => h.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim()); return matrix.slice(1).map(cells => { const row = {}; headers.forEach((h, i) => { row[h] = cells[i] != null ? cells[i] : ''; }); return row; }); } function factDownload(filename, content, mime = 'text/csv;charset=utf-8') { try { const blob = new Blob(['' + content], { type: mime }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(url), 4000); } catch (e) { window.alert('No se pudo generar el archivo: ' + (e?.message || e)); } } function factStockState(cantidad) { const n = Number(cantidad || 0); if (n <= 0) return { key: 'agotado', label: 'Agotado', cls: 'fct-badge-rd' }; if (n < FACT_STOCK_BAJO) return { key: 'bajo', label: 'Bajo', cls: 'fct-badge-or' }; return { key: 'ok', label: 'OK', cls: 'fct-badge-gn' }; } // Reporte imprimible de factura — mismo estilo de membrete que // buildDailyPlanReport (app.jsx) / reportes de Back Orden. function factBuildInvoiceReport(factura) { let logoUrl = 'logo-verona.png'; try { logoUrl = new URL('logo-verona.png', document.baseURI).href; } catch (_) {} const esc = factEsc; const items = factura.items || []; const sub = (it) => { const v = Number(it.cantidad || 0) * Number(it.precio || 0); return Number.isFinite(v) ? v : 0; }; const totalCalc = items.reduce((s, it) => s + sub(it), 0); const rows = items.map((it, i) => ` ${esc(it.codigo)} ${esc(it.descripcion)} ${esc(it.lote)} ${factNum(it.cantidad)} ${factNum(it.precio)} ${factNum(sub(it))} `).join(''); return `Factura ${esc(factura.numero)}
Verona Color Paints
FACTURA N° ${esc(factura.numero)}
Fecha: ${esc(factura.fecha)}
Vence: ${esc(factura.vence) || '—'}
Cond. de pago: ${esc(factura.condicion_pago) || '—'}
Cliente: ${esc(factura.cliente)}
RIF: ${esc(factura.rif)}
Dirección: ${esc(factura.direccion)}
Vendedor: ${esc(factura.vendedor)}
${rows}
Código Descripción Lote Cant. Precio Subtotal
TOTAL ${factNum(totalCalc)}
Sistema de Planificación — VERONA COLOR PAINTS
`; } // Impreso de ORDEN DE ENTREGA (Departamento de Envasado → Departamento de // Producción). Sin precios: código, descripción, lote y cantidad, con firmas. function factBuildOrdenReport(orden) { let logoUrl = 'logo-verona.png'; try { logoUrl = new URL('logo-verona.png', document.baseURI).href; } catch (_) {} const esc = factEsc; const items = orden.items || []; const totalUnidades = items.reduce((s, it) => s + (Number(it.cantidad) || 0), 0); const th = (t, align) => `${t}`; const rows = items.map((it, i) => ` ${i + 1} ${esc(it.codigo)} ${esc(it.descripcion)} ${esc(it.lote)} ${factNum(it.cantidad)} `).join(''); const firma = (titulo, depto) => `
${titulo}
${depto}
Nombre: ____________________________
Fecha: ______ / ______ / __________
`; const devuelta = orden.estado === 'devuelta'; return `Orden de entrega ${esc(orden.numero)}
Verona Color Paints
ORDEN DE ENTREGA N° ${esc(orden.numero)}
${devuelta ? '
DEVUELTA — la mercancía regresó al inventario
' : ''}
Fecha: ${esc(orden.fecha)}
Facturador: ${esc(orden.facturador) || '—'}
Entrega
Departamento de Envasado
→
Recibe
Departamento de Producción
${orden.observacion ? `
Observación: ${esc(orden.observacion)}
` : ''} ${th('#', 'center')}${th('Código')}${th('Descripción')}${th('Lote')}${th('Cantidad', 'right')}${rows}
TOTAL UNIDADES (${items.length} renglón${items.length === 1 ? '' : 'es'}) ${factNum(totalUnidades)}
${firma('Entregado por', 'Departamento de Envasado')} ${firma('Recibido por', 'Departamento de Producción')}
Sistema de Planificación — VERONA COLOR PAINTS
`; } // Elige el impreso según el tipo: las facturas viejas se imprimen como antes. function factBuildDocReport(doc) { return (doc && doc.tipo === 'factura') ? factBuildInvoiceReport(doc) : factBuildOrdenReport(doc); } // Reporte diario de facturación — suma lo facturado en una fecha, agrupado // por presentación (Galón, Cuñete 5GL, Cuartico...). Mismo estilo visual // que el reporte diario de Control de Proceso (buildDailyPlanReport). function factBuildDailyReport(data) { let logoUrl = 'logo-verona.png'; try { logoUrl = new URL('logo-verona.png', document.baseURI).href; } catch (_) {} const esc = factEsc; const [y, m, d] = (data.fecha || '').split('-'); const months = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre']; const dateStr = esc((y && m && d && months[parseInt(m, 10) - 1]) ? `${d} de ${months[parseInt(m, 10) - 1]} de ${y}` : (data.fecha || '')); const now = new Date(); const nowStr = `${now.getDate().toString().padStart(2, '0')}/${(now.getMonth() + 1).toString().padStart(2, '0')}/${now.getFullYear()} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`; const presentaciones = data.presentaciones || []; const facturas = data.facturas || []; const card = (num, label) => `
${num}
${label}
`; const presRows = presentaciones.map((p, i) => ` ${esc(p.presentacion)} ${factNum(p.facturas)} ${factNum(p.cantidad)} `).join('') || `Sin órdenes en esta fecha.`; const facturaRows = facturas.map((f, i) => ` ${esc(f.numero)} ${esc(f.facturador || f.vendedor)} ${esc(f.observacion || f.cliente)} ${factNum(f.unidades)} `).join(''); return `Reporte diario de órdenes de entrega ${esc(data.fecha)}
Verona Color Paints
REPORTE DIARIO DE ÓRDENES DE ENTREGA — ${dateStr}
Generado: ${nowStr}
Fecha: ${esc(data.fecha)}
${card(facturas.length, 'Órdenes emitidas')} ${card(presentaciones.length, 'Presentaciones distintas')} ${card(factNum(data.total_cantidad), 'Unidades totales')}

Totales por presentación

${presRows}
Presentación Órdenes Cantidad total

Órdenes del día

${facturaRows || ``}
N° Facturador Observación Unidades
Sin órdenes.
Sistema de Planificación — VERONA COLOR PAINTS
`; } function factPrint(html) { let win = null; try { win = window.open('', '_blank'); } catch (_) { win = null; } if (!win) { window.alert('Permita las ventanas emergentes para imprimir'); return false; } try { win.document.write(html); win.document.close(); } catch (e) { window.alert('No se pudo preparar la impresión: ' + (e?.message || e)); return false; } setTimeout(() => { try { win.focus(); win.print(); } catch (_) {} }, 300); return true; } // ════════════════════════════════════════════════════════════ // Componente principal // ════════════════════════════════════════════════════════════ function FacturacionPage({ callApi, apiUrl, showToast, onBack }) { const [tab, setTab] = fctUseState('inventario'); const [catalog, setCatalog] = fctUseState([]); const [clases, setClases] = fctUseState([]); const [inventory, setInventory] = fctUseState([]); const [invoices, setInvoices] = fctUseState([]); const [loading, setLoading] = fctUseState(true); const [pendingLines, setPendingLines] = fctUseState(null); // renglones pre-cargados desde "Facturar seleccionados" const toast = (msg, type) => { if (showToast) showToast(msg, type); }; const loadAll = async () => { setLoading(true); try { const [c, cl, i, f] = await Promise.all([ callApi(`${apiUrl}?action=fact_catalogo_get`, {}, 'catálogo de facturación'), callApi(`${apiUrl}?action=fact_clases_get`, {}, 'clases del catálogo'), callApi(`${apiUrl}?action=fact_inventario_get`, {}, 'inventario de facturación'), callApi(`${apiUrl}?action=fact_factura_list`, {}, 'historial de facturas'), ]); setCatalog(c.data || []); setClases(cl.data || []); setInventory(i.data || []); setInvoices(f.data || []); } catch (err) { toast(factErrMsg(err, 'No se pudieron cargar los datos de facturación'), 'err'); } setLoading(false); }; fctUseEffect(() => { loadAll(); }, []); const refreshInventory = async () => { try { const r = await callApi(`${apiUrl}?action=fact_inventario_get`, {}, 'inventario'); setInventory(r.data || []); } catch (_) {} }; const refreshInvoices = async () => { try { const r = await callApi(`${apiUrl}?action=fact_factura_list`, {}, 'historial de facturas'); setInvoices(r.data || []); } catch (_) {} }; const refreshCatalog = async () => { try { const r = await callApi(`${apiUrl}?action=fact_catalogo_get`, {}, 'catálogo'); setCatalog(r.data || []); } catch (_) {} }; const refreshClases = async () => { try { const r = await callApi(`${apiUrl}?action=fact_clases_get`, {}, 'clases del catálogo'); setClases(r.data || []); } catch (_) {} }; // Orden abierta en la ventana de detalle (id) y producto a mostrar en // Trazabilidad: permiten saltar de un apartado a otro con un clic. const [ordenAbierta, setOrdenAbierta] = fctUseState(null); const [trazaTarget, setTrazaTarget] = fctUseState(null); // { codigo, nombre, lote, n } const openOrden = (id) => { if (id) setOrdenAbierta(id); }; const goTraza = (codigo, nombre, lote) => { setOrdenAbierta(null); setTrazaTarget({ codigo, nombre: nombre || '', lote: lote == null ? null : lote, n: Date.now() }); setTab('trazabilidad'); }; const TABS = [ ['inventario', 'Inventario'], ['catalogo', 'Catálogo'], ['nueva', 'Nueva orden'], ['historial', 'Órdenes'], ['trazabilidad', 'Trazabilidad'], ]; return (

Facturación · Órdenes de entrega

{TABS.map(([k, label]) => ( ))}
{ordenAbierta && ( setOrdenAbierta(null)} onGoTraza={goTraza} onChanged={() => { refreshInvoices(); refreshInventory(); }} /> )}
{loading ? (
⏳

Cargando datos de facturación…

) : ( {tab === 'inventario' && ( { setPendingLines(lines); setTab('nueva'); }} onGoTraza={goTraza} /> )} {tab === 'catalogo' && ( )} {tab === 'nueva' && ( setPendingLines(null)} onSaved={() => { refreshInventory(); refreshInvoices(); }} onOpenOrden={openOrden} /> )} {tab === 'historial' && ( )} {tab === 'trazabilidad' && ( )} )}
); } // ── INVENTARIO ────────────────────────────────────────────── const fctBlankInventarioRow = () => ({ uid: factUid(), codigo: '', nombre: '', lote: '', cantidad: '' }); // Buscador con autocompletar para elegir un producto del catálogo por // código o nombre, en vez de un setOpen(true)} onChange={e => setQuery(e.target.value)} onBlur={() => setTimeout(() => setOpen(false), 120)} /> {selected && ( )} {open && !selected && (
{results.length === 0 &&
Sin resultados
} {results.map(c => (
{ e.preventDefault(); pick(c); }}> {c.codigo} — {c.nombre_comercial || c.nombre || '(sin nombre)'}
))} {catalog.length > FCT_PICKER_MAX_RESULTS && results.length === FCT_PICKER_MAX_RESULTS && (
Sigue escribiendo para acotar la búsqueda…
)}
)} ); } function FctInventarioTab({ inventory, catalog, callApi, apiUrl, toast, onChanged, onFacturarSeleccionados, onGoTraza }) { const [q, setQ] = fctUseState(''); const [selected, setSelected] = fctUseState({}); const [showForm, setShowForm] = fctUseState(false); const [rows, setRows] = fctUseState([fctBlankInventarioRow()]); const fileRef = fctUseRef(null); const setRow = (uid, patch) => setRows(rs => rs.map(r => (r.uid === uid ? { ...r, ...patch } : r))); const addRow = () => setRows(rs => [...rs, fctBlankInventarioRow()]); const removeRow = (uid) => setRows(rs => (rs.length > 1 ? rs.filter(r => r.uid !== uid) : rs)); // Palabras sueltas, no necesariamente en el orden del nombre. const queryWords = q.trim().toLowerCase().split(/\s+/).filter(Boolean); // Un lote en 0 ya no sirve para facturar (es pintura: cada lote es un // ítem aparte, no se mezclan) — se oculta por defecto para no ensuciar // la lista, con opción de verlos si hace falta revisar el historial. const [showAgotados, setShowAgotados] = fctUseState(false); const filtered = inventory.filter(r => (showAgotados || Number(r.cantidad || 0) > 0) && (!queryWords.length || queryWords.every(w => `${r.codigo || ''} ${r.nombre || ''} ${r.lote || ''}`.toLowerCase().includes(w))) ); // Solo cuentan las filas VISIBLES (no se factura algo oculto por el filtro). const selectedIds = filtered.filter(r => selected[r.id]).map(r => r.id); const toggle = (id) => setSelected(s => ({ ...s, [id]: !s[id] })); const clearSelection = () => setSelected({}); const handleTemplate = () => { factDownload('plantilla_inventario.csv', factToCSV(['codigo', 'nombre', 'lote', 'cantidad'], [ { codigo: 'PRD-001', nombre: 'Ejemplo Producto', lote: 'L-2026-01', cantidad: '100' }, ])); }; const handleImport = async (e) => { const file = e.target.files?.[0]; if (!file) return; try { const text = await file.text(); let malas = 0; const rows = factParseCSV(text) .map(r => ({ codigo: (r.codigo || '').trim(), nombre: (r.nombre || '').trim(), lote: (r.lote || '').trim(), cantidad: factParseNumber(r.cantidad) })) .filter(r => r.codigo) .filter(r => { if (r.cantidad == null || Number.isNaN(r.cantidad) || r.cantidad < 0) { malas++; return false; } return true; }); if (malas) toast(`${malas} fila(s) omitida(s): cantidad vacía, no numérica o negativa`, 'err'); if (!rows.length) { toast('El archivo no tiene filas válidas', 'err'); if (fileRef.current) fileRef.current.value = ''; return; } const res = await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_inventario_import', items: rows }), }, 'importar inventario'); toast(`Inventario importado: ${res.imported || rows.length} fila(s) (sumadas al stock existente)`); onChanged(); } catch (err) { toast(factErrMsg(err, 'No se pudo importar el inventario'), 'err'); } if (fileRef.current) fileRef.current.value = ''; }; const handleAdd = async () => { const items = rows .filter(r => r.codigo.trim()) .map(r => ({ codigo: r.codigo.trim(), nombre: r.nombre.trim(), lote: r.lote.trim(), cantidad: Number(r.cantidad || 0) })); if (!items.length) { toast('Selecciona al menos un producto del catálogo', 'err'); return; } if (items.some(i => !Number.isFinite(i.cantidad) || i.cantidad <= 0)) { toast('Cada entrada necesita una cantidad mayor a 0', 'err'); return; } try { const res = await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_inventario_import', origen: 'manual', items }), }, 'agregar entradas de inventario'); toast(`${res.imported || items.length} entrada(s) agregada(s) al inventario`); setRows([fctBlankInventarioRow()]); setShowForm(false); onChanged(); } catch (_) {} }; const handleDelete = async (row) => { if (!window.verifyDeleteKey(`¿Eliminar la entrada de inventario "${row.codigo}" (lote ${row.lote || '—'})?`)) return; try { await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_inventario_delete', id: row.id }), }, 'eliminar entrada de inventario'); toast('Entrada eliminada'); onChanged(); } catch (err) { toast(factErrMsg(err, 'No se pudo eliminar la entrada'), 'err'); } }; // Corrige lote/cantidad de una entrada ya guardada (p. ej. un error al // tipear). No toca facturas ya emitidas — cada línea de factura guarda su // propio lote/cantidad como una foto independiente de este inventario. const [editRow, setEditRow] = fctUseState(null); // { id, codigo, lote, cantidad } const startEdit = (row) => setEditRow({ id: row.id, codigo: row.codigo, lote: row.lote || '', cantidad: String(row.cantidad ?? ''), motivo: '' }); const saveEdit = async () => { const cant = factParseNumber(editRow.cantidad); if (cant == null || Number.isNaN(cant) || cant < 0) { toast('La cantidad debe ser un número igual o mayor a 0', 'err'); return; } try { await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_inventario_edit', id: editRow.id, lote: editRow.lote, cantidad: cant, motivo: String(editRow.motivo || '').trim() }), }, 'editar entrada de inventario'); toast('Entrada actualizada'); setEditRow(null); onChanged(); } catch (err) { toast(factErrMsg(err, 'No se pudo actualizar la entrada'), 'err'); } }; const facturarSeleccionados = () => { const rows = filtered.filter(r => selected[r.id]); if (!rows.length) return; const lines = rows.map(r => ({ id: factUid(), codigo: r.codigo, descripcion: r.nombre, lote: r.lote || '', disponible: Number(r.cantidad || 0), cantidad: '', })); onFacturarSeleccionados(lines); clearSelection(); }; return (
setQ(e.target.value)} />
{showForm && (
{catalog.length === 0 && (

El catálogo está vacío — agrega productos en la pestaña "Catálogo" primero.

)} {rows.map(r => (
setRow(r.uid, { codigo, nombre })} /> setRow(r.uid, { lote: e.target.value })} /> setRow(r.uid, { cantidad: e.target.value })} />
))}
)} {editRow && (
Editando {editRow.codigo}: setEditRow({ ...editRow, lote: e.target.value })} /> setEditRow({ ...editRow, cantidad: e.target.value })} /> setEditRow({ ...editRow, motivo: e.target.value })} />
)}
{filtered.map(r => { const st = factStockState(r.cantidad); return ( ); })} {!filtered.length && ( )}
CódigoNombreLoteCantidadÚltima actualizaciónEstado
toggle(r.id)} aria-label={`Seleccionar ${r.codigo}`} /> {r.nombre} {r.lote || '—'} {factNum(r.cantidad)} {(r.updated_at || '').slice(0, 16).replace('T', ' ')} {st.label}
Sin resultados.
{selectedIds.length > 0 && (
{selectedIds.length} producto{selectedIds.length !== 1 ? 's' : ''} seleccionado{selectedIds.length !== 1 ? 's' : ''}
)}
); } // ── CATÁLOGO ──────────────────────────────────────────────── function FctCatalogoTab({ catalog, clases, callApi, apiUrl, toast, onChanged, onClasesChanged }) { const [q, setQ] = fctUseState(''); const [claseFilter, setClaseFilter] = fctUseState(''); const [showForm, setShowForm] = fctUseState(false); const [showClases, setShowClases] = fctUseState(false); const [nuevaClase, setNuevaClase] = fctUseState(''); const [form, setForm] = fctUseState({ presentacion: FACT_PRESENTACIONES[0], codigo: '', nombre: '', nombre_comercial: '', cpe: '', cpe_vencimiento: '', cpe_estatus: '', marca: '', tipo_envase: '', clase: '', peso_neto: '', }); const fileRef = fctUseRef(null); const codesFileRef = fctUseRef(null); const [dragOver, setDragOver] = fctUseState(false); const [importingCodes, setImportingCodes] = fctUseState(false); const [cpeCheck, setCpeCheck] = fctUseState({ status: 'idle', unidad: '' }); // idle | checking | found | notfound // Selección múltiple — para deshacer en un click una importación masiva // equivocada (borrar uno por uno cientos de filas no es viable). const [selected, setSelected] = fctUseState({}); const toggleSelected = (codigo) => setSelected(s => ({ ...s, [codigo]: !s[codigo] })); const clearSelection = () => setSelected({}); // Orden por columna (clic en el encabezado), dentro de cada grupo de clase. const [sortBy, setSortBy] = fctUseState(null); const [sortDir, setSortDir] = fctUseState('asc'); // Encuentra, entre los encabezados de una fila, la columna que mejor // coincide con "código" o "nombre" — flexible porque una lista externa // (como un Excel de ventas) rara vez usa los nombres exactos de la // plantilla interna ("codigo", "nombre_comercial"). // Primero busca una coincidencia EXACTA (p. ej. columna "Codigo") antes de // caer a "contiene la palabra" — si no, un encabezado como "Nombre // comercial y codigo" hace match con ambas búsquedas (nombre y código) y // termina usando el mismo texto para las dos columnas. const findColumn = (headers, matches, exclude = -1) => { const norm = (s) => String(s || '').toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').trim(); const exact = headers.findIndex((h, i) => i !== exclude && matches.includes(norm(h))); if (exact !== -1) return exact; return headers.findIndex((h, i) => i !== exclude && matches.some(m => norm(h).includes(m))); }; // Importa una lista simple de "código + nombre" (ej. un listado de ventas // en Excel) al catálogo, dejando el resto de los campos (CPE, marca, etc.) // vacíos para completarlos después con "Editar". Acepta .xlsx/.xls/.csv. const importCodigos = async (file) => { if (!file) return; setImportingCodes(true); try { let headers = []; let rows = []; const isExcel = /\.(xlsx|xls)$/i.test(file.name); if (isExcel) { const buf = await file.arrayBuffer(); if (typeof window.spLoadXLSX === 'function') await window.spLoadXLSX(); // la librería de Excel se descarga solo la primera vez const wb = XLSX.read(buf, { type: 'array' }); const ws = wb.Sheets[wb.SheetNames[0]]; const raw = XLSX.utils.sheet_to_json(ws, { header: 1, defval: '' }); headers = (raw[0] || []).map(h => String(h || '')); rows = raw.slice(1); } else { // Mismo parser que la importación del catálogo: acepta , y ; y comillas. const matrix = factParseCSVMatrix(await file.text()); headers = (matrix[0] || []).map(h => String(h || '')); rows = matrix.slice(1); } const codigoIdx = findColumn(headers, ['codigo']); const nombreIdx = findColumn(headers, ['nombre'], codigoIdx); if (codigoIdx === -1) { toast('No se encontró una columna de código en el archivo', 'err'); setImportingCodes(false); return; } // Solo se envían los campos que existen: sin columna de nombre (o con la // celda vacía) NO se manda nombre_comercial, para no borrar el existente. const items = rows .map(r => { const it = { codigo: String(r[codigoIdx] ?? '').trim() }; if (nombreIdx !== -1) { const n = String(r[nombreIdx] ?? '').trim(); if (n) it.nombre_comercial = n; } return it; }) .filter(r => r.codigo); if (!items.length) { toast('El archivo no tiene códigos válidos', 'err'); setImportingCodes(false); return; } const res = await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_catalogo_import', items }), }, 'importar lista de códigos'); toast(`Códigos importados: ${res.imported || items.length}. Ahora puedes anexarles el CPE con "Editar".`); onChanged(); } catch (err) { toast(factErrMsg(err, 'No se pudo importar la lista de códigos'), 'err'); } setImportingCodes(false); }; const addClase = async (nombre) => { const limpio = nombre.trim(); if (!limpio) return; try { await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_clases_save', nombre: limpio }), }, 'crear clase'); toast(`Clase "${limpio}" creada`); setNuevaClase(''); onClasesChanged(); return limpio; } catch (_) { return null; } }; const deleteClase = async (c) => { if (!window.verifyDeleteKey(`¿Eliminar la clase "${c.nombre}"? Los productos que la tengan asignada no se borran, solo quedan sin clase.`)) return; try { await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_clases_delete', id: c.id }), }, 'eliminar clase'); toast('Clase eliminada'); onClasesChanged(); } catch (err) { toast(factErrMsg(err, 'No se pudo eliminar la clase'), 'err'); } }; const handleClaseSelect = async (value) => { if (value === '__nueva__') { const nombre = window.prompt('Nombre de la nueva clase (ej. Tipo A, Premium):'); if (nombre && nombre.trim()) { const creada = await addClase(nombre); if (creada) setForm(f => ({ ...f, clase: creada })); } return; } setForm(f => ({ ...f, clase: value })); }; const lookupCpe = async (cpeValue) => { const codigo = cpeValue.trim(); if (!codigo) { setCpeCheck({ status: 'idle', unidad: '' }); return; } setCpeCheck({ status: 'checking', unidad: '' }); try { const res = await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_cpe_lookup', cpe: codigo }), }, 'consultar CPE'); if (res.found) { setCpeCheck({ status: 'found', unidad: res.data.unidad_medida || '' }); setForm(f => (f.cpe.trim() !== codigo ? f : { ...f, nombre: f.nombre.trim() ? f.nombre : (res.data.nombre_producto || f.nombre), cpe_vencimiento: f.cpe_vencimiento || res.data.vencimiento || '', cpe_estatus: res.data.status || f.cpe_estatus, marca: f.marca.trim() ? f.marca : (res.data.marca || f.marca), tipo_envase: f.tipo_envase.trim() ? f.tipo_envase : (res.data.tipo_envase || f.tipo_envase), peso_neto: f.peso_neto ? f.peso_neto : (res.data.peso_neto != null ? String(res.data.peso_neto) : f.peso_neto), presentacion: factInferPresentacion(res.data.peso_neto, res.data.unidad_medida) || f.presentacion, })); } else { setCpeCheck({ status: 'notfound', unidad: '' }); } } catch (_) { setCpeCheck({ status: 'notfound', unidad: '' }); } }; // Palabras sueltas, no necesariamente en el orden del nombre: "azul viva" // debe encontrar "GALON CAUCHO VIVA COLOR TIPO C- AZUL". const queryWords = q.trim().toLowerCase().split(/\s+/).filter(Boolean); const filtered = catalog.filter(r => (!queryWords.length || queryWords.every(w => `${r.codigo || ''} ${r.nombre || ''} ${r.nombre_comercial || ''}`.toLowerCase().includes(w))) && (!claseFilter || r.clase === claseFilter) ); // Agrupado por clase (los productos sin clase van al final, bajo "Sin clase"). const grupos = []; const porClase = {}; filtered.forEach(r => { const key = r.clase || ''; if (!porClase[key]) { porClase[key] = []; grupos.push(key); } porClase[key].push(r); }); grupos.sort((a, b) => (a === '' ? 1 : b === '' ? -1 : a.localeCompare(b))); // Las acciones masivas solo aplican a filas VISIBLES (la selección además se // limpia al cambiar búsqueda/filtro). const selectedCodigos = filtered.filter(r => selected[r.codigo]).map(r => r.codigo); // Ordenar por columna (clic en el encabezado) — se aplica DENTRO de cada // grupo de clase, para no perder el agrupado que ya existe. const sortStr = (a, b) => String(a || '').localeCompare(String(b || '')); if (sortBy) { const dir = sortDir === 'asc' ? 1 : -1; grupos.forEach(g => { porClase[g] = porClase[g].slice().sort((a, b) => { if (sortBy === 'peso_neto') return dir * ((Number(a.peso_neto) || 0) - (Number(b.peso_neto) || 0)); return dir * sortStr(a[sortBy], b[sortBy]); }); }); } const toggleSort = (field) => { if (sortBy === field) setSortDir(d => (d === 'asc' ? 'desc' : 'asc')); else { setSortBy(field); setSortDir('asc'); } }; const SortTh = ({ field, className, children }) => ( toggleSort(field)} title="Ordenar por esta columna"> {children} {sortBy === field ? (sortDir === 'asc' ? '▲' : '▼') : '↕'} ); const handleTemplate = () => { factDownload('plantilla_catalogo.csv', factToCSV( ['presentacion', 'codigo', 'nombre', 'nombre_comercial', 'cpe', 'cpe_vencimiento', 'marca', 'tipo_envase', 'clase', 'peso_neto'], [{ presentacion: 'Galón', codigo: 'PRD-001', nombre: 'Ejemplo Producto', nombre_comercial: '', cpe: 'CPE-0001', cpe_vencimiento: '2027-01-01', marca: '', tipo_envase: '', clase: 'Tipo A', peso_neto: '3.78' }] )); }; const importFile = async (file) => { if (!file) return; try { const text = await file.text(); // Por fila solo viajan las columnas que EXISTEN en el archivo y tienen // valor: lo ausente/vacío no se envía (el servidor no pisa CPE, marca, // clase, peso, etc.). Consecuencia: una celda vacía no borra el dato actual. const TEXTOS = ['presentacion', 'nombre', 'nombre_comercial', 'marca', 'tipo_envase', 'clase', 'cpe']; const avisos = []; const rows = factParseCSV(text) .map((r, idx) => { const codigo = String(r.codigo ?? '').trim(); if (!codigo) return null; const it = { codigo }; TEXTOS.forEach(k => { if (k in r) { const v = String(r[k] ?? '').trim(); if (v) it[k] = v; } }); if ('cpe_vencimiento' in r && String(r.cpe_vencimiento ?? '').trim()) { const d = factNormDate(r.cpe_vencimiento); if (d) it.cpe_vencimiento = d; else avisos.push(`${codigo}: vencimiento "${r.cpe_vencimiento}" inválido`); } if ('peso_neto' in r) { const n = factParseNumber(r.peso_neto); if (n == null) { /* vacío: no se envía */ } else if (Number.isNaN(n) || n < 0) avisos.push(`${codigo}: peso neto "${r.peso_neto}" no numérico`); else it.peso_neto = n; } return it; }) .filter(Boolean); if (avisos.length) toast(`${avisos.length} valor(es) omitido(s) por formato inválido. Ej.: ${avisos.slice(0, 3).join('; ')}`, 'err'); if (!rows.length) { toast('El archivo no tiene filas válidas', 'err'); return; } const res = await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_catalogo_import', items: rows }), }, 'importar catálogo'); toast(`Catálogo importado: ${res.imported || rows.length} fila(s)`); onChanged(); } catch (err) { toast(factErrMsg(err, 'No se pudo importar el catálogo'), 'err'); } }; const handleAdd = async () => { if (!form.codigo.trim()) { toast('El código es obligatorio', 'err'); return; } const pesoAdd = factParseNumber(form.peso_neto); if (Number.isNaN(pesoAdd) || (pesoAdd != null && pesoAdd < 0)) { toast('El peso neto debe ser un número válido', 'err'); return; } try { await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_catalogo_save', ...form, codigo: form.codigo.trim(), peso_neto: pesoAdd || 0 }), }, 'guardar producto de catálogo'); toast('Producto guardado en el catálogo'); setForm({ presentacion: FACT_PRESENTACIONES[0], codigo: '', nombre: '', nombre_comercial: '', cpe: '', cpe_vencimiento: '', cpe_estatus: '', marca: '', tipo_envase: '', clase: '', peso_neto: '', }); setCpeCheck({ status: 'idle', unidad: '' }); setShowForm(false); onChanged(); } catch (_) {} }; const handleDelete = async (row) => { if (!window.verifyDeleteKey(`¿Eliminar "${row.nombre || row.codigo}" del catálogo de facturación?`)) return; try { await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_catalogo_delete', codigo: row.codigo }), }, 'eliminar producto de catálogo'); toast('Producto eliminado'); onChanged(); } catch (err) { toast(factErrMsg(err, 'No se pudo eliminar el producto'), 'err'); } }; const [bulkClase, setBulkClase] = fctUseState(''); const [applyingClase, setApplyingClase] = fctUseState(false); const handleApplyClaseSelected = async () => { if (!selectedCodigos.length) return; if (!window.confirm(`¿Asignar la clase "${bulkClase || 'Sin clase'}" a ${selectedCodigos.length} producto(s)?`)) return; setApplyingClase(true); try { const res = await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_catalogo_set_clase_bulk', codigos: selectedCodigos, clase: bulkClase }), }, 'cambiar clase de los productos seleccionados'); toast(`Clase actualizada en ${res.updated ?? selectedCodigos.length} producto(s)`); clearSelection(); setBulkClase(''); onChanged(); } catch (err) { toast(factErrMsg(err, 'No se pudo cambiar la clase'), 'err'); } setApplyingClase(false); }; const handleDeleteSelected = async () => { if (!selectedCodigos.length) return; if (!window.verifyDeleteKey(`¿Eliminar ${selectedCodigos.length} producto(s) seleccionado(s) del catálogo? Esta acción no se puede deshacer.`)) return; try { const res = await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_catalogo_delete_bulk', codigos: selectedCodigos }), }, 'eliminar productos seleccionados del catálogo'); toast(`${res.deleted ?? selectedCodigos.length} producto(s) eliminado(s)`); clearSelection(); onChanged(); } catch (err) { toast(factErrMsg(err, 'No se pudieron eliminar los productos'), 'err'); } }; // Edición: código, nombre comercial, clase y todo lo del CPE — así se // le puede "anexar" el CPE a un producto importado sin uno (con // auto-verificación, igual que al crear). El nombre oficial de SENCAMER, // marca, tipo de envase y peso viajan junto al CPE pero no se muestran // como campos propios: solo se ven/editan código, nombre comercial y clase. const [editRow, setEditRow] = fctUseState(null); const [refreshingCpe, setRefreshingCpe] = fctUseState(null); // codigo en curso, o null const [editCpeCheck, setEditCpeCheck] = fctUseState({ status: 'idle', unidad: '' }); // sp_fact_catalogo.peso_neto es DECIMAL, así que PDO lo devuelve como texto // ("0.0000") en vez de number — un "0.0000" es truthy en JS, así que un // `row.peso_neto || ''` simple nunca lo trataba como vacío. Eso dejaba el // campo "atascado" en 0 para siempre: como el valor inicial no era realmente // vacío, la auto-verificación de CPE nunca lo sobrescribía con el peso real // de SENCAMER en ediciones futuras, aunque el producto sí tuviera uno. const pesoOrBlank = v => (v && Number(v) !== 0 ? String(v) : ''); const startEdit = (row) => { setEditRow({ codigo_original: row.codigo, codigo: row.codigo, presentacion: row.presentacion || '', // cpe_al_abrir: el CPE que tenía la fila al abrir "Editar". Si el // usuario lo cambia a otro (p. ej. porque se equivocó al cargarlo la // primera vez), los datos que dependen del CPE (nombre, marca, tipo de // envase, peso, presentación) deben venir del CPE nuevo aunque la fila // ya tuviera algo cargado — solo se "completa sin pisar" cuando el CPE // no cambió (re-verificar el mismo). cpe_al_abrir: row.cpe || '', nombre: row.nombre || '', nombre_comercial: row.nombre_comercial || '', clase: row.clase || '', cpe: row.cpe || '', cpe_vencimiento: row.cpe_vencimiento || '', cpe_estatus: row.cpe_estatus || '', marca: row.marca || '', tipo_envase: row.tipo_envase || '', peso_neto: pesoOrBlank(row.peso_neto), }); setEditCpeCheck({ status: 'idle', unidad: '' }); }; const editLookupCpe = async (cpeValue) => { const codigo = cpeValue.trim(); if (!codigo) { setEditCpeCheck({ status: 'idle', unidad: '' }); return; } setEditCpeCheck({ status: 'checking', unidad: '' }); try { const res = await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_cpe_lookup', cpe: codigo }), }, 'consultar CPE'); if (res.found) { setEditCpeCheck({ status: 'found', unidad: res.data.unidad_medida || '' }); setEditRow(f => { if (!f || f.cpe.trim() !== codigo) return f; // CPE distinto al que tenía la fila → los datos del CPE anterior // (posiblemente equivocado) se reemplazan por los del nuevo en vez // de "completar solo si está vacío". const cambioCpe = f.cpe_al_abrir.trim() !== codigo; const pick = (actual, nuevo) => (cambioCpe ? (nuevo || actual) : (String(actual).trim() ? actual : (nuevo || actual))); return { ...f, nombre: pick(f.nombre, res.data.nombre_producto), cpe_vencimiento: cambioCpe ? (res.data.vencimiento || f.cpe_vencimiento) : (f.cpe_vencimiento || res.data.vencimiento || ''), cpe_estatus: res.data.status || f.cpe_estatus, marca: pick(f.marca, res.data.marca), tipo_envase: pick(f.tipo_envase, res.data.tipo_envase), peso_neto: cambioCpe ? (res.data.peso_neto != null ? String(res.data.peso_neto) : f.peso_neto) : (pesoOrBlank(f.peso_neto) ? f.peso_neto : (res.data.peso_neto != null ? String(res.data.peso_neto) : f.peso_neto)), presentacion: cambioCpe ? (factInferPresentacion(res.data.peso_neto, res.data.unidad_medida) || f.presentacion) : (f.presentacion || factInferPresentacion(res.data.peso_neto, res.data.unidad_medida) || f.presentacion), }; }); } else { setEditCpeCheck({ status: 'notfound', unidad: '' }); } } catch (_) { setEditCpeCheck({ status: 'notfound', unidad: '' }); } }; const saveEdit = async () => { if (!editRow.codigo.trim()) { toast('El código es obligatorio', 'err'); return; } const pesoEd = factParseNumber(editRow.peso_neto); if (Number.isNaN(pesoEd) || (pesoEd != null && pesoEd < 0)) { toast('El peso neto debe ser un número válido', 'err'); return; } try { await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_catalogo_edit', ...editRow, codigo: editRow.codigo.trim(), peso_neto: pesoEd || 0 }), }, 'editar producto de catálogo'); toast('Producto actualizado'); setEditRow(null); onChanged(); } catch (err) { toast(factErrMsg(err, 'No se pudo actualizar el producto'), 'err'); } }; const refreshCpe = async (row) => { if (!row.cpe) { toast('Este producto no tiene CPE registrado', 'err'); return; } setRefreshingCpe(row.codigo); try { const res = await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_catalogo_cpe_refresh', codigo: row.codigo }), }, 'actualizar estatus del CPE'); if (res.found) { toast(`CPE ${row.cpe}: ${res.data.status || 'consultado'}`); onChanged(); } else { toast('No se pudo verificar el CPE en SENCAMER en este momento', 'err'); } } catch (_) {} setRefreshingCpe(null); }; // CPE directo desde la fila (sin tener que abrir "Editar" arriba de la // tabla): un input inline que aparece en la columna CPE cuando el // producto todavía no tiene uno, verifica contra SENCAMER al perder el // foco y guarda de una vez con lo que ya trae la fila (nombre comercial, // clase, etc. no se tocan). const [quickCpe, setQuickCpe] = fctUseState({}); // { [codigo]: valor en curso } const [quickCpeStatus, setQuickCpeStatus] = fctUseState({}); // { [codigo]: 'checking'|'notfound' } // fact_catalogo_edit sobrescribe TODAS las columnas, así que antes de guardar // un cambio puntual se vuelve a leer la fila del servidor: se parte de lo // último guardado (no de una copia vieja en pantalla) y solo se cambia el // campo tocado. Devuelve null si el producto ya no existe. const fetchFreshRow = async (codigo) => { const r = await callApi(`${apiUrl}?action=fact_catalogo_get`, {}, 'leer catálogo'); return (r.data || []).find(c => c.codigo === codigo) || null; }; const rowPayload = (r) => ({ action: 'fact_catalogo_edit', codigo_original: r.codigo, codigo: r.codigo, presentacion: r.presentacion || '', nombre: r.nombre || '', nombre_comercial: r.nombre_comercial || '', clase: r.clase || '', cpe: r.cpe || '', cpe_vencimiento: r.cpe_vencimiento || '', cpe_estatus: r.cpe_estatus || '', marca: r.marca || '', tipo_envase: r.tipo_envase || '', peso_neto: pesoOrBlank(r.peso_neto), }); const quickCpeBlur = async (row, value) => { const cpeValue = value.trim(); if (!cpeValue) { setQuickCpe(m => { const n = { ...m }; delete n[row.codigo]; return n; }); return; } setQuickCpeStatus(m => ({ ...m, [row.codigo]: 'checking' })); try { const res = await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_cpe_lookup', cpe: cpeValue }), }, 'consultar CPE'); if (!res.found) { setQuickCpeStatus(m => ({ ...m, [row.codigo]: 'notfound' })); toast('CPE no encontrado en SENCAMER', 'err'); return; } const fresh = await fetchFreshRow(row.codigo); if (!fresh) { toast('El producto ya no existe en el catálogo; se recargó la lista', 'err'); setQuickCpeStatus(m => { const n = { ...m }; delete n[row.codigo]; return n; }); onChanged(); return; } if (fresh.cpe && fresh.cpe !== cpeValue) { toast(`Otro usuario ya asignó el CPE ${fresh.cpe} a este producto; no se sobrescribió`, 'err'); setQuickCpeStatus(m => { const n = { ...m }; delete n[row.codigo]; return n; }); onChanged(); return; } const presentacion = fresh.presentacion || factInferPresentacion(res.data.peso_neto, res.data.unidad_medida) || ''; await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...rowPayload(fresh), nombre: fresh.nombre || res.data.nombre_producto || '', cpe: cpeValue, cpe_vencimiento: res.data.vencimiento || '', cpe_estatus: res.data.status || '', marca: fresh.marca || res.data.marca || '', tipo_envase: fresh.tipo_envase || res.data.tipo_envase || '', peso_neto: pesoOrBlank(fresh.peso_neto) || (res.data.peso_neto != null ? String(res.data.peso_neto) : ''), presentacion, }), }, 'guardar CPE'); toast(`CPE verificado: ${res.data.status || 'consultado'}`); setQuickCpe(m => { const n = { ...m }; delete n[row.codigo]; return n; }); setQuickCpeStatus(m => { const n = { ...m }; delete n[row.codigo]; return n; }); onChanged(); } catch (err) { setQuickCpeStatus(m => ({ ...m, [row.codigo]: 'notfound' })); toast(factErrMsg(err, 'No se pudo guardar el CPE'), 'err'); } }; // Presentación editable directo desde la fila (select), sin abrir // "Editar". Se autocompleta sola al verificar el CPE (ver quickCpeBlur / // editLookupCpe / fact_catalogo_cpe_refresh), pero el usuario siempre // puede corregirla a mano aquí mismo. const [savingPresentacion, setSavingPresentacion] = fctUseState(null); // codigo en curso, o null const savePresentacion = async (row, value) => { setSavingPresentacion(row.codigo); try { const fresh = await fetchFreshRow(row.codigo); if (!fresh) { toast('El producto ya no existe en el catálogo; se recargó la lista', 'err'); onChanged(); } else { await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...rowPayload(fresh), presentacion: value }), }, 'cambiar presentación'); onChanged(); } } catch (err) { toast(factErrMsg(err, 'No se pudo cambiar la presentación'), 'err'); onChanged(); } setSavingPresentacion(null); }; return (
{ setQ(e.target.value); clearSelection(); }} />
{ importFile(e.target.files?.[0]); e.target.value = ''; }} /> { importCodigos(e.target.files?.[0]); e.target.value = ''; }} />
{showClases && (
setNuevaClase(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') addClase(nuevaClase); }} />
{clases.length === 0 &&

Aún no has creado ninguna clase.

} {clases.length > 0 && ( )}
)}
{ e.preventDefault(); setDragOver(true); }} onDragLeave={() => setDragOver(false)} onDrop={e => { e.preventDefault(); setDragOver(false); importFile(e.dataTransfer.files?.[0]); }} > Arrastra aquí tu archivo CSV para importar el catálogo, o usa el botón «Importar».
{showForm && (
setForm({ ...form, codigo: e.target.value })} /> setForm({ ...form, nombre: e.target.value })} /> setForm({ ...form, nombre_comercial: e.target.value })} />
{ setForm({ ...form, cpe: e.target.value }); setCpeCheck({ status: 'idle', unidad: '' }); }} onBlur={e => lookupCpe(e.target.value)} /> {cpeCheck.status === 'checking' && Verificando…} {cpeCheck.status === 'found' && ✓ CPE verificado (SENCAMER)} {cpeCheck.status === 'notfound' && ⚠ No encontrado en SENCAMER}
setForm({ ...form, cpe_vencimiento: e.target.value })} /> setForm({ ...form, cpe_estatus: e.target.value })} /> setForm({ ...form, marca: e.target.value })} /> setForm({ ...form, tipo_envase: e.target.value })} />
setForm({ ...form, peso_neto: e.target.value })} /> {cpeCheck.status === 'found' && cpeCheck.unidad && {cpeCheck.unidad}}
)} {editRow && (
Editando {editRow.codigo_original}: setEditRow({ ...editRow, codigo: e.target.value })} /> setEditRow({ ...editRow, nombre_comercial: e.target.value })} />
{ setEditRow({ ...editRow, cpe: e.target.value }); setEditCpeCheck({ status: 'idle', unidad: '' }); }} onBlur={e => editLookupCpe(e.target.value)} /> {editCpeCheck.status === 'checking' && Verificando…} {editCpeCheck.status === 'found' && ✓ CPE verificado (SENCAMER)} {editCpeCheck.status === 'notfound' && ⚠ No encontrado en SENCAMER}
setEditRow({ ...editRow, peso_neto: e.target.value })} /> {editCpeCheck.status === 'found' && editCpeCheck.unidad && {editCpeCheck.unidad}}
)}
PresentaciónCódigoNombreNombre comercialEstatusMarcaTipo de envasePeso neto {grupos.map(g => ( {porClase[g].map(r => ( ))} ))} {!filtered.length && ( )}
0 && filtered.every(r => selected[r.codigo])} onChange={e => { const on = e.target.checked; setSelected(s => { const next = { ...s }; filtered.forEach(r => { next[r.codigo] = on; }); return next; }); }} title="Seleccionar todos los visibles" /> CPEVencimiento CPE
{g || 'Sin clase'} ({porClase[g].length})
toggleSelected(r.codigo)} /> {r.codigo} {r.nombre} {r.nombre_comercial || '—'} {r.cpe ? r.cpe : (
setQuickCpe(m => ({ ...m, [r.codigo]: e.target.value }))} onBlur={e => quickCpeBlur(r, e.target.value)} /> {quickCpeStatus[r.codigo] === 'checking' && …} {quickCpeStatus[r.codigo] === 'notfound' && ⚠}
)}
{r.cpe_vencimiento || '—'} {r.cpe_estatus || '—'} {r.marca || '—'} {r.tipo_envase || '—'} {factNum(r.peso_neto)}
Sin resultados.
{selectedCodigos.length > 0 && (
{selectedCodigos.length} producto{selectedCodigos.length !== 1 ? 's' : ''} seleccionado{selectedCodigos.length !== 1 ? 's' : ''}
)}
); } // ── NUEVA ORDEN DE ENTREGA ────────────────────────────────── // Se conserva el mismo consecutivo de las facturas (fact_factura_next). const FCT_FACTURADOR_KEY = 'fct_ultimo_facturador'; function fctUltimoFacturador() { try { return localStorage.getItem(FCT_FACTURADOR_KEY) || ''; } catch (_) { return ''; } } function fctEmptyHeader() { return { numero: '', fecha: factToday(), facturador: fctUltimoFacturador(), observacion: '' }; } function fctEmptyLine() { return { id: factUid(), codigo: '', descripcion: '', lote: '', disponible: null, cantidad: '' }; } // Borradores: se guardan en el navegador para no perder el avance si se // recarga o se sale de la página, y permiten armar varias órdenes a la vez. function fctNewDraft(lines) { return { id: factUid(), header: fctEmptyHeader(), lines: lines && lines.length ? lines : [fctEmptyLine()] }; } const fctDraftsKey = (apiUrl) => `fct_borradores_orden:${apiUrl}`; // `disponibleDe(codigo, lote)` recalcula el disponible contra el inventario // ACTUAL: el `disponible` guardado en el borrador puede estar viejo. function fctLoadDrafts(apiUrl, disponibleDe) { try { const raw = JSON.parse(localStorage.getItem(fctDraftsKey(apiUrl)) || 'null'); if (raw && Array.isArray(raw.drafts) && raw.drafts.length) { const drafts = raw.drafts .filter(d => d && d.id && d.header && Array.isArray(d.lines)) .map(d => ({ ...d, header: { ...fctEmptyHeader(), ...d.header }, lines: (d.lines.length ? d.lines : [fctEmptyLine()]).map(l => ({ ...l, disponible: l && l.codigo && disponibleDe ? disponibleDe(l.codigo, l.lote || '') : null, })), })); if (drafts.length) return { drafts, activeId: drafts.some(d => d.id === raw.activeId) ? raw.activeId : drafts[0].id }; } } catch (_) {} const d = fctNewDraft(); return { drafts: [d], activeId: d.id }; } function fctDraftHasContent(d) { const h = d.header; return !!(h.numero || h.observacion || d.lines.some(l => l.codigo || l.descripcion || l.lote || Number(l.cantidad) > 0)); } function FctNuevaFacturaTab({ inventory, catalog, callApi, apiUrl, toast, pendingLines, onConsumePending, onSaved, onOpenOrden }) { const [store, setStore] = fctUseState(() => fctLoadDrafts(apiUrl, (codigo, lote) => { const row = (inventory || []).find(r => r.codigo === codigo && (r.lote || '') === lote); return row ? Number(row.cantidad || 0) : 0; })); const [saving, setSaving] = fctUseState(false); const [nextNumero, setNextNumero] = fctUseState(''); const [ultima, setUltima] = fctUseState(null); // { id, numero } de la última orden guardada const { drafts } = store; const active = drafts.find(d => d.id === store.activeId) || drafts[0]; const header = active.header; const lines = active.lines; const patchActive = (fn) => setStore(s => ({ ...s, drafts: s.drafts.map(d => d.id === s.activeId ? { ...d, ...fn(d) } : d), })); const setHeader = (h) => patchActive(() => ({ header: h })); const setLines = (fn) => patchActive(d => ({ lines: typeof fn === 'function' ? fn(d.lines) : fn })); fctUseEffect(() => { try { localStorage.setItem(fctDraftsKey(apiUrl), JSON.stringify(store)); } catch (_) {} }, [store]); const loadNext = async () => { try { const r = await callApi(`${apiUrl}?action=fact_factura_next`, {}, 'siguiente número de orden'); setNextNumero(r.numero != null ? String(r.numero) : ''); } catch (_) {} }; fctUseEffect(() => { loadNext(); }, []); // Renglones que llegan desde "Crear orden de entrega" (Inventario): van al // borrador activo si está vacío; si no, se abre un borrador nuevo. fctUseEffect(() => { if (pendingLines && pendingLines.length) { setStore(s => { const cur = s.drafts.find(d => d.id === s.activeId) || s.drafts[0]; if (!fctDraftHasContent(cur)) { return { ...s, drafts: s.drafts.map(d => d.id === cur.id ? { ...d, lines: pendingLines } : d) }; } const nd = fctNewDraft(pendingLines); return { drafts: [...s.drafts, nd], activeId: nd.id }; }); onConsumePending(); } }, [pendingLines]); const selectDraft = (id) => setStore(s => ({ ...s, activeId: id })); const addDraft = () => setStore(s => { const nd = fctNewDraft(); return { drafts: [...s.drafts, nd], activeId: nd.id }; }); const removeDraft = (id) => setStore(s => { const idx = s.drafts.findIndex(d => d.id === id); const rest = s.drafts.filter(d => d.id !== id); if (!rest.length) { const nd = fctNewDraft(); return { drafts: [nd], activeId: nd.id }; } return { drafts: rest, activeId: s.activeId === id ? rest[Math.max(0, idx - 1)].id : s.activeId }; }); const closeDraft = (d) => { if (fctDraftHasContent(d) && !window.confirm('¿Descartar este borrador? Se perderá lo que has cargado en él.')) return; removeDraft(d.id); }; // Lotes disponibles por código (a partir del inventario cargado). const lotesPorCodigo = fctUseMemo(() => { const map = {}; inventory.forEach(r => { if (Number(r.cantidad || 0) <= 0) return; if (!map[r.codigo]) map[r.codigo] = []; map[r.codigo].push(r); }); return map; }, [inventory]); // Productos con existencias, para el buscador del renglón (código + nombre). const catalogoConStock = fctUseMemo(() => { const byCode = {}; (catalog || []).forEach(c => { byCode[c.codigo] = c; }); return Object.keys(lotesPorCodigo).sort().map(codigo => { const c = byCode[codigo]; return { codigo, nombre: (c && (c.nombre_comercial || c.nombre)) || lotesPorCodigo[codigo][0].nombre || '', nombre_comercial: '' }; }); }, [lotesPorCodigo, catalog]); const invRow = (codigo, lote) => inventory.find(r => r.codigo === codigo && (r.lote || '') === (lote || '')); const disponibleDe = (codigo, lote) => { const row = invRow(codigo, lote); return row ? Number(row.cantidad || 0) : 0; }; const catRow = (codigo) => (catalog || []).find(c => c.codigo === codigo); const updateLine = (id, patch) => setLines(ls => ls.map(l => { if (l.id !== id) return l; const next = { ...l, ...patch }; if ('codigo' in patch) { const opciones = lotesPorCodigo[patch.codigo] || []; const cat = catRow(patch.codigo); next.nombre = (opciones[0] && opciones[0].nombre) || (cat && (cat.nombre_comercial || cat.nombre)) || ''; next.descripcion = next.nombre; next.lote = opciones.length === 1 ? (opciones[0].lote || '') : ''; next.disponible = (patch.codigo && (opciones.length === 1)) ? disponibleDe(patch.codigo, next.lote) : null; } if ('lote' in patch) { next.disponible = disponibleDe(next.codigo, patch.lote); } return next; })); const addLine = () => setLines(ls => [...ls, fctEmptyLine()]); const removeLine = (id) => setLines(ls => ls.length > 1 ? ls.filter(l => l.id !== id) : ls); const totalUnidades = lines.reduce((s, l) => s + (Number(l.cantidad) > 0 ? Number(l.cantidad) : 0), 0); // Total pedido por (código, lote) sumando TODOS los renglones. const keyCL = (l) => `${l.codigo}\u0001${l.lote || ''}`; const pedidoPorClave = {}; lines.forEach(l => { if (!l.codigo) return; const c = Number(l.cantidad); pedidoPorClave[keyCL(l)] = (pedidoPorClave[keyCL(l)] || 0) + (Number.isFinite(c) && c > 0 ? c : 0); }); const lineVacia = (l) => !l.codigo && !l.lote && !(Number(l.cantidad) > 0) && !String(l.descripcion || '').trim(); const lineError = (l) => { if (lineVacia(l)) return null; if (!l.codigo) return 'Falta el código del producto'; const row = invRow(l.codigo, l.lote); if (!row) return l.lote ? 'El lote no existe en el inventario' : 'Elige un lote'; const cant = Number(l.cantidad); if (!(cant > 0)) return 'Indica una cantidad mayor a 0'; const disp = Number(row.cantidad || 0); if (disp <= 0) return 'El lote no tiene existencias'; const pedido = pedidoPorClave[keyCL(l)] || 0; if (pedido > disp) { return pedido === cant ? `Cantidad supera el disponible del lote (${factNum(disp)})` : `Entre todos los renglones de este lote suman ${factNum(pedido)} y solo hay ${factNum(disp)}`; } return null; }; const cpeVencido = (codigo, fecha) => { const c = catRow(codigo); if (!c) return false; const venc = String(c.cpe_vencimiento || '').slice(0, 10); const ref = factNormDate(fecha) || factToday(); return (!!venc && venc < ref) || /vencid/i.test(String(c.cpe_estatus || '')); }; const hasErrors = lines.some(l => lineError(l)) || lines.every(l => lineVacia(l)); const limpiar = () => patchActive(() => ({ header: fctEmptyHeader(), lines: [fctEmptyLine()] })); const imprimir = () => { factPrint(factBuildOrdenReport({ ...header, tipo: 'orden', numero: header.numero || nextNumero, items: lines.filter(l => l.codigo).map(l => ({ ...l, cantidad: Number(l.cantidad) || 0 })), })); }; const guardar = async () => { if (saving) return; const facturador = String(header.facturador || '').trim(); if (!facturador) { toast('Falta el facturador', 'err'); return; } if (!factNormDate(header.fecha) || !/^\d{4}-\d{2}-\d{2}$/.test(String(header.fecha))) { toast('La fecha de la orden no es válida', 'err'); return; } const bad = lines.find(l => lineError(l)); if (bad) { toast(`Revisa los renglones: ${lineError(bad)}`, 'err'); return; } const validLines = lines.filter(l => !lineVacia(l)); if (!validLines.length) { toast('Agrega al menos un renglón con código, lote y cantidad', 'err'); return; } const vencidos = [...new Set(validLines.filter(l => cpeVencido(l.codigo, header.fecha)).map(l => l.codigo))]; if (vencidos.length && !window.confirm(`Estos productos tienen el CPE VENCIDO:\n\n${vencidos.join(', ')}\n\n¿Crear la orden de todas formas?`)) return; const draftId = active.id; setSaving(true); try { const r = await callApi(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'fact_factura_save', tipo: 'orden', numero: String(header.numero || '').trim(), fecha: header.fecha, facturador, observacion: String(header.observacion || '').trim(), items: validLines.map(l => ({ codigo: l.codigo, descripcion: String(l.descripcion || '').trim(), lote: l.lote || '', cantidad: Number(l.cantidad), precio: 0, })), }), }, 'guardar orden de entrega'); try { localStorage.setItem(FCT_FACTURADOR_KEY, facturador); } catch (_) {} toast(`Orden de entrega N° ${r.numero || header.numero} guardada`); setUltima({ id: r.id, numero: r.numero || header.numero }); removeDraft(draftId); loadNext(); onSaved(); } catch (err) { toast(factErrMsg(err, 'No se pudo guardar la orden'), 'err'); onSaved(); } setSaving(false); }; return (
{ultima && (
✅ Orden N° {ultima.numero} guardada.
)}
{drafts.map((d, i) => (
{(drafts.length > 1 || fctDraftHasContent(d)) && ( )}
))} Los borradores se guardan solos en este navegador.
EntregaDepartamento de Envasado
RecibeDepartamento de Producción