// ════════════════════════════════════════════ // Mantenimiento — Verona Color Paints // Registro de equipos, reporte/resolución de fallas (equipos y máquinas) // e informes imprimibles. Reutiliza los equipos (sp_equipos) y los perfiles // de máquina (fallas) que ya existen; no crea tablas nuevas. // ════════════════════════════════════════════ const { useState: mtUseState, useMemo: mtUseMemo } = React; const MT_GRAV = { urgente: { label: 'Urgente', cls: 'falla-badge--urgente', order: 0 }, medio: { label: 'Medio', cls: 'falla-badge--medio', order: 1 }, leve: { label: 'Leve', cls: 'falla-badge--leve', order: 2 }, }; function mtEsc(v) { return String(v == null ? '' : v) .replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') .replace(/'/g, ''').replace(/`/g, '`'); } function mtFmtDate(d) { if (!d) return '—'; const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(d); return m ? `${m[3]}/${m[2]}/${m[1]}` : d; } function mtDaysOpen(dateStr) { if (!dateStr) return 0; const a = new Date(dateStr + 'T12:00:00Z').getTime(); const b = new Date(cpCaracasDateStr() + 'T12:00:00Z').getTime(); return Math.max(0, Math.round((b - a) / 86400000)); } function mtNowStr() { // Epoch real sincronizado: toLocaleString ya aplica la zona de Caracas // (usar cpVetNow() desplazaría la hora dos veces). return new Date(cpNowMs()).toLocaleString('es', { timeZone: 'America/Caracas', day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }); } // Aplana equipos + máquinas en una lista de fallas con su origen. function mtCollectFallas(equipos, machines, machineProfiles) { const meta = window.EQUIPO_META; const out = []; (equipos || []).forEach(e => (e.fallas || []).forEach(f => out.push({ key: 'e:' + e.id + ':' + f.id, kind: 'equipo', refId: e.id, code: e.code, name: e.name, area: e.area, tipo: meta.categoryLabel(e.category), falla: f, }))); (machines || []).forEach(m => { const code = m.code || m.id; const prof = (machineProfiles && machineProfiles[code]) || {}; (prof.fallas || []).forEach(f => out.push({ key: 'm:' + code + ':' + f.id, kind: 'maquina', refId: code, code, name: m.name, area: meta.machineArea(m.type), tipo: 'Máquina · ' + (m.type || ''), falla: f, })); }); return out; } // ── Informe imprimible ────────────────────────────────────────────── function mtReportHtml({ title, rows, kind, logo }) { const now = mtNowStr(); const meta = window.EQUIPO_META; let head, body; if (kind === 'inventario') { head = ['Código', 'Nombre', 'Categoría', 'Área', 'Ubicación', 'Responsable', 'Estado', 'Fallas', 'Próx. mant.']; body = rows.map(r => ` ${mtEsc(r.code)}${mtEsc(r.name)}${mtEsc(r.tipo)} ${mtEsc(meta.areaLabel(r.area))}${mtEsc(r.ubicacion || '—')}${mtEsc(r.responsable || '—')} ${mtEsc(r.estado)}${r.abiertas || '—'}${mtEsc(mtFmtDate(r.proximo))}`).join(''); } else { const hist = kind === 'historial'; head = ['Código', 'Equipo / Máquina', 'Área', 'Gravedad', 'Reportada', 'Por', 'Descripción'].concat(hist ? ['Estado', 'Resolución'] : ['Días abierta']); body = rows.map(r => { const f = r.falla; const g = (MT_GRAV[f.gravedad] || MT_GRAV.leve).label; const base = `${mtEsc(r.code)}${mtEsc(r.name)}
${mtEsc(r.tipo)}
${mtEsc(meta.areaLabel(r.area))}${mtEsc(g)} ${mtEsc(mtFmtDate(f.fechaReporte))}${mtEsc(f.reportadoPor || '—')}${mtEsc(f.descripcion)}`; if (!hist) return `${base}${mtDaysOpen(f.fechaReporte)}`; const res = f.resuelta ? `${mtEsc(mtFmtDate(f.fechaResolucion))}${f.reparadoPor ? ' · ' + mtEsc(f.reparadoPor) : ''}
${mtEsc(f.solucion || '')}
` : '—'; return `${base}${f.resuelta ? 'Resuelta' : 'Abierta'}${res}`; }).join(''); } return `${mtEsc(title)}
Verona Color Paints
${mtEsc(title)} (${rows.length})
Generado: ${mtEsc(now)}
${rows.length ? `${head.map(h => ``).join('')}${body}
${h}
` : '

✓ No hay registros para los filtros seleccionados.

'}
Elaborado por (Mantenimiento)
Revisado por (Supervisor)
Sistema de Planificación — VERONA COLOR PAINTS — ${mtEsc(now)}
`; } function mtExportXlsx(kind, rows, headers, toRow) { if (!window.XLSX) return false; const aoa = [headers].concat(rows.map(toRow)); const ws = window.XLSX.utils.aoa_to_sheet(aoa); const wb = window.XLSX.utils.book_new(); window.XLSX.utils.book_append_sheet(wb, ws, 'Mantenimiento'); window.XLSX.writeFile(wb, `mantenimiento-${kind}-${cpCaracasDateStr()}.xlsx`); return true; } function MtReportModal({ equipos, machines, machineProfiles, onClose }) { const meta = window.EQUIPO_META; const [kind, setKind] = mtUseState('abiertas'); const [area, setArea] = mtUseState(''); const [grav, setGrav] = mtUseState(''); const [desde, setDesde] = mtUseState(''); const [hasta, setHasta] = mtUseState(''); const [inclMaq, setInclMaq] = mtUseState(true); const rows = mtUseMemo(() => { if (kind === 'inventario') { const out = (equipos || []).map(e => { const st = meta.STATUS[e.status || 'operativo'] || meta.STATUS.operativo; return { code: e.code, name: e.name, tipo: meta.categoryLabel(e.category), area: e.area, ubicacion: e.ubicacion, responsable: e.responsable, estado: st.label, abiertas: (e.fallas || []).filter(f => !f.resuelta).length, proximo: e.proximoMantenimiento }; }); return out.filter(r => !area || r.area === area); } let all = mtCollectFallas(equipos, inclMaq ? machines : [], machineProfiles); if (kind === 'abiertas') all = all.filter(r => !r.falla.resuelta); return all .filter(r => (!area || r.area === area) && (!grav || r.falla.gravedad === grav) && (!desde || (r.falla.fechaReporte || '') >= desde) && (!hasta || (r.falla.fechaReporte || '') <= hasta)) .sort((a, b) => ((MT_GRAV[a.falla.gravedad] || {}).order ?? 9) - ((MT_GRAV[b.falla.gravedad] || {}).order ?? 9) || (a.falla.fechaReporte || '').localeCompare(b.falla.fechaReporte || '')); }, [kind, area, grav, desde, hasta, inclMaq, equipos, machines, machineProfiles]); const titles = { abiertas: 'INFORME DE FALLAS ABIERTAS', historial: 'HISTORIAL DE FALLAS', inventario: 'INVENTARIO DE EQUIPOS' }; const print = () => { const w = window.open('', '_blank'); if (!w) { const msg = 'Permite ventanas emergentes para ver el informe.'; if (window.showToast) window.showToast(msg, 'err'); else window.alert(msg); return; } w.document.write(mtReportHtml({ title: titles[kind], rows, kind, logo: CP_LOGO_URL })); w.document.close(); }; const excel = () => { let ok; if (kind === 'inventario') { ok = mtExportXlsx(kind, rows, ['Código', 'Nombre', 'Categoría', 'Área', 'Ubicación', 'Responsable', 'Estado', 'Fallas abiertas', 'Próximo mantenimiento'], r => [r.code, r.name, r.tipo, meta.areaLabel(r.area), r.ubicacion || '', r.responsable || '', r.estado, r.abiertas, r.proximo || '']); } else { ok = mtExportXlsx(kind, rows, ['Código', 'Equipo/Máquina', 'Tipo', 'Área', 'Gravedad', 'Reportada', 'Reportado por', 'Descripción', 'Estado', 'Resuelta', 'Reparado por', 'Solución'], r => [r.code, r.name, r.tipo, meta.areaLabel(r.area), (MT_GRAV[r.falla.gravedad] || {}).label || '', r.falla.fechaReporte || '', r.falla.reportadoPor || '', r.falla.descripcion || '', r.falla.resuelta ? 'Resuelta' : 'Abierta', r.falla.fechaResolucion || '', r.falla.reparadoPor || '', r.falla.solucion || '']); } if (!ok) window.alert('No se pudo cargar la librería de Excel. Verifique la conexión.'); }; return (
e.stopPropagation()}>
{window.t('🖨 Informes de mantenimiento')}
{kind !== 'inventario' && (<>
setDesde(e.target.value)} />
setHasta(e.target.value)} />
)}
{rows.length} {window.t('registro(s) en el informe')}
); } // ── Registrar equipo ──────────────────────────────────────────────── function MtNewEquipoModal({ list, userName, onSave, onClose }) { const meta = window.EQUIPO_META; const [f, setF] = mtUseState({ code: '', name: '', category: meta.CATEGORIES[0].id, area: meta.AREAS[0].id, marca: '', modelo: '', serial: '', ubicacion: '', responsable: '', proximoMantenimiento: '', notas: '' }); const [err, setErr] = mtUseState(''); const set = (k) => (e) => setF(p => ({ ...p, [k]: e.target.value })); const submit = () => { const code = f.code.trim().toUpperCase(); if (!code || !f.name.trim()) { setErr('Código y nombre son obligatorios.'); return; } if ((list || []).some(e => (e.code || '').toUpperCase() === code)) { setErr('Ya existe un equipo con ese código.'); return; } onSave({ id: meta.newId(), code, name: f.name.trim(), category: f.category, area: f.area, status: 'operativo', marca: f.marca.trim(), modelo: f.modelo.trim(), serial: f.serial.trim(), ubicacion: f.ubicacion.trim(), responsable: f.responsable.trim(), proximoMantenimiento: f.proximoMantenimiento, notas: f.notas.trim(), fallas: [], registradoPor: userName || '', fechaRegistro: cpCaracasDateStr(), }); }; return (
e.stopPropagation()}>
{window.t('+ Registrar equipo')}