@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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-bookings",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.15.1",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,16 +25,16 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.
|
|
29
|
-
"@aglyn/shared-data-mdi": "1.
|
|
30
|
-
"@aglyn/shared-ui-jsx": "1.
|
|
31
|
-
"@aglyn/shared-ui-snackstack": "1.
|
|
32
|
-
"@aglyn/shared-util-email": "1.
|
|
33
|
-
"@aglyn/shared-util-http": "1.
|
|
34
|
-
"@aglyn/shared-util-timestamp": "1.
|
|
35
|
-
"@aglyn/tenant-data-admin": "1.
|
|
36
|
-
"@aglyn/tenant-feature-instance": "1.
|
|
37
|
-
"@aglyn/tenant-runtime": "1.
|
|
28
|
+
"@aglyn/aglyn": "1.15.1",
|
|
29
|
+
"@aglyn/shared-data-mdi": "1.15.1",
|
|
30
|
+
"@aglyn/shared-ui-jsx": "1.15.1",
|
|
31
|
+
"@aglyn/shared-ui-snackstack": "1.15.1",
|
|
32
|
+
"@aglyn/shared-util-email": "1.15.1",
|
|
33
|
+
"@aglyn/shared-util-http": "1.15.1",
|
|
34
|
+
"@aglyn/shared-util-timestamp": "1.15.1",
|
|
35
|
+
"@aglyn/tenant-data-admin": "1.15.1",
|
|
36
|
+
"@aglyn/tenant-feature-instance": "1.15.1",
|
|
37
|
+
"@aglyn/tenant-runtime": "1.15.1",
|
|
38
38
|
"@swc/helpers": "0.5.23"
|
|
39
39
|
},
|
|
40
40
|
"peerDependencies": {
|
|
@@ -143,8 +143,12 @@ import { bookingContactLines, readBookingPhone } from "../model/booking-contact-
|
|
|
143
143
|
settled: outcome.kind === 'reversed' ? 'reversed' : 'failed'
|
|
144
144
|
};
|
|
145
145
|
}
|
|
146
|
-
export const bookingsBillingWebhookHandler = async ({ type, object })=>{
|
|
146
|
+
export const bookingsBillingWebhookHandler = async ({ type, object, event })=>{
|
|
147
147
|
var _object_metadata;
|
|
148
|
+
// The seller's account when this event is about a DIRECT charge: Stripe
|
|
149
|
+
// delivers those through the Connect endpoint with the account on the
|
|
150
|
+
// event itself. Empty for the platform's own (destination) charges.
|
|
151
|
+
const eventAccount = typeof (event == null ? void 0 : event.account) === 'string' ? event.account.trim() : '';
|
|
148
152
|
// Fraud signals on a paid booking (AGL-3360): an issuer's early fraud
|
|
149
153
|
// warning, a Radar review, or a dispute. Booking deposits never heard
|
|
150
154
|
// about any of them, so the merchant learned of a chargeback from Stripe
|
|
@@ -197,6 +201,15 @@ export const bookingsBillingWebhookHandler = async ({ type, object })=>{
|
|
|
197
201
|
claimed: true,
|
|
198
202
|
hostId
|
|
199
203
|
};
|
|
204
|
+
// A DIRECT charge's dispute is debited from the seller's own account by
|
|
205
|
+
// Stripe, and there was never a transfer for the platform to pull back,
|
|
206
|
+
// so a lost one is settled as recorded above and claimed.
|
|
207
|
+
if (eventAccount || booking.get('chargeModel') === 'direct') {
|
|
208
|
+
return {
|
|
209
|
+
claimed: true,
|
|
210
|
+
hostId
|
|
211
|
+
};
|
|
212
|
+
}
|
|
200
213
|
const recovered = await reverseBookingSellerShare(booking.ref, object);
|
|
201
214
|
if (recovered.cents > 0 && hostId) {
|
|
202
215
|
var _booking_get1, _booking_get2;
|
|
@@ -221,7 +234,7 @@ export const bookingsBillingWebhookHandler = async ({ type, object })=>{
|
|
|
221
234
|
const { hostId, bookingId } = (_object_metadata1 = object.metadata) != null ? _object_metadata1 : {};
|
|
222
235
|
if (hostId && bookingId) {
|
|
223
236
|
var _ref6, _ref7, _ref8, _ref9, _booking_name, _booking_serviceName;
|
|
224
|
-
var _object_metadata2, _object_payment_intent1, _object_metadata3;
|
|
237
|
+
var _object_metadata2, _object_payment_intent1, _object_metadata3, _object_metadata4;
|
|
225
238
|
const firestore = firebaseAdmin.app().firestore();
|
|
226
239
|
const bookingRef = firestore.collection('hosts').doc(String(hostId)).collection('bookings').doc(String(bookingId));
|
|
227
240
|
// WHAT THE CLIENT HANDED OVER, ALL OF IT. Tax included: this is the
|
|
@@ -260,6 +273,10 @@ export const bookingsBillingWebhookHandler = async ({ type, object })=>{
|
|
|
260
273
|
// taken. `'0'` is a real recorded answer on the 0%-rate tiers.
|
|
261
274
|
const paymentIntentId = typeof (object == null ? void 0 : object.payment_intent) === 'string' ? object.payment_intent : String((_ref8 = object == null ? void 0 : (_object_payment_intent1 = object.payment_intent) == null ? void 0 : _object_payment_intent1.id) != null ? _ref8 : '');
|
|
262
275
|
const chargedFeeCents = Math.max(0, Math.round(Number((_ref9 = object == null ? void 0 : (_object_metadata3 = object.metadata) == null ? void 0 : _object_metadata3.feeCents) != null ? _ref9 : 0)));
|
|
276
|
+
// A DIRECT charge lives on the seller's account, which a refund has
|
|
277
|
+
// to be sent to. The event names that account; `server.ts` stamped it
|
|
278
|
+
// on the hold too, so an event without one leaves that stamp alone.
|
|
279
|
+
const direct = (object == null ? void 0 : (_object_metadata4 = object.metadata) == null ? void 0 : _object_metadata4.chargeModel) === 'direct' || Boolean(eventAccount);
|
|
263
280
|
// Redelivery guard (AGL-1755), the AGL-1748 shape. This was an
|
|
264
281
|
// unconditional merge-set with no status check at all — idempotent
|
|
265
282
|
// only by accident, because every value it wrote was fixed. A
|
|
@@ -325,7 +342,11 @@ export const bookingsBillingWebhookHandler = async ({ type, object })=>{
|
|
|
325
342
|
paymentIntentId
|
|
326
343
|
} : {}, {
|
|
327
344
|
feeCents: chargedFeeCents
|
|
328
|
-
},
|
|
345
|
+
}, direct ? _extends({
|
|
346
|
+
chargeModel: 'direct'
|
|
347
|
+
}, eventAccount ? {
|
|
348
|
+
stripeAccountId: eventAccount
|
|
349
|
+
} : {}) : {}, (object == null ? void 0 : object.id) ? {
|
|
329
350
|
checkoutSessionId: String(object.id)
|
|
330
351
|
} : {}, {
|
|
331
352
|
// NOTE the absent `refundedCents: 0`. Seeding it here would be
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/billing-webhook.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\n// `after()`, never a bare `void promise` (AGL-2327). This handler runs inside\n// the console's `/api/billing/webhook` invocation, which AGL-1133 measured on\n// production is frozen the moment the response is sent — so fire-and-forget\n// work scheduled any other way simply does not run.\nimport { after } from 'next/server'\n\nimport type { BillingWebhookHandler } from '@aglyn/aglyn/server'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n notifyHostManagers,\n notifyRiskEvent,\n renderHostEmailWithTokens,\n sendGa4Purchase,\n} from '@aglyn/tenant-data-admin'\nimport { paymentRiskEventFrom } from '@aglyn/aglyn/app-utils/payment-risk'\nimport {\n recordPaymentRiskOnRecord,\n settlePaymentRiskDisputeOnRecord,\n} from '@aglyn/tenant-data-admin/server/payment-risk-record'\nimport {\n reverseDestinationTransfer,\n type TransferReversalFailure,\n} from '@aglyn/tenant-data-admin/server/stripe-transfer-reversal'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport {\n bookingPlatformNetCents,\n shouldSendBookingPlatformPurchase,\n} from '../model/booking-purchase-analytics'\nimport { sendEmail } from '@aglyn/shared-util-email'\nimport { pluginTaxProfile } from '@aglyn/aglyn/plugin-manager/plugin-tax-profile'\nimport { fileBookingOnCrm } from './booking-crm'\nimport { stageBookingEvent } from './booking-events'\nimport { bookingTimeZoneFor } from './booking-time-zone'\nimport { formatBookingWhen } from '../model/booking-time'\nimport {\n bookingContactLines,\n readBookingPhone,\n} from '../model/booking-contact-fields'\n\n/**\n * Paid-booking section of the platform Stripe webhook (AGL-170/418):\n * payment confirms the pendingPayment hold — relocated verbatim from the\n * console route; registered via registerBookingsConsoleApi.\n */\n/** gRPC `Status.FAILED_PRECONDITION` — Firestore's \"this query needs an index\". */\nconst GRPC_FAILED_PRECONDITION = 9\n\n/**\n * The booking a charge paid for, found by the `paymentIntentId` the paid\n * handler below records (AGL-2315), or null. A missing collection-group\n * index is logged and answered null rather than thrown: no redelivery can\n * fix it, and the dispute then reaches staff through the route's\n * unattributed-dispute alert instead of vanishing.\n */\nasync function findBookingForPayment(\n paymentIntentId: string,\n): Promise<FirebaseFirestore.QueryDocumentSnapshot | null> {\n if (!paymentIntentId) return null\n const matches = await firebaseAdmin\n .app()\n .firestore()\n .collectionGroup('bookings')\n .where('paymentIntentId', '==', paymentIntentId)\n .limit(2)\n .get()\n .catch((error: { code?: number }) => {\n if (error?.code !== GRPC_FAILED_PRECONDITION) throw error\n console.error(\n 'Booking payment lookup needs the collection-group index on ' +\n 'bookings.paymentIntentId (AGL-3360)',\n error,\n )\n return null\n })\n // One payment intent pays one booking; two is corrupt data, and stamping\n // an arbitrary one would tell the wrong merchant.\n return matches && matches.docs.length === 1 ? matches.docs[0] : null\n}\n\n/** What a booking records once its lost dispute's reversal is settled. */\ninterface BookingDisputeReversal {\n disputeId: string\n reversedTransferCents: number\n transferReversalId?: string\n /** Why nothing was pulled back, when nothing was. */\n failedReason?: TransferReversalFailure\n owedCents?: number\n atMs: number\n}\n\n/**\n * The merchant's share of a LOST booking dispute, pulled back from the\n * connected account (AGL-3363), by the AGL-1794 policy a store order follows:\n * the Stripe half is the shared `reverseDestinationTransfer`, this is only\n * the booking's own record.\n *\n * IDEMPOTENT BY THE BOOKING: `disputeReversal` for this dispute, present,\n * means settled and a redelivery returns before any Stripe call. A delivery\n * that died after the POST is healed by the seam adopting the reversal the\n * transfer already carries. A transient Stripe failure THROWS (the seam\n * does), leaving the marker unset so Stripe's redelivery retries it. A final\n * failure is settled with its reason and the owed amount, so it is findable.\n *\n * `cents` is non-zero only for the delivery that wrote the reversal, which\n * is the one that tells the merchant.\n */\nasync function reverseBookingSellerShare(\n bookingRef: FirebaseFirestore.DocumentReference,\n dispute: any,\n): Promise<{ cents: number; settled: 'reversed' | 'failed' | 'pending' }> {\n const disputeId = String(dispute?.id ?? '')\n const amountCents = Math.max(0, Math.round(Number(dispute?.amount ?? 0)))\n if (!disputeId || !(amountCents > 0)) return { cents: 0, settled: 'failed' }\n const firestore = firebaseAdmin.app().firestore()\n const prior = (await bookingRef.get()).get('disputeReversal') as\n | BookingDisputeReversal\n | undefined\n if (prior?.disputeId === disputeId) {\n return { cents: 0, settled: prior.failedReason ? 'failed' : 'reversed' }\n }\n const outcome = await reverseDestinationTransfer({\n kind: 'dispute',\n id: disputeId,\n amountCents,\n chargeId:\n typeof dispute?.charge === 'string' ? dispute.charge : String(dispute?.charge?.id ?? ''),\n metadata: { bookingId: bookingRef.id },\n })\n if (outcome.kind === 'skipped') {\n console.error('Booking transfer reversal skipped: STRIPE_SECRET_KEY is not set (AGL-3363)')\n return { cents: 0, settled: 'pending' }\n }\n const record: BookingDisputeReversal =\n outcome.kind === 'reversed'\n ? {\n disputeId,\n reversedTransferCents: outcome.cents,\n ...(outcome.reversalId ? { transferReversalId: outcome.reversalId } : {}),\n atMs: Date.now(),\n }\n : {\n disputeId,\n reversedTransferCents: 0,\n failedReason: outcome.reason,\n ...(outcome.owedCents != null ? { owedCents: outcome.owedCents } : {}),\n atMs: Date.now(),\n }\n if (outcome.kind === 'not-reversed') {\n console.error('Booking seller share NOT reversed — recorded on the booking', {\n bookingId: bookingRef.id,\n disputeId,\n reason: outcome.reason,\n })\n }\n const wrote = await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n if (!fresh.exists) return false\n const current = fresh.get('disputeReversal') as BookingDisputeReversal | undefined\n if (current?.disputeId === disputeId) return false\n transaction.set(bookingRef, { disputeReversal: record }, { merge: true })\n return true\n })\n return {\n cents: wrote && outcome.kind === 'reversed' ? outcome.cents : 0,\n settled: outcome.kind === 'reversed' ? 'reversed' : 'failed',\n }\n}\n\nexport const bookingsBillingWebhookHandler: BillingWebhookHandler = async ({\n type,\n object,\n}) => {\n // Fraud signals on a paid booking (AGL-3360): an issuer's early fraud\n // warning, a Radar review, or a dispute. Booking deposits never heard\n // about any of them, so the merchant learned of a chargeback from Stripe\n // alone. The signal now lands on the BOOKING, through the shared\n // `paymentRisk` shape every plugin stamps, and the site's managers are\n // told once. Nothing is refunded or canceled: the merchant decides.\n const risk = paymentRiskEventFrom(type, object)\n if (risk) {\n const booking = await findBookingForPayment(risk.paymentIntentId)\n if (!booking) return\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n await recordPaymentRiskOnRecord(\n {\n ref: booking.ref,\n signal: risk.signal,\n hostId,\n subjectLabel: `the booking for ${String(booking.get('serviceName') ?? booking.id)}`,\n link: `/${hostId}/bookings`,\n notificationType: 'content.booking',\n amount: Number.isFinite(Number(booking.get('paidAmountCents')))\n ? `$${(Number(booking.get('paidAmountCents')) / 100).toFixed(2)}`\n : null,\n evidenceDueByMs:\n Number((object as { evidence_details?: { due_by?: unknown } })?.evidence_details?.due_by ?? 0) * 1000 || null,\n },\n { firestore: firebaseAdmin.app().firestore(), notifyRisk: notifyRiskEvent },\n )\n return { claimed: true, hostId }\n }\n // A dispute's outcome, on the signal `created` stamped. A LOST one pulls\n // the merchant's share back from the connected account (AGL-3363), through\n // the same seam a lost store order uses, so the platform no longer absorbs\n // a booking chargeback. Claimed when the share came back; a reversal that\n // could not be made stays unclaimed, so the route's unattributed-dispute\n // alert still tells staff about money nothing recovered.\n if (type === 'charge.dispute.closed') {\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const booking = await findBookingForPayment(paymentIntentId)\n if (!booking) return\n const outcome = String(object?.status ?? '')\n await settlePaymentRiskDisputeOnRecord(\n booking.ref,\n String(object?.id ?? ''),\n outcome,\n { firestore: firebaseAdmin.app().firestore() },\n )\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n if (outcome !== 'lost') return { claimed: true, hostId }\n const recovered = await reverseBookingSellerShare(booking.ref, object)\n if (recovered.cents > 0 && hostId) {\n const recoveredText = `$${(recovered.cents / 100).toFixed(2)}`\n const guest = String(booking.get('name') ?? '').trim()\n const service = String(booking.get('serviceName') ?? '').trim() || 'a service'\n await notifyHostManagers(hostId, {\n type: 'content.booking',\n title: `Payout adjusted — ${recoveredText} recovered for a lost chargeback`,\n body:\n `${guest ? `${guest}'s payment` : 'A payment'} for ${service} on ` +\n `{site} was charged back and the dispute was lost, so ` +\n `the ${recoveredText} transferred to you for it has been taken back. ` +\n `If your balance does not cover it, Stripe recovers the rest from ` +\n `your future payouts.`,\n link: `/${hostId}/bookings`,\n })\n }\n return recovered.settled === 'reversed' ? { claimed: true, hostId } : undefined\n }\n // Paid bookings (AGL-170): payment confirms the pendingPayment hold.\n if (\n type === 'checkout.session.completed' &&\n object?.metadata?.type === 'booking-payment' &&\n object?.payment_status === 'paid'\n ) {\n const { hostId, bookingId } = object.metadata ?? {}\n if (hostId && bookingId) {\n const firestore = firebaseAdmin.app().firestore()\n const bookingRef = firestore\n .collection('hosts')\n .doc(String(hostId))\n .collection('bookings')\n .doc(String(bookingId))\n // WHAT THE CLIENT HANDED OVER, ALL OF IT. Tax included: this is the\n // ceiling `refund.ts` reverses against, and the client paid the tax\n // too — a net figure here would strand part of a refund.\n const paidAmountCents = Math.max(\n 0,\n Math.round(Number(object?.amount_total ?? 0)),\n )\n // THE MERCHANT'S SERVICE TAX, SEPARATED OUT (AGL-2028).\n //\n // `server.ts` charges the merchant's own service rate as an ordinary\n // `line_items[1]` Stripe is never told is tax (the AGL-1711\n // construction, which is what keeps the figure the MERCHANT's rather\n // than something computed against Aglyn's registrations). So\n // `amount_total` is service-plus-tax while Stripe's own tax fields\n // read zero, and the session's metadata is the only witness — exactly\n // as it is for a buy-now sale.\n const taxCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.taxCents ?? 0)),\n )\n // The merchant's REVENUE, which is the charge less the tax. Used for\n // the contact's lifetime value below: tax is collected on behalf of\n // an authority and is not money the business earned, so counting it\n // would over-state every service client's worth.\n const serviceCents = Math.max(0, paidAmountCents - taxCents)\n // WHAT A REFUND WILL NEED (AGL-2315). A paid booking is now a\n // destination charge to the merchant's connected account, and\n // reversing one requires the PaymentIntent — which lives only on this\n // event. The booking document recorded `paidAmountCents` and nothing\n // that identifies the charge, so a refund had no handle to pull and\n // the information was gone the moment the webhook returned. Unlike\n // most gaps this one cannot be backfilled from our own data later:\n // every booking taken before this line landed can only be refunded by\n // hand in the Stripe dashboard.\n //\n // `feeCents` is Aglyn's cut as CHARGED, read back off the session's\n // own metadata rather than re-derived from the org at refund time. The\n // rate follows the plan (AGL-2289's rule) and the plan moves, so\n // re-resolving it during a refund would reverse a share that was never\n // taken. `'0'` is a real recorded answer on the 0%-rate tiers.\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const chargedFeeCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.feeCents ?? 0)),\n )\n // Redelivery guard (AGL-1755), the AGL-1748 shape. This was an\n // unconditional merge-set with no status check at all — idempotent\n // only by accident, because every value it wrote was fixed. A\n // redelivery re-sent the guest's confirmation and re-metered it, and\n // the moment this handler carries money to a contact the accident stops\n // holding: `purchaseCents` is a `FieldValue.increment`, so every retry\n // would inflate the customer's lifetime value.\n //\n // Keyed on the STATUS, not on the document existing: `server.ts` writes\n // the booking as `pendingPayment` BEFORE it opens the Stripe session,\n // so existence is guaranteed by the time any event arrives and proves\n // nothing — the AGL-1748 reasoning, not AGL-1732's `checkoutSessionId`\n // key, which existed because a sibling event wrote the same path.\n //\n // The key is \"not yet confirmed\" rather than \"is pendingPayment\" on\n // purpose. The lapsed-hold sweeper in `server.ts` cancels a\n // `pendingPayment` booking after 24h, and refusing a payment that\n // landed anyway would take the money and record nothing; `confirmed` is\n // reachable for a PAID booking only by this handler having already run,\n // so it is an exact \"already processed\" test. The existence check is\n // new and deliberate: the old merge-set would CREATE a stub booking\n // from a metadata `bookingId` that pointed at nothing.\n let booking: Record<string, any> = {}\n const confirmedNow = await firestore.runTransaction(\n async (transaction) => {\n const snapshot = await transaction.get(bookingRef)\n if (!snapshot.exists) return false\n if (snapshot.get('status') === 'confirmed') return false\n // \"Already processed\" is WIDER than `confirmed` once money can\n // flow back out (AGL-2315). A refunded booking is moved off\n // `confirmed`, so a redelivery arriving afterwards would otherwise\n // read as unprocessed and re-confirm an appointment the merchant\n // has already cancelled and refunded — re-sending the guest a\n // confirmation for it and re-metering the email. Any evidence this\n // handler has run before is the real test, and a refund counter or\n // a recorded PaymentIntent is exactly that evidence.\n if (\n Number(snapshot.get('refundedCents') ?? 0) > 0 ||\n snapshot.get('paymentIntentId')\n ) {\n return false\n }\n booking = (snapshot.data() as any) ?? {}\n transaction.set(\n bookingRef,\n {\n status: 'confirmed',\n paidAmountCents,\n // WHICH TAX REGIME THIS BOOKING CARRIED (AGL-2028), on the\n // document the merchant reads — the stamp every other\n // storefront money door already carries (AGL-2451).\n //\n // DERIVED from the one shared derivation, never a constant.\n // A hand-written \"manual when the metadata says so\" would be\n // a second rule that can drift from the `storefrontTaxCollected`\n // row filed for the same Stripe id, which is the exact\n // disagreement AGL-2451 exists to prevent.\n //\n // TWO-ARGUMENT, because the manual line makes Stripe report\n // `total_details.amount_tax: 0` on a booking that really did\n // charge the client tax; the one-argument form would stamp\n // `none` on precisely those. `absent` remains a fourth state\n // meaning \"recorded before this shipped\".\n taxMode: pluginTaxProfile().taxModeOf(object, taxCents),\n // The figure itself. Absent rather than a defaulted `0` — a\n // zero written through `merge` is the AGL-1758 shape, and\n // this handler can re-enter (see the widened guard above).\n ...(taxCents > 0 ? { taxCents } : {}),\n // The refund handles (AGL-2315). Written inside the same\n // transaction as the status, so a booking can never read\n // `confirmed` while the means to refund it are missing.\n ...(paymentIntentId ? { paymentIntentId } : {}),\n feeCents: chargedFeeCents,\n // WHICH CHECKOUT PAID FOR THIS (AGL-2481). The guest's browser\n // comes back from Stripe holding a session id and nothing\n // else — a booking id was never in the return URL — so this is\n // what lets `booking-analytics.ts` answer \"what did I just\n // buy?\" for the merchant-side `purchase`, and it is written\n // here because the session id first exists on this event.\n //\n // Inside the transaction with the status on purpose: the\n // lookup refuses anything that is not `confirmed`, so a\n // booking can never be findable by session id while reading as\n // unpaid.\n ...(object?.id ? { checkoutSessionId: String(object.id) } : {}),\n // NOTE the absent `refundedCents: 0`. Seeding it here would be\n // the AGL-1758 shape: a defaulted field written through\n // `merge` destroying the real one. This handler can re-enter\n // after a refund has already accumulated a counter (see the\n // widened guard above), and a zero written back over it would\n // re-open the full amount for refunding a second time. Absent\n // IS zero — every reader coerces with `?? 0`.\n expiresAtMs: firebaseAdmin.firestore.FieldValue.delete(),\n confirmedAt:\n firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n // The booking is confirmed now, in this transaction (AGL-3643).\n const nowMs = Date.now()\n stageBookingEvent(transaction, firestore, {\n event: 'booking.created',\n hostId: String(hostId),\n bookingId: String(bookingId),\n booking: {\n ...booking,\n status: 'confirmed',\n paidAmountCents,\n ...(taxCents > 0 ? { taxCents } : {}),\n expiresAtMs: null,\n },\n nowMs,\n })\n return true\n },\n )\n if (!confirmedNow) return\n // THE RECORD'S MEETING (AGL-2660). Payment is what confirms a paid\n // booking, so this is where it reaches the CRM: the meeting on the\n // record's timeline and, when the service asks, the follow-up task.\n // Inside the idempotency gate for the same reason the GA4 purchase\n // below is — a redelivery must not file a second meeting — and\n // through `after()` for the same reason too: this invocation is\n // frozen the moment the response is sent (AGL-2327). Never thrown:\n // the writer swallows its own failures, and the catch is for the\n // scheduling itself.\n after(() =>\n fileBookingOnCrm(firestore, {\n hostId: String(hostId),\n bookingId: String(bookingId),\n booking,\n }).catch(() => undefined),\n )\n // AGLYN'S REVENUE ON THIS BOOKING (AGL-2481) — into OUR GA4 property.\n //\n // ## Why it is inside the idempotency gate rather than beside it\n //\n // This sits AFTER `if (!confirmedNow) return` and that placement is the\n // whole guard. Stripe redelivers `checkout.session.completed` for up to\n // three days after any 500, and this endpoint 500s on purpose; a\n // redelivery re-enters this handler, the transaction above sees a\n // `confirmed` status (or a refund counter, or a recorded PaymentIntent)\n // and answers false, and everything below — the contact, the email, and\n // now this — is skipped. A `purchase` fired before that gate, or beside\n // it, would inflate our own reported revenue by the redelivery rate.\n //\n // `transaction_id` is the checkout session id, which is the same key\n // the guard turns on, so GA4's own de-duplication is a second\n // independent line of defence: even if the Firestore guard were ever\n // bypassed, GA would collapse the repeats.\n //\n // ## Platform NET, and the fee is the measured one\n //\n // `value` is our fee and not the $95 the guest paid — the AGL-1639\n // settlement. This is our property, the subscription and marketplace\n // `purchase` events in it already mean \"what Aglyn was paid\", and a\n // gross booking figure sitting beside them would make every combined\n // total, ARPA and revenue audience wrong. The merchant's own gross goes\n // to the MERCHANT's property, client-side, and the two never meet.\n //\n // The figure comes off the session's `metadata.feeCents` — the fee\n // Stripe actually charged as `application_fee_amount` — never from the\n // plan's rate re-applied here. See `bookingPlatformNetCents`.\n //\n // ## Scheduling and failure posture\n //\n // `after()`, never a bare `void` (AGL-2327/AGL-2346): this runs inside\n // the console's `/api/billing/webhook` invocation, which is frozen the\n // moment the response is sent, so fire-and-forget work scheduled any\n // other way simply does not run — the exact way marketplace revenue\n // reported to nothing. And `.catch()`, because a throw here would\n // un-claim the Stripe event and turn a missed analytics hit into a\n // repeated billing side effect.\n if (shouldSendBookingPlatformPurchase(object)) {\n const netCents = bookingPlatformNetCents(object)\n after(() =>\n sendGa4Purchase({\n transactionId: String(object?.id ?? ''),\n value: netCents / 100,\n currency: String(object?.currency ?? 'usd'),\n items: [\n {\n // Ids only, no merchant free text. A service name is\n // merchant-authored and one edit away from carrying a\n // person's name into a dimension in OUR property; the id\n // already identifies it. The merchant's own property gets\n // the name, because there it is their own content.\n item_id: String(booking['serviceId'] ?? bookingId),\n item_name: String(booking['serviceId'] ?? bookingId),\n item_category: 'booking',\n // GA expects the items to sum to `value`; one item, one\n // price, and that price is our fee — not the service's.\n price: netCents / 100,\n quantity: 1,\n },\n ],\n // Booking sessions carry no `ga_client_id` today — nothing\n // captures one on a tenant site — so this is read for the day\n // one is stamped and the seed below is what actually resolves.\n clientId: object?.metadata?.ga_client_id,\n // ONE PAYING GUEST, ONE SYNTHETIC USER. Seeded from Stripe's\n // customer where there is one, and otherwise from the guest's\n // email, which `server.ts` passes as `customer_email` and Stripe\n // echoes on `customer_details`. The seed is hashed inside\n // `synthesizeClientId` and never transmitted.\n //\n // The booking id is the LAST resort deliberately: it is unique\n // per appointment, so seeding from it would turn a regular\n // client into a crowd of one-purchase strangers and make ARPA\n // nonsense — precisely what that helper's determinism exists to\n // prevent. Without any seed at all `sendGa4Purchase` returns\n // `no-client-id` and the event is silently never sent, which is\n // the void this whole change exists to close.\n stripeCustomerId:\n String(object?.customer ?? '') ||\n String(object?.customer_details?.email ?? '') ||\n String(bookingId),\n }).catch(() => undefined),\n )\n }\n // Contacts ingestion (AGL-1755). `server.ts` captures the contact at\n // REQUEST time, which is the right place — the booking is written\n // `pendingPayment` and at that moment no money has moved, so passing an\n // amount there would be a lie. But payment completes HERE, and this\n // handler never returned to the contact, so a paid booking's money\n // reached the booking document and nothing else. The same structural\n // shape as AGL-1748's draft branch: the completion handler does\n // everything except the contact.\n //\n // `source` stays `'booking'` — the same source the request-time capture\n // used — so the `sources` map still says where this person came from\n // and no schema change is needed to keep service revenue\n // distinguishable from product revenue. The second interaction is\n // deliberate rather than a duplicate: \"Booked X\" and \"Paid for X\" are\n // two real events, and `mergeContactInteraction` does not dedupe on\n // `refId`.\n //\n // The amount is `amount_total`, the money that moved, per AGL-1698 and\n // AGL-1711 — the booking document stores no price to re-derive it from.\n if (booking['email']) {\n void recordCapturedContact({\n orgId: '',\n hostId: String(hostId),\n identity: {\n email: booking['email'],\n ...(booking['name'] ? { name: String(booking['name']) } : {}),\n },\n // Paid, so a relationship (AGL-3232): the lead the request-time\n // capture filed for the address is closed onto the contact.\n surface: 'relationship',\n // The phone the booking form asked for (AGL-3493), onto the\n // contact only where it holds none — as the request-time\n // capture put it on the lead.\n ...(readBookingPhone(booking['phone'])\n ? { profileFill: { phone: readBookingPhone(booking['phone']) } }\n : {}),\n // Paid, so a customer (AGL-2612) — the request-time capture\n // said `lead`, and this is the door that has seen the money.\n lifecycleFloor: 'customer',\n // The SERVICE, not the charge (AGL-2028). `amount_total` now\n // includes the merchant's service tax where they set one, and\n // tax is collected for an authority rather than earned — booking\n // it as lifetime value would over-state what every service\n // client is worth. Identical to `paidAmountCents` on the default\n // store, which sets no rate.\n ...(serviceCents > 0 ? { purchaseCents: serviceCents } : {}),\n interaction: {\n source: 'booking',\n refId: String(bookingId),\n summary: `Paid for \"${String(\n booking['serviceName'] ?? 'a service',\n ).slice(0, 60)}\" ($${(serviceCents / 100).toFixed(2)})`,\n },\n })\n }\n // In the booking's own zone, and named (AGL-3432): a formatter with\n // no zone reads in the server's — UTC — and tells a paying guest the\n // wrong hour, and an empty zone prints \"()\".\n const timezone = await bookingTimeZoneFor(\n firestore,\n String(hostId),\n booking,\n )\n const when = formatBookingWhen(Number(booking['startsAtMs']), timezone)\n const paid = `$${(paidAmountCents / 100).toFixed(2)}`\n // The site's managers hear of a PAID booking too (AGL-3500): the\n // free path tells them when the request lands, and a paid one is\n // only a booking once this event has cleared the charge, so this is\n // its moment. Who, what, when, what was paid, and the phone and\n // address the service asked for.\n const contactLines = bookingContactLines(booking)\n void notifyHostManagers(String(hostId), {\n type: 'content.booking',\n title: 'New booking on {site}',\n body:\n `${String(booking['name'] ?? '') || 'A guest'}` +\n (booking['email'] ? ` (${String(booking['email'])})` : '') +\n ` booked ${String(booking['serviceName'] ?? '') || 'a service'} ` +\n `on {site} for ${when} (${timezone}). ${paid} was paid.` +\n (contactLines.length ? ` ${contactLines.join('. ')}.` : ''),\n link: `/${hostId}/bookings`,\n })\n // Confirmation email now that payment cleared (env-gated inside\n // sendEmail, which no-ops when Resend isn't configured).\n if (booking['email']) {\n const fallbackText =\n `Hi ${booking['name'] ?? ''},\\n\\nPayment received — ` +\n `\"${booking['serviceName'] ?? 'your booking'}\" is ` +\n `confirmed for ${when} (${timezone}). You paid ${paid}.` +\n `\\n\\nReference: ${bookingId}`\n // Site-owner-designed template when published (AGL-770); null keeps\n // the built-in copy.\n const designed = await renderHostEmailWithTokens(\n firebaseAdmin.app().firestore(),\n String(hostId),\n 'booking-confirmed',\n {\n name: String(booking['name'] ?? ''),\n 'service.name': String(booking['serviceName'] ?? ''),\n when,\n timezone,\n 'booking.payment': `You paid ${paid}.`,\n 'booking.ref': String(bookingId),\n },\n )\n // White-label sender identity (White-Label Phase 3), matching the\n // free-booking path — the store's brand via the one shared resolver.\n const branding = resolveBrandingProfile(\n (await getOrgForHost(String(hostId)).catch(() => null))?.org as never,\n )\n await sendEmail({\n to: String(booking['email']),\n subject:\n designed?.subject ??\n `Booking confirmed: ${booking['serviceName'] ?? ''}`,\n text: designed?.text || fallbackText,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(String(hostId)),\n audience: 'tenant',\n context: 'paid booking confirmation',\n // Owed to the recipient by their own booking: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'booking',\n })\n // Cost meter (AGL-1438), matching the free-booking path.\n // Transactional: the guest has already paid.\n await meterHostEmail(String(hostId))\n }\n }\n }\n}\n"],"names":["after","resolveBrandingProfile","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","notifyHostManagers","notifyRiskEvent","renderHostEmailWithTokens","sendGa4Purchase","paymentRiskEventFrom","recordPaymentRiskOnRecord","settlePaymentRiskDisputeOnRecord","reverseDestinationTransfer","recordCapturedContact","bookingPlatformNetCents","shouldSendBookingPlatformPurchase","sendEmail","pluginTaxProfile","fileBookingOnCrm","stageBookingEvent","bookingTimeZoneFor","formatBookingWhen","bookingContactLines","readBookingPhone","GRPC_FAILED_PRECONDITION","findBookingForPayment","paymentIntentId","matches","app","firestore","collectionGroup","where","limit","get","catch","error","code","console","docs","length","reverseBookingSellerShare","bookingRef","dispute","disputeId","String","id","amountCents","Math","max","round","Number","amount","cents","settled","prior","failedReason","outcome","kind","chargeId","charge","metadata","bookingId","record","reversedTransferCents","reversalId","transferReversalId","atMs","Date","now","reason","owedCents","wrote","runTransaction","transaction","fresh","exists","current","set","disputeReversal","merge","bookingsBillingWebhookHandler","type","object","risk","booking","hostId","ref","parent","signal","subjectLabel","link","notificationType","isFinite","toFixed","evidenceDueByMs","evidence_details","due_by","notifyRisk","claimed","payment_intent","status","recovered","recoveredText","guest","trim","service","title","body","undefined","payment_status","collection","doc","paidAmountCents","amount_total","taxCents","serviceCents","chargedFeeCents","feeCents","confirmedNow","snapshot","data","taxMode","taxModeOf","checkoutSessionId","expiresAtMs","FieldValue","delete","confirmedAt","serverTimestamp","nowMs","event","netCents","transactionId","value","currency","items","item_id","item_name","item_category","price","quantity","clientId","ga_client_id","stripeCustomerId","customer","customer_details","email","orgId","identity","name","surface","profileFill","phone","lifecycleFloor","purchaseCents","interaction","source","refId","summary","slice","timezone","when","paid","contactLines","join","fallbackText","designed","branding","org","to","subject","text","html","fromName","sendingIdentity","audience","context","owedFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,8EAA8E;AAC9E,4EAA4E;AAC5E,oDAAoD;AACpD,SAASA,KAAK,QAAQ,cAAa;AAGnC,SAASC,sBAAsB,QAAQ,sBAAqB;AAC5D,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,kBAAkB,EAClBC,eAAe,EACfC,yBAAyB,EACzBC,eAAe,QACV,2BAA0B;AACjC,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SACEC,yBAAyB,EACzBC,gCAAgC,QAC3B,sDAAqD;AAC5D,SACEC,0BAA0B,QAErB,2DAA0D;AACjE,OAAOC,2BAA2B,sDAAqD;AACvF,SACEC,uBAAuB,EACvBC,iCAAiC,QAC5B,yCAAqC;AAC5C,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,gBAAgB,QAAQ,iDAAgD;AACjF,SAASC,gBAAgB,QAAQ,mBAAe;AAChD,SAASC,iBAAiB,QAAQ,sBAAkB;AACpD,SAASC,kBAAkB,QAAQ,yBAAqB;AACxD,SAASC,iBAAiB,QAAQ,2BAAuB;AACzD,SACEC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAiC;AAExC;;;;CAIC,GACD,iFAAiF,GACjF,MAAMC,2BAA2B;AAEjC;;;;;;CAMC,GACD,eAAeC,sBACbC,eAAuB;IAEvB,IAAI,CAACA,iBAAiB,OAAO;IAC7B,MAAMC,UAAU,MAAM1B,cACnB2B,GAAG,GACHC,SAAS,GACTC,eAAe,CAAC,YAChBC,KAAK,CAAC,mBAAmB,MAAML,iBAC/BM,KAAK,CAAC,GACNC,GAAG,GACHC,KAAK,CAAC,CAACC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AOyC,SAASnD,KAAK,CAAC,IAAM,0BAAjD,AAAC,MAAwDsI,GAAG;gBAE9D,MAAMxJ,UAAU;oBACdyJ,IAAI7H,OAAOwC,OAAO,CAAC,QAAQ;oBAC3BsF,OAAO,YACLJ,4BAAAA,SAAUI,OAAO,qBACjB,CAAC,mBAAmB,GAAEtF,wBAAAA,OAAO,CAAC,cAAc,YAAtBA,wBAA0B,IAAI;oBACtDuF,MAAML,CAAAA,4BAAAA,SAAUK,IAAI,KAAIN;mBACpBC,CAAAA,4BAAAA,SAAUM,IAAI,IAAG;oBAAEA,MAAMN,SAASM,IAAI;gBAAC,IAAI,CAAC;oBAChDC,UAAUN,SAASM,QAAQ;oBAC3BC,iBAAiB,MAAM3K,oBAAoByC,OAAOyC;oBAClD0F,UAAU;oBACVC,SAAS;oBACT,2DAA2D;oBAC3D,gDAAgD;oBAChDC,SAAS;;gBAEX,yDAAyD;gBACzD,6CAA6C;gBAC7C,MAAM7K,eAAewC,OAAOyC;YAC9B;QACF;IACF;AACJ,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/billing-webhook.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\n// `after()`, never a bare `void promise` (AGL-2327). This handler runs inside\n// the console's `/api/billing/webhook` invocation, which AGL-1133 measured on\n// production is frozen the moment the response is sent — so fire-and-forget\n// work scheduled any other way simply does not run.\nimport { after } from 'next/server'\n\nimport type { BillingWebhookHandler } from '@aglyn/aglyn/server'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n notifyHostManagers,\n notifyRiskEvent,\n renderHostEmailWithTokens,\n sendGa4Purchase,\n} from '@aglyn/tenant-data-admin'\nimport { paymentRiskEventFrom } from '@aglyn/aglyn/app-utils/payment-risk'\nimport {\n recordPaymentRiskOnRecord,\n settlePaymentRiskDisputeOnRecord,\n} from '@aglyn/tenant-data-admin/server/payment-risk-record'\nimport {\n reverseDestinationTransfer,\n type TransferReversalFailure,\n} from '@aglyn/tenant-data-admin/server/stripe-transfer-reversal'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport {\n bookingPlatformNetCents,\n shouldSendBookingPlatformPurchase,\n} from '../model/booking-purchase-analytics'\nimport { sendEmail } from '@aglyn/shared-util-email'\nimport { pluginTaxProfile } from '@aglyn/aglyn/plugin-manager/plugin-tax-profile'\nimport { fileBookingOnCrm } from './booking-crm'\nimport { stageBookingEvent } from './booking-events'\nimport { bookingTimeZoneFor } from './booking-time-zone'\nimport { formatBookingWhen } from '../model/booking-time'\nimport {\n bookingContactLines,\n readBookingPhone,\n} from '../model/booking-contact-fields'\n\n/**\n * Paid-booking section of the platform Stripe webhook (AGL-170/418):\n * payment confirms the pendingPayment hold — relocated verbatim from the\n * console route; registered via registerBookingsConsoleApi.\n */\n/** gRPC `Status.FAILED_PRECONDITION` — Firestore's \"this query needs an index\". */\nconst GRPC_FAILED_PRECONDITION = 9\n\n/**\n * The booking a charge paid for, found by the `paymentIntentId` the paid\n * handler below records (AGL-2315), or null. A missing collection-group\n * index is logged and answered null rather than thrown: no redelivery can\n * fix it, and the dispute then reaches staff through the route's\n * unattributed-dispute alert instead of vanishing.\n */\nasync function findBookingForPayment(\n paymentIntentId: string,\n): Promise<FirebaseFirestore.QueryDocumentSnapshot | null> {\n if (!paymentIntentId) return null\n const matches = await firebaseAdmin\n .app()\n .firestore()\n .collectionGroup('bookings')\n .where('paymentIntentId', '==', paymentIntentId)\n .limit(2)\n .get()\n .catch((error: { code?: number }) => {\n if (error?.code !== GRPC_FAILED_PRECONDITION) throw error\n console.error(\n 'Booking payment lookup needs the collection-group index on ' +\n 'bookings.paymentIntentId (AGL-3360)',\n error,\n )\n return null\n })\n // One payment intent pays one booking; two is corrupt data, and stamping\n // an arbitrary one would tell the wrong merchant.\n return matches && matches.docs.length === 1 ? matches.docs[0] : null\n}\n\n/** What a booking records once its lost dispute's reversal is settled. */\ninterface BookingDisputeReversal {\n disputeId: string\n reversedTransferCents: number\n transferReversalId?: string\n /** Why nothing was pulled back, when nothing was. */\n failedReason?: TransferReversalFailure\n owedCents?: number\n atMs: number\n}\n\n/**\n * The merchant's share of a LOST booking dispute, pulled back from the\n * connected account (AGL-3363), by the AGL-1794 policy a store order follows:\n * the Stripe half is the shared `reverseDestinationTransfer`, this is only\n * the booking's own record.\n *\n * IDEMPOTENT BY THE BOOKING: `disputeReversal` for this dispute, present,\n * means settled and a redelivery returns before any Stripe call. A delivery\n * that died after the POST is healed by the seam adopting the reversal the\n * transfer already carries. A transient Stripe failure THROWS (the seam\n * does), leaving the marker unset so Stripe's redelivery retries it. A final\n * failure is settled with its reason and the owed amount, so it is findable.\n *\n * `cents` is non-zero only for the delivery that wrote the reversal, which\n * is the one that tells the merchant.\n */\nasync function reverseBookingSellerShare(\n bookingRef: FirebaseFirestore.DocumentReference,\n dispute: any,\n): Promise<{ cents: number; settled: 'reversed' | 'failed' | 'pending' }> {\n const disputeId = String(dispute?.id ?? '')\n const amountCents = Math.max(0, Math.round(Number(dispute?.amount ?? 0)))\n if (!disputeId || !(amountCents > 0)) return { cents: 0, settled: 'failed' }\n const firestore = firebaseAdmin.app().firestore()\n const prior = (await bookingRef.get()).get('disputeReversal') as\n | BookingDisputeReversal\n | undefined\n if (prior?.disputeId === disputeId) {\n return { cents: 0, settled: prior.failedReason ? 'failed' : 'reversed' }\n }\n const outcome = await reverseDestinationTransfer({\n kind: 'dispute',\n id: disputeId,\n amountCents,\n chargeId:\n typeof dispute?.charge === 'string' ? dispute.charge : String(dispute?.charge?.id ?? ''),\n metadata: { bookingId: bookingRef.id },\n })\n if (outcome.kind === 'skipped') {\n console.error('Booking transfer reversal skipped: STRIPE_SECRET_KEY is not set (AGL-3363)')\n return { cents: 0, settled: 'pending' }\n }\n const record: BookingDisputeReversal =\n outcome.kind === 'reversed'\n ? {\n disputeId,\n reversedTransferCents: outcome.cents,\n ...(outcome.reversalId ? { transferReversalId: outcome.reversalId } : {}),\n atMs: Date.now(),\n }\n : {\n disputeId,\n reversedTransferCents: 0,\n failedReason: outcome.reason,\n ...(outcome.owedCents != null ? { owedCents: outcome.owedCents } : {}),\n atMs: Date.now(),\n }\n if (outcome.kind === 'not-reversed') {\n console.error('Booking seller share NOT reversed — recorded on the booking', {\n bookingId: bookingRef.id,\n disputeId,\n reason: outcome.reason,\n })\n }\n const wrote = await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n if (!fresh.exists) return false\n const current = fresh.get('disputeReversal') as BookingDisputeReversal | undefined\n if (current?.disputeId === disputeId) return false\n transaction.set(bookingRef, { disputeReversal: record }, { merge: true })\n return true\n })\n return {\n cents: wrote && outcome.kind === 'reversed' ? outcome.cents : 0,\n settled: outcome.kind === 'reversed' ? 'reversed' : 'failed',\n }\n}\n\nexport const bookingsBillingWebhookHandler: BillingWebhookHandler = async ({\n type,\n object,\n event,\n}) => {\n // The seller's account when this event is about a DIRECT charge: Stripe\n // delivers those through the Connect endpoint with the account on the\n // event itself. Empty for the platform's own (destination) charges.\n const eventAccount =\n typeof event?.account === 'string' ? event.account.trim() : ''\n // Fraud signals on a paid booking (AGL-3360): an issuer's early fraud\n // warning, a Radar review, or a dispute. Booking deposits never heard\n // about any of them, so the merchant learned of a chargeback from Stripe\n // alone. The signal now lands on the BOOKING, through the shared\n // `paymentRisk` shape every plugin stamps, and the site's managers are\n // told once. Nothing is refunded or canceled: the merchant decides.\n const risk = paymentRiskEventFrom(type, object)\n if (risk) {\n const booking = await findBookingForPayment(risk.paymentIntentId)\n if (!booking) return\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n await recordPaymentRiskOnRecord(\n {\n ref: booking.ref,\n signal: risk.signal,\n hostId,\n subjectLabel: `the booking for ${String(booking.get('serviceName') ?? booking.id)}`,\n link: `/${hostId}/bookings`,\n notificationType: 'content.booking',\n amount: Number.isFinite(Number(booking.get('paidAmountCents')))\n ? `$${(Number(booking.get('paidAmountCents')) / 100).toFixed(2)}`\n : null,\n evidenceDueByMs:\n Number((object as { evidence_details?: { due_by?: unknown } })?.evidence_details?.due_by ?? 0) * 1000 || null,\n },\n { firestore: firebaseAdmin.app().firestore(), notifyRisk: notifyRiskEvent },\n )\n return { claimed: true, hostId }\n }\n // A dispute's outcome, on the signal `created` stamped. A LOST one pulls\n // the merchant's share back from the connected account (AGL-3363), through\n // the same seam a lost store order uses, so the platform no longer absorbs\n // a booking chargeback. Claimed when the share came back; a reversal that\n // could not be made stays unclaimed, so the route's unattributed-dispute\n // alert still tells staff about money nothing recovered.\n if (type === 'charge.dispute.closed') {\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const booking = await findBookingForPayment(paymentIntentId)\n if (!booking) return\n const outcome = String(object?.status ?? '')\n await settlePaymentRiskDisputeOnRecord(\n booking.ref,\n String(object?.id ?? ''),\n outcome,\n { firestore: firebaseAdmin.app().firestore() },\n )\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n if (outcome !== 'lost') return { claimed: true, hostId }\n // A DIRECT charge's dispute is debited from the seller's own account by\n // Stripe, and there was never a transfer for the platform to pull back,\n // so a lost one is settled as recorded above and claimed.\n if (eventAccount || booking.get('chargeModel') === 'direct') {\n return { claimed: true, hostId }\n }\n const recovered = await reverseBookingSellerShare(booking.ref, object)\n if (recovered.cents > 0 && hostId) {\n const recoveredText = `$${(recovered.cents / 100).toFixed(2)}`\n const guest = String(booking.get('name') ?? '').trim()\n const service = String(booking.get('serviceName') ?? '').trim() || 'a service'\n await notifyHostManagers(hostId, {\n type: 'content.booking',\n title: `Payout adjusted — ${recoveredText} recovered for a lost chargeback`,\n body:\n `${guest ? `${guest}'s payment` : 'A payment'} for ${service} on ` +\n `{site} was charged back and the dispute was lost, so ` +\n `the ${recoveredText} transferred to you for it has been taken back. ` +\n `If your balance does not cover it, Stripe recovers the rest from ` +\n `your future payouts.`,\n link: `/${hostId}/bookings`,\n })\n }\n return recovered.settled === 'reversed' ? { claimed: true, hostId } : undefined\n }\n // Paid bookings (AGL-170): payment confirms the pendingPayment hold.\n if (\n type === 'checkout.session.completed' &&\n object?.metadata?.type === 'booking-payment' &&\n object?.payment_status === 'paid'\n ) {\n const { hostId, bookingId } = object.metadata ?? {}\n if (hostId && bookingId) {\n const firestore = firebaseAdmin.app().firestore()\n const bookingRef = firestore\n .collection('hosts')\n .doc(String(hostId))\n .collection('bookings')\n .doc(String(bookingId))\n // WHAT THE CLIENT HANDED OVER, ALL OF IT. Tax included: this is the\n // ceiling `refund.ts` reverses against, and the client paid the tax\n // too — a net figure here would strand part of a refund.\n const paidAmountCents = Math.max(\n 0,\n Math.round(Number(object?.amount_total ?? 0)),\n )\n // THE MERCHANT'S SERVICE TAX, SEPARATED OUT (AGL-2028).\n //\n // `server.ts` charges the merchant's own service rate as an ordinary\n // `line_items[1]` Stripe is never told is tax (the AGL-1711\n // construction, which is what keeps the figure the MERCHANT's rather\n // than something computed against Aglyn's registrations). So\n // `amount_total` is service-plus-tax while Stripe's own tax fields\n // read zero, and the session's metadata is the only witness — exactly\n // as it is for a buy-now sale.\n const taxCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.taxCents ?? 0)),\n )\n // The merchant's REVENUE, which is the charge less the tax. Used for\n // the contact's lifetime value below: tax is collected on behalf of\n // an authority and is not money the business earned, so counting it\n // would over-state every service client's worth.\n const serviceCents = Math.max(0, paidAmountCents - taxCents)\n // WHAT A REFUND WILL NEED (AGL-2315). A paid booking is now a\n // destination charge to the merchant's connected account, and\n // reversing one requires the PaymentIntent — which lives only on this\n // event. The booking document recorded `paidAmountCents` and nothing\n // that identifies the charge, so a refund had no handle to pull and\n // the information was gone the moment the webhook returned. Unlike\n // most gaps this one cannot be backfilled from our own data later:\n // every booking taken before this line landed can only be refunded by\n // hand in the Stripe dashboard.\n //\n // `feeCents` is Aglyn's cut as CHARGED, read back off the session's\n // own metadata rather than re-derived from the org at refund time. The\n // rate follows the plan (AGL-2289's rule) and the plan moves, so\n // re-resolving it during a refund would reverse a share that was never\n // taken. `'0'` is a real recorded answer on the 0%-rate tiers.\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const chargedFeeCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.feeCents ?? 0)),\n )\n // A DIRECT charge lives on the seller's account, which a refund has\n // to be sent to. The event names that account; `server.ts` stamped it\n // on the hold too, so an event without one leaves that stamp alone.\n const direct =\n object?.metadata?.chargeModel === 'direct' || Boolean(eventAccount)\n // Redelivery guard (AGL-1755), the AGL-1748 shape. This was an\n // unconditional merge-set with no status check at all — idempotent\n // only by accident, because every value it wrote was fixed. A\n // redelivery re-sent the guest's confirmation and re-metered it, and\n // the moment this handler carries money to a contact the accident stops\n // holding: `purchaseCents` is a `FieldValue.increment`, so every retry\n // would inflate the customer's lifetime value.\n //\n // Keyed on the STATUS, not on the document existing: `server.ts` writes\n // the booking as `pendingPayment` BEFORE it opens the Stripe session,\n // so existence is guaranteed by the time any event arrives and proves\n // nothing — the AGL-1748 reasoning, not AGL-1732's `checkoutSessionId`\n // key, which existed because a sibling event wrote the same path.\n //\n // The key is \"not yet confirmed\" rather than \"is pendingPayment\" on\n // purpose. The lapsed-hold sweeper in `server.ts` cancels a\n // `pendingPayment` booking after 24h, and refusing a payment that\n // landed anyway would take the money and record nothing; `confirmed` is\n // reachable for a PAID booking only by this handler having already run,\n // so it is an exact \"already processed\" test. The existence check is\n // new and deliberate: the old merge-set would CREATE a stub booking\n // from a metadata `bookingId` that pointed at nothing.\n let booking: Record<string, any> = {}\n const confirmedNow = await firestore.runTransaction(\n async (transaction) => {\n const snapshot = await transaction.get(bookingRef)\n if (!snapshot.exists) return false\n if (snapshot.get('status') === 'confirmed') return false\n // \"Already processed\" is WIDER than `confirmed` once money can\n // flow back out (AGL-2315). A refunded booking is moved off\n // `confirmed`, so a redelivery arriving afterwards would otherwise\n // read as unprocessed and re-confirm an appointment the merchant\n // has already cancelled and refunded — re-sending the guest a\n // confirmation for it and re-metering the email. Any evidence this\n // handler has run before is the real test, and a refund counter or\n // a recorded PaymentIntent is exactly that evidence.\n if (\n Number(snapshot.get('refundedCents') ?? 0) > 0 ||\n snapshot.get('paymentIntentId')\n ) {\n return false\n }\n booking = (snapshot.data() as any) ?? {}\n transaction.set(\n bookingRef,\n {\n status: 'confirmed',\n paidAmountCents,\n // WHICH TAX REGIME THIS BOOKING CARRIED (AGL-2028), on the\n // document the merchant reads — the stamp every other\n // storefront money door already carries (AGL-2451).\n //\n // DERIVED from the one shared derivation, never a constant.\n // A hand-written \"manual when the metadata says so\" would be\n // a second rule that can drift from the `storefrontTaxCollected`\n // row filed for the same Stripe id, which is the exact\n // disagreement AGL-2451 exists to prevent.\n //\n // TWO-ARGUMENT, because the manual line makes Stripe report\n // `total_details.amount_tax: 0` on a booking that really did\n // charge the client tax; the one-argument form would stamp\n // `none` on precisely those. `absent` remains a fourth state\n // meaning \"recorded before this shipped\".\n taxMode: pluginTaxProfile().taxModeOf(object, taxCents),\n // The figure itself. Absent rather than a defaulted `0` — a\n // zero written through `merge` is the AGL-1758 shape, and\n // this handler can re-enter (see the widened guard above).\n ...(taxCents > 0 ? { taxCents } : {}),\n // The refund handles (AGL-2315). Written inside the same\n // transaction as the status, so a booking can never read\n // `confirmed` while the means to refund it are missing.\n ...(paymentIntentId ? { paymentIntentId } : {}),\n feeCents: chargedFeeCents,\n ...(direct\n ? {\n chargeModel: 'direct',\n ...(eventAccount ? { stripeAccountId: eventAccount } : {}),\n }\n : {}),\n // WHICH CHECKOUT PAID FOR THIS (AGL-2481). The guest's browser\n // comes back from Stripe holding a session id and nothing\n // else — a booking id was never in the return URL — so this is\n // what lets `booking-analytics.ts` answer \"what did I just\n // buy?\" for the merchant-side `purchase`, and it is written\n // here because the session id first exists on this event.\n //\n // Inside the transaction with the status on purpose: the\n // lookup refuses anything that is not `confirmed`, so a\n // booking can never be findable by session id while reading as\n // unpaid.\n ...(object?.id ? { checkoutSessionId: String(object.id) } : {}),\n // NOTE the absent `refundedCents: 0`. Seeding it here would be\n // the AGL-1758 shape: a defaulted field written through\n // `merge` destroying the real one. This handler can re-enter\n // after a refund has already accumulated a counter (see the\n // widened guard above), and a zero written back over it would\n // re-open the full amount for refunding a second time. Absent\n // IS zero — every reader coerces with `?? 0`.\n expiresAtMs: firebaseAdmin.firestore.FieldValue.delete(),\n confirmedAt:\n firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n // The booking is confirmed now, in this transaction (AGL-3643).\n const nowMs = Date.now()\n stageBookingEvent(transaction, firestore, {\n event: 'booking.created',\n hostId: String(hostId),\n bookingId: String(bookingId),\n booking: {\n ...booking,\n status: 'confirmed',\n paidAmountCents,\n ...(taxCents > 0 ? { taxCents } : {}),\n expiresAtMs: null,\n },\n nowMs,\n })\n return true\n },\n )\n if (!confirmedNow) return\n // THE RECORD'S MEETING (AGL-2660). Payment is what confirms a paid\n // booking, so this is where it reaches the CRM: the meeting on the\n // record's timeline and, when the service asks, the follow-up task.\n // Inside the idempotency gate for the same reason the GA4 purchase\n // below is — a redelivery must not file a second meeting — and\n // through `after()` for the same reason too: this invocation is\n // frozen the moment the response is sent (AGL-2327). Never thrown:\n // the writer swallows its own failures, and the catch is for the\n // scheduling itself.\n after(() =>\n fileBookingOnCrm(firestore, {\n hostId: String(hostId),\n bookingId: String(bookingId),\n booking,\n }).catch(() => undefined),\n )\n // AGLYN'S REVENUE ON THIS BOOKING (AGL-2481) — into OUR GA4 property.\n //\n // ## Why it is inside the idempotency gate rather than beside it\n //\n // This sits AFTER `if (!confirmedNow) return` and that placement is the\n // whole guard. Stripe redelivers `checkout.session.completed` for up to\n // three days after any 500, and this endpoint 500s on purpose; a\n // redelivery re-enters this handler, the transaction above sees a\n // `confirmed` status (or a refund counter, or a recorded PaymentIntent)\n // and answers false, and everything below — the contact, the email, and\n // now this — is skipped. A `purchase` fired before that gate, or beside\n // it, would inflate our own reported revenue by the redelivery rate.\n //\n // `transaction_id` is the checkout session id, which is the same key\n // the guard turns on, so GA4's own de-duplication is a second\n // independent line of defence: even if the Firestore guard were ever\n // bypassed, GA would collapse the repeats.\n //\n // ## Platform NET, and the fee is the measured one\n //\n // `value` is our fee and not the $95 the guest paid — the AGL-1639\n // settlement. This is our property, the subscription and marketplace\n // `purchase` events in it already mean \"what Aglyn was paid\", and a\n // gross booking figure sitting beside them would make every combined\n // total, ARPA and revenue audience wrong. The merchant's own gross goes\n // to the MERCHANT's property, client-side, and the two never meet.\n //\n // The figure comes off the session's `metadata.feeCents` — the fee\n // Stripe actually charged as `application_fee_amount` — never from the\n // plan's rate re-applied here. See `bookingPlatformNetCents`.\n //\n // ## Scheduling and failure posture\n //\n // `after()`, never a bare `void` (AGL-2327/AGL-2346): this runs inside\n // the console's `/api/billing/webhook` invocation, which is frozen the\n // moment the response is sent, so fire-and-forget work scheduled any\n // other way simply does not run — the exact way marketplace revenue\n // reported to nothing. And `.catch()`, because a throw here would\n // un-claim the Stripe event and turn a missed analytics hit into a\n // repeated billing side effect.\n if (shouldSendBookingPlatformPurchase(object)) {\n const netCents = bookingPlatformNetCents(object)\n after(() =>\n sendGa4Purchase({\n transactionId: String(object?.id ?? ''),\n value: netCents / 100,\n currency: String(object?.currency ?? 'usd'),\n items: [\n {\n // Ids only, no merchant free text. A service name is\n // merchant-authored and one edit away from carrying a\n // person's name into a dimension in OUR property; the id\n // already identifies it. The merchant's own property gets\n // the name, because there it is their own content.\n item_id: String(booking['serviceId'] ?? bookingId),\n item_name: String(booking['serviceId'] ?? bookingId),\n item_category: 'booking',\n // GA expects the items to sum to `value`; one item, one\n // price, and that price is our fee — not the service's.\n price: netCents / 100,\n quantity: 1,\n },\n ],\n // Booking sessions carry no `ga_client_id` today — nothing\n // captures one on a tenant site — so this is read for the day\n // one is stamped and the seed below is what actually resolves.\n clientId: object?.metadata?.ga_client_id,\n // ONE PAYING GUEST, ONE SYNTHETIC USER. Seeded from Stripe's\n // customer where there is one, and otherwise from the guest's\n // email, which `server.ts` passes as `customer_email` and Stripe\n // echoes on `customer_details`. The seed is hashed inside\n // `synthesizeClientId` and never transmitted.\n //\n // The booking id is the LAST resort deliberately: it is unique\n // per appointment, so seeding from it would turn a regular\n // client into a crowd of one-purchase strangers and make ARPA\n // nonsense — precisely what that helper's determinism exists to\n // prevent. Without any seed at all `sendGa4Purchase` returns\n // `no-client-id` and the event is silently never sent, which is\n // the void this whole change exists to close.\n stripeCustomerId:\n String(object?.customer ?? '') ||\n String(object?.customer_details?.email ?? '') ||\n String(bookingId),\n }).catch(() => undefined),\n )\n }\n // Contacts ingestion (AGL-1755). `server.ts` captures the contact at\n // REQUEST time, which is the right place — the booking is written\n // `pendingPayment` and at that moment no money has moved, so passing an\n // amount there would be a lie. But payment completes HERE, and this\n // handler never returned to the contact, so a paid booking's money\n // reached the booking document and nothing else. The same structural\n // shape as AGL-1748's draft branch: the completion handler does\n // everything except the contact.\n //\n // `source` stays `'booking'` — the same source the request-time capture\n // used — so the `sources` map still says where this person came from\n // and no schema change is needed to keep service revenue\n // distinguishable from product revenue. The second interaction is\n // deliberate rather than a duplicate: \"Booked X\" and \"Paid for X\" are\n // two real events, and `mergeContactInteraction` does not dedupe on\n // `refId`.\n //\n // The amount is `amount_total`, the money that moved, per AGL-1698 and\n // AGL-1711 — the booking document stores no price to re-derive it from.\n if (booking['email']) {\n void recordCapturedContact({\n orgId: '',\n hostId: String(hostId),\n identity: {\n email: booking['email'],\n ...(booking['name'] ? { name: String(booking['name']) } : {}),\n },\n // Paid, so a relationship (AGL-3232): the lead the request-time\n // capture filed for the address is closed onto the contact.\n surface: 'relationship',\n // The phone the booking form asked for (AGL-3493), onto the\n // contact only where it holds none — as the request-time\n // capture put it on the lead.\n ...(readBookingPhone(booking['phone'])\n ? { profileFill: { phone: readBookingPhone(booking['phone']) } }\n : {}),\n // Paid, so a customer (AGL-2612) — the request-time capture\n // said `lead`, and this is the door that has seen the money.\n lifecycleFloor: 'customer',\n // The SERVICE, not the charge (AGL-2028). `amount_total` now\n // includes the merchant's service tax where they set one, and\n // tax is collected for an authority rather than earned — booking\n // it as lifetime value would over-state what every service\n // client is worth. Identical to `paidAmountCents` on the default\n // store, which sets no rate.\n ...(serviceCents > 0 ? { purchaseCents: serviceCents } : {}),\n interaction: {\n source: 'booking',\n refId: String(bookingId),\n summary: `Paid for \"${String(\n booking['serviceName'] ?? 'a service',\n ).slice(0, 60)}\" ($${(serviceCents / 100).toFixed(2)})`,\n },\n })\n }\n // In the booking's own zone, and named (AGL-3432): a formatter with\n // no zone reads in the server's — UTC — and tells a paying guest the\n // wrong hour, and an empty zone prints \"()\".\n const timezone = await bookingTimeZoneFor(\n firestore,\n String(hostId),\n booking,\n )\n const when = formatBookingWhen(Number(booking['startsAtMs']), timezone)\n const paid = `$${(paidAmountCents / 100).toFixed(2)}`\n // The site's managers hear of a PAID booking too (AGL-3500): the\n // free path tells them when the request lands, and a paid one is\n // only a booking once this event has cleared the charge, so this is\n // its moment. Who, what, when, what was paid, and the phone and\n // address the service asked for.\n const contactLines = bookingContactLines(booking)\n void notifyHostManagers(String(hostId), {\n type: 'content.booking',\n title: 'New booking on {site}',\n body:\n `${String(booking['name'] ?? '') || 'A guest'}` +\n (booking['email'] ? ` (${String(booking['email'])})` : '') +\n ` booked ${String(booking['serviceName'] ?? '') || 'a service'} ` +\n `on {site} for ${when} (${timezone}). ${paid} was paid.` +\n (contactLines.length ? ` ${contactLines.join('. ')}.` : ''),\n link: `/${hostId}/bookings`,\n })\n // Confirmation email now that payment cleared (env-gated inside\n // sendEmail, which no-ops when Resend isn't configured).\n if (booking['email']) {\n const fallbackText =\n `Hi ${booking['name'] ?? ''},\\n\\nPayment received — ` +\n `\"${booking['serviceName'] ?? 'your booking'}\" is ` +\n `confirmed for ${when} (${timezone}). You paid ${paid}.` +\n `\\n\\nReference: ${bookingId}`\n // Site-owner-designed template when published (AGL-770); null keeps\n // the built-in copy.\n const designed = await renderHostEmailWithTokens(\n firebaseAdmin.app().firestore(),\n String(hostId),\n 'booking-confirmed',\n {\n name: String(booking['name'] ?? ''),\n 'service.name': String(booking['serviceName'] ?? ''),\n when,\n timezone,\n 'booking.payment': `You paid ${paid}.`,\n 'booking.ref': String(bookingId),\n },\n )\n // White-label sender identity (White-Label Phase 3), matching the\n // free-booking path — the store's brand via the one shared resolver.\n const branding = resolveBrandingProfile(\n (await getOrgForHost(String(hostId)).catch(() => null))?.org as never,\n )\n await sendEmail({\n to: String(booking['email']),\n subject:\n designed?.subject ??\n `Booking confirmed: ${booking['serviceName'] ?? ''}`,\n text: designed?.text || fallbackText,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(String(hostId)),\n audience: 'tenant',\n context: 'paid booking confirmation',\n // Owed to the recipient by their own booking: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'booking',\n })\n // Cost meter (AGL-1438), matching the free-booking path.\n // Transactional: the guest has already paid.\n await meterHostEmail(String(hostId))\n }\n }\n }\n}\n"],"names":["after","resolveBrandingProfile","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","notifyHostManagers","notifyRiskEvent","renderHostEmailWithTokens","sendGa4Purchase","paymentRiskEventFrom","recordPaymentRiskOnRecord","settlePaymentRiskDisputeOnRecord","reverseDestinationTransfer","recordCapturedContact","bookingPlatformNetCents","shouldSendBookingPlatformPurchase","sendEmail","pluginTaxProfile","fileBookingOnCrm","stageBookingEvent","bookingTimeZoneFor","formatBookingWhen","bookingContactLines","readBookingPhone","GRPC_FAILED_PRECONDITION","findBookingForPayment","paymentIntentId","matches","app","firestore","collectionGroup","where","limit","get","catch","error","code","console","docs","length","reverseBookingSellerShare","bookingRef","dispute","disputeId","String","id","amountCents","Math","max","round","Number","amount","cents","settled","prior","failedReason","outcome","kind","chargeId","charge","metadata","bookingId","record","reversedTransferCents","reversalId","transferReversalId","atMs","Date","now","reason","owedCents","wrote","runTransaction","transaction","fresh","exists","current","set","disputeReversal","merge","bookingsBillingWebhookHandler","type","object","event","eventAccount","account","trim","risk","booking","hostId","ref","parent","signal","subjectLabel","link","notificationType","isFinite","toFixed","evidenceDueByMs","evidence_details","due_by","notifyRisk","claimed","payment_intent","status","recovered","recoveredText","guest","service","title","body","undefined","payment_status","collection","doc","paidAmountCents","amount_total","taxCents","serviceCents","chargedFeeCents","feeCents","direct","chargeModel","Boolean","confirmedNow","snapshot","data","taxMode","taxModeOf","stripeAccountId","checkoutSessionId","expiresAtMs","FieldValue","delete","confirmedAt","serverTimestamp","nowMs","netCents","transactionId","value","currency","items","item_id","item_name","item_category","price","quantity","clientId","ga_client_id","stripeCustomerId","customer","customer_details","email","orgId","identity","name","surface","profileFill","phone","lifecycleFloor","purchaseCents","interaction","source","refId","summary","slice","timezone","when","paid","contactLines","join","fallbackText","designed","branding","org","to","subject","text","html","fromName","sendingIdentity","audience","context","owedFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,8EAA8E;AAC9E,4EAA4E;AAC5E,oDAAoD;AACpD,SAASA,KAAK,QAAQ,cAAa;AAGnC,SAASC,sBAAsB,QAAQ,sBAAqB;AAC5D,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,kBAAkB,EAClBC,eAAe,EACfC,yBAAyB,EACzBC,eAAe,QACV,2BAA0B;AACjC,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SACEC,yBAAyB,EACzBC,gCAAgC,QAC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C,OAAO6C,SAASvD,KAAK,CAAC,IAAM,0BAAjD,AAAC,MAAwD4I,GAAG;gBAE9D,MAAM9J,UAAU;oBACd+J,IAAInI,OAAO4C,OAAO,CAAC,QAAQ;oBAC3BwF,OAAO,YACLJ,4BAAAA,SAAUI,OAAO,qBACjB,CAAC,mBAAmB,GAAExF,wBAAAA,OAAO,CAAC,cAAc,YAAtBA,wBAA0B,IAAI;oBACtDyF,MAAML,CAAAA,4BAAAA,SAAUK,IAAI,KAAIN;mBACpBC,CAAAA,4BAAAA,SAAUM,IAAI,IAAG;oBAAEA,MAAMN,SAASM,IAAI;gBAAC,IAAI,CAAC;oBAChDC,UAAUN,SAASM,QAAQ;oBAC3BC,iBAAiB,MAAMjL,oBAAoByC,OAAO6C;oBAClD4F,UAAU;oBACVC,SAAS;oBACT,2DAA2D;oBAC3D,gDAAgD;oBAChDC,SAAS;;gBAEX,yDAAyD;gBACzD,6CAA6C;gBAC7C,MAAMnL,eAAewC,OAAO6C;YAC9B;QACF;IACF;AACJ,EAAC"}
|
|
@@ -254,7 +254,10 @@ async function start(staff, bookingId, body, req, res) {
|
|
|
254
254
|
// same rate a paid booking is charged online.
|
|
255
255
|
const tax = pluginTaxProfile().flatTax(await pluginTaxProfile().flatRate(staff.hostId, 'service'), serviceCents, 'Service tax');
|
|
256
256
|
const amountCents = serviceCents + tax.taxCents;
|
|
257
|
-
|
|
257
|
+
// A reader's card, priced at the in-person rate (AGL-4198).
|
|
258
|
+
const feeCents = resolveTransactionFeeCents(staff.org, 'service', serviceCents, amountCents, {
|
|
259
|
+
inPerson: true
|
|
260
|
+
});
|
|
258
261
|
// A pending intent for this booking that is not this attempt's: release it
|
|
259
262
|
// first, so one booking never has two cards in flight.
|
|
260
263
|
if ((existing == null ? void 0 : existing.status) === 'pending' && existing.paymentIntentId) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/in-person-payment.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 { createHash } from 'crypto'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { merchantAccountIsReady } from '@aglyn/tenant-data-admin/server/payment-provider'\nimport {\n checkEntitlement,\n resolveTransactionFeeCents,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { pluginTaxProfile } from '@aglyn/aglyn/plugin-manager/plugin-tax-profile'\nimport {\n bookingInPersonAmountProblem,\n bookingInPersonState,\n type BookingInPersonPayment,\n} from '../model/booking-in-person'\nimport { bookingsSitePermissionRefusal } from '../model/bookings-permissions'\nimport { holdsBookingsSiteKey } from './bookings-site-keys'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\n\n/*==========================================\n * `POST /api/bookings/in-person-payment` (AGL-3618).\n *\n * Takes payment for a booking at the counter, on the card reader the native\n * Aglyn POS app has connected (Tap to Pay or a Bluetooth reader). The server\n * owns the money; the app only presents the card:\n *\n * - `start` prices the charge (the amount staff typed, plus the merchant's\n * own service tax), and creates a card-present PaymentIntent: a\n * DESTINATION charge to the merchant, settled on Aglyn's platform account\n * with no `on_behalf_of` (ToS §10.7, AGL-3607), with the take and\n * Stripe's card cost as `application_fee_amount` — exactly the fee a paid\n * booking already carries online (`resolveTransactionFeeCents`, `service`).\n * Returns the intent's client secret for the app's Terminal SDK.\n * - `settle` re-reads the intent from Stripe (never trusting the app's word),\n * captures an authorized one, and records the booking paid with the same\n * fields an online payment writes, so the console's refund and the dispute\n * handling work on it unchanged.\n * - `cancel` releases an intent that was not collected.\n *\n * MANUAL capture, so a card that authorizes but whose booking was changed in\n * between is released rather than charged. On-reader tipping is not offered\n * here; the amount is the amount.\n *\n * Gate: a site `admin` or `editor`, and the owning org's `bookings` and\n * `pos` entitlements (taking card-present payments is a POS capability).\n *=========================================*/\n\nconst BOOKING_ID = /^[A-Za-z0-9_-]{1,128}$/\nconst PAYMENT_INTENT_ID = /^pi_[A-Za-z0-9_]{6,128}$/\n\ntype Res = Parameters<PluginApiHandler>[1]\n\ninterface Staff {\n uid: string\n hostId: string\n org: Record<string, any> | null\n}\n\nfunction requestBody(req: Parameters<PluginApiHandler>[0]): Record<string, any> {\n if (typeof req.body === 'string') {\n try {\n const parsed = JSON.parse(req.body)\n return parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n return {}\n }\n }\n return req.body && typeof req.body === 'object' ? req.body : {}\n}\n\n/** Card-present payments: always in test mode, in live mode once switched on. */\nexport function inPersonCardsAvailable(): boolean {\n const key = String(process.env.STRIPE_SECRET_KEY ?? '')\n if (!key) return false\n return (\n key.startsWith('sk_test_') ||\n String(process.env.STRIPE_TERMINAL_LIVE_ENABLED ?? '').toLowerCase() === 'true'\n )\n}\n\nasync function stripe(\n method: 'GET' | 'POST',\n path: string,\n options: { params?: Record<string, string | number | boolean | undefined>; idempotencyKey?: string } = {},\n): Promise<{ ok: boolean; status: number; body: any }> {\n const form = new URLSearchParams()\n for (const [key, value] of Object.entries(options.params ?? {})) {\n if (value !== undefined) form.append(key, String(value))\n }\n const query = method === 'GET' && form.toString() ? `?${form}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(options.idempotencyKey ? { 'Idempotency-Key': options.idempotencyKey } : {}),\n },\n ...(method === 'POST' ? { body: form.toString() } : {}),\n })\n const body = await response.json().catch(() => null)\n return { ok: response.ok, status: response.status, body }\n}\n\nfunction stripeMessage(body: any, fallback: string): string {\n const message = body?.error?.message\n return typeof message === 'string' && message ? message : fallback\n}\n\nasync function authorize(\n req: Parameters<PluginApiHandler>[0],\n hostId: string,\n): Promise<{ ok: true; staff: Staff } | { ok: false; status: number; error: string }> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ') ? authorization.slice(7) : ''\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n if (!hostId) return { ok: false, status: 400, error: 'Missing hostId' }\n let uid: string\n try {\n uid = (await firebaseAdmin.app().auth().verifyIdToken(idToken)).uid\n } catch (error) {\n if (!isRefusedIdToken(error)) throw error\n return { ok: false, status: 401, error: 'Unauthenticated' }\n }\n const host = await firebaseAdmin.app().firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n // \"Take booking payments in person\" (AGL-4047), whose preset is the site\n // Admin and Editor who took them before.\n if (!holdsBookingsSiteKey(host, uid, 'bookings.payments')) {\n return { ok: false, status: 403, error: bookingsSitePermissionRefusal('bookings.payments') }\n }\n const org = ((await getOrgForHost(hostId))?.org as Record<string, any> | undefined) ?? null\n if (!checkEntitlement(org as never, 'bookings') || !checkEntitlement(org as never, 'pos')) {\n return { ok: false, status: 403, error: 'Taking booking payments in person needs the POS plan.' }\n }\n return { ok: true, staff: { uid, hostId, org } }\n}\n\nexport const bookingInPersonPaymentHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = requestBody(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n const gate = await authorize(req, hostId)\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n if (!BOOKING_ID.test(bookingId)) return res.status(400).json({ error: 'Missing bookingId' })\n if (!inPersonCardsAvailable()) {\n return res.status(409).json({ error: 'Card readers are not available yet.' })\n }\n const action = String(body['action'] ?? '')\n try {\n switch (action) {\n case 'start':\n return await start(gate.staff, bookingId, body, req, res)\n case 'settle':\n return await settle(gate.staff, bookingId, res)\n case 'cancel':\n return await cancel(gate.staff, bookingId, res)\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[bookings/in-person-payment]', action, error)\n return res.status(500).json({ error: 'The payment could not be updated. Check the booking before trying again.' })\n }\n}\n\nfunction bookingRef(hostId: string, bookingId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('bookings')\n .doc(bookingId)\n}\n\nasync function merchantAccount(org: Record<string, any> | null, hostId: string): Promise<string | null> {\n const ownerUid = String(org?.['ownerUid'] ?? '')\n if (!ownerUid) return null\n const profile = await firebaseAdmin.app().firestore().collection('profiles').doc(ownerUid).get()\n const accountId = String(profile.get('stripeAccountId') ?? '')\n return merchantAccountIsReady(\n {\n accountId,\n chargesEnabled: profile.get('stripeChargesEnabled'),\n accountLivemode: profile.get('stripeAccountLivemode'),\n },\n { subject: `booking in-person host ${hostId}` },\n )\n ? accountId\n : null\n}\n\nasync function start(\n staff: Staff,\n bookingId: string,\n body: Record<string, any>,\n req: Parameters<PluginApiHandler>[0],\n res: Res,\n) {\n const attemptKey = String(req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '')\n .trim()\n .slice(0, 200)\n if (!attemptKey) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n const serviceCents = typeof body['amountCents'] === 'number' ? body['amountCents'] : NaN\n const problem = bookingInPersonAmountProblem(serviceCents)\n if (problem) return res.status(400).json({ error: problem })\n\n const ref = bookingRef(staff.hostId, bookingId)\n const snapshot = await ref.get()\n if (!snapshot.exists) return res.status(404).json({ error: 'Unknown booking' })\n const booking = snapshot.data() as Record<string, any>\n const state = bookingInPersonState(booking)\n const existing = booking['inPersonPayment'] as BookingInPersonPayment | undefined\n const attempt = createHash('sha256').update(`${bookingId}:${attemptKey}`).digest('hex').slice(0, 40)\n\n if (state === 'paid') return res.status(409).json({ error: 'This booking is already paid.' })\n if (state === 'canceled') return res.status(409).json({ error: 'This booking was canceled.' })\n if (state === 'awaiting-online') {\n return res.status(409).json({ error: 'The customer is paying for this booking online right now.' })\n }\n\n const destination = await merchantAccount(staff.org, staff.hostId)\n if (!destination) return res.status(409).json({ error: 'Finish setting up payments before taking cards.' })\n\n // The merchant's own service tax, off unless they set one (AGL-2028): the\n // same rate a paid booking is charged online.\n const tax = pluginTaxProfile().flatTax(\n await pluginTaxProfile().flatRate(staff.hostId, 'service'),\n serviceCents,\n 'Service tax',\n )\n const amountCents = serviceCents + tax.taxCents\n const feeCents = resolveTransactionFeeCents(staff.org as never, 'service', serviceCents, amountCents)\n\n // A pending intent for this booking that is not this attempt's: release it\n // first, so one booking never has two cards in flight.\n if (existing?.status === 'pending' && existing.paymentIntentId) {\n const sameAttempt = existing.attempt === attempt\n if (sameAttempt) {\n const replay = await stripe('GET', `payment_intents/${existing.paymentIntentId}`)\n if (replay.ok && replay.body?.client_secret) {\n return res.status(200).json(startAnswer(existing, String(replay.body.client_secret)))\n }\n } else {\n const released = await releaseIntent(existing.paymentIntentId)\n if (!released) {\n return res.status(409).json({\n error: 'A card was already authorized for this booking. Settle it before starting another payment.',\n })\n }\n }\n }\n\n const intent = await stripe('POST', 'payment_intents', {\n idempotencyKey: `booking-in-person:${attempt}`,\n params: {\n amount: amountCents,\n currency: 'usd',\n 'payment_method_types[]': 'card_present',\n capture_method: 'manual',\n 'transfer_data[destination]': destination,\n ...(feeCents > 0 ? { application_fee_amount: feeCents } : {}),\n description: `Booking: ${String(booking['serviceName'] ?? 'appointment').slice(0, 80)}`,\n 'metadata[type]': 'booking-in-person',\n 'metadata[hostId]': staff.hostId,\n 'metadata[bookingId]': bookingId,\n 'metadata[feeCents]': feeCents,\n 'metadata[cashierId]': staff.uid,\n ...(tax.taxCents > 0 ? { 'metadata[taxCents]': tax.taxCents, 'metadata[taxPct]': tax.pct } : {}),\n },\n })\n if (!intent.ok || !intent.body?.id || !intent.body?.client_secret) {\n return res.status(502).json({ error: stripeMessage(intent.body, 'The card payment could not be started.') })\n }\n const payment: BookingInPersonPayment = {\n paymentIntentId: String(intent.body.id),\n amountCents,\n serviceCents,\n taxCents: tax.taxCents,\n feeCents,\n status: 'pending',\n startedAtMs: Date.now(),\n startedBy: staff.uid,\n attempt,\n }\n // Recorded in a transaction that re-checks the booking: a payment that\n // landed meanwhile (online, or on another device) wins, and this intent is\n // released instead of left to authorize a second charge.\n const recorded = await firebaseAdmin.app().firestore().runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(ref)\n const freshState = bookingInPersonState((fresh.data() ?? {}) as Record<string, any>)\n const freshPending = fresh.get('inPersonPayment') as BookingInPersonPayment | undefined\n if (freshState === 'paid' || freshState === 'canceled' || freshState === 'awaiting-online') return false\n if (\n freshPending?.status === 'pending' &&\n freshPending.paymentIntentId !== payment.paymentIntentId &&\n freshPending.paymentIntentId !== existing?.paymentIntentId\n ) {\n return false\n }\n transaction.set(ref, { inPersonPayment: payment }, { merge: true })\n return true\n })\n if (!recorded) {\n await releaseIntent(payment.paymentIntentId)\n return res.status(409).json({ error: 'This booking changed while the payment started. Open it again.' })\n }\n return res.status(200).json(startAnswer(payment, String(intent.body.client_secret)))\n}\n\nfunction startAnswer(payment: BookingInPersonPayment, clientSecret: string) {\n return {\n paymentIntentId: payment.paymentIntentId,\n clientSecret,\n amountCents: payment.amountCents,\n serviceCents: payment.serviceCents,\n taxCents: payment.taxCents,\n }\n}\n\n/** Cancels an intent that holds no money yet; false when it does. */\nasync function releaseIntent(paymentIntentId: string): Promise<boolean> {\n const current = await stripe('GET', `payment_intents/${paymentIntentId}`)\n const status = String(current.body?.status ?? '')\n if (status === 'canceled') return true\n if (status === 'succeeded' || status === 'requires_capture' || status === 'processing') return false\n const canceled = await stripe('POST', `payment_intents/${paymentIntentId}/cancel`, {\n idempotencyKey: `booking-in-person-cancel:${paymentIntentId}`,\n })\n return canceled.ok || String(canceled.body?.status ?? '') === 'canceled'\n}\n\nasync function settle(staff: Staff, bookingId: string, res: Res) {\n const ref = bookingRef(staff.hostId, bookingId)\n const snapshot = await ref.get()\n if (!snapshot.exists) return res.status(404).json({ error: 'Unknown booking' })\n const payment = snapshot.get('inPersonPayment') as BookingInPersonPayment | undefined\n if (payment?.status === 'paid') return res.status(200).json({ status: 'paid', amountCents: payment.amountCents })\n if (!payment || payment.status !== 'pending' || !PAYMENT_INTENT_ID.test(String(payment.paymentIntentId))) {\n return res.status(409).json({ error: 'No card payment is in progress for this booking.' })\n }\n let intent = (await stripe('GET', `payment_intents/${payment.paymentIntentId}`)).body\n // The intent must be the one this route made for THIS booking on THIS site.\n if (\n intent?.metadata?.type !== 'booking-in-person' ||\n intent?.metadata?.hostId !== staff.hostId ||\n intent?.metadata?.bookingId !== bookingId\n ) {\n return res.status(409).json({ error: 'That payment is not for this booking.' })\n }\n if (intent.status === 'requires_capture') {\n const captured = await stripe('POST', `payment_intents/${payment.paymentIntentId}/capture`, {\n idempotencyKey: `booking-in-person-capture:${payment.paymentIntentId}`,\n params: payment.feeCents > 0 ? { application_fee_amount: payment.feeCents } : {},\n })\n if (!captured.ok) {\n return res.status(502).json({ error: stripeMessage(captured.body, 'The card could not be charged. Try again.') })\n }\n intent = captured.body\n }\n if (intent?.status !== 'succeeded') {\n // Not collected yet, declined, or canceled: the booking stays payable.\n const status = intent?.status === 'canceled' ? 'canceled' : 'pending'\n if (status === 'canceled') {\n await ref.set({ inPersonPayment: { ...payment, status: 'canceled' } }, { merge: true })\n }\n return res.status(200).json({ status })\n }\n const paidAmountCents = Math.max(0, Math.round(Number(intent.amount_received ?? intent.amount ?? 0)))\n const paidAtMs = Date.now()\n await firebaseAdmin.app().firestore().runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(ref)\n if (fresh.get('paymentIntentId')) return\n transaction.set(\n ref,\n {\n // The same fields an online payment writes (billing-webhook.ts), so\n // the console's refund and dispute handling read it unchanged.\n paidAmountCents,\n paymentIntentId: payment.paymentIntentId,\n feeCents: payment.feeCents,\n taxMode: pluginTaxProfile().taxModeOf(intent, payment.taxCents),\n ...(payment.taxCents > 0 ? { taxCents: payment.taxCents } : {}),\n paidInPerson: true,\n inPersonPayment: { ...payment, status: 'paid', paidAtMs },\n },\n { merge: true },\n )\n })\n return res.status(200).json({ status: 'paid', amountCents: paidAmountCents })\n}\n\nasync function cancel(staff: Staff, bookingId: string, res: Res) {\n const ref = bookingRef(staff.hostId, bookingId)\n const snapshot = await ref.get()\n if (!snapshot.exists) return res.status(404).json({ error: 'Unknown booking' })\n const payment = snapshot.get('inPersonPayment') as BookingInPersonPayment | undefined\n if (!payment || payment.status !== 'pending') return res.status(200).json({ status: 'none' })\n if (!(await releaseIntent(payment.paymentIntentId))) {\n return res.status(409).json({ error: 'The card was already authorized. Settle the payment instead.' })\n }\n await ref.set({ inPersonPayment: { ...payment, status: 'canceled' } }, { merge: true })\n return res.status(200).json({ status: 'canceled' })\n}\n"],"names":["createHash","firebaseAdmin","getOrgForHost","merchantAccountIsReady","checkEntitlement","resolveTransactionFeeCents","pluginTaxProfile","bookingInPersonAmountProblem","bookingInPersonState","bookingsSitePermissionRefusal","holdsBookingsSiteKey","isRefusedIdToken","BOOKING_ID","PAYMENT_INTENT_ID","requestBody","req","body","parsed","JSON","parse","inPersonCardsAvailable","process","key","String","env","STRIPE_SECRET_KEY","startsWith","STRIPE_TERMINAL_LIVE_ENABLED","toLowerCase","stripe","method","path","options","form","URLSearchParams","value","Object","entries","params","undefined","append","query","toString","response","fetch","headers","Authorization","idempotencyKey","json","catch","ok","status","stripeMessage","fallback","message","error","authorize","hostId","authorization","idToken","slice","uid","app","auth","verifyIdToken","host","firestore","collection","doc","get","exists","org","staff","bookingInPersonPaymentHandler","res","bookingId","gate","test","action","start","settle","cancel","console","bookingRef","merchantAccount","profile","ownerUid","accountId","chargesEnabled","accountLivemode","subject","booking","intent","attemptKey","trim","serviceCents","NaN","problem","ref","snapshot","data","state","existing","attempt","update","digest","destination","tax","flatTax","flatRate","amountCents","taxCents","feeCents","paymentIntentId","sameAttempt","replay","client_secret","startAnswer","released","releaseIntent","amount","currency","capture_method","application_fee_amount","description","pct","id","payment","startedAtMs","Date","now","startedBy","recorded","runTransaction","transaction","fresh","freshState","freshPending","set","inPersonPayment","merge","clientSecret","current","canceled","metadata","type","captured","paidAmountCents","Math","max","round","Number","amount_received","paidAtMs","taxMode","taxModeOf","paidInPerson"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SACEC,gBAAgB,EAChBC,0BAA0B,QAErB,sBAAqB;AAC5B,SAASC,gBAAgB,QAAQ,iDAAgD;AACjF,SACEC,4BAA4B,EAC5BC,oBAAoB,QAEf,gCAA4B;AACnC,SAASC,6BAA6B,QAAQ,mCAA+B;AAC7E,SAASC,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,gBAAgB,QAAQ,mDAAkD;AAEnF;;;;;;;;;;;;;;;;;;;;;;;;;;2CA0B2C,GAE3C,MAAMC,aAAa;AACnB,MAAMC,oBAAoB;AAU1B,SAASC,YAAYC,GAAoC;IACvD,IAAI,OAAOA,IAAIC,IAAI,KAAK,UAAU;QAChC,IAAI;YACF,MAAMC,SAASC,KAAKC,KAAK,CAACJ,IAAIC,IAAI;YAClC,OAAOC,UAAU,OAAOA,WAAW,WAAWA,SAAS,CAAC;QAC1D,EAAE,eAAM;YACN,OAAO,CAAC;QACV;IACF;IACA,OAAOF,IAAIC,IAAI,IAAI,OAAOD,IAAIC,IAAI,KAAK,WAAWD,IAAIC,IAAI,GAAG,CAAC;AAChE;AAEA,+EAA+E,GAC/E,OAAO,SAASI;QACKC,gCAIVA;IAJT,MAAMC,MAAMC,QAAOF,iCAAAA,QAAQG,GAAG,CAACC,iBAAiB,YAA7BJ,iCAAiC;IACpD,IAAI,CAACC,KAAK,OAAO;IACjB,OACEA,IAAII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AOlE,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEG,QAAQ;QAAQ2D,aAAaqC;IAAgB;AAC7E;AAEA,eAAelE,OAAOT,KAAY,EAAEG,SAAiB,EAAED,GAAQ;IAC7D,MAAMwB,MAAMf,WAAWX,MAAMf,MAAM,EAAEkB;IACrC,MAAMwB,WAAW,MAAMD,IAAI7B,GAAG;IAC9B,IAAI,CAAC8B,SAAS7B,MAAM,EAAE,OAAOI,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEO,OAAO;IAAkB;IAC7E,MAAMwE,UAAU5B,SAAS9B,GAAG,CAAC;IAC7B,IAAI,CAAC0D,WAAWA,QAAQ5E,MAAM,KAAK,WAAW,OAAOuB,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEG,QAAQ;IAAO;IAC3F,IAAI,CAAE,MAAMoE,cAAcQ,QAAQd,eAAe,GAAI;QACnD,OAAOvC,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;YAAEO,OAAO;QAA+D;IACtG;IACA,MAAM2C,IAAIwC,GAAG,CAAC;QAAEC,iBAAiB,aAAKZ;YAAS5E,QAAQ;;IAAa,GAAG;QAAEyF,OAAO;IAAK;IACrF,OAAOlE,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEG,QAAQ;IAAW;AACnD"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/in-person-payment.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 { createHash } from 'crypto'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { merchantAccountIsReady } from '@aglyn/tenant-data-admin/server/payment-provider'\nimport {\n checkEntitlement,\n resolveTransactionFeeCents,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { pluginTaxProfile } from '@aglyn/aglyn/plugin-manager/plugin-tax-profile'\nimport {\n bookingInPersonAmountProblem,\n bookingInPersonState,\n type BookingInPersonPayment,\n} from '../model/booking-in-person'\nimport { bookingsSitePermissionRefusal } from '../model/bookings-permissions'\nimport { holdsBookingsSiteKey } from './bookings-site-keys'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\n\n/*==========================================\n * `POST /api/bookings/in-person-payment` (AGL-3618).\n *\n * Takes payment for a booking at the counter, on the card reader the native\n * Aglyn POS app has connected (Tap to Pay or a Bluetooth reader). The server\n * owns the money; the app only presents the card:\n *\n * - `start` prices the charge (the amount staff typed, plus the merchant's\n * own service tax), and creates a card-present PaymentIntent: a\n * DESTINATION charge to the merchant, settled on Aglyn's platform account\n * with no `on_behalf_of` (ToS §10.7, AGL-3607), with the take and\n * Stripe's card cost as `application_fee_amount` — exactly the fee a paid\n * booking already carries online (`resolveTransactionFeeCents`, `service`).\n * Returns the intent's client secret for the app's Terminal SDK.\n * - `settle` re-reads the intent from Stripe (never trusting the app's word),\n * captures an authorized one, and records the booking paid with the same\n * fields an online payment writes, so the console's refund and the dispute\n * handling work on it unchanged.\n * - `cancel` releases an intent that was not collected.\n *\n * MANUAL capture, so a card that authorizes but whose booking was changed in\n * between is released rather than charged. On-reader tipping is not offered\n * here; the amount is the amount.\n *\n * Gate: a site `admin` or `editor`, and the owning org's `bookings` and\n * `pos` entitlements (taking card-present payments is a POS capability).\n *=========================================*/\n\nconst BOOKING_ID = /^[A-Za-z0-9_-]{1,128}$/\nconst PAYMENT_INTENT_ID = /^pi_[A-Za-z0-9_]{6,128}$/\n\ntype Res = Parameters<PluginApiHandler>[1]\n\ninterface Staff {\n uid: string\n hostId: string\n org: Record<string, any> | null\n}\n\nfunction requestBody(req: Parameters<PluginApiHandler>[0]): Record<string, any> {\n if (typeof req.body === 'string') {\n try {\n const parsed = JSON.parse(req.body)\n return parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n return {}\n }\n }\n return req.body && typeof req.body === 'object' ? req.body : {}\n}\n\n/** Card-present payments: always in test mode, in live mode once switched on. */\nexport function inPersonCardsAvailable(): boolean {\n const key = String(process.env.STRIPE_SECRET_KEY ?? '')\n if (!key) return false\n return (\n key.startsWith('sk_test_') ||\n String(process.env.STRIPE_TERMINAL_LIVE_ENABLED ?? '').toLowerCase() === 'true'\n )\n}\n\nasync function stripe(\n method: 'GET' | 'POST',\n path: string,\n options: { params?: Record<string, string | number | boolean | undefined>; idempotencyKey?: string } = {},\n): Promise<{ ok: boolean; status: number; body: any }> {\n const form = new URLSearchParams()\n for (const [key, value] of Object.entries(options.params ?? {})) {\n if (value !== undefined) form.append(key, String(value))\n }\n const query = method === 'GET' && form.toString() ? `?${form}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(options.idempotencyKey ? { 'Idempotency-Key': options.idempotencyKey } : {}),\n },\n ...(method === 'POST' ? { body: form.toString() } : {}),\n })\n const body = await response.json().catch(() => null)\n return { ok: response.ok, status: response.status, body }\n}\n\nfunction stripeMessage(body: any, fallback: string): string {\n const message = body?.error?.message\n return typeof message === 'string' && message ? message : fallback\n}\n\nasync function authorize(\n req: Parameters<PluginApiHandler>[0],\n hostId: string,\n): Promise<{ ok: true; staff: Staff } | { ok: false; status: number; error: string }> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ') ? authorization.slice(7) : ''\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n if (!hostId) return { ok: false, status: 400, error: 'Missing hostId' }\n let uid: string\n try {\n uid = (await firebaseAdmin.app().auth().verifyIdToken(idToken)).uid\n } catch (error) {\n if (!isRefusedIdToken(error)) throw error\n return { ok: false, status: 401, error: 'Unauthenticated' }\n }\n const host = await firebaseAdmin.app().firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n // \"Take booking payments in person\" (AGL-4047), whose preset is the site\n // Admin and Editor who took them before.\n if (!holdsBookingsSiteKey(host, uid, 'bookings.payments')) {\n return { ok: false, status: 403, error: bookingsSitePermissionRefusal('bookings.payments') }\n }\n const org = ((await getOrgForHost(hostId))?.org as Record<string, any> | undefined) ?? null\n if (!checkEntitlement(org as never, 'bookings') || !checkEntitlement(org as never, 'pos')) {\n return { ok: false, status: 403, error: 'Taking booking payments in person needs the POS plan.' }\n }\n return { ok: true, staff: { uid, hostId, org } }\n}\n\nexport const bookingInPersonPaymentHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = requestBody(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n const gate = await authorize(req, hostId)\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n if (!BOOKING_ID.test(bookingId)) return res.status(400).json({ error: 'Missing bookingId' })\n if (!inPersonCardsAvailable()) {\n return res.status(409).json({ error: 'Card readers are not available yet.' })\n }\n const action = String(body['action'] ?? '')\n try {\n switch (action) {\n case 'start':\n return await start(gate.staff, bookingId, body, req, res)\n case 'settle':\n return await settle(gate.staff, bookingId, res)\n case 'cancel':\n return await cancel(gate.staff, bookingId, res)\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[bookings/in-person-payment]', action, error)\n return res.status(500).json({ error: 'The payment could not be updated. Check the booking before trying again.' })\n }\n}\n\nfunction bookingRef(hostId: string, bookingId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('bookings')\n .doc(bookingId)\n}\n\nasync function merchantAccount(org: Record<string, any> | null, hostId: string): Promise<string | null> {\n const ownerUid = String(org?.['ownerUid'] ?? '')\n if (!ownerUid) return null\n const profile = await firebaseAdmin.app().firestore().collection('profiles').doc(ownerUid).get()\n const accountId = String(profile.get('stripeAccountId') ?? '')\n return merchantAccountIsReady(\n {\n accountId,\n chargesEnabled: profile.get('stripeChargesEnabled'),\n accountLivemode: profile.get('stripeAccountLivemode'),\n },\n { subject: `booking in-person host ${hostId}` },\n )\n ? accountId\n : null\n}\n\nasync function start(\n staff: Staff,\n bookingId: string,\n body: Record<string, any>,\n req: Parameters<PluginApiHandler>[0],\n res: Res,\n) {\n const attemptKey = String(req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '')\n .trim()\n .slice(0, 200)\n if (!attemptKey) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n const serviceCents = typeof body['amountCents'] === 'number' ? body['amountCents'] : NaN\n const problem = bookingInPersonAmountProblem(serviceCents)\n if (problem) return res.status(400).json({ error: problem })\n\n const ref = bookingRef(staff.hostId, bookingId)\n const snapshot = await ref.get()\n if (!snapshot.exists) return res.status(404).json({ error: 'Unknown booking' })\n const booking = snapshot.data() as Record<string, any>\n const state = bookingInPersonState(booking)\n const existing = booking['inPersonPayment'] as BookingInPersonPayment | undefined\n const attempt = createHash('sha256').update(`${bookingId}:${attemptKey}`).digest('hex').slice(0, 40)\n\n if (state === 'paid') return res.status(409).json({ error: 'This booking is already paid.' })\n if (state === 'canceled') return res.status(409).json({ error: 'This booking was canceled.' })\n if (state === 'awaiting-online') {\n return res.status(409).json({ error: 'The customer is paying for this booking online right now.' })\n }\n\n const destination = await merchantAccount(staff.org, staff.hostId)\n if (!destination) return res.status(409).json({ error: 'Finish setting up payments before taking cards.' })\n\n // The merchant's own service tax, off unless they set one (AGL-2028): the\n // same rate a paid booking is charged online.\n const tax = pluginTaxProfile().flatTax(\n await pluginTaxProfile().flatRate(staff.hostId, 'service'),\n serviceCents,\n 'Service tax',\n )\n const amountCents = serviceCents + tax.taxCents\n // A reader's card, priced at the in-person rate (AGL-4198).\n const feeCents = resolveTransactionFeeCents(staff.org as never, 'service', serviceCents, amountCents, {\n inPerson: true,\n })\n\n // A pending intent for this booking that is not this attempt's: release it\n // first, so one booking never has two cards in flight.\n if (existing?.status === 'pending' && existing.paymentIntentId) {\n const sameAttempt = existing.attempt === attempt\n if (sameAttempt) {\n const replay = await stripe('GET', `payment_intents/${existing.paymentIntentId}`)\n if (replay.ok && replay.body?.client_secret) {\n return res.status(200).json(startAnswer(existing, String(replay.body.client_secret)))\n }\n } else {\n const released = await releaseIntent(existing.paymentIntentId)\n if (!released) {\n return res.status(409).json({\n error: 'A card was already authorized for this booking. Settle it before starting another payment.',\n })\n }\n }\n }\n\n const intent = await stripe('POST', 'payment_intents', {\n idempotencyKey: `booking-in-person:${attempt}`,\n params: {\n amount: amountCents,\n currency: 'usd',\n 'payment_method_types[]': 'card_present',\n capture_method: 'manual',\n 'transfer_data[destination]': destination,\n ...(feeCents > 0 ? { application_fee_amount: feeCents } : {}),\n description: `Booking: ${String(booking['serviceName'] ?? 'appointment').slice(0, 80)}`,\n 'metadata[type]': 'booking-in-person',\n 'metadata[hostId]': staff.hostId,\n 'metadata[bookingId]': bookingId,\n 'metadata[feeCents]': feeCents,\n 'metadata[cashierId]': staff.uid,\n ...(tax.taxCents > 0 ? { 'metadata[taxCents]': tax.taxCents, 'metadata[taxPct]': tax.pct } : {}),\n },\n })\n if (!intent.ok || !intent.body?.id || !intent.body?.client_secret) {\n return res.status(502).json({ error: stripeMessage(intent.body, 'The card payment could not be started.') })\n }\n const payment: BookingInPersonPayment = {\n paymentIntentId: String(intent.body.id),\n amountCents,\n serviceCents,\n taxCents: tax.taxCents,\n feeCents,\n status: 'pending',\n startedAtMs: Date.now(),\n startedBy: staff.uid,\n attempt,\n }\n // Recorded in a transaction that re-checks the booking: a payment that\n // landed meanwhile (online, or on another device) wins, and this intent is\n // released instead of left to authorize a second charge.\n const recorded = await firebaseAdmin.app().firestore().runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(ref)\n const freshState = bookingInPersonState((fresh.data() ?? {}) as Record<string, any>)\n const freshPending = fresh.get('inPersonPayment') as BookingInPersonPayment | undefined\n if (freshState === 'paid' || freshState === 'canceled' || freshState === 'awaiting-online') return false\n if (\n freshPending?.status === 'pending' &&\n freshPending.paymentIntentId !== payment.paymentIntentId &&\n freshPending.paymentIntentId !== existing?.paymentIntentId\n ) {\n return false\n }\n transaction.set(ref, { inPersonPayment: payment }, { merge: true })\n return true\n })\n if (!recorded) {\n await releaseIntent(payment.paymentIntentId)\n return res.status(409).json({ error: 'This booking changed while the payment started. Open it again.' })\n }\n return res.status(200).json(startAnswer(payment, String(intent.body.client_secret)))\n}\n\nfunction startAnswer(payment: BookingInPersonPayment, clientSecret: string) {\n return {\n paymentIntentId: payment.paymentIntentId,\n clientSecret,\n amountCents: payment.amountCents,\n serviceCents: payment.serviceCents,\n taxCents: payment.taxCents,\n }\n}\n\n/** Cancels an intent that holds no money yet; false when it does. */\nasync function releaseIntent(paymentIntentId: string): Promise<boolean> {\n const current = await stripe('GET', `payment_intents/${paymentIntentId}`)\n const status = String(current.body?.status ?? '')\n if (status === 'canceled') return true\n if (status === 'succeeded' || status === 'requires_capture' || status === 'processing') return false\n const canceled = await stripe('POST', `payment_intents/${paymentIntentId}/cancel`, {\n idempotencyKey: `booking-in-person-cancel:${paymentIntentId}`,\n })\n return canceled.ok || String(canceled.body?.status ?? '') === 'canceled'\n}\n\nasync function settle(staff: Staff, bookingId: string, res: Res) {\n const ref = bookingRef(staff.hostId, bookingId)\n const snapshot = await ref.get()\n if (!snapshot.exists) return res.status(404).json({ error: 'Unknown booking' })\n const payment = snapshot.get('inPersonPayment') as BookingInPersonPayment | undefined\n if (payment?.status === 'paid') return res.status(200).json({ status: 'paid', amountCents: payment.amountCents })\n if (!payment || payment.status !== 'pending' || !PAYMENT_INTENT_ID.test(String(payment.paymentIntentId))) {\n return res.status(409).json({ error: 'No card payment is in progress for this booking.' })\n }\n let intent = (await stripe('GET', `payment_intents/${payment.paymentIntentId}`)).body\n // The intent must be the one this route made for THIS booking on THIS site.\n if (\n intent?.metadata?.type !== 'booking-in-person' ||\n intent?.metadata?.hostId !== staff.hostId ||\n intent?.metadata?.bookingId !== bookingId\n ) {\n return res.status(409).json({ error: 'That payment is not for this booking.' })\n }\n if (intent.status === 'requires_capture') {\n const captured = await stripe('POST', `payment_intents/${payment.paymentIntentId}/capture`, {\n idempotencyKey: `booking-in-person-capture:${payment.paymentIntentId}`,\n params: payment.feeCents > 0 ? { application_fee_amount: payment.feeCents } : {},\n })\n if (!captured.ok) {\n return res.status(502).json({ error: stripeMessage(captured.body, 'The card could not be charged. Try again.') })\n }\n intent = captured.body\n }\n if (intent?.status !== 'succeeded') {\n // Not collected yet, declined, or canceled: the booking stays payable.\n const status = intent?.status === 'canceled' ? 'canceled' : 'pending'\n if (status === 'canceled') {\n await ref.set({ inPersonPayment: { ...payment, status: 'canceled' } }, { merge: true })\n }\n return res.status(200).json({ status })\n }\n const paidAmountCents = Math.max(0, Math.round(Number(intent.amount_received ?? intent.amount ?? 0)))\n const paidAtMs = Date.now()\n await firebaseAdmin.app().firestore().runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(ref)\n if (fresh.get('paymentIntentId')) return\n transaction.set(\n ref,\n {\n // The same fields an online payment writes (billing-webhook.ts), so\n // the console's refund and dispute handling read it unchanged.\n paidAmountCents,\n paymentIntentId: payment.paymentIntentId,\n feeCents: payment.feeCents,\n taxMode: pluginTaxProfile().taxModeOf(intent, payment.taxCents),\n ...(payment.taxCents > 0 ? { taxCents: payment.taxCents } : {}),\n paidInPerson: true,\n inPersonPayment: { ...payment, status: 'paid', paidAtMs },\n },\n { merge: true },\n )\n })\n return res.status(200).json({ status: 'paid', amountCents: paidAmountCents })\n}\n\nasync function cancel(staff: Staff, bookingId: string, res: Res) {\n const ref = bookingRef(staff.hostId, bookingId)\n const snapshot = await ref.get()\n if (!snapshot.exists) return res.status(404).json({ error: 'Unknown booking' })\n const payment = snapshot.get('inPersonPayment') as BookingInPersonPayment | undefined\n if (!payment || payment.status !== 'pending') return res.status(200).json({ status: 'none' })\n if (!(await releaseIntent(payment.paymentIntentId))) {\n return res.status(409).json({ error: 'The card was already authorized. Settle the payment instead.' })\n }\n await ref.set({ inPersonPayment: { ...payment, status: 'canceled' } }, { merge: true })\n return res.status(200).json({ status: 'canceled' })\n}\n"],"names":["createHash","firebaseAdmin","getOrgForHost","merchantAccountIsReady","checkEntitlement","resolveTransactionFeeCents","pluginTaxProfile","bookingInPersonAmountProblem","bookingInPersonState","bookingsSitePermissionRefusal","holdsBookingsSiteKey","isRefusedIdToken","BOOKING_ID","PAYMENT_INTENT_ID","requestBody","req","body","parsed","JSON","parse","inPersonCardsAvailable","process","key","String","env","STRIPE_SECRET_KEY","startsWith","STRIPE_TERMINAL_LIVE_ENABLED","toLowerCase","stripe","method","path","options","form","URLSearchParams","value","Object","entries","params","undefined","append","query","toString","response","fetch","headers","Authorization","idempotencyKey","json","catch","ok","status","stripeMessage","fallback","message","error","authorize","hostId","authorization","idToken","slice","uid","app","auth","verifyIdToken","host","firestore","collection","doc","get","exists","org","staff","bookingInPersonPaymentHandler","res","bookingId","gate","test","action","start","settle","cancel","console","bookingRef","merchantAccount","profile","ownerUid","accountId","chargesEnabled","accountLivemode","subject","booking","intent","attemptKey","trim","serviceCents","NaN","problem","ref","snapshot","data","state","existing","attempt","update","digest","destination","tax","flatTax","flatRate","amountCents","taxCents","feeCents","inPerson","paymentIntentId","sameAttempt","replay","client_secret","startAnswer","released","releaseIntent","amount","currency","capture_method","application_fee_amount","description","pct","id","payment","startedAtMs","Date","now","startedBy","recorded","runTransaction","transaction","fresh","freshState","freshPending","set","inPersonPayment","merge","clientSecret","current","canceled","metadata","type","captured","paidAmountCents","Math","max","round","Number","amount_received","paidAtMs","taxMode","taxModeOf","paidInPerson"],"mappings":";AAAA;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AAMwB,WAAW,MAAMD,IAAI7B,GAAG;IAC9B,IAAI,CAAC8B,SAAS7B,MAAM,EAAE,OAAOI,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEO,OAAO;IAAkB;IAC7E,MAAMyE,UAAU7B,SAAS9B,GAAG,CAAC;IAC7B,IAAI,CAAC2D,WAAWA,QAAQ7E,MAAM,KAAK,WAAW,OAAOuB,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEG,QAAQ;IAAO;IAC3F,IAAI,CAAE,MAAMqE,cAAcQ,QAAQd,eAAe,GAAI;QACnD,OAAOxC,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;YAAEO,OAAO;QAA+D;IACtG;IACA,MAAM2C,IAAIyC,GAAG,CAAC;QAAEC,iBAAiB,aAAKZ;YAAS7E,QAAQ;;IAAa,GAAG;QAAE0F,OAAO;IAAK;IACrF,OAAOnE,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEG,QAAQ;IAAW;AACnD"}
|
|
@@ -61,5 +61,11 @@ import { type PluginApiHandler } from '@aglyn/aglyn/server';
|
|
|
61
61
|
* written inside one transaction, BEFORE Stripe is called, so a lost
|
|
62
62
|
* response leaves the amount counted and the retry refunds less, never
|
|
63
63
|
* more.
|
|
64
|
+
*
|
|
65
|
+
* A DIRECT-charge booking (`chargeModel: 'direct'`) was charged on the
|
|
66
|
+
* seller's own account, so its refund is made there (`Stripe-Account`) and is
|
|
67
|
+
* debited from the seller's balance. There is no transfer to reverse, so
|
|
68
|
+
* `reverse_transfer` is never sent; `refund_application_fee` still is, for the
|
|
69
|
+
* same reason as above.
|
|
64
70
|
*/
|
|
65
71
|
export declare const bookingRefundHandler: PluginApiHandler;
|