Files
Projects-plastic/process_recovery_response.js
Marcelo b66cb97f16 MVP
2025-11-28 09:11:59 -06:00

65 lines
2.5 KiB
JavaScript

// ===== PROCESS RECOVERY RESPONSE =====
// This function processes the database response from startup recovery query
// Connect this to the output of the MySQL node that executed the startup query
if (!msg.payload || msg.payload.length === 0) {
// No previous session found - start fresh
node.warn("No previous session found. Starting fresh.");
msg._recoveryStatus = "no-session";
msg.payload = {
type: "info",
message: "No previous session to restore. System ready for new work orders."
};
return [null, msg]; // Output 2: info message to dashboard
}
const sessionData = msg.payload[0];
const now = Date.now();
const timeSinceLastUpdate = now - sessionData.last_update_time;
const hoursElapsed = timeSinceLastUpdate / (1000 * 60 * 60);
// If last update was more than 24 hours ago, consider it stale
if (hoursElapsed > 24) {
node.warn(`Previous session is stale (${hoursElapsed.toFixed(1)} hours old). Starting fresh.`);
msg._recoveryStatus = "session-stale";
msg.payload = {
type: "warning",
message: `Previous session found but is ${hoursElapsed.toFixed(1)} hours old. Starting fresh.`
};
// Deactivate stale session
const deactivateMsg = {
topic: `UPDATE session_state SET is_active = 0 WHERE session_id = '${sessionData.session_id}';`,
_mode: "deactivate-stale"
};
return [deactivateMsg, msg]; // Output 1: DB query, Output 2: info message
}
// Session is recent - prepare recovery prompt
msg._recoveryStatus = "session-found";
msg.sessionData = sessionData;
const lastUpdateFormatted = new Date(sessionData.last_update_time).toLocaleString();
const operatingHours = (sessionData.operating_time / 3600).toFixed(2);
msg.payload = {
type: "recovery-prompt",
title: "Previous Session Found",
message: `A previous production session was found from ${hoursElapsed.toFixed(1)} hours ago (${lastUpdateFormatted})`,
details: {
workOrderId: sessionData.active_work_order_id || "None",
cyclesCompleted: sessionData.cycle_count,
operatingTime: operatingHours + " hours",
trackingWas: sessionData.tracking_enabled ? "RUNNING" : "STOPPED",
lastUpdate: lastUpdateFormatted
},
buttons: [
{ label: "Restore Session", action: "restore-session", value: sessionData },
{ label: "Start Fresh", action: "start-fresh", value: sessionData.session_id }
]
};
// Output 2: Send prompt to dashboard for user decision
return [null, msg];