payfrit-api/api/admin/scheduledTasks/runDue.php
John Mizerek 4d806d4e1e Port admin, cron, and receipt endpoints from CFML to PHP
- admin/quickTasks: list, create, save, delete
- admin/scheduledTasks: list, save, delete, toggle, run, runDue
- cron: expireStaleChats, expireTabs
- receipt: public order receipt page (no auth, UUID-secured)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 15:57:25 -07:00

79 lines
2.6 KiB
PHP

<?php
require_once __DIR__ . '/../../helpers.php';
require_once __DIR__ . '/_cronUtils.php';
// No runAuth() — this is a cron/public endpoint
/**
* Process all due scheduled tasks.
* Called by cron every minute. Creates Tasks entries for any due ScheduledTaskDefinitions.
*/
try {
$dueTasks = queryTimed("
SELECT
ID AS ScheduledTaskID,
BusinessID,
TaskCategoryID AS CategoryID,
Title,
Details,
CronExpression,
COALESCE(ScheduleType, 'cron') AS ScheduleType,
IntervalMinutes
FROM ScheduledTaskDefinitions
WHERE IsActive = 1
AND NextRunOn <= NOW()
");
$createdTasks = [];
foreach ($dueTasks as $task) {
queryTimed("
INSERT INTO Tasks (BusinessID, CategoryID, TaskTypeID, Title, Details, CreatedOn, ClaimedByUserID)
VALUES (?, ?, 0, ?, ?, NOW(), 0)
", [
$task['BusinessID'],
$task['CategoryID'],
$task['Title'],
$task['Details'],
]);
$newTaskID = (int) lastInsertId();
// Calculate next run based on schedule type
$st = $task['ScheduleType'];
$interval = (int) ($task['IntervalMinutes'] ?? 0);
if ($st === 'interval_after_completion' && $interval > 0) {
$nextRunStr = null; // Paused until task completion
} elseif ($st === 'interval' && $interval > 0) {
$nextRun = new DateTime("+{$interval} minutes", new DateTimeZone('UTC'));
$nextRunStr = $nextRun->format('Y-m-d H:i:s');
} else {
$nextRun = calculateNextRun($task['CronExpression']);
$nextRunStr = $nextRun->format('Y-m-d H:i:s');
}
queryTimed("
UPDATE ScheduledTaskDefinitions SET LastRunOn = NOW(), NextRunOn = ?
WHERE ID = ?
", [$nextRunStr, $task['ScheduledTaskID']]);
$createdTasks[] = [
'ScheduledTaskID' => (int) $task['ScheduledTaskID'],
'TaskID' => $newTaskID,
'BusinessID' => (int) $task['BusinessID'],
'Title' => $task['Title'],
];
}
jsonResponse([
'OK' => true,
'MESSAGE' => 'Processed ' . count($createdTasks) . ' scheduled task(s)',
'CREATED_TASKS' => $createdTasks,
'CHECKED_COUNT' => count($dueTasks),
'RAN_AT' => gmdate('Y-m-d H:i:s'),
]);
} catch (Exception $e) {
jsonResponse(['OK' => false, 'ERROR' => 'server_error', 'MESSAGE' => $e->getMessage()]);
}