// ════════════════════════════════════════════
// 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)}
${mtEsc(title)} (${rows.length})
Generado: ${mtEsc(now)}
${rows.length ? `${head.map(h => `| ${h} | `).join('')}
${body}
`
: '✓ 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' && (<>
>)}
{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')}
{err &&
{err}
}
);
}
// ── Reportar falla (equipo o máquina) ───────────────────────────────
function MtFallaModal({ equipos, machines, preset, onReport, onClose }) {
const [target, setTarget] = mtUseState(preset ? preset.kind : 'equipo');
const [refId, setRefId] = mtUseState(preset ? preset.refId : '');
const [grav, setGrav] = mtUseState('leve');
const [desc, setDesc] = mtUseState('');
const [q, setQ] = mtUseState('');
const options = mtUseMemo(() => {
const src = target === 'equipo'
? (equipos || []).map(e => ({ id: e.id, label: `${e.code} — ${e.name}` }))
: (machines || []).map(m => ({ id: m.code || m.id, label: `${m.code || m.id} — ${m.name || ''}` }));
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean);
return src.filter(o => words.every(w => o.label.toLowerCase().includes(w)));
}, [target, equipos, machines, q]);
const submit = () => {
if (!refId || !desc.trim()) return;
onReport(target, refId, desc.trim(), grav);
};
return (
e.stopPropagation()}>
{window.t('⚠ Reportar falla')}
setQ(e.target.value)} />
{options.length === 0 &&
{target === 'equipo' ? window.t('No hay equipos registrados todavía') : window.t('Sin máquinas para este filtro')}
}
);
}
function MtResolveModal({ item, userName, onResolve, onClose }) {
const [fecha, setFecha] = mtUseState(cpCaracasDateStr());
const [por, setPor] = mtUseState(userName || '');
const [sol, setSol] = mtUseState('');
return (
e.stopPropagation()}>
{window.t('✓ Marcar como resuelta')} — {item.code}
{item.falla.descripcion}
);
}
// ── Vista principal ─────────────────────────────────────────────────
function MantenimientoView({ equipos, machines, machineProfiles, canManage, userName, onChangeEquipos,
onReportMachineFalla, onResolveMachineFalla, onOpenEquipos }) {
const meta = window.EQUIPO_META;
const list = equipos || [];
const [tab, setTab] = mtUseState('abiertas');
const [q, setQ] = mtUseState('');
const [areaF, setAreaF] = mtUseState('');
const [gravF, setGravF] = mtUseState('');
const [showNew, setShowNew] = mtUseState(false);
const [showFalla, setShowFalla] = mtUseState(false);
const [showReport, setShowReport] = mtUseState(false);
const [resolving, setResolving] = mtUseState(null);
const [detailId, setDetailId] = mtUseState(null);
const [fallaPreset, setFallaPreset] = mtUseState(null);
const all = mtUseMemo(() => mtCollectFallas(list, machines, machineProfiles), [list, machines, machineProfiles]);
const open = mtUseMemo(() => all.filter(r => !r.falla.resuelta), [all]);
const today = cpCaracasDateStr();
const kpi = mtUseMemo(() => ({
equipos: list.length,
enFalla: list.filter(e => (e.status || 'operativo') === 'falla').length,
enMant: list.filter(e => e.status === 'mantenimiento').length,
abiertas: open.length,
urgentes: open.filter(r => r.falla.gravedad === 'urgente').length,
vencidos: list.filter(e => e.proximoMantenimiento && e.proximoMantenimiento < today).length,
}), [list, open, today]);
const match = (r) => {
if (areaF && r.area !== areaF) return false;
if (gravF && r.falla.gravedad !== gravF) return false;
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean);
const hay = `${r.code} ${r.name} ${r.falla.descripcion || ''} ${r.falla.reportadoPor || ''}`.toLowerCase();
return words.every(w => hay.includes(w));
};
const cmpGrav = (a, b) => ((MT_GRAV[a.falla.gravedad] || {}).order ?? 9) - ((MT_GRAV[b.falla.gravedad] || {}).order ?? 9);
const shownOpen = open.filter(match).sort((a, b) => cmpGrav(a, b) || (a.falla.fechaReporte || '').localeCompare(b.falla.fechaReporte || ''));
const shownDone = all.filter(r => r.falla.resuelta).filter(match)
.sort((a, b) => (b.falla.fechaResolucion || '').localeCompare(a.falla.fechaResolucion || ''));
const shownEq = list.filter(e => {
if (areaF && e.area !== areaF) return false;
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean);
return words.every(w => `${e.code} ${e.name} ${e.marca || ''} ${e.serial || ''}`.toLowerCase().includes(w));
});
const saveEquipo = (id, patch) => onChangeEquipos(list.map(e => e.id === id ? { ...e, ...patch } : e));
const reportFalla = (target, refId, descripcion, gravedad) => {
if (target === 'maquina') {
onReportMachineFalla && onReportMachineFalla(refId, descripcion, gravedad);
} else {
const eq = list.find(e => e.id === refId);
if (!eq) return;
const f = { id: 'f' + Date.now() + Math.random().toString(36).slice(2, 5), descripcion, gravedad,
fechaReporte: today, reportadoPor: userName || 'Mantenimiento', resuelta: false, fechaResolucion: null, solucion: '' };
saveEquipo(refId, { fallas: [...(eq.fallas || []), f], status: 'falla' });
}
setShowFalla(false); setFallaPreset(null);
};
const resolveFalla = (item, data) => {
if (item.kind === 'maquina') {
onResolveMachineFalla && onResolveMachineFalla(item.refId, item.falla.id, data);
} else {
const eq = list.find(e => e.id === item.refId);
if (!eq) return;
const next = (eq.fallas || []).map(f => f.id === item.falla.id
? { ...f, resuelta: true, fechaResolucion: data.fecha, solucion: data.solucion, reparadoPor: data.reparadoPor } : f);
saveEquipo(eq.id, { fallas: next, status: next.some(f => !f.resuelta) ? 'falla' : 'operativo' });
}
setResolving(null);
};
const FallaRow = ({ r }) => {
const f = r.falla;
const g = MT_GRAV[f.gravedad] || MT_GRAV.leve;
return (
{r.code}
{r.name}
{r.tipo}
{window.t(g.label)}
{mtFmtDate(f.fechaReporte)}
{!f.resuelta && {mtDaysOpen(f.fechaReporte)} {window.t('día(s) abierta')}}
{window.t('por')} {f.reportadoPor || '—'}
{f.descripcion}
{f.resuelta && (
✓ {mtFmtDate(f.fechaResolucion)}{f.reparadoPor ? ` · ${f.reparadoPor}` : ''}{f.solucion ? ` — ${f.solucion}` : ''}
)}
{!f.resuelta && canManage && (
)}
);
};
const detail = detailId ? list.find(e => e.id === detailId) : null;
return (
🔧 {window.t('Mantenimiento')}
{window.t('Registro de equipos, reporte de fallas e informes')}
{canManage && }
{onOpenEquipos && }
{kpi.equipos}{window.t('Equipos')}
{kpi.abiertas}{window.t('Fallas abiertas')}
{kpi.urgentes}{window.t('Urgentes')}
{kpi.enFalla}{window.t('Equipos en falla')}
{kpi.enMant}{window.t('En mantenimiento')}
{kpi.vencidos}{window.t('Mant. vencido')}
{[['abiertas', 'Fallas abiertas', kpi.abiertas], ['resueltas', 'Resueltas', shownDone.length], ['equipos', 'Equipos', list.length]].map(([k, l, n]) => (
))}
setQ(e.target.value)} />
{tab !== 'equipos' && (
)}
{tab === 'abiertas' && (shownOpen.length === 0
?
✅
{window.t('Sin fallas activas')}
: shownOpen.map(r =>
))}
{tab === 'resueltas' && (shownDone.length === 0
?
📋
{window.t('Sin fallas resueltas')}
: shownDone.map(r =>
))}
{tab === 'equipos' && (shownEq.length === 0
?
🧰
{list.length === 0 ? window.t('No hay equipos registrados todavía') : window.t('Sin resultados para este filtro')}
:
{shownEq.map(e => {
const st = meta.STATUS[e.status || 'operativo'] || meta.STATUS.operativo;
const act = (e.fallas || []).filter(f => !f.resuelta).length;
const venc = e.proximoMantenimiento && e.proximoMantenimiento < today;
return (
{e.code}
{e.name}
{window.t(meta.categoryLabel(e.category))}{e.marca ? ` · ${e.marca}` : ''}{e.modelo ? ` ${e.modelo}` : ''}
{e.area &&
{window.t(meta.areaLabel(e.area))}}
{e.proximoMantenimiento &&
🛠 {mtFmtDate(e.proximoMantenimiento)}}
{window.t(st.label)}
{act > 0 &&
⚠ {act}}
);
})}
)}
{showNew &&
{ onChangeEquipos([...list, eq]); setShowNew(false); setTab('equipos'); }} onClose={() => setShowNew(false)} />}
{showFalla && { setShowFalla(false); setFallaPreset(null); }} />}
{showReport && setShowReport(false)} />}
{resolving && resolveFalla(resolving, d)} onClose={() => setResolving(null)} />}
{detail && window.EquipoDetailModal && (
saveEquipo(detail.id, patch)} onClose={() => setDetailId(null)} />
)}
);
}
window.MantenimientoView = MantenimientoView;