This repository has been archived on 2026-03-21. You can view files and clone it, but cannot push or open issues or pull requests.
payfrit-biz/api/admin/scheduledTasks/toggle.cfm
John Mizerek 1210249f54 Normalize database column and table names across entire codebase
Update all SQL queries, query result references, and ColdFusion code to match
the renamed database schema. Tables use plural CamelCase, PKs are all `ID`,
column prefixes stripped (e.g. BusinessName→Name, UserFirstName→FirstName).

Key changes:
- Strip table-name prefixes from all column references (Businesses, Users,
  Addresses, Hours, Menus, Categories, Items, Stations, Orders,
  OrderLineItems, Tasks, TaskCategories, TaskRatings, QuickTaskTemplates,
  ScheduledTaskDefinitions, ChatMessages, Beacons, ServicePoints, Employees,
  VisitorTrackings, ApiPerfLogs, tt_States, tt_Days, tt_AddressTypes,
  tt_OrderTypes, tt_TaskTypes)
- Rename PK references from {TableName}ID to ID in all queries
- Rewrite 7 admin beacon files to use ServicePoints.BeaconID instead of
  dropped lt_Beacon_Businesses_ServicePoints link table
- Rewrite beacon assignment files (list, save, delete) for new schema
- Fix FK references incorrectly changed to ID (OrderLineItems.OrderID,
  Categories.MenuID, Tasks.CategoryID, ServicePoints.BeaconID)
- Update Addresses: AddressLat→Latitude, AddressLng→Longitude
- Update Users: UserPassword→Password, UserIsEmailVerified→IsEmailVerified,
  UserIsActive→IsActive, UserBalance→Balance, etc.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-30 15:39:12 -08:00

163 lines
5.7 KiB
Text

<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">
<cfcontent type="application/json; charset=utf-8" reset="true">
<cfscript>
// Enable or disable a scheduled task
// Input: BusinessID (required), ScheduledTaskID (required), IsActive (required)
// Output: { OK: true }
function apiAbort(required struct payload) {
writeOutput(serializeJSON(payload));
abort;
}
function readJsonBody() {
var raw = getHttpRequestData().content;
if (isNull(raw)) raw = "";
if (!len(trim(raw))) return {};
try {
var data = deserializeJSON(raw);
if (isStruct(data)) return data;
} catch (any e) {}
return {};
}
// Calculate next run time from cron expression
function calculateNextRun(required string cronExpression) {
var parts = listToArray(cronExpression, " ");
if (arrayLen(parts) != 5) {
return dateAdd("d", 1, now());
}
var cronMinute = parts[1];
var cronHour = parts[2];
var cronDay = parts[3];
var cronMonth = parts[4];
var cronWeekday = parts[5];
var checkDate = dateAdd("n", 1, now());
checkDate = createDateTime(year(checkDate), month(checkDate), day(checkDate), hour(checkDate), minute(checkDate), 0);
var maxIterations = 400 * 24 * 60;
var iterations = 0;
while (iterations < maxIterations) {
var matchMinute = (cronMinute == "*" || (isNumeric(cronMinute) && minute(checkDate) == int(cronMinute)));
var matchHour = (cronHour == "*" || (isNumeric(cronHour) && hour(checkDate) == int(cronHour)));
var matchDay = (cronDay == "*" || (isNumeric(cronDay) && day(checkDate) == int(cronDay)));
var matchMonth = (cronMonth == "*" || (isNumeric(cronMonth) && month(checkDate) == int(cronMonth)));
var dow = dayOfWeek(checkDate) - 1;
var matchWeekday = (cronWeekday == "*");
if (!matchWeekday) {
if (find("-", cronWeekday)) {
var range = listToArray(cronWeekday, "-");
if (arrayLen(range) == 2 && isNumeric(range[1]) && isNumeric(range[2])) {
matchWeekday = (dow >= int(range[1]) && dow <= int(range[2]));
}
} else if (isNumeric(cronWeekday)) {
matchWeekday = (dow == int(cronWeekday));
}
}
if (matchMinute && matchHour && matchDay && matchMonth && matchWeekday) {
return checkDate;
}
checkDate = dateAdd("n", 1, checkDate);
iterations++;
}
return dateAdd("d", 1, now());
}
try {
data = readJsonBody();
// Get BusinessID
businessID = 0;
httpHeaders = getHttpRequestData().headers;
if (structKeyExists(data, "BusinessID") && isNumeric(data.BusinessID)) {
businessID = int(data.BusinessID);
} else if (structKeyExists(httpHeaders, "X-Business-ID") && isNumeric(httpHeaders["X-Business-ID"])) {
businessID = int(httpHeaders["X-Business-ID"]);
}
if (businessID == 0) {
apiAbort({ "OK": false, "ERROR": "missing_params", "MESSAGE": "BusinessID is required" });
}
// Get task ID and new state
taskID = structKeyExists(data, "ScheduledTaskID") && isNumeric(data.ScheduledTaskID) ? int(data.ScheduledTaskID) : 0;
isActive = structKeyExists(data, "IsActive") ? (data.IsActive ? 1 : 0) : 0;
if (taskID == 0) {
apiAbort({ "OK": false, "ERROR": "missing_params", "MESSAGE": "ScheduledTaskID is required" });
}
// Verify exists and get cron expression and schedule type
qCheck = queryExecute("
SELECT ScheduledTaskID, CronExpression as CronExpression,
COALESCE(ScheduleType, 'cron') as ScheduleType,
IntervalMinutes as IntervalMinutes
FROM ScheduledTaskDefinitions
WHERE ID = :id AND BusinessID = :businessID
", {
id: { value: taskID, cfsqltype: "cf_sql_integer" },
businessID: { value: businessID, cfsqltype: "cf_sql_integer" }
}, { datasource: "payfrit" });
if (qCheck.recordCount == 0) {
apiAbort({ "OK": false, "ERROR": "not_found", "MESSAGE": "Scheduled task not found" });
}
// If enabling, recalculate next run time based on schedule type
nextRunUpdate = "";
if (isActive) {
if ((qCheck.ScheduleType == "interval" || qCheck.ScheduleType == "interval_after_completion") && !isNull(qCheck.IntervalMinutes) && qCheck.IntervalMinutes > 0) {
// Interval-based: next run = NOW + interval minutes
nextRunOn = dateAdd("n", qCheck.IntervalMinutes, now());
} else {
// Cron-based: use cron parser
nextRunOn = calculateNextRun(qCheck.CronExpression);
}
nextRunUpdate = ", NextRunOn = :nextRun";
}
// Update status
if (isActive) {
queryExecute("
UPDATE ScheduledTaskDefinitions SET
IsActive = :isActive,
NextRunOn = :nextRun
WHERE ID = :id
", {
isActive: { value: isActive, cfsqltype: "cf_sql_bit" },
nextRun: { value: nextRunOn, cfsqltype: "cf_sql_timestamp" },
id: { value: taskID, cfsqltype: "cf_sql_integer" }
}, { datasource: "payfrit" });
} else {
queryExecute("
UPDATE ScheduledTaskDefinitions SET IsActive = :isActive
WHERE ID = :id
", {
isActive: { value: isActive, cfsqltype: "cf_sql_bit" },
id: { value: taskID, cfsqltype: "cf_sql_integer" }
}, { datasource: "payfrit" });
}
apiAbort({
"OK": true,
"MESSAGE": isActive ? "Scheduled task enabled" : "Scheduled task disabled"
});
} catch (any e) {
apiAbort({
"OK": false,
"ERROR": "server_error",
"MESSAGE": e.message
});
}
</cfscript>