// ════════════════════════════════════════════════════════════
// Tablero de Producción — pantalla nueva de Control de Proceso (copia de prueba)
// ────────────────────────────────────────────────────────────
// Reemplaza la pantalla "Control de Proceso" por un tablero pensado para tablet:
// · MÁQUINAS: lote en curso, fases con un toque, FILA de lotes en espera.
// · HISTORIAL DEL DÍA: línea de tiempo de cuándo estuvo ocupada cada máquina.
// Usa EXACTAMENTE el mismo modelo de datos que la pantalla clásica
// (machine.assignments / phases / history / operario …) y solo agrega
// `machine.queue` = [{ qid, operario, items:[asignaciones], addedAt }].
// El historial se arma con los snapshots que ya guarda "desocupar", así que
// nada cambia en la base de datos salvo el campo `queue`.
// La pantalla clásica sigue disponible con "Vista clásica".
// Depende de funciones globales de control-proceso.jsx (cp*) y components.jsx.
// ════════════════════════════════════════════════════════════
(function () {
const { useState, useMemo, useEffect, useRef } = React;
const HEX = /^#[0-9a-f]{3,8}$/i;
const swatch = c => (c && HEX.test(c)) ? c : '#c9d3df';
const MODE_KEY = 'sp_cp_ui_mode';
const PRACTICE_KEY = 'sp_tablero_practica';
const SHIFT0 = 6 * 60, SHIFT1 = 22 * 60; // jornada para el % de ocupación
const fmt = m => {
const x = ((Math.round(m) % 1440) + 1440) % 1440;
return String(Math.floor(x / 60)).padStart(2, '0') + ':' + String(x % 60).padStart(2, '0');
};
const dur = m => {
m = Math.max(0, Math.round(m));
const h = Math.floor(m / 60);
return h ? `${h} ${window.t('h')} ${String(m % 60).padStart(2, '0')} ${window.t('min')}` : `${m} ${window.t('min')}`;
};
const nowMin = () => { const d = cpVetNow(); return d.getUTCHours() * 60 + d.getUTCMinutes(); };
const acceptsOf = type => ((window.AppData.MACHINE_TYPES || {})[type] || {}).accepts || ['base', 'color'];
const isEmpty = v => !String(v ?? '').trim();
const qItems = q => q.items || [];
const itemsName = items => [...new Set(items.map(a => a.nombre))].join(' + ');
const itemsGL = items => {
const b = items.find(a => a.kind === 'base');
return b ? (Number(b.cantidad) || 0) : items.reduce((s, a) => s + (Number(a.cantidad) || 0), 0);
};
// i18n: tf = clave con marcadores {x} → texto; tfx = igual pero admite elementos JSX como valores
const tf = (k, v) => { let o = window.t(k); Object.keys(v || {}).forEach(x => { o = o.split('{' + x + '}').join(v[x]); }); return o; };
const tfx = (k, v) => window.t(k).split(/\{(\w+)\}/).map((x, i) => i % 2 ? React.createElement(React.Fragment, { key: i }, v[x]) : x);
const loc = () => window.SP_LANG === 'ar' ? 'ar' : 'es';
const useLang = () => { // re-render al cambiar de idioma
const [, setL] = useState(window.SP_LANG);
useEffect(() => { const h = () => setL(window.SP_LANG); window.addEventListener('sp_lang_change', h); return () => window.removeEventListener('sp_lang_change', h); }, []);
};
const practiceOn = () => (typeof window.spPracticeOn === 'function') ? window.spPracticeOn() : false;
// ── Estimaciones ────────────────────────────────────────────
function avgPhaseMins(machines) {
const sum = {}, cnt = {};
(machines || []).forEach(m => (m.history || []).filter(h => !h.failed).forEach(h => (h.phases || []).forEach(p => {
const v = Number(p.computedMins);
if (v > 0 && v < 600) { sum[p.name] = (sum[p.name] || 0) + v; cnt[p.name] = (cnt[p.name] || 0) + 1; }
})));
const out = {};
Object.keys(sum).forEach(k => { out[k] = Math.round(sum[k] / cnt[k]); });
return out;
}
const phaseEst = (p, avg) => avg[p.name] > 0 ? avg[p.name] : (Number(p.limitMins) > 0 ? Number(p.limitMins) : null);
function estMins(machine, avg) {
let total = 0, known = 0;
const ph = machine.phases || [];
ph.forEach(p => { const e = phaseEst(p, avg); if (e) { total += e; known++; } });
return { mins: total > 0 ? total : 60, exact: ph.length > 0 && known === ph.length };
}
const curIndex = m => (m.phases || []).findIndex(p => p.status !== 'done');
// Horas estimadas de la fila de una máquina
function schedule(machine, avg, now) {
const est = estMins(machine, avg);
const hasBatch = (machine.assignments || []).length > 0;
let t = now;
if (hasBatch && cpMachineStatus(machine) !== 'done') {
const elapsed = Math.floor(cpMachineTotalSeconds(machine) / 60);
t = now + Math.max(0, est.mins - elapsed);
}
const blocks = (machine.queue || []).map(q => { const s = t; t += est.mins; return { q, s, e: t }; });
return { est, hasBatch, finish: t, blocks };
}
// ── Operaciones sobre la fila ───────────────────────────────
function takeNext(machine) {
const q = machine.queue || [];
if (!q.length) return null;
const [entry, ...rest] = q;
return {
entry,
machine: {
...machine, queue: rest, assignments: qItems(entry),
operario: entry.operario || '', cantidad: '', lote: '', hrInicialBatch: '', notes: '',
fecha: cpCaracasDateStr(),
},
};
}
// ── Operaciones sobre fases (mismas reglas que la pantalla clásica) ──
const syncAcc = (p, s, e) => { const d = cpCalcTimeDiffMins(s, e); return d !== null ? d * 60 : p.accumulated; };
const resetFields = p => ({ ...p, running: false, accumulated: 0, startedAt: null, status: 'pending', startTime: '', endTime: '', phaseStatus: 'pendiente' });
const newPhase = name => ({ id: cpUid(), name: name || 'Nueva fase', status: 'pending', running: false, startedAt: null, accumulated: 0, startTime: '', endTime: '', phaseStatus: 'pendiente' });
const mapPhase = (m, idx, fn) => ({ ...m, phases: m.phases.map((p, i) => i === idx ? fn(p) : p) });
function startPhase(m, idx) {
// Solo una fase en marcha por máquina: las demás que corrían se pausan (sin perder su tiempo).
const upd = {
...m,
phases: m.phases.map((p, i) => i === idx
? { ...p, running: true, startedAt: cpNowMs(), status: 'running', startTime: p.startTime || cpNowHHMM(), phaseStatus: cpPhaseStatusOnStart(p.phaseStatus) }
: (p.running ? { ...p, running: false, accumulated: cpElapsed(p), startedAt: null, status: 'paused' } : p)),
};
if (isEmpty(upd.hrInicialBatch)) upd.hrInicialBatch = cpNowHHMM();
if (isEmpty(upd.fecha)) upd.fecha = cpCaracasDateStr();
return upd;
}
const pausePhase = (m, idx) => mapPhase(m, idx, p => ({ ...p, running: false, accumulated: cpElapsed(p), startedAt: null, status: 'paused' }));
const doneFields = p => {
const endTime = p.endTime || cpNowHHMM();
const diff = cpCalcTimeDiffMins(p.startTime, endTime);
const acc = (diff !== null ? diff * 60 : p.accumulated) || cpElapsed(p);
return { ...p, running: false, accumulated: acc, startedAt: null, status: 'done', endTime, phaseStatus: 'finalizado' };
};
const finishPhase = (m, idx) => mapPhase(m, idx, doneFields);
function nextPhase(m, idx) { // "Fase lista": cierra la actual y arranca la siguiente
let upd = finishPhase(m, idx);
if (idx + 1 < upd.phases.length) upd = startPhase(upd, idx + 1);
return upd;
}
const batchMissing = m => {
const f = [];
if (!(m.assignments || []).length) f.push(window.t('Asignación (base o color)'));
if (isEmpty(m.lote)) f.push(window.t('Lote'));
if (isEmpty(m.cantidad) || !(Number(m.cantidad) > 0)) f.push(window.t('Cantidad (GL)'));
if (isEmpty(m.fecha)) f.push(window.t('Fecha'));
if (isEmpty(m.hrInicialBatch)) f.push(window.t('Hr inicial batch'));
if (isEmpty(m.operario)) f.push(window.t('Operario'));
if (isEmpty(m.notes)) f.push(window.t('Observaciones'));
return f;
};
// Cierra el lote: termina fases pendientes, guarda el snapshot en el historial
// (igual que "desocupar") y deja cargado el siguiente de la fila.
// Con `failReason` el lote se guarda como FALLIDO: queda en el historial (en rojo) con el problema
// como observación, no cierra la base del plan y no suma puntos.
function closeBatch(machine, failReason) {
const failed = !!failReason;
// fallido: las fases no se dan por terminadas; solo se detiene la que corría y se le pone la hora final
const stopFields = p => (p.startTime && !p.endTime)
? { ...p, running: false, accumulated: cpElapsed(p), startedAt: null, endTime: cpNowHHMM(), status: p.status === 'done' ? 'done' : 'paused' }
: { ...p, running: false, accumulated: cpElapsed(p), startedAt: null };
const phases = machine.phases.map(p => failed ? stopFields(p) : (p.status === 'done' ? p : doneFields(p)));
const snapshot = {
id: cpUid(),
timestamp: cpNowIso(), // reloj sincronizado (no el del PC)
fecha: machine.fecha || cpCaracasDateStr(),
assignments: machine.assignments || [],
lote: machine.lote || '',
cantidad: machine.cantidad || '',
operario: machine.operario || '',
hrInicialBatch: machine.hrInicialBatch || '',
notes: failed ? failReason : (machine.notes || ''),
...(failed ? { failed: true, failReason } : {}),
phases: phases.map(p => ({
name: p.name, status: p.status, phaseStatus: p.phaseStatus || 'pendiente',
startTime: p.startTime || '', endTime: p.endTime || '',
elapsedSecs: cpElapsed(p), computedMins: cpPhaseDisplayMins(p), phaseDate: p.phaseDate || null,
})),
};
const resetPhases = machine.phases.map(p => ({
...p, running: false, accumulated: 0, startedAt: null, status: 'pending',
startTime: '', endTime: '', phaseStatus: 'pendiente',
}));
const cleared = {
...machine, assignments: [], lote: '', cantidad: '', operario: '', hrInicialBatch: '', notes: '',
fecha: cpCaracasDateStr(), phases: resetPhases, history: [...(machine.history || []), snapshot],
};
const nx = takeNext(cleared);
return { next: nx ? nx.machine : cleared, loaded: nx ? nx.entry : null, closed: { ...machine, phases } };
}
// ── Historial: cuándo ocupó la máquina un lote (puede cruzar la medianoche) ───
// Las horas de las fases son solo HH:MM. Recorremos las fases en orden; cada vez que el reloj
// "retrocede" pasó la medianoche. Así un lote que empezó ayer 20:40 y terminó hoy 10:10 queda
// entre dos días y se reparte por día en vez de estirarse hacia mañana.
const daysBetween = (a, b) => Math.round((Date.parse(b + 'T12:00:00Z') - Date.parse(a + 'T12:00:00Z')) / 86400000);
const relDay = d => {
const t = cpCaracasDateStr();
if (d === t) return window.t('hoy');
if (d === shiftDate(t, -1)) return window.t('ayer');
return new Date(d + 'T12:00:00').toLocaleDateString(loc(), { day: 'numeric', month: 'short' });
};
function vetParts(ts) { // timestamp ISO (UTC) → día y minuto en hora de Venezuela
const d = new Date(Date.parse(ts) - 4 * 3600 * 1000);
return { day: d.getUTCFullYear() + '-' + String(d.getUTCMonth() + 1).padStart(2, '0') + '-' + String(d.getUTCDate()).padStart(2, '0'), min: d.getUTCHours() * 60 + d.getUTCMinutes() };
}
const unionLen = ivs => { // minutos cubiertos sin contar dos veces un tramo traslapado
const a = ivs.filter(x => x[1] > x[0]).sort((x, y) => x[0] - y[0]);
let tot = 0, end = -1;
a.forEach(([x, y]) => { if (y > end) { tot += y - Math.max(x, end); end = y; } });
return tot;
};
function batchTimeline(b, liveNow) {
const ph = b.phases || [];
let off = 0, prev = null;
// Un retroceso grande del reloj (≥ 6 h) = pasó la medianoche. Uno pequeño es un traslape o un
// dato fuera de orden: se deja en la hora anterior para no inventar un día de más.
const abs = t => {
const m = cpTimeToMins(t);
if (m == null) return null;
let a = m + off * 1440;
if (prev != null && a < prev) {
if (prev - a >= 360) { off++; a += 1440; } else a = prev;
}
prev = a;
return a;
};
const segs = [];
ph.forEach((p, idx) => {
if (!p.startTime && !p.endTime) return;
const s = p.startTime ? abs(p.startTime) : null;
const e = p.endTime ? abs(p.endTime) : null;
if (s == null && e == null) return;
segs.push({ idx, s: s != null ? s : e, e: e != null ? e : s, open: e == null });
});
let S, E;
if (segs.length) { S = segs[0].s; E = segs[segs.length - 1].e; }
else {
const hr = cpTimeToMins(b.hrInicialBatch);
if (hr == null) return null;
S = hr; prev = hr; E = hr + ph.reduce((a, p) => a + (Number(p.computedMins) || 0), 0);
}
if (liveNow != null) { // lote en curso: termina "ahora"
let n = liveNow + off * 1440;
if (n < prev) n = (prev - n >= 360) ? n + 1440 : prev;
E = Math.max(E, n);
}
if (E < S) E = S;
if (E - S > 5 * 1440) return null; // dato incoherente: no se dibuja
// Tiempo sin fase en marcha con la máquina cargada: entre una fase y la siguiente (≥ 10 min) y,
// en un lote en curso, desde que terminó la última fase hasta ahora.
const pauses = [];
for (let i = 0; i + 1 < segs.length; i++) if (segs[i + 1].s - segs[i].e >= 10) pauses.push([segs[i].e, segs[i + 1].s]);
const lastSeg = segs[segs.length - 1];
if (liveNow != null && lastSeg) {
if (lastSeg.open) lastSeg.e = Math.max(lastSeg.e, E); // fase aún en marcha: cubre hasta ahora
else if (E - lastSeg.e >= 10) pauses.push([lastSeg.e, E]);
}
return { S, E, segs, pauses, spanDays: Math.floor(E / 1440) };
}
// ── Piezas de UI ────────────────────────────────────────────
function OperarioSelect({ machine, value, onChange, operators, disabled, className }) {
const dept = cpOperatorDept(machine.type);
const o = (operators && dept && operators[dept]) || null;
const groups = (o && o.groups) || [], people = (o && o.people) || [];
const known = groups.includes(value) || people.includes(value);
if (!groups.length && !people.length) {
return onChange(e.target.value)} />;
}
return (
onChange(e.target.value)}>
{window.t('Sin operario')}
{groups.length > 0 && {groups.map(g => {g} )} }
{people.length > 0 && {people.map(p => {p} )} }
{value && !known && {value} }
);
}
function Sheet({ title, sub, onClose, children }) {
return (
{ if (e.target === e.currentTarget) onClose(); }}>
);
}
// Datos del lote (los mismos campos obligatorios del sistema)
function DatosSheet({ machine, operators, canEdit, onChange, onClose, onFinalize, finalizing }) {
const miss = batchMissing(machine);
const set = patch => onChange({ ...machine, ...patch });
return (
{window.t('Lote')} set({ lote: e.target.value })} placeholder={tf('Ej. {n}', { n: '300920261291' })} />
{window.t('Cantidad (GL)')} set({ cantidad: e.target.value })} />
{window.t('Fecha')} set({ fecha: e.target.value })} />
{window.t('Hr inicial batch')}
set({ hrInicialBatch: e.target.value })} />
{canEdit && set({ hrInicialBatch: cpNowHHMM() })}>{window.t('Ahora')} }
{window.t('Operario')} set({ operario: v })} />
{window.t('Observaciones')}
{miss.length > 0 && {tf('Falta completar: {list}.', { list: miss.join(window.SP_LANG === 'ar' ? '، ' : ', ') })}
}
{onFinalize && (
0 || finalizing} onClick={onFinalize}>{window.t('Finalizar lote y guardar en historial')}
)}
{!onFinalize && {window.t('Listo')} }
);
}
// Lote fallido: el problema se guarda como observación del lote en el historial
function FailSheet({ machine, onClose, onConfirm }) {
const [txt, setTxt] = useState('');
const ok = txt.trim().length > 0;
return (
{window.t('Observación: ¿cuál fue el problema?')}
{window.t('El lote se guarda en el historial marcado en rojo con esta observación y la máquina queda libre (o carga el siguiente de la fila). La base no se da por producida.')}
{window.t('Cancelar')}
onConfirm(txt.trim())}>{window.t('Guardar como fallida')}
);
}
// Bases y colores libres de un día del plan (los que ya están en una máquina o fila no salen)
function buildGroups(plan, day, machines) {
const taken = new Set();
machines.forEach(m => {
(m.assignments || []).forEach(a => taken.add(a.id));
(m.queue || []).forEach(q => qItems(q).forEach(a => taken.add(a.id)));
});
return ((plan || {})[day] || [])
.filter(b => b.status !== 'cancelled' && b.status !== 'done')
.map(b => ({
title: b.nombre,
code: b.code,
cantidad: b.cantidad,
tipo: b.tipo,
base: taken.has(b.id) ? null : { 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, planDate: day },
colors: (b.colors || []).filter(c => !c.cancelled && !(c.checkEM || c.status === 'ready') && !taken.has(c.id))
.map(c => ({ id: c.id, kind: 'color', nombre: c.nombre, cantidad: c.cantidad, unit: c.unit || b.unit, color: c.hex || '#ccc', parentId: b.id, planDate: day, lote: c.lote })),
}))
.filter(g => g.base || g.colors.length);
}
const dayLabel = d => new Date(d + 'T12:00:00').toLocaleDateString(loc(), { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' });
// Selector de bases/colores para la fila, con cambio de día
function PickSheet({ machine, machines, plan, startDay, today, onLoadDay, onAdd, onClose }) {
const [sel, setSel] = useState([]);
const [day, setDay] = useState(startDay);
const [range, setRange] = useState(false); // últimos 7 días
const [q, setQ] = useState('');
const acc = acceptsOf(machine.type);
const words = q.trim().toLowerCase().split(/\s+/).filter(Boolean);
const hit = txt => words.every(w => txt.includes(w));
const loteOf = it => it.kind === 'base' ? it.code : it.lote;
const days = range ? [0, 1, 2, 3, 4, 5, 6].map(i => shiftDate(today, -i)) : [day];
const need = days.join(',');
useEffect(() => { days.forEach(d => { if (onLoadDay && (plan || {})[d] === undefined) onLoadDay(d); }); }, [need]);
const toggle = it => setSel(s => s.some(x => x.id === it.id) ? s.filter(x => x.id !== it.id) : [...s, it]);
const has = it => sel.some(x => x.id === it.id);
const Row = ({ it, indent }) => (
toggle(it)}>
{has(it) ? '✓' : ''}
{it.nombre}
{it.kind === 'base' ? window.t('BASE') : window.t('COLOR')}{it.cantidad ? ` · ${it.cantidad} ${it.unit || 'GL'}` : ''}
{window.t('Lote')}: {loteOf(it) || '—'}
);
let total = 0;
const blocks = days.map(d => {
// Buscar por nombre o lote. Si coincide la base (nombre o lote) se muestran TODOS sus colores;
// si solo coinciden algunos colores, se muestran esos junto con su base.
const groups = buildGroups(plan, d, machines).map(g => {
const baseTxt = (g.title + ' ' + (g.code || '') + ' ' + (g.cantidad || '') + ' ' + (g.tipo || '')).toLowerCase();
const baseHit = !words.length || hit(baseTxt);
const cols = acc.includes('color')
? (baseHit ? g.colors : g.colors.filter(c => hit(baseTxt + ' ' + (c.nombre + ' ' + (c.lote || '') + ' ' + (c.cantidad || '')).toLowerCase())))
: [];
return { base: g.base && acc.includes('base') ? g.base : null, colors: cols, title: g.title, code: g.code, show: baseHit || cols.length > 0 };
}).filter(g => g.show && (g.base || g.colors.length));
total += groups.length;
return { d, groups, loaded: (plan || {})[d] !== undefined };
});
return (
{ setRange(false); setDay(shiftDate(day, -1)); }} aria-label={window.t('Día anterior')}>‹
{range ? window.t('Últimos 7 días') : (day === today ? window.t('Hoy') + ' · ' : '') + dayLabel(day)}
{ setRange(false); setDay(shiftDate(day, 1)); }} aria-label={window.t('Día siguiente')} disabled={!range && day >= today}>›
{ if (e.target.value) { setRange(false); setDay(e.target.value); } }} />
{(day !== today || range) &&
{ setRange(false); setDay(today); }}>{window.t('Hoy')} }
setRange(r => !r)}>{range ? window.t('Viendo 7 días') : window.t('Ver últimos 7 días')}
setQ(e.target.value)} />
{blocks.map(({ d, groups, loaded }) => (
{range &&
{dayLabel(d)}{d === today ? ' · ' + window.t('hoy') : ''}
}
{!loaded &&
{window.t('Cargando bases de este día…')}
}
{loaded && groups.length === 0 && !range &&
{words.length ? window.t('Nada coincide con la búsqueda en este día.') : window.t('No quedan bases o colores por asignar para este día en esta máquina.')}
}
{groups.map(g => (
{g.base ?
|
:
{g.title}{g.code ? ' · ' + window.t('Lote') + ': ' + g.code : ''}
}
{g.colors.map(c =>
|
)}
))}
))}
{range && total === 0 && blocks.every(x => x.loaded) && {words.length ? window.t('Nada coincide con la búsqueda en los últimos 7 días.') : window.t('No quedan bases ni colores por asignar en los últimos 7 días.')}
}
{sel.length ? tf(sel.length > 1 ? '{n} seleccionados: {names}' : '{n} seleccionado: {names}', { n: sel.length, names: itemsName(sel) }) : window.t('Puedes elegir varios, incluso de días distintos.')}
onAdd([sel])}>{window.t('Agregar como 1 lote')}
{sel.length > 1 && onAdd(sel.map(x => [x]))}>{window.t('Cada uno como lote aparte')} }
);
}
function MoveSheet({ entry, from, machines, onMove, onClose, profileOf }) {
const kinds = qItems(entry).map(a => a.kind);
const dest = machines.filter(m => m.id !== from.id && kinds.every(k => acceptsOf(m.type).includes(k)));
return (
{dest.length === 0 && {window.t('No hay otra máquina que acepte este lote.')}
}
{dest.map(m => (
onMove(m.id)}>
{m.name} {m.code || ''} · {tf('{n} en fila', { n: (m.queue || []).length })}{profileOf && cpMachineBlockReason(profileOf(m)) ? ' · ⚠ ' + cpMachineBlockReason(profileOf(m)) : ''}
{window.t('Pasar aquí')}
))}
);
}
function DetailSheet({ rec, onClose }) {
const { m, b, live, tl } = rec;
const phases = b.phases || [];
const total = phases.reduce((a, p) => a + (Number(p.computedMins) || 0), 0);
const multi = tl.spanDays > 0;
const dayOf = abs => relDay(shiftDate(tl.startDay, Math.floor(abs / 1440)));
const byIdx = {}; tl.segs.forEach(sg => { byIdx[sg.idx] = sg; });
const tag = abs => (multi && abs != null) ? {dayOf(abs)} : null;
return (
{b.failed && {window.t('Lote fallido')} {b.failReason || b.notes || window.t('Sin observación')}
}
{window.t('Máquina')} {m.name}
{window.t('Operario')} {b.operario || '—'}
{window.t('Lote')} {b.lote || '—'}
{window.t('Cantidad')} {b.cantidad ? b.cantidad + ' GL' : '—'}
{window.t('Ocupó la máquina')} {multi ? dayOf(tl.S) + ' ' : ''}{fmt(tl.S)} → {live ? window.t('ahora') : (multi ? dayOf(tl.E) + ' ' : '') + fmt(tl.E)}
{window.t('Tiempo total en la máquina')} {dur(tl.E - tl.S)}
{window.t('Sin fase en marcha')} {tl.pauses.length ? dur(unionLen(tl.pauses)) : window.t('ninguno')}
{tl.pauses.length > 0 && {window.t('Tiempo muerto con la máquina cargada')}: {tl.pauses.map(([x, y]) => `${fmt(x)}–${fmt(y)} (${dur(y - x)})`).join(' · ')}
}
{multi && {window.t('Este lote cruzó la medianoche: en el historial de cada día aparece solo la parte que ocurrió ese día.')}
}
{window.t('Fase')} {window.t('Hr inicial')} {window.t('Hr final')} {window.t('Min')}
{phases.map((p, i) => {
const sg = byIdx[i];
return (
{p.name}
{p.startTime || '—'}{sg && p.startTime ? tag(sg.s) : null}
{p.endTime || '—'}{sg && p.endTime ? tag(sg.e) : null}
{p.computedMins != null ? p.computedMins : '—'}
);
})}
{window.t('TOTAL (suma de fases)')} {total}
{b.notes && !b.failed ? {window.t('Observaciones')} {b.notes}
: null}
);
}
// ── Perfiles de fases por máquina ───────────────────────────
// machine.phaseProfiles = [{ id, name, phases:[{ name, limitMins }] }] · machine.phaseProfileId = perfil activo
// Las fases siguen siendo las mismas de siempre (machine.phases); el perfil solo guarda
// "juegos" de fases para cambiar entre ellos sin borrar y volver a crear.
const phasesFromList = list => list.map(x => ({ ...newPhase(x.name), limitMins: x.limitMins || null }));
const snapshotPhases = m => (m.phases || []).map(p => ({ name: p.name, limitMins: p.limitMins || null }));
const hasProgress = m => (m.phases || []).some(p => p.status !== 'pending' || p.running || p.startTime || p.endTime || (p.accumulated || 0) > 0);
function applyProfile(m, id) {
const MT = window.AppData.MACHINE_TYPES || {};
if (!id) return { ...m, phaseProfileId: '' };
if (id === '__std') {
const names = ((MT[m.type] || {}).defaultPhases || []);
return { ...m, phaseProfileId: '__std', phases: phasesFromList(names.map(n => ({ name: n }))) };
}
const pr = (m.phaseProfiles || []).find(x => x.id === id);
return pr ? { ...m, phaseProfileId: id, phases: phasesFromList(pr.phases) } : m;
}
function ProfileSelect({ m, canEdit, onPatch }) {
const MT = window.AppData.MACHINE_TYPES || {};
const mt = MT[m.type] || {};
const profiles = m.phaseProfiles || [];
const locked = hasProgress(m);
return (
{window.t('Perfil de fases')}
onPatch(x => applyProfile(x, e.target.value))}>
{window.t('Fases actuales')}{profiles.length ? ' (' + window.t('sin perfil') + ')' : ''}
{(mt.defaultPhases || []).length > 0 && {tf('Estándar de {name}', { name: window.t(mt.name || 'la máquina') })} }
{profiles.map(pr => {pr.name} · {tf('{n} fases', { n: pr.phases.length })} )}
{locked && canEdit && {window.t('Hay fases con avance: finaliza el lote para cambiar de perfil.')} }
);
}
// Fases y horas: el mismo detalle de la pantalla clásica, en grande
function PhasesSheet({ machine, canEdit, onPatch, onClose }) {
const MT = window.AppData.MACHINE_TYPES || {};
const mt = MT[machine.type] || {};
const options = mt.defaultPhases || [];
const PS = window.AppData.PHASE_STATUSES || [];
const [naming, setNaming] = useState(null); // 'new' | 'rename' | null
const [nameVal, setNameVal] = useState('');
const [confirmDel, setConfirmDel] = useState(false);
const profiles = machine.phaseProfiles || [];
const active = profiles.find(x => x.id === machine.phaseProfileId);
const dirty = !!active && JSON.stringify(snapshotPhases(machine)) !== JSON.stringify(active.phases);
const upd = (i, fn) => onPatch(m => mapPhase(m, i, fn));
const saveNew = () => {
const name = nameVal.trim(); if (!name) return;
const id = cpUid();
onPatch(m => ({ ...m, phaseProfiles: [...(m.phaseProfiles || []), { id, name, phases: snapshotPhases(m) }], phaseProfileId: id }));
setNaming(null); setNameVal('');
};
const rename = () => {
const name = nameVal.trim(); if (!name) return;
onPatch(m => ({ ...m, phaseProfiles: (m.phaseProfiles || []).map(x => x.id === m.phaseProfileId ? { ...x, name } : x) }));
setNaming(null); setNameVal('');
};
return (
{canEdit && naming === null && (
{ setNaming('new'); setNameVal(''); }}>{window.t('Guardar fases como perfil nuevo')}
{active && dirty && onPatch(m => ({ ...m, phaseProfiles: (m.phaseProfiles || []).map(x => x.id === m.phaseProfileId ? { ...x, phases: snapshotPhases(m) } : x) }))}>{tf('Actualizar “{name}”', { name: active.name })} }
{active && { setNaming('rename'); setNameVal(active.name); }}>{window.t('Renombrar perfil')} }
{active && {
if (!confirmDel) { setConfirmDel(true); return; }
onPatch(m => ({ ...m, phaseProfiles: (m.phaseProfiles || []).filter(x => x.id !== m.phaseProfileId), phaseProfileId: '' })); setConfirmDel(false);
}}>{confirmDel ? window.t('Toca otra vez para eliminar') : window.t('Eliminar perfil')} }
)}
{naming !== null && (
setNameVal(e.target.value)} />
{window.t('Guardar')}
setNaming(null)}>{window.t('Cancelar')}
)}
{dirty &&
{tf('Cambiaste las fases respecto a “{name}”. Usa “Actualizar” para guardar el cambio en el perfil.', { name: active.name })}
}
{machine.phases.map((p, i) => {
const mins = cpPhaseDisplayMins(p);
const lim = Number(p.limitMins) || 0;
const over = lim && mins != null && mins > lim;
return (
{i + 1}
{canEdit && options.length > 0 ? (
upd(i, x => ({ ...x, name: e.target.value }))}>
{!options.includes(p.name) && {p.name} }
{options.map((o, k) => {o} )}
) : (
upd(i, x => ({ ...x, name: e.target.value }))} />
)}
{mins != null ? mins : '–'} {window.t('min')}{over ? ' ⚠' : ''}
{window.t('Hr inicial')}
upd(i, x => x.running ? x : ({ ...x, startTime: e.target.value, accumulated: syncAcc(x, e.target.value, x.endTime) }))} />
{canEdit && !p.running && upd(i, x => { const n = cpNowHHMM(); return { ...x, startTime: n, accumulated: syncAcc(x, n, x.endTime) }; })}>{window.t('Ahora')} }
{window.t('Hr final')}
upd(i, x => x.running ? x : ({ ...x, endTime: e.target.value, accumulated: syncAcc(x, x.startTime, e.target.value) }))} />
{canEdit && !p.running && upd(i, x => { const n = cpNowHHMM(); return { ...x, endTime: n, accumulated: syncAcc(x, x.startTime, n) }; })}>{window.t('Ahora')} }
{window.t('Límite (min)')}
upd(i, x => ({ ...x, limitMins: e.target.value ? Number(e.target.value) : null }))} />
{window.t('Estado')}
upd(i, x => ({ ...x, phaseStatus: e.target.value }))}>
{window.t('Pendiente')}
{PS.map(s => {s.label} )}
{canEdit && (
{p.status !== 'done' && (p.running
? onPatch(m => pausePhase(m, i))}>{window.t('Pausar')}
: onPatch(m => startPhase(m, i))}>{p.status === 'paused' ? window.t('Reanudar') : window.t('Iniciar')} )}
{p.status !== 'done' && onPatch(m => finishPhase(m, i))}>{window.t('Terminar fase')} }
{p.status === 'done' && {window.t('✓ Terminada')} }
upd(i, resetFields)}>{window.t('Reiniciar')}
{ if (confirm(tf('¿Quitar la fase "{name}"?', { name: p.name || i + 1 }))) onPatch(m => ({ ...m, phases: m.phases.filter((_, k) => k !== i) })); }}>{window.t('Quitar')}
)}
);
})}
{canEdit && onPatch(m => ({ ...m, phases: [...m.phases, newPhase(options[0])] }))}>{window.t('+ Agregar fase')} }
{tfx('Total: {n} min en {k} fases.', { n: {machine.phases.reduce((a, p) => a + (cpPhaseDisplayMins(p) || 0), 0)} , k: machine.phases.length })}
);
}
// ── Bases y colores del día ────────────────────────────────
const ST_LABEL = { pend: 'Pendiente', fila: 'En fila', curso: 'En máquina', proc: 'En proceso', listo: 'Listo', canc: 'Cancelado' };
function BasesView({ plan, machines, cpDate, search, filter, setFilter, canEdit, onAssign }) {
const place = {};
machines.forEach(m => {
(m.assignments || []).forEach(a => { place[a.id] = { m, w: 'curso' }; });
(m.queue || []).forEach(q => qItems(q).forEach(a => { place[a.id] = { m, w: 'fila' }; }));
});
const bases = (plan || {})[cpDate] || [];
const colorSt = c => {
if (c.cancelled) return 'canc';
if (c.checkEM || c.status === 'ready') return 'listo';
if (place[c.id]) return place[c.id].w;
if (c.checkEC || c.status === 'running') return 'proc';
return 'pend';
};
const baseSt = b => {
if (b.status === 'cancelled') return 'canc';
const cols = (b.colors || []).filter(c => !c.cancelled);
if (b.status === 'done' || b.checkFN || (cols.length && cols.every(c => c.checkEM || c.status === 'ready'))) return 'listo';
if (place[b.id]) return place[b.id].w;
if (b.status === 'running' || b.checkEC || cols.some(c => c.checkEC)) return 'proc';
return 'pend';
};
const words = search.trim().toLowerCase().split(/\s+/).filter(Boolean);
const rows = bases.map(b => {
const bs = baseSt(b);
const cols = (b.colors || []).map(c => ({ c, st: colorSt(c) }));
return { b, bs, cols };
}).filter(r => {
if (words.length) {
const hay = [r.b.nombre, r.b.code, r.cols.map(x => x.c.nombre + ' ' + (x.c.lote || '')).join(' ')].join(' ').toLowerCase();
if (!words.every(w => hay.includes(w))) return false;
}
if (filter === 'all') return true;
const grp = s => filter === 'maq' ? (s === 'curso' || s === 'fila' || s === 'proc') : s === filter;
return grp(r.bs) || r.cols.some(x => grp(x.st));
});
const cnt = { pend: 0, maq: 0, listo: 0 };
bases.forEach(b => {
const all = [baseSt(b), ...(b.colors || []).map(colorSt)];
if (all.includes('pend')) cnt.pend++;
if (all.some(s => ['curso', 'fila', 'proc'].includes(s))) cnt.maq++;
if (baseSt(b) === 'listo') cnt.listo++;
});
const asItem = (b, kind, c) => kind === 'base'
? { 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, planDate: cpDate }
: { id: c.id, kind: 'color', nombre: c.nombre, cantidad: c.cantidad, unit: c.unit || b.unit, color: c.hex || '#ccc', parentId: b.id, planDate: cpDate, lote: c.lote };
const where = id => place[id] ? tf(place[id].w === 'curso' ? 'En {name}' : 'En fila de {name}', { name: place[id].m.name }) : '';
return (
{[['all', window.t('Todas') + ' ' + bases.length], ['pend', window.t('Pendientes') + ' ' + cnt.pend], ['maq', window.t('En máquina o fila') + ' ' + cnt.maq], ['listo', window.t('Listas') + ' ' + cnt.listo]].map(([k, l]) => (
setFilter(k)}>{l}
))}
{bases.length === 0 &&
{window.t('No hay bases de producción para este día.')}
}
{bases.length > 0 && rows.length === 0 &&
{window.t('Ninguna base coincide con el filtro.')}
}
{rows.map(({ b, bs, cols }) => (
{b.nombre}
{b.code ? b.code + ' · ' : ''}{b.cantidad} {b.unit || 'GL'}{b.tipo ? ' · ' + b.tipo : ''} · {cols.length} {window.t(cols.length === 1 ? 'color' : 'colores')}
{where(b.id) && {where(b.id)} }
{window.t(ST_LABEL[bs])}
{canEdit && bs === 'pend' &&
onAssign(asItem(b, 'base'))}>{window.t('Mandar a máquina')} }
{cols.length > 0 && (
{cols.map(({ c, st }) => (
{c.nombre}
{c.lote ? c.lote + ' · ' : ''}{c.cantidad} {c.unit || b.unit || 'GL'}{where(c.id) ? ' · ' + where(c.id) : ''}
{window.t(ST_LABEL[st])}
{canEdit && st === 'pend' &&
onAssign(asItem(b, 'color', c))}>{window.t('Mandar')} }
))}
)}
))}
);
}
function AssignSheet({ item, machines, onPick, onClose, profileOf }) {
const dest = machines.filter(m => acceptsOf(m.type).includes(item.kind));
return (
{dest.length === 0 && {window.t('Ninguna máquina acepta este tipo.')}
}
{dest.map(m => {
const st = cpMachineStatus(m);
return (
onPick(m)}>
{m.name}
{m.code || ''} · {window.t(st === 'running' ? 'En proceso' : st === 'paused' ? 'En pausa' : (m.assignments || []).length ? 'Cargada' : 'Libre')} · {tf('{n} en fila', { n: (m.queue || []).length })}{profileOf && cpMachineBlockReason(profileOf(m)) ? ' · ⚠ ' + cpMachineBlockReason(profileOf(m)) : ''}
{window.t('Mandar aquí')}
);
})}
);
}
// ── Tarjeta de máquina ──────────────────────────────────────
// ── Fila de máquina (presentación 2: fila con línea del día) ─────────
// Bloques ya terminados hoy, en minutos del día, para la mini línea de tiempo
function dayBlocks(m, day) {
const out = [];
(m.history || []).forEach(b => {
let startDay, c = null;
if (b.timestamp) { c = vetParts(b.timestamp); if (c.day < day || c.day > shiftDate(day, 6)) return; }
else { startDay = cpBatchDay(b); if (!startDay || startDay > day || startDay < shiftDate(day, -6)) return; }
const tl = batchTimeline(b, null); if (!tl) return;
if (c) { const endDay = (c.min >= tl.E % 1440) ? c.day : shiftDate(c.day, -1); startDay = shiftDate(endDay, -tl.spanDays); }
const off = daysBetween(day, startDay) * 1440;
const s = Math.max(off + tl.S, 0), e = Math.min(off + tl.E, 1440);
if (e > s) out.push([s, e, !!b.failed]);
});
return out;
}
function MachineRow({ m, avg, now, canEdit, operators, profile, ui, order, open, onToggle, today }) {
const st = cpMachineStatus(m);
const hasBatch = (m.assignments || []).length > 0;
const ci = curIndex(m);
const sc = schedule(m, avg, now);
const q = m.queue || [];
const out = (profile.status || 'operativa') === 'inactiva';
const lastPhase = ci === m.phases.length - 1;
const allDone = hasBatch && ci === -1;
let chip = window.t('Libre'), chipCls = '';
if (st === 'running') { chip = window.t('En proceso'); chipCls = 'run'; }
else if (st === 'paused') { chip = window.t('En pausa'); chipCls = 'pau'; }
else if (allDone) { chip = window.t('Fases terminadas'); chipCls = 'run'; }
else if (hasBatch) { chip = window.t('Lista para iniciar'); chipCls = 'pau'; }
const cur = ci >= 0 ? m.phases[ci] : null;
const curMins = cur ? (cpPhaseDisplayMins(cur) || 0) : 0;
const curEst = cur ? phaseEst(cur, avg) : null;
const running = cur && cur.running;
const missing = batchMissing(m);
const elapsed = hasBatch ? Math.floor(cpMachineTotalSeconds(m) / 60) : 0;
const curEnd = hasBatch ? now + Math.max(0, sc.est.mins - elapsed) : null;
const startMin = (() => {
const h = cpTimeToMins(m.hrInicialBatch);
if (h != null) return h;
const f = (m.phases || []).find(p => p.startTime);
const fm0 = f ? cpTimeToMins(f.startTime) : null;
return fm0 != null ? fm0 : now - elapsed;
})();
// mini línea de tiempo del día: hecho · en curso · fila proyectada
const W0 = Math.floor((now - 240) / 60) * 60, W1 = W0 + 720;
const pos = t => Math.max(0, Math.min(100, (t - W0) / (W1 - W0) * 100));
const blk = (a, b, cls, key, ttl, inner) => (b > W0 && a < W1)
? {inner} : null;
const done = today ? dayBlocks(m, today) : [];
const act = canEdit && (hasBatch ? (
<>
{cur && !running && ui.patch(m.id, x => startPhase(x, ci))}>{cur.status === 'paused' ? window.t('Reanudar') : window.t('Iniciar fase')} }
{cur && running && ui.patch(m.id, x => pausePhase(x, ci))}>{window.t('Pausar')} }
{cur && !lastPhase && ui.patch(m.id, x => nextPhase(x, ci))}>{window.t('Fase lista')} }
{(lastPhase || allDone) && ui.finalize(m, missing)}>{window.t('Finalizar lote')} }
ui.open({ t: 'fail', mid: m.id })} title={window.t('Marcar el lote como fallido y guardarlo en el historial')}>{window.t('Fallida')}
>
) : (q.length > 0
? ui.startNext(m)}>{window.t('Iniciar #1')}: {itemsName(qItems(q[0]))}
: ui.open({ t: 'pick', mid: m.id })}>{window.t('+ Agregar a la fila')} ));
return (
{open ? '⌄' : '›'}
{order && order.move(m.id, -1)}>▲ order.move(m.id, 1)}>▼ }
{m.name}
{m.code || ''}
{out && {window.t('Fuera de servicio')} }
{!out && cpMachineBlockReason(profile) && {window.t('Falla urgente')} }
{chip}
{hasBatch &&
{itemsName(m.assignments)} {m.lote || window.t('sin lote')}{m.operario ? ' · ' + String(m.operario).split(' ')[0] : ''}
}
{done.map((d, i) => blk(d[0], d[1], d[2] ? 'past failed' : 'past', 'd' + i, (d[2] ? window.t('FALLIDO') + ' ' : window.t('Terminado') + ' ') + fmt(d[0]) + '–' + fmt(d[1])))}
{hasBatch && blk(startMin, curEnd, 'cur', 'cur', window.t('En curso') + ' ' + fmt(startMin) + '–~' + fmt(curEnd), )}
{sc.blocks.map((b, i) => blk(b.s, b.e, 'plan', 'q' + i, itemsName(qItems(b.q)) + ' · ' + fmt(b.s) + '–' + fmt(b.e)))}
{hasBatch ? (
{m.phases.map((p, i) => {p.status === 'done' ? '✓' : i + 1} )}
{cur ? <>{cur.name} {curMins}{curEst ? '/' + curEst : ''} {window.t('min')}{cur.status === 'paused' ? ' · ' + window.t('en pausa') : ''} > : {window.t('Todas las fases terminadas')} }
) :
{tf(ui.doneToday(m) === 1 ? 'Sin lote en proceso · hoy {n} lote terminado' : 'Sin lote en proceso · hoy {n} lotes terminados', { n: ui.doneToday(m) })}
}
{q.length > 0 && (
{sc.blocks.slice(0, 3).map((b, i) => {i + 1} {itemsName(qItems(b.q))} {fmt(b.s)} )}
{q.length > 3 && {tf('+{n} más', { n: q.length - 3 })} }
)}
{hasBatch ? <>{fmt(curEnd)} {tf('termina · faltan {t}', { t: dur(curEnd - now) })} >
: <>{q.length ? fmt(sc.finish) : '—'} {q.length ? window.t('fila termina ≈') : window.t('libre')} >}
{act}
{open && (
{window.t('Fases')} {m.phases.length ? `(${m.phases.filter(p => p.status === 'done').length}/${m.phases.length})` : ''}
{m.phases.map((p, i) => (
{p.status === 'done' ? '✓' : i + 1}
{p.name}
{p.startTime || '—'}{p.endTime ? '–' + p.endTime : ''}
{cpPhaseDisplayMins(p) || 0}{phaseEst(p, avg) ? '/' + phaseEst(p, avg) : ''} {window.t('min')}
))}
{m.phases.length === 0 &&
{window.t('Esta máquina no tiene fases.')}
}
ui.open({ t: 'fases', mid: m.id })}>{window.t('Fases y horas')}
ui.patch(m.id, fn)} />
{ui.canReport && ui.reportFalla(m)}>{window.t('⚠ Reportar falla')} }
{ui.classic && {window.t('Vista clásica para esto')} }
{window.t('Datos del lote')}
{hasBatch ? (
<>
{window.t('Lote')} {m.lote || '—'}
{window.t('Cantidad')} {m.cantidad ? m.cantidad + ' GL' : '—'}
{window.t('Operario')} {m.operario || '—'}
{m.hrInicialBatch ? window.t('En la máquina desde') : window.t('Estado')} {m.hrInicialBatch || window.t('Sin iniciar')}
{itemsGL(m.assignments) ? itemsGL(m.assignments) + ' GL · ' : ''}{tf(sc.est.exact ? 'lote de {t} estimado' : 'lote de {t} (aprox.)', { t: dur(sc.est.mins) })}
{m.notes ?
{window.t('Observaciones')} {m.notes}
: null}
{m.assignments.filter(a => ui.canPack(m, a)).map(a => (
ui.openPack(m, a)} title={window.t('Cargar el envasado real (empaquetado) de este color')}>📦 {window.t('Empaque')}: {a.nombre}
))}
{canEdit &&
ui.open({ t: 'datos', mid: m.id })}>{window.t('Editar datos')} }
>
) :
{tf('Máquina libre. Hoy: {n} lotes terminados.', { n: ui.doneToday(m) })}
}
{window.t('Fila de producción')} ({q.length})
{sc.blocks.length === 0 &&
{window.t('No hay lotes en espera.')}
}
{sc.blocks.map((b, i) => (
#{i + 1} {itemsName(qItems(b.q))}
{itemsGL(qItems(b.q)) ? itemsGL(qItems(b.q)) + ' GL · ' : ''}{sc.est.exact ? '' : '~'}{fmt(b.s)}–{fmt(b.e)}
ui.patch(m.id, x => ({ ...x, queue: x.queue.map(z => z.qid === b.q.qid ? { ...z, operario: v } : z) }))} />
{canEdit && (
ui.patch(m.id, x => { const a = [...x.queue]; [a[i - 1], a[i]] = [a[i], a[i - 1]]; return { ...x, queue: a }; })}>▲
ui.patch(m.id, x => { const a = [...x.queue]; [a[i + 1], a[i]] = [a[i], a[i + 1]]; return { ...x, queue: a }; })}>▼
ui.open({ t: 'move', mid: m.id, qid: b.q.qid })}>⇄
ui.patch(m.id, x => ({ ...x, queue: x.queue.filter(z => z.qid !== b.q.qid) }))}>✕
)}
))}
{canEdit &&
ui.open({ t: 'pick', mid: m.id })}>{window.t('+ Agregar a la fila')} }
{q.length > 0 &&
{window.t('Fila termina ≈')} {fmt(sc.finish)}
}
)}
);
}
// ── Orden de las máquinas ───────────────────────────────────
const SORTS = [
['def', 'Orden del sistema'], ['name', 'Nombre A–Z'], ['code', 'Código'], ['type', 'Tipo de máquina'],
['state', 'En proceso primero'], ['busy', 'Más ocupadas'], ['idle', 'Menos ocupadas'], ['lotes', 'Más lotes'],
['manual', 'Mi orden (con flechas)'],
];
const HIST_ONLY = ['busy', 'idle', 'lotes'];
const SORT_KEY = 'sp_tb_sort_v1', ORDER_KEY = 'sp_tb_order_v1';
const loadLS = (k, d) => { try { const v = localStorage.getItem(k); return v == null ? d : JSON.parse(v); } catch (_) { return d; } };
const saveLS = (k, v) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch (_) {} };
const stateRank = m => {
const st = cpMachineStatus(m);
return st === 'running' ? 0 : st === 'paused' ? 1 : (m.assignments || []).length ? 2 : (m.queue || []).length ? 3 : 4;
};
function sortMachines(list, by, manual, stats) {
const MTs = window.AppData.MACHINE_TYPES || {};
const typeName = m => (MTs[m.type] || {}).name || m.type || '';
const cmp = (x, y) => String(x).localeCompare(String(y), 'es', { numeric: true, sensitivity: 'base' });
const idx = new Map(list.map((m, i) => [m.id, i]));
const st = stats || {};
const f = {
name: (x, y) => cmp(x.name, y.name),
code: (x, y) => cmp(x.code || '', y.code || ''),
type: (x, y) => cmp(typeName(x), typeName(y)) || cmp(x.name, y.name),
state: (x, y) => (stateRank(x) - stateRank(y)) || cmp(x.name, y.name),
busy: (x, y) => ((st[y.id] || {}).occ || 0) - ((st[x.id] || {}).occ || 0),
idle: (x, y) => ((st[x.id] || {}).occ || 0) - ((st[y.id] || {}).occ || 0),
lotes: (x, y) => ((st[y.id] || {}).n || 0) - ((st[x.id] || {}).n || 0),
manual: (x, y) => {
const px = manual.indexOf(x.id), py = manual.indexOf(y.id);
return (px < 0 ? 1e6 + idx.get(x.id) : px) - (py < 0 ? 1e6 + idx.get(y.id) : py);
},
}[by];
return f ? [...list].sort((x, y) => f(x, y) || (idx.get(x.id) - idx.get(y.id))) : [...list];
}
function SortSelect({ value, onChange, histView }) {
const opts = SORTS.filter(([k]) => histView || !HIST_ONLY.includes(k));
const v = opts.some(o => o[0] === value) ? value : 'def';
return (
{window.t('Ordenar máquinas')}
onChange(e.target.value)} aria-label={window.t('Ordenar máquinas')}>
{opts.map(([k, l]) => {window.t(l)} )}
);
}
// ── Historial (uno o varios días) ───────────────────────────
function HistoryView({ machines, cpDate, now, search, sortBy, manual, onMoveOrder, onOpen, onFull }) {
useLang();
const today = cpCaracasDateStr();
const [mode, setMode] = useState('line');
const [span, setSpan] = useState(1); // días que se ven, terminando en cpDate
const [zoom, setZoom] = useState(null); // px por hora; null = ajustar al ancho
const [cw, setCw] = useState(1100);
const hsRef = useRef(null);
const anchor = useRef(null);
const fromDay = shiftDate(cpDate, -(span - 1));
const winEnd = span * 1440;
const todayIdx = daysBetween(fromDay, today); // 0..span-1 si hoy está en la ventana
const todayIn = todayIdx >= 0 && todayIdx < span;
useEffect(() => {
const el = hsRef.current; if (!el) return;
const upd = () => setCw(el.clientWidth || 1100);
upd(); window.addEventListener('resize', upd);
return () => window.removeEventListener('resize', upd);
}, [mode]);
const recs = useMemo(() => {
const out = [];
const words = (search || '').trim().toLowerCase().split(/\s+/).filter(Boolean);
const toDay = cpDate;
const add = (m, b, tl, live) => {
const off = daysBetween(fromDay, tl.startDay) * 1440;
const S0 = off + tl.S, E0 = off + tl.E;
if (E0 <= 0 || S0 >= winEnd) return;
const s = Math.max(S0, 0), e = Math.min(E0, winEnd);
if (e <= s) return;
if (words.length) {
const hay = [m.name, m.code, b.lote, b.operario, (b.assignments || []).map(a => a.nombre).join(' ')].filter(Boolean).join(' ').toLowerCase();
if (!words.every(w => hay.includes(w))) return;
}
out.push({
m, b, tl, live, s, e, fromPrev: S0 < 0, toNext: E0 > winEnd,
pauses: tl.pauses.map(([x, y]) => [Math.max(off + x, s), Math.min(off + y, e)]).filter(([x, y]) => y > x),
});
};
machines.forEach(m => {
(m.history || []).forEach(b => {
let startDay, c = null;
if (b.timestamp) {
c = vetParts(b.timestamp);
if (c.day < fromDay || c.day > shiftDate(toDay, 6)) return;
} else {
startDay = cpBatchDay(b);
if (!startDay || startDay > toDay || startDay < shiftDate(fromDay, -6)) return;
}
const tl = batchTimeline(b, null);
if (!tl) return;
if (c) {
const endDay = (c.min >= tl.E % 1440) ? c.day : shiftDate(c.day, -1);
startDay = shiftDate(endDay, -tl.spanDays);
}
tl.startDay = startDay;
add(m, b, tl, false);
});
if ((m.assignments || []).length && (m.phases || []).some(p => p.startTime)) {
const b = {
assignments: m.assignments, operario: m.operario, lote: m.lote, cantidad: m.cantidad, notes: m.notes, hrInicialBatch: m.hrInicialBatch,
phases: m.phases.map(p => ({ name: p.name, startTime: p.startTime, endTime: p.endTime, computedMins: cpPhaseDisplayMins(p) })),
};
const tl = batchTimeline(b, now);
if (tl) { tl.startDay = shiftDate(today, -tl.spanDays); add(m, b, tl, true); }
}
});
return out;
}, [machines, cpDate, span, today, now, search]);
// métricas por máquina → permiten ordenar por ocupación
const stats = {};
machines.forEach(m => {
const mine = recs.filter(r => r.m.id === m.id);
stats[m.id] = { occ: unionLen(mine.map(r => [r.s, r.e])), n: mine.length };
});
const ordered = sortMachines(machines, sortBy, manual, stats);
// escala horizontal
const FIXED = 200 + 150 + 4;
const fit = Math.max(2.5, (cw - FIXED) / (span * 24));
const ppm = zoom == null ? fit : zoom; // px por hora
const px = t => t / 60 * ppm;
const trackW = Math.round(span * 24 * ppm);
const stepH = [1, 2, 3, 4, 6, 12, 24].find(h => h * ppm >= 56) || 24;
const ticks = []; for (let h = 0; h <= span * 24; h += stepH) ticks.push(h);
const dayNames = []; for (let i = 0; i < span; i++) dayNames.push(shiftDate(fromDay, i));
const dayTxt = d => new Date(d + 'T12:00:00').toLocaleDateString(loc(), { weekday: 'short', day: 'numeric', month: 'short' }) + (d === today ? ' · ' + window.t('hoy') : '');
const zoomBy = (f, screenX) => {
const el = hsRef.current; if (!el) return;
const sx = screenX != null ? screenX : 200 + Math.max(0, el.clientWidth - FIXED) / 2;
const t = ((el.scrollLeft + sx) - 200) / ppm * 60;
anchor.current = { t, sx };
setZoom(Math.min(400, Math.max(2.5, ppm * f)));
};
useEffect(() => { // conserva lo que se mira al cambiar el zoom
const el = hsRef.current, a = anchor.current; if (!el || !a) return;
el.scrollLeft = Math.max(0, 200 + a.t / 60 * ppm - a.sx); anchor.current = null;
}, [zoom]);
useEffect(() => { // Ctrl + rueda = zoom
const el = hsRef.current; if (!el) return;
const h = e => {
if (!e.ctrlKey) return;
e.preventDefault();
const r = el.getBoundingClientRect();
zoomBy(e.deltaY < 0 ? 1.2 : 1 / 1.2, e.clientX - r.left);
};
el.addEventListener('wheel', h, { passive: false });
return () => el.removeEventListener('wheel', h);
});
const focusNow = () => {
const el = hsRef.current; if (!el || !todayIn) return;
el.scrollLeft = Math.max(0, 200 + px(todayIdx * 1440 + now) - (el.clientWidth - FIXED) / 2);
};
const focusKey = span + '|' + cpDate + '|' + mode;
useEffect(() => { // al cambiar de rango/día: ir a "ahora" o al primer lote
const el = hsRef.current; if (!el || mode !== 'line') return;
if (todayIn) { focusNow(); return; }
const first = recs.reduce((m, r) => Math.min(m, r.s), Infinity);
el.scrollLeft = isFinite(first) ? Math.max(0, 200 + px(first) - 80) : 0;
}, [focusKey]);
// cifras
let totOcc = 0, totShift = 0, denom = 0;
const rows = ordered.map(m => {
const mine = recs.filter(r => r.m.id === m.id).sort((x, y) => x.s - y.s);
const occ = unionLen(mine.map(r => [r.s, r.e]));
totOcc += occ;
const wins = [];
for (let i = 0; i < span; i++) {
const w0 = i * 1440 + SHIFT0;
let w1 = i * 1440 + SHIFT1;
if (i === todayIdx) w1 = Math.min(w1, i * 1440 + Math.max(now, SHIFT0 + 60));
else if (i > todayIdx && todayIdx >= 0) continue;
if (w1 > w0) wins.push([w0, w1]);
}
wins.forEach(([w0, w1]) => { totShift += unionLen(mine.map(r => [Math.max(r.s, w0), Math.min(r.e, w1)])); });
if (m === ordered[0]) wins.forEach(([w0, w1]) => { denom += w1 - w0; });
const gaps = []; let prev = SHIFT0;
const lim = todayIn ? todayIdx * 1440 + now : winEnd;
mine.forEach(r => { if (r.s - prev >= 25) gaps.push([prev, r.s]); prev = Math.max(prev, r.e); });
if (lim - prev >= 25) gaps.push([prev, lim]);
return { m, mine, occ, gaps };
});
const sortedList = [...recs].sort((x, y) => x.s - y.s);
const spanTxt = r => {
const t = r.tl, multi = t.spanDays > 0;
const d = abs => relDay(shiftDate(t.startDay, Math.floor(abs / 1440)));
return (multi ? d(t.S) + ' ' : '') + fmt(t.S) + ' → ' + (r.live ? window.t('ahora') : (multi ? d(t.E) + ' ' : '') + fmt(t.E));
};
const manualOn = sortBy === 'manual';
return (
setMode('line')}>{window.t('Línea de tiempo')}
setMode('list')}>{window.t('Lista de lotes')}
{[1, 2, 3, 7, 14].map(n => { setSpan(n); setZoom(null); }}>{n === 1 ? window.t('1 día') : tf('{n} días', { n })} )}
{mode === 'line' && (
zoomBy(1 / 1.4)} aria-label={window.t('Alejar')}>−
{Math.round(ppm)} px/h
zoomBy(1.4)} aria-label={window.t('Acercar')}>+
{ setZoom(null); }}>{window.t('Ajustar')}
{todayIn && {window.t('Ir a ahora')} }
)}
{onFull &&
{window.t('Historial completo (todos los días)')} }
{span === 1 ? dayTxt(cpDate) : tf('Del {a} al {b}', { a: dayTxt(fromDay), b: dayTxt(cpDate) })} · {window.t('usa ‹ › arriba para mover el rango')}
{mode === 'line' ? ' · ' + window.t('zoom: botones + / −, o Ctrl + rueda del mouse') : ''}
{recs.length} {span === 1 ? window.t('Lotes en este día') : tf('Lotes en {n} días', { n: span })}
{dur(totOcc)} {window.t('Horas-máquina ocupadas')}
{Math.min(100, Math.round(totShift / Math.max(60, denom * Math.max(1, machines.length)) * 100))}% {window.t('Ocupación dentro de la jornada 06:00–22:00')}
{mode === 'list' && (
{window.t('Ocupó la máquina')} {window.t('Máquina')} {window.t('Bases y colores')} {window.t('Lote')} {window.t('Cant.')} {window.t('Operario')} {window.t('Tiempo en la máquina')} {window.t('Sin fase')}
{sortedList.map((r, i) => (
onOpen(r)} className={'tb-clk' + (r.b.failed ? ' tb-failrow' : '')}>
{spanTxt(r)}
{r.m.name} {r.m.code || ''}
{(r.b.assignments || []).map(a => {a.nombre} )}{r.live && {window.t('En curso')} }{r.b.failed && {window.t('Fallido')} }{r.b.failed && r.b.failReason && {r.b.failReason} }
{r.b.lote || '—'}
{r.b.cantidad ? r.b.cantidad + ' GL' : '—'}
{r.b.operario || '—'}
{dur(r.tl.E - r.tl.S)}{(r.fromPrev || r.toNext) ? {tf('en este rango: {t}', { t: dur(r.e - r.s) })} : null}
{r.tl.pauses.length ? dur(unionLen(r.tl.pauses)) : '—'}
))}
{sortedList.length === 0 && {window.t('No hay lotes con horas registradas en este rango.')} }
)}
{mode === 'line' && (
{window.t('Máquina')}
{dayNames.map((d, i) => {dayTxt(d)} )}
{ticks.map(h => {String(h % 24).padStart(2, '0')}:00 )}
{window.t('Ocupación')}
{rows.map(({ m, mine, occ, gaps }, ri) => (
{m.name} {m.code || ''}
{manualOn && onMoveOrder && (
onMoveOrder(m.id, -1)}>▲
onMoveOrder(m.id, 1)}>▼
)}
{dayNames.map((d, i) => i > 0 &&
)}
{gaps.map((g, i) => { const w = px(g[1]) - px(g[0]); return w >= 70 ?
{tf('libre {t}', { t: dur(g[1] - g[0]) })} : null; })}
{mine.map((r, i) => {
const len = Math.max(1, r.e - r.s), t = r.tl, multi = t.spanDays > 0;
const d = abs => relDay(shiftDate(t.startDay, Math.floor(abs / 1440)));
const w = Math.max(6, px(r.e) - px(r.s));
return (
onOpen(r)}
title={(r.b.failed ? window.t('FALLIDO') + ': ' + (r.b.failReason || '') + ' · ' : '') + itemsName(r.b.assignments || []) + ' · ' + spanTxt(r) + (r.pauses.length ? ' · ' + tf('sin fase {t}', { t: dur(unionLen(r.pauses)) }) : '')}>
{r.pauses.map((pz, k) => )}
{w >= 40 && {r.b.failed ? '✖ ' : ''}{itemsName(r.b.assignments || []) || window.t('Lote')} }
{w >= 90 && {fmt(r.s)}–{r.live ? window.t('ahora') : fmt(r.e)}{r.fromPrev ? ' ◀' : ''}{r.toNext ? ' ▶' : ''}{multi && !r.fromPrev && !r.toNext ? ' · ' + d(t.S) + '→' + d(t.E) : ''}{!multi && r.b.operario ? ' · ' + String(r.b.operario).split(' ')[0] : ''}{r.pauses.length && w >= 190 ? ' · ' + tf('{t} sin fase', { t: dur(unionLen(r.pauses)) }) : ''} }
);
})}
{todayIn &&
}
{dur(occ)} {mine.length} {window.t(mine.length === 1 ? 'lote' : 'lotes')}
))}
{rows.length === 0 &&
{window.t('No hay máquinas con este filtro.')}
}
)}
{window.t('Cada barra es un lote: de la hora en que arrancó a la hora en que terminó. En varios días el lote que cruza la medianoche se ve continuo; en un solo día se corta en el límite del día (◀ viene del día anterior, ▶ sigue al día siguiente). Las franjas rayadas son tiempo sin fase en marcha con la máquina cargada (10 min o más entre una fase y la siguiente, o después de la última fase mientras el lote sigue en la máquina): ahí ves si hubo tiempo muerto. Toca una barra para ver sus fases.')}
{recs.length === 0 ? ' ' + window.t('No hay lotes con horas registradas en este rango.') : ''}
);
}
// ── Pantalla principal ──────────────────────────────────────
function Tablero(props) {
useLang();
const { allPlan, initDate, onCpDateChange, onBaseComplete, onBaseStarted, onAssignmentRemoved, onSetPackagingEnvasado, machines, setMachines, canEdit, tick, machineProfiles, operators, isAdmin } = props;
// Reporte de fallas: solo si app.jsx lo pasa (hoy lo recibe la vista móvil, no ControlProceso).
const onReportMachineFalla = props.onReportMachineFalla, canReportMachineFalla = !!props.canReportMachineFalla;
const profileOf = m => (machineProfiles && machineProfiles[m.code || m.id]) || {};
// Bloquea (o, siendo admin, pide confirmación) cargar lotes en máquinas inactivas o con falla urgente abierta.
const loadGuard = m => cpCheckMachineAssignable(profileOf(m), !!isAdmin, m.code || m.name);
// Ítems ya presentes en alguna máquina o fila (evita asignar lo mismo a dos máquinas)
const takenIds = () => {
const t = new Set();
machines.forEach(m => { (m.assignments || []).forEach(a => t.add(a.id)); (m.queue || []).forEach(q => qItems(q).forEach(a => t.add(a.id))); });
return t;
};
const dupOf = items => { const t = takenIds(); return items.find(a => t.has(a.id)) || null; };
const [cpDate, setCpDate] = useState(initDate || todayStr());
const [view, setView] = useState('maq');
const [bFilter, setBFilter] = useState('all');
const [sortBy, setSortBy] = useState(() => loadLS(SORT_KEY, 'def'));
const [manual, setManual] = useState(() => loadLS(ORDER_KEY, []));
const [typeF, setTypeF] = useState('all');
const [search, setSearch] = useState('');
const [openRows, setOpenRows] = useState(() => new Set());
const toggleRow = id => setOpenRows(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
const [sheet, setSheet] = useState(null);
const [pack, setPack] = useState(null); // { m, a, entries } — envasado real (empaquetadora)
const [toastMsg, setToastMsg] = useState('');
const [practice, setPractice] = useState(practiceOn());
const MT = window.AppData.MACHINE_TYPES || {};
const now = nowMin();
const avg = useMemo(() => avgPhaseMins(machines), [machines]);
useEffect(() => { if (!toastMsg) return; const t = setTimeout(() => setToastMsg(''), 3000); return () => clearTimeout(t); }, [toastMsg]);
const patch = (id, fn) => { if (!canEdit || !setMachines) return; setMachines(prev => prev.map(m => m.id === id ? fn(m) : m)); };
const byId = id => machines.find(m => m.id === id);
const navDate = d => { const nd = shiftDate(cpDate, d); setCpDate(nd); if (onCpDateChange) onCpDateChange(nd); };
const today = todayStr();
const startedFor = (items, type) => items.forEach(a => { if (onBaseStarted) onBaseStarted(a.id, a.kind, a.planDate || cpDate, type); });
const ui = {
patch,
open: setSheet,
doneToday: m => (m.history || []).filter(b => !b.failed && cpBatchDay(b) === cpDate).length,
startNext: m => {
if (!loadGuard(m)) return;
const nx = takeNext(m);
if (!nx) return;
let upd = nx.machine;
if (upd.phases.length) upd = startPhase(upd, 0);
patch(m.id, () => upd);
startedFor(qItems(nx.entry), m.type);
setToastMsg(tf('Lote iniciado: {names}', { names: itemsName(qItems(nx.entry)) }));
},
finalize: (m, missing) => setSheet({ t: missing.length ? 'datos-fin' : 'fin', mid: m.id }),
canPack: (m, a) => !!canEdit && !!onSetPackagingEnvasado && m.type === 'empaquetadora' && a.kind === 'color',
openPack: (m, a) => {
const day = a.planDate || m.fecha || cpDate;
let planColor = null;
for (const b of ((allPlan || {})[day] || [])) { const c = (b.colors || []).find(x => x.id === a.id); if (c) { planColor = c; break; } }
const src = planColor && ((planColor.envasadoReal && planColor.envasadoReal.length) ? planColor.envasadoReal : planColor.envasado);
const entries = (src && src.length) ? src.map(e => ({ ...e, id: e.id || cpUid() })) : [{ id: cpUid(), tipo: 'gl', cantidad: 0, marca: '' }];
setPack({ m, a, day, entries });
},
canReport: !!onReportMachineFalla && canReportMachineFalla,
reportFalla: m => setSheet({ t: 'falla', mid: m.id }),
classic: props.onClassic || null,
};
const doFinalize = (m) => {
const refDate = m.fecha || cpDate;
const r = closeBatch(m);
patch(m.id, () => r.next);
(m.assignments || []).filter(a => a.kind === 'base').forEach(a => { if (onBaseComplete) onBaseComplete(a.id, a.planDate || refDate); });
try { cpAwardMachinePoints(r.closed, refDate); } catch (_) {}
if (r.loaded) startedFor(qItems(r.loaded), m.type);
setSheet(null);
setToastMsg(r.loaded ? tf('Lote guardado en el historial. Siguiente cargado: {names}', { names: itemsName(qItems(r.loaded)) }) : window.t('Lote guardado en el historial'));
};
const doFail = (m, reason) => {
// El lote fallido no da la base por producida: se revierten los checks de cada asignación.
if (onAssignmentRemoved) (m.assignments || []).forEach(a => onAssignmentRemoved(a.id, a.kind, a.planDate || m.fecha || cpDate, m.type));
const r = closeBatch(m, reason);
patch(m.id, () => r.next);
if (r.loaded) startedFor(qItems(r.loaded), m.type);
setSheet(null);
setToastMsg(window.t('Lote marcado como FALLIDO y guardado en el historial'));
};
// bases y colores libres del día de la pantalla (para el contador)
const groups = useMemo(() => buildGroups(allPlan, cpDate, machines), [allPlan, cpDate, machines]);
const porAsignar = groups.reduce((a, g) => a + (g.base ? 1 : 0) + g.colors.length, 0);
const presentTypes = useMemo(() => { const o = {}; machines.forEach(m => { o[m.type] = (o[m.type] || 0) + 1; }); return o; }, [machines]);
const filtered = machines.filter(m => {
if (typeF !== 'all' && m.type !== typeF) return false;
if (search.trim() && view === 'maq') {
const hay = [m.name, m.code, m.operario, m.lote, (m.assignments || []).map(a => a.nombre).join(' ')].filter(Boolean).join(' ').toLowerCase();
if (!search.toLowerCase().split(/\s+/).filter(Boolean).every(w => hay.includes(w))) return false;
}
return true;
});
const changeSort = v => { setSortBy(v); saveLS(SORT_KEY, v); };
const effSort = (view !== 'his' && HIST_ONLY.includes(sortBy)) ? 'def' : sortBy;
// en "Máquinas" el orden se aplica aquí; en "Historial" lo aplica la propia vista (necesita las horas ocupadas)
const shown = view === 'his' ? filtered : sortMachines(filtered, effSort, manual);
const moveOrder = (id, dir) => {
const full = sortMachines(machines, 'manual', manual).map(m => m.id);
const vis = new Set(filtered.map(m => m.id));
const order = view === 'his' ? full.filter(x => vis.has(x)) : shown.map(m => m.id);
const k = order.indexOf(id), n = order[k + dir];
if (k < 0 || n == null) return;
const a = full.indexOf(id), b = full.indexOf(n);
[full[a], full[b]] = [full[b], full[a]];
setManual(full); saveLS(ORDER_KEY, full);
};
const busy = machines.filter(m => ['running', 'paused'].includes(cpMachineStatus(m))).length;
const doneToday = machines.reduce((a, m) => a + ui.doneToday(m), 0);
const inQueue = machines.reduce((a, m) => a + (m.queue || []).length, 0);
const d = new Date(cpDate + 'T12:00:00');
const dlab = cpDate === today ? window.t('Hoy') + ' · ' : '';
const dtxt = dlab + d.toLocaleDateString(loc(), { day: 'numeric', month: 'short', year: 'numeric' });
const togglePractice = () => {
const nv = !practice;
try { localStorage.setItem(PRACTICE_KEY, nv ? '1' : '0'); } catch (_) {}
setPractice(nv);
setToastMsg(nv ? window.t('Modo práctica: lo que hagas NO se guarda') : window.t('Modo real: los cambios se guardan en la base de datos'));
};
const sm = sheet && byId(sheet.mid);
return (
{typeof window.spPracticeOn === 'function' && ( // solo en la copia de prueba; en la planta original no hay modo práctica
{practice
? window.t('MODO PRÁCTICA · puedes probar todo; nada se guarda y al recargar vuelve a como estaba.')
: window.t('MODO REAL · los cambios se guardan en la base de datos de producción.')}
{practice ? window.t('Pasar a modo real') : window.t('Volver a modo práctica')}
)}
{window.t('Tablero de Producción')}{window.t('Planta Caucho · Control de Proceso')}
navDate(-1)} aria-label={window.t('Día anterior')}>‹
{dtxt}
navDate(1)} aria-label={window.t('Día siguiente')}>›
setView('maq')}>{window.t('Máquinas')}
setView('bas')}>{window.t('Bases del día')}
setView('his')}>{window.t('Historial del día')}
{fmt(now)}
{props.onClassic &&
{window.t('Vista clásica')} }
{view !== 'bas' && <>
setTypeF('all')}>{window.t('Todas')} {machines.length}
{Object.entries(presentTypes).map(([t, n]) => (
setTypeF(t)}>{window.t((MT[t] && MT[t].name) || t)} {n}
))}
>}
{view !== 'bas' && }
setSearch(e.target.value)} />
{view === 'maq' && (
<>
{busy} / {machines.length} {window.t('Máquinas trabajando')}
{doneToday} {window.t('Lotes terminados')}
{inQueue} {window.t('Lotes en fila')}
{porAsignar} {window.t('Por asignar')}
{machines.length === 0 &&
{window.t('No hay máquinas configuradas. Usa “Vista clásica” para agregar una.')}
}
setOpenRows(new Set(shown.map(m => m.id)))}>{window.t('Expandir todas')}
setOpenRows(new Set())}>{window.t('Colapsar')}
{shown.map(m => (
toggleRow(m.id)} />
))}
>
)}
{view === 'bas' &&
setSheet({ t: 'assign', item })} />}
{view === 'his' && setSheet({ t: 'det', rec: r })} onFull={props.onShowHistorial} />}
{sheet && sheet.t === 'fases' && sm && patch(sm.id, fn)} onClose={() => setSheet(null)} />}
{sheet && sheet.t === 'assign' && (
setSheet(null)} onPick={m => {
if (dupOf([sheet.item])) { setToastMsg(tf('{name} ya está en otra máquina o fila', { name: sheet.item.nombre })); setSheet(null); return; }
if (!loadGuard(m)) return;
patch(m.id, x => ({ ...x, queue: [...(x.queue || []), { qid: cpUid(), operario: '', addedAt: cpNowIso(), items: [sheet.item] }] }));
setSheet(null); setToastMsg(tf('{name} → fila de {m}', { name: sheet.item.nombre, m: m.name }));
}} />
)}
{sheet && sheet.t === 'pick' && sm && (
{ if (onCpDateChange) onCpDateChange(d); }} onClose={() => setSheet(null)} onAdd={lotes => {
const dup = dupOf(lotes.flat());
if (dup) { setToastMsg(tf('{name} ya está en otra máquina o fila', { name: dup.nombre })); return; }
if (!loadGuard(sm)) return;
patch(sm.id, x => ({ ...x, queue: [...(x.queue || []), ...lotes.map(items => ({ qid: cpUid(), operario: '', addedAt: cpNowIso(), items }))] }));
setSheet(null); setToastMsg(lotes.length > 1 ? tf('{n} lotes agregados a la fila', { n: lotes.length }) : window.t('Agregado a la fila'));
}} />
)}
{sheet && sheet.t === 'move' && sm && (() => {
const entry = (sm.queue || []).find(z => z.qid === sheet.qid);
if (!entry) return null;
return setSheet(null)} onMove={toId => {
const dest = byId(toId);
if (!canEdit || !setMachines) return;
if (dest && !loadGuard(dest)) return;
setMachines(prev => prev.map(m => {
if (m.id === sm.id) return { ...m, queue: (m.queue || []).filter(z => z.qid !== entry.qid) };
if (m.id === toId) return { ...m, queue: [...(m.queue || []), entry] };
return m;
}));
setSheet(null); setToastMsg(tf('Lote pasado a {name}', { name: (byId(toId) || {}).name }));
}} />;
})()}
{sheet && (sheet.t === 'datos' || sheet.t === 'datos-fin') && sm && (
setSheet(null)}
onChange={upd => patch(sm.id, () => upd)}
onFinalize={sheet.t === 'datos-fin' ? () => doFinalize(sm) : null} />
)}
{sheet && sheet.t === 'fin' && sm && (
setSheet(null)}>
{window.t('Operario')} {sm.operario}
{window.t('Lote')} {sm.lote}
{window.t('Cantidad')} {sm.cantidad} GL
{window.t('Desde')} {sm.hrInicialBatch}
{curIndex(sm) === -1 ? window.t('Todas las fases están terminadas.') : window.t('La última fase se marcará como terminada ahora.')}
{(sm.queue || []).length ? ' ' + tf('Después se cargará el siguiente de la fila: {names}.', { names: itemsName(qItems(sm.queue[0])) }) : ''}
setSheet({ t: 'datos', mid: sm.id })}>{window.t('Revisar datos')}
doFinalize(sm)}>{window.t('Finalizar y guardar en historial')}
)}
{sheet && sheet.t === 'fail' && sm && (
setSheet(null)} onConfirm={reason => doFail(sm, reason)} />
)}
{sheet && sheet.t === 'det' && setSheet(null)} />}
{sheet && sheet.t === 'falla' && sm && typeof MachineFallaModal === 'function' && (
onReportMachineFalla && onReportMachineFalla(sm.code || sm.id, descripcion, gravedad)}
onClose={() => setSheet(null)} />
)}
{pack && typeof EnvasadoRealModal === 'function' && (
setPack(x => x ? { ...x, entries } : x)}
onCancel={() => setPack(null)}
onConfirm={() => { if (onSetPackagingEnvasado) onSetPackagingEnvasado(pack.a.id, pack.day, pack.entries); setPack(null); setToastMsg(tf('Empaquetado guardado: {name}', { name: pack.a.nombre })); }} />
)}
{toastMsg}
);
}
// ── Selector Tablero ⇄ Vista clásica ────────────────────────
const Classic = window.ControlProceso;
function ControlProcesoSwitch(props) {
useLang();
const [mode, setMode] = useState(() => { try { return localStorage.getItem(MODE_KEY) || 'tablero'; } catch (_) { return 'tablero'; } });
const set = v => { setMode(v); try { localStorage.setItem(MODE_KEY, v); } catch (_) {} };
if (mode === 'classic') {
return (
<>
set('tablero')}>{window.t('← Volver al Tablero de Producción')}
>
);
}
return set('classic')} />;
}
window.ControlProcesoClasico = Classic;
window.ControlProceso = ControlProcesoSwitch;
window.TableroProduccion = Tablero;
})();