// Customer initiates a chat with staff // Input: BusinessID, ServicePointID, OrderID (optional), UserID (optional), Message (optional initial message) // Output: { OK: true, TaskID: ... } 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 {}; } try { data = readJsonBody(); businessID = val(structKeyExists(data, "BusinessID") ? data.BusinessID : 0); servicePointID = val(structKeyExists(data, "ServicePointID") ? data.ServicePointID : 0); orderID = val(structKeyExists(data, "OrderID") ? data.OrderID : 0); initialMessage = trim(structKeyExists(data, "Message") ? data.Message : ""); userID = val(structKeyExists(data, "UserID") ? data.UserID : 0); if (businessID == 0) { apiAbort({ "OK": false, "ERROR": "missing_params", "MESSAGE": "BusinessID is required" }); } // ServicePointID = 0 is allowed for remote chats (non-dine-in users) // In that case, we use userID to match existing chats // Check for existing open chat at this service point // An open chat is one where TaskTypeID=2 (Chat) and TaskCompletedOn IS NULL forceNew = structKeyExists(data, "ForceNew") && data.ForceNew == true; if (!forceNew) { // Look for any active chat for this business // Check by: order match, service point match, OR user match (for remote chats) existingChat = queryExecute(" SELECT t.TaskID, t.TaskAddedOn, (SELECT MAX(cm.CreatedOn) FROM ChatMessages cm WHERE cm.TaskID = t.TaskID) as LastMessageTime FROM Tasks t LEFT JOIN ChatMessages cm2 ON cm2.TaskID = t.TaskID AND cm2.SenderUserID = :userID WHERE t.TaskBusinessID = :businessID AND t.TaskTypeID = 2 AND t.TaskCompletedOn IS NULL AND ( (t.TaskOrderID = :orderID AND :orderID > 0) OR (t.TaskSourceType = 'servicepoint' AND t.TaskSourceID = :servicePointID AND :servicePointID > 0) OR (t.TaskSourceType = 'user' AND t.TaskSourceID = :userID AND :userID > 0) OR (cm2.SenderUserID = :userID AND :userID > 0) ) ORDER BY t.TaskAddedOn DESC LIMIT 1 ", { businessID: { value: businessID, cfsqltype: "cf_sql_integer" }, servicePointID: { value: servicePointID, cfsqltype: "cf_sql_integer" }, orderID: { value: orderID, cfsqltype: "cf_sql_integer" }, userID: { value: userID, cfsqltype: "cf_sql_integer" } }, { datasource: "payfrit" }); if (existingChat.recordCount > 0) { // Check if chat is stale (more than 30 minutes since last message, or 30 min since creation if no messages) lastActivity = existingChat.LastMessageTime; if (isNull(lastActivity) || !isDate(lastActivity)) { lastActivity = existingChat.TaskAddedOn; } chatAge = dateDiff("n", lastActivity, now()); if (chatAge > 30) { // Auto-close stale chat queryExecute(" UPDATE Tasks SET TaskCompletedOn = NOW() WHERE TaskID = :taskID ", { taskID: { value: existingChat.TaskID, cfsqltype: "cf_sql_integer" } }, { datasource: "payfrit" }); } else { // Return existing chat apiAbort({ "OK": true, "TaskID": existingChat.TaskID, "MESSAGE": "Rejoined existing chat", "EXISTING": true }); } } } // Get service point info (table name) - only if dine-in tableName = ""; if (servicePointID > 0) { spQuery = queryExecute(" SELECT ServicePointName FROM ServicePoints WHERE ServicePointID = :spID ", { spID: { value: servicePointID, cfsqltype: "cf_sql_integer" } }, { datasource: "payfrit" }); tableName = spQuery.recordCount ? spQuery.ServicePointName : "Table ##" & servicePointID; } // Get user name if available userName = ""; if (userID > 0) { userQuery = queryExecute(" SELECT UserFirstName FROM Users WHERE UserID = :userID ", { userID: { value: userID, cfsqltype: "cf_sql_integer" } }, { datasource: "payfrit" }); if (userQuery.recordCount && len(trim(userQuery.UserFirstName))) { userName = userQuery.UserFirstName; } } // Create task title - different format for dine-in vs remote if (servicePointID > 0) { // Dine-in: "Chat - UserName (TableName)" or "Chat - TableName" taskTitle = "Chat - " & tableName; if (len(userName)) { taskTitle = "Chat - " & userName & " (" & tableName & ")"; } } else { // Remote: "Chat - UserName (Remote)" or "Remote Chat" if (len(userName)) { taskTitle = "Chat - " & userName & " (Remote)"; } else { taskTitle = "Remote Chat"; } } taskDetails = "Customer initiated chat"; if (len(initialMessage)) { taskDetails = initialMessage; } // Look up or create a "Chat" category for this business catQuery = queryExecute(" SELECT TaskCategoryID FROM TaskCategories WHERE TaskCategoryBusinessID = :businessID AND TaskCategoryName = 'Chat' LIMIT 1 ", { businessID: { value: businessID, cfsqltype: "cf_sql_integer" } }, { datasource: "payfrit" }); if (catQuery.recordCount == 0) { // Create the category (blue color for chat) queryExecute(" INSERT INTO TaskCategories (TaskCategoryBusinessID, TaskCategoryName, TaskCategoryColor) VALUES (:businessID, 'Chat', '##2196F3') ", { businessID: { value: businessID, cfsqltype: "cf_sql_integer" } }, { datasource: "payfrit" }); catResult = queryExecute("SELECT LAST_INSERT_ID() as newID", [], { datasource: "payfrit" }); categoryID = catResult.newID; } else { categoryID = catQuery.TaskCategoryID; } // Determine source type and ID based on dine-in vs remote if (servicePointID > 0) { sourceType = "servicepoint"; sourceID = servicePointID; } else { sourceType = "user"; sourceID = userID; } // Insert task with TaskTypeID = 2 (Chat) queryExecute(" INSERT INTO Tasks ( TaskBusinessID, TaskCategoryID, TaskOrderID, TaskTypeID, TaskTitle, TaskDetails, TaskClaimedByUserID, TaskSourceType, TaskSourceID, TaskAddedOn ) VALUES ( :businessID, :categoryID, :orderID, 2, :title, :details, 0, :sourceType, :sourceID, NOW() ) ", { businessID: { value: businessID, cfsqltype: "cf_sql_integer" }, categoryID: { value: categoryID, cfsqltype: "cf_sql_integer" }, orderID: { value: orderID > 0 ? orderID : javaCast("null", ""), cfsqltype: "cf_sql_integer", null: orderID == 0 }, title: { value: taskTitle, cfsqltype: "cf_sql_varchar" }, details: { value: taskDetails, cfsqltype: "cf_sql_varchar" }, sourceType: { value: sourceType, cfsqltype: "cf_sql_varchar" }, sourceID: { value: sourceID, cfsqltype: "cf_sql_integer" } }, { datasource: "payfrit" }); // Get the new task ID result = queryExecute("SELECT LAST_INSERT_ID() as newID", [], { datasource: "payfrit" }); taskID = result.newID; // If there's an initial message, save it if (len(initialMessage) && userID > 0) { queryExecute(" INSERT INTO ChatMessages (TaskID, SenderUserID, SenderType, MessageText) VALUES (:taskID, :userID, 'customer', :message) ", { taskID: { value: taskID, cfsqltype: "cf_sql_integer" }, userID: { value: userID, cfsqltype: "cf_sql_integer" }, message: { value: initialMessage, cfsqltype: "cf_sql_varchar" } }, { datasource: "payfrit" }); } apiAbort({ "OK": true, "TaskID": taskID, "MESSAGE": "Chat started" }); } catch (any e) { apiAbort({ "OK": false, "ERROR": "server_error", "MESSAGE": e.message }); }