// ════════════════════════════════════════════
// 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 cpEsc(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);
}
// Escapa texto/atributos para interpolar en HTML (informes en ventanas nuevas).
function cpEsc(v) {
return String(v == null ? '' : v)
.replace(/&/g, '&').replace(//g, '>')
.replace(/"/g, '"').replace(/'/g, ''').replace(/`/g, '`');
}
// Aviso visible (toast si existe; si no, alert).
function cpNotify(msg, kind) {
try { if (window.showToast) { window.showToast(msg, kind); return; } } catch (_) {}
try { alert(msg); } catch (_) {}
}
// Usuario actual (nombre) desde variables globales conocidas; 'Usuario' si no hay.
function cpCurrentUserName(explicit) {
if (explicit) return explicit;
try {
const w = window;
const u = w.currentUser || w.CURRENT_USER || w.spCurrentUser || w.AppData?.currentUser;
if (u) {
if (typeof u === 'string') return u;
return u.name || u.nombre || u.username || u.user || u.email || 'Usuario';
}
if (typeof w.getCurrentUser === 'function') {
const g = w.getCurrentUser();
if (g) return typeof g === 'string' ? g : (g.name || g.nombre || g.username || 'Usuario');
}
} catch (_) {}
return 'Usuario';
}
// Escribe un informe HTML en una ventana nueva; avisa si el navegador la bloquea.
function cpOpenReport(html, features) {
const w = window.open('', '_blank', features);
if (!w) { cpNotify('Permite ventanas emergentes para ver el informe.', 'err'); return null; }
try { w.document.write(html); w.document.close(); } catch (_) {}
return w;
}
// Neutraliza fórmulas en celdas CSV (=, +, -, @, tab, CR).
function cpCsvSafe(v) {
const s = String(v == null ? '' : v);
return /^[=+\-@\t\r]/.test(s) ? "'" + s : s;
}
// Fecha ISO sincronizada (reloj del servidor) para cierres.
function cpNowIso() { return new Date(cpNowMs()).toISOString(); }
// Etiqueta legible de un estado de fase ('pendiente' no existe en PHASE_STATUSES).
function cpPhaseStatusLabel(id) {
if (!id || id === 'pendiente') return 'Pendiente';
const f = ((window.AppData && window.AppData.PHASE_STATUSES) || []).find(s => s.id === id);
return f ? f.label : id;
}
// Estado de fase coherente al iniciar: sale de pendiente/preparativos/finalizado a en_proceso.
function cpPhaseStatusOnStart(ps) {
return (!ps || ps === 'pendiente' || ps === 'preparativos' || ps === 'finalizado') ? 'en_proceso' : ps;
}
// Motivo por el que NO conviene asignar lotes a una máquina (inactiva o con
// falla urgente abierta). null = sin impedimento.
function cpMachineBlockReason(profile) {
const pr = profile || {};
if ((pr.status || 'operativa') === 'inactiva') return 'La máquina está INACTIVA.';
const urg = (pr.fallas || []).filter(f => !f.resuelta && f.gravedad === 'urgente');
if (urg.length) return `La máquina tiene ${urg.length} falla(s) URGENTE(S) abierta(s).`;
return null;
}
// Máquina inactiva o con falla urgente: se pide confirmación (a cualquier usuario que
// pueda editar Control de Proceso, no solo al admin). true = se puede continuar.
function cpCheckMachineAssignable(profile, isAdmin, label) {
const reason = cpMachineBlockReason(profile);
if (!reason) return true;
return confirm(`${reason}\n\n¿Asignar el lote a ${label || 'esta máquina'} de todas formas?`);
}
// ¿Ya está este ítem (base/color) asignado o en fila en OTRA máquina?
function cpFindItemElsewhere(itemId, machineId, allMachines) {
return (allMachines || []).find(m => m.id !== machineId &&
((m.assignments || []).some(a => a.id === itemId) ||
(m.queue || []).some(q => (q.items || []).some(a => a.id === itemId)))) || null;
}
// Validaciones + construcción de la máquina resultante al asignar un ítem.
// Devuelve la máquina nueva o null si se rechaza (ya avisó al usuario).
function cpPrepareAssign({ machine, item, allMachines, profile, isAdmin, cpDate, acceptsOverride }) {
if (!item) return null;
const mt = (window.AppData.MACHINE_TYPES || {})[machine.type] || {};
const accepts = acceptsOverride || mt.accepts || ['base', 'color'];
if (!accepts.includes(item.kind)) return null;
if ((machine.assignments || []).some(a => a.id === item.id)) return null;
const usedIn = cpFindItemElsewhere(item.id, machine.id, allMachines);
if (usedIn) {
cpNotify(`"${item.nombre || item.id}" ya está asignado a ${usedIn.code || usedIn.name || 'otra máquina'}.`, 'err');
return null;
}
if (!cpCheckMachineAssignable(profile, isAdmin, machine.code || machine.name)) return null;
// Si la máquina ya tiene un lote de OTRA fecha no se le pisa la fecha:
// el ítem recuerda el día del plan al que pertenece (planDate).
const hasBatch = (machine.assignments || []).length > 0 || !!machine.lote;
const keepFecha = hasBatch && machine.fecha && machine.fecha !== cpDate;
const it = keepFecha ? { ...item, planDate: cpDate } : item;
if (keepFecha) cpNotify(`La máquina ya tiene un lote del ${machine.fecha}; se mantiene su fecha.`);
return { ...machine, fecha: keepFecha ? machine.fecha : cpDate, assignments: [...(machine.assignments || []), it] };
}
// Aplica el cambio de una fase garantizando una sola fase 'running' por máquina.
function cpApplyPhaseUpdate(machine, idx, updated) {
const prev = (machine.phases || [])[idx];
const phases = [...machine.phases];
phases[idx] = updated;
if (updated.running && !(prev && prev.running)) {
let paused = false;
for (let i = 0; i < phases.length; i++) {
if (i !== idx && phases[i].running) {
phases[i] = { ...phases[i], running: false, accumulated: cpElapsed(phases[i]), startedAt: null, status: 'paused' };
paused = true;
}
}
if (paused) cpNotify('Se pausó la otra fase en marcha: solo puede haber una fase corriendo por máquina.');
}
return { ...machine, phases };
}
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';
}
// 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) => cpNotify(m, k);
const asgn = machine.assignments || [];
const payload = 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: machine.hrInicialBatch || '',
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,
});
const attempt = (n) => {
fetch('./api.php', {
method: 'POST', credentials: 'include',
headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'sp' },
body: payload,
})
.then(r => {
if (r.status >= 500) { const e = new Error('http ' + r.status); e.retry = true; throw e; }
return r.json().catch(() => ({}));
})
.then(j => {
if (!j) return;
if (j.error) { toast('Máquina liberada, pero no se pudieron registrar los puntos: ' + j.error, 'err'); return; }
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');
} else if (j.reason === 'sin_operario') {
toast('Máquina liberada. Sin operario asignado: no se otorgaron puntos.', 'err');
} else if (j.reason === 'tipo_sin_departamento') {
toast('Máquina liberada. Este tipo de máquina no tiene departamento de personal: no se otorgaron puntos.', 'err');
} else if (j.reason && j.reason !== 'ya_otorgado') {
toast('Máquina liberada. No se otorgaron puntos (' + j.reason + ').', 'err');
}
})
.catch(() => {
// Fallo de red / 5xx: reintenta con backoff (1.5 s, 3 s); el servidor evita duplicados.
if (n < 3) setTimeout(() => attempt(n + 1), 1500 * n);
else toast('Máquina liberada, pero NO se pudieron registrar los puntos (sin conexión con el servidor). Avisa al administrador.', 'err');
});
};
attempt(1);
}
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(),
hrInicialBatch: '', 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'];
// Día al que pertenece un batch para filtros y Reporte Diario.
// Manda la FECHA cargada en el batch; si está vacía, el día en que se cerró
// EN HORA DE VENEZUELA (usar el ISO en UTC mandaba al día siguiente todo lo
// cerrado después de las 20:00).
function cpBatchDay(b) {
if (!b) return '';
if (b.fecha) return b.fecha;
if (!b.timestamp) return '';
const d = new Date(new Date(b.timestamp).getTime() + _CP_VET_MS);
return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}-${String(d.getUTCDate()).padStart(2, '0')}`;
}
// Hora HH:MM en Venezuela (UTC-4) de un ISO guardado en UTC.
function cpFmtVetHHMM(isoStr) {
const t = new Date(isoStr).getTime();
if (!isoStr || isNaN(t)) return '—';
const d = new Date(t + _CP_VET_MS);
return String(d.getUTCHours()).padStart(2, '0') + ':' + String(d.getUTCMinutes()).padStart(2, '0');
}
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) || (m.queue || []).some(q => (q.items || []).some(a => a.id === itemId)));
const deriveBaseStatus = (b) => {
if (b.status === 'cancelled') return 'cancelled';
const _activeColors = (b.colors || []).filter(c => !c.cancelled);
if (b.status === 'done' || b.checkFN || (_activeColors.length > 0 && _activeColors.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 searchWords = search.trim().toLowerCase().split(/\s+/).filter(Boolean);
if (searchWords.length) {
filtered = filtered.filter(b => {
const haystack = [b.nombre, b.code, b.lote, (b.colors || []).map(c => `${c.nombre} ${c.lote || ''}`).join(' ')]
.filter(Boolean).join(' ').toLowerCase();
return searchWords.every(w => haystack.includes(w));
});
}
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 && (
{searchWords.length ? `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 = searchWords.length
? (b.colors || []).filter(c => searchWords.every(w => `${c.nombre} ${b.nombre}`.toLowerCase().includes(w)))
: (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 && !searchWords.length && (
onAddColor(b.id)}>
Agregar color a esta base
)}
)}
);
})}
{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;
};
// Con la fase en marcha, editar HR inicial/final duplicaría el tiempo
// (acumulado recalculado + cronómetro vivo): se bloquea hasta pausar.
const timeLocked = !!phase.running;
const lockMsg = () => cpNotify('Pausa la fase para editar sus horas manualmente.', 'err');
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, phaseStatus: cpPhaseStatusOnStart(phase.phaseStatus) });
};
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, phaseStatus: 'finalizado' });
};
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()}
>
{canEdit && phaseOptions && phaseOptions.length > 0 ? (
onUpdate({ ...phase, name: e.target.value })}
>
{!phaseOptions.includes(phase.name) && phase.name && (
{phase.name}
)}
{phaseOptions.map((opt, oi) => {opt} )}
) : (
canEdit && onUpdate({ ...phase, name: e.target.value })}
/>
)}
{isContinuation && (
canEdit && onUpdate({ ...phase, phaseDate: null })}
>
📅 {cpFmtShortDate(phase.phaseDate)}
)}
{
if (!canEdit) return;
if (timeLocked) { lockMsg(); return; }
const newStart = e.target.value;
const acc = syncAccumulated(newStart, phase.endTime);
onUpdate({ ...phase, startTime: newStart, accumulated: acc });
}}
/>
{
if (!canEdit) return;
if (timeLocked) { lockMsg(); return; }
const now = cpNowHHMM();
const acc = syncAccumulated(now, phase.endTime);
onUpdate({ ...phase, startTime: now, accumulated: acc });
}}
disabled={!canEdit}
title="Hora actual"
>
{
if (!canEdit) return;
if (timeLocked) { lockMsg(); return; }
const newEnd = e.target.value;
const acc = syncAccumulated(phase.startTime, newEnd);
onUpdate({ ...phase, endTime: newEnd, accumulated: acc });
}}
/>
{
if (!canEdit) return;
if (timeLocked) { lockMsg(); 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
)}
canEdit && onUpdate({ ...phase, phaseStatus: e.target.value })}
>
Pendiente
{PHASE_STATUSES.map(s => (
{s.label}
))}
{phase.status !== 'done' ? (
<>
{!phase.running ? (
) : (
)}
>
) : (
✓
)}
{canEdit && (
{ if (confirm(`¿Eliminar la fase "${phase.name || ''}"?`)) onRemove && onRemove(); }} title="Eliminar fase">
)}
);
}
// ─── FallaModal ───────────────────────────────
function FallaModal({ machine, profile, onSave, onClose, userName, currentUser }) {
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: cpCurrentUserName(userName || currentUser),
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);
cpOpenReport(html);
}}
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, onSetPackagingEnvasado, allPlan, cpDate, operators, allMachines, userName, onRenameMachineCode }) {
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);
const [packagingCtx, setPackagingCtx] = cpUseState(null); // { colorId, colorName, entries }
// Día del plan al que pertenece el ítem (planDate si la máquina conserva otra fecha).
const planDayOf = (itemId) => {
const asg = (machine.assignments || []).find(x => x.id === itemId);
return (asg && asg.planDate) || machine.fecha || cpDate;
};
const findPlanColor = (colorId) => {
const refDate = planDayOf(colorId);
const dayBases = (allPlan && allPlan[refDate]) || [];
for (const b of dayBases) {
const c = (b.colors || []).find(x => x.id === colorId);
if (c) return c;
}
return null;
};
const openPackagingModal = (a) => {
const planColor = findPlanColor(a.id);
const prefill = planColor && planColor.envasadoReal && planColor.envasadoReal.length > 0
? planColor.envasadoReal.map(e => ({ ...e, id: e.id || cpUid() }))
: planColor && planColor.envasado && planColor.envasado.length > 0
? planColor.envasado.map(e => ({ ...e, id: cpUid() }))
: [{ id: cpUid(), tipo: 'gl', cantidad: 0, marca: '' }];
setPackagingCtx({ colorId: a.id, colorName: a.nombre, entries: prefill });
};
const confirmPackaging = () => {
if (!packagingCtx) return;
if (onSetPackagingEnvasado) {
onSetPackagingEnvasado(packagingCtx.colorId, planDayOf(packagingCtx.colorId), packagingCtx.entries);
}
setPackagingCtx(null);
};
// 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(machine.hrInicialBatch)) faltan.push('Hr inicial batch');
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' : '';
// Asignación común a drop de mouse y de toque.
const assignItem = (item) => {
if (!canEdit || !item) return;
const next = cpPrepareAssign({ machine, item, allMachines, profile, isAdmin, cpDate });
if (!next) return;
onUpdate(next);
if (onBaseStarted) onBaseStarted(item.id, item.kind, cpDate, machine.type);
};
// Registro del drop handler para soporte táctil (tablet)
const _cpDropRef = cpUseRef(null);
_cpDropRef.current = (item) => assignItem(item);
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;
onUpdate(cpApplyPhaseUpdate(machine, idx, updated));
};
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, a.planDate || refDate);
});
}
cpAwardMachinePoints(machine, refDate);
};
// Revierte los checks de la base de datos por cada asignación antes de vaciar la máquina.
const revertAssignments = () => {
if (!onAssignmentRemoved) return;
(machine.assignments || []).forEach(a => {
onAssignmentRemoved(a.id, a.kind, a.planDate || machine.fecha || cpDate, machine.type);
});
};
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;
const resetPhases = machine.phases.map(p => ({
...p, running: false, accumulated: 0, startedAt: null,
status: 'pending', startTime: '', endTime: '', phaseStatus: 'pendiente',
}));
revertAssignments();
onUpdate({
...machine,
assignments: [], lote: '', cantidad: '', operario: '',
hrInicialBatch: '', notes: '',
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;
// Snapshot del batch actual con tiempos completos por fase
const snapshot = {
id: cpUid(),
timestamp: cpNowIso(),
fecha: machine.fecha || cpCaracasDateStr(),
assignments: machine.assignments || [],
lote: machine.lote || '',
cantidad: machine.cantidad || '',
operario: machine.operario || '',
hrInicialBatch: machine.hrInicialBatch || '',
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,
};
}),
};
// Reiniciar fases a estado pendiente
const resetPhases = machine.phases.map(p => ({
...p,
running: false,
accumulated: 0,
startedAt: null,
status: 'pending',
startTime: '',
endTime: '',
phaseStatus: 'pendiente',
}));
onUpdate({
...machine,
assignments: [],
lote: '',
cantidad: '',
operario: '',
hrInicialBatch: '',
notes: '',
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, a.planDate || refDate);
});
}
};
// Lote fallido: se guarda en el historial (en rojo) con el problema como observación.
// No cierra la base del plan ni suma puntos.
const marcarFallida = () => {
if (!canEdit) return;
if (!(machine.assignments || []).length && !machine.lote) { alert('Esta máquina no tiene un lote cargado.'); return; }
const reason = (window.prompt('LOTE FALLIDO — ' + machine.name + (machine.lote ? ' · ' + machine.lote : '') + '\n\nEscribe el problema (observación). El lote se guardará en el historial en rojo y la máquina quedará libre:', machine.notes || '') || '').trim();
if (!reason) return;
const now = cpNowHHMM();
const snapshot = {
id: cpUid(),
timestamp: cpNowIso(),
fecha: machine.fecha || cpCaracasDateStr(),
assignments: machine.assignments || [],
lote: machine.lote || '',
cantidad: machine.cantidad || '',
operario: machine.operario || '',
hrInicialBatch: machine.hrInicialBatch || '',
notes: reason,
failed: true,
failReason: reason,
phases: machine.phases.map(p => {
const q = (p.startTime && !p.endTime) ? { ...p, endTime: now, status: p.status === 'done' ? 'done' : 'paused' } : p;
return {
name: q.name,
status: q.status,
phaseStatus: q.phaseStatus || 'pendiente',
startTime: q.startTime || '',
endTime: q.endTime || '',
elapsedSecs: cpElapsed(p),
computedMins: cpPhaseDisplayMins(q),
phaseDate: q.phaseDate || null,
};
}),
};
revertAssignments();
onUpdate({
...machine,
assignments: [], lote: '', cantidad: '', operario: '', hrInicialBatch: '', notes: '',
fecha: cpCaracasDateStr(),
phases: machine.phases.map(p => ({ ...p, running: false, accumulated: 0, startedAt: null, status: 'pending', startTime: '', endTime: '', phaseStatus: 'pendiente' })),
history: [...(machine.history || []), snapshot],
});
};
const [showHistory, setShowHistory] = cpUseState(false);
// Guarda código/nombre validando unicidad del código y avisando de la
// asociación de fallas/mantenimiento al código.
const saveMeta = () => {
const nc = editCode.trim();
const nm = editName.trim();
if (nc) {
const dup = (allMachines || []).find(m => m.id !== machine.id && (m.code || '').trim().toLowerCase() === nc.toLowerCase());
if (dup) { cpNotify(`El código "${nc}" ya lo usa otra máquina (${dup.name || dup.id}). Elige uno distinto.`, 'err'); return; }
}
const oldKey = machine.code || machine.id;
const newKey = nc || machine.id;
const hasData = ((profile && profile.fallas) || []).length > 0 || ((profile && profile.mantenimientos) || []).length > 0 || (profile && profile.status);
let migrate = false;
if (newKey !== oldKey && hasData) {
if (onRenameMachineCode) {
migrate = confirm(`Las fallas, el mantenimiento y el estado operativo están asociados al código "${oldKey}".\n\n¿Migrarlos al nuevo código "${newKey}"?\n\nAceptar = migrar · Cancelar = dejarlos con el código anterior.`);
} else if (!confirm(`Aviso: las fallas y el mantenimiento están asociados al código "${oldKey}". Si lo cambias a "${newKey}" la máquina aparecerá sin ese historial.\n\n¿Continuar?`)) {
return;
}
}
onUpdate({ ...machine, code: nc, name: nm });
if (migrate && onRenameMachineCode) onRenameMachineCode(oldKey, newKey);
setEditingMeta(false);
};
const onDragOver = (e) => { e.preventDefault(); setDragOver(true); };
const onDragLeave = () => setDragOver(false);
const onDrop = (e) => {
e.preventDefault();
setDragOver(false);
if (!canEdit) return;
let item = null;
try { item = JSON.parse(e.dataTransfer.getData('cp-item')); } catch (_) { return; }
assignItem(item);
};
const removeAssignment = (id) => {
if (!canEdit) return;
const removed = (machine.assignments || []).find(a => a.id === id);
if (removed && !confirm(`¿Quitar "${removed.nombre || id}" de esta máquina? Se revertirá su marca de proceso en la base.`)) return;
onUpdate({ ...machine, assignments: (machine.assignments || []).filter(a => a.id !== id) });
if (removed && onAssignmentRemoved) {
onAssignmentRemoved(id, removed.kind, removed.planDate || 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(); saveMeta(); }} 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)
FECHA
HR INICIAL BATCH
OPERARIO
{/* ASIGNACIÓN */}
{(machine.assignments || []).length > 0 ? (
{machine.assignments.map(a => {
const showPackaging = canEdit && !!onSetPackagingEnvasado && machine.type === 'empaquetadora' && a.kind === 'color';
const planColor = showPackaging ? findPlanColor(a.id) : null;
const envEntries = planColor ? (planColor.envasadoReal && planColor.envasadoReal.length > 0 ? planColor.envasadoReal : planColor.envasado) : null;
const envSummary = (envEntries && envEntries.length > 0)
? envEntries.map(e => `${e.cantidad} ${TIPO_ENV_LABEL[e.tipo] || e.tipo}`).join(' · ')
: null;
return (
{a.nombre}
{a.kind === 'base' ? 'B' : 'C'}
{showPackaging && (
openPackagingModal(a)}
style={{ marginLeft: 4, border: 'none', background: 'transparent', cursor: 'pointer', fontSize: 12 }}
>📦{envSummary ? ` ${envSummary}` : ''}
)}
{canEdit && removeAssignment(a.id)} className="cp-asgn-remove">× }
);
})}
) : (
Sin asignar
)}
{/* LOTE */}
canEdit && onUpdate({ ...machine, lote: e.target.value })}
placeholder="—"
/>
{/* CANTIDAD */}
0))}`}
type="number"
value={machine.cantidad || ''}
readOnly={!canEdit}
onChange={e => canEdit && onUpdate({ ...machine, cantidad: e.target.value })}
placeholder="—"
/>
{/* FECHA */}
canEdit && onUpdate({ ...machine, fecha: e.target.value })}
/>
{/* HR INICIAL BATCH */}
canEdit && onUpdate({ ...machine, hrInicialBatch: e.target.value })}
placeholder="--:--"
/>
{canEdit && (
onUpdate({ ...machine, hrInicialBatch: cpNowHHMM() })}
title="Hora actual"
>
)}
{/* OPERARIO — selección de grupo o persona del área de la máquina */}
{(() => {
const dept = cpOperatorDept(machine.type);
const opt = (operators && dept && operators[dept]) ? operators[dept] : null;
const groups = (opt && opt.groups) || [];
const people = (opt && opt.people) || [];
const cur = machine.operario || '';
const known = groups.includes(cur) || people.includes(cur);
const hasOpts = groups.length > 0 || people.length > 0;
return (
👤
{hasOpts ? (
canEdit && onUpdate({ ...machine, operario: e.target.value })}
>
Sin asignar
{groups.length > 0 && (
{groups.map(g => {g} )}
)}
{people.length > 0 && (
{people.map(p => {p} )}
)}
{cur && !known && {cur} }
) : (
canEdit && onUpdate({ ...machine, operario: e.target.value })}
placeholder={dept ? 'Sin personal cargado' : 'Nombre'}
/>
)}
);
})()}
{/* Observaciones */}
{/* Tabla de fases */}
FASE
HR INICIAL
HR FINAL
MIN. / LÍM.
STATUS
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
Fallida
>
)}
{/* 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.failed && ✖ FALLIDO }
{snap.lote && Lote: {snap.lote} }
{snap.cantidad && {snap.cantidad} GL }
{snap.operario && 👤 {snap.operario} }
{doneCount}/{totalCount} fases
{totalMinsSnap > 0 && {totalMinsSnap} min total }
{snap.failed &&
Problema: {snap.failReason || snap.notes || 'Sin observación'}
}
{/* 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
STATUS
{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 : '—'}
{cpPhaseStatusLabel(p.phaseStatus)}
))}
)}
);
})}
)}
)}
)}
{packagingCtx && (
setPackagingCtx(ctx => ctx ? { ...ctx, entries } : ctx)}
onConfirm={confirmPackaging}
onCancel={() => setPackagingCtx(null)}
colorName={packagingCtx.colorName}
/>
)}
>
);
}
// ─── Bloque "Bases fallidas" de la vista previa del reporte ─────────────────
function FailedReportBlock({ batches }) {
if (!batches.length) return null;
const gl = batches.reduce((s, b) => s + (Number(b.cantidad) || 0), 0);
return (
✖ BASES FALLIDAS
{batches.length} lote{batches.length !== 1 ? 's' : ''} · {gl} GL
{batches.map(b => (
✖
{(b.assignments || []).map(a => a.nombre).join(', ') || 'Sin asignación'}
{b.machineCode}
{b.lote && Lote: {b.lote} }
{b.cantidad && {b.cantidad} GL }
{b.operario && 👤 {b.operario} }
Problema: {b.failReason || b.notes || 'Sin observación'}
))}
);
}
// ─── generateDailyReportHtml ─────────────────
// Equivalencias de envasado → galones (única fuente en este archivo).
// TODO confirmar con producción: cu4/ku/cu7
const CP_PACK_TIPO_LABEL = { gl:'Galón', cu4:'Cuña (1/4 GL)', cu5:'Cuñete 5GL', cu7:'Cuñete 7GL', ku:'Cuñete', pl:'1L', pm:'0.5L' };
const CP_PACK_TIPO_GL = { gl:1, cu4:4, cu5:5, cu7:2, ku:0.25, pl:0.264, pm:0.132 };
function generateDailyReportHtml(batches, date, machineTypes, allPlan) {
const esc = cpEsc;
batches = batches || [];
// `date` puede ser una fecha YYYY-MM-DD o una etiqueta libre (rango filtrado).
const isIsoDate = /^\d{4}-\d{2}-\d{2}$/.test(String(date || ''));
const dateH = esc(date);
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());
// Etiquetas y factor de conversión a galones equivalentes para el desglose
// de envasado del reporte. Réplica local (con nombre propio para no chocar
// con TIPO_ENV_LABEL de components.jsx) de la convención ya usada en
// EnvasadoPills / DayHeader.TIPO_GL_EQUIV.
const PACK_TIPO_LABEL = CP_PACK_TIPO_LABEL;
const PACK_TIPO_GL = CP_PACK_TIPO_GL;
const findColorInPlan = (fecha, colorId) => {
const dayBases = (allPlan && allPlan[fecha]) || [];
for (const b of dayBases) {
const c = (b.colors || []).find(x => x.id === colorId);
if (c) return c;
}
return null;
};
const areas = { prep: [], mati: [], env: [], emp: [] };
// Los lotes fallidos no cuentan como producción: van aparte, en "BASES FALLIDAS".
const failedBatches = batches.filter(b => b.failed);
batches = batches.filter(b => !b.failed);
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);
const makeItem = (nombre, a) => ({
nombre,
lote: batch.lote || '—',
glPlan: Number((a && a.cantidad) || 0),
glReal: Number(batch.cantidad || 0),
mins: bMins,
machine: batch.machineCode || '',
fecha: batch.fecha || date,
});
if ((batch.assignments||[]).length) {
// Clasificar primero, y recién después volcar a cada área: un batch es
// UN volumen físico, así que su Vol. Real no puede sumarse una vez por
// asignación dentro de la misma área.
const enPrep = [], enMati = [], enEnv = [], enEmp = [];
batch.assignments.forEach(a => {
if (isEnv) enEnv.push(a);
else if (isEmp) enEmp.push(a);
else if (isProd && a.kind === 'color' && !isPasta && !isProdOverride(a.nombre)) enMati.push(a);
else if (isProd) enPrep.push(a);
});
// PREPARADORES: una sola fila por batch. La base y un color marcado como
// Producción (ej. FAA + FONDO ANTIALCALINO) son el MISMO producto físico;
// listarlos por separado duplicaba las filas y el total de galones.
if (enPrep.length) {
const nombre = [...new Set(enPrep.map(a => a.nombre || '—'))].join(' · ');
const ref = enPrep.find(a => a.kind === 'base') || enPrep[0];
areas.prep.push(makeItem(nombre, ref));
}
// Resto de áreas: se conserva una fila por asignación (trazabilidad),
// pero el Vol. Real del batch se atribuye una sola vez.
const volUnaVez = (arr, destino, attachEnvasado) => arr.forEach((a, i) => {
const item = makeItem(a.nombre || '—', a);
if (i > 0) item.glReal = 0;
if (attachEnvasado && a.kind === 'color') {
const fecha = batch.fecha || date;
const planColor = findColorInPlan(fecha, a.id);
const entries = planColor ? (planColor.envasadoReal && planColor.envasadoReal.length > 0 ? planColor.envasadoReal : planColor.envasado) : null;
if (entries && entries.length > 0) {
item.envasadoEntries = entries;
item.envasadoEquivGL = entries.reduce((s, e) => s + Number(e.cantidad || 0) * (PACK_TIPO_GL[e.tipo] || 0), 0);
const byBrand = {};
entries.forEach(e => {
const brand = e.marca || 'SIN MARCA';
if (!byBrand[brand]) byBrand[brand] = {};
byBrand[brand][e.tipo] = (byBrand[brand][e.tipo] || 0) + Number(e.cantidad || 0);
});
item.envasadoTexto = Object.entries(byBrand).map(([brand, totals]) => {
const parts = Object.entries(totals).filter(([, n]) => n > 0)
.map(([t, n]) => `${n} ${PACK_TIPO_LABEL[t] || t}`).join(', ');
return brand === 'SIN MARCA' ? parts : `${brand}: ${parts}`;
}).join(' · ');
}
}
destino.push(item);
});
volUnaVez(enMati, areas.mati);
volUnaVez(enEnv, areas.env);
volUnaVez(enEmp, areas.emp, true);
} 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 months = ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
let dateStr = dateH;
if (isIsoDate) {
const [y, m, d] = String(date).split('-');
const mi = parseInt(m, 10) - 1;
if (mi >= 0 && mi < 12) dateStr = `${d} de ${months[mi]} de ${y}`;
}
const now = cpVetNow(); // hora de Venezuela (reloj sincronizado)
const nowStr = `${now.getUTCDate().toString().padStart(2,'0')}/${(now.getUTCMonth()+1).toString().padStart(2,'0')}/${now.getUTCFullYear()} ${now.getUTCHours().toString().padStart(2,'0')}:${now.getUTCMinutes().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} `;
// Para EMPAQUETADO: cuando el renglón tiene desglose de envasado real
// (envasadoEntries), la columna "Vol. Real" que este mismo total usaría se
// reemplaza por el equivalente en galones del desglose (envasadoEquivGL);
// los renglones sin desglose (batches previos a esta función) siguen
// usando glReal tal como hoy.
const rowEquivGL = i => (i.envasadoEntries ? i.envasadoEquivGL : i.glReal);
const buildSection = (title, items, showTime, isPackaging) => {
if (!items.length) return '';
const totalPlan = sumGL(items, 'glPlan');
const totalReal = isPackaging ? items.reduce((s, i) => s + (rowEquivGL(i) || 0), 0) : sumGL(items, 'glReal');
const empHeadCols = isPackaging
? `${th('Empacado')}${thr('Equiv. (GAL)')}`
: `${thr('Vol. Plan. (gal)')}${thr('Vol. Real (gal)')}`;
return `
${title}
${th('Fecha')}${th('Máquina')}${th('Producto')}${th('Lote')}${empHeadCols}${showTime?thr('Tiempo (min)'):''}
${items.map((i, idx) => `
${td(esc(i.fecha),'font-family:monospace;font-size:10.5px;color:#666;')}
${td(`${esc(i.machine)} `,'')}
${td(`${esc(i.nombre)} `,'')}
${td(esc(i.lote),'font-family:monospace;font-size:10.5px;color:#555;')}
${isPackaging && i.envasadoEntries
? `${td(esc(i.envasadoTexto || '—'),'font-size:10.5px;')}${tdR(i.envasadoEquivGL > 0 ? fmtGL(i.envasadoEquivGL) : '—', true)}`
: `${tdR(i.glPlan > 0 ? fmtGL(i.glPlan) : '—')}${tdR(i.glReal > 0 ? fmtGL(i.glReal) : '—', true)}`}
${showTime ? tdR(i.mins > 0 ? i.mins : '—') : ''}
`).join('')}
Total
${isPackaging ? ' ' : tdR(totalPlan > 0 ? fmtGL(totalPlan) : '—')}
${totalReal > 0 ? fmtGL(totalReal) : '—'}
${showTime ? ` ` : ''}
`;
};
const failedSection = !failedBatches.length ? '' : `
BASES FALLIDAS — ${failedBatches.length} lote${failedBatches.length !== 1 ? 's' : ''}
${th('Fecha')}${th('Máquina')}${th('Base / Producto')}${th('Lote')}${thr('Vol. (gal)')}${th('Operario')}${th('Problema (observación)')}
${failedBatches.map(b => `
${td(esc(b.fecha || date),'font-family:monospace;font-size:10.5px;color:#666;')}
${td(`${esc(b.machineCode)} `,'')}
${td(`${esc((b.assignments||[]).map(a => a.nombre).join(' · ') || '(Sin asignación)')} `,'')}
${td(esc(b.lote || '—'),'font-family:monospace;font-size:10.5px;color:#555;')}
${tdR(Number(b.cantidad) > 0 ? fmtGL(Number(b.cantidad)) : '—', true)}
${td(esc(b.operario || '—'),'font-size:10.5px;')}
${td(esc(b.failReason || b.notes || 'Sin observación'),'font-size:10.5px;color:#c62828;')}
`).join('')}
Total perdido
${fmtGL(failedBatches.reduce((a, b) => a + (Number(b.cantidad) || 0), 0))}
`;
const prepGL = sumGL(areas.prep, 'glReal') || sumGL(areas.prep, 'glPlan');
const envGL = sumGL(areas.env, 'glReal') || sumGL(areas.env, 'glPlan');
const empGL = areas.emp.reduce((s, i) => s + (rowEquivGL(i) || 0), 0) || sumGL(areas.emp, 'glPlan');
const nColores = areas.mati.length;
const card = (num, label, dark=false) =>
``;
return `
Reporte Producción ${dateH}
REPORTE DIARIO DE PRODUCCIÓN — ${dateStr}
Dirigido al: Departamento de Producción
Generado: ${nowStr}
Fecha: ${dateH}
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)}
${failedBatches.length ? card(failedBatches.length, 'Bases Fallidas') : ''}
${buildSection('PREPARADORES — Bases de Producción', areas.prep, true)}
${buildSection('MATIZACIÓN — Colores', areas.mati, true)}
${buildSection('ENVASADO', areas.env, true)}
${buildSection('EMPAQUETADO', areas.emp, false, true)}
${failedSection}
${!areas.prep.length && !areas.mati.length && !areas.env.length && !areas.emp.length && !failedBatches.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 — ${dateH}
`;
}
// ─── 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 || '',
hrInicialBatch: batch.hrInicialBatch || '',
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.
// Igual que cpCalcTimeDiffMins: admite cruce de medianoche (fin < inicio).
const suspicious = [];
const phases = d.phases.map(p => {
let computedMins = p.computedMins != null ? p.computedMins : null;
if (p.startTime && p.endTime) {
const diff = cpCalcTimeDiffMins(p.startTime, p.endTime);
if (diff !== null) {
computedMins = diff;
const crosses = cpTimeToMins(p.endTime) < cpTimeToMins(p.startTime);
if (crosses && diff > 12 * 60) suspicious.push(`${p.name || 'Fase'}: ${p.startTime} → ${p.endTime} = ${Math.floor(diff / 60)} h ${diff % 60} min`);
}
}
return { ...p, computedMins };
});
if (suspicious.length && !confirm(`La hora final es menor que la inicial y eso da una duración de más de 12 h (cruce de medianoche):\n\n• ${suspicious.join('\n• ')}\n\n¿Es correcto?`)) return;
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, allPlan }) {
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 => cpBatchDay(b) >= filterDateFrom);
if (filterDateTo) out = out.filter(b => cpBatchDay(b) <= filterDateTo);
if (filterBase.trim()) {
out = out.filter(b =>
(b.assignments || []).some(a => a.nombre === filterBase)
);
}
const qWords = filterSearch.trim().toLowerCase().split(/\s+/).filter(Boolean);
if (qWords.length) {
out = out.filter(b => {
const assignmentText = (b.assignments || [])
.map(a => [a.nombre, a.code, a.lote, a.tipo, a.kind].filter(Boolean).join(' '))
.join(' ');
const haystack = [assignmentText, b.lote, b.codigo, b.code, b.machineName, b.machineCode, b.operario]
.filter(Boolean).join(' ').toLowerCase();
return qWords.every(w => haystack.includes(w));
});
}
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 qWords = phaseSearchQ.trim().toLowerCase().split(/\s+/).filter(Boolean);
if (qWords.length) out = out.filter(b => {
const haystack = [(b.assignments||[]).map(a => `${a.nombre||''} ${a.code||''}`).join(' '), b.lote||'']
.join(' ').toLowerCase();
return qWords.every(w => haystack.includes(w));
});
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 => cpBatchDay(b) === reportDate),
[allBatches, reportDate]);
const printDailyReport = () => {
if (!reportBatches.length) { alert('No hay batches registrados para esta fecha.'); return; }
const html = generateDailyReportHtml(reportBatches, reportDate, MACHINE_TYPES, allPlan);
const win = cpOpenReport(html, 'width=940,height=720');
if (win) setTimeout(() => { try { win.focus(); win.print(); } catch (_) {} }, 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(' · ');
// `label` es una etiqueta (rango/filtro), no una fecha: el generador la valida.
const html = generateDailyReportHtml(filtered, label, MACHINE_TYPES, allPlan);
const win = cpOpenReport(html, 'width=940,height=720');
if (win) setTimeout(() => { try { win.focus(); win.print(); } catch (_) {} }, 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: cpNowIso(),
};
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','Cierre (VET)','Lote','Cantidad GL','Operario','HR Inicial 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.phaseStatus||''})`
).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),
cpBatchDay(b) || '', dtStr, b.lote || '', b.cantidad || '', b.operario || '',
b.hrInicialBatch || '',
`${donePhases}/${(b.phases||[]).length}`,
totalPhaseMins, phasesDetail, assigns,
];
});
const csv = [headers, ...rows]
.map(r => r.map(cell => `"${(typeof cell === 'number' ? String(cell) : cpCsvSafe(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.filter(b => !b.failed).reduce((s,b) => s + Number(b.cantidad||0), 0)} GL
{reportBatches.filter(b => !b.failed && (b.phases||[]).length > 0 && (b.phases||[]).every(p => p.status === 'done')).length}/{reportBatches.filter(b => !b.failed).length} completados
{reportBatches.filter(b => !b.failed).reduce((s,b) => s+(b.phases||[]).reduce((ps,p) => ps+(p.computedMins||0),0),0)} min
{reportBatches.some(b => b.failed) && ✖ {reportBatches.filter(b => b.failed).length} fallida{reportBatches.filter(b => b.failed).length !== 1 ? 's' : ''} }
{(() => {
const byMac = {};
reportBatches.filter(b => !b.failed).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 (
{batch.failed ? '✖' : 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 }
);
})}
)),
b.failed)} />];
})()}
))
: (
filtered.length === 0 ? (
Sin registros con los filtros actuales.
) : (
Vista previa — {filtered.length} batch{filtered.length !== 1 ? 'es' : ''} filtrados
{filtered.filter(b => !b.failed).reduce((s,b) => s + Number(b.cantidad||0), 0)} GL
{filtered.filter(b => !b.failed && (b.phases||[]).length > 0 && (b.phases||[]).every(p => p.status === 'done')).length}/{filtered.filter(b => !b.failed).length} completados
{filtered.filter(b => !b.failed).reduce((s,b) => s+(b.phases||[]).reduce((ps,p) => ps+(p.computedMins||0),0),0)} min
{filtered.some(b => b.failed) && ✖ {filtered.filter(b => b.failed).length} fallida{filtered.filter(b => b.failed).length !== 1 ? 's' : ''} }
{(() => {
const byMac = {};
filtered.filter(b => !b.failed).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 (
{batch.failed ? '✖' : 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 }
);
})}
)),
b.failed)} />];
})()}
)
)}
)}
{/* — 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 });
// El batch se agrupa (filtros y Reporte Diario) por su campo FECHA.
// Si no coincide con el día en que se cerró, se avisa: si no, el
// batch "desaparece" del reporte de ese día sin explicación.
const cierreDia = batch.timestamp
? cpBatchDay({ timestamp: batch.timestamp })
: '';
const diaDistinto = !!(batch.fecha && cierreDia && batch.fecha !== cierreDia);
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.failed && ✖ FALLIDO }
{diaDistinto && (
📅 cuenta en {batch.fecha}
)}
{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.failed &&
Problema: {batch.failReason || batch.notes || 'Sin observación'}
}
{(batch.assignments||[]).length > 0 && (
ASIGNACIÓN
{batch.assignments.map(a => (
{a.nombre}
{a.kind === 'base' ? 'B' : 'C'}
))}
)}
{(batch.operario || batch.hrInicialBatch || batch.fecha) && (
{batch.operario && (
OPERARIO
👤 {batch.operario}
)}
{batch.hrInicialBatch && (
HR INICIAL BATCH
{batch.hrInicialBatch}
)}
{batch.fecha && (
)}
)}
{(batch.phases||[]).length > 0 && (
FASE
HR INICIAL
HR FINAL
MIN
STATUS
{batch.phases.map((p, i) => (
{p.name}
{p.phaseDate && p.phaseDate !== batch.fecha && (
📅 {cpFmtShortDate(p.phaseDate)}
)}
{p.startTime || '—'}
{p.endTime || '—'}
{p.computedMins != null ? p.computedMins : '—'}
{cpPhaseStatusLabel(p.phaseStatus)}
))}
{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]);
// Códigos ya usados (sin distinguir mayúsculas) y siguiente PREFIJO-NNN libre.
const usedCodes = new Set((machines || []).map(m => String(m.code || '').trim().toLowerCase()).filter(Boolean));
const suggestedCode = (() => {
const prefix = cpMachineTypePrefix(type);
for (let n = countOfType + 1; n < countOfType + 1000; n++) {
const c = `${prefix}-${String(n).padStart(3, '0')}`;
if (!usedCodes.has(c.toLowerCase())) return c;
}
return `${prefix}-${cpUid().slice(2).toUpperCase()}`;
})();
const codeDup = !!code.trim() && usedCodes.has(code.trim().toLowerCase());
const handleAdd = () => {
if (codeDup) { cpNotify(`El código "${code.trim()}" ya lo usa otra máquina. Elige uno distinto.`, 'err'); return; }
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
))}
{(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, onSetPackagingEnvasado, onCancelBase, onUpdateBase, machines, setMachines, onDeleteMachine, canEdit, tick, isAdmin, machineProfiles, onSaveMachineProfile, onAddBase, onAddColor, onShowHistorial, operators, userName, currentUser, onRenameMachineCode }) {
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 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 qWords = search.toLowerCase().split(/\s+/).filter(Boolean);
out = out.filter(m => {
const haystack = [m.name, m.code, m.operario, m.lote, (m.assignments || []).map(a => a.nombre).join(' ')]
.filter(Boolean).join(' ').toLowerCase();
return qWords.every(w => haystack.includes(w));
});
}
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}
)}
);
})()}
{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}
onBaseStarted={onBaseStarted}
onAssignmentRemoved={handleAssignmentRemoved}
onSetPackagingEnvasado={onSetPackagingEnvasado}
allPlan={allPlan}
cpDate={cpDate}
operators={operators}
allMachines={machines}
userName={userName || currentUser}
onRenameMachineCode={onRenameMachineCode}
/>
))}
{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)}
userName={userName || currentUser}
/>
)}
);
}
window.ControlProceso = ControlProceso;
window.HistorialPage = HistorialPage;
// ════════════════════════════════════════════════════════════
// MOBILE · Control de Proceso
// ────────────────────────────────────────────────────────────
// Mismo patrón que MobileDayView (mobile.jsx): reutiliza el estado y los
// handlers de escritorio (allPlan, machines, onUpdate, onBaseStarted, etc.)
// que ya recibe en app.jsx — solo cambia la presentación.
// La asignación de bases/colores en escritorio es DRAG-AND-DROP (BasesPanel
// arrastrado sobre CPProcessRow, con soporte táctil vía _cpDropReg para
// tablets). En móvil no hay drag real, así que esta vista expone la MISMA
// acción (agregar a machine.assignments + onBaseStarted) como una hoja de
// selección táctil, en vez de reinventar la asignación.
// ════════════════════════════════════════════════════════════
function MobileMachinePhaseRow({ phase, canEdit, onUpdate, onRemove }) {
const displayMins = cpPhaseDisplayMins(phase);
const start = () => {
if (!canEdit || phase.running) return;
const now = cpNowHHMM();
onUpdate({ ...phase, running: true, startedAt: cpNowMs(), status: 'running', startTime: phase.startTime || now, phaseStatus: cpPhaseStatusOnStart(phase.phaseStatus) });
};
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 diff = cpCalcTimeDiffMins(phase.startTime, endTime);
const acc = (diff !== null ? diff * 60 : null) || cpElapsed(phase);
onUpdate({ ...phase, running: false, accumulated: acc, startedAt: null, status: 'done', endTime, phaseStatus: 'finalizado' });
};
return (
{phase.name}
{phase.startTime || '--:--'} → {phase.endTime || '--:--'}
{displayMins !== null && · {displayMins}m }
{phase.status !== 'done' ? (
{!phase.running ? (
INICIAR
) : (
PAUSA
)}
FIN
) : (
✓ Hecha
)}
);
}
function MobileMachineCard({
machine, expanded, onToggle, canEdit, onUpdate, onRemove,
onOpenAssign, onRemoveAssignment, onOpenFalla, canReportFalla,
}) {
const MACHINE_TYPES = window.AppData.MACHINE_TYPES || {};
const mt = MACHINE_TYPES[machine.type] || {};
const status = cpMachineStatus(machine);
const statusCls = { idle: 'idle', running: 'running', paused: 'paused', done: 'done' }[status] || 'idle';
const statusLabel = { idle: 'INACTIVA', running: 'EN PROCESO', paused: 'PAUSADA', done: 'FINALIZADA' }[status] || 'INACTIVA';
const isEmptyVal = (v) => !String(v ?? '').trim();
const noOperario = isEmptyVal(machine.operario);
const asgn = machine.assignments || [];
return (
›
{machine.name}
{mt.name || machine.type}
{machine.code || '—'}
·
{noOperario
? Sin operario
: {machine.operario} }
{statusLabel}
{expanded && (
Asignación
{asgn.length > 0 ? (
{asgn.map(a => (
{a.kind === 'color' && }
{a.nombre}
{canEdit && (
onRemoveAssignment(a.id)}>✕
)}
))}
{canEdit && (
+ Agregar
)}
) : (
canEdit ? (
Sin asignar · toca para asignar una base o color
) : (
Sin asignar
)
)}
{(machine.phases || []).map((p, i) => (
onUpdate(cpApplyPhaseUpdate(machine, i, upd))}
/>
))}
{(machine.phases || []).length === 0 && (
Sin fases configuradas.
)}
{canReportFalla && (
⚠ Reportar falla
)}
)}
);
}
// ─── Hoja de asignación (tap-to-assign) ───────────────────────
// Equivalente táctil del drag-and-drop de BasesPanel: mismas reglas
// (no repetir asignaciones, respetar mt.accepts) y misma acción resultante.
function MobileAssignSheet({ machine, bases, onAssign, onClose, allMachines }) {
const [search, setSearch] = cpUseState('');
const MACHINE_TYPES = window.AppData.MACHINE_TYPES || {};
const mt = MACHINE_TYPES[machine.type] || {};
const accepts = mt.accepts || ['base', 'color'];
const assignedIds = new Set((machine.assignments || []).map(a => a.id));
// También oculta lo ya asignado/en fila en cualquier otra máquina.
(allMachines || []).forEach(m => {
(m.assignments || []).forEach(a => assignedIds.add(a.id));
(m.queue || []).forEach(q => (q.items || []).forEach(a => assignedIds.add(a.id)));
});
const items = [];
(bases || []).forEach(b => {
if (b.status === 'cancelled') return;
if (accepts.includes('base') && !assignedIds.has(b.id)) {
items.push({ id: b.id, kind: 'base', nombre: b.nombre, lote: b.lote, code: b.code, cantidad: b.cantidad, unit: b.unit, color: b.color, tipo: b.tipo, colorsCount: (b.colors || []).length });
}
if (accepts.includes('color')) {
(b.colors || []).forEach(c => {
if (c.cancelled || assignedIds.has(c.id)) return;
items.push({ id: c.id, kind: 'color', nombre: `${c.nombre} (${b.nombre})`, lote: c.lote || b.lote, cantidad: c.cantidad, unit: c.unit || b.unit, color: c.hex || '#ccc', parentId: b.id });
});
}
});
const qWords = search.trim().toLowerCase().split(/\s+/).filter(Boolean);
const filtered = qWords.length ? items.filter(it =>
qWords.every(w => `${it.nombre} ${it.lote || ''}`.toLowerCase().includes(w))
) : items;
return (
e.stopPropagation()}>
Asignar a {machine.name}
setSearch(e.target.value)} autoFocus />
{filtered.length === 0 &&
Nada pendiente para asignar.
}
{filtered.map(it => (
{ onAssign(it); onClose(); }}>
{it.kind === 'color' && }
{it.nombre}
{it.lote && {it.lote} }
{it.kind === 'base' ? 'Base' : 'Color'}
))}
);
}
function MobileControlView({
allPlan, initDate, onCpDateChange, machines, setMachines, onDeleteMachine,
canEdit, tick, isAdmin, machineProfiles, onReportMachineFalla, canReportMachineFalla,
onBaseStarted, onAssignmentRemoved,
}) {
const [cpDate, setCpDate] = cpUseState(initDate || todayStr());
const [expanded, setExpanded] = cpUseState(new Set());
const [filterType, setFilterType] = cpUseState('all');
const [filterStatus, setFilterStatus] = cpUseState('all');
const [search, setSearch] = cpUseState('');
const [filterSheetOpen, setFilterSheetOpen] = cpUseState(false);
const [showAddModal, setShowAddModal] = cpUseState(false);
const [assignMachine, setAssignMachine] = cpUseState(null);
const [fallaMachine, setFallaMachine] = cpUseState(null);
const bases = cpUseMemo(() => (allPlan || {})[cpDate] || [], [allPlan, cpDate]);
const MACHINE_TYPES = window.AppData.MACHINE_TYPES || {};
const onDate = (d) => {
setCpDate(d);
if (onCpDateChange) onCpDateChange(d);
};
// Mismo cálculo que cp-stats en ControlProceso (escritorio) — cpMachineStatus.
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 typeCounts = { all: machines.length };
Object.keys(MACHINE_TYPES).forEach(t => { typeCounts[t] = machines.filter(m => m.type === t).length; });
const statusOptions = [['all', 'Todos'], ['running', 'En proceso'], ['paused', 'Pausadas'], ['done', 'Finalizadas'], ['idle', 'Inactivas']];
const statusLabel = (v) => (statusOptions.find(([sv]) => sv === v) || [])[1] || v;
const filtersActive = filterType !== 'all' || filterStatus !== 'all';
const filteredMachines = cpUseMemo(() => {
let out = machines;
if (filterType !== 'all') out = out.filter(m => m.type === filterType);
if (filterStatus !== 'all') out = out.filter(m => cpMachineStatus(m) === filterStatus);
if (search.trim()) {
const qWords = search.toLowerCase().split(/\s+/).filter(Boolean);
out = out.filter(m => {
const haystack = [m.name, m.code, m.operario, m.lote, (m.assignments || []).map(a => a.nombre).join(' ')]
.filter(Boolean).join(' ').toLowerCase();
return qWords.every(w => haystack.includes(w));
});
}
return out;
}, [machines, filterType, filterStatus, search, tick]);
const toggleExpand = (id) => {
setExpanded(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]); setExpanded(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 assignToMachine = (machine, item) => {
if (!canEdit) return;
const profile = (machineProfiles && machineProfiles[machine.code || machine.id]) || {};
const next = cpPrepareAssign({ machine, item, allMachines: machines, profile, isAdmin, cpDate });
if (!next) return;
updateMachine(machine.id, next);
if (onBaseStarted) onBaseStarted(item.id, item.kind, cpDate, machine.type);
};
const removeAssignmentFromMachine = (machine, id) => {
if (!canEdit) return;
const removed = (machine.assignments || []).find(a => a.id === id);
if (removed && !confirm(`¿Quitar "${removed.nombre || id}" de esta máquina? Se revertirá su marca de proceso en la base.`)) return;
updateMachine(machine.id, { ...machine, assignments: (machine.assignments || []).filter(a => a.id !== id) });
if (removed && onAssignmentRemoved) onAssignmentRemoved(id, removed.kind, removed.planDate || machine.fecha || cpDate, machine.type);
};
const d = new Date(cpDate + 'T12:00:00');
const dayStr = d.toISOString().slice(0, 10);
return (
{stats.running}
En proceso
{canEdit && (
setShowAddModal(true)}>+ Nueva Máquina
)}
{filtersActive && (
{filterType !== 'all' && (
setFilterType('all')}>{MACHINE_TYPES[filterType]?.name || filterType} ✕
)}
{filterStatus !== 'all' && (
setFilterStatus('all')}>{statusLabel(filterStatus)} ✕
)}
)}
{filterSheetOpen && (
setFilterSheetOpen(false)}>
e.stopPropagation()}>
Filtros
Tipo de máquina
setFilterType('all')}>Todas {typeCounts.all}
{Object.keys(MACHINE_TYPES).filter(t => typeCounts[t] > 0).map(t => (
setFilterType(t)}>{MACHINE_TYPES[t].name} {typeCounts[t]}
))}
Estado
{statusOptions.map(([v, l]) => (
setFilterStatus(v)}>{l}
))}
setFilterSheetOpen(false)}>Aplicar
)}
{filteredMachines.length === 0 && (
Sin máquinas para este filtro.
)}
{filteredMachines.map(m => (
toggleExpand(m.id)}
canEdit={canEdit}
onUpdate={upd => updateMachine(m.id, upd)}
onOpenAssign={() => setAssignMachine(m)}
onRemoveAssignment={id => removeAssignmentFromMachine(m, id)}
onOpenFalla={() => setFallaMachine(m)}
canReportFalla={canReportMachineFalla}
/>
))}
{showAddModal && canEdit && (
setShowAddModal(false)} machines={machines} />
)}
{assignMachine && (
assignToMachine(assignMachine, item)}
onClose={() => setAssignMachine(null)}
/>
)}
{fallaMachine && (
onReportMachineFalla && onReportMachineFalla(fallaMachine.code || fallaMachine.id, descripcion, gravedad)}
onClose={() => setFallaMachine(null)}
/>
)}
);
}
window.MobileControlView = MobileControlView;
// ════════════════════════════════════════════
// 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) {
// Con varias fases en curso (datos antiguos) se muestra la de mayor tiempo.
return (machine.phases || []).filter(p => p.running).reduce((mx, p) => Math.max(mx, cpElapsed(p)), 0);
}
function svIsDelayed(machine) {
// Retrasada si CUALQUIER fase en curso superó su límite.
return (machine.phases || []).filter(p => p.running).some(phase => {
const limitSecs = phase.limitMins ? Number(phase.limitMins) * 60 : SV_ALERT_MINS * 60;
return cpElapsed(phase) > 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;
let _svAudioBlocked = false;
function svGetAudioCtx() {
if (!_svAudioCtx) _svAudioCtx = new (window.AudioContext || window.webkitAudioContext)();
return _svAudioCtx;
}
// Avisa a la vista si el navegador bloqueó el audio (sin gesto del usuario).
function svSetAudioBlocked(v) {
if (_svAudioBlocked === v) return;
_svAudioBlocked = v;
try { window.dispatchEvent(new CustomEvent('sv-audio-state')); } catch (_) {}
}
// Intenta activar el audio tras un gesto del usuario.
function svUnlockAudio() {
try {
const ctx = svGetAudioCtx();
const p = ctx.resume && ctx.resume();
Promise.resolve(p).then(() => svSetAudioBlocked(ctx.state !== 'running')).catch(() => svSetAudioBlocked(true));
} catch (_) { svSetAudioBlocked(true); }
}
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') {
Promise.resolve(ctx.resume()).then(() => {
if (ctx.state === 'running') { svSetAudioBlocked(false); doPlay(); } else svSetAudioBlocked(true);
}).catch(() => svSetAudioBlocked(true));
// Algunos navegadores nunca resuelven resume() sin gesto: se comprueba igual.
setTimeout(() => { if (ctx.state !== 'running') svSetAudioBlocked(true); }, 500);
} else { svSetAudioBlocked(false); doPlay(); }
} catch (_) { svSetAudioBlocked(true); }
}
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 esc = cpEsc;
profile = profile || {};
const now = new Date(cpNowMs()); // epoch real; toLocaleString aplica la zona de Caracas
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) => String(b.fecha || '').localeCompare(String(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]) =>
`${esc(l)}
${esc(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 `
${esc((f.gravedad||'').toUpperCase())}
Reportada: ${esc(f.fechaReporte || '—')}
${f.resuelta ? `✓ Resuelta: ${esc(f.fechaResolucion || '—')} ` : ''}
${f.reparadoPor ? `Reparó: ${esc(f.reparadoPor)} ` : ''}
${f.numeroReporte ? `Reporte #${esc(f.numeroReporte)} ` : ''}
${esc(f.descripcion || '')}
${f.solucion ? `
Solución: ${esc(f.solucion)}
` : ''}
`;
};
const mantCard = (m) =>
`
${esc(m.fecha || '—')}
${m.realizadoPor ? `por ${esc(m.realizadoPor)} ` : ''}
${m.numeroReporte ? `Reporte #${esc(m.numeroReporte)} ` : ''}
${esc(m.descripcion || '')}
`;
const section = (title, content, color='#1a1a1a') =>
``;
const obsHtml = profile.observacion
? `
Observación
${esc(profile.observacion)}
`
: '';
return `
Ficha de Máquina — ${esc(machine.code || machine.id)}
🖨 Imprimir
✕ Ocultar información
${resolvedFallas.length > 0 ? `🔧 Incluir reparaciones ` : ''}
${mantenimientos.length > 0 ? `📋 Incluir mantenimiento ` : ''}
FICHA DE MÁQUINA — ${esc(String(machine.code || machine.id).toUpperCase())}
${esc(machine.name || '')}
Generado: ${esc(nowStr)}
Estado: ${esc((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 — ${esc(nowStr)}
`;
}
// ─── MachineDetailModal ───────────────────────
function MachineDetailModal({ machine, profile, onSave, onClose, isAdmin, userName, currentUser }) {
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) => String(b.fecha || '').localeCompare(String(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: cpCurrentUserName(userName || currentUser),
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);
cpOpenReport(html);
}}
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;
// Con varias fases en curso se muestra la de mayor tiempo transcurrido.
const currentPhase = (machine.phases || []).filter(p => p.running).sort((a, b) => cpElapsed(b) - cpElapsed(a))[0];
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) || (m.queue || []).some(q => (q.items || []).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 esc = cpEsc;
machineProfiles = machineProfiles || {};
const now = new Date(cpNowMs()); // epoch real (toLocaleString ya aplica America/Caracas)
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 `
${esc(m.code || m.id)}
${esc(m.name || '—')}
${esc(m.type || '—')}
${esc(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 `
${esc(m.code || m.id)} — ${esc(m.name || '')}
${esc(status.toUpperCase())}
${infoRows.length ? `
${infoRows.map(([l,v]) => `${esc(l)} ${esc(v)} `).join('')}
` : ''}
${fallas.length
? fallas.map(f => `
${esc(f.gravedad || '')} · ${esc(f.fechaReporte || '')} — ${esc(f.descripcion || '')}
`).join('')
: `
✓ Sin fallas activas
`}
`;
};
return `
Informe general de máquinas
🖨 Imprimir
INFORME GENERAL DE MÁQUINAS (${selected.length})
Generado: ${esc(nowStr)}
Código
Nombre
Tipo
Estado
Fallas activas
${summaryRows}
${selected.map(machineSection).join('')}
Sistema de Planificación — VERONA COLOR PAINTS — ${esc(nowStr)}
`;
}
function cpGenerateGeneralReportTxt(selected, machineProfiles) {
const esc = cpEsc;
machineProfiles = machineProfiles || {};
const now = new Date(cpNowMs()); // epoch real (toLocaleString ya aplica America/Caracas)
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 words = q.trim().toLowerCase().split(/\s+/).filter(Boolean);
const haystack = `${m.code || m.id || ''} ${m.name || ''}`.toLowerCase();
if (!words.every(w => haystack.includes(w))) 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);
cpOpenReport(html);
};
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, userName, currentUser }) {
const [typeFilter, setTypeFilter] = svUseState('all');
const [detailMachine, setDetailMachine] = svUseState(null);
const [showGeneralReport, setShowGeneralReport] = svUseState(false);
const [mutedAlarms, setMutedAlarms] = svUseState(new Set());
const [reportDate, setReportDate] = svUseState(currentDate);
const [expandedDept, setExpandedDept] = svUseState(null);
const [svSection, setSvSection] = svUseState('produccion'); // 'produccion' | 'maquinas'
const alertedRef = svUseRef(new Set());
const lastBeepRef = svUseRef({});
const [audioBlocked, setAudioBlocked] = svUseState(_svAudioBlocked);
svUseEffect(() => {
const onState = () => setAudioBlocked(_svAudioBlocked);
window.addEventListener('sv-audio-state', onState);
// El primer clic/toque en la página desbloquea el audio automáticamente.
const unlock = () => svUnlockAudio();
document.addEventListener('pointerdown', unlock, { once: true });
return () => {
window.removeEventListener('sv-audio-state', onState);
document.removeEventListener('pointerdown', unlock);
};
}, []);
const bases = allPlan[currentDate] || [];
const MACHINE_TYPES = window.AppData.MACHINE_TYPES || {};
/* ── Producción por departamento (historial real de máquinas) ──
Misma clasificación que el "Reporte diario de producción" (Historial):
un batch hecho en un Dispersor/Molino/Mezclador cuenta como "Matización"
si su asignación es un color sin marcar como PRODUCCION_OVERRIDES —
así ambas vistas coinciden en qué es "base" y qué es "color matizado"
en la misma máquina, en vez de agrupar solo por tipo de máquina. */
const dayBatches = svUseMemo(() => {
const PROD_AREA_TYPES = new Set(['dispersor', 'dispersor1', 'dispersorp', 'molino', 'mezclador']);
const prodOverrides = new Set(
((window.AppData && window.AppData.PRODUCCION_OVERRIDES) || [])
.map(s => String(s || '').trim().toUpperCase())
.filter(Boolean)
);
const classifyProdArea = (b) => {
const mType = b.machineType || '';
if (!PROD_AREA_TYPES.has(mType)) return mType || 'otro';
const isPasta = mType === 'dispersorp';
// Se revisa CADA asignación: si alguna es un color sin marcar como
// producción, el batch cuenta como matización (no solo assignments[0]).
const isColorNoOverride = !isPasta && (b.assignments || []).some(a =>
a && a.kind === 'color' && !prodOverrides.has(String(a.nombre || '').trim().toUpperCase()));
return isColorNoOverride ? 'matizacion' : mType;
};
return machines
.flatMap(m => (m.history || []).map(snap => ({
...snap,
machineName: m.name,
machineType: m.type,
})))
.filter(b => !b.failed && cpBatchDay(b) === reportDate) // los lotes fallidos no son producción
.map(b => ({ ...b, prodArea: classifyProdArea(b) }))
.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
}, [machines, reportDate]);
const deptProduction = svUseMemo(() => {
const byType = {};
dayBatches.forEach(b => {
const key = b.prodArea || 'otro';
const label = key === 'matizacion' ? window.t('Matización') : (MACHINE_TYPES[key]?.name || key);
if (!byType[key]) byType[key] = { type: key, label, batches: 0, totalGL: 0 };
byType[key].batches += 1;
byType[key].totalGL += Number(b.cantidad || 0);
});
return Object.values(byType).sort((a, b) => b.totalGL - a.totalGL);
}, [dayBatches]);
const dayTotalGL = deptProduction.reduce((s, d) => s + d.totalGL, 0);
const isReportToday = reportDate === currentDate;
const deriveBaseStatus = (b) => {
if (b.status === 'cancelled') return 'cancelled';
const _ac = (b.colors || []).filter(c => !c.cancelled);
if (b.status === 'done' || b.checkFN || (_ac.length > 0 && _ac.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')}
{/* ── Indicador persistente: alarma activa pero el audio está bloqueado ── */}
{delayedCount > 0 && audioBlocked && (
🔕 ALARMA ACTIVA — {delayedCount} máquina(s) con fase excedida. El navegador bloqueó el sonido: haz clic aquí para activarlo.
)}
{/* ── 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')}
{/* ── PESTAÑAS DE SECCIÓN ── */}
setSvSection('produccion')}
>
{window.t('Producción del día')}
setSvSection('maquinas')}
>
{window.t('Máquinas')}
{activeMachines.length + pendingBases.length}
{/* ── PRODUCCIÓN DIARIA POR DEPARTAMENTO ── */}
{svSection === 'produccion' && (
{deptProduction.length === 0 ? (
{window.t('Sin producción registrada para esta fecha.')}
) : (
<>
{deptProduction.map(d => {
const pct = dayTotalGL > 0 ? Math.round((d.totalGL / dayTotalGL) * 100) : 0;
const isOpen = expandedDept === d.type;
return (
setExpandedDept(isOpen ? null : d.type)}
role="button" tabIndex={0}
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setExpandedDept(isOpen ? null : d.type); } }}
title={window.t('Ver detalle de este departamento')}
>
{d.label}
{d.batches} {window.t('lotes')}
{d.totalGL % 1 === 0 ? d.totalGL : d.totalGL.toFixed(1)} GL
{pct}% {window.t('del total del día')}
);
})}
{/* Detalle del departamento expandido — en un bloque aparte a
todo lo ancho, para no desbalancear las columnas del grid
de tarjetas de arriba. */}
{expandedDept && (() => {
const dept = deptProduction.find(d => d.type === expandedDept);
const deptBatches = dayBatches.filter(b => (b.prodArea || 'otro') === expandedDept);
return (
{dept ? dept.label : expandedDept}
setExpandedDept(null)}>{window.t('Cerrar')} ✕
{deptBatches.map((b, i) => (
{cpFmtVetHHMM(b.timestamp)}
{b.machineName}
{(b.assignments || []).map(a => a.nombre).filter(Boolean).join(', ') || b.lote || '—'}
{b.cantidad ?? '—'} GL
{b.operario || '—'}
))}
{!deptBatches.length &&
{window.t('Sin registros.')}
}
);
})()}
{window.t('Hora')}
{window.t('Departamento')}
{window.t('Máquina')}
{window.t('Producto / Lote')}
{window.t('GL')}
{window.t('Operario')}
{dayBatches.map((b, i) => (
{cpFmtVetHHMM(b.timestamp)}
{b.prodArea === 'matizacion' ? window.t('Matización') : (MACHINE_TYPES[b.machineType]?.name || b.machineType || '—')}
{b.machineName}
{(b.assignments || []).map(a => a.nombre).filter(Boolean).join(', ') || b.lote || '—'}
{b.cantidad ?? '—'}
{b.operario || '—'}
))}
>
)}
)}
{/* ── LAYOUT: MÁQUINAS | BASES PENDIENTES ── */}
{svSection === 'maquinas' && (
{/* 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}
userName={userName || currentUser}
/>
)}
);
}
// ══════════════════════════════════════════
// 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); }
function EquiposView({ equipos, isAdmin, canManage, userName, onChange, machines, machineProfiles, canReportMachineFalla, onReportMachineFalla }) {
// Admin y Mantenimiento registran/editan equipos y resuelven fallas.
const canEdit = canManage != null ? !!canManage : !!isAdmin;
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 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 (q.trim()) {
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean);
const haystack = `${e.code || ''} ${e.name || ''}`.toLowerCase();
if (!words.every(w => haystack.includes(w))) return false;
}
return true;
}), [list, q, catFilter, statFilter, areaFilter]);
const filteredMachines = svUseMemo(() => (machines || []).filter(m => {
if (areaFilter && cpMachineArea(m.type) !== areaFilter) return false;
if (q.trim()) {
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean);
const haystack = `${m.code || m.id || ''} ${m.name || ''}`.toLowerCase();
if (!words.every(w => haystack.includes(w))) 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(),
proximoMantenimiento: '', notas: '', fallas: [],
};
onChange([...list, e]);
setNCode(''); setNName(''); setNUbic(''); setNResp(''); setNCat(EQUIPO_CATEGORIES[0].id); setNArea(EQUIPO_AREAS[0].id);
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...')}
{canEdit &&
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} }
{window.t(st.label)}
{activeFallas.length > 0 &&
⚠ {activeFallas.length} }
setDetail(e)}>{window.t('Ver detalles')}
{canEdit &&
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={canEdit}
userName={userName}
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, userName, 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 [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(userName || '');
const [resFecha, setResFecha] = svUseState(cpCaracasDateStr());
const saveInfo = () => {
onSave({ area: eArea, ubicacion: eUbic.trim(), responsable: eResp.trim(), proximoMantenimiento: eMant, notas: eNotas.trim() });
setEditInfo(false);
};
const reportarFalla = () => {
if (!rDesc.trim()) return;
const f = {
id: eqNewId(), descripcion: rDesc.trim(), gravedad: rGrav,
fechaReporte: cpCaracasDateStr(), reportadoPor: cpCurrentUserName(userName),
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')}
)}
{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.EquipoDetailModal = EquipoDetailModal;
window.EQUIPO_META = { CATEGORIES: EQUIPO_CATEGORIES, AREAS: EQUIPO_AREAS, STATUS: EQUIPO_STATUS,
categoryLabel: eqCategoryLabel, areaLabel: eqAreaLabel, machineArea: cpMachineArea, newId: eqNewId };
window.SupervisorView = SupervisorView;