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/orders/submitCash.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

183 lines
7 KiB
Text

<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">
<cffunction name="readJsonBody" access="public" returntype="struct" output="false">
<cfset var raw = getHttpRequestData().content>
<cfif isNull(raw) OR len(trim(raw)) EQ 0>
<cfreturn {}>
</cfif>
<cftry>
<cfset var data = deserializeJSON(raw)>
<cfif isStruct(data)>
<cfreturn data>
<cfelse>
<cfreturn {}>
</cfif>
<cfcatch>
<cfreturn {}>
</cfcatch>
</cftry>
</cffunction>
<cffunction name="apiAbort" access="public" returntype="void" output="true">
<cfargument name="payload" type="struct" required="true">
<cfcontent type="application/json; charset=utf-8">
<cfoutput>#serializeJSON(arguments.payload)#</cfoutput>
<cfabort>
</cffunction>
<cfset data = readJsonBody()>
<cfset OrderID = val( structKeyExists(data,"OrderID") ? data.OrderID : 0 )>
<cfset CashAmount = val( structKeyExists(data,"CashAmount") ? data.CashAmount : 0 )>
<cfset Tip = val( structKeyExists(data,"Tip") ? data.Tip : 0 )>
<cfif OrderID LTE 0>
<cfset apiAbort({ "OK": false, "ERROR": "missing_orderid", "MESSAGE": "OrderID is required." })>
</cfif>
<cfif CashAmount LTE 0>
<cfset apiAbort({ "OK": false, "ERROR": "missing_amount", "MESSAGE": "CashAmount is required." })>
</cfif>
<cftry>
<!--- Get order details with business fee rate --->
<cfset qOrder = queryExecute(
"SELECT o.ID, o.StatusID, o.UserID, o.BusinessID, o.ServicePointID, o.PaymentID,
o.DeliveryFee, o.OrderTypeID,
b.PayfritFee, b.TaxRate
FROM Orders o
INNER JOIN Businesses b ON b.ID = o.BusinessID
WHERE o.ID = ? LIMIT 1",
[ { value = OrderID, cfsqltype = "cf_sql_integer" } ],
{ datasource = "payfrit" }
)>
<cfif qOrder.recordCount EQ 0>
<cfset apiAbort({ "OK": false, "ERROR": "not_found", "MESSAGE": "Order not found." })>
</cfif>
<cfif qOrder.StatusID NEQ 0>
<cfset apiAbort({ "OK": false, "ERROR": "bad_state", "MESSAGE": "Order is not in cart state." })>
</cfif>
<!--- Calculate platform fee (customer portion — shown in cart) --->
<cfset feeRate = (isNumeric(qOrder.PayfritFee) AND val(qOrder.PayfritFee) GT 0) ? val(qOrder.PayfritFee) : 0>
<cfset customerFee = CashAmount * feeRate / (1 + feeRate)>
<!--- CashAmount already includes the customer fee (subtotal+tax+fee), back it out:
Actually CashAmount is what the Android app sends as the order total including fee.
The fee was calculated on subtotal, so we need the actual subtotal from line items. --->
<cfset qSubtotal = queryExecute(
"SELECT COALESCE(SUM(Price * Quantity), 0) AS Subtotal
FROM OrderLineItems WHERE OrderID = ? AND IsDeleted = b'0'",
[ { value = OrderID, cfsqltype = "cf_sql_integer" } ],
{ datasource = "payfrit" }
)>
<cfset subtotal = val(qSubtotal.Subtotal)>
<cfset platformFee = subtotal * feeRate>
<!--- Calculate full order total for balance application --->
<cfset taxRate = (isNumeric(qOrder.TaxRate) AND val(qOrder.TaxRate) GT 0) ? val(qOrder.TaxRate) : 0>
<cfset taxAmount = subtotal * taxRate>
<cfset deliveryFee = (val(qOrder.OrderTypeID) EQ 3) ? val(qOrder.DeliveryFee) : 0>
<cfset orderTotal = subtotal + taxAmount + platformFee + Tip + deliveryFee>
<!--- Auto-apply user balance (silently reduces cash owed) --->
<cfset balanceApplied = 0>
<cfset cashNeeded = orderTotal>
<cfif val(qOrder.UserID) GT 0>
<cfset qBalance = queryExecute(
"SELECT Balance FROM Users WHERE ID = ?",
[ { value = qOrder.UserID, cfsqltype = "cf_sql_integer" } ],
{ datasource = "payfrit" }
)>
<cfset userBalance = val(qBalance.Balance)>
<cfif userBalance GT 0>
<cfset balanceToApply = min(userBalance, orderTotal)>
<!--- Atomic deduct: only succeeds if balance is still sufficient --->
<cfset qDeduct = queryExecute(
"UPDATE Users SET Balance = Balance - ? WHERE ID = ? AND Balance >= ?",
[
{ value = balanceToApply, cfsqltype = "cf_sql_decimal" },
{ value = qOrder.UserID, cfsqltype = "cf_sql_integer" },
{ value = balanceToApply, cfsqltype = "cf_sql_decimal" }
],
{ datasource = "payfrit", result = "deductResult" }
)>
<cfif val(deductResult.recordCount) GT 0>
<cfset balanceApplied = balanceToApply>
<cfset cashNeeded = orderTotal - balanceApplied>
<cfif cashNeeded LT 0><cfset cashNeeded = 0></cfif>
</cfif>
</cfif>
</cfif>
<!--- Create Payment record with adjusted cash amount --->
<cfset CashAmountCents = round(cashNeeded * 100)>
<cfset qInsertPayment = queryExecute(
"INSERT INTO Payments (
PaymentPaidInCash,
PaymentFromPayfritBalance,
PaymentFromCreditCard,
PaymentSentByUserID,
PaymentReceivedByUserID,
PaymentOrderID,
PaymentPayfritsCut,
PaymentAddedOn
) VALUES (?, ?, 0, ?, 0, ?, ?, NOW())",
[
{ value = cashNeeded, cfsqltype = "cf_sql_decimal" },
{ value = balanceApplied, cfsqltype = "cf_sql_decimal" },
{ value = qOrder.UserID, cfsqltype = "cf_sql_integer" },
{ value = OrderID, cfsqltype = "cf_sql_integer" },
{ value = platformFee, cfsqltype = "cf_sql_decimal" }
],
{ datasource = "payfrit", result = "insertResult" }
)>
<cfset PaymentID = insertResult.generatedKey>
<!--- Update order: link payment, set status to submitted, store platform fee and balance --->
<!--- If balance covers full order, mark as paid immediately (no cash task needed) --->
<cfset fullyPaidByBalance = (cashNeeded LTE 0)>
<cfset paymentStatus = fullyPaidByBalance ? "paid" : "pending">
<cfset queryExecute(
"UPDATE Orders
SET StatusID = 1,
PaymentID = ?,
PaymentStatus = ?,
PlatformFee = ?,
TipAmount = ?,
BalanceApplied = ?,
SubmittedOn = NOW(),
LastEditedOn = NOW(),
PaymentCompletedOn = CASE WHEN ? = 1 THEN NOW() ELSE PaymentCompletedOn END
WHERE ID = ?",
[
{ value = PaymentID, cfsqltype = "cf_sql_integer" },
{ value = paymentStatus, cfsqltype = "cf_sql_varchar" },
{ value = platformFee, cfsqltype = "cf_sql_decimal" },
{ value = Tip, cfsqltype = "cf_sql_decimal" },
{ value = balanceApplied, cfsqltype = "cf_sql_decimal" },
{ value = fullyPaidByBalance ? 1 : 0, cfsqltype = "cf_sql_integer" },
{ value = OrderID, cfsqltype = "cf_sql_integer" }
],
{ datasource = "payfrit" }
)>
<cfset response = { "OK": true, "OrderID": OrderID, "PaymentID": PaymentID, "CashAmountCents": CashAmountCents, "MESSAGE": "Order submitted with cash payment." }>
<cfif balanceApplied GT 0>
<cfset response["BalanceApplied"] = round(balanceApplied * 100) / 100>
<cfset response["BalanceAppliedCents"] = round(balanceApplied * 100)>
<cfset response["FullyPaidByBalance"] = (cashNeeded LTE 0)>
</cfif>
<cfset apiAbort(response)>
<cfcatch>
<cfset apiAbort({
"OK": false,
"ERROR": "server_error",
"MESSAGE": "Failed to submit cash order",
"DETAIL": cfcatch.message
})>
</cfcatch>
</cftry>