@aglyn/plugins-bookings 1.15.2 → 1.16.0

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-bookings",
3
- "version": "1.15.2",
3
+ "version": "1.16.0",
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.15.2",
29
- "@aglyn/shared-data-mdi": "1.15.2",
30
- "@aglyn/shared-ui-jsx": "1.15.2",
31
- "@aglyn/shared-ui-snackstack": "1.15.2",
32
- "@aglyn/shared-util-email": "1.15.2",
33
- "@aglyn/shared-util-http": "1.15.2",
34
- "@aglyn/shared-util-timestamp": "1.15.2",
35
- "@aglyn/tenant-data-admin": "1.15.2",
36
- "@aglyn/tenant-feature-instance": "1.15.2",
37
- "@aglyn/tenant-runtime": "1.15.2",
28
+ "@aglyn/aglyn": "1.16.0",
29
+ "@aglyn/shared-data-mdi": "1.16.0",
30
+ "@aglyn/shared-ui-jsx": "1.16.0",
31
+ "@aglyn/shared-ui-snackstack": "1.16.0",
32
+ "@aglyn/shared-util-email": "1.16.0",
33
+ "@aglyn/shared-util-http": "1.16.0",
34
+ "@aglyn/shared-util-timestamp": "1.16.0",
35
+ "@aglyn/tenant-data-admin": "1.16.0",
36
+ "@aglyn/tenant-feature-instance": "1.16.0",
37
+ "@aglyn/tenant-runtime": "1.16.0",
38
38
  "@swc/helpers": "0.5.23"
39
39
  },
