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 {}; } data = readJsonBody(); businessId = structKeyExists(data, "BusinessID") ? val(data.BusinessID) : 0; userId = structKeyExists(data, "UserID") ? val(data.UserID) : 0; roleId = structKeyExists(data, "RoleID") ? val(data.RoleID) : 1; if (roleId < 1 || roleId > 3) roleId = 1; if (businessId <= 0) { apiAbort({ "OK": false, "ERROR": "missing_business_id" }); } if (userId <= 0) { apiAbort({ "OK": false, "ERROR": "missing_user_id" }); } try { // Check if already exists qCheck = queryTimed(" SELECT ID, IsActive FROM Employees WHERE BusinessID = ? AND UserID = ? ", [ { value: businessId, cfsqltype: "cf_sql_integer" }, { value: userId, cfsqltype: "cf_sql_integer" } ], { datasource: "payfrit" }); if (qCheck.recordCount > 0) { // Update to active with role queryTimed(" UPDATE Employees SET IsActive = 1, StatusID = 2, RoleID = ? WHERE BusinessID = ? AND UserID = ? ", [ { value: roleId, cfsqltype: "cf_sql_integer" }, { value: businessId, cfsqltype: "cf_sql_integer" }, { value: userId, cfsqltype: "cf_sql_integer" } ], { datasource: "payfrit" }); apiAbort({ "OK": true, "MESSAGE": "Employee reactivated", "EmployeeID": qCheck.ID }); } // Insert new // NOTE: BusinessID in Employees is technically redundant since // the business relationship is established via ServicePoint -> Beacon chain. // Kept for legacy/convenience but could be derived from context. queryTimed(" INSERT INTO Employees (BusinessID, UserID, StatusID, IsActive, RoleID) VALUES (?, ?, 2, 1, ?) ", [ { value: businessId, cfsqltype: "cf_sql_integer" }, { value: userId, cfsqltype: "cf_sql_integer" }, { value: roleId, cfsqltype: "cf_sql_integer" } ], { datasource: "payfrit" }); qNew = queryTimed("SELECT LAST_INSERT_ID() AS EmployeeID", {}, { datasource: "payfrit" }); apiAbort({ "OK": true, "MESSAGE": "Team member added", "EmployeeID": qNew.EmployeeID }); } catch (any e) { apiAbort({ "OK": false, "ERROR": "server_error", "MESSAGE": e.message }); }