| const db = require('../config/db'); |
|
|
| const DEFAULT_ONLINE_STALE_SECONDS = 120; |
|
|
| function getOnlineStaleSeconds() { |
| const configured = Number(process.env.DEVICE_ONLINE_STALE_SECONDS); |
| return Number.isFinite(configured) && configured > 0 |
| ? Math.floor(configured) |
| : DEFAULT_ONLINE_STALE_SECONDS; |
| } |
|
|
| async function markStaleOnlineDevicesOffline(context = 'deviceStatus') { |
| const staleSeconds = getOnlineStaleSeconds(); |
|
|
| await db.query( |
| `INSERT INTO device_status_log (device_id, old_status, new_status) |
| SELECT id, status, 'offline' |
| FROM devices |
| WHERE status = 'online' |
| AND billing_status != 'cancelled' |
| AND (last_seen_at IS NULL OR TIMESTAMPDIFF(SECOND, last_seen_at, NOW()) > ?)`, |
| [staleSeconds], |
| ); |
|
|
| const result = await db.query( |
| `UPDATE devices |
| SET status = 'offline' |
| WHERE status = 'online' |
| AND billing_status != 'cancelled' |
| AND (last_seen_at IS NULL OR TIMESTAMPDIFF(SECOND, last_seen_at, NOW()) > ?)`, |
| [staleSeconds], |
| ); |
|
|
| const changed = result.affectedRows || 0; |
| if (changed > 0) { |
| console.log(`[${context}] Marked ${changed} stale online device(s) offline`); |
| } |
| return changed; |
| } |
|
|
| module.exports = { |
| DEFAULT_ONLINE_STALE_SECONDS, |
| getOnlineStaleSeconds, |
| markStaleOnlineDevicesOffline, |
| }; |
|
|