// ════════════════════════════════════════════════════════════ // 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 ( ); } function Sheet({ title, sub, onClose, children }) { return (
{ if (e.target === e.currentTarget) onClose(); }}>

{title}

{sub &&
{sub}
}
{children}
); } // 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 (