diff --git a/README.md b/README.md index 5341114..64eefab 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,36 @@ sudo systemctl daemon-reload sudo systemctl enable --now mis-control-tower-reminders.timer ``` +## Downtime Reason Backfill + +Control-Tower now preserves manual downtime reasons from `downtime-acknowledged` events when later default stop events (`PENDIENTE` / `UNCLASSIFIED`) arrive for the same incident. + +If historical rows were already overwritten, run the one-time backfill: + +1) Dry run (default lookback: 30 days): + +```bash +npm run backfill:downtime-reasons -- --dry-run --since 30d +``` + +2) Apply updates: + +```bash +npm run backfill:downtime-reasons -- --since 30d +``` + +Optional filters: + +```bash +npm run backfill:downtime-reasons -- --dry-run --since 14d --org-id --machine-id +``` + +Quick verification query (shows recent incidents with reason + source): + +```bash +node -e 'const {PrismaClient}=require("@prisma/client");const p=new PrismaClient();(async()=>{const rows=await p.reasonEntry.findMany({where:{kind:"downtime"},orderBy:{capturedAt:"desc"},take:30,select:{id:true,orgId:true,machineId:true,episodeId:true,reasonCode:true,reasonLabel:true,capturedAt:true,meta:true}});console.log(JSON.stringify(rows,(_,v)=>typeof v==="bigint"?v.toString():v,2));})().finally(()=>p.$disconnect());' +``` + ## Production build and deploy **Dev uses Turbopack, production build uses Webpack.** Next.js 16 defaults to Turbopack for both, but Turbopack production builds have known issues. This project uses: diff --git a/app/(app)/machines/MachinesClient.tsx b/app/(app)/machines/MachinesClient.tsx index 4ea2c7e..0e89e17 100644 --- a/app/(app)/machines/MachinesClient.tsx +++ b/app/(app)/machines/MachinesClient.tsx @@ -31,7 +31,7 @@ function secondsAgo(ts: string | undefined, locale: string, fallback: string) { function isOffline(ts?: string) { if (!ts) return true; - return Date.now() - new Date(ts).getTime() > 30000; // 30s threshold + return Date.now() - new Date(ts).getTime() > 10 * 60 * 1000; // 10 min (sincronizado con RECAP_HEARTBEAT_STALE_MS) } function normalizeStatus(status?: string) { diff --git a/app/(app)/machines/MachinesClient.tsx.bak b/app/(app)/machines/MachinesClient.tsx.bak new file mode 100644 index 0000000..4ea2c7e --- /dev/null +++ b/app/(app)/machines/MachinesClient.tsx.bak @@ -0,0 +1,347 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useEffect, useState, type KeyboardEvent } from "react"; +import { useI18n } from "@/lib/i18n/useI18n"; + +type MachineRow = { + id: string; + name: string; + code?: string | null; + location?: string | null; + latestHeartbeat: null | { + ts: string; + tsServer?: string | null; + status: string; + message?: string | null; + ip?: string | null; + fwVersion?: string | null; + }; +}; +const LIVE_REFRESH_MS = 5000; + +function secondsAgo(ts: string | undefined, locale: string, fallback: string) { + if (!ts) return fallback; + const diff = Math.floor((Date.now() - new Date(ts).getTime()) / 1000); + const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" }); + if (diff < 60) return rtf.format(-diff, "second"); + return rtf.format(-Math.floor(diff / 60), "minute"); +} + +function isOffline(ts?: string) { + if (!ts) return true; + return Date.now() - new Date(ts).getTime() > 30000; // 30s threshold +} + +function normalizeStatus(status?: string) { + const s = (status ?? "").toUpperCase(); + if (s === "ONLINE") return "RUN"; + return s; +} + +function badgeClass(status?: string, offline?: boolean) { + if (offline) return "bg-white/10 text-zinc-300"; + const s = (status ?? "").toUpperCase(); + if (s === "RUN") return "bg-emerald-500/15 text-emerald-300"; + if (s === "IDLE") return "bg-yellow-500/15 text-yellow-300"; + if (s === "STOP" || s === "DOWN") return "bg-red-500/15 text-red-300"; + return "bg-white/10 text-white"; +} + +export default function MachinesClient({ initialMachines = [] }: { initialMachines?: MachineRow[] }) { + const { t, locale } = useI18n(); + const router = useRouter(); + const [machines, setMachines] = useState(() => initialMachines); + const [loading, setLoading] = useState(() => initialMachines.length === 0); + const [showCreate, setShowCreate] = useState(false); + const [createName, setCreateName] = useState(""); + const [createCode, setCreateCode] = useState(""); + const [createLocation, setCreateLocation] = useState(""); + const [creating, setCreating] = useState(false); + const [createError, setCreateError] = useState(null); + const [createdMachine, setCreatedMachine] = useState<{ + id: string; + name: string; + pairingCode: string; + pairingExpiresAt: string; + } | null>(null); + const [copyStatus, setCopyStatus] = useState(null); + + useEffect(() => { + let alive = true; + let timer: ReturnType | null = null; + + async function load(initial: boolean) { + try { + if (!initial && typeof document !== "undefined" && document.hidden) { + return; + } + + const res = await fetch("/api/machines", { cache: "no-store" }); + const json = await res.json(); + if (alive) { + setMachines(json.machines ?? []); + if (initial) setLoading(false); + } + } catch { + if (alive && initial) setLoading(false); + } finally { + if (!alive) return; + timer = setTimeout(() => { + void load(false); + }, LIVE_REFRESH_MS); + } + } + + void load(initialMachines.length === 0); + return () => { + alive = false; + if (timer) clearTimeout(timer); + }; + }, [initialMachines.length]); + + async function createMachine() { + if (!createName.trim()) { + setCreateError(t("machines.create.error.nameRequired")); + return; + } + + setCreating(true); + setCreateError(null); + + try { + const res = await fetch("/api/machines", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + name: createName, + code: createCode, + location: createLocation, + }), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok || !data.ok) { + throw new Error(data.error || t("machines.create.error.failed")); + } + + const nextMachine = { + ...data.machine, + latestHeartbeat: null, + }; + setMachines((prev) => [nextMachine, ...prev]); + setCreatedMachine({ + id: data.machine.id, + name: data.machine.name, + pairingCode: data.machine.pairingCode, + pairingExpiresAt: data.machine.pairingCodeExpiresAt, + }); + setCreateName(""); + setCreateCode(""); + setCreateLocation(""); + setShowCreate(false); + } catch (err: unknown) { + const message = err instanceof Error ? err.message : null; + setCreateError(message || t("machines.create.error.failed")); + } finally { + setCreating(false); + } + } + + async function copyText(text: string) { + try { + if (navigator.clipboard?.writeText) { + await navigator.clipboard.writeText(text); + setCopyStatus(t("machines.pairing.copied")); + } else { + setCopyStatus(t("machines.pairing.copyUnsupported")); + } + } catch { + setCopyStatus(t("machines.pairing.copyFailed")); + } + setTimeout(() => setCopyStatus(null), 2000); + } + + function handleCardKeyDown(event: KeyboardEvent, machineId: string) { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + router.push(`/machines/${machineId}`); + } + } + + const showCreateCard = showCreate || (!loading && machines.length === 0); + + return ( +
+
+
+

{t("machines.title")}

+

{t("machines.subtitle")}

+
+ +
+ + + {t("machines.backOverview")} + +
+
+ + {showCreateCard && ( +
+
+
+
{t("machines.addCardTitle")}
+
{t("machines.addCardSubtitle")}
+
+
+ +
+ + + +
+ +
+ + {createError &&
{createError}
} +
+
+ )} + + {createdMachine && ( +
+
{t("machines.pairing.title")}
+
+ {t("machines.pairing.machine")} {createdMachine.name} +
+
+
{t("machines.pairing.codeLabel")}
+
{createdMachine.pairingCode}
+
+ {t("machines.pairing.expires")}{" "} + {createdMachine.pairingExpiresAt + ? new Date(createdMachine.pairingExpiresAt).toLocaleString(locale) + : t("machines.pairing.soon")} +
+
+
+ {t("machines.pairing.instructions")} +
+
+ + {copyStatus &&
{copyStatus}
} +
+
+ )} + + {loading &&
{t("machines.loading")}
} + + {!loading && machines.length === 0 && ( +
{t("machines.empty")}
+ )} + +
+ {(!loading ? machines : []).map((m) => { + const hb = m.latestHeartbeat; + const hbTs = hb?.tsServer ?? hb?.ts; + const offline = isOffline(hbTs); + const normalizedStatus = normalizeStatus(hb?.status); + const statusLabel = offline ? t("machines.status.offline") : (normalizedStatus || t("machines.status.unknown")); + const lastSeen = secondsAgo(hbTs, locale, t("common.never")); + + return ( +
router.push(`/machines/${m.id}`)} + onKeyDown={(event) => handleCardKeyDown(event, m.id)} + className="cursor-pointer rounded-2xl border border-white/10 bg-white/5 p-5 hover:bg-white/10" + > +
+
+
{m.name}
+
+ {m.code ? m.code : t("common.na")} - {t("machines.lastSeen", { time: lastSeen })} +
+
+ + + {statusLabel} + +
+ +
{t("machines.status")}
+
+ {offline ? ( + <> +
+ +
+ ); + })} +
+
+ ); +} diff --git a/app/(app)/machines/[machineId]/MachineDetailClient.tsx b/app/(app)/machines/[machineId]/MachineDetailClient.tsx index 76cb4e9..c6ceac7 100644 --- a/app/(app)/machines/[machineId]/MachineDetailClient.tsx +++ b/app/(app)/machines/[machineId]/MachineDetailClient.tsx @@ -26,6 +26,7 @@ import { formatDuration, formatTime, normalizeTimelineSegments, + SEGMENT_MIN_WIDTH_PCT, TIMELINE_COLORS, } from "@/components/recap/timelineRender"; @@ -106,6 +107,9 @@ type WorkOrderUpload = { sku?: string; targetQty?: number; cycleTime?: number; + mold?: string; + cavitiesTotal?: number; + cavitiesActive?: number; }; type WorkOrderRow = Record; @@ -192,8 +196,31 @@ const WORK_ORDER_KEYS = { "theoretical_cycle_time", ]), target: new Set(["targetquantity", "targetqty", "target", "target_qty"]), + mold: new Set(["mold", "molde", "moldid", "mold_id"]), + cavitiesTotal: new Set([ + "totalcavities", + "cavitiestotal", + "cavities_total", + "total_cavities", + ]), + cavitiesActive: new Set([ + "activecavities", + "cavitiesactive", + "cavities_active", + "active_cavities", + ]), }; +const WORK_ORDER_TEMPLATE_HEADERS = [ + "Work Order ID", + "SKU", + "Theoretical Cycle Time (Seconds)", + "Target Quantity", + "Mold", + "Total Cavities", + "Active Cavities", +] as const; + function normalizeKey(value: string) { return value.toLowerCase().replace(/[^a-z0-9]/g, ""); } @@ -278,7 +305,26 @@ function rowsToWorkOrders(rows: WorkOrderRow[]): WorkOrderUpload[] { const targetQty = Number.isFinite(Number(targetRaw)) ? Math.trunc(Number(targetRaw)) : undefined; const cycleTime = Number.isFinite(Number(cycleRaw)) ? Number(cycleRaw) : undefined; - out.push({ workOrderId, sku: sku || undefined, targetQty, cycleTime }); + const moldRaw = pickRowValue(row, WORK_ORDER_KEYS.mold); + const mold = String(moldRaw ?? "").trim(); + const totalCavRaw = pickRowValue(row, WORK_ORDER_KEYS.cavitiesTotal); + const activeCavRaw = pickRowValue(row, WORK_ORDER_KEYS.cavitiesActive); + const cavitiesTotal = Number.isFinite(Number(totalCavRaw)) + ? Math.trunc(Number(totalCavRaw)) + : undefined; + const cavitiesActive = Number.isFinite(Number(activeCavRaw)) + ? Math.trunc(Number(activeCavRaw)) + : undefined; + + out.push({ + workOrderId, + sku: sku || undefined, + targetQty, + cycleTime, + mold: mold || undefined, + cavitiesTotal, + cavitiesActive, + }); }); return out; @@ -308,6 +354,14 @@ type MachineActivityTimelineProps = { t: (key: string, vars?: Record) => string; }; +function getMinuteFlooredOneHourRange(referenceMs = Date.now()) { + const endMs = Math.floor(referenceMs / 60000) * 60000; + return { + startMs: endMs - 60 * 60 * 1000, + endMs, + }; +} + function MachineActivityTimeline({ machineId, locale, t }: MachineActivityTimelineProps) { const [timeline, setTimeline] = useState(null); const [timelineLoading, setTimelineLoading] = useState(true); @@ -321,11 +375,18 @@ function MachineActivityTimeline({ machineId, locale, t }: MachineActivityTimeli async function loadTimeline() { try { - const res = await fetch(`/api/recap/${machineId}/timeline?range=1h`, { cache: "no-store" }); + const range = getMinuteFlooredOneHourRange(); + const params = new URLSearchParams({ + start: String(range.startMs), + end: String(range.endMs), + }); + const res = await fetch(`/api/recap/${machineId}/timeline?${params.toString()}`, { cache: "no-store" }); const json = await res.json().catch(() => null); if (!alive || !res.ok || !json) return; const nextTimeline = json as RecapTimelineResponse; const nextHash = JSON.stringify({ + start: nextTimeline.range.start, + end: nextTimeline.range.end, hasData: nextTimeline.hasData, segments: nextTimeline.segments.map((segment) => ({ type: segment.type, @@ -353,14 +414,18 @@ function MachineActivityTimeline({ machineId, locale, t }: MachineActivityTimeli }, [machineId]); const hasData = timeline?.hasData ?? false; - const startMs = timeline ? new Date(timeline.range.start).getTime() : Date.now() - 60 * 60 * 1000; - const endMs = timeline ? new Date(timeline.range.end).getTime() : Date.now(); + const fallbackRange = getMinuteFlooredOneHourRange(); + const startMs = timeline ? new Date(timeline.range.start).getTime() : fallbackRange.startMs; + const endMs = timeline ? new Date(timeline.range.end).getTime() : fallbackRange.endMs; const totalMs = Math.max(1, endMs - startMs); const normalized = useMemo(() => { if (!timeline || !hasData) return [] as RecapTimelineSegment[]; return normalizeTimelineSegments(timeline.segments, startMs, endMs); }, [timeline, hasData, startMs, endMs]); - const widths = useMemo(() => computeWidths(normalized, totalMs, 1.5), [normalized, totalMs]); + const widths = useMemo( + () => computeWidths(normalized, totalMs, SEGMENT_MIN_WIDTH_PCT), + [normalized, totalMs] + ); return (
@@ -586,6 +651,23 @@ export default function MachineDetailClient() { return null; } + async function downloadWorkOrderTemplate() { + const xlsx = await import("xlsx"); + const wb = xlsx.utils.book_new(); + const ws = xlsx.utils.aoa_to_sheet([Array.from(WORK_ORDER_TEMPLATE_HEADERS)]); + xlsx.utils.book_append_sheet(wb, ws, "Work Orders"); + const wbout = xlsx.write(wb, { bookType: "xlsx", type: "array" }); + const blob = new Blob([wbout], { + type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + }); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = "work-orders-template.xlsx"; + a.click(); + URL.revokeObjectURL(url); + } + async function handleWorkOrderUpload(event: ChangeEvent) { const file = event.target.files?.[0]; if (!file) return; @@ -1005,6 +1087,13 @@ export default function MachineDetailClient() { className="hidden" onChange={handleWorkOrderUpload} /> + \n \n \n\n \n \n
\n
OEE V1.0
\n \n\n
\n
\n
\n
\n
OEE
\n
0%
\n
\n
\n
Disponibilidad
\n
0%
\n
\n
\n
Rendimiento
\n
0%
\n
\n
\n
Calidad
\n
0%
\n
\n
\n\n
\n

Orden de trabajo actual

\n
\n
\n
ID Orden trabajo
\n
 
\n
\n
\n
SKU
\n
 
\n
\n
\n
Tiempo de ciclo
\n
0
\n
\n
\n
\n
\n
0%
\n
\n
\n\n
\n
\n
Piezas buenas
\n
0
\n
de 0
\n
\n\n
\n
MaquinaOFFLINE
\n
ProducciónDETENIDA
\n
\n\n \n
\n Cambio de molde en curso desde {{ moldChange.startMs | date:'HH:mm' }} · {{ moldChangeElapsedMin() }} min\n
\n
\n \n
\n\n
\n
\n \n\n\n\n\n \n\n
\n\n\n\n
\n
\n

Orden de trabajo en proceso

\n

{{ resumePrompt.id }}

\n

\n {{ resumePrompt.goodParts }} of {{ resumePrompt.targetQty }} partes completadas\n ({{ resumePrompt.progressPercent }}%)\n

\n

Ciclos: {{ resumePrompt.cycleCount }}

\n\n
\n \n \n
\n
\n
\n
\n
\n

{{ scrapPrompt.title || 'Orden de trabajo completada' }}

\n

{{ scrapPrompt.orderId }}

\n

\n Producido {{ scrapPrompt.produced }} de {{ scrapPrompt.target }} piezas\n

\n\n

\n Scrap acumulado: {{ scrapPrompt.scrapSoFar }}\n

\n\n
\n {{ scrapPrompt.manual ? '¿Cuántas piezas de scrap quieres agregar ahora?' : 'Hubo piezas de scrap?' }}\n
\n\n \n
\n
{{ scrapPrompt.scrapCount || 0 }}
\n
{{ scrapPrompt.error }}
\n\n
\n \n \n \n\n \n \n \n\n \n \n \n\n \n \n \n
\n\n
\n \n
\n
\n\n \n
\n \n
\n \n \n
\n\n \n \n
\n
\n
\n\n
\n
\n

Selecciona razón de scrap

\n
\n Paso {{ scrapReasonPrompt.step }} de 2\n | {{ scrapReasonPrompt.selectedCategory.label }}\n
\n\n
\n \n
\n\n
\n \n
\n\n
\n \n \n
\n
\n
\n\n\n\n\n", + "storeOutMessages": true, + "fwdInMessages": true, + "resendOnRefresh": true, + "templateScope": "local", + "className": "", + "x": 380, + "y": 280, + "wires": [ + [ + "44d2ce4b810b508b", + "ad66f1edaba40aaa", + "14c8fb75a042909e" + ] + ] + }, + { + "id": "d230dfcd0d152ded", + "type": "ui_template", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "group": "e2f3a4b5c6d7e8f9", + "name": "Alerts Template", + "order": 0, + "width": "25", + "height": "25", + "format": "\n
\n \n\n
\n
\n
\n

Incidentes

\n
\n\n
\n \n \n \n
\n\n
\n
\n \n \n
\n
\n \n \n
\n \n
\n
\n
\n
\n\n", + "storeOutMessages": true, + "fwdInMessages": true, + "resendOnRefresh": true, + "templateScope": "local", + "className": "", + "x": 380, + "y": 360, + "wires": [ + [ + "44d2ce4b810b508b", + "fa78b7dee85d560d" + ] + ] + }, + { + "id": "765441c17d3d41b6", + "type": "ui_template", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "group": "e3f4a5b6c7d8e9f0", + "name": "Graphs Template", + "order": 0, + "width": "25", + "height": "25", + "format": "\n\n
\n \n\n
\n
\n

Graphs

\n\n\n
\n
\n

OEE

\n
\n
\n\n
\n

Disponibilidad

\n
\n
\n\n
\n

Rendimiendo

\n
\n
\n\n
\n

Calidad

\n
\n
\n
\n
\n
\n
\n\n\n\n", + "storeOutMessages": true, + "fwdInMessages": true, + "resendOnRefresh": true, + "templateScope": "local", + "className": "", + "x": 390, + "y": 400, + "wires": [ + [ + "44d2ce4b810b508b" + ] + ] + }, + { + "id": "fd2616266cc640d6", + "type": "ui_template", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "group": "e4f5a6b7c8d9e0f1", + "name": "Help Template", + "order": 0, + "width": "25", + "height": "25", + "format": "\n
\n \n\n
\n
\n
\n

Help

\n
\n\n
\n

Acerca de este panel

\n

Esta interfaz monitorea los indicadores de Eficiencia Global del Equipo (OEE), el avance de producción y el registro de incidentes para operaciones de inyección de plástico. Navega entre las pestañas usando la barra lateral para acceder a órdenes de trabajo, monitoreo en tiempo real, gráficas de desempeño, registro de incidentes y configuración de máquina.

\n
\n\n
\n

Cómo empezar con una orden de trabajo

\n

Ve a la pestaña Órdenes de Trabajo y carga un archivo de Excel con tus órdenes, o selecciona una orden existente en la tabla. Haz clic en Cargar para activar una orden de trabajo y luego navega a la pestaña Inicio, donde verás los detalles de la orden actual. Antes de iniciar producción, configura tu molde en la pestaña Configuración, seleccionando un preset de molde o ingresando manualmente el número de cavidades.

\n
\n\n
\n

Ejecutando producción

\n

En la pestaña Inicio, presiona el botón INICIAR para comenzar la producción. El sistema registra conteo de ciclos, piezas buenas, scrap y el avance hacia tu cantidad objetivo. Presiona DETENER para pausar la producción. Monitorea en tiempo real los KPIs, incluyendo OEE, Disponibilidad, Rendimiento y Calidad mostrados en el tablero.

\n
\n\n
\n

Registro de incidentes

\n

Usa la pestaña Alertas para registrar incidentes de producción. Registra rápidamente problemas comunes con botones preconfigurados como Falta de Material, Máquina Detenida o Paro de Emergencia. Para un registro más detallado, selecciona un tipo de alerta en el menú desplegable, agrega notas y envía. Todos los incidentes se registran con sello de tiempo y se utilizan en los cálculos de Disponibilidad y OEE.

\n
\n\n
\n

Configuración de moldes

\n

En la pestaña Configuración, utiliza la sección de Preconfigurados de Molde para buscar tu molde por fabricante y nombre. Selecciona una configuración para cargar automáticamente el número de cavidades, o ajusta manualmente los campos de Configuración de Molde. Si tu molde no aparece, usa el botón Agregar Molde en la sección de Integraciones para crear un nuevo preset con fabricante, nombre y detalles de cavidades.

\n
\n\n
\n

Visualización de datos de desempeño

\n

La pestaña Gráficas muestra el historial de tendencias de OEE desglosado por Disponibilidad, Desempeño y Calidad. Usa estas gráficas para identificar patrones, dar seguimiento a mejoras y diagnosticar problemas recurrentes que afecten la eficiencia de tu producción

\n
\n
\n
\n
\n\n\n", + "storeOutMessages": true, + "fwdInMessages": true, + "resendOnRefresh": true, + "templateScope": "local", + "className": "", + "x": 380, + "y": 440, + "wires": [ + [ + "44d2ce4b810b508b" + ] + ] + }, + { + "id": "afb514404a6ecda1", + "type": "ui_template", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "group": "e5f6a7b8c9d0e1f2", + "name": "Settings Template", + "order": 0, + "width": "25", + "height": "25", + "format": "\n
\n \n\n
\n
\n
\n

Ajustes

\n
\n\n
\n

Moldes Preconfigurados

\n
\n
\n \n \n
\n
\n \n \n
\n
\n\n
\n \n
\n

Seleccionar un fabricante y el molde de las siguientes opciones.

\n
\n\n \n
\n
\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n \n \n
\n
\n
\n
\n\n
\n

Configuraciones de Molde

\n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n\n
\n

Integraciones

\n
\n
\n \n
\n
\n

No encuentras lo que buscas?

\n \n
\n
\n
\n
\n

Enlace Control Tower

\n

Ingresa el codigo de 5 caracteres que aparece en Control Tower para enlazar esta Raspberry Pi.

\n
\n
\n \n \n
\n
\n \n
\n
\n

{{ pairingStatus }}

\n
\n
\n

WiFi

\n

Conecta esta Raspberry Pi a una red WiFi (sin salir del dashboard).

\n \n
\n
\n \n \n
\n \n
\n \n \n
\n
\n \n
\n
\n \n \n
\n \n
\n \n \n
\n
\n \n
\n \n \n \n \n \n
\n \n

\n {{ wifiStatusText }}\n

\n
\n
\n

Programación de Producción

\n\n \n
\n
\n \n
\n
\n\n
\n
\n \n \n
\n
\n \n \n
\n
1\">\n \n
\n
\n\n \n\n \n
\n
\n \n \n
\n
\n \n \n
\n
\n
\n
\n \n \n {{ saveStatus }}\n \n
\n\n
\n

Umbral OEE

\n
\n
\n \n \n

\n Gap > (Cycle Time × {{thresholdMultiplier || 1.5}}) = Stoppage\n

\n
\n
\n \n \n
\n
\n
\n
\n
\n
\n\n", + "storeOutMessages": true, + "fwdInMessages": true, + "resendOnRefresh": true, + "templateScope": "local", + "className": "", + "x": 390, + "y": 480, + "wires": [ + [ + "44d2ce4b810b508b", + "c0dd0940ec7f53ba", + "fe77ffa843b0dcfb" + ] + ] + }, + { + "id": "b1a448897989958f", + "type": "ui_template", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "group": "b99c269687d574aa", + "name": "WO Template", + "order": 1, + "width": "25", + "height": "25", + "format": "\n
\n \n\n
\n
\n
\n

Ordenes de trabajo

\n
\n \n 0 selected\n \n \n \n \n \n \n \n
\n
\n\n
\n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
IDSKUMETABUENASSCRAPPROGRESOSTATUSULTIMA ACTUALIZACIÓN
\n
\n
\n 0 items\n Tip: Dejale picado para seleccionar multiples ordenes\n
\n
\n
\n
\n
\n\n\n", + "storeOutMessages": true, + "fwdInMessages": true, + "resendOnRefresh": true, + "templateScope": "local", + "className": "", + "x": 380, + "y": 320, + "wires": [ + [ + "44d2ce4b810b508b", + "ad66f1edaba40aaa" + ] + ] + }, + { + "id": "44d2ce4b810b508b", + "type": "function", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "Tab navigation", + "func": "if (msg.ui_control && msg.ui_control.tab) {\n msg.payload = { tab: msg.ui_control.tab };\n delete msg.ui_control;\n return msg;\n}\nreturn null;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 620, + "y": 380, + "wires": [ + [ + "5dd7945ae90715a0" + ] + ] + }, + { + "id": "5dd7945ae90715a0", + "type": "ui_ui_control", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "ui_control", + "events": "all", + "x": 800, + "y": 380, + "wires": [ + [] + ] + }, + { + "id": "bfa9fe745d22c79a", + "type": "ui_template", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "group": "", + "name": "General Style", + "order": 0, + "width": 0, + "height": 0, + "format": "", + "storeOutMessages": true, + "fwdInMessages": true, + "resendOnRefresh": true, + "templateScope": "global", + "className": "", + "x": 760, + "y": 300, + "wires": [ + [] + ] + }, + { + "id": "9748899355370bae", + "type": "ui_template", + "z": "05d4cb231221b842", + "g": "d9a9ee7bc71b0f53", + "group": "919b5b8d778e2b6c", + "name": "Anomaly Alert System (Global)", + "order": 1, + "width": "25", + "height": "25", + "format": "\n\n\n\n\n\n
\n
\n

Active Alerts

\n \n
\n\n
\n
\n
\n

No active alerts

\n

All systems operating normally

\n
\n\n
\n
\n

{{anomaly.title}}

\n {{anomaly.severity}}\n
\n

{{anomaly.description}}

\n

{{formatTimestamp(anomaly.tsMs)}}

\n
\n \n
\n
\n
\n
\n\n\n
\n
\n
\n

{{popup.title}}

\n \n
\n

{{popup.description}}

\n \n
\n
\n\n
\n
\n

Selecciona razón de paro

\n

{{reasonPrompt.anomalyTitle || 'Incidente de downtime'}}

\n
\n Paso {{reasonPrompt.step}} de 2\n | {{reasonPrompt.selectedCategory.label}}\n
\n\n
\n \n
\n\n
\n \n
\n\n
\n \n \n
\n
\n
\n\n\n", + "storeOutMessages": true, + "fwdInMessages": true, + "resendOnRefresh": true, + "templateScope": "local", + "className": "", + "x": 430, + "y": 60, + "wires": [ + [ + "4ee66ceb859b7cf1", + "adba20c2e33f1b18" + ] + ] + }, + { + "id": "4ee66ceb859b7cf1", + "type": "function", + "z": "05d4cb231221b842", + "g": "d9a9ee7bc71b0f53", + "name": "Handle Anomaly Acknowledgment", + "func": "// Handle anomaly acknowledgments and downtime-reason submit.\n// Output 1: SQL update for anomaly_events\n// Output 2: event payload for Build Event Outbox Payload\nconst anomaly = global.get(\"anomaly\") || {};\nconst topic = msg.topic || \"\";\n\nfunction persistAnomaly(next) {\n global.set(\"anomaly\", next);\n try {\n global.set(\"anomaly\", next, \"file\");\n } catch (err) {\n // ignore if file store is not configured\n }\n}\n\nfunction parseReason(payload) {\n const reasonPath = Array.isArray(payload.reasonPath) ? payload.reasonPath : [];\n const category = reasonPath[0] || {};\n const detail = reasonPath[1] || {};\n return {\n type: payload.reasonType || \"downtime\",\n categoryId: category.id || null,\n categoryLabel: category.label || null,\n detailId: detail.id || null,\n detailLabel: detail.label || null,\n reasonText: payload.reasonText || [\n category.label || \"\",\n detail.label || \"\"\n ].filter(Boolean).join(\" > \") || null,\n catalogVersion: payload.catalogVersion || null,\n incidentKey: payload.incidentKey || payload.incident_key || null\n };\n}\n\nfunction removeFromActive(eventId) {\n let activeAnomalies = anomaly.activeAnomalies || [];\n const idx = activeAnomalies.findIndex((a) => a.event_id === eventId || a.tsMs === eventId);\n if (idx !== -1) {\n activeAnomalies.splice(idx, 1);\n anomaly.activeAnomalies = activeAnomalies;\n }\n}\n\nif (topic === \"acknowledge-anomaly\" || topic === \"anomaly-reason-submit\") {\n const ackData = msg.payload || {};\n const eventId = ackData.event_id ?? ackData.tsMs;\n const ackTimestamp = typeof ackData.tsMs === \"number\" ? ackData.tsMs : Date.now();\n const incidentKey = ackData.incidentKey || ackData.incident_key || null;\n\n if (!eventId) {\n node.warn(\"[ANOMALY ACK] No event_id provided\");\n return null;\n }\n\n if (String(eventId).startsWith(\"temp_\")) {\n removeFromActive(eventId);\n persistAnomaly(anomaly);\n return null;\n }\n\n const sql = (\n \"UPDATE anomaly_events \" +\n \"SET status = 'acknowledged', acknowledged_at = \" + Number(ackTimestamp) + \" \" +\n \"WHERE event_timestamp = \" + Number(eventId)\n );\n const dbMsg = { topic: sql, payload: [] };\n\n removeFromActive(eventId);\n\n if (topic === \"anomaly-reason-submit\") {\n anomaly.reasonsByIncident = anomaly.reasonsByIncident || {};\n anomaly.ackedIncidentKeys = anomaly.ackedIncidentKeys || {};\n\n const reason = parseReason(ackData);\n if (incidentKey) {\n anomaly.reasonsByIncident[incidentKey] = reason;\n anomaly.ackedIncidentKeys[incidentKey] = true;\n }\n\n persistAnomaly(anomaly);\n\n const alreadySent = !!(incidentKey && anomaly.reasonEventsSent && anomaly.reasonEventsSent[incidentKey]);\n if (alreadySent) {\n return [dbMsg, null];\n }\n\n if (incidentKey) {\n anomaly.reasonEventsSent = anomaly.reasonEventsSent || {};\n anomaly.reasonEventsSent[incidentKey] = true;\n persistAnomaly(anomaly);\n }\n\n const eventTsMs = Number(ackData.tsMs) || Date.now();\n const anomalyType = ackData.anomalyType || ackData.anomaly_type || \"downtime\";\n const outEvent = {\n tsMs: eventTsMs,\n eventType: \"downtime-acknowledged\",\n anomalyType,\n eventId: eventId,\n incidentKey: incidentKey || null,\n // Keep reason attached to generic event payload for current ingest.\n reason,\n // Explicit separation for future split in Control Tower.\n downtime: {\n incidentKey: incidentKey || null,\n eventId: eventId,\n anomalyType,\n acknowledgedAtMs: eventTsMs,\n reason\n }\n };\n\n return [{ ...dbMsg }, { payload: outEvent, tsMs: eventTsMs }];\n }\n\n if (incidentKey) {\n anomaly.ackedIncidentKeys = anomaly.ackedIncidentKeys || {};\n anomaly.ackedIncidentKeys[incidentKey] = true;\n }\n persistAnomaly(anomaly);\n\n return [dbMsg, null];\n}\n\nreturn null;\n", + "outputs": 2, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 720, + "y": 60, + "wires": [ + [ + "8e60972fea4bd36a" + ], + [ + "bf17a2d4b88f7694" + ] + ] + }, + { + "id": "a819f394fe7fc6aa", + "type": "inject", + "z": "05d4cb231221b842", + "g": "6e514144a570aa72", + "name": "Simula Inyectora", + "props": [ + { + "p": "payload" + } + ], + "repeat": "", + "crontab": "", + "once": false, + "onceDelay": 0.1, + "topic": "", + "payload": "1", + "payloadType": "num", + "x": 1260, + "y": 180, + "wires": [ + [ + "05112cf4f0821cfd", + "25dfb62e7131af6b", + "b219495329321d63", + "482feffe728ab41a" + ] + ] + }, + { + "id": "86b533aacff8b212", + "type": "function", + "z": "05d4cb231221b842", + "g": "6e514144a570aa72", + "name": "1,0", + "func": "// Get current global value (default to 0 if not set)\nconst state = global.get(\"state\") || {};\nlet estado = state.machineToggle || 0;\nlet stop = flow.get('stop') || false;\n\nif (stop) {\n // Manual stop active → force 0, don't reschedule\n state.machineToggle = 0;\nglobal.set(\"state\", state);\n msg.payload = 0;\n node.send(msg);\n return;\n}\n\n// Toggle between 1 and 0\nestado = estado === 1 ? 0 : 1;\n\n// Update the global variable\nstate.machineToggle = estado;\nglobal.set(\"state\", state);\n\n// Send it out\nmsg.payload = estado;\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1670, + "y": 200, + "wires": [ + [ + "093d9631fbd43003" + ] + ] + }, + { + "id": "dc743dbc93f7b7ad", + "type": "function", + "z": "05d4cb231221b842", + "g": "878b79013722e91f", + "name": "Cavities Settings", + "func": "const settings = global.get(\"settings\") || {};\nconst state = global.get(\"state\") || {};\nconst moldByWorkOrder = state.moldByWorkOrder || {};\n\nconst persistSettings = () => {\n global.set(\"settings\", settings);\n try {\n global.set(\"settings\", settings, \"file\");\n } catch (err) {\n // ignore if file store is not configured\n }\n};\n\nconst persistMoldCache = () => {\n const cache = {\n lastMoldActive: state.lastMoldActive ?? null,\n lastMoldTotal: state.lastMoldTotal ?? null,\n moldByWorkOrder: state.moldByWorkOrder || {}\n };\n global.set(\"moldCache\", cache);\n try {\n global.set(\"moldCache\", cache, \"file\");\n } catch (err) {\n // ignore if file store is not configured\n }\n};\n\nconst persistState = () => {\n global.set(\"state\", state);\n};\n\nconst persistMoldSelection = (total, active) => {\n if (!Number.isFinite(active) || active <= 0) return;\n state.lastMoldActive = active;\n if (Number.isFinite(total) && total > 0) {\n state.lastMoldTotal = total;\n }\n if (state.activeWorkOrder?.id) {\n state.activeWorkOrder.cavities = active;\n if (Number.isFinite(total) && total > 0) {\n state.activeWorkOrder.cavities_total = total;\n }\n moldByWorkOrder[state.activeWorkOrder.id] = {\n total: Number.isFinite(total) && total > 0 ? total : (state.lastMoldTotal ?? null),\n active\n };\n }\n state.moldByWorkOrder = moldByWorkOrder;\n persistState();\n persistMoldCache();\n};\n\nconst buildCavitiesUpdate = (total, active) => {\n const activeId = state.activeWorkOrder?.id;\n if (!activeId || !Number.isFinite(active) || active <= 0) return null;\n const totalSafe = Number.isFinite(total) && total > 0 ? total : 0;\n return {\n topic: \"UPDATE work_orders SET cavities_total = COALESCE(NULLIF(?,0), cavities_total), cavities_active = COALESCE(NULLIF(?,0), cavities_active), updated_at = NOW() WHERE work_order_id = ?\",\n payload: [totalSafe, active, activeId]\n };\n};\n\nif (msg.topic === \"moldSettings\" && msg.payload) {\n const total = Number(msg.payload.total || 0);\n const active = Number(msg.payload.active || 0);\n\n // Store settings\n settings.moldTotal = total;\n settings.moldActive = active;\n persistSettings();\n\n persistMoldSelection(total, active);\n\n node.status({ fill: \"green\", shape: \"dot\", text: `Saved: ${active}/${total}` });\n\n const dbMsg = buildCavitiesUpdate(total, active);\n\n msg.payload = { saved: true, total, active };\n return [msg, dbMsg];\n}\n\n// Handle preset selection\nif (msg.topic === \"selectMoldPreset\" && msg.payload) {\n const preset = msg.payload;\n const total = Number(preset.theoretical_cavities || 0);\n const active = Number(preset.functional_cavities || 0);\n\n // Store settings\n settings.moldTotal = total;\n settings.moldActive = active;\n persistSettings();\n\n persistMoldSelection(total, active);\n\n node.status({ fill: \"blue\", shape: \"dot\", text: `Preset: ${preset.mold_name}` });\n\n // Send to UI to update fields\n msg.topic = \"moldPresetSelected\";\n msg.payload = { total, active, presetName: preset.mold_name };\n\n const dbMsg = buildCavitiesUpdate(total, active);\n\n return [msg, dbMsg];\n}\n\n//node.status({ fill: \"red\", shape: \"ring\", text: \"Invalid payload\" });\nreturn [null, null];", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 470, + "y": 600, + "wires": [ + [ + "4056bc6a05189ca8" + ] + ] + }, + { + "id": "9e5a27b63b362466", + "type": "function", + "z": "05d4cb231221b842", + "g": "878b79013722e91f", + "name": "Mold Presets Handler", + "func": "const topic = msg.topic || '';\nconst payload = msg.payload || {};\n\n// ===== IGNORE NON-MOLD TOPICS SILENTLY =====\n// These are KPI/dashboard messages not meant for this handler\nconst ignoredTopics = [\n 'machineStatus',\n 'kpis',\n 'chartsData',\n 'activeWorkOrder',\n 'workOrderCycle',\n 'workOrdersList',\n 'scrapPrompt',\n 'uploadStatus'\n];\n\nif (ignoredTopics.includes(topic) || topic === '') {\n return null; // Silent ignore\n}\n\n// Log only mold-related requests\nnode.warn(`Received: ${topic}`);\n\n// CRITICAL: Use a processing lock to prevent simultaneous requests\nlet dedupeKey = topic;\nif (topic === 'addMoldPreset') {\n dedupeKey = `add_${payload.manufacturer}_${payload.mold_name}`;\n} else if (topic === 'getMoldsByManufacturer') {\n dedupeKey = `getmolds_${payload.manufacturer}`;\n}\n\nconst lockKey = `lock_${dedupeKey}`;\nconst lastRequestKey = `last_request_${dedupeKey}`;\n\n// Check if currently processing this request\nif (flow.get(lockKey) === true) {\n node.warn(`${topic} already processing - duplicate blocked`);\n return null;\n}\n\n// Check timing\nconst now = Date.now();\nconst lastRequestTime = flow.get(lastRequestKey) || 0;\nif (now - lastRequestTime < 2000) {\n node.warn(`Duplicate ${topic} request ignored (within 2s)`);\n return null;\n}\n\n// Set lock IMMEDIATELY before any async operations\nflow.set(lockKey, true);\nflow.set(lastRequestKey, now);\n\n// Release lock after 3 seconds (safety timeout)\nsetTimeout(() => {\n flow.set(lockKey, false);\n}, 3000);\n\n// Load all presets (legacy)\nif (topic === 'loadMoldPresets') {\n msg._originalTopic = 'loadMoldPresets';\n msg.topic = 'SELECT * FROM mold_presets ORDER BY manufacturer, mold_name;';\n node.warn('Querying all presets');\n return msg;\n}\n\n// Search/filter presets (legacy)\nif (topic === 'searchMoldPresets') {\n const filters = msg.payload || {};\n const searchTerm = (filters.searchTerm || '').trim().replace(/['\\\"\\\\\\\\]/g, '');\n const manufacturer = (filters.manufacturer || '').replace(/['\\\"\\\\\\\\]/g, '');\n const theoreticalCavities = filters.theoreticalCavities || '';\n\n let query = 'SELECT * FROM mold_presets WHERE 1=1';\n\n if (searchTerm) {\n const searchPattern = `%${searchTerm}%`;\n query += ` AND (mold_name LIKE '${searchPattern.replace(/'/g, \"''\")}' OR manufacturer LIKE '${searchPattern.replace(/'/g, \"''\")}')`;\n }\n\n if (manufacturer && manufacturer !== 'All') {\n query += ` AND manufacturer = '${manufacturer.replace(/'/g, \"''\")}'`;\n }\n\n if (theoreticalCavities && theoreticalCavities !== '') {\n const cavities = Number(theoreticalCavities);\n if (!isNaN(cavities)) {\n query += ` AND theoretical_cavities = ${cavities}`;\n }\n }\n\n query += ' ORDER BY manufacturer, mold_name;';\n\n msg._originalTopic = 'searchMoldPresets';\n msg.topic = query;\n return msg;\n}\n\n// Get unique manufacturers for dropdown\nif (topic === 'getManufacturers') {\n msg._originalTopic = 'getManufacturers';\n msg.topic = 'SELECT DISTINCT manufacturer FROM mold_presets ORDER BY manufacturer;';\n node.warn('Querying manufacturers');\n return msg;\n}\n\n// Get molds for a specific manufacturer\nif (topic === 'getMoldsByManufacturer') {\n const data = msg.payload || {};\n const manufacturerRaw = (data.manufacturer || '').trim();\n if (!manufacturerRaw) {\n node.warn('No manufacturer provided');\n return null;\n }\n\n const manufacturerSafe = manufacturerRaw.replace(/['\\\"\\\\\\\\]/g, '').replace(/'/g, \"''\");\n\n msg._originalTopic = 'getMoldsByManufacturer';\n msg.topic = `SELECT * FROM mold_presets WHERE manufacturer = '${manufacturerSafe}' ORDER BY mold_name;`;\n node.warn(`Querying molds for: ${manufacturerSafe}`);\n return msg;\n}\n\n// Add a new mold preset - CRITICAL: Strong deduplication\nif (topic === 'addMoldPreset') {\n const data = msg.payload || {};\n const manufacturerRaw = (data.manufacturer || '').trim();\n const moldNameRaw = (data.mold_name || '').trim();\n const theoreticalRaw = (data.theoretical || '').trim();\n const activeRaw = (data.active || '').trim();\n\n if (!manufacturerRaw || !moldNameRaw || !theoreticalRaw || !activeRaw) {\n node.status({ fill: 'red', shape: 'ring', text: 'Missing value' });\n node.warn('Missing required fields');\n return null;\n }\n\n // Additional safety check for already-processed flag\n if (msg._addMoldProcessed) {\n node.warn('addMoldPreset already processed flag detected, ignoring');\n return null;\n }\n msg._addMoldProcessed = true;\n\n const manufacturerSafe = manufacturerRaw.replace(/['\\\"\\\\\\\\]/g, '').replace(/'/g, \"''\");\n const moldNameSafe = moldNameRaw.replace(/['\\\"\\\\\\\\]/g, '').replace(/'/g, \"''\");\n const theoreticalSafe = theoreticalRaw.replace(/['\\\"\\\\\\\\]/g, '').replace(/'/g, \"''\");\n const activeSafe = activeRaw.replace(/['\\\"\\\\\\\\]/g, '').replace(/'/g, \"''\");\n\n msg._originalTopic = 'addMoldPreset';\n msg.topic =\n \"INSERT INTO mold_presets (manufacturer, mold_name, theoretical_cavities, functional_cavities) \" +\n \"VALUES ('\" + manufacturerSafe + \"', '\" + moldNameSafe + \"', \" + theoreticalSafe + \", \" + activeSafe + \");\";\n\n node.status({ fill: 'blue', shape: 'dot', text: 'Inserting mold...' });\n node.warn(`Inserting: ${manufacturerSafe} - ${moldNameSafe}`);\n return msg;\n}\n\nnode.warn(`Unknown topic: ${topic}`);\nreturn null;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 400, + "y": 660, + "wires": [ + [ + "5542672209bd0479" + ] + ] + }, + { + "id": "5542672209bd0479", + "type": "mysql", + "z": "05d4cb231221b842", + "g": "878b79013722e91f", + "mydb": "fc9634aabefee16b", + "name": "Mold Presets DB", + "x": 610, + "y": 660, + "wires": [ + [ + "4056bc6a05189ca8" + ] + ] + }, + { + "id": "4056bc6a05189ca8", + "type": "function", + "z": "05d4cb231221b842", + "g": "878b79013722e91f", + "name": "Process DB Results", + "func": "// Replace function in \"Process DB Results\" node\n\nconst originalTopic = msg._originalTopic || '';\nconst dbResults = Array.isArray(msg.payload) ? msg.payload : [];\n\nif (!originalTopic) {\n return null;\n}\n\n// IMPORTANT: Clear socketid to prevent loops back to sender\ndelete msg._socketid;\ndelete msg.socketid;\n\n// Manufacturers query → list for first dropdown\nif (originalTopic === 'getManufacturers') {\n const manufacturers = dbResults\n .map(row => row.manufacturer)\n .filter((mfg, index, arr) => mfg && arr.indexOf(mfg) === index)\n .sort();\n\n msg.topic = 'manufacturersList';\n msg.payload = manufacturers;\n\n node.status({ fill: 'green', shape: 'dot', text: `${manufacturers.length} manufacturers` });\n return msg;\n}\n\n// Preset lists (legacy load/search)\nif (originalTopic === 'loadMoldPresets' || originalTopic === 'searchMoldPresets') {\n const presets = dbResults.map(row => ({\n mold_name: row.mold_name || '',\n manufacturer: row.manufacturer || '',\n theoretical_cavities: Number(row.theoretical_cavities) || 0,\n functional_cavities: Number(row.functional_cavities) || 0\n }));\n\n msg.topic = 'moldPresetsList';\n msg.payload = presets;\n\n node.status({ fill: 'green', shape: 'dot', text: `${presets.length} presets found` });\n return msg;\n}\n\n// Molds for selected manufacturer\nif (originalTopic === 'getMoldsByManufacturer') {\n const presets = dbResults.map(row => ({\n mold_name: row.mold_name || '',\n manufacturer: row.manufacturer || '',\n theoretical_cavities: Number(row.theoretical_cavities) || 0,\n functional_cavities: Number(row.functional_cavities) || 0\n }));\n\n msg.topic = 'moldPresetsList';\n msg.payload = presets;\n\n node.status({ fill: 'blue', shape: 'dot', text: `${presets.length} molds for manufacturer` });\n return msg;\n}\n\n// Result of inserting a new mold\nif (originalTopic === 'addMoldPreset') {\n msg.topic = 'addMoldResult';\n msg.payload = {\n success: true,\n result: msg.payload\n };\n\n node.status({ fill: 'green', shape: 'dot', text: 'Mold added' });\n return msg;\n}\n\nnode.status({ fill: 'yellow', shape: 'ring', text: 'Unknown topic: ' + originalTopic });\nreturn null;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 740, + "y": 600, + "wires": [ + [ + "4101967d16ba7f8b" + ] + ] + }, + { + "id": "c0dd0940ec7f53ba", + "type": "link out", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "link out 1", + "mode": "link", + "links": [ + "3a5788e9d86542d0" + ], + "x": 505, + "y": 480, + "wires": [] + }, + { + "id": "3a5788e9d86542d0", + "type": "link in", + "z": "05d4cb231221b842", + "g": "878b79013722e91f", + "name": "link in 1", + "links": [ + "c0dd0940ec7f53ba" + ], + "x": 215, + "y": 660, + "wires": [ + [ + "dc743dbc93f7b7ad", + "9e5a27b63b362466", + "ba626f3a3b37e653", + "063447515a79e473" + ] + ] + }, + { + "id": "204c7a49f98a9944", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Work Order buttons", + "func": "const config = global.get(\"config\") || {};\nconst settings = global.get(\"settings\") || {};\nconst state = global.get(\"state\") || {};\nconst reasonCatalog = settings.reasonCatalog || {};\n\n// ✨ La WO de la BD es la única fuente de cavidades.\n// attachMold solo normaliza nombres (cavities/cavitiesActive, cavities_total/cavitiesTotal)\n// para que el resto del código pueda leerlos con cualquier alias.\n// YA NO escribe en state.lastMoldActive ni state.moldByWorkOrder (cache global eliminado).\nconst attachMold = (order) => {\n if (!order || !order.id) return;\n\n const cavities = Number(\n order.cavitiesActive ??\n order.cavities_active ??\n order.cavities ??\n 0\n );\n const total = Number(\n order.cavitiesTotal ??\n order.cavities_total ??\n 0\n );\n\n if (Number.isFinite(cavities) && cavities > 0) {\n order.cavitiesActive = cavities;\n order.cavities = cavities; // alias para código viejo\n }\n if (Number.isFinite(total) && total > 0) {\n order.cavitiesTotal = total;\n order.cavities_total = total; // alias para código viejo\n }\n};\n\nconst finalize = (ret) => {\n global.set(\"state\", state);\n return ret;\n};\n\nconst normalizeReason = (payload, fallbackType) => {\n const path = Array.isArray(payload.reasonPath) ? payload.reasonPath : [];\n const category = path[0] || {};\n const detail = path[1] || {};\n return {\n type: payload.reasonType || fallbackType || \"downtime\",\n categoryId: category.id || null,\n categoryLabel: category.label || null,\n detailId: detail.id || null,\n detailLabel: detail.label || null,\n reasonText: payload.reasonText || [\n category.label || \"\",\n detail.label || \"\"\n ].filter(Boolean).join(\" > \") || null,\n catalogVersion: payload.catalogVersion || reasonCatalog.version || null,\n incidentKey: payload.incidentKey || null\n };\n};\n\n\n// ===== MOLD CHANGE AUTO-CLOSE =====\n// If a mold change is active and user is starting/resuming/restarting a WO, close it.\nif (state.moldChange && state.moldChange.active &&\n (msg.action === \"start\" || msg.action === \"start-work-order\" || msg.action === \"resume-work-order\" || msg.action === \"restart-work-order\")) {\n const now = Date.now();\n const mc = state.moldChange;\n const durationSec = Math.max(0, Math.round((now - (mc.startMs || now)) / 1000));\n const closedMc = {\n active: false,\n startMs: mc.startMs,\n endMs: now,\n fromMoldId: mc.fromMoldId || null,\n toMoldId: null,\n durationSec\n };\n state.moldChange = closedMc;\n global.set(\"state\", state);\n const closeEvent = {\n payload: {\n anomaly_type: \"mold-change\",\n eventType: \"mold-change\",\n severity: \"info\",\n requires_ack: false,\n title: \"Cambio de molde finalizado (automatico)\",\n description: \"Duracion: \" + Math.round(durationSec / 60) + \" min\",\n status: \"resolved\",\n tsMs: now,\n data: {\n status: \"resolved\",\n start_ms: closedMc.startMs,\n end_ms: now,\n duration_sec: durationSec,\n stoppage_duration_seconds: durationSec,\n from_mold_id: closedMc.fromMoldId,\n to_mold_id: closedMc.toMoldId,\n incidentKey: \"mold-change:\" + (closedMc.startMs || now)\n }\n },\n tsMs: now\n };\n const uiClose = { _mode: \"mold-change-status\", payload: { active: false, endMs: now, durationSec } };\n node.send([null, uiClose, null, null, null, closeEvent]);\n}\n\nconst mode = msg._mode || '';\nswitch (msg.action) {\n case \"upload-excel\":\n msg._mode = \"upload\";\n return finalize([msg, null, null, null]);\n case \"refresh-work-orders\": {\n const selectMsg = {\n ...msg,\n _mode: \"select\",\n topic: \"SELECT * FROM work_orders ORDER BY created_at DESC;\"\n };\n const fetchMsg = {\n ...msg,\n topic: \"workOrdersRefresh\",\n forceRefresh: true,\n payload: msg.payload && typeof msg.payload === \"object\" ? msg.payload : {}\n };\n return finalize([null, selectMsg, null, null, null, null, fetchMsg]);\n }\n case \"start-work-order\": {\n msg._mode = \"start-check-progress\";\n const order = msg.payload || {};\n if (!order.id) {\n node.error(\"No work order id supplied for start\", msg);\n return finalize([null, null, null, null]);\n }\n\n // ✨ FIX: pausar inmediatamente la WO actual antes de cargar la nueva.\n // Previene que se sumen ciclos a la WO anterior mientras llega el resume-prompt.\n if (state.activeWorkOrder && state.activeWorkOrder.id !== order.id) {\n node.warn(`[START-WO] Pausando WO actual ${state.activeWorkOrder.id} antes de cargar ${order.id}`);\n state.trackingEnabled = false;\n state.productionStarted = false;\n flow.set(\"lastMachineState\", 0);\n\n // ✨ También sincronizar state.lastState para que el polling cada 500ms\n // del HMI (get-current-state) no devuelva valores viejos al template\n // y reactive el botón DETENER.\n if (state.lastState && typeof state.lastState === \"object\") {\n state.lastState = {\n ...state.lastState,\n trackingEnabled: false,\n productionStarted: false,\n tsMs: Date.now()\n };\n }\n }\n flow.set(\"pendingWorkOrder\", order);\n\n msg.topic = \"SELECT cycle_count, good_parts, scrap_parts, progress_percent, target_qty, cavities_total, cavities_active FROM work_orders WHERE work_order_id = ? LIMIT 1\";\n msg.payload = [order.id];\n\n return finalize([null, msg, null, null]);\n }\n case \"resume-work-order\": {\n const now = Date.now();\n state.productionStartTime = now;\n state.actualRunTime = 0;\n state.lastStartChangeTime = now;\n state.runSeconds = 0;\n state.stopSeconds = 0;\n state.kpiLastTick = null;\n msg._mode = \"resume\";\n const order = msg.payload || {};\n if (!order.id) {\n node.error(\"No work order id supplied for resume\", msg);\n return finalize([null, null, null, null]);\n }\n\n // Set status to RUNNING without resetting progress\n msg.topic = \"UPDATE work_orders SET status = CASE WHEN work_order_id = ? THEN 'RUNNING' ELSE 'PENDING' END, updated_at = CASE WHEN work_order_id = ? THEN NOW() ELSE updated_at END, cavities_total = COALESCE(NULLIF(?,0), cavities_total), cavities_active = COALESCE(NULLIF(?,0), cavities_active) WHERE status <> 'DONE'\";\n // ✨ Acepta cavitiesActive (nuevo) o cavities (alias viejo)\n msg.payload = [\n order.id,\n order.id,\n Number(order.cavitiesTotal || order.cavities_total || 0),\n Number(order.cavitiesActive || order.cavities_active || order.cavities || 0)\n ];\n msg.startOrder = order;\n\n // Load existing values into global state\n order.scrapParts = Number(order.scrapParts) || 0;\n order.goodParts = Number(order.goodParts) || 0;\n\n attachMold(order);\n\n state.activeWorkOrder = order;\n state.cycleCount = Number(order.cycleCount) || 0;\n state.activeOrderHasProgress = true;\n flow.set(\"lastMachineState\", 0);\n state.scrapPromptIssuedFor = null;\n\n return finalize([null, null, msg, null]);\n }\n case \"restart-work-order\": {\n const now = Date.now();\n state.productionStartTime = now;\n state.actualRunTime = 0;\n state.lastStartChangeTime = now;\n state.runSeconds = 0;\n state.stopSeconds = 0;\n state.kpiLastTick = null;\n msg._mode = \"restart\";\n const order = msg.payload || {};\n if (!order.id) {\n node.error(\"No work order id supplied for restart\", msg);\n return finalize([null, null, null, null]);\n }\n\n // Reset progress in database AND set status to RUNNING\n msg.topic = \"UPDATE work_orders SET status = CASE WHEN work_order_id = ? THEN 'RUNNING' ELSE 'PENDING' END, cycle_count = 0, good_parts = 0, scrap_parts = 0, progress_percent = 0, updated_at = NOW(), cavities_total = COALESCE(NULLIF(?,0), cavities_total), cavities_active = COALESCE(NULLIF(?,0), cavities_active) WHERE work_order_id = ? OR status = 'RUNNING'\";\n // ✨ Acepta cavitiesActive (nuevo) o cavities (alias viejo)\n msg.payload = [\n order.id,\n order.id,\n Number(order.cavitiesTotal || order.cavities_total || 0),\n Number(order.cavitiesActive || order.cavities_active || order.cavities || 0),\n order.id\n ];\n msg.startOrder = order;\n\n // Initialize global state to 0\n order.scrapParts = 0;\n order.goodParts = 0;\n\n attachMold(order);\n\n state.activeWorkOrder = order;\n state.cycleCount = 0;\n state.activeOrderHasProgress = false;\n flow.set(\"lastMachineState\", 0);\n state.scrapPromptIssuedFor = null;\n\n return finalize([null, null, msg, null]);\n }\n case \"complete-work-order\": {\n state.productionStartTime = null;\n state.runSeconds = 0;\n state.stopSeconds = 0;\n state.kpiLastTick = null;\n msg._mode = \"complete\";\n const order = msg.payload || {};\n if (!order.id) {\n node.error(\"No work order id supplied for complete\", msg);\n return finalize([null, null, null, null]);\n }\n\n // Get final values from global state before clearing\n const activeOrder = state.activeWorkOrder || {};\n const finalCycleCount = Number(state.cycleCount || 0);\n const finalGoodParts = Number(activeOrder.goodParts) || 0;\n const finalScrapParts = Number(activeOrder.scrapParts) || 0;\n\n msg.completeOrder = order;\n\n // SQL: Persist final counts AND set status to DONE\n msg.topic = \"UPDATE work_orders SET status = 'DONE', cycle_count = ?, good_parts = ?, scrap_parts = ?, progress_percent = 100, updated_at = NOW() WHERE work_order_id = ?\";\n msg.payload = [finalCycleCount, finalGoodParts, finalScrapParts, order.id];\n\n // Clear ALL state on completion\n state.activeWorkOrder = null;\n state.activeOrderHasProgress = false;\n state.trackingEnabled = false;\n state.productionStarted = false;\n state.kpiStartupMode = false;\n state.operatingTime = 0;\n state.lastCycleTime = null;\n state.cycleCount = 0;\n flow.set(\"lastMachineState\", 0);\n state.scrapPromptIssuedFor = null;\n state.actualRunTime = 0;\n state.lastStateChangeTime = null;\n\n if (state.lastState && typeof state.lastState === \"object\") {\n state.lastState = {\n ...state.lastState,\n activeWorkOrder: null,\n cycleCount: 0,\n goodParts: 0,\n scrapParts: 0,\n cycleTime: 0,\n actualCycleTime: 0,\n trackingEnabled: false,\n productionStarted: false,\n tsMs: Date.now()\n };\n }\n\n // ============================================================\n // HIGH SCRAP DETECTION\n // ============================================================\n const targetQty = Number(activeOrder.target) || 0;\n const scrapCount = finalScrapParts;\n const scrapPercent = targetQty > 0 ? (scrapCount / targetQty) * 100 : 0;\n\n let anomalyMsg = null;\n if (scrapPercent > 10 && targetQty > 0) {\n const severity = scrapPercent > 25 ? 'critical' : 'warning';\n\n const highScrapAnomaly = {\n anomaly_type: 'high-scrap',\n severity: severity,\n title: `High Waste Detected`,\n description: `Work order completed with ${scrapCount} scrap parts (${scrapPercent.toFixed(1)}% of target ${targetQty}). Why is there so much waste?`,\n data: {\n scrap_count: scrapCount,\n target_quantity: targetQty,\n scrap_percent: Math.round(scrapPercent * 10) / 10,\n good_parts: finalGoodParts,\n total_cycles: finalCycleCount\n },\n kpi_snapshot: {\n oee: (msg.kpis && msg.kpis.oee) || state.currentKPIs?.oee || 0,\n availability: (msg.kpis && msg.kpis.availability) || state.currentKPIs?.availability || 0,\n performance: (msg.kpis && msg.kpis.performance) || state.currentKPIs?.performance || 0,\n quality: (msg.kpis && msg.kpis.quality) || state.currentKPIs?.quality || 0\n },\n work_order_id: order.id,\n cycle_count: finalCycleCount,\n tsMs: Date.now(),\n status: 'active'\n };\n\n anomalyMsg = {\n topic: \"anomaly-detected\",\n payload: [highScrapAnomaly]\n };\n }\n\n return finalize([null, null, null, msg, anomalyMsg]);\n }\n case \"get-current-state\": {\n // Single truth for UI: state.lastState\n const s = state.lastState || {};\n\n const validWorkOrders = state.workOrdersById || null;\n if (state.activeWorkOrder?.id && validWorkOrders && !validWorkOrders[state.activeWorkOrder.id]) {\n node.warn(`[STATE] activeWorkOrder ${state.activeWorkOrder.id} not in work order list; clearing`);\n state.activeWorkOrder = null;\n }\n\n const activeOrder = (state.activeWorkOrder && state.activeWorkOrder.id)\n ? state.activeWorkOrder\n : null;\n\n const trackingEnabled =\n (typeof s.trackingEnabled === \"boolean\" ? s.trackingEnabled : (state.trackingEnabled || false));\n\n const productionStarted =\n (typeof s.productionStarted === \"boolean\" ? s.productionStarted : (state.productionStarted || false));\n\n const kpis =\n (s.kpis && typeof s.kpis === \"object\")\n ? s.kpis\n : (state.currentKPIs || { oee: 0, availability: 0, performance: 0, quality: 0 });\n\n // ✨ Las cavidades vienen ÚNICAMENTE de la WO activa (sin fallback al global cache)\n const cavities = Number(\n activeOrder?.cavitiesActive ??\n activeOrder?.cavities ??\n s.cavities ??\n 0\n ) || null;\n\n msg._mode = \"current-state\";\n msg.payload = {\n machineId: s.machineId ?? config.machineId ?? undefined,\n\n activeWorkOrder: activeOrder,\n\n cycleCount: s.cycleCount,\n goodParts: s.goodParts,\n scrapParts: s.scrapParts,\n cavities,\n\n cycleTime: s.cycleTime,\n actualCycleTime: s.actualCycleTime,\n\n trackingEnabled,\n productionStarted,\n kpis,\n reasonCatalog,\n\n tsMs: s.tsMs\n };\n\n return finalize([null, msg, null, null]);\n }\n case \"restore-session\": {\n // Query DB for any RUNNING work order on startup\n msg._mode = \"restore-query\";\n msg.topic = \"SELECT * FROM work_orders WHERE status = 'RUNNING' LIMIT 1\";\n msg.payload = [];\n return finalize([null, msg, null, null]);\n }\n case \"scrap-entry\": {\n const { id, scrap } = msg.payload || {};\n const scrapNum = Number(scrap) || 0;\n\n if (!id) {\n node.error(\"No work order id supplied for scrap entry\", msg);\n return finalize([null, null, null, null]);\n }\n\n const activeOrder = state.activeWorkOrder;\n if (activeOrder && activeOrder.id === id) {\n activeOrder.scrapParts = (Number(activeOrder.scrapParts) || 0) + scrapNum;\n state.activeWorkOrder = activeOrder;\n }\n\n state.scrapPromptIssuedFor = null;\n\n msg._mode = \"scrap-update\";\n msg.scrapEntry = { id, scrap: scrapNum, reason: null };\n msg.topic = \"UPDATE work_orders SET scrap_parts = scrap_parts + ?, updated_at = NOW() WHERE work_order_id = ?\";\n msg.payload = [scrapNum, id];\n\n return finalize([null, null, msg, null]);\n }\n case \"scrap-entry-with-reason\": {\n const { id, scrap } = msg.payload || {};\n const scrapNum = Number(scrap) || 0;\n const reason = normalizeReason(msg.payload || {}, \"scrap\");\n\n if (!id) {\n node.error(\"No work order id supplied for scrap entry with reason\", msg);\n return finalize([null, null, null, null, null, null]);\n }\n\n const activeOrder = state.activeWorkOrder;\n if (activeOrder && activeOrder.id === id) {\n activeOrder.scrapParts = (Number(activeOrder.scrapParts) || 0) + scrapNum;\n state.activeWorkOrder = activeOrder;\n }\n\n state.scrapPromptIssuedFor = null;\n state.lastScrapReasonByOrder = state.lastScrapReasonByOrder || {};\n state.lastScrapReasonByOrder[id] = reason;\n\n const tsMs = Date.now();\n const outEvent = {\n tsMs,\n eventType: \"scrap-manual-entry\",\n workOrderId: id,\n scrapDelta: scrapNum,\n source: \"home-ui\",\n reason,\n downtime: null\n };\n\n msg._mode = \"scrap-update\";\n msg.scrapEntry = { id, scrap: scrapNum, reason };\n msg.topic = \"UPDATE work_orders SET scrap_parts = scrap_parts + ?, updated_at = NOW() WHERE work_order_id = ?\";\n msg.payload = [scrapNum, id];\n\n return finalize([null, null, msg, null, null, { payload: outEvent, tsMs }]);\n }\n case \"scrap-open\": {\n const active = state.activeWorkOrder || null;\n if (!active?.id) return finalize([null, null, null, null, null]);\n\n const good = Number(active.goodParts) || 0;\n const scrap = Number(active.scrapParts) || 0;\n const produced = good + scrap;\n\n msg._mode = \"scrap-prompt\";\n msg.scrapPrompt = {\n id: active.id,\n sku: active.sku || \"\",\n target: Number(active.target) || 0,\n produced,\n scrapSoFar: scrap,\n\n manual: true,\n title: \"Registrar scrap (parcial)\",\n enterMode: true,\n validateMax: false,\n reasonCatalog: reasonCatalog\n };\n\n delete msg.topic;\n delete msg.payload;\n\n return finalize([null, msg, null, null, null]);\n }\n case \"scrap-skip\": {\n const { id, remindAgain } = msg.payload || {};\n\n if (!id) {\n node.error(\"No work order id supplied for scrap skip\", msg);\n return finalize([null, null, null, null]);\n }\n\n if (remindAgain) {\n state.scrapPromptIssuedFor = null;\n }\n\n msg._mode = \"scrap-skipped\";\n return finalize([null, null, null, null]);\n }\n case \"start\": {\n // START with KPI timestamp init - FIXED\n const now = Date.now();\n const shifts = settings.shifts || [{ start: '06:00', end: '13:00' }];\n const shiftChangeComp = settings.shiftChangeCompensation || 10;\n const lunchBreak = settings.lunchBreakMinutes || 30;\n\n\n let totalShiftSeconds = 0;\n shifts.forEach(shift => {\n const [startH, startM] = (shift.start || '06:00').split(':').map(Number);\n const [endH, endM] = (shift.end || '15:00').split(':').map(Number);\n\n let startMinutes = startH * 60 + startM;\n let endMinutes = endH * 60 + endM;\n\n if (endMinutes <= startMinutes) {\n endMinutes += 24 * 60;\n }\n\n totalShiftSeconds += (endMinutes - startMinutes) * 60;\n });\n const compensationSeconds = shifts.length * shiftChangeComp * 60;\n const lunchSeconds = lunchBreak * 60;\n const plannedProductionTime = Math.max(0, totalShiftSeconds - compensationSeconds - lunchSeconds);\n state.plannedProductionTime = plannedProductionTime;\n\n const existingCycles = Number(state.cycleCount || 0);\n const activeOrderState = state.activeWorkOrder || {};\n const orderGood = Number(activeOrderState.goodParts) || 0;\n const orderScrap = Number(activeOrderState.scrapParts) || 0;\n\n const hasProgressFlag = state.activeOrderHasProgress;\n\n const hasProgress = (typeof hasProgressFlag === 'boolean')\n ? hasProgressFlag\n : (\n existingCycles > 0 ||\n (orderGood + orderScrap) > 0\n );\n\n if (!hasProgress) {\n state.stopTime = 0;\n state.trackingEnabled = true;\n state.productionStarted = true;\n state.kpiStartupMode = true;\n state.kpiBuffer = [];\n state.lastKPIRecordTime = now - 60000;\n state.productionStartTime = now;\n state.lastMachineCycleTime = now;\n state.lastCycleTime = now;\n state.operatingTime = 0;\n state.actualRunTime = 0;\n state.lastStartChangeTime = now;\n state.lastCycleCompletionTime = null;\n state.runSeconds = 0;\n state.stopSeconds = 0;\n state.kpiLastTick = null;\n } else {\n state.trackingEnabled = true;\n state.productionStarted = true;\n state.kpiStartupMode = false;\n }\n\n const activeOrder = state.activeWorkOrder || {};\n msg._mode = \"production-state\";\n\n msg.payload = msg.payload || {};\n\n msg.trackingEnabled = true;\n msg.productionStarted = true;\n msg.machineOnline = true;\n\n msg.payload.trackingEnabled = true;\n msg.payload.productionStarted = true;\n msg.payload.machineOnline = true;\n\n return finalize([null, msg, null, null]);\n }\n case \"stop\": {\n state.trackingEnabled = false;\n state.productionStarted = false;\n\n msg._mode = \"production-state\";\n msg.payload = msg.payload || {};\n msg.trackingEnabled = false;\n msg.productionStarted = false;\n msg.machineOnline = true;\n msg.payload.trackingEnabled = false;\n msg.payload.productionStarted = false;\n msg.payload.machineOnline = true;\n\n const s = state.lastState || {};\n s.trackingEnabled = false;\n s.productionStarted = false;\n s.tsMs = Date.now();\n state.lastState = s;\n\n return finalize([null, msg, null, null]);\n }\n case \"start-tracking\": {\n const activeOrder = state.activeWorkOrder || {};\n\n if (!activeOrder.id) {\n return finalize([null, { topic: \"alert\", payload: \"Error: No active work order loaded.\" }, null, null]);\n }\n\n const now = Date.now();\n state.trackingEnabled = true;\n\n state.kpiBuffer = [];\n state.lastKPIRecordTime = now - 60000;\n state.lastMachineCycleTime = now;\n state.lastCycleTime = now;\n state.operatingTime = 0.001;\n\n const stateMsg = {\n _mode: \"production-state\",\n payload: {\n trackingEnabled: true,\n machineOnline: true\n }\n };\n\n return finalize([null, stateMsg, null, null]);\n }\n case \"start-mold-change\": {\n const now = Date.now();\n const p = msg.payload || {};\n const mc = {\n active: true,\n startMs: now,\n endMs: null,\n fromMoldId: p.fromMoldId || null,\n toMoldId: null,\n operator: p.operator || null\n };\n state.moldChange = mc;\n // Disable tracking during mold change so KPI/anomaly are paused\n state.trackingEnabled = false;\n state.productionStarted = false;\n const event = {\n payload: {\n anomaly_type: \"mold-change\",\n eventType: \"mold-change\",\n severity: \"info\",\n requires_ack: false,\n title: \"Cambio de molde iniciado\",\n description: \"Inicio de cambio de molde\",\n status: \"active\",\n tsMs: now,\n data: {\n status: \"active\",\n start_ms: now,\n from_mold_id: mc.fromMoldId,\n operator: mc.operator,\n incidentKey: \"mold-change:\" + now\n }\n },\n tsMs: now\n };\n const uiMsg = { _mode: \"mold-change-status\", payload: { active: true, startMs: now, fromMoldId: mc.fromMoldId } };\n return finalize([null, uiMsg, null, null, null, event]);\n }\n case \"end-mold-change\": {\n const now = Date.now();\n const p = msg.payload || {};\n const mc = state.moldChange || {};\n if (!mc.active) {\n return finalize([null, null, null, null, null, null]);\n }\n const durationSec = Math.max(0, Math.round((now - (mc.startMs || now)) / 1000));\n const closed = {\n active: false,\n startMs: mc.startMs,\n endMs: now,\n fromMoldId: mc.fromMoldId || null,\n toMoldId: p.toMoldId || null,\n durationSec\n };\n state.moldChange = closed;\n const event = {\n payload: {\n anomaly_type: \"mold-change\",\n eventType: \"mold-change\",\n severity: \"info\",\n requires_ack: false,\n title: \"Cambio de molde finalizado\",\n description: \"Duracion: \" + Math.round(durationSec / 60) + \" min\",\n status: \"resolved\",\n tsMs: now,\n data: {\n status: \"resolved\",\n start_ms: closed.startMs,\n end_ms: now,\n duration_sec: durationSec,\n stoppage_duration_seconds: durationSec,\n from_mold_id: closed.fromMoldId,\n to_mold_id: closed.toMoldId,\n incidentKey: \"mold-change:\" + (closed.startMs || now)\n }\n },\n tsMs: now\n };\n const uiMsg = { _mode: \"mold-change-status\", payload: { active: false, endMs: now, durationSec } };\n return finalize([null, uiMsg, null, null, null, event]);\n }\n\n}", + "outputs": 7, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1150, + "y": 680, + "wires": [ + [ + "ff9a2476ccda2ac4" + ], + [ + "a3d41a656eb3b2ce", + "babe66a431cd1760", + "5df5be609ff6e622", + "d098028be97741ba", + "d447044432536eca" + ], + [ + "bfb9b7c7af23bd5c", + "a3d41a656eb3b2ce", + "d098028be97741ba", + "b4a971f8826b7422" + ], + [ + "bfb9b7c7af23bd5c" + ], + [ + "1212f599b9ab36f0" + ], + [ + "bf17a2d4b88f7694" + ], + [ + "c09c71a7e4908231" + ] + ] + }, + { + "id": "ad66f1edaba40aaa", + "type": "link out", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "link out 2", + "mode": "link", + "links": [ + "7b210ef16e508259" + ], + "x": 585, + "y": 300, + "wires": [] + }, + { + "id": "7b210ef16e508259", + "type": "link in", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "link in 2", + "links": [ + "ad66f1edaba40aaa" + ], + "x": 1305, + "y": 540, + "wires": [ + [ + "204c7a49f98a9944" + ] + ] + }, + { + "id": "7b91e5cc70af6ff3", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Build Insert SQL", + "func": "const rows = Array.isArray(msg.payload) ? msg.payload : [];\n\nconst values = rows\n .map((r) => {\n const id = String(r[\"Work Order ID\"] ?? \"\").trim();\n if (!id) return null;\n\n const sku = String(r[\"SKU\"] ?? \"\").trim();\n const targetQty = Number(r[\"Target Quantity\"]) || 0;\n const cycleTime =\n Number(r[\"Theoretical Cycle Time (Seconds)\"]) || 0;\n\n return [id, sku, targetQty, cycleTime, \"PENDING\"];\n })\n .filter(Boolean);\n\nif (!values.length) {\n return null;\n}\n\nmsg.topic = `\n INSERT INTO work_orders\n (work_order_id, sku, target_qty, cycle_time, status)\n VALUES ?\n ON DUPLICATE KEY UPDATE\n sku = VALUES(sku),\n target_qty = VALUES(target_qty),\n cycle_time = VALUES(cycle_time);\n`;\n\nmsg.payload = [values];\n\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1800, + "y": 500, + "wires": [ + [ + "bfb9b7c7af23bd5c" + ] + ] + }, + { + "id": "bfb9b7c7af23bd5c", + "type": "mysql", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "mydb": "fc9634aabefee16b", + "name": "mariaDB", + "x": 1820, + "y": 920, + "wires": [ + [ + "16b778a1349b8102" + ] + ] + }, + { + "id": "7df6eebd9b7c7c7b", + "type": "mysql", + "z": "05d4cb231221b842", + "g": "9221454c45afd1ba", + "mydb": "fc9634aabefee16b", + "name": "mariaDB (Graph Data)", + "x": 1600, + "y": 80, + "wires": [ + [ + "9f929db1f49b6e16" + ] + ] + }, + { + "id": "babe66a431cd1760", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Back to UI", + "func": "const mode = msg._mode || '';\nconst started = msg.startOrder || null;\nconst completed = msg.completeOrder || null;\nconst state = global.get(\"state\") || {};\nconst settings = global.get(\"settings\") || {};\n\n// ✨ La WO de la BD es la única fuente de cavidades.\n// attachMold solo normaliza nombres entre cavities/cavitiesActive y cavities_total/cavitiesTotal\n// para compatibilidad con código que aún lee los nombres viejos.\n// YA NO escribe en state.lastMoldActive ni state.moldByWorkOrder (cache global eliminado).\nconst attachMold = (order) => {\n if (!order || !order.id) return;\n\n const cavities = Number(\n order.cavitiesActive ??\n order.cavities_active ??\n order.cavities ??\n 0\n );\n const total = Number(\n order.cavitiesTotal ??\n order.cavities_total ??\n 0\n );\n\n if (Number.isFinite(cavities) && cavities > 0) {\n order.cavitiesActive = cavities;\n order.cavities = cavities; // alias para código viejo\n }\n if (Number.isFinite(total) && total > 0) {\n order.cavitiesTotal = total;\n order.cavities_total = total; // alias para código viejo\n }\n};\n\nconst finalize = (ret) => {\n global.set(\"state\", state);\n return ret;\n};\n\nconst toIsoString = (v) => {\n if (!v) return null;\n if (typeof v === \"string\") return v;\n if (v instanceof Date) return v.toISOString();\n if (typeof v.toISOString === \"function\") return v.toISOString();\n if (typeof v.toISO === \"function\") return v.toISO();\n if (typeof v.format === \"function\") return v.format();\n return String(v);\n};\n\ndelete msg._mode;\ndelete msg.startOrder;\ndelete msg.completeOrder;\ndelete msg.action;\ndelete msg.filename;\n\n// ========================================================\n// MODE: UPLOAD\n// ========================================================\nif (mode === \"upload\") {\n msg.topic = \"uploadStatus\";\n msg.payload = { message: \"✅ Work orders uploaded successfully.\" };\n return finalize([msg, null, null, null]);\n}\n\n// ========================================================\n// MODE: SELECT (Load Work Orders)\n// ========================================================\nif (mode === \"select\") {\n const rawRows = Array.isArray(msg.payload) ? msg.payload : [];\n msg.topic = \"workOrdersList\";\n msg.payload = rawRows.map(row => ({\n id: row.work_order_id ?? row.id ?? \"\",\n sku: row.sku ?? \"\",\n target: Number(row.target_qty ?? row.target ?? 0),\n goodParts: Number(row.good_parts ?? row.goodParts ?? 0),\n scrapParts: Number(row.scrap_count ?? row.scrap_parts ?? row.scrapParts ?? 0),\n progressPercent: Number(row.progress_percent ?? row.progress ?? 0),\n status: (row.status ?? \"PENDING\").toUpperCase(),\n lastUpdateIso: toIsoString(row.updated_at ?? row.last_update),\n cycleTime: Number(row.cycle_time ?? row.theoretical_cycle_time ?? 0)\n }));\n return finalize([msg, null, null, null]);\n}\n\n// ========================================================\n// MODE: START WORK ORDER\n// ========================================================\nif (mode === \"start\") {\n const order = started || {};\n attachMold(order);\n const kpis = msg.kpis || state.currentKPIs || {\n oee: 0, availability: 0, performance: 0, quality: 0\n };\n\n const homeMsg = {\n topic: \"activeWorkOrder\",\n payload: {\n id: order.id || \"\",\n sku: order.sku || \"\",\n target: Number(order.target) || 0,\n goodParts: Number(order.goodParts) || 0,\n scrapParts: Number(order.scrapParts) || 0,\n cycleTime: Number(order.cycleTime || order.theoreticalCycleTime || 0),\n progressPercent: Number(order.progressPercent) || 0,\n lastUpdateIso: toIsoString(order.lastUpdateIso) || null,\n kpis: kpis\n }\n };\n\n return finalize([null, homeMsg, null, null]);\n}\n\n// ========================================================\n// MODE: COMPLETE WORK ORDER\n// ========================================================\nif (mode === \"complete\") {\n const homeMsg = { topic: \"activeWorkOrder\", payload: null };\n return finalize([null, homeMsg, null, null]);\n}\n\n// ========================================================\n// MODE: CYCLE UPDATE DURING PRODUCTION\n// ========================================================\nif (mode === \"cycle\") {\n const cycle = msg.cycle || {};\n\n const workOrderMsg = {\n topic: \"workOrderCycle\",\n payload: {\n id: cycle.id || \"\",\n sku: cycle.sku || \"\",\n target: Number(cycle.target) || 0,\n goodParts: Number(cycle.goodParts) || 0,\n scrapParts: Number(cycle.scrapParts) || 0,\n progressPercent: Number(cycle.progressPercent) || 0,\n lastUpdateIso: toIsoString(cycle.lastUpdateIso) || null,\n status: cycle.progressPercent >= 100 ? \"DONE\" : \"RUNNING\"\n }\n };\n\n const kpis = msg.kpis || state.currentKPIs || {\n oee: 0, availability: 0, performance: 0, quality: 0\n };\n\n const homeMsg = {\n topic: \"activeWorkOrder\",\n payload: {\n id: cycle.id || \"\",\n sku: cycle.sku || \"\",\n target: Number(cycle.target) || 0,\n goodParts: Number(cycle.goodParts) || 0,\n scrapParts: Number(cycle.scrapParts) || 0,\n cycleTime: Number(cycle.cycleTime) || 0,\n progressPercent: Number(cycle.progressPercent) || 0,\n lastUpdateIso: toIsoString(cycle.lastUpdateIso) || new Date().toISOString(),\n kpis: kpis\n }\n };\n\n return finalize([workOrderMsg, homeMsg, null, null]);\n}\n\n// ========================================================\n// MODE: MACHINE PRODUCTION STATE\n// ========================================================\nif (mode === \"production-state\") {\n const homeMsg = {\n topic: \"machineStatus\",\n payload: {\n machineOnline: msg.machineOnline ?? true,\n productionStarted: !!msg.productionStarted,\n trackingEnabled: msg.payload?.trackingEnabled ?? msg.trackingEnabled ?? false\n }\n };\n return finalize([null, homeMsg, null, null]);\n}\n\n// ========================================================\n// MODE: CURRENT STATE (for tab switch sync)\n// ========================================================\nif (mode === \"current-state\") {\n const stateData = msg.payload || {};\n const homeMsg = {\n topic: \"currentState\",\n payload: {\n activeWorkOrder: stateData.activeWorkOrder,\n trackingEnabled: stateData.trackingEnabled,\n productionStarted: stateData.productionStarted,\n kpis: stateData.kpis\n }\n };\n return finalize([null, homeMsg, null, null]);\n}\n\n// ========================================================\n// MODE: RESTORE QUERY (startup state recovery)\n// ========================================================\n// ✨ Cuando arranca Node-RED después de reinicio del Pi, se recupera la WO en RUNNING\n// junto con sus cavidades de la BD. La BD es la fuente de verdad.\nif (mode === \"restore-query\") {\n const rows = Array.isArray(msg.payload) ? msg.payload : [];\n\n if (rows.length > 0) {\n const row = rows[0];\n\n // ✨ Lee cavidades de la BD y las pone con TODOS los aliases (camelCase y snake_case)\n const cavitiesActive = Number(row.cavities_active || 0);\n const cavitiesTotal = Number(row.cavities_total || 0);\n\n const restoredOrder = {\n id: row.work_order_id || row.id || \"\",\n sku: row.sku || \"\",\n target: Number(row.target_qty || row.target || 0),\n goodParts: Number(row.good_parts || row.goodParts || 0),\n scrapParts: Number(row.scrap_parts || row.scrapParts || 0),\n progressPercent: Number(row.progress_percent || 0),\n cycleTime: Number(row.cycle_time || 0),\n lastUpdateIso: toIsoString(row.updated_at ?? row.last_update),\n mold: row.mold || null,\n // ✨ Cavidades con todos los nombres (nuevos + aliases viejos)\n cavitiesActive: cavitiesActive > 0 ? cavitiesActive : null,\n cavities: cavitiesActive > 0 ? cavitiesActive : null,\n cavitiesTotal: cavitiesTotal > 0 ? cavitiesTotal : null,\n cavities_total: cavitiesTotal > 0 ? cavitiesTotal : null\n };\n\n // attachMold normaliza nombres (sin tocar cache global)\n attachMold(restoredOrder);\n\n const restoredCycleCount = Number(row.cycle_count) || 0;\n const restoredGood = Number(row.good_parts || 0);\n const restoredScrap = Number(row.scrap_parts || 0);\n const hasProgress = restoredCycleCount > 0 || (restoredGood + restoredScrap) > 0;\n\n // Restore global state\n state.activeWorkOrder = restoredOrder;\n state.cycleCount = restoredCycleCount;\n state.activeOrderHasProgress = hasProgress;\n // Auto-resume tracking for RUNNING work order\n state.trackingEnabled = true;\n state.productionStarted = true;\n state.kpiStartupMode = !hasProgress;\n\n // Reset tick so KPI integration doesn't jump\n state.kpiLastTick = null;\n\n let restoreTs = Date.parse(row.updated_at || \"\");\n if (!isFinite(restoreTs)) {\n restoreTs = Date.now();\n }\n state.lastMachineCycleTime = restoreTs;\n state.lastCycleCompletionTime = restoreTs;\n\n node.warn('[RESTORE] Restored work order: ' + restoredOrder.id +\n ' with ' + state.cycleCount + ' cycles, cavitiesActive=' + cavitiesActive +\n ', cavitiesTotal=' + cavitiesTotal + ', mold=' + (row.mold || 'null'));\n\n const homeMsg = {\n topic: \"activeWorkOrder\",\n payload: restoredOrder\n };\n\n const stateMsg = {\n topic: \"machineStatus\",\n payload: {\n machineOnline: true,\n productionStarted: true,\n trackingEnabled: true\n }\n };\n\n // Set status back to RUNNING in database (if not already DONE)\n const dbMsg = {\n topic: \"UPDATE work_orders SET status = 'RUNNING', updated_at = NOW() WHERE work_order_id = ? AND status != 'DONE'\",\n payload: [restoredOrder.id]\n };\n\n return finalize([dbMsg, [homeMsg, stateMsg], null, null]);\n } else {\n node.warn('[RESTORE] No running work order found');\n }\n return finalize([null, null, null, null]);\n}\n\n// ========================================================\n// MODE: SCRAP PROMPT\n// ========================================================\nif (mode === \"scrap-prompt\") {\n const prompt = msg.scrapPrompt || {};\n\n const homeMsg = { topic: \"scrapPrompt\", payload: prompt };\n const tabMsg = { ui_control: { tab: \"Home\" } };\n\n return finalize([null, homeMsg, tabMsg, null]);\n}\n\n// ========================================================\n// MODE: SCRAP UPDATE\n// ========================================================\nif (mode === \"scrap-update\") {\n const activeOrder = state.activeWorkOrder || {};\n const kpis = msg.kpis || state.currentKPIs || {\n oee: 0, availability: 0, performance: 0, quality: 0\n };\n\n const homeMsg = {\n topic: \"activeWorkOrder\",\n payload: {\n id: activeOrder.id || \"\",\n sku: activeOrder.sku || \"\",\n target: Number(activeOrder.target) || 0,\n goodParts: Number(activeOrder.goodParts) || 0,\n scrapParts: Number(activeOrder.scrapParts) || 0,\n cycleTime: Number(activeOrder.cycleTime) || 0,\n progressPercent: Number(activeOrder.progressPercent) || 0,\n lastUpdateIso: toIsoString(activeOrder.lastUpdateIso) || new Date().toISOString(),\n kpis: kpis\n }\n };\n\n return finalize([null, homeMsg, null, null]);\n}\n\n// ========================================================\n// MODE: SCRAP COMPLETE\n// ========================================================\nif (mode === \"scrap-complete\") {\n const homeMsg = { topic: \"activeWorkOrder\", payload: null };\n return finalize([null, homeMsg, null, null]);\n}\n\n// ========================================================\n// MODE: RESUME-PROMPT\n// ========================================================\n// Cuando el operador selecciona una WO con progreso existente,\n// el Progress Check Handler envía este mode para que la UI muestre\n// el prompt de \"¿reanudar o reiniciar?\"\n// ========================================================\n// MODE: RESUME-PROMPT\n// ========================================================\nif (mode === \"resume-prompt\") {\n const order = msg.payload.order || null;\n\n if (order) {\n attachMold(order);\n\n // ✨ FIX: actualiza el state CONSISTENTEMENTE con la nueva WO\n // - cycleCount sincronizado para que Machine cycles no sume al contador anterior\n // - tracking apagado: el operador debe presionar COMENZAR explícitamente\n // (esto previene que se sumen ciclos a la WO equivocada si el modal no aparece)\n state.activeWorkOrder = order;\n state.cycleCount = Number(order.cycleCount) || 0;\n state.activeOrderHasProgress = true;\n state.trackingEnabled = false;\n state.productionStarted = false;\n state.scrapPromptIssuedFor = null;\n flow.set(\"lastMachineState\", 0);\n // ✨ FIX: sincronizar state.lastState para que el polling cada 500ms\n // del HMI (get-current-state) no devuelva valores viejos al template\n // y reactive el botón DETENER. State Accumulator solo actualiza lastState\n // cuando hay ciclos, así que tenemos que hacerlo aquí explícitamente.\n if (state.lastState && typeof state.lastState === \"object\") {\n state.lastState = {\n ...state.lastState,\n activeWorkOrder: order,\n cycleCount: Number(order.cycleCount) || 0,\n goodParts: Number(order.goodParts) || 0,\n scrapParts: Number(order.scrapParts) || 0,\n trackingEnabled: false,\n productionStarted: false,\n tsMs: Date.now()\n };\n }\n node.warn(`[RESUME-PROMPT] activeWorkOrder=${order.id} cycleCount=${state.cycleCount} tracking=OFF`);\n }\n\n const homeMsg = {\n topic: msg.topic || \"resumePrompt\",\n payload: msg.payload,\n };\n\n const kpis =\n msg.kpis ||\n state.currentKPIs || {\n oee: 0,\n availability: 0,\n performance: 0,\n quality: 0,\n };\n\n const activeMsg = order\n ? {\n topic: \"activeWorkOrder\",\n payload: {\n id: order.id || \"\",\n sku: order.sku || \"\",\n target: Number(order.target) || 0,\n goodParts: Number(order.goodParts) || 0,\n scrapParts: Number(order.scrapParts) || 0,\n cycleTime: Number(\n order.cycleTime ||\n order.theoreticalCycleTime ||\n 0\n ),\n progressPercent: Number(\n msg.payload?.progressPercent ??\n order.progressPercent ??\n 0\n ),\n lastUpdateIso: order.lastUpdateIso || null,\n kpis,\n },\n }\n : null;\n\n // ✨ FIX: también enviar el estado de tracking apagado al HMI\n // para que el botón muestre COMENZAR (no DETENER)\n const machineMsg = {\n topic: \"machineStatus\",\n payload: {\n machineOnline: true,\n productionStarted: false,\n trackingEnabled: false\n }\n };\n\n return finalize([\n null,\n activeMsg ? [activeMsg, homeMsg, machineMsg] : [homeMsg, machineMsg],\n null,\n null,\n ]);\n}\n\n// ========================================================\n// MODE: MOLD CHANGE STATUS\n// ========================================================\nif (mode === \"mold-change-status\") {\n const homeMsg = {\n topic: \"moldChangeStatus\",\n payload: msg.payload || {}\n };\n return finalize([null, homeMsg, null, null]);\n}\n\n// ========================================================\n// DEFAULT\n// ========================================================\nreturn finalize([null, null, null, null]);", + "outputs": 4, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 2190, + "y": 560, + "wires": [ + [ + "eb61ec7045cb4fab" + ], + [ + "8d2fcc3bc64141a0" + ], + [ + "7d0b25dedd60803a" + ], + [] + ] + }, + { + "id": "eb61ec7045cb4fab", + "type": "link out", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "link out 3", + "mode": "link", + "links": [ + "5084f1955153578d" + ], + "x": 2305, + "y": 520, + "wires": [] + }, + { + "id": "5084f1955153578d", + "type": "link in", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "link in 3", + "links": [ + "eb61ec7045cb4fab" + ], + "x": 275, + "y": 320, + "wires": [ + [ + "b1a448897989958f" + ] + ] + }, + { + "id": "ca4956aff7158938", + "type": "book", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "", + "raw": false, + "x": 1810, + "y": 460, + "wires": [ + [ + "afb78150ffe54054" + ] + ] + }, + { + "id": "afb78150ffe54054", + "type": "sheet", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "", + "sheetName": "Sheet1", + "x": 1930, + "y": 460, + "wires": [ + [ + "6d19a182b174127e" + ] + ] + }, + { + "id": "6d19a182b174127e", + "type": "sheet-to-json", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "", + "raw": "false", + "range": "", + "header": "default", + "blankrows": false, + "x": 2070, + "y": 460, + "wires": [ + [ + "7b91e5cc70af6ff3" + ] + ] + }, + { + "id": "ff9a2476ccda2ac4", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Base64", + "func": "const filename =\n msg.filename ||\n (msg.meta && msg.meta.filename) ||\n (msg.payload && msg.payload.filename) ||\n msg.name ||\n 'upload.xlsx';\n\nconst candidates = [];\nif (typeof msg.payload === 'string') candidates.push(msg.payload);\nif (msg.payload && typeof msg.payload.payload === 'string') candidates.push(msg.payload.payload);\nif (msg.payload && typeof msg.payload.file === 'string') candidates.push(msg.payload.file);\nif (msg.payload && typeof msg.payload.base64 === 'string') candidates.push(msg.payload.base64);\nif (typeof msg.file === 'string') candidates.push(msg.file);\nif (typeof msg.data === 'string') candidates.push(msg.data);\n\nfunction stripDataUrl(s) {\n return (s && s.startsWith('data:')) ? s.split(',')[1] : s;\n}\n\nlet b64 = candidates.map(stripDataUrl).find(s => typeof s === 'string' && s.length > 0);\nif (!b64 && Buffer.isBuffer(msg.payload)) { msg.filename = filename; return msg; }\nif (!b64) { node.error('No base64 data found on msg', msg); return null; }\n\nmsg.payload = Buffer.from(b64, 'base64');\nmsg.filename = filename;\nreturn msg;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1680, + "y": 460, + "wires": [ + [ + "ca4956aff7158938" + ] + ] + }, + { + "id": "8d2fcc3bc64141a0", + "type": "link out", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "link out 4", + "mode": "link", + "links": [ + "5201b1255d81c6a1" + ], + "x": 2305, + "y": 560, + "wires": [] + }, + { + "id": "5201b1255d81c6a1", + "type": "link in", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "link in 4", + "links": [ + "8d2fcc3bc64141a0" + ], + "x": 275, + "y": 280, + "wires": [ + [ + "dbfd127c516efa87" + ] + ] + }, + { + "id": "d569d16fc0423be8", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Refresh Trigger", + "func": "if (msg._mode === \"sync-work-orders\") {\n msg._mode = \"select\";\n msg.topic = \"SELECT * FROM work_orders ORDER BY updated_at DESC;\";\n return [msg, null];\n}\nif (msg._mode === \"start\" || msg._mode === \"complete\" || msg._mode === \"resume\" || msg._mode === \"restart\") {\n // Preserve original message for Back to UI (output 2)\n const originalMsg = {...msg};\n // Create select message for refreshing WO table (output 1)\n msg._mode = \"select\";\n msg.topic = \"SELECT * FROM work_orders ORDER BY updated_at DESC;\";\n return [msg, originalMsg];\n}\nif (msg._mode === \"cycle\" || msg._mode === \"production-state\") {\n return [null, msg];\n}\nif (msg._mode === \"scrap-prompt\") {\n return [null, msg];\n}\nif (msg._mode === \"restore-query\") {\n // Pass restore query results to Back to UI\n return [null, msg];\n}\nif (msg._mode === \"current-state\") {\n // Pass current state to Back to UI\n return [null, msg];\n}\nif (msg._mode === \"scrap-complete\") {\n // Preserve original message for Back to UI (output 2)\n const originalMsg = {...msg};\n // Create select message for refreshing WO table (output 1)\n msg._mode = \"select\";\n msg.topic = \"SELECT * FROM work_orders ORDER BY updated_at DESC;\";\n return [msg, originalMsg];\n}\nreturn [null, msg];", + "outputs": 2, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1960, + "y": 600, + "wires": [ + [ + "bfb9b7c7af23bd5c" + ], + [ + "babe66a431cd1760" + ] + ] + }, + { + "id": "093d9631fbd43003", + "type": "function", + "z": "05d4cb231221b842", + "g": "6e514144a570aa72", + "name": "Machine cycles", + "func": "const current = Number(msg.payload) || 0;\nconst now = Date.now();\n\nconst state = global.get(\"state\") || {};\nconst settings = global.get(\"settings\") || {};\nconst saveState = () => global.set(\"state\", state);\nconst finalize = (ret) => { saveState(); return ret; };\n\nlet zeroStreak = flow.get(\"zeroStreak\") || 0;\nzeroStreak = current === 0 ? zeroStreak + 1 : 0;\nflow.set(\"zeroStreak\", zeroStreak);\n\nconst prev = flow.get(\"lastMachineState\") ?? 0;\n\nconst activeOrder = state.activeWorkOrder;\nconst trackingEnabled = !!state.trackingEnabled;\n\n// ALWAYS update state tracking (before any early returns)\nstate.lastStateChangeTime = now;\nflow.set(\"lastMachineState\", current);\n\n// =============================================\n// MACHINE ONLINE STATUS\n// =============================================\nstate.machineOnline = true;\n\nlet productionRunning = !!state.productionStarted;\nlet stateChanged = false;\n\nif (current === 1 && !productionRunning) {\n productionRunning = true;\n stateChanged = true;\n} else if (current === 0 && zeroStreak >= 2 && productionRunning) {\n productionRunning = false;\n stateChanged = true;\n}\n\nstate.productionStarted = productionRunning;\n\nconst stateMsg = stateChanged\n ? {\n _mode: \"production-state\",\n machineOnline: true,\n productionStarted: productionRunning\n }\n : null;\n\n// =============================================\n// EARLY EXIT CONDITIONS\n// =============================================\nconst cavities = Number(\n activeOrder?.cavitiesActive ??\n activeOrder?.cavities ??\n 0\n);\n\nif (!activeOrder || !activeOrder.id || !Number.isFinite(cavities) || cavities <= 0) {\n return finalize([null, stateMsg, { _triggerKPI: true }, null]);\n}\n\nactiveOrder.cavities = cavities;\nactiveOrder.cavitiesActive = cavities;\n\nif (!trackingEnabled) {\n return finalize([null, stateMsg, { _triggerKPI: true }, null]);\n}\n\n// Only count cycles on rising edge (0→1)\nif (prev === 1 || current !== 1) {\n return finalize([null, stateMsg, { _triggerKPI: true }, null]);\n}\n\n// =============================================\n// DEBOUNCE: ignorar rebotes del sensor\n// Si pasaron menos del 30% del cycle_time esperado desde el último ciclo,\n// es un rebote del sensor — no contamos.\n// =============================================\nconst expectedCycleTimeSec = Number(activeOrder.cycleTime || 0);\nconst lastCompletion = state.lastCycleCompletionTime;\nif (lastCompletion && expectedCycleTimeSec > 0) {\n const elapsedSec = (now - lastCompletion) / 1000;\n const minIntervalSec = expectedCycleTimeSec * 0.3;\n if (elapsedSec < minIntervalSec) {\n node.warn(`[DEBOUNCE] Ciclo ignorado (rebote): ${elapsedSec.toFixed(2)}s desde último ciclo, mínimo ${minIntervalSec.toFixed(1)}s. wo=${activeOrder.id}`);\n return finalize([null, stateMsg, { _triggerKPI: true }, null]);\n }\n}\n\n// =============================================\n// CYCLE COUNTING\n// =============================================\nif (lastCompletion) {\n const actualCycleTime = (now - lastCompletion) / 1000;\n state.lastActualCycleTime = actualCycleTime;\n}\n\nlet cycles = Number(state.cycleCount || 0) + 1;\nstate.cycleCount = cycles;\nstate.lastCycleCompletionTime = now;\n\nif (state.kpiStartupMode) {\n state.kpiStartupMode = false;\n node.warn('[MACHINE CYCLE] First cycle - cleared kpiStartupMode');\n}\n\nstate.lastMachineCycleTime = now;\nstate.saveKpis = 1;\n\n// =============================================\n// PRODUCTION METRICS\n// =============================================\nconst scrapTotal = Number(activeOrder.scrapParts) || 0;\nconst totalProduced = cycles * cavities;\nconst produced = Math.max(0, totalProduced - scrapTotal);\nconst target = Number(activeOrder.target) || 0;\nconst progress = target > 0 ? Math.min(100, Math.round((produced / target) * 100)) : 0;\n\nactiveOrder.goodParts = produced;\nactiveOrder.progressPercent = progress;\nactiveOrder.lastUpdateIso = new Date().toISOString();\nstate.activeWorkOrder = activeOrder;\n\n// =============================================\n// SCRAP PROMPT CHECK\n// =============================================\nconst promptIssued = state.scrapPromptIssuedFor || null;\nif (!promptIssued && target > 0 && produced >= target) {\n state.scrapPromptIssuedFor = activeOrder.id;\n msg._mode = \"scrap-prompt\";\n msg.scrapPrompt = {\n id: activeOrder.id,\n sku: activeOrder.sku || \"\",\n target,\n produced\n };\n return finalize([null, msg, null, null]);\n}\n\n// =============================================\n// DATABASE UPDATE\n// =============================================\nconst dbMsg = {\n _mode: \"cycle\",\n cycle: {\n id: activeOrder.id,\n sku: activeOrder.sku || \"\",\n target,\n goodParts: produced,\n scrapParts: scrapTotal,\n cycleTime: Number(activeOrder.cycleTime || activeOrder.theoreticalCycleTime || 0),\n progressPercent: progress,\n lastUpdateIso: activeOrder.lastUpdateIso,\n machineOnline: true,\n productionStarted: productionRunning\n },\n topic: \"UPDATE work_orders SET good_parts = ?, progress_percent = ?, updated_at = NOW() WHERE work_order_id = ?\",\n payload: [produced, progress, activeOrder.id]\n};\n\nconst kpiTrigger = { _triggerKPI: true };\n\n// ✨ Persistir cycle_count en cada ciclo (antes solo se persistía good_parts)\n// Esto evita perder ciclos si reinicia Node-RED\nconst persistWorkOrder = {\n topic: \"UPDATE work_orders SET cycle_count = ?, good_parts = ?, scrap_parts = ?, progress_percent = ?, updated_at = NOW() WHERE work_order_id = ?\",\n payload: [cycles, produced, scrapTotal, progress, activeOrder.id]\n};\n\ndbMsg.cycleRow = {\n tsMs: now,\n cycle_count: cycles,\n actual_cycle_time: Number(state.lastActualCycleTime || 0),\n theoretical_cycle_time: Number(activeOrder.cycleTime || 0),\n work_order_id: String(activeOrder.id),\n sku: String(activeOrder.sku || \"\"),\n cavities: cavities,\n good_delta: cavities,\n scrap_total: scrapTotal,\n};\n\nreturn finalize([dbMsg, stateMsg, kpiTrigger, persistWorkOrder]);", + "outputs": 4, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1860, + "y": 220, + "wires": [ + [ + "8ebf807b7c65eb42", + "3c78c68f64843c22" + ], + [ + "d7fce9cf6a8c8f9b", + "ed8c202dde4b6ff9" + ], + [], + [ + "d45345c05485d114" + ] + ] + }, + { + "id": "8ebf807b7c65eb42", + "type": "link out", + "z": "05d4cb231221b842", + "g": "6e514144a570aa72", + "name": "link out 5", + "mode": "link", + "links": [ + "5f1b67667a0c39f4" + ], + "x": 2015, + "y": 200, + "wires": [] + }, + { + "id": "5f1b67667a0c39f4", + "type": "link in", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "link in 5", + "links": [ + "8ebf807b7c65eb42" + ], + "x": 1525, + "y": 480, + "wires": [ + [ + "bfb9b7c7af23bd5c" + ] + ] + }, + { + "id": "d7fce9cf6a8c8f9b", + "type": "link out", + "z": "05d4cb231221b842", + "g": "6e514144a570aa72", + "name": "link out 6", + "mode": "link", + "links": [ + "1f26139ec9079c2d" + ], + "x": 2035, + "y": 240, + "wires": [] + }, + { + "id": "1f26139ec9079c2d", + "type": "link in", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "link in 6", + "links": [ + "d7fce9cf6a8c8f9b" + ], + "x": 1755, + "y": 580, + "wires": [ + [ + "d569d16fc0423be8" + ] + ] + }, + { + "id": "7d0b25dedd60803a", + "type": "link out", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "link out 7", + "mode": "link", + "links": [ + "01705d77724ccc51" + ], + "x": 2305, + "y": 600, + "wires": [] + }, + { + "id": "01705d77724ccc51", + "type": "link in", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "link in 7", + "links": [ + "7d0b25dedd60803a" + ], + "x": 535, + "y": 420, + "wires": [ + [ + "44d2ce4b810b508b" + ] + ] + }, + { + "id": "4101967d16ba7f8b", + "type": "link out", + "z": "05d4cb231221b842", + "g": "878b79013722e91f", + "name": "link out 8", + "mode": "link", + "links": [ + "6b3c45059b9b7c6c" + ], + "x": 955, + "y": 660, + "wires": [] + }, + { + "id": "6b3c45059b9b7c6c", + "type": "link in", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "link in 8", + "links": [ + "4101967d16ba7f8b", + "2c8562b2471078ab" + ], + "x": 275, + "y": 480, + "wires": [ + [ + "afb514404a6ecda1" + ] + ] + }, + { + "id": "a3d41a656eb3b2ce", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Calculate KPIs", + "func": "// ========================================\n// KPI HEARTBEAT - Continuous OEE calculation\n// Runs every second from a dedicated inject node\n// ========================================\n\nconst state = global.get(\"state\") || {};\nconst settings = global.get(\"settings\") || {};\n\n// 1) Basic guards: only run when tracking an active work order\nconst trackingEnabled = state.trackingEnabled || false;\nconst activeOrder = state.activeWorkOrder || {};\nif (!trackingEnabled || !activeOrder.id) {\n return null;\n}\n\n// Detect work-order change and restore/reset KPI counters\nconst currentId = activeOrder.id;\nif (state.kpiOrderId !== currentId) {\n const byOrder = state.kpiByWorkOrder || {};\n const saved = byOrder[currentId];\n\n if (saved && state.activeOrderHasProgress) {\n state.productionStartTime = saved.productionStartTime;\n state.runSeconds = saved.runSeconds;\n state.stopSeconds = saved.stopSeconds;\n state.kpiStartupMode = !!saved.kpiStartupMode;\n state.kpiLastTick = null; // avoid huge dt jump\n } else {\n state.productionStartTime = Date.now();\n state.runSeconds = 0;\n state.stopSeconds = 0;\n state.kpiStartupMode = true;\n state.kpiLastTick = null;\n }\n\n state.kpiOrderId = currentId;\n state.perf = { lastCycleCount: 0, runSeconds: 0 };\n\n}\n\n\n// Production must have a start time\n//const productionStartTime = state.productionStartTime;\n//if (!productionStartTime) {\n// return null;\n//}\n\n// Optional startup mode: keep 100/100/100/100 until first real cycle\nlet kpiStartupMode = !!state.kpiStartupMode;\n\nif (kpiStartupMode && Number(state.cycleCount || 0) > 0) {\n state.kpiStartupMode = false;\n kpiStartupMode = false;\n}\n\n// 2) Time step (dt) since last KPI tick\nconst now = Date.now();\nlet lastTick = state.kpiLastTick;\nlet dt;\nif (!lastTick) {\n dt = 0; // first run: don't integrate any time yet\n} else {\n dt = (now - lastTick) / 1000;\n}\nstate.kpiLastTick = now;\n\n// Clamp weird dt values (e.g. after long pause)\nif (dt < 0 || dt > 5) {\n dt = 1;\n}\nlet productionStartTime = state.productionStartTime;\nif (!productionStartTime) {\n // if we’re tracking a valid order, start the clock now\n productionStartTime = now;\n state.productionStartTime = productionStartTime;\n}\n\n// 3) Scheduled production time so far (denominator for Availability)\nlet elapsedSeconds = (now - productionStartTime) / 1000;\nif (elapsedSeconds < 0) elapsedSeconds = 0;\n\nconst plannedProductionTime = Number(state.plannedProductionTime || 0);\n\n// scheduledSeconds = time in the shift that *should* be production\nlet scheduledSeconds = elapsedSeconds;\nif (plannedProductionTime > 0) {\n scheduledSeconds = Math.min(elapsedSeconds, plannedProductionTime);\n}\n\n// 4) Determine machine state from last cycle timestamp\nconst lastCycleTime = state.lastMachineCycleTime || null;\nlet machineState = state.machineState || \"IDLE\";\n\nif (lastCycleTime) {\n const sinceLastCycle = (now - lastCycleTime) / 1000;\n const idealCycleTime = Number(activeOrder.cycleTime) || 1;\n const thresholdMultiplier = Number(settings.thresholdMultiplier || 1.5);\n const stopThreshold = idealCycleTime * thresholdMultiplier;\n\n machineState = (sinceLastCycle <= stopThreshold) ? \"RUNNING\" : \"STOPPED\";\n state.machineState = machineState;\n\n if (kpiStartupMode && sinceLastCycle > stopThreshold) {\n state.kpiStartupMode = false;\n kpiStartupMode = false;\n }\n}\n// ---- Shift-based availability (daily) ----\nconst shifts = settings.shifts || [{ start: '06:00', end: '15:00' }];\nconst shiftChangeComp = Number(settings.shiftChangeCompensation ?? 10);\nconst lunchBreak = Number(settings.lunchBreakMinutes ?? 30);\n\nfunction hmToMinutes(hm) {\n const parts = String(hm || '00:00').split(':').map(Number);\n return (parts[0] || 0) * 60 + (parts[1] || 0);\n}\nfunction isInShift(nowMs) {\n const d = new Date(nowMs);\n const dayStart = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0).getTime();\n return shifts.some(s => {\n let startM = hmToMinutes(s.start);\n let endM = hmToMinutes(s.end);\n let start = dayStart + startM * 60000;\n let end = dayStart + endM * 60000;\n if (end <= start) end += 24 * 60 * 60000; // overnight\n return nowMs >= start && nowMs <= end;\n });\n}\nfunction plannedDaySeconds() {\n let total = 0;\n shifts.forEach(s => {\n let startM = hmToMinutes(s.start);\n let endM = hmToMinutes(s.end);\n if (endM <= startM) endM += 24 * 60;\n total += (endM - startM) * 60;\n });\n const compensation = shifts.length * shiftChangeComp * 60;\n const lunch = lunchBreak * 60;\n return Math.max(0, total - compensation - lunch);\n}\n\nconst d = new Date(now);\nconst dayKey = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;\nif (state.availDayKey !== dayKey) {\n state.availDayKey = dayKey;\n state.availDowntimeSeconds = 0;\n}\n\nconst inShift = isInShift(now);\nconst plannedSeconds = plannedDaySeconds();\nif (inShift && dt > 0 && machineState !== \"RUNNING\") {\n state.availDowntimeSeconds = Number(state.availDowntimeSeconds || 0) + dt;\n}\nconst availabilityPct = plannedSeconds > 0\n ? ((plannedSeconds - (state.availDowntimeSeconds || 0)) / plannedSeconds) * 100\n : 0;\n\n\n// 5) Integrate run / stop time (numerators)\n// We keep these as smooth, per-second counters\nlet runSeconds = Number(state.runSeconds || 0);\nlet stopSeconds = Number(state.stopSeconds || 0);\n\n// During startup mode (before first cycle), don't integrate anything\nif (!kpiStartupMode && dt > 0 && scheduledSeconds > 0) {\n if (machineState === \"RUNNING\") {\n runSeconds += dt;\n } else if (machineState === \"STOPPED\") {\n stopSeconds += dt;\n }\n}\n\nstate.runSeconds = runSeconds;\nstate.stopSeconds = stopSeconds;\n\n// 6) Pull counters for Performance & Quality\nconst cycleCount = Number(state.cycleCount || 0);\nconst cavities = Number(\n activeOrder.cavities ??\n (state.moldByWorkOrder?.[activeOrder.id]?.active) ??\n state.lastMoldActive ??\n settings.moldActive ??\n 0\n);\nconst totalParts = cycleCount * cavities;\nconst totalCycles = cycleCount;\n\n\nconst scrapTotal = Number(activeOrder.scrapParts) || 0;\nconst goodParts = Math.max(0, totalParts - scrapTotal);\n\nconst idealCycleTime = Number(activeOrder.cycleTime) || 1;\n\n// 7) Compute KPIs\n\n// Helper to keep values sane\nfunction clampPercent(v) {\n if (!isFinite(v) || isNaN(v)) return 0;\n return Math.max(0, Math.min(100, v));\n}\n\nlet availability = 0;\nlet performance = 0;\nlet quality = 100;\nlet oee = 0;\n\n// Startup mode: skip KPI emit until first real cycle/state transition\nif (kpiStartupMode) {\n global.set(\"state\", state);\n return null;\n} else {\n // Availability = Run Time / Scheduled Production Time\n availability = availabilityPct;\n\n\n // Performance = (Ideal Cycle Time × Cycles) / Sum of actual cycle times\n const actualCycleTime = Number(state.lastActualCycleTime || 0);\n state.perf = state.perf || { lastCycleCount: 0, runSeconds: 0 };\n\n // Use same threshold you use for slow-cycle\n const perfThreshold = idealCycleTime * Number(settings.thresholdMultiplier || 1.5);\n\n if (cycleCount > state.perf.lastCycleCount && actualCycleTime > 0) {\n // Cap at threshold so time beyond becomes downtime, not performance loss\n const perfCycleTime = Math.min(actualCycleTime, perfThreshold);\n state.perf.runSeconds += perfCycleTime;\n state.perf.lastCycleCount = cycleCount;\n }\n\n if (state.perf.runSeconds > 0 && cycleCount > 0) {\n const idealTime = idealCycleTime * cycleCount;\n performance = (idealTime / state.perf.runSeconds) * 100;\n }\n\n // Quality = Good Parts / Total Parts\n if (totalParts > 0) {\n quality = (goodParts / totalParts) * 100;\n }\n\n availability = clampPercent(availability);\n performance = clampPercent(performance);\n quality = clampPercent(quality);\n\n // OEE = A × P × Q\n oee = (availability * performance * quality) / 10000;\n}\n\n// Clamp & round to 1 decimal\noee = clampPercent(oee);\n\nmsg.kpis = {\n availability: Math.round(availability * 10) / 10,\n performance: Math.round(performance * 10) / 10,\n quality: Math.round(quality * 10) / 10,\n oee: Math.round(oee * 10) / 10\n};\n\nstate.currentKPIs = msg.kpis;\nstate.kpiByWorkOrder = state.kpiByWorkOrder || {};\nstate.kpiByWorkOrder[activeOrder.id] = {\n productionStartTime: state.productionStartTime,\n runSeconds: state.runSeconds,\n stopSeconds: state.stopSeconds,\n kpiStartupMode: state.kpiStartupMode,\n kpiLastTick: state.kpiLastTick\n};\nglobal.set(\"state\", state);\nreturn msg;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1380, + "y": 680, + "wires": [ + [ + "d569d16fc0423be8", + "bb14a0293698c0e0", + "68709c57900ed80e", + "dcaa582c9b2277ba", + "79e027bf3befb2d9" + ] + ] + }, + { + "id": "4a62662fea532976", + "type": "function", + "z": "05d4cb231221b842", + "g": "443b758222662fdf", + "name": "Process Alert for DB", + "func": "// Process incoming alert\nif (msg.payload && msg.payload.action === 'alert') {\n const alert = msg.payload;\n\n const tsMs = typeof alert.tsMs === \"number\" ? alert.tsMs : Date.now();\n const timestamp = new Date(tsMs).toISOString().slice(0, 19).replace('T', ' ');\n\n // Prepare INSERT query\n const alertType = (alert.type || 'Unknown').replace(/'/g, \"''\"); // Escape quotes\n const description = (alert.description || '').replace(/'/g, \"''\"); // Escape quotes\n\n msg.topic = `\n INSERT INTO alerts_log (timestamp, alert_type, description)\n VALUES ('${timestamp}', '${alertType}', '${description}')\n `;\n\n node.status({\n fill: 'green',\n shape: 'dot',\n text: `Logging: ${alertType}`\n });\n\n // Store original message for passthrough\n msg._originalAlert = alert;\n\n return msg;\n}\n\nreturn null;", + "outputs": 1, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 440, + "y": 860, + "wires": [ + [ + "6e76f33c5b84574a" + ] + ] + }, + { + "id": "6e76f33c5b84574a", + "type": "mysql", + "z": "05d4cb231221b842", + "g": "443b758222662fdf", + "mydb": "fc9634aabefee16b", + "name": "Log Alert to DB", + "x": 640, + "y": 860, + "wires": [ + [] + ] + }, + { + "id": "87ed4eae56c5ef99", + "type": "link in", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "link in 9", + "links": [ + "6de9cd8265d1e821", + "cc31f7b315638ba5" + ], + "x": 275, + "y": 400, + "wires": [ + [ + "765441c17d3d41b6" + ] + ] + }, + { + "id": "6de9cd8265d1e821", + "type": "link out", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "link out 9", + "mode": "link", + "links": [ + "87ed4eae56c5ef99" + ], + "x": 1935, + "y": 660, + "wires": [] + }, + { + "id": "bb14a0293698c0e0", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Record KPI History", + "func": "// Complete Record KPI History function with robust initialization and averaging\n\nconst state = global.get(\"state\") || {};\nconst saveState = () => global.set(\"state\", state);\n\n// ========== INITIALIZATION ==========\n// Initialize buffer\nlet buffer = state.kpiBuffer;\nif (!buffer || !Array.isArray(buffer)) {\n buffer = [];\n state.kpiBuffer = buffer;\n node.warn('[KPI History] Initialized kpiBuffer');\n}\n\n// Initialize last record time\nlet lastRecordTime = state.lastKPIRecordTime;\nif (!lastRecordTime || typeof lastRecordTime !== 'number') {\n // Set to 1 minute ago to ensure immediate recording on startup\n lastRecordTime = Date.now() - 60000;\n state.lastKPIRecordTime = lastRecordTime;\n node.warn('[KPI History] Initialized lastKPIRecordTime');\n}\n\n// ========== ACCUMULATE ==========\nconst kpis = msg.payload?.kpis || msg.kpis;\nif (!kpis) {\n node.warn('[KPI History] No KPIs in message, skipping');\n saveState();\n return null;\n}\n\nbuffer.push({\n tsMs: Date.now(),\n oee: kpis.oee || 0,\n availability: kpis.availability || 0,\n performance: kpis.performance || 0,\n quality: kpis.quality || 0\n});\n\n// Prevent buffer from growing too large (safety limit)\nif (buffer.length > 100) {\n buffer = buffer.slice(-60); // Keep last 60 entries\n node.warn('[KPI History] Buffer exceeded 100 entries, trimmed to 60');\n}\n\nstate.kpiBuffer = buffer;\nsaveState();\n\n// ========== CHECK IF TIME TO RECORD ==========\nconst now = Date.now();\nconst timeSinceLastRecord = now - lastRecordTime;\nconst ONE_MINUTE = 60 * 1000;\n\nif (timeSinceLastRecord < ONE_MINUTE) {\n // Not time to record yet\n return null; // Don't send to charts yet\n}\n\n// ========== CALCULATE AVERAGES ==========\nif (buffer.length === 0) {\n node.warn('[KPI History] Buffer empty at recording time, skipping');\n return null;\n}\n\nconst avg = {\n oee: buffer.reduce((sum, d) => sum + d.oee, 0) / buffer.length,\n availability: buffer.reduce((sum, d) => sum + d.availability, 0) / buffer.length,\n performance: buffer.reduce((sum, d) => sum + d.performance, 0) / buffer.length,\n quality: buffer.reduce((sum, d) => sum + d.quality, 0) / buffer.length\n};\n\nnode.warn(`[KPI History] Recording averaged KPIs from ${buffer.length} samples: OEE=${avg.oee.toFixed(1)}%`);\n\n// ========== RECORD TO HISTORY ==========\n// Load history arrays\nlet oeeHist = state.realOEE || [];\nlet availHist = state.realAvailability || [];\nlet perfHist = state.realPerformance || [];\nlet qualHist = state.realQuality || [];\n\n// Append averaged values\noeeHist.push({ tsMs: now, value: Math.round(avg.oee * 10) / 10 });\navailHist.push({ tsMs: now, value: Math.round(avg.availability * 10) / 10 });\nperfHist.push({ tsMs: now, value: Math.round(avg.performance * 10) / 10 });\nqualHist.push({ tsMs: now, value: Math.round(avg.quality * 10) / 10 });\n\n// Trim arrays (avoid memory explosion)\noeeHist = oeeHist.slice(-300);\navailHist = availHist.slice(-300);\nperfHist = perfHist.slice(-300);\nqualHist = qualHist.slice(-300);\n\n// Save\nstate.realOEE = oeeHist;\nstate.realAvailability = availHist;\nstate.realPerformance = perfHist;\nstate.realQuality = qualHist;\n\n// Update state\nstate.lastKPIRecordTime = now;\nstate.kpiBuffer = []; // Clear buffer\nsaveState();\n\n// Send to graphs\nreturn {\n topic: \"chartsData\",\n payload: {\n oee: oeeHist,\n availability: availHist,\n performance: perfHist,\n quality: qualHist\n }\n};\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1750, + "y": 660, + "wires": [ + [ + "6de9cd8265d1e821" + ] + ] + }, + { + "id": "fbed0d5d49b02e4c", + "type": "inject", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "Init on Deploy", + "props": [ + { + "p": "payload" + } + ], + "repeat": "", + "crontab": "", + "once": true, + "onceDelay": 0.1, + "topic": "", + "payload": "", + "payloadType": "date", + "x": 380, + "y": 220, + "wires": [ + [ + "e6d76d15a304de1a" + ] + ] + }, + { + "id": "e6d76d15a304de1a", + "type": "function", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "Initialize Global Variables", + "func": "node.warn(\"[INIT] Initializing global variables\");\n\nconst settings = global.get(\"settings\") || {};\nconst state = global.get(\"state\") || {};\n\nlet fileSettings = null;\ntry {\n fileSettings = global.get(\"settings\", \"file\");\n} catch (err) {\n fileSettings = null;\n}\nif (fileSettings && typeof fileSettings === \"object\") {\n // ✨ Eliminado: import de moldTotal/moldActive (ya no se usa).\n // Las cavidades vienen ÚNICAMENTE de la WO de la BD.\n if (!Array.isArray(settings.shifts) && Array.isArray(fileSettings.shifts)) {\n settings.shifts = fileSettings.shifts;\n }\n if (settings.shiftChangeCompensation == null && fileSettings.shiftChangeCompensation != null) {\n settings.shiftChangeCompensation = fileSettings.shiftChangeCompensation;\n }\n if (settings.lunchBreakMinutes == null && fileSettings.lunchBreakMinutes != null) {\n settings.lunchBreakMinutes = fileSettings.lunchBreakMinutes;\n }\n if (settings.thresholdMultiplier == null && fileSettings.thresholdMultiplier != null) {\n settings.thresholdMultiplier = fileSettings.thresholdMultiplier;\n }\n}\n\n// ✨ Eliminado: lectura del moldCache (cache global viejo).\n// Limpiar variables del cache viejo del state si quedaron de versiones previas.\ndelete state.lastMoldActive;\ndelete state.lastMoldTotal;\ndelete state.moldByWorkOrder;\n\n// KPI Buffer for averaging\nif (!Array.isArray(state.kpiBuffer)) {\n state.kpiBuffer = [];\n node.warn(\"[INIT] Set state.kpiBuffer to []\");\n}\n\n// Last KPI record time - set to 1 min ago for immediate first record\nif (typeof state.lastKPIRecordTime !== \"number\") {\n state.lastKPIRecordTime = Date.now() - 60000;\n node.warn(\"[INIT] Set state.lastKPIRecordTime\");\n}\n\n// Last machine cycle time - set to now to prevent immediate 0% availability\nif (typeof state.lastMachineCycleTime !== \"number\") {\n state.lastMachineCycleTime = Date.now();\n node.warn(\"[INIT] Set state.lastMachineCycleTime to prevent 0% availability on startup\");\n}\n\n// Last KPI values\nif (!state.lastKPIValues || typeof state.lastKPIValues !== \"object\") {\n state.lastKPIValues = {};\n node.warn(\"[INIT] Set state.lastKPIValues to {}\");\n}\n\n// KPI Startup Mode - ensure clean state on deploy\nstate.kpiStartupMode = false;\nnode.warn(\"[INIT] Set state.kpiStartupMode to false\");\n\n// Tracking flags - ensure clean state\nif (typeof state.trackingEnabled !== \"boolean\") {\n state.trackingEnabled = false;\n}\nif (typeof state.productionStarted !== \"boolean\") {\n state.productionStarted = false;\n}\n\n// Settings defaults\nif (!Array.isArray(settings.shifts) || settings.shifts.length === 0) {\n settings.shifts = [{ start: \"06:00\", end: \"15:00\" }];\n node.warn(\"[INIT] Set default shift: 06:00-15:00\");\n}\n\nif (typeof settings.shiftChangeCompensation !== \"number\") {\n settings.shiftChangeCompensation = 10;\n}\n\nif (typeof settings.lunchBreakMinutes !== \"number\") {\n settings.lunchBreakMinutes = 30;\n}\n\nif (typeof settings.thresholdMultiplier !== \"number\") {\n settings.thresholdMultiplier = 1.5;\n}\n\n// State defaults\nif (typeof state.operatingTime !== \"number\") {\n state.operatingTime = 0;\n}\n\nif (typeof state.stopTime !== \"number\") {\n state.stopTime = 0;\n}\n\nif (typeof state.plannedProductionTime !== \"number\") {\n state.plannedProductionTime = 0;\n}\n\nif (!Object.prototype.hasOwnProperty.call(state, \"lastCycleCompletionTime\")) {\n state.lastCycleCompletionTime = null;\n}\n\nglobal.set(\"settings\", settings);\ntry {\n global.set(\"settings\", settings, \"file\");\n} catch (err) {\n // ignore if file store is not configured\n}\nglobal.set(\"state\", state);\n\n// ✨ Borra el moldCache de disco (variable obsoleta)\ntry {\n global.set(\"moldCache\", null, \"file\");\n} catch (err) {\n // ignore\n}\nglobal.set(\"moldCache\", null);\n\nnode.warn(\"[INIT] Global variable initialization complete\");\n\n// Trigger restore-session to check for running work orders\nconst restoreMsg = { action: \"restore-session\" };\nreturn [null, restoreMsg];", + "outputs": 2, + "timeout": "", + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 630, + "y": 220, + "wires": [ + [], + [ + "ad66f1edaba40aaa" + ] + ] + }, + { + "id": "d45345c05485d114", + "type": "switch", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "DB Guard (Cycles)", + "property": "topic", + "propertyType": "msg", + "rules": [ + { + "t": "istype", + "v": "string", + "vt": "string" + } + ], + "checkall": "true", + "repair": false, + "outputs": 1, + "x": 1690, + "y": 380, + "wires": [ + [ + "bfb9b7c7af23bd5c" + ] + ] + }, + { + "id": "cc31f7b315638ba5", + "type": "link out", + "z": "05d4cb231221b842", + "g": "9221454c45afd1ba", + "name": "link out 10", + "mode": "link", + "links": [ + "87ed4eae56c5ef99" + ], + "x": 1955, + "y": 80, + "wires": [] + }, + { + "id": "16b778a1349b8102", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Progress Check Handler", + "func": "// Handle DB result from start-work-order progress check\nconst state = global.get(\"state\") || {};\n\nconst persistState = () => {\n global.set(\"state\", state);\n};\n\nif (msg._mode === \"start-check-progress\") {\n const order = flow.get(\"pendingWorkOrder\");\n\n if (!order || !order.id) {\n node.error(\"No pending work order found\", msg);\n return [null, null];\n }\n\n // Get progress from DB query result\n const dbRow = (Array.isArray(msg.payload) && msg.payload.length > 0) ? msg.payload[0] : null;\n const cycleCount = dbRow ? (Number(dbRow.cycle_count) || 0) : 0;\n const goodParts = dbRow ? (Number(dbRow.good_parts) || 0) : 0;\n const scrapParts = dbRow ? (Number(dbRow.scrap_parts) || 0) : 0;\n const targetQty = dbRow ? (Number(dbRow.target_qty) || 0) : (Number(order.target) || 0);\n const cavitiesTotal = dbRow ? (Number(dbRow.cavities_total) || 0) : 0;\n const cavitiesActive = dbRow ? (Number(dbRow.cavities_active) || 0) : 0;\n\n const hasProgress = cycleCount > 0 || (goodParts + scrapParts) > 0;\n state.activeOrderHasProgress = hasProgress;\n state.activeOrderId = order.id;\n\n node.warn(`[PROGRESS-CHECK] WO ${order.id}: cycles=${cycleCount}, good=${goodParts}, target=${targetQty}, cavitiesActive=${cavitiesActive}, cavitiesTotal=${cavitiesTotal}`);\n\n // ✨ La WO de la BD es la única fuente de cavidades\n // Se popula con todos los aliases para compatibilidad con código existente\n if (Number.isFinite(cavitiesActive) && cavitiesActive > 0) {\n order.cavitiesActive = cavitiesActive;\n order.cavities = cavitiesActive; // alias\n }\n if (Number.isFinite(cavitiesTotal) && cavitiesTotal > 0) {\n order.cavitiesTotal = cavitiesTotal;\n order.cavities_total = cavitiesTotal; // alias\n }\n\n // Check if work order has existing progress\n if (hasProgress) {\n // Work order has progress - send prompt to UI\n node.warn(`[PROGRESS-CHECK] Work order has existing progress - sending prompt to UI`);\n\n const promptMsg = {\n _mode: \"resume-prompt\",\n topic: \"resumePrompt\",\n payload: {\n id: order.id,\n sku: order.sku || \"\",\n cycleCount: cycleCount,\n goodParts: goodParts,\n targetQty: targetQty,\n progressPercent: targetQty > 0 ? Math.round((goodParts / targetQty) * 100) : 0,\n // Include full order object for resume/restart actions\n order: { ...order, cycleCount: cycleCount, goodParts: goodParts, scrapParts: scrapParts }\n }\n };\n\n persistState();\n return [null, promptMsg];\n } else {\n // No existing progress - proceed with normal start\n // But still use DB values (even if 0) to ensure DB is source of truth\n node.warn(`[PROGRESS-CHECK] No existing progress - proceeding with normal start`);\n\n state.activeOrderHasProgress = false;\n\n // Update order object with DB values (makes DB the source of truth)\n order.cycleCount = cycleCount; // Will be 0 from DB\n order.goodParts = goodParts; // Will be 0 from DB\n order.scrapParts = scrapParts; // Will be 0 from DB\n order.target = targetQty; // From DB\n\n const startMsg = {\n _mode: \"start\",\n startOrder: order,\n topic: \"UPDATE work_orders SET status = CASE WHEN work_order_id = ? THEN 'RUNNING' ELSE 'PENDING' END, updated_at = CASE WHEN work_order_id = ? THEN NOW() ELSE updated_at END, cavities_total = COALESCE(NULLIF(?,0), cavities_total), cavities_active = COALESCE(NULLIF(?,0), cavities_active) WHERE status <> 'DONE'\",\n payload: [\n order.id,\n order.id,\n Number(order.cavitiesTotal || order.cavities_total || 0),\n Number(order.cavitiesActive || order.cavities_active || order.cavities || 0)\n ]\n };\n\n // Initialize global state with DB values (even if 0)\n state.activeWorkOrder = order;\n state.cycleCount = cycleCount;\n flow.set(\"lastMachineState\", 0);\n state.scrapPromptIssuedFor = null;\n persistState();\n\n node.warn(`[PROGRESS-CHECK] Initialized from DB: cycles=${cycleCount}, good=${goodParts}, scrap=${scrapParts}, cavitiesActive=${cavitiesActive}`);\n\n return [startMsg, null];\n }\n}\n\n// Pass through all other messages\nreturn [msg, null];", + "outputs": 2, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1910, + "y": 540, + "wires": [ + [ + "d569d16fc0423be8" + ], + [ + "babe66a431cd1760" + ] + ] + }, + { + "id": "68709c57900ed80e", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Merge Cycle + KPI Data", + "func": "// ============================================================\n// DATA MERGER - Combines Cycle + KPI data for Anomaly Detector\n// ============================================================\n\nconst state = global.get(\"state\") || {};\nconst settings = global.get(\"settings\") || {};\n\n// Get KPIs from incoming message (from Calculate KPIs node)\nconst kpis = msg.kpis || msg.payload?.kpis || {};\n\n// Get cycle data from global context\nconst activeOrder = state.activeWorkOrder || {};\nconst cycleCount = state.cycleCount || 0;\nconst moldByWorkOrder = state.moldByWorkOrder || {};\nconst cavities = Number(\n activeOrder.cavities ??\n moldByWorkOrder[activeOrder.id]?.active ??\n state.lastMoldActive ??\n settings.moldActive ??\n 0\n);\nconst lastActualCycleTime = Number(state.lastActualCycleTime || 0);\n\n\n// Build cycle object with all necessary data\nconst cycle = {\n id: activeOrder.id,\n sku: activeOrder.sku || \"\",\n cycles: cycleCount,\n goodParts: Number(activeOrder.goodParts) || 0,\n scrapParts: Number(activeOrder.scrapParts) || 0,\n target: Number(activeOrder.target) || 0,\n cycleTime: Number(activeOrder.cycleTime || activeOrder.theoreticalCycleTime || 0),\n progressPercent: Number(activeOrder.progressPercent) || 0,\n cavities: cavities,\n actualCycleTime: lastActualCycleTime\n\n};\n\n// Merge both into the message\nmsg.cycle = cycle;\nmsg.kpis = kpis;\n\n//node.warn(`[DATA MERGER] Merged cycle (count: ${cycleCount}) + KPIs (OEE: ${kpis.oee || 0}%) for anomaly detection`);\n\nreturn msg;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1330, + "y": 480, + "wires": [ + [ + "dc24aea451e9b976" + ] + ] + }, + { + "id": "dc24aea451e9b976", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Anomaly Detector", + "func": "\n// ============================================================\n// ANOMALY DETECTOR - FIXED VERSION\n// Key fixes:\n// 1. Removed duplicate suppression that blocks microstop alerts\n// 2. Added periodic updates for active macrostops\n// 3. Improved logging for debugging\n// ============================================================\n\nconst state = global.get(\"state\") || {};\nconst settings = global.get(\"settings\") || {};\nconst anomaly = global.get(\"anomaly\") || {};\n\n// Suppress anomaly detection during mold change\nif (state.moldChange && state.moldChange.active) return null;\n\nconst cycle = msg.cycle || {};\nconst kpis = msg.kpis || {};\nconst activeOrder = state.activeWorkOrder || {};\nconst cycleCountNow = Number(cycle.cycles || 0);\n\n\n// Must have active work order to detect anomalies\nif (!activeOrder.id) {\n return null;\n}\n\nconst theoreticalCycleTime = Number(activeOrder.cycleTime) || 0;\nconst now = Date.now();\n\n// Get or initialize anomaly tracking state\nlet anomalyState = global.get(\"anomalyState\") || {\n lastCycleTime: Number(state.lastMachineCycleTime || now),\n //lastCycleCount: cycleCountNow,\n lastCycleCount: 0,\n activeStoppageEvent: null,\n oeeHistory: [],\n performanceHistory: [],\n qualityHistory: [],\n activeOeeDrop: false,\n oeeLowStreak: 0,\n activeQualitySpike: false,\n qualityHighStreak: 0,\n lastSlowCycleCount: 0,\n lastCycleEventCount: 0,\n lastStoppageUpdateMs: 0\n};\n// Reset anomaly cycle baseline when work order changes\nif (anomalyState.work_order_id && anomalyState.work_order_id !== activeOrder.id) {\n node.warn(`[RESET] Work order changed ${anomalyState.work_order_id} -> ${activeOrder.id}. Resetting anomalyState counters.`);\n anomalyState.lastCycleCount = 0;\n anomalyState.lastCycleEventCount = 0;\n anomalyState.lastSlowCycleCount = 0;\n anomalyState.activeStoppageEvent = null;\n anomalyState.lastStoppageUpdateMs = 0;\n}\nanomalyState.work_order_id = activeOrder.id;\n\nif (!isFinite(anomalyState.lastCycleTime)) {\n anomalyState.lastCycleTime = Number(state.lastMachineCycleTime || now);\n}\nif (!isFinite(anomalyState.lastCycleCount)) {\n anomalyState.lastCycleCount = cycleCountNow;\n}\n\nconst stateLastCycleTime = Number(state.lastMachineCycleTime || 0);\n//node.warn(`[TS CHECK] state.lastMachineCycleTime=${stateLastCycleTime} iso=${stateLastCycleTime ? new Date(stateLastCycleTime).toISOString() : 'n/a'}`);\nlet lastCycleTime = Number(anomalyState.lastCycleTime || 0);\nif (stateLastCycleTime > 0 && (lastCycleTime <= 0 || stateLastCycleTime > lastCycleTime)) {\n lastCycleTime = stateLastCycleTime;\n}\nconst prevCount = Number(anomalyState.lastCycleCount || 0);\n\n// If PLC/logic reset the counter (or new batch), re-baseline\nif (cycleCountNow > 0 && prevCount > 0 && cycleCountNow < prevCount) {\n node.warn(`[RESET] cycle counter reset detected: ${prevCount} -> ${cycleCountNow}. Re-baselining.`);\n anomalyState.lastCycleCount = cycleCountNow;\n anomalyState.lastCycleTime = stateLastCycleTime > 0 ? stateLastCycleTime : now;\n anomalyState.lastCycleEventCount = cycleCountNow;\n anomalyState.lastSlowCycleCount = cycleCountNow;\n anomalyState.activeStoppageEvent = null;\n anomalyState.lastStoppageUpdateMs = 0;\n}\nconst hasNewCycle = cycleCountNow > Number(anomalyState.lastCycleCount || 0);\n//node.warn(`[CYCLE CHECK PRE] cycleCountNow: ${cycleCountNow}, lastCycleCount: ${anomalyState.lastCycleCount}, hasNewCycle: ${cycleCountNow > Number(anomalyState.lastCycleCount || 0)}`);\n//node.warn(`[TS CHECK] stateLastCycleTime=${stateLastCycleTime} iso=${stateLastCycleTime ? new Date(stateLastCycleTime).toISOString() : 'n/a'}`);\nif (hasNewCycle) {\n anomalyState.lastCycleCount = cycleCountNow;\n anomalyState.lastCycleTime = stateLastCycleTime > 0 ? stateLastCycleTime : now;\n lastCycleTime = anomalyState.lastCycleTime;\n}\n//node.warn(`[CYCLE CHECK] cycleCountNow: ${cycleCountNow}, lastCycleCount: ${anomalyState.lastCycleCount}, hasNewCycle: ${hasNewCycle}`);\n//node.warn(`[CYCLE CHECK] msg.cycle.cycles: ${msg.cycle.cycles}, type: ${typeof msg.cycle.cycles}`);\n// Configuration\nconst OEE_THRESHOLD = settings.oeeAlertThreshold || 90;\nconst HISTORY_WINDOW = 20;\nconst QUALITY_SPIKE_THRESHOLD = 5;\nconst PERFORMANCE_THRESHOLD = settings.performanceThreshold || 85;\nconst microMultiplier = Number(settings.thresholdMultiplier || 1.5);\nconst macroMultiplier = Math.max(\n microMultiplier,\n Number(settings.macroStoppageMultiplier || 5)\n);\n\n// NEW: Update interval for macrostop notifications (default 10 seconds)\nconst updateIntervalMs = Number(settings.stoppageUpdateIntervalMs || 10000);\n\nconst detectedAnomalies = [];\n\nconst DEFAULT_DOWNTIME_REASON = {\n type: \"downtime\",\n categoryId: \"sin-clasificar\",\n categoryLabel: \"Sin clasificar\",\n detailId: \"pendiente\",\n detailLabel: \"Pendiente de clasificar\",\n reasonCode: \"PENDIENTE\",\n reasonText: \"Pendiente de clasificar\"\n};\n\nfunction applyDefaultDowntimeReason(event) {\n if (!event || (event.anomaly_type !== \"microstop\" && event.anomaly_type !== \"macrostop\")) {\n return event;\n }\n if (event.reason && typeof event.reason === \"object\") {\n return event;\n }\n return {\n ...event,\n reason: { ...DEFAULT_DOWNTIME_REASON }\n };\n}\n\n// ============================================================\n// TIER 1: CYCLE CLASSIFICATION + STOPPAGE WATCHDOG\n// ============================================================\nif (theoreticalCycleTime > 0) {\n const actualCycleTime = Number(cycle.actualCycleTime || 0);\n const currentCycleCount = Number(cycle.cycles || 0);\n const lastCycleEventCount = Number(\n anomalyState.lastCycleEventCount ?? anomalyState.lastSlowCycleCount ?? 0\n );\n\n const microThresholdSec = theoreticalCycleTime * microMultiplier;\n const macroThresholdSec = theoreticalCycleTime * macroMultiplier;\n const timeSinceLastCycleSec = lastCycleTime > 0 ? (now - lastCycleTime) / 1000 : 0;\n\n // DEBUG LOGGING\n // node.warn(`[DEBUG] actualCycleTime: ${actualCycleTime}s, theoretical: ${theoreticalCycleTime}s`);\n // node.warn(`[DEBUG] microThreshold: ${microThresholdSec}s, macroThreshold: ${macroThresholdSec}s`);\n // node.warn(`[DEBUG] timeSinceLastCycle: ${timeSinceLastCycleSec}s, hasNewCycle: ${hasNewCycle}`);\n\n let resolvedStoppageThisCycle = false;\n\n // Resolve any active stoppage when a new cycle arrives\n if (anomalyState.activeStoppageEvent && hasNewCycle) {\n const resolvedDurationSec = actualCycleTime > 0 ? actualCycleTime : timeSinceLastCycleSec;\n\n detectedAnomalies.push({\n ...anomalyState.activeStoppageEvent,\n status: \"resolved\",\n resolved_at: now,\n auto_resolved: true,\n data: {\n ...anomalyState.activeStoppageEvent.data,\n stoppage_duration_seconds: Math.round(resolvedDurationSec)\n },\n tsMs: now\n });\n\n node.warn(`[RESOLVED] Stoppage resolved: ${anomalyState.activeStoppageEvent.anomaly_type}, duration: ${resolvedDurationSec}s`);\n anomalyState.activeStoppageEvent = null;\n anomalyState.lastStoppageUpdateMs = 0;\n resolvedStoppageThisCycle = true;\n }\n\n if (hasNewCycle) {\n //node.warn(`[CYCLE RESUME] New cycle detected! Count: ${cycleCountNow}, lastCount: ${anomalyState.lastCycleCount}`);\n //node.warn(`[CYCLE RESUME] lastCycleTime updated from ${lastCycleTime} to ${anomalyState.lastCycleTime}`);\n //node.warn(`[CYCLE RESUME] activeStoppageEvent cleared: ${anomalyState.activeStoppageEvent === null}`);\n }\n\n // Add before the periodic update section (around line ~270)\n // if (anomalyState.activeStoppageEvent) {\n // node.warn(`[WATCHDOG] Active stoppage exists: ${anomalyState.activeStoppageEvent.anomaly_type}`);\n //node.warn(`[WATCHDOG] timeSinceLastCycle: ${timeSinceLastCycleSec}s, lastCycleTime: ${lastCycleTime}, now: ${now}`);\n // }\n\n // Per-cycle classification (uses actualCycleTime)\n if (actualCycleTime > 0 && currentCycleCount > lastCycleEventCount) {\n let cycleEvent = null;\n\n const SLOW_MARGIN = Number(settings.slowCycleMarginPercent ?? 5); // 5% default\n\n if (\n actualCycleTime > 0 &&\n actualCycleTime > theoreticalCycleTime * (1 + SLOW_MARGIN / 100) &&\n actualCycleTime < microThresholdSec\n ) {\n const deltaPercent = ((actualCycleTime - theoreticalCycleTime) / theoreticalCycleTime) * 100;\n\n cycleEvent = {\n anomaly_type: \"slow-cycle\",\n severity: \"warning\",\n requires_ack: false,\n title: \"Slow Cycle Detected\",\n description: `Cycle took ${actualCycleTime.toFixed(1)}s (+${deltaPercent.toFixed(0)}% vs ${theoreticalCycleTime.toFixed(1)}s target)`,\n data: {\n actual_cycle_time: actualCycleTime,\n theoretical_cycle_time: theoreticalCycleTime,\n delta_percent: Math.round(deltaPercent),\n micro_threshold_multiplier: microMultiplier,\n macro_threshold_multiplier: macroMultiplier\n },\n kpi_snapshot: {\n oee: kpis.oee || 0,\n availability: kpis.availability || 0,\n performance: kpis.performance || 0,\n quality: kpis.quality || 0\n },\n work_order_id: activeOrder.id,\n cycle_count: currentCycleCount,\n tsMs: now\n };\n\n //node.warn(`[SLOW-CYCLE] ${actualCycleTime.toFixed(1)}s (expected ${theoreticalCycleTime}s)`);\n\n } /*else if (actualCycleTime >= macroThresholdSec) {\n cycleEvent = {\n anomaly_type: \"macrostop\",\n severity: \"critical\",\n requires_ack: true,\n title: \"Macrostop Detected\",\n description: `Cycle gap ${actualCycleTime.toFixed(1)}s (threshold: ${macroThresholdSec.toFixed(1)}s)`,\n data: {\n stoppage_duration_seconds: Math.round(actualCycleTime),\n theoretical_cycle_time: theoreticalCycleTime,\n micro_threshold_multiplier: microMultiplier,\n macro_threshold_multiplier: macroMultiplier\n },\n kpi_snapshot: {\n oee: kpis.oee || 0,\n availability: kpis.availability || 0,\n performance: kpis.performance || 0,\n quality: kpis.quality || 0\n },\n work_order_id: activeOrder.id,\n cycle_count: currentCycleCount,\n tsMs: now,\n status: \"resolved\" // Changed to resolved since cycle completed\n };\n\n node.warn(`[MACROSTOP] ${actualCycleTime.toFixed(1)}s gap detected`);\n }*/\n\n // FIXED: Always push cycle events (removed duplicate suppression)\n if (cycleEvent) {\n detectedAnomalies.push(cycleEvent);\n //node.warn(`[CYCLE EVENT] Added ${cycleEvent.anomaly_type} to detectedAnomalies`);\n }\n\n anomalyState.lastCycleEventCount = currentCycleCount;\n anomalyState.lastSlowCycleCount = currentCycleCount;\n }\n\n // No new cycle yet: start or escalate stoppage\n if (!hasNewCycle && lastCycleTime > 0) {\n // Start stoppage once when we cross micro threshold\n if (!anomalyState.activeStoppageEvent && timeSinceLastCycleSec >= microThresholdSec) {\n const isMacro = timeSinceLastCycleSec >= macroThresholdSec;\n const anomalyType = isMacro ? \"macrostop\" : \"microstop\";\n const severity = isMacro ? \"critical\" : \"warning\";\n\n const stoppageEvent = {\n alert_id: `${anomalyType}:${activeOrder.id}:${lastCycleTime}`,\n anomaly_type: anomalyType,\n severity,\n requires_ack: true,\n title: isMacro ? \"Macrostop In Progress\" : \"Microstop In Progress\",\n description: `No cycles for ${timeSinceLastCycleSec.toFixed(0)}s (expected cycle every ${theoreticalCycleTime}s)`,\n data: {\n stoppage_duration_seconds: Math.round(timeSinceLastCycleSec),\n theoretical_cycle_time: theoreticalCycleTime,\n last_cycle_timestamp: lastCycleTime,\n micro_threshold_multiplier: microMultiplier,\n macro_threshold_multiplier: macroMultiplier\n },\n kpi_snapshot: {\n oee: kpis.oee || 0,\n availability: kpis.availability || 0,\n performance: kpis.performance || 0,\n quality: kpis.quality || 0\n },\n work_order_id: activeOrder.id,\n cycle_count: cycle.cycles || 0,\n tsMs: now,\n status: \"active\"\n };\n\n detectedAnomalies.push(stoppageEvent);\n anomalyState.activeStoppageEvent = stoppageEvent;\n anomalyState.lastStoppageUpdateMs = now;\n //node.warn(`[STOPPAGE START] ${anomalyType} started at ${timeSinceLastCycleSec.toFixed(0)}s`);\n }\n\n // Escalate micro -> macro once\n if (\n anomalyState.activeStoppageEvent &&\n anomalyState.activeStoppageEvent.anomaly_type === \"microstop\" &&\n timeSinceLastCycleSec >= macroThresholdSec\n ) {\n detectedAnomalies.push({\n ...anomalyState.activeStoppageEvent,\n status: \"resolved\",\n resolved_at: now,\n auto_resolved: true,\n requires_ack: false,\n data: {\n ...anomalyState.activeStoppageEvent.data,\n stoppage_duration_seconds: Math.round(timeSinceLastCycleSec)\n },\n tsMs: now\n });\n\n const macroEvent = {\n alert_id: `macrostop:${activeOrder.id}:${lastCycleTime}`,\n anomaly_type: \"macrostop\",\n severity: \"critical\",\n requires_ack: true,\n title: \"Macrostop In Progress\",\n description: `No cycles for ${timeSinceLastCycleSec.toFixed(0)}s (expected cycle every ${theoreticalCycleTime}s)`,\n data: {\n stoppage_duration_seconds: Math.round(timeSinceLastCycleSec),\n theoretical_cycle_time: theoreticalCycleTime,\n last_cycle_timestamp: lastCycleTime,\n micro_threshold_multiplier: microMultiplier,\n macro_threshold_multiplier: macroMultiplier\n },\n kpi_snapshot: {\n oee: kpis.oee || 0,\n availability: kpis.availability || 0,\n performance: kpis.performance || 0,\n quality: kpis.quality || 0\n },\n work_order_id: activeOrder.id,\n cycle_count: cycle.cycles || 0,\n tsMs: now,\n status: \"active\"\n };\n\n detectedAnomalies.push(macroEvent);\n anomalyState.activeStoppageEvent = macroEvent;\n anomalyState.lastStoppageUpdateMs = now;\n //node.warn(`[ESCALATION] Microstop -> Macrostop at ${timeSinceLastCycleSec.toFixed(0)}s`);\n }\n\n // NEW: Send periodic updates for active macrostops\n if (\n anomalyState.activeStoppageEvent &&\n anomalyState.activeStoppageEvent.anomaly_type === \"macrostop\"\n ) {\n const timeSinceLastUpdate = now - (anomalyState.lastStoppageUpdateMs || 0);\n \n if (timeSinceLastUpdate >= updateIntervalMs) {\n const prev = anomalyState.activeStoppageEvent;\n\n // 1) AUTO-ACK the previous active macrostop alert\n const autoAck = {\n ...prev,\n status: \"resolved\",\n resolved_at: now,\n auto_resolved: true,\n requires_ack: false,\n title: \"Macrostop Updated\",\n description: \"Auto-acknowledged due to periodic refresh\",\n tsMs: now,\n is_auto_ack: true\n };\n\n // 2) Send a NEW active macrostop alert with updated duration + NEW alert_id\n const refreshed = {\n ...prev,\n alert_id: `macrostop:${activeOrder.id}:${now}`, // new instance id so UI treats it as new\n status: \"active\",\n requires_ack: true,\n title: \"Macrostop Ongoing\",\n description: `Machine still stopped for ${timeSinceLastCycleSec.toFixed(0)}s (expected cycle every ${theoreticalCycleTime}s)`,\n data: {\n ...prev.data,\n stoppage_duration_seconds: Math.round(timeSinceLastCycleSec)\n },\n kpi_snapshot: {\n oee: kpis.oee || 0,\n availability: kpis.availability || 0,\n performance: kpis.performance || 0,\n quality: kpis.quality || 0\n },\n tsMs: now,\n is_update: true\n };\n\n detectedAnomalies.push(autoAck, refreshed);\n\n // IMPORTANT: set the active event to the refreshed one\n anomalyState.activeStoppageEvent = refreshed;\n anomalyState.lastStoppageUpdateMs = now;\n\n //node.warn(`[MACROSTOP REFRESH] Auto-acked previous, new duration: ${timeSinceLastCycleSec.toFixed(0)}s`);\n }\n }\n }\n}\n\n\n\n// ============================================================\n// TIER 2: OEE DROP DETECTION\n// Trigger: OEE falls below threshold\n// ============================================================\nconst currentOEE = Number(kpis.oee) || 0;\n\nif (currentOEE > 0) {\n const lowThreshold = OEE_THRESHOLD; // e.g. 90\n const recoveryThreshold = OEE_THRESHOLD + 2; // some hysteresis\n\n if (currentOEE < lowThreshold) {\n // Count consecutive low points\n anomalyState.oeeLowStreak = (anomalyState.oeeLowStreak || 0) + 1;\n\n const REQUIRED_STREAK = 3; // only alert after 3 bad readings\n\n // Only fire when we ENTER the bad zone\n if (!anomalyState.activeOeeDrop &&\n anomalyState.oeeLowStreak >= REQUIRED_STREAK) {\n\n let severity = 'warning';\n if (currentOEE < 75) severity = 'critical';\n\n detectedAnomalies.push({\n anomaly_type: 'oee-drop',\n severity,\n title: 'OEE Below Threshold',\n description: `OEE at ${currentOEE.toFixed(1)}% (threshold: ${OEE_THRESHOLD}%)`,\n data: {\n current_oee: currentOEE,\n threshold: OEE_THRESHOLD,\n delta: OEE_THRESHOLD - currentOEE\n },\n kpi_snapshot: {\n oee: kpis.oee || 0,\n availability: kpis.availability || 0,\n performance: kpis.performance || 0,\n quality: kpis.quality || 0\n },\n work_order_id: activeOrder.id,\n cycle_count: cycle.cycles || 0,\n tsMs: now,\n status: 'active'\n });\n\n anomalyState.activeOeeDrop = true;\n //node.warn(`[ANOMALY] OEE drop started at ${currentOEE.toFixed(1)}%`);\n }\n\n } else if (currentOEE >= recoveryThreshold) {\n // We are OUT of the bad zone\n anomalyState.oeeLowStreak = 0;\n\n if (anomalyState.activeOeeDrop) {\n detectedAnomalies.push({\n anomaly_type: 'oee-drop',\n severity: 'info',\n title: 'OEE Recovered',\n description: `OEE recovered to ${currentOEE.toFixed(1)}% (threshold: ${OEE_THRESHOLD}%)`,\n data: {\n current_oee: currentOEE,\n threshold: OEE_THRESHOLD\n },\n kpi_snapshot: {\n oee: kpis.oee || 0,\n availability: kpis.availability || 0,\n performance: kpis.performance || 0,\n quality: kpis.quality || 0\n },\n work_order_id: activeOrder.id,\n cycle_count: cycle.cycles || 0,\n tsMs: now,\n status: 'resolved'\n });\n\n anomalyState.activeOeeDrop = false;\n //node.warn(`[ANOMALY] OEE recovered to ${currentOEE.toFixed(1)}%`);\n }\n }\n}\n\n// Update OEE history for trend analysis\nanomalyState.oeeHistory.push({ tsMs: now, value: currentOEE });\nif (anomalyState.oeeHistory.length > HISTORY_WINDOW) {\n anomalyState.oeeHistory.shift(); // Keep only recent history\n}\n\n// ============================================================\n// TIER 2: QUALITY SPIKE DETECTION\n// Trigger: Sudden increase in scrap/defect rate\n// ============================================================\nconst totalParts = (cycle.goodParts || 0) + (cycle.scrapParts || 0);\nconst currentScrapRate =\n totalParts > 0 ? ((cycle.scrapParts || 0) / totalParts) * 100 : 0;\n\n// Keep history for trend\nanomalyState.qualityHistory.push({ tsMs: now, value: currentScrapRate });\nif (anomalyState.qualityHistory.length > HISTORY_WINDOW) {\n anomalyState.qualityHistory.shift();\n}\n\n// Only evaluate when we have enough data and enough volume in this cycle\nconst MIN_SAMPLES = 5;\nconst MIN_PARTS_THIS_CYCLE = 10;\n\nif (\n anomalyState.qualityHistory.length >= MIN_SAMPLES &&\n totalParts >= MIN_PARTS_THIS_CYCLE\n) {\n const recentHistory = anomalyState.qualityHistory.slice(0, -1); // exclude current\n const avgScrapRate =\n recentHistory.reduce((sum, p) => sum + p.value, 0) /\n recentHistory.length;\n\n const scrapRateIncrease = currentScrapRate - avgScrapRate;\n\n const SPIKE_DELTA = QUALITY_SPIKE_THRESHOLD || 5; // your existing config\n const MIN_SCRAP_RATE = 5; // ignore small scrap percentages\n const RECOVERY_MARGIN = 2; // how far back towards avg to consider \"recovered\"\n\n // ----- When scrap is HIGH / SPIKE ZONE -----\n if (\n currentScrapRate > MIN_SCRAP_RATE &&\n scrapRateIncrease > SPIKE_DELTA\n ) {\n // count how many consecutive \"bad\" cycles\n anomalyState.qualityHighStreak =\n (anomalyState.qualityHighStreak || 0) + 1;\n\n const REQUIRED_STREAK = 2; // require 2 consecutive bad cycles\n\n // fire ONLY when we ENTER the spike (not every cycle)\n if (\n !anomalyState.activeQualitySpike &&\n anomalyState.qualityHighStreak >= REQUIRED_STREAK\n ) {\n let severity = \"warning\";\n if (scrapRateIncrease > 10 || currentScrapRate > 15) {\n severity = \"critical\";\n }\n\n detectedAnomalies.push({\n anomaly_type: \"quality-spike\",\n severity,\n title: \"Quality Issue Detected\",\n description: `Scrap rate at ${currentScrapRate.toFixed(\n 1\n )}% (avg: ${avgScrapRate.toFixed(\n 1\n )}%, +${scrapRateIncrease.toFixed(1)}%)`,\n data: {\n current_scrap_rate: currentScrapRate,\n average_scrap_rate: avgScrapRate,\n increase: scrapRateIncrease,\n scrap_parts: cycle.scrapParts || 0,\n total_parts: totalParts\n },\n kpi_snapshot: {\n oee: kpis.oee || 0,\n availability: kpis.availability || 0,\n performance: kpis.performance || 0,\n quality: kpis.quality || 0\n },\n work_order_id: activeOrder.id,\n cycle_count: cycle.cycles || 0,\n tsMs: now,\n status: \"active\"\n });\n\n anomalyState.activeQualitySpike = true;\n /*node.warn(\n `[ANOMALY] Quality spike started: scrap ${currentScrapRate.toFixed(\n 1\n )}% (avg ${avgScrapRate.toFixed(1)}%)`\n );*/\n }\n } else {\n // ----- When scrap is NORMAL / RECOVERY -----\n anomalyState.qualityHighStreak = 0;\n\n // if we had an active spike, send a single \"resolved\" event\n if (\n anomalyState.activeQualitySpike &&\n currentScrapRate <= avgScrapRate + RECOVERY_MARGIN\n ) {\n detectedAnomalies.push({\n anomaly_type: \"quality-spike\",\n severity: \"info\",\n title: \"Quality Issue Resolved\",\n description: `Scrap rate back to ${currentScrapRate.toFixed(\n 1\n )}% (avg: ${avgScrapRate.toFixed(1)}%)`,\n data: {\n current_scrap_rate: currentScrapRate,\n average_scrap_rate: avgScrapRate\n },\n kpi_snapshot: {\n oee: kpis.oee || 0,\n availability: kpis.availability || 0,\n performance: kpis.performance || 0,\n quality: kpis.quality || 0\n },\n work_order_id: activeOrder.id,\n cycle_count: cycle.cycles || 0,\n tsMs: now,\n status: \"resolved\"\n });\n\n anomalyState.activeQualitySpike = false;\n /*node.warn(\n `[ANOMALY] Quality spike resolved: scrap ${currentScrapRate.toFixed(\n 1\n )}%`\n );*/\n }\n }\n}\n\n// ============================================================\n// TIER 2: PERFORMANCE DEGRADATION\n// Trigger: Consistent underperformance over time\n// ============================================================\nconst currentPerformance = Number(kpis.performance) || 0;\nanomalyState.performanceHistory.push({ tsMs: now, value: currentPerformance });\nif (anomalyState.performanceHistory.length > HISTORY_WINDOW) {\n anomalyState.performanceHistory.shift();\n}\n\n// Check for sustained poor performance (at least 10 data points)\nif (anomalyState.performanceHistory.length >= 10) {\n const recent10 = anomalyState.performanceHistory.slice(-10);\n const avgPerformance = recent10.reduce((sum, point) => sum + point.value, 0) / recent10.length;\n\n const PERF_LOW_THRESHOLD = PERFORMANCE_THRESHOLD; // 85%\n const PERF_RECOVERY_THRESHOLD = PERFORMANCE_THRESHOLD + 3; // 88% to recover\n\n // Check if we're in degraded state\n if (avgPerformance > 0 && avgPerformance < PERF_LOW_THRESHOLD) {\n // Count consecutive low readings\n anomalyState.performanceLowStreak = (anomalyState.performanceLowStreak || 0) + 1;\n\n const REQUIRED_STREAK = 3; // Need 3 consecutive low readings\n\n // Only fire ONCE when entering degraded state\n if (!anomalyState.activePerformanceDegradation &&\n anomalyState.performanceLowStreak >= REQUIRED_STREAK) {\n\n let severity = 'warning';\n if (avgPerformance < 75) {\n severity = 'critical';\n }\n\n detectedAnomalies.push({\n anomaly_type: 'performance-degradation',\n severity: severity,\n title: `Performance Degradation`,\n description: `Performance at ${avgPerformance.toFixed(1)}% (sustained over last 10 cycles)`,\n data: {\n average_performance: avgPerformance,\n current_performance: currentPerformance,\n threshold: PERF_LOW_THRESHOLD,\n sample_size: 10\n },\n kpi_snapshot: {\n oee: kpis.oee || 0,\n availability: kpis.availability || 0,\n performance: kpis.performance || 0,\n quality: kpis.quality || 0\n },\n work_order_id: activeOrder.id,\n cycle_count: cycle.cycles || 0,\n tsMs: now,\n status: 'active'\n });\n\n // Mark as active so we don't spam\n anomalyState.activePerformanceDegradation = true;\n //node.warn(`[ANOMALY] Performance degradation STARTED: ${avgPerformance.toFixed(1)}%`);\n }\n\n } else if (avgPerformance >= PERF_RECOVERY_THRESHOLD) {\n // Performance recovered\n anomalyState.performanceLowStreak = 0;\n\n // Only send recovery message if we were previously in degraded state\n if (anomalyState.activePerformanceDegradation) {\n detectedAnomalies.push({\n anomaly_type: 'performance-degradation',\n severity: 'info',\n title: 'Performance Recovered',\n description: `Performance recovered to ${avgPerformance.toFixed(1)}% (threshold: ${PERF_LOW_THRESHOLD}%)`,\n data: {\n average_performance: avgPerformance,\n current_performance: currentPerformance,\n threshold: PERF_LOW_THRESHOLD\n },\n kpi_snapshot: {\n oee: kpis.oee || 0,\n availability: kpis.availability || 0,\n performance: kpis.performance || 0,\n quality: kpis.quality || 0\n },\n work_order_id: activeOrder.id,\n cycle_count: cycle.cycles || 0,\n tsMs: now,\n status: 'resolved'\n });\n\n anomalyState.activePerformanceDegradation = false;\n //node.warn(`[ANOMALY] Performance degradation RESOLVED: ${avgPerformance.toFixed(1)}%`);\n }\n }\n}\n\n// ============================================================\n// TIER 3: PREDICTIVE ALERTS (Trend Analysis)\n// Predict issues before they become critical\n// ============================================================\nif (anomalyState.oeeHistory.length >= 15) {\n // Simple linear trend analysis on OEE\n const recent15 = anomalyState.oeeHistory.slice(-15);\n const firstHalf = recent15.slice(0, 7);\n const secondHalf = recent15.slice(-7);\n\n const avgFirstHalf = firstHalf.reduce((sum, p) => sum + p.value, 0) / firstHalf.length;\n const avgSecondHalf = secondHalf.reduce((sum, p) => sum + p.value, 0) / secondHalf.length;\n\n const oeeTrend = avgSecondHalf - avgFirstHalf;\n\n // Predict if OEE is trending downward significantly\n if (oeeTrend < -5 && avgSecondHalf > OEE_THRESHOLD * 0.95 && avgSecondHalf < OEE_THRESHOLD * 1.05) {\n detectedAnomalies.push({\n anomaly_type: 'predictive-oee-decline',\n severity: 'info',\n title: `Declining OEE Trend Detected`,\n description: `OEE trending down ${Math.abs(oeeTrend).toFixed(1)}% over last 15 cycles. Current: ${avgSecondHalf.toFixed(1)}%`,\n data: {\n trend: oeeTrend,\n first_half_avg: avgFirstHalf,\n second_half_avg: avgSecondHalf,\n prediction: 'OEE may drop below threshold soon'\n },\n kpi_snapshot: {\n oee: kpis.oee || 0,\n availability: kpis.availability || 0,\n performance: kpis.performance || 0,\n quality: kpis.quality || 0\n },\n work_order_id: activeOrder.id,\n cycle_count: cycle.cycles || 0,\n tsMs: now\n });\n\n //node.warn(`[PREDICTIVE] OEE trending down: ${oeeTrend.toFixed(1)}%`);\n }\n}\n\n// Update last cycle time for next iteration\nanomalyState.lastCycleTime = lastCycleTime;\nglobal.set(\"anomalyState\", anomalyState);\n//anomaly.state = anomalyState;\n//global.set(\"anomaly\", anomaly);\n\n\n// ============================================================\n// OUTPUT\n// ============================================================\nconst normalizedAnomalies = detectedAnomalies.map(applyDefaultDowntimeReason);\n\nif (normalizedAnomalies.length > 0) {\n node.warn(`[ANOMALY DETECTOR] Detected ${normalizedAnomalies.length} anomaly/ies`);\n\n normalizedAnomalies.forEach((a, i) => {\n node.warn(` [${i + 1}] ${a.anomaly_type} - ${a.title} - ${a.status || 'N/A'}`);\n });\n\n msg.topic = \"anomaly-detected\";\n msg.payload = normalizedAnomalies;\n msg.originalMsg = msg.originalMsg || null;\n msg._anomaly_source = \"anomaly_detector\";\n return msg;\n}\nreturn null;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1350, + "y": 440, + "wires": [ + [ + "1212f599b9ab36f0", + "245a057bdff1fc14", + "bf17a2d4b88f7694", + "e2cb9e6a86c0d549" + ] + ] + }, + { + "id": "1212f599b9ab36f0", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Event Logger (Simplified)", + "func": "// ============================================================\n// EVENT LOGGER - SIMPLIFIED (INSERTS ONLY)\n// Every anomaly gets inserted as a new row\n// ============================================================\n\nconst anomalies = msg.payload || [];\nconst settings = global.get(\"settings\") || {};\nconst anomalyStateStore = global.get(\"anomaly\") || {};\nconst reasonsByIncident = anomalyStateStore.reasonsByIncident || {};\n\nif (!Array.isArray(anomalies) || anomalies.length === 0) {\n return null;\n}\n\n// SQL escape helper\nconst esc = (v) => {\n if (v === null || v === undefined) return 'NULL';\n return \"'\" + String(v).replace(/\\\\/g, '\\\\').replace(/'/g, \"''\") + \"'\";\n};\n\nconst dbInserts = [];\nconst activeAnomalies = [];\nconst softNotifications = []; \n\n\nanomalies.forEach(anomaly => {\n const tsMs = Number(anomaly.tsMs) || Date.now();\n const woId = anomaly.work_order_id || '';\n const aType = anomaly.anomaly_type || 'unknown';\n const sev = anomaly.severity || 'warning';\n const title = anomaly.title || '';\n const desc = anomaly.description || '';\n const dataJson = JSON.stringify(anomaly.data || {});\n const kpiJson = JSON.stringify(anomaly.kpi_snapshot || {});\n const cycle = Number(anomaly.cycle_count) || 0;\n const requiresAck = anomaly.requires_ack !== false;\n const incidentKey = anomaly.incidentKey || (anomaly.data && anomaly.data.last_cycle_timestamp\n ? [aType, woId, String(anomaly.data.last_cycle_timestamp)].join(\":\")\n : (anomaly.alert_id || null));\n const reason = incidentKey ? (reasonsByIncident[incidentKey] || null) : null;\n\n // Build INSERT query\n const insertQuery = \n \"INSERT INTO anomaly_events \" +\n \"(`event_timestamp`, `work_order_id`, `anomaly_type`, `severity`, `title`, `description`, \" +\n \"`data_json`, `kpi_snapshot_json`, `status`, `cycle_count`, `occurrence_count`, `last_occurrence`) VALUES (\" +\n tsMs + \", \" +\n esc(woId) + \", \" +\n esc(aType) + \", \" +\n esc(sev) + \", \" +\n esc(title) + \", \" +\n esc(desc) + \", \" +\n esc(dataJson) + \", \" +\n esc(kpiJson) + \", \" +\n \"'active', \" +\n cycle + \", \" +\n \"1, \" +\n tsMs + \")\";\n\n dbInserts.push({ topic: insertQuery, payload: [] });\n\n // Add to active list for UI\n if (requiresAck) {\n // Hard alerts that go to the panel + require acknowledgment\n activeAnomalies.push({\n event_id: null,\n tsMs: tsMs,\n work_order_id: woId,\n anomaly_type: aType,\n incidentKey: incidentKey || null,\n severity: sev,\n title: title,\n description: desc,\n status: 'active',\n reason: reason,\n kpi_snapshot: anomaly.kpi_snapshot || {}\n });\n\n node.warn(`[EVENT LOGGER] Inserting ${aType}: ${title} (requires ack)`);\n } else {\n // Soft alerts (e.g. slow-cycle) -> just show a transient popup\n softNotifications.push({\n tsMs: tsMs,\n anomaly_type: aType,\n severity: sev,\n title: title,\n description: desc,\n requires_ack: false\n });\n\n node.warn(`[EVENT LOGGER] Logging soft anomaly ${aType}: ${title}`);\n }\n});\n\n// UI update message\nconst uiMsg = {\n topic: \"anomaly-ui-update\",\n payload: {\n activeCount: activeAnomalies.length,\n activeAnomalies: activeAnomalies,\n updates: activeAnomalies.map(a => ({ status: 'new', anomaly: a })),\n softNotifications: softNotifications,\n reasonCatalog: settings.reasonCatalog || null\n }\n};\n\nreturn [dbInserts, uiMsg];\n", + "outputs": 2, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1370, + "y": 400, + "wires": [ + [ + "7e94b5651ed96f24", + "1b6eda85e72ecff1", + "dc14ef2f723f75b7" + ], + [ + "78925efc4a55f04d", + "2fd4067492e5549b" + ] + ] + }, + { + "id": "1b6eda85e72ecff1", + "type": "split", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Split DB Inserts", + "splt": "\\n", + "spltType": "str", + "arraySplt": 1, + "arraySpltType": "len", + "stream": false, + "addname": "", + "x": 1940, + "y": 380, + "wires": [ + [ + "875d5f193c768af0" + ] + ] + }, + { + "id": "8e60972fea4bd36a", + "type": "mysql", + "z": "05d4cb231221b842", + "g": "d9a9ee7bc71b0f53", + "mydb": "fc9634aabefee16b", + "name": "Anomaly Events DB", + "x": 1020, + "y": 60, + "wires": [ + [] + ] + }, + { + "id": "ba6de546969ea278", + "type": "inject", + "z": "05d4cb231221b842", + "name": "Initialize OEE Threshold (90%)", + "props": [ + { + "p": "payload" + } + ], + "repeat": "", + "crontab": "", + "once": true, + "onceDelay": 0.1, + "topic": "", + "payload": "90", + "payloadType": "num", + "x": 360, + "y": 940, + "wires": [ + [ + "4f9cf7814f1575f2" + ] + ] + }, + { + "id": "4f9cf7814f1575f2", + "type": "function", + "z": "05d4cb231221b842", + "name": "Set OEE Threshold Global", + "func": "// Initialize OEE alert threshold\nconst settings = global.get(\"settings\") || {};\nconst threshold = Number(msg.payload) || 90;\nsettings.oeeAlertThreshold = threshold;\nglobal.set(\"settings\", settings);\n\nnode.warn(`[CONFIG] OEE Alert Threshold set to ${threshold}%`);\n\nreturn msg;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 680, + "y": 940, + "wires": [ + [] + ] + }, + { + "id": "dcaa582c9b2277ba", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Save KPIs to Database", + "func": "// ============================================================\n// SAVE KPIs TO DATABASE - 1 SNAPSHOT PER CYCLE\n// ============================================================\n\nconst state = global.get(\"state\") || {};\nconst kpis = msg.kpis || {};\n\n// Rising edge guard: only save once per cycle\nconst saveFlag = state.saveKpis || 0;\nif (!saveFlag) {\n return null;\n}\nstate.saveKpis = 0;\nglobal.set(\"state\", state);\n\nconst dbInserts = [];\n\nconst activeOrder = state.activeWorkOrder || {};\nconst workorder_id = activeOrder.id;\nconst oee = Number(kpis.oee);\nconst performance = Number(kpis.performance);\nconst availability = Number(kpis.availability);\nconst quality = Number(kpis.quality);\nconst tsMs = Date.now();\n\nif (!workorder_id) {\n return null;\n}\n\nconst insertQuery =\n \"INSERT INTO kpi_snapshots \" +\n \"(work_order_id,oee_percent, performance_percent, availability_percent, quality_percent, timestamp) VALUES (\" +\n \"'\" + workorder_id + \"', \" +\n oee + \", \" +\n performance + \", \" +\n availability + \", \" +\n quality + \", \" +\n tsMs + \")\";\n\ndbInserts.push({ topic: insertQuery, payload: [] });\n\nreturn [dbInserts];\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1710, + "y": 720, + "wires": [ + [ + "e19e54018a466662" + ] + ] + }, + { + "id": "e19e54018a466662", + "type": "mysql", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "mydb": "fc9634aabefee16b", + "name": "Save kpis to database", + "x": 1980, + "y": 700, + "wires": [ + [ + "7aac414134d40b3a" + ] + ] + }, + { + "id": "25a2e7a04827039a", + "type": "template", + "z": "05d4cb231221b842", + "g": "9221454c45afd1ba", + "name": "Format query 1", + "field": "topic", + "fieldType": "msg", + "format": "handlebars", + "syntax": "mustache", + "template": "SELECT\n oee_percent,\n availability_percent,\n quality_percent,\n performance_percent,\n tsMs\nFROM (\n SELECT\n oee_percent,\n availability_percent,\n quality_percent,\n performance_percent,\n timestamp AS tsMs\n FROM kpi_snapshots\n ORDER BY timestamp DESC\n LIMIT 50\n) AS t\nORDER BY tsMs ASC;\n", + "output": "str", + "x": 1380, + "y": 80, + "wires": [ + [ + "7df6eebd9b7c7c7b" + ] + ] + }, + { + "id": "9f929db1f49b6e16", + "type": "function", + "z": "05d4cb231221b842", + "g": "9221454c45afd1ba", + "name": "Format Graph Data", + "func": "// Format Graph Data for KPI charts\n\n // Build labels and data arrays\n const labels = [];\n const oeeData = [];\n const availData = [];\n const perfData = [];\n const qualData = [];\n\n function bucketSeries(source, size) {\n const bucketSize = size || 5; // 3 points → 1 smoother point\n if (!Array.isArray(source) || source.length <= bucketSize) return source;\n\n const result = [];\n for (let i = 0; i < source.length; i += bucketSize) {\n const bucket = source.slice(i, i + bucketSize);\n const avgY = bucket.reduce((sum, p) => sum + Number(p.y || 0), 0) / bucket.length;\n const midPoint = bucket[Math.floor(bucket.length / 2)] || bucket[0];\n result.push({ x: midPoint.x, y: avgY });\n }\n return result;\n}\n\n \n msg.payload.forEach(row => {\n let x_value = new Date(row.tsMs); \n const dateObject = new Date(x_value);\n const year = dateObject.getFullYear();\n const month = dateObject.getMonth() + 1; // Months are 0-indexed\n const day = dateObject.getDate();\n const hours = dateObject.getHours();\n const minutes = dateObject.getMinutes();\n const seconds = dateObject.getSeconds();\n const formattedx_value = `${day.toString().padStart(2, '0')}-${month.toString().padStart(2, '0')} ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;\n\n oeeData.push({ x: formattedx_value, y: row.oee_percent });\n availData.push({ x: formattedx_value, y: row.availability_percent });\n perfData.push({ x: formattedx_value, y: row.performance_percent });\n qualData.push({ x: formattedx_value, y: row.quality_percent });\n });\n\n const smoothOee = bucketSeries(oeeData, 5);\n const smoothAvail = bucketSeries(availData, 5);\n const smoothPerf = bucketSeries(perfData, 5);\n const smoothQual = bucketSeries(qualData, 5);\n\n msg.graphData = {\n labels: labels,\n datasets: [\n { label: 'OEE %', data: smoothOee },\n { label: 'Availability %', data: smoothAvail },\n { label: 'Performance %', data: smoothPerf },\n { label: 'Quality %', data: smoothQual }\n ]\n };\n\n //node.warn(`[GRAPH DATA] Formatted ${labels.length} KPI history points`);\n\n delete msg.topic;\n delete msg.payload;\n return msg;\n\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1830, + "y": 80, + "wires": [ + [ + "cc31f7b315638ba5" + ] + ] + }, + { + "id": "fa78b7dee85d560d", + "type": "link out", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "link out 11", + "mode": "link", + "links": [ + "96dfd46a1435d111" + ], + "x": 485, + "y": 360, + "wires": [] + }, + { + "id": "96dfd46a1435d111", + "type": "link in", + "z": "05d4cb231221b842", + "g": "443b758222662fdf", + "name": "link in 10", + "links": [ + "fa78b7dee85d560d" + ], + "x": 275, + "y": 860, + "wires": [ + [ + "4a62662fea532976" + ] + ] + }, + { + "id": "78925efc4a55f04d", + "type": "link out", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "link out 12", + "mode": "link", + "links": [ + "3c80936f0a0918c3" + ], + "x": 1685, + "y": 420, + "wires": [] + }, + { + "id": "3c80936f0a0918c3", + "type": "link in", + "z": "05d4cb231221b842", + "g": "d9a9ee7bc71b0f53", + "name": "link in 11", + "links": [ + "78925efc4a55f04d" + ], + "x": 265, + "y": 60, + "wires": [ + [ + "9748899355370bae" + ] + ] + }, + { + "id": "875d5f193c768af0", + "type": "link out", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "link out 13", + "mode": "link", + "links": [ + "f27352133669b6fa" + ], + "x": 2065, + "y": 380, + "wires": [] + }, + { + "id": "f27352133669b6fa", + "type": "link in", + "z": "05d4cb231221b842", + "g": "d9a9ee7bc71b0f53", + "name": "link in 12", + "links": [ + "875d5f193c768af0", + "7e94b5651ed96f24" + ], + "x": 895, + "y": 80, + "wires": [ + [ + "8e60972fea4bd36a" + ] + ] + }, + { + "id": "7e94b5651ed96f24", + "type": "link out", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "link out 14", + "mode": "link", + "links": [ + "f27352133669b6fa" + ], + "x": 2215, + "y": 420, + "wires": [] + }, + { + "id": "05112cf4f0821cfd", + "type": "link out", + "z": "05d4cb231221b842", + "g": "6e514144a570aa72", + "name": "link out 15", + "mode": "link", + "links": [ + "5109df0f8b1e20e3" + ], + "x": 1505, + "y": 200, + "wires": [] + }, + { + "id": "5109df0f8b1e20e3", + "type": "link in", + "z": "05d4cb231221b842", + "g": "9221454c45afd1ba", + "name": "link in 13", + "links": [ + "05112cf4f0821cfd" + ], + "x": 1235, + "y": 80, + "wires": [ + [ + "25a2e7a04827039a" + ] + ] + }, + { + "id": "245a057bdff1fc14", + "type": "link out", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "link out 16", + "mode": "link", + "links": [], + "x": 1535, + "y": 440, + "wires": [] + }, + { + "id": "ba626f3a3b37e653", + "type": "function", + "z": "05d4cb231221b842", + "g": "878b79013722e91f", + "name": "Shift Config Handler", + "func": "// Shift Config Handler\nconst topic = msg.topic || \"\";\nconst config = global.get(\"config\") || {};\nconst readOnly = config.settingsReadOnly !== false;\nconst settings = global.get(\"settings\") || {};\n\nif (readOnly && (topic === \"saveShiftConfig\" || topic === \"saveThresholdConfig\" || topic === \"saveAllSettings\")) {\n node.status({ fill: \"yellow\", shape: \"ring\", text: \"Read-only\" });\n return null;\n}\n\n// Save shift config\nif (topic === \"saveShiftConfig\") {\n const config = msg.payload || {};\n settings.shifts = config.shifts || [];\n settings.shiftChangeCompensation = config.shiftChangeCompensation || 10;\n settings.lunchBreakMinutes = config.lunchBreakMinutes || 30;\n global.set(\"settings\", settings);\n\n node.status({ fill: \"green\", shape: \"dot\", text: `${config.shifts.length} sh ${config.shiftChangeCompensation} ch ${config.shiftChangeCompensation} lu` });\n return null;\n}\n\n// Save threshold config\nif (topic === \"saveThresholdConfig\") {\n const config = msg.payload || {};\n settings.thresholdMultiplier = config.thresholdMultiplier || 1.5;\n settings.macroStoppageMultiplier = config.macroStoppageMultiplier || 5;\n settings.oeeAlertThreshold = config.oeeAlertThreshold || 90;\n global.set(\"settings\", settings);\n\n node.status({ fill: \"green\", shape: \"dot\", text: `Threshold: ${config.thresholdMultiplier}x / ${config.macroStoppageMultiplier}x` });\n return null;\n}\n\n// Load shift config\nif (topic === \"getShiftConfig\") {\n msg.topic = \"shiftConfigData\";\n msg.payload = {\n shifts: settings.shifts || [{ start: \"08:00\", end: \"16:00\" }],\n shiftChangeCompensation: settings.shiftChangeCompensation || 10,\n lunchBreakMinutes: settings.lunchBreakMinutes || 30,\n thresholdMultiplier: settings.thresholdMultiplier || 1.5,\n macroStoppageMultiplier: settings.macroStoppageMultiplier || 5,\n oeeAlertThreshold: settings.oeeAlertThreshold || 90\n };\n return msg; // Send back to UI\n}\n\n// Save all settings at once\nif (topic === \"getShiftConfig\") {\n msg.topic = \"shiftConfigData\";\n msg.payload = {\n shifts: settings.shifts || [{ start: \"08:00\", end: \"16:00\" }],\n shiftChangeCompensation: settings.shiftChangeCompensation || 10,\n lunchBreakMinutes: settings.lunchBreakMinutes || 30,\n thresholdMultiplier: settings.thresholdMultiplier || 1.5,\n macroStoppageMultiplier: settings.macroStoppageMultiplier || 5,\n oeeAlertThreshold: settings.oeeAlertThreshold || 90\n };\n return msg; // Send back to UI\n}\n\nreturn null;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 400, + "y": 720, + "wires": [ + [ + "2c8562b2471078ab" + ] + ] + }, + { + "id": "2c8562b2471078ab", + "type": "link out", + "z": "05d4cb231221b842", + "g": "878b79013722e91f", + "name": "link out 17", + "mode": "link", + "links": [ + "6b3c45059b9b7c6c" + ], + "x": 525, + "y": 720, + "wires": [] + }, + { + "id": "09c77467731a6a66", + "type": "inject", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "KPI Tick", + "props": [ + { + "p": "payload" + } + ], + "repeat": "1", + "crontab": "", + "once": true, + "onceDelay": 0.1, + "topic": "", + "payload": "1", + "payloadType": "num", + "x": 1200, + "y": 600, + "wires": [ + [ + "a3d41a656eb3b2ce" + ] + ] + }, + { + "id": "5fa1dfb48ee969e0", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 2", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "false", + "statusVal": "", + "statusType": "auto", + "x": 2360, + "y": 140, + "wires": [] + }, + { + "id": "ce36a3271d9df8ae", + "type": "function", + "z": "05d4cb231221b842", + "name": "function 1", + "func": "let last = context.get('last') || 0;\nlet current = Number(msg.payload);\nif (current !== last) {\n context.set('last', current);\n return msg;\n}\nreturn null;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 2400, + "y": 240, + "wires": [ + [ + "5fa1dfb48ee969e0", + "093d9631fbd43003" + ] + ] + }, + { + "id": "5df5be609ff6e622", + "type": "switch", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "", + "property": "topic", + "propertyType": "msg", + "rules": [ + { + "t": "istype", + "v": "string", + "vt": "string" + } + ], + "checkall": "true", + "repair": false, + "outputs": 1, + "x": 1530, + "y": 820, + "wires": [ + [ + "bfb9b7c7af23bd5c" + ] + ] + }, + { + "id": "7aac414134d40b3a", + "type": "change", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Reset saveKpis flag", + "rules": [ + { + "t": "set", + "p": "state", + "pt": "global", + "to": "$merge([($globalContext(\"state\") ? $globalContext(\"state\") : {}), {\"saveKpis\": 0}])", + "tot": "jsonata" + } + ], + "action": "", + "property": "", + "from": "", + "to": "", + "reg": false, + "x": 2200, + "y": 660, + "wires": [ + [] + ] + }, + { + "id": "25dfb62e7131af6b", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 4", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 2140, + "y": 80, + "wires": [] + }, + { + "id": "472e0f6f0c888c6c", + "type": "rpi-gpio in", + "z": "05d4cb231221b842", + "d": true, + "name": "", + "pin": "17", + "intype": "up", + "debounce": "25", + "read": true, + "bcm": true, + "x": 2220, + "y": 200, + "wires": [ + [ + "ce36a3271d9df8ae" + ] + ] + }, + { + "id": "d098028be97741ba", + "type": "function", + "z": "05d4cb231221b842", + "name": "Build Current State Snapshot", + "func": "// Build Current State Snapshot (outbox payload)\n\nconst config = global.get(\"config\") || {};\nconst machineId = config.machineId;\nconst now = Date.now();\nconst state = global.get(\"state\") || {};\nconst snapshot = state.lastState;\nconst settings = global.get(\"settings\") || {};\nconst lastMoldActive = Number(state.lastMoldActive ?? 0);\nconst moldActive = Number(\n snapshot?.activeWorkOrder?.cavities ??\n lastMoldActive ??\n snapshot?.cavities ??\n settings.moldActive ??\n global.get(\"moldActive\") ??\n 0\n);\nconst cavities = moldActive > 0 ? moldActive : null;\nmsg.tsMs = now;\n\n// This is the state you already have (from UI or from your state builder)\nconst s = msg.payload || {};\n\nmsg._mode = \"current-state\";\n\n// what you POST to cloud\nmsg.payload = {\n machineId: machineId,\n tsMs: now,\n activeWorkOrder: s.activeWorkOrder ?? null,\n cycle_count: s.cycleCount ?? null,\n good_parts: s.goodParts ?? null,\n scrap_parts: s.scrapParts ?? null,\n cavities,\n cycleTime: s.cycleTime ?? null,\n actualCycleTime: s.actualCycleTime ?? null,\n trackingEnabled: s.trackingEnabled ?? null,\n productionStarted: s.productionStarted ?? null,\n kpis: s.kpis ?? null,\n};\n\n// what goes into outbox (MUST MATCH what you intend to send)\nconst p = msg.payload || {};\n\nmsg.outbox = {\n type: \"kpi\",\n payload: {\n tsMs: p.tsMs,\n activeWorkOrder: p.activeWorkOrder,\n cycle_count: p.cycle_count,\n good_parts: p.good_parts,\n scrap_parts: p.scrap_parts,\n cavities: p.cavities,\n cycleTime: p.cycleTime,\n actualCycleTime: p.actualCycleTime,\n trackingEnabled: p.trackingEnabled,\n productionStarted: p.productionStarted,\n kpis: p.kpis,\n },\n};\n\nreturn msg;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 2420, + "y": 980, + "wires": [ + [ + "d90934911557dde5" + ] + ] + }, + { + "id": "bf17a2d4b88f7694", + "type": "function", + "z": "05d4cb231221b842", + "name": "Build Event Outbox Payload", + "func": "// Build event outbox payload(s) — handle both single event and array (from Anomaly Detector).\n// Original single-event behavior preserved byte-for-byte for scrap-entry and\n// downtime-acknowledged paths. Array input emits one outbox message per anomaly.\n\nconst anomaly = global.get(\"anomaly\") || {};\n\nconst incoming = msg.payload;\nconst rawEvents = Array.isArray(incoming)\n ? incoming\n : (incoming && typeof incoming === \"object\" ? [incoming] : []);\nif (rawEvents.length === 0) return null;\n\nfor (const raw of rawEvents) {\n if (!raw || typeof raw !== \"object\") continue;\n\n const event = { ...raw };\n const tsMs = typeof event.tsMs === \"number\" ? event.tsMs : Date.now();\n\n const incidentKey =\n event.incidentKey ||\n event.incident_key ||\n (event.data && event.data.last_cycle_timestamp\n ? [event.anomaly_type || event.anomalyType || \"event\",\n event.work_order_id || event.workOrderId || \"\",\n String(event.data.last_cycle_timestamp)].join(\":\")\n : null);\n\n const reasonFromStore = incidentKey && anomaly.reasonsByIncident\n ? anomaly.reasonsByIncident[incidentKey]\n : null;\n if (!event.reason && reasonFromStore) event.reason = reasonFromStore;\n\n const anomalyType = event.anomaly_type || event.anomalyType || null;\n const isDowntimeType = anomalyType === \"microstop\" || anomalyType === \"macrostop\";\n if (!event.downtime) {\n event.downtime = isDowntimeType ? {\n incidentKey: incidentKey || null,\n anomalyType,\n durationSeconds: event.data && Number(event.data.stoppage_duration_seconds) || null\n } : null;\n }\n\n node.send({\n ...msg,\n tsMs,\n outbox: { type: \"event\", payload: { event } }\n });\n}\n\nreturn null;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 2540, + "y": 780, + "wires": [ + [ + "e120c11f093ebd9b" + ] + ] + }, + { + "id": "ea46abcb46717837", + "type": "inject", + "z": "05d4cb231221b842", + "name": "", + "props": [ + { + "p": "payload" + }, + { + "p": "topic", + "vt": "str" + } + ], + "repeat": "120", + "crontab": "", + "once": true, + "onceDelay": 0.1, + "topic": "", + "payload": "", + "payloadType": "date", + "x": 2290, + "y": 700, + "wires": [ + [ + "f2998a8d050e7d3f" + ] + ] + }, + { + "id": "f2998a8d050e7d3f", + "type": "function", + "z": "05d4cb231221b842", + "name": "Online HeartBeat", + "func": "// Heartbeat Producer (feeds Outbox Enqueue v1)\n\nconst config = global.get(\"config\") || {};\nconst machineId = msg.machineId || config.machineId;\nif (!machineId) {\n node.status({ fill: \"yellow\", shape: \"ring\", text: \"Heartbeat waiting for pairing\" });\n return null;\n}\nmsg.machineId = machineId;\n\n// Edge heartbeat = \"I am alive and running Node-RED\"\nconst status = \"ONLINE\";\n\n// pull these from globals if possible (set once at boot)\nconst ip = config.edgeIp || msg.ip || \"192.168.18.33\";\nconst fwVersion = config.fwVersion || \"raspi-nodered-1.0\";\nconst message = \"NR heartbeat\";\n\n// ---- DEDUPE / THROTTLE ----\n// Only enqueue if changed OR interval elapsed\nconst now = Date.now();\nmsg.tsMs = now;\nmsg.tsDevice = now; // epoch ms for API v1 (same instant as tsMs)\nconst intervalMs = Number(config.heartbeatIntervalMs || 15000);\n\n// Only include \"stable\" fields in signature; don't include timestamps\nconst signature = JSON.stringify({ status, ip, fwVersion });\n\nconst last = flow.get(\"hb_last\");\nif (last && last.signature === signature && (now - last.tsMs) < intervalMs) {\n return null; // skip enqueue (prevents spamming)\n}\nflow.set(\"hb_last\", { signature, tsMs: now });\n\n// This is what Outbox Enqueue v1 consumes\nmsg.outbox = {\n type: \"heartbeat\",\n payload: { status, message, ip, fwVersion },\n};\n\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 2540, + "y": 640, + "wires": [ + [ + "5b485289491bb538" + ] + ] + }, + { + "id": "3c78c68f64843c22", + "type": "function", + "z": "05d4cb231221b842", + "name": "Build Cycle Outbox Payload", + "func": "// Build cycle outbox payload (direct HTTP disabled)\n\nconst config = global.get(\"config\") || {};\nconst machineId = config.machineId;\n\nif (!msg.cycleRow) return null;\n\nmsg.tsMs = typeof msg.cycleRow.tsMs === \"number\" ? msg.cycleRow.tsMs : Date.now();\n\n// Deduplicate (extra safety)\nconst dedupeKey = `cc:${msg.cycleRow.cycle_count}`;\nconst lastKey = flow.get(\"lastCyclePostedKey\");\nif (lastKey === dedupeKey) return null;\nflow.set(\"lastCyclePostedKey\", dedupeKey);\n\n// For debugging visibility\nmsg._debug = {\n machineId: machineId,\n cycle_count: msg.cycleRow.cycle_count,\n actual_cycle_time: msg.cycleRow.actual_cycle_time,\n theoretical_cycle_time: msg.cycleRow.theoretical_cycle_time,\n};\n\nmsg.outbox = {\n type: \"cycle\",\n payload: { cycle: msg.cycleRow },\n};\n\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 2540, + "y": 720, + "wires": [ + [ + "e120c11f093ebd9b" + ] + ] + }, + { + "id": "f197ef50dc5354d4", + "type": "http request", + "z": "05d4cb231221b842", + "d": true, + "name": "Legacy Direct Cycle HTTP (disabled)", + "method": "POST", + "ret": "txt", + "paytoqs": "ignore", + "url": "http://mis.maliountech.com.mx/api/ingest/cycle", + "tls": "", + "persist": false, + "proxy": "", + "insecureHTTPParser": false, + "authType": "", + "senderr": false, + "headers": [ + { + "keyType": "Content-Type", + "keyValue": "", + "valueType": "other", + "valueValue": "application/json" + }, + { + "keyType": "other", + "keyValue": "x-api-key", + "valueType": "other", + "valueValue": "e0113ab0688769179fce30a44d21e4fd0576747b0886e9a1" + } + ], + "x": 2770, + "y": 320, + "wires": [ + [ + "fa101d173bfce159" + ] + ] + }, + { + "id": "fa101d173bfce159", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 9", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 2660, + "y": 180, + "wires": [] + }, + { + "id": "83a5536b1b938477", + "type": "inject", + "z": "05d4cb231221b842", + "name": "", + "props": [ + { + "p": "payload" + }, + { + "p": "topic", + "vt": "str" + } + ], + "repeat": "", + "crontab": "", + "once": false, + "onceDelay": 0.1, + "topic": "0", + "payload": "1", + "payloadType": "num", + "x": 2500, + "y": 360, + "wires": [ + [ + "ce36a3271d9df8ae" + ] + ] + }, + { + "id": "e120c11f093ebd9b", + "type": "subflow:080d227df7fb2db1", + "z": "05d4cb231221b842", + "name": "Outbox Enqueue v1", + "x": 2920, + "y": 780, + "wires": [ + [ + "6ae3a59730db0e5c", + "b5ddb99732d4fd14" + ] + ] + }, + { + "id": "915121c1c41661ba", + "type": "inject", + "z": "05d4cb231221b842", + "name": "Publisher tick", + "props": [ + { + "p": "payload" + }, + { + "p": "topic", + "vt": "str" + } + ], + "repeat": "10", + "crontab": "", + "once": true, + "onceDelay": 0.5, + "topic": "", + "payload": "", + "payloadType": "date", + "x": 2480, + "y": 920, + "wires": [ + [ + "b5ddb99732d4fd14" + ] + ] + }, + { + "id": "01785ce1bc3d7919", + "type": "mysql", + "z": "05d4cb231221b842", + "mydb": "fc9634aabefee16b", + "name": "Fetch pending outbox", + "x": 3040, + "y": 880, + "wires": [ + [ + "ef6299b3d440c194" + ] + ] + }, + { + "id": "b5ddb99732d4fd14", + "type": "function", + "z": "05d4cb231221b842", + "name": "Select pending batch", + "func": "// Lock de flow: si la ronda anterior aún no termina, saltar este tick\nif (flow.get(\"publisherBusy\")) {\n node.status({ fill: \"yellow\", shape: \"ring\", text: \"busy, skipping\" });\n return null;\n}\nflow.set(\"publisherBusy\", true);\n\n// Marcar como \"sending\" hasta 25 filas pendientes (atómico)\nmsg.topic = `\nUPDATE outbox_messages\nSET status='sending'\nWHERE status='pending'\n AND (next_attempt_at IS NULL OR next_attempt_at <= NOW())\nORDER BY id ASC\nLIMIT 25;\n`.trim();\n\nmsg._stage = \"claim\";\nreturn msg;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 2800, + "y": 880, + "wires": [ + [ + "01785ce1bc3d7919", + "a6bc13525d5bfc63" + ] + ] + }, + { + "id": "85a333219d51a809", + "type": "switch", + "z": "05d4cb231221b842", + "name": "Has rows?", + "property": "payload", + "propertyType": "msg", + "rules": [ + { + "t": "eq", + "v": "", + "vt": "str" + }, + { + "t": "neq", + "v": "", + "vt": "str" + } + ], + "checkall": "true", + "repair": false, + "outputs": 2, + "x": 3270, + "y": 880, + "wires": [ + [ + "5dbbcccbadfb8038" + ], + [ + "96288a2a99c5611f" + ] + ] + }, + { + "id": "96288a2a99c5611f", + "type": "split", + "z": "05d4cb231221b842", + "name": "Split rows", + "splt": "\\n", + "spltType": "str", + "arraySplt": 1, + "arraySpltType": "len", + "stream": false, + "addname": "", + "property": "payload", + "x": 3440, + "y": 880, + "wires": [ + [ + "391080652f38d9eb" + ] + ] + }, + { + "id": "391080652f38d9eb", + "type": "function", + "z": "05d4cb231221b842", + "name": "Build HTTP request", + "func": "const row = msg.payload; // row from DB\n\nconst config = global.get(\"config\") || {};\nconst base = config.cloudBaseUrl;\nconst apiKey = config.apiKey;\n\nconst machineId = config.machineId;\n\nif (machineId && row && row.machine_id && String(row.machine_id) !== String(machineId)) {\n node.status({ fill: \"yellow\", shape: \"ring\", text: \"Stale row (machine mismatch)\" });\n msg.topic = `\nUPDATE outbox_messages\nSET status='failed',\n last_http_status=?,\n last_error=?,\n next_attempt_at=NULL\nWHERE id=?;\n`.trim();\n msg.payload = [409, \"stale_machine\", Number(row.id)];\n return [null, msg];\n}\n\n\n\nif (!base || !apiKey) {\n node.status({ fill: \"yellow\", shape: \"ring\", text: \"Publisher waiting for pairing\" });\n return null;\n}\n\nconst baseUrl = String(base).replace(/\\/+$/, \"\");\nconst endpoint = String(row.endpoint || \"\");\nif (!endpoint.startsWith(\"/\")) throw new Error(\"Publisher: bad endpoint on row \" + row.id);\n\nmsg._row = row;\n\nmsg.method = row.method || \"POST\";\nmsg.url = baseUrl + endpoint;\n\nmsg.headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n};\n\n// payload_json may be string (most common) or object depending on mysql node\nlet payload = row.payload_json;\nif (typeof payload === \"string\") {\n try { payload = JSON.parse(payload); } catch (e) { }\n}\nmsg.payload = payload;\n\nreturn msg;\n", + "outputs": 2, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 3610, + "y": 880, + "wires": [ + [ + "b00c9fddfd900764", + "01fa15279b7facf2" + ], + [ + "039f8b69df0eae25" + ] + ] + }, + { + "id": "4770e1bb4693f2f2", + "type": "http request", + "z": "05d4cb231221b842", + "name": "Send outbox HTTP", + "method": "use", + "ret": "txt", + "paytoqs": "ignore", + "url": "", + "tls": "", + "persist": false, + "proxy": "", + "insecureHTTPParser": false, + "authType": "", + "senderr": false, + "headers": [], + "x": 3710, + "y": 680, + "wires": [ + [ + "2a40881a42a2bc54" + ] + ] + }, + { + "id": "2a40881a42a2bc54", + "type": "switch", + "z": "05d4cb231221b842", + "name": "HTTP 200?", + "property": "statusCode", + "propertyType": "msg", + "rules": [ + { + "t": "eq", + "v": "200", + "vt": "str" + }, + { + "t": "neq", + "v": "200", + "vt": "str" + } + ], + "checkall": "true", + "repair": false, + "outputs": 2, + "x": 3850, + "y": 880, + "wires": [ + [ + "ee9c83b346454502" + ], + [ + "219c83a26541c43e" + ] + ] + }, + { + "id": "ee9c83b346454502", + "type": "function", + "z": "05d4cb231221b842", + "name": "Mark Sent", + "func": "const row = msg._row;\nconst status = Number(msg.statusCode ?? 0);\n\nmsg.topic = `\nUPDATE outbox_messages\nSET status='sent',\n sent_at=NOW(),\n last_http_status=?,\n last_error=NULL\nWHERE id=? AND status='sending';\n`.trim();\n\nmsg.payload = [status, Number(row.id)];\nreturn msg;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 4020, + "y": 860, + "wires": [ + [ + "039f8b69df0eae25" + ] + ] + }, + { + "id": "219c83a26541c43e", + "type": "function", + "z": "05d4cb231221b842", + "name": "Retry", + "func": "const row = msg._row;\nconst attempts = Number(row.attempts || 0) + 1;\n\nconst retryConfig = {\n shortDelaySec: 5,\n mediumDelaySec: 30,\n longDelaySec: 180,\n mediumAfter: 5,\n longAfter: 20,\n errorMaxLen: 450,\n};\n\nconst status = Number(msg.statusCode || 0);\nlet err = \"\";\nif (msg.payload && typeof msg.payload === \"object\") {\n err = JSON.stringify(msg.payload).slice(0, retryConfig.errorMaxLen);\n} else if (msg.payload != null) {\n err = String(msg.payload).slice(0, retryConfig.errorMaxLen);\n} else {\n err = \"request_failed\";\n}\n\nif (status === 401 || status === 403) {\n node.status({ fill: \"red\", shape: \"ring\", text: \"Unauthorized - re-pair\" });\n msg.topic = `\nUPDATE outbox_messages\nSET status='failed',\n last_http_status=?,\n last_error=?,\n next_attempt_at=NULL\nWHERE id=?;\n`.trim();\n msg.payload = [ status || null, err, Number(row.id) ];\n return msg;\n}\n\n// Backoff policy\nlet delaySec = retryConfig.shortDelaySec;\nif (attempts <= retryConfig.mediumAfter) delaySec = retryConfig.shortDelaySec;\nelse if (attempts <= retryConfig.longAfter) delaySec = retryConfig.mediumDelaySec;\nelse delaySec = retryConfig.longDelaySec;\n\nmsg.topic = `\nUPDATE outbox_messages\nSET status='pending',\n attempts=?,\n next_attempt_at=DATE_ADD(NOW(), INTERVAL ? SECOND),\n last_http_status=?,\n last_error=?\nWHERE id=? AND status='sending';\n`.trim();\n\nmsg.payload = [ attempts, delaySec, status || null, err, Number(row.id) ];\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 4010, + "y": 900, + "wires": [ + [ + "039f8b69df0eae25" + ] + ] + }, + { + "id": "039f8b69df0eae25", + "type": "mysql", + "z": "05d4cb231221b842", + "mydb": "fc9634aabefee16b", + "name": "Update outbox status", + "x": 4360, + "y": 900, + "wires": [ + [ + "acacb8894c9125bc", + "c7f59092785681d1" + ] + ] + }, + { + "id": "79e027bf3befb2d9", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "State Accumulator global", + "func": "const config = global.get(\"config\") || {};\nconst state = global.get(\"state\") || {};\nconst settings = global.get(\"settings\") || {};\nconst machineId = config.machineId; // set this once at boot (see below)\nif (!machineId) { node.warn(\"lastState: missing config.machineId\"); return null; }\nconst active = state.activeWorkOrder || null;\nconst trackingEnabled = !!state.trackingEnabled;\nconst productionStarted = !!state.productionStarted;\nconst kpis = msg.kpis || state.currentKPIs || { oee: 0, availability: 0, performance: 0, quality: 0 };\nconst moldByWorkOrder = state.moldByWorkOrder || {};\nconst moldActive = Number(\n active?.cavities ??\n moldByWorkOrder[active?.id]?.active ??\n state.lastMoldActive ??\n settings.moldActive ??\n global.get(\"moldActive\") ??\n 0\n);\nconst cavities = moldActive > 0 ? moldActive : null;\n\nconst lastState = {\n machineId,\n activeWorkOrder: active,\n cycleCount: Number(state.cycleCount ?? 0),\n goodParts: Number(active?.goodParts ?? 0),\n scrapParts: Number(active?.scrapParts ?? 0),\n cavities,\n cycleTime: Number(active?.cycleTime ?? state.lastCycleTime ?? 0),\n actualCycleTime: Number(state.lastActualCycleTime ?? 0),\n trackingEnabled,\n productionStarted,\n kpis,\n tsMs: Date.now(),\n};\n\nstate.lastState = lastState;\nglobal.set(\"state\", state);\nmsg.lastState = lastState;\nreturn msg;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1690, + "y": 760, + "wires": [ + [] + ] + }, + { + "id": "7c214a102e0172e1", + "type": "inject", + "z": "05d4cb231221b842", + "name": "KPI state getter", + "props": [ + { + "p": "payload" + }, + { + "p": "topic", + "vt": "str" + } + ], + "repeat": "60", + "crontab": "", + "once": false, + "onceDelay": 0.1, + "topic": "", + "payload": "", + "payloadType": "date", + "x": 2210, + "y": 1020, + "wires": [ + [ + "37c463333a5b3799" + ] + ] + }, + { + "id": "37c463333a5b3799", + "type": "function", + "z": "05d4cb231221b842", + "name": "Build KPI Outbox from lastState", + "func": "// Build KPI Outbox from lastState\n\nconst config = global.get(\"config\") || {};\nconst state = global.get(\"state\") || {};\nconst snapshot = state.lastState;\nconst settings = global.get(\"settings\") || {};\nconst moldByWorkOrder = state.moldByWorkOrder || {};\nconst moldActive = Number(settings.moldActive ?? global.get(\"moldActive\") ?? snapshot?.activeWorkOrder?.cavities ?? 0);\n//const cavities = moldActive > 0 ? moldActive : snapshot?.cavities ?? null;\n\nif (!snapshot) return null;\n\nconst machineId = snapshot.machineId || config.machineId;\nif (!machineId) return null;\n\nmsg.machineId = machineId;\n\nconst activeWorkOrder = snapshot?.activeWorkOrder ? { ...snapshot.activeWorkOrder } : null;\nif (activeWorkOrder?.lastUpdateIso && typeof activeWorkOrder.lastUpdateIso !== \"string\") {\n delete activeWorkOrder.lastUpdateIso;\n}\n\nconst cavitiesRaw = Number(\n activeWorkOrder?.cavities ??\n moldByWorkOrder[activeWorkOrder?.id]?.active ??\n snapshot?.cavities ??\n state.lastMoldActive ??\n settings.moldActive ??\n global.get(\"moldActive\") ??\n 0\n);\nconst cavities = cavitiesRaw > 0 ? cavitiesRaw : null;\n\n\n\nmsg.outbox = {\n type: \"kpi\",\n payload: {\n tsMs: snapshot.tsMs,\n activeWorkOrder,\n cycle_count: snapshot.cycleCount,\n good_parts: snapshot.goodParts,\n scrap_parts: snapshot.scrapParts,\n cavities,\n cycleTime: snapshot.cycleTime,\n actualCycleTime: snapshot.actualCycleTime,\n trackingEnabled: snapshot.trackingEnabled,\n productionStarted: snapshot.productionStarted,\n kpis: snapshot.kpis,\n },\n};\n\nmsg.tsMs = typeof snapshot.tsMs === \"number\" ? snapshot.tsMs : Date.now();\n\n// keep timestamp so you can see it ticking\nmsg.payload = msg.tsMs;\nmsg.topic = \"\";\n\nreturn msg;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 2450, + "y": 1020, + "wires": [ + [ + "20bb0702bcbc8ed8" + ] + ] + }, + { + "id": "6ae3a59730db0e5c", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 1", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 3190, + "y": 1120, + "wires": [] + }, + { + "id": "acacb8894c9125bc", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 3", + "active": true, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 4540, + "y": 1100, + "wires": [] + }, + { + "id": "d90934911557dde5", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 5", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 2590, + "y": 1220, + "wires": [] + }, + { + "id": "20bb0702bcbc8ed8", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 6", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 3030, + "y": 1200, + "wires": [] + }, + { + "id": "b00c9fddfd900764", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 7", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 3400, + "y": 1080, + "wires": [] + }, + { + "id": "a6bc13525d5bfc63", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 8", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 3050, + "y": 1020, + "wires": [] + }, + { + "id": "16ccb5b864e17142", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 10", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 2010, + "y": 1080, + "wires": [] + }, + { + "id": "ed8c202dde4b6ff9", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 11", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 2000, + "y": 1140, + "wires": [] + }, + { + "id": "b245b3157fa7ee3c", + "type": "inject", + "z": "05d4cb231221b842", + "name": "Init config inject", + "props": [ + { + "p": "payload" + }, + { + "p": "topic", + "vt": "str" + } + ], + "repeat": "", + "crontab": "", + "once": true, + "onceDelay": 0.1, + "topic": "", + "payload": "", + "payloadType": "date", + "x": 3250, + "y": 220, + "wires": [ + [ + "4e7a2904be0f9a37" + ] + ] + }, + { + "id": "063447515a79e473", + "type": "function", + "z": "05d4cb231221b842", + "g": "878b79013722e91f", + "name": "Pair Machine Request", + "func": "const topic = msg.topic || \"\";\nif (topic != \"pairMachine\") {\n return null;\n}\n\nconst raw = (msg.payload && (msg.payload.code || msg.payload.pairingCode || msg.payload)) || \"\";\nconst code = String(raw).trim().toUpperCase().replace(/[^A-Z0-9]/g, \"\");\n\nif (code.length != 5) {\n node.status({ fill: \"red\", shape: \"ring\", text: \"Bad code\" });\n return [null, { topic: \"pairMachineResult\", payload: { ok: false, error: \"Codigo invalido.\" } }];\n}\n\nconst config = global.get(\"config\") || {};\nconst baseUrl = String(config.cloudBaseUrl || \"https://mis.maliountech.com.mx\").replace(/\\/+$/, \"\");\n\nmsg.method = \"POST\";\nmsg.url = baseUrl + \"/api/machines/pair\";\nmsg.headers = { \"Content-Type\": \"application/json\" };\nmsg.payload = { code: code };\n\nnode.status({ fill: \"blue\", shape: \"dot\", text: \"Pairing...\" });\nreturn [msg, null];\n", + "outputs": 2, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 430, + "y": 780, + "wires": [ + [ + "43893f8a2123b078" + ], + [ + "2c8562b2471078ab" + ] + ] + }, + { + "id": "43893f8a2123b078", + "type": "http request", + "z": "05d4cb231221b842", + "name": "Pair Machine HTTP", + "method": "use", + "ret": "obj", + "paytoqs": "ignore", + "url": "", + "tls": "", + "persist": false, + "proxy": "", + "insecureHTTPParser": false, + "authType": "", + "senderr": false, + "headers": [], + "x": 640, + "y": 780, + "wires": [ + [ + "2d87bd0e7c2e45af" + ] + ] + }, + { + "id": "2d87bd0e7c2e45af", + "type": "function", + "z": "05d4cb231221b842", + "g": "878b79013722e91f", + "name": "Pair Machine Response", + "func": "let res = msg.payload;\nif (typeof res == \"string\") {\n try { res = JSON.parse(res); } catch (e) { res = { error: res }; }\n}\nres = res || {};\n\nconst ok = res.ok === true || res.success === true;\nconst cfg = res.config || res;\n\nif (ok && cfg && cfg.machineId && cfg.apiKey) {\n const current = global.get(\"config\") || {};\n current.cloudBaseUrl = cfg.cloudBaseUrl || current.cloudBaseUrl;\n current.machineId = cfg.machineId;\n current.apiKey = cfg.apiKey;\n current.orgId = cfg.orgId || current.orgId;\n global.set(\"config\", current);\n\n node.status({ fill: \"green\", shape: \"dot\", text: \"Paired\" });\n msg.topic = \"pairMachineResult\";\n msg.payload = { ok: true, machineId: current.machineId };\n return msg;\n}\n\nconst error = (res && (res.error || res.message)) || (msg.statusCode ? (\"HTTP \" + msg.statusCode) : \"Pairing failed\");\nnode.status({ fill: \"red\", shape: \"ring\", text: \"Pair failed\" });\nmsg.topic = \"pairMachineResult\";\nmsg.payload = { ok: false, error: error };\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 860, + "y": 780, + "wires": [ + [ + "2c8562b2471078ab", + "5a84fb165be942a5" + ] + ] + }, + { + "id": "39d72779cd51be9a", + "type": "link in", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "link into settings", + "links": [], + "x": 255, + "y": 440, + "wires": [ + [ + "afb514404a6ecda1" + ] + ] + }, + { + "id": "fe77ffa843b0dcfb", + "type": "switch", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "Wifi switch", + "property": "topic", + "propertyType": "msg", + "rules": [ + { + "t": "eq", + "v": "wifi:scan", + "vt": "str" + }, + { + "t": "eq", + "v": "wifi:status", + "vt": "str" + }, + { + "t": "eq", + "v": "wifi:apply", + "vt": "str" + } + ], + "checkall": "true", + "repair": false, + "outputs": 3, + "x": 700, + "y": 460, + "wires": [ + [ + "a981c7f429b397f0" + ], + [ + "ebebd1c90b0e488a" + ], + [ + "b699e16ddfa987d9" + ] + ] + }, + { + "id": "ebebd1c90b0e488a", + "type": "link out", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "wifi:status from settings", + "mode": "link", + "links": [], + "x": 815, + "y": 460, + "wires": [] + }, + { + "id": "a981c7f429b397f0", + "type": "link out", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "wifi:scan from settings", + "mode": "link", + "links": [], + "x": 815, + "y": 420, + "wires": [] + }, + { + "id": "b699e16ddfa987d9", + "type": "link out", + "z": "05d4cb231221b842", + "g": "def89ffb5f14d456", + "name": "wifi:apply from settings", + "mode": "link", + "links": [], + "x": 815, + "y": 500, + "wires": [] + }, + { + "id": "0be8578d40ec4541", + "type": "function", + "z": "05d4cb231221b842", + "name": "Parse settings update", + "func": "let payload = msg.payload;\n\nif (Buffer.isBuffer(payload)) {\n payload = payload.toString(\"utf8\");\n}\n\nif (typeof payload === \"string\") {\n try {\n payload = JSON.parse(payload);\n } catch (err) {\n payload = {};\n }\n}\n\nif (!payload || typeof payload !== \"object\") {\n payload = {};\n}\n\nconst topic = String(msg.topic || \"\");\nconst parts = topic.split(\"/\");\n\nfunction pickPart(label) {\n const idx = parts.indexOf(label);\n if (idx === -1) return null;\n return parts[idx + 1] || null;\n}\n\nconst orgId = payload.orgId || pickPart(\"org\");\nconst machineId = payload.machineId || pickPart(\"machines\");\n\nif (orgId) payload.orgId = orgId;\nif (machineId) payload.machineId = machineId;\n\nmsg.payload = payload;\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 480, + "y": 920, + "wires": [ + [ + "a71ab02358e3321d" + ] + ] + }, + { + "id": "a71ab02358e3321d", + "type": "function", + "z": "05d4cb231221b842", + "name": "Fetch settings from Control Tower", + "func": "const config = global.get(\"config\") || {};\nconst base = config.cloudBaseUrl;\nconst apiKey = config.apiKey;\nconst machineId = config.machineId;\n\nif (!base || !apiKey || !machineId) {\n node.status({ fill: \"yellow\", shape: \"ring\", text: \"Settings fetch waiting for pairing\" });\n return null;\n}\n\nconst update = msg.payload || {};\nconst forced = msg.topic === \"settingsRefresh\" || msg.forceRefresh === true;\n\nif (!forced) {\n if (update.machineId && update.machineId !== machineId) {\n return null;\n }\n if (config.orgId && update.orgId && update.orgId !== config.orgId) {\n return null;\n }\n}\n\nconst baseUrl = String(base).replace(/\\/+$/, \"\");\nmsg.method = \"GET\";\nmsg.url = baseUrl + \"/api/settings/machines/\" + machineId;\nmsg.headers = {\n \"x-api-key\": apiKey,\n \"Accept\": \"application/json\"\n};\n\nmsg._settingsUpdate = {\n orgId: update.orgId || config.orgId,\n machineId: update.machineId || machineId,\n version: update.version\n};\nmsg._settingsRequestedAt = Date.now();\n\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 760, + "y": 920, + "wires": [ + [ + "a959b56beda0970f" + ] + ] + }, + { + "id": "a959b56beda0970f", + "type": "http request", + "z": "05d4cb231221b842", + "name": "Fetch settings HTTP", + "method": "use", + "ret": "obj", + "paytoqs": "ignore", + "url": "", + "tls": "", + "persist": false, + "proxy": "", + "insecureHTTPParser": false, + "authType": "", + "senderr": false, + "headers": [], + "x": 1020, + "y": 920, + "wires": [ + [ + "abbec199700a5e29" + ] + ] + }, + { + "id": "abbec199700a5e29", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Apply settings + update UI", + "func": "let payload = msg.payload;\n\nif (Buffer.isBuffer(payload)) {\n payload = payload.toString(\"utf8\");\n}\n\nif (typeof payload === \"string\") {\n try {\n payload = JSON.parse(payload);\n } catch (err) {\n payload = {};\n }\n}\n\nif (!payload || payload.ok === false) {\n node.status({ fill: \"red\", shape: \"ring\", text: \"Settings fetch failed\" });\n return [null, null];\n}\n\nconst effective = payload.effectiveSettings || payload.settings || payload;\nif (!effective || typeof effective !== \"object\") {\n node.status({ fill: \"red\", shape: \"ring\", text: \"Settings payload missing\" });\n return [null, null];\n}\n\nconst defaults = effective.defaults || {};\nconst shiftSchedule = effective.shiftSchedule || {};\nconst thresholds = effective.thresholds || {};\nconst incomingCatalog = effective.reasonCatalog || null;\n\nconst settings = global.get(\"settings\") || {};\n\nconst nextMoldTotal = Number(defaults.moldTotal ?? settings.moldTotal ?? 0);\nconst nextMoldActive = Number(defaults.moldActive ?? settings.moldActive ?? 0);\n\nsettings.moldTotal = nextMoldTotal;\nsettings.moldActive = nextMoldActive;\n\nif (Array.isArray(shiftSchedule.shifts) && shiftSchedule.shifts.length) {\n settings.shifts = shiftSchedule.shifts.map((s) => ({\n start: s.start,\n end: s.end\n }));\n} else if (!Array.isArray(settings.shifts)) {\n settings.shifts = [{ start: \"08:00\", end: \"16:00\" }];\n}\n\nsettings.shiftChangeCompensation = Number(\n shiftSchedule.shiftChangeCompensationMin ?? settings.shiftChangeCompensation ?? 10\n);\nsettings.lunchBreakMinutes = Number(\n shiftSchedule.lunchBreakMin ?? settings.lunchBreakMinutes ?? 30\n);\n\nsettings.thresholdMultiplier = Number(\n thresholds.stoppageMultiplier ?? settings.thresholdMultiplier ?? 1.5\n);\nsettings.macroStoppageMultiplier = Number(\n thresholds.macroStoppageMultiplier ?? settings.macroStoppageMultiplier ?? 5\n);\nsettings.oeeAlertThreshold = Number(\n thresholds.oeeAlertThresholdPct ?? settings.oeeAlertThreshold ?? 90\n);\n\nconst normalizeCatalogItems = (list, fallbackLabelPrefix) => {\n if (!Array.isArray(list)) return [];\n return list\n .map((c, idx) => {\n const categoryId = String(c.id || c.categoryId || (\"cat_\" + idx));\n const categoryLabel = String(c.label || c.categoryLabel || (fallbackLabelPrefix + \" \" + (idx + 1)));\n const detailsRaw = Array.isArray(c.children) ? c.children : (Array.isArray(c.details) ? c.details : []);\n const details = detailsRaw.map((d, jdx) => ({\n id: String(d.id || d.detailId || (categoryId + \"_d\" + jdx)),\n label: String(d.label || d.detailLabel || (\"Detalle \" + (jdx + 1)))\n }));\n return {\n id: categoryId,\n label: categoryLabel,\n children: details\n };\n })\n .filter((c) => c.label && c.children.length > 0);\n};\n\nconst currentCatalog = settings.reasonCatalog || {};\nconst nextCatalogVersion =\n Number(\n (incomingCatalog && incomingCatalog.version) ??\n effective.reasonCatalogVersion ??\n currentCatalog.version ??\n 1\n ) || 1;\n\nconst hasIncomingCatalog = !!(incomingCatalog && (Array.isArray(incomingCatalog.downtime) || Array.isArray(incomingCatalog.scrap)));\nconst normalizedIncoming = hasIncomingCatalog ? {\n version: nextCatalogVersion,\n downtime: normalizeCatalogItems(incomingCatalog.downtime || [], \"Paro\"),\n scrap: normalizeCatalogItems(incomingCatalog.scrap || [], \"Scrap\")\n} : null;\n\nconst fallbackCatalog = {\n version: Number(currentCatalog.version || nextCatalogVersion || 1),\n downtime: normalizeCatalogItems(currentCatalog.downtime || [], \"Paro\"),\n scrap: normalizeCatalogItems(currentCatalog.scrap || [], \"Scrap\")\n};\n\nsettings.reasonCatalog = normalizedIncoming || fallbackCatalog;\nsettings.reasonCatalog.version = Number(settings.reasonCatalog.version || 1);\n\n\nif (effective.version !== undefined) {\n settings.version = Number(effective.version);\n}\n\nglobal.set(\"settings\", settings);\ntry {\n global.set(\"settings\", settings, \"file\");\n} catch (err) {\n // ignore if file store is not configured\n}\nglobal.set(\"moldActive\", settings.moldActive);\nglobal.set(\"moldTotal\", settings.moldTotal);\n\nconst config = global.get(\"config\") || {};\nif (effective.orgId && !config.orgId) {\n config.orgId = effective.orgId;\n global.set(\"config\", config);\n}\n\nnode.status({ fill: \"green\", shape: \"dot\", text: \"Settings synced\" });\n\nconst uiConfigMsg = {\n topic: \"shiftConfigData\",\n payload: {\n shifts: settings.shifts || [],\n shiftChangeCompensation: settings.shiftChangeCompensation || 10,\n lunchBreakMinutes: settings.lunchBreakMinutes || 30,\n thresholdMultiplier: settings.thresholdMultiplier || 1.5,\n macroStoppageMultiplier: settings.macroStoppageMultiplier || 5,\n oeeAlertThreshold: settings.oeeAlertThreshold || 90\n }\n};\n\n\nconst uiMoldMsg = {\n topic: \"moldPresetSelected\",\n payload: {\n total: settings.moldTotal || 0,\n active: settings.moldActive || 0\n }\n};\n\nconst readOnly = config.settingsReadOnly !== false;\nconst uiReadOnlyMsg = { topic: \"settingsReadOnly\", payload: readOnly };\nconst uiReasonCatalogMsg = {\n topic: \"reasonCatalogData\",\n payload: settings.reasonCatalog\n};\n\nnode.send([uiConfigMsg, null]);\nnode.send([uiMoldMsg, null]);\nnode.send([uiReadOnlyMsg, null]);\nnode.send([uiReasonCatalogMsg, null]);\n\nconst update = msg._settingsUpdate || {};\nconst orgId = update.orgId || config.orgId || effective.orgId;\nconst machineId = update.machineId || config.machineId;\nconst version = Number(effective.version ?? update.version ?? 0);\n\nif (!orgId || !machineId) {\n return [null, null];\n}\n\nconst prefix = String(config.mqttTopicPrefix || \"mis\").replace(/\\/+$/, \"\");\nconst ackTopic = prefix + \"/org/\" + orgId + \"/machines/\" + machineId + \"/settings/ack\";\n\nconst ackMsg = {\n topic: ackTopic,\n payload: JSON.stringify({\n type: \"settings_ack\",\n orgId,\n machineId,\n version,\n source: \"node-red\",\n ts: new Date().toISOString()\n })\n};\n\nreturn [null, ackMsg];\n", + "outputs": 2, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1280, + "y": 920, + "wires": [ + [ + "2c8562b2471078ab", + "dbfd127c516efa87", + "9748899355370bae" + ], + [] + ] + }, + { + "id": "3d0065431c1b254c", + "type": "inject", + "z": "05d4cb231221b842", + "name": "Refresh settings (poll)", + "props": [ + { + "p": "payload" + }, + { + "p": "topic", + "vt": "str" + } + ], + "repeat": "600", + "crontab": "", + "once": true, + "onceDelay": 1, + "topic": "settingsRefresh", + "payload": "", + "payloadType": "date", + "x": 240, + "y": 980, + "wires": [ + [ + "a71ab02358e3321d" + ] + ] + }, + { + "id": "c09c71a7e4908231", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Fetch work orders from Control Tower", + "func": "const config = global.get(\"config\") || {};\nconst base = config.cloudBaseUrl;\nconst apiKey = config.apiKey;\nconst machineId = config.machineId;\n\nif (!base || !apiKey || !machineId) {\n node.status({ fill: \"yellow\", shape: \"ring\", text: \"Work orders fetch waiting for pairing\" });\n return null;\n}\n\nconst update = msg.payload || {};\nif (update.machineId && update.machineId !== machineId) {\n return null;\n}\nif (config.orgId && update.orgId && update.orgId !== config.orgId) {\n return null;\n}\n\nconst baseUrl = String(base).replace(/\\/+$/, \"\");\nmsg.method = \"GET\";\nmsg.url = baseUrl + \"/api/work-orders/machines/\" + machineId;\nmsg.headers = {\n \"x-api-key\": apiKey,\n \"Accept\": \"application/json\"\n};\n\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1770, + "y": 320, + "wires": [ + [ + "f9bbe50ab55c42a1" + ] + ] + }, + { + "id": "f9bbe50ab55c42a1", + "type": "http request", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Fetch work orders HTTP", + "method": "use", + "ret": "obj", + "paytoqs": "ignore", + "url": "", + "tls": "", + "persist": false, + "proxy": "", + "insecureHTTPParser": false, + "authType": "", + "senderr": false, + "headers": [], + "x": 2060, + "y": 320, + "wires": [ + [ + "0638171f0c347095", + "d5155c4988b7c5f0" + ] + ] + }, + { + "id": "0638171f0c347095", + "type": "function", + "z": "05d4cb231221b842", + "g": "a1b43a9e095c10db", + "name": "Upsert work orders to local DB", + "func": "let payload = msg.payload;\nif (Buffer.isBuffer(payload)) {\n payload = payload.toString(\"utf8\");\n}\nif (typeof payload === \"string\") {\n try {\n payload = JSON.parse(payload);\n } catch (err) {\n payload = {};\n }\n}\nif (!payload || payload.ok === false) {\n node.status({ fill: \"red\", shape: \"ring\", text: \"Work orders fetch failed\" });\n return null;\n}\n\nconst list = Array.isArray(payload.workOrders)\n ? payload.workOrders\n : Array.isArray(payload.orders)\n ? payload.orders\n : [];\n\nif (!list.length) {\n node.status({ fill: \"yellow\", shape: \"ring\", text: \"No work orders\" });\n return null;\n}\n\nfunction intOrNull(value) {\n if (value === null || value === undefined || value === \"\") return null;\n const n = Number(value);\n if (!Number.isFinite(n) || n < 0) return null;\n return Math.trunc(n);\n}\n\nfunction strOrNull(value, maxLen) {\n if (value === null || value === undefined) return null;\n const s = String(value).trim();\n if (!s) return null;\n return maxLen ? s.slice(0, maxLen) : s;\n}\n\nconst seen = new Set();\nconst values = [];\n\nlist.forEach((order) => {\n const id = String(\n order.workOrderId || order.id || order.work_order_id || \"\"\n ).trim();\n if (!id || seen.has(id)) return;\n seen.add(id);\n\n const sku = String(order.sku || \"\").trim();\n\n const targetQtyRaw = order.targetQty ?? order.target_qty ?? order.target ?? 0;\n const cycleTimeRaw = order.cycleTime ?? order.theoreticalCycleTime ?? order.theoretical_cycle_time ?? 0;\n\n const targetQty = Number.isFinite(Number(targetQtyRaw)) ? Math.trunc(Number(targetQtyRaw)) : 0;\n const cycleTime = Number.isFinite(Number(cycleTimeRaw)) ? Number(cycleTimeRaw) : 0;\n\n // ✨ NUEVO: leer mold y cavidades\n const mold = strOrNull(order.mold ?? order.moldId ?? order.mold_id, 50);\n const cavitiesTotal = intOrNull(order.cavitiesTotal ?? order.cavities_total);\n const cavitiesActive = intOrNull(order.cavitiesActive ?? order.cavities_active);\n\n values.push([id, sku, targetQty, cycleTime, \"PENDING\", mold, cavitiesTotal, cavitiesActive]);\n});\n\nif (!values.length) {\n node.status({ fill: \"yellow\", shape: \"ring\", text: \"No valid work orders\" });\n return null;\n}\n\nmsg.topic = `\n INSERT INTO work_orders\n (work_order_id, sku, target_qty, cycle_time, status, mold, cavities_total, cavities_active)\n VALUES ?\n ON DUPLICATE KEY UPDATE\n sku = VALUES(sku),\n target_qty = VALUES(target_qty),\n cycle_time = VALUES(cycle_time),\n mold = COALESCE(VALUES(mold), mold),\n cavities_total = COALESCE(VALUES(cavities_total), cavities_total),\n cavities_active = COALESCE(VALUES(cavities_active), cavities_active);\n`;\nmsg.payload = [values];\nmsg._mode = \"sync-work-orders\";\n\nnode.status({\n fill: \"green\",\n shape: \"dot\",\n text: `Synced ${values.length} work orders`,\n});\nreturn msg;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 2310, + "y": 320, + "wires": [ + [ + "bfb9b7c7af23bd5c", + "211007c33d60f7ab" + ] + ] + }, + { + "id": "15aea8f70f04da01", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 15", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 1670, + "y": 1340, + "wires": [] + }, + { + "id": "d5155c4988b7c5f0", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 16", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 1860, + "y": 1300, + "wires": [] + }, + { + "id": "211007c33d60f7ab", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 17", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 2020, + "y": 1300, + "wires": [] + }, + { + "id": "07cd5623ad17abdb", + "type": "inject", + "z": "05d4cb231221b842", + "name": "Refresh work orders (poll)", + "props": [ + { + "p": "payload" + }, + { + "p": "topic", + "vt": "str" + } + ], + "repeat": "86400", + "crontab": "", + "once": true, + "onceDelay": 1, + "topic": "workOrdersRefresh", + "payload": "", + "payloadType": "date", + "x": 1350, + "y": 1240, + "wires": [ + [ + "c09c71a7e4908231" + ] + ] + }, + { + "id": "b4a971f8826b7422", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 18", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 1690, + "y": 1120, + "wires": [] + }, + { + "id": "e2cb9e6a86c0d549", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 19", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 2270, + "y": 1220, + "wires": [] + }, + { + "id": "adba20c2e33f1b18", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 20", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 960, + "y": 220, + "wires": [] + }, + { + "id": "2fd4067492e5549b", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 21", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 1710, + "y": 1060, + "wires": [] + }, + { + "id": "dc14ef2f723f75b7", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 22", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 1770, + "y": 1000, + "wires": [] + }, + { + "id": "01fa15279b7facf2", + "type": "function", + "z": "05d4cb231221b842", + "name": "function 3", + "func": "const awo = msg.payload?.activeWorkOrder;\nif (awo) {\n const v = awo.lastUpdateIso;\n\n // If it's already a string, keep it\n if (typeof v === \"string\") {\n // ok\n } else if (v instanceof Date) {\n awo.lastUpdateIso = v.toISOString();\n } else if (v && typeof v.toISO === \"function\") {\n // Luxon DateTime\n awo.lastUpdateIso = v.toISO();\n } else if (v && typeof v.toISOString === \"function\") {\n // Some date-like objects\n awo.lastUpdateIso = v.toISOString();\n } else if (v && typeof v.format === \"function\") {\n // Moment-like\n awo.lastUpdateIso = v.format();\n } else {\n // Last resort: try to stringify, otherwise null it out\n awo.lastUpdateIso = v ? String(v) : null;\n }\n node.warn(`[lastUpdateIso] typeof=${typeof v} value=${v}`);\n node.warn(`[lastUpdateIso] JSON=${JSON.stringify(v)}`);\n}\n\nreturn msg;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 3560, + "y": 740, + "wires": [ + [ + "4770e1bb4693f2f2" + ] + ] + }, + { + "id": "5b485289491bb538", + "type": "function", + "z": "05d4cb231221b842", + "name": "Build Heartbeat HTTP", + "func": "// Build direct heartbeat HTTP request\nconst config = global.get(\"config\") || {};\nconst base = config.cloudBaseUrl;\nconst apiKey = config.apiKey;\n\nif (!base || !apiKey) {\n node.status({ fill: \"yellow\", shape: \"ring\", text: \"Heartbeat waiting for pairing\" });\n return null;\n}\n\nconst baseUrl = String(base).replace(/\\/+$/, \"\");\nmsg.method = \"POST\";\nmsg.url = baseUrl + \"/api/ingest/heartbeat\";\nmsg.headers = {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n};\n\n// Use the same payload you already build in Online HeartBeat\nmsg.payload = {\n machineId: msg.machineId,\n tsDevice: msg.tsMs,\n tsMs: msg.tsMs, // device time; same as tsDevice for preprocess\n status: \"ONLINE\",\n message: \"NR heartbeat\",\n ip: (config.edgeIp || msg.ip || \"192.168.18.33\"),\n fwVersion: (config.fwVersion || \"raspi-nodered-1.0\"),\n};\n\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 2800, + "y": 640, + "wires": [ + [ + "dbaeb91d1ca63eb2" + ] + ] + }, + { + "id": "dbaeb91d1ca63eb2", + "type": "http request", + "z": "05d4cb231221b842", + "name": "Send Heartbeat", + "method": "use", + "ret": "txt", + "paytoqs": "ignore", + "url": "", + "tls": "", + "persist": false, + "proxy": "", + "insecureHTTPParser": false, + "authType": "", + "senderr": false, + "headers": [], + "x": 3040, + "y": 640, + "wires": [ + [ + "d43f0a9277605f85" + ] + ] + }, + { + "id": "d43f0a9277605f85", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 24", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 3210, + "y": 660, + "wires": [] + }, + { + "id": "14c8fb75a042909e", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 25", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 970, + "y": 380, + "wires": [] + }, + { + "id": "d447044432536eca", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 26", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 960, + "y": 420, + "wires": [] + }, + { + "id": "0f0afb7fd521f2c2", + "type": "inject", + "z": "05d4cb231221b842", + "g": "6e514144a570aa72", + "name": "", + "props": [ + { + "p": "payload" + } + ], + "repeat": "", + "crontab": "", + "once": true, + "onceDelay": 0.1, + "topic": "", + "payload": "1", + "payloadType": "num", + "x": 1260, + "y": 240, + "wires": [ + [ + "482feffe728ab41a" + ] + ] + }, + { + "id": "482feffe728ab41a", + "type": "function", + "z": "05d4cb231221b842", + "d": true, + "g": "6e514144a570aa72", + "name": "Simula Inyectora", + "func": "/**\n * Machine Cycle Simulator (0/1 square wave with realistic variance)\n *\n * How to use:\n * - Trigger this node ONCE (Inject once after deploy). It will start emitting 0/1 on its own.\n * - To stop: send a message with msg.payload = \"stop\" (or msg.topic=\"stop\")\n * - To reset state: msg.payload = \"reset\"\n *\n * Output:\n * - msg.payload = 0 or 1\n */\n\nconst CFG = {\n halfPeriodMs: 7250,\n jitterMs: 250,\n perfectRunMs: 30 * 60 * 1000,\n pEnterPerfect: 0, // was 0.12 — disable perfect runs\n pSlowPhase: 0, // was 0.10 — disable slow phases\n pMicroStop: 0.5, // was 0.06 — force frequent microstops\n pMacroStop: 0.2, // was 0.008 — force frequent macrostops\n microStopMs: [5000, 15000],\n macroStopMs: [60 * 1000, 120 * 1000], // shorter macros (1-2 min) so you don't wait 8 min\n slowFactor: [1.25, 1.9],\n slowPhaseToggles: [6, 25],\n minGapMicroMs: 10 * 1000, // was 20s — allow faster retriggering\n minGapMacroMs: 30 * 1000, // was 60s\n};\n\nfunction randInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }\nfunction randFloat(min, max) { return Math.random() * (max - min) + min; }\nfunction pickMs(range) { return randInt(range[0], range[1]); }\nfunction clamp(n, a, b) { return Math.max(a, Math.min(b, n)); }\n\nfunction clearTimer() {\n const t = context.get(\"timer\");\n if (t) clearTimeout(t);\n context.set(\"timer\", null);\n context.set(\"running\", false);\n}\n\nif (msg && (msg.payload === \"stop\" || msg.topic === \"stop\")) {\n clearTimer();\n node.status({ fill: \"grey\", shape: \"ring\", text: \"stopped\" });\n return null;\n}\n\nif (msg && msg.payload === \"reset\") {\n context.set(\"state\", 0);\n node.status({ fill: \"grey\", shape: \"dot\", text: \"reset to 0\" });\n return null;\n}\n\n// Store a template msg (so you can pass machineId/topic/etc. once)\nif (msg && typeof msg === \"object\") {\n const template = Object.assign({}, msg);\n delete template.payload; // we'll overwrite payload each emit\n context.set(\"template\", template);\n}\n\nlet running = context.get(\"running\") || false;\nlet timer = context.get(\"timer\");\nlet state = context.get(\"state\");\nif (state === undefined || state === null) state = 0;\n\nlet phase = context.get(\"phase\") || { type: \"idle\", until: 0, slowLeft: 0 };\nlet lastStopAt = context.get(\"lastStopAt\") || 0;\n\nfunction decideNextDelayMs() {\n const now = Date.now();\n\n // Perfect run active\n if (phase.type === \"perfect\" && now < phase.until) {\n const jitter = randInt(-CFG.jitterMs, CFG.jitterMs);\n return clamp(CFG.halfPeriodMs + jitter, 300, 30 * 60 * 1000);\n }\n\n // Slow phase active (counted in toggles)\n if (phase.type === \"slow\" && phase.slowLeft > 0) {\n phase.slowLeft -= 1;\n context.set(\"phase\", phase);\n\n const factor = randFloat(CFG.slowFactor[0], CFG.slowFactor[1]);\n const jitter = randInt(-CFG.jitterMs, CFG.jitterMs);\n node.status({ fill: \"blue\", shape: \"dot\", text: `slow (${phase.slowLeft} left)` });\n return clamp(Math.round(CFG.halfPeriodMs * factor) + jitter, 300, 30 * 60 * 1000);\n }\n\n // Phase ended → maybe enter a new perfect run\n if (Math.random() < CFG.pEnterPerfect) {\n phase = { type: \"perfect\", until: now + CFG.perfectRunMs, slowLeft: 0 };\n context.set(\"phase\", phase);\n node.status({ fill: \"green\", shape: \"dot\", text: \"perfect run\" });\n return decideNextDelayMs();\n }\n\n // Event selection (macro > micro > slow > normal)\n const sinceStop = now - lastStopAt;\n\n if (sinceStop > CFG.minGapMacroMs && Math.random() < CFG.pMacroStop) {\n lastStopAt = now;\n context.set(\"lastStopAt\", lastStopAt);\n node.status({ fill: \"red\", shape: \"dot\", text: \"MACRO STOP\" });\n return pickMs(CFG.macroStopMs);\n }\n\n if (sinceStop > CFG.minGapMicroMs && Math.random() < CFG.pMicroStop) {\n lastStopAt = now;\n context.set(\"lastStopAt\", lastStopAt);\n node.status({ fill: \"yellow\", shape: \"dot\", text: \"micro stop\" });\n return pickMs(CFG.microStopMs);\n }\n\n if (Math.random() < CFG.pSlowPhase) {\n phase = { type: \"slow\", until: 0, slowLeft: randInt(CFG.slowPhaseToggles[0], CFG.slowPhaseToggles[1]) };\n context.set(\"phase\", phase);\n return decideNextDelayMs();\n }\n\n // Normal running\n node.status({ fill: \"green\", shape: \"dot\", text: \"running\" });\n const jitter = randInt(-CFG.jitterMs, CFG.jitterMs);\n return clamp(CFG.halfPeriodMs + jitter, 300, 30 * 60 * 1000);\n}\n\nfunction emitTick() {\n // Toggle 0/1\n state = state ? 0 : 1;\n context.set(\"state\", state);\n\n const template = context.get(\"template\") || {};\n const out = Object.assign({}, template, { payload: state });\n\n node.send(out);\n\n // Schedule next emission\n const delay = decideNextDelayMs();\n const t = setTimeout(emitTick, delay);\n context.set(\"timer\", t);\n}\n\nif (!running) {\n context.set(\"running\", true);\n node.status({ fill: \"green\", shape: \"dot\", text: \"started\" });\n}\n\n// Don’t start multiple timers if you accidentally keep the old repeating inject\n// before\n// after — always start fresh on trigger; ignore stale post-deploy refs\nclearTimeout(context.get(\"timer\"));\ncontext.set(\"timer\", setTimeout(emitTick, 100));\n\nreturn null;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1440, + "y": 240, + "wires": [ + [ + "1b3bf7d736a4afd3" + ] + ] + }, + { + "id": "5a84fb165be942a5", + "type": "function", + "z": "05d4cb231221b842", + "name": "Persist pairing config", + "func": "const result = msg.payload || {};\nif (!result.ok) return null;\n\nconst config = global.get(\"config\") || {};\nif (!config.machineId || !config.apiKey) return null;\n\nconst settings = global.get(\"settings\") || {};\nconst shifts = settings.shifts || [{ start: \"08:00\", end: \"16:00\" }];\n\nmsg.topic = `\nINSERT INTO current_config (\n machine_id,\n api_key,\n org_id,\n cloud_base_url,\n shifts_json,\n shift_change_comp_min,\n lunch_break_min,\n threshold_multiplier,\n oee_alert_threshold,\n mold_total,\n mold_active,\n updated_at\n) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())\nON DUPLICATE KEY UPDATE\n api_key=VALUES(api_key),\n org_id=VALUES(org_id),\n cloud_base_url=VALUES(cloud_base_url),\n updated_at=NOW();\n`.trim();\n\nmsg.payload = [\n config.machineId,\n config.apiKey,\n config.orgId || null,\n config.cloudBaseUrl || null,\n JSON.stringify(shifts),\n Number(settings.shiftChangeCompensation ?? 10),\n Number(settings.lunchBreakMinutes ?? 30),\n Number(settings.thresholdMultiplier ?? 1.5),\n Number(settings.oeeAlertThreshold ?? 90),\n Number(settings.moldTotal ?? 0),\n Number(settings.moldActive ?? 0)\n];\n\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 1000, + "y": 1060, + "wires": [ + [ + "b686a55196a3aecb", + "1784a31b62b3d253" + ] + ] + }, + { + "id": "b686a55196a3aecb", + "type": "mysql", + "z": "05d4cb231221b842", + "mydb": "fc9634aabefee16b", + "name": "Mold Presets DB", + "x": 1230, + "y": 1060, + "wires": [ + [ + "8a19aa0866695a2d" + ] + ] + }, + { + "id": "49bd3489167d68a3", + "type": "mysql", + "z": "05d4cb231221b842", + "mydb": "fc9634aabefee16b", + "name": "Mold Presets DB", + "x": 3850, + "y": 220, + "wires": [ + [ + "bdd693b849e6f67a", + "023a802a851a13c3" + ] + ] + }, + { + "id": "2cae7ffd21b50dff", + "type": "function", + "z": "05d4cb231221b842", + "name": "load config from DB", + "func": "msg.topic = `\nSELECT machine_id, api_key, org_id, cloud_base_url\nFROM current_config\nWHERE machine_id IS NOT NULL AND machine_id <> '' AND api_key IS NOT NULL AND api_key <> ''\nORDER BY updated_at DESC\nLIMIT 1;\n`.trim();\nmsg.payload = [];\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 3650, + "y": 220, + "wires": [ + [ + "49bd3489167d68a3" + ] + ] + }, + { + "id": "bdd693b849e6f67a", + "type": "function", + "z": "05d4cb231221b842", + "name": "apply config from DB", + "func": "const rows = msg.payload;\n\nif (!Array.isArray(rows) || rows.length === 0) {\n msg._configRetry = (msg._configRetry || 0) + 1;\n msg._configLoaded = false;\n return [null, msg]; // retry path\n}\n\nconst row = rows[0] || {};\nconst machineId = (row.machine_id || \"\").toString().trim();\nconst apiKey = (row.api_key || \"\").toString().trim();\n\nif (!machineId || !apiKey) {\n msg._configRetry = (msg._configRetry || 0) + 1;\n msg._configLoaded = false;\n return [null, msg]; // retry path\n}\n\nif (msg._configRetry > 12) return [null, null]; // optional stop after 12 tries\n\nconst config = global.get(\"config\") || {};\nconfig.machineId = machineId;\nconfig.apiKey = apiKey;\nif (row.org_id) config.orgId = row.org_id;\nif (row.cloud_base_url) config.cloudBaseUrl = row.cloud_base_url;\nif (config.settingsReadOnly === undefined) config.settingsReadOnly = true;\nif (!config.mqttTopicPrefix) config.mqttTopicPrefix = \"mis\";\n\nglobal.set(\"config\", config);\nmsg._configLoaded = true;\nreturn [msg, null];\n", + "outputs": 2, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 4080, + "y": 220, + "wires": [ + [], + [ + "e96d4a126d54edcb" + ] + ] + }, + { + "id": "79e70ba16106b462", + "type": "function", + "z": "05d4cb231221b842", + "d": true, + "name": "throttle + dedupe", + "func": "// KPI Gate: 1/min throttle + dedupe + fresh timestamp\nconst now = Date.now();\nconst minIntervalMs = 60000;\n\nconst payload = msg.outbox?.payload;\nif (!payload) return null;\n\n// stable signature (no tsMs)\nconst sig = JSON.stringify({\n workOrderId: payload.activeWorkOrder?.id || null,\n cycle_count: payload.cycle_count || 0,\n good_parts: payload.good_parts || 0,\n scrap_parts: payload.scrap_parts || 0,\n cavities: payload.cavities || null,\n cycleTime: payload.cycleTime || 0,\n actualCycleTime: payload.actualCycleTime || 0,\n trackingEnabled: !!payload.trackingEnabled,\n productionStarted: !!payload.productionStarted,\n kpis: payload.kpis || {},\n});\n\nconst lastSentAt = flow.get(\"kpi_lastSentAt\") || 0;\nconst lastSig = flow.get(\"kpi_lastSig\") || \"\";\n\n// Drop if too soon and unchanged\nif ((now - lastSentAt) < minIntervalMs && sig === lastSig) {\n return null;\n}\n\n// Update gate state\nflow.set(\"kpi_lastSentAt\", now);\nflow.set(\"kpi_lastSig\", sig);\n\n// Ensure fresh timestamp to avoid timeline weirdness\npayload.tsMs = now;\nmsg.outbox.payload = payload;\nmsg.tsMs = now;\n\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 2410, + "y": 1080, + "wires": [ + [] + ] + }, + { + "id": "4acf0c0395ed5cdc", + "type": "inject", + "z": "05d4cb231221b842", + "name": "KPI minute tick", + "props": [ + { + "p": "payload" + }, + { + "p": "topic", + "vt": "str" + } + ], + "repeat": "60", + "crontab": "", + "once": false, + "onceDelay": 0.1, + "topic": "", + "payload": "", + "payloadType": "date", + "x": 2520, + "y": 840, + "wires": [ + [ + "83e321bafb545a0a" + ] + ] + }, + { + "id": "83e321bafb545a0a", + "type": "function", + "z": "05d4cb231221b842", + "name": "Build KPI Minute Snapshot", + "func": "// Build KPI Minute Snapshot (single source of KPI outbox)\nconst config = global.get(\"config\") || {};\nconst state = global.get(\"state\") || {};\nconst machineId = config.machineId;\nif (!machineId) return null;\n\nconst now = Date.now();\n// Optional: align to minute boundary for clean timeline\nconst tsMs = now - (now % 60000);\n\nconst rawActive = state.activeWorkOrder || null;\nconst active = rawActive ? { ...rawActive } : null;\n\n// Normalize activeWorkOrder.lastUpdateIso to string if present\nif (active && active.lastUpdateIso != null) {\n const v = active.lastUpdateIso;\n if (typeof v === \"string\") {\n // ok\n } else if (v instanceof Date) {\n active.lastUpdateIso = v.toISOString();\n } else if (typeof v === \"number\") {\n active.lastUpdateIso = new Date(v).toISOString();\n } else if (v && typeof v.toISOString === \"function\") {\n active.lastUpdateIso = v.toISOString();\n } else if (v && typeof v.toISO === \"function\") {\n active.lastUpdateIso = v.toISO();\n } else if (v && typeof v.format === \"function\") {\n active.lastUpdateIso = v.format();\n } else {\n delete active.lastUpdateIso; // avoid invalid payload\n }\n}\n\nconst kpis = state.currentKPIs || { oee: 0, availability: 0, performance: 0, quality: 0 };\n\nconst cavitiesRaw = Number(\n active?.cavities ??\n state.lastMoldActive ??\n 0\n);\nconst cavities = cavitiesRaw > 0 ? cavitiesRaw : null;\n\nmsg.machineId = machineId;\nmsg.tsMs = tsMs;\n\nmsg.outbox = {\n type: \"kpi\",\n payload: {\n tsMs,\n activeWorkOrder: active,\n cycle_count: Number(state.cycleCount ?? 0),\n good_parts: Number(active?.goodParts ?? 0),\n scrap_parts: Number(active?.scrapParts ?? 0),\n cavities,\n cycleTime: Number(active?.cycleTime ?? state.lastCycleTime ?? 0),\n actualCycleTime: Number(state.lastActualCycleTime ?? 0),\n trackingEnabled: !!state.trackingEnabled,\n productionStarted: !!state.productionStarted,\n kpis,\n },\n};\n\nreturn msg;\n", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 2740, + "y": 820, + "wires": [ + [ + "e120c11f093ebd9b" + ] + ] + }, + { + "id": "4e7a2904be0f9a37", + "type": "delay", + "z": "05d4cb231221b842", + "name": "", + "pauseType": "delay", + "timeout": "2", + "timeoutUnits": "seconds", + "rate": "1", + "nbRateUnits": "1", + "rateUnits": "second", + "randomFirst": "1", + "randomLast": "5", + "randomUnits": "seconds", + "drop": false, + "allowrate": false, + "outputs": 1, + "x": 3460, + "y": 220, + "wires": [ + [ + "2cae7ffd21b50dff" + ] + ] + }, + { + "id": "e96d4a126d54edcb", + "type": "switch", + "z": "05d4cb231221b842", + "name": "", + "property": "config.apiKey", + "propertyType": "global", + "rules": [ + { + "t": "nempty" + }, + { + "t": "empty" + } + ], + "checkall": "true", + "repair": false, + "outputs": 2, + "x": 4290, + "y": 220, + "wires": [ + [], + [ + "4e7a2904be0f9a37" + ] + ] + }, + { + "id": "1784a31b62b3d253", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 12", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 1210, + "y": 1160, + "wires": [] + }, + { + "id": "8a19aa0866695a2d", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 27", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 1050, + "y": 1240, + "wires": [] + }, + { + "id": "023a802a851a13c3", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 13", + "active": true, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "false", + "statusVal": "", + "statusType": "auto", + "x": 4030, + "y": 140, + "wires": [] + }, + { + "id": "1b3bf7d736a4afd3", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 14", + "active": true, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "true", + "targetType": "full", + "statusVal": "", + "statusType": "auto", + "x": 2710, + "y": 460, + "wires": [] + }, + { + "id": "b219495329321d63", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 23", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "false", + "statusVal": "", + "statusType": "auto", + "x": 2310, + "y": 60, + "wires": [] + }, + { + "id": "d83778d03dc54c39", + "type": "16inpind", + "z": "05d4cb231221b842", + "d": true, + "name": "", + "stack": "0", + "channel": "5", + "x": 2740, + "y": 120, + "wires": [ + [ + "ce36a3271d9df8ae", + "601d2022200f67c1" + ] + ] + }, + { + "id": "6d2a75aa076da9b6", + "type": "inject", + "z": "05d4cb231221b842", + "name": "", + "props": [ + { + "p": "payload" + }, + { + "p": "topic", + "vt": "str" + } + ], + "repeat": "0.01", + "crontab": "", + "once": true, + "onceDelay": 0.1, + "topic": "", + "payload": "", + "payloadType": "date", + "x": 2550, + "y": 120, + "wires": [ + [ + "d83778d03dc54c39", + "bfcff0fe51b169c8" + ] + ] + }, + { + "id": "ef6299b3d440c194", + "type": "function", + "z": "05d4cb231221b842", + "name": "Fetch claimed rows", + "func": "// Después del UPDATE...status='sending', leer las filas que acabamos de reservar\nmsg.topic = `\nSELECT id, machine_id, msg_type, endpoint, schema_version, seq, ts_device_ms,\n payload_json, attempts, next_attempt_at\nFROM outbox_messages\nWHERE status='sending'\nORDER BY id ASC\nLIMIT 25;\n`.trim();\n\nmsg._stage = \"fetch\";\nreturn msg;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 3190, + "y": 720, + "wires": [ + [ + "b81555cd8e9fcc31" + ] + ] + }, + { + "id": "b81555cd8e9fcc31", + "type": "mysql", + "z": "05d4cb231221b842", + "mydb": "fc9634aabefee16b", + "name": "Fetch pending outbox", + "x": 3360, + "y": 780, + "wires": [ + [ + "85a333219d51a809" + ] + ] + }, + { + "id": "5dbbcccbadfb8038", + "type": "function", + "z": "05d4cb231221b842", + "name": "Release lock no rows", + "func": "flow.set(\"publisherBusy\", false);\nnode.status({ fill: \"grey\", shape: \"dot\", text: \"idle\" });\nreturn null;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 3460, + "y": 840, + "wires": [ + [] + ] + }, + { + "id": "c7f59092785681d1", + "type": "function", + "z": "05d4cb231221b842", + "name": "Release dock", + "func": "flow.set(\"publisherBusy\", false);\nreturn null;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 4530, + "y": 800, + "wires": [ + [] + ] + }, + { + "id": "36a23edb4d1ac99a", + "type": "function", + "z": "05d4cb231221b842", + "name": "Watchdog cleanup", + "func": "msg.topic = `\nUPDATE outbox_messages\nSET status=?\nWHERE status=?\n AND updated_at < DATE_SUB(NOW(), INTERVAL ? SECOND);\n`.trim();\n\nmsg.payload = ['pending', 'sending', 60];\n\nflow.set(\"publisherBusy\", false);\nreturn msg;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 4130, + "y": 580, + "wires": [ + [ + "ff8cf061308cbbcd" + ] + ] + }, + { + "id": "ff8cf061308cbbcd", + "type": "mysql", + "z": "05d4cb231221b842", + "mydb": "fc9634aabefee16b", + "name": "Update outbox status", + "x": 4360, + "y": 580, + "wires": [ + [ + "c57fd79d84b867c4" + ] + ] + }, + { + "id": "d33dd7b6ed5d7fe3", + "type": "inject", + "z": "05d4cb231221b842", + "name": "", + "props": [ + { + "p": "payload" + }, + { + "p": "topic", + "vt": "str" + } + ], + "repeat": "60", + "crontab": "", + "once": true, + "onceDelay": 0.1, + "topic": "", + "payload": "", + "payloadType": "date", + "x": 3920, + "y": 520, + "wires": [ + [ + "36a23edb4d1ac99a" + ] + ] + }, + { + "id": "66f93cb8bab967d0", + "type": "inject", + "z": "05d4cb231221b842", + "name": "", + "props": [ + { + "p": "payload" + }, + { + "p": "topic", + "vt": "str" + } + ], + "repeat": "", + "crontab": "", + "once": false, + "onceDelay": 0.1, + "topic": "", + "payload": "", + "payloadType": "date", + "x": 4120, + "y": 380, + "wires": [ + [ + "64a1a270cb5c06e0" + ] + ] + }, + { + "id": "307af4023994831e", + "type": "function", + "z": "05d4cb231221b842", + "name": "function 2", + "func": "const state = global.get(\"state\") || {};\nnode.warn(\"activeWorkOrder: \" + JSON.stringify(state.activeWorkOrder, null, 2));\nnode.warn(\"trackingEnabled: \" + state.trackingEnabled);\nnode.warn(\"productionStarted: \" + state.productionStarted);\nreturn null;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 4320, + "y": 380, + "wires": [ + [] + ] + }, + { + "id": "c57fd79d84b867c4", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 28", + "active": true, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "false", + "statusVal": "", + "statusType": "auto", + "x": 4660, + "y": 580, + "wires": [] + }, + { + "id": "a81eeab71b69af87", + "type": "function", + "z": "05d4cb231221b842", + "name": "function 4", + "func": "const state = global.get(\"state\") || {};\nnode.warn(\"activeWorkOrder.id: \" + state.activeWorkOrder?.id);\nnode.warn(\"cavitiesActive: \" + state.activeWorkOrder?.cavitiesActive);\nnode.warn(\"trackingEnabled: \" + state.trackingEnabled);\nnode.warn(\"productionStarted: \" + state.productionStarted);\nnode.warn(\"cycleCount: \" + state.cycleCount);\nreturn null;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 4330, + "y": 440, + "wires": [ + [] + ] + }, + { + "id": "ac109fb4fedbe7ad", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 29", + "active": true, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "false", + "statusVal": "", + "statusType": "auto", + "x": 4510, + "y": 440, + "wires": [] + }, + { + "id": "946c834f8b50e15a", + "type": "function", + "z": "05d4cb231221b842", + "name": "function 5", + "func": "const state = global.get(\"state\") || {};\nnode.warn(\"=== DIAGNÓSTICO STATE ===\");\nnode.warn(\"activeWorkOrder.id: \" + state.activeWorkOrder?.id);\nnode.warn(\"cycleCount: \" + state.cycleCount);\nnode.warn(\"trackingEnabled: \" + state.trackingEnabled);\nnode.warn(\"productionStarted: \" + state.productionStarted);\nnode.warn(\"flow.lastMachineState: \" + flow.get(\"lastMachineState\"));\nreturn null;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 4320, + "y": 320, + "wires": [ + [ + "b567a5cf1a50ab28" + ] + ] + }, + { + "id": "64a1a270cb5c06e0", + "type": "function", + "z": "05d4cb231221b842", + "name": "function 6", + "func": "const state = global.get(\"state\") || {};\nstate.activeWorkOrder = null;\nstate.activeOrderId = null;\nstate.activeOrderHasProgress = false;\nstate.cycleCount = 0;\nstate.trackingEnabled = false;\nstate.productionStarted = false;\nstate.lastState = {\n ...(state.lastState || {}),\n activeWorkOrder: null,\n cycleCount: 0,\n goodParts: 0,\n scrapParts: 0,\n trackingEnabled: false,\n productionStarted: false,\n tsMs: Date.now()\n};\ndelete state.lastMoldActive;\ndelete state.lastMoldTotal;\ndelete state.moldByWorkOrder;\nglobal.set(\"state\", state);\nglobal.set(\"moldCache\", null);\nflow.set(\"lastMachineState\", 0);\nnode.warn(\"State limpiado\");\nreturn null;", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 4320, + "y": 480, + "wires": [ + [] + ] + }, + { + "id": "601d2022200f67c1", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 30", + "active": false, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "payload", + "targetType": "msg", + "statusVal": "", + "statusType": "auto", + "x": 2960, + "y": 80, + "wires": [] + }, + { + "id": "bfcff0fe51b169c8", + "type": "exec", + "z": "05d4cb231221b842", + "command": "16inpind 0 rd 5", + "addpay": "", + "append": "", + "useSpawn": "false", + "timer": "", + "winHide": false, + "oldrc": false, + "name": "Read sensor", + "x": 2720, + "y": 60, + "wires": [ + [ + "601d2022200f67c1", + "ce36a3271d9df8ae" + ], + [], + [] + ] + }, + { + "id": "b567a5cf1a50ab28", + "type": "debug", + "z": "05d4cb231221b842", + "name": "debug 31", + "active": true, + "tosidebar": true, + "console": false, + "tostatus": false, + "complete": "false", + "statusVal": "", + "statusType": "auto", + "x": 4490, + "y": 320, + "wires": [] + }, + { + "id": "092651abe2113f4e", + "type": "function", + "z": "05d4cb231221b842", + "name": "function 7", + "func": "// Test: mandar SOLO machineStatus, sin nada más\nreturn [{\n topic: \"machineStatus\",\n payload: {\n machineOnline: true,\n productionStarted: false,\n trackingEnabled: false\n }\n}];", + "outputs": 1, + "timeout": 0, + "noerr": 0, + "initialize": "", + "finalize": "", + "libs": [], + "x": 100, + "y": 320, + "wires": [ + [ + "dbfd127c516efa87" + ] + ] + }, + { + "id": "be9412bfa9abb589", + "type": "inject", + "z": "05d4cb231221b842", + "name": "", + "props": [ + { + "p": "payload" + }, + { + "p": "topic", + "vt": "str" + } + ], + "repeat": "", + "crontab": "", + "once": false, + "onceDelay": 0.1, + "topic": "", + "payload": "", + "payloadType": "date", + "x": 80, + "y": 200, + "wires": [ + [ + "092651abe2113f4e" + ] + ] + }, + { + "id": "919b5b8d778e2b6c", + "type": "ui_group", + "name": "Default", + "tab": "c567195d86466cd5", + "order": 1, + "disp": false, + "width": "25", + "collapse": false, + "className": "" + }, + { + "id": "e2f3a4b5c6d7e8f9", + "type": "ui_group", + "name": "Alerts Group", + "tab": "a1b2c3d4e5f60718", + "order": 1, + "disp": false, + "width": "25", + "collapse": false, + "className": "" + }, + { + "id": "e3f4a5b6c7d8e9f0", + "type": "ui_group", + "name": "Graphs Group", + "tab": "b2c3d4e5f6a70182", + "order": 1, + "disp": false, + "width": "25", + "collapse": false, + "className": "" + }, + { + "id": "e4f5a6b7c8d9e0f1", + "type": "ui_group", + "name": "Help Group", + "tab": "c3d4e5f6a7b80192", + "order": 1, + "disp": false, + "width": "25", + "collapse": false, + "className": "" + }, + { + "id": "e5f6a7b8c9d0e1f2", + "type": "ui_group", + "name": "Settings Group", + "tab": "d4e5f6a7b8c90123", + "order": 1, + "disp": false, + "width": "25", + "collapse": false, + "className": "" + }, + { + "id": "b99c269687d574aa", + "type": "ui_group", + "name": "Work Orders Group", + "tab": "d1a1e2f3a4b5c6d7", + "order": 1, + "disp": false, + "width": 25, + "collapse": false, + "className": "" + }, + { + "id": "fc9634aabefee16b", + "type": "MySQLdatabase", + "name": "Edge Outbox", + "host": "127.0.0.1", + "port": "3306", + "db": "edge_outbox", + "tz": "", + "charset": "UTF8" + }, + { + "id": "c567195d86466cd5", + "type": "ui_tab", + "name": "Home", + "icon": "dashboard", + "order": 1, + "disabled": false, + "hidden": false + }, + { + "id": "a1b2c3d4e5f60718", + "type": "ui_tab", + "name": "Alerts", + "icon": "warning", + "order": 3, + "disabled": false, + "hidden": false + }, + { + "id": "b2c3d4e5f6a70182", + "type": "ui_tab", + "name": "Graphs", + "icon": "show_chart", + "order": 4, + "disabled": false, + "hidden": false + }, + { + "id": "c3d4e5f6a7b80192", + "type": "ui_tab", + "name": "Help", + "icon": "help", + "order": 5, + "disabled": false, + "hidden": false + }, + { + "id": "d4e5f6a7b8c90123", + "type": "ui_tab", + "name": "Settings", + "icon": "settings", + "order": 6, + "disabled": false, + "hidden": false + }, + { + "id": "d1a1e2f3a4b5c6d7", + "type": "ui_tab", + "name": "Work Orders", + "icon": "list", + "order": 2, + "disabled": false, + "hidden": false + }, + { + "id": "6ad577d11bccd256", + "type": "global-config", + "env": [], + "modules": { + "node-red-node-mysql": "2.0.0", + "node-red-dashboard": "3.6.6", + "node-red-contrib-spreadsheet-in": "0.7.2", + "node-red-node-pi-gpio": "2.0.6", + "node-red-contrib-sm-16inpind": "1.0.1" + } + } +] \ No newline at end of file diff --git a/lib/i18n/en.json b/lib/i18n/en.json index 5883809..2cc24f6 100644 --- a/lib/i18n/en.json +++ b/lib/i18n/en.json @@ -1,106 +1,106 @@ -{ - "---": "---", - "common.loading": "Loading...", - "common.loadingShort": "Loading", - "common.never": "never", - "common.na": "--", - "common.back": "Back", - "common.cancel": "Cancel", +{ + "---": "---", + "common.loading": "Loading...", + "common.loadingShort": "Loading", + "common.never": "never", + "common.na": "--", + "common.back": "Back", + "common.cancel": "Cancel", "common.close": "Close", "common.save": "Save", "common.copy": "Copy", "common.yes": "Yes", "common.no": "No", - "nav.overview": "Overview", - "nav.machines": "Machines", - "nav.reports": "Reports", - "nav.alerts": "Alerts", - "nav.financial": "Financial", - "nav.settings": "Settings", - "sidebar.productTitle": "MIS", - "sidebar.productSubtitle": "Control Tower", - "sidebar.userFallback": "User", - "sidebar.loadingOrg": "Loading...", - "sidebar.themeTooltip": "Theme and language settings", - "sidebar.switchToDark": "Switch to dark mode", - "sidebar.switchToLight": "Switch to light mode", - "sidebar.logout": "Logout", - "sidebar.role.member": "MEMBER", - "sidebar.role.admin": "ADMIN", - "sidebar.role.owner": "OWNER", - "login.title": "Control Tower", - "login.subtitle": "Sign in to your organization", - "login.email": "Email", - "login.password": "Password", - "login.error.default": "Login failed", - "login.error.network": "Network error", - "login.submit.loading": "Signing in...", - "login.submit.default": "Login", - "login.newHere": "New here?", - "login.createAccount": "Create an account", - "signup.verify.title": "Verify your email", - "signup.verify.sent": "We sent a verification link to {email}.", - "signup.verify.failed": "Verification email failed to send. Please contact support.", - "signup.verify.notice": "Once verified, you can sign in and invite your team.", - "signup.verify.back": "Back to login", - "signup.title": "Create your Control Tower", - "signup.subtitle": "Set up your organization and invite the team.", - "signup.orgName": "Organization name", - "signup.yourName": "Your name", - "signup.email": "Email", - "signup.password": "Password", - "signup.error.default": "Signup failed", - "signup.error.network": "Network error", - "signup.submit.loading": "Creating account...", - "signup.submit.default": "Create account", - "signup.alreadyHave": "Already have access?", - "signup.signIn": "Sign in", - "invite.loading": "Loading invite...", - "invite.notFound": "Invite not found.", - "invite.joinTitle": "Join {org}", - "invite.acceptCopy": "Accept the invite for {email} as {role}.", - "invite.yourName": "Your name", - "invite.password": "Password", - "invite.error.notFound": "Invite not found", - "invite.error.acceptFailed": "Invite acceptance failed", - "invite.submit.loading": "Joining...", - "invite.submit.default": "Join organization", - "overview.title": "Overview", - "overview.subtitle": "Fleet pulse, alerts, and top attention items.", - "overview.viewMachines": "View Machines", - "overview.loading": "Loading overview...", - "overview.fleetHealth": "Fleet Health", - "overview.machinesTotal": "Machines total", - "overview.online": "Online", - "overview.offline": "Offline", - "overview.run": "Run", - "overview.idle": "Idle", - "overview.stop": "Stop", - "overview.productionTotals": "Production Totals", - "overview.good": "Good", - "overview.scrap": "Scrap", - "overview.target": "Target", - "overview.kpiSumNote": "Sum of latest KPIs across machines.", - "overview.activityFeed": "Activity Feed", - "overview.eventsRefreshing": "Refreshing recent events...", - "overview.eventsLast30": "Last 30 merged events", - "overview.eventsNone": "No recent events.", - "overview.oeeAvg": "OEE (avg)", - "overview.availabilityAvg": "Availability (avg)", - "overview.performanceAvg": "Performance (avg)", - "overview.qualityAvg": "Quality (avg)", - "overview.attentionList": "Attention List", - "overview.shown": "shown", - "overview.noUrgent": "No urgent issues detected.", - "overview.timeline": "Unified Timeline", - "overview.items": "items", - "overview.noEvents": "No events yet.", - "overview.ack": "ACK", - "overview.severity.critical": "CRITICAL", - "overview.severity.warning": "WARNING", - "overview.severity.info": "INFO", - "overview.source.ingested": "ingested", - "overview.source.derived": "derived", + "nav.overview": "Overview", + "nav.machines": "Machines", + "nav.reports": "Reports", + "nav.alerts": "Alerts", + "nav.financial": "Financial", + "nav.settings": "Settings", + "sidebar.productTitle": "MIS", + "sidebar.productSubtitle": "Control Tower", + "sidebar.userFallback": "User", + "sidebar.loadingOrg": "Loading...", + "sidebar.themeTooltip": "Theme and language settings", + "sidebar.switchToDark": "Switch to dark mode", + "sidebar.switchToLight": "Switch to light mode", + "sidebar.logout": "Logout", + "sidebar.role.member": "MEMBER", + "sidebar.role.admin": "ADMIN", + "sidebar.role.owner": "OWNER", + "login.title": "Control Tower", + "login.subtitle": "Sign in to your organization", + "login.email": "Email", + "login.password": "Password", + "login.error.default": "Login failed", + "login.error.network": "Network error", + "login.submit.loading": "Signing in...", + "login.submit.default": "Login", + "login.newHere": "New here?", + "login.createAccount": "Create an account", + "signup.verify.title": "Verify your email", + "signup.verify.sent": "We sent a verification link to {email}.", + "signup.verify.failed": "Verification email failed to send. Please contact support.", + "signup.verify.notice": "Once verified, you can sign in and invite your team.", + "signup.verify.back": "Back to login", + "signup.title": "Create your Control Tower", + "signup.subtitle": "Set up your organization and invite the team.", + "signup.orgName": "Organization name", + "signup.yourName": "Your name", + "signup.email": "Email", + "signup.password": "Password", + "signup.error.default": "Signup failed", + "signup.error.network": "Network error", + "signup.submit.loading": "Creating account...", + "signup.submit.default": "Create account", + "signup.alreadyHave": "Already have access?", + "signup.signIn": "Sign in", + "invite.loading": "Loading invite...", + "invite.notFound": "Invite not found.", + "invite.joinTitle": "Join {org}", + "invite.acceptCopy": "Accept the invite for {email} as {role}.", + "invite.yourName": "Your name", + "invite.password": "Password", + "invite.error.notFound": "Invite not found", + "invite.error.acceptFailed": "Invite acceptance failed", + "invite.submit.loading": "Joining...", + "invite.submit.default": "Join organization", + "overview.title": "Overview", + "overview.subtitle": "Fleet pulse, alerts, and top attention items.", + "overview.viewMachines": "View Machines", + "overview.loading": "Loading overview...", + "overview.fleetHealth": "Fleet Health", + "overview.machinesTotal": "Machines total", + "overview.online": "Online", + "overview.offline": "Offline", + "overview.run": "Run", + "overview.idle": "Idle", + "overview.stop": "Stop", + "overview.productionTotals": "Production Totals", + "overview.good": "Good", + "overview.scrap": "Scrap", + "overview.target": "Target", + "overview.kpiSumNote": "Sum of latest KPIs across machines.", + "overview.activityFeed": "Activity Feed", + "overview.eventsRefreshing": "Refreshing recent events...", + "overview.eventsLast30": "Last 30 merged events", + "overview.eventsNone": "No recent events.", + "overview.oeeAvg": "OEE (avg)", + "overview.availabilityAvg": "Availability (avg)", + "overview.performanceAvg": "Performance (avg)", + "overview.qualityAvg": "Quality (avg)", + "overview.attentionList": "Attention List", + "overview.shown": "shown", + "overview.noUrgent": "No urgent issues detected.", + "overview.timeline": "Unified Timeline", + "overview.items": "items", + "overview.noEvents": "No events yet.", + "overview.ack": "ACK", + "overview.severity.critical": "CRITICAL", + "overview.severity.warning": "WARNING", + "overview.severity.info": "INFO", + "overview.source.ingested": "ingested", + "overview.source.derived": "derived", "overview.event.macrostop": "macrostop", "overview.event.microstop": "microstop", "overview.event.slow-cycle": "slow-cycle", @@ -192,15 +192,15 @@ "recap.timeline.type.idle": "Idle", "recap.empty.production": "No production recorded", "machines.title": "Machines", - "machines.subtitle": "Select a machine to view live KPIs.", - "machines.cancel": "Cancel", - "machines.addMachine": "Add Machine", - "machines.backOverview": "Back to Overview", - "machines.addCardTitle": "Add a machine", - "machines.addCardSubtitle": "Generate the machine ID and API key for your Node-RED edge.", - "machines.field.name": "Machine Name", - "machines.field.code": "Code (optional)", - "machines.field.location": "Location (optional)", + "machines.subtitle": "Select a machine to view live KPIs.", + "machines.cancel": "Cancel", + "machines.addMachine": "Add Machine", + "machines.backOverview": "Back to Overview", + "machines.addCardTitle": "Add a machine", + "machines.addCardSubtitle": "Generate the machine ID and API key for your Node-RED edge.", + "machines.field.name": "Machine Name", + "machines.field.code": "Code (optional)", + "machines.field.location": "Location (optional)", "machines.create.loading": "Creating...", "machines.create.default": "Create Machine", "machines.create.error.nameRequired": "Machine name is required", @@ -210,279 +210,280 @@ "machines.delete.confirm": "Remove {name}? This will delete the machine and its data.", "machines.delete.error.failed": "Failed to remove machine", "machines.pairing.title": "Edge pairing code", - "machines.pairing.machine": "Machine:", - "machines.pairing.codeLabel": "Pairing code", - "machines.pairing.expires": "Expires", - "machines.pairing.soon": "soon", - "machines.pairing.instructions": "Enter this code on the Node-RED Control Tower settings screen to link the edge device.", - "machines.pairing.copy": "Copy Code", - "machines.pairing.copied": "Copied", - "machines.pairing.copyUnsupported": "Copy not supported", - "machines.pairing.copyFailed": "Copy failed", - "machines.loading": "Loading machines...", - "machines.empty": "No machines found for this org.", - "machines.status": "Status", - "machines.status.noHeartbeat": "No heartbeat", - "machines.status.ok": "Heartbeat", - "machines.status.offline": "OFFLINE", - "machines.status.unknown": "UNKNOWN", - "machines.lastSeen": "Last seen {time}", - "machine.detail.titleFallback": "Machine", - "machine.detail.lastSeen": "Last seen {time}", - "machine.detail.loading": "Loading...", - "machine.detail.error.failed": "Failed to load machine", - "machine.detail.error.network": "Network error", - "machine.detail.back": "Back", - "machine.detail.workOrders.upload": "Upload Work Orders", - "machine.detail.workOrders.uploading": "Uploading...", - "machine.detail.workOrders.uploadParsing": "Parsing file...", - "machine.detail.workOrders.uploadHint": "CSV or XLSX with Work Order ID, SKU, Theoretical Cycle Time (Seconds), Target Quantity.", - "machine.detail.workOrders.uploadSuccess": "Uploaded {count} work orders", - "machine.detail.workOrders.uploadError": "Upload failed", - "machine.detail.workOrders.uploadInvalid": "No valid work orders found", - "machine.detail.workOrders.uploadUnauthorized": "Not authorized to upload work orders", - "machine.detail.status.offline": "OFFLINE", - "machine.detail.status.unknown": "UNKNOWN", - "machine.detail.status.run": "RUN", - "machine.detail.status.idle": "IDLE", - "machine.detail.status.stop": "STOP", - "machine.detail.status.down": "DOWN", - "machine.detail.bucket.normal": "Normal Cycle", - "machine.detail.bucket.slow": "Slow Cycle", - "machine.detail.bucket.microstop": "Microstop", - "machine.detail.bucket.macrostop": "Macrostop", - "machine.detail.bucket.unknown": "Unknown", - "machine.detail.activity.title": "Machine Activity Timeline", - "machine.detail.activity.subtitle": "Real-time analysis of production cycles", - "machine.detail.activity.noData": "No timeline data yet.", - "machine.detail.tooltip.cycle": "Cycle: {label}", - "machine.detail.tooltip.duration": "Duration", - "machine.detail.tooltip.ideal": "Ideal", - "machine.detail.tooltip.deviation": "Deviation", + "machines.pairing.machine": "Machine:", + "machines.pairing.codeLabel": "Pairing code", + "machines.pairing.expires": "Expires", + "machines.pairing.soon": "soon", + "machines.pairing.instructions": "Enter this code on the Node-RED Control Tower settings screen to link the edge device.", + "machines.pairing.copy": "Copy Code", + "machines.pairing.copied": "Copied", + "machines.pairing.copyUnsupported": "Copy not supported", + "machines.pairing.copyFailed": "Copy failed", + "machines.loading": "Loading machines...", + "machines.empty": "No machines found for this org.", + "machines.status": "Status", + "machines.status.noHeartbeat": "No heartbeat", + "machines.status.ok": "Heartbeat", + "machines.status.offline": "OFFLINE", + "machines.status.unknown": "UNKNOWN", + "machines.lastSeen": "Last seen {time}", + "machine.detail.titleFallback": "Machine", + "machine.detail.lastSeen": "Last seen {time}", + "machine.detail.loading": "Loading...", + "machine.detail.error.failed": "Failed to load machine", + "machine.detail.error.network": "Network error", + "machine.detail.back": "Back", + "machine.detail.workOrders.upload": "Upload Work Orders", + "machine.detail.workOrders.downloadTemplate": "Download Template", + "machine.detail.workOrders.uploading": "Uploading...", + "machine.detail.workOrders.uploadParsing": "Parsing file...", + "machine.detail.workOrders.uploadHint": "CSV or XLSX: Work Order ID, SKU, Theoretical Cycle Time (Seconds), Target Quantity, Mold, Total Cavities, Active Cavities (first four columns are enough for legacy files).", + "machine.detail.workOrders.uploadSuccess": "Uploaded {count} work orders", + "machine.detail.workOrders.uploadError": "Upload failed", + "machine.detail.workOrders.uploadInvalid": "No valid work orders found", + "machine.detail.workOrders.uploadUnauthorized": "Not authorized to upload work orders", + "machine.detail.status.offline": "OFFLINE", + "machine.detail.status.unknown": "UNKNOWN", + "machine.detail.status.run": "RUN", + "machine.detail.status.idle": "IDLE", + "machine.detail.status.stop": "STOP", + "machine.detail.status.down": "DOWN", + "machine.detail.bucket.normal": "Normal Cycle", + "machine.detail.bucket.slow": "Slow Cycle", + "machine.detail.bucket.microstop": "Microstop", + "machine.detail.bucket.macrostop": "Macrostop", + "machine.detail.bucket.unknown": "Unknown", + "machine.detail.activity.title": "Machine Activity Timeline", + "machine.detail.activity.subtitle": "Real-time analysis of production cycles", + "machine.detail.activity.noData": "No timeline data yet.", + "machine.detail.tooltip.cycle": "Cycle: {label}", + "machine.detail.tooltip.duration": "Duration", + "machine.detail.tooltip.ideal": "Ideal", + "machine.detail.tooltip.deviation": "Deviation", "machine.detail.kpi.oeeCurrent": "Current OEE", "machine.detail.kpi.updated": "Updated {time}", - "machine.detail.currentWorkOrder": "Current Work Order", - "machine.detail.recentEvents": "Critical Events", - "machine.detail.noEvents": "No events yet.", - "machine.detail.cycleTarget": "Cycle target", - "machine.detail.mini.events": "Detected Events", - "machine.detail.mini.events.subtitle": "Canonical events (all)", - "machine.detail.mini.deviation": "Actual vs Standard Cycle", - "machine.detail.mini.deviation.subtitle": "Average deviation", - "machine.detail.mini.impact": "Production Impact", - "machine.detail.mini.impact.subtitle": "Extra time vs ideal", - "machine.detail.modal.events": "Detected Events", - "machine.detail.modal.deviation": "Actual vs Standard Cycle", - "machine.detail.modal.impact": "Production Impact", - "machine.detail.modal.standardCycle": "Standard cycle (ideal)", - "machine.detail.modal.avgDeviation": "Average deviation", - "machine.detail.modal.sample": "Sample", - "machine.detail.modal.cycles": "cycles", - "machine.detail.modal.tip": "Tip: the faint line is the ideal. Each point is a real cycle.", - "machine.detail.modal.totalExtra": "Total extra time", - "machine.detail.modal.microstops": "Microstops", - "machine.detail.modal.macroStops": "Macro stops", - "machine.detail.modal.extraTimeLabel": "Extra time", - "machine.detail.modal.extraTimeNote": "This is \"lost time\" vs ideal, distributed by event type.", - "reports.title": "Reports", - "reports.subtitle": "Trends, downtime, and quality analytics across machines.", - "reports.exportCsv": "Export CSV", - "reports.exportPdf": "Export PDF", - "reports.filters": "Filters", - "reports.rangeLabel.last24": "Last 24 hours", - "reports.rangeLabel.last7": "Last 7 days", - "reports.rangeLabel.last30": "Last 30 days", - "reports.rangeLabel.custom": "Custom range", - "reports.filter.range": "Range", - "reports.filter.machine": "Machine", - "reports.filter.workOrder": "Work Order", - "reports.filter.sku": "SKU", - "reports.filter.allMachines": "All machines", - "reports.filter.allWorkOrders": "All work orders", - "reports.filter.allSkus": "All SKUs", - "reports.loading": "Loading reports...", - "reports.error.failed": "Failed to load reports", - "reports.error.network": "Network error", - "reports.kpi.note.withData": "Computed from KPI snapshots.", - "reports.kpi.note.noData": "No data in selected range.", - "reports.oeeTrend": "OEE Trend", - "reports.downtimePareto": "Downtime Pareto", - "reports.cycleDistribution": "Cycle Time Distribution", - "reports.scrapTrend": "Scrap Trend", - "reports.topLossDrivers": "Top Loss Drivers", - "reports.qualitySummary": "Quality Summary", - "reports.notes": "Notes for Ops", - "alerts.title": "Alerts", - "alerts.subtitle": "Alert history with filters and drilldowns.", - "alerts.comingSoon": "Alert configuration UI is coming soon.", - "alerts.loading": "Loading alerts...", - "alerts.error.loadPolicy": "Failed to load alert policy.", - "alerts.error.savePolicy": "Failed to save alert policy.", - "alerts.error.loadContacts": "Failed to load alert contacts.", - "alerts.error.saveContacts": "Failed to save alert contact.", - "alerts.error.deleteContact": "Failed to delete alert contact.", - "alerts.error.createContact": "Failed to create alert contact.", - "alerts.policy.title": "Alert policy", - "alerts.policy.subtitle": "Configure escalation by role, channel, and duration.", - "alerts.policy.save": "Save policy", - "alerts.policy.saving": "Saving...", - "alerts.policy.defaults": "Default escalation (per role)", - "alerts.policy.enabled": "Enabled", - "alerts.policy.afterMinutes": "After minutes", - "alerts.policy.channels": "Channels", - "alerts.policy.repeatMinutes": "Repeat (min)", - "alerts.policy.readOnly": "You can view alert policy settings, but only owners can edit.", - "alerts.policy.defaultsHelp": "Defaults apply when a specific event is reset or not customized.", - "alerts.policy.eventSelectLabel": "Event type", - "alerts.policy.eventSelectHelper": "Adjust escalation rules for a single event type.", - "alerts.policy.applyDefaults": "Apply defaults", - "alerts.event.macrostop": "Macrostop", - "alerts.event.microstop": "Microstop", - "alerts.event.slow-cycle": "Slow cycle", - "alerts.event.offline": "Offline", - "alerts.event.error": "Error", - "alerts.contacts.title": "Alert contacts", - "alerts.contacts.subtitle": "External recipients and role targeting.", - "alerts.contacts.name": "Name", - "alerts.contacts.roleScope": "Role scope", - "alerts.contacts.email": "Email", - "alerts.contacts.phone": "Phone", - "alerts.contacts.eventTypes": "Event types (optional)", - "alerts.contacts.eventTypesPlaceholder": "macrostop, microstop, offline", - "alerts.contacts.eventTypesHelper": "Leave empty to receive all event types.", - "alerts.contacts.add": "Add contact", - "alerts.contacts.creating": "Adding...", - "alerts.contacts.empty": "No alert contacts yet.", - "alerts.contacts.save": "Save", - "alerts.contacts.saving": "Saving...", - "alerts.contacts.delete": "Delete", - "alerts.contacts.deleting": "Deleting...", - "alerts.contacts.active": "Active", - "alerts.contacts.linkedUser": "Linked user (edit in profile)", - "alerts.contacts.role.custom": "Custom", - "alerts.contacts.role.member": "Member", - "alerts.contacts.role.admin": "Admin", - "alerts.contacts.role.owner": "Owner", - "alerts.contacts.readOnly": "You can view contacts, but only owners can add or edit.", - "alerts.inbox.title": "Alerts Inbox", - "alerts.inbox.loading": "Loading alerts...", - "alerts.inbox.loadingFilters": "Loading filters...", - "alerts.inbox.empty": "No alerts found.", - "alerts.inbox.error": "Failed to load alerts.", - "alerts.inbox.range.24h": "Last 24 hours", - "alerts.inbox.range.7d": "Last 7 days", - "alerts.inbox.range.30d": "Last 30 days", - "alerts.inbox.range.custom": "Custom", - "alerts.inbox.filters.title": "Filters", - "alerts.inbox.filters.range": "Range", - "alerts.inbox.filters.start": "Start", - "alerts.inbox.filters.end": "End", - "alerts.inbox.filters.machine": "Machine", - "alerts.inbox.filters.site": "Site", - "alerts.inbox.filters.shift": "Shift", - "alerts.inbox.filters.type": "Classification", - "alerts.inbox.filters.severity": "Severity", - "alerts.inbox.filters.status": "Status", - "alerts.inbox.filters.search": "Search", - "alerts.inbox.filters.searchPlaceholder": "Title, description, machine...", - "alerts.inbox.filters.includeUpdates": "Include updates", - "alerts.inbox.filters.allMachines": "All machines", - "alerts.inbox.filters.allSites": "All sites", - "alerts.inbox.filters.allShifts": "All shifts", - "alerts.inbox.filters.allTypes": "All types", - "alerts.inbox.filters.allSeverities": "All severities", - "alerts.inbox.filters.allStatuses": "All statuses", - "alerts.inbox.table.time": "Time", - "alerts.inbox.table.machine": "Machine", - "alerts.inbox.table.site": "Site", - "alerts.inbox.table.shift": "Shift", - "alerts.inbox.table.type": "Type", - "alerts.inbox.table.severity": "Severity", - "alerts.inbox.table.status": "Status", - "alerts.inbox.table.duration": "Duration", - "alerts.inbox.table.title": "Title", - "alerts.inbox.table.unknown": "Unknown", - "alerts.inbox.status.active": "Active", - "alerts.inbox.status.resolved": "Resolved", - "alerts.inbox.status.unknown": "Unknown", - "alerts.inbox.duration.na": "n/a", - "alerts.inbox.duration.sec": "s", - "alerts.inbox.duration.min": " min", - "alerts.inbox.duration.hr": " h", - "alerts.inbox.meta.workOrder": "WO", - "alerts.inbox.meta.sku": "SKU", - "reports.notes.suggested": "Suggested actions", - "reports.notes.none": "No insights yet. Generate reports after data collection.", - "reports.noTrend": "No trend data yet.", - "reports.noDowntime": "No downtime data yet.", - "reports.noCycle": "No cycle data yet.", - "reports.scrapRate": "Scrap Rate", - "reports.topScrapSku": "Top Scrap SKU", - "reports.topScrapWorkOrder": "Top Scrap Work Order", - "reports.loss.macrostop": "Macrostop", - "reports.loss.microstop": "Microstop", - "reports.loss.slowCycle": "Slow Cycle", - "reports.loss.qualitySpike": "Quality Spike", - "reports.loss.oeeDrop": "OEE Drop", - "reports.loss.perfDegradation": "Perf Degradation", - "reports.tooltip.cycles": "Cycles", - "reports.tooltip.range": "Range", - "reports.tooltip.below": "Below", - "reports.tooltip.above": "Above", - "reports.tooltip.extremes": "Extremes", - "reports.tooltip.downtime": "Downtime", - "reports.tooltip.extraTime": "Extra time", - "reports.csv.section": "section", - "reports.csv.key": "key", - "reports.csv.value": "value", - "reports.pdf.title": "Report Export", - "reports.pdf.range": "Range", - "reports.pdf.machine": "Machine", - "reports.pdf.workOrder": "Work Order", - "reports.pdf.sku": "SKU", - "reports.pdf.metric": "Metric", - "reports.pdf.value": "Value", - "reports.pdf.topLoss": "Top Loss Drivers", - "reports.pdf.qualitySummary": "Quality Summary", - "reports.pdf.cycleDistribution": "Cycle Time Distribution", - "reports.pdf.notes": "Notes for Ops", - "reports.pdf.none": "None", - "settings.title": "Settings", - "settings.subtitle": "Live configuration for shifts, alerts, and defaults.", - "settings.tabs.general": "General", - "settings.tabs.shifts": "Shifts", - "settings.tabs.thresholds": "Thresholds", - "settings.tabs.alerts": "Alerts", - "settings.tabs.financial": "Financial", - "settings.tabs.team": "Team", - "settings.loading": "Loading settings...", - "settings.loadingTeam": "Loading team...", - "settings.refresh": "Refresh", - "settings.save": "Save changes", - "settings.saving": "Saving...", - "settings.saved": "Settings saved", - "settings.failedLoad": "Failed to load settings", - "settings.failedTeam": "Failed to load team", - "settings.failedSave": "Failed to save settings", - "settings.unavailable": "Settings are unavailable.", - "settings.conflict": "Settings changed elsewhere. Refresh and try again.", - "settings.org.title": "Organization", - "settings.org.plantName": "Plant Name", - "settings.org.slug": "Slug", - "settings.org.timeZone": "Time Zone", - "settings.shiftSchedule": "Shift Schedule", - "settings.shiftSubtitle": "Define active shifts and downtime compensation.", - "settings.shiftName": "Shift name", - "settings.shiftStart": "Start", - "settings.shiftEnd": "End", - "settings.shiftEnabled": "Enabled", - "settings.shiftAdd": "Add shift", - "settings.shiftRemove": "Remove", - "settings.shiftComp": "Shift change compensation", - "settings.lunchBreak": "Lunch break", - "settings.minutes": "minutes", - "settings.shiftHint": "Max 3 shifts, HH:mm", - "settings.shiftTo": "to", + "machine.detail.currentWorkOrder": "Current Work Order", + "machine.detail.recentEvents": "Critical Events", + "machine.detail.noEvents": "No events yet.", + "machine.detail.cycleTarget": "Cycle target", + "machine.detail.mini.events": "Detected Events", + "machine.detail.mini.events.subtitle": "Canonical events (all)", + "machine.detail.mini.deviation": "Actual vs Standard Cycle", + "machine.detail.mini.deviation.subtitle": "Average deviation", + "machine.detail.mini.impact": "Production Impact", + "machine.detail.mini.impact.subtitle": "Extra time vs ideal", + "machine.detail.modal.events": "Detected Events", + "machine.detail.modal.deviation": "Actual vs Standard Cycle", + "machine.detail.modal.impact": "Production Impact", + "machine.detail.modal.standardCycle": "Standard cycle (ideal)", + "machine.detail.modal.avgDeviation": "Average deviation", + "machine.detail.modal.sample": "Sample", + "machine.detail.modal.cycles": "cycles", + "machine.detail.modal.tip": "Tip: the faint line is the ideal. Each point is a real cycle.", + "machine.detail.modal.totalExtra": "Total extra time", + "machine.detail.modal.microstops": "Microstops", + "machine.detail.modal.macroStops": "Macro stops", + "machine.detail.modal.extraTimeLabel": "Extra time", + "machine.detail.modal.extraTimeNote": "This is \"lost time\" vs ideal, distributed by event type.", + "reports.title": "Reports", + "reports.subtitle": "Trends, downtime, and quality analytics across machines.", + "reports.exportCsv": "Export CSV", + "reports.exportPdf": "Export PDF", + "reports.filters": "Filters", + "reports.rangeLabel.last24": "Last 24 hours", + "reports.rangeLabel.last7": "Last 7 days", + "reports.rangeLabel.last30": "Last 30 days", + "reports.rangeLabel.custom": "Custom range", + "reports.filter.range": "Range", + "reports.filter.machine": "Machine", + "reports.filter.workOrder": "Work Order", + "reports.filter.sku": "SKU", + "reports.filter.allMachines": "All machines", + "reports.filter.allWorkOrders": "All work orders", + "reports.filter.allSkus": "All SKUs", + "reports.loading": "Loading reports...", + "reports.error.failed": "Failed to load reports", + "reports.error.network": "Network error", + "reports.kpi.note.withData": "Computed from KPI snapshots.", + "reports.kpi.note.noData": "No data in selected range.", + "reports.oeeTrend": "OEE Trend", + "reports.downtimePareto": "Downtime Pareto", + "reports.cycleDistribution": "Cycle Time Distribution", + "reports.scrapTrend": "Scrap Trend", + "reports.topLossDrivers": "Top Loss Drivers", + "reports.qualitySummary": "Quality Summary", + "reports.notes": "Notes for Ops", + "alerts.title": "Alerts", + "alerts.subtitle": "Alert history with filters and drilldowns.", + "alerts.comingSoon": "Alert configuration UI is coming soon.", + "alerts.loading": "Loading alerts...", + "alerts.error.loadPolicy": "Failed to load alert policy.", + "alerts.error.savePolicy": "Failed to save alert policy.", + "alerts.error.loadContacts": "Failed to load alert contacts.", + "alerts.error.saveContacts": "Failed to save alert contact.", + "alerts.error.deleteContact": "Failed to delete alert contact.", + "alerts.error.createContact": "Failed to create alert contact.", + "alerts.policy.title": "Alert policy", + "alerts.policy.subtitle": "Configure escalation by role, channel, and duration.", + "alerts.policy.save": "Save policy", + "alerts.policy.saving": "Saving...", + "alerts.policy.defaults": "Default escalation (per role)", + "alerts.policy.enabled": "Enabled", + "alerts.policy.afterMinutes": "After minutes", + "alerts.policy.channels": "Channels", + "alerts.policy.repeatMinutes": "Repeat (min)", + "alerts.policy.readOnly": "You can view alert policy settings, but only owners can edit.", + "alerts.policy.defaultsHelp": "Defaults apply when a specific event is reset or not customized.", + "alerts.policy.eventSelectLabel": "Event type", + "alerts.policy.eventSelectHelper": "Adjust escalation rules for a single event type.", + "alerts.policy.applyDefaults": "Apply defaults", + "alerts.event.macrostop": "Macrostop", + "alerts.event.microstop": "Microstop", + "alerts.event.slow-cycle": "Slow cycle", + "alerts.event.offline": "Offline", + "alerts.event.error": "Error", + "alerts.contacts.title": "Alert contacts", + "alerts.contacts.subtitle": "External recipients and role targeting.", + "alerts.contacts.name": "Name", + "alerts.contacts.roleScope": "Role scope", + "alerts.contacts.email": "Email", + "alerts.contacts.phone": "Phone", + "alerts.contacts.eventTypes": "Event types (optional)", + "alerts.contacts.eventTypesPlaceholder": "macrostop, microstop, offline", + "alerts.contacts.eventTypesHelper": "Leave empty to receive all event types.", + "alerts.contacts.add": "Add contact", + "alerts.contacts.creating": "Adding...", + "alerts.contacts.empty": "No alert contacts yet.", + "alerts.contacts.save": "Save", + "alerts.contacts.saving": "Saving...", + "alerts.contacts.delete": "Delete", + "alerts.contacts.deleting": "Deleting...", + "alerts.contacts.active": "Active", + "alerts.contacts.linkedUser": "Linked user (edit in profile)", + "alerts.contacts.role.custom": "Custom", + "alerts.contacts.role.member": "Member", + "alerts.contacts.role.admin": "Admin", + "alerts.contacts.role.owner": "Owner", + "alerts.contacts.readOnly": "You can view contacts, but only owners can add or edit.", + "alerts.inbox.title": "Alerts Inbox", + "alerts.inbox.loading": "Loading alerts...", + "alerts.inbox.loadingFilters": "Loading filters...", + "alerts.inbox.empty": "No alerts found.", + "alerts.inbox.error": "Failed to load alerts.", + "alerts.inbox.range.24h": "Last 24 hours", + "alerts.inbox.range.7d": "Last 7 days", + "alerts.inbox.range.30d": "Last 30 days", + "alerts.inbox.range.custom": "Custom", + "alerts.inbox.filters.title": "Filters", + "alerts.inbox.filters.range": "Range", + "alerts.inbox.filters.start": "Start", + "alerts.inbox.filters.end": "End", + "alerts.inbox.filters.machine": "Machine", + "alerts.inbox.filters.site": "Site", + "alerts.inbox.filters.shift": "Shift", + "alerts.inbox.filters.type": "Classification", + "alerts.inbox.filters.severity": "Severity", + "alerts.inbox.filters.status": "Status", + "alerts.inbox.filters.search": "Search", + "alerts.inbox.filters.searchPlaceholder": "Title, description, machine...", + "alerts.inbox.filters.includeUpdates": "Include updates", + "alerts.inbox.filters.allMachines": "All machines", + "alerts.inbox.filters.allSites": "All sites", + "alerts.inbox.filters.allShifts": "All shifts", + "alerts.inbox.filters.allTypes": "All types", + "alerts.inbox.filters.allSeverities": "All severities", + "alerts.inbox.filters.allStatuses": "All statuses", + "alerts.inbox.table.time": "Time", + "alerts.inbox.table.machine": "Machine", + "alerts.inbox.table.site": "Site", + "alerts.inbox.table.shift": "Shift", + "alerts.inbox.table.type": "Type", + "alerts.inbox.table.severity": "Severity", + "alerts.inbox.table.status": "Status", + "alerts.inbox.table.duration": "Duration", + "alerts.inbox.table.title": "Title", + "alerts.inbox.table.unknown": "Unknown", + "alerts.inbox.status.active": "Active", + "alerts.inbox.status.resolved": "Resolved", + "alerts.inbox.status.unknown": "Unknown", + "alerts.inbox.duration.na": "n/a", + "alerts.inbox.duration.sec": "s", + "alerts.inbox.duration.min": " min", + "alerts.inbox.duration.hr": " h", + "alerts.inbox.meta.workOrder": "WO", + "alerts.inbox.meta.sku": "SKU", + "reports.notes.suggested": "Suggested actions", + "reports.notes.none": "No insights yet. Generate reports after data collection.", + "reports.noTrend": "No trend data yet.", + "reports.noDowntime": "No downtime data yet.", + "reports.noCycle": "No cycle data yet.", + "reports.scrapRate": "Scrap Rate", + "reports.topScrapSku": "Top Scrap SKU", + "reports.topScrapWorkOrder": "Top Scrap Work Order", + "reports.loss.macrostop": "Macrostop", + "reports.loss.microstop": "Microstop", + "reports.loss.slowCycle": "Slow Cycle", + "reports.loss.qualitySpike": "Quality Spike", + "reports.loss.oeeDrop": "OEE Drop", + "reports.loss.perfDegradation": "Perf Degradation", + "reports.tooltip.cycles": "Cycles", + "reports.tooltip.range": "Range", + "reports.tooltip.below": "Below", + "reports.tooltip.above": "Above", + "reports.tooltip.extremes": "Extremes", + "reports.tooltip.downtime": "Downtime", + "reports.tooltip.extraTime": "Extra time", + "reports.csv.section": "section", + "reports.csv.key": "key", + "reports.csv.value": "value", + "reports.pdf.title": "Report Export", + "reports.pdf.range": "Range", + "reports.pdf.machine": "Machine", + "reports.pdf.workOrder": "Work Order", + "reports.pdf.sku": "SKU", + "reports.pdf.metric": "Metric", + "reports.pdf.value": "Value", + "reports.pdf.topLoss": "Top Loss Drivers", + "reports.pdf.qualitySummary": "Quality Summary", + "reports.pdf.cycleDistribution": "Cycle Time Distribution", + "reports.pdf.notes": "Notes for Ops", + "reports.pdf.none": "None", + "settings.title": "Settings", + "settings.subtitle": "Live configuration for shifts, alerts, and defaults.", + "settings.tabs.general": "General", + "settings.tabs.shifts": "Shifts", + "settings.tabs.thresholds": "Thresholds", + "settings.tabs.alerts": "Alerts", + "settings.tabs.financial": "Financial", + "settings.tabs.team": "Team", + "settings.loading": "Loading settings...", + "settings.loadingTeam": "Loading team...", + "settings.refresh": "Refresh", + "settings.save": "Save changes", + "settings.saving": "Saving...", + "settings.saved": "Settings saved", + "settings.failedLoad": "Failed to load settings", + "settings.failedTeam": "Failed to load team", + "settings.failedSave": "Failed to save settings", + "settings.unavailable": "Settings are unavailable.", + "settings.conflict": "Settings changed elsewhere. Refresh and try again.", + "settings.org.title": "Organization", + "settings.org.plantName": "Plant Name", + "settings.org.slug": "Slug", + "settings.org.timeZone": "Time Zone", + "settings.shiftSchedule": "Shift Schedule", + "settings.shiftSubtitle": "Define active shifts and downtime compensation.", + "settings.shiftName": "Shift name", + "settings.shiftStart": "Start", + "settings.shiftEnd": "End", + "settings.shiftEnabled": "Enabled", + "settings.shiftAdd": "Add shift", + "settings.shiftRemove": "Remove", + "settings.shiftComp": "Shift change compensation", + "settings.lunchBreak": "Lunch break", + "settings.minutes": "minutes", + "settings.shiftHint": "Max 3 shifts, HH:mm", + "settings.shiftTo": "to", "settings.shiftCompLabel": "Shift change compensation (min)", "settings.lunchBreakLabel": "Lunch break (min)", "settings.shift.defaultName": "Shift {index}", @@ -501,124 +502,124 @@ "settings.shiftOverrides.sat": "Saturday", "settings.shiftOverrides.sun": "Sunday", "settings.thresholds": "Alert thresholds", - "settings.thresholdsSubtitle": "Tune production health alerts.", - "settings.thresholds.appliesAll": "Applies to all machines", - "settings.thresholds.oee": "OEE alert threshold", - "settings.thresholds.performance": "Performance threshold", - "settings.thresholds.qualitySpike": "Quality spike delta", - "settings.thresholds.stoppage": "Stoppage multiplier", - "settings.thresholds.macroStoppage": "Macro stoppage multiplier", - "settings.alerts": "Alerts", - "settings.alertsSubtitle": "Choose which alerts to notify.", - "settings.alerts.oeeDrop": "OEE drop alerts", - "settings.alerts.oeeDropHelper": "Notify when OEE falls below threshold", - "settings.alerts.performanceDegradation": "Performance degradation alerts", - "settings.alerts.performanceDegradationHelper": "Flag prolonged slow cycles", - "settings.alerts.qualitySpike": "Quality spike alerts", - "settings.alerts.qualitySpikeHelper": "Alert on scrap spikes", - "settings.alerts.predictive": "Predictive OEE decline alerts", - "settings.alerts.predictiveHelper": "Warn before OEE drops", - "settings.defaults": "Mold Defaults", - "settings.defaults.moldTotal": "Total molds", - "settings.defaults.moldActive": "Active molds", - "settings.updated": "Updated", - "settings.updatedBy": "Updated by", - "settings.team": "Team Members", - "settings.teamTotal": "{count} total", - "settings.teamNone": "No team members yet.", - "settings.invites": "Invitations", - "settings.inviteEmail": "Invite email", - "settings.inviteRole": "Role", - "settings.inviteSend": "Create invite", - "settings.inviteSending": "Creating...", - "settings.inviteStatus.copied": "Invite link copied", - "settings.inviteStatus.emailRequired": "Email is required", - "settings.inviteStatus.failed": "Failed to revoke invite", - "settings.inviteStatus.sent": "Invite email sent", - "settings.inviteStatus.createFailed": "Failed to create invite", - "settings.inviteStatus.emailFailed": "Invite created, email failed: {url}", - "settings.inviteNone": "No pending invites.", - "settings.inviteExpires": "Expires {date}", - "settings.inviteRole.member": "Member", - "settings.inviteRole.admin": "Admin", - "settings.inviteRole.owner": "Owner", - "settings.inviteCopy": "Copy link", - "settings.inviteRevoke": "Revoke", - "settings.role.owner": "Owner", - "settings.role.admin": "Admin", - "settings.role.member": "Member", - "settings.role.inactive": "Inactive", - "settings.integrations": "Integrations", - "settings.integrations.webhook": "Webhook URL", - "settings.integrations.erp": "ERP Sync", - "settings.integrations.erpNotConfigured": "Not configured", - "financial.title": "Financial Impact", - "financial.subtitle": "Translate downtime, slow cycles, and scrap into money.", - "financial.ownerOnly": "Financial impact is available only to owners.", + "settings.thresholdsSubtitle": "Tune production health alerts.", + "settings.thresholds.appliesAll": "Applies to all machines", + "settings.thresholds.oee": "OEE alert threshold", + "settings.thresholds.performance": "Performance threshold", + "settings.thresholds.qualitySpike": "Quality spike delta", + "settings.thresholds.stoppage": "Stoppage multiplier", + "settings.thresholds.macroStoppage": "Macro stoppage multiplier", + "settings.alerts": "Alerts", + "settings.alertsSubtitle": "Choose which alerts to notify.", + "settings.alerts.oeeDrop": "OEE drop alerts", + "settings.alerts.oeeDropHelper": "Notify when OEE falls below threshold", + "settings.alerts.performanceDegradation": "Performance degradation alerts", + "settings.alerts.performanceDegradationHelper": "Flag prolonged slow cycles", + "settings.alerts.qualitySpike": "Quality spike alerts", + "settings.alerts.qualitySpikeHelper": "Alert on scrap spikes", + "settings.alerts.predictive": "Predictive OEE decline alerts", + "settings.alerts.predictiveHelper": "Warn before OEE drops", + "settings.defaults": "Mold Defaults", + "settings.defaults.moldTotal": "Total molds", + "settings.defaults.moldActive": "Active molds", + "settings.updated": "Updated", + "settings.updatedBy": "Updated by", + "settings.team": "Team Members", + "settings.teamTotal": "{count} total", + "settings.teamNone": "No team members yet.", + "settings.invites": "Invitations", + "settings.inviteEmail": "Invite email", + "settings.inviteRole": "Role", + "settings.inviteSend": "Create invite", + "settings.inviteSending": "Creating...", + "settings.inviteStatus.copied": "Invite link copied", + "settings.inviteStatus.emailRequired": "Email is required", + "settings.inviteStatus.failed": "Failed to revoke invite", + "settings.inviteStatus.sent": "Invite email sent", + "settings.inviteStatus.createFailed": "Failed to create invite", + "settings.inviteStatus.emailFailed": "Invite created, email failed: {url}", + "settings.inviteNone": "No pending invites.", + "settings.inviteExpires": "Expires {date}", + "settings.inviteRole.member": "Member", + "settings.inviteRole.admin": "Admin", + "settings.inviteRole.owner": "Owner", + "settings.inviteCopy": "Copy link", + "settings.inviteRevoke": "Revoke", + "settings.role.owner": "Owner", + "settings.role.admin": "Admin", + "settings.role.member": "Member", + "settings.role.inactive": "Inactive", + "settings.integrations": "Integrations", + "settings.integrations.webhook": "Webhook URL", + "settings.integrations.erp": "ERP Sync", + "settings.integrations.erpNotConfigured": "Not configured", + "financial.title": "Financial Impact", + "financial.subtitle": "Translate downtime, slow cycles, and scrap into money.", + "financial.ownerOnly": "Financial impact is available only to owners.", "financial.costsMoved": "Cost settings are now in", "financial.costsMovedLink": "Settings -> Financial", "financial.export.html": "HTML", "financial.export.csv": "CSV", "financial.refresh": "Refresh", "financial.totalLoss": "Total Loss", - "financial.currencyLabel": "Currency: {currency}", - "financial.noImpact": "No impact data yet.", - "financial.chart.title": "Lost Money Over Time", - "financial.chart.subtitle": "Stacked by event type", - "financial.range.day": "Day", - "financial.range.week": "Week", - "financial.range.month": "Month", - "financial.filters.title": "Filters", - "financial.filters.machine": "Machine", - "financial.filters.location": "Location", - "financial.filters.sku": "SKU", - "financial.filters.currency": "Currency", - "financial.filters.allMachines": "All machines", - "financial.filters.allLocations": "All locations", - "financial.filters.skuPlaceholder": "Filter by SKU", - "financial.filters.currencyPlaceholder": "MXN", - "financial.loadingMachines": "Loading machines...", - "financial.config.title": "Cost Parameters", - "financial.config.subtitle": "Defaults apply to all machines unless overridden.", - "financial.config.applyOrg": "Apply org defaults to all machines", - "financial.config.save": "Save", - "financial.config.saving": "Saving...", - "financial.config.saved": "Saved", - "financial.config.saveFailed": "Save failed", - "financial.config.orgDefaults": "Org Defaults", - "financial.config.locationOverrides": "Location Overrides", - "financial.config.machineOverrides": "Machine Overrides", - "financial.config.productOverrides": "Product Overrides", - "financial.config.addLocation": "Add location override", - "financial.config.addMachine": "Add machine override", - "financial.config.addProduct": "Add product override", - "financial.config.noneLocation": "No location overrides yet.", - "financial.config.noneMachine": "No machine overrides yet.", - "financial.config.noneProduct": "No product overrides yet.", - "financial.config.location": "Location", - "financial.config.selectLocation": "Select location", - "financial.config.machine": "Machine", - "financial.config.selectMachine": "Select machine", - "financial.config.currency": "Currency", - "financial.config.sku": "SKU", - "financial.config.rawMaterialUnit": "Raw material / unit", - "financial.config.ownerOnly": "Financial cost settings are available only to owners.", - "financial.config.loading": "Loading financials...", - "financial.field.machineCostPerMin": "Machine cost / min", - "financial.field.operatorCostPerMin": "Operator cost / min", - "financial.field.ratedRunningKw": "Running kW", - "financial.field.idleKw": "Idle kW", - "financial.field.kwhRate": "kWh rate", - "financial.field.energyMultiplier": "Energy multiplier", + "financial.currencyLabel": "Currency: {currency}", + "financial.noImpact": "No impact data yet.", + "financial.chart.title": "Lost Money Over Time", + "financial.chart.subtitle": "Stacked by event type", + "financial.range.day": "Day", + "financial.range.week": "Week", + "financial.range.month": "Month", + "financial.filters.title": "Filters", + "financial.filters.machine": "Machine", + "financial.filters.location": "Location", + "financial.filters.sku": "SKU", + "financial.filters.currency": "Currency", + "financial.filters.allMachines": "All machines", + "financial.filters.allLocations": "All locations", + "financial.filters.skuPlaceholder": "Filter by SKU", + "financial.filters.currencyPlaceholder": "MXN", + "financial.loadingMachines": "Loading machines...", + "financial.config.title": "Cost Parameters", + "financial.config.subtitle": "Defaults apply to all machines unless overridden.", + "financial.config.applyOrg": "Apply org defaults to all machines", + "financial.config.save": "Save", + "financial.config.saving": "Saving...", + "financial.config.saved": "Saved", + "financial.config.saveFailed": "Save failed", + "financial.config.orgDefaults": "Org Defaults", + "financial.config.locationOverrides": "Location Overrides", + "financial.config.machineOverrides": "Machine Overrides", + "financial.config.productOverrides": "Product Overrides", + "financial.config.addLocation": "Add location override", + "financial.config.addMachine": "Add machine override", + "financial.config.addProduct": "Add product override", + "financial.config.noneLocation": "No location overrides yet.", + "financial.config.noneMachine": "No machine overrides yet.", + "financial.config.noneProduct": "No product overrides yet.", + "financial.config.location": "Location", + "financial.config.selectLocation": "Select location", + "financial.config.machine": "Machine", + "financial.config.selectMachine": "Select machine", + "financial.config.currency": "Currency", + "financial.config.sku": "SKU", + "financial.config.rawMaterialUnit": "Raw material / unit", + "financial.config.ownerOnly": "Financial cost settings are available only to owners.", + "financial.config.loading": "Loading financials...", + "financial.field.machineCostPerMin": "Machine cost / min", + "financial.field.operatorCostPerMin": "Operator cost / min", + "financial.field.ratedRunningKw": "Running kW", + "financial.field.idleKw": "Idle kW", + "financial.field.kwhRate": "kWh rate", + "financial.field.energyMultiplier": "Energy multiplier", "financial.field.energyCostPerMin": "Energy cost / min", "financial.field.scrapCostPerUnit": "Scrap cost / unit", "financial.field.rawMaterialCostPerUnit": "Raw material / unit", "nav.downtime": "Downtime", "nav.recap": "Daily recap", "settings.tabs.modules": "Modules", - "settings.modules.title": "Modules", - "settings.modules.subtitle": "Enable/disable UI modules depending on how the plant operates.", - "settings.modules.screenless.title": "Screenless mode", - "settings.modules.screenless.helper": "Hide the Downtime module from navigation (for plants without Node-RED reason capture).", - "settings.modules.note": "This setting is org-wide." -} + "settings.modules.title": "Modules", + "settings.modules.subtitle": "Enable/disable UI modules depending on how the plant operates.", + "settings.modules.screenless.title": "Screenless mode", + "settings.modules.screenless.helper": "Hide the Downtime module from navigation (for plants without Node-RED reason capture).", + "settings.modules.note": "This setting is org-wide." +} diff --git a/lib/i18n/es-MX.json b/lib/i18n/es-MX.json index bfe078a..695f5da 100644 --- a/lib/i18n/es-MX.json +++ b/lib/i18n/es-MX.json @@ -1,106 +1,106 @@ -{ - "---": "---", - "common.loading": "Cargando...", - "common.loadingShort": "Cargando", - "common.never": "nunca", - "common.na": "--", - "common.back": "Volver", - "common.cancel": "Cancelar", +{ + "---": "---", + "common.loading": "Cargando...", + "common.loadingShort": "Cargando", + "common.never": "nunca", + "common.na": "--", + "common.back": "Volver", + "common.cancel": "Cancelar", "common.close": "Cerrar", "common.save": "Guardar", "common.copy": "Copiar", "common.yes": "Sí", "common.no": "No", - "nav.overview": "Resumen", - "nav.machines": "Máquinas", - "nav.reports": "Reportes", - "nav.alerts": "Alertas", - "nav.financial": "Finanzas", - "nav.settings": "Configuración", - "sidebar.productTitle": "MIS", - "sidebar.productSubtitle": "Control Tower", - "sidebar.userFallback": "Usuario", - "sidebar.loadingOrg": "Cargando...", - "sidebar.themeTooltip": "Tema e idioma", - "sidebar.switchToDark": "Cambiar a modo oscuro", - "sidebar.switchToLight": "Cambiar a modo claro", - "sidebar.logout": "Cerrar sesión", - "sidebar.role.member": "MIEMBRO", - "sidebar.role.admin": "ADMIN", - "sidebar.role.owner": "PROPIETARIO", - "login.title": "Control Tower", - "login.subtitle": "Inicia sesión en tu organización", - "login.email": "Correo electrónico", - "login.password": "Contraseña", - "login.error.default": "Inicio de sesión fallido", - "login.error.network": "Error de red", - "login.submit.loading": "Iniciando sesión...", - "login.submit.default": "Iniciar sesión", - "login.newHere": "¿Nuevo aquí?", - "login.createAccount": "Crear cuenta", - "signup.verify.title": "Verifica tu correo", - "signup.verify.sent": "Enviamos un enlace de verificación a {email}.", - "signup.verify.failed": "No se pudo enviar el correo de verificación. Contacta a soporte.", - "signup.verify.notice": "Después de verificar, puedes iniciar sesión e invitar a tu equipo.", - "signup.verify.back": "Volver al inicio de sesión", - "signup.title": "Crea tu Control Tower", - "signup.subtitle": "Configura tu organización e invita al equipo.", - "signup.orgName": "Nombre de la organización", - "signup.yourName": "Tu nombre", - "signup.email": "Correo electrónico", - "signup.password": "Contraseña", - "signup.error.default": "Registro fallido", - "signup.error.network": "Error de red", - "signup.submit.loading": "Creando cuenta...", - "signup.submit.default": "Crear cuenta", - "signup.alreadyHave": "¿Ya tienes acceso?", - "signup.signIn": "Iniciar sesión", - "invite.loading": "Cargando invitación...", - "invite.notFound": "Invitación no encontrada.", - "invite.joinTitle": "Únete a {org}", - "invite.acceptCopy": "Acepta la invitación para {email} como {role}.", - "invite.yourName": "Tu nombre", - "invite.password": "Contraseña", - "invite.error.notFound": "Invitación no encontrada", - "invite.error.acceptFailed": "No se pudo aceptar la invitación", - "invite.submit.loading": "Uniéndote...", - "invite.submit.default": "Unirse a la organización", - "overview.title": "Resumen", - "overview.subtitle": "Pulso de flota, alertas y elementos prioritarios.", - "overview.viewMachines": "Ver Máquinas", - "overview.loading": "Cargando resumen...", - "overview.fleetHealth": "Salud de flota", - "overview.machinesTotal": "Máquinas totales", - "overview.online": "En línea", - "overview.offline": "Fuera de línea", - "overview.run": "En marcha", - "overview.idle": "En espera", - "overview.stop": "Paro", - "overview.productionTotals": "Totales de producción", - "overview.good": "Buenas", - "overview.scrap": "Scrap", - "overview.target": "Meta", - "overview.kpiSumNote": "Suma de los últimos KPIs por máquina.", - "overview.activityFeed": "Actividad", - "overview.eventsRefreshing": "Actualizando eventos recientes...", - "overview.eventsLast30": "Últimos 30 eventos combinados", - "overview.eventsNone": "Sin eventos recientes.", - "overview.oeeAvg": "OEE (avg)", - "overview.availabilityAvg": "Availability (avg)", - "overview.performanceAvg": "Performance (avg)", - "overview.qualityAvg": "Quality (avg)", - "overview.attentionList": "Lista de atención", - "overview.shown": "mostrados", - "overview.noUrgent": "No se detectaron problemas urgentes.", - "overview.timeline": "Línea de tiempo unificada", - "overview.items": "elementos", - "overview.noEvents": "Sin eventos aún.", - "overview.ack": "ACK", - "overview.severity.critical": "CRÍTICO", - "overview.severity.warning": "ADVERTENCIA", - "overview.severity.info": "INFO", - "overview.source.ingested": "ingestado", - "overview.source.derived": "derivado", + "nav.overview": "Resumen", + "nav.machines": "Máquinas", + "nav.reports": "Reportes", + "nav.alerts": "Alertas", + "nav.financial": "Finanzas", + "nav.settings": "Configuración", + "sidebar.productTitle": "MIS", + "sidebar.productSubtitle": "Control Tower", + "sidebar.userFallback": "Usuario", + "sidebar.loadingOrg": "Cargando...", + "sidebar.themeTooltip": "Tema e idioma", + "sidebar.switchToDark": "Cambiar a modo oscuro", + "sidebar.switchToLight": "Cambiar a modo claro", + "sidebar.logout": "Cerrar sesión", + "sidebar.role.member": "MIEMBRO", + "sidebar.role.admin": "ADMIN", + "sidebar.role.owner": "PROPIETARIO", + "login.title": "Control Tower", + "login.subtitle": "Inicia sesión en tu organización", + "login.email": "Correo electrónico", + "login.password": "Contraseña", + "login.error.default": "Inicio de sesión fallido", + "login.error.network": "Error de red", + "login.submit.loading": "Iniciando sesión...", + "login.submit.default": "Iniciar sesión", + "login.newHere": "¿Nuevo aquí?", + "login.createAccount": "Crear cuenta", + "signup.verify.title": "Verifica tu correo", + "signup.verify.sent": "Enviamos un enlace de verificación a {email}.", + "signup.verify.failed": "No se pudo enviar el correo de verificación. Contacta a soporte.", + "signup.verify.notice": "Después de verificar, puedes iniciar sesión e invitar a tu equipo.", + "signup.verify.back": "Volver al inicio de sesión", + "signup.title": "Crea tu Control Tower", + "signup.subtitle": "Configura tu organización e invita al equipo.", + "signup.orgName": "Nombre de la organización", + "signup.yourName": "Tu nombre", + "signup.email": "Correo electrónico", + "signup.password": "Contraseña", + "signup.error.default": "Registro fallido", + "signup.error.network": "Error de red", + "signup.submit.loading": "Creando cuenta...", + "signup.submit.default": "Crear cuenta", + "signup.alreadyHave": "¿Ya tienes acceso?", + "signup.signIn": "Iniciar sesión", + "invite.loading": "Cargando invitación...", + "invite.notFound": "Invitación no encontrada.", + "invite.joinTitle": "Únete a {org}", + "invite.acceptCopy": "Acepta la invitación para {email} como {role}.", + "invite.yourName": "Tu nombre", + "invite.password": "Contraseña", + "invite.error.notFound": "Invitación no encontrada", + "invite.error.acceptFailed": "No se pudo aceptar la invitación", + "invite.submit.loading": "Uniéndote...", + "invite.submit.default": "Unirse a la organización", + "overview.title": "Resumen", + "overview.subtitle": "Pulso de flota, alertas y elementos prioritarios.", + "overview.viewMachines": "Ver Máquinas", + "overview.loading": "Cargando resumen...", + "overview.fleetHealth": "Salud de flota", + "overview.machinesTotal": "Máquinas totales", + "overview.online": "En línea", + "overview.offline": "Fuera de línea", + "overview.run": "En marcha", + "overview.idle": "En espera", + "overview.stop": "Paro", + "overview.productionTotals": "Totales de producción", + "overview.good": "Buenas", + "overview.scrap": "Scrap", + "overview.target": "Meta", + "overview.kpiSumNote": "Suma de los últimos KPIs por máquina.", + "overview.activityFeed": "Actividad", + "overview.eventsRefreshing": "Actualizando eventos recientes...", + "overview.eventsLast30": "Últimos 30 eventos combinados", + "overview.eventsNone": "Sin eventos recientes.", + "overview.oeeAvg": "OEE (avg)", + "overview.availabilityAvg": "Availability (avg)", + "overview.performanceAvg": "Performance (avg)", + "overview.qualityAvg": "Quality (avg)", + "overview.attentionList": "Lista de atención", + "overview.shown": "mostrados", + "overview.noUrgent": "No se detectaron problemas urgentes.", + "overview.timeline": "Línea de tiempo unificada", + "overview.items": "elementos", + "overview.noEvents": "Sin eventos aún.", + "overview.ack": "ACK", + "overview.severity.critical": "CRÍTICO", + "overview.severity.warning": "ADVERTENCIA", + "overview.severity.info": "INFO", + "overview.source.ingested": "ingestado", + "overview.source.derived": "derivado", "overview.event.macrostop": "macroparo", "overview.event.microstop": "microparo", "overview.event.slow-cycle": "ciclo lento", @@ -192,15 +192,15 @@ "recap.timeline.type.idle": "Idle", "recap.empty.production": "Sin producción registrada", "machines.title": "Máquinas", - "machines.subtitle": "Selecciona una máquina para ver KPIs en vivo.", - "machines.cancel": "Cancelar", - "machines.addMachine": "Agregar máquina", - "machines.backOverview": "Volver al Resumen", - "machines.addCardTitle": "Agregar máquina", - "machines.addCardSubtitle": "Genera el ID de máquina y la API key para tu edge Node-RED.", - "machines.field.name": "Nombre de la máquina", - "machines.field.code": "Código (opcional)", - "machines.field.location": "Ubicación (opcional)", + "machines.subtitle": "Selecciona una máquina para ver KPIs en vivo.", + "machines.cancel": "Cancelar", + "machines.addMachine": "Agregar máquina", + "machines.backOverview": "Volver al Resumen", + "machines.addCardTitle": "Agregar máquina", + "machines.addCardSubtitle": "Genera el ID de máquina y la API key para tu edge Node-RED.", + "machines.field.name": "Nombre de la máquina", + "machines.field.code": "Código (opcional)", + "machines.field.location": "Ubicación (opcional)", "machines.create.loading": "Creando...", "machines.create.default": "Crear máquina", "machines.create.error.nameRequired": "El nombre de la máquina es obligatorio", @@ -210,279 +210,280 @@ "machines.delete.confirm": "¿Eliminar {name}? Esto borrará la máquina y sus datos.", "machines.delete.error.failed": "No se pudo eliminar la máquina", "machines.pairing.title": "Código de emparejamiento", - "machines.pairing.machine": "Máquina:", - "machines.pairing.codeLabel": "Código de emparejamiento", - "machines.pairing.expires": "Expira", - "machines.pairing.soon": "pronto", - "machines.pairing.instructions": "Ingresa este código en la pantalla de configuración de Node-RED Control Tower para vincular el dispositivo.", - "machines.pairing.copy": "Copiar código", - "machines.pairing.copied": "Copiado", - "machines.pairing.copyUnsupported": "Copiar no disponible", - "machines.pairing.copyFailed": "Falló la copia", - "machines.loading": "Cargando máquinas...", - "machines.empty": "No se encontraron máquinas para esta organización.", - "machines.status": "Estado", - "machines.status.noHeartbeat": "Sin heartbeat", - "machines.status.ok": "Latido", - "machines.status.offline": "FUERA DE LÍNEA", - "machines.status.unknown": "DESCONOCIDO", - "machines.lastSeen": "Visto hace {time}", - "machine.detail.titleFallback": "Máquina", - "machine.detail.lastSeen": "Visto hace {time}", - "machine.detail.loading": "Cargando...", - "machine.detail.error.failed": "No se pudo cargar la máquina", - "machine.detail.error.network": "Error de red", - "machine.detail.back": "Volver", - "machine.detail.workOrders.upload": "Subir ordenes de trabajo", - "machine.detail.workOrders.uploading": "Subiendo...", - "machine.detail.workOrders.uploadParsing": "Leyendo archivo...", - "machine.detail.workOrders.uploadHint": "CSV o XLSX con Work Order ID, SKU, Theoretical Cycle Time (Seconds), Target Quantity.", - "machine.detail.workOrders.uploadSuccess": "Se cargaron {count} ordenes de trabajo", - "machine.detail.workOrders.uploadError": "No se pudo cargar", - "machine.detail.workOrders.uploadInvalid": "No se encontraron ordenes de trabajo validas", - "machine.detail.workOrders.uploadUnauthorized": "No autorizado para cargar ordenes de trabajo", - "machine.detail.status.offline": "FUERA DE LÍNEA", - "machine.detail.status.unknown": "DESCONOCIDO", - "machine.detail.status.run": "EN MARCHA", - "machine.detail.status.idle": "EN ESPERA", - "machine.detail.status.stop": "PARO", - "machine.detail.status.down": "CAÍDA", - "machine.detail.bucket.normal": "Ciclo normal", - "machine.detail.bucket.slow": "Ciclo lento", - "machine.detail.bucket.microstop": "Microparo", - "machine.detail.bucket.macrostop": "Macroparo", - "machine.detail.bucket.unknown": "Desconocido", - "machine.detail.activity.title": "Línea de tiempo de actividad", - "machine.detail.activity.subtitle": "Análisis en tiempo real de ciclos de producción", - "machine.detail.activity.noData": "Sin datos de línea de tiempo.", - "machine.detail.tooltip.cycle": "Ciclo: {label}", - "machine.detail.tooltip.duration": "Duración", - "machine.detail.tooltip.ideal": "Ideal", - "machine.detail.tooltip.deviation": "Desviación", + "machines.pairing.machine": "Máquina:", + "machines.pairing.codeLabel": "Código de emparejamiento", + "machines.pairing.expires": "Expira", + "machines.pairing.soon": "pronto", + "machines.pairing.instructions": "Ingresa este código en la pantalla de configuración de Node-RED Control Tower para vincular el dispositivo.", + "machines.pairing.copy": "Copiar código", + "machines.pairing.copied": "Copiado", + "machines.pairing.copyUnsupported": "Copiar no disponible", + "machines.pairing.copyFailed": "Falló la copia", + "machines.loading": "Cargando máquinas...", + "machines.empty": "No se encontraron máquinas para esta organización.", + "machines.status": "Estado", + "machines.status.noHeartbeat": "Sin heartbeat", + "machines.status.ok": "Latido", + "machines.status.offline": "FUERA DE LÍNEA", + "machines.status.unknown": "DESCONOCIDO", + "machines.lastSeen": "Visto hace {time}", + "machine.detail.titleFallback": "Máquina", + "machine.detail.lastSeen": "Visto hace {time}", + "machine.detail.loading": "Cargando...", + "machine.detail.error.failed": "No se pudo cargar la máquina", + "machine.detail.error.network": "Error de red", + "machine.detail.back": "Volver", + "machine.detail.workOrders.upload": "Subir ordenes de trabajo", + "machine.detail.workOrders.downloadTemplate": "Descargar plantilla", + "machine.detail.workOrders.uploading": "Subiendo...", + "machine.detail.workOrders.uploadParsing": "Leyendo archivo...", + "machine.detail.workOrders.uploadHint": "CSV o XLSX: Work Order ID, SKU, Theoretical Cycle Time (Seconds), Target Quantity, Molde, Total de cavidades, Cavidades activas (los primeros cuatro campos bastan para archivos antiguos).", + "machine.detail.workOrders.uploadSuccess": "Se cargaron {count} ordenes de trabajo", + "machine.detail.workOrders.uploadError": "No se pudo cargar", + "machine.detail.workOrders.uploadInvalid": "No se encontraron ordenes de trabajo validas", + "machine.detail.workOrders.uploadUnauthorized": "No autorizado para cargar ordenes de trabajo", + "machine.detail.status.offline": "FUERA DE LÍNEA", + "machine.detail.status.unknown": "DESCONOCIDO", + "machine.detail.status.run": "EN MARCHA", + "machine.detail.status.idle": "EN ESPERA", + "machine.detail.status.stop": "PARO", + "machine.detail.status.down": "CAÍDA", + "machine.detail.bucket.normal": "Ciclo normal", + "machine.detail.bucket.slow": "Ciclo lento", + "machine.detail.bucket.microstop": "Microparo", + "machine.detail.bucket.macrostop": "Macroparo", + "machine.detail.bucket.unknown": "Desconocido", + "machine.detail.activity.title": "Línea de tiempo de actividad", + "machine.detail.activity.subtitle": "Análisis en tiempo real de ciclos de producción", + "machine.detail.activity.noData": "Sin datos de línea de tiempo.", + "machine.detail.tooltip.cycle": "Ciclo: {label}", + "machine.detail.tooltip.duration": "Duración", + "machine.detail.tooltip.ideal": "Ideal", + "machine.detail.tooltip.deviation": "Desviación", "machine.detail.kpi.oeeCurrent": "OEE actual", "machine.detail.kpi.updated": "Actualizado {time}", - "machine.detail.currentWorkOrder": "Orden de trabajo actual", - "machine.detail.recentEvents": "Eventos críticos", - "machine.detail.noEvents": "Sin eventos aún.", - "machine.detail.cycleTarget": "Ciclo objetivo", - "machine.detail.mini.events": "Eventos detectados", - "machine.detail.mini.events.subtitle": "Eventos canónicos (todos)", - "machine.detail.mini.deviation": "Ciclo real vs estándar", - "machine.detail.mini.deviation.subtitle": "Desviación promedio", - "machine.detail.mini.impact": "Impacto en producción", - "machine.detail.mini.impact.subtitle": "Tiempo extra vs ideal", - "machine.detail.modal.events": "Eventos detectados", - "machine.detail.modal.deviation": "Ciclo real vs estándar", - "machine.detail.modal.impact": "Impacto en producción", - "machine.detail.modal.standardCycle": "Ciclo estándar (ideal)", - "machine.detail.modal.avgDeviation": "Desviación promedio", - "machine.detail.modal.sample": "Muestra", - "machine.detail.modal.cycles": "ciclos", - "machine.detail.modal.tip": "Tip: la línea tenue es el ideal. Cada punto es un ciclo real.", - "machine.detail.modal.totalExtra": "Tiempo extra total", - "machine.detail.modal.microstops": "Microparos", - "machine.detail.modal.macroStops": "Macroparos", - "machine.detail.modal.extraTimeLabel": "Tiempo extra", - "machine.detail.modal.extraTimeNote": "Esto es \"tiempo perdido\" vs ideal, distribuido por tipo de evento.", - "reports.title": "Reportes", - "reports.subtitle": "Tendencias, paros y analítica de calidad por máquina.", - "reports.exportCsv": "Exportar CSV", - "reports.exportPdf": "Exportar PDF", - "reports.filters": "Filtros", - "reports.rangeLabel.last24": "Últimas 24 horas", - "reports.rangeLabel.last7": "Últimos 7 días", - "reports.rangeLabel.last30": "Últimos 30 días", - "reports.rangeLabel.custom": "Rango personalizado", - "reports.filter.range": "Rango", - "reports.filter.machine": "Máquina", - "reports.filter.workOrder": "Orden de trabajo", - "reports.filter.sku": "SKU", - "reports.filter.allMachines": "Todas las máquinas", - "reports.filter.allWorkOrders": "Todas las órdenes", - "reports.filter.allSkus": "Todos los SKUs", - "reports.loading": "Cargando reportes...", - "reports.error.failed": "No se pudieron cargar los reportes", - "reports.error.network": "Error de red", - "reports.kpi.note.withData": "Calculado a partir de KPIs.", - "reports.kpi.note.noData": "Sin datos en el rango seleccionado.", - "reports.oeeTrend": "Tendencia de OEE", - "reports.downtimePareto": "Pareto de paros", - "reports.cycleDistribution": "Distribución de tiempos de ciclo", - "reports.scrapTrend": "Tendencia de scrap", - "reports.topLossDrivers": "Principales causas de pérdida", - "reports.qualitySummary": "Resumen de calidad", - "reports.notes": "Notas para operaciones", - "alerts.title": "Alertas", - "alerts.subtitle": "Historial de alertas con filtros y detalle.", - "alerts.comingSoon": "La configuracion de alertas estara disponible pronto.", - "alerts.loading": "Cargando alertas...", - "alerts.error.loadPolicy": "No se pudo cargar la politica de alertas.", - "alerts.error.savePolicy": "No se pudo guardar la politica de alertas.", - "alerts.error.loadContacts": "No se pudieron cargar los contactos de alertas.", - "alerts.error.saveContacts": "No se pudo guardar el contacto de alertas.", - "alerts.error.deleteContact": "No se pudo eliminar el contacto de alertas.", - "alerts.error.createContact": "No se pudo crear el contacto de alertas.", - "alerts.policy.title": "Politica de alertas", - "alerts.policy.subtitle": "Configura escalamiento por rol, canal y duracion.", - "alerts.policy.save": "Guardar politica", - "alerts.policy.saving": "Guardando...", - "alerts.policy.defaults": "Escalamiento por defecto (por rol)", - "alerts.policy.enabled": "Habilitado", - "alerts.policy.afterMinutes": "Despues de minutos", - "alerts.policy.channels": "Canales", - "alerts.policy.repeatMinutes": "Repetir (min)", - "alerts.policy.readOnly": "Puedes ver la politica de alertas, pero solo propietarios pueden editar.", - "alerts.policy.defaultsHelp": "Los valores por defecto aplican cuando un evento se reinicia o no se personaliza.", - "alerts.policy.eventSelectLabel": "Tipo de evento", - "alerts.policy.eventSelectHelper": "Ajusta escalamiento para un solo tipo de evento.", - "alerts.policy.applyDefaults": "Aplicar por defecto", - "alerts.event.macrostop": "Macroparo", - "alerts.event.microstop": "Microparo", - "alerts.event.slow-cycle": "Ciclo lento", - "alerts.event.offline": "Fuera de linea", - "alerts.event.error": "Error", - "alerts.contacts.title": "Contactos de alertas", - "alerts.contacts.subtitle": "Destinatarios externos y alcance por rol.", - "alerts.contacts.name": "Nombre", - "alerts.contacts.roleScope": "Rol", - "alerts.contacts.email": "Correo", - "alerts.contacts.phone": "Telefono", - "alerts.contacts.eventTypes": "Tipos de evento (opcional)", - "alerts.contacts.eventTypesPlaceholder": "macroparo, microparo, fuera-de-linea", - "alerts.contacts.eventTypesHelper": "Deja vacío para recibir todos los tipos de evento.", - "alerts.contacts.add": "Agregar contacto", - "alerts.contacts.creating": "Agregando...", - "alerts.contacts.empty": "Sin contactos de alertas.", - "alerts.contacts.save": "Guardar", - "alerts.contacts.saving": "Guardando...", - "alerts.contacts.delete": "Eliminar", - "alerts.contacts.deleting": "Eliminando...", - "alerts.contacts.active": "Activo", - "alerts.contacts.linkedUser": "Usuario vinculado (editar en perfil)", - "alerts.contacts.role.custom": "Personalizado", - "alerts.contacts.role.member": "Miembro", - "alerts.contacts.role.admin": "Admin", - "alerts.contacts.role.owner": "Propietario", - "alerts.contacts.readOnly": "Puedes ver contactos, pero solo propietarios pueden agregar o editar.", - "alerts.inbox.title": "Bandeja de alertas", - "alerts.inbox.loading": "Cargando alertas...", - "alerts.inbox.loadingFilters": "Cargando filtros...", - "alerts.inbox.empty": "No se encontraron alertas.", - "alerts.inbox.error": "No se pudieron cargar las alertas.", - "alerts.inbox.range.24h": "Últimas 24 horas", - "alerts.inbox.range.7d": "Últimos 7 días", - "alerts.inbox.range.30d": "Últimos 30 días", - "alerts.inbox.range.custom": "Personalizado", - "alerts.inbox.filters.title": "Filtros", - "alerts.inbox.filters.range": "Rango", - "alerts.inbox.filters.start": "Inicio", - "alerts.inbox.filters.end": "Fin", - "alerts.inbox.filters.machine": "Máquina", - "alerts.inbox.filters.site": "Sitio", - "alerts.inbox.filters.shift": "Turno", - "alerts.inbox.filters.type": "Clasificación", - "alerts.inbox.filters.severity": "Severidad", - "alerts.inbox.filters.status": "Estado", - "alerts.inbox.filters.search": "Buscar", - "alerts.inbox.filters.searchPlaceholder": "Título, descripción, máquina...", - "alerts.inbox.filters.includeUpdates": "Incluir actualizaciones", - "alerts.inbox.filters.allMachines": "Todas las máquinas", - "alerts.inbox.filters.allSites": "Todos los sitios", - "alerts.inbox.filters.allShifts": "Todos los turnos", - "alerts.inbox.filters.allTypes": "Todas las clasificaciones", - "alerts.inbox.filters.allSeverities": "Todas las severidades", - "alerts.inbox.filters.allStatuses": "Todos los estados", - "alerts.inbox.table.time": "Hora", - "alerts.inbox.table.machine": "Máquina", - "alerts.inbox.table.site": "Sitio", - "alerts.inbox.table.shift": "Turno", - "alerts.inbox.table.type": "Tipo", - "alerts.inbox.table.severity": "Severidad", - "alerts.inbox.table.status": "Estado", - "alerts.inbox.table.duration": "Duración", - "alerts.inbox.table.title": "Título", - "alerts.inbox.table.unknown": "Sin dato", - "alerts.inbox.status.active": "Activa", - "alerts.inbox.status.resolved": "Resuelta", - "alerts.inbox.status.unknown": "Sin dato", - "alerts.inbox.duration.na": "n/d", - "alerts.inbox.duration.sec": "s", - "alerts.inbox.duration.min": " min", - "alerts.inbox.duration.hr": " h", - "alerts.inbox.meta.workOrder": "OT", - "alerts.inbox.meta.sku": "SKU", - "reports.notes.suggested": "Acciones sugeridas", - "reports.notes.none": "Sin insights todavía. Genera reportes tras recolectar datos.", - "reports.noTrend": "Sin datos de tendencia.", - "reports.noDowntime": "Sin datos de paros.", - "reports.noCycle": "Sin datos de ciclo.", - "reports.scrapRate": "Scrap Rate", - "reports.topScrapSku": "SKU con más scrap", - "reports.topScrapWorkOrder": "Orden con más scrap", - "reports.loss.macrostop": "Macroparo", - "reports.loss.microstop": "Microparo", - "reports.loss.slowCycle": "Ciclo lento", - "reports.loss.qualitySpike": "Pico de calidad", - "reports.loss.oeeDrop": "Caída de OEE", - "reports.loss.perfDegradation": "Baja de desempeño", - "reports.tooltip.cycles": "Ciclos", - "reports.tooltip.range": "Rango", - "reports.tooltip.below": "Debajo de", - "reports.tooltip.above": "Encima de", - "reports.tooltip.extremes": "Extremos", - "reports.tooltip.downtime": "Tiempo de paro", - "reports.tooltip.extraTime": "Tiempo extra", - "reports.csv.section": "sección", - "reports.csv.key": "clave", - "reports.csv.value": "valor", - "reports.pdf.title": "Exportación de reporte", - "reports.pdf.range": "Rango", - "reports.pdf.machine": "Máquina", - "reports.pdf.workOrder": "Orden de trabajo", - "reports.pdf.sku": "SKU", - "reports.pdf.metric": "Métrica", - "reports.pdf.value": "Valor", - "reports.pdf.topLoss": "Principales causas de pérdida", - "reports.pdf.qualitySummary": "Resumen de calidad", - "reports.pdf.cycleDistribution": "Distribución de tiempos de ciclo", - "reports.pdf.notes": "Notas para operaciones", - "reports.pdf.none": "Ninguna", - "settings.title": "Configuración", - "settings.subtitle": "Configuración en vivo para turnos, alertas y valores predeterminados.", - "settings.tabs.general": "General", - "settings.tabs.shifts": "Turnos", - "settings.tabs.thresholds": "Umbrales", - "settings.tabs.alerts": "Alertas", - "settings.tabs.financial": "Finanzas", - "settings.tabs.team": "Equipo", - "settings.loading": "Cargando configuración...", - "settings.loadingTeam": "Cargando equipo...", - "settings.refresh": "Actualizar", - "settings.save": "Guardar cambios", - "settings.saving": "Guardando...", - "settings.saved": "Configuración guardada", - "settings.failedLoad": "No se pudo cargar la configuración", - "settings.failedTeam": "No se pudo cargar el equipo", - "settings.failedSave": "No se pudo guardar la configuración", - "settings.unavailable": "La configuración no está disponible.", - "settings.conflict": "La configuración cambió en otro lugar. Actualiza e intenta de nuevo.", - "settings.org.title": "Organización", - "settings.org.plantName": "Nombre de planta", - "settings.org.slug": "Slug", - "settings.org.timeZone": "Zona horaria", - "settings.shiftSchedule": "Turnos", - "settings.shiftSubtitle": "Define turnos activos y compensación de paros.", - "settings.shiftName": "Nombre del turno", - "settings.shiftStart": "Inicio", - "settings.shiftEnd": "Fin", - "settings.shiftEnabled": "Activo", - "settings.shiftAdd": "Agregar turno", - "settings.shiftRemove": "Eliminar", - "settings.shiftComp": "Compensación por cambio de turno", - "settings.lunchBreak": "Comida", - "settings.minutes": "minutos", - "settings.shiftHint": "Máx 3 turnos, HH:mm", - "settings.shiftTo": "a", + "machine.detail.currentWorkOrder": "Orden de trabajo actual", + "machine.detail.recentEvents": "Eventos críticos", + "machine.detail.noEvents": "Sin eventos aún.", + "machine.detail.cycleTarget": "Ciclo objetivo", + "machine.detail.mini.events": "Eventos detectados", + "machine.detail.mini.events.subtitle": "Eventos canónicos (todos)", + "machine.detail.mini.deviation": "Ciclo real vs estándar", + "machine.detail.mini.deviation.subtitle": "Desviación promedio", + "machine.detail.mini.impact": "Impacto en producción", + "machine.detail.mini.impact.subtitle": "Tiempo extra vs ideal", + "machine.detail.modal.events": "Eventos detectados", + "machine.detail.modal.deviation": "Ciclo real vs estándar", + "machine.detail.modal.impact": "Impacto en producción", + "machine.detail.modal.standardCycle": "Ciclo estándar (ideal)", + "machine.detail.modal.avgDeviation": "Desviación promedio", + "machine.detail.modal.sample": "Muestra", + "machine.detail.modal.cycles": "ciclos", + "machine.detail.modal.tip": "Tip: la línea tenue es el ideal. Cada punto es un ciclo real.", + "machine.detail.modal.totalExtra": "Tiempo extra total", + "machine.detail.modal.microstops": "Microparos", + "machine.detail.modal.macroStops": "Macroparos", + "machine.detail.modal.extraTimeLabel": "Tiempo extra", + "machine.detail.modal.extraTimeNote": "Esto es \"tiempo perdido\" vs ideal, distribuido por tipo de evento.", + "reports.title": "Reportes", + "reports.subtitle": "Tendencias, paros y analítica de calidad por máquina.", + "reports.exportCsv": "Exportar CSV", + "reports.exportPdf": "Exportar PDF", + "reports.filters": "Filtros", + "reports.rangeLabel.last24": "Últimas 24 horas", + "reports.rangeLabel.last7": "Últimos 7 días", + "reports.rangeLabel.last30": "Últimos 30 días", + "reports.rangeLabel.custom": "Rango personalizado", + "reports.filter.range": "Rango", + "reports.filter.machine": "Máquina", + "reports.filter.workOrder": "Orden de trabajo", + "reports.filter.sku": "SKU", + "reports.filter.allMachines": "Todas las máquinas", + "reports.filter.allWorkOrders": "Todas las órdenes", + "reports.filter.allSkus": "Todos los SKUs", + "reports.loading": "Cargando reportes...", + "reports.error.failed": "No se pudieron cargar los reportes", + "reports.error.network": "Error de red", + "reports.kpi.note.withData": "Calculado a partir de KPIs.", + "reports.kpi.note.noData": "Sin datos en el rango seleccionado.", + "reports.oeeTrend": "Tendencia de OEE", + "reports.downtimePareto": "Pareto de paros", + "reports.cycleDistribution": "Distribución de tiempos de ciclo", + "reports.scrapTrend": "Tendencia de scrap", + "reports.topLossDrivers": "Principales causas de pérdida", + "reports.qualitySummary": "Resumen de calidad", + "reports.notes": "Notas para operaciones", + "alerts.title": "Alertas", + "alerts.subtitle": "Historial de alertas con filtros y detalle.", + "alerts.comingSoon": "La configuracion de alertas estara disponible pronto.", + "alerts.loading": "Cargando alertas...", + "alerts.error.loadPolicy": "No se pudo cargar la politica de alertas.", + "alerts.error.savePolicy": "No se pudo guardar la politica de alertas.", + "alerts.error.loadContacts": "No se pudieron cargar los contactos de alertas.", + "alerts.error.saveContacts": "No se pudo guardar el contacto de alertas.", + "alerts.error.deleteContact": "No se pudo eliminar el contacto de alertas.", + "alerts.error.createContact": "No se pudo crear el contacto de alertas.", + "alerts.policy.title": "Politica de alertas", + "alerts.policy.subtitle": "Configura escalamiento por rol, canal y duracion.", + "alerts.policy.save": "Guardar politica", + "alerts.policy.saving": "Guardando...", + "alerts.policy.defaults": "Escalamiento por defecto (por rol)", + "alerts.policy.enabled": "Habilitado", + "alerts.policy.afterMinutes": "Despues de minutos", + "alerts.policy.channels": "Canales", + "alerts.policy.repeatMinutes": "Repetir (min)", + "alerts.policy.readOnly": "Puedes ver la politica de alertas, pero solo propietarios pueden editar.", + "alerts.policy.defaultsHelp": "Los valores por defecto aplican cuando un evento se reinicia o no se personaliza.", + "alerts.policy.eventSelectLabel": "Tipo de evento", + "alerts.policy.eventSelectHelper": "Ajusta escalamiento para un solo tipo de evento.", + "alerts.policy.applyDefaults": "Aplicar por defecto", + "alerts.event.macrostop": "Macroparo", + "alerts.event.microstop": "Microparo", + "alerts.event.slow-cycle": "Ciclo lento", + "alerts.event.offline": "Fuera de linea", + "alerts.event.error": "Error", + "alerts.contacts.title": "Contactos de alertas", + "alerts.contacts.subtitle": "Destinatarios externos y alcance por rol.", + "alerts.contacts.name": "Nombre", + "alerts.contacts.roleScope": "Rol", + "alerts.contacts.email": "Correo", + "alerts.contacts.phone": "Telefono", + "alerts.contacts.eventTypes": "Tipos de evento (opcional)", + "alerts.contacts.eventTypesPlaceholder": "macroparo, microparo, fuera-de-linea", + "alerts.contacts.eventTypesHelper": "Deja vacío para recibir todos los tipos de evento.", + "alerts.contacts.add": "Agregar contacto", + "alerts.contacts.creating": "Agregando...", + "alerts.contacts.empty": "Sin contactos de alertas.", + "alerts.contacts.save": "Guardar", + "alerts.contacts.saving": "Guardando...", + "alerts.contacts.delete": "Eliminar", + "alerts.contacts.deleting": "Eliminando...", + "alerts.contacts.active": "Activo", + "alerts.contacts.linkedUser": "Usuario vinculado (editar en perfil)", + "alerts.contacts.role.custom": "Personalizado", + "alerts.contacts.role.member": "Miembro", + "alerts.contacts.role.admin": "Admin", + "alerts.contacts.role.owner": "Propietario", + "alerts.contacts.readOnly": "Puedes ver contactos, pero solo propietarios pueden agregar o editar.", + "alerts.inbox.title": "Bandeja de alertas", + "alerts.inbox.loading": "Cargando alertas...", + "alerts.inbox.loadingFilters": "Cargando filtros...", + "alerts.inbox.empty": "No se encontraron alertas.", + "alerts.inbox.error": "No se pudieron cargar las alertas.", + "alerts.inbox.range.24h": "Últimas 24 horas", + "alerts.inbox.range.7d": "Últimos 7 días", + "alerts.inbox.range.30d": "Últimos 30 días", + "alerts.inbox.range.custom": "Personalizado", + "alerts.inbox.filters.title": "Filtros", + "alerts.inbox.filters.range": "Rango", + "alerts.inbox.filters.start": "Inicio", + "alerts.inbox.filters.end": "Fin", + "alerts.inbox.filters.machine": "Máquina", + "alerts.inbox.filters.site": "Sitio", + "alerts.inbox.filters.shift": "Turno", + "alerts.inbox.filters.type": "Clasificación", + "alerts.inbox.filters.severity": "Severidad", + "alerts.inbox.filters.status": "Estado", + "alerts.inbox.filters.search": "Buscar", + "alerts.inbox.filters.searchPlaceholder": "Título, descripción, máquina...", + "alerts.inbox.filters.includeUpdates": "Incluir actualizaciones", + "alerts.inbox.filters.allMachines": "Todas las máquinas", + "alerts.inbox.filters.allSites": "Todos los sitios", + "alerts.inbox.filters.allShifts": "Todos los turnos", + "alerts.inbox.filters.allTypes": "Todas las clasificaciones", + "alerts.inbox.filters.allSeverities": "Todas las severidades", + "alerts.inbox.filters.allStatuses": "Todos los estados", + "alerts.inbox.table.time": "Hora", + "alerts.inbox.table.machine": "Máquina", + "alerts.inbox.table.site": "Sitio", + "alerts.inbox.table.shift": "Turno", + "alerts.inbox.table.type": "Tipo", + "alerts.inbox.table.severity": "Severidad", + "alerts.inbox.table.status": "Estado", + "alerts.inbox.table.duration": "Duración", + "alerts.inbox.table.title": "Título", + "alerts.inbox.table.unknown": "Sin dato", + "alerts.inbox.status.active": "Activa", + "alerts.inbox.status.resolved": "Resuelta", + "alerts.inbox.status.unknown": "Sin dato", + "alerts.inbox.duration.na": "n/d", + "alerts.inbox.duration.sec": "s", + "alerts.inbox.duration.min": " min", + "alerts.inbox.duration.hr": " h", + "alerts.inbox.meta.workOrder": "OT", + "alerts.inbox.meta.sku": "SKU", + "reports.notes.suggested": "Acciones sugeridas", + "reports.notes.none": "Sin insights todavía. Genera reportes tras recolectar datos.", + "reports.noTrend": "Sin datos de tendencia.", + "reports.noDowntime": "Sin datos de paros.", + "reports.noCycle": "Sin datos de ciclo.", + "reports.scrapRate": "Scrap Rate", + "reports.topScrapSku": "SKU con más scrap", + "reports.topScrapWorkOrder": "Orden con más scrap", + "reports.loss.macrostop": "Macroparo", + "reports.loss.microstop": "Microparo", + "reports.loss.slowCycle": "Ciclo lento", + "reports.loss.qualitySpike": "Pico de calidad", + "reports.loss.oeeDrop": "Caída de OEE", + "reports.loss.perfDegradation": "Baja de desempeño", + "reports.tooltip.cycles": "Ciclos", + "reports.tooltip.range": "Rango", + "reports.tooltip.below": "Debajo de", + "reports.tooltip.above": "Encima de", + "reports.tooltip.extremes": "Extremos", + "reports.tooltip.downtime": "Tiempo de paro", + "reports.tooltip.extraTime": "Tiempo extra", + "reports.csv.section": "sección", + "reports.csv.key": "clave", + "reports.csv.value": "valor", + "reports.pdf.title": "Exportación de reporte", + "reports.pdf.range": "Rango", + "reports.pdf.machine": "Máquina", + "reports.pdf.workOrder": "Orden de trabajo", + "reports.pdf.sku": "SKU", + "reports.pdf.metric": "Métrica", + "reports.pdf.value": "Valor", + "reports.pdf.topLoss": "Principales causas de pérdida", + "reports.pdf.qualitySummary": "Resumen de calidad", + "reports.pdf.cycleDistribution": "Distribución de tiempos de ciclo", + "reports.pdf.notes": "Notas para operaciones", + "reports.pdf.none": "Ninguna", + "settings.title": "Configuración", + "settings.subtitle": "Configuración en vivo para turnos, alertas y valores predeterminados.", + "settings.tabs.general": "General", + "settings.tabs.shifts": "Turnos", + "settings.tabs.thresholds": "Umbrales", + "settings.tabs.alerts": "Alertas", + "settings.tabs.financial": "Finanzas", + "settings.tabs.team": "Equipo", + "settings.loading": "Cargando configuración...", + "settings.loadingTeam": "Cargando equipo...", + "settings.refresh": "Actualizar", + "settings.save": "Guardar cambios", + "settings.saving": "Guardando...", + "settings.saved": "Configuración guardada", + "settings.failedLoad": "No se pudo cargar la configuración", + "settings.failedTeam": "No se pudo cargar el equipo", + "settings.failedSave": "No se pudo guardar la configuración", + "settings.unavailable": "La configuración no está disponible.", + "settings.conflict": "La configuración cambió en otro lugar. Actualiza e intenta de nuevo.", + "settings.org.title": "Organización", + "settings.org.plantName": "Nombre de planta", + "settings.org.slug": "Slug", + "settings.org.timeZone": "Zona horaria", + "settings.shiftSchedule": "Turnos", + "settings.shiftSubtitle": "Define turnos activos y compensación de paros.", + "settings.shiftName": "Nombre del turno", + "settings.shiftStart": "Inicio", + "settings.shiftEnd": "Fin", + "settings.shiftEnabled": "Activo", + "settings.shiftAdd": "Agregar turno", + "settings.shiftRemove": "Eliminar", + "settings.shiftComp": "Compensación por cambio de turno", + "settings.lunchBreak": "Comida", + "settings.minutes": "minutos", + "settings.shiftHint": "Máx 3 turnos, HH:mm", + "settings.shiftTo": "a", "settings.shiftCompLabel": "Compensación por cambio de turno (min)", "settings.lunchBreakLabel": "Comida (min)", "settings.shift.defaultName": "Turno {index}", @@ -501,124 +502,124 @@ "settings.shiftOverrides.sat": "Sábado", "settings.shiftOverrides.sun": "Domingo", "settings.thresholds": "Umbrales de alertas", - "settings.thresholdsSubtitle": "Ajusta alertas de salud de producción.", - "settings.thresholds.appliesAll": "Aplica a todas las máquinas", - "settings.thresholds.oee": "Umbral de alerta OEE", - "settings.thresholds.performance": "Umbral de Performance", - "settings.thresholds.qualitySpike": "Delta de pico de calidad", - "settings.thresholds.stoppage": "Multiplicador de paro", - "settings.thresholds.macroStoppage": "Multiplicador de macroparo", - "settings.alerts": "Alertas", - "settings.alertsSubtitle": "Elige qué alertas notificar.", - "settings.alerts.oeeDrop": "Alertas por caída de OEE", - "settings.alerts.oeeDropHelper": "Notificar cuando OEE esté por debajo del umbral", - "settings.alerts.performanceDegradation": "Alertas por baja de Performance", - "settings.alerts.performanceDegradationHelper": "Marcar ciclos lentos prolongados", - "settings.alerts.qualitySpike": "Alertas por picos de calidad", - "settings.alerts.qualitySpikeHelper": "Alertar por picos de scrap", - "settings.alerts.predictive": "Alertas predictivas de caída OEE", - "settings.alerts.predictiveHelper": "Avisar antes de que OEE caiga", - "settings.defaults": "Valores predeterminados de moldes", - "settings.defaults.moldTotal": "Moldes totales", - "settings.defaults.moldActive": "Moldes activos", - "settings.updated": "Actualizado", - "settings.updatedBy": "Actualizado por", - "settings.team": "Miembros del equipo", - "settings.teamTotal": "{count} total", - "settings.teamNone": "Sin miembros del equipo.", - "settings.invites": "Invitaciones", - "settings.inviteEmail": "Correo de invitación", - "settings.inviteRole": "Rol", - "settings.inviteSend": "Crear invitación", - "settings.inviteSending": "Creando...", - "settings.inviteStatus.copied": "Enlace de invitación copiado", - "settings.inviteStatus.emailRequired": "El correo es obligatorio", - "settings.inviteStatus.failed": "No se pudo revocar la invitación", - "settings.inviteStatus.sent": "Correo de invitación enviado", - "settings.inviteStatus.createFailed": "No se pudo crear la invitación", - "settings.inviteStatus.emailFailed": "Invitación creada, falló el correo: {url}", - "settings.inviteNone": "Sin invitaciones pendientes.", - "settings.inviteExpires": "Expira {date}", - "settings.inviteRole.member": "Miembro", - "settings.inviteRole.admin": "Admin", - "settings.inviteRole.owner": "Propietario", - "settings.inviteCopy": "Copiar enlace", - "settings.inviteRevoke": "Revocar", - "settings.role.owner": "Propietario", - "settings.role.admin": "Admin", - "settings.role.member": "Miembro", - "settings.role.inactive": "Inactivo", - "settings.integrations": "Integraciones", - "settings.integrations.webhook": "Webhook URL", - "settings.integrations.erp": "ERP Sync", - "settings.integrations.erpNotConfigured": "No configurado", - "financial.title": "Impacto financiero", - "financial.subtitle": "Convierte paros, ciclos lentos y scrap en dinero.", - "financial.ownerOnly": "El impacto financiero solo está disponible para propietarios.", + "settings.thresholdsSubtitle": "Ajusta alertas de salud de producción.", + "settings.thresholds.appliesAll": "Aplica a todas las máquinas", + "settings.thresholds.oee": "Umbral de alerta OEE", + "settings.thresholds.performance": "Umbral de Performance", + "settings.thresholds.qualitySpike": "Delta de pico de calidad", + "settings.thresholds.stoppage": "Multiplicador de paro", + "settings.thresholds.macroStoppage": "Multiplicador de macroparo", + "settings.alerts": "Alertas", + "settings.alertsSubtitle": "Elige qué alertas notificar.", + "settings.alerts.oeeDrop": "Alertas por caída de OEE", + "settings.alerts.oeeDropHelper": "Notificar cuando OEE esté por debajo del umbral", + "settings.alerts.performanceDegradation": "Alertas por baja de Performance", + "settings.alerts.performanceDegradationHelper": "Marcar ciclos lentos prolongados", + "settings.alerts.qualitySpike": "Alertas por picos de calidad", + "settings.alerts.qualitySpikeHelper": "Alertar por picos de scrap", + "settings.alerts.predictive": "Alertas predictivas de caída OEE", + "settings.alerts.predictiveHelper": "Avisar antes de que OEE caiga", + "settings.defaults": "Valores predeterminados de moldes", + "settings.defaults.moldTotal": "Moldes totales", + "settings.defaults.moldActive": "Moldes activos", + "settings.updated": "Actualizado", + "settings.updatedBy": "Actualizado por", + "settings.team": "Miembros del equipo", + "settings.teamTotal": "{count} total", + "settings.teamNone": "Sin miembros del equipo.", + "settings.invites": "Invitaciones", + "settings.inviteEmail": "Correo de invitación", + "settings.inviteRole": "Rol", + "settings.inviteSend": "Crear invitación", + "settings.inviteSending": "Creando...", + "settings.inviteStatus.copied": "Enlace de invitación copiado", + "settings.inviteStatus.emailRequired": "El correo es obligatorio", + "settings.inviteStatus.failed": "No se pudo revocar la invitación", + "settings.inviteStatus.sent": "Correo de invitación enviado", + "settings.inviteStatus.createFailed": "No se pudo crear la invitación", + "settings.inviteStatus.emailFailed": "Invitación creada, falló el correo: {url}", + "settings.inviteNone": "Sin invitaciones pendientes.", + "settings.inviteExpires": "Expira {date}", + "settings.inviteRole.member": "Miembro", + "settings.inviteRole.admin": "Admin", + "settings.inviteRole.owner": "Propietario", + "settings.inviteCopy": "Copiar enlace", + "settings.inviteRevoke": "Revocar", + "settings.role.owner": "Propietario", + "settings.role.admin": "Admin", + "settings.role.member": "Miembro", + "settings.role.inactive": "Inactivo", + "settings.integrations": "Integraciones", + "settings.integrations.webhook": "Webhook URL", + "settings.integrations.erp": "ERP Sync", + "settings.integrations.erpNotConfigured": "No configurado", + "financial.title": "Impacto financiero", + "financial.subtitle": "Convierte paros, ciclos lentos y scrap en dinero.", + "financial.ownerOnly": "El impacto financiero solo está disponible para propietarios.", "financial.costsMoved": "Los costos ahora están en", "financial.costsMovedLink": "Configuración -> Finanzas", "financial.export.html": "HTML", "financial.export.csv": "CSV", "financial.refresh": "Actualizar", "financial.totalLoss": "Pérdida total", - "financial.currencyLabel": "Moneda: {currency}", - "financial.noImpact": "Sin datos de impacto.", - "financial.chart.title": "Pérdida de dinero en el tiempo", - "financial.chart.subtitle": "Acumulado por tipo de evento", - "financial.range.day": "Día", - "financial.range.week": "Semana", - "financial.range.month": "Mes", - "financial.filters.title": "Filtros", - "financial.filters.machine": "Máquina", - "financial.filters.location": "Ubicación", - "financial.filters.sku": "SKU", - "financial.filters.currency": "Moneda", - "financial.filters.allMachines": "Todas las máquinas", - "financial.filters.allLocations": "Todas las ubicaciones", - "financial.filters.skuPlaceholder": "Filtrar por SKU", - "financial.filters.currencyPlaceholder": "MXN", - "financial.loadingMachines": "Cargando máquinas...", - "financial.config.title": "Parámetros de costo", - "financial.config.subtitle": "Los valores aplican a todas las máquinas salvo override.", - "financial.config.applyOrg": "Aplicar valores de organización a todas", - "financial.config.save": "Guardar", - "financial.config.saving": "Guardando...", - "financial.config.saved": "Guardado", - "financial.config.saveFailed": "No se pudo guardar", - "financial.config.orgDefaults": "Valores de organización", - "financial.config.locationOverrides": "Overrides por ubicación", - "financial.config.machineOverrides": "Overrides por máquina", - "financial.config.productOverrides": "Overrides por producto", - "financial.config.addLocation": "Agregar override de ubicación", - "financial.config.addMachine": "Agregar override de máquina", - "financial.config.addProduct": "Agregar override de producto", - "financial.config.noneLocation": "Sin overrides de ubicación.", - "financial.config.noneMachine": "Sin overrides de máquina.", - "financial.config.noneProduct": "Sin overrides de producto.", - "financial.config.location": "Ubicación", - "financial.config.selectLocation": "Selecciona ubicación", - "financial.config.machine": "Máquina", - "financial.config.selectMachine": "Selecciona máquina", - "financial.config.currency": "Moneda", - "financial.config.sku": "SKU", - "financial.config.rawMaterialUnit": "Materia prima / unidad", - "financial.config.ownerOnly": "Los costos financieros solo están disponibles para propietarios.", - "financial.config.loading": "Cargando finanzas...", - "financial.field.machineCostPerMin": "Costo máquina / min", - "financial.field.operatorCostPerMin": "Costo operador / min", - "financial.field.ratedRunningKw": "kW en operación", - "financial.field.idleKw": "kW en espera", - "financial.field.kwhRate": "Tarifa kWh", - "financial.field.energyMultiplier": "Multiplicador de energía", + "financial.currencyLabel": "Moneda: {currency}", + "financial.noImpact": "Sin datos de impacto.", + "financial.chart.title": "Pérdida de dinero en el tiempo", + "financial.chart.subtitle": "Acumulado por tipo de evento", + "financial.range.day": "Día", + "financial.range.week": "Semana", + "financial.range.month": "Mes", + "financial.filters.title": "Filtros", + "financial.filters.machine": "Máquina", + "financial.filters.location": "Ubicación", + "financial.filters.sku": "SKU", + "financial.filters.currency": "Moneda", + "financial.filters.allMachines": "Todas las máquinas", + "financial.filters.allLocations": "Todas las ubicaciones", + "financial.filters.skuPlaceholder": "Filtrar por SKU", + "financial.filters.currencyPlaceholder": "MXN", + "financial.loadingMachines": "Cargando máquinas...", + "financial.config.title": "Parámetros de costo", + "financial.config.subtitle": "Los valores aplican a todas las máquinas salvo override.", + "financial.config.applyOrg": "Aplicar valores de organización a todas", + "financial.config.save": "Guardar", + "financial.config.saving": "Guardando...", + "financial.config.saved": "Guardado", + "financial.config.saveFailed": "No se pudo guardar", + "financial.config.orgDefaults": "Valores de organización", + "financial.config.locationOverrides": "Overrides por ubicación", + "financial.config.machineOverrides": "Overrides por máquina", + "financial.config.productOverrides": "Overrides por producto", + "financial.config.addLocation": "Agregar override de ubicación", + "financial.config.addMachine": "Agregar override de máquina", + "financial.config.addProduct": "Agregar override de producto", + "financial.config.noneLocation": "Sin overrides de ubicación.", + "financial.config.noneMachine": "Sin overrides de máquina.", + "financial.config.noneProduct": "Sin overrides de producto.", + "financial.config.location": "Ubicación", + "financial.config.selectLocation": "Selecciona ubicación", + "financial.config.machine": "Máquina", + "financial.config.selectMachine": "Selecciona máquina", + "financial.config.currency": "Moneda", + "financial.config.sku": "SKU", + "financial.config.rawMaterialUnit": "Materia prima / unidad", + "financial.config.ownerOnly": "Los costos financieros solo están disponibles para propietarios.", + "financial.config.loading": "Cargando finanzas...", + "financial.field.machineCostPerMin": "Costo máquina / min", + "financial.field.operatorCostPerMin": "Costo operador / min", + "financial.field.ratedRunningKw": "kW en operación", + "financial.field.idleKw": "kW en espera", + "financial.field.kwhRate": "Tarifa kWh", + "financial.field.energyMultiplier": "Multiplicador de energía", "financial.field.energyCostPerMin": "Costo energía / min", "financial.field.scrapCostPerUnit": "Costo scrap / unidad", "financial.field.rawMaterialCostPerUnit": "Costo materia prima / unidad", "nav.downtime": "Downtime", "nav.recap": "Resumen diario", "settings.tabs.modules": "Módulos", - "settings.modules.title": "Módulos", - "settings.modules.subtitle": "Activa/desactiva módulos según cómo opera la planta.", - "settings.modules.screenless.title": "Modo sin pantalla", - "settings.modules.screenless.helper": "Oculta el módulo de Paros (Downtime) del menú (para plantas sin captura de razones en Node-RED).", - "settings.modules.note": "Este ajuste aplica a toda la organización." -} + "settings.modules.title": "Módulos", + "settings.modules.subtitle": "Activa/desactiva módulos según cómo opera la planta.", + "settings.modules.screenless.title": "Modo sin pantalla", + "settings.modules.screenless.helper": "Oculta el módulo de Paros (Downtime) del menú (para plantas sin captura de razones en Node-RED).", + "settings.modules.note": "Este ajuste aplica a toda la organización." +} diff --git a/lib/recap/redesign.ts b/lib/recap/redesign.ts index b317fe4..08f3b86 100644 --- a/lib/recap/redesign.ts +++ b/lib/recap/redesign.ts @@ -468,7 +468,7 @@ async function resolveCurrentShiftRange(params: { orgId: string; now: Date }) { } async function resolveDetailRange(params: { orgId: string; input: DetailRangeInput }) { - const now = new Date(); + const now = new Date(Math.floor(Date.now() / 60000) * 60000); const requestedMode = normalizedRangeMode(params.input.mode); const shiftEnabledCount = await prisma.orgShift.count({ where: { diff --git a/lib/recap/timelineApi.ts b/lib/recap/timelineApi.ts index e58dbc3..8c58f37 100644 --- a/lib/recap/timelineApi.ts +++ b/lib/recap/timelineApi.ts @@ -55,7 +55,8 @@ function parseMaxSegments(searchParams: URLSearchParams) { } export function parseRecapTimelineRange(searchParams: URLSearchParams) { - const end = parseDateInput(searchParams.get("end")) ?? new Date(); + const defaultEnd = new Date(Math.floor(Date.now() / 60000) * 60000); + const end = parseDateInput(searchParams.get("end")) ?? defaultEnd; const startParam = parseDateInput(searchParams.get("start")); if (startParam && startParam < end) { return { diff --git a/package.json b/package.json index 49af182..0e088f0 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,8 @@ "build": "next build --webpack", "start": "next start", "lint": "eslint", + "test:downtime-reason-guard": "node scripts/test-downtime-reason-guard.mjs", + "backfill:downtime-reasons": "node scripts/backfill-downtime-reasons.mjs", "prisma:generate": "prisma generate", "prisma:migrate:deploy": "prisma migrate deploy" }, diff --git a/prisma/migrations/20260427120000_machine_work_order_mold_cavities/migration.sql b/prisma/migrations/20260427120000_machine_work_order_mold_cavities/migration.sql new file mode 100644 index 0000000..37cc398 --- /dev/null +++ b/prisma/migrations/20260427120000_machine_work_order_mold_cavities/migration.sql @@ -0,0 +1,4 @@ +-- AlterTable +ALTER TABLE "machine_work_orders" ADD COLUMN "mold" TEXT; +ALTER TABLE "machine_work_orders" ADD COLUMN "cavities_total" INTEGER; +ALTER TABLE "machine_work_orders" ADD COLUMN "cavities_active" INTEGER; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 1f2ae98..30e38ed 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -254,6 +254,9 @@ model MachineWorkOrder { goodParts Int @default(0) @map("good_parts") scrapParts Int @default(0) @map("scrap_parts") cycleCount Int @default(0) @map("cycle_count") + mold String? + cavitiesTotal Int? @map("cavities_total") + cavitiesActive Int? @map("cavities_active") machine Machine @relation(fields: [machineId], references: [id], onDelete: Cascade) org Org @relation(fields: [orgId], references: [id], onDelete: Cascade) diff --git a/scripts/backfill-downtime-reasons.mjs b/scripts/backfill-downtime-reasons.mjs new file mode 100644 index 0000000..80d3bd9 --- /dev/null +++ b/scripts/backfill-downtime-reasons.mjs @@ -0,0 +1,308 @@ +#!/usr/bin/env node + +import { PrismaClient } from "@prisma/client"; + +const prisma = new PrismaClient(); +const NON_AUTHORITATIVE_REASON_CODES = new Set(["PENDIENTE", "UNCLASSIFIED"]); + +function parseArgs(argv) { + const out = { + dryRun: false, + since: "30d", + orgId: null, + machineId: null, + }; + + for (let i = 0; i < argv.length; i += 1) { + const token = argv[i]; + if (token === "--dry-run") { + out.dryRun = true; + continue; + } + if (token === "--since") { + out.since = argv[i + 1] || out.since; + i += 1; + continue; + } + if (token === "--org-id") { + out.orgId = argv[i + 1] || null; + i += 1; + continue; + } + if (token === "--machine-id") { + out.machineId = argv[i + 1] || null; + i += 1; + continue; + } + throw new Error(`Unknown argument: ${token}`); + } + + return out; +} + +function parseSince(value) { + const now = Date.now(); + const text = String(value || "30d").trim().toLowerCase(); + const relative = text.match(/^(\d+)\s*([dhm])$/); + if (relative) { + const amount = Number(relative[1]); + const unit = relative[2]; + const factor = unit === "d" ? 24 * 60 * 60 * 1000 : unit === "h" ? 60 * 60 * 1000 : 60 * 1000; + return new Date(now - amount * factor); + } + const dt = new Date(value); + if (Number.isNaN(dt.getTime())) { + throw new Error(`Invalid --since value: ${value}. Use ISO date, or relative like 30d / 12h / 90m.`); + } + return dt; +} + +function asRecord(value) { + return value && typeof value === "object" && !Array.isArray(value) ? value : null; +} + +function clampText(value, maxLen) { + if (value === null || value === undefined) return null; + const text = String(value).trim().replace(/[\u0000-\u001f\u007f]/g, ""); + if (!text) return null; + return text.length > maxLen ? text.slice(0, maxLen) : text; +} + +function canonicalId(input) { + const text = String(input ?? "") + .normalize("NFD") + .replace(/[\u0300-\u036f]/g, "") + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); + return text || null; +} + +function toReasonCode(categoryId, detailId) { + const cat = canonicalId(categoryId); + const det = canonicalId(detailId); + if (!cat || !det) return null; + return `${cat}__${det}`.toUpperCase(); +} + +function isNonAuthoritativeReasonCode(code) { + const normalized = clampText(code, 64)?.toUpperCase(); + return !!normalized && NON_AUTHORITATIVE_REASON_CODES.has(normalized); +} + +function extractReasonPayload(data) { + const rec = asRecord(data); + if (!rec) return null; + const direct = asRecord(rec.reason); + if (direct) return direct; + const downtime = asRecord(rec.downtime); + const nested = asRecord(downtime?.reason); + return nested || null; +} + +function extractIncidentKey(data, reason) { + const rec = asRecord(data); + const downtime = asRecord(rec?.downtime); + return ( + clampText(rec?.incidentKey, 128) ?? + clampText(downtime?.incidentKey, 128) ?? + clampText(reason?.incidentKey, 128) ?? + null + ); +} + +function normalizeAckReason(reasonRaw) { + const categoryId = clampText(reasonRaw?.categoryId, 64); + const detailId = clampText(reasonRaw?.detailId, 64); + const categoryLabel = clampText(reasonRaw?.categoryLabel, 120); + const detailLabel = clampText(reasonRaw?.detailLabel, 120); + + const reasonCode = + clampText(reasonRaw?.reasonCode, 64)?.toUpperCase() ?? + toReasonCode(categoryId ?? categoryLabel, detailId ?? detailLabel) ?? + null; + if (!reasonCode) return null; + + const reasonLabel = + clampText(reasonRaw?.reasonText, 240) ?? + (categoryLabel && detailLabel ? `${categoryLabel} > ${detailLabel}` : null) ?? + detailLabel ?? + categoryLabel ?? + reasonCode; + + return { + type: "downtime", + categoryId, + categoryLabel, + detailId, + detailLabel, + reasonCode, + reasonLabel, + reasonText: reasonLabel, + }; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const since = parseSince(args.since); + + const where = { + eventType: "downtime-acknowledged", + ts: { gte: since }, + ...(args.orgId ? { orgId: args.orgId } : {}), + ...(args.machineId ? { machineId: args.machineId } : {}), + }; + + const ackEvents = await prisma.machineEvent.findMany({ + where, + orderBy: { ts: "desc" }, + select: { + id: true, + orgId: true, + machineId: true, + ts: true, + data: true, + }, + }); + + const latestByIncident = new Map(); + for (const event of ackEvents) { + const reasonRaw = extractReasonPayload(event.data); + if (!reasonRaw) continue; + const normalized = normalizeAckReason(reasonRaw); + if (!normalized) continue; + if (isNonAuthoritativeReasonCode(normalized.reasonCode)) continue; + + const incidentKey = extractIncidentKey(event.data, reasonRaw); + if (!incidentKey) continue; + + const mapKey = `${event.orgId}::${incidentKey}`; + if (latestByIncident.has(mapKey)) continue; + latestByIncident.set(mapKey, { + orgId: event.orgId, + machineId: event.machineId, + incidentKey, + eventId: event.id, + eventTs: event.ts, + reason: normalized, + }); + } + + let scanned = 0; + let candidates = 0; + let updated = 0; + let missingReasonEntry = 0; + let alreadyManual = 0; + let skippedNonPendingIncoming = 0; + const samples = []; + + for (const item of latestByIncident.values()) { + scanned += 1; + const existing = await prisma.reasonEntry.findFirst({ + where: { + orgId: item.orgId, + kind: "downtime", + episodeId: item.incidentKey, + }, + select: { + id: true, + reasonCode: true, + reasonLabel: true, + reasonText: true, + capturedAt: true, + schemaVersion: true, + }, + }); + + if (!existing) { + missingReasonEntry += 1; + continue; + } + if (!isNonAuthoritativeReasonCode(existing.reasonCode)) { + alreadyManual += 1; + continue; + } + if (isNonAuthoritativeReasonCode(item.reason.reasonCode)) { + skippedNonPendingIncoming += 1; + continue; + } + + candidates += 1; + const next = { + reasonCode: item.reason.reasonCode, + reasonLabel: item.reason.reasonLabel ?? item.reason.reasonCode, + reasonText: item.reason.reasonText ?? item.reason.reasonLabel ?? item.reason.reasonCode, + schemaVersion: Math.max(1, Number(existing.schemaVersion || 1)), + meta: { + source: "backfill:downtime-acknowledged", + eventId: item.eventId, + eventTs: item.eventTs.toISOString(), + incidentKey: item.incidentKey, + reason: { + type: "downtime", + categoryId: item.reason.categoryId, + categoryLabel: item.reason.categoryLabel, + detailId: item.reason.detailId, + detailLabel: item.reason.detailLabel, + reasonText: item.reason.reasonText, + }, + }, + }; + + samples.push({ + reasonEntryId: existing.id, + orgId: item.orgId, + machineId: item.machineId, + incidentKey: item.incidentKey, + from: { + reasonCode: existing.reasonCode, + reasonLabel: existing.reasonLabel, + reasonText: existing.reasonText, + }, + to: { + reasonCode: next.reasonCode, + reasonLabel: next.reasonLabel, + reasonText: next.reasonText, + }, + }); + + if (!args.dryRun) { + await prisma.reasonEntry.update({ + where: { id: existing.id }, + data: next, + }); + updated += 1; + } + } + + const summary = { + ok: true, + mode: args.dryRun ? "dry-run" : "apply", + since: since.toISOString(), + filters: { + orgId: args.orgId, + machineId: args.machineId, + }, + eventsRead: ackEvents.length, + incidentsDeduped: latestByIncident.size, + scanned, + candidates, + updated, + missingReasonEntry, + alreadyManual, + skippedNonPendingIncoming, + sampleUpdates: samples.slice(0, 25), + }; + + console.log(JSON.stringify(summary, null, 2)); +} + +main() + .catch((err) => { + console.error("[backfill-downtime-reasons] failed:", err); + process.exitCode = 1; + }) + .finally(async () => { + await prisma.$disconnect(); + }); + diff --git a/scripts/pi-work_orders_add_mold_cavities.sql b/scripts/pi-work_orders_add_mold_cavities.sql new file mode 100644 index 0000000..6d51d8d --- /dev/null +++ b/scripts/pi-work_orders_add_mold_cavities.sql @@ -0,0 +1,8 @@ +-- Run on the Pi/MariaDB instance used by Node-RED (local `work_orders` table). +-- Required before importing updated flows that INSERT/UPDATE mold, cavities_total, cavities_active. + +ALTER TABLE work_orders ADD COLUMN mold VARCHAR(256) NULL; +ALTER TABLE work_orders ADD COLUMN cavities_total INT NULL; +ALTER TABLE work_orders ADD COLUMN cavities_active INT NULL; + +-- If columns already exist, skip this script or adjust manually. diff --git a/scripts/test-downtime-reason-guard.mjs b/scripts/test-downtime-reason-guard.mjs new file mode 100644 index 0000000..b24b791 --- /dev/null +++ b/scripts/test-downtime-reason-guard.mjs @@ -0,0 +1,68 @@ +#!/usr/bin/env node + +import assert from "node:assert/strict"; + +const NON_AUTHORITATIVE_REASON_CODES = new Set(["PENDIENTE", "UNCLASSIFIED"]); + +function isNonAuthoritativeReasonCode(code) { + const normalized = String(code ?? "").trim().toUpperCase(); + return !!normalized && NON_AUTHORITATIVE_REASON_CODES.has(normalized); +} + +function shouldPreserveManualReason({ + incomingReasonCode, + existingReasonCode, + isManualAckEvent, +}) { + if (isManualAckEvent) return false; + if (!isNonAuthoritativeReasonCode(incomingReasonCode)) return false; + if (!existingReasonCode) return false; + return !isNonAuthoritativeReasonCode(existingReasonCode); +} + +function run() { + // 1) pending -> manual ack -> later pending: preserve manual + assert.equal( + shouldPreserveManualReason({ + incomingReasonCode: "PENDIENTE", + existingReasonCode: "OPERACION__OTRO", + isManualAckEvent: false, + }), + true + ); + + // 2) manual ack followed by another manual reason: latest manual should be allowed + assert.equal( + shouldPreserveManualReason({ + incomingReasonCode: "SERVICIOS__OTRO", + existingReasonCode: "OPERACION__OTRO", + isManualAckEvent: true, + }), + false + ); + + // 3) no manual reason ever applied: pending stays pending + assert.equal( + shouldPreserveManualReason({ + incomingReasonCode: "UNCLASSIFIED", + existingReasonCode: "PENDIENTE", + isManualAckEvent: false, + }), + false + ); + + console.log( + JSON.stringify( + { + ok: true, + testedAt: new Date().toISOString(), + scenarios: 3, + }, + null, + 2 + ) + ); +} + +run(); +