// ════════════════════════════════════════════ // Control de Proceso — Verona Color Paints // ════════════════════════════════════════════ const { useState: cpUseState, useEffect: cpUseEffect, useMemo: cpUseMemo, useRef: cpUseRef } = React; // URL absoluta del logo para las ventanas de impresión/PDF (se abren como // about:blank vía document.write, por lo que una ruta relativa no resolvería). const CP_LOGO_URL = (() => { try { return new URL('logo-verona.png', document.baseURI).href; } catch (_) { return 'logo-verona.png'; } })(); // ─── Touch drag-and-drop (soporte para tablets) ─────────────────────────────── let _cpTouchItem = null; // datos del item siendo arrastrado por toque let _cpTouchGhost = null; // elemento visual "fantasma" const _cpDropReg = {}; // machineId → función de drop function _cpGhostCreate(sourceEl, cx, cy) { const r = sourceEl.getBoundingClientRect(); const g = sourceEl.cloneNode(true); Object.assign(g.style, { position: 'fixed', pointerEvents: 'none', zIndex: '9999', width: r.width + 'px', opacity: '0.88', top: (cy - r.height / 2) + 'px', left: (cx - r.width / 2) + 'px', transform: 'scale(1.06)', boxShadow: '0 8px 28px rgba(0,0,0,.22)', transition: 'none', }); document.body.appendChild(g); return g; } function _cpGhostMove(cx, cy) { if (!_cpTouchGhost) return; _cpTouchGhost.style.top = (cy - _cpTouchGhost.offsetHeight / 2) + 'px'; _cpTouchGhost.style.left = (cx - _cpTouchGhost.offsetWidth / 2) + 'px'; } function _cpGhostEnd() { if (_cpTouchGhost) { _cpTouchGhost.remove(); _cpTouchGhost = null; } document.querySelectorAll('.proc-row.touch-drag-over') .forEach(el => el.classList.remove('touch-drag-over')); } function _cpTouchHandleEnd(cx, cy) { const target = document.elementFromPoint(cx, cy); const row = target && target.closest('[data-cp-mid]'); if (row && _cpTouchItem) { const fn = _cpDropReg[row.getAttribute('data-cp-mid')]; if (fn) fn(_cpTouchItem); } } // Manejadores reutilizables para onTouchMove sobre items arrastrables function _cpItemTouchMove(e) { if (!_cpTouchItem) return; e.preventDefault(); const t = e.touches[0]; _cpGhostMove(t.clientX, t.clientY); const el = document.elementFromPoint(t.clientX, t.clientY); const row = el && el.closest('[data-cp-mid]'); document.querySelectorAll('.proc-row.touch-drag-over') .forEach(r => r.classList.remove('touch-drag-over')); if (row) row.classList.add('touch-drag-over'); } function _cpItemTouchEnd(e) { if (!_cpTouchItem) return; const t = e.changedTouches[0]; _cpTouchHandleEnd(t.clientX, t.clientY); _cpGhostEnd(); _cpTouchItem = null; } function _cpItemTouchCancel() { _cpGhostEnd(); _cpTouchItem = null; } // ─── Paleta de colores para máquinas ───────── const CP_MACHINE_COLORS = [ '#3b6fd4','#138a52','#b56e08','#6b46c1', '#c43050','#0891b2','#059669','#d97706', ]; // ─── Utilities ─────────────────────────────── function cpUid() { return 'cp' + Math.random().toString(36).slice(2, 9); } function cpFormatDuration(secs) { if (!secs || secs < 0) return '00:00'; const h = Math.floor(secs / 3600); const m = Math.floor((secs % 3600) / 60); const s = secs % 60; if (h > 0) return `${h}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`; return `${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`; } function cpElapsed(phase) { if (!phase) return 0; const acc = phase.accumulated || 0; if (!phase.running || !phase.startedAt) return acc; // Math.max(0, …) evita valores negativos por desfases de reloj (p. ej. una // fase iniciada en otra máquina cuyo startedAt quedó adelantado). return acc + Math.max(0, Math.floor((cpNowMs() - phase.startedAt) / 1000)); } function cpMachineTotalSeconds(machine) { return (machine.phases || []).reduce((s, p) => { let pSecs = 0; if (p.startTime && p.endTime) { const diff = cpCalcTimeDiffMins(p.startTime, p.endTime); if (diff !== null) pSecs += diff * 60; } else { pSecs += cpElapsed(p); } (p.extraSegments || []).forEach(seg => { if (seg.start && seg.end) { const d = cpCalcTimeDiffMins(seg.start, seg.end); if (d !== null) pSecs += d * 60; } }); return s + pSecs; }, 0); } function cpMachineProgress(machine) { const phases = machine.phases || []; if (!phases.length) return 0; const done = phases.filter(p => p.status === 'done').length; return Math.round((done / phases.length) * 100); } function cpMachineStatus(machine) { const phases = machine.phases || []; if (!phases.length) return 'idle'; if (phases.every(p => p.status === 'done')) return 'done'; if (phases.some(p => p.running)) return 'running'; if (phases.some(p => p.status === 'paused')) return 'paused'; return 'idle'; } function cpMachineTypePrefix(type) { const map = { dispersor: 'DISP', dispersor1: 'DISPM', dispersorp: 'DISPP', envasado: 'ENV', mezclador: 'MIX', molino: 'MOL', empaquetadora: 'EMP' }; return map[type] || 'MAQ'; } // ── Empaques de la empaquetadora ──────────────────────────── // Lo que realmente salió empacado del batch, por presentación. El reporte // diario usa esto en vez del galonaje de la tolva. // Ej.: una tolva de 200 GL → 400 cuñas (0,25 GL c/u = 100 GL) + 100 GL. const CP_EMP_TIPOS = [ { id: 'ku', label: 'Cuña (1/4 GL)', gl: 0.25 }, { id: 'gl', label: 'Galón', gl: 1 }, { id: 'cu4', label: 'Cuñete 4 GL', gl: 4 }, { id: 'cu7', label: 'Cuñete 2 GL', gl: 2 }, { id: 'p4', label: '4 L', gl: 1.056 }, { id: 'pl', label: '1 L', gl: 0.264 }, { id: 'pm', label: '0,5 L', gl: 0.132 }, ]; const cpFmtGL = (n) => { const v = Number(n || 0); return Number.isInteger(v) ? String(v) : v.toFixed(2).replace(/\.?0+$/, ''); }; const cpEmpTipo = (id) => CP_EMP_TIPOS.find(t => t.id === id) || null; const cpEmpLabel = (id) => (cpEmpTipo(id) || {}).label || id; // Galones equivalentes de una lista de empaques [{tipo, cantidad}]. function cpEmpaquesGL(empaques) { return (empaques || []).reduce((s, e) => { const t = cpEmpTipo(e.tipo); return s + (t ? t.gl * (Number(e.cantidad) || 0) : 0); }, 0); } // Resumen legible: "400 Cuña (1/4 GL) · 100 Galón" function cpEmpaquesResumen(empaques) { return (empaques || []) .filter(e => Number(e.cantidad) > 0) .map(e => `${Number(e.cantidad)} ${cpEmpLabel(e.tipo)}`) .join(' · '); } // Hora final del batch. Los batches antiguos guardaban 'hrInicialBatch'; // se usa como respaldo para no perder el dato ya cargado. function cpBatchHrFinal(m) { if (!m) return ''; return m.hrFinalBatch || m.hrInicialBatch || ''; } // Departamento de personal que opera cada tipo de máquina: // Dispersor Matización → matización · Envasado/Empaque → envasado · // Dispersor / Pasta / Mezclador / Molino → preparadores. function cpOperatorDept(type) { if (type === 'dispersor1') return 'matizacion'; if (type === 'envasado' || type === 'empaquetadora') return 'envasado'; if (['dispersor', 'dispersorp', 'mezclador', 'molino'].includes(type)) return 'preparadores'; return null; } // Al liberar una máquina, otorga los puntos configurados para su tipo a los // trabajadores que estuvieron en ella (el grupo o la persona del campo // Operario). Los puntos por tipo se configuran en Personal → Puntos por // máquina (solo administrador). El backend decide el monto y evita duplicados. function cpAwardMachinePoints(machine, fecha) { const toast = (m, k) => { if (window.showToast) window.showToast(m, k); }; const asgn = machine.assignments || []; fetch('./api.php', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'prep_award_machine', machine_id: machine.id, machine_type: machine.type, machine_name: `${machine.name || ''}${machine.code ? ' (' + machine.code + ')' : ''}`.trim(), operario: machine.operario || '', fecha: fecha || '', // Identidad del batch: la máquina puede cerrarse varias veces al día y // cada corrida (lote) debe otorgar sus propios puntos. lote: machine.lote || '', hr_inicial: cpBatchHrFinal(machine), cantidad: machine.cantidad || '', // Lo que llevó el batch: suma los extras por base y por color. n_bases: asgn.filter(a => a.kind === 'base').length, n_colors: asgn.filter(a => a.kind === 'color').length, }), }) .then(r => r.json().catch(() => ({}))) .then(j => { if (!j || j.error) return; // silencioso: no bloquea el cierre if (j.awarded) { const det = [j.nBases ? `${j.nBases} base(s)` : '', j.nColors ? `${j.nColors} color(es)` : ''].filter(Boolean).join(' + '); toast(`+${j.points} pts a ${j.count} persona(s) · ${j.operario}${det ? ' · ' + det : ''}`); } else if (j.reason === 'sin_puntos_configurados') { toast('Máquina liberada. Sin puntos configurados para este tipo de máquina.', 'err'); } else if (j.reason === 'operario_sin_personal') { toast(`Máquina liberada. "${j.operario}" no tiene personal registrado.`, 'err'); } }) .catch(() => {}); } function cpNewMachine(type) { const mt = (window.AppData.MACHINE_TYPES || {})[type] || {}; const phases = (mt.defaultPhases || ['Fase 1', 'Fase 2']).map(name => ({ id: cpUid(), name, status: 'pending', running: false, startedAt: null, accumulated: 0, startTime: '', endTime: '', phaseStatus: 'pendiente', })); return { id: cpUid(), type, name: mt.name || type, code: '', color: '', phases, assignments: [], notes: '', lote: '', cantidad: '', fecha: cpCaracasDateStr(), hrFinalBatch: '', operario: '', }; } // Venezuela Standard Time = UTC-4 — delega en el reloj interno de components.jsx const _CP_VET_MS = -4 * 60 * 60 * 1000; function cpGetVetOffset() { return 0; } function cpVetNow() { return typeof vetNow === 'function' ? vetNow() : new Date(Date.now() + _CP_VET_MS); } // Epoch (ms) sincronizado con el servidor — NO depende del reloj del PC. // Se usa para cronometrar las fases: así el tiempo es idéntico en todas las // máquinas aunque su reloj del sistema esté adelantado o atrasado. function cpNowMs() { return cpVetNow().getTime() - _CP_VET_MS; } function cpCaracasDateStr() { const d = cpVetNow(); return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1).toString().padStart(2,'0') + '-' + d.getUTCDate().toString().padStart(2,'0'); } function cpNextDayStr(dateStr) { const base = dateStr || cpCaracasDateStr(); const d = new Date(base + 'T12:00:00Z'); d.setUTCDate(d.getUTCDate() + 1); return d.toISOString().slice(0, 10); } function cpFmtShortDate(dateStr) { if (!dateStr) return ''; const [, m, day] = dateStr.split('-'); return `${parseInt(day)}/${parseInt(m)}`; } function cpNowHHMM() { const d = cpVetNow(); return d.getUTCHours().toString().padStart(2,'0') + ':' + d.getUTCMinutes().toString().padStart(2,'0'); } // Formatea un ISO timestamp almacenado (UTC) a fecha/hora legible en VET const _CP_MONTHS_SHORT = ['ene','feb','mar','abr','may','jun','jul','ago','sep','oct','nov','dic']; function cpFmtVetTimestamp(isoStr, opts = {}) { const d = new Date(new Date(isoStr).getTime() + _CP_VET_MS); const day = d.getUTCDate().toString().padStart(2,'0'); const mon = _CP_MONTHS_SHORT[d.getUTCMonth()]; const year = d.getUTCFullYear(); const hh = d.getUTCHours().toString().padStart(2,'0'); const mm = d.getUTCMinutes().toString().padStart(2,'0'); return opts.sep ? `${day} ${mon} ${year} · ${hh}:${mm}` : `${day} ${mon} ${year} ${hh}:${mm}`; } // ─── Helpers de tiempo manual ───────────────── // Convierte "HH:MM" a minutos totales desde medianoche function cpTimeToMins(t) { if (!t) return null; const parts = t.split(':'); if (parts.length < 2) return null; const h = parseInt(parts[0], 10); const m = parseInt(parts[1], 10); if (isNaN(h) || isNaN(m)) return null; return h * 60 + m; } // Diferencia en minutos entre dos strings "HH:MM". Admite cruce de medianoche. function cpCalcTimeDiffMins(startTime, endTime) { const s = cpTimeToMins(startTime); const e = cpTimeToMins(endTime); if (s === null || e === null) return null; let diff = e - s; if (diff < 0) diff += 24 * 60; return diff; } // Minutos a mostrar en la columna MIN: // Prioriza la diferencia entre HR INICIAL y HR FINAL si ambas existen, // de lo contrario usa el cronómetro acumulado. function cpPhaseDisplayMins(phase) { let total = 0; if (phase.startTime && phase.endTime) { const diff = cpCalcTimeDiffMins(phase.startTime, phase.endTime); if (diff !== null) total += diff; } else { const elapsed = cpElapsed(phase); if (elapsed > 0) total += Math.floor(elapsed / 60); } (phase.extraSegments || []).forEach(seg => { if (seg.start && seg.end) { const d = cpCalcTimeDiffMins(seg.start, seg.end); if (d !== null) total += d; } }); return total > 0 ? total : null; } // ─── Ícono: Reset (flecha circular) ────────── const ResetIcon = (p) => ( ); // ─── BasesPanel ────────────────────────────── function BasesPanel({ bases, machines, canEdit, onAddBase, onAddColor, onCancelBase, onUpdateBase }) { const [filter, setFilter] = cpUseState('all'); const [search, setSearch] = cpUseState(''); const isAssigned = (itemId) => machines.some(m => (m.assignments || []).some(a => a.id === itemId)); const deriveBaseStatus = (b) => { if (b.status === 'cancelled') return 'cancelled'; if (b.status === 'done' || b.checkFN || b.colors.filter(c => !c.cancelled).every(c => c.checkEM || c.status === 'ready')) return 'done'; if (isAssigned(b.id) || b.status === 'running' || b.checkEC || b.colors.some(c => c.checkEC)) return 'running'; return 'pending'; }; const STATUS_LABELS = { all: 'Todas', pending: 'Pend.', running: 'En Proc.', done: 'Final.', cancelled: 'Canc.' }; const STATUS_COUNTS = { all: bases.length }; bases.forEach(b => { const s = deriveBaseStatus(b); STATUS_COUNTS[s] = (STATUS_COUNTS[s] || 0) + 1; }); // Aplicar filtro de estado let filtered = filter === 'all' ? bases : bases.filter(b => deriveBaseStatus(b) === filter); // Aplicar búsqueda const searchQ = search.trim().toLowerCase(); if (searchQ) { filtered = filtered.filter(b => b.nombre.toLowerCase().includes(searchQ) || (b.code || '').toLowerCase().includes(searchQ) || (b.lote || '').toLowerCase().includes(searchQ) || (b.colors || []).some(c => c.nombre.toLowerCase().includes(searchQ) || (c.lote || '').toLowerCase().includes(searchQ) ) ); } const BASE_STATUS_PILL = { pending: { label: 'Pendiente', cls: 'pending' }, running: { label: 'En Proceso', cls: 'running' }, done: { label: 'Finalizada', cls: 'done' }, cancelled: { label: 'Cancelada', cls: 'cancelled'}, }; return (
BASES DE PRODUCCIÓN
{/* ── Buscador ── */}
setSearch(e.target.value)} /> {search && ( )}
{/* ── Filtros de estado ── */}
{['all', 'pending', 'running', 'done'].map(f => ( ))}
{filtered.length === 0 && (
{searchQ ? `Sin resultados para "${search}"` : `Sin bases ${filter !== 'all' ? `"${STATUS_LABELS[filter].toLowerCase()}"` : 'planificadas'} para hoy`}
)} {filtered.map(b => { const bStatus = deriveBaseStatus(b); const pill = BASE_STATUS_PILL[bStatus]; const assigned = isAssigned(b.id); const doneColors = b.colors.filter(c => (c.checkEM || c.status === 'ready') && !c.cancelled).length; const totalColors = b.colors.length; const pct = totalColors ? Math.round(doneColors / totalColors * 100) : 0; const visibleColors = searchQ ? (b.colors || []).filter(c => c.nombre.toLowerCase().includes(searchQ) || b.nombre.toLowerCase().includes(searchQ)) : (b.colors || []); return (
{ if (assigned || bStatus === 'cancelled') return; e.dataTransfer.setData('cp-item', JSON.stringify({ id: b.id, kind: 'base', nombre: b.nombre, code: b.code, cantidad: b.cantidad, unit: b.unit, color: b.color, tipo: b.tipo, colorsCount: b.colors.length, })); }} onTouchStart={e => { if (assigned || bStatus === 'cancelled') return; _cpTouchItem = { id: b.id, kind: 'base', nombre: b.nombre, code: b.code, cantidad: b.cantidad, unit: b.unit, color: b.color, tipo: b.tipo, colorsCount: b.colors.length, }; const t = e.touches[0]; _cpTouchGhost = _cpGhostCreate(e.currentTarget, t.clientX, t.clientY); }} onTouchMove={_cpItemTouchMove} onTouchEnd={_cpItemTouchEnd} onTouchCancel={_cpItemTouchCancel} >
{b.nombre} {b.code} · {b.colors.length} colores · {b.cantidad} {b.unit} {b.carryoverFrom && (() => { const f = fmtDate(b.carryoverFrom); return ( ↩ pendiente del {f.day} {f.month.toLowerCase().slice(0, 3)} ); })()} {/* Barra de avance */} {totalColors > 0 && bStatus !== 'cancelled' && (
)}
{assigned && EN MÁQUINA} {canEdit && onCancelBase && bStatus !== 'cancelled' && bStatus !== 'done' && ( )} {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 && !searchQ && (
onAddColor(b.id)}> Agregar color a esta base
)}
)} {(b.formulaTipo === 'molienda' || b.formulaTipo === 'ambas') && bStatus !== 'cancelled' && (() => { const molId = b.id + ':mol'; const molAssigned = isAssigned(molId); const molNombre = (b.molienda && b.molienda.producto) ? b.molienda.producto : (b.nombre + ' (molienda)'); const molCant = (b.molienda && b.molienda.cantidad) ? b.molienda.cantidad : ''; const molLote = (b.molienda && b.molienda.lote) ? b.molienda.lote : (b.lote || ''); const molPayload = { id: molId, kind: 'molienda', nombre: molNombre, cantidad: molCant, unit: 'Kg', color: '#b45309', parentId: b.id, lote: molLote }; return (
{ if (molAssigned) return; e.dataTransfer.setData('cp-item', JSON.stringify(molPayload)); }} onTouchStart={e => { if (molAssigned) return; _cpTouchItem = molPayload; const t = e.touches[0]; _cpTouchGhost = _cpGhostCreate(e.currentTarget, t.clientX, t.clientY); }} onTouchMove={_cpItemTouchMove} onTouchEnd={_cpItemTouchEnd} onTouchCancel={_cpItemTouchCancel} >
🧪 {molNombre} Molienda{molLote ? ` · ${molLote}` : ''}{molCant ? ` · ${molCant} Kg` : ''}
{molAssigned && ✓}
); })()}
); })}
{canEdit && onAddBase && ( )}
); } // ─── PhaseRow ───────────────────────────────── function PhaseRow({ phase, canEdit, onUpdate, onRemove, tick, isDragOver, onDragStart, onDragOver, onDragEnd, phaseIndex, batchDate, phaseOptions }) { const PHASE_STATUSES = window.AppData.PHASE_STATUSES || []; const isContinuation = phase.phaseDate && phase.phaseDate !== batchDate; // MIN: prioriza diferencia HR INICIAL/HR FINAL; si no, usa cronómetro const displayMins = cpPhaseDisplayMins(phase); // Segundos acumulados para el display HH:MM:SS del cronómetro const totalSecs = cpElapsed(phase); // Cuando cambia una hora manual, sincroniza el acumulado del cronómetro const syncAccumulated = (startTime, endTime) => { const diff = cpCalcTimeDiffMins(startTime, endTime); return diff !== null ? diff * 60 : phase.accumulated; }; const start = () => { if (!canEdit || phase.running) return; const now = cpNowHHMM(); const newStart = phase.startTime || now; onUpdate({ ...phase, running: true, startedAt: cpNowMs(), status: 'running', startTime: newStart }); }; const stopPhase = () => { if (!canEdit || !phase.running) return; onUpdate({ ...phase, running: false, accumulated: cpElapsed(phase), startedAt: null, status: 'paused' }); }; const finish = () => { if (!canEdit) return; const endTime = phase.endTime || cpNowHHMM(); const acc = syncAccumulated(phase.startTime, endTime) || cpElapsed(phase); onUpdate({ ...phase, running: false, accumulated: acc, startedAt: null, status: 'done', endTime }); }; const reset = () => { if (!canEdit) return; onUpdate({ ...phase, running: false, accumulated: 0, startedAt: null, status: 'pending', startTime: '', endTime: '', phaseStatus: 'pendiente' }); }; // Alerta de tiempo límite const limitMins = phase.limitMins ? Number(phase.limitMins) : null; const isOverLimit = limitMins && displayMins !== null && displayMins > limitMins; const isApproachingLimit = limitMins && displayMins !== null && !isOverLimit && displayMins >= limitMins * 0.85; return (
{ e.preventDefault(); onDragOver && onDragOver(phaseIndex); }} onDragLeave={() => onDragOver && onDragOver(null)} onDrop={e => { e.preventDefault(); onDragEnd && onDragEnd(); }} >
onDragStart && onDragStart()} onDragEnd={() => onDragEnd && onDragEnd()} >
{canEdit && phaseOptions && phaseOptions.length > 0 ? ( ) : ( canEdit && onUpdate({ ...phase, name: e.target.value })} /> )}
{/* Observación de la fase — queda guardada en el historial del batch */} canEdit && onUpdate({ ...phase, nota: e.target.value })} />
{ if (!canEdit) return; const newStart = e.target.value; const acc = syncAccumulated(newStart, phase.endTime); onUpdate({ ...phase, startTime: newStart, accumulated: acc }); }} />
{ if (!canEdit) 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 }) { const fallas = profile.fallas || []; const mantenimientos = profile.mantenimientos || []; const [tab, setTab] = cpUseState('activas'); const [showAddFalla, setShowAddFalla] = cpUseState(false); const [newDesc, setNewDesc] = cpUseState(''); const [newGrav, setNewGrav] = cpUseState('leve'); const [resolveId, setResolveId] = cpUseState(null); const [resFecha, setResFecha] = cpUseState(cpCaracasDateStr()); const [resSol, setResSol] = cpUseState(''); const [resPor, setResPor] = cpUseState(''); const [resNumRep, setResNumRep] = cpUseState(''); const [showAddMant, setShowAddMant] = cpUseState(false); const [mantDesc, setMantDesc] = cpUseState(''); const [mantPor, setMantPor] = cpUseState(''); const [mantFecha, setMantFecha] = cpUseState(cpCaracasDateStr()); const [mantNumRep, setMantNumRep] = cpUseState(''); const activeFallas = fallas.filter(f => !f.resuelta); const resolvedFallas = fallas.filter(f => f.resuelta); const gravLabel = { leve: 'Leve', medio: 'Medio', urgente: 'Urgente' }; const gravCls = { leve: 'falla-badge--leve', medio: 'falla-badge--medio', urgente: 'falla-badge--urgente' }; const addFalla = () => { if (!newDesc.trim()) return; const f = { id: 'f' + Date.now() + Math.random().toString(36).slice(2, 5), descripcion: newDesc.trim(), gravedad: newGrav, fechaReporte: cpCaracasDateStr(), reportadoPor: 'Admin', resuelta: false, fechaResolucion: null, solucion: '', }; onSave({ ...profile, fallas: [...fallas, f] }); setNewDesc(''); setNewGrav('leve'); setShowAddFalla(false); }; const resolverFalla = (id) => { if (!resSol.trim()) return; onSave({ ...profile, fallas: fallas.map(f => f.id === id ? { ...f, resuelta: true, fechaResolucion: resFecha, solucion: resSol.trim(), reparadoPor: resPor.trim(), numeroReporte: resNumRep.trim() } : f) }); setResolveId(null); setResSol(""); setResFecha(cpCaracasDateStr()); setResPor(""); setResNumRep(""); }; const addMantenimiento = () => { if (!mantDesc.trim()) return; const m = { id: 'm' + Date.now() + Math.random().toString(36).slice(2, 5), fecha: mantFecha, descripcion: mantDesc.trim(), realizadoPor: mantPor.trim(), numeroReporte: mantNumRep.trim(), }; onSave({ ...profile, mantenimientos: [...mantenimientos, m] }); setMantDesc(''); setMantPor(''); setMantFecha(cpCaracasDateStr()); setMantNumRep(''); setShowAddMant(false); }; const toggleStatus = () => { onSave({ ...profile, status: (profile.status || 'operativa') === 'operativa' ? 'inactiva' : 'operativa' }); }; return (
e.stopPropagation()}>
{machine.code || machine.id} {machine.name}
{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'}} />