// ════════════════════════════════════════════ // 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 && ( )}
{/* ── Filtros de estado ── */}
{['all', 'pending', 'running', 'done'].map(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' && ( )} {canEdit && onCancelBase && bStatus === 'cancelled' && ( )}
{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 && ( )}
); } // ─── 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 ? ( ) : ( 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 newEnd = e.target.value; const acc = syncAccumulated(phase.startTime, newEnd); onUpdate({ ...phase, endTime: newEnd, accumulated: acc }); }} />
{displayMins !== null ? displayMins : '–'} {isOverLimit && ⚠} {canEdit ? ( onUpdate({ ...phase, limitMins: e.target.value ? Number(e.target.value) : null })} title="Tiempo límite (minutos)" /> ) : ( phase.limitMins ? {phase.limitMins}m : null )}
{phase.status !== 'done' ? ( <> {!phase.running ? ( ) : ( )} ) : ( ✓ )} {canEdit && ( )}
); } // ─── FallaModal ─────────────────────────────── function FallaModal({ machine, profile, onSave, onClose, 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}
{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 ? (
setResFecha(e.target.value)} className="falla-input" />
setResPor(e.target.value)} /> setResNumRep(e.target.value)} style={{maxWidth:'140px'}} />