// ════════════════════════════════════════════
// Control de Proceso — Verona Color Paints
// ════════════════════════════════════════════
const { useState: cpUseState, useEffect: cpUseEffect, useMemo: cpUseMemo, useRef: cpUseRef } = React;
// URL absoluta del logo para las ventanas de impresión/PDF (se abren como
// about:blank vía document.write, por lo que una ruta relativa no resolvería).
const CP_LOGO_URL = (() => {
try { return new URL('logo-verona.png', document.baseURI).href; }
catch (_) { return 'logo-verona.png'; }
})();
// ─── Touch drag-and-drop (soporte para tablets) ───────────────────────────────
let _cpTouchItem = null; // datos del item siendo arrastrado por toque
let _cpTouchGhost = null; // elemento visual "fantasma"
const _cpDropReg = {}; // machineId → función de drop
function _cpGhostCreate(sourceEl, cx, cy) {
const r = sourceEl.getBoundingClientRect();
const g = sourceEl.cloneNode(true);
Object.assign(g.style, {
position: 'fixed', pointerEvents: 'none', zIndex: '9999',
width: r.width + 'px', opacity: '0.88',
top: (cy - r.height / 2) + 'px',
left: (cx - r.width / 2) + 'px',
transform: 'scale(1.06)',
boxShadow: '0 8px 28px rgba(0,0,0,.22)',
transition: 'none',
});
document.body.appendChild(g);
return g;
}
function _cpGhostMove(cx, cy) {
if (!_cpTouchGhost) return;
_cpTouchGhost.style.top = (cy - _cpTouchGhost.offsetHeight / 2) + 'px';
_cpTouchGhost.style.left = (cx - _cpTouchGhost.offsetWidth / 2) + 'px';
}
function _cpGhostEnd() {
if (_cpTouchGhost) { _cpTouchGhost.remove(); _cpTouchGhost = null; }
document.querySelectorAll('.proc-row.touch-drag-over')
.forEach(el => el.classList.remove('touch-drag-over'));
}
function _cpTouchHandleEnd(cx, cy) {
const target = document.elementFromPoint(cx, cy);
const row = target && target.closest('[data-cp-mid]');
if (row && _cpTouchItem) {
const fn = _cpDropReg[row.getAttribute('data-cp-mid')];
if (fn) fn(_cpTouchItem);
}
}
// Manejadores reutilizables para onTouchMove sobre items arrastrables
function _cpItemTouchMove(e) {
if (!_cpTouchItem) return;
e.preventDefault();
const t = e.touches[0];
_cpGhostMove(t.clientX, t.clientY);
const el = document.elementFromPoint(t.clientX, t.clientY);
const row = el && el.closest('[data-cp-mid]');
document.querySelectorAll('.proc-row.touch-drag-over')
.forEach(r => r.classList.remove('touch-drag-over'));
if (row) row.classList.add('touch-drag-over');
}
function _cpItemTouchEnd(e) {
if (!_cpTouchItem) return;
const t = e.changedTouches[0];
_cpTouchHandleEnd(t.clientX, t.clientY);
_cpGhostEnd();
_cpTouchItem = null;
}
function _cpItemTouchCancel() {
_cpGhostEnd();
_cpTouchItem = null;
}
// ─── Paleta de colores para máquinas ─────────
const CP_MACHINE_COLORS = [
'#3b6fd4','#138a52','#b56e08','#6b46c1',
'#c43050','#0891b2','#059669','#d97706',
];
// ─── Utilities ───────────────────────────────
function cpUid() {
return 'cp' + Math.random().toString(36).slice(2, 9);
}
function cpFormatDuration(secs) {
if (!secs || secs < 0) return '00:00';
const h = Math.floor(secs / 3600);
const m = Math.floor((secs % 3600) / 60);
const s = secs % 60;
if (h > 0) return `${h}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
return `${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
}
function cpElapsed(phase) {
if (!phase) return 0;
const acc = phase.accumulated || 0;
if (!phase.running || !phase.startedAt) return acc;
// Math.max(0, …) evita valores negativos por desfases de reloj (p. ej. una
// fase iniciada en otra máquina cuyo startedAt quedó adelantado).
return acc + Math.max(0, Math.floor((cpNowMs() - phase.startedAt) / 1000));
}
function cpMachineTotalSeconds(machine) {
return (machine.phases || []).reduce((s, p) => {
let pSecs = 0;
if (p.startTime && p.endTime) {
const diff = cpCalcTimeDiffMins(p.startTime, p.endTime);
if (diff !== null) pSecs += diff * 60;
} else {
pSecs += cpElapsed(p);
}
(p.extraSegments || []).forEach(seg => {
if (seg.start && seg.end) {
const d = cpCalcTimeDiffMins(seg.start, seg.end);
if (d !== null) pSecs += d * 60;
}
});
return s + pSecs;
}, 0);
}
function cpMachineProgress(machine) {
const phases = machine.phases || [];
if (!phases.length) return 0;
const done = phases.filter(p => p.status === 'done').length;
return Math.round((done / phases.length) * 100);
}
function cpMachineStatus(machine) {
const phases = machine.phases || [];
if (!phases.length) return 'idle';
if (phases.every(p => p.status === 'done')) return 'done';
if (phases.some(p => p.running)) return 'running';
if (phases.some(p => p.status === 'paused')) return 'paused';
return 'idle';
}
function cpMachineTypePrefix(type) {
const map = { dispersor: 'DISP', dispersor1: 'DISPM', dispersorp: 'DISPP', envasado: 'ENV', mezclador: 'MIX', molino: 'MOL', empaquetadora: 'EMP' };
return map[type] || 'MAQ';
}
// ── Empaques de la empaquetadora ────────────────────────────
// Lo que realmente salió empacado del batch, por presentación. El reporte
// diario usa esto en vez del galonaje de la tolva.
// Ej.: una tolva de 200 GL → 400 cuñas (0,25 GL c/u = 100 GL) + 100 GL.
const CP_EMP_TIPOS = [
{ id: 'ku', label: 'Cuña (1/4 GL)', gl: 0.25 },
{ id: 'gl', label: 'Galón', gl: 1 },
{ id: 'cu4', label: 'Cuñete 4 GL', gl: 4 },
{ id: 'cu7', label: 'Cuñete 2 GL', gl: 2 },
{ id: 'p4', label: '4 L', gl: 1.056 },
{ id: 'pl', label: '1 L', gl: 0.264 },
{ id: 'pm', label: '0,5 L', gl: 0.132 },
];
const cpFmtGL = (n) => {
const v = Number(n || 0);
return Number.isInteger(v) ? String(v) : v.toFixed(2).replace(/\.?0+$/, '');
};
const cpEmpTipo = (id) => CP_EMP_TIPOS.find(t => t.id === id) || null;
const cpEmpLabel = (id) => (cpEmpTipo(id) || {}).label || id;
// Galones equivalentes de una lista de empaques [{tipo, cantidad}].
function cpEmpaquesGL(empaques) {
return (empaques || []).reduce((s, e) => {
const t = cpEmpTipo(e.tipo);
return s + (t ? t.gl * (Number(e.cantidad) || 0) : 0);
}, 0);
}
// Resumen legible: "400 Cuña (1/4 GL) · 100 Galón"
function cpEmpaquesResumen(empaques) {
return (empaques || [])
.filter(e => Number(e.cantidad) > 0)
.map(e => `${Number(e.cantidad)} ${cpEmpLabel(e.tipo)}`)
.join(' · ');
}
// Hora final del batch. Los batches antiguos guardaban 'hrInicialBatch';
// se usa como respaldo para no perder el dato ya cargado.
function cpBatchHrFinal(m) {
if (!m) return '';
return m.hrFinalBatch || m.hrInicialBatch || '';
}
// Departamento de personal que opera cada tipo de máquina:
// Dispersor Matización → matización · Envasado/Empaque → envasado ·
// Dispersor / Pasta / Mezclador / Molino → preparadores.
function cpOperatorDept(type) {
if (type === 'dispersor1') return 'matizacion';
if (type === 'envasado' || type === 'empaquetadora') return 'envasado';
if (['dispersor', 'dispersorp', 'mezclador', 'molino'].includes(type)) return 'preparadores';
return null;
}
// Al liberar una máquina, otorga los puntos configurados para su tipo a los
// trabajadores que estuvieron en ella (el grupo o la persona del campo
// Operario). Los puntos por tipo se configuran en Personal → Puntos por
// máquina (solo administrador). El backend decide el monto y evita duplicados.
function cpAwardMachinePoints(machine, fecha) {
const toast = (m, k) => { if (window.showToast) window.showToast(m, k); };
const asgn = machine.assignments || [];
fetch('./api.php', {
method: 'POST', credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'prep_award_machine',
machine_id: machine.id,
machine_type: machine.type,
machine_name: `${machine.name || ''}${machine.code ? ' (' + machine.code + ')' : ''}`.trim(),
operario: machine.operario || '',
fecha: fecha || '',
// Identidad del batch: la máquina puede cerrarse varias veces al día y
// cada corrida (lote) debe otorgar sus propios puntos.
lote: machine.lote || '',
hr_inicial: cpBatchHrFinal(machine),
cantidad: machine.cantidad || '',
// Lo que llevó el batch: suma los extras por base y por color.
n_bases: asgn.filter(a => a.kind === 'base').length,
n_colors: asgn.filter(a => a.kind === 'color').length,
}),
})
.then(r => r.json().catch(() => ({})))
.then(j => {
if (!j || j.error) return; // silencioso: no bloquea el cierre
if (j.awarded) {
const det = [j.nBases ? `${j.nBases} base(s)` : '', j.nColors ? `${j.nColors} color(es)` : ''].filter(Boolean).join(' + ');
toast(`+${j.points} pts a ${j.count} persona(s) · ${j.operario}${det ? ' · ' + det : ''}`);
} else if (j.reason === 'sin_puntos_configurados') {
toast('Máquina liberada. Sin puntos configurados para este tipo de máquina.', 'err');
} else if (j.reason === 'operario_sin_personal') {
toast(`Máquina liberada. "${j.operario}" no tiene personal registrado.`, 'err');
}
})
.catch(() => {});
}
function cpNewMachine(type) {
const mt = (window.AppData.MACHINE_TYPES || {})[type] || {};
const phases = (mt.defaultPhases || ['Fase 1', 'Fase 2']).map(name => ({
id: cpUid(), name,
status: 'pending', running: false,
startedAt: null, accumulated: 0,
startTime: '', endTime: '',
phaseStatus: 'pendiente',
}));
return {
id: cpUid(), type, name: mt.name || type,
code: '', color: '',
phases, assignments: [], notes: '',
lote: '', cantidad: '',
fecha: cpCaracasDateStr(),
hrFinalBatch: '', operario: '',
};
}
// Venezuela Standard Time = UTC-4 — delega en el reloj interno de components.jsx
const _CP_VET_MS = -4 * 60 * 60 * 1000;
function cpGetVetOffset() { return 0; }
function cpVetNow() { return typeof vetNow === 'function' ? vetNow() : new Date(Date.now() + _CP_VET_MS); }
// Epoch (ms) sincronizado con el servidor — NO depende del reloj del PC.
// Se usa para cronometrar las fases: así el tiempo es idéntico en todas las
// máquinas aunque su reloj del sistema esté adelantado o atrasado.
function cpNowMs() { return cpVetNow().getTime() - _CP_VET_MS; }
function cpCaracasDateStr() {
const d = cpVetNow();
return d.getUTCFullYear() + '-' +
(d.getUTCMonth() + 1).toString().padStart(2,'0') + '-' +
d.getUTCDate().toString().padStart(2,'0');
}
function cpNextDayStr(dateStr) {
const base = dateStr || cpCaracasDateStr();
const d = new Date(base + 'T12:00:00Z');
d.setUTCDate(d.getUTCDate() + 1);
return d.toISOString().slice(0, 10);
}
function cpFmtShortDate(dateStr) {
if (!dateStr) return '';
const [, m, day] = dateStr.split('-');
return `${parseInt(day)}/${parseInt(m)}`;
}
function cpNowHHMM() {
const d = cpVetNow();
return d.getUTCHours().toString().padStart(2,'0') + ':' +
d.getUTCMinutes().toString().padStart(2,'0');
}
// Formatea un ISO timestamp almacenado (UTC) a fecha/hora legible en VET
const _CP_MONTHS_SHORT = ['ene','feb','mar','abr','may','jun','jul','ago','sep','oct','nov','dic'];
function cpFmtVetTimestamp(isoStr, opts = {}) {
const d = new Date(new Date(isoStr).getTime() + _CP_VET_MS);
const day = d.getUTCDate().toString().padStart(2,'0');
const mon = _CP_MONTHS_SHORT[d.getUTCMonth()];
const year = d.getUTCFullYear();
const hh = d.getUTCHours().toString().padStart(2,'0');
const mm = d.getUTCMinutes().toString().padStart(2,'0');
return opts.sep
? `${day} ${mon} ${year} · ${hh}:${mm}`
: `${day} ${mon} ${year} ${hh}:${mm}`;
}
// ─── Helpers de tiempo manual ─────────────────
// Convierte "HH:MM" a minutos totales desde medianoche
function cpTimeToMins(t) {
if (!t) return null;
const parts = t.split(':');
if (parts.length < 2) return null;
const h = parseInt(parts[0], 10);
const m = parseInt(parts[1], 10);
if (isNaN(h) || isNaN(m)) return null;
return h * 60 + m;
}
// Diferencia en minutos entre dos strings "HH:MM". Admite cruce de medianoche.
function cpCalcTimeDiffMins(startTime, endTime) {
const s = cpTimeToMins(startTime);
const e = cpTimeToMins(endTime);
if (s === null || e === null) return null;
let diff = e - s;
if (diff < 0) diff += 24 * 60;
return diff;
}
// Minutos a mostrar en la columna MIN:
// Prioriza la diferencia entre HR INICIAL y HR FINAL si ambas existen,
// de lo contrario usa el cronómetro acumulado.
function cpPhaseDisplayMins(phase) {
let total = 0;
if (phase.startTime && phase.endTime) {
const diff = cpCalcTimeDiffMins(phase.startTime, phase.endTime);
if (diff !== null) total += diff;
} else {
const elapsed = cpElapsed(phase);
if (elapsed > 0) total += Math.floor(elapsed / 60);
}
(phase.extraSegments || []).forEach(seg => {
if (seg.start && seg.end) {
const d = cpCalcTimeDiffMins(seg.start, seg.end);
if (d !== null) total += d;
}
});
return total > 0 ? total : null;
}
// ─── Ícono: Reset (flecha circular) ──────────
const ResetIcon = (p) => (
);
// ─── BasesPanel ──────────────────────────────
function BasesPanel({ bases, machines, canEdit, onAddBase, onAddColor, onCancelBase, onUpdateBase }) {
const [filter, setFilter] = cpUseState('all');
const [search, setSearch] = cpUseState('');
const isAssigned = (itemId) =>
machines.some(m => (m.assignments || []).some(a => a.id === itemId));
const deriveBaseStatus = (b) => {
if (b.status === 'cancelled') return 'cancelled';
if (b.status === 'done' || b.checkFN || b.colors.filter(c => !c.cancelled).every(c => c.checkEM || c.status === 'ready')) return 'done';
if (isAssigned(b.id) || b.status === 'running' || b.checkEC || b.colors.some(c => c.checkEC)) return 'running';
return 'pending';
};
const STATUS_LABELS = { all: 'Todas', pending: 'Pend.', running: 'En Proc.', done: 'Final.', cancelled: 'Canc.' };
const STATUS_COUNTS = { all: bases.length };
bases.forEach(b => {
const s = deriveBaseStatus(b);
STATUS_COUNTS[s] = (STATUS_COUNTS[s] || 0) + 1;
});
// Aplicar filtro de estado
let filtered = filter === 'all' ? bases : bases.filter(b => deriveBaseStatus(b) === filter);
// Aplicar búsqueda
const searchQ = search.trim().toLowerCase();
if (searchQ) {
filtered = filtered.filter(b =>
b.nombre.toLowerCase().includes(searchQ) ||
(b.code || '').toLowerCase().includes(searchQ) ||
(b.lote || '').toLowerCase().includes(searchQ) ||
(b.colors || []).some(c =>
c.nombre.toLowerCase().includes(searchQ) ||
(c.lote || '').toLowerCase().includes(searchQ)
)
);
}
const BASE_STATUS_PILL = {
pending: { label: 'Pendiente', cls: 'pending' },
running: { label: 'En Proceso', cls: 'running' },
done: { label: 'Finalizada', cls: 'done' },
cancelled: { label: 'Cancelada', cls: 'cancelled'},
};
return (
BASES DE PRODUCCIÓN
{/* ── Buscador ── */}
setSearch(e.target.value)}
/>
{search && (
setSearch('')}>×
)}
{/* ── Filtros de estado ── */}
{['all', 'pending', 'running', 'done'].map(f => (
setFilter(f)}
>
{STATUS_LABELS[f]}
))}
{filtered.length === 0 && (
{searchQ ? `Sin resultados para "${search}"` : `Sin bases ${filter !== 'all' ? `"${STATUS_LABELS[filter].toLowerCase()}"` : 'planificadas'} para hoy`}
)}
{filtered.map(b => {
const bStatus = deriveBaseStatus(b);
const pill = BASE_STATUS_PILL[bStatus];
const assigned = isAssigned(b.id);
const doneColors = b.colors.filter(c => (c.checkEM || c.status === 'ready') && !c.cancelled).length;
const totalColors = b.colors.length;
const pct = totalColors ? Math.round(doneColors / totalColors * 100) : 0;
const visibleColors = searchQ
? (b.colors || []).filter(c => c.nombre.toLowerCase().includes(searchQ) || b.nombre.toLowerCase().includes(searchQ))
: (b.colors || []);
return (
{
if (assigned || bStatus === 'cancelled') return;
e.dataTransfer.setData('cp-item', JSON.stringify({
id: b.id, kind: 'base', nombre: b.nombre, code: b.code,
cantidad: b.cantidad, unit: b.unit, color: b.color,
tipo: b.tipo, colorsCount: b.colors.length,
}));
}}
onTouchStart={e => {
if (assigned || bStatus === 'cancelled') return;
_cpTouchItem = {
id: b.id, kind: 'base', nombre: b.nombre, code: b.code,
cantidad: b.cantidad, unit: b.unit, color: b.color,
tipo: b.tipo, colorsCount: b.colors.length,
};
const t = e.touches[0];
_cpTouchGhost = _cpGhostCreate(e.currentTarget, t.clientX, t.clientY);
}}
onTouchMove={_cpItemTouchMove}
onTouchEnd={_cpItemTouchEnd}
onTouchCancel={_cpItemTouchCancel}
>
{b.nombre}
{b.code} · {b.colors.length} colores · {b.cantidad} {b.unit}
{b.carryoverFrom && (() => {
const f = fmtDate(b.carryoverFrom);
return (
↩ pendiente del {f.day} {f.month.toLowerCase().slice(0, 3)}
);
})()}
{/* Barra de avance */}
{totalColors > 0 && bStatus !== 'cancelled' && (
)}
{assigned && EN MÁQUINA }
{canEdit && onCancelBase && bStatus !== 'cancelled' && bStatus !== 'done' && (
{
e.stopPropagation();
if (confirm(`¿Cancelar la base "${b.nombre}"?`)) onCancelBase(b.id);
}}
>✕
)}
{canEdit && onCancelBase && bStatus === 'cancelled' && (
{ e.stopPropagation(); onCancelBase(b.id, true); }}
>↩
)}
{visibleColors.length > 0 && bStatus !== 'cancelled' && (
{visibleColors.map(c => {
const colorAssigned = isAssigned(c.id);
const cStatus = c.checkEM ? 'ready' : c.checkEC ? 'running' : 'pending';
return (
{
if (colorAssigned) return;
e.dataTransfer.setData('cp-item', JSON.stringify({
id: c.id, kind: 'color', nombre: c.nombre,
cantidad: c.cantidad, unit: c.unit || b.unit,
color: c.hex || '#ccc', parentId: b.id,
}));
}}
onTouchStart={e => {
if (colorAssigned) return;
_cpTouchItem = {
id: c.id, kind: 'color', nombre: c.nombre,
cantidad: c.cantidad, unit: c.unit || b.unit,
color: c.hex || '#ccc', parentId: b.id,
};
const t = e.touches[0];
_cpTouchGhost = _cpGhostCreate(e.currentTarget, t.clientX, t.clientY);
}}
onTouchMove={_cpItemTouchMove}
onTouchEnd={_cpItemTouchEnd}
onTouchCancel={_cpItemTouchCancel}
>
{c.nombre}
{c.lote ? `${c.lote} · ` : ''}{c.cantidad} {c.unit || b.unit}
{colorAssigned &&
✓ }
);
})}
{canEdit && onAddColor && !searchQ && (
onAddColor(b.id)}>
Agregar color a esta base
)}
)}
{(b.formulaTipo === 'molienda' || b.formulaTipo === 'ambas') && bStatus !== 'cancelled' && (() => {
const molId = b.id + ':mol';
const molAssigned = isAssigned(molId);
const molNombre = (b.molienda && b.molienda.producto) ? b.molienda.producto : (b.nombre + ' (molienda)');
const molCant = (b.molienda && b.molienda.cantidad) ? b.molienda.cantidad : '';
const molLote = (b.molienda && b.molienda.lote) ? b.molienda.lote : (b.lote || '');
const molPayload = { id: molId, kind: 'molienda', nombre: molNombre, cantidad: molCant, unit: 'Kg', color: '#b45309', parentId: b.id, lote: molLote };
return (
{ if (molAssigned) return; e.dataTransfer.setData('cp-item', JSON.stringify(molPayload)); }}
onTouchStart={e => { if (molAssigned) return; _cpTouchItem = molPayload; const t = e.touches[0]; _cpTouchGhost = _cpGhostCreate(e.currentTarget, t.clientX, t.clientY); }}
onTouchMove={_cpItemTouchMove}
onTouchEnd={_cpItemTouchEnd}
onTouchCancel={_cpItemTouchCancel}
>
🧪 {molNombre}
Molienda{molLote ? ` · ${molLote}` : ''}{molCant ? ` · ${molCant} Kg` : ''}
{molAssigned &&
✓ }
);
})()}
);
})}
{canEdit && onAddBase && (
Nueva base
)}
);
}
// ─── PhaseRow ─────────────────────────────────
function PhaseRow({ phase, canEdit, onUpdate, onRemove, tick, isDragOver, onDragStart, onDragOver, onDragEnd, phaseIndex, batchDate, phaseOptions }) {
const PHASE_STATUSES = window.AppData.PHASE_STATUSES || [];
const isContinuation = phase.phaseDate && phase.phaseDate !== batchDate;
// MIN: prioriza diferencia HR INICIAL/HR FINAL; si no, usa cronómetro
const displayMins = cpPhaseDisplayMins(phase);
// Segundos acumulados para el display HH:MM:SS del cronómetro
const totalSecs = cpElapsed(phase);
// Cuando cambia una hora manual, sincroniza el acumulado del cronómetro
const syncAccumulated = (startTime, endTime) => {
const diff = cpCalcTimeDiffMins(startTime, endTime);
return diff !== null ? diff * 60 : phase.accumulated;
};
const start = () => {
if (!canEdit || phase.running) return;
const now = cpNowHHMM();
const newStart = phase.startTime || now;
onUpdate({ ...phase, running: true, startedAt: cpNowMs(), status: 'running', startTime: newStart });
};
const stopPhase = () => {
if (!canEdit || !phase.running) return;
onUpdate({ ...phase, running: false, accumulated: cpElapsed(phase), startedAt: null, status: 'paused' });
};
const finish = () => {
if (!canEdit) return;
const endTime = phase.endTime || cpNowHHMM();
const acc = syncAccumulated(phase.startTime, endTime) || cpElapsed(phase);
onUpdate({ ...phase, running: false, accumulated: acc, startedAt: null,
status: 'done', endTime });
};
const reset = () => {
if (!canEdit) return;
onUpdate({ ...phase, running: false, accumulated: 0, startedAt: null,
status: 'pending', startTime: '', endTime: '', phaseStatus: 'pendiente' });
};
// Alerta de tiempo límite
const limitMins = phase.limitMins ? Number(phase.limitMins) : null;
const isOverLimit = limitMins && displayMins !== null && displayMins > limitMins;
const isApproachingLimit = limitMins && displayMins !== null && !isOverLimit && displayMins >= limitMins * 0.85;
return (
{ e.preventDefault(); onDragOver && onDragOver(phaseIndex); }}
onDragLeave={() => onDragOver && onDragOver(null)}
onDrop={e => { e.preventDefault(); onDragEnd && onDragEnd(); }}
>
onDragStart && onDragStart()}
onDragEnd={() => onDragEnd && onDragEnd()}
>
{
if (!canEdit) return;
const newStart = e.target.value;
const acc = syncAccumulated(newStart, phase.endTime);
onUpdate({ ...phase, startTime: newStart, accumulated: acc });
}}
/>
{
if (!canEdit) return;
const now = cpNowHHMM();
const acc = syncAccumulated(now, phase.endTime);
onUpdate({ ...phase, startTime: now, accumulated: acc });
}}
disabled={!canEdit}
title="Hora actual"
>
{
if (!canEdit) return;
const newEnd = e.target.value;
const acc = syncAccumulated(phase.startTime, newEnd);
onUpdate({ ...phase, endTime: newEnd, accumulated: acc });
}}
/>
{
if (!canEdit) return;
const now = cpNowHHMM();
const acc = syncAccumulated(phase.startTime, now);
onUpdate({ ...phase, endTime: now, accumulated: acc });
}}
disabled={!canEdit}
title="Hora actual"
>
{displayMins !== null ? displayMins : '–'}
{isOverLimit && ⚠ }
{canEdit ? (
onUpdate({ ...phase, limitMins: e.target.value ? Number(e.target.value) : null })}
title="Tiempo límite (minutos)"
/>
) : (
phase.limitMins ? {phase.limitMins}m : null
)}
{phase.status !== 'done' ? (
<>
{!phase.running ? (
) : (
)}
>
) : (
✓
)}
{canEdit && (
)}
);
}
// ─── FallaModal ───────────────────────────────
function FallaModal({ machine, profile, onSave, onClose }) {
const fallas = profile.fallas || [];
const mantenimientos = profile.mantenimientos || [];
const [tab, setTab] = cpUseState('activas');
const [showAddFalla, setShowAddFalla] = cpUseState(false);
const [newDesc, setNewDesc] = cpUseState('');
const [newGrav, setNewGrav] = cpUseState('leve');
const [resolveId, setResolveId] = cpUseState(null);
const [resFecha, setResFecha] = cpUseState(cpCaracasDateStr());
const [resSol, setResSol] = cpUseState('');
const [resPor, setResPor] = cpUseState('');
const [resNumRep, setResNumRep] = cpUseState('');
const [showAddMant, setShowAddMant] = cpUseState(false);
const [mantDesc, setMantDesc] = cpUseState('');
const [mantPor, setMantPor] = cpUseState('');
const [mantFecha, setMantFecha] = cpUseState(cpCaracasDateStr());
const [mantNumRep, setMantNumRep] = cpUseState('');
const activeFallas = fallas.filter(f => !f.resuelta);
const resolvedFallas = fallas.filter(f => f.resuelta);
const gravLabel = { leve: 'Leve', medio: 'Medio', urgente: 'Urgente' };
const gravCls = { leve: 'falla-badge--leve', medio: 'falla-badge--medio', urgente: 'falla-badge--urgente' };
const addFalla = () => {
if (!newDesc.trim()) return;
const f = {
id: 'f' + Date.now() + Math.random().toString(36).slice(2, 5),
descripcion: newDesc.trim(), gravedad: newGrav,
fechaReporte: cpCaracasDateStr(), reportadoPor: 'Admin',
resuelta: false, fechaResolucion: null, solucion: '',
};
onSave({ ...profile, fallas: [...fallas, f] });
setNewDesc(''); setNewGrav('leve'); setShowAddFalla(false);
};
const resolverFalla = (id) => {
if (!resSol.trim()) return;
onSave({ ...profile, fallas: fallas.map(f => f.id === id ? { ...f, resuelta: true, fechaResolucion: resFecha, solucion: resSol.trim(), reparadoPor: resPor.trim(), numeroReporte: resNumRep.trim() } : f) });
setResolveId(null); setResSol(""); setResFecha(cpCaracasDateStr()); setResPor(""); setResNumRep("");
};
const addMantenimiento = () => {
if (!mantDesc.trim()) return;
const m = {
id: 'm' + Date.now() + Math.random().toString(36).slice(2, 5),
fecha: mantFecha, descripcion: mantDesc.trim(),
realizadoPor: mantPor.trim(), numeroReporte: mantNumRep.trim(),
};
onSave({ ...profile, mantenimientos: [...mantenimientos, m] });
setMantDesc(''); setMantPor(''); setMantFecha(cpCaracasDateStr()); setMantNumRep(''); setShowAddMant(false);
};
const toggleStatus = () => {
onSave({ ...profile, status: (profile.status || 'operativa') === 'operativa' ? 'inactiva' : 'operativa' });
};
return (
e.stopPropagation()}>
{machine.code || machine.id}
{machine.name}
{(profile.status || 'operativa') === 'operativa' ? '✓ OPERATIVA' : '✗ INACTIVA'}
{
const html = cpGenerateMachineReportHtml(machine, profile);
const w = window.open('', '_blank');
w.document.write(html);
w.document.close();
}}
title="Imprimir ficha de máquina"
>{window.t('🖨 Imprimir')}
✕
setTab('activas')}>
{window.t('Fallas activas')}{activeFallas.length > 0 ? {activeFallas.length} : null}
setTab('historial')}>
{window.t('Resueltas')}{resolvedFallas.length > 0 ? {resolvedFallas.length} : null}
setTab('mantenimiento')}>
{window.t('Mantenimiento')}{mantenimientos.length > 0 ? {mantenimientos.length} : null}
{tab === 'activas' && (
{activeFallas.length === 0 && !showAddFalla && (
{window.t('Sin fallas activas')}
)}
{activeFallas.map(f => (
{gravLabel[f.gravedad]}
{f.fechaReporte}
{window.t('por')} {f.reportadoPor}
{f.descripcion}
{resolveId === f.id ? (
) : (
{ setResolveId(f.id); setResSol(''); setResFecha(cpCaracasDateStr()); setResPor(''); setResNumRep(''); }}>
{window.t('✓ Marcar como resuelta')}
)}
))}
{showAddFalla ? (
setNewGrav(e.target.value)}>
{window.t('Leve')}
{window.t('Medio')}
{window.t('Urgente')}
) : (
setShowAddFalla(true)}>{window.t('⚠ Reportar nueva falla')}
)}
)}
{tab === 'historial' && (
{resolvedFallas.length === 0 &&
{window.t('Sin fallas resueltas')}
}
{resolvedFallas.map(f => (
{gravLabel[f.gravedad]}
{window.t('Reportada:')} {f.fechaReporte}
{window.t('✓ Resuelta:')} {f.fechaResolucion}
{f.descripcion}
{f.solucion &&
Solución: {f.solucion}
}
))}
)}
{tab === 'mantenimiento' && (
{mantenimientos.length === 0 && !showAddMant && (
{window.t('Sin registros de mantenimiento')}
)}
{[...mantenimientos].reverse().map(m => (
{m.fecha}
{m.realizadoPor && {window.t('por')} {m.realizadoPor} }
{m.numeroReporte && Reporte #{m.numeroReporte} }
{m.descripcion}
))}
{showAddMant ? (
) : (
setShowAddMant(true)}>{window.t('+ Registrar mantenimiento')}
)}
)}
);
}
// ─── CPProcessRow ─────────────────────────────
function CPProcessRow({ machine, canEdit, isAdmin, profile, onSaveProfile, onShowFallaModal, onUpdate, onRemove, tick, isOpen, onToggle, onBaseComplete, onBaseStarted, onAssignmentRemoved, onMoliendaComplete, cpDate, equipos, onEquiposChange }) {
const MACHINE_TYPES = window.AppData.MACHINE_TYPES || {};
const mt = MACHINE_TYPES[machine.type] || {};
const status = cpMachineStatus(machine);
const totalSecs = cpMachineTotalSeconds(machine);
const totalMins = Math.floor(totalSecs / 60);
const donePhases = (machine.phases || []).filter(p => p.status === 'done').length;
const totalPhases = (machine.phases || []).length;
const open = isOpen !== undefined ? isOpen : false;
const [dragOver, setDragOver] = cpUseState(false);
const [dragPhaseIdx, setDragPhaseIdx] = cpUseState(null);
const [dragOverPhaseIdx, setDragOverPhaseIdx] = cpUseState(null);
const [editingMeta, setEditingMeta] = cpUseState(false);
const [editCode, setEditCode] = cpUseState('');
const [editName, setEditName] = cpUseState('');
const [showMissing, setShowMissing] = cpUseState(false);
// Casillas del batch que deben estar llenas antes de guardar la máquina
const isEmptyVal = (v) => !String(v ?? '').trim();
const batchMissing = () => {
const faltan = [];
if (!(machine.assignments || []).length) faltan.push('Asignación (base o color)');
if (isEmptyVal(machine.lote)) faltan.push('Lote');
if (isEmptyVal(machine.cantidad) || !(Number(machine.cantidad) > 0)) faltan.push('Cantidad (GL)');
if (isEmptyVal(machine.fecha)) faltan.push('Fecha');
if (isEmptyVal(cpBatchHrFinal(machine))) faltan.push('Hr final batch');
// El molino se lleva en kilos: sin peso final la molienda entra sin cantidad.
if (machine.type === 'molino' && (isEmptyVal(machine.pesoFinalKg) || !(Number(machine.pesoFinalKg) > 0)))
faltan.push('Peso final (Kg)');
if (isEmptyVal(machine.operario)) faltan.push('Operario');
if (isEmptyVal(machine.notes)) faltan.push('Observaciones');
return faltan;
};
const requireBatchComplete = (accion) => {
const faltan = batchMissing();
if (faltan.length) {
setShowMissing(true);
alert(`⚠ Para ${accion} debes llenar todas las casillas disponibles.\n\nFalta completar:\n• ${faltan.join('\n• ')}`);
return false;
}
setShowMissing(false);
return true;
};
// Marca en rojo la casilla vacía después de un intento de guardado
const missCls = (empty) => (showMissing && empty) ? ' cp-batch-missing' : '';
// Registro del drop handler para soporte táctil (tablet)
const _cpDropRef = cpUseRef(null);
_cpDropRef.current = (item) => {
if (!canEdit) return;
const accepts = mt.accepts || ['base', 'color'];
if (!accepts.includes(item.kind)) return;
if ((machine.assignments || []).some(a => a.id === item.id)) return;
onUpdate({ ...machine, fecha: cpDate, assignments: [...(machine.assignments || []), item] });
if (onBaseStarted) onBaseStarted(item.id, item.kind, cpDate, machine.type);
};
cpUseEffect(() => {
const mid = machine.id;
_cpDropReg[mid] = (item) => _cpDropRef.current && _cpDropRef.current(item);
return () => { delete _cpDropReg[mid]; };
}, [machine.id]);
const updatePhase = (idx, updated) => {
if (!canEdit) return;
const phases = [...machine.phases];
phases[idx] = updated;
onUpdate({ ...machine, phases });
};
const removePhase = (idx) => {
if (!canEdit) return;
onUpdate({ ...machine, phases: machine.phases.filter((_, i) => i !== idx) });
};
const movePhase = (from, to) => {
if (from === null || to === null || from === to) return;
const phases = [...machine.phases];
const [moved] = phases.splice(from, 1);
phases.splice(to, 0, moved);
onUpdate({ ...machine, phases });
};
const addPhase = () => {
if (!canEdit) return;
const defaultName = (mt.defaultPhases && mt.defaultPhases.length > 0) ? mt.defaultPhases[0] : 'Nueva fase';
const ph = {
id: cpUid(), name: defaultName, status: 'pending', running: false,
startedAt: null, accumulated: 0, startTime: '', endTime: '', phaseStatus: 'pendiente',
};
onUpdate({ ...machine, phases: [...machine.phases, ph] });
};
const liberar = () => {
if (!canEdit) return;
if (!requireBatchComplete('liberar la máquina')) return;
// Sin operario no se puede liberar: los puntos del cierre no tendrían
// a quién asignarse.
if (isEmptyVal(machine.operario)) {
setShowMissing(true);
alert('⚠ Asigna el Operario antes de liberar la máquina.\n\nLos puntos del cierre se otorgan al grupo o persona que estuvo en ella.');
return;
}
if (!confirm('¿Liberar esta máquina? Todas las fases serán marcadas como finalizadas.')) return;
const refDate = machine.fecha || cpDate;
const phases = machine.phases.map(p => ({
...p, running: false, status: 'done',
accumulated: cpElapsed(p), startedAt: null,
endTime: p.endTime || cpNowHHMM(),
}));
onUpdate({ ...machine, phases });
if (onBaseComplete) {
(machine.assignments || []).filter(a => a.kind === 'base').forEach(a => {
onBaseComplete(a.id, refDate);
});
}
if (machine.type === 'molino' && onMoliendaComplete) onMoliendaComplete(machine);
cpAwardMachinePoints(machine, refDate);
};
// ── Tolva / tanque asociado a la máquina ──────────────────
// Un solo proceso: se elige una tolva/tanque disponible y su
// "ocupación" (contenido/lote/proceso) se llena sola desde el batch.
const CONTAINER_CATS = ['tolva', 'tanque'];
const contenedores = (equipos || []).filter(e => CONTAINER_CATS.includes(e.category));
const contenedoresDisp = contenedores.filter(e => eqDisponible(e) || e.id === machine.tolvaId);
const tolvaLinked = contenedores.find(e => e.id === machine.tolvaId) || null;
const tolvaContenido = () => {
const a = (machine.assignments || [])[0];
return (a && a.nombre) || machine.name || '';
};
const tolvaProceso = () => {
const map = { dispersor: 'Dispersión', dispersor1: 'Dispersión', dispersorp: 'Dispersión', molino: 'Molienda', envasado: 'Envasado', empaquetadora: 'Empaque' };
return map[machine.type] || (MACHINE_TYPES[machine.type]?.name) || '';
};
const releaseTolva = (id) => {
if (!id || !onEquiposChange) return;
onEquiposChange((equipos || []).map(e =>
e.id === id && CONTAINER_CATS.includes(e.category)
? { ...e, disponible: true, contenido: '', lote: '', proceso: '' }
: e));
};
const selectTolva = (newId) => {
if (!canEdit || !onEquiposChange) return;
const prevId = machine.tolvaId || '';
if (newId === prevId) return;
onEquiposChange((equipos || []).map(e => {
if (!CONTAINER_CATS.includes(e.category)) return e;
if (e.id === prevId) return { ...e, disponible: true, contenido: '', lote: '', proceso: '' };
if (newId && e.id === newId) return { ...e, disponible: false, contenido: tolvaContenido(), lote: machine.lote || '', proceso: tolvaProceso() };
return e;
}));
onUpdate({ ...machine, tolvaId: newId || '' });
};
// Mantener sincronizada la ocupación de la tolva enlazada con el batch
cpUseEffect(() => {
if (!machine.tolvaId || !onEquiposChange) return;
const t = (equipos || []).find(e => e.id === machine.tolvaId && CONTAINER_CATS.includes(e.category));
if (!t) return;
const cont = tolvaContenido(), lot = machine.lote || '', proc = tolvaProceso();
if (t.disponible !== false || (t.contenido || '') !== cont || (t.lote || '') !== lot || (t.proceso || '') !== proc) {
onEquiposChange((equipos || []).map(e => e.id === t.id ? { ...e, disponible: false, contenido: cont, lote: lot, proceso: proc } : e));
}
}, [machine.tolvaId, machine.lote, machine.type, (machine.assignments || []).map(a => a.nombre).join(','), equipos]);
const resetOnly = () => {
if (!canEdit) return;
if (!window.verifyDeleteKey('¿Reiniciar esta máquina?\n\nEsto borrará todos los datos del batch actual SIN guardarlos en el historial. Úsalo solo si cargaste algo por error.')) return;
releaseTolva(machine.tolvaId);
const resetPhases = machine.phases.map(p => ({
...p, running: false, accumulated: 0, startedAt: null,
status: 'pending', startTime: '', endTime: '', phaseStatus: 'pendiente', nota: '',
}));
onUpdate({
...machine,
assignments: [], lote: '', cantidad: '', operario: '',
hrFinalBatch: '', pesoFinalKg: '', empaques: [], notes: '', tolvaId: '',
fecha: cpCaracasDateStr(),
phases: resetPhases,
});
};
const desocupar = () => {
if (!canEdit) return;
if (!requireBatchComplete('desocupar la máquina (guardar el batch en el historial)')) return;
if (!confirm('¿Desocupar esta máquina? El batch actual se guardará en el historial y la máquina quedará lista para una nueva producción.')) return;
releaseTolva(machine.tolvaId);
// Snapshot del batch actual con tiempos completos por fase
const snapshot = {
id: cpUid(),
timestamp: new Date().toISOString(),
fecha: machine.fecha || cpCaracasDateStr(),
assignments: machine.assignments || [],
lote: machine.lote || '',
cantidad: machine.cantidad || '',
operario: machine.operario || '',
pesoFinalKg: machine.pesoFinalKg || '',
empaques: (machine.empaques || []).filter(e => Number(e.cantidad) > 0),
hrFinalBatch: cpBatchHrFinal(machine),
notes: machine.notes || '',
phases: machine.phases.map(p => {
const computedMins = cpPhaseDisplayMins(p);
return {
name: p.name,
status: p.status,
phaseStatus: p.phaseStatus || 'pendiente',
startTime: p.startTime || '',
endTime: p.endTime || '',
elapsedSecs: cpElapsed(p),
computedMins: computedMins,
phaseDate: p.phaseDate || null,
nota: p.nota || '',
};
}),
};
// Reiniciar fases a estado pendiente
const resetPhases = machine.phases.map(p => ({
...p,
running: false,
accumulated: 0,
startedAt: null,
status: 'pending',
startTime: '',
endTime: '',
phaseStatus: 'pendiente',
nota: '',
}));
onUpdate({
...machine,
assignments: [],
lote: '',
cantidad: '',
operario: '',
hrFinalBatch: '',
pesoFinalKg: '',
empaques: [],
notes: '',
tolvaId: '',
fecha: cpCaracasDateStr(),
phases: resetPhases,
history: [...(machine.history || []), snapshot],
});
if (onBaseComplete) {
const refDate = machine.fecha || cpDate;
(machine.assignments || []).filter(a => a.kind === 'base').forEach(a => {
onBaseComplete(a.id, refDate);
});
}
if (machine.type === 'molino' && onMoliendaComplete) onMoliendaComplete(machine);
};
const [showHistory, setShowHistory] = cpUseState(false);
const onDragOver = (e) => { e.preventDefault(); setDragOver(true); };
const onDragLeave = () => setDragOver(false);
const onDrop = (e) => {
e.preventDefault();
setDragOver(false);
if (!canEdit) return;
try {
const item = JSON.parse(e.dataTransfer.getData('cp-item'));
const accepts = mt.accepts || ['base', 'color'];
if (!accepts.includes(item.kind)) return;
if ((machine.assignments || []).some(a => a.id === item.id)) return;
onUpdate({ ...machine, fecha: cpDate, assignments: [...(machine.assignments || []), item] });
if (onBaseStarted) onBaseStarted(item.id, item.kind, cpDate, machine.type);
} catch (_) {}
};
const removeAssignment = (id) => {
if (!canEdit) return;
const removed = (machine.assignments || []).find(a => a.id === id);
onUpdate({ ...machine, assignments: (machine.assignments || []).filter(a => a.id !== id) });
if (removed && onAssignmentRemoved) {
onAssignmentRemoved(id, removed.kind, machine.fecha || cpDate, machine.type);
}
};
const statusCls = { idle: 'idle', running: 'running', paused: 'paused', done: 'done' }[status] || 'idle';
const statusLabel = { idle: 'INACTIVO', running: 'EN PROCESO', paused: 'PAUSADO', done: 'FINALIZADO' }[status] || 'INACTIVO';
const machineColor = machine.color || 'var(--ac)';
const machineCode = machine.code || `${cpMachineTypePrefix(machine.type)}-001`;
const typeName = (mt.name || machine.type).toUpperCase();
// Assignment summary for the row header
const firstBase = (machine.assignments || []).find(a => a.kind === 'base');
const firstColor = (machine.assignments || []).find(a => a.kind === 'color');
const assignSummary = firstBase
? [
firstBase.nombre,
firstBase.tipo ? firstBase.tipo : null,
firstBase.colorsCount != null ? `${firstBase.colorsCount} colores` : null,
firstBase.cantidad ? `${firstBase.cantidad} ${firstBase.unit || 'GL'}` : null,
].filter(Boolean).join(' - ')
: firstColor
? [
firstColor.nombre,
firstColor.cantidad ? `${firstColor.cantidad} ${firstColor.unit || 'GL'}` : null,
].filter(Boolean).join(' - ')
: null;
const assignKind = firstBase ? 'BASE' : firstColor ? 'COLOR' : null;
return (
{/* ── CABECERA ── */}
{editingMeta ? (
e.stopPropagation()}>
setEditCode(e.target.value)} placeholder="Código" title="Código de máquina" />
setEditName(e.target.value)} placeholder="Nombre" title="Nombre de la máquina" />
{ e.stopPropagation(); onUpdate({ ...machine, code: editCode.trim(), name: editName.trim() }); setEditingMeta(false); }} title="Guardar">✓
{ e.stopPropagation(); setEditingMeta(false); }} title="Cancelar">✕
) : (
{machineCode}
)}
{editingMeta ? null : {machine.name} }
{typeName}
{assignSummary ? (
{assignKind}
{assignSummary}
) : (
Sin asignar — arrastra una base o color desde el panel
)}
{(() => {
const machOpStatus = profile.status || 'operativa';
const activeFallas = (profile.fallas || []).filter(f => !f.resuelta);
return (
{machOpStatus === 'operativa' ? '✓ OP' : '✗ IN'}
{activeFallas.length > 0 && {activeFallas.length} }
);
})()}
{statusLabel}
{donePhases}/{totalPhases}
{totalMins} min
{(machine.history || []).length > 0 && (
{machine.history.length}
)}
e.stopPropagation()}>
{isAdmin && onSaveProfile && (
{ e.stopPropagation(); onShowFallaModal && onShowFallaModal(); }}
title="Reportar falla / ver estado de la máquina"
>
⚠
)}
{canEdit && (
<>
{ e.stopPropagation(); setEditCode(machine.code || machineCode); setEditName(machine.name || ''); setEditingMeta(v => !v); }}
title="Editar código y nombre de la máquina"
style={{ color: editingMeta ? 'var(--ac)' : undefined }}
>
{ e.stopPropagation(); desocupar(); }}
title="Desocupar máquina (guarda historial y limpia para nuevo batch)"
>
{ e.stopPropagation(); if (window.verifyDeleteKey('¿Eliminar esta máquina?')) onRemove(); }}
title="Eliminar máquina"
>
>
)}
{/* ── CUERPO ── */}
{open && (
{/* Info de batch */}
ASIGNACIÓN
LOTE
CANTIDAD (GL)
{machine.type === 'molino' &&
PESO FINAL (KG)
}
FECHA
HR FINAL BATCH
OPERARIO
{/* Tolva / tanque asociado — se llena solo desde el batch */}
TOLVA / TANQUE
selectTolva(e.target.value)}
>
— Sin tolva —
{contenedoresDisp.map(t => (
{t.code} · {t.name}{t.capacidad ? ` (${t.capacidad} ${t.capacidadUnidad || ''})` : ''}
))}
{tolvaLinked ? (
🧪 {tolvaContenido() || '—'}{machine.lote ? ' · ' + machine.lote : ''} · {tolvaProceso()}
) : contenedores.length === 0 ? (
No hay tolvas/tanques en Equipos.
) : (
Elegí una tolva/tanque para ocuparla con este batch.
)}
{/* EMPAQUES — solo empaquetadora: qué salió realmente empacado.
El reporte diario usa esto en vez del galonaje de la tolva. */}
{machine.type === 'empaquetadora' && (() => {
const empaques = machine.empaques || [];
const setEmpaques = (next) => onUpdate({ ...machine, empaques: next });
const upd = (i, k, v) => setEmpaques(empaques.map((e, j) => j === i ? { ...e, [k]: v } : e));
const add = () => setEmpaques([...empaques, { tipo: 'ku', cantidad: '' }]);
const del = (i) => setEmpaques(empaques.filter((_, j) => j !== i));
const totalGL = cpEmpaquesGL(empaques);
const batchGL = Number(machine.cantidad) || 0;
const dif = batchGL > 0 ? totalGL - batchGL : 0;
const cuadra = batchGL > 0 && Math.abs(dif) < 0.5;
return (
EMPAQUES REALIZADOS
{canEdit && + Agregar presentación }
{empaques.length === 0 ? (
Sin empaques cargados. Anotá cuántas unidades de cada presentación salieron de este batch.
) : (
{empaques.map((e, i) => {
const t = cpEmpTipo(e.tipo);
const sub = t ? t.gl * (Number(e.cantidad) || 0) : 0;
return (
canEdit && upd(i, 'tipo', ev.target.value)}>
{CP_EMP_TIPOS.map(o => {o.label} )}
canEdit && upd(i, 'cantidad', ev.target.value)} />
= {cpFmtGL(sub)} GL
{canEdit && del(i)} title="Quitar">× }
);
})}
0 ? (cuadra ? ' ok' : ' warn') : ''}`}>
TOTAL EMPACADO
{cpFmtGL(totalGL)} GL
{batchGL > 0 && (
{cuadra
? `✓ coincide con el batch (${cpFmtGL(batchGL)} GL)`
: `⚠ el batch es ${cpFmtGL(batchGL)} GL (${dif > 0 ? '+' : ''}${cpFmtGL(dif)} GL)`}
)}
)}
);
})()}
{/* Observaciones */}
{/* Tabla de fases */}
FASE
HR INICIAL
HR FINAL
MIN. / LÍM.
CRONÓMETRO
{machine.phases.map((ph, i) => (
updatePhase(i, updated)}
onRemove={() => removePhase(i)}
tick={tick}
isDragOver={dragOverPhaseIdx === i}
onDragStart={() => setDragPhaseIdx(i)}
onDragOver={j => setDragOverPhaseIdx(j)}
onDragEnd={() => { movePhase(dragPhaseIdx, dragOverPhaseIdx); setDragPhaseIdx(null); setDragOverPhaseIdx(null); }}
phaseIndex={i}
phaseOptions={mt.defaultPhases || []}
/>
))}
{canEdit && (
<>
Agregar fase
{machine.phases.some(p => p.status !== 'done') && (
{
const nextDay = cpNextDayStr(machine.fecha);
const phases = machine.phases.map(p =>
p.status === 'done' ? p : { ...p, phaseDate: nextDay }
);
onUpdate({ ...machine, phases });
}}
title="Asignar las fases pendientes al día siguiente"
>
📅 Continuar jornada
)}
{machine.phases.some(p => p.phaseDate) && (
{
const phases = machine.phases.map(p => ({ ...p, phaseDate: null }));
onUpdate({ ...machine, phases });
}}
title="Quitar todas las fechas de continuación"
>
✕ Quitar continuaciones
)}
>
)}
{donePhases}/{totalPhases} FASES
{totalMins} MINUTOS
{cpFormatDuration(totalSecs)} TIEMPO TOTAL
{canEdit && (
<>
Liberar
Reiniciar
Desocupar
>
)}
{/* Historial de batches */}
{(machine.history || []).length > 0 && (
setShowHistory(h => !h)}>
HISTORIAL DE BATCHES
{machine.history.length}
{showHistory && (
{machine.history.slice().reverse().map(snap => {
const dtStr = cpFmtVetTimestamp(snap.timestamp);
const doneCount = snap.phases.filter(p => p.status === 'done').length;
const totalCount = snap.phases.length;
const totalMinsSnap = snap.phases.reduce((acc, p) => acc + (p.computedMins || 0), 0);
return (
{/* Cabecera del batch */}
{dtStr}
{snap.lote && Lote: {snap.lote} }
{snap.cantidad && {snap.cantidad} GL }
{snap.operario && 👤 {snap.operario} }
{doneCount}/{totalCount} fases
{totalMinsSnap > 0 && {totalMinsSnap} min total }
{/* Asignaciones */}
{snap.assignments.length > 0 && (
{snap.assignments.map(a => (
{a.nombre}
{a.kind === 'base' ? 'B' : 'C'}
))}
)}
{/* Detalle por fase */}
{snap.phases.length > 0 && (
FASE
HR INICIAL
HR FINAL
MIN
{snap.phases.map((p, i) => (
{p.name}
{p.phaseDate && p.phaseDate !== snap.fecha && (
📅 {cpFmtShortDate(p.phaseDate)}
)}
{p.startTime || '—'}
{p.endTime || '—'}
{p.computedMins !== null && p.computedMins !== undefined ? p.computedMins : '—'}
))}
)}
);
})}
)}
)}
)}
);
}
// ─── generateDailyReportHtml ─────────────────
function generateDailyReportHtml(batches, date, machineTypes) {
const PROD_TYPES = new Set(['dispersor','dispersor1','dispersorp','molino','mezclador']);
// Productos marcados como PRODUCCIÓN (base) aunque su kind sea 'color'.
// Editable desde Config → "Producción / Matización" (window.AppData.PRODUCCION_OVERRIDES).
const prodOverrides = new Set(
((window.AppData && window.AppData.PRODUCCION_OVERRIDES) || [])
.map(s => String(s || '').trim().toUpperCase())
.filter(Boolean)
);
const isProdOverride = nombre => prodOverrides.has(String(nombre || '').trim().toUpperCase());
const areas = { prep: [], mati: [], env: [], emp: [] };
batches.forEach(batch => {
const bMins = (batch.phases||[]).reduce((s,p) => s+(p.computedMins||0), 0);
const mType = batch.machineType || '';
const isEnv = mType === 'envasado';
const isEmp = mType === 'empaquetadora';
const isPasta = mType === 'dispersorp';
const isProd = PROD_TYPES.has(mType);
// Empaquetadora: lo empacado manda sobre el galonaje de la tolva.
const empaques = (batch.empaques || []).filter(e => Number(e.cantidad) > 0);
const empGLBatch = cpEmpaquesGL(empaques);
const makeItem = (nombre, a) => ({
nombre,
lote: batch.lote || '—',
glPlan: Number((a && a.cantidad) || 0),
glReal: (isEmp && empGLBatch > 0) ? empGLBatch : Number(batch.cantidad || 0),
mins: bMins,
machine: batch.machineCode || '',
fecha: batch.fecha || date,
empaques,
glTolva: Number(batch.cantidad || 0),
});
if ((batch.assignments||[]).length) {
batch.assignments.forEach(a => {
const item = makeItem(a.nombre || '—', a);
if (isEnv) areas.env.push(item);
else if (isEmp) areas.emp.push(item);
else if (isProd && a.kind === 'color' && !isPasta && !isProdOverride(a.nombre)) areas.mati.push(item);
else if (isProd) areas.prep.push(item);
});
} else {
const item = makeItem('(Sin asignación)', null);
if (isEnv) areas.env.push(item);
else if (isEmp) areas.emp.push(item);
else areas.prep.push(item);
}
});
const [y, m, d] = date.split('-');
const months = ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
const dateStr = `${d} de ${months[parseInt(m,10)-1]} de ${y}`;
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 sumGL = (items, field) => items.reduce((s,i) => s + (i[field]||0), 0);
const fmtGL = v => (v % 1 === 0 ? v : v.toFixed(1));
const th = txt => `${txt} `;
const thr = txt => `${txt} `;
const td = (txt, extra='') => `${txt} `;
const tdR = (txt, bold=false) => `${txt} `;
// Sección de EMPAQUETADO: en vez del galonaje de la tolva, muestra las
// unidades empacadas por presentación y su equivalencia en galones.
const buildEmpSection = (title, items) => {
if (!items.length) return '';
const totalGL = sumGL(items, 'glReal');
// Total de unidades por presentación en todo el día.
const porTipo = {};
items.forEach(i => (i.empaques || []).forEach(e => {
porTipo[e.tipo] = (porTipo[e.tipo] || 0) + (Number(e.cantidad) || 0);
}));
const resumenDia = CP_EMP_TIPOS.filter(t => porTipo[t.id] > 0)
.map(t => `${porTipo[t.id]} ${t.label} `).join('');
return `
${title}
${resumenDia ? `
${resumenDia}
` : ''}
${th('Fecha')}${th('Máquina')}${th('Producto')}${th('Lote')}${th('Empacado')}${thr('Equiv. (gal)')}
${items.map((i, idx) => `
${td(i.fecha,'font-family:monospace;font-size:10.5px;color:#666;')}
${td(`${i.machine} `,'')}
${td(`${i.nombre} `,'')}
${td(i.lote,'font-family:monospace;font-size:10.5px;color:#555;')}
${td((i.empaques || []).length
? cpEmpaquesResumen(i.empaques)
: `sin empaques cargados${i.glTolva > 0 ? ` · tolva ${fmtGL(i.glTolva)} gal` : ''} `,
'font-size:11px;')}
${tdR(i.glReal > 0 ? fmtGL(i.glReal) : '—', true)}
`).join('')}
Total empacado
${totalGL > 0 ? fmtGL(totalGL) : '—'}
`;
};
const buildSection = (title, items, showTime) => {
if (!items.length) return '';
const totalPlan = sumGL(items, 'glPlan');
const totalReal = sumGL(items, 'glReal');
return `
${title}
${th('Fecha')}${th('Máquina')}${th('Producto')}${th('Lote')}${thr('Vol. Plan. (gal)')}${thr('Vol. Real (gal)')}${showTime?thr('Tiempo (min)'):''}
${items.map((i, idx) => `
${td(i.fecha,'font-family:monospace;font-size:10.5px;color:#666;')}
${td(`${i.machine} `,'')}
${td(`${i.nombre} `,'')}
${td(i.lote,'font-family:monospace;font-size:10.5px;color:#555;')}
${tdR(i.glPlan > 0 ? fmtGL(i.glPlan) : '—')}
${tdR(i.glReal > 0 ? fmtGL(i.glReal) : '—', true)}
${showTime ? tdR(i.mins > 0 ? i.mins : '—') : ''}
`).join('')}
Total
${tdR(totalPlan > 0 ? fmtGL(totalPlan) : '—')}
${totalReal > 0 ? fmtGL(totalReal) : '—'}
${showTime ? ` ` : ''}
`;
};
const prepGL = sumGL(areas.prep, 'glReal') || sumGL(areas.prep, 'glPlan');
const envGL = sumGL(areas.env, 'glReal') || sumGL(areas.env, 'glPlan');
const empGL = sumGL(areas.emp, 'glReal') || sumGL(areas.emp, 'glPlan');
const nColores = areas.mati.length;
const card = (num, label, dark=false) =>
``;
return `
Reporte Producción ${date}
REPORTE DIARIO DE PRODUCCIÓN — ${dateStr}
Dirigido al: Departamento de Producción
Generado: ${nowStr}
Fecha: ${date}
Control de Proceso:
Control Gerente de Planta:
${card(fmtGL(prepGL), 'GL Producción (Bases)')}
${card(fmtGL(envGL), 'GL Envasado')}
${card(fmtGL(empGL), 'GL Empaquetado')}
${card(nColores, 'Colores Matizados', true)}
${buildSection('PREPARADORES — Bases de Producción', areas.prep, true)}
${buildSection('MATIZACIÓN — Colores', areas.mati, true)}
${buildSection('ENVASADO', areas.env, true)}
${buildEmpSection('EMPAQUETADO', areas.emp)}
${!areas.prep.length && !areas.mati.length && !areas.env.length && !areas.emp.length
? 'No se registraron batches para esta fecha.
'
: ''}
Firma Control de Proceso:
Nombre y sello
Firma Gerente de Planta:
Nombre y sello
Sistema de Planificación — VERONA COLOR PAINTS — ${date}
`;
}
// ─── MODAL: editar un registro guardado del historial ───────
// Solo administrador. Permite corregir los datos del batch ya cerrado
// (fecha, lote, cantidad, operario, horas, observaciones y las fases).
// NO se puede cambiar la base ni los colores asignados: eso definiría otro
// batch. Cada edición queda firmada con quién y cuándo.
function CPEditBatchModal({ batch, onSave, onClose }) {
const [d, setD] = cpUseState(() => ({
fecha: batch.fecha || '',
lote: batch.lote || '',
cantidad: batch.cantidad || '',
operario: batch.operario || '',
hrFinalBatch: cpBatchHrFinal(batch),
pesoFinalKg: batch.pesoFinalKg || '',
notes: batch.notes || '',
phases: (batch.phases || []).map(p => ({ ...p })),
}));
const set = (k, v) => setD(x => ({ ...x, [k]: v }));
const setPhase = (i, k, v) =>
setD(x => ({ ...x, phases: x.phases.map((p, j) => j === i ? { ...p, [k]: v } : p) }));
const guardar = () => {
if (!d.fecha) { alert('La fecha no puede quedar vacía.'); return; }
// Recalcular los minutos de cada fase si se corrigieron las horas.
const phases = d.phases.map(p => {
const mins = cpTimeToMins(p.endTime) - cpTimeToMins(p.startTime);
const computedMins = (p.startTime && p.endTime && Number.isFinite(mins) && mins >= 0)
? mins
: (p.computedMins != null ? p.computedMins : null);
return { ...p, computedMins };
});
onSave({ ...d, phases });
};
return (
e.stopPropagation()}>
Editar registro del historial
{batch.machineCode} · {(batch.assignments || []).map(a => a.nombre).join(', ') || 'Sin asignación'}
✕
Guardar cambios
Cancelar
);
}
// ─── HistorialPage ────────────────────────────
function HistorialPage({ machines, setMachines, canEdit, canEditHistorial, isAdmin, canFixHistorial, currentUserName, onBack, typeFilter, backLabel, areaLabel }) {
const [filterBase, setFilterBase] = cpUseState('');
const [filterSearch, setFilterSearch] = cpUseState('');
const [filterDateFrom, setFilterDateFrom] = cpUseState('');
const [filterDateTo, setFilterDateTo] = cpUseState('');
const [filterOperario, setFilterOperario] = cpUseState('');
const [filterMachineType, setFilterMachineType] = cpUseState('all');
const [openBatch, setOpenBatch] = cpUseState(null);
const [activeTab, setActiveTab] = cpUseState('batches');
const [reportDate, setReportDate] = cpUseState(cpCaracasDateStr);
const [reportMode, setReportMode] = cpUseState('dia'); // 'dia' | 'filtro'
const MACHINE_TYPES = window.AppData.MACHINE_TYPES || {};
// Aplanar historial de todas las máquinas (o solo de los tipos del área: matización, envasado…)
const allBatches = cpUseMemo(() =>
machines
.filter(m => !typeFilter || typeFilter.includes(m.type))
.flatMap(m =>
(m.history || []).map(snap => ({
...snap,
machineId: m.id,
machineName: m.name,
machineCode: m.code || m.id,
machineColor: m.color || 'var(--ac)',
machineType: m.type,
}))
).sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp)),
[machines, typeFilter && typeFilter.join(',')]);
// Productos únicos existentes en el historial para el desplegable
const baseOptions = cpUseMemo(() => {
const seen = new Map();
allBatches.forEach(b => {
(b.assignments || []).forEach(a => {
const key = (a.code || '') + '||' + a.nombre;
if (!seen.has(key)) seen.set(key, { nombre: a.nombre, code: a.code || '' });
});
});
return [...seen.values()].sort((a, b) => a.nombre.localeCompare(b.nombre, 'es'));
}, [allBatches]);
const filtered = cpUseMemo(() => {
let out = allBatches;
if (filterMachineType !== 'all') out = out.filter(b => b.machineType === filterMachineType);
if (filterDateFrom) out = out.filter(b => (b.fecha || b.timestamp?.slice(0,10)) >= filterDateFrom);
if (filterDateTo) out = out.filter(b => (b.fecha || b.timestamp?.slice(0,10)) <= filterDateTo);
if (filterBase.trim()) {
out = out.filter(b =>
(b.assignments || []).some(a => a.nombre === filterBase)
);
}
const q = filterSearch.trim().toLowerCase();
if (q) {
out = out.filter(b => {
const assignmentText = (b.assignments || [])
.map(a => [a.nombre, a.code, a.lote, a.tipo, a.kind].filter(Boolean).join(' '))
.join(' ');
return [assignmentText, b.lote, b.codigo, b.code, b.machineName, b.machineCode, b.operario]
.filter(Boolean)
.some(val => String(val).toLowerCase().includes(q));
});
}
if (filterOperario) {
out = out.filter(b => b.operario === filterOperario);
}
return out;
}, [allBatches, filterMachineType, filterDateFrom, filterDateTo, filterBase, filterSearch, filterOperario]);
const stats = cpUseMemo(() => {
const totalGL = filtered.reduce((s, b) => s + Number(b.cantidad || 0), 0);
const totalMins = filtered.reduce((s, b) =>
s + (b.phases || []).reduce((ps, p) => ps + (p.computedMins || 0), 0), 0);
return {
total: filtered.length,
totalGL: totalGL % 1 === 0 ? totalGL : totalGL.toFixed(1),
avgMins: filtered.length ? Math.round(totalMins / filtered.length) : 0,
totalMins,
};
}, [filtered]);
// Filtros adicionales para estadísticas de fases
const [phaseSearchQ, setPhaseSearchQ] = cpUseState('');
const [phaseGLMin, setPhaseGLMin] = cpUseState('');
const [phaseGLMax, setPhaseGLMax] = cpUseState('');
const phaseFilteredBatches = cpUseMemo(() => {
let out = filtered;
const q = phaseSearchQ.trim().toLowerCase();
if (q) out = out.filter(b =>
(b.assignments||[]).some(a =>
a.nombre.toLowerCase().includes(q) || (a.code||'').toLowerCase().includes(q)
) || (b.lote||'').toLowerCase().includes(q)
);
if (phaseGLMin) out = out.filter(b => Number(b.cantidad||0) >= Number(phaseGLMin));
if (phaseGLMax) out = out.filter(b => Number(b.cantidad||0) <= Number(phaseGLMax));
return out;
}, [filtered, phaseSearchQ, phaseGLMin, phaseGLMax]);
// Estadísticas de fases: promedio, min, max, total + proyectado (basado en allBatches)
const phaseStats = cpUseMemo(() => {
const buildMap = (batches) => {
const map = {};
batches.forEach(b => {
(b.phases || []).forEach(p => {
if (p.computedMins == null || p.computedMins <= 0) return;
if (!map[p.name]) map[p.name] = [];
map[p.name].push(p.computedMins);
});
});
return map;
};
const filteredMap = buildMap(phaseFilteredBatches);
const allMap = buildMap(allBatches);
return Object.entries(filteredMap).map(([name, vals]) => {
const allVals = allMap[name] || vals;
const avg = Math.round(vals.reduce((s, v) => s + v, 0) / vals.length);
const min = Math.min(...vals);
const max = Math.max(...vals);
const total = vals.reduce((s, v) => s + v, 0);
const projected = Math.round(allVals.reduce((s, v) => s + v, 0) / allVals.length);
const diff = projected > 0 ? Math.round((avg - projected) / projected * 100) : 0;
return { name, avg, min, max, total, count: vals.length, projected, diff };
}).sort((a, b) => b.total - a.total);
}, [phaseFilteredBatches, allBatches]);
const operators = cpUseMemo(() => {
const set = new Set(allBatches.map(b => b.operario).filter(Boolean));
return [...set].sort();
}, [allBatches]);
const presentTypes = cpUseMemo(() => {
const set = new Set(allBatches.map(b => b.machineType).filter(Boolean));
return [...set];
}, [allBatches]);
const reportBatches = cpUseMemo(() =>
allBatches.filter(b => (b.fecha || b.timestamp?.slice(0,10)) === reportDate),
[allBatches, reportDate]);
const printDailyReport = () => {
if (!reportBatches.length) { alert('No hay batches registrados para esta fecha.'); return; }
const html = generateDailyReportHtml(reportBatches, reportDate, MACHINE_TYPES);
const win = window.open('', '_blank', 'width=940,height=720');
win.document.write(html);
win.document.close();
setTimeout(() => { win.focus(); win.print(); }, 600);
};
const printFilteredReport = () => {
if (!filtered.length) { alert('No hay registros con los filtros actuales.'); return; }
const label = [
filterDateFrom && filterDateTo ? `${filterDateFrom} al ${filterDateTo}` : filterDateFrom || filterDateTo || 'Todos los registros',
filterBase ? filterBase : null,
].filter(Boolean).join(' · ');
const html = generateDailyReportHtml(filtered, label, MACHINE_TYPES);
const win = window.open('', '_blank', 'width=940,height=720');
win.document.write(html);
win.document.close();
setTimeout(() => { win.focus(); win.print(); }, 600);
};
// ── Edición de un registro guardado (solo administrador) ──
const [editBatch, setEditBatch] = cpUseState(null); // { ...snapshot, machineId }
const saveEditedBatch = (cambios) => {
if (!(isAdmin || canFixHistorial) || !setMachines || !editBatch) return;
const { machineId, id: snapId } = editBatch;
const firma = {
editedBy: currentUserName || 'Administrador',
editedAt: new Date().toISOString(),
};
setMachines(prev => prev.map(m =>
m.id === machineId
? { ...m, history: (m.history || []).map(h => h.id === snapId ? { ...h, ...cambios, ...firma } : h) }
: m
));
setEditBatch(null);
};
const deleteBatch = (machineId, snapId) => {
if (!canEditHistorial || !setMachines) return;
if (!window.verifyDeleteKey('¿Eliminar este registro del historial? Esta acción no se puede deshacer.')) return;
setMachines(prev => prev.map(m =>
m.id === machineId
? { ...m, history: (m.history || []).filter(h => h.id !== snapId) }
: m
));
if (openBatch === snapId) setOpenBatch(null);
};
const exportCSV = () => {
const BOM = '';
const headers = ['Máquina','Código','Tipo','Fecha','Lote','Cantidad GL','Operario','HR Final Batch','Fases Completas','Minutos Totales','Fases Detalle','Asignaciones'];
const rows = filtered.map(b => {
const totalPhaseMins = (b.phases || []).reduce((s, p) => s + (p.computedMins || 0), 0);
const donePhases = (b.phases || []).filter(p => p.status === 'done').length;
const phasesDetail = (b.phases || []).map(p =>
`${p.name}(${p.startTime||'—'}→${p.endTime||'—'} ${p.computedMins != null ? p.computedMins : '?'}min${p.phaseDate && p.phaseDate !== b.fecha ? ' 📅'+p.phaseDate : ''}${(p.nota||'').trim() ? ' obs: '+String(p.nota).replace(/[|\n]/g,' ') : ''})`
).join(' | ');
const assigns = (b.assignments || []).map(a => a.nombre).join(', ');
const dtStr = cpFmtVetTimestamp(b.timestamp);
return [
b.machineName, b.machineCode,
(MACHINE_TYPES[b.machineType]?.name || b.machineType),
dtStr, b.lote || '', b.cantidad || '', b.operario || '',
cpBatchHrFinal(b),
`${donePhases}/${(b.phases||[]).length}`,
totalPhaseMins, phasesDetail, assigns,
];
});
const csv = [headers, ...rows]
.map(r => r.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
.join('\r\n');
const blob = new Blob([BOM + csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
const areaSlug = (areaLabel || 'batches').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '-');
a.download = `historial-${areaSlug}-${cpCaracasDateStr()}.csv`;
a.click();
URL.revokeObjectURL(url);
};
const hasFilters = filterBase || filterSearch || filterDateFrom || filterDateTo || filterOperario || filterMachineType !== 'all';
const clearFilters = () => {
setFilterBase(''); setFilterSearch(''); setFilterDateFrom(''); setFilterDateTo('');
setFilterOperario(''); setFilterMachineType('all');
};
return (
{/* ── CABECERA ── */}
{window.t(backLabel || 'Volver al Control')}
{window.t('Historial de Producción')}{areaLabel ? ` — ${areaLabel}` : ''}
{allBatches.length} {window.t('registros totales')}
{filtered.length > 0 && (
{window.t('Exportar CSV')}
)}
{/* ── ESTADÍSTICAS RESUMEN ── */}
{stats.total}
{window.t(hasFilters ? 'Batches filtrados' : 'Batches')}
{stats.totalGL}
{window.t('GL Totales')}
{stats.totalMins}
{window.t('Min Totales')}
{stats.avgMins}
{window.t('Min Prom. / Batch')}
{/* ── FILTROS ── */}
{window.t('BASE / PRODUCTO')}
setFilterBase(e.target.value)}
>
{window.t('Todos los productos')}
{baseOptions.map(o => (
{o.code ? `${o.code} — ${o.nombre}` : o.nombre}
))}
{window.t('FECHA DESDE')}
setFilterDateFrom(e.target.value)}
/>
{window.t('FECHA HASTA')}
setFilterDateTo(e.target.value)}
/>
{window.t('OPERARIO')}
setFilterOperario(e.target.value)}
>
{window.t('Todos')}
{operators.map(op => (
{op}
))}
{(!typeFilter || presentTypes.length > 1) && (
{window.t('MÁQUINA / TIPO')}
setFilterMachineType(e.target.value)}
>
{window.t('Todas')}
{presentTypes.map(type => (
{MACHINE_TYPES[type]?.name || type}
))}
)}
{hasFilters && (
{window.t('Limpiar filtros')}
)}
{hasFilters && (
Mostrando {filtered.length} de {allBatches.length} registros
)}
{/* ── TABS ── */}
setActiveTab('batches')}
>
{window.t('Registros')}
{filtered.length}
setActiveTab('phases')}
>
{window.t('Estadísticas de Fases')}
{phaseStats.length > 0 && {phaseStats.length} }
setActiveTab('reporte')}
>
{window.t('Reporte Diario')}
{/* ── CUERPO ── */}
{/* — TAB: ESTADÍSTICAS DE FASES — */}
{activeTab === 'phases' && (
{/* Filtros de fases */}
{(phaseSearchQ || phaseGLMin || phaseGLMax) && (
Mostrando fases de {phaseFilteredBatches.length} de {filtered.length} batches filtrados
)}
{phaseStats.length === 0 ? (
Sin datos de fases para los filtros aplicados.
) : (
<>
Tiempos en minutos . Proyectado = promedio histórico global de esa fase en todos los registros. Real = promedio dentro del conjunto filtrado. La diferencia indica si el set filtrado es más rápido o lento que el histórico.
FASE
REGISTROS
PROYECTADO
REAL (PROM.)
DIFERENCIA
MÍNIMO
MÁXIMO
TOTAL
{phaseStats.map(ps => (
{ps.name}
{ps.count}
{ps.projected} min
{ps.avg} min
0 ? 'over' : ps.diff < 0 ? 'under' : 'neutral'}`}>
{ps.diff > 0 ? `+${ps.diff}%` : ps.diff < 0 ? `${ps.diff}%` : '—'}
{ps.min} min
{ps.max} min
{ps.total} min
))}
TOTALES / PROM.
{filtered.length} batches
{phaseStats.length > 0
? Math.round(phaseStats.reduce((s, ps) => s + ps.avg, 0) / phaseStats.length)
: '—'} min prom.
{phaseStats.reduce((s, ps) => s + ps.total, 0)} min
>
)}
)}
{/* — TAB: REPORTE DIARIO — */}
{activeTab === 'reporte' && (
{/* Selector de modo */}
setReportMode('dia')}
>{window.t('📅 Reporte por día')}
setReportMode('filtro')}
>{window.t('🔍 Reporte del filtrado')}
{reportMode === 'dia' ? (
<>
{window.t('FECHA DEL REPORTE')}
setReportDate(e.target.value)}
/>
{window.t('Generar e Imprimir')}
>
) : (
<>
{filtered.length} registro{filtered.length !== 1 ? 's' : ''} con los filtros actuales
{filterBase ? ` · ${filterBase}` : ''}
{filterDateFrom || filterDateTo ? ` · ${filterDateFrom || '…'} → ${filterDateTo || '…'}` : ''}
{window.t('Generar e Imprimir')}
>
)}
{reportMode === 'dia' ? (
reportBatches.length === 0 ? (
No hay batches registrados para {reportDate}.
) : (
Vista previa — {reportBatches.length} batch{reportBatches.length !== 1 ? 'es' : ''} el {reportDate}
{reportBatches.reduce((s,b) => s + Number(b.cantidad||0), 0)} GL
{reportBatches.filter(b => (b.phases||[]).length > 0 && (b.phases||[]).every(p => p.status === 'done')).length}/{reportBatches.length} completados
{reportBatches.reduce((s,b) => s+(b.phases||[]).reduce((ps,p) => ps+(p.computedMins||0),0),0)} min
{(() => {
const byMac = {};
reportBatches.forEach(b => {
if (!byMac[b.machineCode]) byMac[b.machineCode] = { code: b.machineCode, name: b.machineName, batches: [] };
byMac[b.machineCode].batches.push(b);
});
return Object.values(byMac).sort((a,b) => a.code.localeCompare(b.code)).map(mac => (
{mac.code}
{mac.name}
{mac.batches.length} batch{mac.batches.length !== 1 ? 'es' : ''}
{mac.batches.map(batch => {
const allDone = (batch.phases||[]).length > 0 && (batch.phases||[]).every(p => p.status === 'done');
const anyDone = (batch.phases||[]).some(p => p.status === 'done');
const bMins = (batch.phases||[]).reduce((s,p) => s+(p.computedMins||0),0);
return (
{allDone ? '✓' : anyDone ? '½' : '○'}
{(batch.assignments||[]).map(a => a.nombre).join(', ') || 'Sin asignación'}
{batch.lote && Lote: {batch.lote} }
{batch.cantidad && {batch.cantidad} GL }
{batch.operario && 👤 {batch.operario} }
{bMins > 0 && {bMins} min }
);
})}
));
})()}
))
: (
filtered.length === 0 ? (
Sin registros con los filtros actuales.
) : (
Vista previa — {filtered.length} batch{filtered.length !== 1 ? 'es' : ''} filtrados
{filtered.reduce((s,b) => s + Number(b.cantidad||0), 0)} GL
{filtered.filter(b => (b.phases||[]).length > 0 && (b.phases||[]).every(p => p.status === 'done')).length}/{filtered.length} completados
{filtered.reduce((s,b) => s+(b.phases||[]).reduce((ps,p) => ps+(p.computedMins||0),0),0)} min
{(() => {
const byMac = {};
filtered.forEach(b => {
if (!byMac[b.machineCode]) byMac[b.machineCode] = { code: b.machineCode, name: b.machineName, batches: [] };
byMac[b.machineCode].batches.push(b);
});
return Object.values(byMac).sort((a,b) => a.code.localeCompare(b.code)).map(mac => (
{mac.code}
{mac.name}
{mac.batches.length} batch{mac.batches.length !== 1 ? 'es' : ''}
{mac.batches.map(batch => {
const allDone = (batch.phases||[]).length > 0 && (batch.phases||[]).every(p => p.status === 'done');
const anyDone = (batch.phases||[]).some(p => p.status === 'done');
const bMins = (batch.phases||[]).reduce((s,p) => s+(p.computedMins||0),0);
return (
{allDone ? '✓' : anyDone ? '½' : '○'}
{(batch.assignments||[]).map(a => a.nombre).join(', ') || 'Sin asignación'}
{batch.lote && Lote: {batch.lote} }
{batch.cantidad && {batch.cantidad} GL }
{batch.operario && 👤 {batch.operario} }
{bMins > 0 && {bMins} min }
);
})}
));
})()}
)
)}
)}
{/* — TAB: LISTA DE REGISTROS — */}
{activeTab === 'batches' && (
{filtered.length === 0 && (
{allBatches.length === 0
? 'No hay batches registrados aún. Usa "Desocupar" en una máquina para guardar el primer registro.'
: 'Sin resultados para los filtros aplicados.'}
)}
{filtered.map(batch => {
const isOpen = openBatch === batch.id;
const dtStr = cpFmtVetTimestamp(batch.timestamp, { sep: true });
const donePhases = (batch.phases||[]).filter(p => p.status === 'done').length;
const totalPhases = (batch.phases||[]).length;
const totalMins = (batch.phases||[]).reduce((s, p) => s + (p.computedMins || 0), 0);
return (
setOpenBatch(isOpen ? null : batch.id)}>
{batch.machineCode}
{batch.machineName}
{dtStr}
{batch.lote && {batch.lote} }
{batch.cantidad && {batch.cantidad} GL }
{batch.operario && 👤 {batch.operario} }
{(batch.assignments||[]).length > 0 && (
{batch.assignments.map(a => a.nombre).join(', ')}
)}
{donePhases}/{totalPhases}
{totalMins > 0 && {totalMins} min }
{isOpen && (
{(batch.assignments||[]).length > 0 && (
ASIGNACIÓN
{batch.assignments.map(a => (
{a.nombre}
{a.kind === 'base' ? 'B' : 'C'}
))}
)}
{(batch.operario || cpBatchHrFinal(batch) || batch.fecha || batch.pesoFinalKg || (batch.empaques || []).length > 0) && (
{batch.operario && (
OPERARIO
👤 {batch.operario}
)}
{cpBatchHrFinal(batch) && (
HR FINAL BATCH
{cpBatchHrFinal(batch)}
)}
{batch.pesoFinalKg && (
PESO FINAL
{batch.pesoFinalKg} Kg
)}
{(batch.empaques || []).length > 0 && (
EMPACADO
{cpEmpaquesResumen(batch.empaques)}
· {cpFmtGL(cpEmpaquesGL(batch.empaques))} GL
)}
{batch.fecha && (
)}
)}
{(batch.phases||[]).length > 0 && (
FASE
HR INICIAL
HR FINAL
MIN
{batch.phases.map((p, i) => (
{p.name}
{p.phaseDate && p.phaseDate !== batch.fecha && (
📅 {cpFmtShortDate(p.phaseDate)}
)}
{(p.nota || '').trim() && (
“{p.nota}”
)}
{p.startTime || '—'}
{p.endTime || '—'}
{p.computedMins != null ? p.computedMins : '—'}
))}
{totalMins > 0 && (
TOTAL
{totalMins}
)}
)}
{batch.notes && (
)}
{(batch.editedBy || batch.editedAt) && (
✎ Registro corregido por {batch.editedBy || '—'}
{batch.editedAt ? ` el ${cpFmtVetTimestamp(batch.editedAt, { sep: true })}` : ''}
)}
{(canEditHistorial || isAdmin || canFixHistorial) && setMachines ? (
{(isAdmin || canFixHistorial) && (
setEditBatch(batch)}
title="Corregir los datos de este registro guardado"
>
✎ Corregir registro
)}
{canEditHistorial && (
deleteBatch(batch.machineId, batch.id)}
>
Eliminar registro
)}
) : !canEditHistorial && canEdit ? (
Se requiere permiso "Editar Historial" para eliminar registros
) : null}
)}
);
})}
)}
{editBatch && (isAdmin || canFixHistorial) && (
setEditBatch(null)}
/>
)}
);
}
// ─── AddMachineModal ──────────────────────────
function AddMachineModal({ onAdd, onClose, machines }) {
const [type, setType] = cpUseState('dispersor');
const MACHINE_TYPES = window.AppData.MACHINE_TYPES || {};
const mt = MACHINE_TYPES[type] || {};
const countOfType = (machines || []).filter(m => m.type === type).length;
const suggestedName = `${mt.name || type} Nº ${countOfType + 1}`;
const [name, setName] = cpUseState('');
const [code, setCode] = cpUseState('');
cpUseEffect(() => { setName(''); setCode(''); }, [type]);
const suggestedCode = `${cpMachineTypePrefix(type)}-${String(countOfType + 1).padStart(3, '0')}`;
const handleAdd = () => {
const m = cpNewMachine(type);
m.name = name.trim() || suggestedName;
m.code = code.trim() || suggestedCode;
m.color = CP_MACHINE_COLORS[(machines || []).length % CP_MACHINE_COLORS.length];
onAdd(m);
onClose();
};
return (
e.stopPropagation()}>
Nueva Máquina
Selecciona el tipo de máquina a agregar al control
×
TIPO
{Object.entries(MACHINE_TYPES).map(([k, v]) => (
setType(k)}
>
{k === 'dispersor' && }
{k === 'dispersor1' && }
{k === 'dispersorp' && }
{k === 'envasado' && }
{k === 'mezclador' && }
{k === 'molino' && }
{k === 'empaquetadora' && }
{v.name}
{(v.defaultPhases || []).length} fases predefinidas
))}
IDENTIFICACIÓN
CÓDIGO DE LA MÁQUINA
setCode(e.target.value.toUpperCase())}
onKeyDown={e => e.key === 'Enter' && handleAdd()}
style={{ marginBottom: 10 }}
/>
NOMBRE / TAG DE LA MÁQUINA
setName(e.target.value)}
onKeyDown={e => e.key === 'Enter' && handleAdd()}
/>
{(mt.defaultPhases || []).length > 0 && (
FASES PREDETERMINADAS
{mt.defaultPhases.map((p, i) => (
{p}
))}
Podrás editar, agregar o eliminar fases después.
)}
Cancelar
Crear máquina
);
}
// ─── ControlProceso ───────────────────────────
function ControlProceso({ allPlan, initDate, onCpDateChange, onBaseComplete, onBaseStarted, onAssignmentRemoved, onMoliendaComplete, onCancelBase, onUpdateBase, machines, setMachines, onDeleteMachine, canEdit, tick, isAdmin, machineProfiles, onSaveMachineProfile, onAddBase, onAddColor, onShowHistorial, equipos, onEquiposChange }) {
const [cpDate, setCpDate] = cpUseState(initDate || todayStr());
const [fallaMachine, setFallaMachine] = cpUseState(null);
const bases = cpUseMemo(() => (allPlan || {})[cpDate] || [], [allPlan, cpDate]);
const navigateCpDate = (delta) => {
const newDate = shiftDate(cpDate, delta);
setCpDate(newDate);
if (onCpDateChange) onCpDateChange(newDate);
};
const goToday = () => {
const t = todayStr();
setCpDate(t);
if (onCpDateChange) onCpDateChange(t);
};
const [showAddModal, setShowAddModal] = cpUseState(false);
const [openMachines, setOpenMachines] = cpUseState(new Set());
const [filterType, setFilterType] = cpUseState('all');
const [filterStatus, setFilterStatus] = cpUseState('all');
const [search, setSearch] = cpUseState('');
const [showTolvasBoard, setShowTolvasBoard] = cpUseState(false);
// ── Tablero manual de tanques y tolvas ──
const CONTAINER_CATS_CP = ['tolva', 'tanque'];
const contenedoresCP = cpUseMemo(
() => (equipos || []).filter(e => CONTAINER_CATS_CP.includes(e.category)),
[equipos]);
const nContenedoresOcup = contenedoresCP.filter(e => e.disponible === false).length;
// Qué máquina (código) tiene enlazada cada tolva/tanque
const containerMachine = cpUseMemo(() => {
const map = {};
(machines || []).forEach(m => { if (m.tolvaId) map[m.tolvaId] = m.code || m.name || m.id; });
return map;
}, [machines]);
// Liberar a mano: vuelve a Disponible, limpia contenido y desengancha la máquina
const boardLiberar = (equipoId) => {
if (onEquiposChange) onEquiposChange((equipos || []).map(e =>
e.id === equipoId ? { ...e, disponible: true, contenido: '', lote: '', proceso: '' } : e));
if (setMachines) setMachines(prev => prev.map(m => m.tolvaId === equipoId ? { ...m, tolvaId: '' } : m));
};
// Ocupar/editar a mano
const boardOcupar = (equipoId, vals) => {
if (onEquiposChange) onEquiposChange((equipos || []).map(e =>
e.id === equipoId ? { ...e, disponible: false, contenido: vals.contenido, lote: vals.lote, proceso: vals.proceso } : e));
};
const d = new Date(cpDate + 'T12:00:00');
const dayName = ['DOMINGO','LUNES','MARTES','MIÉRCOLES','JUEVES','VIERNES','SÁBADO'][d.getDay()];
const dayNum = String(d.getDate()).padStart(2, '0');
const monthYear = d.toLocaleDateString('es', { month: 'long', year: 'numeric' });
const stats = cpUseMemo(() => {
const running = machines.filter(m => cpMachineStatus(m) === 'running').length;
const paused = machines.filter(m => cpMachineStatus(m) === 'paused').length;
const done = machines.filter(m => cpMachineStatus(m) === 'done').length;
const idle = machines.filter(m => cpMachineStatus(m) === 'idle').length;
return { total: machines.length, running, paused, done, idle };
}, [machines, tick]);
const presentTypes = cpUseMemo(() => {
const map = {};
machines.forEach(m => { map[m.type] = (map[m.type] || 0) + 1; });
return map;
}, [machines]);
const filteredMachines = cpUseMemo(() => {
let out = machines;
if (filterType !== 'all') out = out.filter(m => m.type === filterType);
if (filterStatus === 'running') out = out.filter(m => cpMachineStatus(m) === 'running');
else if (filterStatus === 'paused') out = out.filter(m => cpMachineStatus(m) === 'paused');
else if (filterStatus === 'done') out = out.filter(m => cpMachineStatus(m) === 'done');
if (search.trim()) {
const q = search.toLowerCase();
out = out.filter(m =>
m.name.toLowerCase().includes(q) ||
(m.code || '').toLowerCase().includes(q) ||
(m.operario || '').toLowerCase().includes(q) ||
(m.lote || '').toLowerCase().includes(q) ||
(m.assignments || []).some(a => a.nombre.toLowerCase().includes(q))
);
}
return out;
}, [machines, filterType, filterStatus, search, tick]);
const expandAll = () => setOpenMachines(new Set(machines.map(m => m.id)));
const collapseAll = () => setOpenMachines(new Set());
const toggleMachine = (id) => {
setOpenMachines(prev => {
const next = new Set(prev);
if (next.has(id)) next.delete(id); else next.add(id);
return next;
});
};
const addMachine = (m) => { if (!canEdit || !setMachines) return; setMachines(prev => [...prev, m]); setOpenMachines(prev => new Set([...prev, m.id])); };
const updateMachine = (id, upd) => { if (!canEdit || !setMachines) return; setMachines(prev => prev.map(m => m.id === id ? upd : m)); };
const removeMachine = (id) => { if (!canEdit) return; if (onDeleteMachine) onDeleteMachine(id); else if (setMachines) setMachines(prev => prev.filter(m => m.id !== id)); };
const handleAssignmentRemoved = onAssignmentRemoved || null;
const MACHINE_TYPES = window.AppData.MACHINE_TYPES || {};
return (
{/* ── HEADER ── */}
navigateCpDate(-1)} title="Día anterior">
{dayNum}
{dayName}
{monthYear.charAt(0).toUpperCase() + monthYear.slice(1)}
navigateCpDate(1)} title="Día siguiente">
{cpDate !== todayStr() && (
Hoy
)}
{stats.running}
En proceso
{machines.length > 0 && (
<>
Expandir todas
Colapsar
>
)}
{/* Botón historial — abre página dedicada */}
{(() => {
const totalBatches = machines.reduce((s, m) => s + (m.history||[]).length, 0);
return (
Historial
{totalBatches > 0 && (
{totalBatches}
)}
);
})()}
setShowTolvasBoard(true)} title="Ver y gestionar disponibilidad de tanques y tolvas">
🛢 Tanques y tolvas
{nContenedoresOcup > 0 && {nContenedoresOcup} }
{canEdit && (
setShowAddModal(true)}>
Nueva Máquina
)}
{/* ── BARRA DE FILTROS ── */}
{machines.length > 0 && (
TIPO:
setFilterType('all')}>
Todas {machines.length}
{Object.entries(presentTypes).map(([type, count]) => (
setFilterType(type)}
>
{MACHINE_TYPES[type]?.name || type} {count}
))}
ESTADO:
setFilterStatus('all')}>Todos
setFilterStatus('running')}>En proceso
setFilterStatus('paused')}>Pausadas
setFilterStatus('done')}>Finalizadas
setSearch(e.target.value)}
/>
)}
onUpdateBase(baseId, patch, cpDate) : null}
/>
{machines.length === 0 && (
Sin máquinas en proceso
{canEdit
? 'Agrega una máquina y arrastra bases o colores desde el panel lateral.'
: 'No hay máquinas configuradas para este día.'}
{canEdit && (
setShowAddModal(true)}>
Nueva Máquina
)}
)}
{filteredMachines.map(m => (
onSaveMachineProfile(m.code || m.id, prof) : null}
onShowFallaModal={() => setFallaMachine(m)}
onUpdate={upd => updateMachine(m.id, upd)}
onRemove={() => removeMachine(m.id)}
tick={tick}
isOpen={openMachines.has(m.id)}
onToggle={() => toggleMachine(m.id)}
onBaseComplete={onBaseComplete}
onMoliendaComplete={onMoliendaComplete}
onBaseStarted={onBaseStarted}
onAssignmentRemoved={handleAssignmentRemoved}
cpDate={cpDate}
equipos={equipos}
onEquiposChange={onEquiposChange}
/>
))}
{machines.length > 0 && filteredMachines.length === 0 && (
Sin resultados
No hay máquinas que coincidan con los filtros aplicados.
)}
{filteredMachines.length > 0 && canEdit && (
setShowAddModal(true)}>
Agregar máquina
)}
{showAddModal && canEdit && (
setShowAddModal(false)}
machines={machines}
/>
)}
{fallaMachine && isAdmin && onSaveMachineProfile && (
onSaveMachineProfile(fallaMachine.code || fallaMachine.id, prof)}
onClose={() => setFallaMachine(null)}
/>
)}
{showTolvasBoard && (
setShowTolvasBoard(false)}
/>
)}
);
}
// ─── TolvasBoardModal — tablero manual de tanques y tolvas ───
function TolvasBoardModal({ contenedores, linkedMap, canEdit, onLiberar, onOcupar, onClose }) {
const list = contenedores || [];
const [q, setQ] = cpUseState('');
const [ocuparId, setOcuparId] = cpUseState(null);
const [oCont, setOCont] = cpUseState('');
const [oLote, setOLote] = cpUseState('');
const [oProc, setOProc] = cpUseState('');
const fmtCap = (e) => e.capacidad ? `${e.capacidad} ${e.capacidadUnidad || ''}` : '—';
const disp = (e) => e.disponible !== false;
const startOcupar = (e) => { setOcuparId(e.id); setOCont(e.contenido || ''); setOLote(e.lote || ''); setOProc(e.proceso || ''); };
const confirmOcupar = (e) => { onOcupar(e.id, { contenido: oCont.trim(), lote: oLote.trim(), proceso: oProc.trim() }); setOcuparId(null); };
const liberar = (e) => {
const via = linkedMap && linkedMap[e.id] ? `\n\nEstá enlazada a la máquina ${linkedMap[e.id]}; también se desenganchará de esa máquina.` : '';
if (!confirm(`¿Liberar ${e.code} · ${e.name}?\nVolverá a Disponible y se limpiará su contenido.${via}`)) return;
onLiberar(e.id);
};
const s = q.trim().toLowerCase();
const filtered = !s ? list : list.filter(e =>
[e.code, e.name, e.contenido, e.lote, e.proceso].some(v => (v || '').toLowerCase().includes(s)));
const nDisp = list.filter(disp).length;
const nOcup = list.length - nDisp;
return (
e.stopPropagation()}>
🛢 Tanques y tolvas
{nDisp} disponibles · {nOcup} ocupados
✕
setQ(e.target.value)} style={{ marginBottom: 12 }} />
{list.length === 0 ? (
No hay tanques ni tolvas registrados en Equipos.
) : filtered.length === 0 ? (
Sin resultados para la búsqueda.
) : (
{filtered.map(e => {
const libre = disp(e);
const editing = ocuparId === e.id;
const maq = linkedMap && linkedMap[e.id];
return (
{e.code}
{e.name}
{eqCategoryLabel(e.category)}
🛢 {fmtCap(e)}
{libre ? 'Disponible' : 'Ocupado'}
{maq && ⚙ {maq} }
{!libre && !editing && (e.contenido || e.lote || e.proceso) && (
🧪 {e.contenido || '—'}{e.lote ? ' · ' + e.lote : ''}{e.proceso ? ' · ' + e.proceso : ''}
)}
{canEdit && (editing ? (
) : (
{libre ? (
startOcupar(e)}>Ocupar
) : (
<>
{!maq && startOcupar(e)}>Editar }
liberar(e)}>Liberar
>
)}
))}
);
})}
)}
);
}
window.ControlProceso = ControlProceso;
window.HistorialPage = HistorialPage;
// ════════════════════════════════════════════
// VISTA SUPERVISOR
// ════════════════════════════════════════════
const { useState: svUseState, useEffect: svUseEffect, useMemo: svUseMemo, useRef: svUseRef } = React;
const SV_STATUS_CONFIG = {
running: { label: 'En Proceso', cls: 'sv-badge--running' },
paused: { label: 'Pausada', cls: 'sv-badge--paused' },
done: { label: 'Finalizada', cls: 'sv-badge--done' },
idle: { label: 'Inactiva', cls: 'sv-badge--idle' },
};
const SV_MACHINE_ICONS = {
dispersor: 'Dispersor',
dispersor1: 'Dispersor Matización',
dispersorp: 'Dispersor Pasta',
envasado: 'Envasado',
mezclador: 'Mezclador',
molino: 'Molino',
empaquetadora: 'Empaquetadora',
};
const SV_TYPE_GROUPS = [
{ id: 'all', label: 'Todas', types: null },
{ id: 'dispersoresp', label: 'Dispersores Pasta', types: ['dispersorp'] },
{ id: 'dispersores1', label: 'Dispersores Matización', types: ['dispersor1'] },
{ id: 'dispersores', label: 'Dispersores', types: ['dispersor'] },
{ id: 'envasado', label: 'Envasado', types: ['envasado'] },
{ id: 'mezclador', label: 'Mezclador', types: ['mezclador'] },
{ id: 'molino', label: 'Molino', types: ['molino'] },
{ id: 'empaquetadora', label: 'Empaquetadora', types: ['empaquetadora'] },
];
const SV_WARN_MINS = 30;
const SV_ALERT_MINS = 180;
function svCurrentPhaseElapsed(machine) {
const phase = (machine.phases || []).find(p => p.running);
return phase ? cpElapsed(phase) : 0;
}
function svIsDelayed(machine) {
const phase = (machine.phases || []).find(p => p.running);
if (!phase) return false;
const elapsed = cpElapsed(phase);
const limitSecs = phase.limitMins ? Number(phase.limitMins) * 60 : SV_ALERT_MINS * 60;
return elapsed > limitSecs;
}
function svPhaseTimerCls(secs, limitMins) {
const alertSecs = limitMins ? Number(limitMins) * 60 : SV_ALERT_MINS * 60;
const warnSecs = limitMins ? Number(limitMins) * 60 * 0.85 : SV_WARN_MINS * 60;
if (secs > alertSecs) return 'sv-phase-timer--alert';
if (secs > warnSecs) return 'sv-phase-timer--warn';
return 'sv-phase-timer--ok';
}
let _svAudioCtx = null;
function svGetAudioCtx() {
if (!_svAudioCtx) _svAudioCtx = new (window.AudioContext || window.webkitAudioContext)();
return _svAudioCtx;
}
function svPlayBeep() {
try {
const ctx = svGetAudioCtx();
const doPlay = () => {
[0, 0.25, 0.50].forEach(offset => {
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.connect(gain);
gain.connect(ctx.destination);
osc.type = 'square';
osc.frequency.value = 960;
gain.gain.setValueAtTime(1.0, ctx.currentTime + offset);
gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + offset + 0.22);
osc.start(ctx.currentTime + offset);
osc.stop(ctx.currentTime + offset + 0.22);
});
};
if (ctx.state === 'suspended') ctx.resume().then(doPlay); else doPlay();
} catch (_) {}
}
function svInitials(name) {
if (!name) return '?';
const parts = name.trim().split(/\s+/);
return parts.length === 1
? parts[0][0].toUpperCase()
: (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
// ─── Generador HTML de reporte de máquina ─────
function cpGenerateMachineReportHtml(machine, profile) {
const now = cpVetNow();
const nowStr = now.toLocaleString('es', { timeZone: 'America/Caracas', day:'2-digit', month:'2-digit', year:'numeric', hour:'2-digit', minute:'2-digit' });
const fallas = profile.fallas || [];
const mantenimientos = profile.mantenimientos || [];
const activeFallas = fallas.filter(f => !f.resuelta);
const resolvedFallas = fallas.filter(f => f.resuelta);
const lastMant = [...mantenimientos].sort((a,b) => b.fecha.localeCompare(a.fecha))[0];
const gravColor = { leve: '#16a34a', medio: '#ea580c', urgente: '#dc2626' };
const gravBg = { leve: '#f0fdf4', medio: '#fff7ed', urgente: '#fef2f2' };
const gravBorder= { leve: '#86efac', medio: '#fdba74', urgente: '#fca5a5' };
const infoRows = [
['Código', machine.code || machine.id],
['Nombre', machine.name || '—'],
['Marca', profile.marca || '—'],
['Modelo', profile.modelo || '—'],
['Serial', profile.serial || '—'],
['Tipo de maquinaria',profile.tipoMaquinaria || '—'],
['FUENTE / PU', profile.fuentePU || '—'],
['Capacidad', profile.capacidad || '—'],
['Tipo (sistema)', machine.type || '—'],
['Estado operativo', (profile.status || 'operativa').toUpperCase()],
].filter(([,v]) => v && v !== '—');
const infoHtml = infoRows.map(([l,v]) =>
`${l}
${v} `
).join('');
const fallaCard = (f, tipo) => {
const gc = gravColor[f.gravedad] || '#555';
const gb = gravBg[f.gravedad] || '#f9f9f9';
const gbo= gravBorder[f.gravedad]|| '#ccc';
return `
${(f.gravedad||'').toUpperCase()}
Reportada: ${f.fechaReporte || '—'}
${f.resuelta ? `✓ Resuelta: ${f.fechaResolucion || '—'} ` : ''}
${f.reparadoPor ? `Reparó: ${f.reparadoPor} ` : ''}
${f.numeroReporte ? `Reporte #${f.numeroReporte} ` : ''}
${f.descripcion || ''}
${f.solucion ? `
Solución: ${f.solucion}
` : ''}
`;
};
const mantCard = (m) =>
`
${m.fecha || '—'}
${m.realizadoPor ? `por ${m.realizadoPor} ` : ''}
${m.numeroReporte ? `Reporte #${m.numeroReporte} ` : ''}
${m.descripcion || ''}
`;
const section = (title, content, color='#1a1a1a') =>
``;
const obsHtml = profile.observacion
? `
Observación
${profile.observacion}
`
: '';
return `
Ficha de Máquina — ${machine.code || machine.id}
🖨 Imprimir
✕ Ocultar información
${resolvedFallas.length > 0 ? `🔧 Incluir reparaciones ` : ''}
${mantenimientos.length > 0 ? `📋 Incluir mantenimiento ` : ''}
FICHA DE MÁQUINA — ${(machine.code || machine.id).toUpperCase()}
${machine.name || ''}
Generado: ${nowStr}
Estado: ${(profile.status||'operativa').toUpperCase()}
${section('Información técnica',
`
`, '#374151')}
${obsHtml}
${activeFallas.length > 0
? section(`Fallas activas (${activeFallas.length})`, activeFallas.map(f => fallaCard(f,'activa')).join(''), '#b91c1c')
: `✓ Sin fallas activas
`}
${resolvedFallas.length > 0
? `${section(`Historial de reparaciones (${resolvedFallas.length})`, resolvedFallas.map(f => fallaCard(f,'resuelta')).join(''), '#166534')}
`
: ''}
${mantenimientos.length > 0
? `${section(`Último mantenimiento`, lastMant ? mantCard(lastMant) : '', '#1d4ed8')}
`
: ''}
${['Responsable de mantenimiento','Supervisor de planta','Supervisor de Fallas de planta'].map(label =>
`
`
).join('')}
Sistema de Planificación — VERONA COLOR PAINTS — ${nowStr}
`;
}
// ─── MachineDetailModal ───────────────────────
function MachineDetailModal({ machine, profile, onSave, onClose, isAdmin }) {
const fallas = profile.fallas || [];
const mantenimientos = profile.mantenimientos || [];
const activeFallas = fallas.filter(f => !f.resuelta);
const resolvedFallas = fallas.filter(f => f.resuelta);
const lastMant = [...mantenimientos].sort((a, b) => b.fecha.localeCompare(a.fecha))[0];
const gravLabel = { leve: 'Leve', medio: 'Medio', urgente: 'Urgente' };
const gravCls = { leve: 'falla-badge--leve', medio: 'falla-badge--medio', urgente: 'falla-badge--urgente' };
const [tab, setTab] = svUseState('info');
const [editInfo, setEditInfo] = svUseState(false);
const [editMarca, setEditMarca] = svUseState(profile.marca || '');
const [editModelo, setEditModelo] = svUseState(profile.modelo || '');
const [editSerial, setEditSerial] = svUseState(profile.serial || '');
const [editTipoM, setEditTipoM] = svUseState(profile.tipoMaquinaria || '');
const [editFuente, setEditFuente] = svUseState(profile.fuentePU || '');
const [editCap, setEditCap] = svUseState(profile.capacidad || '');
const [editObs, setEditObs] = svUseState(profile.observacion || '');
const [showAddFalla, setShowAddFalla] = svUseState(false);
const [newDesc, setNewDesc] = svUseState('');
const [newGrav, setNewGrav] = svUseState('leve');
const [resolveId, setResolveId] = svUseState(null);
const [resFecha, setResFecha] = svUseState(cpCaracasDateStr());
const [resSol, setResSol] = svUseState('');
const [resPor, setResPor] = svUseState('');
const [resNumRep, setResNumRep] = svUseState('');
const [showAddMant, setShowAddMant] = svUseState(false);
const [mantDesc, setMantDesc] = svUseState('');
const [mantPor, setMantPor] = svUseState('');
const [mantFecha, setMantFecha] = svUseState(cpCaracasDateStr());
const [mantNumRep, setMantNumRep] = svUseState('');
const saveInfo = () => {
onSave({ ...profile,
marca: editMarca.trim(), modelo: editModelo.trim(), serial: editSerial.trim(),
tipoMaquinaria: editTipoM.trim(), fuentePU: editFuente.trim(),
capacidad: editCap.trim(), observacion: editObs.trim(),
});
setEditInfo(false);
};
const toggleStatus = () => {
onSave({ ...profile, status: (profile.status || 'operativa') === 'operativa' ? 'inactiva' : 'operativa' });
};
const addFalla = () => {
if (!newDesc.trim()) return;
const f = {
id: 'f' + Date.now() + Math.random().toString(36).slice(2, 5),
descripcion: newDesc.trim(), gravedad: newGrav,
fechaReporte: cpCaracasDateStr(), reportadoPor: 'Admin',
resuelta: false, fechaResolucion: null, solucion: '',
};
onSave({ ...profile, fallas: [...fallas, f] });
setNewDesc(''); setNewGrav('leve'); setShowAddFalla(false);
};
const resolverFalla = (id) => {
if (!resSol.trim()) return;
onSave({ ...profile, fallas: fallas.map(f => f.id === id ? { ...f, resuelta: true, fechaResolucion: resFecha, solucion: resSol.trim(), reparadoPor: resPor.trim(), numeroReporte: resNumRep.trim() } : f) });
setResolveId(null); setResSol(''); setResFecha(cpCaracasDateStr()); setResPor(''); setResNumRep('');
};
const addMantenimiento = () => {
if (!mantDesc.trim()) return;
const m = {
id: 'm' + Date.now() + Math.random().toString(36).slice(2, 5),
fecha: mantFecha, descripcion: mantDesc.trim(),
realizadoPor: mantPor.trim(), numeroReporte: mantNumRep.trim(),
};
onSave({ ...profile, mantenimientos: [...mantenimientos, m] });
setMantDesc(''); setMantPor(''); setMantFecha(cpCaracasDateStr()); setMantNumRep(''); setShowAddMant(false);
};
const machStatus = profile.status || 'operativa';
return (
e.stopPropagation()}>
{machine.code || machine.id}
{machine.name}
{machine.type}
{machStatus === 'operativa' ? '✓ OPERATIVA' : '✗ INACTIVA'}
{activeFallas.length > 0 && (
⚠ {activeFallas.length} falla{activeFallas.length !== 1 ? 's' : ''}
)}
{
const html = cpGenerateMachineReportHtml(machine, profile);
const w = window.open('', '_blank');
w.document.write(html);
w.document.close();
}}
title="Imprimir ficha de máquina"
>{window.t('🖨 Imprimir')}
✕
setTab('info')}>{window.t('Información')}
setTab('fallas')}>
{window.t('Fallas activas')}{activeFallas.length > 0 && {activeFallas.length} }
setTab('resueltas')}>
{window.t('Resueltas')}{resolvedFallas.length > 0 && {resolvedFallas.length} }
setTab('mantenimiento')}>
{window.t('Mantenimiento')}{mantenimientos.length > 0 && {mantenimientos.length} }
{/* TAB: Información */}
{tab === 'info' && (
{window.t('Información')}
{isAdmin && !editInfo && setEditInfo(true)}>{window.t('Editar')} }
{isAdmin && editInfo && (
{window.t('Guardar')}
setEditInfo(false)}>{window.t('Cancelar')}
)}
{[
['Marca', 'marca', editMarca, setEditMarca ],
['Modelo', 'modelo', editModelo, setEditModelo],
['Serial', 'serial', editSerial, setEditSerial],
['Tipo de maquinaria','tipoMaquinaria', editTipoM, setEditTipoM ],
['FUENTE / PU', 'fuentePU', editFuente, setEditFuente],
['Capacidad', 'capacidad', editCap, setEditCap ],
].map(([label, key, val, setter]) => (
{window.t(label)}
{editInfo
? setter(e.target.value)} placeholder={`${label}...`} />
: {profile[key] || '—'} }
))}
{window.t('Tipo (sistema)')}
{machine.type || '—'}
{lastMant && (
{window.t('Último mantenimiento')}
{lastMant.fecha}{lastMant.realizadoPor ? ` — ${lastMant.realizadoPor}` : ''}
{lastMant.numeroReporte ? ` · Reporte #${lastMant.numeroReporte}` : ''}
)}
{(editInfo || profile.observacion) && (
)}
)}
{/* TAB: Fallas activas */}
{tab === 'fallas' && (
{activeFallas.length === 0 && !showAddFalla &&
{window.t('Sin fallas activas')}
}
{activeFallas.map(f => (
{gravLabel[f.gravedad]}
{f.fechaReporte}
{window.t('por')} {f.reportadoPor}
{f.descripcion}
{isAdmin && resolveId === f.id ? (
) : isAdmin ? (
{ setResolveId(f.id); setResSol(''); setResFecha(cpCaracasDateStr()); setResPor(''); setResNumRep(''); }}>
{window.t('✓ Marcar como resuelta')}
) : null}
))}
{isAdmin && (showAddFalla ? (
setNewGrav(e.target.value)}>
{window.t('Leve')}
{window.t('Medio')}
{window.t('Urgente')}
) : (
setShowAddFalla(true)}>{window.t('⚠ Reportar nueva falla')}
))}
)}
{/* TAB: Resueltas */}
{tab === 'resueltas' && (
{resolvedFallas.length === 0 &&
{window.t('Sin fallas resueltas')}
}
{resolvedFallas.map(f => (
{gravLabel[f.gravedad]}
{window.t('Reportada:')} {f.fechaReporte}
{window.t('✓ Resuelta:')} {f.fechaResolucion}
{f.descripcion}
{f.solucion &&
Solución: {f.solucion}
}
))}
)}
{/* TAB: Mantenimiento */}
{tab === 'mantenimiento' && (
{mantenimientos.length === 0 && !showAddMant &&
{window.t('Sin registros de mantenimiento')}
}
{[...mantenimientos].reverse().map(m => (
{m.fecha}
{m.realizadoPor && {window.t('por')} {m.realizadoPor} }
{m.numeroReporte && Reporte #{m.numeroReporte} }
{m.descripcion}
))}
{isAdmin && (showAddMant ? (
) : (
setShowAddMant(true)}>{window.t('+ Registrar mantenimiento')}
))}
)}
);
}
function SvMachineCard({ machine, tick, profile, onSaveProfile, isAdmin, onShowDetail, isMuted, onMuteAlarm }) {
const status = cpMachineStatus(machine);
const progress = cpMachineProgress(machine);
const elapsed = cpMachineTotalSeconds(machine);
const badge = SV_STATUS_CONFIG[status] || SV_STATUS_CONFIG.idle;
const IconName = SV_MACHINE_ICONS[machine.type] || 'Activity';
const MachIcon = window.Icons?.[IconName] || window.Icons?.Activity;
const currentPhase = (machine.phases || []).find(p => p.running);
const donePhases = (machine.phases || []).filter(p => p.status === 'done').length;
const totalPhases = (machine.phases || []).length;
const phaseElapsed = svCurrentPhaseElapsed(machine);
const timerCls = svPhaseTimerCls(phaseElapsed, currentPhase?.limitMins);
const delayed = svIsDelayed(machine);
const cardColor = machine.color || '#3b6fd4';
const safeProfile = profile || {};
const activeFallas = (safeProfile.fallas || []).filter(f => !f.resuelta);
const machOpStatus = safeProfile.status || 'operativa';
return (
{/* ── Cabecera de color ── */}
{MachIcon && }
{machine.name}
{machine.code && {machine.code} }
{delayed && ⚠ }
0 ? ' sv-mach-cond-badge--fallas' : ''}`}
title={`Estado: ${machOpStatus}${activeFallas.length > 0 ? ` · ${activeFallas.length} falla(s)` : ''}`}
>
{machOpStatus === 'operativa' ? '✓' : '✗'}
{activeFallas.length > 0 && {activeFallas.length} }
{status === 'running' && }
{badge.label}
{/* ── Cuerpo ── */}
{/* Operario */}
{svInitials(machine.operario)}
{window.t('OPERARIO')}
{machine.operario || {window.t('Sin asignar')} }
{/* Lote + Cantidad */}
{window.t('LOTE')}
{machine.lote || '—'}
{machine.cantidad && (
GL
{machine.cantidad}
)}
{elapsed > 0 && (
{window.t('TIEMPO TOTAL')}
{cpFormatDuration(elapsed)}
)}
{/* Fase activa con temporizador */}
{currentPhase ? (
{window.t('FASE ACTIVA')}
{cpFormatDuration(phaseElapsed)}
{currentPhase.name}
) : status === 'idle' ? (
{window.t('Sin fase en curso')}
) : null}
{/* Puntos de progreso de fases */}
{totalPhases > 0 && (
{(machine.phases || []).map((p, i) => (
))}
{donePhases}/{totalPhases}
)}
{/* Asignaciones */}
{(machine.assignments || []).length > 0 && (
{(machine.assignments || []).map(a => (
{a.kind === 'color' && (
)}
{a.nombre}
{a.cantidad && {a.cantidad} {a.unit} }
))}
)}
{/* Botón apagar alarma */}
{delayed && (
{ e.stopPropagation(); onMuteAlarm && onMuteAlarm(); }}
title={isMuted ? window.t('Alarma silenciada') : window.t('Apagar alarma')}
>
{isMuted ? window.t('🔕 Alarma silenciada') : window.t('🔔 Apagar alarma')}
)}
{/* Botón ver detalles */}
{ e.stopPropagation(); onShowDetail && onShowDetail(); }}
>
{window.t('Ver detalles')}
);
}
function SvBaseCard({ base, machines }) {
const isAssigned = (itemId) =>
machines.some(m => (m.assignments || []).some(a => a.id === itemId));
const doneColors = (base.colors || []).filter(c => c.checkEM || c.status === 'ready').length;
const inProcColors = (base.colors || []).filter(c => c.checkEC && !(c.checkEM || c.status === 'ready')).length;
const totalColors = (base.colors || []).length;
const pct = totalColors ? Math.round(doneColors / totalColors * 100) : 0;
const assigned = isAssigned(base.id);
return (
{base.tipo || 'BASE'}
{base.nombre}
{base.code} · {base.cantidad} {base.unit}
{base.carryoverFrom && (
↩ pendiente anterior
)}
{assigned &&
EN MÁQUINA }
{totalColors > 0 && (
<>
{doneColors}/{totalColors} listos
{inProcColors > 0 && ` · ${inProcColors} en proceso`}
{(base.colors || []).map(c => {
const cDone = c.checkEM || c.status === 'ready';
const cRunning = c.checkEC && !cDone;
return (
{c.nombre}
{cDone ? '✓' : cRunning ? '◉' : '○'}
);
})}
>
)}
);
}
// ─── Informe general (multi-máquina) ─────────
function cpGenerateGeneralReportHtml(selected, machineProfiles) {
const now = cpVetNow();
const nowStr = now.toLocaleString('es', { timeZone: 'America/Caracas', day:'2-digit', month:'2-digit', year:'numeric', hour:'2-digit', minute:'2-digit' });
const statusColor = (s) => s === 'operativa' ? '#16a34a' : '#dc2626';
const summaryRows = selected.map(m => {
const profile = machineProfiles[m.code || m.id] || {};
const fallas = (profile.fallas || []).filter(f => !f.resuelta);
const status = profile.status || 'operativa';
return `
${m.code || m.id}
${m.name || '—'}
${m.type || '—'}
${status.toUpperCase()}
${fallas.length || '—'}
`;
}).join('');
const machineSection = (m) => {
const profile = machineProfiles[m.code || m.id] || {};
const fallas = (profile.fallas || []).filter(f => !f.resuelta);
const status = profile.status || 'operativa';
const infoRows = [
['Marca', profile.marca], ['Modelo', profile.modelo], ['Serial', profile.serial],
['Tipo de maquinaria', profile.tipoMaquinaria], ['Capacidad', profile.capacidad],
].filter(([,v]) => v);
return `
${m.code || m.id} — ${m.name || ''}
${status.toUpperCase()}
${infoRows.length ? `
${infoRows.map(([l,v]) => `${l} ${v} `).join('')}
` : ''}
${fallas.length
? fallas.map(f => `
${f.gravedad || ''} · ${f.fechaReporte || ''} — ${f.descripcion || ''}
`).join('')
: `
✓ Sin fallas activas
`}
`;
};
return `
Informe general de máquinas
🖨 Imprimir
INFORME GENERAL DE MÁQUINAS (${selected.length})
Generado: ${nowStr}
Código
Nombre
Tipo
Estado
Fallas activas
${summaryRows}
${selected.map(machineSection).join('')}
Sistema de Planificación — VERONA COLOR PAINTS — ${nowStr}
`;
}
function cpGenerateGeneralReportTxt(selected, machineProfiles) {
const now = cpVetNow();
const nowStr = now.toLocaleString('es', { timeZone: 'America/Caracas', day:'2-digit', month:'2-digit', year:'numeric', hour:'2-digit', minute:'2-digit' });
let txt = `INFORME GENERAL DE MÁQUINAS — VERONA COLOR PAINTS\nGenerado: ${nowStr}\n${'='.repeat(50)}\n\n`;
selected.forEach(m => {
const profile = machineProfiles[m.code || m.id] || {};
const status = (profile.status || 'operativa').toUpperCase();
const fallas = (profile.fallas || []).filter(f => !f.resuelta);
txt += `${m.code || m.id} — ${m.name || ''} [${m.type || ''}]\nEstado: ${status}\n`;
if (fallas.length) {
txt += `Fallas activas (${fallas.length}):\n`;
fallas.forEach(f => { txt += ` - [${(f.gravedad||'').toUpperCase()}] ${f.fechaReporte || ''}: ${f.descripcion || ''}\n`; });
} else {
txt += `Sin fallas activas\n`;
}
txt += `${'-'.repeat(40)}\n`;
});
return txt;
}
function GeneralMachineReportModal({ machines, machineProfiles, onClose }) {
const [q, setQ] = svUseState('');
const [typeFilter, setTypeFilter] = svUseState('');
const [statusFilter, setStatusFilter] = svUseState('');
const [selected, setSelected] = svUseState(new Set());
const presentTypes = svUseMemo(() => Array.from(new Set(machines.map(m => m.type))).sort(), [machines]);
const filtered = svUseMemo(() => machines.filter(m => {
const profile = machineProfiles[m.code || m.id] || {};
const status = profile.status || 'operativa';
if (typeFilter && m.type !== typeFilter) return false;
if (statusFilter && status !== statusFilter) return false;
if (q.trim()) {
const s = q.trim().toLowerCase();
if (!(m.code || m.id || '').toLowerCase().includes(s) && !(m.name || '').toLowerCase().includes(s)) return false;
}
return true;
}), [machines, machineProfiles, q, typeFilter, statusFilter]);
const toggle = (id) => setSelected(prev => { const s = new Set(prev); s.has(id) ? s.delete(id) : s.add(id); return s; });
const toggleAll = () => setSelected(prev => prev.size === filtered.length ? new Set() : new Set(filtered.map(m => m.id)));
const selectedMachines = machines.filter(m => selected.has(m.id));
const openHtmlReport = () => {
if (!selectedMachines.length) return;
const html = cpGenerateGeneralReportHtml(selectedMachines, machineProfiles);
const w = window.open('', '_blank');
w.document.write(html);
w.document.close();
};
const exportTxt = () => {
if (!selectedMachines.length) return;
const txt = cpGenerateGeneralReportTxt(selectedMachines, machineProfiles);
const blob = new Blob([txt], { type: 'text/plain;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = `informe-general-maquinas-${cpCaracasDateStr()}.txt`;
a.click();
URL.revokeObjectURL(url);
};
return (
e.stopPropagation()}>
{window.t('📑 Informe general de máquinas')}
✕
setQ(e.target.value)} />
setTypeFilter(e.target.value)}>
{window.t('Todos los tipos')}
{presentTypes.map(t => {t} )}
setStatusFilter(e.target.value)}>
{window.t('Todos los estados')}
{window.t('Operativa')}
{window.t('Inactiva')}
{selected.size === filtered.length && filtered.length > 0 ? window.t('Deseleccionar todas') : window.t('Seleccionar todas')}
{selected.size} {window.t('seleccionadas')} · {filtered.length} {window.t('en lista')}
{filtered.map(m => {
const profile = machineProfiles[m.code || m.id] || {};
const status = profile.status || 'operativa';
return (
toggle(m.id)} />
{m.code || m.id}
{m.name}
{m.type}
{status === 'operativa' ? '✓ OPERATIVA' : '✗ INACTIVA'}
);
})}
{filtered.length === 0 &&
{window.t('Sin resultados')}
}
{window.t('🖨 Generar / Imprimir')}
{window.t('⬇ Exportar TXT')}
{window.t('Cerrar')}
);
}
function SupervisorView({ allPlan, currentDate, machines, tick, isAdmin, machineProfiles, onSaveMachineProfile, onOpenPersonal }) {
const [typeFilter, setTypeFilter] = svUseState('all');
const [detailMachine, setDetailMachine] = svUseState(null);
const [showGeneralReport, setShowGeneralReport] = svUseState(false);
const [mutedAlarms, setMutedAlarms] = svUseState(new Set());
const alertedRef = svUseRef(new Set());
const lastBeepRef = svUseRef({});
const bases = allPlan[currentDate] || [];
const deriveBaseStatus = (b) => {
if (b.status === 'cancelled') return 'cancelled';
if (b.status === 'done' || b.checkFN || (b.colors || []).filter(c => !c.cancelled).every(c => c.checkEM || c.status === 'ready')) return 'done';
if (
machines.some(m => (m.assignments || []).some(a => a.id === b.id)) ||
b.status === 'running' ||
b.checkEC ||
(b.colors || []).some(c => c.checkEC)
) return 'running';
return 'pending';
};
const pendingBases = svUseMemo(() =>
bases.filter(b => { const s = deriveBaseStatus(b); return s === 'pending' || s === 'running'; }),
[bases, machines, tick]
);
const activeMachines = svUseMemo(() =>
machines.filter(m => { const s = cpMachineStatus(m); return s === 'running' || s === 'paused'; }),
[machines, tick]
);
const idleMachines = svUseMemo(() =>
machines.filter(m => cpMachineStatus(m) === 'idle'),
[machines, tick]
);
const doneMachines = svUseMemo(() =>
machines.filter(m => cpMachineStatus(m) === 'done'),
[machines, tick]
);
/* ── KPIs ── */
const runningCount = activeMachines.filter(m => cpMachineStatus(m) === 'running').length;
const pausedCount = activeMachines.filter(m => cpMachineStatus(m) === 'paused').length;
const delayedCount = machines.filter(m => cpMachineStatus(m) === 'running' && svIsDelayed(m)).length;
const doneBases = bases.filter(b => deriveBaseStatus(b) === 'done').length;
const efficiency = machines.length > 0 ? Math.round((runningCount / machines.length) * 100) : 0;
const avgTimeSecs = doneMachines.length > 0
? Math.round(doneMachines.reduce((s, m) => s + cpMachineTotalSeconds(m), 0) / doneMachines.length)
: 0;
/* ── Alerta sonora al exceder tiempo de fase ── */
svUseEffect(() => {
let shouldBeep = false;
const now = Date.now();
machines.forEach(m => {
if (cpMachineStatus(m) === 'running' && svIsDelayed(m)) {
if (!mutedAlarms.has(m.id)) {
const last = lastBeepRef.current[m.id] || 0;
if (now - last > 4000) {
lastBeepRef.current[m.id] = now;
shouldBeep = true;
}
}
} else {
delete lastBeepRef.current[m.id];
alertedRef.current.delete(m.id);
if (mutedAlarms.has(m.id)) {
setMutedAlarms(prev => { const s = new Set(prev); s.delete(m.id); return s; });
}
}
});
if (shouldBeep) svPlayBeep();
}, [tick]);
/* ── Filtro por tipo ── */
const presentTypes = svUseMemo(() => new Set(machines.map(m => m.type)), [machines]);
const availableGroups = SV_TYPE_GROUPS.filter(g => g.id === 'all' || (g.types && g.types.some(t => presentTypes.has(t))));
const typeGroup = SV_TYPE_GROUPS.find(g => g.id === typeFilter);
const filterFn = (m) => !typeGroup?.types || typeGroup.types.includes(m.type);
const filteredActive = activeMachines.filter(filterFn);
const filteredDone = doneMachines.filter(filterFn);
const filteredIdle = idleMachines.filter(filterFn);
const filteredOther = [...filteredDone, ...filteredIdle];
/* ── Fecha ── */
const d = new Date(currentDate + 'T12:00:00');
const dayName = d.toLocaleDateString('es', { weekday: 'long' });
const dayNum = String(d.getDate()).padStart(2, '0');
const monthYear = d.toLocaleDateString('es', { month: 'long', year: 'numeric' });
return (
{/* ── ENCABEZADO ── */}
{dayNum}
{dayName.charAt(0).toUpperCase() + dayName.slice(1)}
{monthYear.charAt(0).toUpperCase() + monthYear.slice(1)}
{runningCount}
{window.t('EN PROCESO')}
{pausedCount}
{window.t('PAUSADAS')}
{doneMachines.length}
{window.t('FINALIZADAS')}
{idleMachines.length}
{window.t('INACTIVAS')}
{pendingBases.length}
{window.t('BASES PENDIENTES')}
{onOpenPersonal && (
Personal
)}
{window.t('VISTA SUPERVISOR')}
{/* ── BARRA KPI ── */}
{efficiency}%
{window.t('EFICIENCIA TURNO')}
{doneBases}
{window.t('LOTES COMPLETADOS')}
{avgTimeSecs > 0 ? cpFormatDuration(avgTimeSecs) : '—'}
{window.t('TIEMPO PROM. LOTE')}
0 ? ' sv-kpi-item--alert' : ''}`}>
{delayedCount > 0 && }
{delayedCount}
{window.t('FASE EXCEDIDA')}
{/* ── LAYOUT: MÁQUINAS | BASES PENDIENTES ── */}
{/* Panel izquierdo: máquinas */}
{/* Filtro por tipo */}
{availableGroups.length > 1 && (
{availableGroups.map(g => (
setTypeFilter(g.id)}
>
{g.label}
{g.types
? machines.filter(m => g.types.includes(m.type)).length
: machines.length}
))}
)}
{window.t('MÁQUINAS ACTIVAS')}
{filteredActive.length} {window.t('activas')}
setShowGeneralReport(true)}>
{window.t('📑 Informe general')}
{machines.length === 0 && (
⚙️
No hay máquinas configuradas
)}
{filteredActive.length > 0 && (
{filteredActive.map(m => (
onSaveMachineProfile(m.code || m.id, prof) : null}
isAdmin={!!isAdmin}
onShowDetail={() => setDetailMachine(m)}
isMuted={mutedAlarms.has(m.id)}
onMuteAlarm={() => setMutedAlarms(prev => { const s = new Set(prev); s.add(m.id); return s; })}
/>
))}
)}
{filteredActive.length === 0 && machines.length > 0 && (
{window.t('Ninguna máquina activa en este grupo')}
)}
{filteredOther.length > 0 && (
<>
{window.t('OTRAS MÁQUINAS')}
{filteredOther.map(m => (
onSaveMachineProfile(m.code || m.id, prof) : null}
isAdmin={!!isAdmin}
onShowDetail={() => setDetailMachine(m)}
isMuted={mutedAlarms.has(m.id)}
onMuteAlarm={() => setMutedAlarms(prev => { const s = new Set(prev); s.add(m.id); return s; })}
/>
))}
>
)}
{/* Panel derecho: bases pendientes */}
{window.t('BASES PENDIENTES')}
{pendingBases.length} {window.t('pendientes')}
{pendingBases.length === 0 && (
✅
{window.t('Todas las bases han sido completadas')}
)}
{pendingBases.map(b => (
))}
{showGeneralReport && (
setShowGeneralReport(false)}
/>
)}
{detailMachine && (
onSaveMachineProfile(detailMachine.code || detailMachine.id, prof)
: () => {}}
onClose={() => setDetailMachine(null)}
isAdmin={!!isAdmin}
/>
)}
);
}
// ══════════════════════════════════════════
// EQUIPOS — herramientas y maquinaria auxiliar
// (bombas, pesos, equipos de traslado, tolvas, tanques, tornillos sin fin...)
// ══════════════════════════════════════════
const EQUIPO_CATEGORIES = [
{ id: 'bomba', label: 'Bombas' },
{ id: 'peso', label: 'Pesos' },
{ id: 'traslado', label: 'Equipos de traslado' },
{ id: 'tolva', label: 'Tolvas' },
{ id: 'tanque', label: 'Tanques' },
{ id: 'tornillo', label: 'Tornillos sin fin' },
{ id: 'otro', label: 'Otros' },
];
const EQUIPO_AREAS = [
{ id: 'preparadores', label: 'Preparadores' },
{ id: 'matizacion', label: 'Matización' },
{ id: 'envasadores', label: 'Envasadores' },
{ id: 'control_proceso', label: 'Control de Proceso' },
];
function eqAreaLabel(id) { return (EQUIPO_AREAS.find(a => a.id === id) || {}).label || id || '—'; }
// Mapea el tipo de máquina del sistema al área/departamento que la opera
function cpMachineArea(type) {
if (type === 'dispersor1') return 'matizacion';
if (type === 'envasado') return 'envasadores';
if (type === 'dispersorp' || type === 'dispersor') return 'preparadores';
return 'control_proceso';
}
const EQUIPO_STATUS = {
operativo: { label: 'Operativo', cls: 'eq-status--ok' },
falla: { label: 'En falla', cls: 'eq-status--falla' },
mantenimiento: { label: 'Mantenimiento', cls: 'eq-status--mant' },
fuera_servicio: { label: 'Fuera de servicio', cls: 'eq-status--off' },
};
function eqCategoryLabel(id) { return (EQUIPO_CATEGORIES.find(c => c.id === id) || {}).label || id || '—'; }
function eqNewId() { return 'eq' + Date.now() + Math.random().toString(36).slice(2, 6); }
// Unidades de capacidad y procesos sugeridos (esmalte)
const EQUIPO_UNIDADES = ['GL', 'Kg', 'Lt'];
const EQUIPO_PROCESOS = ['Dispersión', 'Molienda', 'Reposo', 'Matización', 'Control de calidad', 'Ajuste', 'Envasado', 'Limpieza'];
// Categorías que "contienen" material y por tanto tienen ocupación/actividad
const EQ_OCUPABLE = ['tanque', 'tolva', 'traslado'];
function eqUsaOcupacion(cat) { return EQ_OCUPABLE.includes(cat); }
// Disponible por defecto (mientras no se marque ocupado explícitamente)
function eqDisponible(e) { return e.disponible !== false; }
function EquiposView({ equipos, isAdmin, onChange, machines, machineProfiles, canReportMachineFalla, onReportMachineFalla }) {
const list = equipos || [];
const [q, setQ] = svUseState('');
const [catFilter, setCatFilter] = svUseState('');
const [statFilter, setStatFilter] = svUseState('');
const [areaFilter, setAreaFilter] = svUseState('');
const [detail, setDetail] = svUseState(null);
const [fallaMachine, setFallaMachine] = svUseState(null);
const [showAdd, setShowAdd] = svUseState(false);
const [nCode, setNCode] = svUseState('');
const [nName, setNName] = svUseState('');
const [nCat, setNCat] = svUseState(EQUIPO_CATEGORIES[0].id);
const [nArea, setNArea] = svUseState(EQUIPO_AREAS[0].id);
const [nUbic, setNUbic] = svUseState('');
const [nResp, setNResp] = svUseState('');
const [nCap, setNCap] = svUseState('');
const [nCapUnit, setNCapUnit] = svUseState(EQUIPO_UNIDADES[0]);
const [availFilter, setAvailFilter] = svUseState('');
const filtered = svUseMemo(() => list.filter(e => {
if (catFilter && e.category !== catFilter) return false;
if (statFilter && (e.status || 'operativo') !== statFilter) return false;
if (areaFilter && e.area !== areaFilter) return false;
if (availFilter) {
if (!eqUsaOcupacion(e.category)) return false;
if (availFilter === 'disponible' && !eqDisponible(e)) return false;
if (availFilter === 'ocupado' && eqDisponible(e)) return false;
}
if (q.trim()) {
const s = q.trim().toLowerCase();
if (!(e.code || '').toLowerCase().includes(s) && !(e.name || '').toLowerCase().includes(s)
&& !(e.contenido || '').toLowerCase().includes(s) && !(e.lote || '').toLowerCase().includes(s)) return false;
}
return true;
}), [list, q, catFilter, statFilter, areaFilter, availFilter]);
const filteredMachines = svUseMemo(() => (machines || []).filter(m => {
if (areaFilter && cpMachineArea(m.type) !== areaFilter) return false;
if (q.trim()) {
const s = q.trim().toLowerCase();
if (!(m.code || m.id || '').toLowerCase().includes(s) && !(m.name || '').toLowerCase().includes(s)) return false;
}
return true;
}), [machines, q, areaFilter]);
const presentCats = svUseMemo(() => new Set(list.map(e => e.category)), [list]);
const saveEquipo = (id, patch) => {
onChange(list.map(e => e.id === id ? { ...e, ...patch } : e));
};
const addEquipo = () => {
if (!nCode.trim() || !nName.trim()) return;
const e = {
id: eqNewId(), code: nCode.trim().toUpperCase(), name: nName.trim(),
category: nCat, area: nArea, status: 'operativo', ubicacion: nUbic.trim(), responsable: nResp.trim(),
capacidad: nCap.trim(), capacidadUnidad: nCapUnit,
disponible: true, contenido: '', lote: '', proceso: '',
proximoMantenimiento: '', notas: '', fallas: [],
};
onChange([...list, e]);
setNCode(''); setNName(''); setNUbic(''); setNResp(''); setNCat(EQUIPO_CATEGORIES[0].id); setNArea(EQUIPO_AREAS[0].id);
setNCap(''); setNCapUnit(EQUIPO_UNIDADES[0]);
setShowAdd(false);
};
const delEquipo = (id) => {
if (!window.verifyDeleteKey(window.t('¿Eliminar este equipo?'))) return;
onChange(list.filter(e => e.id !== id));
if (detail && detail.id === id) setDetail(null);
};
return (
{window.t('Equipos y herramientas')}
{window.t('Bombas, pesos, equipos de traslado, tolvas, tanques, tornillos sin fin...')}
{isAdmin &&
setShowAdd(s => !s)}>{window.t('+ Nuevo equipo')} }
{showAdd && (
)}
{window.t('Equipos')}
{filtered.length}
{filtered.length === 0 && (
🧰
{list.length === 0 ? window.t('No hay equipos registrados todavía') : window.t('Sin resultados para este filtro')}
)}
{filtered.map(e => {
const st = EQUIPO_STATUS[e.status || 'operativo'] || EQUIPO_STATUS.operativo;
const activeFallas = (e.fallas || []).filter(f => !f.resuelta);
return (
{e.code}
{e.name}
{window.t(eqCategoryLabel(e.category))}
{e.area &&
{window.t(eqAreaLabel(e.area))} }
{e.ubicacion &&
📍 {e.ubicacion} }
{e.responsable &&
👤 {e.responsable} }
{e.capacidad &&
🛢 {e.capacidad} {e.capacidadUnidad || ''} }
{eqUsaOcupacion(e.category) && (
{eqDisponible(e) ? window.t('Disponible') : window.t('Ocupado')}
)}
{eqUsaOcupacion(e.category) && !eqDisponible(e) && (e.contenido || e.proceso) && (
🧪 {e.contenido || '—'}{e.lote ? ' · ' + e.lote : ''}{e.proceso ? ' · ' + e.proceso : ''}
)}
{window.t(st.label)}
{activeFallas.length > 0 &&
⚠ {activeFallas.length} }
setDetail(e)}>{window.t('Ver detalles')}
{isAdmin &&
delEquipo(e.id)} title={window.t('Eliminar')}>✕ }
);
})}
{window.t('Máquinas')}
{filteredMachines.length}
{window.t('Solo lectura — cualquier supervisor puede reportar fallas')}
{filteredMachines.length === 0 && (
⚙️
{window.t('Sin máquinas para este filtro')}
)}
{filteredMachines.map(m => {
const profile = (machineProfiles && machineProfiles[m.code || m.id]) || {};
const status = profile.status || 'operativa';
const activeFallas = (profile.fallas || []).filter(f => !f.resuelta);
return (
{m.code || m.id}
{m.name}
{m.type}
{window.t(eqAreaLabel(cpMachineArea(m.type)))}
{status === 'operativa' ? '✓ OPERATIVA' : '✗ INACTIVA'}
{activeFallas.length > 0 &&
⚠ {activeFallas.length} }
setFallaMachine(m)}>{window.t('Ver detalles')}
);
})}
{detail && (
e.id === detail.id) || detail}
isAdmin={!!isAdmin}
onSave={patch => saveEquipo(detail.id, patch)}
onClose={() => setDetail(null)}
/>
)}
{fallaMachine && (
onReportMachineFalla && onReportMachineFalla(fallaMachine.code || fallaMachine.id, descripcion, gravedad)}
onClose={() => setFallaMachine(null)}
/>
)}
);
}
function MachineFallaModal({ machine, profile, canReport, onReport, onClose }) {
const fallas = profile.fallas || [];
const activeFallas = fallas.filter(f => !f.resuelta);
const resolvedFallas = fallas.filter(f => f.resuelta);
const gravLabel = { leve: 'Leve', medio: 'Medio', urgente: 'Urgente' };
const gravCls = { leve: 'falla-badge--leve', medio: 'falla-badge--medio', urgente: 'falla-badge--urgente' };
const status = profile.status || 'operativa';
const [showReport, setShowReport] = svUseState(false);
const [rDesc, setRDesc] = svUseState('');
const [rGrav, setRGrav] = svUseState('leve');
const submit = () => {
if (!rDesc.trim()) return;
onReport(rDesc.trim(), rGrav);
setRDesc(''); setRGrav('leve'); setShowReport(false);
};
return (
e.stopPropagation()}>
{machine.code || machine.id}
{machine.name}
{machine.type}
{status === 'operativa' ? '✓ OPERATIVA' : '✗ INACTIVA'}
{activeFallas.length > 0 && (
⚠ {activeFallas.length} falla{activeFallas.length !== 1 ? 's' : ''}
)}
✕
{window.t('Fallas activas')}
{activeFallas.length === 0 && !showReport &&
{window.t('Sin fallas activas')}
}
{activeFallas.map(f => (
{gravLabel[f.gravedad]}
{f.fechaReporte}
{window.t('por')} {f.reportadoPor}
{f.descripcion}
))}
{canReport && (showReport ? (
setRGrav(e.target.value)}>
{window.t('Leve')}
{window.t('Medio')}
{window.t('Urgente')}
) : (
setShowReport(true)}>{window.t('⚠ Reportar nueva falla')}
))}
{resolvedFallas.length > 0 && (
<>
{window.t('Resueltas')}
{resolvedFallas.map(f => (
{gravLabel[f.gravedad]}
{window.t('Reportada:')} {f.fechaReporte}
{window.t('✓ Resuelta:')} {f.fechaResolucion}
{f.descripcion}
{f.solucion &&
Solución: {f.solucion}
}
))}
>
)}
);
}
function EquipoDetailModal({ equipo, isAdmin, onSave, onClose }) {
const fallas = equipo.fallas || [];
const activeFallas = fallas.filter(f => !f.resuelta);
const resolvedFallas = fallas.filter(f => f.resuelta);
const gravLabel = { leve: 'Leve', medio: 'Medio', urgente: 'Urgente' };
const gravCls = { leve: 'falla-badge--leve', medio: 'falla-badge--medio', urgente: 'falla-badge--urgente' };
const st = EQUIPO_STATUS[equipo.status || 'operativo'] || EQUIPO_STATUS.operativo;
const [tab, setTab] = svUseState('info');
const [editInfo, setEditInfo] = svUseState(false);
const [eArea, setEArea] = svUseState(equipo.area || EQUIPO_AREAS[0].id);
const [eUbic, setEUbic] = svUseState(equipo.ubicacion || '');
const [eResp, setEResp] = svUseState(equipo.responsable || '');
const [eMant, setEMant] = svUseState(equipo.proximoMantenimiento || '');
const [eNotas, setENotas] = svUseState(equipo.notas || '');
const [eCap, setECap] = svUseState(equipo.capacidad || '');
const [eCapUnit, setECapUnit] = svUseState(equipo.capacidadUnidad || EQUIPO_UNIDADES[0]);
const [eDisp, setEDisp] = svUseState(eqDisponible(equipo));
const [eCont, setECont] = svUseState(equipo.contenido || '');
const [eLote, setELote] = svUseState(equipo.lote || '');
const [eProc, setEProc] = svUseState(equipo.proceso || '');
const usaOcup = eqUsaOcupacion(equipo.category);
const [showReport, setShowReport] = svUseState(false);
const [rDesc, setRDesc] = svUseState('');
const [rGrav, setRGrav] = svUseState('leve');
const [resolveId, setResolveId] = svUseState(null);
const [resSol, setResSol] = svUseState('');
const [resPor, setResPor] = svUseState('');
const [resFecha, setResFecha] = svUseState(cpCaracasDateStr());
const saveInfo = () => {
onSave({
area: eArea, ubicacion: eUbic.trim(), responsable: eResp.trim(), proximoMantenimiento: eMant, notas: eNotas.trim(),
capacidad: (eCap + '').trim(), capacidadUnidad: eCapUnit,
disponible: usaOcup ? eDisp : true,
contenido: usaOcup ? eCont.trim() : '',
lote: usaOcup ? eLote.trim() : '',
proceso: usaOcup ? eProc.trim() : '',
});
setEditInfo(false);
};
const reportarFalla = () => {
if (!rDesc.trim()) return;
const f = {
id: eqNewId(), descripcion: rDesc.trim(), gravedad: rGrav,
fechaReporte: cpCaracasDateStr(), reportadoPor: 'Admin',
resuelta: false, fechaResolucion: null, solucion: '',
};
onSave({ fallas: [...fallas, f], status: 'falla' });
setRDesc(''); setRGrav('leve'); setShowReport(false);
};
const resolverFalla = (id) => {
if (!resSol.trim()) return;
const nextFallas = fallas.map(f => f.id === id ? { ...f, resuelta: true, fechaResolucion: resFecha, solucion: resSol.trim(), reparadoPor: resPor.trim() } : f);
const stillActive = nextFallas.some(f => !f.resuelta);
onSave({ fallas: nextFallas, status: stillActive ? 'falla' : 'operativo' });
setResolveId(null); setResSol(''); setResPor(''); setResFecha(cpCaracasDateStr());
};
const setStatus = (key) => onSave({ status: key });
return (
e.stopPropagation()}>
{equipo.code}
{equipo.name}
{window.t(eqCategoryLabel(equipo.category))}
{isAdmin ? (
setStatus(e.target.value)}>
{Object.entries(EQUIPO_STATUS).map(([k, v]) => {window.t(v.label)} )}
) : (
{window.t(st.label)}
)}
{activeFallas.length > 0 && ⚠ {activeFallas.length} falla{activeFallas.length !== 1 ? 's' : ''} }
✕
setTab('info')}>{window.t('Información')}
setTab('fallas')}>
{window.t('Fallas activas')}{activeFallas.length > 0 && {activeFallas.length} }
setTab('resueltas')}>
{window.t('Resueltas')}{resolvedFallas.length > 0 && {resolvedFallas.length} }
{tab === 'info' && (
{window.t('Información')}
{isAdmin && !editInfo && setEditInfo(true)}>{window.t('Editar')} }
{isAdmin && editInfo && (
{window.t('Guardar')}
setEditInfo(false)}>{window.t('Cancelar')}
)}
{usaOcup && (
{window.t('Actividad / ocupación')}
)}
{window.t('Notas')}
{editInfo
?
)}
{tab === 'fallas' && (
{activeFallas.length === 0 && !showReport &&
{window.t('Sin fallas activas')}
}
{activeFallas.map(f => (
{gravLabel[f.gravedad]}
{f.fechaReporte}
{window.t('por')} {f.reportadoPor}
{f.descripcion}
{isAdmin && resolveId === f.id ? (
) : isAdmin ? (
{ setResolveId(f.id); setResSol(''); setResFecha(cpCaracasDateStr()); setResPor(''); }}>
{window.t('✓ Marcar como resuelta')}
) : null}
))}
{isAdmin && (showReport ? (
setRGrav(e.target.value)}>
{window.t('Leve')}
{window.t('Medio')}
{window.t('Urgente')}
) : (
setShowReport(true)}>{window.t('⚠ Reportar nueva falla')}
))}
)}
{tab === 'resueltas' && (
{resolvedFallas.length === 0 &&
{window.t('Sin fallas resueltas')}
}
{resolvedFallas.map(f => (
{gravLabel[f.gravedad]}
{window.t('Reportada:')} {f.fechaReporte}
{window.t('✓ Resuelta:')} {f.fechaResolucion}
{f.descripcion}
{f.solucion &&
Solución: {f.solucion}
}
))}
)}
);
}
window.EquiposView = EquiposView;
window.SupervisorView = SupervisorView;