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/auth/profile.cfm
John Mizerek c580e6ec78 Auto-apply user balance on cash and card orders
Balance from cash change now silently reduces the amount owed on the
next order. For cash: deducted immediately in submitCash, reduces cash
the worker needs to collect (or skips cash task entirely if fully
covered). For card: reduces the Stripe PaymentIntent amount, deducted
in webhook on successful payment. Receipt shows "Balance applied" line.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 14:16:21 -08:00

189 lines
5 KiB
Text

<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">
<cfcontent type="application/json; charset=utf-8" reset="true">
<cfheader name="Cache-Control" value="no-store">
<cfscript>
/**
* User Profile API
*
* GET: Returns current user's profile info
* POST: Updates profile (firstName, lastName)
*/
function apiAbort(required struct payload) {
writeOutput(serializeJSON(payload));
abort;
}
// Helper to get header value - use servlet request object (CGI scope doesn't expose custom HTTP headers in Lucee)
function getHeader(name) {
try {
req = getPageContext().getRequest();
val = req.getHeader(arguments.name);
if (!isNull(val)) return trim(val);
} catch (any e) {
// Fall back to CGI scope
k = "HTTP_" & ucase(reReplace(arguments.name, "[^A-Za-z0-9]", "_", "all"));
if (structKeyExists(cgi, k)) return trim(cgi[k]);
}
return "";
}
// Get authenticated user - try request scope first, then do token lookup
userId = 0;
if (structKeyExists(request, "UserID") && isNumeric(request.UserID) && request.UserID > 0) {
userId = request.UserID;
} else {
userToken = getHeader("X-User-Token");
if (len(userToken)) {
try {
qTok = queryTimed(
"SELECT UserID FROM UserTokens WHERE Token = ? LIMIT 1",
[ { value = userToken, cfsqltype = "cf_sql_varchar" } ],
{ datasource = "payfrit" }
);
if (qTok.recordCount EQ 1) {
userId = qTok.UserID;
}
} catch (any e) { /* ignore */ }
}
}
if (userId <= 0) {
apiAbort({ "OK": false, "ERROR": "not_logged_in", "MESSAGE": "Authentication required" });
}
// Handle GET - return profile
if (cgi.REQUEST_METHOD == "GET") {
try {
qUser = queryTimed("
SELECT
ID,
FirstName,
LastName,
EmailAddress,
ContactNumber,
ImageExtension,
Balance
FROM Users
WHERE ID = :userId
LIMIT 1
", { userId: { value = userId, cfsqltype = "cf_sql_integer" } });
if (qUser.recordCount == 0) {
apiAbort({ "OK": false, "ERROR": "user_not_found", "MESSAGE": "User not found" });
}
// Build avatar URL if user has an image
avatarUrl = "";
if (len(trim(qUser.ImageExtension))) {
avatarUrl = application.baseUrl & "/uploads/users/" & qUser.ID & "." & qUser.ImageExtension & "?t=" & getTickCount();
}
writeOutput(serializeJSON({
"OK": true,
"USER": {
"UserID": qUser.ID,
"FirstName": qUser.FirstName ?: "",
"LastName": qUser.LastName ?: "",
"Email": qUser.EmailAddress ?: "",
"Phone": qUser.ContactNumber ?: "",
"AvatarUrl": avatarUrl,
"Balance": val(qUser.Balance)
}
}));
abort;
} catch (any e) {
apiAbort({
"OK": false,
"ERROR": "server_error",
"MESSAGE": "Failed to load profile",
"DETAIL": e.message
});
}
}
// Handle POST - update profile
if (cgi.REQUEST_METHOD == "POST") {
try {
requestBody = toString(getHttpRequestData().content);
if (!len(requestBody)) {
apiAbort({ "OK": false, "ERROR": "missing_body", "MESSAGE": "Request body required" });
}
data = deserializeJSON(requestBody);
// Build update fields
updates = [];
params = { userId: { value = userId, cfsqltype = "cf_sql_integer" } };
if (structKeyExists(data, "firstName")) {
arrayAppend(updates, "FirstName = :firstName");
params.firstName = { value = data.firstName, cfsqltype = "cf_sql_varchar" };
}
if (structKeyExists(data, "lastName")) {
arrayAppend(updates, "LastName = :lastName");
params.lastName = { value = data.lastName, cfsqltype = "cf_sql_varchar" };
}
if (arrayLen(updates) == 0) {
apiAbort({ "OK": false, "ERROR": "no_changes", "MESSAGE": "No fields to update" });
}
// Execute update
queryTimed("
UPDATE Users
SET #arrayToList(updates, ', ')#
WHERE ID = :userId
", params);
// Return updated profile
qUser = queryTimed("
SELECT
ID,
FirstName,
LastName,
EmailAddress,
ContactNumber,
ImageExtension
FROM Users
WHERE ID = :userId
LIMIT 1
", { userId: { value = userId, cfsqltype = "cf_sql_integer" } });
// Build avatar URL if user has an image
avatarUrl = "";
if (len(trim(qUser.ImageExtension))) {
avatarUrl = application.baseUrl & "/uploads/users/" & qUser.ID & "." & qUser.ImageExtension & "?t=" & getTickCount();
}
writeOutput(serializeJSON({
"OK": true,
"MESSAGE": "Profile updated",
"USER": {
"UserID": qUser.ID,
"FirstName": qUser.FirstName ?: "",
"LastName": qUser.LastName ?: "",
"Email": qUser.EmailAddress ?: "",
"Phone": qUser.ContactNumber ?: "",
"AvatarUrl": avatarUrl
}
}));
abort;
} catch (any e) {
apiAbort({
"OK": false,
"ERROR": "server_error",
"MESSAGE": "Failed to update profile",
"DETAIL": e.message
});
}
}
// Unknown method
apiAbort({ "OK": false, "ERROR": "bad_method", "MESSAGE": "Use GET or POST" });
</cfscript>