@aglyn/plugins-bookings 1.14.0 → 1.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +11 -11
- package/src/lib/server/billing-webhook.js +24 -3
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/in-person-payment.js +4 -1
- package/src/lib/server/in-person-payment.js.map +1 -1
- package/src/lib/server/refund.d.ts +6 -0
- package/src/lib/server/refund.js +27 -2
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server.js +26 -6
- package/src/lib/server.js.map +1 -1
package/src/lib/server/refund.js
CHANGED
|
@@ -70,6 +70,12 @@ import { raiseBookingEvent } from "./booking-events.js";
|
|
|
70
70
|
* written inside one transaction, BEFORE Stripe is called, so a lost
|
|
71
71
|
* response leaves the amount counted and the retry refunds less, never
|
|
72
72
|
* more.
|
|
73
|
+
*
|
|
74
|
+
* A DIRECT-charge booking (`chargeModel: 'direct'`) was charged on the
|
|
75
|
+
* seller's own account, so its refund is made there (`Stripe-Account`) and is
|
|
76
|
+
* debited from the seller's balance. There is no transfer to reverse, so
|
|
77
|
+
* `reverse_transfer` is never sent; `refund_application_fee` still is, for the
|
|
78
|
+
* same reason as above.
|
|
73
79
|
*/ export const bookingRefundHandler = async (req, res)=>{
|
|
74
80
|
var _req_headers_authorization, _req_body, _body_hostId, _body_bookingId, _ref, _req_headers_idempotencykey;
|
|
75
81
|
if (req.method !== 'POST') {
|
|
@@ -106,7 +112,7 @@ import { raiseBookingEvent } from "./booking-events.js";
|
|
|
106
112
|
});
|
|
107
113
|
}
|
|
108
114
|
try {
|
|
109
|
-
var _bookingSnapshot_data, _bookingSnapshot_get, _bookingSnapshot_get1;
|
|
115
|
+
var _bookingSnapshot_data, _bookingSnapshot_get, _bookingSnapshot_get1, _bookingSnapshot_get2;
|
|
110
116
|
const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
|
|
111
117
|
const firestore = firebaseAdmin.app().firestore();
|
|
112
118
|
const hostRef = firestore.collection('hosts').doc(hostId);
|
|
@@ -147,6 +153,16 @@ import { raiseBookingEvent } from "./booking-events.js";
|
|
|
147
153
|
error: 'This booking was paid before refunds were supported here. ' + 'Refund it in the Stripe dashboard, and tick “Reverse transfer” ' + 'so the amount comes back from the merchant account.'
|
|
148
154
|
});
|
|
149
155
|
}
|
|
156
|
+
// Where the charge lives. A direct booking records the seller's account
|
|
157
|
+
// when it is held; without it the refund would be sent to the platform,
|
|
158
|
+
// where Stripe cannot find the payment, so refuse before reserving.
|
|
159
|
+
const direct = bookingSnapshot.get('chargeModel') === 'direct';
|
|
160
|
+
const chargeAccountId = direct ? String((_bookingSnapshot_get2 = bookingSnapshot.get('stripeAccountId')) != null ? _bookingSnapshot_get2 : '').trim() : '';
|
|
161
|
+
if (direct && !chargeAccountId) {
|
|
162
|
+
return res.status(409).json({
|
|
163
|
+
error: 'This booking was paid on your Stripe account. ' + 'Refund it in your Stripe dashboard.'
|
|
164
|
+
});
|
|
165
|
+
}
|
|
150
166
|
// Replay a settled attempt before anything else can reject it. This read
|
|
151
167
|
// is only a short-circuit, never the dedupe primitive — the atomic
|
|
152
168
|
// `create()` below is.
|
|
@@ -210,7 +226,14 @@ import { raiseBookingEvent } from "./booking-events.js";
|
|
|
210
226
|
error: 'Nothing left to refund'
|
|
211
227
|
});
|
|
212
228
|
}
|
|
213
|
-
const params = new URLSearchParams({
|
|
229
|
+
const params = direct ? new URLSearchParams({
|
|
230
|
+
payment_intent: paymentIntentId,
|
|
231
|
+
amount: String(refundCents),
|
|
232
|
+
// The money is already the seller's, so the refund comes out of
|
|
233
|
+
// their balance with no transfer to reverse. Aglyn's commission on
|
|
234
|
+
// the refunded share still goes back to them.
|
|
235
|
+
refund_application_fee: 'true'
|
|
236
|
+
}) : new URLSearchParams({
|
|
214
237
|
payment_intent: paymentIntentId,
|
|
215
238
|
amount: String(refundCents),
|
|
216
239
|
// THE SELLER SHARE COMES BACK. Without this the merchant keeps their
|
|
@@ -227,6 +250,8 @@ import { raiseBookingEvent } from "./booking-events.js";
|
|
|
227
250
|
'Content-Type': 'application/x-www-form-urlencoded'
|
|
228
251
|
}, claimRef ? {
|
|
229
252
|
'Idempotency-Key': claimRef.id
|
|
253
|
+
} : {}, direct ? {
|
|
254
|
+
'Stripe-Account': chargeAccountId
|
|
230
255
|
} : {}),
|
|
231
256
|
body: params.toString()
|
|
232
257
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/refund.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\n// Leaf import, not the barrel: the specs in this library mock\n// `@aglyn/tenant-data-admin` wholesale, and a permissive stub would turn a\n// reversal that never happened green.\nimport { reverseOrderConversion } from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { createHash } from 'crypto'\nimport { apiIdempotencyExpiry } from '@aglyn/aglyn/app-utils/api-idempotency'\nimport { bookingsSitePermissionRefusal } from '../model/bookings-permissions'\nimport { holdsBookingsSiteKey } from './bookings-site-keys'\nimport { raiseBookingEvent } from './booking-events'\n\n/**\n * Refund a paid booking (AGL-2315), full or partial, site-admin only.\n *\n * This route exists BECAUSE of the destination charge, not alongside it. While\n * a paid booking settled in Aglyn's own balance there was nothing here to get\n * wrong: cancelling a booking refunded the guest nothing at all, and any\n * refund issued by hand simply gave back money Aglyn was already holding. Once\n * the charge goes to the merchant's connected account that stops being true in\n * two directions at once, and both are money:\n *\n * - **The guest.** Cancelling a paid booking wrote `status: 'canceled'` from\n * the console and moved no money. The slot reopened, the appointment was\n * gone, and the guest had paid for it. That was survivable only because the\n * platform still held the funds and could be made to give them back; with\n * the money at the merchant it is a silent, unrecoverable overcharge.\n * - **Aglyn.** A refund on a destination charge that does NOT set\n * `reverse_transfer` is paid entirely out of the PLATFORM's balance while\n * the merchant keeps the transfer in full. The merchant cancels, the guest\n * is made whole, and Aglyn funds the whole concession out of a cut that was\n * at most 5% of it. This repo has shipped that exact bug once already, on a\n * marketplace partial refund.\n *\n * So both switches are sent, and they are two different decisions:\n *\n * - `reverse_transfer` pulls the refunded share back OUT of the merchant's\n * account. Stripe prorates it against a partial refund, so a $30 refund on\n * a $75 booking claws back $30 of the merchant's $71.25, not all of it.\n * - `refund_application_fee` returns Aglyn's commission on the refunded\n * share. A refunded appointment earned the platform nothing, and this\n * matches `commerce/refund.ts`, which has sent both since AGL-287. The\n * DISPUTE path deliberately sends only the reversal — that asymmetry is\n * AGL-1809's and is not copied here.\n *\n * Two SEPARATE controls guard the money, the AGL-1696 lesson from the order\n * refund, and conflating them is how that one originally went wrong:\n *\n * - The idempotency key stops a DUPLICATE refund — one attempt sent twice\n * because the response was lost or the admin double-clicked. It is minted\n * per attempt by the console and deliberately not derived from the booking\n * or the amount: two $10 refunds on a $75 booking are two real refunds.\n * - The cap stops an OVER-refund — several partials summing past what was\n * captured, including two admins refunding at once, where the attempts are\n * genuinely distinct and no key can help. That needs the counter read and\n * written inside one transaction, BEFORE Stripe is called, so a lost\n * response leaves the amount counted and the retry refunds less, never\n * more.\n */\nexport const bookingRefundHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const bookingId = String(body.bookingId ?? '')\n // `null`/absent means \"everything still refundable\"; a number is a partial.\n const amountCents = body.amountCents == null ? null : Number(body.amountCents)\n // Node lowercases incoming headers, but read both spellings — the plugin API\n // request type makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n )\n .trim()\n .slice(0, 200)\n if (!hostId || !bookingId) {\n return res.status(400).json({ error: 'Missing hostId or bookingId' })\n }\n if (amountCents != null && !(Number.isFinite(amountCents) && amountCents > 0)) {\n return res.status(400).json({ error: 'Invalid refund amount' })\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // \"Refund bookings\" (AGL-4047), not merely a member: this moves money.\n // Its preset is the site Admin, the gate `commerce/refund.ts` applies.\n if (!holdsBookingsSiteKey(hostSnapshot, decoded.uid, 'bookings.refunds')) {\n return res.status(403).json({ error: bookingsSitePermissionRefusal('bookings.refunds') })\n }\n const bookingRef = hostRef.collection('bookings').doc(bookingId)\n const bookingSnapshot = await bookingRef.get()\n if (!bookingSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown booking' })\n }\n // As it stood before this refund, for the event a full refund raises.\n const bookingBefore = (bookingSnapshot.data() ?? {}) as Record<string, unknown>\n const paymentIntentId = String(bookingSnapshot.get('paymentIntentId') ?? '')\n const paidCents = Math.max(\n 0,\n Math.round(Number(bookingSnapshot.get('paidAmountCents') ?? 0)),\n )\n if (!paidCents) {\n return res.status(409).json({ error: 'This booking was never paid' })\n }\n if (!paymentIntentId) {\n // A booking paid BEFORE the webhook began recording the PaymentIntent\n // (AGL-2315). Refundable, but only by hand — and saying so beats a 500\n // an admin cannot act on.\n return res.status(409).json({\n error:\n 'This booking was paid before refunds were supported here. ' +\n 'Refund it in the Stripe dashboard, and tick “Reverse transfer” ' +\n 'so the amount comes back from the merchant account.',\n })\n }\n\n // Replay a settled attempt before anything else can reject it. This read\n // is only a short-circuit, never the dedupe primitive — the atomic\n // `create()` below is.\n const claimRef = idempotencyKey\n ? firestore.collection('apiIdempotency').doc(\n createHash('sha256')\n // Scoped by the BOOKING, so a client that reused one key across\n // two bookings cannot dedupe two legitimately distinct refunds.\n // NOT by the amount: that would swallow a real second partial.\n .update(`booking-refund:${hostId}:${bookingId}:${idempotencyKey}`)\n .digest('hex'),\n )\n : null\n if (claimRef) {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n try {\n // The claim's shape is every claim's (`claimApiIdempotency`): its\n // kind, scope and org name it on the staff claims list, `createdAtMs`\n // ages it there, and `expiresAt` lets the TTL policy reap it — a\n // claim stranded by a killed process otherwise holds its key forever.\n await claimRef.create({\n kind: 'booking-refund',\n scopeId: hostId,\n orgId: String(hostSnapshot.get('orgId') ?? '') || null,\n bookingId,\n status: 'pending',\n createdAtMs: Date.now(),\n expiresAt: apiIdempotencyExpiry(),\n })\n } catch {\n // Another attempt with this key is in flight.\n return res\n .status(409)\n .json({ error: 'This refund is already being processed' })\n }\n }\n\n // RESERVE. Read and write the counter in ONE transaction so two concurrent\n // refunds cannot both see the same `refundedCents` and each send a full\n // amount to Stripe — the failure the order refund shipped with.\n let refundCents = 0\n let alreadyRefunded = 0\n await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n alreadyRefunded = Math.max(\n 0,\n Math.round(Number(fresh.get('refundedCents') ?? 0)),\n )\n const remaining = paidCents - alreadyRefunded\n refundCents =\n amountCents == null\n ? remaining\n : Math.min(Math.round(amountCents), remaining)\n if (!(refundCents > 0)) {\n refundCents = 0\n return\n }\n transaction.set(\n bookingRef,\n { refundedCents: alreadyRefunded + refundCents },\n { merge: true },\n )\n })\n if (!(refundCents > 0)) {\n await claimRef?.delete().catch(() => undefined)\n return res.status(400).json({ error: 'Nothing left to refund' })\n }\n\n const params = new URLSearchParams({\n payment_intent: paymentIntentId,\n amount: String(refundCents),\n // THE SELLER SHARE COMES BACK. Without this the merchant keeps their\n // transfer in full and Aglyn funds the entire refund.\n reverse_transfer: 'true',\n // ...and so does Aglyn's commission on the refunded share. A refunded\n // appointment earned the platform nothing.\n refund_application_fee: 'true',\n })\n const response = await fetch('https://api.stripe.com/v1/refunds', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(claimRef ? { 'Idempotency-Key': claimRef.id } : {}),\n },\n body: params.toString(),\n })\n const refund = await response.json().catch(() => ({}) as any)\n if (!response.ok) {\n console.error('Stripe booking refund error', (refund as any)?.error)\n // Stripe said no, so we KNOW no money moved: give the reservation back\n // and let the same attempt be retried.\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(bookingRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n bookingRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claimRef?.delete().catch(() => undefined)\n return res.status(502).json({ error: 'Refund failed' })\n }\n\n // A FULL refund ends the appointment; a partial leaves it standing. The\n // guest who got half their money back still has the slot, and moving the\n // booking off `confirmed` would reopen a time the merchant is still\n // committed to.\n const totalRefunded = alreadyRefunded + refundCents\n const fullyRefunded = totalRefunded >= paidCents\n await bookingRef\n .set(\n {\n refundedCents: totalRefunded,\n ...(fullyRefunded ? { status: 'canceled' } : {}),\n },\n { merge: true },\n )\n .catch(() => undefined)\n // The full refund is what cancels a paid booking (AGL-3643). Keyed by the\n // booking, so a booking canceled before is not announced again.\n if (fullyRefunded && bookingBefore['status'] !== 'canceled') {\n await raiseBookingEvent(firestore, {\n event: 'booking.canceled',\n hostId,\n bookingId,\n booking: {\n ...bookingBefore,\n refundedCents: totalRefunded,\n status: 'canceled',\n },\n })\n }\n\n const payload = {\n refundedCents: refundCents,\n totalRefundedCents: totalRefunded,\n fullyRefunded,\n }\n await claimRef\n ?.set(\n {\n status: 'done',\n responseStatus: 200,\n response: payload,\n settledAtMs: Date.now(),\n },\n { merge: true },\n )\n .catch(() => undefined)\n /*\n * The campaign's side of the ledger.\n *\n * A paid booking is credited to the campaign that led to it — the sale\n * announces itself through `upsertHostContact` with a `purchaseCents` and\n * this booking's id, exactly as a store order does — so a refunded one\n * has to stop counting. Without this, a booking site's campaign revenue\n * could only ever rise.\n *\n * Keyed by the BOOKING id, which is what the credit was filed under, so\n * this needs no email and works for a guest who never became a contact.\n * Recorded beside the credit rather than subtracted from it, and swallowed\n * whole: the money has already left the merchant's account and the booking\n * already records it, so nothing here may fail a refund.\n */\n await reverseOrderConversion({\n hostId,\n orderId: bookingId,\n amountCents: refundCents,\n closedTheOrder: fullyRefunded,\n })\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Refund failed' })\n }\n}\n"],"names":["firebaseAdmin","reverseOrderConversion","createHash","apiIdempotencyExpiry","bookingsSitePermissionRefusal","holdsBookingsSiteKey","raiseBookingEvent","bookingRefundHandler","req","res","body","method","status","json","error","process","env","STRIPE_SECRET_KEY","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","bookingId","amountCents","Number","idempotencyKey","trim","isFinite","bookingSnapshot","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","bookingRef","bookingBefore","data","paymentIntentId","paidCents","Math","max","round","claimRef","update","digest","prior","priorResponse","create","kind","scopeId","orgId","createdAtMs","Date","now","expiresAt","refundCents","alreadyRefunded","runTransaction","transaction","fresh","remaining","min","set","refundedCents","merge","delete","catch","params","URLSearchParams","payment_intent","amount","reverse_transfer","refund_application_fee","response","fetch","Authorization","id","toString","refund","ok","console","current","totalRefunded","fullyRefunded","event","booking","payload","totalRefundedCents","responseStatus","settledAtMs","orderId","closedTheOrder"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AAExD,8DAA8D;AAC9D,2EAA2E;AAC3E,sCAAsC;AACtC,SAASC,sBAAsB,QAAQ,uDAAsD;AAC7F,SAASC,UAAU,QAAQ,SAAQ;AACnC,SAASC,oBAAoB,QAAQ,yCAAwC;AAC7E,SAASC,6BAA6B,QAAQ,mCAA+B;AAC7E,SAASC,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,iBAAiB,QAAQ,sBAAkB;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CC,GACD,OAAO,MAAMC,uBAAyC,OAAOC,KAAKC;QAOnCD,4BAM4BA,WACnCE,cACGA,iBAMvBF,MAAAA;IApBF,IAAIA,IAAIG,MAAM,KAAK,QAAQ;QACzB,OAAOF,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,IAAI,CAACC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAOR,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA+B;IACtE;IACA,MAAMI,gBAAgBC,QAAOX,6BAAAA,IAAIY,OAAO,CAACF,aAAa,YAAzBV,6BAA6B;IAC1D,MAAMa,UAAUH,cAAcI,UAAU,CAAC,aACrCJ,cAAcK,KAAK,CAAC,UAAUC,MAAM,IACpCC;IACJ,IAAI,CAACJ,SAAS,OAAOZ,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;QAAEC,OAAO;IAAkB;IACrE,MAAMJ,OACJ,OAAOF,IAAIE,IAAI,KAAK,WAAWgB,KAAKC,KAAK,CAACnB,IAAI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;YAAgB;QACvD;QAEA,wEAAwE;QACxE,yEAAyE;QACzE,oEAAoE;QACpE,gBAAgB;QAChB,MAAMkF,gBAAgB1B,kBAAkBD;QACxC,MAAM4B,gBAAgBD,iBAAiB5C;QACvC,MAAMJ,WACH4B,GAAG,CACF;YACEC,eAAemB;WACXC,gBAAgB;YAAErF,QAAQ;QAAW,IAAI,CAAC,IAEhD;YAAEkE,OAAO;QAAK,GAEfE,KAAK,CAAC,IAAMvD;QACf,0EAA0E;QAC1E,gEAAgE;QAChE,IAAIwE,iBAAiBhD,aAAa,CAAC,SAAS,KAAK,YAAY;YAC3D,MAAM3C,kBAAkBkC,WAAW;gBACjC0D,OAAO;gBACPtE;gBACAC;gBACAsE,SAAS,aACJlD;oBACH4B,eAAemB;oBACfpF,QAAQ;;YAEZ;QACF;QAEA,MAAMwF,UAAU;YACdvB,eAAeR;YACfgC,oBAAoBL;YACpBC;QACF;QACA,OAAMzC,4BAAAA,SACFoB,GAAG,CACH;YACEhE,QAAQ;YACR0F,gBAAgB;YAChBf,UAAUa;YACVG,aAAarC,KAAKC,GAAG;QACvB,GACA;YAAEW,OAAO;QAAK,GAEfE,KAAK,CAAC,IAAMvD;QACf;;;;;;;;;;;;;;KAcC,GACD,MAAMxB,uBAAuB;YAC3B2B;YACA4E,SAAS3E;YACTC,aAAauC;YACboC,gBAAgBR;QAClB;QACA,OAAOxF,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAACuF;IAC9B,EAAE,OAAOtF,OAAO;QACdgF,QAAQhF,KAAK,CAACA;QACd,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAgB;IACvD;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/refund.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\n// Leaf import, not the barrel: the specs in this library mock\n// `@aglyn/tenant-data-admin` wholesale, and a permissive stub would turn a\n// reversal that never happened green.\nimport { reverseOrderConversion } from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { createHash } from 'crypto'\nimport { apiIdempotencyExpiry } from '@aglyn/aglyn/app-utils/api-idempotency'\nimport { bookingsSitePermissionRefusal } from '../model/bookings-permissions'\nimport { holdsBookingsSiteKey } from './bookings-site-keys'\nimport { raiseBookingEvent } from './booking-events'\n\n/**\n * Refund a paid booking (AGL-2315), full or partial, site-admin only.\n *\n * This route exists BECAUSE of the destination charge, not alongside it. While\n * a paid booking settled in Aglyn's own balance there was nothing here to get\n * wrong: cancelling a booking refunded the guest nothing at all, and any\n * refund issued by hand simply gave back money Aglyn was already holding. Once\n * the charge goes to the merchant's connected account that stops being true in\n * two directions at once, and both are money:\n *\n * - **The guest.** Cancelling a paid booking wrote `status: 'canceled'` from\n * the console and moved no money. The slot reopened, the appointment was\n * gone, and the guest had paid for it. That was survivable only because the\n * platform still held the funds and could be made to give them back; with\n * the money at the merchant it is a silent, unrecoverable overcharge.\n * - **Aglyn.** A refund on a destination charge that does NOT set\n * `reverse_transfer` is paid entirely out of the PLATFORM's balance while\n * the merchant keeps the transfer in full. The merchant cancels, the guest\n * is made whole, and Aglyn funds the whole concession out of a cut that was\n * at most 5% of it. This repo has shipped that exact bug once already, on a\n * marketplace partial refund.\n *\n * So both switches are sent, and they are two different decisions:\n *\n * - `reverse_transfer` pulls the refunded share back OUT of the merchant's\n * account. Stripe prorates it against a partial refund, so a $30 refund on\n * a $75 booking claws back $30 of the merchant's $71.25, not all of it.\n * - `refund_application_fee` returns Aglyn's commission on the refunded\n * share. A refunded appointment earned the platform nothing, and this\n * matches `commerce/refund.ts`, which has sent both since AGL-287. The\n * DISPUTE path deliberately sends only the reversal — that asymmetry is\n * AGL-1809's and is not copied here.\n *\n * Two SEPARATE controls guard the money, the AGL-1696 lesson from the order\n * refund, and conflating them is how that one originally went wrong:\n *\n * - The idempotency key stops a DUPLICATE refund — one attempt sent twice\n * because the response was lost or the admin double-clicked. It is minted\n * per attempt by the console and deliberately not derived from the booking\n * or the amount: two $10 refunds on a $75 booking are two real refunds.\n * - The cap stops an OVER-refund — several partials summing past what was\n * captured, including two admins refunding at once, where the attempts are\n * genuinely distinct and no key can help. That needs the counter read and\n * written inside one transaction, BEFORE Stripe is called, so a lost\n * response leaves the amount counted and the retry refunds less, never\n * more.\n *\n * A DIRECT-charge booking (`chargeModel: 'direct'`) was charged on the\n * seller's own account, so its refund is made there (`Stripe-Account`) and is\n * debited from the seller's balance. There is no transfer to reverse, so\n * `reverse_transfer` is never sent; `refund_application_fee` still is, for the\n * same reason as above.\n */\nexport const bookingRefundHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const bookingId = String(body.bookingId ?? '')\n // `null`/absent means \"everything still refundable\"; a number is a partial.\n const amountCents = body.amountCents == null ? null : Number(body.amountCents)\n // Node lowercases incoming headers, but read both spellings — the plugin API\n // request type makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n )\n .trim()\n .slice(0, 200)\n if (!hostId || !bookingId) {\n return res.status(400).json({ error: 'Missing hostId or bookingId' })\n }\n if (amountCents != null && !(Number.isFinite(amountCents) && amountCents > 0)) {\n return res.status(400).json({ error: 'Invalid refund amount' })\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // \"Refund bookings\" (AGL-4047), not merely a member: this moves money.\n // Its preset is the site Admin, the gate `commerce/refund.ts` applies.\n if (!holdsBookingsSiteKey(hostSnapshot, decoded.uid, 'bookings.refunds')) {\n return res.status(403).json({ error: bookingsSitePermissionRefusal('bookings.refunds') })\n }\n const bookingRef = hostRef.collection('bookings').doc(bookingId)\n const bookingSnapshot = await bookingRef.get()\n if (!bookingSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown booking' })\n }\n // As it stood before this refund, for the event a full refund raises.\n const bookingBefore = (bookingSnapshot.data() ?? {}) as Record<string, unknown>\n const paymentIntentId = String(bookingSnapshot.get('paymentIntentId') ?? '')\n const paidCents = Math.max(\n 0,\n Math.round(Number(bookingSnapshot.get('paidAmountCents') ?? 0)),\n )\n if (!paidCents) {\n return res.status(409).json({ error: 'This booking was never paid' })\n }\n if (!paymentIntentId) {\n // A booking paid BEFORE the webhook began recording the PaymentIntent\n // (AGL-2315). Refundable, but only by hand — and saying so beats a 500\n // an admin cannot act on.\n return res.status(409).json({\n error:\n 'This booking was paid before refunds were supported here. ' +\n 'Refund it in the Stripe dashboard, and tick “Reverse transfer” ' +\n 'so the amount comes back from the merchant account.',\n })\n }\n // Where the charge lives. A direct booking records the seller's account\n // when it is held; without it the refund would be sent to the platform,\n // where Stripe cannot find the payment, so refuse before reserving.\n const direct = bookingSnapshot.get('chargeModel') === 'direct'\n const chargeAccountId = direct\n ? String(bookingSnapshot.get('stripeAccountId') ?? '').trim()\n : ''\n if (direct && !chargeAccountId) {\n return res.status(409).json({\n error:\n 'This booking was paid on your Stripe account. ' +\n 'Refund it in your Stripe dashboard.',\n })\n }\n\n // Replay a settled attempt before anything else can reject it. This read\n // is only a short-circuit, never the dedupe primitive — the atomic\n // `create()` below is.\n const claimRef = idempotencyKey\n ? firestore.collection('apiIdempotency').doc(\n createHash('sha256')\n // Scoped by the BOOKING, so a client that reused one key across\n // two bookings cannot dedupe two legitimately distinct refunds.\n // NOT by the amount: that would swallow a real second partial.\n .update(`booking-refund:${hostId}:${bookingId}:${idempotencyKey}`)\n .digest('hex'),\n )\n : null\n if (claimRef) {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n try {\n // The claim's shape is every claim's (`claimApiIdempotency`): its\n // kind, scope and org name it on the staff claims list, `createdAtMs`\n // ages it there, and `expiresAt` lets the TTL policy reap it — a\n // claim stranded by a killed process otherwise holds its key forever.\n await claimRef.create({\n kind: 'booking-refund',\n scopeId: hostId,\n orgId: String(hostSnapshot.get('orgId') ?? '') || null,\n bookingId,\n status: 'pending',\n createdAtMs: Date.now(),\n expiresAt: apiIdempotencyExpiry(),\n })\n } catch {\n // Another attempt with this key is in flight.\n return res\n .status(409)\n .json({ error: 'This refund is already being processed' })\n }\n }\n\n // RESERVE. Read and write the counter in ONE transaction so two concurrent\n // refunds cannot both see the same `refundedCents` and each send a full\n // amount to Stripe — the failure the order refund shipped with.\n let refundCents = 0\n let alreadyRefunded = 0\n await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n alreadyRefunded = Math.max(\n 0,\n Math.round(Number(fresh.get('refundedCents') ?? 0)),\n )\n const remaining = paidCents - alreadyRefunded\n refundCents =\n amountCents == null\n ? remaining\n : Math.min(Math.round(amountCents), remaining)\n if (!(refundCents > 0)) {\n refundCents = 0\n return\n }\n transaction.set(\n bookingRef,\n { refundedCents: alreadyRefunded + refundCents },\n { merge: true },\n )\n })\n if (!(refundCents > 0)) {\n await claimRef?.delete().catch(() => undefined)\n return res.status(400).json({ error: 'Nothing left to refund' })\n }\n\n const params = direct\n ? new URLSearchParams({\n payment_intent: paymentIntentId,\n amount: String(refundCents),\n // The money is already the seller's, so the refund comes out of\n // their balance with no transfer to reverse. Aglyn's commission on\n // the refunded share still goes back to them.\n refund_application_fee: 'true',\n })\n : new URLSearchParams({\n payment_intent: paymentIntentId,\n amount: String(refundCents),\n // THE SELLER SHARE COMES BACK. Without this the merchant keeps their\n // transfer in full and Aglyn funds the entire refund.\n reverse_transfer: 'true',\n // ...and so does Aglyn's commission on the refunded share. A refunded\n // appointment earned the platform nothing.\n refund_application_fee: 'true',\n })\n const response = await fetch('https://api.stripe.com/v1/refunds', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(claimRef ? { 'Idempotency-Key': claimRef.id } : {}),\n // A direct booking's payment is on the seller's account.\n ...(direct ? { 'Stripe-Account': chargeAccountId } : {}),\n },\n body: params.toString(),\n })\n const refund = await response.json().catch(() => ({}) as any)\n if (!response.ok) {\n console.error('Stripe booking refund error', (refund as any)?.error)\n // Stripe said no, so we KNOW no money moved: give the reservation back\n // and let the same attempt be retried.\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(bookingRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n bookingRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claimRef?.delete().catch(() => undefined)\n return res.status(502).json({ error: 'Refund failed' })\n }\n\n // A FULL refund ends the appointment; a partial leaves it standing. The\n // guest who got half their money back still has the slot, and moving the\n // booking off `confirmed` would reopen a time the merchant is still\n // committed to.\n const totalRefunded = alreadyRefunded + refundCents\n const fullyRefunded = totalRefunded >= paidCents\n await bookingRef\n .set(\n {\n refundedCents: totalRefunded,\n ...(fullyRefunded ? { status: 'canceled' } : {}),\n },\n { merge: true },\n )\n .catch(() => undefined)\n // The full refund is what cancels a paid booking (AGL-3643). Keyed by the\n // booking, so a booking canceled before is not announced again.\n if (fullyRefunded && bookingBefore['status'] !== 'canceled') {\n await raiseBookingEvent(firestore, {\n event: 'booking.canceled',\n hostId,\n bookingId,\n booking: {\n ...bookingBefore,\n refundedCents: totalRefunded,\n status: 'canceled',\n },\n })\n }\n\n const payload = {\n refundedCents: refundCents,\n totalRefundedCents: totalRefunded,\n fullyRefunded,\n }\n await claimRef\n ?.set(\n {\n status: 'done',\n responseStatus: 200,\n response: payload,\n settledAtMs: Date.now(),\n },\n { merge: true },\n )\n .catch(() => undefined)\n /*\n * The campaign's side of the ledger.\n *\n * A paid booking is credited to the campaign that led to it — the sale\n * announces itself through `upsertHostContact` with a `purchaseCents` and\n * this booking's id, exactly as a store order does — so a refunded one\n * has to stop counting. Without this, a booking site's campaign revenue\n * could only ever rise.\n *\n * Keyed by the BOOKING id, which is what the credit was filed under, so\n * this needs no email and works for a guest who never became a contact.\n * Recorded beside the credit rather than subtracted from it, and swallowed\n * whole: the money has already left the merchant's account and the booking\n * already records it, so nothing here may fail a refund.\n */\n await reverseOrderConversion({\n hostId,\n orderId: bookingId,\n amountCents: refundCents,\n closedTheOrder: fullyRefunded,\n })\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Refund failed' })\n }\n}\n"],"names":["firebaseAdmin","reverseOrderConversion","createHash","apiIdempotencyExpiry","bookingsSitePermissionRefusal","holdsBookingsSiteKey","raiseBookingEvent","bookingRefundHandler","req","res","body","method","status","json","error","process","env","STRIPE_SECRET_KEY","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","bookingId","amountCents","Number","idempotencyKey","trim","isFinite","bookingSnapshot","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","bookingRef","bookingBefore","data","paymentIntentId","paidCents","Math","max","round","direct","chargeAccountId","claimRef","update","digest","prior","priorResponse","create","kind","scopeId","orgId","createdAtMs","Date","now","expiresAt","refundCents","alreadyRefunded","runTransaction","transaction","fresh","remaining","min","set","refundedCents","merge","delete","catch","params","URLSearchParams","payment_intent","amount","refund_application_fee","reverse_transfer","response","fetch","Authorization","id","toString","refund","ok","console","current","totalRefunded","fullyRefunded","event","booking","payload","totalRefundedCents","responseStatus","settledAtMs","orderId","closedTheOrder"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AAExD,8DAA8D;AAC9D,2EAA2E;AAC3E,sCAAsC;AACtC,SAASC,sBAAsB,QAAQ,uDAAsD;AAC7F,SAASC,UAAU,QAAQ,SAAQ;AACnC,SAASC,oBAAoB,QAAQ,yCAAwC;AAC7E,SAASC,6BAA6B,QAAQ,mCAA+B;AAC7E,SAASC,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,iBAAiB,QAAQ,sBAAkB;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoDC,GACD,OAAO,MAAMC,uBAAyC,OAAOC,KAAKC;QAOnCD,4BAM4BA,WACnCE,cACGA,iBAMvBF,MAAAA;IApBF,IAAIA,IAAIG,MAAM,KAAK,QAAQ;QACzB,OAAOF,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,IAAI,CAACC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAOR,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA+B;IACtE;IACA,MAAMI,gBAAgBC,QAAOX,6BAAAA,IAAIY,OAAO,CAACF,aAAa,YAAzBV,6BAA6B;IAC1D,MAAMa,UAAUH,cAAcI,UAAU,CAAC,aACrCJ,cAAcK,KAAK,CAAC,UA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M0F,UAAU;YACdvB,eAAeR;YACfgC,oBAAoBL;YACpBC;QACF;QACA,OAAMzC,4BAAAA,SACFoB,GAAG,CACH;YACElE,QAAQ;YACR4F,gBAAgB;YAChBf,UAAUa;YACVG,aAAarC,KAAKC,GAAG;QACvB,GACA;YAAEW,OAAO;QAAK,GAEfE,KAAK,CAAC,IAAMzD;QACf;;;;;;;;;;;;;;KAcC,GACD,MAAMxB,uBAAuB;YAC3B2B;YACA8E,SAAS7E;YACTC,aAAayC;YACboC,gBAAgBR;QAClB;QACA,OAAO1F,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAACyF;IAC9B,EAAE,OAAOxF,OAAO;QACdkF,QAAQlF,KAAK,CAACA;QACd,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAgB;IACvD;AACF,EAAC"}
|
package/src/lib/server.js
CHANGED
|
@@ -15,6 +15,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { siteReturnOrigin } from "@aglyn/aglyn/app-utils/site-return-url";
|
|
18
|
+
import { excludeBuyNowPayLater } from "@aglyn/aglyn/app-utils/buy-now-pay-later";
|
|
18
19
|
import { checkEntitlement, registerPluginConfigSchema, registerPluginJob, resolveBrandingProfile, resolveTransactionFeeCents } from "@aglyn/aglyn/server";
|
|
19
20
|
// The leaf, not the barrel: the console's `x-cron-secret` door asks the
|
|
20
21
|
// site's lockdown directly (AGL-3356) — core's registry has no resolver in
|
|
@@ -91,7 +92,7 @@ registerPluginJob({
|
|
|
91
92
|
}
|
|
92
93
|
});
|
|
93
94
|
import { firebaseAdmin, getOrgForHost, meterHostEmail, notifyHostManagers, getPluginConfig, resolveOrgIdForHost, renderHostEmailWithTokens, hostSendingIdentity } from "@aglyn/tenant-data-admin";
|
|
94
|
-
import { merchantAccountIsReady } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
95
|
+
import { connectedAccountHeader, directChargeParams, merchantAccountIsReady, saleChargeModel } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
95
96
|
import { checkoutSessionCardAuthenticationParams } from "@aglyn/tenant-data-admin/server/stripe-card-authentication";
|
|
96
97
|
import { emitHostEvent } from "@aglyn/tenant-runtime";
|
|
97
98
|
import recordCapturedContact from "@aglyn/aglyn/plugin-manager/record-captured-contact";
|
|
@@ -393,6 +394,10 @@ export const slotsHandler = async (req, res)=>{
|
|
|
393
394
|
// would strand a real appointment slot as `pendingPayment` for 15 minutes
|
|
394
395
|
// on a booking that could never be paid.
|
|
395
396
|
let chargeAccountId = '';
|
|
397
|
+
// DIRECT or DESTINATION, by the seller's profile. A direct charge is made
|
|
398
|
+
// ON the seller's own account, which Stripe bills itself; everything else
|
|
399
|
+
// keeps the destination charge this path has always made.
|
|
400
|
+
let chargeModel = 'destination';
|
|
396
401
|
let feeCents = 0;
|
|
397
402
|
// No tax until a paid booking asks the tenant's tax rule what is owed.
|
|
398
403
|
let serviceTax = {
|
|
@@ -423,6 +428,7 @@ export const slotsHandler = async (req, res)=>{
|
|
|
423
428
|
error: 'Payments are not set up yet'
|
|
424
429
|
});
|
|
425
430
|
}
|
|
431
|
+
chargeModel = saleChargeModel(ownerProfile == null ? void 0 : ownerProfile.get('stripeChargeModel'));
|
|
426
432
|
// THE TAKE RATE IS THE STOREFRONT LADDER'S, NOT A NEW ONE (AGL-2315).
|
|
427
433
|
//
|
|
428
434
|
// the decision, 2026-08-19: bookings mirror the storefront ladder —
|
|
@@ -503,7 +509,13 @@ export const slotsHandler = async (req, res)=>{
|
|
|
503
509
|
// (AGL-2152). The comment above already promised this: "a fee derived
|
|
504
510
|
// from `priceUsd` stays off the tax the moment tax is added". This is
|
|
505
511
|
// the moment.
|
|
506
|
-
|
|
512
|
+
//
|
|
513
|
+
// A DIRECT charge passes no card cost through: Stripe bills the seller
|
|
514
|
+
// its own fee and charges the platform nothing for the sale, so the
|
|
515
|
+
// application fee is the take alone.
|
|
516
|
+
feeCents = resolveTransactionFeeCents(ownerOrg, 'service', chargeCents, chargeCents + serviceTax.taxCents, chargeModel === 'direct' ? {
|
|
517
|
+
direct: true
|
|
518
|
+
} : {});
|
|
507
519
|
}
|
|
508
520
|
// Transaction: re-read overlapping bookings and validate the slot so
|
|
509
521
|
// two simultaneous requests cannot double-book.
|
|
@@ -545,6 +557,9 @@ export const slotsHandler = async (req, res)=>{
|
|
|
545
557
|
expiresAtMs: Date.now() + 15 * 60000
|
|
546
558
|
}, crmRef ? {
|
|
547
559
|
crmRef: formatBookingRecordRef(crmRef)
|
|
560
|
+
} : {}, paid && chargeModel === 'direct' ? {
|
|
561
|
+
chargeModel: 'direct',
|
|
562
|
+
stripeAccountId: chargeAccountId
|
|
548
563
|
} : {});
|
|
549
564
|
transaction.set(bookingRef, _extends({}, record, {
|
|
550
565
|
createdAt: FieldValue.serverTimestamp()
|
|
@@ -676,7 +691,7 @@ export const slotsHandler = async (req, res)=>{
|
|
|
676
691
|
'line_items[1][price_data][currency]': 'usd',
|
|
677
692
|
'line_items[1][price_data][unit_amount]': String(serviceTax.taxCents),
|
|
678
693
|
'line_items[1][price_data][product_data][name]': serviceTax.label
|
|
679
|
-
} : {}, {
|
|
694
|
+
} : {}, chargeModel === 'direct' ? directChargeParams(feeCents) : _extends({
|
|
680
695
|
// Destination charge to the MERCHANT's connected account (AGL-2315).
|
|
681
696
|
// Unconditional: `transfer_data[destination]` is what makes this the
|
|
682
697
|
// merchant's money, and it is required on every paid booking whatever
|
|
@@ -684,7 +699,7 @@ export const slotsHandler = async (req, res)=>{
|
|
|
684
699
|
'payment_intent_data[transfer_data][destination]': chargeAccountId
|
|
685
700
|
}, feeCents > 0 ? {
|
|
686
701
|
'payment_intent_data[application_fee_amount]': String(feeCents)
|
|
687
|
-
} : {}, {
|
|
702
|
+
} : {}), {
|
|
688
703
|
// `{CHECKOUT_SESSION_ID}` is Stripe's own template token, substituted
|
|
689
704
|
// on the redirect (AGL-2481). Without it the guest came back holding
|
|
690
705
|
// the word `paid` and nothing else — no id, no amount — so the
|
|
@@ -707,12 +722,17 @@ export const slotsHandler = async (req, res)=>{
|
|
|
707
722
|
}, serviceTax.taxCents > 0 ? {
|
|
708
723
|
'metadata[taxCents]': String(serviceTax.taxCents),
|
|
709
724
|
'metadata[taxPct]': String(serviceTax.pct)
|
|
725
|
+
} : {}, chargeModel === 'direct' ? {
|
|
726
|
+
'metadata[chargeModel]': 'direct'
|
|
710
727
|
} : {}, {
|
|
711
728
|
expires_at: String(Math.floor(Date.now() / 1000) + 30 * 60)
|
|
712
729
|
}));
|
|
730
|
+
// No buy-now-pay-later on a booking (AGL-4198), so the fee above,
|
|
731
|
+
// priced at the card rate, covers whatever the guest pays with.
|
|
732
|
+
excludeBuyNowPayLater(params);
|
|
713
733
|
const stripeResponse = await fetch('https://api.stripe.com/v1/checkout/sessions', {
|
|
714
734
|
method: 'POST',
|
|
715
|
-
headers: {
|
|
735
|
+
headers: _extends({
|
|
716
736
|
Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
|
|
717
737
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
718
738
|
// AGL-2147. This was the ONE session-creating path in the repo
|
|
@@ -734,7 +754,7 @@ export const slotsHandler = async (req, res)=>{
|
|
|
734
754
|
// that opens a SECOND payable session against one held slot, and
|
|
735
755
|
// a guest who pays both is charged twice for one appointment.
|
|
736
756
|
'Idempotency-Key': `booking-${bookingId}`
|
|
737
|
-
},
|
|
757
|
+
}, connectedAccountHeader(chargeModel, chargeAccountId)),
|
|
738
758
|
body: params.toString()
|
|
739
759
|
});
|
|
740
760
|
const session = await stripeResponse.json();
|