40
40
  "peerDependencies": {
@@ -29,6 +29,13 @@ export interface BookingInPersonPayment {
29
29
  paidAtMs?: number;
30
30
  /** Which start request made it, so a retried start returns it again. */
31
31
  attempt?: string;
32
+ /**
33
+ * `direct` when the intent was made ON the store's own Stripe account
34
+ * (`stripeAccountId`), where its capture, cancel and refund go. Absent for
35
+ * a destination charge on the platform.
36
+ */
37
+ chargeModel?: 'direct';
38
+ stripeAccountId?: string;
32
39
  }
33
40
  /** The fields of a booking this reads; any booking document has them. */
34
41
  export interface BookingPaymentFields {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/model/booking-in-person.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/*==========================================\n * TAKING PAYMENT FOR A BOOKING IN PERSON (AGL-3618).\n *\n * A booking whose price was not charged online (a free booking, or one whose\n * price `varies`, is an `estimate` or is `contact`) is paid at the counter\n * once the work is done: staff type the amount and the customer taps or\n * inserts a card on the register's reader. Pure: the server route, the\n * console and the native Aglyn POS app all read a booking through these.\n *\n * Imports nothing, so client and server code alike may import it.\n *=========================================*/\n\n/** The in-person payment a booking carries while it is being taken. */\nexport interface BookingInPersonPayment {\n paymentIntentId: string\n /** The whole charge: service plus tax. */\n amountCents: number\n /** The service amount staff typed, before tax. */\n serviceCents: number\n taxCents: number\n feeCents: number\n status: 'pending' | 'paid' | 'canceled'\n startedAtMs: number\n startedBy: string\n paidAtMs?: number\n /** Which start request made it, so a retried start returns it again. */\n attempt?: string\n}\n\n/** The fields of a booking this reads; any booking document has them. */\nexport interface BookingPaymentFields {\n status?: string\n expiresAtMs?: number\n paidAmountCents?: number\n refundedCents?: number\n paymentIntentId?: string\n inPersonPayment?: Partial<BookingInPersonPayment> | null\n}\n\nexport type BookingInPersonState =\n /** Paid already, online or in person. */\n | 'paid'\n /** Canceled: nothing to pay. */\n | 'canceled'\n /** Still holding for its online Checkout: the customer is paying there. */\n | 'awaiting-online'\n /** A card is being taken for it now. */\n | 'collecting'\n /** Can be paid at the counter. */\n | 'payable'\n\nexport function bookingInPersonState(\n booking: BookingPaymentFields,\n nowMs = Date.now(),\n): BookingInPersonState {\n if (\n Math.round(Number(booking.paidAmountCents ?? 0)) > 0 ||\n Boolean(booking.paymentIntentId) ||\n booking.inPersonPayment?.status === 'paid'\n ) {\n return 'paid'\n }\n if (booking.status === 'canceled') return 'canceled'\n if (booking.status === 'pendingPayment') {\n // A lapsed online hold released its slot; it is not an appointment.\n return Number(booking.expiresAtMs ?? 0) < nowMs ? 'canceled' : 'awaiting-online'\n }\n if (booking.inPersonPayment?.status === 'pending') return 'collecting'\n return 'payable'\n}\n\n/** The most one in-person booking charge may be: $10,000. */\nexport const BOOKING_IN_PERSON_MAX_CENTS = 1_000_000\n/** Stripe's card minimum in USD. */\nexport const BOOKING_IN_PERSON_MIN_CENTS = 50\n\n/** Null when `serviceCents` is an amount staff may charge; otherwise why not. */\nexport function bookingInPersonAmountProblem(serviceCents: unknown): string | null {\n if (typeof serviceCents !== 'number' || !Number.isInteger(serviceCents)) {\n return 'Enter the amount to charge.'\n }\n if (serviceCents < BOOKING_IN_PERSON_MIN_CENTS) return 'Card payments start at $0.50.'\n if (serviceCents > BOOKING_IN_PERSON_MAX_CENTS) return 'Charge at most $10,000 at a time.'\n return null\n}\n\n/**\n * The amount to suggest: the service's fixed price, when it has one. A\n * `varies`, `estimate` or `contact` price suggests nothing; staff type it.\n */\nexport function bookingSuggestedCents(service: {\n priceUsd?: number\n priceDisplay?: string\n} | null | undefined): number | null {\n if (!service) return null\n if (service.priceDisplay && service.priceDisplay !== 'fixed') return null\n const cents = Math.round(Number(service.priceUsd ?? 0) * 100)\n return Number.isFinite(cents) && cents >= BOOKING_IN_PERSON_MIN_CENTS ? cents : null\n}\n\n/** The start and end of the local day that holds `atMs`, in milliseconds. */\nexport function bookingDayRange(atMs: number, offsetMinutes = new Date(atMs).getTimezoneOffset()): {\n startMs: number\n endMs: number\n} {\n const local = atMs - offsetMinutes * 60_000\n const dayStart = Math.floor(local / 86_400_000) * 86_400_000\n const startMs = dayStart + offsetMinutes * 60_000\n return { startMs, endMs: startMs + 86_400_000 }\n}\n"],"names":["bookingInPersonState","booking","nowMs","Date","now","Math","round","Number","paidAmountCents","Boolean","paymentIntentId","inPersonPayment","status","expiresAtMs","BOOKING_IN_PERSON_MAX_CENTS","BOOKING_IN_PERSON_MIN_CENTS","bookingInPersonAmountProblem","serviceCents","isInteger","bookingSuggestedCents","service","priceDisplay","cents","priceUsd","isFinite","bookingDayRange","atMs","offsetMinutes","getTimezoneOffset","local","dayStart","floor","startMs","endMs"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;2CAU2C,GAE3C,qEAAqE,GAuCrE,OAAO,SAASA,qBACdC,OAA6B,EAC7BC,QAAQC,KAAKC,GAAG,EAAE;QAGEH;QAElBA,0BASEA;IAZJ,IACEI,KAAKC,KAAK,CAACC,QAAON,2BAAAA,QAAQO,eAAe,YAAvBP,2BAA2B,MAAM,KACnDQ,QAAQR,QAAQS,eAAe,KAC/BT,EAAAA,2BAAAA,QAAQU,eAAe,qBAAvBV,yBAAyBW,MAAM,MAAK,QACpC;QACA,OAAO;IACT;IACA,IAAIX,QAAQW,MAAM,KAAK,YAAY,OAAO;IAC1C,IAAIX,QAAQW,MAAM,KAAK,kBAAkB;YAEzBX;QADd,oEAAoE;QACpE,OAAOM,QAAON,uBAAAA,QAAQY,WAAW,YAAnBZ,uBAAuB,KAAKC,QAAQ,aAAa;IACjE;IACA,IAAID,EAAAA,4BAAAA,QAAQU,eAAe,qBAAvBV,0BAAyBW,MAAM,MAAK,WAAW,OAAO;IAC1D,OAAO;AACT;AAEA,2DAA2D,GAC3D,OAAO,MAAME,8BAA8B,QAAS;AACpD,kCAAkC,GAClC,OAAO,MAAMC,8BAA8B,GAAE;AAE7C,+EAA+E,GAC/E,OAAO,SAASC,6BAA6BC,YAAqB;IAChE,IAAI,OAAOA,iBAAiB,YAAY,CAACV,OAAOW,SAAS,CAACD,eAAe;QACvE,OAAO;IACT;IACA,IAAIA,eAAeF,6BAA6B,OAAO;IACvD,IAAIE,eAAeH,6BAA6B,OAAO;IACvD,OAAO;AACT;AAEA;;;CAGC,GACD,OAAO,SAASK,sBAAsBC,OAGlB;QAGcA;IAFhC,IAAI,CAACA,SAAS,OAAO;IACrB,IAAIA,QAAQC,YAAY,IAAID,QAAQC,YAAY,KAAK,SAAS,OAAO;IACrE,MAAMC,QAAQjB,KAAKC,KAAK,CAACC,QAAOa,oBAAAA,QAAQG,QAAQ,YAAhBH,oBAAoB,KAAK;IACzD,OAAOb,OAAOiB,QAAQ,CAACF,UAAUA,SAASP,8BAA8BO,QAAQ;AAClF;AAEA,2EAA2E,GAC3E,OAAO,SAASG,gBAAgBC,IAAY,EAAEC,gBAAgB,IAAIxB,KAAKuB,MAAME,iBAAiB,EAAE;IAI9F,MAAMC,QAAQH,OAAOC,gBAAgB;IACrC,MAAMG,WAAWzB,KAAK0B,KAAK,CAACF,QAAQ,YAAc;IAClD,MAAMG,UAAUF,WAAWH,gBAAgB;IAC3C,OAAO;QAAEK;QAASC,OAAOD,UAAU;IAAW;AAChD"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/model/booking-in-person.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/*==========================================\n * TAKING PAYMENT FOR A BOOKING IN PERSON (AGL-3618).\n *\n * A booking whose price was not charged online (a free booking, or one whose\n * price `varies`, is an `estimate` or is `contact`) is paid at the counter\n * once the work is done: staff type the amount and the customer taps or\n * inserts a card on the register's reader. Pure: the server route, the\n * console and the native Aglyn POS app all read a booking through these.\n *\n * Imports nothing, so client and server code alike may import it.\n *=========================================*/\n\n/** The in-person payment a booking carries while it is being taken. */\nexport interface BookingInPersonPayment {\n paymentIntentId: string\n /** The whole charge: service plus tax. */\n amountCents: number\n /** The service amount staff typed, before tax. */\n serviceCents: number\n taxCents: number\n feeCents: number\n status: 'pending' | 'paid' | 'canceled'\n startedAtMs: number\n startedBy: string\n paidAtMs?: number\n /** Which start request made it, so a retried start returns it again. */\n attempt?: string\n /**\n * `direct` when the intent was made ON the store's own Stripe account\n * (`stripeAccountId`), where its capture, cancel and refund go. Absent for\n * a destination charge on the platform.\n */\n chargeModel?: 'direct'\n stripeAccountId?: string\n}\n\n/** The fields of a booking this reads; any booking document has them. */\nexport interface BookingPaymentFields {\n status?: string\n expiresAtMs?: number\n paidAmountCents?: number\n refundedCents?: number\n paymentIntentId?: string\n inPersonPayment?: Partial<BookingInPersonPayment> | null\n}\n\nexport type BookingInPersonState =\n /** Paid already, online or in person. */\n | 'paid'\n /** Canceled: nothing to pay. */\n | 'canceled'\n /** Still holding for its online Checkout: the customer is paying there. */\n | 'awaiting-online'\n /** A card is being taken for it now. */\n | 'collecting'\n /** Can be paid at the counter. */\n | 'payable'\n\nexport function bookingInPersonState(\n booking: BookingPaymentFields,\n nowMs = Date.now(),\n): BookingInPersonState {\n if (\n Math.round(Number(booking.paidAmountCents ?? 0)) > 0 ||\n Boolean(booking.paymentIntentId) ||\n booking.inPersonPayment?.status === 'paid'\n ) {\n return 'paid'\n }\n if (booking.status === 'canceled') return 'canceled'\n if (booking.status === 'pendingPayment') {\n // A lapsed online hold released its slot; it is not an appointment.\n return Number(booking.expiresAtMs ?? 0) < nowMs ? 'canceled' : 'awaiting-online'\n }\n if (booking.inPersonPayment?.status === 'pending') return 'collecting'\n return 'payable'\n}\n\n/** The most one in-person booking charge may be: $10,000. */\nexport const BOOKING_IN_PERSON_MAX_CENTS = 1_000_000\n/** Stripe's card minimum in USD. */\nexport const BOOKING_IN_PERSON_MIN_CENTS = 50\n\n/** Null when `serviceCents` is an amount staff may charge; otherwise why not. */\nexport function bookingInPersonAmountProblem(serviceCents: unknown): string | null {\n if (typeof serviceCents !== 'number' || !Number.isInteger(serviceCents)) {\n return 'Enter the amount to charge.'\n }\n if (serviceCents < BOOKING_IN_PERSON_MIN_CENTS) return 'Card payments start at $0.50.'\n if (serviceCents > BOOKING_IN_PERSON_MAX_CENTS) return 'Charge at most $10,000 at a time.'\n return null\n}\n\n/**\n * The amount to suggest: the service's fixed price, when it has one. A\n * `varies`, `estimate` or `contact` price suggests nothing; staff type it.\n */\nexport function bookingSuggestedCents(service: {\n priceUsd?: number\n priceDisplay?: string\n} | null | undefined): number | null {\n if (!service) return null\n if (service.priceDisplay && service.priceDisplay !== 'fixed') return null\n const cents = Math.round(Number(service.priceUsd ?? 0) * 100)\n return Number.isFinite(cents) && cents >= BOOKING_IN_PERSON_MIN_CENTS ? cents : null\n}\n\n/** The start and end of the local day that holds `atMs`, in milliseconds. */\nexport function bookingDayRange(atMs: number, offsetMinutes = new Date(atMs).getTimezoneOffset()): {\n startMs: number\n endMs: number\n} {\n const local = atMs - offsetMinutes * 60_000\n const dayStart = Math.floor(local / 86_400_000) * 86_400_000\n const startMs = dayStart + offsetMinutes * 60_000\n return { startMs, endMs: startMs + 86_400_000 }\n}\n"],"names":["bookingInPersonState","booking","nowMs","Date","now","Math","round","Number","paidAmountCents","Boolean","paymentIntentId","inPersonPayment","status","expiresAtMs","BOOKING_IN_PERSON_MAX_CENTS","BOOKING_IN_PERSON_MIN_CENTS","bookingInPersonAmountProblem","serviceCents","isInteger","bookingSuggestedCents","service","priceDisplay","cents","priceUsd","isFinite","bookingDayRange","atMs","offsetMinutes","getTimezoneOffset","local","dayStart","floor","startMs","endMs"],"mappings":"AAAA;;;;;;;;;;;;;;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UA,SAASP,8BAA8BO,QAAQ;AAClF;AAEA,2EAA2E,GAC3E,OAAO,SAASG,gBAAgBC,IAAY,EAAEC,gBAAgB,IAAIxB,KAAKuB,MAAME,iBAAiB,EAAE;IAI9F,MAAMC,QAAQH,OAAOC,gBAAgB;IACrC,MAAMG,WAAWzB,KAAK0B,KAAK,CAACF,QAAQ,YAAc;IAClD,MAAMG,UAAUF,WAAWH,gBAAgB;IAC3C,OAAO;QAAEK;QAASC,OAAOD,UAAU;IAAW;AAChD"}
@@ -17,6 +17,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
17
17
  */ import { createHash } from "crypto";
18
18
  import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
19
19
  import { merchantAccountIsReady } from "@aglyn/tenant-data-admin/server/payment-provider";
20
+ import { sellerPaymentAccount } from "@aglyn/tenant-data-admin/server/seller-payment-account";
20
21
  import { checkEntitlement, resolveTransactionFeeCents } from "@aglyn/aglyn/server";
21
22
  import { pluginTaxProfile } from "@aglyn/aglyn/plugin-manager/plugin-tax-profile";
22
23
  import { bookingInPersonAmountProblem, bookingInPersonState } from "../model/booking-in-person.js";
@@ -31,12 +32,16 @@ import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refus
31
32
  * owns the money; the app only presents the card:
32
33
  *
33
34
  * - `start` prices the charge (the amount staff typed, plus the merchant's
34
- * own service tax), and creates a card-present PaymentIntent: a
35
- * DESTINATION charge to the merchant, settled on Aglyn's platform account
36
- * with no `on_behalf_of` (ToS §10.7, AGL-3607), with the take and
37
- * Stripe's card cost as `application_fee_amount` — exactly the fee a paid
38
- * booking already carries online (`resolveTransactionFeeCents`, `service`).
39
- * Returns the intent's client secret for the app's Terminal SDK.
35
+ * own service tax), and creates a card-present PaymentIntent. For a
36
+ * destination store it is a DESTINATION charge to the merchant, settled on
37
+ * Aglyn's platform account with no `on_behalf_of` (ToS §10.7, AGL-3607),
38
+ * with the take and Stripe's card cost as `application_fee_amount`. For a
39
+ * store on its own Stripe account it is a DIRECT charge made ON that
40
+ * account (ToS v24 §10.2(a)), with the take alone as the application fee,
41
+ * where the app's Terminal SDK (whose connection token was minted on that
42
+ * account) collects it. Either way exactly the fee a paid booking carries
43
+ * online (`resolveTransactionFeeCents`, `service`). Returns the intent's
44
+ * client secret for the app's Terminal SDK.
40
45
  * - `settle` re-reads the intent from Stripe (never trusting the app's word),
41
46
  * captures an authorized one, and records the booking paid with the same
42
47
  * fields an online payment writes, so the console's refund and the dispute
@@ -82,6 +87,8 @@ async function stripe(method, path, options = {}) {
82
87
  'Content-Type': 'application/x-www-form-urlencoded'
83
88
  }, options.idempotencyKey ? {
84
89
  'Idempotency-Key': options.idempotencyKey
90
+ } : {}, options.stripeAccount ? {
91
+ 'Stripe-Account': options.stripeAccount
85
92
  } : {})
86
93
  }, method === 'POST' ? {
87
94
  body: form.toString()
@@ -200,19 +207,28 @@ export const bookingInPersonPaymentHandler = async (req, res)=>{
200
207
  function bookingRef(hostId, bookingId) {
201
208
  return firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('bookings').doc(bookingId);
202
209
  }
203
- async function merchantAccount(org, hostId) {
204
- var _ref, _profile_get;
205
- const ownerUid = String((_ref = org == null ? void 0 : org['ownerUid']) != null ? _ref : '');
206
- if (!ownerUid) return null;
207
- const profile = await firebaseAdmin.app().firestore().collection('profiles').doc(ownerUid).get();
208
- const accountId = String((_profile_get = profile.get('stripeAccountId')) != null ? _profile_get : '');
210
+ /**
211
+ * The store's selling account and how it sells, when it can take cards now.
212
+ * Read through `sellerPaymentAccount`, the one place that knows where the
213
+ * account is recorded.
214
+ */ async function merchantAccount(org, hostId) {
215
+ const seller = await sellerPaymentAccount(hostId, org);
216
+ if (!seller) return null;
209
217
  return merchantAccountIsReady({
210
- accountId,
211
- chargesEnabled: profile.get('stripeChargesEnabled'),
212
- accountLivemode: profile.get('stripeAccountLivemode')
218
+ accountId: seller.accountId,
219
+ chargesEnabled: seller.chargesEnabled,
220
+ accountLivemode: seller.accountLivemode
213
221
  }, {
214
222
  subject: `booking in-person host ${hostId}`
215
- }) ? accountId : null;
223
+ }) ? {
224
+ accountId: seller.accountId,
225
+ chargeModel: seller.chargeModel
226
+ } : null;
227
+ }
228
+ /** The account a recorded in-person payment's intent lives on; null for the platform. */ function paymentAccount(payment) {
229
+ var _ref;
230
+ const id = String((_ref = payment == null ? void 0 : payment.stripeAccountId) != null ? _ref : '').trim();
231
+ return (payment == null ? void 0 : payment.chargeModel) === 'direct' && id ? id : null;
216
232
  }
217
233
  async function start(staff, bookingId, body, req, res) {
218
234
  var _ref, _req_headers_idempotencykey, _booking_serviceName;
@@ -246,30 +262,38 @@ async function start(staff, bookingId, body, req, res) {
246
262
  error: 'The customer is paying for this booking online right now.'
247
263
  });
248
264
  }
249
- const destination = await merchantAccount(staff.org, staff.hostId);
250
- if (!destination) return res.status(409).json({
265
+ const merchant = await merchantAccount(staff.org, staff.hostId);
266
+ if (!merchant) return res.status(409).json({
251
267
  error: 'Finish setting up payments before taking cards.'
252
268
  });
269
+ const direct = merchant.chargeModel === 'direct';
270
+ const account = direct ? merchant.accountId : null;
253
271
  // The merchant's own service tax, off unless they set one (AGL-2028): the
254
272
  // same rate a paid booking is charged online.
255
273
  const tax = pluginTaxProfile().flatTax(await pluginTaxProfile().flatRate(staff.hostId, 'service'), serviceCents, 'Service tax');
256
274
  const amountCents = serviceCents + tax.taxCents;
257
275
  // A reader's card, priced at the in-person rate (AGL-4198).
258
- const feeCents = resolveTransactionFeeCents(staff.org, 'service', serviceCents, amountCents, {
276
+ // On the store's own account Stripe bills the store its card fee, so the
277
+ // fee is the take alone (`direct`), as on a direct online booking.
278
+ const feeCents = resolveTransactionFeeCents(staff.org, 'service', serviceCents, amountCents, _extends({
259
279
  inPerson: true
260
- });
280
+ }, direct ? {
281
+ direct: true
282
+ } : {}));
261
283
  // A pending intent for this booking that is not this attempt's: release it
262
284
  // first, so one booking never has two cards in flight.
263
285
  if ((existing == null ? void 0 : existing.status) === 'pending' && existing.paymentIntentId) {
264
286
  const sameAttempt = existing.attempt === attempt;
265
287
  if (sameAttempt) {
266
288
  var _replay_body;
267
- const replay = await stripe('GET', `payment_intents/${existing.paymentIntentId}`);
289
+ const replay = await stripe('GET', `payment_intents/${existing.paymentIntentId}`, {
290
+ stripeAccount: paymentAccount(existing)
291
+ });
268
292
  if (replay.ok && ((_replay_body = replay.body) == null ? void 0 : _replay_body.client_secret)) {
269
293
  return res.status(200).json(startAnswer(existing, String(replay.body.client_secret)));
270
294
  }
271
295
  } else {
272
- const released = await releaseIntent(existing.paymentIntentId);
296
+ const released = await releaseIntent(existing.paymentIntentId, paymentAccount(existing));
273
297
  if (!released) {
274
298
  return res.status(409).json({
275
299
  error: 'A card was already authorized for this booking. Settle it before starting another payment.'
@@ -278,15 +302,19 @@ async function start(staff, bookingId, body, req, res) {
278
302
  }
279
303
  }
280
304
  const intent = await stripe('POST', 'payment_intents', {
281
- idempotencyKey: `booking-in-person:${attempt}`,
305
+ idempotencyKey: direct ? `booking-in-person:${account}:${attempt}` : `booking-in-person:${attempt}`,
306
+ stripeAccount: account,
282
307
  params: _extends({
283
308
  amount: amountCents,
284
309
  currency: 'usd',
285
310
  'payment_method_types[]': 'card_present',
286
- capture_method: 'manual',
287
- 'transfer_data[destination]': destination
311
+ capture_method: 'manual'
312
+ }, direct ? {} : {
313
+ 'transfer_data[destination]': merchant.accountId
288
314
  }, feeCents > 0 ? {
289
315
  application_fee_amount: feeCents
316
+ } : {}, direct ? {
317
+ 'metadata[chargeModel]': 'direct'
290
318
  } : {}, {
291
319
  description: `Booking: ${String((_booking_serviceName = booking['serviceName']) != null ? _booking_serviceName : 'appointment').slice(0, 80)}`,
292
320
  'metadata[type]': 'booking-in-person',
@@ -304,7 +332,7 @@ async function start(staff, bookingId, body, req, res) {
304
332
  error: stripeMessage(intent.body, 'The card payment could not be started.')
305
333
  });
306
334
  }
307
- const payment = {
335
+ const payment = _extends({
308
336
  paymentIntentId: String(intent.body.id),
309
337
  amountCents,
310
338
  serviceCents,
@@ -314,7 +342,10 @@ async function start(staff, bookingId, body, req, res) {
314
342
  startedAtMs: Date.now(),
315
343
  startedBy: staff.uid,
316
344
  attempt
317
- };
345
+ }, direct ? {
346
+ chargeModel: 'direct',
347
+ stripeAccountId: merchant.accountId
348
+ } : {});
318
349
  // Recorded in a transaction that re-checks the booking: a payment that
319
350
  // landed meanwhile (online, or on another device) wins, and this intent is
320
351
  // released instead of left to authorize a second charge.
@@ -335,7 +366,7 @@ async function start(staff, bookingId, body, req, res) {
335
366
  return true;
336
367
  });
337
368
  if (!recorded) {
338
- await releaseIntent(payment.paymentIntentId);
369
+ await releaseIntent(payment.paymentIntentId, account);
339
370
  return res.status(409).json({
340
371
  error: 'This booking changed while the payment started. Open it again.'
341
372
  });
@@ -351,15 +382,18 @@ function startAnswer(payment, clientSecret) {
351
382
  taxCents: payment.taxCents
352
383
  };
353
384
  }
354
- /** Cancels an intent that holds no money yet; false when it does. */ async function releaseIntent(paymentIntentId) {
385
+ /** Cancels an intent that holds no money yet; false when it does. */ async function releaseIntent(paymentIntentId, account) {
355
386
  var _ref, _ref1;
356
387
  var _current_body, _canceled_body;
357
- const current = await stripe('GET', `payment_intents/${paymentIntentId}`);
388
+ const current = await stripe('GET', `payment_intents/${paymentIntentId}`, {
389
+ stripeAccount: account
390
+ });
358
391
  const status = String((_ref = (_current_body = current.body) == null ? void 0 : _current_body.status) != null ? _ref : '');
359
392
  if (status === 'canceled') return true;
360
393
  if (status === 'succeeded' || status === 'requires_capture' || status === 'processing') return false;
361
394
  const canceled = await stripe('POST', `payment_intents/${paymentIntentId}/cancel`, {
362
- idempotencyKey: `booking-in-person-cancel:${paymentIntentId}`
395
+ idempotencyKey: `booking-in-person-cancel:${paymentIntentId}`,
396
+ stripeAccount: account
363
397
  });
364
398
  return canceled.ok || String((_ref1 = (_canceled_body = canceled.body) == null ? void 0 : _canceled_body.status) != null ? _ref1 : '') === 'canceled';
365
399
  }
@@ -381,7 +415,11 @@ async function settle(staff, bookingId, res) {
381
415
  error: 'No card payment is in progress for this booking.'
382
416
  });
383
417
  }
384
- let intent = (await stripe('GET', `payment_intents/${payment.paymentIntentId}`)).body;
418
+ // The intent lives where it was made: the store's own account for a direct one.
419
+ const account = paymentAccount(payment);
420
+ let intent = (await stripe('GET', `payment_intents/${payment.paymentIntentId}`, {
421
+ stripeAccount: account
422
+ })).body;
385
423
  // The intent must be the one this route made for THIS booking on THIS site.
386
424
  if ((intent == null ? void 0 : (_intent_metadata = intent.metadata) == null ? void 0 : _intent_metadata.type) !== 'booking-in-person' || (intent == null ? void 0 : (_intent_metadata1 = intent.metadata) == null ? void 0 : _intent_metadata1.hostId) !== staff.hostId || (intent == null ? void 0 : (_intent_metadata2 = intent.metadata) == null ? void 0 : _intent_metadata2.bookingId) !== bookingId) {
387
425
  return res.status(409).json({
@@ -393,7 +431,8 @@ async function settle(staff, bookingId, res) {
393
431
  idempotencyKey: `booking-in-person-capture:${payment.paymentIntentId}`,
394
432
  params: payment.feeCents > 0 ? {
395
433
  application_fee_amount: payment.feeCents
396
- } : {}
434
+ } : {},
435
+ stripeAccount: account
397
436
  });
398
437
  if (!captured.ok) {
399
438
  return res.status(502).json({
@@ -433,7 +472,11 @@ async function settle(staff, bookingId, res) {
433
472
  }, payment.taxCents > 0 ? {
434
473
  taxCents: payment.taxCents
435
474
  } : {}, {
436
- paidInPerson: true,
475
+ paidInPerson: true
476
+ }, account ? {
477
+ chargeModel: 'direct',
478
+ stripeAccountId: account
479
+ } : {}, {
437
480
  inPersonPayment: _extends({}, payment, {
438
481
  status: 'paid',
439
482
  paidAtMs
@@ -457,7 +500,7 @@ async function cancel(staff, bookingId, res) {
457
500
  if (!payment || payment.status !== 'pending') return res.status(200).json({
458
501
  status: 'none'
459
502
  });
460
- if (!await releaseIntent(payment.paymentIntentId)) {
503
+ if (!await releaseIntent(payment.paymentIntentId, paymentAccount(payment))) {
461
504
  return res.status(409).json({
462
505
  error: 'The card was already authorized. Settle the payment instead.'
463
506
  });
@@ -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 // 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;;;;;;;;;;;;;;;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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QAAQ;WAC1DiB,QAAQjB,QAAQ,GAAG,IAAI;YAAEA,UAAUiB,QAAQjB,QAAQ;QAAC,IAAI,CAAC;YAC7D8C,cAAc;YACdjB,iBAAiB,aAAKZ;gBAAS7E,QAAQ;gBAAQuG;;YAEjD;YAAEb,OAAO;QAAK;IAElB;IACA,OAAOnE,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEG,QAAQ;QAAQ2D,aAAasC;IAAgB;AAC7E;AAEA,eAAenE,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,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"}
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 {\n merchantAccountIsReady,\n type SaleChargeModel,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { sellerPaymentAccount } from '@aglyn/tenant-data-admin/server/seller-payment-account'\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. For a\n * destination store it is a DESTINATION charge to the merchant, settled on\n * Aglyn's platform account with no `on_behalf_of` (ToS §10.7, AGL-3607),\n * with the take and Stripe's card cost as `application_fee_amount`. For a\n * store on its own Stripe account it is a DIRECT charge made ON that\n * account (ToS v24 §10.2(a)), with the take alone as the application fee,\n * where the app's Terminal SDK (whose connection token was minted on that\n * account) collects it. Either way exactly the fee a paid booking carries\n * online (`resolveTransactionFeeCents`, `service`). Returns the intent's\n * 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: {\n params?: Record<string, string | number | boolean | undefined>\n idempotencyKey?: string\n /** A direct-charge store's own account: the request is made ON it. */\n stripeAccount?: string | null\n } = {},\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 ...(options.stripeAccount ? { 'Stripe-Account': options.stripeAccount } : {}),\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\n/**\n * The store's selling account and how it sells, when it can take cards now.\n * Read through `sellerPaymentAccount`, the one place that knows where the\n * account is recorded.\n */\nasync function merchantAccount(\n org: Record<string, any> | null,\n hostId: string,\n): Promise<{ accountId: string; chargeModel: SaleChargeModel } | null> {\n const seller = await sellerPaymentAccount(hostId, org)\n if (!seller) return null\n return merchantAccountIsReady(\n {\n accountId: seller.accountId,\n chargesEnabled: seller.chargesEnabled,\n accountLivemode: seller.accountLivemode,\n },\n { subject: `booking in-person host ${hostId}` },\n )\n ? { accountId: seller.accountId, chargeModel: seller.chargeModel }\n : null\n}\n\n/** The account a recorded in-person payment's intent lives on; null for the platform. */\nfunction paymentAccount(payment: Partial<BookingInPersonPayment> | undefined): string | null {\n const id = String(payment?.stripeAccountId ?? '').trim()\n return payment?.chargeModel === 'direct' && id ? id : 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 merchant = await merchantAccount(staff.org, staff.hostId)\n if (!merchant) return res.status(409).json({ error: 'Finish setting up payments before taking cards.' })\n const direct = merchant.chargeModel === 'direct'\n const account = direct ? merchant.accountId : null\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 // On the store's own account Stripe bills the store its card fee, so the\n // fee is the take alone (`direct`), as on a direct online booking.\n const feeCents = resolveTransactionFeeCents(staff.org as never, 'service', serviceCents, amountCents, {\n inPerson: true,\n ...(direct ? { direct: 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 stripeAccount: paymentAccount(existing),\n })\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, paymentAccount(existing))\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: direct ? `booking-in-person:${account}:${attempt}` : `booking-in-person:${attempt}`,\n stripeAccount: account,\n params: {\n amount: amountCents,\n currency: 'usd',\n 'payment_method_types[]': 'card_present',\n capture_method: 'manual',\n // A direct charge is the store's money already: nothing is transferred.\n ...(direct ? {} : { 'transfer_data[destination]': merchant.accountId }),\n ...(feeCents > 0 ? { application_fee_amount: feeCents } : {}),\n ...(direct ? { 'metadata[chargeModel]': 'direct' } : {}),\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 ...(direct ? { chargeModel: 'direct' as const, stripeAccountId: merchant.accountId } : {}),\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, account)\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, account: string | null): Promise<boolean> {\n const current = await stripe('GET', `payment_intents/${paymentIntentId}`, { stripeAccount: account })\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 stripeAccount: account,\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 // The intent lives where it was made: the store's own account for a direct one.\n const account = paymentAccount(payment)\n let intent = (await stripe('GET', `payment_intents/${payment.paymentIntentId}`, { stripeAccount: account })).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 stripeAccount: account,\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 // Where the charge lives, as a direct online booking records it, so\n // the console's refund and the dispute branch act on the store's account.\n ...(account ? { chargeModel: 'direct', stripeAccountId: account } : {}),\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, paymentAccount(payment)))) {\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","sellerPaymentAccount","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","stripeAccount","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","seller","accountId","chargesEnabled","accountLivemode","subject","chargeModel","paymentAccount","payment","id","stripeAccountId","trim","booking","intent","attemptKey","serviceCents","NaN","problem","ref","snapshot","data","state","existing","attempt","update","digest","merchant","direct","account","tax","flatTax","flatRate","amountCents","taxCents","feeCents","inPerson","paymentIntentId","sameAttempt","replay","client_secret","startAnswer","released","releaseIntent","amount","currency","capture_method","application_fee_amount","description","pct","startedAtMs","Date","now","startedBy","recorded","runTransaction","transaction","fresh","freshState","freshPending","set","inPersonPayment","merge","clientSecret","current","canceled","metadata","type","captured","paidAmountCents","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;IAAO;IAC3F,IAAI,CAAE,MAAM2E,cAAclC,QAAQ4B,eAAe,EAAE7B,eAAeC,WAAY;QAC5E,OAAOlB,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;YAAEO,OAAO;QAA+D;IACtG;IACA,MAAM+C,IAAIyC,GAAG,CAAC;QAAEC,iBAAiB,aAAKpD;YAASzC,QAAQ;;IAAa,GAAG;QAAE8F,OAAO;IAAK;IACrF,OAAOvE,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEG,QAAQ;IAAW;AACnD"}
@@ -112,7 +112,7 @@ import { raiseBookingEvent } from "./booking-events.js";
112
112
  });
113
113
  }
114
114
  try {
115
- var _bookingSnapshot_data, _bookingSnapshot_get, _bookingSnapshot_get1, _bookingSnapshot_get2;
115
+ var _bookingSnapshot_data, _bookingSnapshot_get, _bookingSnapshot_get1, _bookingSnapshot_get2, _ref1;
116
116
  const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
117
117
  const firestore = firebaseAdmin.app().firestore();
118
118
  const hostRef = firestore.collection('hosts').doc(hostId);
@@ -243,19 +243,31 @@ import { raiseBookingEvent } from "./booking-events.js";
243
243
  // appointment earned the platform nothing.
244
244
  refund_application_fee: 'true'
245
245
  });
246
- const response = await fetch('https://api.stripe.com/v1/refunds', {
247
- method: 'POST',
248
- headers: _extends({
249
- Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
250
- 'Content-Type': 'application/x-www-form-urlencoded'
251
- }, claimRef ? {
252
- 'Idempotency-Key': claimRef.id
253
- } : {}, direct ? {
254
- 'Stripe-Account': chargeAccountId
255
- } : {}),
256
- body: params.toString()
257
- });
258
- const refund = await response.json().catch(()=>({}));
246
+ const send = (body, keySuffix = '')=>fetch('https://api.stripe.com/v1/refunds', {
247
+ method: 'POST',
248
+ headers: _extends({
249
+ Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
250
+ 'Content-Type': 'application/x-www-form-urlencoded'
251
+ }, claimRef ? {
252
+ 'Idempotency-Key': `${claimRef.id}${keySuffix}`
253
+ } : {}, direct ? {
254
+ 'Stripe-Account': chargeAccountId
255
+ } : {}),
256
+ body: body.toString()
257
+ });
258
+ let response = await send(params);
259
+ let refund = await response.json().catch(()=>({}));
260
+ // NO PLATFORM FEE ON THE CHARGE. A direct booking on a plan whose take is
261
+ // 0% carried no application fee, and Stripe refuses
262
+ // `refund_application_fee` on it. There is nothing of the platform's to
263
+ // hand back, so the same refund goes again without the flag, under its
264
+ // own key (a different request).
265
+ const noFee = refund == null ? void 0 : refund.error;
266
+ if (!response.ok && ((noFee == null ? void 0 : noFee.param) === 'refund_application_fee' || /no application fee to refund/i.test(String((_ref1 = noFee == null ? void 0 : noFee.message) != null ? _ref1 : '')))) {
267
+ params.delete('refund_application_fee');
268
+ response = await send(params, ':no-fee');
269
+ refund = await response.json().catch(()=>({}));
270
+ }
259
271
  if (!response.ok) {
260
272
  console.error('Stripe booking refund error', refund == null ? void 0 : refund.error);
261
273
  // Stripe said no, so we KNOW no money moved: give the reservation back
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/refund.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\n// Leaf import, not the barrel: the specs in this library mock\n// `@aglyn/tenant-data-admin` wholesale, and a permissive stub would turn a\n// reversal that never happened green.\nimport { reverseOrderConversion } from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { createHash } from 'crypto'\nimport { apiIdempotencyExpiry } from '@aglyn/aglyn/app-utils/api-idempotency'\nimport { bookingsSitePermissionRefusal } from '../model/bookings-permissions'\nimport { holdsBookingsSiteKey } from './bookings-site-keys'\nimport { raiseBookingEvent } from './booking-events'\n\n/**\n * Refund a paid booking (AGL-2315), full or partial, site-admin only.\n *\n * This route exists BECAUSE of the destination charge, not alongside it. While\n * a paid booking settled in Aglyn's own balance there was nothing here to get\n * wrong: cancelling a booking refunded the guest nothing at all, and any\n * refund issued by hand simply gave back money Aglyn was already holding. Once\n * the charge goes to the merchant's connected account that stops being true in\n * two directions at once, and both are money:\n *\n * - **The guest.** Cancelling a paid booking wrote `status: 'canceled'` from\n * the console and moved no money. The slot reopened, the appointment was\n * gone, and the guest had paid for it. That was survivable only because the\n * platform still held the funds and could be made to give them back; with\n * the money at the merchant it is a silent, unrecoverable overcharge.\n * - **Aglyn.** A refund on a destination charge that does NOT set\n * `reverse_transfer` is paid entirely out of the PLATFORM's balance while\n * the merchant keeps the transfer in full. The merchant cancels, the guest\n * is made whole, and Aglyn funds the whole concession out of a cut that was\n * at most 5% of it. This repo has shipped that exact bug once already, on a\n * marketplace partial refund.\n *\n * So both switches are sent, and they are two different decisions:\n *\n * - `reverse_transfer` pulls the refunded share back OUT of the merchant's\n * account. Stripe prorates it against a partial refund, so a $30 refund on\n * a $75 booking claws back $30 of the merchant's $71.25, not all of it.\n * - `refund_application_fee` returns Aglyn's commission on the refunded\n * share. A refunded appointment earned the platform nothing, and this\n * matches `commerce/refund.ts`, which has sent both since AGL-287. The\n * DISPUTE path deliberately sends only the reversal — that asymmetry is\n * AGL-1809's and is not copied here.\n *\n * Two SEPARATE controls guard the money, the AGL-1696 lesson from the order\n * refund, and conflating them is how that one originally went wrong:\n *\n * - The idempotency key stops a DUPLICATE refund — one attempt sent twice\n * because the response was lost or the admin double-clicked. It is minted\n * per attempt by the console and deliberately not derived from the booking\n * or the amount: two $10 refunds on a $75 booking are two real refunds.\n * - The cap stops an OVER-refund — several partials summing past what was\n * captured, including two admins refunding at once, where the attempts are\n * genuinely distinct and no key can help. That needs the counter read and\n * written inside one transaction, BEFORE Stripe is called, so a lost\n * response leaves the amount counted and the retry refunds less, never\n * more.\n *\n * A DIRECT-charge booking (`chargeModel: 'direct'`) was charged on the\n * seller's own account, so its refund is made there (`Stripe-Account`) and is\n * debited from the seller's balance. There is no transfer to reverse, so\n * `reverse_transfer` is never sent; `refund_application_fee` still is, for the\n * same reason as above.\n */\nexport const bookingRefundHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const bookingId = String(body.bookingId ?? '')\n // `null`/absent means \"everything still refundable\"; a number is a partial.\n const amountCents = body.amountCents == null ? null : Number(body.amountCents)\n // Node lowercases incoming headers, but read both spellings — the plugin API\n // request type makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n )\n .trim()\n .slice(0, 200)\n if (!hostId || !bookingId) {\n return res.status(400).json({ error: 'Missing hostId or bookingId' })\n }\n if (amountCents != null && !(Number.isFinite(amountCents) && amountCents > 0)) {\n return res.status(400).json({ error: 'Invalid refund amount' })\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // \"Refund bookings\" (AGL-4047), not merely a member: this moves money.\n // Its preset is the site Admin, the gate `commerce/refund.ts` applies.\n if (!holdsBookingsSiteKey(hostSnapshot, decoded.uid, 'bookings.refunds')) {\n return res.status(403).json({ error: bookingsSitePermissionRefusal('bookings.refunds') })\n }\n const bookingRef = hostRef.collection('bookings').doc(bookingId)\n const bookingSnapshot = await bookingRef.get()\n if (!bookingSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown booking' })\n }\n // As it stood before this refund, for the event a full refund raises.\n const bookingBefore = (bookingSnapshot.data() ?? {}) as Record<string, unknown>\n const paymentIntentId = String(bookingSnapshot.get('paymentIntentId') ?? '')\n const paidCents = Math.max(\n 0,\n Math.round(Number(bookingSnapshot.get('paidAmountCents') ?? 0)),\n )\n if (!paidCents) {\n return res.status(409).json({ error: 'This booking was never paid' })\n }\n if (!paymentIntentId) {\n // A booking paid BEFORE the webhook began recording the PaymentIntent\n // (AGL-2315). Refundable, but only by hand — and saying so beats a 500\n // an admin cannot act on.\n return res.status(409).json({\n error:\n 'This booking was paid before refunds were supported here. ' +\n 'Refund it in the Stripe dashboard, and tick “Reverse transfer” ' +\n 'so the amount comes back from the merchant account.',\n })\n }\n // Where the charge lives. A direct booking records the seller's account\n // when it is held; without it the refund would be sent to the platform,\n // where Stripe cannot find the payment, so refuse before reserving.\n const direct = bookingSnapshot.get('chargeModel') === 'direct'\n const chargeAccountId = direct\n ? String(bookingSnapshot.get('stripeAccountId') ?? '').trim()\n : ''\n if (direct && !chargeAccountId) {\n return res.status(409).json({\n error:\n 'This booking was paid on your Stripe account. ' +\n 'Refund it in your Stripe dashboard.',\n })\n }\n\n // Replay a settled attempt before anything else can reject it. This read\n // is only a short-circuit, never the dedupe primitive — the atomic\n // `create()` below is.\n const claimRef = idempotencyKey\n ? firestore.collection('apiIdempotency').doc(\n createHash('sha256')\n // Scoped by the BOOKING, so a client that reused one key across\n // two bookings cannot dedupe two legitimately distinct refunds.\n // NOT by the amount: that would swallow a real second partial.\n .update(`booking-refund:${hostId}:${bookingId}:${idempotencyKey}`)\n .digest('hex'),\n )\n : null\n if (claimRef) {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n try {\n // The claim's shape is every claim's (`claimApiIdempotency`): its\n // kind, scope and org name it on the staff claims list, `createdAtMs`\n // ages it there, and `expiresAt` lets the TTL policy reap it — a\n // claim stranded by a killed process otherwise holds its key forever.\n await claimRef.create({\n kind: 'booking-refund',\n scopeId: hostId,\n orgId: String(hostSnapshot.get('orgId') ?? '') || null,\n bookingId,\n status: 'pending',\n createdAtMs: Date.now(),\n expiresAt: apiIdempotencyExpiry(),\n })\n } catch {\n // Another attempt with this key is in flight.\n return res\n .status(409)\n .json({ error: 'This refund is already being processed' })\n }\n }\n\n // RESERVE. Read and write the counter in ONE transaction so two concurrent\n // refunds cannot both see the same `refundedCents` and each send a full\n // amount to Stripe — the failure the order refund shipped with.\n let refundCents = 0\n let alreadyRefunded = 0\n await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n alreadyRefunded = Math.max(\n 0,\n Math.round(Number(fresh.get('refundedCents') ?? 0)),\n )\n const remaining = paidCents - alreadyRefunded\n refundCents =\n amountCents == null\n ? remaining\n : Math.min(Math.round(amountCents), remaining)\n if (!(refundCents > 0)) {\n refundCents = 0\n return\n }\n transaction.set(\n bookingRef,\n { refundedCents: alreadyRefunded + refundCents },\n { merge: true },\n )\n })\n if (!(refundCents > 0)) {\n await claimRef?.delete().catch(() => undefined)\n return res.status(400).json({ error: 'Nothing left to refund' })\n }\n\n const params = direct\n ? new URLSearchParams({\n payment_intent: paymentIntentId,\n amount: String(refundCents),\n // The money is already the seller's, so the refund comes out of\n // their balance with no transfer to reverse. Aglyn's commission on\n // the refunded share still goes back to them.\n refund_application_fee: 'true',\n })\n : new URLSearchParams({\n payment_intent: paymentIntentId,\n amount: String(refundCents),\n // THE SELLER SHARE COMES BACK. Without this the merchant keeps their\n // transfer in full and Aglyn funds the entire refund.\n reverse_transfer: 'true',\n // ...and so does Aglyn's commission on the refunded share. A refunded\n // appointment earned the platform nothing.\n refund_application_fee: 'true',\n })\n const response = await fetch('https://api.stripe.com/v1/refunds', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(claimRef ? { 'Idempotency-Key': claimRef.id } : {}),\n // A direct booking's payment is on the seller's account.\n ...(direct ? { 'Stripe-Account': chargeAccountId } : {}),\n },\n body: params.toString(),\n })\n const refund = await response.json().catch(() => ({}) as any)\n if (!response.ok) {\n console.error('Stripe booking refund error', (refund as any)?.error)\n // Stripe said no, so we KNOW no money moved: give the reservation back\n // and let the same attempt be retried.\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(bookingRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n bookingRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claimRef?.delete().catch(() => undefined)\n return res.status(502).json({ error: 'Refund failed' })\n }\n\n // A FULL refund ends the appointment; a partial leaves it standing. The\n // guest who got half their money back still has the slot, and moving the\n // booking off `confirmed` would reopen a time the merchant is still\n // committed to.\n const totalRefunded = alreadyRefunded + refundCents\n const fullyRefunded = totalRefunded >= paidCents\n await bookingRef\n .set(\n {\n refundedCents: totalRefunded,\n ...(fullyRefunded ? { status: 'canceled' } : {}),\n },\n { merge: true },\n )\n .catch(() => undefined)\n // The full refund is what cancels a paid booking (AGL-3643). Keyed by the\n // booking, so a booking canceled before is not announced again.\n if (fullyRefunded && bookingBefore['status'] !== 'canceled') {\n await raiseBookingEvent(firestore, {\n event: 'booking.canceled',\n hostId,\n bookingId,\n booking: {\n ...bookingBefore,\n refundedCents: totalRefunded,\n status: 'canceled',\n },\n })\n }\n\n const payload = {\n refundedCents: refundCents,\n totalRefundedCents: totalRefunded,\n fullyRefunded,\n }\n await claimRef\n ?.set(\n {\n status: 'done',\n responseStatus: 200,\n response: payload,\n settledAtMs: Date.now(),\n },\n { merge: true },\n )\n .catch(() => undefined)\n /*\n * The campaign's side of the ledger.\n *\n * A paid booking is credited to the campaign that led to it — the sale\n * announces itself through `upsertHostContact` with a `purchaseCents` and\n * this booking's id, exactly as a store order does — so a refunded one\n * has to stop counting. Without this, a booking site's campaign revenue\n * could only ever rise.\n *\n * Keyed by the BOOKING id, which is what the credit was filed under, so\n * this needs no email and works for a guest who never became a contact.\n * Recorded beside the credit rather than subtracted from it, and swallowed\n * whole: the money has already left the merchant's account and the booking\n * already records it, so nothing here may fail a refund.\n */\n await reverseOrderConversion({\n hostId,\n orderId: bookingId,\n amountCents: refundCents,\n closedTheOrder: fullyRefunded,\n })\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Refund failed' })\n }\n}\n"],"names":["firebaseAdmin","reverseOrderConversion","createHash","apiIdempotencyExpiry","bookingsSitePermissionRefusal","holdsBookingsSiteKey","raiseBookingEvent","bookingRefundHandler","req","res","body","method","status","json","error","process","env","STRIPE_SECRET_KEY","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","bookingId","amountCents","Number","idempotencyKey","trim","isFinite","bookingSnapshot","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","bookingRef","bookingBefore","data","paymentIntentId","paidCents","Math","max","round","direct","chargeAccountId","claimRef","update","digest","prior","priorResponse","create","kind","scopeId","orgId","createdAtMs","Date","now","expiresAt","refundCents","alreadyRefunded","runTransaction","transaction","fresh","remaining","min","set","refundedCents","merge","delete","catch","params","URLSearchParams","payment_intent","amount","refund_application_fee","reverse_transfer","response","fetch","Authorization","id","toString","refund","ok","console","current","totalRefunded","fullyRefunded","event","booking","payload","totalRefundedCents","responseStatus","settledAtMs","orderId","closedTheOrder"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa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,EAAE,OAAOxF,OAAO;QACdkF,QAAQlF,KAAK,CAACA;QACd,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAgB;IACvD;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/refund.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\n// Leaf import, not the barrel: the specs in this library mock\n// `@aglyn/tenant-data-admin` wholesale, and a permissive stub would turn a\n// reversal that never happened green.\nimport { reverseOrderConversion } from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { createHash } from 'crypto'\nimport { apiIdempotencyExpiry } from '@aglyn/aglyn/app-utils/api-idempotency'\nimport { bookingsSitePermissionRefusal } from '../model/bookings-permissions'\nimport { holdsBookingsSiteKey } from './bookings-site-keys'\nimport { raiseBookingEvent } from './booking-events'\n\n/**\n * Refund a paid booking (AGL-2315), full or partial, site-admin only.\n *\n * This route exists BECAUSE of the destination charge, not alongside it. While\n * a paid booking settled in Aglyn's own balance there was nothing here to get\n * wrong: cancelling a booking refunded the guest nothing at all, and any\n * refund issued by hand simply gave back money Aglyn was already holding. Once\n * the charge goes to the merchant's connected account that stops being true in\n * two directions at once, and both are money:\n *\n * - **The guest.** Cancelling a paid booking wrote `status: 'canceled'` from\n * the console and moved no money. The slot reopened, the appointment was\n * gone, and the guest had paid for it. That was survivable only because the\n * platform still held the funds and could be made to give them back; with\n * the money at the merchant it is a silent, unrecoverable overcharge.\n * - **Aglyn.** A refund on a destination charge that does NOT set\n * `reverse_transfer` is paid entirely out of the PLATFORM's balance while\n * the merchant keeps the transfer in full. The merchant cancels, the guest\n * is made whole, and Aglyn funds the whole concession out of a cut that was\n * at most 5% of it. This repo has shipped that exact bug once already, on a\n * marketplace partial refund.\n *\n * So both switches are sent, and they are two different decisions:\n *\n * - `reverse_transfer` pulls the refunded share back OUT of the merchant's\n * account. Stripe prorates it against a partial refund, so a $30 refund on\n * a $75 booking claws back $30 of the merchant's $71.25, not all of it.\n * - `refund_application_fee` returns Aglyn's commission on the refunded\n * share. A refunded appointment earned the platform nothing, and this\n * matches `commerce/refund.ts`, which has sent both since AGL-287. The\n * DISPUTE path deliberately sends only the reversal — that asymmetry is\n * AGL-1809's and is not copied here.\n *\n * Two SEPARATE controls guard the money, the AGL-1696 lesson from the order\n * refund, and conflating them is how that one originally went wrong:\n *\n * - The idempotency key stops a DUPLICATE refund — one attempt sent twice\n * because the response was lost or the admin double-clicked. It is minted\n * per attempt by the console and deliberately not derived from the booking\n * or the amount: two $10 refunds on a $75 booking are two real refunds.\n * - The cap stops an OVER-refund — several partials summing past what was\n * captured, including two admins refunding at once, where the attempts are\n * genuinely distinct and no key can help. That needs the counter read and\n * written inside one transaction, BEFORE Stripe is called, so a lost\n * response leaves the amount counted and the retry refunds less, never\n * more.\n *\n * A DIRECT-charge booking (`chargeModel: 'direct'`) was charged on the\n * seller's own account, so its refund is made there (`Stripe-Account`) and is\n * debited from the seller's balance. There is no transfer to reverse, so\n * `reverse_transfer` is never sent; `refund_application_fee` still is, for the\n * same reason as above.\n */\nexport const bookingRefundHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const bookingId = String(body.bookingId ?? '')\n // `null`/absent means \"everything still refundable\"; a number is a partial.\n const amountCents = body.amountCents == null ? null : Number(body.amountCents)\n // Node lowercases incoming headers, but read both spellings — the plugin API\n // request type makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n )\n .trim()\n .slice(0, 200)\n if (!hostId || !bookingId) {\n return res.status(400).json({ error: 'Missing hostId or bookingId' })\n }\n if (\n amountCents != null &&\n !(Number.isFinite(amountCents) && amountCents > 0)\n ) {\n return res.status(400).json({ error: 'Invalid refund amount' })\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // \"Refund bookings\" (AGL-4047), not merely a member: this moves money.\n // Its preset is the site Admin, the gate `commerce/refund.ts` applies.\n if (!holdsBookingsSiteKey(hostSnapshot, decoded.uid, 'bookings.refunds')) {\n return res\n .status(403)\n .json({ error: bookingsSitePermissionRefusal('bookings.refunds') })\n }\n const bookingRef = hostRef.collection('bookings').doc(bookingId)\n const bookingSnapshot = await bookingRef.get()\n if (!bookingSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown booking' })\n }\n // As it stood before this refund, for the event a full refund raises.\n const bookingBefore = (bookingSnapshot.data() ?? {}) as Record<\n string,\n unknown\n >\n const paymentIntentId = String(bookingSnapshot.get('paymentIntentId') ?? '')\n const paidCents = Math.max(\n 0,\n Math.round(Number(bookingSnapshot.get('paidAmountCents') ?? 0)),\n )\n if (!paidCents) {\n return res.status(409).json({ error: 'This booking was never paid' })\n }\n if (!paymentIntentId) {\n // A booking paid BEFORE the webhook began recording the PaymentIntent\n // (AGL-2315). Refundable, but only by hand — and saying so beats a 500\n // an admin cannot act on.\n return res.status(409).json({\n error:\n 'This booking was paid before refunds were supported here. ' +\n 'Refund it in the Stripe dashboard, and tick “Reverse transfer” ' +\n 'so the amount comes back from the merchant account.',\n })\n }\n // Where the charge lives. A direct booking records the seller's account\n // when it is held; without it the refund would be sent to the platform,\n // where Stripe cannot find the payment, so refuse before reserving.\n const direct = bookingSnapshot.get('chargeModel') === 'direct'\n const chargeAccountId = direct\n ? String(bookingSnapshot.get('stripeAccountId') ?? '').trim()\n : ''\n if (direct && !chargeAccountId) {\n return res.status(409).json({\n error:\n 'This booking was paid on your Stripe account. ' +\n 'Refund it in your Stripe dashboard.',\n })\n }\n\n // Replay a settled attempt before anything else can reject it. This read\n // is only a short-circuit, never the dedupe primitive — the atomic\n // `create()` below is.\n const claimRef = idempotencyKey\n ? firestore.collection('apiIdempotency').doc(\n createHash('sha256')\n // Scoped by the BOOKING, so a client that reused one key across\n // two bookings cannot dedupe two legitimately distinct refunds.\n // NOT by the amount: that would swallow a real second partial.\n .update(`booking-refund:${hostId}:${bookingId}:${idempotencyKey}`)\n .digest('hex'),\n )\n : null\n if (claimRef) {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n try {\n // The claim's shape is every claim's (`claimApiIdempotency`): its\n // kind, scope and org name it on the staff claims list, `createdAtMs`\n // ages it there, and `expiresAt` lets the TTL policy reap it — a\n // claim stranded by a killed process otherwise holds its key forever.\n await claimRef.create({\n kind: 'booking-refund',\n scopeId: hostId,\n orgId: String(hostSnapshot.get('orgId') ?? '') || null,\n bookingId,\n status: 'pending',\n createdAtMs: Date.now(),\n expiresAt: apiIdempotencyExpiry(),\n })\n } catch {\n // Another attempt with this key is in flight.\n return res\n .status(409)\n .json({ error: 'This refund is already being processed' })\n }\n }\n\n // RESERVE. Read and write the counter in ONE transaction so two concurrent\n // refunds cannot both see the same `refundedCents` and each send a full\n // amount to Stripe — the failure the order refund shipped with.\n let refundCents = 0\n let alreadyRefunded = 0\n await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n alreadyRefunded = Math.max(\n 0,\n Math.round(Number(fresh.get('refundedCents') ?? 0)),\n )\n const remaining = paidCents - alreadyRefunded\n refundCents =\n amountCents == null\n ? remaining\n : Math.min(Math.round(amountCents), remaining)\n if (!(refundCents > 0)) {\n refundCents = 0\n return\n }\n transaction.set(\n bookingRef,\n { refundedCents: alreadyRefunded + refundCents },\n { merge: true },\n )\n })\n if (!(refundCents > 0)) {\n await claimRef?.delete().catch(() => undefined)\n return res.status(400).json({ error: 'Nothing left to refund' })\n }\n\n const params = direct\n ? new URLSearchParams({\n payment_intent: paymentIntentId,\n amount: String(refundCents),\n // The money is already the seller's, so the refund comes out of\n // their balance with no transfer to reverse. Aglyn's commission on\n // the refunded share still goes back to them.\n refund_application_fee: 'true',\n })\n : new URLSearchParams({\n payment_intent: paymentIntentId,\n amount: String(refundCents),\n // THE SELLER SHARE COMES BACK. Without this the merchant keeps their\n // transfer in full and Aglyn funds the entire refund.\n reverse_transfer: 'true',\n // ...and so does Aglyn's commission on the refunded share. A refunded\n // appointment earned the platform nothing.\n refund_application_fee: 'true',\n })\n const send = (body: URLSearchParams, keySuffix = '') =>\n fetch('https://api.stripe.com/v1/refunds', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(claimRef\n ? { 'Idempotency-Key': `${claimRef.id}${keySuffix}` }\n : {}),\n // A direct booking's payment is on the seller's account.\n ...(direct ? { 'Stripe-Account': chargeAccountId } : {}),\n },\n body: body.toString(),\n })\n let response = await send(params)\n let refund = await response.json().catch(() => ({}) as any)\n // NO PLATFORM FEE ON THE CHARGE. A direct booking on a plan whose take is\n // 0% carried no application fee, and Stripe refuses\n // `refund_application_fee` on it. There is nothing of the platform's to\n // hand back, so the same refund goes again without the flag, under its\n // own key (a different request).\n const noFee = (refund as any)?.error\n if (\n !response.ok &&\n (noFee?.param === 'refund_application_fee' ||\n /no application fee to refund/i.test(String(noFee?.message ?? '')))\n ) {\n params.delete('refund_application_fee')\n response = await send(params, ':no-fee')\n refund = await response.json().catch(() => ({}) as any)\n }\n if (!response.ok) {\n console.error('Stripe booking refund error', (refund as any)?.error)\n // Stripe said no, so we KNOW no money moved: give the reservation back\n // and let the same attempt be retried.\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(bookingRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n bookingRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claimRef?.delete().catch(() => undefined)\n return res.status(502).json({ error: 'Refund failed' })\n }\n\n // A FULL refund ends the appointment; a partial leaves it standing. The\n // guest who got half their money back still has the slot, and moving the\n // booking off `confirmed` would reopen a time the merchant is still\n // committed to.\n const totalRefunded = alreadyRefunded + refundCents\n const fullyRefunded = totalRefunded >= paidCents\n await bookingRef\n .set(\n {\n refundedCents: totalRefunded,\n ...(fullyRefunded ? { status: 'canceled' } : {}),\n },\n { merge: true },\n )\n .catch(() => undefined)\n // The full refund is what cancels a paid booking (AGL-3643). Keyed by the\n // booking, so a booking canceled before is not announced again.\n if (fullyRefunded && bookingBefore['status'] !== 'canceled') {\n await raiseBookingEvent(firestore, {\n event: 'booking.canceled',\n hostId,\n bookingId,\n booking: {\n ...bookingBefore,\n refundedCents: totalRefunded,\n status: 'canceled',\n },\n })\n }\n\n const payload = {\n refundedCents: refundCents,\n totalRefundedCents: totalRefunded,\n fullyRefunded,\n }\n await claimRef\n ?.set(\n {\n status: 'done',\n responseStatus: 200,\n response: payload,\n settledAtMs: Date.now(),\n },\n { merge: true },\n )\n .catch(() => undefined)\n /*\n * The campaign's side of the ledger.\n *\n * A paid booking is credited to the campaign that led to it — the sale\n * announces itself through `upsertHostContact` with a `purchaseCents` and\n * this booking's id, exactly as a store order does — so a refunded one\n * has to stop counting. Without this, a booking site's campaign revenue\n * could only ever rise.\n *\n * Keyed by the BOOKING id, which is what the credit was filed under, so\n * this needs no email and works for a guest who never became a contact.\n * Recorded beside the credit rather than subtracted from it, and swallowed\n * whole: the money has already left the merchant's account and the booking\n * already records it, so nothing here may fail a refund.\n */\n await reverseOrderConversion({\n hostId,\n orderId: bookingId,\n amountCents: refundCents,\n closedTheOrder: fullyRefunded,\n })\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Refund failed' })\n }\n}\n"],"names":["firebaseAdmin","reverseOrderConversion","createHash","apiIdempotencyExpiry","bookingsSitePermissionRefusal","holdsBookingsSiteKey","raiseBookingEvent","bookingRefundHandler","req","res","body","method","status","json","error","process","env","STRIPE_SECRET_KEY","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","bookingId","amountCents","Number","idempotencyKey","trim","isFinite","bookingSnapshot","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","bookingRef","bookingBefore","data","paymentIntentId","paidCents","Math","max","round","direct","chargeAccountId","claimRef","update","digest","prior","priorResponse","create","kind","scopeId","orgId","createdAtMs","Date","now","expiresAt","refundCents","alreadyRefunded","runTransaction","transaction","fresh","remaining","min","set","refundedCents","merge","delete","catch","params","URLSearchParams","payment_intent","amount","refund_application_fee","reverse_transfer","send","keySuffix","fetch","Authorization","id","toString","response","refund","noFee","ok","param","test","message","console","current","totalRefunded","fullyRefunded","event","booking","payload","totalRefundedCents","responseStatus","settledAtMs","orderId","closedTheOrder"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AAExD,8DAA8D;AAC9D,2EAA2E;AAC3E,sCAAsC;AACtC,SAASC,sBAAsB,QAAQ,uDAAsD;AAC7F,SAASC,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