payfrit-api/api/tasks/expireStaleChats.php
John Mizerek 1f81d98c52 Initial PHP API migration from CFML
Complete port of all 163 API endpoints from Lucee/CFML to PHP 8.3.
Shared helpers in api/helpers.php (DB, auth, request/response, security).
PDO prepared statements throughout. Same JSON response shapes as CFML.
2026-03-14 14:26:59 -07:00

51 lines
1.4 KiB
PHP

<?php
require_once __DIR__ . '/../helpers.php';
runAuth();
/**
* Scheduled task to expire stale chats (>20 min with no activity)
*/
try {
// Find open chat tasks older than 20 minutes
$staleChats = queryTimed("
SELECT t.ID, t.CreatedOn,
(SELECT MAX(cm.CreatedOn) FROM ChatMessages cm WHERE cm.TaskID = t.ID) as LastMessageOn
FROM Tasks t
WHERE t.TaskTypeID = 2
AND t.CompletedOn IS NULL
AND t.CreatedOn < DATE_SUB(NOW(), INTERVAL 20 MINUTE)
", []);
$expiredCount = 0;
$expiredIds = [];
foreach ($staleChats as $chat) {
$shouldExpire = false;
if (empty($chat['LastMessageOn'])) {
$shouldExpire = true;
} else {
$lastMsgAge = (int) ((time() - strtotime($chat['LastMessageOn'])) / 60);
if ($lastMsgAge > 20) {
$shouldExpire = true;
}
}
if ($shouldExpire) {
queryTimed("UPDATE Tasks SET CompletedOn = NOW() WHERE ID = ?", [$chat['ID']]);
$expiredCount++;
$expiredIds[] = (int) $chat['ID'];
}
}
jsonResponse([
'OK' => true,
'MESSAGE' => "Expired $expiredCount stale chat(s)",
'EXPIRED_TASK_IDS' => $expiredIds,
'CHECKED_COUNT' => count($staleChats),
]);
} catch (Exception $e) {
jsonResponse(['OK' => false, 'ERROR' => 'server_error', 'MESSAGE' => $e->getMessage()]);
}