4246 lines
449 KiB
JSON
4246 lines
449 KiB
JSON
[
|
||
{
|
||
"id": "080d227df7fb2db1",
|
||
"type": "subflow",
|
||
"name": "Outbox Enqueue v1 (1) (4) (2) (3) (1) (3) (1)",
|
||
"info": "",
|
||
"category": "",
|
||
"in": [
|
||
{
|
||
"x": 40,
|
||
"y": 40,
|
||
"wires": [
|
||
{
|
||
"id": "e59e58cf20a7d000"
|
||
}
|
||
]
|
||
}
|
||
],
|
||
"out": [
|
||
{
|
||
"x": 1160,
|
||
"y": 40,
|
||
"wires": [
|
||
{
|
||
"id": "2a6a83800fd51968",
|
||
"port": 0
|
||
}
|
||
]
|
||
}
|
||
],
|
||
"env": [],
|
||
"meta": {},
|
||
"color": "#DDAA99"
|
||
},
|
||
{
|
||
"id": "e59e58cf20a7d000",
|
||
"type": "function",
|
||
"z": "080d227df7fb2db1",
|
||
"name": "Prepare + Validate + Call next_seq",
|
||
"func": "// Outbox Enqueue v1 - Step 1\nconst config = global.get(\"config\") || {};\nconst out = msg.outbox || {};\nconst type = out.type;\nconst payload = out.payload;\n\nif (!type) throw new Error(\"Outbox Enqueue: missing msg.outbox.type\");\nif (!payload || typeof payload !== \"object\") throw new Error(\"Outbox Enqueue: missing/invalid msg.outbox.payload\");\n\n// Where to send later (Publisher will use this)\nconst endpointByType = {\n cycle: \"/api/ingest/cycle\",\n event: \"/api/ingest/event\",\n kpi: \"/api/ingest/kpi\",\n heartbeat: \"/api/ingest/heartbeat\",\n segment: \"/api/ingest/segment\", // future; ok to queue now even if not used yet\n};\n\nconst endpoint = out.endpoint || endpointByType[type];\nif (!endpoint) throw new Error(`Outbox Enqueue: unknown type '${type}' and no endpoint provided`);\n\n// Get machineId from msg or global config\nconst machineId = msg.machineId || config.machineId;\nif (!machineId) {\n node.status({ fill: \"yellow\", shape: \"ring\", text: \"Outbox waiting for pairing\" });\n return null;\n}\n\nconst schemaVersion = msg.schemaVersion || \"1.0\";\nconst tsMs = typeof msg.tsMs === \"number\" ? msg.tsMs : Date.now();\n\n// Stash meta for later nodes\nmsg._outboxMeta = { type, endpoint, machineId, schemaVersion, tsMs, payload };\n\nconst validators = {\n cycle: (p) => p && typeof p.cycle === \"object\",\n event: (p) => p && typeof p.event === \"object\",\n kpi: (p) => p && p.kpis && typeof p.kpis === \"object\",\n heartbeat: (p) => p && typeof p.status === \"string\",\n segment: (p) => p && typeof p === \"object\",\n};\n\nconst validator = validators[type];\nif (!validator || !validator(payload)) {\n node.warn(`Outbox Enqueue: invalid ${type} payload`);\n return null;\n}\n\n// Call stored procedure to get next seq (safe + persistent)\nmsg.topic = \"CALL next_seq(?);\";\nmsg.payload = [machineId];\n\nreturn msg;\n",
|
||
"outputs": 1,
|
||
"timeout": 0,
|
||
"noerr": 0,
|
||
"initialize": "",
|
||
"finalize": "",
|
||
"libs": [],
|
||
"x": 220,
|
||
"y": 40,
|
||
"wires": [
|
||
[
|
||
"41ed55d743833df6"
|
||
]
|
||
]
|
||
},
|
||
{
|
||
"id": "41ed55d743833df6",
|
||
"type": "mysql",
|
||
"z": "080d227df7fb2db1",
|
||
"mydb": "fc9634aabefee16b",
|
||
"name": "CALL next_seq",
|
||
"x": 460,
|
||
"y": 40,
|
||
"wires": [
|
||
[
|
||
"3aa8af5ed40c0681"
|
||
]
|
||
]
|
||
},
|
||
{
|
||
"id": "3aa8af5ed40c0681",
|
||
"type": "function",
|
||
"z": "080d227df7fb2db1",
|
||
"name": "Build envelope + prepare INSERT",
|
||
"func": "// Outbox Enqueue v1 - Step 2\nconst meta = msg._outboxMeta;\nif (!meta) throw new Error(\"Outbox Enqueue: missing _outboxMeta\");\n\nfunction stripNil(obj) {\n if (!obj || typeof obj !== \"object\") return obj;\n const out = Array.isArray(obj) ? [] : {};\n for (const [k, v] of Object.entries(obj)) {\n if (v === undefined || v === null) continue; // <— key change\n out[k] = (v && typeof v === \"object\") ? stripNil(v) : v;\n }\n return out;\n}\n\n// Parse seq from MySQL result\n// mysql node often returns an array of result sets for CALL\nlet seq = null;\nconst res = msg.payload;\n\nif (Array.isArray(res)) {\n // common shape: [ [ { seq: 123 } ], ... ]\n if (Array.isArray(res[0]) && res[0][0] && res[0][0].seq != null) seq = res[0][0].seq;\n // sometimes: [ { seq: 123 } ]\n if (seq == null && res[0] && res[0].seq != null) seq = res[0].seq;\n}\n\nif (seq == null) throw new Error(\"Outbox Enqueue: could not parse seq from DB result\");\n\n\n\n\nfunction normalizeIsoDeep(obj) {\n if (!obj || typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) return obj.map(normalizeIsoDeep);\n\n for (const k of Object.keys(obj)) {\n const v = obj[k];\n\n // recurse first\n if (v && typeof v === \"object\") obj[k] = normalizeIsoDeep(v);\n\n // ISO fields: must be string|null\n if (k.toLowerCase().endsWith(\"iso\")) {\n const vv = obj[k];\n if (typeof vv === \"string\") continue;\n if (typeof vv === \"number\") obj[k] = new Date(vv).toISOString();\n else if (vv == null) obj[k] = null;\n else obj[k] = null; // <- kills {} forever\n }\n }\n return obj;\n}\n\n\n\n\n\nconst cleanPayload = normalizeIsoDeep(stripNil(meta.payload));\nconst envelope = {\n schemaVersion: meta.schemaVersion,\n machineId: meta.machineId,\n tsMs: meta.tsMs,\n seq: String(seq),\n type: meta.type,\n payload: cleanPayload\n};\n\n\n// Prepare insert into outbox_messages\nmsg.topic = `\nINSERT INTO outbox_messages\n(machine_id, msg_type, endpoint, schema_version, seq, ts_device_ms, payload_json, status, attempts, next_attempt_at)\nVALUES (?, ?, ?, ?, ?, ?, ?, 'pending', 0, NULL);\n`.trim();\n\nmsg.payload = [\n meta.machineId,\n meta.type,\n meta.endpoint,\n meta.schemaVersion,\n Number(seq), // BIGINT\n meta.tsMs, // BIGINT\n JSON.stringify(envelope),\n];\n\n// Keep a copy for debugging\nmsg._envelope = envelope;\nmsg._seq = Number(seq);\n\nreturn msg;\n",
|
||
"outputs": 1,
|
||
"timeout": 0,
|
||
"noerr": 0,
|
||
"initialize": "",
|
||
"finalize": "",
|
||
"libs": [],
|
||
"x": 720,
|
||
"y": 40,
|
||
"wires": [
|
||
[
|
||
"2a6a83800fd51968"
|
||
]
|
||
]
|
||
},
|
||
{
|
||
"id": "2a6a83800fd51968",
|
||
"type": "mysql",
|
||
"z": "080d227df7fb2db1",
|
||
"mydb": "fc9634aabefee16b",
|
||
"name": "Insert outbox_messages",
|
||
"x": 1010,
|
||
"y": 40,
|
||
"wires": [
|
||
[]
|
||
]
|
||
},
|
||
{
|
||
"id": "05d4cb231221b842",
|
||
"type": "tab",
|
||
"label": "Flow 2.1",
|
||
"disabled": false,
|
||
"info": "",
|
||
"env": []
|
||
},
|
||
{
|
||
"id": "6e514144a570aa72",
|
||
"type": "group",
|
||
"z": "05d4cb231221b842",
|
||
"name": "Start ",
|
||
"style": {
|
||
"stroke": "#92d04f",
|
||
"fill": "#addb7b",
|
||
"label": true
|
||
},
|
||
"nodes": [
|
||
"a819f394fe7fc6aa",
|
||
"86b533aacff8b212",
|
||
"093d9631fbd43003",
|
||
"8ebf807b7c65eb42",
|
||
"d7fce9cf6a8c8f9b",
|
||
"05112cf4f0821cfd",
|
||
"0f0afb7fd521f2c2",
|
||
"482feffe728ab41a"
|
||
],
|
||
"x": 1134,
|
||
"y": 139,
|
||
"w": 942,
|
||
"h": 142
|
||
},
|
||
{
|
||
"id": "3d465304d3ddfb72",
|
||
"type": "group",
|
||
"z": "05d4cb231221b842",
|
||
"name": "Cavity Settings ",
|
||
"style": {
|
||
"stroke": "#ff7f7f",
|
||
"fill": "#ffbfbf",
|
||
"label": true
|
||
},
|
||
"nodes": [
|
||
"f75c03c8eb84ebf6"
|
||
],
|
||
"x": 122,
|
||
"y": 507,
|
||
"w": 926,
|
||
"h": 306
|
||
},
|
||
{
|
||
"id": "def89ffb5f14d456",
|
||
"type": "group",
|
||
"z": "05d4cb231221b842",
|
||
"name": "UI/UX",
|
||
"style": {
|
||
"fill": "#d1d1d1",
|
||
"label": true
|
||
},
|
||
"nodes": [
|
||
"dbfd127c516efa87",
|
||
"d230dfcd0d152ded",
|
||
"765441c17d3d41b6",
|
||
"fd2616266cc640d6",
|
||
"afb514404a6ecda1",
|
||
"b1a448897989958f",
|
||
"44d2ce4b810b508b",
|
||
"5dd7945ae90715a0",
|
||
"bfa9fe745d22c79a",
|
||
"c0dd0940ec7f53ba",
|
||
"ad66f1edaba40aaa",
|
||
"5084f1955153578d",
|
||
"5201b1255d81c6a1",
|
||
"01705d77724ccc51",
|
||
"6b3c45059b9b7c6c",
|
||
"e6d76d15a304de1a",
|
||
"fbed0d5d49b02e4c",
|
||
"39d72779cd51be9a",
|
||
"fe77ffa843b0dcfb",
|
||
"b699e16ddfa987d9",
|
||
"a981c7f429b397f0",
|
||
"ebebd1c90b0e488a"
|
||
],
|
||
"x": 214,
|
||
"y": 179,
|
||
"w": 672,
|
||
"h": 362
|
||
},
|
||
{
|
||
"id": "a1b43a9e095c10db",
|
||
"type": "group",
|
||
"z": "05d4cb231221b842",
|
||
"name": "Work Orders",
|
||
"style": {
|
||
"stroke": "#9363b7",
|
||
"fill": "#dbcbe7",
|
||
"label": true
|
||
},
|
||
"nodes": [
|
||
"eb61ec7045cb4fab",
|
||
"e19e54018a466662",
|
||
"0638171f0c347095",
|
||
"ca4956aff7158938",
|
||
"c09c71a7e4908231",
|
||
"79e027bf3befb2d9",
|
||
"245a057bdff1fc14",
|
||
"1212f599b9ab36f0",
|
||
"7b210ef16e508259",
|
||
"875d5f193c768af0",
|
||
"1f26139ec9079c2d",
|
||
"ff9a2476ccda2ac4",
|
||
"a3d41a656eb3b2ce",
|
||
"7e94b5651ed96f24",
|
||
"bb14a0293698c0e0",
|
||
"204c7a49f98a9944",
|
||
"6d19a182b174127e",
|
||
"5f1b67667a0c39f4",
|
||
"09c77467731a6a66",
|
||
"babe66a431cd1760",
|
||
"bfb9b7c7af23bd5c",
|
||
"f9bbe50ab55c42a1",
|
||
"afb78150ffe54054",
|
||
"d45345c05485d114",
|
||
"7b91e5cc70af6ff3",
|
||
"d569d16fc0423be8",
|
||
"7d0b25dedd60803a",
|
||
"dc24aea451e9b976",
|
||
"6de9cd8265d1e821",
|
||
"68709c57900ed80e",
|
||
"1b6eda85e72ecff1",
|
||
"7aac414134d40b3a",
|
||
"78925efc4a55f04d",
|
||
"5df5be609ff6e622",
|
||
"dcaa582c9b2277ba",
|
||
"8d2fcc3bc64141a0",
|
||
"16b778a1349b8102",
|
||
"abbec199700a5e29"
|
||
],
|
||
"x": 1034,
|
||
"y": 279,
|
||
"w": 1432,
|
||
"h": 682
|
||
},
|
||
{
|
||
"id": "d9a9ee7bc71b0f53",
|
||
"type": "group",
|
||
"z": "05d4cb231221b842",
|
||
"name": "Anomaly System",
|
||
"style": {
|
||
"stroke": "#ffC000",
|
||
"fill": "#ffdf7f",
|
||
"label": true
|
||
},
|
||
"nodes": [
|
||
"9748899355370bae",
|
||
"4ee66ceb859b7cf1",
|
||
"8e60972fea4bd36a",
|
||
"3c80936f0a0918c3",
|
||
"f27352133669b6fa"
|
||
],
|
||
"x": 224,
|
||
"y": 19,
|
||
"w": 922,
|
||
"h": 102
|
||
},
|
||
{
|
||
"id": "443b758222662fdf",
|
||
"type": "group",
|
||
"z": "05d4cb231221b842",
|
||
"name": "Alerts",
|
||
"style": {
|
||
"fill": "#bfdbef",
|
||
"label": true
|
||
},
|
||
"nodes": [
|
||
"4a62662fea532976",
|
||
"6e76f33c5b84574a",
|
||
"96dfd46a1435d111"
|
||
],
|
||
"x": 234,
|
||
"y": 819,
|
||
"w": 512,
|
||
"h": 82
|
||
},
|
||
{
|
||
"id": "9221454c45afd1ba",
|
||
"type": "group",
|
||
"z": "05d4cb231221b842",
|
||
"name": "Graphs",
|
||
"style": {
|
||
"fill": "#bfbfbf",
|
||
"label": true
|
||
},
|
||
"nodes": [
|
||
"7df6eebd9b7c7c7b",
|
||
"cc31f7b315638ba5",
|
||
"25a2e7a04827039a",
|
||
"9f929db1f49b6e16",
|
||
"5109df0f8b1e20e3"
|
||
],
|
||
"x": 1194,
|
||
"y": 39,
|
||
"w": 802,
|
||
"h": 82
|
||
},
|
||
{
|
||
"id": "f75c03c8eb84ebf6",
|
||
"type": "group",
|
||
"z": "05d4cb231221b842",
|
||
"g": "3d465304d3ddfb72",
|
||
"name": "Cavities Settings",
|
||
"style": {
|
||
"stroke": "#ffff00",
|
||
"fill": "#ffffbf",
|
||
"label": true
|
||
},
|
||
"nodes": [
|
||
"878b79013722e91f"
|
||
],
|
||
"x": 148,
|
||
"y": 533,
|
||
"w": 874,
|
||
"h": 254
|
||
},
|
||
{
|
||
"id": "878b79013722e91f",
|
||
"type": "group",
|
||
"z": "05d4cb231221b842",
|
||
"g": "f75c03c8eb84ebf6",
|
||
"name": "Settings",
|
||
"style": {
|
||
"stroke": "#92d04f",
|
||
"fill": "#ffffbf",
|
||
"label": true
|
||
},
|
||
"nodes": [
|
||
"dc743dbc93f7b7ad",
|
||
"9e5a27b63b362466",
|
||
"5542672209bd0479",
|
||
"4056bc6a05189ca8",
|
||
"3a5788e9d86542d0",
|
||
"4101967d16ba7f8b",
|
||
"ba626f3a3b37e653",
|
||
"2c8562b2471078ab"
|
||
],
|
||
"x": 174,
|
||
"y": 559,
|
||
"w": 822,
|
||
"h": 202
|
||
},
|
||
{
|
||
"id": "dbfd127c516efa87",
|
||
"type": "ui_template",
|
||
"z": "05d4cb231221b842",
|
||
"g": "def89ffb5f14d456",
|
||
"group": "919b5b8d778e2b6c",
|
||
"name": "Home Template",
|
||
"order": 0,
|
||
"width": "25",
|
||
"height": "25",
|
||
"format": "<style>\n@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@600;700&display=swap');\n\n/* SCALE: align 100% zoom with prior 125% appearance */\n:root {\nfont-size: 100%; /* was 120% */\n--bg-0: #0c1117;\n--bg-1: #131a23;\n--panel: #151e2b;\n--panel-hi: #1a2433;\n--text: #ecf3ff;\n--muted: #96a5b7;\n--accent: #2ea3ff;\n--accent-2: #1f8cf3;\n--good: #24d06f;\n--warn: #ffd100;\n--bad: #ff4d4f;\n\n--radius: 0.75rem;\n--shadow: 0 0.5rem 1rem rgba(0, 0, 0, .35),\ninset 0 0.0625rem 0 rgba(255, 255, 255, .05);\n\n--sidebar-width: 3.75rem;\n--sidebar-gap: clamp(0.75rem, 1.2vh, 1rem);\n\n/* Tuned for a 10.1\" 1280×800 screen */\n--content-max: 72rem; /* was 100rem */\n--content-pad: clamp(1rem, 1.2vw, 1.4rem);\n--section-gap: clamp(0.75rem, 1vw, 1rem);\n--card-pad: clamp(1rem, 1.1vw, 1.25rem);\n--card-pad-lg: clamp(1.1rem, 1.2vw, 1.35rem);\n\n--fs-page-title: clamp(1.2rem, 1vw + 0.35rem, 1.7rem);\n--fs-section-title: clamp(0.95rem, 0.9vw + 0.25rem, 1.25rem);\n--fs-label: clamp(0.85rem, 0.7vw + 0.3rem, 1.05rem);\n--fs-label-lg: clamp(0.95rem, 0.8vw + 0.32rem, 1.15rem);\n--fs-kpi: clamp(2.25rem, 2.5vw, 3.25rem);\n--fs-kpi-unit: clamp(1.25rem, 1.4vw, 1.5rem);\n--fs-body: clamp(0.8rem, 0.7vw + 0.28rem, 1rem);\n--progress-height: 0.875rem;\n--start-min-height: 9.375rem;\n}\n/* IMPORTANT: must NOT be inside :root – older Chromium needs this */\n#oee md-content,\n#oee .nr-dashboard-template,\n#oee .nr-dashboard-template md-content,\n#oee .nr-dashboard-cardpanel,\n#oee .nr-dashboard-cardpanel md-card,\n#oee .nr-dashboard-cardpanel md-card-content {\nbackground: transparent !important;\nbox-shadow: none !important;\n}\n\n* {\n box-sizing: border-box;\n}\n/* FORCE DASHBOARD TO BE FULL-BLEED, NO CARD FRAME */\nbody > md-content,\nbody > md-content > md-content,\n.nr-dashboard-template,\n.nr-dashboard-template md-content {\nmargin: 0 !important;\npadding: 0 !important;\nbackground: var(--bg-0) !important;\n}\n\n/* Remove margin/radius from the card that holds the ui_template */\n.nr-dashboard-cardpanel,\n.nr-dashboard-cardpanel md-card,\n.nr-dashboard-cardpanel md-card-content {\nbackground: transparent !important;\nbox-shadow: none !important;\npadding: 0 !important;\nmargin: 0 !important;\nborder-radius: 0 !important;\n}\n\nhtml,\nbody,\n#oee {\n width: 100vw;\n height: 100vh;\n}\n\nhtml,\nbody {\n margin: 0;\n padding: 0;\n overflow-x: hidden;\n background: var(--bg-0);\n color: var(--text);\n font-family: 'Poppins', system-ui, 'Segoe UI', 'Roboto', sans-serif;\n font-weight: 600;\n}\n\nbody {\n overflow: hidden;\n}\n\n\n\n/* LAYOUT: lock sidebar + content grid across tabs */\n#oee {\n position: fixed;\n inset: 0;\n display: flex;\n overflow: hidden;\n}\n\n.sidebar {\n width: var(--sidebar-width);\n background: #0b1119;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: space-between;\n padding: clamp(0.625rem, 1.4vh, 0.9rem) clamp(0.5rem, 0.8vw, 0.75rem);\n}\n\n.side-top {\n display: flex;\n flex-direction: column;\n gap: var(--sidebar-gap);\n align-items: center;\n}\n\n.sb-btn {\n width: 2.75rem;\n height: 2.75rem;\n border-radius: 0.75rem;\n background: #0f1721;\n border: 1px solid #19222e;\n display: grid;\n place-items: center;\n color: #8fb3d9;\n cursor: pointer;\n transition: 0.16s box-shadow, 0.16s transform, 0.16s border-color;\n}\n\n.sb-btn.active {\n border-color: #2fd289;\n box-shadow: 0 0 0 0.125rem rgba(36, 208, 111, .25), 0 0.625rem 1.125rem rgba(36, 208, 111, .28);\n color: #2fd289;\n}\n\n.sb-ico {\n font-size: clamp(1.1rem, 1.2vw, 1.25rem);\n line-height: 1;\n}\n\n.sb-foot {\n font-size: clamp(0.6rem, 0.6vw, 0.7rem);\n color: #6c7b8d;\n letter-spacing: 0.12em;\n text-transform: uppercase;\n}\n\n.main {\nflex: 1;\noverflow: auto;\npadding: var(--content-pad);\nbackground: var(--bg-0); /* force dark background */\n}\n\n.container {\n max-width: var(--content-max);\n margin: 0 auto;\n display: flex;\n flex-direction: column;\n gap: var(--section-gap);\n}\n\n.card {\n background: linear-gradient(160deg, var(--panel) 0%, var(--panel-hi) 100%);\n border-radius: var(--radius);\n box-shadow: var(--shadow);\n}\n\n.label {\n color: var(--text);\n text-transform: uppercase;\n letter-spacing: 0.04em;\n font-weight: 700;\n font-size: var(--fs-label);\n text-align: center;\n}\n\n.kpis {\n display: grid;\n grid-template-columns: repeat(4, minmax(11.25rem, 1fr));\n gap: var(--section-gap);\n}\n\n.kpi {\n height: 6.25rem;\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: center;\n gap: 0.25rem;\n padding: var(--card-pad);\n}\n\n.kpi .label {\n font-size: var(--fs-label-lg);\n}\n\n.kval {\n display: flex;\n align-items: flex-end;\n gap: 0.3rem;\n color: var(--good);\n font-weight: 700;\n}\n.kpi .label {\ncolor: var(--good);\n}\n\n.knum {\n font-size: var(--fs-kpi);\n line-height: 1;\n}\n\n.kunit {\n font-size: var(--fs-kpi-unit);\n line-height: 1;\n}\n\n.panel {\n padding: var(--card-pad-lg);\n display: flex;\n flex-direction: column;\n gap: clamp(0.75rem, 0.9vw, 0.95rem);\n}\n\n.panel-title {\n font-size: var(--fs-section-title);\n text-transform: uppercase;\n letter-spacing: 0.05em;\n font-weight: 700;\n color: var(--text) !important;\n margin: 0;\n padding: 0;\n background: transparent !important;\n border: none;\n box-shadow: none;\n}\n\n.panel-strip {\n background: transparent;\n border: none;\n padding: 0;\n margin: 0;\n color: var(--text);\n}\n\n.row-3 {\n display: flex;\n gap: var(--section-gap);\n background: transparent;\n}\n\n.mini {\n flex: 1;\n min-height: 6.25rem;\n padding: var(--card-pad);\n display: flex;\n flex-direction: column;\n gap: 0.4rem;\n}\n\n.mini .val {\n font-size: var(--fs-body);\n color: var(--text);\n font-weight: 700;\n}\n.row-3 .mini {\nalign-items: center;\ntext-align: center;\n}\n\n.row-3 .mini .label {\nfont-size: var(--fs-label-lg);\n/* stays default color (white/muted) */\n}\n\n/* Only the value in green */\n.row-3 .mini .val {\nfont-size: clamp(1.1rem, 1.7vw, 1.7rem);\nfont-weight: 700;\ncolor: var(--good);\n}\n\n.progress {\n display: flex;\n align-items: center;\n gap: 0.4rem;\n}\n\n.track {\n flex: 1;\n height: var(--progress-height);\n background: #111a24;\n border-radius: 999px;\n overflow: hidden;\n box-shadow: inset 0 0.0625rem 0 rgba(255, 255, 255, .05);\n}\n\n.fill {\n height: 100%;\n width: 0;\n background: var(--good);\n transition: width 0.35s ease;\n}\n\n.pct {\n min-width: 3rem;\n text-align: right;\n color: var(--text);\n font-weight: 700;\n font-size: var(--fs-body);\n}\n\n.bottom {\n display: grid;\n grid-template-columns: repeat(3, minmax(0, 1fr));\n gap: var(--section-gap);\n}\n\n.gparts,\n.status,\n.start-wrap {\n min-height: clamp(9.375rem, 18vw, 11.25rem);\n padding: var(--card-pad-lg);\n display: flex;\n flex-direction: column;\n gap: 0.4rem;\n}\n\n.gnum {\n font-size: clamp(2.5rem, 3.2vw, 3.5rem);\n color: var(--good);\n font-weight: 700;\n}\n\n.gmeta {\n color: var(--muted);\n font-size: clamp(0.75rem, 0.9vw, 0.85rem);\n}\n\n.status {\n justify-content: center;\n gap: clamp(0.75rem, 1vw, 1rem);\n}\n\n.st-row {\n background: #121c28;\n border-radius: 0.625rem;\n border: 1px solid #243244;\n padding: 0.9rem 1rem;\n display: flex;\n align-items: center;\n justify-content: space-between;\n}\n\n.st-name {\n color: var(--text);\n font-weight: 600;\n font-size: var(--fs-body);\n}\n\n.st-val {\n font-weight: 700;\n font-size: clamp(1.25rem, 1.4vw, 1.5rem);\n text-transform: uppercase;\n}\n\n.st-on {\n color: var(--good);\n}\n\n.st-off {\n color: var(--bad);\n}\n\n.start-wrap {\n align-items: center;\n justify-content: center;\n padding: 0;\n}\n\n.start {\n width: 100%;\n height: 100%;\n min-height: var(--start-min-height);\n border-radius: var(--radius);\n border: none;\n background: linear-gradient(180deg, #32ff7e 0%, #2fd289 100%);\n color: var(--text);\n font-weight: 700;\n font-size: clamp(1.4rem, 2vw, 2rem);\n letter-spacing: 0.08em;\n text-transform: uppercase;\n box-shadow: 0 0 1.25rem rgba(36, 208, 111, .5), inset 0 0.0625rem 0 rgba(255, 255, 255, .1);\n cursor: pointer;\n transition: 0.16s transform, 0.16s filter;\n}\n\n.start:hover {\n transform: translateY(-0.05rem);\n filter: brightness(1.08);\n}\n.modal {\nposition: fixed;\ninset: 0;\ndisplay: flex;\nalign-items: center;\njustify-content: center;\nbackground: rgba(12, 17, 23, 0.82);\nbackdrop-filter: blur(4px);\nz-index: 999;\npadding: 2rem;\n}\n\n.modal.ng-hide {\ndisplay: none !important;\n}\n\n.modal-card {\nwidth: clamp(18rem, 32vw, 26rem);\nbackground: rgba(20, 30, 44, 0.94);\nborder-radius: 1rem;\nborder: 1px solid rgba(46, 163, 255, 0.35);\nbox-shadow: 0 1.25rem 2.5rem rgba(0, 0, 0, 0.45);\npadding: 1.75rem;\ndisplay: flex;\nflex-direction: column;\ngap: 0.75rem;\ncolor: var(--text);\n}\n\n.prompt-actions,\n.prompt-entry {\ndisplay: flex;\ngap: 0.75rem;\njustify-content: center;\n}\n\n.prompt-no,\n.prompt-yes,\n.prompt-entry button {\nflex: 1;\npadding: 0.9rem 1rem;\nborder-radius: 0.75rem;\nborder: none;\nfont-weight: 700;\ntext-transform: uppercase;\ncursor: pointer;\ntransition: transform 0.16s ease, filter 0.16s ease;\n}\n\n.prompt-no {\nbackground: rgba(36, 208, 111, 0.85);\ncolor: var(--text);\n}\n\n.prompt-yes,\n.prompt-entry button {\nbackground: rgba(46, 163, 255, 0.85);\ncolor: var(--text);\n}\n\n.prompt-entry input {\nflex: 1;\npadding: 0.85rem 1rem;\nborder-radius: 0.75rem;\nborder: 1px solid rgba(46, 163, 255, 0.35);\nbackground: rgba(15, 22, 33, 0.9);\ncolor: var(--text);\nfont-size: 1rem;\n}\n\n.start:active {\n transform: none;\n filter: brightness(0.96);\n}\n\n\n\n/* Override Node-RED Dashboard's gray backgrounds on text elements */\n.nr-dashboard-template p,\n.nr-dashboard-template h1,\n.nr-dashboard-template h2,\n.nr-dashboard-template h3,\n.nr-dashboard-template h4,\n.nr-dashboard-template label {\n background-color: transparent !important;\n}\n\n/* Scrap modal sizing - responsive */\n.modal-card-scrap {\n width: min(90vw, 28rem);\n max-height: 85vh;\n overflow-y: auto;\n}\n\n.wo-info {\n color: var(--accent);\n font-size: var(--fs-section-title);\n margin: 0.5rem 0;\n}\n\n.wo-summary {\n color: var(--muted);\n margin: 0.25rem 0 0.75rem;\n}\n\n.scrap-question {\n font-size: var(--fs-label-lg);\n text-align: center;\n margin-bottom: 0.75rem;\n color: var(--text);\n}\n\n/* Numpad styling */\n.numpad-container {\n display: flex;\n flex-direction: column;\n gap: 0.4rem;\n}\n\n.numpad-display {\n background: #0f1721;\n border: 2px solid var(--accent);\n border-radius: var(--radius);\n padding: 0.5rem;\n font-size: clamp(1rem, 4vw, 1.5rem);\n font-weight: 700;\n text-align: right;\n color: var(--text);\n min-height: 2rem;\n display: flex;\n align-items: center;\n justify-content: flex-end;\n word-break: break-all;\n overflow-wrap: anywhere;\n}\n\n.numpad-error {\n background: rgba(255, 77, 79, 0.2);\n border: 1px solid var(--bad);\n border-radius: var(--radius);\n padding: 0.5rem;\n color: var(--bad);\n text-align: center;\n font-size: var(--fs-body);\n margin-top: -0.3rem;\n}\n\n.numpad-grid {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n gap: 0.4rem;\n}\n\n.numpad-btn {\n background: linear-gradient(160deg, #1a2433 0%, #151e2b 100%);\n border: 1px solid #243244;\n border-radius: var(--radius);\n color: var(--text);\n font-size: clamp(1rem, 3vw, 1.4rem);\n font-weight: 700;\n padding: 0.5rem;\n cursor: pointer;\n transition: 0.16s transform, 0.16s filter;\n min-height: 2.5rem;\n}\n\n.numpad-btn:active {\n transform: scale(0.95);\n filter: brightness(1.2);\n}\n\n.numpad-clear,\n.numpad-back {\n background: linear-gradient(160deg, #2a1a1a 0%, #1f1515 100%);\n color: var(--warn);\n}\n\n.numpad-actions {\n display: flex;\n gap: 0.75rem;\n margin-top: 0.5rem;\n}\n\n.scrap-submit-btn {\n flex: 1;\n background: linear-gradient(180deg, #32ff7e 0%, #2fd289 100%);\n box-shadow: 0 0 1.25rem rgba(36, 208, 111, .5);\n border: none;\n border-radius: var(--radius);\n color: var(--text);\n padding: 0.5rem;\n font-weight: 700;\n font-size: clamp(0.85rem, 2vw, 1rem);\n text-transform: uppercase;\n cursor: pointer;\n transition: 0.16s transform, 0.16s filter;\n}\n\n.scrap-submit-btn:active {\n transform: scale(0.98);\n filter: brightness(1.1);\n}\n\n.reason-overlay {\n position: fixed;\n inset: 0;\n background: rgba(12, 17, 23, 0.82);\n backdrop-filter: blur(4px);\n z-index: 1200;\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 1rem;\n}\n\n.reason-card {\n width: min(90vw, 34rem);\n background: rgba(20, 30, 44, 0.96);\n border: 1px solid rgba(46, 163, 255, 0.35);\n border-radius: 1rem;\n box-shadow: 0 1rem 2.2rem rgba(0, 0, 0, 0.48);\n padding: 1rem;\n}\n\n.reason-title {\n margin: 0;\n color: var(--text);\n font-size: var(--fs-section-title);\n}\n\n.reason-breadcrumb {\n color: var(--muted);\n font-size: var(--fs-body);\n margin: 0.4rem 0 0.8rem;\n}\n\n.reason-grid {\n display: grid;\n grid-template-columns: repeat(2, minmax(0, 1fr));\n gap: 0.55rem;\n margin-bottom: 0.75rem;\n}\n\n.reason-option {\n min-height: 64px;\n border: 1px solid #243244;\n border-radius: var(--radius);\n background: #111a24;\n color: var(--text);\n font-weight: 700;\n padding: 0.65rem;\n text-align: left;\n cursor: pointer;\n}\n\n.reason-actions {\n display: flex;\n gap: 0.65rem;\n}\n\n.reason-btn {\n flex: 1;\n min-height: 52px;\n border-radius: var(--radius);\n border: none;\n font-weight: 700;\n text-transform: uppercase;\n cursor: pointer;\n}\n\n.reason-back {\n background: #32445a;\n color: var(--text);\n}\n\n.reason-cancel {\n background: rgba(255, 77, 79, 0.8);\n color: var(--text);\n}\n\n/* Updated button styles */\n.prompt-continue {\n flex: 1;\n padding: 1.2rem;\n border-radius: var(--radius);\n border: none;\n font-weight: 700;\n font-size: var(--fs-label);\n text-transform: uppercase;\n cursor: pointer;\n background: linear-gradient(180deg, #2ea3ff 0%, #1f8cf3 100%);\n color: var(--text);\n transition: 0.16s transform, 0.16s filter;\n}\n\n.prompt-continue:active {\n transform: scale(0.98);\n filter: brightness(1.1);\n}\n\n.prompt-yes {\n flex: 1;\n padding: 1.2rem;\n border-radius: var(--radius);\n border: none;\n font-weight: 700;\n font-size: var(--fs-label);\n text-transform: uppercase;\n cursor: pointer;\n background: linear-gradient(180deg, #ffd100 0%, #e6bd00 100%);\n color: var(--bg-0);\n transition: 0.16s transform, 0.16s filter;\n}\n\n.prompt-yes:active {\n transform: scale(0.98);\n filter: brightness(1.1);\n}\n\n/* STOP button styling */\n.start.stop-btn {\n background: linear-gradient(180deg, #ff4d4f 0%, #e63946 100%);\n box-shadow: 0 0 1.25rem rgba(255, 77, 79, .5);\n}\n\n.start.stop-btn:hover {\n filter: brightness(1.15);\n}\n\n/* Disabled START button */\n.start:disabled {\n background: linear-gradient(180deg, #3a3a3a 0%, #2a2a2a 100%);\n box-shadow: none;\n cursor: not-allowed;\n opacity: 0.5;\n}\n.start-col { \n display:flex; \n flex-direction:column; \n gap: .6rem; \n}\n\n.scrap-now {\nwidth: 100%;\npadding: 1rem;\nborder-radius: 16px;\nfont-weight: 800;\nborder: 2px solid rgba(255,255,255,.25);\nbackground: transparent;\ncolor: #fff;\n}\n\n.start:disabled:hover {\n transform: none;\n filter: none;\n}\n\n@media (max-width: 1366px) and (max-height: 900px) {\n:root {\nfont-size: 110%;\n--content-max: 60rem;\n}\n\n.kpi {\nheight: 5.5rem;\n}\n\n.gparts,\n.status,\n.start-wrap {\nmin-height: 8.5rem;\n}\n}\n .panel-title {\n color: var(--text) !important;\n }\n\n .mini .label {\n color: var(--text);\n }\n\n .mini .val {\n color: var(--good); /* your existing green */\n }\n \n.fab-mold{\n position: fixed;\n left: 1.2rem;\n bottom: 1.2rem;\n z-index: 2000;\n\n display: flex;\n align-items: center;\n gap: 0.55rem;\n\n padding: 0.9rem 1.1rem;\n border-radius: 999px;\n\n background: linear-gradient(180deg, #b58900 0%, #8a6500 100%);\n color: #0c1117;\n border: 1px solid rgba(255,255,255,.25);\n\n font-weight: 900;\n letter-spacing: 0.04em;\n text-transform: uppercase;\n\n box-shadow: 0 0.9rem 1.6rem rgba(0,0,0,.45);\n cursor: pointer;\n}\n.fab-mold:hover{ filter: brightness(1.1); }\n.fab-mold.fab-mold-end{\n background: linear-gradient(180deg, #22c55e 0%, #16a34a 100%);\n}\n\n.fab-scrap{\n position: fixed;\n right: 1.2rem;\n bottom: 1.2rem;\n z-index: 2000;\n\n display: flex;\n align-items: center;\n gap: 0.55rem;\n\n padding: 0.9rem 1.1rem;\n border-radius: 999px;\n\n background: linear-gradient(180deg, #ffb020 0%, #ff8a00 100%);\n color: #0c1117;\n border: 1px solid rgba(255,255,255,.25);\n\n font-weight: 900;\n letter-spacing: 0.04em;\n text-transform: uppercase;\n\n box-shadow: 0 0.9rem 1.6rem rgba(0,0,0,.45),\n 0 0 0 0.15rem rgba(255, 176, 32, 0.22);\n cursor: pointer;\n transition: transform .12s ease, filter .12s ease, opacity .12s ease;\n }\n\n .fab-scrap:hover{\n filter: brightness(1.06);\n transform: translateY(-1px);\n }\n\n .fab-scrap:active{\n transform: translateY(0);\n filter: brightness(.98);\n }\n\n .fab-scrap[disabled],\n .fab-scrap:disabled{\n opacity: 0.35;\n cursor: not-allowed;\n transform: none;\n filter: none;\n }\n\n</style>\n<div id=\"oee\">\n <aside class=\"sidebar\">\n <div class=\"side-top\">\n <button class=\"sb-btn active\" data-label=\"Home\" ng-click=\"gotoTab('Home')\"><span class=\"sb-ico\">🏠</span></button>\n <button class=\"sb-btn\" data-label=\"Work Orders\" ng-click=\"gotoTab('Work Orders')\"><span class=\"sb-ico\">📋</span></button>\n <button class=\"sb-btn\" data-label=\"Alerts\" ng-click=\"gotoTab('Alerts')\"><span class=\"sb-ico\">⚠️</span></button>\n<!-- <button class=\"sb-btn\" data-label=\"Graphs\" ng-click=\"gotoTab('Graphs')\"><span class=\"sb-ico\">📊</span></button> -->\n <button class=\"sb-btn\" data-label=\"Help\" ng-click=\"gotoTab('Help')\"><span class=\"sb-ico\">❓</span></button>\n <button class=\"sb-btn\" data-label=\"Settings\" ng-click=\"gotoTab('Settings')\"><span class=\"sb-ico\">⚙️</span></button>\n </div>\n <div class=\"sb-foot\">OEE V1.0</div>\n </aside>\n\n <main class=\"main\">\n <div class=\"container\">\n <section class=\"kpis\">\n <article class=\"card kpi\">\n <div class=\"label\">OEE</div>\n <div class=\"kval\"><span id=\"kpi-oee-value\" class=\"knum\">0</span><span class=\"kunit\">%</span></div>\n </article>\n <article class=\"card kpi\">\n <div class=\"label\">Disponibilidad</div>\n <div class=\"kval\"><span id=\"kpi-availability-value\" class=\"knum\">0</span><span class=\"kunit\">%</span></div>\n </article>\n <article class=\"card kpi\">\n <div class=\"label\">Rendimiento</div>\n <div class=\"kval\"><span id=\"kpi-performance-value\" class=\"knum\">0</span><span class=\"kunit\">%</span></div>\n </article>\n <article class=\"card kpi\">\n <div class=\"label\">Calidad</div>\n <div class=\"kval\"><span id=\"kpi-quality-value\" class=\"knum\">0</span><span class=\"kunit\">%</span></div>\n </article>\n </section>\n\n <section class=\"card panel\">\n <div class=\"panel-strip\"><h2 class=\"panel-title\">Orden de trabajo actual</h2></div>\n <div class=\"row-3\">\n <div class=\"card mini\">\n <div class=\"label\">ID Orden trabajo</div>\n <div id=\"workorder-id\" class=\"val\"> </div>\n </div>\n <div class=\"card mini\">\n <div class=\"label\">SKU</div>\n <div id=\"workorder-sku\" class=\"val\"> </div>\n </div>\n <div class=\"card mini\">\n <div class=\"label\">Tiempo de ciclo</div>\n <div id=\"workorder-cycle\" class=\"val\">0</div>\n </div>\n </div>\n <div class=\"progress\">\n <div class=\"track\"><div id=\"workorder-progress-fill\" class=\"fill\"></div></div>\n <div id=\"workorder-progress-percent\" class=\"pct\">0%</div>\n </div>\n </section>\n\n <section class=\"bottom\">\n <article class=\"card gparts\">\n <div class=\"label\">Piezas buenas</div>\n <div id=\"good-parts-value\" class=\"gnum\">0</div>\n <div id=\"good-parts-meta\" class=\"gmeta\">de 0</div>\n </article>\n\n <article class=\"card status\">\n <div class=\"st-row\"><span class=\"st-name\">Maquina</span><span id=\"machine-state\" class=\"st-val st-off\">OFFLINE</span></div>\n <div class=\"st-row\"><span class=\"st-name\">Producción</span><span id=\"production-state\" class=\"st-val st-off\">DETENIDA</span></div>\n </article>\n\n \n <div ng-show=\"moldChange.active\" class=\"mold-change-banner\" style=\"background:#3b2a00;border:1px solid #b58900;color:#fde68a;padding:10px 14px;border-radius:12px;margin:8px 0;font-weight:600;\">\n Cambio de molde en curso desde {{ moldChange.startMs | date:'HH:mm' }} · {{ moldChangeElapsedMin() }} min\n </div>\n<article class=\"card start-wrap\">\n <button id=\"start-button\" type=\"button\" class=\"start\"\n ng-click=\"toggleStartStop()\"\n ng-class=\"{'stop-btn': isProductionRunning}\"\n ng-disabled=\"!hasActiveOrder && !isProductionRunning\">\n {{ isProductionRunning ? 'DETENER' : 'COMENZAR' }}\n </button>\n </article>\n\n </section>\n </div>\n \n<!-- MOLD CHANGE FAB -->\n<button class=\"fab-mold\"\n ng-click=\"startMoldChange()\"\n ng-show=\"!moldChange.active && !isProductionRunning\"\n title=\"Iniciar cambio de molde\">\n Cambio de molde\n</button>\n<button class=\"fab-mold fab-mold-end\"\n ng-click=\"endMoldChange()\"\n ng-show=\"moldChange.active\"\n title=\"Finalizar cambio de molde\">\n Finalizar cambio\n</button>\n\n <button class=\"fab-scrap\"\n ng-click=\"openManualScrapPrompt()\"\n ng-disabled=\"!hasActiveOrder\"\n title=\"Registrar scrap\">\n Scrap\n </button>\n\n </main>\n\n\n<!-- Resume/Restart Prompt Modal -->\n<div id=\"resume-modal\" class=\"modal\" ng-show=\"resumePrompt.show\">\n <div class=\"modal-card\">\n <h2>Orden de trabajo en proceso</h2>\n <p class=\"wo-info\">{{ resumePrompt.id }}</p>\n <p class=\"wo-summary\">\n <strong>{{ resumePrompt.goodParts }}</strong> of <strong>{{ resumePrompt.targetQty }}</strong> partes completadas\n ({{ resumePrompt.progressPercent }}%)\n </p>\n <p class=\"wo-summary\">Ciclos: <strong>{{ resumePrompt.cycleCount }}</strong></p>\n\n <div style=\"margin-top: 1.5rem; display: flex; flex-direction: column; gap: 0.75rem;\">\n <button class=\"prompt-continue\" ng-click=\"resumeWorkOrder()\">\n Reaundar de {{ resumePrompt.goodParts }} piezas\n </button>\n <button class=\"prompt-yes\" ng-click=\"confirmRestart()\">\n Reanudar de 0 (Advertencia: Progreso se perdera!)\n </button>\n </div>\n </div>\n</div>\n<div id=\"scrap-modal\" class=\"modal\" ng-show=\"scrapPrompt.show\">\n <div class=\"modal-card modal-card-scrap\">\n <h2>{{ scrapPrompt.title || 'Orden de trabajo completada' }}</h2>\n <p class=\"wo-info\">{{ scrapPrompt.orderId }}</p>\n <p class=\"wo-summary\">\n Producido <strong>{{ scrapPrompt.produced }}</strong> de <strong>{{ scrapPrompt.target }}</strong> piezas\n </p>\n\n <p class=\"wo-summary\" ng-if=\"scrapPrompt.manual\">\n Scrap acumulado: <strong>{{ scrapPrompt.scrapSoFar }}</strong>\n </p>\n\n <div class=\"scrap-question\">\n {{ scrapPrompt.manual ? '¿Cuántas piezas de scrap quieres agregar ahora?' : 'Hubo piezas de scrap?' }}\n </div>\n\n <!-- Numpad interface -->\n <div class=\"numpad-container\" ng-if=\"scrapPrompt.enterMode\">\n <div class=\"numpad-display\">{{ scrapPrompt.scrapCount || 0 }}</div>\n <div class=\"numpad-error\" ng-if=\"scrapPrompt.error\">{{ scrapPrompt.error }}</div>\n\n <div class=\"numpad-grid\">\n <button class=\"numpad-btn\" ng-click=\"addDigit(7)\">7</button>\n <button class=\"numpad-btn\" ng-click=\"addDigit(8)\">8</button>\n <button class=\"numpad-btn\" ng-click=\"addDigit(9)\">9</button>\n\n <button class=\"numpad-btn\" ng-click=\"addDigit(4)\">4</button>\n <button class=\"numpad-btn\" ng-click=\"addDigit(5)\">5</button>\n <button class=\"numpad-btn\" ng-click=\"addDigit(6)\">6</button>\n\n <button class=\"numpad-btn\" ng-click=\"addDigit(1)\">1</button>\n <button class=\"numpad-btn\" ng-click=\"addDigit(2)\">2</button>\n <button class=\"numpad-btn\" ng-click=\"addDigit(3)\">3</button>\n\n <button class=\"numpad-btn numpad-clear\" ng-click=\"clearScrap()\">C</button>\n <button class=\"numpad-btn\" ng-click=\"addDigit(0)\">0</button>\n <button class=\"numpad-btn numpad-back\" ng-click=\"backspace()\">⌫</button>\n </div>\n\n <div class=\"numpad-actions\">\n <button class=\"scrap-submit-btn\" ng-click=\"submitScrapValidated(scrapPrompt.scrapCount)\">\n Enviar Scrap\n </button>\n </div>\n </div>\n\n <!-- Initial choice buttons -->\n <div class=\"prompt-actions\" ng-if=\"!scrapPrompt.enterMode\">\n <!-- Don't ask again checkbox -->\n <div style=\"display: flex; align-items: center; justify-content: center; gap: 0.5rem; margin-bottom: 0.75rem;\">\n <input type=\"checkbox\" id=\"remind-checkbox\" ng-model=\"scrapPrompt.remindAgain\" style=\"width: 1.2rem; height: 1.2rem; cursor: pointer;\">\n <label for=\"remind-checkbox\" style=\"cursor: pointer; margin: 0; font-size: var(--fs-body); color: var(--muted);\">\n Recuerdame si seguimos sobreproduciendo\n </label>\n </div>\n\n <button class=\"prompt-continue\" ng-click=\"skipScrap()\">\n No, continuar producción\n </button>\n <button class=\"prompt-yes\" ng-click=\"openScrapEntry()\">\n Si, Enviar Scrap\n </button>\n </div>\n </div>\n</div>\n\n<div class=\"reason-overlay\" ng-if=\"scrapReasonPrompt.show\">\n <div class=\"reason-card\">\n <h3 class=\"reason-title\">Selecciona razón de scrap</h3>\n <div class=\"reason-breadcrumb\">\n Paso {{ scrapReasonPrompt.step }} de 2\n <span ng-if=\"scrapReasonPrompt.selectedCategory\"> | {{ scrapReasonPrompt.selectedCategory.label }}</span>\n </div>\n\n <div class=\"reason-grid\" ng-if=\"scrapReasonPrompt.step === 1\">\n <button class=\"reason-option\" ng-repeat=\"c in scrapReasonPrompt.categories\" ng-click=\"pickScrapReasonCategory(c)\">\n {{ c.label }}\n </button>\n </div>\n\n <div class=\"reason-grid\" ng-if=\"scrapReasonPrompt.step === 2\">\n <button class=\"reason-option\" ng-repeat=\"d in scrapReasonPrompt.details\" ng-click=\"confirmScrapReason(d)\">\n {{ d.label }}\n </button>\n </div>\n\n <div class=\"reason-actions\">\n <button class=\"reason-btn reason-back\" ng-if=\"scrapReasonPrompt.step === 2\" ng-click=\"scrapReasonPrompt.step = 1\">Atrás</button>\n <button class=\"reason-btn reason-cancel\" ng-click=\"cancelScrapReasonPrompt()\">Cancelar</button>\n </div>\n </div>\n</div>\n</div>\n\n<script>\n(function(scope) {\n scope.gotoTab = function(tabName) {\n scope.send({ ui_control: { tab: tabName } });\n };\n\n // Phase 7: Tab activation listener - refresh data when returning to Home\n scope.$on('$destroy', function() {\n if (scope.tabRefreshInterval) {\n clearInterval(scope.tabRefreshInterval);\n }\n });\n\n // Request current state when tab becomes visible\n scope.refreshHomeData = function() {\n scope.send({ action: \"get-current-state\" });\n };\n\n // Poll for updates when on Home tab (every 2 seconds)\n // This ensures UI stays fresh when returning from other tabs\nscope.tabRefreshInterval = setInterval(function() {\n var homeElement = document.getElementById('oee');\n if (homeElement) {\n scope.refreshHomeData();\n }\n}, 500);\n\n\n window.kpiOeePercent = window.kpiOeePercent || 0;\n window.kpiAvailabilityPercent = window.kpiAvailabilityPercent || 0;\n window.kpiPerformancePercent = window.kpiPerformancePercent || 0;\n window.kpiQualityPercent = window.kpiQualityPercent || 0;\n window.currentWorkOrderId = window.currentWorkOrderId || \"\";\n window.currentSku = window.currentSku || \"\";\n window.currentCycleTime = window.currentCycleTime || 0;\n window.currentProgressPercent = window.currentProgressPercent || 0;\n window.goodPartsCount = window.goodPartsCount || 0;\n window.goodPartsTarget = window.goodPartsTarget || 0;\n window.machineOnline = typeof window.machineOnline === \"boolean\" ? window.machineOnline : false;\n window.productionStarted = typeof window.productionStarted === \"boolean\" ? window.productionStarted : false;\n\n var elements = {\n kpiOee: document.getElementById(\"kpi-oee-value\"),\n kpiAvailability: document.getElementById(\"kpi-availability-value\"),\n kpiPerformance: document.getElementById(\"kpi-performance-value\"),\n kpiQuality: document.getElementById(\"kpi-quality-value\"),\n workOrderId: document.getElementById(\"workorder-id\"),\n workOrderSku: document.getElementById(\"workorder-sku\"),\n workOrderCycle: document.getElementById(\"workorder-cycle\"),\n progressFill: document.getElementById(\"workorder-progress-fill\"),\n progressPercent: document.getElementById(\"workorder-progress-percent\"),\n goodPartsValue: document.getElementById(\"good-parts-value\"),\n goodPartsMeta: document.getElementById(\"good-parts-meta\"),\n machineState: document.getElementById(\"machine-state\"),\n productionState: document.getElementById(\"production-state\"),\n startButton: document.getElementById(\"start-button\")\n };\n\n function setText(el, value) {\n if (el) {\n el.textContent = value;\n }\n }\n\n function setNumber(el, value) {\n setText(el, String(Math.max(0, Math.round(Number(value) || 0))));\n }\n\n function clampPercent(value) {\n var num = Number(value) || 0;\n return Math.max(0, Math.min(100, Math.round(num)));\n }\n\n function updateState(el, isActive, onLabel, offLabel) {\n if (!el) {\n return;\n }\n el.textContent = isActive ? onLabel : offLabel;\n el.classList.remove(\"st-on\", \"st-off\");\n el.classList.add(isActive ? \"st-on\" : \"st-off\");\n }\n\n function renderDashboard() {\n setNumber(elements.kpiOee, window.kpiOeePercent);\n setNumber(elements.kpiAvailability, window.kpiAvailabilityPercent);\n setNumber(elements.kpiPerformance, window.kpiPerformancePercent);\n setNumber(elements.kpiQuality, window.kpiQualityPercent);\n\n setText(elements.workOrderId, window.currentWorkOrderId || \"\");\n setText(elements.workOrderSku, window.currentSku || \"\");\n setText(elements.workOrderCycle, window.currentCycleTime ? String(window.currentCycleTime) : \"0\");\n\n var progress = clampPercent(window.currentProgressPercent);\n if (elements.progressFill) {\n elements.progressFill.style.width = progress + \"%\";\n }\n setText(elements.progressPercent, progress + \"%\");\n\n setText(elements.goodPartsValue, String(window.goodPartsCount || 0));\n setText(elements.goodPartsMeta, \" de \" + String(window.goodPartsTarget || 0));\n\n updateState(elements.machineState, !!window.machineOnline, \"ONLINE\", \"OFFLINE\");\n updateState(elements.productionState, !!window.productionStarted, \"STARTED\", \"STOPPED\");\n }\n\n scope.renderDashboard = renderDashboard;\n\n scope.reasonCatalog = {\n version: 1,\n downtime: [],\n scrap: []\n };\n scope.pendingScrapEntry = null;\n scope.scrapReasonPrompt = {\n show: false,\n step: 1,\n categories: [],\n details: [],\n selectedCategory: null\n };\n\n function normalizeReasonCatalog(raw) {\n if (!raw || !Array.isArray(raw.scrap) || raw.scrap.length === 0) {\n return {\n version: 1,\n downtime: [],\n scrap: [\n {\n id: \"scrap-general\",\n label: \"General\",\n children: [{ id: \"scrap-sin-detalle\", label: \"Sin detalle\" }]\n }\n ]\n };\n }\n return raw;\n }\n scope.normalizeReasonCatalog = normalizeReasonCatalog;\n\n scope.scrapPrompt = {\n show:false, enterMode:false,\n orderId:'', sku:'', target:0, produced:0,\n scrapSoFar: 0,\n scrapCount:0, remindAgain:false,\n manual:false,\n title:'',\n validateMax:true\n };\n\n scope.cancelScrapReasonPrompt = function() {\n scope.scrapReasonPrompt.show = false;\n scope.scrapReasonPrompt.step = 1;\n scope.scrapReasonPrompt.selectedCategory = null;\n scope.scrapReasonPrompt.details = [];\n };\n\n scope.pickScrapReasonCategory = function(category) {\n scope.scrapReasonPrompt.selectedCategory = category;\n scope.scrapReasonPrompt.details = Array.isArray(category.children) ? category.children : [];\n scope.scrapReasonPrompt.step = 2;\n };\n\n scope.confirmScrapReason = function(detail) {\n if (!scope.pendingScrapEntry || !scope.scrapReasonPrompt.selectedCategory || !detail) return;\n const c = scope.scrapReasonPrompt.selectedCategory;\n scope.send({\n action: \"scrap-entry-with-reason\",\n payload: {\n id: scope.pendingScrapEntry.id,\n scrap: scope.pendingScrapEntry.scrap,\n reasonType: \"scrap\",\n reasonPath: [\n { id: c.id || null, label: c.label || null },\n { id: detail.id || null, label: detail.label || null }\n ],\n reasonText: [c.label || \"\", detail.label || \"\"].filter(Boolean).join(\" > \"),\n catalogVersion: scope.reasonCatalog.version || null,\n tsMs: Date.now()\n }\n });\n scope.pendingScrapEntry = null;\n scope.cancelScrapReasonPrompt();\n };\n\n // Numpad digit entry\n scope.addDigit = function(digit) {\n scope.scrapPrompt.error = '';\n const current = String(scope.scrapPrompt.scrapCount || 0);\n const newValue = current === '0' ? String(digit) : current + String(digit);\n scope.scrapPrompt.scrapCount = Number(newValue);\n };\n\n // Clear scrap count\n scope.clearScrap = function() {\n scope.scrapPrompt.scrapCount = 0;\n scope.scrapPrompt.error = '';\n };\n\n // Backspace\n scope.backspace = function() {\n scope.scrapPrompt.error = '';\n const current = String(scope.scrapPrompt.scrapCount || 0);\n const newValue = current.length > 1 ? current.slice(0, -1) : '0';\n scope.scrapPrompt.scrapCount = Number(newValue);\n };\n\n // Open scrap entry (validate and show numpad)\n scope.openScrapEntry = function() {\n scope.scrapPrompt.enterMode = true;\n scope.scrapPrompt.scrapCount = 0;\n scope.scrapPrompt.error = '';\n };\n\n scope.openManualScrapPrompt = function() {\n if (!scope.hasActiveOrder) return;\n scope.send({ action: 'scrap-open' }); // backend uses state.activeWorkOrder\n };\n\n // Skip scrap (No, Continue)\n scope.skipScrap = function() {\n scope.send({\n action: 'scrap-skip',\n payload: {\n id: scope.scrapPrompt.orderId,\n remindAgain: !!scope.scrapPrompt.remindAgain\n }\n });\n scope.scrapPrompt.show = false;\n scope.scrapPrompt.enterMode = false;\n scope.scrapPrompt.remindAgain = false;\n scope.scrapPrompt.error = '';\n };\n\n\n // ===== MOLD CHANGE =====\n scope.moldChange = { active: false, startMs: null, fromMoldId: null };\n scope.startMoldChange = function() {\n if (scope.isProductionRunning) return;\n if (scope.moldChange.active) return;\n scope.send({ action: \"start-mold-change\", payload: { fromMoldId: null } });\n };\n scope.endMoldChange = function() {\n if (!scope.moldChange.active) return;\n scope.send({ action: \"end-mold-change\", payload: {} });\n };\n scope.moldChangeElapsedMin = function() {\n if (!scope.moldChange.active || !scope.moldChange.startMs) return 0;\n return Math.max(0, Math.round((Date.now() - scope.moldChange.startMs) / 60000));\n };\n\n // START/STOP toggle\n //scope.isProductionRunning = false;\n //scope.hasActiveOrder = false;\n\n scope.toggleStartStop = function() {\n if (scope.isProductionRunning) {\n // STOP production - pause tracking (work order stays active)\n scope.send({ action: \"stop\" });\n scope.isProductionRunning = false;\n isProductionRunning: scope.isProductionRunning\n // Keep hasActiveOrder=true so button stays enabled (resume pattern)\n } else {\n // START/RESUME production - send start action to backend\n scope.send({ action: \"start\" });\n scope.isProductionRunning = true;\n isProductionRunning: scope.isProductionRunning\n }\n };\n // Submit scrap with validation\n scope.submitScrapValidated = function(scrapCount) {\n scrapCount = Math.max(0, Number(scrapCount) || 0);\n\n if (scope.scrapPrompt.validateMax && scrapCount > scope.scrapPrompt.produced) {\n scope.scrapPrompt.error =\n \"Scrap cannot exceed produced quantity (\" + scope.scrapPrompt.produced + \")\";\n return;\n }\n scope.pendingScrapEntry = {\n id: scope.scrapPrompt.orderId,\n scrap: scrapCount\n };\n scope.scrapPrompt.show = false;\n scope.scrapPrompt.enterMode = false;\n scope.scrapPrompt.remindAgain = false;\n scope.scrapPrompt.scrapCount = 0;\n scope.scrapPrompt.error = \"\";\n\n var catalog = normalizeReasonCatalog(scope.reasonCatalog);\n scope.reasonCatalog = catalog;\n scope.scrapReasonPrompt.show = true;\n scope.scrapReasonPrompt.step = 1;\n scope.scrapReasonPrompt.selectedCategory = null;\n scope.scrapReasonPrompt.details = [];\n scope.scrapReasonPrompt.categories = Array.isArray(catalog.scrap) ? catalog.scrap : [];\n};\n\n\n\n renderDashboard();\n\n\n})(scope);\n\n(function ensureNoMaterialTint(){\n const root = document.getElementById('oee');\n if (!root) return;\n\n const targets = root.querySelectorAll([\n '.md-toolbar',\n 'md-toolbar',\n '.md-subheader',\n 'md-subheader',\n '.md-toolbar-tools',\n '.md-card-title'\n ].join(','));\n\n targets.forEach(el => {\n if (el && el.style) {\n if (el.style.background) {\n el.style.background = 'transparent';\n }\n if (el.style.backgroundColor) {\n el.style.backgroundColor = 'transparent';\n }\n }\n if (el && el.classList) {\n el.classList.remove(\n 'md-whiteframe-1dp','md-whiteframe-2dp','md-whiteframe-3dp',\n 'md-whiteframe-z1','md-whiteframe-z2','md-whiteframe-z3'\n );\n }\n });\n\n if (!document.getElementById('oee-theme-sentinel')) {\n const style = document.createElement('style');\n style.id = 'oee-theme-sentinel';\n style.textContent = `\n #oee .md-toolbar::before, #oee .md-toolbar::after,\n #oee .md-subheader::before, #oee .md-subheader::after,\n #oee md-toolbar::before, #oee md-toolbar::after,\n #oee md-subheader::before, #oee md-subheader::after {\n display: none !important;\n content: none !important;\n }\n `;\n document.head.appendChild(style);\n }\n\n scope.$evalAsync(scope.renderDashboard);\n\n})(scope);\n\n\n// optional render trigger\n\n</script>\n<script>\n(function killMaterialTintsLive(){\nconst root = document.getElementById('oee');\nif (!root) return;\n\nconst zap = (el) => {\nif (!el) return;\nel.style.background = 'transparent';\nel.style.backgroundColor = 'transparent';\nel.style.boxShadow = 'none';\n};\n\nconst sel = [\n'.md-subheader','md-subheader','.md-toolbar','md-toolbar',\n'.md-card-title','.md-sticky-clone','._md-sticky-clone',\n'.nr-dashboard-template md-content','md-content'\n].join(',');\n\n// Clean anything present now\nroot.querySelectorAll(sel).forEach(zap);\n\n// Clean future clones dynamically\nconst mo = new MutationObserver((muts) => {\nfor (const m of muts) {\nm.addedNodes && m.addedNodes.forEach(n => {\nif (!(n instanceof HTMLElement)) return;\nif (n.matches && n.matches(sel)) zap(n);\nn.querySelectorAll && n.querySelectorAll(sel).forEach(zap);\n});\n}\n});\nmo.observe(document.body, { childList: true, subtree: true });\n})();\n\n\n\n (function(scope) {\n scope.$watch('msg', function(msg) {\n if (!msg) {\n return;\n }\n\n // Handle current state updates (from tab refresh)\n if (msg.topic === 'currentState' && msg.payload) {\n var state = msg.payload;\n if (state.reasonCatalog) {\n scope.reasonCatalog = scope.normalizeReasonCatalog(state.reasonCatalog);\n }\n \n if (state.activeWorkOrder) {\n window.currentWorkOrderId = state.activeWorkOrder.id || \"\";\n window.currentSku = state.activeWorkOrder.sku || \"\";\n window.currentCycleTime = state.activeWorkOrder.cycleTime || 0;\n window.goodPartsCount = state.activeWorkOrder.goodParts || 0;\n window.goodPartsTarget = state.activeWorkOrder.target || 0;\n window.currentProgressPercent = state.activeWorkOrder.progressPercent || 0;\n }\n \n if (state.kpis) {\n window.kpiOeePercent = state.kpis.oee || 0;\n window.kpiAvailabilityPercent = state.kpis.availability || 0;\n window.kpiPerformancePercent = state.kpis.performance || 0;\n window.kpiQualityPercent = state.kpis.quality || 0;\n }\n \n scope.isProductionRunning = state.trackingEnabled || false;\n scope.hasActiveOrder = !!state.activeWorkOrder;\n window.productionStarted = state.productionStarted;\n \n scope.renderDashboard();\n return;\n }\n\n if (msg.topic === \"reasonCatalogData\") {\n scope.reasonCatalog = scope.normalizeReasonCatalog(msg.payload || null);\n return;\n }\n\n \n // Handle resume prompt\n if (msg.topic === 'resumePrompt' && msg.payload) {\n // ✨ FIX: usar setTimeout + $apply para forzar el digest cycle correctamente\n // El $evalAsync no funciona en este contexto del Node-RED Dashboard\n console.log('[RESUME-PROMPT-UI] received:', JSON.stringify(msg.payload));\n setTimeout(function() {\n console.log('[RESUME-PROMPT-UI] inside setTimeout');\n scope.$apply(function() {\n console.log('[RESUME-PROMPT-UI] inside $apply');\n if (!scope.resumePrompt) {\n scope.resumePrompt = {\n show: false, id: '', sku: '',\n cycleCount: 0, goodParts: 0, targetQty: 0,\n progressPercent: 0, order: null\n };\n }\n scope.resumePrompt.show = true;\n console.log('[RESUME-PROMPT-UI] show ahora es:', scope.resumePrompt.show);\n scope.resumePrompt.id = msg.payload.id || '';\n scope.resumePrompt.sku = msg.payload.sku || '';\n scope.resumePrompt.cycleCount = msg.payload.cycleCount || 0;\n scope.resumePrompt.goodParts = msg.payload.goodParts || 0;\n scope.resumePrompt.targetQty = msg.payload.targetQty || 0;\n scope.resumePrompt.progressPercent = msg.payload.progressPercent || 0;\n scope.resumePrompt.order = msg.payload.order || null;\n if (scope.gotoTab) scope.gotoTab(\"Home\");\n });\n }, 0);\n return;\n }\n\n if (msg.topic === 'moldChangeStatus' && msg.payload) {\n console.log('[MOLD-CHANGE-STATUS] received:', JSON.stringify(msg.payload));\n console.log('[MOLD-CHANGE-STATUS] startMs as date:', new Date(msg.payload.startMs).toLocaleString());\n scope.moldChange = {\n active: !!msg.payload.active,\n startMs: msg.payload.startMs || null,\n fromMoldId: msg.payload.fromMoldId || null\n };\n return;\n }\n\n if (msg.topic === 'machineStatus') {\n \n // ===== UPDATE PRODUCTION STATE =====\n if (msg.payload.trackingEnabled !== undefined) {\n scope.isProductionRunning = msg.payload.trackingEnabled;\n }\n if (msg.payload.productionStarted !== undefined) {\n window.productionStarted = msg.payload.productionStarted;\n }\n if (msg.payload.machineOnline !== undefined) {\n window.machineOnline = msg.payload.machineOnline;\n }\n\n // ===== UPDATE KPI DISPLAYS =====\n if (msg.payload && msg.payload.kpis) {\n var kpis = msg.payload.kpis;\n\n // Update OEE\n if (window.kpiOeePercent !== kpis.oee) {\n window.kpiOeePercent = kpis.oee;\n var oeeEl = document.getElementById('kpi-oee-value');\n if (oeeEl) oeeEl.textContent = kpis.oee.toFixed(1) + '%';\n }\n\n // Update Availability\n if (window.kpiAvailabilityPercent !== kpis.availability) {\n window.kpiAvailabilityPercent = kpis.availability;\n var availEl = document.getElementById('kpi-availability-value');\n if (availEl) availEl.textContent = kpis.availability.toFixed(1) + '%';\n }\n\n // Update Performance\n if (window.kpiPerformancePercent !== kpis.performance) {\n window.kpiPerformancePercent = kpis.performance;\n var perfEl = document.getElementById('kpi-performance-value');\n if (perfEl) perfEl.textContent = kpis.performance.toFixed(1) + '%';\n }\n\n // Update Quality\n if (window.kpiQualityPercent !== kpis.quality) {\n window.kpiQualityPercent = kpis.quality;\n var qualEl = document.getElementById('kpi-quality-value');\n if (qualEl) qualEl.textContent = kpis.quality.toFixed(1) + '%';\n }\n }\n\n window.machineOnline = msg.payload.machineOnline;\n window.productionStarted = msg.payload.productionStarted;\n scope.renderDashboard();\n return;\n }\n if (msg.topic === 'activeWorkOrder') {\n const order = msg.payload || {};\n if (!order || !order.id) {\n window.currentWorkOrderId = \"\";\n window.currentSku = \"\";\n window.currentCycleTime = 0;\n window.currentProgressPercent = 0;\n window.goodPartsCount = 0;\n window.goodPartsTarget = 0;\n } else {\n window.currentWorkOrderId = order.id || \"\";\n window.currentSku = order.sku || \"\";\n window.currentCycleTime = Number(order.cycleTime) || 0;\n window.currentProgressPercent = Number(order.progressPercent) || 0;\n window.goodPartsCount = Number(order.goodParts) || 0;\n window.goodPartsTarget = Number(order.target) || 0;\n }\n \n // ===== UPDATE KPI DISPLAYS =====\n if (order.kpis) {\n var kpis = order.kpis;\n \n // Update OEE\n window.kpiOeePercent = kpis.oee || 0;\n var oeeEl = document.getElementById('kpi-oee-value');\n if (oeeEl) oeeEl.textContent = (kpis.oee || 0).toFixed(1) + '%';\n \n // Update Availability\n window.kpiAvailabilityPercent = kpis.availability || 0;\n var availEl = document.getElementById('kpi-availability-value');\n if (availEl) availEl.textContent = (kpis.availability || 0).toFixed(1) + '%';\n \n // Update Performance\n window.kpiPerformancePercent = kpis.performance || 0;\n var perfEl = document.getElementById('kpi-performance-value');\n if (perfEl) perfEl.textContent = (kpis.performance || 0).toFixed(1) + '%';\n \n // Update Quality\n window.kpiQualityPercent = kpis.quality || 0;\n var qualEl = document.getElementById('kpi-quality-value');\n if (qualEl) qualEl.textContent = (kpis.quality || 0).toFixed(1) + '%';\n }\n \n // Update START button availability\n scope.hasActiveOrder = !!(order && order.id);\n if (!order.id) {\n scope.isProductionRunning = false;\n }\n scope.renderDashboard();\n }\n if (!scope.scrapPrompt) {\n scope.scrapPrompt = {\n show:false, enterMode:false,\n orderId:'', sku:'', target:0, produced:0,\n scrapSoFar: 0,\n scrapCount:0, remindAgain:false,\n manual:false,\n title:'',\n validateMax:true\n };\n }\n \n if (msg.topic === \"scrapPrompt\") {\n const p = msg.payload || {};\n if (p.reasonCatalog) {\n scope.reasonCatalog = scope.normalizeReasonCatalog(p.reasonCatalog);\n }\n\n scope.scrapPrompt.show = true;\n\n // NEW: respect payload\n scope.scrapPrompt.manual = !!p.manual;\n scope.scrapPrompt.title = p.title || \"\";\n scope.scrapPrompt.validateMax = (p.validateMax !== false);\n scope.scrapPrompt.enterMode = !!p.enterMode;\n\n scope.scrapPrompt.orderId = p.id || \"\";\n scope.scrapPrompt.sku = p.sku || \"\";\n scope.scrapPrompt.target = Number(p.target) || 0;\n scope.scrapPrompt.produced = Number(p.produced) || 0;\n scope.scrapPrompt.scrapSoFar = Number(p.scrapSoFar) || 0;\n\n scope.scrapPrompt.scrapCount = 0;\n scope.scrapPrompt.remindAgain = false;\n scope.scrapPrompt.error = \"\";\n\n if (scope.gotoTab) scope.gotoTab(\"Home\");\n scope.$evalAsync();\n return;\n }\n\n scope.submitScrap = function(scrapCount) {\n scope.submitScrapValidated(scrapCount);\n };\n });\n\n // Resume/Restart Prompt State\n scope.resumePrompt = {\n show: false,\n id: '',\n sku: '',\n cycleCount: 0,\n goodParts: 0,\n targetQty: 0,\n progressPercent: 0,\n order: null\n };\n\n scope.resumeWorkOrder = function() {\n if (!scope.resumePrompt.order) {\n console.error('No order data for resume');\n return;\n }\n\n scope.send({\n action: 'resume-work-order',\n payload: scope.resumePrompt.order\n });\n\n scope.resumePrompt.show = false;\n scope.hasActiveOrder = true;\n };\n\n scope.confirmRestart = function() {\n if (!confirm('Are you sure you want to restart? All progress (' + scope.resumePrompt.goodParts + ' parts) will be lost!')) {\n return;\n }\n\n if (!scope.resumePrompt.order) {\n console.error('No order data for restart');\n return;\n }\n\n scope.send({\n action: 'restart-work-order',\n payload: scope.resumePrompt.order\n });\n\n scope.resumePrompt.show = false;\n scope.hasActiveOrder = true;\n };\n\n })(scope);\n\n\n</script>\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": "<style>\n@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@600;700&display=swap');\n\n/* SCALE: align 100% zoom with prior 125% appearance */\n:root {\nfont-size: 100%; /* was 120% */\n--bg-0: #0c1117;\n --bg-1: #131a23;\n --panel: #151e2b;\n --panel-hi: #1a2433;\n --text: #ecf3ff;\n --muted: #96a5b7;\n --accent: #2ea3ff;\n --accent-2: #1f8cf3;\n --good: #24d06f;\n --warn: #ffd100;\n --bad: #ff4d4f;\n --radius: 0.75rem;\n --shadow: 0 0.5rem 1rem rgba(0, 0, 0, .35), inset 0 0.0625rem 0 rgba(255, 255, 255, .05);\n --sidebar-width: 3.75rem;\n --sidebar-gap: clamp(0.75rem, 1.2vh, 1rem);\n --content-max: 80rem;\n --content-pad: clamp(1rem, 1.2vw, 1.4rem);\n --section-gap: clamp(0.75rem, 1vw, 1rem);\n --card-pad: clamp(1rem, 1.1vw, 1.25rem);\n --fs-page-title: clamp(1.2rem, 1vw + 0.35rem, 1.7rem);\n --fs-section-title: clamp(0.95rem, 0.9vw + 0.25rem, 1.25rem);\n --fs-body: clamp(0.8rem, 0.7vw + 0.28rem, 1rem);\n}\n\n* {\n box-sizing: border-box;\n}\n\nhtml,\nbody,\n#oee {\n width: 100vw;\n height: 100vh;\n}\n\nhtml,\nbody {\n margin: 0;\n padding: 0;\n overflow-x: hidden;\n background: var(--bg-0);\n color: var(--text);\n font-family: 'Poppins', system-ui, 'Segoe UI', 'Roboto', sans-serif;\n font-weight: 600;\n}\n\nbody {\n overflow: hidden;\n}\n\nbody > md-content,\nbody > md-content > md-content,\n.nr-dashboard-template,\n.nr-dashboard-template md-content,\n.nr-dashboard-cardpanel,\n.nr-dashboard-cardpanel md-content {\n background: transparent !important;\n height: 100%;\n overflow: hidden;\n}\n\n.nr-dashboard-cardpanel,\n.nr-dashboard-cardpanel md-card,\n.nr-dashboard-cardpanel md-card-content {\n background: transparent !important;\n box-shadow: none !important;\n padding: 0 !important;\n}\n\n/* LAYOUT: lock sidebar + content grid across tabs */\n#oee {\n position: fixed;\n inset: 0;\n display: flex;\n overflow: hidden;\n}\n\n.sidebar {\n width: var(--sidebar-width);\n background: #0b1119;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: space-between;\n padding: clamp(0.625rem, 1.4vh, 0.9rem) clamp(0.5rem, 0.8vw, 0.75rem);\n}\n\n.side-top {\n display: flex;\n flex-direction: column;\n gap: var(--sidebar-gap);\n align-items: center;\n}\n\n.sb-btn {\n width: 2.75rem;\n height: 2.75rem;\n border-radius: 0.75rem;\n background: #0f1721;\n border: 1px solid #19222e;\n display: grid;\n place-items: center;\n color: #8fb3d9;\n cursor: pointer;\n transition: 0.16s box-shadow, 0.16s transform, 0.16s border-color;\n}\n\n.sb-btn.active {\n border-color: #2fd289;\n box-shadow: 0 0 0 0.125rem rgba(36, 208, 111, .25), 0 0.625rem 1.125rem rgba(36, 208, 111, .28);\n color: #2fd289;\n}\n\n.sb-ico {\n font-size: clamp(1.1rem, 1.2vw, 1.25rem);\n line-height: 1;\n}\n\n.sb-foot {\n font-size: clamp(0.6rem, 0.6vw, 0.7rem);\n color: #6c7b8d;\n letter-spacing: 0.12em;\n text-transform: uppercase;\n}\n\n.main {\n flex: 1;\n overflow: auto;\n padding: var(--content-pad);\n background: var(--bg-0);\n}\n\n.container {\n max-width: var(--content-max);\n margin: 0 auto;\n display: flex;\n flex-direction: column;\n gap: var(--section-gap);\n}\n\n.card {\n background: linear-gradient(160deg, var(--panel) 0%, var(--panel-hi) 100%);\n border-radius: var(--radius);\n box-shadow: var(--shadow);\n}\n\n/* HEADER: maintain title weight + spacing */\n.page-heading {\n display: flex;\n align-items: center;\n padding: 0 0.25rem;\n}\n\n.page-title {\n margin: 0;\n font-size: var(--fs-page-title);\n letter-spacing: 0.05em;\n text-transform: uppercase;\n color: var(--text);\n}\n\n/* QUICK ALERTS: button row stays balanced on any width */\n.quick-alerts {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(13.75rem, 1fr));\n gap: var(--section-gap);\n padding: var(--card-pad);\n}\n\n.quick-alert-btn {\n background: linear-gradient(180deg, #ff5252 0%, #ff4d4f 100%);\n box-shadow: 0 0 1.25rem rgba(255, 77, 79, .5), inset 0 0.0625rem 0 rgba(255, 255, 255, .1);\n border: none;\n border-radius: var(--radius);\n color: var(--text);\n text-transform: uppercase;\n letter-spacing: 0.08em;\n font-weight: 700;\n padding: clamp(1.1rem, 1.8vw, 1.4rem);\n cursor: pointer;\n transition: 0.16s transform, 0.16s filter;\n}\n\n.quick-alert-btn:hover {\n transform: translateY(-0.05rem);\n filter: brightness(1.08);\n}\n\n.quick-alert-btn:active {\n transform: none;\n filter: brightness(0.96);\n}\n\n/* FORM CARD: consistent padding + typography */\n.alert-card {\n padding: var(--card-pad);\n display: flex;\n flex-direction: column;\n gap: clamp(0.9rem, 1vw, 1.1rem);\n}\n\n.form-group {\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n}\n\n.form-group label {\n font-size: var(--fs-section-title);\n letter-spacing: 0.04em;\n text-transform: uppercase;\n}\n\n.form-group select,\n.form-group textarea {\n background: #121c28;\n border: 1px solid #243244;\n border-radius: var(--radius);\n color: var(--text);\n padding: 0.8rem 0.9rem;\n font-family: 'Poppins', system-ui, 'Segoe UI', 'Roboto', sans-serif;\n font-weight: 600;\n font-size: var(--fs-body);\n}\n\ntextarea {\n resize: vertical;\n min-height: 7.5rem;\n}\n\n.alert-send {\n align-self: flex-end;\n background: linear-gradient(180deg, #ff5252 0%, #ff4d4f 100%);\n box-shadow: 0 0 1.25rem rgba(255, 77, 79, .5), inset 0 0.0625rem 0 rgba(255, 255, 255, .1);\n border: none;\n border-radius: var(--radius);\n color: var(--text);\n text-transform: uppercase;\n letter-spacing: 0.08em;\n font-weight: 700;\n padding: 0.8rem 1.4rem;\n cursor: pointer;\n transition: 0.16s transform, 0.16s filter;\n}\n\n.alert-send:hover {\n transform: translateY(-0.05rem);\n filter: brightness(1.08);\n}\n\n.alert-send:active {\n transform: none;\n filter: brightness(0.96);\n}\n\n\n/* Override Node-RED Dashboard's gray backgrounds on text elements */\n.nr-dashboard-template p,\n.nr-dashboard-template h1,\n.nr-dashboard-template h2,\n.nr-dashboard-template h3,\n.nr-dashboard-template h4,\n.nr-dashboard-template label {\n background-color: transparent !important;\n}\n\n/* Alert sent feedback animation */\n@keyframes alert-sent {\n 0% {\n transform: scale(1);\n filter: brightness(1);\n }\n 50% {\n transform: scale(0.98);\n background: linear-gradient(180deg, #24d06f 0%, #2fd289 100%);\n box-shadow: 0 0 1.5rem rgba(36, 208, 111, .7);\n filter: brightness(1.2);\n }\n 100% {\n transform: scale(1);\n filter: brightness(1);\n }\n}\n\n.alert-sent-animation {\n animation: alert-sent 0.4s ease-out;\n}\n\n</style>\n<div id=\"oee\">\n <aside class=\"sidebar\">\n <div class=\"side-top\">\n <button class=\"sb-btn\" data-label=\"Home\" ng-click=\"gotoTab('Home')\"><span class=\"sb-ico\">🏠</span></button>\n <button class=\"sb-btn\" data-label=\"Work Orders\" ng-click=\"gotoTab('Work Orders')\"><span class=\"sb-ico\">📋</span></button>\n <button class=\"sb-btn active\" data-label=\"Alerts\" ng-click=\"gotoTab('Alerts')\"><span class=\"sb-ico\">⚠️</span></button>\n<!-- <button class=\"sb-btn\" data-label=\"Graphs\" ng-click=\"gotoTab('Graphs')\"><span class=\"sb-ico\">📊</span></button> -->\n <button class=\"sb-btn\" data-label=\"Help\" ng-click=\"gotoTab('Help')\"><span class=\"sb-ico\">❓</span></button>\n <button class=\"sb-btn\" data-label=\"Settings\" ng-click=\"gotoTab('Settings')\"><span class=\"sb-ico\">⚙️</span></button>\n </div>\n <div class=\"sb-foot\">OEE V1.0</div>\n </aside>\n\n <main class=\"main\">\n <div class=\"container\">\n <section class=\"page-heading\">\n <h1 class=\"page-title\">Incidentes</h1>\n </section>\n\n <section class=\"card quick-alerts\">\n <button class=\"quick-alert-btn\" data-alert=\"Material Out\">Falta de material</button>\n <button class=\"quick-alert-btn\" data-alert=\"Machine Stopped\">Maquina detenida</button>\n <button class=\"quick-alert-btn\" data-alert=\"Emergency Stop\">Paro Emergencia</button>\n </section>\n\n <section class=\"card alert-card\">\n <div class=\"form-group\">\n <label for=\"alert-type\">Tipo de incidente</label>\n <select id=\"alert-type\">\n <option>Defecto de calidad</option>\n <option>Problema con molde</option>\n <option>Temperatura fuera de rango</option>\n <option>Presión incorrecta</option>\n <option>Desviación tiempo ciclo</option>\n <option>Bloqueo seguridad</option>\n <option>Falla neumática</option>\n <option>Falla eléctrica</option>\n <option>Error de sensor</option>\n <option>Otro</option>\n </select>\n </div>\n <div class=\"form-group\">\n <label for=\"alert-description\">Descripción</label>\n <textarea id=\"alert-description\" rows=\"5\" placeholder=\"Add context or instructions (optional)\"></textarea>\n </div>\n <button id=\"alert-send\" class=\"alert-send\" type=\"button\">Mandar incidente</button>\n </section>\n </div>\n </main>\n</div>\n\n<script>\n(function(scope) {\n scope.gotoTab = function(tabName) {\n scope.send({ ui_control: { tab: tabName } });\n };\n\n // Quick alert buttons - with new features (timestamp, visual feedback, DB logging)\n var quickButtons = document.querySelectorAll('[data-alert]');\n quickButtons.forEach(function(btn) {\n btn.addEventListener('click', function() {\n var type = btn.getAttribute('data-alert');\n var tsMs = Date.now();\n\n // Visual feedback\n btn.classList.add('alert-sent-animation');\n setTimeout(function() {\n btn.classList.remove('alert-sent-animation');\n }, 400);\n\n // Send message with timestamp and description\n scope.send({\n payload: {\n action: 'alert',\n type: type,\n tsMs: tsMs,\n description: ''\n }\n });\n });\n });\n\n // Send alert button - with new features\n var sendButton = document.getElementById('alert-send');\n if (sendButton) {\n sendButton.addEventListener('click', function() {\n var type = document.getElementById('alert-type').value;\n var description = (document.getElementById('alert-description').value || '').trim();\n var tsMs = Date.now();\n\n // Visual feedback\n sendButton.classList.add('alert-sent-animation');\n setTimeout(function() {\n sendButton.classList.remove('alert-sent-animation');\n }, 400);\n\n // Clear form\n document.getElementById('alert-description').value = '';\n\n // Send message with timestamp\n scope.send({\n payload: {\n action: 'alert',\n type: type,\n tsMs: tsMs,\n description: description\n }\n });\n });\n }\n})(scope);\n\n(function ensureNoMaterialTint(){\n const root = document.getElementById('oee');\n if (!root) return;\n\n const targets = root.querySelectorAll([\n '.md-toolbar',\n 'md-toolbar',\n '.md-subheader',\n 'md-subheader',\n '.md-toolbar-tools',\n '.md-card-title'\n ].join(','));\n\n targets.forEach(el => {\n if (el && el.style) {\n if (el.style.background) {\n el.style.background = 'transparent';\n }\n if (el.style.backgroundColor) {\n el.style.backgroundColor = 'transparent';\n }\n }\n if (el && el.classList) {\n el.classList.remove(\n 'md-whiteframe-1dp','md-whiteframe-2dp','md-whiteframe-3dp',\n 'md-whiteframe-z1','md-whiteframe-z2','md-whiteframe-z3'\n );\n }\n });\n\n if (!document.getElementById('oee-theme-sentinel')) {\n const style = document.createElement('style');\n style.id = 'oee-theme-sentinel';\n style.textContent = `\n #oee .md-toolbar::before, #oee .md-toolbar::after,\n #oee .md-subheader::before, #oee .md-subheader::after,\n #oee md-toolbar::before, #oee md-toolbar::after,\n #oee md-subheader::before, #oee md-subheader::after {\n display: none !important;\n content: none !important;\n }\n `;\n document.head.appendChild(style);\n }\n})();\n\n\n// optional render trigger\nscope.$evalAsync(function() {});\n</script>",
|
||
"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": "<style>\n @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@600;700&display=swap');\n\n :root {\nfont-size: 100%; /* was 120% */\n--bg-0: #0c1117;\n --bg-1: #131a23;\n --panel: #151e2b;\n --panel-hi: #1a2433;\n --text: #ecf3ff;\n --muted: #96a5b7;\n --accent: #2ea3ff;\n --accent-2: #1f8cf3;\n --good: #24d06f;\n --warn: #ffd100;\n --bad: #ff4d4f;\n --radius: 0.75rem;\n --shadow: 0 0.5rem 1rem rgba(0, 0, 0, .35),\n inset 0.0625rem 0 rgba(255, 255, 255, .05);\n\n --sidebar-width: 3.75rem;\n --content-max: 120rem;\n --content-pad: clamp(1rem, 1.2vw, 1.4rem);\n --section-gap: clamp(0.75rem, 1vw, 1rem);\n --card-pad: clamp(1rem, 1.1vw, 1.25rem);\n }\n\n .graphs-wrapper {\n display: flex;\n width: 100vw; /* lock to viewport width */\n max-width: 100vw;\n min-height: calc(100vh - 1px);\n background: var(--bg-0);\n overflow-x: hidden; /* no horizontal scroll */\n }\n\n .sidebar {\n width: var(--sidebar-width);\n background: #0b1119;\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 0.75rem;\n padding: 1rem 0.5rem;\n flex-shrink: 0;\n }\n\n .sb-btn {\n width: 2.75rem;\n height: 2.75rem;\n border-radius: .75rem;\n background: #0f1721;\n border: 1px solid #19222e;\n display: grid;\n place-items: center;\n color: #8fb3d9;\n cursor: pointer;\n }\n\n .sb-btn.active {\n border-color: #2fd289;\n color: #2fd289;\n }\n\n .main {\n flex: 1;\n overflow-y: auto;\n padding: var(--content-pad);\n background: var(--bg-0);\n }\n\n .container {\n max-width: var(--content-max);\n margin: auto;\n display: flex;\n flex-direction: column;\n gap: var(--section-gap);\n }\n .chart-grid {\n display: grid;\n grid-template-columns: repeat(2, minmax(0, 1fr)); /* allows shrinking */\n gap: var(--section-gap);\n }\n\n .chart-card {\n background: linear-gradient(160deg, var(--panel), var(--panel-hi));\n border-radius: var(--radius);\n padding: var(--card-pad);\n box-shadow: var(--shadow);\n }\n .chart-placeholder {\n position: relative;\n height: 210px; /* tweak 110–140px until you like it */\n }\n\n .chart-placeholder canvas {\n width: 100% !important;\n height: 100% !important;\n }\n\n .filter-buttons {\n display: flex;\n gap: .5rem;\n flex-wrap: wrap;\n }\n\n .filter-btn {\n padding: 0.3rem 0.75rem;\n border-radius: 0.4rem;\n border: none;\n background: #0f1721;\n color: var(--text);\n cursor: pointer;\n font-size: .8rem;\n border: 1px solid #19222e;\n }\n\n .filter-btn.active {\n background: var(--accent-2);\n border-color: var(--accent-2);\n }\n\n /* Ensure chart titles / small labels are readable */\n .graphs-wrapper h1,\n .chart-card h2 {\n color: var(--text) !important;\n }\n \n \n h1,\n .chart-card h2,\n .chart-title {\n color: var(--text);\n }\n</style>\n\n<div class=\"graphs-wrapper\">\n <aside class=\"sidebar\">\n <button class=\"sb-btn\" ng-click=\"gotoTab('Home')\">🏠</button>\n <button class=\"sb-btn\" ng-click=\"gotoTab('Work Orders')\">📋</button>\n <button class=\"sb-btn\" ng-click=\"gotoTab('Alerts')\">⚠️</button>\n<!-- <button class=\"sb-btn\" data-label=\"Graphs\" ng-click=\"gotoTab('Graphs')\"><span class=\"sb-ico\">📊</span></button> -->\n <button class=\"sb-btn\" ng-click=\"gotoTab('Help')\">❓</button>\n <button class=\"sb-btn\" ng-click=\"gotoTab('Settings')\">⚙️</button>\n <div style=\"margin-top:auto; color:#809ab8; font-size:.7rem;\">OEE V1.0</div>\n </aside>\n\n <main class=\"main\">\n <div class=\"container\">\n <h1 style=\"margin-bottom:0;\">Graphs</h1>\n<!--\n <section class=\"filter-bar\">\n <div class=\"filter-buttons\">\n <button class=\"filter-btn active\" ng-click=\"selectRange('24h')\">24 Hours</button>\n <button class=\"filter-btn\" ng-click=\"selectRange('7d')\">7 Days</button>\n <button class=\"filter-btn\" ng-click=\"selectRange('30d')\">30 Days</button>\n <button class=\"filter-btn\" ng-click=\"selectRange('90d')\">90 Days</button>\n </div>\n </section>\n-->\n\n <section class=\"chart-grid\">\n <article class=\"chart-card\">\n <h2>OEE</h2>\n <div class=\"chart-placeholder\"><canvas id=\"chart-oee\"></canvas></div>\n </article>\n\n <article class=\"chart-card\">\n <h2>Disponibilidad</h2>\n <div class=\"chart-placeholder\"><canvas id=\"chart-availability\"></canvas></div>\n </article>\n\n <article class=\"chart-card\">\n <h2>Rendimiendo</h2>\n <div class=\"chart-placeholder\"><canvas id=\"chart-performance\"></canvas></div>\n </article>\n\n <article class=\"chart-card\">\n <h2>Calidad</h2>\n <div class=\"chart-placeholder\"><canvas id=\"chart-quality\"></canvas></div>\n </article>\n </section>\n </div>\n </main>\n</div>\n\n<script src=\"https://cdn.jsdelivr.net/npm/chart.js\"></script>\n\n<script>\n(function(scope) {\n const rootStyles = getComputedStyle(document.documentElement);\n const chartTextColor = (rootStyles.getPropertyValue('--text') || '#ecf3ff').trim();\n const chartGridColor = 'rgba(148, 163, 184, 0.25)';\n scope.gotoTab = function(t) {\n scope.send({ui_control: {tab: t}});\n };\n\n scope.selectedRange = '24h';\n scope._charts = {};\n scope._debounceTimer = null;\n\n // Tab watcher with 300ms debounce\n scope.$watch('msg', function(msg) {\n if (!msg) return;\n\n if (msg.ui_control && msg.ui_control.tab === 'Graphs') {\n if (scope._debounceTimer) clearTimeout(scope._debounceTimer);\n scope._debounceTimer = setTimeout(function() {\n scope.send({\n topic: 'fetch-graph-data',\n payload: { range: scope.selectedRange }\n });\n }, 300);\n }\n\n // Handle graphData format (from Fetch/Format Graph Data)\n if (msg.graphData) {\n createCharts(scope.selectedRange, msg.graphData);\n }\n\n // Handle chartsData format (from Record KPI History)\n /*\n if (msg.topic === 'chartsData' && msg.payload) {\n var kpiData = msg.payload;\n\n // Build labels and data arrays from KPI history\n var labels = [];\n var oeeData = [];\n var availData = [];\n var perfData = [];\n var qualData = [];\n\n var oeeHist = kpiData.oee || [];\n oeeHist.forEach(function(point, index) {\n var tsMs = new Date(point.tsMs);\n labels.push(tsMs.toLocaleTimeString());\n\n oeeData.push(point.value || 0);\n availData.push((kpiData.availability[index] && kpiData.availability[index].value) || 0);\n perfData.push((kpiData.performance[index] && kpiData.performance[index].value) || 0);\n qualData.push((kpiData.quality[index] && kpiData.quality[index].value) || 0);\n });\n\n var graphData = {\n labels: labels,\n datasets: [\n { label: 'OEE %', data: oeeData },\n { label: 'Availability %', data: availData },\n { label: 'Performance %', data: perfData },\n { label: 'Quality %', data: qualData }\n ]\n };\n\n createCharts(scope.selectedRange, graphData);\n }\n */\n });\n\n scope.selectRange = function(range) {\n scope.selectedRange = range;\n \n setTimeout(function() {\n document.querySelectorAll('.filter-btn').forEach(function(btn) {\n btn.classList.remove('active');\n var text = btn.textContent.toLowerCase();\n if ((range === '24h' && text.includes('24')) ||\n (range === '7d' && text.includes('7')) ||\n (range === '30d' && text.includes('30')) ||\n (range === '90d' && text.includes('90'))) {\n btn.classList.add('active');\n }\n });\n }, 10);\n\n scope.send({\n topic: 'fetch-graph-data',\n payload: { range: range }\n });\n };\n\n function createCharts(range, data) {\n // Destroy existing to prevent stacking\n if (scope._charts.oee) scope._charts.oee.destroy();\n if (scope._charts.availability) scope._charts.availability.destroy();\n if (scope._charts.performance) scope._charts.performance.destroy();\n if (scope._charts.quality) scope._charts.quality.destroy();\n\n var labels = data.labels || [];\n var datasets = data.datasets || [];\n\n var oeeData = datasets.find(function(d) { return d.label === 'OEE %'; }) || { data: [] };\n var availData = datasets.find(function(d) { return d.label === 'Availability %'; }) || { data: [] };\n var perfData = datasets.find(function(d) { return d.label === 'Performance %'; }) || { data: [] };\n var qualData = datasets.find(function(d) { return d.label === 'Quality %'; }) || { data: [] };\n\n var oeeCtx = document.getElementById('chart-oee');\n if (oeeCtx) {\n scope._charts.oee = new Chart(oeeCtx, {\n type: 'line',\n data: {\n labels: labels,\n datasets: [{\n label: 'OEE %',\n data: oeeData.data,\n borderColor: '#24d06f',\n backgroundColor: 'rgba(36, 208, 111, 0.1)',\n borderWidth: 2,\n fill: true,\n tension: 0.35\n \n }]\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n animation: false,\n scales: {\n x: {\n ticks: {\n maxTicksLimit: 6,\n autoSkip: true,\n maxRotation: 45,\n minRotation: 45\n }\n },\n y: {\n min: 0,\n max: 100\n }\n }\n }\n });\n }\n\n var availCtx = document.getElementById('chart-availability');\n if (availCtx) {\n scope._charts.availability = new Chart(availCtx, {\n type: 'line',\n data: {\n labels: labels,\n datasets: [{\n label: 'Availability %',\n data: availData.data,\n borderColor: '#ff4d4f',\n backgroundColor: 'rgba(255, 77, 79, 0.1)',\n borderWidth: 2,\n fill: true,\n tension: 0.35\n \n }]\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n animation: false,\n scales: {\n x: {\n ticks: {\n maxTicksLimit: 6,\n autoSkip: true,\n maxRotation: 45,\n minRotation: 45\n }\n },\n y: {\n min: 0,\n max: 100\n }\n }\n }\n });\n }\n\n var perfCtx = document.getElementById('chart-performance');\n if (perfCtx) {\n scope._charts.performance = new Chart(perfCtx, {\n type: 'line',\n data: {\n labels: labels,\n datasets: [{\n label: 'Performance %',\n data: perfData.data,\n borderColor: '#2196F3',\n backgroundColor: 'rgba(33, 150, 243, 0.1)',\n borderWidth: 2,\n fill: true,\n tension: 0.35\n \n }]\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n animation: false,\n scales: {\n x: {\n ticks: {\n maxTicksLimit: 6,\n autoSkip: true,\n maxRotation: 45,\n minRotation: 45\n }\n },\n y: {\n min: 0,\n max: 100\n }\n }\n }\n });\n }\n\n var qualCtx = document.getElementById('chart-quality');\n if (qualCtx) {\n scope._charts.quality = new Chart(qualCtx, {\n type: 'line',\n data: {\n labels: labels,\n datasets: [{\n label: 'Quality %',\n data: qualData.data,\n borderColor: '#ffd100',\n backgroundColor: 'rgba(255, 209, 0, 0.1)',\n borderWidth: 2,\n fill: true,\n tension: 0.35\n \n }]\n },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n animation: false,\n scales: {\n x: {\n ticks: {\n maxTicksLimit: 6,\n autoSkip: true,\n maxRotation: 45,\n minRotation: 45\n }\n },\n y: {\n min: 0,\n max: 100\n }\n }\n }\n });\n }\n }\n\n})(scope);\n\n\n // Initial load and tab refresh for Graphs\n scope.refreshGraphData = function() {\n // Get current filter selection or default to 24h\n var currentFilter = scope.selectedRange || '24h';\n scope.send({\n topic: 'fetch-graph-data',\n action: 'fetch-graph-data',\n payload: { range: currentFilter }\n });\n };\n\n // Load data immediately on initialization\n setTimeout(function() {\n scope.refreshGraphData();\n }, 500);\n\n // Set up tab refresh interval (every 5 seconds when Graphs tab is visible)\n scope.graphsRefreshInterval = setInterval(function() {\n // Check if Graphs tab is visible\n var graphsElement = document.querySelector('.graphs-wrapper');\n if (graphsElement && graphsElement.offsetParent !== null) {\n scope.refreshGraphData();\n }\n }, 5000);\n\n // Cleanup on destroy\n scope.$on('$destroy', function() {\n if (scope.graphsRefreshInterval) {\n clearInterval(scope.graphsRefreshInterval);\n }\n });\n\n</script>",
|
||
"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": "<style>\n@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@600;700&display=swap');\n\n/* SCALE: align 100% zoom with prior 125% appearance */\n:root {\nfont-size: 100%; /* was 120% */\n--bg-0: #0c1117;\n --bg-1: #131a23;\n --panel: #151e2b;\n --panel-hi: #1a2433;\n --text: #ecf3ff;\n --muted: #96a5b7;\n --accent: #2ea3ff;\n --accent-2: #1f8cf3;\n --good: #24d06f;\n --warn: #ffd100;\n --bad: #ff4d4f;\n --radius: 0.75rem;\n --shadow: 0 0.5rem 1rem rgba(0, 0, 0, .35), inset 0 0.0625rem 0 rgba(255, 255, 255, .05);\n --sidebar-width: 3.75rem;\n --sidebar-gap: clamp(0.75rem, 1.2vh, 1rem);\n --content-max: 70rem;\n --content-pad: clamp(1rem, 1.2vw, 1.4rem);\n --section-gap: clamp(0.75rem, 1vw, 1rem);\n --card-pad: clamp(1rem, 1.1vw, 1.25rem);\n --fs-page-title: clamp(1.2rem, 1vw + 0.35rem, 1.7rem);\n --fs-section-title: clamp(1rem, 0.9vw + 0.3rem, 1.35rem);\n --fs-body: clamp(0.85rem, 0.7vw + 0.3rem, 1.05rem);\n}\n\n* {\n box-sizing: border-box;\n}\n\nhtml,\nbody,\n#oee {\n width: 100vw;\n height: 100vh;\n}\n\nhtml,\nbody {\n margin: 0;\n padding: 0;\n overflow-x: hidden;\n background: var(--bg-0);\n color: var(--text);\n font-family: 'Poppins', system-ui, 'Segoe UI', 'Roboto', sans-serif;\n font-weight: 600;\n}\n\nbody {\n overflow: hidden;\n}\n\nbody > md-content,\nbody > md-content > md-content,\n.nr-dashboard-template,\n.nr-dashboard-template md-content,\n.nr-dashboard-cardpanel,\n.nr-dashboard-cardpanel md-content {\n background: transparent !important;\n height: 100%;\n overflow: hidden;\n}\n\n.nr-dashboard-cardpanel,\n.nr-dashboard-cardpanel md-card,\n.nr-dashboard-cardpanel md-card-content {\n background: transparent !important;\n box-shadow: none !important;\n padding: 0 !important;\n}\n\n/* LAYOUT: lock sidebar + content grid across tabs */\n#oee {\n position: fixed;\n inset: 0;\n display: flex;\n overflow: hidden;\n}\n\n.sidebar {\n width: var(--sidebar-width);\n background: #0b1119;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: space-between;\n padding: clamp(0.625rem, 1.4vh, 0.9rem) clamp(0.5rem, 0.8vw, 0.75rem);\n}\n\n.side-top {\n display: flex;\n flex-direction: column;\n gap: var(--sidebar-gap);\n align-items: center;\n}\n\n.sb-btn {\n width: 2.75rem;\n height: 2.75rem;\n border-radius: 0.75rem;\n background: #0f1721;\n border: 1px solid #19222e;\n display: grid;\n place-items: center;\n color: #8fb3d9;\n cursor: pointer;\n transition: 0.16s box-shadow, 0.16s transform, 0.16s border-color;\n}\n\n.sb-btn.active {\n border-color: #2fd289;\n box-shadow: 0 0 0 0.125rem rgba(36, 208, 111, .25), 0 0.625rem 1.125rem rgba(36, 208, 111, .28);\n color: #2fd289;\n}\n\n.sb-ico {\n font-size: clamp(1.1rem, 1.2vw, 1.25rem);\n line-height: 1;\n}\n\n.sb-foot {\n font-size: clamp(0.6rem, 0.6vw, 0.7rem);\n color: #6c7b8d;\n letter-spacing: 0.12em;\n text-transform: uppercase;\n}\n\n.main {\n flex: 1;\n overflow: auto;\n padding: var(--content-pad);\n background: var(--bg-0);\n}\n\n.container {\n max-width: var(--content-max);\n margin: 0 auto;\n display: flex;\n flex-direction: column;\n gap: var(--section-gap);\n}\n\n.card {\n background: linear-gradient(160deg, var(--panel) 0%, var(--panel-hi) 100%);\n border-radius: var(--radius);\n box-shadow: var(--shadow);\n}\n\n/* HEADER: maintain title styling */\n.page-heading {\n display: flex;\n align-items: center;\n padding: 0 0.25rem;\n}\n\n.page-title {\n margin: 0;\n font-size: var(--fs-page-title);\n letter-spacing: 0.05em;\n text-transform: uppercase;\n color: var(--text);\n}\n\n/* HELP CARDS: keep text hierarchy + spacing clean */\n.help-card {\n display: flex;\n flex-direction: column;\n gap: clamp(0.9rem, 1vw, 1.1rem);\n padding: var(--card-pad);\n}\n\n.help-title {\n margin: 0;\n font-size: var(--fs-section-title);\n letter-spacing: 0.05em;\n text-transform: uppercase;\n color: var(--text) !important;\n}\n.nr-dashboard-template p.help-body {\nmargin: 0;\nfont-size: var(--fs-body);\ncolor: var(--text) !important;\n}\n\n\n/* Override Node-RED Dashboard's gray backgrounds on text elements */\n.nr-dashboard-template p,\n.nr-dashboard-template h1,\n.nr-dashboard-template h2,\n.nr-dashboard-template h3,\n.nr-dashboard-template h4,\n.nr-dashboard-template label {\n background-color: transparent !important;\n}\n\nbody.nr-dashboard-theme h2.help-title {\ncolor: var(--text) !important;\n}\n\nbody.nr-dashboard-theme p.help-body {\ncolor: var(--text) !important;\n}\n</style>\n<div id=\"oee\">\n <aside class=\"sidebar\">\n <div class=\"side-top\">\n <button class=\"sb-btn\" data-label=\"Home\" ng-click=\"gotoTab('Home')\"><span class=\"sb-ico\">🏠</span></button>\n <button class=\"sb-btn\" data-label=\"Work Orders\" ng-click=\"gotoTab('Work Orders')\"><span class=\"sb-ico\">📋</span></button>\n <button class=\"sb-btn\" data-label=\"Alerts\" ng-click=\"gotoTab('Alerts')\"><span class=\"sb-ico\">⚠️</span></button>\n<!-- <button class=\"sb-btn\" data-label=\"Graphs\" ng-click=\"gotoTab('Graphs')\"><span class=\"sb-ico\">📊</span></button> -->\n <button class=\"sb-btn active\" data-label=\"Help\" ng-click=\"gotoTab('Help')\"><span class=\"sb-ico\">❓</span></button>\n <button class=\"sb-btn\" data-label=\"Settings\" ng-click=\"gotoTab('Settings')\"><span class=\"sb-ico\">⚙️</span></button>\n </div>\n <div class=\"sb-foot\">OEE V1.0</div>\n </aside>\n\n <main class=\"main\">\n <div class=\"container\">\n <section class=\"page-heading\">\n <h1 class=\"page-title\">Help</h1>\n </section>\n\n <section class=\"card help-card\">\n <h2 class=\"help-title\">Acerca de este panel</h2>\n <p class=\"help-body\">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.</p>\n </section>\n\n <section class=\"card help-card\">\n <h2 class=\"help-title\">Cómo empezar con una orden de trabajo</h2>\n <p class=\"help-body\">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.</p>\n </section>\n\n <section class=\"card help-card\">\n <h2 class=\"help-title\">Ejecutando producción</h2>\n <p class=\"help-body\">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.</p>\n </section>\n\n <section class=\"card help-card\">\n <h2 class=\"help-title\">Registro de incidentes</h2>\n <p class=\"help-body\">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.</p>\n </section>\n\n <section class=\"card help-card\">\n <h2 class=\"help-title\">Configuración de moldes</h2>\n <p class=\"help-body\">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.</p>\n </section>\n\n <section class=\"card help-card\">\n <h2 class=\"help-title\">Visualización de datos de desempeño</h2>\n <p class=\"help-body\">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</p>\n </section>\n </div>\n </main>\n</div>\n\n<script>\n(function(scope) {\n scope.gotoTab = function(tabName) {\n scope.send({ ui_control: { tab: tabName } });\n };\n})(scope);\n\n(function ensureNoMaterialTint(){\n const root = document.getElementById('oee');\n if (!root) return;\n\n const targets = root.querySelectorAll([\n '.md-toolbar',\n 'md-toolbar',\n '.md-subheader',\n 'md-subheader',\n '.md-toolbar-tools',\n '.md-card-title'\n ].join(','));\n\n targets.forEach(el => {\n if (el && el.style) {\n if (el.style.background) {\n el.style.background = 'transparent';\n }\n if (el.style.backgroundColor) {\n el.style.backgroundColor = 'transparent';\n }\n }\n if (el && el.classList) {\n el.classList.remove(\n 'md-whiteframe-1dp','md-whiteframe-2dp','md-whiteframe-3dp',\n 'md-whiteframe-z1','md-whiteframe-z2','md-whiteframe-z3'\n );\n }\n });\n\n if (!document.getElementById('oee-theme-sentinel')) {\n const style = document.createElement('style');\n style.id = 'oee-theme-sentinel';\n style.textContent = `\n #oee .md-toolbar::before, #oee .md-toolbar::after,\n #oee .md-subheader::before, #oee .md-subheader::after,\n #oee md-toolbar::before, #oee md-toolbar::after,\n #oee md-subheader::before, #oee md-subheader::after {\n display: none !important;\n content: none !important;\n }\n `;\n document.head.appendChild(style);\n }\n})();\n\n\n// optional render trigger\nscope.$evalAsync(function() {});\n</script>\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": "<style>\n @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@600;700&display=swap');\n\n /* SCALE: align 100% zoom with prior 125% appearance */\n :root {\n font-size: 100%;\n /* was 120% */\n --bg-0: #0c1117;\n --bg-1: #131a23;\n --panel: #151e2b;\n --panel-hi: #1a2433;\n --text: #ecf3ff;\n --muted: #96a5b7;\n --accent: #2ea3ff;\n --accent-2: #1f8cf3;\n --good: #24d06f;\n --warn: #ffd100;\n --bad: #ff4d4f;\n --radius: 0.75rem;\n --shadow: 0 0.5rem 1rem rgba(0, 0, 0, .35), inset 0 0.0625rem 0 rgba(255, 255, 255, .05);\n --sidebar-width: 3.75rem;\n --sidebar-gap: clamp(0.75rem, 1.2vh, 1rem);\n --content-max: 70rem;\n --content-pad: clamp(1rem, 1.2vw, 1.4rem);\n --section-gap: clamp(0.75rem, 1vw, 1rem);\n --card-pad: clamp(1rem, 1.1vw, 1.25rem);\n --fs-page-title: clamp(1.2rem, 1vw + 0.35rem, 1.7rem);\n --fs-section-title: clamp(1rem, 0.9vw + 0.3rem, 1.35rem);\n --fs-body: clamp(0.8rem, 0.7vw + 0.28rem, 1rem);\n }\n\n * {\n box-sizing: border-box;\n }\n\n html,\n body,\n #oee {\n width: 100vw;\n height: 100vh;\n }\n\n html,\n body {\n margin: 0;\n padding: 0;\n overflow-x: hidden;\n background: var(--bg-0);\n color: var(--text);\n font-family: 'Poppins', system-ui, 'Segoe UI', 'Roboto', sans-serif;\n font-weight: 600;\n }\n\n body {\n overflow: hidden;\n }\n\n body>md-content,\n body>md-content>md-content,\n .nr-dashboard-template,\n .nr-dashboard-template md-content,\n .nr-dashboard-cardpanel,\n .nr-dashboard-cardpanel md-content {\n background: transparent !important;\n height: 100%;\n overflow: hidden;\n }\n\n .nr-dashboard-cardpanel,\n .nr-dashboard-cardpanel md-card,\n .nr-dashboard-cardpanel md-card-content {\n background: transparent !important;\n box-shadow: none !important;\n padding: 0 !important;\n }\n\n /* LAYOUT: lock sidebar + content grid across tabs */\n #oee {\n position: fixed;\n inset: 0;\n display: flex;\n overflow: hidden;\n }\n\n .sidebar {\n width: var(--sidebar-width);\n background: #0b1119;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: space-between;\n padding: clamp(0.625rem, 1.4vh, 0.9rem) clamp(0.5rem, 0.8vw, 0.75rem);\n }\n\n .side-top {\n display: flex;\n flex-direction: column;\n gap: var(--sidebar-gap);\n align-items: center;\n }\n\n .sb-btn {\n width: 2.75rem;\n height: 2.75rem;\n border-radius: 0.75rem;\n background: #0f1721;\n border: 1px solid #19222e;\n display: grid;\n place-items: center;\n color: #8fb3d9;\n cursor: pointer;\n transition: 0.16s box-shadow, 0.16s transform, 0.16s border-color;\n }\n\n .sb-btn.active {\n border-color: #2fd289;\n box-shadow: 0 0 0 0.125rem rgba(36, 208, 111, .25), 0 0.625rem 1.125rem rgba(36, 208, 111, .28);\n color: #2fd289;\n }\n\n .sb-ico {\n font-size: clamp(1.1rem, 1.2vw, 1.25rem);\n line-height: 1;\n }\n\n .sb-foot {\n font-size: clamp(0.6rem, 0.6vw, 0.7rem);\n color: #6c7b8d;\n letter-spacing: 0.12em;\n text-transform: uppercase;\n }\n\n .main {\n flex: 1;\n overflow: auto;\n padding: var(--content-pad);\n background: var(--bg-0);\n }\n\n .container {\n max-width: var(--content-max);\n margin: 0 auto;\n display: flex;\n flex-direction: column;\n gap: var(--section-gap);\n }\n\n .card {\n background: linear-gradient(160deg, var(--panel) 0%, var(--panel-hi) 100%);\n border-radius: var(--radius);\n box-shadow: var(--shadow);\n }\n\n /* HEADER: maintain title styling */\n .page-heading {\n display: flex;\n align-items: center;\n padding: 0 0.25rem;\n }\n\n .page-title {\n margin: 0;\n font-size: var(--fs-page-title);\n letter-spacing: 0.05em;\n text-transform: uppercase;\n color: var(--text);\n }\n\n .section-title {\n margin: 0;\n font-size: var(--fs-section-title);\n letter-spacing: 0.05em;\n text-transform: uppercase;\n color: var(--text);\n }\n\n /* SETTINGS CARDS: clean grid + balanced inputs */\n .mold-card,\n .integrations-card {\n display: flex;\n flex-direction: column;\n gap: clamp(0.9rem, 1vw, 1.1rem);\n padding: var(--card-pad);\n }\n\n .form-grid {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(13.75rem, 1fr));\n gap: clamp(0.75rem, 1vw, 1rem);\n }\n\n .form-field {\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n }\n\n .form-field label {\n font-size: var(--fs-body);\n letter-spacing: 0.04em;\n text-transform: uppercase;\n color: var(--text);\n }\n\n .form-field input,\n .form-field select {\n background: #121c28;\n border: 1px solid #243244;\n border-radius: var(--radius);\n color: var(--text);\n padding: 0.75rem 0.9rem;\n font-family: 'Poppins', system-ui, 'Segoe UI', 'Roboto', sans-serif;\n font-weight: 600;\n font-size: var(--fs-body);\n }\n\n .integrations-split {\n display: flex;\n gap: clamp(1rem, 1.5vw, 2rem);\n align-items: flex-start;\n }\n\n .integrations-left {\n flex: 1;\n display: flex;\n flex-direction: column;\n gap: 0.75rem;\n }\n\n .integrations-right {\n flex: 1;\n display: flex;\n flex-direction: column;\n gap: 0.75rem;\n align-items: flex-start;\n }\n\n .add-mold-info {\n margin: 0;\n font-size: var(--fs-body);\n color: var(--muted);\n line-height: 1.5;\n }\n\n .integrations-button {\n width: fit-content;\n background: #121c28;\n border: 1px dashed rgba(150, 165, 183, .45);\n border-radius: var(--radius);\n color: rgba(150, 165, 183, .8);\n padding: 0.75rem 1.5rem;\n letter-spacing: 0.1em;\n text-transform: uppercase;\n font-weight: 700;\n cursor: not-allowed;\n }\n\n .preset-add-form {\n margin-top: 1rem;\n display: flex;\n flex-direction: column;\n gap: 0.75rem;\n }\n\n .preset-add-actions {\n display: flex;\n gap: 0.75rem;\n justify-content: flex-end;\n }\n\n /* PRESET SEARCH STYLES */\n .preset-card {\n display: flex;\n flex-direction: column;\n gap: clamp(0.9rem, 1vw, 1.1rem);\n padding: var(--card-pad);\n }\n\n .preset-filters {\n display: grid;\n grid-template-columns: 2fr 1fr 1fr;\n gap: clamp(0.75rem, 1vw, 1rem);\n }\n\n .preset-results {\n max-height: 20rem;\n overflow-y: auto;\n display: flex;\n flex-direction: column;\n gap: 0.75rem;\n }\n\n .preset-item {\n background: #121c28;\n border: 1px solid #243244;\n border-radius: var(--radius);\n padding: 1rem;\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 1rem;\n }\n\n .preset-info {\n flex: 1;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n }\n\n .preset-name {\n font-size: var(--fs-body);\n font-weight: 700;\n color: var(--text);\n }\n\n .preset-details {\n display: flex;\n gap: 1rem;\n font-size: clamp(0.75rem, 0.7vw + 0.25rem, 0.9rem);\n color: var(--muted);\n }\n\n .preset-badge {\n display: inline-block;\n background: rgba(46, 163, 255, 0.2);\n color: var(--accent);\n padding: 0.25rem 0.5rem;\n border-radius: 0.375rem;\n font-size: clamp(0.7rem, 0.6vw + 0.2rem, 0.85rem);\n font-weight: 600;\n }\n\n .preset-select-btn {\n background: linear-gradient(180deg, #32ff7e 0%, #2fd289 100%);\n box-shadow: 0 0 1.25rem rgba(36, 208, 111, .5), inset 0 0.0625rem 0 rgba(255, 255, 255, .1);\n border: none;\n border-radius: var(--radius);\n color: var(--text);\n padding: 0.6rem 1.2rem;\n font-weight: 700;\n font-size: var(--fs-body);\n text-transform: uppercase;\n letter-spacing: 0.05em;\n cursor: pointer;\n transition: 0.16s transform, 0.16s filter;\n }\n\n .preset-select-btn:hover {\n transform: translateY(-0.05rem);\n filter: brightness(1.08);\n }\n\n .preset-select-btn:active {\n transform: none;\n filter: brightness(0.96);\n }\n\n .preset-empty {\n text-align: center;\n color: var(--muted);\n padding: 2rem;\n font-size: var(--fs-body);\n }\n\n\n\n\n .read-only {\n opacity: 0.65;\n }\n\n .read-only input,\n .read-only select,\n .read-only button {\n pointer-events: none;\n }\n\n /* Override Node-RED Dashboard's gray backgrounds on text elements */\n .nr-dashboard-template p,\n .nr-dashboard-template h1,\n .nr-dashboard-template h2,\n .nr-dashboard-template h3,\n .nr-dashboard-template h4,\n .nr-dashboard-template label {\n background-color: transparent !important;\n }\n</style>\n<div id=\"oee\">\n <aside class=\"sidebar\">\n <div class=\"side-top\">\n <button class=\"sb-btn\" data-label=\"Home\" ng-click=\"gotoTab('Home')\"><span class=\"sb-ico\">🏠</span></button>\n <button class=\"sb-btn\" data-label=\"Work Orders\" ng-click=\"gotoTab('Work Orders')\"><span class=\"sb-ico\">📋</span></button>\n <button class=\"sb-btn\" data-label=\"Alerts\" ng-click=\"gotoTab('Alerts')\"><span class=\"sb-ico\">⚠️</span></button>\n<!-- <button class=\"sb-btn\" data-label=\"Graphs\" ng-click=\"gotoTab('Graphs')\"><span class=\"sb-ico\">📊</span></button> -->\n <button class=\"sb-btn\" data-label=\"Help\" ng-click=\"gotoTab('Help')\"><span class=\"sb-ico\">❓</span></button>\n <button class=\"sb-btn active\" data-label=\"Ajustes\" ng-click=\"gotoTab('Settings')\"><span class=\"sb-ico\">⚙️</span></button>\n </div>\n <div class=\"sb-foot\">OEE V1.0</div>\n </aside>\n\n <main class=\"main\">\n <div class=\"container\">\n <section class=\"page-heading\">\n <h1 class=\"page-title\">Ajustes</h1>\n </section>\n\n <section class=\"card preset-card\">\n <h2 class=\"section-title\">Moldes Preconfigurados</h2>\n <div class=\"preset-filters\">\n <div class=\"form-field\">\n <label for=\"preset-manufacturer\">Fabricante</label>\n <select id=\"preset-manufacturer\"\n ng-model=\"selectedManufacturer\"\n ng-change=\"onManufacturerChange()\">\n <option value=\"\">Seleccionar fabricante...</option>\n <option ng-repeat=\"mfg in manufacturers\" value=\"{{mfg}}\">{{mfg}}</option>\n </select>\n </div>\n <div class=\"form-field\">\n <label for=\"preset-mold\">Molde</label>\n <select id=\"preset-mold\"\n ng-model=\"selectedMold\"\n ng-options=\"preset as preset.mold_name for preset in moldsForManufacturer | orderBy:'mold_name'\"\n ng-change=\"onMoldChange()\">\n <option value=\"\">Seleccionar molde...</option>\n </select>\n </div>\n </div>\n\n <div class=\"preset-results\" id=\"preset-results\">\n <!-- Default state: simplified -->\n <div class=\"preset-empty\" ng-if=\"!showAddMoldForm\">\n <p>Seleccionar un fabricante y el molde de las siguientes opciones.</p>\n </div>\n\n <!-- Add Mold form -->\n <div class=\"preset-add-form\" ng-if=\"showAddMoldForm\">\n <div class=\"form-grid\">\n <div class=\"form-field\">\n <label for=\"new-mold-manufacturer\">Fabricante</label>\n <input id=\"new-mold-manufacturer\"\n type=\"text\"\n ng-model=\"newMold.manufacturer\"\n placeholder=\"Type manufacturer...\" />\n </div>\n <div class=\"form-field\">\n <label for=\"new-mold-name\">Nombre del molde</label>\n <input id=\"new-mold-name\"\n type=\"text\"\n ng-model=\"newMold.mold_name\"\n placeholder=\"Type mold name...\" />\n </div>\n <div class=\"form-field\">\n <label for=\"new-mold-cavities\">Cavidades del molde</label>\n <input id=\"new-mold-cavities\"\n type=\"text\"\n ng-model=\"newMold.cavities\"\n placeholder=\"Type Theoretical Cavities...\" />\n </div>\n <div class=\"form-field\">\n <label for=\"new-mold-active\">Cavidades</label>\n <input id=\"new-mold-active\"\n type=\"text\"\n ng-model=\"newMold.active\"\n placeholder=\"Type Active Cavities...\" />\n </div>\n </div>\n <div class=\"preset-add-actions\">\n <button class=\"preset-select-btn\"\n type=\"button\"\n ng-click=\"saveNewMold()\"\n ng-disabled=\"isSavingMold\">\n {{ isSavingMold ? 'Guardando...' : 'Guardar' }}\n </button>\n <button class=\"preset-select-btn\"\n type=\"button\"\n ng-click=\"cancelAddMold()\"\n ng-disabled=\"isSavingMold\">\n Cancel\n </button>\n </div>\n </div>\n </div>\n </section>\n\n <section class=\"card mold-card\">\n <h2 class=\"form-field\">Configuraciones de Molde</h2>\n <div class=\"form-grid\">\n <div class=\"form-field\">\n <label for=\"mold-active\">Cavidades del Molde</label>\n <input id=\"mold-total\" type=\"number\" ng-model=\"moldTotal\" ng-change=\"updateMoldSettings()\" />\n </div>\n <div class=\"form-field\">\n <label for=\"mold-active\">Cavidades Activas</label>\n <input id=\"mold-active\" type=\"number\" ng-model=\"moldActive\" ng-change=\"updateMoldSettings()\" />\n </div>\n </div>\n </section>\n\n <section class=\"card integrations-card\">\n <h2 class=\"section-title\">Integraciones</h2>\n <div class=\"integrations-split\">\n <div class=\"integrations-left\">\n <button class=\"integrations-button\" type=\"button\" disabled>Connectar al ERP</button>\n </div>\n <div class=\"integrations-right\">\n <p class=\"add-mold-info\">No encuentras lo que buscas?</p>\n <button class=\"preset-select-btn\" type=\"button\" ng-click=\"openAddMold()\">Agregar Molde</button>\n </div>\n </div>\n </section>\n <section class=\"card mold-card\">\n <h2 class=\"section-title\">Enlace Control Tower</h2>\n <p class=\"add-mold-info\">Ingresa el codigo de 5 caracteres que aparece en Control Tower para enlazar esta Raspberry Pi.</p>\n <div class=\"form-grid\">\n <div class=\"form-field\">\n <label for=\"pairing-code\">Codigo de enlace</label>\n <input id=\"pairing-code\" type=\"text\" maxlength=\"5\" ng-model=\"pairingCode\" ng-change=\"pairingCode = (pairingCode || '').toUpperCase()\" placeholder=\"ABCDE\" />\n </div>\n <div class=\"form-field\" style=\"align-self: end;\">\n <button class=\"preset-select-btn\" type=\"button\" ng-click=\"submitPairingCode()\" ng-disabled=\"isPairing\">\n {{ isPairing ? 'Conectando...' : 'Conectar' }}\n </button>\n </div>\n </div>\n <p class=\"add-mold-info\" ng-if=\"pairingStatus\">{{ pairingStatus }}</p>\n </section>\n <section class=\"card mold-card\">\n <h2 class=\"section-title\">WiFi</h2>\n <p class=\"add-mold-info\">Conecta esta Raspberry Pi a una red WiFi (sin salir del dashboard).</p>\n \n <div class=\"form-grid\">\n <div class=\"form-field\">\n <label>Red actual</label>\n <input type=\"text\" ng-model=\"wifiCurrent.ssid\" placeholder=\"---\" readonly />\n </div>\n \n <div class=\"form-field\">\n <label>IP</label>\n <input type=\"text\" ng-model=\"wifiCurrent.ip\" placeholder=\"---\" readonly />\n </div>\n </div>\n \n <div class=\"form-grid\" style=\"margin-top: 0.75rem;\">\n <div class=\"form-field\">\n <label>Buscar redes</label>\n <select ng-model=\"wifiForm.ssid\"\n ng-options=\"s for s in wifiOptions\">\n <option value=\"\">Seleccionar WiFi...</option>\n </select>\n </div>\n \n <div class=\"form-field\">\n <label>Contraseña</label>\n <input type=\"password\" ng-model=\"wifiForm.password\" placeholder=\"••••••••\" />\n </div>\n </div>\n \n <div style=\"display:flex; gap:0.75rem; margin-top: 0.75rem; flex-wrap: wrap;\">\n <button class=\"preset-select-btn\" type=\"button\" ng-click=\"wifiRefreshStatus()\">\n Estado\n </button>\n \n <button class=\"preset-select-btn\" type=\"button\" ng-click=\"wifiScan()\" ng-disabled=\"wifiBusy.scan\">\n {{ wifiBusy.scan ? 'Buscando…' : 'Escanear' }}\n </button>\n \n <button class=\"preset-select-btn\" type=\"button\" ng-click=\"wifiApply()\" ng-disabled=\"wifiBusy.apply\">\n {{ wifiBusy.apply ? 'Aplicando…' : 'Conectar' }}\n </button>\n </div>\n \n <p class=\"add-mold-info\" ng-if=\"wifiStatusText\" style=\"margin-top: 0.75rem;\">\n {{ wifiStatusText }}\n </p>\n </section>\n <section class=\"card mold-card\" ng-class=\"{'read-only': readOnly}\">\n <h2 class=\"section-title\">Programación de Producción</h2>\n\n <!-- Shifts -->\n <div class=\"form-grid\">\n <div class=\"form-field\" style=\"grid-column: span 2;\">\n <label>Turnos (Max 3)</label>\n </div>\n </div>\n\n <div ng-repeat=\"shift in shifts track by $index\" class=\"form-grid\" style=\"margin-bottom: 0.5rem;\">\n <div class=\"form-field\">\n <label>Turno {{$index + 1}} Arrancar</label>\n <input type=\"time\" ng-model=\"shift.start\" ng-change=\"updateShiftConfig()\" />\n </div>\n <div class=\"form-field\">\n <label>Turno {{$index + 1}} Terminar</label>\n <input type=\"time\" ng-model=\"shift.end\" ng-change=\"updateShiftConfig()\" />\n </div>\n <div class=\"form-field\" style=\"align-self: end;\" ng-if=\"shifts.length > 1\">\n <button class=\"integrations-button\" style=\"cursor: pointer; border-style: solid; color: var(--bad);\" ng-click=\"removeShift($index)\">Remove</button>\n </div>\n </div>\n\n <button class=\"preset-select-btn\" style=\"margin-top: 0.75rem;\" ng-click=\"addShift()\" ng-disabled=\"readOnly || shifts.length >= 3\">\n + Agregar Turno\n </button>\n\n <!-- Compensations -->\n <div class=\"form-grid\" style=\"margin-top: 1rem;\">\n <div class=\"form-field\">\n <label>Cambiar compensación del turno (min)</label>\n <input type=\"number\" ng-model=\"shiftChangeComp\" ng-change=\"updateShiftConfig()\"/>\n </div>\n <div class=\"form-field\">\n <label>Hora de Comida (min)</label>\n <input type=\"number\" ng-model=\"lunchBreak\" ng-change=\"updateShiftConfig()\"/>\n </div>\n </div>\n </section>\n <div style=\"display: flex; gap: 0.75rem; margin-top: 1rem; align-items: center;\" ng-class=\"{'read-only': readOnly}\">\n <button class=\"preset-select-btn\" ng-click=\"saveAllSettings()\" ng-disabled=\"readOnly || isSaving\">\n {{ isSaving ? 'Guardando...' : 'Guardar Ajustes' }}\n </button>\n <span ng-if=\"saveStatus\" style=\"color: var(--good); font-size: 0.85rem;\">\n {{ saveStatus }}\n </span>\n </div>\n\n <section class=\"card mold-card\" ng-class=\"{'read-only': readOnly}\">\n <h2 class=\"section-title\">Umbral OEE</h2>\n <div class=\"form-grid\">\n <div class=\"form-field\">\n <label>Multiplicador de Umbral de Pago</label>\n <input type=\"number\" ng-model=\"thresholdMultiplier\" ng-change=\"updateThresholdConfig()\" min=\"1.1\" max=\"5\" step=\"0.1\" />\n <p style=\"font-size: 0.75rem; color: var(--muted); margin-top: 0.25rem;\">\n Gap > (Cycle Time × {{thresholdMultiplier || 1.5}}) = Stoppage\n </p>\n </div>\n <div class=\"form-field\">\n <label>Alerta de Umbral de OEE (%)</label>\n <input type=\"number\" ng-model=\"oeeThreshold\" ng-change=\"updateThresholdConfig()\" min=\"50\" max=\"100\" />\n </div>\n </div>\n </section>\n </div>\n </main>\n</div>\n\n<script>\n (function(scope) {\n function toTimeDate(value, fallback) {\n if (value instanceof Date) return value;\n var v = value || fallback;\n if (!v) return null;\n \n // ISO string? e.g. \"2025-12-03T08:00:00\"\n if (typeof v === 'string' && v.indexOf('T') !== -1) {\n var dIso = new Date(v);\n if (!isNaN(dIso.getTime())) return dIso;\n }\n \n // \"HH:MM\" or \"HH:MM:SS\"\n if (typeof v === 'string') {\n var parts = v.split(':');\n var h = parseInt(parts[0], 10) || 0;\n var m = parseInt(parts[1], 10) || 0;\n var d = new Date();\n d.setSeconds(0, 0);\n d.setHours(h, m, 0, 0);\n return d;\n }\n \n return null;\n }\n\n\n // Initialize state\n scope.moldTotal = 0;\n scope.moldActive = 0;\n scope.selectedManufacturer = '';\n scope.moldsForManufacturer = [];\n scope.selectedMold = null;\n scope.manufacturers = [];\n scope.showAddMoldForm = false;\n scope.newMold = { manufacturer: '', mold_name: '', cavities: '', active: '' };\n scope.isSavingMold = false;\n scope.pairingCode = '';\n scope.pairingStatus = '';\n scope.isPairing = false;\n scope.readOnly = true;\n \n // Debounce timers\n scope._moldSettingsDebounceTimer = null;\n scope._saveMoldTimeout = null;\n \n // Track processed messages by topic + timestamp to prevent loops\n scope._processedMessages = {};\n \n // Clean old processed messages every 10 seconds\n setInterval(function() {\n const now = Date.now();\n Object.keys(scope._processedMessages).forEach(function(key) {\n if (now - scope._processedMessages[key] > 10000) {\n delete scope._processedMessages[key];\n }\n });\n }, 10000);\n \n // Navigation\n scope.gotoTab = function(tabName) {\n scope.isSavingMold = false;\n scope.send({ ui_control: { tab: tabName } });\n };\n //Load shift presets\n scope.loadShiftConfig = function() {\n console.log('[SETTINGS] Requesting shift config...');\n scope.send({ topic: 'getShiftConfig' });\n };\n \n // Pair machine to Control Tower\n scope.submitPairingCode = function() {\n var raw = (scope.pairingCode || '').toString().trim();\n var code = raw.toUpperCase().replace(/[^A-Z0-9]/g, '');\n if (code.length != 5) {\n scope.pairingStatus = 'Codigo invalido. Debe tener 5 caracteres.';\n return;\n }\n scope.isPairing = true;\n scope.pairingStatus = '';\n scope.send({ topic: 'pairMachine', payload: { code: code } });\n };\n // =============================\n // WIFI UI STATE\n // =============================\n scope.wifiOptions = [];\n scope.wifiForm = { ssid: '', password: '' };\n scope.wifiCurrent = { ssid: '', ip: '', mask: '', broadcast: '' };\n scope.wifiBusy = { scan: false, apply: false };\n scope.wifiStatusText = '';\n \n // Trigger status + scan helpers\n scope.wifiRefreshStatus = function () {\n scope.wifiStatusText = 'Consultando estado…';\n scope.send({ topic: 'wifi:status' });\n };\n \n scope.wifiScan = function () {\n scope.wifiBusy.scan = true;\n scope.wifiStatusText = 'Escaneando redes…';\n scope.send({ topic: 'wifi:scan' });\n };\n \n scope.wifiApply = function () {\n const ssid = (scope.wifiForm.ssid || '').trim();\n const password = (scope.wifiForm.password || '').toString();\n \n if (!ssid) {\n scope.wifiStatusText = 'Selecciona una red WiFi.';\n return;\n }\n if (!password) {\n scope.wifiStatusText = 'Ingresa la contraseña.';\n return;\n }\n \n scope.wifiBusy.apply = true;\n scope.wifiStatusText = 'Aplicando configuración…';\n scope.send({\n topic: 'wifi:apply',\n payload: { ssid, password }\n });\n };\n \n // Kick once on load\n setTimeout(function () {\n scope.wifiRefreshStatus();\n }, 250);\n\n // Load manufacturers on init\n scope.loadManufacturers = function() {\n console.log('Loading manufacturers');\n scope.send({ topic: 'getManufacturers' }); \n };\n\n\n \n // When manufacturer changes\n scope.onManufacturerChange = function() {\n scope.selectedMold = null;\n scope.moldsForManufacturer = [];\n \n const manufacturer = scope.selectedManufacturer || '';\n if (!manufacturer) {\n return;\n }\n \n console.log('Loading molds for:', manufacturer);\n scope.send({\n topic: 'getMoldsByManufacturer',\n payload: { manufacturer: manufacturer }\n });\n };\n \n // When mold changes\n scope.onMoldChange = function() {\n\n if (!scope.selectedMold) return;\n scope.selectPreset(scope.selectedMold);\n };\n \n // Select a preset\n scope.selectPreset = function(preset) {\n\n scope.send({\n topic: 'selectMoldPreset',\n payload: preset\n });\n \n scope.moldTotal = preset.theoretical_cavities;\n scope.moldActive = preset.functional_cavities;\n };\n \n // Update mold settings with debounce\n scope.updateMoldSettings = function() {\n\n if (scope._moldSettingsDebounceTimer) {\n clearTimeout(scope._moldSettingsDebounceTimer);\n }\n \n scope._moldSettingsDebounceTimer = setTimeout(function() {\n const total = Number(scope.moldTotal || 0);\n const active = Number(scope.moldActive || 0);\n \n if (total === (scope._lastMoldTotal || 0) && active === (scope._lastMoldActive || 0)) {\n return;\n }\n \n scope._lastMoldTotal = total;\n scope._lastMoldActive = active;\n \n scope.send({\n topic: 'moldSettings',\n payload: { total, active }\n });\n }, 500);\n };\n \n // Add mold form\n scope.openAddMold = function() {\n\n scope.showAddMoldForm = true;\n scope.newMold = {\n manufacturer: scope.selectedManufacturer || '',\n mold_name: '',\n cavities: '',\n active: ''\n };\n };\n \n scope.cancelAddMold = function() {\n scope.showAddMoldForm = false;\n scope.isSavingMold = false;\n scope.newMold = { manufacturer: '', mold_name: '', cavities: '', active: '' };\n };\n \n // Save new mold with proper debouncing\n scope.saveNewMold = function() {\n\n if (scope.isSavingMold) {\n console.log('Already saving, ignoring click');\n return;\n }\n \n const manufacturer = (scope.newMold.manufacturer || '').trim();\n const moldName = (scope.newMold.mold_name || '').trim();\n const theoretical = (scope.newMold.cavities || '').trim();\n const active = (scope.newMold.active || '').trim();\n \n if (!manufacturer || !moldName || !theoretical || !active) {\n alert('Please enter all values.');\n return;\n }\n \n scope.isSavingMold = true;\n \n // Clear any pending timeout\n if (scope._saveMoldTimeout) {\n clearTimeout(scope._saveMoldTimeout);\n }\n \n // Send after 100ms to consolidate rapid clicks\n scope._saveMoldTimeout = setTimeout(function() {\n console.log('Sending addMoldPreset request');\n scope.send({\n topic: 'addMoldPreset',\n payload: {\n manufacturer: manufacturer,\n mold_name: moldName,\n theoretical: theoretical,\n active: active\n }\n });\n scope._saveMoldTimeout = null;\n }, 100);\n };\n \n // Watch for incoming messages - FIXED\n // Watch for incoming messages\nscope.$watch('msg', function(newMsg, oldMsg) {\n if (!newMsg || !newMsg.topic) return;\n \n // Create unique key for this message\n const msgKey = newMsg.topic + '_' + (newMsg.payload ? JSON.stringify(newMsg.payload).substring(0, 100) : '');\n const now = Date.now();\n \n // Check if we've processed this message recently (within 1 second)\n if (scope._processedMessages[msgKey] && (now - scope._processedMessages[msgKey]) < 1000) {\n console.log('Duplicate message ignored:', newMsg.topic);\n return;\n }\n \n // Mark as processed\n scope._processedMessages[msgKey] = now;\n \n console.log('Processing message:', newMsg.topic, newMsg.payload);\n \n // =============================================\n // PAIRING HANDLER\n // =============================================\n if (newMsg.topic === 'pairMachineResult') {\n scope.isPairing = false;\n if (newMsg.payload && newMsg.payload.ok) {\n scope.pairingStatus = 'Conectado: ' + (newMsg.payload.machineId || '');\n scope.pairingCode = '';\n } else {\n scope.pairingStatus = (newMsg.payload && newMsg.payload.error) ? newMsg.payload.error : 'No se pudo conectar.';\n }\n return;\n }\n\n if (newMsg.topic === 'settingsReadOnly') {\n scope.readOnly = !!newMsg.payload;\n return;\n }\n\n// =============================================\n // WIFI HANDLERS (incoming from backend)\n // =============================================\n if (newMsg.topic === 'wifi:scan:result') {\n scope.wifiBusy.scan = false;\n scope.wifiOptions = Array.isArray(newMsg.payload) ? newMsg.payload : [];\n scope.wifiStatusText = scope.wifiOptions.length\n ? ('Encontradas ' + scope.wifiOptions.length + ' redes.')\n : 'No se encontraron redes (¿wifi bloqueado / sin antena / permisos?).';\n return;\n }\n\n if (newMsg.topic === 'wifi:status:result') {\n const d = newMsg.payload || {};\n scope.wifiCurrent = {\n ssid: d.ssid || '',\n ip: d.ip || '',\n mask: d.mask || '',\n broadcast: d.broadcast || ''\n };\n scope.wifiStatusText = d.ssid\n ? ('Conectado a: ' + d.ssid)\n : 'No conectado a WiFi.';\n return;\n }\n\n if (newMsg.topic === 'wifi:apply:result') {\n scope.wifiBusy.apply = false;\n const ok = !!(newMsg.payload && newMsg.payload.ok);\n scope.wifiStatusText = (newMsg.payload && newMsg.payload.message)\n ? newMsg.payload.message\n : (ok ? 'WiFi actualizado.' : 'Error actualizando WiFi.');\n\n // If success, refresh status after a moment\n if (ok) {\n setTimeout(function () { scope.wifiRefreshStatus(); scope.$applyAsync(); }, 1500);\n }\n return;\n }\n\n\n // =============================================\n // MOLD PRESET HANDLERS\n // =============================================\n if (newMsg.topic === 'manufacturersList') {\n scope.manufacturers = Array.isArray(newMsg.payload) ? newMsg.payload : [];\n console.log('Manufacturers loaded:', scope.manufacturers.length);\n return;\n }\n \n if (newMsg.topic === 'moldPresetsList') {\n scope.moldsForManufacturer = Array.isArray(newMsg.payload) ? newMsg.payload : [];\n console.log('Molds loaded:', scope.moldsForManufacturer.length);\n return;\n }\n \n if (newMsg.topic === 'moldPresetSelected') {\n const data = newMsg.payload || {};\n scope.moldTotal = data.total || 0;\n scope.moldActive = data.active || 0;\n console.log('Preset selected:', data);\n return;\n }\n \n if (newMsg.topic === 'addMoldResult') {\n console.log('Mold added successfully');\n scope.isSavingMold = false;\n scope.showAddMoldForm = false;\n scope.newMold = { manufacturer: '', mold_name: '', cavities: '', active: '' };\n \n // Refresh the molds list if manufacturer is selected\n if (scope.selectedManufacturer) {\n setTimeout(function() {\n scope.onManufacturerChange();\n }, 500);\n }\n return;\n }\n \n // =============================================\n // SHIFT CONFIG HANDLER - THIS IS THE FIX\n // =============================================\nif (newMsg.topic === 'shiftConfigData') {\n var config = newMsg.payload || {};\n\n // Populate shifts: convert saved strings -> Date objects\n scope.shifts = (config.shifts && config.shifts.length\n ? config.shifts\n : [{ start: '08:00', end: '16:00' }]\n ).map(function(s) {\n return {\n start: toTimeDate(s.start, '08:00'),\n end: toTimeDate(s.end, '16:00')\n };\n });\n\n scope.shiftChangeComp = config.shiftChangeCompensation || 10;\n scope.lunchBreak = config.lunchBreakMinutes || 30;\n scope.thresholdMultiplier = config.thresholdMultiplier || 1.5;\n scope.oeeThreshold = config.oeeAlertThreshold || 90;\n\n console.log('[SETTINGS] Loaded config:', scope.shifts.length, 'shifts');\n console.log('[SETTINGS] Shifts:', JSON.stringify(scope.shifts));\n return;\n }\n});\n \n // Initialize by loading manufacturers\n console.log('Initializing Settings page...');\n scope.loadManufacturers();\n scope.loadShiftConfig();\n\n\n // Initialize shift config\nscope.shifts = scope.shifts || [{\nstart: toTimeDate('08:00'),\nend: toTimeDate('16:00')\n}];\nscope.shiftChangeComp = scope.shiftChangeComp || 10;\nscope.lunchBreak = scope.lunchBreak || 30;\nscope.thresholdMultiplier = scope.thresholdMultiplier || 1.5;\nscope.oeeThreshold = scope.oeeThreshold || 90;\n\n// Load saved config on init\n\n// Add shift\nscope.addShift = function() {\n if (scope.readOnly) return;\n\n if (scope.shifts.length < 3) {\n scope.shifts.push({ start: '16:00', end: '00:00' });\n scope.updateShiftConfig();\n }\n};\n\n// Remove shift\nscope.removeShift = function(index) {\n if (scope.readOnly) return;\n\n if (scope.shifts.length > 1) {\n scope.shifts.splice(index, 1);\n scope.updateShiftConfig();\n }\n};\n\n// Save shift config\nscope.updateShiftConfig = function() {\n if (scope.readOnly) return;\n\n if (scope._shiftDebounce) clearTimeout(scope._shiftDebounce);\n \n scope._shiftDebounce = setTimeout(function() {\n // Convert Date objects to \"HH:MM\" strings if needed\n const cleanShifts = scope.shifts.map(function(shift) {\n let startStr = shift.start;\n let endStr = shift.end;\n \n // If it's a Date object, extract time\n if (shift.start instanceof Date) {\n startStr = shift.start.toTimeString().slice(0, 5); // \"HH:MM\"\n } else if (typeof shift.start === 'string' && shift.start.includes('T')) {\n // ISO string - extract time portion\n startStr = shift.start.split('T')[1].slice(0, 5);\n }\n \n if (shift.end instanceof Date) {\n endStr = shift.end.toTimeString().slice(0, 5);\n } else if (typeof shift.end === 'string' && shift.end.includes('T')) {\n endStr = shift.end.split('T')[1].slice(0, 5);\n }\n \n return { start: startStr, end: endStr };\n });\n \n scope.send({\n topic: 'saveShiftConfig',\n payload: {\n shifts: cleanShifts,\n shiftChangeCompensation: Number(scope.shiftChangeComp) || 10,\n lunchBreakMinutes: Number(scope.lunchBreak) || 30\n }\n });\n }, 500);\n};\n\nscope.isSaving = false;\nscope.saveStatus = '';\n\nscope.saveAllSettings = function() {\n if (scope.readOnly) return;\n\n scope.isSaving = true;\n scope.saveStatus = '';\n \n // Clean shifts (handle Date objects)\n const cleanShifts = scope.shifts.map(function(shift) {\n let startStr = shift.start;\n let endStr = shift.end;\n \n if (shift.start instanceof Date) {\n startStr = shift.start.toTimeString().slice(0, 5);\n } else if (typeof shift.start === 'string' && shift.start.includes('T')) {\n startStr = shift.start.split('T')[1].slice(0, 5);\n }\n \n if (shift.end instanceof Date) {\n endStr = shift.end.toTimeString().slice(0, 5);\n } else if (typeof shift.end === 'string' && shift.end.includes('T')) {\n endStr = shift.end.split('T')[1].slice(0, 5);\n }\n \n return { start: startStr, end: endStr };\n });\n \n scope.send({\n topic: 'saveAllSettings',\n payload: {\n shifts: cleanShifts,\n shiftChangeCompensation: Number(scope.shiftChangeComp) || 10,\n lunchBreakMinutes: Number(scope.lunchBreak) || 30,\n thresholdMultiplier: Number(scope.thresholdMultiplier) || 1.5,\n oeeAlertThreshold: Number(scope.oeeThreshold) || 90\n }\n });\n \n // Show feedback after short delay\n setTimeout(function() {\n scope.isSaving = false;\n scope.saveStatus = '✓ Saved';\n scope.$applyAsync();\n \n // Clear status after 3 seconds\n setTimeout(function() {\n scope.saveStatus = '';\n scope.$applyAsync();\n }, 3000);\n }, 500);\n};\n\n\n\n// Call on init\n\n\n\n\n\n// Save threshold config\nscope.updateThresholdConfig = function() {\n if (scope.readOnly) return;\n\n if (scope._thresholdDebounce) clearTimeout(scope._thresholdDebounce);\n \n scope._thresholdDebounce = setTimeout(function() {\n scope.send({\n topic: 'saveThresholdConfig',\n payload: {\n thresholdMultiplier: Number(scope.thresholdMultiplier) || 1.5,\n oeeAlertThreshold: Number(scope.oeeThreshold) || 90\n }\n });\n }, 500);\n};\n\n// Handle incoming config data\n// Add to existing $watch('msg', ...) block:\n/*\nif (msg.topic === 'shiftConfigData') {\n var config = msg.payload || {};\n scope.shifts = config.shifts || [{ start: '08:00', end: '16:00' }];\n scope.shiftChangeComp = config.shiftChangeCompensation || 10;\n scope.lunchBreak = config.lunchBreakMinutes || 30;\n scope.thresholdMultiplier = config.thresholdMultiplier || 1.5;\n scope.oeeThreshold = config.oeeAlertThreshold || 90;\n return;\n}\n\n// Call on init\nscope.loadShiftConfig();\n */\n})(scope);\n\n// Material theme cleanup\n(function ensureNoMaterialTint(){\n const root = document.getElementById('oee');\n if (!root) return;\n\n const targets = root.querySelectorAll([\n '.md-toolbar',\n 'md-toolbar',\n '.md-subheader',\n 'md-subheader',\n '.md-toolbar-tools',\n '.md-card-title'\n ].join(','));\n\n targets.forEach(el => {\n if (el && el.style) {\n if (el.style.background) {\n el.style.background = 'transparent';\n }\n if (el.style.backgroundColor) {\n el.style.backgroundColor = 'transparent';\n }\n }\n if (el && el.classList) {\n el.classList.remove(\n 'md-whiteframe-1dp','md-whiteframe-2dp','md-whiteframe-3dp',\n 'md-whiteframe-z1','md-whiteframe-z2','md-whiteframe-z3'\n );\n }\n });\n\n if (!document.getElementById('oee-theme-sentinel')) {\n const style = document.createElement('style');\n style.id = 'oee-theme-sentinel';\n style.textContent = `\n #oee .md-toolbar::before, #oee .md-toolbar::after,\n #oee .md-subheader::before, #oee .md-subheader::after,\n #oee md-toolbar::before, #oee md-toolbar::after,\n #oee md-subheader::before, #oee md-subheader::after {\n display: none !important;\n content: none !important;\n }\n `;\n document.head.appendChild(style);\n }\n})();\n</script>",
|
||
"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": "<style>\n@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@600;700&display=swap');\n\n/* SCALE: align 100% zoom with prior 125% appearance */\n:root {\nfont-size: 100%; /* was 120% */\n--bg-0: #0c1117;\n --bg-1: #131a23;\n --panel: #151e2b;\n --panel-hi: #1a2433;\n --text: #ecf3ff;\n --muted: #96a5b7;\n --accent: #2ea3ff;\n --accent-2: #1f8cf3;\n --good: #24d06f;\n --warn: #ffd100;\n --bad: #ff4d4f;\n --radius: 0.75rem;\n --shadow: 0 0.5rem 1rem rgba(0, 0, 0, .35), inset 0 0.0625rem 0 rgba(255, 255, 255, .05);\n --sidebar-width: 3.75rem;\n --sidebar-gap: clamp(0.75rem, 1.2vh, 1rem);\n --content-max: 100rem;\n --content-pad: clamp(1rem, 1.2vw, 1.4rem);\n --section-gap: clamp(0.75rem, 1vw, 1rem);\n --card-pad: clamp(1rem, 1.1vw, 1.25rem);\n --card-pad-lg: clamp(1.1rem, 1.2vw, 1.35rem);\n --fs-page-title: clamp(1.2rem, 1vw + 0.35rem, 1.7rem);\n --fs-section-title: clamp(0.95rem, 0.9vw + 0.25rem, 1.25rem);\n --fs-label: clamp(0.85rem, 0.7vw + 0.3rem, 1.05rem);\n --fs-body: clamp(0.8rem, 0.7vw + 0.28rem, 1rem);\n --progress-height: 0.875rem;\n}\n\n* {\n box-sizing: border-box;\n}\n\nhtml,\nbody,\n#oee {\n width: 100vw;\n height: 100vh;\n}\n\nhtml,\nbody {\n margin: 0;\n padding: 0;\n overflow-x: hidden;\n background: var(--bg-0);\n color: var(--text);\n font-family: 'Poppins', system-ui, 'Segoe UI', 'Roboto', sans-serif;\n font-weight: 600;\n}\n\nbody {\n overflow: hidden;\n}\n\nbody > md-content,\nbody > md-content > md-content,\n.nr-dashboard-template,\n.nr-dashboard-template md-content,\n.nr-dashboard-cardpanel,\n.nr-dashboard-cardpanel md-content {\n background: transparent !important;\n height: 100%;\n overflow: hidden;\n}\n\n.nr-dashboard-cardpanel,\n.nr-dashboard-cardpanel md-card,\n.nr-dashboard-cardpanel md-card-content {\n background: transparent !important;\n box-shadow: none !important;\n padding: 0 !important;\n}\n\n/* LAYOUT: lock sidebar + content grid across tabs */\n#oee {\n position: fixed;\n inset: 0;\n display: flex;\n overflow: hidden;\n}\n\n.sidebar {\n width: var(--sidebar-width);\n background: #0b1119;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: space-between;\n padding: clamp(0.625rem, 1.4vh, 0.9rem) clamp(0.5rem, 0.8vw, 0.75rem);\n}\n\n.side-top {\n display: flex;\n flex-direction: column;\n gap: var(--sidebar-gap);\n align-items: center;\n}\n\n.sb-btn {\n width: 2.75rem;\n height: 2.75rem;\n border-radius: 0.75rem;\n background: #0f1721;\n border: 1px solid #19222e;\n display: grid;\n place-items: center;\n color: #8fb3d9;\n cursor: pointer;\n transition: 0.16s box-shadow, 0.16s transform, 0.16s border-color;\n}\n\n.sb-btn.active {\n border-color: #2fd289;\n box-shadow: 0 0 0 0.125rem rgba(36, 208, 111, .25), 0 0.625rem 1.125rem rgba(36, 208, 111, .28);\n color: #2fd289;\n}\n\n.sb-ico {\n font-size: clamp(1.1rem, 1.2vw, 1.25rem);\n line-height: 1;\n}\n\n.sb-foot {\n font-size: clamp(0.6rem, 0.6vw, 0.7rem);\n color: #6c7b8d;\n letter-spacing: 0.12em;\n text-transform: uppercase;\n}\n\n.main {\n flex: 1;\n overflow: auto;\n padding: var(--content-pad);\n background: var(--bg-0);\n}\n\n.container {\n max-width: var(--content-max);\n margin: 0 auto;\n display: flex;\n flex-direction: column;\n gap: var(--section-gap);\n}\n\n.card {\n background: linear-gradient(160deg, var(--panel) 0%, var(--panel-hi) 100%);\n border-radius: var(--radius);\n box-shadow: var(--shadow);\n}\n\n/* HEADER: keep title and CTA row on one line */\n.page-heading {\n display: flex;\n align-items: center;\n gap: var(--section-gap);\n padding: 0 0.25rem;\n flex-wrap: wrap;\n}\n\n.page-title {\n margin: 0;\n font-size: var(--fs-page-title);\n letter-spacing: 0.05em;\n text-transform: uppercase;\n color: var(--text);\n}\n\n.page-actions {\n margin-left: auto;\n display: flex;\n gap: clamp(0.65rem, 1vw, 0.9rem);\n flex-wrap: wrap;\n align-items: center;\n}\n\n.action-btn {\n background: linear-gradient(180deg, #32ff7e 0%, #2fd289 100%);\n box-shadow: 0 0 1.25rem rgba(36, 208, 111, .5), inset 0 0.0625rem 0 rgba(255, 255, 255, .1);\n border: none;\n border-radius: var(--radius);\n color: var(--text);\n text-transform: uppercase;\n letter-spacing: 0.08em;\n font-weight: 700;\n padding: clamp(0.75rem, 1vw, 0.9rem) clamp(1rem, 1.4vw, 1.25rem);\n cursor: pointer;\n transition: 0.16s transform, 0.16s filter, 0.16s opacity;\n min-width: clamp(8.75rem, 12vw, 10rem);\n}\n\n.action-btn:hover:not(:disabled) {\n transform: translateY(-0.05rem);\n filter: brightness(1.08);\n}\n\n.action-btn:active:not(:disabled) {\n transform: none;\n filter: brightness(0.96);\n}\n\n.action-btn:disabled {\n opacity: 0.4;\n cursor: not-allowed;\n filter: grayscale(0.6);\n}\n\n.exit-multi-select {\n background: linear-gradient(180deg, #ff6b6b 0%, #ff5252 100%);\n box-shadow: 0 0 1.25rem rgba(255, 75, 75, .4), inset 0 0.0625rem 0 rgba(255, 255, 255, .1);\n}\n\n.multi-select-badge {\n display: inline-flex;\n align-items: center;\n gap: 0.5rem;\n background: linear-gradient(135deg, var(--accent) 0%, var(--accent-2) 100%);\n color: var(--text);\n padding: 0.5rem 1rem;\n border-radius: 999px;\n font-size: clamp(0.8rem, 0.9vw, 0.95rem);\n font-weight: 700;\n letter-spacing: 0.05em;\n box-shadow: 0 0.25rem 0.75rem rgba(46, 163, 255, 0.4);\n animation: badge-appear 0.3s ease;\n}\n\n@keyframes badge-appear {\n from {\n opacity: 0;\n transform: scale(0.8);\n }\n to {\n opacity: 1;\n transform: scale(1);\n }\n}\n\n/* TABLE: keep density + typography aligned with Home */\n.table-card {\npadding: var(--card-pad-lg);\ndisplay: flex;\nflex-direction: column;\ngap: clamp(0.75rem, 0.9vw, 0.95rem);\n}\n\n.table-scroll {\noverflow: auto;\nborder-radius: 0.625rem;\nborder: 1px solid rgba(31, 44, 60, 0.55);\nbackground: rgba(13, 19, 27, 0.6);\n}\n\n.workorders-table {\nwidth: 100%;\ntable-layout: fixed;\nborder-collapse: separate;\nborder-spacing: 0;\nmin-width: 52rem;\nfont-variant-numeric: tabular-nums;\n}\n\n.workorders-table thead th {\nposition: sticky;\ntop: 0;\nz-index: 2;\ncolor: var(--text);\ntext-transform: uppercase;\nletter-spacing: 0.04em;\nfont-size: clamp(0.75rem, 0.9vw, 0.85rem);\npadding: clamp(0.65rem, 0.9vw, 0.9rem);\nbackground: rgba(21, 30, 43, 0.9);\ntext-align: left;\nborder-bottom: 1px solid rgba(47, 67, 95, 0.55);\n}\n\n.workorders-table tbody td {\npadding: clamp(0.65rem, 0.95vw, 0.95rem);\ncolor: var(--text);\nfont-size: var(--fs-body);\nbackground: rgba(17, 24, 34, 0.7);\nborder-bottom: 1px solid rgba(31, 44, 60, 0.45);\n}\n\n.workorders-table thead th:not(:last-child),\n.workorders-table tbody td:not(:last-child) {\nborder-right: 1px solid rgba(31, 44, 60, 0.35);\n}\n\n.workorders-table tbody tr:nth-child(odd) td {\nbackground: rgba(17, 27, 39, 0.82);\n}\n\n.workorders-table tbody tr:hover td {\nbackground: rgba(36, 56, 80, 0.55);\n}\n\n.workorders-table thead th:nth-child(4),\n.workorders-table thead th:nth-child(5),\n.workorders-table thead th:nth-child(6),\n.workorders-table thead th:nth-child(9),\n.workorders-table tbody td:nth-child(4),\n.workorders-table tbody td:nth-child(5),\n.workorders-table tbody td:nth-child(6),\n.workorders-table tbody td:nth-child(9) {\ntext-align: right;\n}\n\n.progress-cell {\nmin-width: 9.5rem;\n}\n\n.progress-bar {\nheight: var(--progress-height);\nborder-radius: 999px;\nbackground: #111a24;\nborder: 1px solid #243244;\noverflow: hidden;\n}\n\n.progress-bar__fill {\nheight: 100%;\nwidth: 0;\ntransition: width 0.4s ease;\n}\n\n.workorders-table tbody tr {\ncursor: pointer;\ntransition: background 0.18s ease, border-color 0.18s ease;\nuser-select: none;\n}\n\n.workorders-table tbody tr.row-selected td {\nbackground: rgba(46, 163, 255, 0.18);\nborder-bottom-color: rgba(46, 163, 255, 0.45);\nbox-shadow: inset 0 0 0 1px rgba(46, 163, 255, 0.28);\n}\n\n.checkbox-cell {\nwidth: 3rem;\npadding-left: clamp(0.75rem, 1vw, 1rem) !important;\nopacity: 0;\npointer-events: none;\ntransition: opacity 0.2s ease;\n}\n\n.multi-select-mode .checkbox-cell {\nopacity: 1;\npointer-events: auto;\n}\n\n.checkbox-cell input[type=\"checkbox\"] {\nwidth: 1.125rem;\nheight: 1.125rem;\ncursor: pointer;\naccent-color: var(--accent);\n}\n\n.progress-bar__fill--pending {\n background: linear-gradient(90deg, rgba(150, 165, 183, .5), rgba(150, 165, 183, .8));\n}\n\n.progress-bar__fill--running {\n background: linear-gradient(90deg, rgba(46, 163, 255, .6), rgba(46, 163, 255, .85));\n}\n\n.progress-bar__fill--done {\n background: linear-gradient(90deg, rgba(36, 208, 111, .75), rgba(36, 208, 111, .95));\n}\n\n.status-badge {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n padding: 0.375rem 0.875rem;\n border-radius: 999px;\n font-size: clamp(0.75rem, 0.9vw, 0.85rem);\n letter-spacing: 0.2em;\n text-transform: uppercase;\n font-weight: 700;\n}\n\n.status-badge--pending {\n color: var(--muted);\n background: rgba(20, 28, 40, .65);\n border: 1px solid rgba(150, 165, 183, .35);\n}\n\n.status-badge--running {\n color: var(--text);\n background: rgba(30, 52, 73, .7);\n border: 1px solid rgba(46, 163, 255, .45);\n}\n\n.status-badge--done {\n color: var(--good);\n background: rgba(20, 56, 44, .7);\n border: 1px solid rgba(36, 208, 111, .45);\n}\n\n.table-footer {\n display: flex;\n justify-content: space-between;\n align-items: center;\n font-size: clamp(0.75rem, 0.9vw, 0.85rem);\n color: var(--muted);\n}\n\n.table-footer-hint {\n font-size: clamp(0.7rem, 0.8vw, 0.8rem);\n color: rgba(150, 165, 183, 0.6);\n font-style: italic;\n}\n\n@media (max-width: 68.75rem) {\n .page-actions {\n width: 100%;\n justify-content: flex-start;\n }\n}\n\n/* Override Node-RED Dashboard's gray backgrounds on text elements */\n.nr-dashboard-template p,\n.nr-dashboard-template h1,\n.nr-dashboard-template h2,\n.nr-dashboard-template h3,\n.nr-dashboard-template h4,\n.nr-dashboard-template label {\n background-color: transparent !important;\n}\n</style>\n<div id=\"oee\">\n <aside class=\"sidebar\">\n <div class=\"side-top\">\n <button class=\"sb-btn\" data-label=\"Home\" ng-click=\"gotoTab('Home')\"><span class=\"sb-ico\">🏠</span></button>\n <button class=\"sb-btn active\" data-label=\"Work Orders\" ng-click=\"gotoTab('Work Orders')\"><span class=\"sb-ico\">📋</span></button>\n <button class=\"sb-btn\" data-label=\"Alerts\" ng-click=\"gotoTab('Alerts')\"><span class=\"sb-ico\">⚠️</span></button>\n<!-- <button class=\"sb-btn\" data-label=\"Graphs\" ng-click=\"gotoTab('Graphs')\"><span class=\"sb-ico\">📊</span></button> -->\n <button class=\"sb-btn\" data-label=\"Help\" ng-click=\"gotoTab('Help')\"><span class=\"sb-ico\">❓</span></button>\n <button class=\"sb-btn\" data-label=\"Settings\" ng-click=\"gotoTab('Settings')\"><span class=\"sb-ico\">⚙️</span></button>\n </div>\n <div class=\"sb-foot\">OEE V1.0</div>\n </aside>\n\n <main class=\"main\">\n <div class=\"container\">\n <section class=\"page-heading\">\n <h1 class=\"page-title\">Ordenes de trabajo</h1>\n <div class=\"page-actions\">\n <span id=\"multi-select-badge\" class=\"multi-select-badge\" style=\"display:none;\">\n <span id=\"selected-count\">0</span> selected\n </span>\n <button class=\"action-btn\" data-action=\"upload-excel\">Subir Excel</button>\n <button class=\"action-btn\" data-action=\"start-work-order\" id=\"load-btn\">Cargar</button>\n <button class=\"action-btn\" data-action=\"complete-work-order\" id=\"done-btn\">Terminado</button>\n <button class=\"action-btn\" data-action=\"refresh-work-orders\">Refrescar</button>\n <button class=\"action-btn exit-multi-select\" id=\"exit-multi-select-btn\" style=\"display:none;\">Salir Multi-Seleccion</button>\n <input type=\"file\" id=\"wo-file\" accept=\".xlsx\" style=\"display:none\" />\n </div>\n </section>\n\n <section class=\"card table-card\">\n <div class=\"table-scroll\">\n <table class=\"workorders-table\" id=\"workorders-table\">\n <thead>\n <tr>\n <th class=\"checkbox-cell\"></th>\n <th>ID</th>\n <th>SKU</th>\n <th>META</th>\n <th>BUENAS</th>\n <th>SCRAP</th>\n <th>PROGRESO</th>\n <th>STATUS</th>\n <th>ULTIMA ACTUALIZACIÓN</th>\n </tr>\n </thead>\n <tbody id=\"workorders-body\"></tbody>\n </table>\n </div>\n <div class=\"table-footer\">\n <span id=\"workorders-count\">0 items</span>\n <span class=\"table-footer-hint\">Tip: Dejale picado para seleccionar multiples ordenes</span>\n </div>\n </section>\n </div>\n </main>\n</div>\n\n<script>\n(function(scope) {\n // Multi-select state\n scope.multiSelectMode = false;\n scope.selectedOrders = [];\n scope.longPressTimer = null;\n scope.longPressDuration = 500; // ms\n\n scope.gotoTab = function(tabName) {\n scope.send({ ui_control: { tab: tabName } });\n };\n\n window.workOrders = window.workOrders || [\n { id:\"WO-101\", sku:\"ST-003\", target:250, good:0, scrap:0, progressPercent:0, status:\"PENDING\", lastUpdateIso:\"\" }\n ];\n\n var elements = {\n tbody: document.getElementById('workorders-body'),\n count: document.getElementById('workorders-count'),\n buttons: document.querySelectorAll('[data-action]'),\n table: document.getElementById('workorders-table'),\n loadBtn: document.getElementById('load-btn'),\n doneBtn: document.getElementById('done-btn'),\n exitMultiSelectBtn: document.getElementById('exit-multi-select-btn'),\n multiSelectBadge: document.getElementById('multi-select-badge'),\n selectedCount: document.getElementById('selected-count')\n };\n\n function formatNumber(value) {\n var num = Number(value);\n return Number.isFinite(num) ? num.toLocaleString() : '0';\n }\n\n function formatDate(isoString) {\n if (!isoString) {\n return '—';\n }\n var date = new Date(isoString);\n if (Number.isNaN(date.valueOf())) {\n return isoString;\n }\n return date.toLocaleString();\n }\n\n function progressFillClass(status) {\n switch ((status || '').toUpperCase()) {\n case 'DONE': return 'progress-bar__fill--done';\n case 'RUNNING': return 'progress-bar__fill--running';\n default: return 'progress-bar__fill--pending';\n }\n }\n\n function statusBadgeClass(status) {\n switch ((status || '').toUpperCase()) {\n case 'DONE': return 'status-badge status-badge--done';\n case 'RUNNING': return 'status-badge status-badge--running';\n default: return 'status-badge status-badge--pending';\n }\n }\n\n function enterMultiSelectMode() {\n scope.multiSelectMode = true;\n elements.table.classList.add('multi-select-mode');\n elements.exitMultiSelectBtn.style.display = 'inline-block';\n updateButtonStates();\n scope.$applyAsync();\n }\n\n function exitMultiSelectMode() {\n scope.multiSelectMode = false;\n scope.selectedOrders = [];\n elements.table.classList.remove('multi-select-mode');\n elements.exitMultiSelectBtn.style.display = 'none';\n elements.multiSelectBadge.style.display = 'none';\n\n // Uncheck all checkboxes\n var checkboxes = elements.tbody.querySelectorAll('input[type=\"checkbox\"]');\n checkboxes.forEach(function(cb) {\n cb.checked = false;\n });\n\n // Remove all row selections\n var rows = elements.tbody.querySelectorAll('tr');\n rows.forEach(function(row) {\n row.classList.remove('row-selected');\n });\n\n updateButtonStates();\n scope.$applyAsync();\n }\n\n function updateButtonStates() {\n var selectedCount = scope.selectedOrders.length;\n\n if (scope.multiSelectMode && selectedCount > 0) {\n elements.multiSelectBadge.style.display = 'inline-flex';\n elements.selectedCount.textContent = selectedCount;\n\n // Disable Load button if multiple selected\n if (selectedCount > 1) {\n elements.loadBtn.disabled = true;\n } else {\n elements.loadBtn.disabled = false;\n }\n\n elements.doneBtn.disabled = false;\n } else if (scope.multiSelectMode) {\n elements.multiSelectBadge.style.display = 'none';\n elements.loadBtn.disabled = true;\n elements.doneBtn.disabled = true;\n } else {\n elements.loadBtn.disabled = false;\n elements.doneBtn.disabled = false;\n }\n }\n\n function toggleOrderSelection(order, checkbox, row) {\n var index = scope.selectedOrders.findIndex(function(o) {\n return o.id === order.id;\n });\n\n if (index === -1) {\n // Add to selection\n scope.selectedOrders.push(order);\n checkbox.checked = true;\n row.classList.add('row-selected');\n } else {\n // Remove from selection\n scope.selectedOrders.splice(index, 1);\n checkbox.checked = false;\n row.classList.remove('row-selected');\n }\n\n updateButtonStates();\n }\n\n function renderWorkOrders() {\n var orders = Array.isArray(window.workOrders) ? window.workOrders : [];\n orders = orders.filter(function(order) {\n return (order.status || '').toUpperCase() !== 'DONE';\n });\n\n if (elements.tbody) {\n elements.tbody.textContent = '';\n\n orders.forEach(function(order) {\n var tr = document.createElement('tr');\n tr.dataset.orderId = order.id || '';\n\n function appendCell(content, alignRight, className) {\n var td = document.createElement('td');\n if (className) td.className = className;\n if (alignRight) td.style.textAlign = 'right';\n if (content instanceof Node) {\n td.appendChild(content);\n } else {\n td.textContent = content;\n }\n tr.appendChild(td);\n }\n\n // Checkbox cell\n var checkboxTd = document.createElement('td');\n checkboxTd.className = 'checkbox-cell';\n var checkbox = document.createElement('input');\n checkbox.type = 'checkbox';\n checkbox.addEventListener('click', function(e) {\n e.stopPropagation();\n if (scope.multiSelectMode) {\n toggleOrderSelection(order, checkbox, tr);\n }\n });\n checkboxTd.appendChild(checkbox);\n tr.appendChild(checkboxTd);\n\n appendCell(order.id || '—');\n appendCell(order.sku || '—');\n appendCell(formatNumber(order.target), true);\n appendCell(formatNumber(order.goodParts), true);\n appendCell(formatNumber(order.scrapParts), true);\n\n var progressCell = document.createElement('td');\n progressCell.className = 'progress-cell';\n var bar = document.createElement('div');\n bar.className = 'progress-bar';\n var fill = document.createElement('div');\n fill.className = 'progress-bar__fill ' + progressFillClass(order.status);\n var percent = Math.max(0, Math.min(100, Math.round(Number(order.progressPercent) || 0)));\n fill.style.width = percent + '%';\n bar.appendChild(fill);\n progressCell.appendChild(bar);\n tr.appendChild(progressCell);\n\n var statusCell = document.createElement('td');\n var badge = document.createElement('span');\n badge.className = statusBadgeClass(order.status);\n badge.textContent = (order.status || 'PENDING').toUpperCase();\n statusCell.appendChild(badge);\n tr.appendChild(statusCell);\n\n appendCell(formatDate(order.lastUpdateIso));\n\n // Long-press functionality for entering multi-select mode\n tr.addEventListener('mousedown', function(e) {\n if (scope.multiSelectMode) return;\n\n scope.longPressTimer = setTimeout(function() {\n enterMultiSelectMode();\n toggleOrderSelection(order, checkbox, tr);\n }, scope.longPressDuration);\n });\n\n tr.addEventListener('mouseup', function() {\n if (scope.longPressTimer) {\n clearTimeout(scope.longPressTimer);\n scope.longPressTimer = null;\n }\n });\n\n tr.addEventListener('mouseleave', function() {\n if (scope.longPressTimer) {\n clearTimeout(scope.longPressTimer);\n scope.longPressTimer = null;\n }\n });\n\n // Right-click to enter multi-select mode\n tr.addEventListener('contextmenu', function(e) {\n e.preventDefault();\n if (!scope.multiSelectMode) {\n enterMultiSelectMode();\n }\n toggleOrderSelection(order, checkbox, tr);\n });\n\n // Regular click behavior\n tr.addEventListener('click', function(e) {\n if (scope.multiSelectMode) {\n toggleOrderSelection(order, checkbox, tr);\n } else {\n // Single-select mode (original behavior)\n if (scope.selectedRow && scope.selectedRow !== tr) {\n scope.selectedRow.classList.remove('row-selected');\n }\n scope.selectedRow = tr;\n scope.selectedOrder = order;\n tr.classList.add('row-selected');\n scope.$applyAsync();\n }\n });\n\n elements.tbody.appendChild(tr);\n });\n }\n\n if (elements.count) {\n var countText = orders.length + (orders.length === 1 ? ' item' : ' items');\n elements.count.textContent = countText;\n }\n }\n\n scope.renderWorkOrders = renderWorkOrders;\n renderWorkOrders();\n\n // Exit multi-select button\n elements.exitMultiSelectBtn.addEventListener('click', function() {\n exitMultiSelectMode();\n });\n\n if (elements.buttons) {\n elements.buttons.forEach(function(btn) {\n btn.addEventListener('click', function() {\n const action = btn.getAttribute(\"data-action\");\n switch (action) {\n case \"upload-excel\": handleUploadExcel(); break;\n case \"refresh-work-orders\": handleRefresh(); break;\n case \"start-work-order\": handleStart(); break;\n case \"complete-work-order\": handleComplete(); break;\n default: scope.send({ action }); break;\n }\n });\n });\n }\n\n function handleUploadExcel() {\n const input = document.getElementById(\"wo-file\");\n input.value = \"\";\n input.onchange = function (event) {\n const file = event.target.files[0];\n if (!file) return;\n const reader = new FileReader();\n reader.onload = function (e) {\n const base64 = e.target.result.split(\",\")[1];\n scope.send({\n action: \"upload-excel\",\n filename: file.name,\n payload: base64\n });\n };\n reader.readAsDataURL(file);\n };\n input.click();\n }\n\n function handleRefresh() {\n scope.send({ action: \"refresh-work-orders\" });\n }\n\n function handleStart() {\n if (scope.multiSelectMode) {\n if (scope.selectedOrders.length === 0) {\n return alert(\"Please select a work order first.\");\n }\n if (scope.selectedOrders.length > 1) {\n return alert(\"Cannot load multiple work orders at once.\");\n }\n scope.send({ action: \"start-work-order\", payload: scope.selectedOrders[0] });\n exitMultiSelectMode();\n } else {\n if (!scope.selectedOrder) return alert(\"Please select a work order first.\");\n scope.send({ action: \"start-work-order\", payload: scope.selectedOrder });\n }\n handleRefresh();\n }\n\n function handleComplete() {\n if (scope.multiSelectMode) {\n if (scope.selectedOrders.length === 0) {\n return alert(\"No work orders selected.\");\n }\n\n // Confirm multi-complete\n var confirmMsg = \"Mark \" + scope.selectedOrders.length + \" work order(s) as done?\";\n if (!confirm(confirmMsg)) return;\n\n // Send all selected orders for completion\n scope.selectedOrders.forEach(function(order) {\n scope.send({ action: \"complete-work-order\", payload: order });\n });\n\n exitMultiSelectMode();\n } else {\n if (!scope.selectedOrder) return alert(\"No active work order selected.\");\n scope.send({ action: \"complete-work-order\", payload: scope.selectedOrder });\n }\n handleRefresh();\n }\n\n scope.$watch(\"msg\", function(msg) {\n if (!msg) return;\n\n if (msg.topic === \"workOrderCycle\") {\n var update = msg.payload || {};\n var orders = Array.isArray(window.workOrders) ? window.workOrders.slice() : [];\n var found = false;\n\n orders = orders.map(function(order) {\n if ((order.id || \"\") === (update.id || \"\")) {\n found = true;\n return Object.assign({}, order, {\n goodParts: Number(update.goodParts) || 0,\n scrapParts: Number(update.scrapParts) || 0,\n target: Number(update.target) || 0,\n progressPercent: Number(update.progressPercent) || 0,\n status: update.status ? update.status.toUpperCase() : (order.status || \"PENDING\"),\n lastUpdateIso: update.lastUpdateIso || order.lastUpdateIso\n });\n }\n return order;\n });\n\n if (!found && update.id) {\n orders.push(update);\n }\n\n window.workOrders = orders;\n scope.renderWorkOrders();\n return;\n }\n\n if (msg.topic === \"workOrdersList\") {\n window.workOrders = msg.payload || [];\n scope.renderWorkOrders();\n }\n\n if (msg.topic === \"uploadStatus\") {\n alert(msg.payload.message || \"Upload complete\");\n handleRefresh();\n }\n });\n\n})(scope);\n\n(function ensureNoMaterialTint(){\n const root = document.getElementById('oee');\n if (!root) return;\n\n const targets = root.querySelectorAll([\n '.md-toolbar',\n 'md-toolbar',\n '.md-subheader',\n 'md-subheader',\n '.md-toolbar-tools',\n '.md-card-title'\n ].join(','));\n\n targets.forEach(el => {\n if (el && el.style) {\n if (el.style.background) {\n el.style.background = 'transparent';\n }\n if (el.style.backgroundColor) {\n el.style.backgroundColor = 'transparent';\n }\n }\n if (el && el.classList) {\n el.classList.remove(\n 'md-whiteframe-1dp','md-whiteframe-2dp','md-whiteframe-3dp',\n 'md-whiteframe-z1','md-whiteframe-z2','md-whiteframe-z3'\n );\n }\n });\n\n if (!document.getElementById('oee-theme-sentinel')) {\n const style = document.createElement('style');\n style.id = 'oee-theme-sentinel';\n style.textContent = `\n #oee .md-toolbar::before, #oee .md-toolbar::after,\n #oee .md-subheader::before, #oee .md-subheader::after,\n #oee md-toolbar::before, #oee md-toolbar::after,\n #oee md-subheader::before, #oee md-subheader::after {\n display: none !important;\n content: none !important;\n }\n `;\n document.head.appendChild(style);\n }\n})();\n\nscope.$evalAsync(scope.renderWorkOrders);\n</script>\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": "<style>\n :root {\n font-size: 125%;\n --bg-0: #0c1117;\n --bg-1: #131a23;\n --panel: #151e2b;\n --panel-hi: #1a2433;\n --text: #ecf3ff;\n --muted: #96a5b7;\n --accent: #2ea3ff;\n --accent-2: #1f8cf3;\n --good: #24d06f;\n --warn: #ffd100;\n --bad: #ff4d4f;\n --radius: 0.75rem;\n --shadow: 0 0.5rem 1rem rgba(0, 0, 0, .35),\n inset 0 0.0625rem 0 rgba(255, 255, 255, .05);\n }\n\n /* Base page styling – dark background + white text */\n html,\n body {\n margin: 0;\n padding: 0;\n width: 100vw;\n height: 100vh;\n overflow: hidden;\n background: var(--bg-0);\n color: var(--text);\n font-family: 'Poppins', system-ui, -apple-system, BlinkMacSystemFont,\n 'Segoe UI', sans-serif;\n font-weight: 600;\n }\n\n /* Kill Node-RED default gray cards / shadows everywhere */\n body.nr-dashboard-theme md-content,\n body.nr-dashboard-theme md-content md-card,\n .nr-dashboard-template,\n .nr-dashboard-template md-content,\n .nr-dashboard-cardpanel,\n .nr-dashboard-cardpanel md-card,\n .nr-dashboard-cardpanel md-card-content {\n background-color: transparent !important;\n box-shadow: none !important;\n border-radius: 0 !important;\n padding: 0 !important;\n }\n\n .masonry-container {\n background: transparent !important;\n }\n\n /* Default text color on all tabs */\n /* Force main text elements to be white */\n .nr-dashboard-template h1,\n .nr-dashboard-template h2,\n .nr-dashboard-template h3,\n .nr-dashboard-template h4,\n .nr-dashboard-template p,\n .nr-dashboard-template label {\n color: var(--text) !important;\n background-color: transparent !important;\n }\n\n /* Default for spans / table cells, but allow more specific overrides (e.g. severity badges) */\n .nr-dashboard-template span,\n .nr-dashboard-template th,\n .nr-dashboard-template td {\n color: var(--text);\n background-color: transparent !important;\n }\n\n /* Utility for softer text (help paragraphs, hints) */\n .nr-dashboard-template .muted {\n color: var(--text) !important;\n }\n\n /* Buttons – remove material text shadow so they look crisp */\n .nr-dashboard-template .md-button {\n text-shadow: none !important;\n }\n\n /* Selection color */\n ::selection {\n background-color: rgba(46, 163, 255, .35);\n color: #fff;\n }\n\n ::-moz-selection {\n background-color: rgba(46, 163, 255, .35);\n color: #fff;\n }\n body.nr-dashboard-theme md-toolbar,\n body.nr-dashboard-theme md-toolbar .md-toolbar-tools,\n body.nr-dashboard-theme md-toolbar h1 {\n color: var(--text) !important;\n }\n\n body.nr-dashboard-theme md-tabs md-tab,\n body.nr-dashboard-theme md-tabs md-tab span {\n color: var(--text) !important;\n }\n\n /* Active tab gets accent color */\n body.nr-dashboard-theme md-tabs md-tab.md-active span {\n color: var(--accent) !important;\n }\n</style>",
|
||
"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": "<style>\n /* ============================================================ */\n /* ANOMALY ALERT SYSTEM - GLOBAL FLOATING PANEL & NOTIFICATIONS */\n /* ============================================================ */\n\n /* Floating Alert Panel Container */\n #anomaly-alert-panel {\n position: fixed;\n top: 0;\n right: 0;\n width: 400px;\n height: 100vh;\n background: linear-gradient(160deg, #151e2b 0%, #1a2433 100%);\n box-shadow: -0.5rem 0 2rem rgba(0, 0, 0, 0.5);\n z-index: 9999;\n transform: translateX(100%);\n transition: transform 0.3s ease;\n display: flex;\n flex-direction: column;\n font-family: 'Poppins', sans-serif;\n border-left: 2px solid #ff4d4f;\n }\n\n #anomaly-alert-panel.expanded {\n transform: translateX(0);\n }\n\n /* Alert Toggle Button */\n #anomaly-toggle-btn {\n position: fixed;\n top: 50%;\n right: 0;\n transform: translateY(-50%);\n background: linear-gradient(180deg, #ff5252 0%, #ff4d4f 100%);\n border: none;\n border-radius: 0.75rem 0 0 0.75rem;\n padding: 1rem 0.75rem;\n cursor: pointer;\n z-index: 10000;\n box-shadow: -0.25rem 0.5rem 1rem rgba(255, 77, 79, 0.6);\n transition: all 0.2s ease;\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: 0.5rem;\n color: #ecf3ff;\n font-weight: 700;\n font-size: 0.75rem;\n letter-spacing: 0.1em;\n text-transform: uppercase;\n writing-mode: vertical-rl;\n }\n\n #anomaly-toggle-btn:hover {\n transform: translateY(-50%) translateX(-0.25rem);\n filter: brightness(1.1);\n }\n\n #anomaly-toggle-btn.has-alerts {\n animation: alert-pulse 2s infinite;\n }\n\n @keyframes alert-pulse {\n\n 0%,\n 100% {\n box-shadow: -0.25rem 0.5rem 1rem rgba(255, 77, 79, 0.6);\n }\n\n 50% {\n box-shadow: -0.25rem 0.5rem 2rem rgba(255, 77, 79, 1);\n }\n }\n\n .alert-badge {\n background: #fff;\n color: #ff4d4f;\n border-radius: 50%;\n width: 24px;\n height: 24px;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 0.7rem;\n font-weight: 700;\n writing-mode: horizontal-tb;\n }\n\n /* Panel Header */\n .anomaly-panel-header {\n padding: 1.5rem;\n border-bottom: 1px solid rgba(255, 255, 255, 0.1);\n display: flex;\n justify-content: space-between;\n align-items: center;\n }\n\n .anomaly-panel-title {\n font-size: 1.1rem;\n font-weight: 700;\n color: #ecf3ff;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n margin: 0;\n }\n\n .anomaly-close-btn {\n background: transparent;\n border: none;\n color: #96a5b7;\n font-size: 1.5rem;\n cursor: pointer;\n transition: color 0.2s;\n }\n\n .anomaly-close-btn:hover {\n color: #ecf3ff;\n }\n\n /* Alert List */\n .anomaly-alert-list {\n flex: 1;\n overflow-y: auto;\n padding: 1rem;\n display: flex;\n flex-direction: column;\n gap: 0.75rem;\n }\n\n .anomaly-alert-item {\n background: rgba(17, 24, 34, 0.7);\n border-radius: 0.75rem;\n padding: 1rem;\n border-left: 4px solid;\n display: flex;\n flex-direction: column;\n gap: 0.5rem;\n transition: all 0.2s;\n }\n\n .anomaly-alert-item:hover {\n background: rgba(36, 56, 80, 0.55);\n }\n\n .anomaly-alert-item.critical {\n border-left-color: #ff4d4f;\n }\n\n .anomaly-alert-item.warning {\n border-left-color: #ffd100;\n }\n\n .anomaly-alert-item.info {\n border-left-color: #2ea3ff;\n }\n\n .anomaly-alert-header {\n display: flex;\n justify-content: space-between;\n align-items: flex-start;\n gap: 0.5rem;\n }\n\n .anomaly-alert-title {\n font-size: 0.9rem;\n font-weight: 700;\n color: #ecf3ff;\n margin: 0;\n flex: 1;\n }\n\n .anomaly-severity-badge {\n font-size: 0.65rem;\n font-weight: 700;\n text-transform: uppercase;\n letter-spacing: 0.1em;\n padding: 0.25rem 0.5rem;\n border-radius: 999px;\n }\n\n .anomaly-severity-badge.critical {\n background: rgba(255, 77, 79, 0.2);\n color: #ff4d4f;\n }\n\n .anomaly-severity-badge.warning {\n background: rgba(255, 209, 0, 0.2);\n color: #ffd100;\n }\n\n .anomaly-severity-badge.info {\n background: rgba(46, 163, 255, 0.2);\n color: #2ea3ff;\n }\n\n .anomaly-alert-desc {\n font-size: 0.8rem;\n color: #96a5b7;\n margin: 0;\n line-height: 1.4;\n }\n\n .anomaly-alert-time {\n font-size: 0.7rem;\n color: #6c7b8d;\n margin: 0;\n }\n\n .anomaly-alert-actions {\n display: flex;\n gap: 0.5rem;\n margin-top: 0.5rem;\n }\n\n .anomaly-ack-btn {\n background: linear-gradient(180deg, #32ff7e 0%, #2fd289 100%);\n border: none;\n border-radius: 0.5rem;\n color: #ecf3ff;\n padding: 0.5rem 1rem;\n font-size: 0.75rem;\n font-weight: 700;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n cursor: pointer;\n transition: all 0.2s;\n }\n\n .anomaly-ack-btn:hover {\n transform: translateY(-1px);\n filter: brightness(1.1);\n }\n\n .anomaly-empty-state {\n text-align: center;\n padding: 3rem 1rem;\n color: #6c7b8d;\n }\n\n .anomaly-empty-icon {\n font-size: 3rem;\n margin-bottom: 1rem;\n }\n\n /* Pop-up Notification */\n #anomaly-popup-container {\n position: fixed;\n top: 2rem;\n left: 50%;\n transform: translateX(-50%);\n z-index: 10001;\n display: flex;\n flex-direction: column;\n gap: 1rem;\n pointer-events: none;\n }\n\n .anomaly-popup {\n background: linear-gradient(160deg, #151e2b 0%, #1a2433 100%);\n border-radius: 0.75rem;\n padding: 1.5rem;\n box-shadow: 0 1rem 3rem rgba(0, 0, 0, 0.7);\n min-width: 400px;\n max-width: 600px;\n border-left: 6px solid;\n pointer-events: auto;\n animation: popup-appear 0.3s ease;\n position: relative;\n }\n\n @keyframes popup-appear {\n from {\n opacity: 0;\n transform: translateY(-2rem);\n }\n\n to {\n opacity: 1;\n transform: translateY(0);\n }\n }\n\n .anomaly-popup.critical {\n border-left-color: #ff4d4f;\n }\n\n .anomaly-popup.warning {\n border-left-color: #ffd100;\n }\n\n .anomaly-popup.info {\n border-left-color: #2ea3ff;\n }\n\n .anomaly-popup-header {\n display: flex;\n justify-content: space-between;\n align-items: flex-start;\n margin-bottom: 0.75rem;\n }\n\n .anomaly-popup-title {\n font-size: 1.1rem;\n font-weight: 700;\n color: #ecf3ff;\n margin: 0;\n flex: 1;\n }\n\n .anomaly-popup-close {\n background: transparent;\n border: none;\n color: #96a5b7;\n font-size: 1.5rem;\n cursor: pointer;\n line-height: 1;\n padding: 0;\n transition: color 0.2s;\n }\n\n .anomaly-popup-close:hover {\n color: #ecf3ff;\n }\n\n .anomaly-popup-desc {\n font-size: 0.9rem;\n color: #96a5b7;\n margin: 0 0 1rem 0;\n line-height: 1.5;\n }\n\n .anomaly-popup-ack {\n background: linear-gradient(180deg, #ff5252 0%, #ff4d4f 100%);\n border: none;\n border-radius: 0.5rem;\n color: #ecf3ff;\n padding: 0.75rem 1.5rem;\n font-size: 0.85rem;\n font-weight: 700;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n cursor: pointer;\n transition: all 0.2s;\n width: 100%;\n }\n\n .anomaly-popup-ack:hover {\n transform: translateY(-2px);\n filter: brightness(1.1);\n }\n\n /* Scrollbar styling */\n .anomaly-alert-list::-webkit-scrollbar {\n width: 8px;\n }\n\n .anomaly-alert-list::-webkit-scrollbar-track {\n background: rgba(0, 0, 0, 0.2);\n border-radius: 4px;\n }\n\n .anomaly-alert-list::-webkit-scrollbar-thumb {\n background: rgba(150, 165, 183, 0.3);\n border-radius: 4px;\n }\n\n .anomaly-alert-list::-webkit-scrollbar-thumb:hover {\n background: rgba(150, 165, 183, 0.5);\n }\n\n .reason-overlay {\n position: fixed;\n inset: 0;\n background: rgba(10, 15, 22, 0.78);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 10002;\n padding: 1rem;\n }\n\n .reason-card {\n width: min(640px, 95vw);\n background: linear-gradient(160deg, #151e2b 0%, #1a2433 100%);\n border: 1px solid rgba(46, 163, 255, 0.35);\n border-radius: 0.9rem;\n box-shadow: 0 1rem 2.5rem rgba(0, 0, 0, 0.6);\n padding: 1rem;\n }\n\n .reason-title {\n margin: 0 0 0.35rem 0;\n color: #ecf3ff;\n font-size: 1.05rem;\n font-weight: 700;\n }\n\n .reason-sub {\n margin: 0 0 0.75rem 0;\n color: #96a5b7;\n font-size: 0.85rem;\n }\n\n .reason-breadcrumb {\n font-size: 0.82rem;\n color: #8fb3d9;\n margin-bottom: 0.75rem;\n }\n\n .reason-grid {\n display: grid;\n grid-template-columns: repeat(2, minmax(0, 1fr));\n gap: 0.55rem;\n margin-bottom: 0.75rem;\n }\n\n .reason-btn {\n min-height: 64px;\n border: 1px solid #243244;\n border-radius: 0.65rem;\n background: #111a24;\n color: #ecf3ff;\n font-size: 0.9rem;\n font-weight: 700;\n padding: 0.65rem;\n text-align: left;\n cursor: pointer;\n }\n\n .reason-actions {\n display: flex;\n gap: 0.5rem;\n }\n\n .reason-action {\n flex: 1;\n min-height: 52px;\n border-radius: 0.6rem;\n border: none;\n font-size: 0.84rem;\n font-weight: 700;\n cursor: pointer;\n text-transform: uppercase;\n }\n\n .reason-back {\n background: #263242;\n color: #ecf3ff;\n }\n\n .reason-cancel {\n background: #32445a;\n color: #ecf3ff;\n }\n\n @media (max-width: 768px) {\n .reason-grid {\n grid-template-columns: 1fr;\n }\n }\n</style>\n\n<!-- Floating Toggle Button -->\n<button id=\"anomaly-toggle-btn\" ng-click=\"toggleAnomalyPanel()\">\n <span class=\"alert-badge\" ng-if=\"activeAnomalyCount > 0\">{{activeAnomalyCount}}</span>\n <span ng-if=\"activeAnomalyCount === 0\">⚠️</span>\n <span style=\"writing-mode: vertical-rl;\">ALERTS</span>\n</button>\n\n<!-- Floating Alert Panel -->\n<div id=\"anomaly-alert-panel\" ng-class=\"{expanded: anomalyPanelExpanded}\">\n <div class=\"anomaly-panel-header\">\n <h2 class=\"anomaly-panel-title\">Active Alerts</h2>\n <button class=\"anomaly-close-btn\" ng-click=\"toggleAnomalyPanel()\">×</button>\n </div>\n\n <div class=\"anomaly-alert-list\">\n <div class=\"anomaly-empty-state\" ng-if=\"activeAnomalies.length === 0\">\n <div class=\"anomaly-empty-icon\">✅</div>\n <p>No active alerts</p>\n <p style=\"font-size: 0.8rem; margin-top: 0.5rem;\">All systems operating normally</p>\n </div>\n\n <div class=\"anomaly-alert-item {{anomaly.severity}}\" ng-repeat=\"anomaly in activeAnomalies\">\n <div class=\"anomaly-alert-header\">\n <h3 class=\"anomaly-alert-title\">{{anomaly.title}}</h3>\n <span class=\"anomaly-severity-badge {{anomaly.severity}}\">{{anomaly.severity}}</span>\n </div>\n <p class=\"anomaly-alert-desc\">{{anomaly.description}}</p>\n <p class=\"anomaly-alert-time\">{{formatTimestamp(anomaly.tsMs)}}</p>\n <div class=\"anomaly-alert-actions\">\n <button class=\"anomaly-ack-btn\" ng-click=\"acknowledgeAnomaly(anomaly)\">Acknowledge</button>\n </div>\n </div>\n </div>\n</div>\n\n<!-- Pop-up Notification Container -->\n<div id=\"anomaly-popup-container\">\n <div class=\"anomaly-popup {{popup.severity}}\" ng-repeat=\"popup in popupNotifications\">\n <div class=\"anomaly-popup-header\">\n <h3 class=\"anomaly-popup-title\">{{popup.title}}</h3>\n <button class=\"anomaly-popup-close\" ng-click=\"closePopup(popup)\">×</button>\n </div>\n <p class=\"anomaly-popup-desc\">{{popup.description}}</p>\n <button class=\"anomaly-popup-ack\"ng-if=\"popup.requires_ack !== false\" ng-click=\"acknowledgePopup(popup)\">Acknowledge Alert</button>\n </div>\n</div>\n\n<div class=\"reason-overlay\" ng-if=\"reasonPrompt.show\">\n <div class=\"reason-card\">\n <h3 class=\"reason-title\">Selecciona razón de paro</h3>\n <p class=\"reason-sub\">{{reasonPrompt.anomalyTitle || 'Incidente de downtime'}}</p>\n <div class=\"reason-breadcrumb\">\n <span>Paso {{reasonPrompt.step}} de 2</span>\n <span ng-if=\"reasonPrompt.selectedCategory\"> | {{reasonPrompt.selectedCategory.label}}</span>\n </div>\n\n <div class=\"reason-grid\" ng-if=\"reasonPrompt.step === 1\">\n <button class=\"reason-btn\" ng-repeat=\"c in reasonPrompt.categories\" ng-click=\"pickReasonCategory(c)\">\n {{c.label}}\n </button>\n </div>\n\n <div class=\"reason-grid\" ng-if=\"reasonPrompt.step === 2\">\n <button class=\"reason-btn\" ng-repeat=\"d in reasonPrompt.details\" ng-click=\"submitReasonForAnomaly(d)\">\n {{d.label}}\n </button>\n </div>\n\n <div class=\"reason-actions\">\n <button class=\"reason-action reason-back\" ng-if=\"reasonPrompt.step === 2\" ng-click=\"reasonPrompt.step = 1\">Atrás</button>\n <button class=\"reason-action reason-cancel\" ng-click=\"cancelReasonPrompt()\">Cancelar</button>\n </div>\n </div>\n</div>\n\n<script>\n (function(scope) {\n scope.anomalyPanelExpanded = false;\n scope.activeAnomalies = [];\n scope.popupNotifications = [];\n scope.activeAnomalyCount = 0;\n scope.reasonCatalog = { version: 1, downtime: [] };\n scope.ackedIncidentKeys = {};\n scope.reasonPrompt = {\n show: false,\n step: 1,\n categories: [],\n details: [],\n selectedCategory: null,\n anomaly: null,\n anomalyTitle: ''\n };\n\n function getKey(a) {\n return a.event_id || a.alert_id || (a.anomaly_type + ':' + (a.work_order_id || '') + ':' + ((a.data && a.data.last_cycle_timestamp) || ''));\n }\n\n function getIncidentKey(a) {\n return a.incidentKey || (a.data && a.data.last_cycle_timestamp\n ? [a.anomaly_type || 'downtime', a.work_order_id || '', String(a.data.last_cycle_timestamp)].join(':')\n : getKey(a));\n }\n\n function requiresDowntimeReason(a) {\n var t = a && a.anomaly_type;\n return t === 'microstop' || t === 'macrostop';\n }\n\n function normalizeCatalog(raw) {\n var fallback = {\n version: 1,\n downtime: [\n {\n id: 'operacion',\n label: 'Operacion',\n children: [{ id: 'sin-detalle', label: 'Sin detalle' }]\n }\n ]\n };\n if (!raw || !Array.isArray(raw.downtime) || raw.downtime.length === 0) {\n return fallback;\n }\n return raw;\n }\n\n function removeFromUi(anomaly) {\n var idx = scope.activeAnomalies.findIndex(function(a) {\n return (a.event_id && a.event_id === anomaly.event_id) || (a.anomaly_type === anomaly.anomaly_type && a.tsMs === anomaly.tsMs);\n });\n if (idx !== -1) {\n scope.activeAnomalies.splice(idx, 1);\n scope.activeAnomalyCount = scope.activeAnomalies.length;\n }\n scope.popupNotifications = scope.popupNotifications.filter(function(p) {\n return getKey(p) !== getKey(anomaly);\n });\n }\n\n function sendSimpleAck(anomaly) {\n var eventId = anomaly.event_id || anomaly.alert_id || anomaly.tsMs;\n var incidentKey = getIncidentKey(anomaly);\n scope.send({\n topic: 'acknowledge-anomaly',\n payload: {\n event_id: eventId,\n incidentKey: incidentKey,\n anomalyType: anomaly.anomaly_type || null,\n tsMs: Date.now()\n }\n });\n scope.ackedIncidentKeys[incidentKey] = true;\n removeFromUi(anomaly);\n scope.$applyAsync();\n }\n\n scope.toggleAnomalyPanel = function() {\n scope.anomalyPanelExpanded = !scope.anomalyPanelExpanded;\n var btn = document.getElementById('anomaly-toggle-btn');\n if (btn) {\n if (scope.activeAnomalyCount > 0) btn.classList.add('has-alerts');\n else btn.classList.remove('has-alerts');\n }\n };\n\n scope.formatTimestamp = function(tsMs) {\n if (!tsMs) return '';\n return new Date(tsMs).toLocaleString();\n };\n\n scope.cancelReasonPrompt = function() {\n scope.reasonPrompt.show = false;\n scope.reasonPrompt.step = 1;\n scope.reasonPrompt.selectedCategory = null;\n scope.reasonPrompt.details = [];\n scope.reasonPrompt.anomaly = null;\n };\n\n scope.pickReasonCategory = function(category) {\n scope.reasonPrompt.selectedCategory = category;\n scope.reasonPrompt.details = Array.isArray(category.children) ? category.children : [];\n scope.reasonPrompt.step = 2;\n };\n\n scope.submitReasonForAnomaly = function(detail) {\n var a = scope.reasonPrompt.anomaly;\n if (!a || !scope.reasonPrompt.selectedCategory || !detail) return;\n var eventId = a.event_id || a.alert_id || a.tsMs;\n var incidentKey = getIncidentKey(a);\n var category = scope.reasonPrompt.selectedCategory;\n\n scope.send({\n topic: 'anomaly-reason-submit',\n payload: {\n event_id: eventId,\n incidentKey: incidentKey,\n anomalyType: a.anomaly_type || null,\n reasonType: 'downtime',\n reasonPath: [\n { id: category.id || null, label: category.label || null },\n { id: detail.id || null, label: detail.label || null }\n ],\n reasonText: [category.label || '', detail.label || ''].filter(Boolean).join(' > '),\n catalogVersion: scope.reasonCatalog.version || null,\n tsMs: Date.now()\n }\n });\n\n scope.ackedIncidentKeys[incidentKey] = true;\n removeFromUi(a);\n scope.cancelReasonPrompt();\n scope.$applyAsync();\n };\n\n function startReasonPrompt(anomaly) {\n var catalog = normalizeCatalog(scope.reasonCatalog);\n var categories = Array.isArray(catalog.downtime) ? catalog.downtime : [];\n if (!categories.length) {\n sendSimpleAck(anomaly);\n return;\n }\n scope.reasonPrompt.show = true;\n scope.reasonPrompt.step = 1;\n scope.reasonPrompt.categories = categories;\n scope.reasonPrompt.details = [];\n scope.reasonPrompt.selectedCategory = null;\n scope.reasonPrompt.anomaly = anomaly;\n scope.reasonPrompt.anomalyTitle = anomaly.title || '';\n scope.$applyAsync();\n }\n\n scope.acknowledgeAnomaly = function(anomaly) {\n if (!anomaly) return;\n var incidentKey = getIncidentKey(anomaly);\n if (requiresDowntimeReason(anomaly) && !scope.ackedIncidentKeys[incidentKey]) {\n startReasonPrompt(anomaly);\n return;\n }\n sendSimpleAck(anomaly);\n };\n\n scope.closePopup = function(popup) {\n var index = scope.popupNotifications.indexOf(popup);\n if (index !== -1) scope.popupNotifications.splice(index, 1);\n };\n\n scope.acknowledgePopup = function(popup) {\n if (!popup) return;\n var incidentKey = getIncidentKey(popup);\n if (requiresDowntimeReason(popup) && !scope.ackedIncidentKeys[incidentKey]) {\n startReasonPrompt(popup);\n return;\n }\n sendSimpleAck(popup);\n };\n\n scope.$watch('msg', function(msg) {\n if (!msg || !msg.topic) return;\n\n if (msg.topic === 'reasonCatalogData') {\n scope.reasonCatalog = normalizeCatalog(msg.payload || null);\n return;\n }\n\n if (msg.topic === 'anomaly-ui-update') {\n var payload = msg.payload || {};\n if (payload.reasonCatalog) {\n scope.reasonCatalog = normalizeCatalog(payload.reasonCatalog);\n }\n\n var map = {};\n (payload.activeAnomalies || []).forEach(function(a) {\n var k = getKey(a);\n if (!map[k] || (a.tsMs || 0) > (map[k].tsMs || 0)) map[k] = a;\n });\n scope.activeAnomalies = Object.keys(map).map(function(k){ return map[k]; })\n .sort(function(a,b){ return (b.tsMs||0) - (a.tsMs||0); });\n scope.activeAnomalyCount = payload.activeCount || scope.activeAnomalies.length;\n\n if (payload.updates && Array.isArray(payload.updates)) {\n payload.updates.forEach(function(update) {\n var anomaly = update.anomaly || update;\n var key = getKey(anomaly);\n if (update.status === 'resolved' || anomaly.status === 'resolved') {\n scope.popupNotifications = scope.popupNotifications.filter(function(p) {\n return getKey(p) !== key;\n });\n } else if (anomaly.severity === 'critical' || anomaly.severity === 'warning') {\n var existingIndex = scope.popupNotifications.findIndex(function(p) {\n return getKey(p) === key;\n });\n if (existingIndex !== -1) scope.popupNotifications[existingIndex] = anomaly;\n else scope.popupNotifications.push(anomaly);\n }\n });\n }\n\n if (payload.softNotifications && Array.isArray(payload.softNotifications)) {\n payload.softNotifications.forEach(function(anomaly) {\n if (anomaly.anomaly_type !== 'slow-cycle') return;\n var existingPopup = scope.popupNotifications.find(function(p) {\n return p.tsMs === anomaly.tsMs && p.anomaly_type === anomaly.anomaly_type;\n });\n if (!existingPopup) {\n anomaly.requires_ack = false;\n scope.popupNotifications.push(anomaly);\n (function(popupRef) {\n setTimeout(function() {\n scope.closePopup(popupRef);\n scope.$applyAsync();\n }, 3000);\n })(anomaly);\n }\n });\n }\n\n var btn = document.getElementById('anomaly-toggle-btn');\n if (btn) {\n if (scope.activeAnomalyCount > 0) btn.classList.add('has-alerts');\n else btn.classList.remove('has-alerts');\n }\n\n scope.$applyAsync();\n }\n });\n})(scope);\n</script>\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"
|
||
}
|
||
}
|
||
] |