@aglyn/plugins-bookings 1.23.1 → 1.25.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.23.1",
3
+ "version": "1.25.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.23.1",
29
- "@aglyn/shared-data-mdi": "1.23.1",
30
- "@aglyn/shared-ui-jsx": "1.23.1",
31
- "@aglyn/shared-ui-snackstack": "1.23.1",
32
- "@aglyn/shared-util-email": "1.23.1",
33
- "@aglyn/shared-util-http": "1.23.1",
34
- "@aglyn/shared-util-timestamp": "1.23.1",
35
- "@aglyn/tenant-data-admin": "1.23.1",
36
- "@aglyn/tenant-feature-instance": "1.23.1",
37
- "@aglyn/tenant-runtime": "1.23.1",
28
+ "@aglyn/aglyn": "1.25.0",
29
+ "@aglyn/shared-data-mdi": "1.25.0",
30
+ "@aglyn/shared-ui-jsx": "1.25.0",
31
+ "@aglyn/shared-ui-snackstack": "1.25.0",
32
+ "@aglyn/shared-util-email": "1.25.0",
33
+ "@aglyn/shared-util-http": "1.25.0",
34
+ "@aglyn/shared-util-timestamp": "1.25.0",
35
+ "@aglyn/tenant-data-admin": "1.25.0",
36
+ "@aglyn/tenant-feature-instance": "1.25.0",
37
+ "@aglyn/tenant-runtime": "1.25.0",
38
38
  "@swc/helpers": "0.5.24"
39
39
  },
40
40
  "peerDependencies": {
@@ -13,7 +13,7 @@
13
13
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
- */ import { booleanField as bool, integerField as int, isoField as iso, nullableField as nullable, objectKindField as OBJECT_FIELD, queryParam as q, stringField as str } from "@aglyn/tenant-data-admin/server/api-v1-description";
16
+ */ import { booleanField as bool, integerField as int, isoField as iso, nullableField as nullable, objectKindField as OBJECT_FIELD, queryParam as q, stringField as str, SITE_ID_PATH_PARAM } from "@aglyn/tenant-data-admin/server/api-v1-description";
17
17
  /**
18
18
  * A site's bookings as the customer API's OpenAPI document describes them
19
19
  * (AGL-3643), in the shape `apps/docs/api/resources/bookings.md` documents.
@@ -78,10 +78,7 @@
78
78
  q('serviceId', 'Bookings of one service.')
79
79
  ],
80
80
  pathParams: [
81
- {
82
- name: 'siteId',
83
- description: 'Site id.'
84
- }
81
+ SITE_ID_PATH_PARAM
85
82
  ]
86
83
  },
87
84
  {
@@ -91,10 +88,7 @@
91
88
  summary: 'Retrieve a booking',
92
89
  returns: 'Booking',
93
90
  pathParams: [
94
- {
95
- name: 'siteId',
96
- description: 'Site id.'
97
- },
91
+ SITE_ID_PATH_PARAM,
98
92
  {
99
93
  name: 'bookingId',
100
94
  description: 'Booking id.'
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/bookings/src/lib/server/api-v1/openapi.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 {\n type ApiV1ResourceDescription,\n booleanField as bool,\n integerField as int,\n isoField as iso,\n nullableField as nullable,\n objectKindField as OBJECT_FIELD,\n queryParam as q,\n stringField as str,\n} from '@aglyn/tenant-data-admin/server/api-v1-description'\n\n/**\n * A site's bookings as the customer API's OpenAPI document describes them\n * (AGL-3643), in the shape `apps/docs/api/resources/bookings.md` documents.\n */\nexport const BOOKINGS_API_V1_DESCRIPTION: ApiV1ResourceDescription = {\n tag: 'Bookings',\n description: 'A site’s bookings. Read-only over the API.',\n schemaName: 'Booking',\n required: ['id', 'object', 'status'],\n fields: {\n id: str('Booking id.'),\n object: OBJECT_FIELD('booking'),\n serviceId: nullable(str('The booked service.')),\n serviceName: nullable(str('The service’s name when it was booked.')),\n status: {\n type: 'string',\n enum: ['confirmed', 'pendingPayment', 'expired', 'canceled'],\n description:\n '`pendingPayment` is a paid booking whose checkout is still open; `expired` is one whose checkout ran out, and its slot was released.',\n },\n name: nullable(str('The guest’s name.')),\n email: nullable(str('The guest’s email address.')),\n phone: nullable(str('The guest’s phone number, when the service asked for one.')),\n address: {\n type: ['object', 'string', 'null'],\n description: 'The address the service is at, when the service asked for one: the guest’s address parts, or the line they typed.',\n additionalProperties: true,\n },\n startsAt: nullable(iso('When the booking starts, UTC.')),\n endsAt: nullable(iso('When the booking ends, UTC.')),\n timeZone: nullable(str('The IANA time zone the booking was made in.')),\n currency: str('Always `usd`.'),\n paidCents: int('What the guest paid, tax included; 0 for a free booking.'),\n taxCents: int('The tax inside `paidCents`.'),\n refundedCents: int('Refunded so far.'),\n checkedIn: bool('Whether the guest was checked in.'),\n checkedInAt: nullable(iso('When the guest was checked in.')),\n rescheduledFrom: nullable(iso('Where a moved booking started before its latest move.')),\n created: nullable(iso('When the booking was made.')),\n },\n ops: [\n {\n path: '/v1/sites/{siteId}/bookings',\n method: 'get',\n operationId: 'listBookings',\n summary: 'List bookings',\n list: true,\n returns: 'Booking',\n filters: [\n q('status', '`confirmed`, `pendingPayment` or `canceled`. An expired checkout is stored as `pendingPayment`.'),\n q('serviceId', 'Bookings of one service.'),\n ],\n pathParams: [{ name: 'siteId', description: 'Site id.' }],\n },\n {\n path: '/v1/sites/{siteId}/bookings/{bookingId}',\n method: 'get',\n operationId: 'getBooking',\n summary: 'Retrieve a booking',\n returns: 'Booking',\n pathParams: [\n { name: 'siteId', description: 'Site id.' },\n { name: 'bookingId', description: 'Booking id.' },\n ],\n },\n ],\n}\n"],"names":["booleanField","bool","integerField","int","isoField","iso","nullableField","nullable","objectKindField","OBJECT_FIELD","queryParam","q","stringField","str","BOOKINGS_API_V1_DESCRIPTION","tag","description","schemaName","required","fields","id","object","serviceId","serviceName","status","type","enum","name","email","phone","address","additionalProperties","startsAt","endsAt","timeZone","currency","paidCents","taxCents","refundedCents","checkedIn","checkedInAt","rescheduledFrom","created","ops","path","method","operationId","summary","list","returns","filters","pathParams"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,gBAAgBC,IAAI,EACpBC,gBAAgBC,GAAG,EACnBC,YAAYC,GAAG,EACfC,iBAAiBC,QAAQ,EACzBC,mBAAmBC,YAAY,EAC/BC,cAAcC,CAAC,EACfC,eAAeC,GAAG,QACb,qDAAoD;AAE3D;;;CAGC,GACD,OAAO,MAAMC,8BAAwD;IACnEC,KAAK;IACLC,aAAa;IACbC,YAAY;IACZC,UAAU;QAAC;QAAM;QAAU;KAAS;IACpCC,QAAQ;QACNC,IAAIP,IAAI;QACRQ,QAAQZ,aAAa;QACrBa,WAAWf,SAASM,IAAI;QACxBU,aAAahB,SAASM,IAAI;QAC1BW,QAAQ;YACNC,MAAM;YACNC,MAAM;gBAAC;gBAAa;gBAAkB;gBAAW;aAAW;YAC5DV,aACE;QACJ;QACAW,MAAMpB,SAASM,IAAI;QACnBe,OAAOrB,SAASM,IAAI;QACpBgB,OAAOtB,SAASM,IAAI;QACpBiB,SAAS;YACPL,MAAM;gBAAC;gBAAU;gBAAU;aAAO;YAClCT,aAAa;YACbe,sBAAsB;QACxB;QACAC,UAAUzB,SAASF,IAAI;QACvB4B,QAAQ1B,SAASF,IAAI;QACrB6B,UAAU3B,SAASM,IAAI;QACvBsB,UAAUtB,IAAI;QACduB,WAAWjC,IAAI;QACfkC,UAAUlC,IAAI;QACdmC,eAAenC,IAAI;QACnBoC,WAAWtC,KAAK;QAChBuC,aAAajC,SAASF,IAAI;QAC1BoC,iBAAiBlC,SAASF,IAAI;QAC9BqC,SAASnC,SAASF,IAAI;IACxB;IACAsC,KAAK;QACH;YACEC,MAAM;YACNC,QAAQ;YACRC,aAAa;YACbC,SAAS;YACTC,MAAM;YACNC,SAAS;YACTC,SAAS;gBACPvC,EAAE,UAAU;gBACZA,EAAE,aAAa;aAChB;YACDwC,YAAY;gBAAC;oBAAExB,MAAM;oBAAUX,aAAa;gBAAW;aAAE;QAC3D;QACA;YACE4B,MAAM;YACNC,QAAQ;YACRC,aAAa;YACbC,SAAS;YACTE,SAAS;YACTE,YAAY;gBACV;oBAAExB,MAAM;oBAAUX,aAAa;gBAAW;gBAC1C;oBAAEW,MAAM;oBAAaX,aAAa;gBAAc;aACjD;QACH;KACD;AACH,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/bookings/src/lib/server/api-v1/openapi.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 {\n type ApiV1ResourceDescription,\n booleanField as bool,\n integerField as int,\n isoField as iso,\n nullableField as nullable,\n objectKindField as OBJECT_FIELD,\n queryParam as q,\n stringField as str,\n SITE_ID_PATH_PARAM,\n} from '@aglyn/tenant-data-admin/server/api-v1-description'\n\n/**\n * A site's bookings as the customer API's OpenAPI document describes them\n * (AGL-3643), in the shape `apps/docs/api/resources/bookings.md` documents.\n */\nexport const BOOKINGS_API_V1_DESCRIPTION: ApiV1ResourceDescription = {\n tag: 'Bookings',\n description: 'A site’s bookings. Read-only over the API.',\n schemaName: 'Booking',\n required: ['id', 'object', 'status'],\n fields: {\n id: str('Booking id.'),\n object: OBJECT_FIELD('booking'),\n serviceId: nullable(str('The booked service.')),\n serviceName: nullable(str('The service’s name when it was booked.')),\n status: {\n type: 'string',\n enum: ['confirmed', 'pendingPayment', 'expired', 'canceled'],\n description:\n '`pendingPayment` is a paid booking whose checkout is still open; `expired` is one whose checkout ran out, and its slot was released.',\n },\n name: nullable(str('The guest’s name.')),\n email: nullable(str('The guest’s email address.')),\n phone: nullable(str('The guest’s phone number, when the service asked for one.')),\n address: {\n type: ['object', 'string', 'null'],\n description: 'The address the service is at, when the service asked for one: the guest’s address parts, or the line they typed.',\n additionalProperties: true,\n },\n startsAt: nullable(iso('When the booking starts, UTC.')),\n endsAt: nullable(iso('When the booking ends, UTC.')),\n timeZone: nullable(str('The IANA time zone the booking was made in.')),\n currency: str('Always `usd`.'),\n paidCents: int('What the guest paid, tax included; 0 for a free booking.'),\n taxCents: int('The tax inside `paidCents`.'),\n refundedCents: int('Refunded so far.'),\n checkedIn: bool('Whether the guest was checked in.'),\n checkedInAt: nullable(iso('When the guest was checked in.')),\n rescheduledFrom: nullable(iso('Where a moved booking started before its latest move.')),\n created: nullable(iso('When the booking was made.')),\n },\n ops: [\n {\n path: '/v1/sites/{siteId}/bookings',\n method: 'get',\n operationId: 'listBookings',\n summary: 'List bookings',\n list: true,\n returns: 'Booking',\n filters: [\n q('status', '`confirmed`, `pendingPayment` or `canceled`. An expired checkout is stored as `pendingPayment`.'),\n q('serviceId', 'Bookings of one service.'),\n ],\n pathParams: [SITE_ID_PATH_PARAM],\n },\n {\n path: '/v1/sites/{siteId}/bookings/{bookingId}',\n method: 'get',\n operationId: 'getBooking',\n summary: 'Retrieve a booking',\n returns: 'Booking',\n pathParams: [\n SITE_ID_PATH_PARAM,\n { name: 'bookingId', description: 'Booking id.' },\n ],\n },\n ],\n}\n"],"names":["booleanField","bool","integerField","int","isoField","iso","nullableField","nullable","objectKindField","OBJECT_FIELD","queryParam","q","stringField","str","SITE_ID_PATH_PARAM","BOOKINGS_API_V1_DESCRIPTION","tag","description","schemaName","required","fields","id","object","serviceId","serviceName","status","type","enum","name","email","phone","address","additionalProperties","startsAt","endsAt","timeZone","currency","paidCents","taxCents","refundedCents","checkedIn","checkedInAt","rescheduledFrom","created","ops","path","method","operationId","summary","list","returns","filters","pathParams"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,gBAAgBC,IAAI,EACpBC,gBAAgBC,GAAG,EACnBC,YAAYC,GAAG,EACfC,iBAAiBC,QAAQ,EACzBC,mBAAmBC,YAAY,EAC/BC,cAAcC,CAAC,EACfC,eAAeC,GAAG,EAClBC,kBAAkB,QACb,qDAAoD;AAE3D;;;CAGC,GACD,OAAO,MAAMC,8BAAwD;IACnEC,KAAK;IACLC,aAAa;IACbC,YAAY;IACZC,UAAU;QAAC;QAAM;QAAU;KAAS;IACpCC,QAAQ;QACNC,IAAIR,IAAI;QACRS,QAAQb,aAAa;QACrBc,WAAWhB,SAASM,IAAI;QACxBW,aAAajB,SAASM,IAAI;QAC1BY,QAAQ;YACNC,MAAM;YACNC,MAAM;gBAAC;gBAAa;gBAAkB;gBAAW;aAAW;YAC5DV,aACE;QACJ;QACAW,MAAMrB,SAASM,IAAI;QACnBgB,OAAOtB,SAASM,IAAI;QACpBiB,OAAOvB,SAASM,IAAI;QACpBkB,SAAS;YACPL,MAAM;gBAAC;gBAAU;gBAAU;aAAO;YAClCT,aAAa;YACbe,sBAAsB;QACxB;QACAC,UAAU1B,SAASF,IAAI;QACvB6B,QAAQ3B,SAASF,IAAI;QACrB8B,UAAU5B,SAASM,IAAI;QACvBuB,UAAUvB,IAAI;QACdwB,WAAWlC,IAAI;QACfmC,UAAUnC,IAAI;QACdoC,eAAepC,IAAI;QACnBqC,WAAWvC,KAAK;QAChBwC,aAAalC,SAASF,IAAI;QAC1BqC,iBAAiBnC,SAASF,IAAI;QAC9BsC,SAASpC,SAASF,IAAI;IACxB;IACAuC,KAAK;QACH;YACEC,MAAM;YACNC,QAAQ;YACRC,aAAa;YACbC,SAAS;YACTC,MAAM;YACNC,SAAS;YACTC,SAAS;gBACPxC,EAAE,UAAU;gBACZA,EAAE,aAAa;aAChB;YACDyC,YAAY;gBAACtC;aAAmB;QAClC;QACA;YACE+B,MAAM;YACNC,QAAQ;YACRC,aAAa;YACbC,SAAS;YACTE,SAAS;YACTE,YAAY;gBACVtC;gBACA;oBAAEc,MAAM;oBAAaX,aAAa;gBAAc;aACjD;QACH;KACD;AACH,EAAC"}
@@ -567,7 +567,7 @@ export const bookingsBillingWebhookHandler = async ({ type, object, event })=>{
567
567
  // White-label sender identity (White-Label Phase 3), matching the
568
568
  // free-booking path — the store's brand via the one shared resolver.
569
569
  const branding = resolveBrandingProfile((_this = await getOrgForHost(String(hostId)).catch(()=>null)) == null ? void 0 : _this.org);
570
- await sendEmail(_extends({
570
+ const emailOutcome = await sendEmail(_extends({
571
571
  to: String(booking['email']),
572
572
  subject: (_ref10 = designed == null ? void 0 : designed.subject) != null ? _ref10 : `Booking confirmed: ${(_booking_serviceName4 = booking['serviceName']) != null ? _booking_serviceName4 : ''}`,
573
573
  text: (designed == null ? void 0 : designed.text) || fallbackText
@@ -584,7 +584,8 @@ export const bookingsBillingWebhookHandler = async ({ type, object, event })=>{
584
584
  }));
585
585
  // Cost meter (AGL-1438), matching the free-booking path.
586
586
  // Transactional: the guest has already paid.
587
- await meterHostEmail(String(hostId));
587
+ // Only a sent email is metered (AGL-4227).
588
+ if (emailOutcome == null ? void 0 : emailOutcome.sent) await meterHostEmail(String(hostId));
588
589
  }
589
590
  }
590
591
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/billing-webhook.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// `after()`, never a bare `void promise` (AGL-2327). This handler runs inside\n// the console's `/api/billing/webhook` invocation, which AGL-1133 measured on\n// production is frozen the moment the response is sent — so fire-and-forget\n// work scheduled any other way simply does not run.\nimport { after } from 'next/server'\n\nimport type { BillingWebhookHandler } from '@aglyn/aglyn/server'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n notifyHostManagers,\n notifyRiskEvent,\n renderHostEmailWithTokens,\n sendGa4Purchase,\n} from '@aglyn/tenant-data-admin'\nimport { paymentRiskEventFrom } from '@aglyn/aglyn/app-utils/payment-risk'\nimport {\n recordPaymentRiskOnRecord,\n settlePaymentRiskDisputeOnRecord,\n} from '@aglyn/tenant-data-admin/server/payment-risk-record'\nimport {\n reverseDestinationTransfer,\n type TransferReversalFailure,\n} from '@aglyn/tenant-data-admin/server/stripe-transfer-reversal'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport {\n bookingPlatformNetCents,\n shouldSendBookingPlatformPurchase,\n} from '../model/booking-purchase-analytics'\nimport { sendEmail } from '@aglyn/shared-util-email'\nimport { pluginTaxProfile } from '@aglyn/aglyn/plugin-manager/plugin-tax-profile'\nimport { fileBookingOnCrm } from './booking-crm'\nimport { stageBookingEvent } from './booking-events'\nimport { bookingTimeZoneFor } from './booking-time-zone'\nimport { formatBookingWhen } from '../model/booking-time'\nimport {\n bookingContactLines,\n readBookingPhone,\n} from '../model/booking-contact-fields'\n\n/**\n * Paid-booking section of the platform Stripe webhook (AGL-170/418):\n * payment confirms the pendingPayment hold — relocated verbatim from the\n * console route; registered via registerBookingsConsoleApi.\n */\n/** gRPC `Status.FAILED_PRECONDITION` — Firestore's \"this query needs an index\". */\nconst GRPC_FAILED_PRECONDITION = 9\n\n/**\n * The booking a charge paid for, found by the `paymentIntentId` the paid\n * handler below records (AGL-2315), or null. A missing collection-group\n * index is logged and answered null rather than thrown: no redelivery can\n * fix it, and the dispute then reaches staff through the route's\n * unattributed-dispute alert instead of vanishing.\n */\nasync function findBookingForPayment(\n paymentIntentId: string,\n): Promise<FirebaseFirestore.QueryDocumentSnapshot | null> {\n if (!paymentIntentId) return null\n const matches = await firebaseAdmin\n .app()\n .firestore()\n .collectionGroup('bookings')\n .where('paymentIntentId', '==', paymentIntentId)\n .limit(2)\n .get()\n .catch((error: { code?: number }) => {\n if (error?.code !== GRPC_FAILED_PRECONDITION) throw error\n console.error(\n 'Booking payment lookup needs the collection-group index on ' +\n 'bookings.paymentIntentId (AGL-3360)',\n error,\n )\n return null\n })\n // One payment intent pays one booking; two is corrupt data, and stamping\n // an arbitrary one would tell the wrong merchant.\n return matches && matches.docs.length === 1 ? matches.docs[0] : null\n}\n\n/** What a booking records once its lost dispute's reversal is settled. */\ninterface BookingDisputeReversal {\n disputeId: string\n reversedTransferCents: number\n transferReversalId?: string\n /** Why nothing was pulled back, when nothing was. */\n failedReason?: TransferReversalFailure\n owedCents?: number\n atMs: number\n}\n\n/**\n * The merchant's share of a LOST booking dispute, pulled back from the\n * connected account (AGL-3363), by the AGL-1794 policy a store order follows:\n * the Stripe half is the shared `reverseDestinationTransfer`, this is only\n * the booking's own record.\n *\n * IDEMPOTENT BY THE BOOKING: `disputeReversal` for this dispute, present,\n * means settled and a redelivery returns before any Stripe call. A delivery\n * that died after the POST is healed by the seam adopting the reversal the\n * transfer already carries. A transient Stripe failure THROWS (the seam\n * does), leaving the marker unset so Stripe's redelivery retries it. A final\n * failure is settled with its reason and the owed amount, so it is findable.\n *\n * `cents` is non-zero only for the delivery that wrote the reversal, which\n * is the one that tells the merchant.\n */\nasync function reverseBookingSellerShare(\n bookingRef: FirebaseFirestore.DocumentReference,\n dispute: any,\n): Promise<{ cents: number; settled: 'reversed' | 'failed' | 'pending' }> {\n const disputeId = String(dispute?.id ?? '')\n const amountCents = Math.max(0, Math.round(Number(dispute?.amount ?? 0)))\n if (!disputeId || !(amountCents > 0)) return { cents: 0, settled: 'failed' }\n const firestore = firebaseAdmin.app().firestore()\n const prior = (await bookingRef.get()).get('disputeReversal') as\n | BookingDisputeReversal\n | undefined\n if (prior?.disputeId === disputeId) {\n return { cents: 0, settled: prior.failedReason ? 'failed' : 'reversed' }\n }\n const outcome = await reverseDestinationTransfer({\n kind: 'dispute',\n id: disputeId,\n amountCents,\n chargeId:\n typeof dispute?.charge === 'string' ? dispute.charge : String(dispute?.charge?.id ?? ''),\n metadata: { bookingId: bookingRef.id },\n })\n if (outcome.kind === 'skipped') {\n console.error('Booking transfer reversal skipped: STRIPE_SECRET_KEY is not set (AGL-3363)')\n return { cents: 0, settled: 'pending' }\n }\n const record: BookingDisputeReversal =\n outcome.kind === 'reversed'\n ? {\n disputeId,\n reversedTransferCents: outcome.cents,\n ...(outcome.reversalId ? { transferReversalId: outcome.reversalId } : {}),\n atMs: Date.now(),\n }\n : {\n disputeId,\n reversedTransferCents: 0,\n failedReason: outcome.reason,\n ...(outcome.owedCents != null ? { owedCents: outcome.owedCents } : {}),\n atMs: Date.now(),\n }\n if (outcome.kind === 'not-reversed') {\n console.error('Booking seller share NOT reversed — recorded on the booking', {\n bookingId: bookingRef.id,\n disputeId,\n reason: outcome.reason,\n })\n }\n const wrote = await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n if (!fresh.exists) return false\n const current = fresh.get('disputeReversal') as BookingDisputeReversal | undefined\n if (current?.disputeId === disputeId) return false\n transaction.set(bookingRef, { disputeReversal: record }, { merge: true })\n return true\n })\n return {\n cents: wrote && outcome.kind === 'reversed' ? outcome.cents : 0,\n settled: outcome.kind === 'reversed' ? 'reversed' : 'failed',\n }\n}\n\nexport const bookingsBillingWebhookHandler: BillingWebhookHandler = async ({\n type,\n object,\n event,\n}) => {\n // The seller's account when this event is about a DIRECT charge: Stripe\n // delivers those through the Connect endpoint with the account on the\n // event itself. Empty for the platform's own (destination) charges.\n const eventAccount =\n typeof event?.account === 'string' ? event.account.trim() : ''\n // Fraud signals on a paid booking (AGL-3360): an issuer's early fraud\n // warning, a Radar review, or a dispute. Booking deposits never heard\n // about any of them, so the merchant learned of a chargeback from Stripe\n // alone. The signal now lands on the BOOKING, through the shared\n // `paymentRisk` shape every plugin stamps, and the site's managers are\n // told once. Nothing is refunded or canceled: the merchant decides.\n const risk = paymentRiskEventFrom(type, object)\n if (risk) {\n const booking = await findBookingForPayment(risk.paymentIntentId)\n if (!booking) return\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n await recordPaymentRiskOnRecord(\n {\n ref: booking.ref,\n signal: risk.signal,\n hostId,\n subjectLabel: `the booking for ${String(booking.get('serviceName') ?? booking.id)}`,\n link: `/${hostId}/bookings`,\n notificationType: 'content.booking',\n amount: Number.isFinite(Number(booking.get('paidAmountCents')))\n ? `$${(Number(booking.get('paidAmountCents')) / 100).toFixed(2)}`\n : null,\n evidenceDueByMs:\n Number((object as { evidence_details?: { due_by?: unknown } })?.evidence_details?.due_by ?? 0) * 1000 || null,\n },\n { firestore: firebaseAdmin.app().firestore(), notifyRisk: notifyRiskEvent },\n )\n return { claimed: true, hostId }\n }\n // A dispute's outcome, on the signal `created` stamped. A LOST one pulls\n // the merchant's share back from the connected account (AGL-3363), through\n // the same seam a lost store order uses, so the platform no longer absorbs\n // a booking chargeback. Claimed when the share came back; a reversal that\n // could not be made stays unclaimed, so the route's unattributed-dispute\n // alert still tells staff about money nothing recovered.\n if (type === 'charge.dispute.closed') {\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const booking = await findBookingForPayment(paymentIntentId)\n if (!booking) return\n const outcome = String(object?.status ?? '')\n await settlePaymentRiskDisputeOnRecord(\n booking.ref,\n String(object?.id ?? ''),\n outcome,\n { firestore: firebaseAdmin.app().firestore() },\n )\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n if (outcome !== 'lost') return { claimed: true, hostId }\n // A DIRECT charge's dispute is debited from the seller's own account by\n // Stripe, and there was never a transfer for the platform to pull back,\n // so a lost one is settled as recorded above and claimed.\n if (eventAccount || booking.get('chargeModel') === 'direct') {\n return { claimed: true, hostId }\n }\n const recovered = await reverseBookingSellerShare(booking.ref, object)\n if (recovered.cents > 0 && hostId) {\n const recoveredText = `$${(recovered.cents / 100).toFixed(2)}`\n const guest = String(booking.get('name') ?? '').trim()\n const service = String(booking.get('serviceName') ?? '').trim() || 'a service'\n await notifyHostManagers(hostId, {\n type: 'content.booking',\n title: `Payout adjusted — ${recoveredText} recovered for a lost chargeback`,\n body:\n `${guest ? `${guest}'s payment` : 'A payment'} for ${service} on ` +\n `{site} was charged back and the dispute was lost, so ` +\n `the ${recoveredText} transferred to you for it has been taken back. ` +\n `If your balance does not cover it, Stripe recovers the rest from ` +\n `your future payouts.`,\n link: `/${hostId}/bookings`,\n })\n }\n return recovered.settled === 'reversed' ? { claimed: true, hostId } : undefined\n }\n // Paid bookings (AGL-170): payment confirms the pendingPayment hold.\n if (\n type === 'checkout.session.completed' &&\n object?.metadata?.type === 'booking-payment' &&\n object?.payment_status === 'paid'\n ) {\n const { hostId, bookingId } = object.metadata ?? {}\n if (hostId && bookingId) {\n const firestore = firebaseAdmin.app().firestore()\n const bookingRef = firestore\n .collection('hosts')\n .doc(String(hostId))\n .collection('bookings')\n .doc(String(bookingId))\n // WHAT THE CLIENT HANDED OVER, ALL OF IT. Tax included: this is the\n // ceiling `refund.ts` reverses against, and the client paid the tax\n // too — a net figure here would strand part of a refund.\n const paidAmountCents = Math.max(\n 0,\n Math.round(Number(object?.amount_total ?? 0)),\n )\n // THE MERCHANT'S SERVICE TAX, SEPARATED OUT (AGL-2028).\n //\n // `server.ts` charges the merchant's own service rate as an ordinary\n // `line_items[1]` Stripe is never told is tax (the AGL-1711\n // construction, which is what keeps the figure the MERCHANT's rather\n // than something computed against Aglyn's registrations). So\n // `amount_total` is service-plus-tax while Stripe's own tax fields\n // read zero, and the session's metadata is the only witness — exactly\n // as it is for a buy-now sale.\n const taxCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.taxCents ?? 0)),\n )\n // The merchant's REVENUE, which is the charge less the tax. Used for\n // the contact's lifetime value below: tax is collected on behalf of\n // an authority and is not money the business earned, so counting it\n // would over-state every service client's worth.\n const serviceCents = Math.max(0, paidAmountCents - taxCents)\n // WHAT A REFUND WILL NEED (AGL-2315). A paid booking is now a\n // destination charge to the merchant's connected account, and\n // reversing one requires the PaymentIntent — which lives only on this\n // event. The booking document recorded `paidAmountCents` and nothing\n // that identifies the charge, so a refund had no handle to pull and\n // the information was gone the moment the webhook returned. Unlike\n // most gaps this one cannot be backfilled from our own data later:\n // every booking taken before this line landed can only be refunded by\n // hand in the Stripe dashboard.\n //\n // `feeCents` is Aglyn's cut as CHARGED, read back off the session's\n // own metadata rather than re-derived from the org at refund time. The\n // rate follows the plan (AGL-2289's rule) and the plan moves, so\n // re-resolving it during a refund would reverse a share that was never\n // taken. `'0'` is a real recorded answer on the 0%-rate tiers.\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const chargedFeeCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.feeCents ?? 0)),\n )\n // A DIRECT charge lives on the seller's account, which a refund has\n // to be sent to. The event names that account; `server.ts` stamped it\n // on the hold too, so an event without one leaves that stamp alone.\n const direct =\n object?.metadata?.chargeModel === 'direct' || Boolean(eventAccount)\n // Redelivery guard (AGL-1755), the AGL-1748 shape. This was an\n // unconditional merge-set with no status check at all — idempotent\n // only by accident, because every value it wrote was fixed. A\n // redelivery re-sent the guest's confirmation and re-metered it, and\n // the moment this handler carries money to a contact the accident stops\n // holding: `purchaseCents` is a `FieldValue.increment`, so every retry\n // would inflate the customer's lifetime value.\n //\n // Keyed on the STATUS, not on the document existing: `server.ts` writes\n // the booking as `pendingPayment` BEFORE it opens the Stripe session,\n // so existence is guaranteed by the time any event arrives and proves\n // nothing — the AGL-1748 reasoning, not AGL-1732's `checkoutSessionId`\n // key, which existed because a sibling event wrote the same path.\n //\n // The key is \"not yet confirmed\" rather than \"is pendingPayment\" on\n // purpose. The lapsed-hold sweeper in `server.ts` cancels a\n // `pendingPayment` booking after 24h, and refusing a payment that\n // landed anyway would take the money and record nothing; `confirmed` is\n // reachable for a PAID booking only by this handler having already run,\n // so it is an exact \"already processed\" test. The existence check is\n // new and deliberate: the old merge-set would CREATE a stub booking\n // from a metadata `bookingId` that pointed at nothing.\n let booking: Record<string, any> = {}\n const confirmedNow = await firestore.runTransaction(\n async (transaction) => {\n const snapshot = await transaction.get(bookingRef)\n if (!snapshot.exists) return false\n if (snapshot.get('status') === 'confirmed') return false\n // \"Already processed\" is WIDER than `confirmed` once money can\n // flow back out (AGL-2315). A refunded booking is moved off\n // `confirmed`, so a redelivery arriving afterwards would otherwise\n // read as unprocessed and re-confirm an appointment the merchant\n // has already cancelled and refunded — re-sending the guest a\n // confirmation for it and re-metering the email. Any evidence this\n // handler has run before is the real test, and a refund counter or\n // a recorded PaymentIntent is exactly that evidence.\n if (\n Number(snapshot.get('refundedCents') ?? 0) > 0 ||\n snapshot.get('paymentIntentId')\n ) {\n return false\n }\n booking = (snapshot.data() as any) ?? {}\n transaction.set(\n bookingRef,\n {\n status: 'confirmed',\n paidAmountCents,\n // WHICH TAX REGIME THIS BOOKING CARRIED (AGL-2028), on the\n // document the merchant reads — the stamp every other\n // storefront money door already carries (AGL-2451).\n //\n // DERIVED from the one shared derivation, never a constant.\n // A hand-written \"manual when the metadata says so\" would be\n // a second rule that can drift from the `storefrontTaxCollected`\n // row filed for the same Stripe id, which is the exact\n // disagreement AGL-2451 exists to prevent.\n //\n // TWO-ARGUMENT, because the manual line makes Stripe report\n // `total_details.amount_tax: 0` on a booking that really did\n // charge the client tax; the one-argument form would stamp\n // `none` on precisely those. `absent` remains a fourth state\n // meaning \"recorded before this shipped\".\n taxMode: pluginTaxProfile().taxModeOf(object, taxCents),\n // The figure itself. Absent rather than a defaulted `0` — a\n // zero written through `merge` is the AGL-1758 shape, and\n // this handler can re-enter (see the widened guard above).\n ...(taxCents > 0 ? { taxCents } : {}),\n // The refund handles (AGL-2315). Written inside the same\n // transaction as the status, so a booking can never read\n // `confirmed` while the means to refund it are missing.\n ...(paymentIntentId ? { paymentIntentId } : {}),\n feeCents: chargedFeeCents,\n ...(direct\n ? {\n chargeModel: 'direct',\n ...(eventAccount ? { stripeAccountId: eventAccount } : {}),\n }\n : {}),\n // WHICH CHECKOUT PAID FOR THIS (AGL-2481). The guest's browser\n // comes back from Stripe holding a session id and nothing\n // else — a booking id was never in the return URL — so this is\n // what lets `booking-analytics.ts` answer \"what did I just\n // buy?\" for the merchant-side `purchase`, and it is written\n // here because the session id first exists on this event.\n //\n // Inside the transaction with the status on purpose: the\n // lookup refuses anything that is not `confirmed`, so a\n // booking can never be findable by session id while reading as\n // unpaid.\n ...(object?.id ? { checkoutSessionId: String(object.id) } : {}),\n // NOTE the absent `refundedCents: 0`. Seeding it here would be\n // the AGL-1758 shape: a defaulted field written through\n // `merge` destroying the real one. This handler can re-enter\n // after a refund has already accumulated a counter (see the\n // widened guard above), and a zero written back over it would\n // re-open the full amount for refunding a second time. Absent\n // IS zero — every reader coerces with `?? 0`.\n expiresAtMs: firebaseAdmin.firestore.FieldValue.delete(),\n confirmedAt:\n firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n // The booking is confirmed now, in this transaction (AGL-3643).\n const nowMs = Date.now()\n stageBookingEvent(transaction, firestore, {\n event: 'booking.created',\n hostId: String(hostId),\n bookingId: String(bookingId),\n booking: {\n ...booking,\n status: 'confirmed',\n paidAmountCents,\n ...(taxCents > 0 ? { taxCents } : {}),\n expiresAtMs: null,\n },\n nowMs,\n })\n return true\n },\n )\n if (!confirmedNow) return\n // THE RECORD'S MEETING (AGL-2660). Payment is what confirms a paid\n // booking, so this is where it reaches the CRM: the meeting on the\n // record's timeline and, when the service asks, the follow-up task.\n // Inside the idempotency gate for the same reason the GA4 purchase\n // below is — a redelivery must not file a second meeting — and\n // through `after()` for the same reason too: this invocation is\n // frozen the moment the response is sent (AGL-2327). Never thrown:\n // the writer swallows its own failures, and the catch is for the\n // scheduling itself.\n after(() =>\n fileBookingOnCrm(firestore, {\n hostId: String(hostId),\n bookingId: String(bookingId),\n booking,\n }).catch(() => undefined),\n )\n // AGLYN'S REVENUE ON THIS BOOKING (AGL-2481) — into OUR GA4 property.\n //\n // ## Why it is inside the idempotency gate rather than beside it\n //\n // This sits AFTER `if (!confirmedNow) return` and that placement is the\n // whole guard. Stripe redelivers `checkout.session.completed` for up to\n // three days after any 500, and this endpoint 500s on purpose; a\n // redelivery re-enters this handler, the transaction above sees a\n // `confirmed` status (or a refund counter, or a recorded PaymentIntent)\n // and answers false, and everything below — the contact, the email, and\n // now this — is skipped. A `purchase` fired before that gate, or beside\n // it, would inflate our own reported revenue by the redelivery rate.\n //\n // `transaction_id` is the checkout session id, which is the same key\n // the guard turns on, so GA4's own de-duplication is a second\n // independent line of defence: even if the Firestore guard were ever\n // bypassed, GA would collapse the repeats.\n //\n // ## Platform NET, and the fee is the measured one\n //\n // `value` is our fee and not the $95 the guest paid — the AGL-1639\n // settlement. This is our property, the subscription and marketplace\n // `purchase` events in it already mean \"what Aglyn was paid\", and a\n // gross booking figure sitting beside them would make every combined\n // total, ARPA and revenue audience wrong. The merchant's own gross goes\n // to the MERCHANT's property, client-side, and the two never meet.\n //\n // The figure comes off the session's `metadata.feeCents` — the fee\n // Stripe actually charged as `application_fee_amount` — never from the\n // plan's rate re-applied here. See `bookingPlatformNetCents`.\n //\n // ## Scheduling and failure posture\n //\n // `after()`, never a bare `void` (AGL-2327/AGL-2346): this runs inside\n // the console's `/api/billing/webhook` invocation, which is frozen the\n // moment the response is sent, so fire-and-forget work scheduled any\n // other way simply does not run — the exact way marketplace revenue\n // reported to nothing. And `.catch()`, because a throw here would\n // un-claim the Stripe event and turn a missed analytics hit into a\n // repeated billing side effect.\n if (shouldSendBookingPlatformPurchase(object)) {\n const netCents = bookingPlatformNetCents(object)\n after(() =>\n sendGa4Purchase({\n transactionId: String(object?.id ?? ''),\n value: netCents / 100,\n currency: String(object?.currency ?? 'usd'),\n items: [\n {\n // Ids only, no merchant free text. A service name is\n // merchant-authored and one edit away from carrying a\n // person's name into a dimension in OUR property; the id\n // already identifies it. The merchant's own property gets\n // the name, because there it is their own content.\n item_id: String(booking['serviceId'] ?? bookingId),\n item_name: String(booking['serviceId'] ?? bookingId),\n item_category: 'booking',\n // GA expects the items to sum to `value`; one item, one\n // price, and that price is our fee — not the service's.\n price: netCents / 100,\n quantity: 1,\n },\n ],\n // Booking sessions carry no `ga_client_id` today — nothing\n // captures one on a tenant site — so this is read for the day\n // one is stamped and the seed below is what actually resolves.\n clientId: object?.metadata?.ga_client_id,\n // ONE PAYING GUEST, ONE SYNTHETIC USER. Seeded from Stripe's\n // customer where there is one, and otherwise from the guest's\n // email, which `server.ts` passes as `customer_email` and Stripe\n // echoes on `customer_details`. The seed is hashed inside\n // `synthesizeClientId` and never transmitted.\n //\n // The booking id is the LAST resort deliberately: it is unique\n // per appointment, so seeding from it would turn a regular\n // client into a crowd of one-purchase strangers and make ARPA\n // nonsense — precisely what that helper's determinism exists to\n // prevent. Without any seed at all `sendGa4Purchase` returns\n // `no-client-id` and the event is silently never sent, which is\n // the void this whole change exists to close.\n stripeCustomerId:\n String(object?.customer ?? '') ||\n String(object?.customer_details?.email ?? '') ||\n String(bookingId),\n }).catch(() => undefined),\n )\n }\n // Contacts ingestion (AGL-1755). `server.ts` captures the contact at\n // REQUEST time, which is the right place — the booking is written\n // `pendingPayment` and at that moment no money has moved, so passing an\n // amount there would be a lie. But payment completes HERE, and this\n // handler never returned to the contact, so a paid booking's money\n // reached the booking document and nothing else. The same structural\n // shape as AGL-1748's draft branch: the completion handler does\n // everything except the contact.\n //\n // `source` stays `'booking'` — the same source the request-time capture\n // used — so the `sources` map still says where this person came from\n // and no schema change is needed to keep service revenue\n // distinguishable from product revenue. The second interaction is\n // deliberate rather than a duplicate: \"Booked X\" and \"Paid for X\" are\n // two real events, and `mergeContactInteraction` does not dedupe on\n // `refId`.\n //\n // The amount is `amount_total`, the money that moved, per AGL-1698 and\n // AGL-1711 — the booking document stores no price to re-derive it from.\n if (booking['email']) {\n void recordCapturedContact({\n orgId: '',\n hostId: String(hostId),\n identity: {\n email: booking['email'],\n ...(booking['name'] ? { name: String(booking['name']) } : {}),\n },\n // Paid, so a relationship (AGL-3232): the lead the request-time\n // capture filed for the address is closed onto the contact.\n surface: 'relationship',\n // The phone the booking form asked for (AGL-3493), onto the\n // contact only where it holds none — as the request-time\n // capture put it on the lead.\n ...(readBookingPhone(booking['phone'])\n ? { profileFill: { phone: readBookingPhone(booking['phone']) } }\n : {}),\n // Paid, so a customer (AGL-2612) — the request-time capture\n // said `lead`, and this is the door that has seen the money.\n lifecycleFloor: 'customer',\n // The SERVICE, not the charge (AGL-2028). `amount_total` now\n // includes the merchant's service tax where they set one, and\n // tax is collected for an authority rather than earned — booking\n // it as lifetime value would over-state what every service\n // client is worth. Identical to `paidAmountCents` on the default\n // store, which sets no rate.\n ...(serviceCents > 0 ? { purchaseCents: serviceCents } : {}),\n interaction: {\n source: 'booking',\n refId: String(bookingId),\n summary: `Paid for \"${String(\n booking['serviceName'] ?? 'a service',\n ).slice(0, 60)}\" ($${(serviceCents / 100).toFixed(2)})`,\n },\n })\n }\n // In the booking's own zone, and named (AGL-3432): a formatter with\n // no zone reads in the server's — UTC — and tells a paying guest the\n // wrong hour, and an empty zone prints \"()\".\n const timezone = await bookingTimeZoneFor(\n firestore,\n String(hostId),\n booking,\n )\n const when = formatBookingWhen(Number(booking['startsAtMs']), timezone)\n const paid = `$${(paidAmountCents / 100).toFixed(2)}`\n // The site's managers hear of a PAID booking too (AGL-3500): the\n // free path tells them when the request lands, and a paid one is\n // only a booking once this event has cleared the charge, so this is\n // its moment. Who, what, when, what was paid, and the phone and\n // address the service asked for.\n const contactLines = bookingContactLines(booking)\n void notifyHostManagers(String(hostId), {\n type: 'content.booking',\n title: 'New booking on {site}',\n body:\n `${String(booking['name'] ?? '') || 'A guest'}` +\n (booking['email'] ? ` (${String(booking['email'])})` : '') +\n ` booked ${String(booking['serviceName'] ?? '') || 'a service'} ` +\n `on {site} for ${when} (${timezone}). ${paid} was paid.` +\n (contactLines.length ? ` ${contactLines.join('. ')}.` : ''),\n link: `/${hostId}/bookings`,\n })\n // Confirmation email now that payment cleared (env-gated inside\n // sendEmail, which no-ops when Resend isn't configured).\n if (booking['email']) {\n const fallbackText =\n `Hi ${booking['name'] ?? ''},\\n\\nPayment received — ` +\n `\"${booking['serviceName'] ?? 'your booking'}\" is ` +\n `confirmed for ${when} (${timezone}). You paid ${paid}.` +\n `\\n\\nReference: ${bookingId}`\n // Site-owner-designed template when published (AGL-770); null keeps\n // the built-in copy.\n const designed = await renderHostEmailWithTokens(\n firebaseAdmin.app().firestore(),\n String(hostId),\n 'booking-confirmed',\n {\n name: String(booking['name'] ?? ''),\n 'service.name': String(booking['serviceName'] ?? ''),\n when,\n timezone,\n 'booking.payment': `You paid ${paid}.`,\n 'booking.ref': String(bookingId),\n },\n )\n // White-label sender identity (White-Label Phase 3), matching the\n // free-booking path — the store's brand via the one shared resolver.\n const branding = resolveBrandingProfile(\n (await getOrgForHost(String(hostId)).catch(() => null))?.org as never,\n )\n await sendEmail({\n to: String(booking['email']),\n subject:\n designed?.subject ??\n `Booking confirmed: ${booking['serviceName'] ?? ''}`,\n text: designed?.text || fallbackText,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(String(hostId)),\n audience: 'tenant',\n context: 'paid booking confirmation',\n // Owed to the recipient by their own booking: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'booking',\n })\n // Cost meter (AGL-1438), matching the free-booking path.\n // Transactional: the guest has already paid.\n await meterHostEmail(String(hostId))\n }\n }\n }\n}\n"],"names":["after","resolveBrandingProfile","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","notifyHostManagers","notifyRiskEvent","renderHostEmailWithTokens","sendGa4Purchase","paymentRiskEventFrom","recordPaymentRiskOnRecord","settlePaymentRiskDisputeOnRecord","reverseDestinationTransfer","recordCapturedContact","bookingPlatformNetCents","shouldSendBookingPlatformPurchase","sendEmail","pluginTaxProfile","fileBookingOnCrm","stageBookingEvent","bookingTimeZoneFor","formatBookingWhen","bookingContactLines","readBookingPhone","GRPC_FAILED_PRECONDITION","findBookingForPayment","paymentIntentId","matches","app","firestore","collectionGroup","where","limit","get","catch","error","code","console","docs","length","reverseBookingSellerShare","bookingRef","dispute","disputeId","String","id","amountCents","Math","max","round","Number","amount","cents","settled","prior","failedReason","outcome","kind","chargeId","charge","metadata","bookingId","record","reversedTransferCents","reversalId","transferReversalId","atMs","Date","now","reason","owedCents","wrote","runTransaction","transaction","fresh","exists","current","set","disputeReversal","merge","bookingsBillingWebhookHandler","type","object","event","eventAccount","account","trim","risk","booking","hostId","ref","parent","signal","subjectLabel","link","notificationType","isFinite","toFixed","evidenceDueByMs","evidence_details","due_by","notifyRisk","claimed","payment_intent","status","recovered","recoveredText","guest","service","title","body","undefined","payment_status","collection","doc","paidAmountCents","amount_total","taxCents","serviceCents","chargedFeeCents","feeCents","direct","chargeModel","Boolean","confirmedNow","snapshot","data","taxMode","taxModeOf","stripeAccountId","checkoutSessionId","expiresAtMs","FieldValue","delete","confirmedAt","serverTimestamp","nowMs","netCents","transactionId","value","currency","items","item_id","item_name","item_category","price","quantity","clientId","ga_client_id","stripeCustomerId","customer","customer_details","email","orgId","identity","name","surface","profileFill","phone","lifecycleFloor","purchaseCents","interaction","source","refId","summary","slice","timezone","when","paid","contactLines","join","fallbackText","designed","branding","org","to","subject","text","html","fromName","sendingIdentity","audience","context","owedFor"],"mappings":";AAAA;;;;;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,SAAS,IAC7Be,OAAO6C,SACP,qBACA;oBACEkE,MAAM/G,QAAO4C,iBAAAA,OAAO,CAAC,OAAO,YAAfA,iBAAmB;oBAChC,gBAAgB5C,QAAO4C,wBAAAA,OAAO,CAAC,cAAc,YAAtBA,wBAA0B;oBACjD+E;oBACAD;oBACA,mBAAmB,CAAC,SAAS,EAAEE,KAAK,CAAC,CAAC;oBACtC,eAAe5H,OAAOiB;gBACxB;gBAEF,kEAAkE;gBAClE,qEAAqE;gBACrE,MAAMgH,WAAW7K,wBACd,QAAA,MAAME,cAAc0C,OAAO6C,SAASvD,KAAK,CAAC,IAAM,0BAAjD,AAAC,MAAwD4I,GAAG;gBAE9D,MAAM9J,UAAU;oBACd+J,IAAInI,OAAO4C,OAAO,CAAC,QAAQ;oBAC3BwF,OAAO,YACLJ,4BAAAA,SAAUI,OAAO,qBACjB,CAAC,mBAAmB,GAAExF,wBAAAA,OAAO,CAAC,cAAc,YAAtBA,wBAA0B,IAAI;oBACtDyF,MAAML,CAAAA,4BAAAA,SAAUK,IAAI,KAAIN;mBACpBC,CAAAA,4BAAAA,SAAUM,IAAI,IAAG;oBAAEA,MAAMN,SAASM,IAAI;gBAAC,IAAI,CAAC;oBAChDC,UAAUN,SAASM,QAAQ;oBAC3BC,iBAAiB,MAAMjL,oBAAoByC,OAAO6C;oBAClD4F,UAAU;oBACVC,SAAS;oBACT,2DAA2D;oBAC3D,gDAAgD;oBAChDC,SAAS;;gBAEX,yDAAyD;gBACzD,6CAA6C;gBAC7C,MAAMnL,eAAewC,OAAO6C;YAC9B;QACF;IACF;AACJ,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/billing-webhook.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// `after()`, never a bare `void promise` (AGL-2327). This handler runs inside\n// the console's `/api/billing/webhook` invocation, which AGL-1133 measured on\n// production is frozen the moment the response is sent — so fire-and-forget\n// work scheduled any other way simply does not run.\nimport { after } from 'next/server'\n\nimport type { BillingWebhookHandler } from '@aglyn/aglyn/server'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n notifyHostManagers,\n notifyRiskEvent,\n renderHostEmailWithTokens,\n sendGa4Purchase,\n} from '@aglyn/tenant-data-admin'\nimport { paymentRiskEventFrom } from '@aglyn/aglyn/app-utils/payment-risk'\nimport {\n recordPaymentRiskOnRecord,\n settlePaymentRiskDisputeOnRecord,\n} from '@aglyn/tenant-data-admin/server/payment-risk-record'\nimport {\n reverseDestinationTransfer,\n type TransferReversalFailure,\n} from '@aglyn/tenant-data-admin/server/stripe-transfer-reversal'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport {\n bookingPlatformNetCents,\n shouldSendBookingPlatformPurchase,\n} from '../model/booking-purchase-analytics'\nimport { sendEmail } from '@aglyn/shared-util-email'\nimport { pluginTaxProfile } from '@aglyn/aglyn/plugin-manager/plugin-tax-profile'\nimport { fileBookingOnCrm } from './booking-crm'\nimport { stageBookingEvent } from './booking-events'\nimport { bookingTimeZoneFor } from './booking-time-zone'\nimport { formatBookingWhen } from '../model/booking-time'\nimport {\n bookingContactLines,\n readBookingPhone,\n} from '../model/booking-contact-fields'\n\n/**\n * Paid-booking section of the platform Stripe webhook (AGL-170/418):\n * payment confirms the pendingPayment hold — relocated verbatim from the\n * console route; registered via registerBookingsConsoleApi.\n */\n/** gRPC `Status.FAILED_PRECONDITION` — Firestore's \"this query needs an index\". */\nconst GRPC_FAILED_PRECONDITION = 9\n\n/**\n * The booking a charge paid for, found by the `paymentIntentId` the paid\n * handler below records (AGL-2315), or null. A missing collection-group\n * index is logged and answered null rather than thrown: no redelivery can\n * fix it, and the dispute then reaches staff through the route's\n * unattributed-dispute alert instead of vanishing.\n */\nasync function findBookingForPayment(\n paymentIntentId: string,\n): Promise<FirebaseFirestore.QueryDocumentSnapshot | null> {\n if (!paymentIntentId) return null\n const matches = await firebaseAdmin\n .app()\n .firestore()\n .collectionGroup('bookings')\n .where('paymentIntentId', '==', paymentIntentId)\n .limit(2)\n .get()\n .catch((error: { code?: number }) => {\n if (error?.code !== GRPC_FAILED_PRECONDITION) throw error\n console.error(\n 'Booking payment lookup needs the collection-group index on ' +\n 'bookings.paymentIntentId (AGL-3360)',\n error,\n )\n return null\n })\n // One payment intent pays one booking; two is corrupt data, and stamping\n // an arbitrary one would tell the wrong merchant.\n return matches && matches.docs.length === 1 ? matches.docs[0] : null\n}\n\n/** What a booking records once its lost dispute's reversal is settled. */\ninterface BookingDisputeReversal {\n disputeId: string\n reversedTransferCents: number\n transferReversalId?: string\n /** Why nothing was pulled back, when nothing was. */\n failedReason?: TransferReversalFailure\n owedCents?: number\n atMs: number\n}\n\n/**\n * The merchant's share of a LOST booking dispute, pulled back from the\n * connected account (AGL-3363), by the AGL-1794 policy a store order follows:\n * the Stripe half is the shared `reverseDestinationTransfer`, this is only\n * the booking's own record.\n *\n * IDEMPOTENT BY THE BOOKING: `disputeReversal` for this dispute, present,\n * means settled and a redelivery returns before any Stripe call. A delivery\n * that died after the POST is healed by the seam adopting the reversal the\n * transfer already carries. A transient Stripe failure THROWS (the seam\n * does), leaving the marker unset so Stripe's redelivery retries it. A final\n * failure is settled with its reason and the owed amount, so it is findable.\n *\n * `cents` is non-zero only for the delivery that wrote the reversal, which\n * is the one that tells the merchant.\n */\nasync function reverseBookingSellerShare(\n bookingRef: FirebaseFirestore.DocumentReference,\n dispute: any,\n): Promise<{ cents: number; settled: 'reversed' | 'failed' | 'pending' }> {\n const disputeId = String(dispute?.id ?? '')\n const amountCents = Math.max(0, Math.round(Number(dispute?.amount ?? 0)))\n if (!disputeId || !(amountCents > 0)) return { cents: 0, settled: 'failed' }\n const firestore = firebaseAdmin.app().firestore()\n const prior = (await bookingRef.get()).get('disputeReversal') as\n | BookingDisputeReversal\n | undefined\n if (prior?.disputeId === disputeId) {\n return { cents: 0, settled: prior.failedReason ? 'failed' : 'reversed' }\n }\n const outcome = await reverseDestinationTransfer({\n kind: 'dispute',\n id: disputeId,\n amountCents,\n chargeId:\n typeof dispute?.charge === 'string' ? dispute.charge : String(dispute?.charge?.id ?? ''),\n metadata: { bookingId: bookingRef.id },\n })\n if (outcome.kind === 'skipped') {\n console.error('Booking transfer reversal skipped: STRIPE_SECRET_KEY is not set (AGL-3363)')\n return { cents: 0, settled: 'pending' }\n }\n const record: BookingDisputeReversal =\n outcome.kind === 'reversed'\n ? {\n disputeId,\n reversedTransferCents: outcome.cents,\n ...(outcome.reversalId ? { transferReversalId: outcome.reversalId } : {}),\n atMs: Date.now(),\n }\n : {\n disputeId,\n reversedTransferCents: 0,\n failedReason: outcome.reason,\n ...(outcome.owedCents != null ? { owedCents: outcome.owedCents } : {}),\n atMs: Date.now(),\n }\n if (outcome.kind === 'not-reversed') {\n console.error('Booking seller share NOT reversed — recorded on the booking', {\n bookingId: bookingRef.id,\n disputeId,\n reason: outcome.reason,\n })\n }\n const wrote = await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n if (!fresh.exists) return false\n const current = fresh.get('disputeReversal') as BookingDisputeReversal | undefined\n if (current?.disputeId === disputeId) return false\n transaction.set(bookingRef, { disputeReversal: record }, { merge: true })\n return true\n })\n return {\n cents: wrote && outcome.kind === 'reversed' ? outcome.cents : 0,\n settled: outcome.kind === 'reversed' ? 'reversed' : 'failed',\n }\n}\n\nexport const bookingsBillingWebhookHandler: BillingWebhookHandler = async ({\n type,\n object,\n event,\n}) => {\n // The seller's account when this event is about a DIRECT charge: Stripe\n // delivers those through the Connect endpoint with the account on the\n // event itself. Empty for the platform's own (destination) charges.\n const eventAccount =\n typeof event?.account === 'string' ? event.account.trim() : ''\n // Fraud signals on a paid booking (AGL-3360): an issuer's early fraud\n // warning, a Radar review, or a dispute. Booking deposits never heard\n // about any of them, so the merchant learned of a chargeback from Stripe\n // alone. The signal now lands on the BOOKING, through the shared\n // `paymentRisk` shape every plugin stamps, and the site's managers are\n // told once. Nothing is refunded or canceled: the merchant decides.\n const risk = paymentRiskEventFrom(type, object)\n if (risk) {\n const booking = await findBookingForPayment(risk.paymentIntentId)\n if (!booking) return\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n await recordPaymentRiskOnRecord(\n {\n ref: booking.ref,\n signal: risk.signal,\n hostId,\n subjectLabel: `the booking for ${String(booking.get('serviceName') ?? booking.id)}`,\n link: `/${hostId}/bookings`,\n notificationType: 'content.booking',\n amount: Number.isFinite(Number(booking.get('paidAmountCents')))\n ? `$${(Number(booking.get('paidAmountCents')) / 100).toFixed(2)}`\n : null,\n evidenceDueByMs:\n Number((object as { evidence_details?: { due_by?: unknown } })?.evidence_details?.due_by ?? 0) * 1000 || null,\n },\n { firestore: firebaseAdmin.app().firestore(), notifyRisk: notifyRiskEvent },\n )\n return { claimed: true, hostId }\n }\n // A dispute's outcome, on the signal `created` stamped. A LOST one pulls\n // the merchant's share back from the connected account (AGL-3363), through\n // the same seam a lost store order uses, so the platform no longer absorbs\n // a booking chargeback. Claimed when the share came back; a reversal that\n // could not be made stays unclaimed, so the route's unattributed-dispute\n // alert still tells staff about money nothing recovered.\n if (type === 'charge.dispute.closed') {\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const booking = await findBookingForPayment(paymentIntentId)\n if (!booking) return\n const outcome = String(object?.status ?? '')\n await settlePaymentRiskDisputeOnRecord(\n booking.ref,\n String(object?.id ?? ''),\n outcome,\n { firestore: firebaseAdmin.app().firestore() },\n )\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n if (outcome !== 'lost') return { claimed: true, hostId }\n // A DIRECT charge's dispute is debited from the seller's own account by\n // Stripe, and there was never a transfer for the platform to pull back,\n // so a lost one is settled as recorded above and claimed.\n if (eventAccount || booking.get('chargeModel') === 'direct') {\n return { claimed: true, hostId }\n }\n const recovered = await reverseBookingSellerShare(booking.ref, object)\n if (recovered.cents > 0 && hostId) {\n const recoveredText = `$${(recovered.cents / 100).toFixed(2)}`\n const guest = String(booking.get('name') ?? '').trim()\n const service = String(booking.get('serviceName') ?? '').trim() || 'a service'\n await notifyHostManagers(hostId, {\n type: 'content.booking',\n title: `Payout adjusted — ${recoveredText} recovered for a lost chargeback`,\n body:\n `${guest ? `${guest}'s payment` : 'A payment'} for ${service} on ` +\n `{site} was charged back and the dispute was lost, so ` +\n `the ${recoveredText} transferred to you for it has been taken back. ` +\n `If your balance does not cover it, Stripe recovers the rest from ` +\n `your future payouts.`,\n link: `/${hostId}/bookings`,\n })\n }\n return recovered.settled === 'reversed' ? { claimed: true, hostId } : undefined\n }\n // Paid bookings (AGL-170): payment confirms the pendingPayment hold.\n if (\n type === 'checkout.session.completed' &&\n object?.metadata?.type === 'booking-payment' &&\n object?.payment_status === 'paid'\n ) {\n const { hostId, bookingId } = object.metadata ?? {}\n if (hostId && bookingId) {\n const firestore = firebaseAdmin.app().firestore()\n const bookingRef = firestore\n .collection('hosts')\n .doc(String(hostId))\n .collection('bookings')\n .doc(String(bookingId))\n // WHAT THE CLIENT HANDED OVER, ALL OF IT. Tax included: this is the\n // ceiling `refund.ts` reverses against, and the client paid the tax\n // too — a net figure here would strand part of a refund.\n const paidAmountCents = Math.max(\n 0,\n Math.round(Number(object?.amount_total ?? 0)),\n )\n // THE MERCHANT'S SERVICE TAX, SEPARATED OUT (AGL-2028).\n //\n // `server.ts` charges the merchant's own service rate as an ordinary\n // `line_items[1]` Stripe is never told is tax (the AGL-1711\n // construction, which is what keeps the figure the MERCHANT's rather\n // than something computed against Aglyn's registrations). So\n // `amount_total` is service-plus-tax while Stripe's own tax fields\n // read zero, and the session's metadata is the only witness — exactly\n // as it is for a buy-now sale.\n const taxCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.taxCents ?? 0)),\n )\n // The merchant's REVENUE, which is the charge less the tax. Used for\n // the contact's lifetime value below: tax is collected on behalf of\n // an authority and is not money the business earned, so counting it\n // would over-state every service client's worth.\n const serviceCents = Math.max(0, paidAmountCents - taxCents)\n // WHAT A REFUND WILL NEED (AGL-2315). A paid booking is now a\n // destination charge to the merchant's connected account, and\n // reversing one requires the PaymentIntent — which lives only on this\n // event. The booking document recorded `paidAmountCents` and nothing\n // that identifies the charge, so a refund had no handle to pull and\n // the information was gone the moment the webhook returned. Unlike\n // most gaps this one cannot be backfilled from our own data later:\n // every booking taken before this line landed can only be refunded by\n // hand in the Stripe dashboard.\n //\n // `feeCents` is Aglyn's cut as CHARGED, read back off the session's\n // own metadata rather than re-derived from the org at refund time. The\n // rate follows the plan (AGL-2289's rule) and the plan moves, so\n // re-resolving it during a refund would reverse a share that was never\n // taken. `'0'` is a real recorded answer on the 0%-rate tiers.\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const chargedFeeCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.feeCents ?? 0)),\n )\n // A DIRECT charge lives on the seller's account, which a refund has\n // to be sent to. The event names that account; `server.ts` stamped it\n // on the hold too, so an event without one leaves that stamp alone.\n const direct =\n object?.metadata?.chargeModel === 'direct' || Boolean(eventAccount)\n // Redelivery guard (AGL-1755), the AGL-1748 shape. This was an\n // unconditional merge-set with no status check at all — idempotent\n // only by accident, because every value it wrote was fixed. A\n // redelivery re-sent the guest's confirmation and re-metered it, and\n // the moment this handler carries money to a contact the accident stops\n // holding: `purchaseCents` is a `FieldValue.increment`, so every retry\n // would inflate the customer's lifetime value.\n //\n // Keyed on the STATUS, not on the document existing: `server.ts` writes\n // the booking as `pendingPayment` BEFORE it opens the Stripe session,\n // so existence is guaranteed by the time any event arrives and proves\n // nothing — the AGL-1748 reasoning, not AGL-1732's `checkoutSessionId`\n // key, which existed because a sibling event wrote the same path.\n //\n // The key is \"not yet confirmed\" rather than \"is pendingPayment\" on\n // purpose. The lapsed-hold sweeper in `server.ts` cancels a\n // `pendingPayment` booking after 24h, and refusing a payment that\n // landed anyway would take the money and record nothing; `confirmed` is\n // reachable for a PAID booking only by this handler having already run,\n // so it is an exact \"already processed\" test. The existence check is\n // new and deliberate: the old merge-set would CREATE a stub booking\n // from a metadata `bookingId` that pointed at nothing.\n let booking: Record<string, any> = {}\n const confirmedNow = await firestore.runTransaction(\n async (transaction) => {\n const snapshot = await transaction.get(bookingRef)\n if (!snapshot.exists) return false\n if (snapshot.get('status') === 'confirmed') return false\n // \"Already processed\" is WIDER than `confirmed` once money can\n // flow back out (AGL-2315). A refunded booking is moved off\n // `confirmed`, so a redelivery arriving afterwards would otherwise\n // read as unprocessed and re-confirm an appointment the merchant\n // has already cancelled and refunded — re-sending the guest a\n // confirmation for it and re-metering the email. Any evidence this\n // handler has run before is the real test, and a refund counter or\n // a recorded PaymentIntent is exactly that evidence.\n if (\n Number(snapshot.get('refundedCents') ?? 0) > 0 ||\n snapshot.get('paymentIntentId')\n ) {\n return false\n }\n booking = (snapshot.data() as any) ?? {}\n transaction.set(\n bookingRef,\n {\n status: 'confirmed',\n paidAmountCents,\n // WHICH TAX REGIME THIS BOOKING CARRIED (AGL-2028), on the\n // document the merchant reads — the stamp every other\n // storefront money door already carries (AGL-2451).\n //\n // DERIVED from the one shared derivation, never a constant.\n // A hand-written \"manual when the metadata says so\" would be\n // a second rule that can drift from the `storefrontTaxCollected`\n // row filed for the same Stripe id, which is the exact\n // disagreement AGL-2451 exists to prevent.\n //\n // TWO-ARGUMENT, because the manual line makes Stripe report\n // `total_details.amount_tax: 0` on a booking that really did\n // charge the client tax; the one-argument form would stamp\n // `none` on precisely those. `absent` remains a fourth state\n // meaning \"recorded before this shipped\".\n taxMode: pluginTaxProfile().taxModeOf(object, taxCents),\n // The figure itself. Absent rather than a defaulted `0` — a\n // zero written through `merge` is the AGL-1758 shape, and\n // this handler can re-enter (see the widened guard above).\n ...(taxCents > 0 ? { taxCents } : {}),\n // The refund handles (AGL-2315). Written inside the same\n // transaction as the status, so a booking can never read\n // `confirmed` while the means to refund it are missing.\n ...(paymentIntentId ? { paymentIntentId } : {}),\n feeCents: chargedFeeCents,\n ...(direct\n ? {\n chargeModel: 'direct',\n ...(eventAccount ? { stripeAccountId: eventAccount } : {}),\n }\n : {}),\n // WHICH CHECKOUT PAID FOR THIS (AGL-2481). The guest's browser\n // comes back from Stripe holding a session id and nothing\n // else — a booking id was never in the return URL — so this is\n // what lets `booking-analytics.ts` answer \"what did I just\n // buy?\" for the merchant-side `purchase`, and it is written\n // here because the session id first exists on this event.\n //\n // Inside the transaction with the status on purpose: the\n // lookup refuses anything that is not `confirmed`, so a\n // booking can never be findable by session id while reading as\n // unpaid.\n ...(object?.id ? { checkoutSessionId: String(object.id) } : {}),\n // NOTE the absent `refundedCents: 0`. Seeding it here would be\n // the AGL-1758 shape: a defaulted field written through\n // `merge` destroying the real one. This handler can re-enter\n // after a refund has already accumulated a counter (see the\n // widened guard above), and a zero written back over it would\n // re-open the full amount for refunding a second time. Absent\n // IS zero — every reader coerces with `?? 0`.\n expiresAtMs: firebaseAdmin.firestore.FieldValue.delete(),\n confirmedAt:\n firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n // The booking is confirmed now, in this transaction (AGL-3643).\n const nowMs = Date.now()\n stageBookingEvent(transaction, firestore, {\n event: 'booking.created',\n hostId: String(hostId),\n bookingId: String(bookingId),\n booking: {\n ...booking,\n status: 'confirmed',\n paidAmountCents,\n ...(taxCents > 0 ? { taxCents } : {}),\n expiresAtMs: null,\n },\n nowMs,\n })\n return true\n },\n )\n if (!confirmedNow) return\n // THE RECORD'S MEETING (AGL-2660). Payment is what confirms a paid\n // booking, so this is where it reaches the CRM: the meeting on the\n // record's timeline and, when the service asks, the follow-up task.\n // Inside the idempotency gate for the same reason the GA4 purchase\n // below is — a redelivery must not file a second meeting — and\n // through `after()` for the same reason too: this invocation is\n // frozen the moment the response is sent (AGL-2327). Never thrown:\n // the writer swallows its own failures, and the catch is for the\n // scheduling itself.\n after(() =>\n fileBookingOnCrm(firestore, {\n hostId: String(hostId),\n bookingId: String(bookingId),\n booking,\n }).catch(() => undefined),\n )\n // AGLYN'S REVENUE ON THIS BOOKING (AGL-2481) — into OUR GA4 property.\n //\n // ## Why it is inside the idempotency gate rather than beside it\n //\n // This sits AFTER `if (!confirmedNow) return` and that placement is the\n // whole guard. Stripe redelivers `checkout.session.completed` for up to\n // three days after any 500, and this endpoint 500s on purpose; a\n // redelivery re-enters this handler, the transaction above sees a\n // `confirmed` status (or a refund counter, or a recorded PaymentIntent)\n // and answers false, and everything below — the contact, the email, and\n // now this — is skipped. A `purchase` fired before that gate, or beside\n // it, would inflate our own reported revenue by the redelivery rate.\n //\n // `transaction_id` is the checkout session id, which is the same key\n // the guard turns on, so GA4's own de-duplication is a second\n // independent line of defence: even if the Firestore guard were ever\n // bypassed, GA would collapse the repeats.\n //\n // ## Platform NET, and the fee is the measured one\n //\n // `value` is our fee and not the $95 the guest paid — the AGL-1639\n // settlement. This is our property, the subscription and marketplace\n // `purchase` events in it already mean \"what Aglyn was paid\", and a\n // gross booking figure sitting beside them would make every combined\n // total, ARPA and revenue audience wrong. The merchant's own gross goes\n // to the MERCHANT's property, client-side, and the two never meet.\n //\n // The figure comes off the session's `metadata.feeCents` — the fee\n // Stripe actually charged as `application_fee_amount` — never from the\n // plan's rate re-applied here. See `bookingPlatformNetCents`.\n //\n // ## Scheduling and failure posture\n //\n // `after()`, never a bare `void` (AGL-2327/AGL-2346): this runs inside\n // the console's `/api/billing/webhook` invocation, which is frozen the\n // moment the response is sent, so fire-and-forget work scheduled any\n // other way simply does not run — the exact way marketplace revenue\n // reported to nothing. And `.catch()`, because a throw here would\n // un-claim the Stripe event and turn a missed analytics hit into a\n // repeated billing side effect.\n if (shouldSendBookingPlatformPurchase(object)) {\n const netCents = bookingPlatformNetCents(object)\n after(() =>\n sendGa4Purchase({\n transactionId: String(object?.id ?? ''),\n value: netCents / 100,\n currency: String(object?.currency ?? 'usd'),\n items: [\n {\n // Ids only, no merchant free text. A service name is\n // merchant-authored and one edit away from carrying a\n // person's name into a dimension in OUR property; the id\n // already identifies it. The merchant's own property gets\n // the name, because there it is their own content.\n item_id: String(booking['serviceId'] ?? bookingId),\n item_name: String(booking['serviceId'] ?? bookingId),\n item_category: 'booking',\n // GA expects the items to sum to `value`; one item, one\n // price, and that price is our fee — not the service's.\n price: netCents / 100,\n quantity: 1,\n },\n ],\n // Booking sessions carry no `ga_client_id` today — nothing\n // captures one on a tenant site — so this is read for the day\n // one is stamped and the seed below is what actually resolves.\n clientId: object?.metadata?.ga_client_id,\n // ONE PAYING GUEST, ONE SYNTHETIC USER. Seeded from Stripe's\n // customer where there is one, and otherwise from the guest's\n // email, which `server.ts` passes as `customer_email` and Stripe\n // echoes on `customer_details`. The seed is hashed inside\n // `synthesizeClientId` and never transmitted.\n //\n // The booking id is the LAST resort deliberately: it is unique\n // per appointment, so seeding from it would turn a regular\n // client into a crowd of one-purchase strangers and make ARPA\n // nonsense — precisely what that helper's determinism exists to\n // prevent. Without any seed at all `sendGa4Purchase` returns\n // `no-client-id` and the event is silently never sent, which is\n // the void this whole change exists to close.\n stripeCustomerId:\n String(object?.customer ?? '') ||\n String(object?.customer_details?.email ?? '') ||\n String(bookingId),\n }).catch(() => undefined),\n )\n }\n // Contacts ingestion (AGL-1755). `server.ts` captures the contact at\n // REQUEST time, which is the right place — the booking is written\n // `pendingPayment` and at that moment no money has moved, so passing an\n // amount there would be a lie. But payment completes HERE, and this\n // handler never returned to the contact, so a paid booking's money\n // reached the booking document and nothing else. The same structural\n // shape as AGL-1748's draft branch: the completion handler does\n // everything except the contact.\n //\n // `source` stays `'booking'` — the same source the request-time capture\n // used — so the `sources` map still says where this person came from\n // and no schema change is needed to keep service revenue\n // distinguishable from product revenue. The second interaction is\n // deliberate rather than a duplicate: \"Booked X\" and \"Paid for X\" are\n // two real events, and `mergeContactInteraction` does not dedupe on\n // `refId`.\n //\n // The amount is `amount_total`, the money that moved, per AGL-1698 and\n // AGL-1711 — the booking document stores no price to re-derive it from.\n if (booking['email']) {\n void recordCapturedContact({\n orgId: '',\n hostId: String(hostId),\n identity: {\n email: booking['email'],\n ...(booking['name'] ? { name: String(booking['name']) } : {}),\n },\n // Paid, so a relationship (AGL-3232): the lead the request-time\n // capture filed for the address is closed onto the contact.\n surface: 'relationship',\n // The phone the booking form asked for (AGL-3493), onto the\n // contact only where it holds none — as the request-time\n // capture put it on the lead.\n ...(readBookingPhone(booking['phone'])\n ? { profileFill: { phone: readBookingPhone(booking['phone']) } }\n : {}),\n // Paid, so a customer (AGL-2612) — the request-time capture\n // said `lead`, and this is the door that has seen the money.\n lifecycleFloor: 'customer',\n // The SERVICE, not the charge (AGL-2028). `amount_total` now\n // includes the merchant's service tax where they set one, and\n // tax is collected for an authority rather than earned — booking\n // it as lifetime value would over-state what every service\n // client is worth. Identical to `paidAmountCents` on the default\n // store, which sets no rate.\n ...(serviceCents > 0 ? { purchaseCents: serviceCents } : {}),\n interaction: {\n source: 'booking',\n refId: String(bookingId),\n summary: `Paid for \"${String(\n booking['serviceName'] ?? 'a service',\n ).slice(0, 60)}\" ($${(serviceCents / 100).toFixed(2)})`,\n },\n })\n }\n // In the booking's own zone, and named (AGL-3432): a formatter with\n // no zone reads in the server's — UTC — and tells a paying guest the\n // wrong hour, and an empty zone prints \"()\".\n const timezone = await bookingTimeZoneFor(\n firestore,\n String(hostId),\n booking,\n )\n const when = formatBookingWhen(Number(booking['startsAtMs']), timezone)\n const paid = `$${(paidAmountCents / 100).toFixed(2)}`\n // The site's managers hear of a PAID booking too (AGL-3500): the\n // free path tells them when the request lands, and a paid one is\n // only a booking once this event has cleared the charge, so this is\n // its moment. Who, what, when, what was paid, and the phone and\n // address the service asked for.\n const contactLines = bookingContactLines(booking)\n void notifyHostManagers(String(hostId), {\n type: 'content.booking',\n title: 'New booking on {site}',\n body:\n `${String(booking['name'] ?? '') || 'A guest'}` +\n (booking['email'] ? ` (${String(booking['email'])})` : '') +\n ` booked ${String(booking['serviceName'] ?? '') || 'a service'} ` +\n `on {site} for ${when} (${timezone}). ${paid} was paid.` +\n (contactLines.length ? ` ${contactLines.join('. ')}.` : ''),\n link: `/${hostId}/bookings`,\n })\n // Confirmation email now that payment cleared (env-gated inside\n // sendEmail, which no-ops when Resend isn't configured).\n if (booking['email']) {\n const fallbackText =\n `Hi ${booking['name'] ?? ''},\\n\\nPayment received — ` +\n `\"${booking['serviceName'] ?? 'your booking'}\" is ` +\n `confirmed for ${when} (${timezone}). You paid ${paid}.` +\n `\\n\\nReference: ${bookingId}`\n // Site-owner-designed template when published (AGL-770); null keeps\n // the built-in copy.\n const designed = await renderHostEmailWithTokens(\n firebaseAdmin.app().firestore(),\n String(hostId),\n 'booking-confirmed',\n {\n name: String(booking['name'] ?? ''),\n 'service.name': String(booking['serviceName'] ?? ''),\n when,\n timezone,\n 'booking.payment': `You paid ${paid}.`,\n 'booking.ref': String(bookingId),\n },\n )\n // White-label sender identity (White-Label Phase 3), matching the\n // free-booking path — the store's brand via the one shared resolver.\n const branding = resolveBrandingProfile(\n (await getOrgForHost(String(hostId)).catch(() => null))?.org as never,\n )\n const emailOutcome = await sendEmail({\n to: String(booking['email']),\n subject:\n designed?.subject ??\n `Booking confirmed: ${booking['serviceName'] ?? ''}`,\n text: designed?.text || fallbackText,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(String(hostId)),\n audience: 'tenant',\n context: 'paid booking confirmation',\n // Owed to the recipient by their own booking: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'booking',\n })\n // Cost meter (AGL-1438), matching the free-booking path.\n // Transactional: the guest has already paid.\n // Only a sent email is metered (AGL-4227).\n if (emailOutcome?.sent) await meterHostEmail(String(hostId))\n }\n }\n }\n}\n"],"names":["after","resolveBrandingProfile","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","notifyHostManagers","notifyRiskEvent","renderHostEmailWithTokens","sendGa4Purchase","paymentRiskEventFrom","recordPaymentRiskOnRecord","settlePaymentRiskDisputeOnRecord","reverseDestinationTransfer","recordCapturedContact","bookingPlatformNetCents","shouldSendBookingPlatformPurchase","sendEmail","pluginTaxProfile","fileBookingOnCrm","stageBookingEvent","bookingTimeZoneFor","formatBookingWhen","bookingContactLines","readBookingPhone","GRPC_FAILED_PRECONDITION","findBookingForPayment","paymentIntentId","matches","app","firestore","collectionGroup","where","limit","get","catch","error","code","console","docs","length","reverseBookingSellerShare","bookingRef","dispute","disputeId","String","id","amountCents","Math","max","round","Number","amount","cents","settled","prior","failedReason","outcome","kind","chargeId","charge","metadata","bookingId","record","reversedTransferCents","reversalId","transferReversalId","atMs","Date","now","reason","owedCents","wrote","runTransaction","transaction","fresh","exists","current","set","disputeReversal","merge","bookingsBillingWebhookHandler","type","object","event","eventAccount","account","trim","risk","booking","hostId","ref","parent","signal","subjectLabel","link","notificationType","isFinite","toFixed","evidenceDueByMs","evidence_details","due_by","notifyRisk","claimed","payment_intent","status","recovered","recoveredText","guest","service","title","body","undefined","payment_status","collection","doc","paidAmountCents","amount_total","taxCents","serviceCents","chargedFeeCents","feeCents","direct","chargeModel","Boolean","confirmedNow","snapshot","data","taxMode","taxModeOf","stripeAccountId","checkoutSessionId","expiresAtMs","FieldValue","delete","confirmedAt","serverTimestamp","nowMs","netCents","transactionId","value","currency","items","item_id","item_name","item_category","price","quantity","clientId","ga_client_id","stripeCustomerId","customer","customer_details","email","orgId","identity","name","surface","profileFill","phone","lifecycleFloor","purchaseCents","interaction","source","refId","summary","slice","timezone","when","paid","contactLines","join","fallbackText","designed","branding","org","emailOutcome","to","subject","text","html","fromName","sendingIdentity","audience","context","owedFor","sent"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,8EAA8E;AAC9E,4EAA4E;AAC5E,oDAAoD;AACpD,SAASA,KAAK,QAAQ,cAAa;AAGnC,SAASC,sBAAsB,QAAQ,sBAAqB;AAC5D,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,kBAAkB,EAClBC,eAAe,EACfC,yBAAyB,EACzBC,eAAe,QACV,2BAA0B;AACjC,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SACEC,yBAAyB,EACzBC,gCAAgC,QAC3B,sDAAqD;AAC5D,SACEC,0BAA0B,QAErB,2DAA0D;AACjE,OAAOC,2BAA2B,sDAAqD;AACvF,SACEC,uBAAuB,EACvBC,iCAAiC,QAC5B,yCAAqC;AAC5C,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,gBAAgB,QAAQ,iDAAgD;AACjF,SAASC,gBAAgB,QAAQ,mBAAe;AAChD,SAASC,iBAAiB,QAAQ,sBAAkB;AACpD,SAASC,kBAAkB,QAAQ,yBAAqB;AACxD,SAASC,iBAAiB,QAAQ,2BAAuB;AACzD,SACEC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAiC;AAExC;;;;CAIC,GACD,iFAAiF,GACjF,MAAMC,2BAA2B;AAEjC;;;;;;CAMC,GACD,eAAeC,sBACbC,eAAuB;IAEvB,IAAI,CAACA,iBAAiB,OAAO;IAC7B,MAAMC,UAAU,MAAM1B,cACnB2B,GAAG,GACHC,SAAS,GACTC,eAAe,CAAC,YAChBC,KAAK,CAAC,mBAAmB,MAAML,iBAC/BM,KAAK,CAAC,GACNC,GAAG,GACHC,KAAK,CAAC,CAACC;QACN,IAAIA,CAAAA,yBAAAA,MAAOC,IAAI,MAAKZ,0BAA0B,MAAMW;QACpDE,QAAQF,KAAK,CACX,gEACE,uCACFA;QAEF,OAAO;IACT;IACF,yEAAyE;IACzE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B,MAAM+G,WAAW,MAAMrK,0BACrBN,cAAc2B,GAAG,GAAGC,SAAS,IAC7Be,OAAO6C,SACP,qBACA;oBACEkE,MAAM/G,QAAO4C,iBAAAA,OAAO,CAAC,OAAO,YAAfA,iBAAmB;oBAChC,gBAAgB5C,QAAO4C,wBAAAA,OAAO,CAAC,cAAc,YAAtBA,wBAA0B;oBACjD+E;oBACAD;oBACA,mBAAmB,CAAC,SAAS,EAAEE,KAAK,CAAC,CAAC;oBACtC,eAAe5H,OAAOiB;gBACxB;gBAEF,kEAAkE;gBAClE,qEAAqE;gBACrE,MAAMgH,WAAW7K,wBACd,QAAA,MAAME,cAAc0C,OAAO6C,SAASvD,KAAK,CAAC,IAAM,0BAAjD,AAAC,MAAwD4I,GAAG;gBAE9D,MAAMC,eAAe,MAAM/J,UAAU;oBACnCgK,IAAIpI,OAAO4C,OAAO,CAAC,QAAQ;oBAC3ByF,OAAO,YACLL,4BAAAA,SAAUK,OAAO,qBACjB,CAAC,mBAAmB,GAAEzF,wBAAAA,OAAO,CAAC,cAAc,YAAtBA,wBAA0B,IAAI;oBACtD0F,MAAMN,CAAAA,4BAAAA,SAAUM,IAAI,KAAIP;mBACpBC,CAAAA,4BAAAA,SAAUO,IAAI,IAAG;oBAAEA,MAAMP,SAASO,IAAI;gBAAC,IAAI,CAAC;oBAChDC,UAAUP,SAASO,QAAQ;oBAC3BC,iBAAiB,MAAMlL,oBAAoByC,OAAO6C;oBAClD6F,UAAU;oBACVC,SAAS;oBACT,2DAA2D;oBAC3D,gDAAgD;oBAChDC,SAAS;;gBAEX,yDAAyD;gBACzD,6CAA6C;gBAC7C,2CAA2C;gBAC3C,IAAIT,gCAAAA,aAAcU,IAAI,EAAE,MAAMrL,eAAewC,OAAO6C;YACtD;QACF;IACF;AACJ,EAAC"}
@@ -337,7 +337,7 @@ export function createBookingRescheduleHandler(deps) {
337
337
  'booking.ref': notice.bookingId
338
338
  });
339
339
  const branding = resolveBrandingProfile((_this = await getOrgForHost(notice.hostId).catch(()=>null)) == null ? void 0 : _this.org);
340
- await sendEmail(_extends({
340
+ const sent = await sendEmail(_extends({
341
341
  to: notice.to,
342
342
  subject: (_ref = designed == null ? void 0 : designed.subject) != null ? _ref : `New time for ${notice.serviceName}`,
343
343
  text: (designed == null ? void 0 : designed.text) || fallbackText
@@ -350,7 +350,8 @@ export function createBookingRescheduleHandler(deps) {
350
350
  context: 'booking rescheduled',
351
351
  owedFor: 'booking'
352
352
  }));
353
- await meterHostEmail(notice.hostId);
353
+ // Metered only when it left (AGL-4227): a refused notice is not a cost.
354
+ if (sent == null ? void 0 : sent.sent) await meterHostEmail(notice.hostId);
354
355
  }
355
356
  /** The production wiring: the Admin SDK, the site lockdown verdict and the real send. */ export function bookingManageDeps() {
356
357
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/booking-manage.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 { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/app-utils/api-plugins'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n} from '@aglyn/tenant-data-admin'\nimport { getSiteLockdown } from '@aglyn/tenant-data-admin/server/tenant-write-lockdown'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/server'\nimport {\n bookingDurationMs,\n bookingState,\n cancelRefusal,\n checkInRefusal,\n type ManagedBooking,\n rescheduleRefusal,\n} from '../model/booking-manage'\nimport { type BookedInterval, type HostBookingService, isSlotOpen } from '../model/bookings'\nimport { bookingTimeZone, formatBookingWhen, storedBookingTimeZone } from '../model/booking-time'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { type BookingEventInput, raiseBookingEvent } from './booking-events'\n\n/*\n * Checking a guest in and moving a booking (AGL-3621), for the site's team.\n *\n * The native Aglyn app's bookings calendar calls these; any console surface\n * may too. Each is a member route: the caller's ID token names them, they\n * must hold \"Edit site content\" on the site (`site.edit`, AGL-4047: the key\n * the rules ask to write a booking directly, whose preset is the\n * content-writing roles that did before), and a locked-down site refuses. Each decides inside\n * ONE transaction, re-reading the booking, so two phones acting at once\n * cannot both move it or check in a guest whose booking was just canceled.\n *\n * Moving a booking re-checks the new slot against the service's hours and\n * every other live booking of that service in the same transaction the\n * public booking route uses, so a move can never double-book. It keeps the\n * booking's own length, clears the reminder stamp so the 24-hour reminder\n * goes out for the new time, and tells the guest by email.\n */\n\n/** The Firestore surface these routes use: the Admin SDK's, narrowed so a spec can hand in a double. */\nexport interface ManageDocSnapshot {\n readonly exists: boolean\n readonly id?: string\n get(field: string): unknown\n data(): Record<string, unknown> | undefined\n}\nexport interface ManageDocRef {\n readonly id: string\n}\nexport interface ManageQuery {\n where(field: string, op: '==' | '>=' | '<', value: unknown): ManageQuery\n limit(count: number): ManageQuery\n}\nexport interface ManageTransaction {\n get(ref: ManageDocRef): Promise<ManageDocSnapshot>\n get(query: ManageQuery): Promise<{ docs: ManageDocSnapshot[] }>\n update(ref: ManageDocRef, data: Record<string, unknown>): unknown\n}\nexport interface ManageFirestore {\n doc(path: string): ManageDocRef & { get(): Promise<ManageDocSnapshot> }\n collection(path: string): ManageQuery\n runTransaction<T>(fn: (transaction: ManageTransaction) => Promise<T>): Promise<T>\n}\n\nexport interface RescheduleNotice {\n hostId: string\n bookingId: string\n to: string\n name: string\n serviceName: string\n when: string\n previousWhen: string\n timezone: string\n}\n\nexport interface BookingManageDeps {\n firestore: () => ManageFirestore\n verifyIdToken: (token: string) => Promise<{ uid: string }>\n /** True when the site is locked down and must not take writes. */\n siteLocked: (hostId: string) => Promise<boolean>\n /** The zone a booking is told in when the document carries none. */\n timeZoneFor: (hostId: string, service: HostBookingService | undefined) => Promise<string>\n notifyRescheduled: (notice: RescheduleNotice) => Promise<void>\n now: () => number\n /**\n * Raises a booking event once the change is written (AGL-3643): the move,\n * the cancel. Never throws. Absent, nothing is raised.\n */\n raiseEvent?: (input: BookingEventInput) => Promise<void>\n}\n\n/** Field the booking stamps when the guest arrives. */\nexport const CHECKED_IN_AT = 'checkedInAtMs'\nexport const CHECKED_IN_BY = 'checkedInBy'\n\nclass Refusal extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message)\n }\n}\n\nconst bearerOf = (req: PluginApiRequest): string => {\n const header = String(req.headers['authorization'] ?? req.headers['Authorization'] ?? '')\n return header.startsWith('Bearer ') ? header.slice('Bearer '.length) : ''\n}\n\nconst bodyOf = (req: PluginApiRequest): Record<string, unknown> => {\n if (typeof req.body === 'string') {\n try {\n return JSON.parse(req.body) as Record<string, unknown>\n } catch {\n return {}\n }\n }\n return (req.body ?? {}) as Record<string, unknown>\n}\n\n/** The member, their right to write this site's bookings, and the site being open. */\nasync function authorize(\n deps: BookingManageDeps,\n req: PluginApiRequest,\n hostId: string,\n): Promise<{ uid: string }> {\n const token = bearerOf(req)\n if (!token) throw new Refusal(401, 'Unauthenticated')\n let uid: string\n try {\n uid = (await deps.verifyIdToken(token)).uid\n } catch (error) {\n if (!isRefusedIdToken(error)) throw error\n throw new Refusal(401, 'Unauthenticated')\n }\n const host = await deps.firestore().doc(`hosts/${hostId}`).get()\n if (!host.exists) throw new Refusal(404, 'Unknown site')\n if (!holdsSiteKey(host, uid, 'site.edit')) throw new Refusal(403, siteKeyRefusal('site.edit'))\n if (await deps.siteLocked(hostId)) throw new Refusal(423, 'This site is locked and cannot take changes right now')\n return { uid }\n}\n\nfunction answer(res: Parameters<PluginApiHandler>[1], error: unknown): void {\n if (error instanceof Refusal) {\n res.status(error.status).json({ error: error.message })\n return\n }\n console.error('[bookings/manage]', error)\n res.status(500).json({ error: 'That did not go through. Try again.' })\n}\n\nexport function createBookingCheckInHandler(deps: BookingManageDeps): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n const checkedIn = body['checkedIn'] !== false\n if (!hostId || !bookingId) return res.status(400).json({ error: 'Missing hostId or bookingId' })\n try {\n const { uid } = await authorize(deps, req, hostId)\n const firestore = deps.firestore()\n const ref = firestore.doc(`hosts/${hostId}/bookings/${bookingId}`)\n const result = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new Refusal(404, 'Unknown booking')\n const booking = (snapshot.data() ?? {}) as ManagedBooking\n const nowMs = deps.now()\n const refusal = checkInRefusal(booking, checkedIn, nowMs)\n if (refusal) throw new Refusal(409, refusal)\n const already = Number(booking.checkedInAtMs ?? 0) > 0\n // Already where it was asked to be: a retried tap changes nothing.\n if (already === checkedIn) return { checkedInAtMs: already ? Number(booking.checkedInAtMs) : null }\n if (checkedIn) {\n transaction.update(ref, { [CHECKED_IN_AT]: nowMs, [CHECKED_IN_BY]: uid })\n return { checkedInAtMs: nowMs }\n }\n transaction.update(ref, { [CHECKED_IN_AT]: null, [CHECKED_IN_BY]: null })\n return { checkedInAtMs: null }\n })\n return res.status(200).json({ ok: true, ...result })\n } catch (error) {\n return answer(res, error)\n }\n }\n}\n\nexport function createBookingRescheduleHandler(deps: BookingManageDeps): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n const startsAtMs = Number(body['startsAtMs'])\n if (!hostId || !bookingId) return res.status(400).json({ error: 'Missing hostId or bookingId' })\n if (!Number.isFinite(startsAtMs) || startsAtMs <= 0) return res.status(400).json({ error: 'Pick a new time' })\n try {\n const { uid } = await authorize(deps, req, hostId)\n const firestore = deps.firestore()\n const ref = firestore.doc(`hosts/${hostId}/bookings/${bookingId}`)\n const first = await ref.get()\n if (!first.exists) throw new Refusal(404, 'Unknown booking')\n const serviceId = String(first.get('serviceId') ?? '')\n const serviceSnapshot = serviceId ? await firestore.doc(`hosts/${hostId}/services/${serviceId}`).get() : null\n const service = serviceSnapshot?.exists ? (serviceSnapshot.data() as unknown as HostBookingService) : undefined\n if (!service || serviceSnapshot?.get('deletedAt')) {\n throw new Refusal(409, 'This booking’s service no longer exists, so it cannot move')\n }\n\n const moved = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new Refusal(404, 'Unknown booking')\n const booking = (snapshot.data() ?? {}) as ManagedBooking & Record<string, unknown>\n const nowMs = deps.now()\n const refusal = rescheduleRefusal(booking, startsAtMs, nowMs)\n if (refusal) throw new Refusal(409, refusal)\n const previousStartsAtMs = Number(booking.startsAtMs ?? 0)\n // Already at that time: a retried move writes nothing and tells no one twice.\n if (previousStartsAtMs === startsAtMs) return null\n const durationMs = bookingDurationMs(booking, service.durationMinutes)\n // The public booking route's own read: every booking of this service\n // from a day before the new time, so one running into it counts.\n const nearby = await transaction.get(\n firestore\n .collection(`hosts/${hostId}/bookings`)\n .where('serviceId', '==', serviceId)\n .where('startsAtMs', '>=', startsAtMs - 24 * 60 * 60_000)\n .limit(500),\n )\n const booked: BookedInterval[] = nearby.docs\n .filter((doc) => doc.id !== bookingId)\n .filter((doc) => {\n const status = doc.get('status')\n if (status === 'canceled') return false\n return !(status === 'pendingPayment' && Number(doc.get('expiresAtMs') ?? 0) < nowMs)\n })\n .map((doc) => ({ startsAtMs: Number(doc.get('startsAtMs') ?? 0), endsAtMs: Number(doc.get('endsAtMs') ?? 0) }))\n if (!isSlotOpen(service, startsAtMs, booked)) throw new Refusal(409, 'That time is not open. Pick another.')\n const endsAtMs = startsAtMs + durationMs\n transaction.update(ref, {\n startsAtMs,\n endsAtMs,\n rescheduledAtMs: nowMs,\n rescheduledBy: uid,\n rescheduledFromMs: previousStartsAtMs,\n // The reminder is owed again, for the new time.\n reminderSentAt: null,\n })\n return { booking, previousStartsAtMs, endsAtMs }\n })\n\n if (!moved) {\n return res.status(200).json({ ok: true, startsAtMs, endsAtMs: Number(first.get('endsAtMs') ?? 0), notified: false })\n }\n // Keyed by the booking and its new time: a retried move raises it once.\n await deps.raiseEvent?.({\n event: 'booking.rescheduled',\n hostId,\n bookingId,\n booking: {\n ...moved.booking,\n startsAtMs,\n endsAtMs: moved.endsAtMs,\n rescheduledFromMs: moved.previousStartsAtMs,\n },\n })\n const to = String(moved.booking['email'] ?? '').trim()\n let notified = false\n if (to) {\n const timezone = storedBookingTimeZone({ timezone: moved.booking['timezone'] }) ?? (await deps.timeZoneFor(hostId, service))\n try {\n await deps.notifyRescheduled({\n hostId,\n bookingId,\n to,\n name: String(moved.booking['name'] ?? ''),\n serviceName: String(moved.booking['serviceName'] ?? service.name ?? ''),\n when: formatBookingWhen(startsAtMs, timezone),\n previousWhen: formatBookingWhen(moved.previousStartsAtMs, timezone),\n timezone,\n })\n notified = true\n } catch (error) {\n // The booking has moved whatever the mail did; the screen says the guest was not told.\n console.error('[bookings/reschedule] notice failed', hostId, bookingId, error)\n }\n }\n return res.status(200).json({ ok: true, startsAtMs, endsAtMs: moved.endsAtMs, notified })\n } catch (error) {\n return answer(res, error)\n }\n }\n}\n\n/**\n * Canceling a booking that has no money on it (AGL-3643): a free booking, or\n * a paid one already refunded in full. The site's team used to write\n * `status: 'canceled'` straight from the console; a route is where the\n * cancel can be told to the plugins that listen for it (`booking.canceled`),\n * and where the rule that a paid booking cancels through its refund is held\n * rather than trusted to the screen. One transaction: a booking checked in\n * or paid a moment ago is refused, and canceling it twice changes nothing.\n */\nexport function createBookingCancelHandler(deps: BookingManageDeps): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n if (!hostId || !bookingId) return res.status(400).json({ error: 'Missing hostId or bookingId' })\n try {\n const { uid } = await authorize(deps, req, hostId)\n const firestore = deps.firestore()\n const ref = firestore.doc(`hosts/${hostId}/bookings/${bookingId}`)\n const canceled = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new Refusal(404, 'Unknown booking')\n const booking = (snapshot.data() ?? {}) as ManagedBooking & Record<string, unknown>\n const nowMs = deps.now()\n const refusal = cancelRefusal(booking, nowMs)\n if (refusal) throw new Refusal(409, refusal)\n // Already canceled: a retried tap writes nothing and tells no one twice.\n if (bookingState(booking, nowMs) === 'canceled') return null\n transaction.update(ref, { status: 'canceled', canceledAtMs: nowMs, canceledBy: uid })\n return { ...booking, status: 'canceled', canceledAtMs: nowMs }\n })\n if (canceled) {\n await deps.raiseEvent?.({ event: 'booking.canceled', hostId, bookingId, booking: canceled })\n }\n return res.status(200).json({ ok: true, canceled: true })\n } catch (error) {\n return answer(res, error)\n }\n }\n}\n\n/** The email that tells a guest their booking moved, as the confirmation is sent. */\nexport async function sendRescheduledNotice(notice: RescheduleNotice): Promise<void> {\n if (!isEmailConfigured()) throw new Error('Email is not configured')\n const firestore = firebaseAdmin.app().firestore()\n const fallbackText =\n `Hi ${notice.name},\\n\\nYour booking for \"${notice.serviceName}\" is now on ` +\n `${notice.when} (${notice.timezone}). It was on ${notice.previousWhen}.\\n\\n` +\n `Reference: ${notice.bookingId}`\n const designed = await renderHostEmailWithTokens(firestore, notice.hostId, 'booking-rescheduled', {\n name: notice.name,\n 'service.name': notice.serviceName,\n when: notice.when,\n previousWhen: notice.previousWhen,\n timezone: notice.timezone,\n 'booking.ref': notice.bookingId,\n })\n const branding = resolveBrandingProfile((await getOrgForHost(notice.hostId).catch(() => null))?.org as never)\n await sendEmail({\n to: notice.to,\n subject: designed?.subject ?? `New time for ${notice.serviceName}`,\n text: designed?.text || fallbackText,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(notice.hostId),\n audience: 'tenant',\n context: 'booking rescheduled',\n owedFor: 'booking',\n })\n await meterHostEmail(notice.hostId)\n}\n\n/** The production wiring: the Admin SDK, the site lockdown verdict and the real send. */\nexport function bookingManageDeps(): BookingManageDeps {\n return {\n firestore: () => firebaseAdmin.app().firestore() as unknown as ManageFirestore,\n verifyIdToken: (token) => firebaseAdmin.app().auth().verifyIdToken(token),\n siteLocked: async (hostId) => Boolean(await getSiteLockdown(hostId)),\n timeZoneFor: async (hostId, service) => {\n const firestore = firebaseAdmin.app().firestore()\n const [host, owner] = await Promise.all([\n firestore.collection('hosts').doc(hostId).get(),\n getOrgForHost(hostId).catch(() => null),\n ])\n return bookingTimeZone({\n service: service ?? null,\n host: host.data() as { timeZone?: string } | undefined,\n org: owner?.org as { timeZone?: string } | null | undefined,\n })\n },\n notifyRescheduled: sendRescheduledNotice,\n now: () => Date.now(),\n raiseEvent: (input) => raiseBookingEvent(firebaseAdmin.app().firestore(), input),\n }\n}\n"],"names":["holdsSiteKey","siteKeyRefusal","isEmailConfigured","sendEmail","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","getSiteLockdown","resolveBrandingProfile","bookingDurationMs","bookingState","cancelRefusal","checkInRefusal","rescheduleRefusal","isSlotOpen","bookingTimeZone","formatBookingWhen","storedBookingTimeZone","isRefusedIdToken","raiseBookingEvent","CHECKED_IN_AT","CHECKED_IN_BY","Refusal","Error","status","message","bearerOf","req","header","String","headers","startsWith","slice","length","bodyOf","body","JSON","parse","authorize","deps","hostId","token","uid","verifyIdToken","error","host","firestore","doc","get","exists","siteLocked","answer","res","json","console","createBookingCheckInHandler","method","bookingId","checkedIn","ref","result","runTransaction","transaction","snapshot","booking","data","nowMs","now","refusal","already","Number","checkedInAtMs","update","ok","createBookingRescheduleHandler","startsAtMs","isFinite","first","moved","serviceId","serviceSnapshot","service","undefined","previousStartsAtMs","durationMs","durationMinutes","nearby","collection","where","limit","booked","docs","filter","id","map","endsAtMs","rescheduledAtMs","rescheduledBy","rescheduledFromMs","reminderSentAt","notified","raiseEvent","event","to","trim","timezone","timeZoneFor","notifyRescheduled","name","serviceName","when","previousWhen","createBookingCancelHandler","canceled","canceledAtMs","canceledBy","sendRescheduledNotice","notice","app","fallbackText","designed","branding","catch","org","subject","text","html","fromName","sendingIdentity","audience","context","owedFor","bookingManageDeps","auth","Boolean","owner","Promise","all","Date","input"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AAEtF,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,QACpB,2BAA0B;AACjC,SAASC,eAAe,QAAQ,wDAAuD;AACvF,SAASC,sBAAsB,QAAQ,sBAAqB;AAC5D,SACEC,iBAAiB,EACjBC,YAAY,EACZC,aAAa,EACbC,cAAc,EAEdC,iBAAiB,QACZ,6BAAyB;AAChC,SAAuDC,UAAU,QAAQ,uBAAmB;AAC5F,SAASC,eAAe,EAAEC,iBAAiB,EAAEC,qBAAqB,QAAQ,2BAAuB;AACjG,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAAiCC,iBAAiB,QAAQ,sBAAkB;AAwE5E,qDAAqD,GACrD,OAAO,MAAMC,gBAAgB,gBAAe;AAC5C,OAAO,MAAMC,gBAAgB,cAAa;AAE1C,IAAA,AAAMC,UAAN,MAAMA,gBAAgBC;IACpB,YACE,AAASC,MAAc,EACvBC,OAAe,CACf;QACA,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,MAAMA,KAAKoB,IAAI;gBACf0D,GAAG,EAAEY,yBAAAA,MAAOZ,GAAG;YACjB;QACF;QACAhB,mBAAmBS;QACnBjD,KAAK,IAAMuE,KAAKvE,GAAG;QACnBkC,YAAY,CAACsC,QAAUxH,kBAAkBjB,cAAcoH,GAAG,GAAGxE,SAAS,IAAI6F;IAC5E;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/booking-manage.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 { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/app-utils/api-plugins'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n} from '@aglyn/tenant-data-admin'\nimport { getSiteLockdown } from '@aglyn/tenant-data-admin/server/tenant-write-lockdown'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/server'\nimport {\n bookingDurationMs,\n bookingState,\n cancelRefusal,\n checkInRefusal,\n type ManagedBooking,\n rescheduleRefusal,\n} from '../model/booking-manage'\nimport { type BookedInterval, type HostBookingService, isSlotOpen } from '../model/bookings'\nimport { bookingTimeZone, formatBookingWhen, storedBookingTimeZone } from '../model/booking-time'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { type BookingEventInput, raiseBookingEvent } from './booking-events'\n\n/*\n * Checking a guest in and moving a booking (AGL-3621), for the site's team.\n *\n * The native Aglyn app's bookings calendar calls these; any console surface\n * may too. Each is a member route: the caller's ID token names them, they\n * must hold \"Edit site content\" on the site (`site.edit`, AGL-4047: the key\n * the rules ask to write a booking directly, whose preset is the\n * content-writing roles that did before), and a locked-down site refuses. Each decides inside\n * ONE transaction, re-reading the booking, so two phones acting at once\n * cannot both move it or check in a guest whose booking was just canceled.\n *\n * Moving a booking re-checks the new slot against the service's hours and\n * every other live booking of that service in the same transaction the\n * public booking route uses, so a move can never double-book. It keeps the\n * booking's own length, clears the reminder stamp so the 24-hour reminder\n * goes out for the new time, and tells the guest by email.\n */\n\n/** The Firestore surface these routes use: the Admin SDK's, narrowed so a spec can hand in a double. */\nexport interface ManageDocSnapshot {\n readonly exists: boolean\n readonly id?: string\n get(field: string): unknown\n data(): Record<string, unknown> | undefined\n}\nexport interface ManageDocRef {\n readonly id: string\n}\nexport interface ManageQuery {\n where(field: string, op: '==' | '>=' | '<', value: unknown): ManageQuery\n limit(count: number): ManageQuery\n}\nexport interface ManageTransaction {\n get(ref: ManageDocRef): Promise<ManageDocSnapshot>\n get(query: ManageQuery): Promise<{ docs: ManageDocSnapshot[] }>\n update(ref: ManageDocRef, data: Record<string, unknown>): unknown\n}\nexport interface ManageFirestore {\n doc(path: string): ManageDocRef & { get(): Promise<ManageDocSnapshot> }\n collection(path: string): ManageQuery\n runTransaction<T>(fn: (transaction: ManageTransaction) => Promise<T>): Promise<T>\n}\n\nexport interface RescheduleNotice {\n hostId: string\n bookingId: string\n to: string\n name: string\n serviceName: string\n when: string\n previousWhen: string\n timezone: string\n}\n\nexport interface BookingManageDeps {\n firestore: () => ManageFirestore\n verifyIdToken: (token: string) => Promise<{ uid: string }>\n /** True when the site is locked down and must not take writes. */\n siteLocked: (hostId: string) => Promise<boolean>\n /** The zone a booking is told in when the document carries none. */\n timeZoneFor: (hostId: string, service: HostBookingService | undefined) => Promise<string>\n notifyRescheduled: (notice: RescheduleNotice) => Promise<void>\n now: () => number\n /**\n * Raises a booking event once the change is written (AGL-3643): the move,\n * the cancel. Never throws. Absent, nothing is raised.\n */\n raiseEvent?: (input: BookingEventInput) => Promise<void>\n}\n\n/** Field the booking stamps when the guest arrives. */\nexport const CHECKED_IN_AT = 'checkedInAtMs'\nexport const CHECKED_IN_BY = 'checkedInBy'\n\nclass Refusal extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message)\n }\n}\n\nconst bearerOf = (req: PluginApiRequest): string => {\n const header = String(req.headers['authorization'] ?? req.headers['Authorization'] ?? '')\n return header.startsWith('Bearer ') ? header.slice('Bearer '.length) : ''\n}\n\nconst bodyOf = (req: PluginApiRequest): Record<string, unknown> => {\n if (typeof req.body === 'string') {\n try {\n return JSON.parse(req.body) as Record<string, unknown>\n } catch {\n return {}\n }\n }\n return (req.body ?? {}) as Record<string, unknown>\n}\n\n/** The member, their right to write this site's bookings, and the site being open. */\nasync function authorize(\n deps: BookingManageDeps,\n req: PluginApiRequest,\n hostId: string,\n): Promise<{ uid: string }> {\n const token = bearerOf(req)\n if (!token) throw new Refusal(401, 'Unauthenticated')\n let uid: string\n try {\n uid = (await deps.verifyIdToken(token)).uid\n } catch (error) {\n if (!isRefusedIdToken(error)) throw error\n throw new Refusal(401, 'Unauthenticated')\n }\n const host = await deps.firestore().doc(`hosts/${hostId}`).get()\n if (!host.exists) throw new Refusal(404, 'Unknown site')\n if (!holdsSiteKey(host, uid, 'site.edit')) throw new Refusal(403, siteKeyRefusal('site.edit'))\n if (await deps.siteLocked(hostId)) throw new Refusal(423, 'This site is locked and cannot take changes right now')\n return { uid }\n}\n\nfunction answer(res: Parameters<PluginApiHandler>[1], error: unknown): void {\n if (error instanceof Refusal) {\n res.status(error.status).json({ error: error.message })\n return\n }\n console.error('[bookings/manage]', error)\n res.status(500).json({ error: 'That did not go through. Try again.' })\n}\n\nexport function createBookingCheckInHandler(deps: BookingManageDeps): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n const checkedIn = body['checkedIn'] !== false\n if (!hostId || !bookingId) return res.status(400).json({ error: 'Missing hostId or bookingId' })\n try {\n const { uid } = await authorize(deps, req, hostId)\n const firestore = deps.firestore()\n const ref = firestore.doc(`hosts/${hostId}/bookings/${bookingId}`)\n const result = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new Refusal(404, 'Unknown booking')\n const booking = (snapshot.data() ?? {}) as ManagedBooking\n const nowMs = deps.now()\n const refusal = checkInRefusal(booking, checkedIn, nowMs)\n if (refusal) throw new Refusal(409, refusal)\n const already = Number(booking.checkedInAtMs ?? 0) > 0\n // Already where it was asked to be: a retried tap changes nothing.\n if (already === checkedIn) return { checkedInAtMs: already ? Number(booking.checkedInAtMs) : null }\n if (checkedIn) {\n transaction.update(ref, { [CHECKED_IN_AT]: nowMs, [CHECKED_IN_BY]: uid })\n return { checkedInAtMs: nowMs }\n }\n transaction.update(ref, { [CHECKED_IN_AT]: null, [CHECKED_IN_BY]: null })\n return { checkedInAtMs: null }\n })\n return res.status(200).json({ ok: true, ...result })\n } catch (error) {\n return answer(res, error)\n }\n }\n}\n\nexport function createBookingRescheduleHandler(deps: BookingManageDeps): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n const startsAtMs = Number(body['startsAtMs'])\n if (!hostId || !bookingId) return res.status(400).json({ error: 'Missing hostId or bookingId' })\n if (!Number.isFinite(startsAtMs) || startsAtMs <= 0) return res.status(400).json({ error: 'Pick a new time' })\n try {\n const { uid } = await authorize(deps, req, hostId)\n const firestore = deps.firestore()\n const ref = firestore.doc(`hosts/${hostId}/bookings/${bookingId}`)\n const first = await ref.get()\n if (!first.exists) throw new Refusal(404, 'Unknown booking')\n const serviceId = String(first.get('serviceId') ?? '')\n const serviceSnapshot = serviceId ? await firestore.doc(`hosts/${hostId}/services/${serviceId}`).get() : null\n const service = serviceSnapshot?.exists ? (serviceSnapshot.data() as unknown as HostBookingService) : undefined\n if (!service || serviceSnapshot?.get('deletedAt')) {\n throw new Refusal(409, 'This booking’s service no longer exists, so it cannot move')\n }\n\n const moved = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new Refusal(404, 'Unknown booking')\n const booking = (snapshot.data() ?? {}) as ManagedBooking & Record<string, unknown>\n const nowMs = deps.now()\n const refusal = rescheduleRefusal(booking, startsAtMs, nowMs)\n if (refusal) throw new Refusal(409, refusal)\n const previousStartsAtMs = Number(booking.startsAtMs ?? 0)\n // Already at that time: a retried move writes nothing and tells no one twice.\n if (previousStartsAtMs === startsAtMs) return null\n const durationMs = bookingDurationMs(booking, service.durationMinutes)\n // The public booking route's own read: every booking of this service\n // from a day before the new time, so one running into it counts.\n const nearby = await transaction.get(\n firestore\n .collection(`hosts/${hostId}/bookings`)\n .where('serviceId', '==', serviceId)\n .where('startsAtMs', '>=', startsAtMs - 24 * 60 * 60_000)\n .limit(500),\n )\n const booked: BookedInterval[] = nearby.docs\n .filter((doc) => doc.id !== bookingId)\n .filter((doc) => {\n const status = doc.get('status')\n if (status === 'canceled') return false\n return !(status === 'pendingPayment' && Number(doc.get('expiresAtMs') ?? 0) < nowMs)\n })\n .map((doc) => ({ startsAtMs: Number(doc.get('startsAtMs') ?? 0), endsAtMs: Number(doc.get('endsAtMs') ?? 0) }))\n if (!isSlotOpen(service, startsAtMs, booked)) throw new Refusal(409, 'That time is not open. Pick another.')\n const endsAtMs = startsAtMs + durationMs\n transaction.update(ref, {\n startsAtMs,\n endsAtMs,\n rescheduledAtMs: nowMs,\n rescheduledBy: uid,\n rescheduledFromMs: previousStartsAtMs,\n // The reminder is owed again, for the new time.\n reminderSentAt: null,\n })\n return { booking, previousStartsAtMs, endsAtMs }\n })\n\n if (!moved) {\n return res.status(200).json({ ok: true, startsAtMs, endsAtMs: Number(first.get('endsAtMs') ?? 0), notified: false })\n }\n // Keyed by the booking and its new time: a retried move raises it once.\n await deps.raiseEvent?.({\n event: 'booking.rescheduled',\n hostId,\n bookingId,\n booking: {\n ...moved.booking,\n startsAtMs,\n endsAtMs: moved.endsAtMs,\n rescheduledFromMs: moved.previousStartsAtMs,\n },\n })\n const to = String(moved.booking['email'] ?? '').trim()\n let notified = false\n if (to) {\n const timezone = storedBookingTimeZone({ timezone: moved.booking['timezone'] }) ?? (await deps.timeZoneFor(hostId, service))\n try {\n await deps.notifyRescheduled({\n hostId,\n bookingId,\n to,\n name: String(moved.booking['name'] ?? ''),\n serviceName: String(moved.booking['serviceName'] ?? service.name ?? ''),\n when: formatBookingWhen(startsAtMs, timezone),\n previousWhen: formatBookingWhen(moved.previousStartsAtMs, timezone),\n timezone,\n })\n notified = true\n } catch (error) {\n // The booking has moved whatever the mail did; the screen says the guest was not told.\n console.error('[bookings/reschedule] notice failed', hostId, bookingId, error)\n }\n }\n return res.status(200).json({ ok: true, startsAtMs, endsAtMs: moved.endsAtMs, notified })\n } catch (error) {\n return answer(res, error)\n }\n }\n}\n\n/**\n * Canceling a booking that has no money on it (AGL-3643): a free booking, or\n * a paid one already refunded in full. The site's team used to write\n * `status: 'canceled'` straight from the console; a route is where the\n * cancel can be told to the plugins that listen for it (`booking.canceled`),\n * and where the rule that a paid booking cancels through its refund is held\n * rather than trusted to the screen. One transaction: a booking checked in\n * or paid a moment ago is refused, and canceling it twice changes nothing.\n */\nexport function createBookingCancelHandler(deps: BookingManageDeps): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n if (!hostId || !bookingId) return res.status(400).json({ error: 'Missing hostId or bookingId' })\n try {\n const { uid } = await authorize(deps, req, hostId)\n const firestore = deps.firestore()\n const ref = firestore.doc(`hosts/${hostId}/bookings/${bookingId}`)\n const canceled = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new Refusal(404, 'Unknown booking')\n const booking = (snapshot.data() ?? {}) as ManagedBooking & Record<string, unknown>\n const nowMs = deps.now()\n const refusal = cancelRefusal(booking, nowMs)\n if (refusal) throw new Refusal(409, refusal)\n // Already canceled: a retried tap writes nothing and tells no one twice.\n if (bookingState(booking, nowMs) === 'canceled') return null\n transaction.update(ref, { status: 'canceled', canceledAtMs: nowMs, canceledBy: uid })\n return { ...booking, status: 'canceled', canceledAtMs: nowMs }\n })\n if (canceled) {\n await deps.raiseEvent?.({ event: 'booking.canceled', hostId, bookingId, booking: canceled })\n }\n return res.status(200).json({ ok: true, canceled: true })\n } catch (error) {\n return answer(res, error)\n }\n }\n}\n\n/** The email that tells a guest their booking moved, as the confirmation is sent. */\nexport async function sendRescheduledNotice(notice: RescheduleNotice): Promise<void> {\n if (!isEmailConfigured()) throw new Error('Email is not configured')\n const firestore = firebaseAdmin.app().firestore()\n const fallbackText =\n `Hi ${notice.name},\\n\\nYour booking for \"${notice.serviceName}\" is now on ` +\n `${notice.when} (${notice.timezone}). It was on ${notice.previousWhen}.\\n\\n` +\n `Reference: ${notice.bookingId}`\n const designed = await renderHostEmailWithTokens(firestore, notice.hostId, 'booking-rescheduled', {\n name: notice.name,\n 'service.name': notice.serviceName,\n when: notice.when,\n previousWhen: notice.previousWhen,\n timezone: notice.timezone,\n 'booking.ref': notice.bookingId,\n })\n const branding = resolveBrandingProfile((await getOrgForHost(notice.hostId).catch(() => null))?.org as never)\n const sent = await sendEmail({\n to: notice.to,\n subject: designed?.subject ?? `New time for ${notice.serviceName}`,\n text: designed?.text || fallbackText,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(notice.hostId),\n audience: 'tenant',\n context: 'booking rescheduled',\n owedFor: 'booking',\n })\n // Metered only when it left (AGL-4227): a refused notice is not a cost.\n if (sent?.sent) await meterHostEmail(notice.hostId)\n}\n\n/** The production wiring: the Admin SDK, the site lockdown verdict and the real send. */\nexport function bookingManageDeps(): BookingManageDeps {\n return {\n firestore: () => firebaseAdmin.app().firestore() as unknown as ManageFirestore,\n verifyIdToken: (token) => firebaseAdmin.app().auth().verifyIdToken(token),\n siteLocked: async (hostId) => Boolean(await getSiteLockdown(hostId)),\n timeZoneFor: async (hostId, service) => {\n const firestore = firebaseAdmin.app().firestore()\n const [host, owner] = await Promise.all([\n firestore.collection('hosts').doc(hostId).get(),\n getOrgForHost(hostId).catch(() => null),\n ])\n return bookingTimeZone({\n service: service ?? null,\n host: host.data() as { timeZone?: string } | undefined,\n org: owner?.org as { timeZone?: string } | null | undefined,\n })\n },\n notifyRescheduled: sendRescheduledNotice,\n now: () => Date.now(),\n raiseEvent: (input) => raiseBookingEvent(firebaseAdmin.app().firestore(), input),\n }\n}\n"],"names":["holdsSiteKey","siteKeyRefusal","isEmailConfigured","sendEmail","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","getSiteLockdown","resolveBrandingProfile","bookingDurationMs","bookingState","cancelRefusal","checkInRefusal","rescheduleRefusal","isSlotOpen","bookingTimeZone","formatBookingWhen","storedBookingTimeZone","isRefusedIdToken","raiseBookingEvent","CHECKED_IN_AT","CHECKED_IN_BY","Refusal","Error","status","message","bearerOf","req","header","String","headers","startsWith","slice","length","bodyOf","body","JSON","parse","authorize","deps","hostId","token","uid","verifyIdToken","error","host","firestore","doc","get","exists","siteLocked","answer","res","json","console","createBookingCheckInHandler","method","bookingId","checkedIn","ref","result","runTransaction","transaction","snapshot","booking","data","nowMs","now","refusal","already","Number","checkedInAtMs","update","ok","createBookingRescheduleHandler","startsAtMs","isFinite","first","moved","serviceId","serviceSnapshot","service","undefined","previousStartsAtMs","durationMs","durationMinutes","nearby","collection","where","limit","booked","docs","filter","id","map","endsAtMs","rescheduledAtMs","rescheduledBy","rescheduledFromMs","reminderSentAt","notified","raiseEvent","event","to","trim","timezone","timeZoneFor","notifyRescheduled","name","serviceName","when","previousWhen","createBookingCancelHandler","canceled","canceledAtMs","canceledBy","sendRescheduledNotice","notice","app","fallbackText","designed","branding","catch","org","sent","subject","text","html","fromName","sendingIdentity","audience","context","owedFor","bookingManageDeps","auth","Boolean","owner","Promise","all","Date","input"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AAEtF,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,QACpB,2BAA0B;AACjC,SAASC,eAAe,QAAQ,wDAAuD;AACvF,SAASC,sBAAsB,QAAQ,sBAAqB;AAC5D,SACEC,iBAAiB,EACjBC,YAAY,EACZC,aAAa,EACbC,cAAc,EAEdC,iBAAiB,QACZ,6BAAyB;AAChC,SAAuDC,UAAU,QAAQ,uBAAmB;AAC5F,SAASC,eAAe,EAAEC,iBAAiB,EAAEC,qBAAqB,QAAQ,2BAAuB;AACjG,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAAiCC,iBAAiB,QAAQ,sBAAkB;AAwE5E,qDAAqD,GACrD,OAAO,MAAMC,gBAAgB,gBAAe;AAC5C,OAAO,MAAMC,gBAAgB,cAAa;AAE1C,IAAA,AAAMC,UAAN,MAAMA,gBAAgBC;IACpB,YACE,AAASC,MAAc,EACvBC,OAAe,CACf;QACA,KAAK,CAACA,eAHGD,SAAAA;IAIX;AACF;AAEA,MAAME,WAAW,CAACC;QACMA,MAAAA;IAAtB,MAAMC,SAASC,QAAOF,QAAAA,6BAAAA,IAAIG,OAAO,CAAC,gBAAgB,YAA5BH,6BAAgCA,IAAIG,OAAO,CAAC,gBAAgB,YAA5DH,OAAgE;IACtF,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ACuC,QAAUzH,kBAAkBjB,cAAcoH,GAAG,GAAGxE,SAAS,IAAI8F;IAC5E;AACF"}
package/src/lib/server.js CHANGED
@@ -820,7 +820,7 @@ export const slotsHandler = async (req, res)=>{
820
820
  // White-label sender identity (White-Label Phase 3): the store's brand
821
821
  // via the one shared resolver, from the owning org doc.
822
822
  const branding = resolveBrandingProfile((_this1 = await getOrgForHost(hostId).catch(()=>null)) == null ? void 0 : _this1.org);
823
- await sendEmail(_extends({
823
+ const confirmation = await sendEmail(_extends({
824
824
  to: email,
825
825
  subject: (_ref6 = designed == null ? void 0 : designed.subject) != null ? _ref6 : `Booking confirmed: ${service.name}`,
826
826
  text: (designed == null ? void 0 : designed.text) || fallbackText
@@ -835,10 +835,10 @@ export const slotsHandler = async (req, res)=>{
835
835
  // screen's soft rules never hold it (AGL-3356).
836
836
  owedFor: 'booking'
837
837
  }));
838
- // Cost meter (AGL-1438). Transactional: counted, never capped — a
839
- // confirmation the customer never receives reads to them as a booking
840
- // that did not happen.
841
- await meterHostEmail(hostId);
838
+ // Cost meter (AGL-1438), for a message that LEFT (AGL-4227): one the
839
+ // workspace's email limit or the provider refused is not a cost, and
840
+ // counting it would show the owner mail their customer never got.
841
+ if (confirmation == null ? void 0 : confirmation.sent) await meterHostEmail(hostId);
842
842
  }
843
843
  // THE RECORD'S MEETING (AGL-2660). A free booking is confirmed right
844
844
  // here, so this is where it reaches the CRM: the meeting on the
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/bookings/src/lib/server.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 {\n type SiteReturnHost,\n siteReturnOrigin,\n} from '@aglyn/aglyn/app-utils/site-return-url'\nimport { excludeBuyNowPayLater } from '@aglyn/aglyn/app-utils/buy-now-pay-later'\nimport { checkEntitlement,\n type PluginJobHostGate,\n registerPluginConfigSchema,\n registerPluginJob,\n resolveBrandingProfile,\n resolveTransactionFeeCents,\n} from '@aglyn/aglyn/server'\n// The leaf, not the barrel: the console's `x-cron-secret` door asks the\n// site's lockdown directly (AGL-3356) — core's registry has no resolver in\n// the console process — and a spec that substitutes the barrel must still\n// reach the real verdict.\nimport { siteLockdownJobGate } from '@aglyn/tenant-data-admin/server/tenant-write-lockdown'\nimport {\n loadHostEmailWithTokens,\n renderLoadedHostEmailWithTokens,\n type LoadedHostEmailWithTokens,\n} from '@aglyn/tenant-data-admin/server/host-email-tokens'\nimport { type BookedInterval, BOOKING_MAX_DAYS_AHEAD, bookingChargeUsd, bookingContactAsks, bookingPriceDisplay, bookingContactLines, readBookingContactFields, bookingServiceIsOffered, bookingTimeZone, computeOpenSlotPage, formatBookingWhen, type HostBookingService, isBookingReminderDue, isSlotOpen, REMINDER_WINDOW_END_HOURS, REMINDER_WINDOW_START_HOURS } from './model'\nimport { bookingTimeZoneFor } from './server/booking-time-zone'\nimport {\n registerBillingWebhookHandler,\n registerPluginApiRoute,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n pluginTaxProfile,\n type PluginResolvedFlatTax,\n} from '@aglyn/aglyn/plugin-manager/plugin-tax-profile'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { BOOKINGS_CONFIG_SCHEMA } from './plugin-config'\nimport { bookingsBillingWebhookHandler } from './server/billing-webhook'\nimport { bookingAnalyticsHandler } from './server/booking-analytics'\nimport { registerBookingFigureReader } from './server/booking-figures'\nimport { registerBookingServiceAiCapability } from './server/booking-service-ai-capability'\nimport { registerBookingServiceDraftWriter } from './server/booking-service-drafts'\nimport { bookingRefundHandler } from './server/refund'\nimport { stageBookingEvent } from './server/booking-events'\nimport { bookingInPersonPaymentHandler } from './server/in-person-payment'\nimport {\n bookingManageDeps,\n createBookingCheckInHandler,\n createBookingCancelHandler,\n createBookingRescheduleHandler,\n} from './server/booking-manage'\n// The booking's way back to the record it was booked from (AGL-2660): the\n// reference a booking link carried, and the meeting a free booking files on\n// landing.\nimport {\n formatBookingRecordRef,\n parseBookingRecordRef,\n} from './model/booking-record'\nimport { fileBookingOnCrm } from './server/booking-crm'\n\n// Settings schema (AGL-428): registered here too so server-only loads\n// (API dispatchers) get defaults-merged getPluginConfig reads.\nregisterPluginConfigSchema(BOOKINGS_CONFIG_SCHEMA)\n\n// Scheduled cleanup (AGL-435): lapse day-old expired payment holds to\n// 'canceled' (the read paths already treat them as released — this keeps\n// the collection tidy and the read-time filter cheap). Bounded + failure\n// tolerant: a missing collection-group index just logs and retries on\n// the next beat.\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'expire-stale-holds',\n intervalMinutes: 6 * 60,\n description: 'Cancel pendingPayment bookings whose hold lapsed >24h ago.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const cutoff = Date.now() - 24 * 60 * 60_000\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collectionGroup('bookings')\n .where('status', '==', 'pendingPayment')\n .where('expiresAtMs', '<', cutoff)\n .limit(100)\n .get()\n let lapsed = 0\n for (const doc of snapshot.docs) {\n // LOCKDOWN (AGL-2495). `bookings` live at `hosts/{hostId}/bookings/{id}`,\n // so the grandparent is the host. This flips a booking to `canceled` for\n // a site that may be suspended mid-dispute, and a status a customer can\n // see is not a change to make while the operator is deciding whether the\n // site should exist.\n //\n // SKIPPED, NOT DROPPED: the query selects on `status == 'pendingPayment'`\n // and an age cutoff that only gets truer with time, so an untouched hold\n // is picked up by the next six-hour beat after the lift. The read paths\n // already treat a lapsed hold as released, so waiting costs tidiness and\n // nothing else — which is why this one can afford to wait at all.\n const hostId = doc.ref.parent.parent?.id ?? ''\n if (await gate.isLocked(hostId)) continue\n await doc.ref.set({ status: 'canceled' }, { merge: true })\n lapsed += 1\n }\n if (lapsed) {\n console.info(`bookings: lapsed ${lapsed} stale payment holds`)\n }\n },\n})\nimport {\n firebaseAdmin,\n getOrgForHost,\n meterHostEmail,\n notifyHostManagers,\n getPluginConfig,\n resolveOrgIdForHost,\n renderHostEmailWithTokens,\n hostSendingIdentity,\n} from '@aglyn/tenant-data-admin'\nimport {\n connectedAccountHeader,\n directChargeParams,\n merchantAccountIsReady,\n saleChargeModel,\n type SaleChargeModel,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { checkoutSessionCardAuthenticationParams } from '@aglyn/tenant-data-admin/server/stripe-card-authentication'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport {\n CONVERSION_TOUCH_DETAIL,\n creditConversion,\n resolveConversionTouch,\n} from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport {\n isEmailConfigured,\n sendEmail,\n} from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n NO_CLIENT_ADDRESS_BUCKET,\n readClientIp,\n} from '@aglyn/aglyn/app-utils/request-ip'\n\nconst BOOKING_EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n// Best-effort per-instance rate limit (mirrors forms/submit).\nconst recentBookingIpHits = new Map<string, number[]>()\nconst BOOKING_RATE_WINDOW_MS = 60_000\nconst BOOKING_RATE_MAX = 5\n\nfunction bookingRateLimited(ip: string): boolean {\n const now = Date.now()\n const hits = (recentBookingIpHits.get(ip) ?? []).filter(\n (t) => now - t < BOOKING_RATE_WINDOW_MS,\n )\n hits.push(now)\n recentBookingIpHits.set(ip, hits)\n return hits.length > BOOKING_RATE_MAX\n}\n\n/**\n * Public open-slot listing (AGL-159): visitors browse a service's next\n * open times. Server-side because bookings (names/emails) must never be\n * client-readable — only the derived busy intervals are used here.\n */\n// Exported for `bookings-slot-window.spec.ts`: the query's bounds are a\n// read-cost and correctness property of THIS handler, and asserting them\n// through the route registry would test the registry instead. Its siblings\n// (`bookHandler`, the refund and analytics handlers) are exported already.\nexport const slotsHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.query['hostId'] ?? '')\n const serviceId = String(req.query['serviceId'] ?? '')\n if (!hostId) {\n return res.status(400).json({ error: 'Missing hostId' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n\n // No serviceId → public service directory for the booking widget\n // (AGL-160): names/durations/prices only, never availability internals.\n if (!serviceId) {\n const services = await hostRef.collection('services').limit(50).get()\n return res.status(200).json({\n // A draft service is offered nowhere until it is activated (AGL-3616).\n services: services.docs\n .filter((doc) => bookingServiceIsOffered(doc.data()))\n .map((doc) => ({\n $id: doc.id,\n name: doc.get('name') ?? '',\n durationMinutes: Number(doc.get('durationMinutes') ?? 30),\n // What booking it charges, never a price a label stands in for\n // (AGL-3475): a labeled service shows its label and charges 0.\n priceUsd: bookingChargeUsd(doc.data()),\n priceDisplay: bookingPriceDisplay(doc.get('priceDisplay')),\n description: doc.get('description') ?? '',\n // What the widget asks for beyond a name and an email (AGL-3493),\n // as the booking route will hold it: the widget renders and\n // checks the fields from these, the route checks them again.\n askPhone: bookingContactAsks(doc.data()).phone,\n askAddress: bookingContactAsks(doc.data()).address,\n })),\n })\n }\n const serviceSnapshot = await hostRef\n .collection('services')\n .doc(serviceId)\n .get()\n const service = serviceSnapshot.data() as HostBookingService | undefined\n // A draft has no slots to show (AGL-3616): it reads as no service at all.\n if (!service || !bookingServiceIsOffered(service)) {\n return res.status(404).json({ error: 'Unknown service' })\n }\n const nowMs = Date.now()\n // Booking horizon (AGL-428): configurable via the plugin settings\n // framework; defaults to BOOKING_MAX_DAYS_AHEAD through the schema.\n //\n // Resolved for THIS SITE (AGL-428, AGL-1014), not just the workspace.\n // The horizon is the setting per-site overrides were built for — one\n // chain, one answer, and the flagship branch taking bookings further out\n // — so reading only the org's would leave the console showing a number\n // this endpoint never honors.\n const config = await getPluginConfig(\n await resolveOrgIdForHost(hostId),\n 'bookings',\n { hostId },\n )\n const maxDaysAhead = Number(config.maxDaysAhead ?? BOOKING_MAX_DAYS_AHEAD)\n // Measured from NOW whichever page is asked for: the horizon is how far\n // ahead a visitor may book, not how far past the page they are on.\n const toMs = nowMs + maxDaysAhead * 24 * 60 * 60_000\n // The page asked for (AGL-3492): `from` is the `nextFromMs` the previous\n // page answered with. Clamped to now, so a stale or hand-written value\n // can never list a time that has passed, and a value past the horizon\n // lists nothing rather than reaching beyond it.\n const askedFromMs = Number(req.query['from'] ?? 0)\n const fromMs = Number.isFinite(askedFromMs)\n ? Math.min(Math.max(askedFromMs, nowMs), toMs)\n : nowMs\n // Bounded at BOTH ends, to the window the slots are actually computed\n // over. `computeOpenSlotPage` below is handed `fromMs`/`toMs` and ignores\n // anything outside them, so a booking past the horizon was read, billed\n // and discarded — and worse, it competed for the 500 with the bookings\n // that do matter, so a service booked far ahead could push the near-term\n // stays out of its own availability check and offer a taken slot.\n //\n // A second range on `startsAtMs` needs no new index: the field already\n // carries one, and the range it narrows is the one already here.\n const bookedSnapshot = await hostRef\n .collection('bookings')\n .where('serviceId', '==', serviceId)\n .where('startsAtMs', '>=', fromMs - 24 * 60 * 60_000)\n // One page never walks further than BOOKING_MAX_DAYS_AHEAD past its\n // start, so a horizon set further out than that is read a page's\n // worth at a time, not all at once.\n .where(\n 'startsAtMs',\n '<=',\n Math.min(toMs, fromMs + BOOKING_MAX_DAYS_AHEAD * 24 * 60 * 60_000),\n )\n .limit(500)\n .get()\n const booked: BookedInterval[] = bookedSnapshot.docs\n .filter(\n (doc) =>\n doc.get('status') !== 'canceled' &&\n // Expired payment holds release the slot (AGL-170).\n !(\n doc.get('status') === 'pendingPayment' &&\n Number(doc.get('expiresAtMs') ?? 0) < Date.now()\n ),\n )\n .map((doc) => ({\n startsAtMs: Number(doc.get('startsAtMs') ?? 0),\n endsAtMs: Number(doc.get('endsAtMs') ?? 0),\n }))\n // Bounded in DAYS, not slots (AGL-3492): a page is the widget's day\n // strip, whole, with every open time each of those days has. The flat\n // cap of 120 it replaces ran out three and a half weekdays in at\n // 15-minute steps, so the widget showed a calendar that ended on\n // Thursday at lunch and a horizon that was never reachable.\n const { slots, nextFromMs } = computeOpenSlotPage(\n service,\n fromMs,\n toMs,\n booked,\n )\n return res.status(200).json({\n service: {\n name: service.name,\n durationMinutes: service.durationMinutes,\n priceUsd: bookingChargeUsd(service),\n priceDisplay: bookingPriceDisplay(service.priceDisplay),\n timezone: service.timezone ?? 'UTC',\n },\n slots,\n // Where the next page starts; `null` once this one reached the horizon.\n nextFromMs,\n // The configured horizon, so the widget's empty state names it.\n horizonDays: maxDaysAhead,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Slot lookup failed' })\n }\n}\n\n/**\n * Booking creation (AGL-159): validates the slot against the service's\n * windows AND stored bookings inside a transaction (double-booking safe),\n * stores the booking, records a lead, emits the `booking` host event, and\n * sends an env-gated Resend confirmation. Plan gate: the owning org\n * needs the `bookings` flag (dark-launch workspaces pass).\n */\n/**\n * Exported for spec (AGL-2000). The tax decision this handler takes lives in\n * the ABSENCE of a parameter, and an absence is only a decision if something\n * asserts it — see `server-booking-tax.spec.ts`.\n */\nexport const bookHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const serviceId = String(req.body?.serviceId ?? '')\n const startsAtMs = Number(req.body?.startsAtMs ?? 0)\n const name = String(req.body?.name ?? '')\n .trim()\n .slice(0, 80)\n const email = String(req.body?.email ?? '')\n .trim()\n .toLowerCase()\n // Explicit opt-in checkbox (AGL-2499) — a booking is not by itself\n // consent to be emailed marketing, so this is only set when the visitor\n // checked it.\n const marketingConsent = req.body?.marketingConsent === true\n // The record the booking link named (AGL-2660), kept on the row so the\n // booking can be attributed to it even when the visitor books with a\n // different address. Parsed, never stored raw: this is a public door.\n const crmRef = parseBookingRecordRef(req.body?.crmRef)\n if (!hostId || !serviceId || !Number.isFinite(startsAtMs) || !startsAtMs) {\n return res.status(400).json({ error: 'Invalid booking request' })\n }\n if (!name) return res.status(400).json({ error: 'Enter your name' })\n if (!BOOKING_EMAIL_PATTERN.test(email)) {\n return res.status(400).json({ error: 'Enter a valid email' })\n }\n if (startsAtMs < Date.now()) {\n return res.status(409).json({ error: 'That time has already passed' })\n }\n // Keeps counting under the no-address bucket rather than being skipped: an\n // unauthenticated booking endpoint that stops counting writes reservations\n // for anyone who can reach it.\n const ip =\n readClientIp(req.headers, { remoteAddress: req.socket?.remoteAddress }) ??\n NO_CLIENT_ADDRESS_BUCKET\n if (bookingRateLimited(ip)) {\n return res.status(429).json({ error: 'Too many booking attempts' })\n }\n\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const [hostSnapshot, serviceSnapshot] = await Promise.all([\n hostRef.get(),\n hostRef.collection('services').doc(serviceId).get(),\n ])\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n const service = serviceSnapshot.data() as HostBookingService | undefined\n // Refused for a draft as for a deleted service (AGL-3616): a request can\n // name a service id the directory never listed.\n if (!service || !bookingServiceIsOffered(service)) {\n return res.status(404).json({ error: 'Unknown service' })\n }\n // The phone and the address, held to what THIS service asks for\n // (AGL-3493) and checked here whatever the widget already checked: this\n // is a public door, and a request can be written by hand. A field the\n // service does not ask for is dropped rather than stored.\n const contact = readBookingContactFields(bookingContactAsks(service), {\n phone: req.body?.phone,\n address: req.body?.address,\n })\n if ('error' in contact) return res.status(400).json({ error: contact.error })\n const { phone, address } = contact.fields\n // `Phone: …`, `Address: …`, for the managers' notification below.\n const contactLines = bookingContactLines(contact.fields)\n\n // Plan gate (dark-launch rule preserved). Plan/quota gates ride the\n // owning org's doc (AGL-238). Hoisted out of its block for AGL-2315:\n // the same org doc now also prices the platform's cut below, and reading\n // it twice would let a gate and a fee disagree within one request.\n const ownerOrg = (await getOrgForHost(hostId))?.org\n if (!checkEntitlement(ownerOrg as never, 'bookings')) {\n return res\n .status(403)\n .json({ error: 'Bookings are not enabled on this site' })\n }\n\n const durationMs =\n Math.max(5, Math.round(service.durationMinutes || 30)) * 60_000\n const endsAtMs = startsAtMs + durationMs\n const bookingsRef = hostRef.collection('bookings')\n // The zone this booking's time is told in (AGL-3432), stored on the\n // booking so the paid confirmation and the reminder — which read the\n // booking and not the service — state the same wall-clock time as the\n // free confirmation below, and name the zone it is in.\n const timezone = bookingTimeZone({\n service,\n host: hostSnapshot.data?.() as { timeZone?: string } | undefined,\n org: ownerOrg as { timeZone?: string } | null | undefined,\n })\n const when = formatBookingWhen(startsAtMs, timezone)\n\n // Paid services (AGL-170): the slot is HELD pending payment — the\n // booking lands as `pendingPayment` with a 15-minute expiry (expired\n // holds release the slot in the collision filters), and the visitor\n // goes to Stripe Checkout; the webhook confirms + emails on payment.\n // A service that states its price as a label books with no charge\n // (AGL-3475), whatever price it stores.\n const priceUsd = bookingChargeUsd(service)\n const paid = priceUsd > 0\n if (paid && !process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({\n error: 'Paid bookings are not configured (STRIPE_SECRET_KEY).',\n })\n }\n\n // WHO GETS THE MONEY (AGL-2315). Until this landed, a paid booking opened\n // a Checkout Session with no Connect wiring of any kind — no\n // `transfer_data`, no `application_fee_amount`, no connected account read\n // anywhere in the plugin — so 100% of every paid booking settled in\n // AGLYN'S OWN platform balance and the merchant was never paid at all.\n // Not under-paid: never paid. Every sibling tenant money path (storefront\n // checkout, cart, draft orders, POS, reservations) was already a\n // destination charge to the merchant's connected account; this was the one\n // door that took a card and kept the proceeds.\n //\n // Resolved BEFORE the hold transaction on purpose, the `reserve.ts`\n // ordering: an unconnected merchant is a deterministic refusal the site\n // owner fixes out of band, and discovering it after the slot is written\n // would strand a real appointment slot as `pendingPayment` for 15 minutes\n // on a booking that could never be paid.\n let chargeAccountId = ''\n // DIRECT or DESTINATION, by the seller's profile. A direct charge is made\n // ON the seller's own account, which Stripe bills itself; everything else\n // keeps the destination charge this path has always made.\n let chargeModel: SaleChargeModel = 'destination'\n let feeCents = 0\n // No tax until a paid booking asks the tenant's tax rule what is owed.\n let serviceTax: PluginResolvedFlatTax = { taxCents: 0, label: '', pct: 0 }\n if (paid) {\n const ownerUid = (ownerOrg as { ownerUid?: unknown } | null)?.ownerUid\n const [ownerProfile, serviceRate] = await Promise.all([\n ownerUid\n ? firestore.collection('profiles').doc(String(ownerUid)).get()\n : Promise.resolve(null),\n // The merchant's own service rate (AGL-2028), in the SAME round trip\n // as the connected-account read this path already makes — asked of\n // the plugin that keeps the merchant's tax settings, which reads them\n // where it stores them.\n pluginTaxProfile().flatRate(hostId, 'service'),\n ])\n chargeAccountId = String(ownerProfile?.get('stripeAccountId') ?? '')\n if (\n !merchantAccountIsReady(\n {\n accountId: chargeAccountId,\n chargesEnabled: ownerProfile?.get('stripeChargesEnabled'),\n accountLivemode: ownerProfile?.get('stripeAccountLivemode'),\n },\n { subject: `booking host ${hostId}` },\n )\n ) {\n return res.status(409).json({ error: 'Payments are not set up yet' })\n }\n chargeModel = saleChargeModel(ownerProfile?.get('stripeChargeModel'))\n\n // THE TAKE RATE IS THE STOREFRONT LADDER'S, NOT A NEW ONE (AGL-2315).\n //\n // the decision, 2026-08-19: bookings mirror the storefront ladder —\n // the same rate a storefront sale already takes, tapering to 0% on the\n // upper tiers. It is consistent with what merchants already agreed to\n // and needs no new price communication, so pricing stays locked for\n // Sept 1.\n //\n // Implemented by ROUTING THROUGH the existing resolver rather than\n // adding a bookings rate: `resolveTransactionFeePct` already carries a\n // `'service'` axis (it resolves to the digital rate), and a booking is a\n // service sale — `reserve.ts` prices a stay through the identical call.\n // So there is no new constant, no new plan-table row, and no second\n // place for a rate to drift out of step with `/pricing`. Every guard\n // that already holds for the storefront rate holds here for free: the\n // malformed-override floor (AGL-2114), the lapsed-plan re-resolution,\n // and the staff override.\n //\n // FEE BASIS: post-discount ITEMS ONLY, matching the one-time storefront\n // paths and deliberately NOT the subscription path's\n // `application_fee_percent`, which Stripe applies to the whole invoice\n // and so takes a cut of sales tax and shipping (AGL-2317). Here the two\n // bases happen to coincide, because this session carries exactly one\n // line item and, by AGL-2000's stated decision, no tax line and no\n // shipping option. That coincidence is not the reason for the choice —\n // sending a computed CENTS amount rather than a percent is what makes\n // the basis survive the day this path does compute service tax: a fee\n // derived from `priceUsd` stays off the tax the moment tax is added,\n // whereas a percent would silently start taxing the state's money.\n //\n // PLUS STRIPE'S CARD COST, AT COST (AGL-2152). A 0%-fee tier used to\n // take a destination charge with NO application fee at all, which is not\n // \"no take rate\" — Stripe debits 2.9% + 30¢ from the PLATFORM's balance\n // when that charge settles, so every paid booking on Pro and above cost\n // Aglyn money. `resolveTransactionFeeCents` is the same resolver's cents\n // form: the advertised take (still 0% where the ladder says 0%) plus the\n // card cost passed through, so the net per booking is the take and never\n // less. The `Math.max(1, …)` floor on a chargeable take is folded into\n // it, unchanged.\n //\n // The fee base and the charge base are the same number here: by\n // AGL-2000's stated decision this session carries one line item, no tax\n // line and no shipping option, so the card runs for exactly `priceUsd`.\n // SERVICE TAX: the MERCHANT'S OWN RATE, off unless they set one\n // (AGL-2028, answering the decision AGL-2000 recorded here).\n //\n // AGL-2000's reasoning is unchanged and is why this is a field of its\n // own rather than a reuse of the goods table. A service is not goods:\n // whether one is taxable is jurisdiction-specific and frequently the\n // opposite answer, so the AGL-285 `rates[]` are still never read here\n // — a test in `server-booking-tax.spec.ts` pins that with a fully\n // configured sales-tax store. Stripe Tax is still never asked either:\n // it has no service tax code from this handler and would compute a\n // goods rate against AGLYN's registrations (AGL-1904).\n //\n // What changed is that the merchant now has somewhere to answer. A\n // service business is one of the three named ICPs and in many states\n // their services ARE taxable, so \"Aglyn does not compute it\" could only\n // ever be a holding position. They type the rate, we compute it, charge\n // it, record it and stamp the regime; the settings card states plainly\n // that determining what is owed and to whom is theirs. Aglyn takes no\n // tax position, and the existence of a separate, blank-by-default field\n // is also AGL-2000's second reason answered — it is the merchant\n // saying, explicitly, that they mean this to cover bookings.\n //\n // DEFAULT OFF, and load-bearing: an absent, zero, negative or\n // out-of-range rate resolves to zero, so no existing merchant's charge\n // moves because this shipped.\n const chargeCents = Math.round(priceUsd * 100)\n // Asked of the plugin that owns the merchant's tax rule, which throws\n // rather than answer zero if none is loaded: an untaxed charge recorded\n // as untaxed is the failure nobody sees until the merchant owes it.\n serviceTax = pluginTaxProfile().flatTax(\n serviceRate,\n chargeCents,\n 'Service tax',\n )\n // THE TWO FEE BASES ARE NOW DIFFERENT NUMBERS (AGL-2028). The take is\n // computed on the SERVICE, never on the state's money — AGL-2317's rule\n // — while Stripe's card cost is debited from the platform balance on\n // the WHOLE charge and so is passed through on the whole charge\n // (AGL-2152). The comment above already promised this: \"a fee derived\n // from `priceUsd` stays off the tax the moment tax is added\". This is\n // the moment.\n //\n // A DIRECT charge passes no card cost through: Stripe bills the seller\n // its own fee and charges the platform nothing for the sale, so the\n // application fee is the take alone.\n feeCents = resolveTransactionFeeCents(\n ownerOrg as never,\n 'service',\n chargeCents,\n chargeCents + serviceTax.taxCents,\n chargeModel === 'direct' ? { direct: true } : {},\n )\n }\n\n // Transaction: re-read overlapping bookings and validate the slot so\n // two simultaneous requests cannot double-book.\n const bookingId = await firestore.runTransaction(async (transaction) => {\n const overlapping = await transaction.get(\n bookingsRef\n .where('serviceId', '==', serviceId)\n .where('startsAtMs', '>=', startsAtMs - 24 * 60 * 60_000)\n .limit(500),\n )\n const booked: BookedInterval[] = overlapping.docs\n .filter(\n (doc) =>\n doc.get('status') !== 'canceled' &&\n // Expired payment holds release the slot (AGL-170).\n !(\n doc.get('status') === 'pendingPayment' &&\n Number(doc.get('expiresAtMs') ?? 0) < Date.now()\n ),\n )\n .map((doc) => ({\n startsAtMs: Number(doc.get('startsAtMs') ?? 0),\n endsAtMs: Number(doc.get('endsAtMs') ?? 0),\n }))\n if (!isSlotOpen(service, startsAtMs, booked)) {\n throw Object.assign(new Error('Slot unavailable'), { code: 409 })\n }\n const bookingRef = bookingsRef.doc()\n const record = {\n serviceId,\n serviceName: service.name ?? '',\n name,\n email,\n ...(phone ? { phone } : {}),\n ...(address ? { address } : {}),\n startsAtMs,\n endsAtMs,\n timezone,\n status: paid ? 'pendingPayment' : 'confirmed',\n ...(paid && { expiresAtMs: Date.now() + 15 * 60_000 }),\n ...(crmRef ? { crmRef: formatBookingRecordRef(crmRef) } : {}),\n // WHERE THE CHARGE LIVES, for a direct one: a refund has to be made on\n // the seller's account, and the booking is what the refund reads.\n // Absent on a destination booking, which is the platform's charge.\n ...(paid && chargeModel === 'direct'\n ? { chargeModel: 'direct', stripeAccountId: chargeAccountId }\n : {}),\n }\n transaction.set(bookingRef, { ...record, createdAt: FieldValue.serverTimestamp() })\n // A free booking is confirmed as it is made (AGL-3643); a paid one\n // raises `booking.created` from the payment webhook instead.\n if (!paid) {\n const nowMs = Date.now()\n stageBookingEvent(transaction, firestore, {\n event: 'booking.created',\n hostId,\n bookingId: bookingRef.id,\n booking: { ...record, createdAt: nowMs },\n nowMs,\n })\n }\n return bookingRef.id\n })\n\n /*\n * WHERE THE VISITOR ARRIVED FROM, RESOLVED ONCE FOR THE WHOLE BOOKING.\n *\n * A booking is an identify moment: the visitor was anonymous while they\n * browsed and picked a slot, and this request is the first thing that\n * names them. The plugin that credits outcomes\n * (`plugin-conversion-credit`) is asked with what their device carried\n * and the address they just typed, and decides what earns the credit.\n *\n * Resolved once and handed to the booking record, the contact and the\n * lead below, so the lookup is paid once for the whole request and the\n * three records cannot be credited to different arrivals.\n */\n const bookedAtMs = Date.now()\n const arrival = await resolveConversionTouch({\n hostId,\n wire: req.body?.campaignTouch,\n email,\n atMs: bookedAtMs,\n })\n void creditConversion({\n hostId,\n kind: 'booking',\n refId: bookingId,\n touch: arrival,\n convertedAtMs: bookedAtMs,\n })\n\n /*\n * Contacts ingestion (AGL-197) — booking requests identify a person —\n * reported to whichever plugin keeps people rather than written by this\n * one (AGL-3080). Bookings knows it just met somebody; what a person\n * record is belongs to the plugin that models it, and a workspace that\n * keeps none is a quiet, correct answer here.\n */\n /*\n * A booking request is a LEAD SURFACE (AGL-3232): interest, not a sale\n * — no money has moved, and the payment webhook is the door that makes\n * a customer. The record system files the person as a lead, or lands\n * the request on the contact the workspace already holds for the\n * address; which record, and the lead's ceiling and dedupe, are its to\n * decide. Awaited rather than voided so the lead is there before the\n * response, as it was when this door wrote it itself; the seam never\n * throws, so a refused capture still cannot fail the booking.\n */\n await recordCapturedContact({\n /*\n * Not resolved here. The record system keys a person on the SITE they\n * were met on, so this costs the capture nothing — and resolving it\n * would put a Firestore read in front of the writer, which is the one\n * thing `recordCapturedContact` asks a door not to do.\n */\n orgId: '',\n hostId,\n identity: { email, name: name || undefined },\n interaction: {\n source: 'booking',\n refId: bookingId,\n summary: `Booked \"${String(service.name ?? 'a service').slice(0, 60)}\"`,\n },\n surface: 'lead',\n // The phone the booker gave (AGL-3493), onto the person only where\n // the record holds none: a number somebody typed on the record, or\n // gave the business before, is not replaced by one typed into a\n // booking form. The address is the JOB's, not the person's, and\n // rides the meeting below instead.\n ...(phone ? { profileFill: { phone } } : {}),\n ...(marketingConsent ? { marketingConsent: true } : {}),\n // Where the visitor ARRIVED from — a fact about this visit and not\n // about the person, which is what `detail` carries.\n ...(arrival ? { detail: { [CONVERSION_TOUCH_DETAIL]: arrival } } : {}),\n })\n\n if (paid) {\n // The site's own origin, never a header's say-so (AGL-3363): a\n // caller writes `Origin` and `Host`, and Stripe sends the payer here.\n const origin = siteReturnOrigin({\n candidates: [\n typeof req.headers.origin === 'string' ? req.headers.origin : '',\n `https://${req.headers.host}`,\n ],\n site: hostSnapshot.data?.() as SiteReturnHost | undefined,\n requestHost: String(req.headers.host ?? ''),\n })\n // TAX ON A PAID BOOKING: the merchant's own service rate, resolved\n // above and default OFF (AGL-2028, answering AGL-2000).\n //\n // The rate rides as an ORDINARY product line Stripe is never told is\n // tax — the AGL-1711 construction every other manual rate in this\n // repo uses. That is what makes the derived `taxMode` read `manual`:\n // the figure is the merchant's own, from their own rate, and is never\n // computed against Aglyn's registrations the way `automatic_tax` would\n // be (AGL-1904). Absent entirely when no rate is set, so a default\n // store's session carries no tax parameter of any kind — the property\n // `server-booking-tax.spec.ts` asserts over the whole emitted body.\n //\n // The sale is recorded either way: `booking-payment` has been in\n // `storefront-tax-record.ts`'s SESSION_TYPES since AGL-2000, so an\n // untaxed booking still files a row reading `taxMode: 'none'` and a\n // taxed one files `manual` with the figure, both with no further\n // wiring.\n const params = new URLSearchParams({\n mode: 'payment',\n // 3-D Secure, from the one seam every card payment shares (AGL-3360).\n ...checkoutSessionCardAuthenticationParams('payment'),\n 'line_items[0][quantity]': '1',\n 'line_items[0][price_data][currency]': 'usd',\n 'line_items[0][price_data][unit_amount]': String(\n Math.round(priceUsd * 100),\n ),\n 'line_items[0][price_data][product_data][name]': String(\n service.name ?? 'Booking',\n ).slice(0, 120),\n ...(serviceTax.taxCents > 0\n ? {\n 'line_items[1][quantity]': '1',\n 'line_items[1][price_data][currency]': 'usd',\n 'line_items[1][price_data][unit_amount]': String(\n serviceTax.taxCents,\n ),\n 'line_items[1][price_data][product_data][name]': serviceTax.label,\n }\n : {}),\n // A DIRECT charge is the seller's money by where the session lives\n // (the `Stripe-Account` header below), so it carries no\n // `transfer_data`, only Aglyn's take as the application fee.\n ...(chargeModel === 'direct'\n ? directChargeParams(feeCents)\n : {\n // Destination charge to the MERCHANT's connected account (AGL-2315).\n // Unconditional: `transfer_data[destination]` is what makes this the\n // merchant's money, and it is required on every paid booking whatever\n // the take rate. Only the fee below is conditional.\n 'payment_intent_data[transfer_data][destination]': chargeAccountId,\n ...(feeCents > 0\n ? { 'payment_intent_data[application_fee_amount]': String(feeCents) }\n : {}),\n }),\n // `{CHECKOUT_SESSION_ID}` is Stripe's own template token, substituted\n // on the redirect (AGL-2481). Without it the guest came back holding\n // the word `paid` and nothing else — no id, no amount — so the\n // merchant-side `purchase` had nothing to look itself up by and could\n // not have stated what was actually charged. The id is safe in the\n // URL: Stripe hands it only to the payer, and\n // `booking-analytics.ts` scopes it to the host and answers with a\n // projection rather than the booking document.\n success_url: `${origin}/?booking=paid&session_id={CHECKOUT_SESSION_ID}`,\n cancel_url: `${origin}/?booking=canceled`,\n customer_email: email,\n 'metadata[type]': 'booking-payment',\n 'metadata[hostId]': hostId,\n 'metadata[bookingId]': bookingId,\n // The fee actually charged, recorded on the session exactly as every\n // sibling path records it — the figure a refund reverses and the\n // figure a reconciliation reads. `'0'` on a 0%-fee tier is a real\n // answer, not a missing one.\n 'metadata[feeCents]': String(feeCents),\n // The only witness to the tax (AGL-2028). By the construction above\n // Stripe does not know the second line is tax and reports\n // `total_details.amount_tax: 0`, so the session's own metadata is\n // what `storefront-tax-record.ts` and the confirmation webhook read\n // to record the figure and derive the regime — exactly as\n // `checkout.ts` stamps it for a buy-now sale. Absent when there is no\n // tax, never a reassuring `'0'`: absent and zero are different facts.\n ...(serviceTax.taxCents > 0\n ? {\n 'metadata[taxCents]': String(serviceTax.taxCents),\n 'metadata[taxPct]': String(serviceTax.pct),\n }\n : {}),\n // Tells the webhook and the refund that this session, and the charge\n // it makes, live on the seller's account. Absent on a destination one.\n ...(chargeModel === 'direct' ? { 'metadata[chargeModel]': 'direct' } : {}),\n expires_at: String(Math.floor(Date.now() / 1000) + 30 * 60),\n })\n // No buy-now-pay-later on a booking (AGL-4198), so the fee above,\n // priced at the card rate, covers whatever the guest pays with.\n excludeBuyNowPayLater(params)\n const stripeResponse = await fetch(\n 'https://api.stripe.com/v1/checkout/sessions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n // AGL-2147. This was the ONE session-creating path in the repo\n // with no idempotency key: console checkout, enterprise billing,\n // marketplace checkout, and commerce's checkout / cart-checkout /\n // draft-order / reservation / POS paths all carry one, and this\n // takes a card payment exactly as they do.\n //\n // Keyed on the BOOKING, not on a client-minted header: the\n // transaction above mints a fresh `bookingId` per attempt, so it\n // already names this attempt uniquely and needs no widget change\n // to supply. That also sidesteps Stripe's 24h key expiry — a key\n // reused across attempts eventually replays a session that has\n // since expired (these are opened with a 30-minute `expires_at`),\n // handing the guest a dead checkout page instead of a new one.\n //\n // What it closes: a retried POST after Stripe has already created\n // the session but before its response arrived. Without the key\n // that opens a SECOND payable session against one held slot, and\n // a guest who pays both is charged twice for one appointment.\n 'Idempotency-Key': `booking-${bookingId}`,\n // A direct charge's session is opened ON the seller's account.\n ...connectedAccountHeader(chargeModel, chargeAccountId),\n },\n body: params.toString(),\n },\n )\n const session = (await stripeResponse.json()) as {\n url?: string\n error?: unknown\n }\n if (!stripeResponse.ok || !session.url) {\n console.error('Stripe booking checkout error', session.error)\n // Release the hold so the slot isn't stuck for 15 minutes.\n await bookingsRef\n .doc(bookingId)\n .set({ status: 'canceled' }, { merge: true })\n .catch(() => undefined)\n return res.status(502).json({ error: 'Payment setup failed' })\n }\n // The lead landed above; the confirmation email and the managers'\n // notification go out from the payment webhook.\n return res\n .status(200)\n .json({ bookingId, startsAtMs, endsAtMs, checkoutUrl: session.url })\n }\n\n // Event trigger (AGL-128/148/159).\n // In-app notification to the site's managers (AGL-259): who booked what,\n // and when, in the booking's own zone and naming it (AGL-3432), and the\n // phone and address the service asked for (AGL-3493) — the two things\n // an on-site service needs before it can do anything with the booking.\n void notifyHostManagers(hostId, {\n type: 'content.booking',\n title: 'New booking on {site}',\n body:\n `${name} (${email}) booked ${String(service.name ?? 'a service')} ` +\n `on {site} for ${when} (${timezone}).` +\n (contactLines.length ? ` ${contactLines.join('. ')}.` : ''),\n link: `/${hostId}/bookings`,\n })\n const { alerts } = await emitHostEvent(\n hostId,\n 'booking',\n { serviceName: service.name ?? '', email, startsAtMs },\n // The visitor who booked (AGL-3376).\n { actor: { kind: 'visitor', email } },\n )\n\n // Env-gated confirmation email (same provider as AGL-98).\n if (isEmailConfigured()) {\n const fallbackText =\n `Hi ${name},\\n\\nYour booking for \"${service.name}\" is ` +\n `confirmed for ${when} (${timezone}).\\n\\n` +\n `Reference: ${bookingId}`\n // Site-owner-designed template when published (AGL-770); null keeps the\n // built-in copy above.\n const designed = await renderHostEmailWithTokens(\n firestore,\n hostId,\n 'booking-confirmed',\n {\n name: String(name ?? ''),\n 'service.name': String(service.name ?? ''),\n when,\n timezone,\n // A free booking charged nothing: empty, so the line is left out.\n 'booking.payment': '',\n 'booking.ref': String(bookingId),\n },\n )\n // White-label sender identity (White-Label Phase 3): the store's brand\n // via the one shared resolver, from the owning org doc.\n const branding = resolveBrandingProfile(\n (await getOrgForHost(hostId).catch(() => null))?.org as never,\n )\n await sendEmail({\n to: email,\n subject: designed?.subject ?? `Booking confirmed: ${service.name}`,\n text: designed?.text || fallbackText,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(hostId),\n audience: 'tenant',\n context: 'booking confirmation',\n // Owed to the recipient by their own booking: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'booking',\n })\n // Cost meter (AGL-1438). Transactional: counted, never capped — a\n // confirmation the customer never receives reads to them as a booking\n // that did not happen.\n await meterHostEmail(hostId)\n }\n\n // THE RECORD'S MEETING (AGL-2660). A free booking is confirmed right\n // here, so this is where it reaches the CRM: the meeting on the\n // record's timeline and, when the service asks, the follow-up task. A\n // paid booking waits for the webhook, which files it once the charge\n // has cleared. Awaited, because a route handler is frozen the moment\n // it answers (AGL-2327) — and never thrown: the slot is the guest's\n // whatever the CRM did.\n await fileBookingOnCrm(firestore, {\n hostId,\n bookingId,\n booking: {\n serviceId,\n serviceName: service.name ?? '',\n email,\n ...(phone ? { phone } : {}),\n ...(address ? { address } : {}),\n startsAtMs,\n endsAtMs,\n ...(crmRef ? { crmRef: formatBookingRecordRef(crmRef) } : {}),\n },\n service,\n })\n\n return res.status(200).json({ bookingId, startsAtMs, endsAtMs, alerts })\n } catch (error: unknown) {\n if ((error as { code?: number })?.code === 409) {\n return res\n .status(409)\n .json({ error: 'That time was just taken — pick another slot' })\n }\n console.error(error)\n return res.status(500).json({ error: 'Booking failed' })\n }\n}\n\n/**\n * One reminder pass (AGL-160), extracted from its HTTP door in AGL-2431.\n *\n * Finds confirmed bookings starting 23–25 hours out (collection-group query,\n * so one call covers every host), emails each visitor through the env-gated\n * Resend path, and stamps `reminderSentAt` so re-runs are idempotent.\n *\n * WHY THIS IS A FUNCTION NOW. It only ever existed as `POST bookings/reminders`\n * behind `x-cron-secret`, and nothing anywhere POSTed to it — not\n * `scheduled-crons.yml`, not `vercel.json` (which has no `crons` key), not\n * `registerPluginJob`. The route's own docblock said \"invoke hourly from the\n * scheduler\" for as long as it has existed. It never ran, for anyone. Same\n * shape as the two commerce beats in AGL-2227, one plugin over.\n */\nexport async function scanBookingReminders(\n /** The lockdown gate, injected by the caller (AGL-2495). Not optional. */\n gate: PluginJobHostGate,\n): Promise<{\n scanned: number\n sent: number\n skipped: number\n skippedLocked: number\n}> {\n const firestore = firebaseAdmin.app().firestore()\n // ONE instant for the query bounds and for the per-booking predicate. Two\n // `Date.now()` calls would put a booking sitting on an edge inside the\n // query and outside the test, so the pass would fetch it, skip it, and\n // report a `skipped` the console could not explain.\n const nowMs = Date.now()\n const windowStart = nowMs + REMINDER_WINDOW_START_HOURS * 60 * 60 * 1000\n const windowEnd = nowMs + REMINDER_WINDOW_END_HOURS * 60 * 60 * 1000\n const upcoming = await firestore\n .collectionGroup('bookings')\n .where('startsAtMs', '>=', windowStart)\n .where('startsAtMs', '<=', windowEnd)\n .limit(500)\n .get()\n\n let sent = 0\n let skipped = 0\n let skippedLocked = 0\n // Resolve each host's designed reminder template once per run (AGL-770),\n // not once per booking — a busy site has many bookings in the window.\n const templateCache = new Map<string, LoadedHostEmailWithTokens | null>()\n // White-label brand per host (White-Label Phase 3): resolved once per host\n // from the owning org doc through the one shared resolver, so a reminder\n // reads as the store's brand.\n const brandingByHost = new Map<\n string,\n ReturnType<typeof resolveBrandingProfile>\n >()\n /*\n * One identity resolution per SITE, not per booking.\n *\n * The same reason the branding and template maps above exist: this sweep\n * runs across every site, and an uncached resolution would be two Firestore\n * reads per reminder rather than per host. Scoped to the run, so a domain\n * un-verified between runs is picked up on the next one.\n */\n const identityByHost = new Map<\n string,\n Awaited<ReturnType<typeof hostSendingIdentity>>\n >()\n // The zone for a booking that predates storing one (AGL-3432), resolved\n // once per service for the whole run.\n const zoneByService = new Map<string, Promise<string>>()\n for (const doc of upcoming.docs) {\n const data = doc.data()\n // The shared predicate, not a local copy of it (AGL-2431): the console\n // card counts what is waiting with this same function, so the number a\n // merchant reads is the number this loop will act on.\n if (!isBookingReminderDue(data as never, nowMs)) {\n skipped += 1\n continue\n }\n // bookings live at hosts/{hostId}/bookings/{id}, so the grandparent is\n // the host.\n const hostId = doc.ref.parent.parent?.id ?? ''\n // LOCKDOWN (AGL-2495), ahead of the send, the meter and the\n // `reminderSentAt` stamp — the three things this loop does, all of them\n // for the host. Counted separately from `skipped` on purpose: `skipped`\n // means \"this booking was not due\", and folding a locked site into it\n // would make a suspended merchant's silence read as an ordinary quiet\n // hour on the console card that shows these numbers.\n //\n // SKIPPED, NOT DROPPED: `reminderSentAt` is what retires a booking from\n // this pass, and it is stamped only on a successful send. An unstamped\n // booking is re-scanned hourly — though unlike the other five, this one\n // has a real deadline: the 23–25h window closes. A reminder whose window\n // passed under a lock is genuinely lost, and that is the correct\n // outcome, not a defect to engineer around. A site under takedown should\n // not be mailing its customers, and a reminder that arrives after the\n // appointment is worse than none.\n if (await gate.isLocked(hostId)) {\n skippedLocked += 1\n continue\n }\n // The booking's own zone, named beside the time (AGL-3432). A formatter\n // with no zone reads in the server's — UTC — and states the wrong hour.\n const timezone = await bookingTimeZoneFor(\n firestore,\n hostId,\n data,\n zoneByService,\n )\n const when = formatBookingWhen(Number(data['startsAtMs']), timezone)\n let loaded = templateCache.get(hostId)\n if (loaded === undefined) {\n loaded = hostId\n ? await // The template, or the built-in copy in the site's header and\n // footer, once per site for the whole batch (AGL-3287, AGL-3370).\n loadHostEmailWithTokens(firestore, hostId, 'booking-reminder')\n : null\n templateCache.set(hostId, loaded)\n brandingByHost.set(\n hostId,\n resolveBrandingProfile(\n (hostId\n ? await getOrgForHost(hostId).catch(() => null)\n : null\n )?.org as never,\n ),\n )\n }\n const serviceName = String(data['serviceName'] ?? 'your booking')\n const designed = loaded\n ? renderLoadedHostEmailWithTokens(\n loaded,\n {\n name: String(data['name'] ?? ''),\n 'service.name': serviceName,\n when,\n timezone,\n },\n )\n : null\n const result = await sendEmail({\n to: String(data['email']),\n subject: designed?.subject ?? `Reminder: ${serviceName} tomorrow`,\n text:\n designed?.text ||\n `Hi ${data['name'] ?? ''},\\n\\nA reminder that \"${serviceName}\" is ` +\n `scheduled for ${when} (${timezone}).\\n\\nReference: ${doc.id}`,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: brandingByHost.get(hostId)?.fromName,\n sendingIdentity: await hostSendingIdentity(hostId, identityByHost),\n audience: 'tenant',\n context: 'booking reminder',\n // Owed to the recipient by their own booking: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'booking',\n })\n if (result.sent) {\n // Cost meter (AGL-1438). Transactional: a reminder a quota refused is\n // a missed appointment for the site's own customer.\n await meterHostEmail(hostId)\n sent += 1\n await doc.ref\n .set(\n {\n reminderSentAt:\n firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n .catch(() => undefined)\n }\n }\n return { scanned: upcoming.size, sent, skipped, skippedLocked }\n}\n\n/**\n * The reminder beat (AGL-2431).\n *\n * MODULE SCOPE, like `expire-stale-holds` above and the three commerce beats:\n * the runner route reaches jobs through `ensureAll(['tenantApi'])`, so a\n * registration inside a `register*` function would depend on which entry\n * point happened to be loaded — the AGL-2227 lesson.\n *\n * HOURLY, matching the window's own resolution. The scan mails a two-hour\n * band 23–25h out, so a beat faster than the band buys nothing; a beat slower\n * than 2h could step over the band entirely and skip a day's reminders. An\n * hour sits inside that with room, and the pass is bounded (500 docs) and\n * idempotent — `reminderSentAt` is stamped on send — so an overlapping or\n * repeated beat cannot double-mail anybody.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'booking-reminders',\n intervalMinutes: 60,\n description: 'Email a 24-hour reminder for each upcoming confirmed booking.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n // Quietly, not as an error: email is optional per deployment, and a beat\n // that logs hourly on a self-host without Resend buries everything else.\n if (!isEmailConfigured()) return\n const { sent } = await scanBookingReminders(gate)\n if (sent) console.info(`bookings: sent ${sent} booking reminders`)\n },\n})\n\n/**\n * The manual door, kept for ops (AGL-2431): the scheduling now lives in the\n * `booking-reminders` job above, and this stays so a pass can be forced\n * without waiting for the beat.\n */\nconst remindersHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const cronSecret = process.env.CRON_SECRET\n if (!cronSecret) {\n return res\n .status(501)\n .json({ error: 'Reminders are not configured (CRON_SECRET).' })\n }\n if (req.headers['x-cron-secret'] !== cronSecret) {\n return res.status(401).json({ error: 'Unauthenticated' })\n }\n if (!isEmailConfigured()) {\n return res.status(501).json({\n error: 'Reminders are not configured (RESEND_API_KEY, USAGE_EMAIL_FROM).',\n })\n }\n try {\n // The manual door asks the same question the beat does (AGL-2495).\n return res.status(200).json(await scanBookingReminders(siteLockdownJobGate()))\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Reminders failed' })\n }\n}\n\n/** Registers the bookings plugin's public (site-facing) API routes (AGL-396). */\nexport function registerBookingsApi(): void {\n registerPluginApiRoute('bookings/slots', slotsHandler)\n // A deposit opens a Stripe Checkout Session for whoever books, so the\n // dispatcher holds this door to the card-testing counters (AGL-3363).\n registerPluginApiRoute('bookings/book', bookHandler, { cardPayment: true })\n}\n\n/** Registers the bookings plugin's console-side API routes (AGL-396). */\nexport function registerBookingsConsoleApi(): void {\n registerPluginApiRoute('bookings/reminders', remindersHandler)\n // Refunding a paid booking (AGL-2315). Console-side, because it is\n // site-admin-gated and moves money — never a site-facing route.\n registerPluginApiRoute('bookings/refund', bookingRefundHandler)\n // Paying for a booking at the counter, on the native Aglyn POS app's reader\n // (AGL-3618). Staff-gated like a refund, and it moves money the same way.\n registerPluginApiRoute('bookings/in-person-payment', bookingInPersonPaymentHandler)\n // Checking a guest in and moving a booking (AGL-3621), for the site's\n // team in the native Aglyn app: member routes, one transaction each.\n registerPluginApiRoute('bookings/check-in', createBookingCheckInHandler(bookingManageDeps()))\n registerPluginApiRoute('bookings/reschedule', createBookingRescheduleHandler(bookingManageDeps()))\n // Canceling a booking with no money on it (AGL-3643): the console's cancel\n // for a free booking, so the cancel reaches the plugins listening for it.\n registerPluginApiRoute('bookings/cancel', createBookingCancelHandler(bookingManageDeps()))\n // The merchant-side `purchase` lookup (AGL-2481). A public, unauthenticated\n // read like `bookings/slots`, authorised by the unguessable Stripe session\n // id and answering with a projection that carries no guest identity.\n registerPluginApiRoute('bookings/booking-analytics', bookingAnalyticsHandler)\n // Paid-booking confirmation rides the platform Stripe webhook (AGL-418).\n registerBillingWebhookHandler(bookingsBillingWebhookHandler)\n // Bookings by service as a figure table (AGL-2915), for the AI plugin's\n // insights to read by id; the console runs insight jobs.\n registerBookingFigureReader(() => firebaseAdmin.app().firestore())\n // A draft service another plugin asks for by name (AGL-3616) — an AI build\n // setting a site up from a brief. The console runs AI jobs (AGL-3026).\n registerBookingServiceDraftWriter()\n // …and the operation an AI build plans for it, which that writer executes.\n registerBookingServiceAiCapability()\n}\n"],"names":["siteReturnOrigin","excludeBuyNowPayLater","checkEntitlement","registerPluginConfigSchema","registerPluginJob","resolveBrandingProfile","resolveTransactionFeeCents","siteLockdownJobGate","loadHostEmailWithTokens","renderLoadedHostEmailWithTokens","BOOKING_MAX_DAYS_AHEAD","bookingChargeUsd","bookingContactAsks","bookingPriceDisplay","bookingContactLines","readBookingContactFields","bookingServiceIsOffered","bookingTimeZone","computeOpenSlotPage","formatBookingWhen","isBookingReminderDue","isSlotOpen","REMINDER_WINDOW_END_HOURS","REMINDER_WINDOW_START_HOURS","bookingTimeZoneFor","registerBillingWebhookHandler","registerPluginApiRoute","pluginTaxProfile","BUNDLE_ID","BOOKINGS_CONFIG_SCHEMA","bookingsBillingWebhookHandler","bookingAnalyticsHandler","registerBookingFigureReader","registerBookingServiceAiCapability","registerBookingServiceDraftWriter","bookingRefundHandler","stageBookingEvent","bookingInPersonPaymentHandler","bookingManageDeps","createBookingCheckInHandler","createBookingCancelHandler","createBookingRescheduleHandler","formatBookingRecordRef","parseBookingRecordRef","fileBookingOnCrm","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","cutoff","Date","now","snapshot","firebaseAdmin","app","firestore","collectionGroup","where","limit","get","lapsed","doc","docs","hostId","ref","parent","id","isLocked","set","status","merge","console","info","getOrgForHost","meterHostEmail","notifyHostManagers","getPluginConfig","resolveOrgIdForHost","renderHostEmailWithTokens","hostSendingIdentity","connectedAccountHeader","directChargeParams","merchantAccountIsReady","saleChargeModel","checkoutSessionCardAuthenticationParams","emitHostEvent","recordCapturedContact","CONVERSION_TOUCH_DETAIL","creditConversion","resolveConversionTouch","isEmailConfigured","sendEmail","FieldValue","NO_CLIENT_ADDRESS_BUCKET","readClientIp","BOOKING_EMAIL_PATTERN","recentBookingIpHits","Map","BOOKING_RATE_WINDOW_MS","BOOKING_RATE_MAX","bookingRateLimited","ip","hits","filter","t","push","length","slotsHandler","req","res","method","json","error","String","query","serviceId","config","service","hostRef","collection","services","data","map","$id","durationMinutes","Number","priceUsd","priceDisplay","askPhone","phone","askAddress","address","serviceSnapshot","nowMs","maxDaysAhead","toMs","askedFromMs","fromMs","isFinite","Math","min","max","bookedSnapshot","booked","startsAtMs","endsAtMs","slots","nextFromMs","timezone","horizonDays","bookHandler","body","trim","slice","email","toLowerCase","marketingConsent","crmRef","test","headers","remoteAddress","socket","hostSnapshot","Promise","all","exists","contact","fields","contactLines","ownerOrg","org","durationMs","round","bookingsRef","host","when","paid","process","env","STRIPE_SECRET_KEY","chargeAccountId","chargeModel","feeCents","serviceTax","taxCents","label","pct","ownerUid","ownerProfile","serviceRate","resolve","flatRate","accountId","chargesEnabled","accountLivemode","subject","chargeCents","flatTax","direct","bookingId","runTransaction","transaction","overlapping","Object","assign","Error","code","bookingRef","record","serviceName","expiresAtMs","stripeAccountId","createdAt","serverTimestamp","event","booking","bookedAtMs","arrival","wire","campaignTouch","atMs","kind","refId","touch","convertedAtMs","orgId","identity","undefined","interaction","source","summary","surface","profileFill","detail","origin","candidates","site","requestHost","params","URLSearchParams","mode","success_url","cancel_url","customer_email","expires_at","floor","stripeResponse","fetch","Authorization","toString","session","ok","url","catch","checkoutUrl","type","title","join","link","alerts","actor","fallbackText","designed","branding","to","text","html","fromName","sendingIdentity","audience","context","owedFor","scanBookingReminders","windowStart","windowEnd","upcoming","sent","skipped","skippedLocked","templateCache","brandingByHost","identityByHost","zoneByService","loaded","result","reminderSentAt","scanned","size","remindersHandler","cronSecret","CRON_SECRET","registerBookingsApi","cardPayment","registerBookingsConsoleApi"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,gBAAgB,QACX,yCAAwC;AAC/C,SAASC,qBAAqB,QAAQ,2CAA0C;AAChF,SAASC,gBAAgB,EAEvBC,0BAA0B,EAC1BC,iBAAiB,EACjBC,sBAAsB,EACtBC,0BAA0B,QACrB,sBAAqB;AAC5B,wEAAwE;AACxE,2EAA2E;AAC3E,0EAA0E;AAC1E,0BAA0B;AAC1B,SAASC,mBAAmB,QAAQ,wDAAuD;AAC3F,SACEC,uBAAuB,EACvBC,+BAA+B,QAE1B,oDAAmD;AAC1D,SAA8BC,sBAAsB,EAAEC,gBAAgB,EAAEC,kBAAkB,EAAEC,mBAAmB,EAAEC,mBAAmB,EAAEC,wBAAwB,EAAE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;AACF;AAEA,+EAA+E,GAC/E,OAAO,SAASmL;IACd7Q,uBAAuB,kBAAkBqF;IACzC,sEAAsE;IACtE,sEAAsE;IACtErF,uBAAuB,iBAAiBgI,aAAa;QAAE8I,aAAa;IAAK;AAC3E;AAEA,uEAAuE,GACvE,OAAO,SAASC;IACd/Q,uBAAuB,sBAAsB0Q;IAC7C,mEAAmE;IACnE,gEAAgE;IAChE1Q,uBAAuB,mBAAmBS;IAC1C,4EAA4E;IAC5E,0EAA0E;IAC1ET,uBAAuB,8BAA8BW;IACrD,sEAAsE;IACtE,qEAAqE;IACrEX,uBAAuB,qBAAqBa,4BAA4BD;IACxEZ,uBAAuB,uBAAuBe,+BAA+BH;IAC7E,2EAA2E;IAC3E,0EAA0E;IAC1EZ,uBAAuB,mBAAmBc,2BAA2BF;IACrE,4EAA4E;IAC5E,2EAA2E;IAC3E,qEAAqE;IACrEZ,uBAAuB,8BAA8BK;IACrD,yEAAyE;IACzEN,8BAA8BK;IAC9B,wEAAwE;IACxE,yDAAyD;IACzDE,4BAA4B,IAAMyB,cAAcC,GAAG,GAAGC,SAAS;IAC/D,2EAA2E;IAC3E,uEAAuE;IACvEzB;IACA,2EAA2E;IAC3ED;AACF"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/bookings/src/lib/server.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 {\n type SiteReturnHost,\n siteReturnOrigin,\n} from '@aglyn/aglyn/app-utils/site-return-url'\nimport { excludeBuyNowPayLater } from '@aglyn/aglyn/app-utils/buy-now-pay-later'\nimport { checkEntitlement,\n type PluginJobHostGate,\n registerPluginConfigSchema,\n registerPluginJob,\n resolveBrandingProfile,\n resolveTransactionFeeCents,\n} from '@aglyn/aglyn/server'\n// The leaf, not the barrel: the console's `x-cron-secret` door asks the\n// site's lockdown directly (AGL-3356) — core's registry has no resolver in\n// the console process — and a spec that substitutes the barrel must still\n// reach the real verdict.\nimport { siteLockdownJobGate } from '@aglyn/tenant-data-admin/server/tenant-write-lockdown'\nimport {\n loadHostEmailWithTokens,\n renderLoadedHostEmailWithTokens,\n type LoadedHostEmailWithTokens,\n} from '@aglyn/tenant-data-admin/server/host-email-tokens'\nimport { type BookedInterval, BOOKING_MAX_DAYS_AHEAD, bookingChargeUsd, bookingContactAsks, bookingPriceDisplay, bookingContactLines, readBookingContactFields, bookingServiceIsOffered, bookingTimeZone, computeOpenSlotPage, formatBookingWhen, type HostBookingService, isBookingReminderDue, isSlotOpen, REMINDER_WINDOW_END_HOURS, REMINDER_WINDOW_START_HOURS } from './model'\nimport { bookingTimeZoneFor } from './server/booking-time-zone'\nimport {\n registerBillingWebhookHandler,\n registerPluginApiRoute,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n pluginTaxProfile,\n type PluginResolvedFlatTax,\n} from '@aglyn/aglyn/plugin-manager/plugin-tax-profile'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { BOOKINGS_CONFIG_SCHEMA } from './plugin-config'\nimport { bookingsBillingWebhookHandler } from './server/billing-webhook'\nimport { bookingAnalyticsHandler } from './server/booking-analytics'\nimport { registerBookingFigureReader } from './server/booking-figures'\nimport { registerBookingServiceAiCapability } from './server/booking-service-ai-capability'\nimport { registerBookingServiceDraftWriter } from './server/booking-service-drafts'\nimport { bookingRefundHandler } from './server/refund'\nimport { stageBookingEvent } from './server/booking-events'\nimport { bookingInPersonPaymentHandler } from './server/in-person-payment'\nimport {\n bookingManageDeps,\n createBookingCheckInHandler,\n createBookingCancelHandler,\n createBookingRescheduleHandler,\n} from './server/booking-manage'\n// The booking's way back to the record it was booked from (AGL-2660): the\n// reference a booking link carried, and the meeting a free booking files on\n// landing.\nimport {\n formatBookingRecordRef,\n parseBookingRecordRef,\n} from './model/booking-record'\nimport { fileBookingOnCrm } from './server/booking-crm'\n\n// Settings schema (AGL-428): registered here too so server-only loads\n// (API dispatchers) get defaults-merged getPluginConfig reads.\nregisterPluginConfigSchema(BOOKINGS_CONFIG_SCHEMA)\n\n// Scheduled cleanup (AGL-435): lapse day-old expired payment holds to\n// 'canceled' (the read paths already treat them as released — this keeps\n// the collection tidy and the read-time filter cheap). Bounded + failure\n// tolerant: a missing collection-group index just logs and retries on\n// the next beat.\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'expire-stale-holds',\n intervalMinutes: 6 * 60,\n description: 'Cancel pendingPayment bookings whose hold lapsed >24h ago.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const cutoff = Date.now() - 24 * 60 * 60_000\n const snapshot = await firebaseAdmin\n .app()\n .firestore()\n .collectionGroup('bookings')\n .where('status', '==', 'pendingPayment')\n .where('expiresAtMs', '<', cutoff)\n .limit(100)\n .get()\n let lapsed = 0\n for (const doc of snapshot.docs) {\n // LOCKDOWN (AGL-2495). `bookings` live at `hosts/{hostId}/bookings/{id}`,\n // so the grandparent is the host. This flips a booking to `canceled` for\n // a site that may be suspended mid-dispute, and a status a customer can\n // see is not a change to make while the operator is deciding whether the\n // site should exist.\n //\n // SKIPPED, NOT DROPPED: the query selects on `status == 'pendingPayment'`\n // and an age cutoff that only gets truer with time, so an untouched hold\n // is picked up by the next six-hour beat after the lift. The read paths\n // already treat a lapsed hold as released, so waiting costs tidiness and\n // nothing else — which is why this one can afford to wait at all.\n const hostId = doc.ref.parent.parent?.id ?? ''\n if (await gate.isLocked(hostId)) continue\n await doc.ref.set({ status: 'canceled' }, { merge: true })\n lapsed += 1\n }\n if (lapsed) {\n console.info(`bookings: lapsed ${lapsed} stale payment holds`)\n }\n },\n})\nimport {\n firebaseAdmin,\n getOrgForHost,\n meterHostEmail,\n notifyHostManagers,\n getPluginConfig,\n resolveOrgIdForHost,\n renderHostEmailWithTokens,\n hostSendingIdentity,\n} from '@aglyn/tenant-data-admin'\nimport {\n connectedAccountHeader,\n directChargeParams,\n merchantAccountIsReady,\n saleChargeModel,\n type SaleChargeModel,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { checkoutSessionCardAuthenticationParams } from '@aglyn/tenant-data-admin/server/stripe-card-authentication'\nimport { emitHostEvent } from '@aglyn/tenant-runtime'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport {\n CONVERSION_TOUCH_DETAIL,\n creditConversion,\n resolveConversionTouch,\n} from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport {\n isEmailConfigured,\n sendEmail,\n} from '@aglyn/shared-util-email'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n NO_CLIENT_ADDRESS_BUCKET,\n readClientIp,\n} from '@aglyn/aglyn/app-utils/request-ip'\n\nconst BOOKING_EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n// Best-effort per-instance rate limit (mirrors forms/submit).\nconst recentBookingIpHits = new Map<string, number[]>()\nconst BOOKING_RATE_WINDOW_MS = 60_000\nconst BOOKING_RATE_MAX = 5\n\nfunction bookingRateLimited(ip: string): boolean {\n const now = Date.now()\n const hits = (recentBookingIpHits.get(ip) ?? []).filter(\n (t) => now - t < BOOKING_RATE_WINDOW_MS,\n )\n hits.push(now)\n recentBookingIpHits.set(ip, hits)\n return hits.length > BOOKING_RATE_MAX\n}\n\n/**\n * Public open-slot listing (AGL-159): visitors browse a service's next\n * open times. Server-side because bookings (names/emails) must never be\n * client-readable — only the derived busy intervals are used here.\n */\n// Exported for `bookings-slot-window.spec.ts`: the query's bounds are a\n// read-cost and correctness property of THIS handler, and asserting them\n// through the route registry would test the registry instead. Its siblings\n// (`bookHandler`, the refund and analytics handlers) are exported already.\nexport const slotsHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.query['hostId'] ?? '')\n const serviceId = String(req.query['serviceId'] ?? '')\n if (!hostId) {\n return res.status(400).json({ error: 'Missing hostId' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n\n // No serviceId → public service directory for the booking widget\n // (AGL-160): names/durations/prices only, never availability internals.\n if (!serviceId) {\n const services = await hostRef.collection('services').limit(50).get()\n return res.status(200).json({\n // A draft service is offered nowhere until it is activated (AGL-3616).\n services: services.docs\n .filter((doc) => bookingServiceIsOffered(doc.data()))\n .map((doc) => ({\n $id: doc.id,\n name: doc.get('name') ?? '',\n durationMinutes: Number(doc.get('durationMinutes') ?? 30),\n // What booking it charges, never a price a label stands in for\n // (AGL-3475): a labeled service shows its label and charges 0.\n priceUsd: bookingChargeUsd(doc.data()),\n priceDisplay: bookingPriceDisplay(doc.get('priceDisplay')),\n description: doc.get('description') ?? '',\n // What the widget asks for beyond a name and an email (AGL-3493),\n // as the booking route will hold it: the widget renders and\n // checks the fields from these, the route checks them again.\n askPhone: bookingContactAsks(doc.data()).phone,\n askAddress: bookingContactAsks(doc.data()).address,\n })),\n })\n }\n const serviceSnapshot = await hostRef\n .collection('services')\n .doc(serviceId)\n .get()\n const service = serviceSnapshot.data() as HostBookingService | undefined\n // A draft has no slots to show (AGL-3616): it reads as no service at all.\n if (!service || !bookingServiceIsOffered(service)) {\n return res.status(404).json({ error: 'Unknown service' })\n }\n const nowMs = Date.now()\n // Booking horizon (AGL-428): configurable via the plugin settings\n // framework; defaults to BOOKING_MAX_DAYS_AHEAD through the schema.\n //\n // Resolved for THIS SITE (AGL-428, AGL-1014), not just the workspace.\n // The horizon is the setting per-site overrides were built for — one\n // chain, one answer, and the flagship branch taking bookings further out\n // — so reading only the org's would leave the console showing a number\n // this endpoint never honors.\n const config = await getPluginConfig(\n await resolveOrgIdForHost(hostId),\n 'bookings',\n { hostId },\n )\n const maxDaysAhead = Number(config.maxDaysAhead ?? BOOKING_MAX_DAYS_AHEAD)\n // Measured from NOW whichever page is asked for: the horizon is how far\n // ahead a visitor may book, not how far past the page they are on.\n const toMs = nowMs + maxDaysAhead * 24 * 60 * 60_000\n // The page asked for (AGL-3492): `from` is the `nextFromMs` the previous\n // page answered with. Clamped to now, so a stale or hand-written value\n // can never list a time that has passed, and a value past the horizon\n // lists nothing rather than reaching beyond it.\n const askedFromMs = Number(req.query['from'] ?? 0)\n const fromMs = Number.isFinite(askedFromMs)\n ? Math.min(Math.max(askedFromMs, nowMs), toMs)\n : nowMs\n // Bounded at BOTH ends, to the window the slots are actually computed\n // over. `computeOpenSlotPage` below is handed `fromMs`/`toMs` and ignores\n // anything outside them, so a booking past the horizon was read, billed\n // and discarded — and worse, it competed for the 500 with the bookings\n // that do matter, so a service booked far ahead could push the near-term\n // stays out of its own availability check and offer a taken slot.\n //\n // A second range on `startsAtMs` needs no new index: the field already\n // carries one, and the range it narrows is the one already here.\n const bookedSnapshot = await hostRef\n .collection('bookings')\n .where('serviceId', '==', serviceId)\n .where('startsAtMs', '>=', fromMs - 24 * 60 * 60_000)\n // One page never walks further than BOOKING_MAX_DAYS_AHEAD past its\n // start, so a horizon set further out than that is read a page's\n // worth at a time, not all at once.\n .where(\n 'startsAtMs',\n '<=',\n Math.min(toMs, fromMs + BOOKING_MAX_DAYS_AHEAD * 24 * 60 * 60_000),\n )\n .limit(500)\n .get()\n const booked: BookedInterval[] = bookedSnapshot.docs\n .filter(\n (doc) =>\n doc.get('status') !== 'canceled' &&\n // Expired payment holds release the slot (AGL-170).\n !(\n doc.get('status') === 'pendingPayment' &&\n Number(doc.get('expiresAtMs') ?? 0) < Date.now()\n ),\n )\n .map((doc) => ({\n startsAtMs: Number(doc.get('startsAtMs') ?? 0),\n endsAtMs: Number(doc.get('endsAtMs') ?? 0),\n }))\n // Bounded in DAYS, not slots (AGL-3492): a page is the widget's day\n // strip, whole, with every open time each of those days has. The flat\n // cap of 120 it replaces ran out three and a half weekdays in at\n // 15-minute steps, so the widget showed a calendar that ended on\n // Thursday at lunch and a horizon that was never reachable.\n const { slots, nextFromMs } = computeOpenSlotPage(\n service,\n fromMs,\n toMs,\n booked,\n )\n return res.status(200).json({\n service: {\n name: service.name,\n durationMinutes: service.durationMinutes,\n priceUsd: bookingChargeUsd(service),\n priceDisplay: bookingPriceDisplay(service.priceDisplay),\n timezone: service.timezone ?? 'UTC',\n },\n slots,\n // Where the next page starts; `null` once this one reached the horizon.\n nextFromMs,\n // The configured horizon, so the widget's empty state names it.\n horizonDays: maxDaysAhead,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Slot lookup failed' })\n }\n}\n\n/**\n * Booking creation (AGL-159): validates the slot against the service's\n * windows AND stored bookings inside a transaction (double-booking safe),\n * stores the booking, records a lead, emits the `booking` host event, and\n * sends an env-gated Resend confirmation. Plan gate: the owning org\n * needs the `bookings` flag (dark-launch workspaces pass).\n */\n/**\n * Exported for spec (AGL-2000). The tax decision this handler takes lives in\n * the ABSENCE of a parameter, and an absence is only a decision if something\n * asserts it — see `server-booking-tax.spec.ts`.\n */\nexport const bookHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const serviceId = String(req.body?.serviceId ?? '')\n const startsAtMs = Number(req.body?.startsAtMs ?? 0)\n const name = String(req.body?.name ?? '')\n .trim()\n .slice(0, 80)\n const email = String(req.body?.email ?? '')\n .trim()\n .toLowerCase()\n // Explicit opt-in checkbox (AGL-2499) — a booking is not by itself\n // consent to be emailed marketing, so this is only set when the visitor\n // checked it.\n const marketingConsent = req.body?.marketingConsent === true\n // The record the booking link named (AGL-2660), kept on the row so the\n // booking can be attributed to it even when the visitor books with a\n // different address. Parsed, never stored raw: this is a public door.\n const crmRef = parseBookingRecordRef(req.body?.crmRef)\n if (!hostId || !serviceId || !Number.isFinite(startsAtMs) || !startsAtMs) {\n return res.status(400).json({ error: 'Invalid booking request' })\n }\n if (!name) return res.status(400).json({ error: 'Enter your name' })\n if (!BOOKING_EMAIL_PATTERN.test(email)) {\n return res.status(400).json({ error: 'Enter a valid email' })\n }\n if (startsAtMs < Date.now()) {\n return res.status(409).json({ error: 'That time has already passed' })\n }\n // Keeps counting under the no-address bucket rather than being skipped: an\n // unauthenticated booking endpoint that stops counting writes reservations\n // for anyone who can reach it.\n const ip =\n readClientIp(req.headers, { remoteAddress: req.socket?.remoteAddress }) ??\n NO_CLIENT_ADDRESS_BUCKET\n if (bookingRateLimited(ip)) {\n return res.status(429).json({ error: 'Too many booking attempts' })\n }\n\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const [hostSnapshot, serviceSnapshot] = await Promise.all([\n hostRef.get(),\n hostRef.collection('services').doc(serviceId).get(),\n ])\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n const service = serviceSnapshot.data() as HostBookingService | undefined\n // Refused for a draft as for a deleted service (AGL-3616): a request can\n // name a service id the directory never listed.\n if (!service || !bookingServiceIsOffered(service)) {\n return res.status(404).json({ error: 'Unknown service' })\n }\n // The phone and the address, held to what THIS service asks for\n // (AGL-3493) and checked here whatever the widget already checked: this\n // is a public door, and a request can be written by hand. A field the\n // service does not ask for is dropped rather than stored.\n const contact = readBookingContactFields(bookingContactAsks(service), {\n phone: req.body?.phone,\n address: req.body?.address,\n })\n if ('error' in contact) return res.status(400).json({ error: contact.error })\n const { phone, address } = contact.fields\n // `Phone: …`, `Address: …`, for the managers' notification below.\n const contactLines = bookingContactLines(contact.fields)\n\n // Plan gate (dark-launch rule preserved). Plan/quota gates ride the\n // owning org's doc (AGL-238). Hoisted out of its block for AGL-2315:\n // the same org doc now also prices the platform's cut below, and reading\n // it twice would let a gate and a fee disagree within one request.\n const ownerOrg = (await getOrgForHost(hostId))?.org\n if (!checkEntitlement(ownerOrg as never, 'bookings')) {\n return res\n .status(403)\n .json({ error: 'Bookings are not enabled on this site' })\n }\n\n const durationMs =\n Math.max(5, Math.round(service.durationMinutes || 30)) * 60_000\n const endsAtMs = startsAtMs + durationMs\n const bookingsRef = hostRef.collection('bookings')\n // The zone this booking's time is told in (AGL-3432), stored on the\n // booking so the paid confirmation and the reminder — which read the\n // booking and not the service — state the same wall-clock time as the\n // free confirmation below, and name the zone it is in.\n const timezone = bookingTimeZone({\n service,\n host: hostSnapshot.data?.() as { timeZone?: string } | undefined,\n org: ownerOrg as { timeZone?: string } | null | undefined,\n })\n const when = formatBookingWhen(startsAtMs, timezone)\n\n // Paid services (AGL-170): the slot is HELD pending payment — the\n // booking lands as `pendingPayment` with a 15-minute expiry (expired\n // holds release the slot in the collision filters), and the visitor\n // goes to Stripe Checkout; the webhook confirms + emails on payment.\n // A service that states its price as a label books with no charge\n // (AGL-3475), whatever price it stores.\n const priceUsd = bookingChargeUsd(service)\n const paid = priceUsd > 0\n if (paid && !process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({\n error: 'Paid bookings are not configured (STRIPE_SECRET_KEY).',\n })\n }\n\n // WHO GETS THE MONEY (AGL-2315). Until this landed, a paid booking opened\n // a Checkout Session with no Connect wiring of any kind — no\n // `transfer_data`, no `application_fee_amount`, no connected account read\n // anywhere in the plugin — so 100% of every paid booking settled in\n // AGLYN'S OWN platform balance and the merchant was never paid at all.\n // Not under-paid: never paid. Every sibling tenant money path (storefront\n // checkout, cart, draft orders, POS, reservations) was already a\n // destination charge to the merchant's connected account; this was the one\n // door that took a card and kept the proceeds.\n //\n // Resolved BEFORE the hold transaction on purpose, the `reserve.ts`\n // ordering: an unconnected merchant is a deterministic refusal the site\n // owner fixes out of band, and discovering it after the slot is written\n // would strand a real appointment slot as `pendingPayment` for 15 minutes\n // on a booking that could never be paid.\n let chargeAccountId = ''\n // DIRECT or DESTINATION, by the seller's profile. A direct charge is made\n // ON the seller's own account, which Stripe bills itself; everything else\n // keeps the destination charge this path has always made.\n let chargeModel: SaleChargeModel = 'destination'\n let feeCents = 0\n // No tax until a paid booking asks the tenant's tax rule what is owed.\n let serviceTax: PluginResolvedFlatTax = { taxCents: 0, label: '', pct: 0 }\n if (paid) {\n const ownerUid = (ownerOrg as { ownerUid?: unknown } | null)?.ownerUid\n const [ownerProfile, serviceRate] = await Promise.all([\n ownerUid\n ? firestore.collection('profiles').doc(String(ownerUid)).get()\n : Promise.resolve(null),\n // The merchant's own service rate (AGL-2028), in the SAME round trip\n // as the connected-account read this path already makes — asked of\n // the plugin that keeps the merchant's tax settings, which reads them\n // where it stores them.\n pluginTaxProfile().flatRate(hostId, 'service'),\n ])\n chargeAccountId = String(ownerProfile?.get('stripeAccountId') ?? '')\n if (\n !merchantAccountIsReady(\n {\n accountId: chargeAccountId,\n chargesEnabled: ownerProfile?.get('stripeChargesEnabled'),\n accountLivemode: ownerProfile?.get('stripeAccountLivemode'),\n },\n { subject: `booking host ${hostId}` },\n )\n ) {\n return res.status(409).json({ error: 'Payments are not set up yet' })\n }\n chargeModel = saleChargeModel(ownerProfile?.get('stripeChargeModel'))\n\n // THE TAKE RATE IS THE STOREFRONT LADDER'S, NOT A NEW ONE (AGL-2315).\n //\n // the decision, 2026-08-19: bookings mirror the storefront ladder —\n // the same rate a storefront sale already takes, tapering to 0% on the\n // upper tiers. It is consistent with what merchants already agreed to\n // and needs no new price communication, so pricing stays locked for\n // Sept 1.\n //\n // Implemented by ROUTING THROUGH the existing resolver rather than\n // adding a bookings rate: `resolveTransactionFeePct` already carries a\n // `'service'` axis (it resolves to the digital rate), and a booking is a\n // service sale — `reserve.ts` prices a stay through the identical call.\n // So there is no new constant, no new plan-table row, and no second\n // place for a rate to drift out of step with `/pricing`. Every guard\n // that already holds for the storefront rate holds here for free: the\n // malformed-override floor (AGL-2114), the lapsed-plan re-resolution,\n // and the staff override.\n //\n // FEE BASIS: post-discount ITEMS ONLY, matching the one-time storefront\n // paths and deliberately NOT the subscription path's\n // `application_fee_percent`, which Stripe applies to the whole invoice\n // and so takes a cut of sales tax and shipping (AGL-2317). Here the two\n // bases happen to coincide, because this session carries exactly one\n // line item and, by AGL-2000's stated decision, no tax line and no\n // shipping option. That coincidence is not the reason for the choice —\n // sending a computed CENTS amount rather than a percent is what makes\n // the basis survive the day this path does compute service tax: a fee\n // derived from `priceUsd` stays off the tax the moment tax is added,\n // whereas a percent would silently start taxing the state's money.\n //\n // PLUS STRIPE'S CARD COST, AT COST (AGL-2152). A 0%-fee tier used to\n // take a destination charge with NO application fee at all, which is not\n // \"no take rate\" — Stripe debits 2.9% + 30¢ from the PLATFORM's balance\n // when that charge settles, so every paid booking on Pro and above cost\n // Aglyn money. `resolveTransactionFeeCents` is the same resolver's cents\n // form: the advertised take (still 0% where the ladder says 0%) plus the\n // card cost passed through, so the net per booking is the take and never\n // less. The `Math.max(1, …)` floor on a chargeable take is folded into\n // it, unchanged.\n //\n // The fee base and the charge base are the same number here: by\n // AGL-2000's stated decision this session carries one line item, no tax\n // line and no shipping option, so the card runs for exactly `priceUsd`.\n // SERVICE TAX: the MERCHANT'S OWN RATE, off unless they set one\n // (AGL-2028, answering the decision AGL-2000 recorded here).\n //\n // AGL-2000's reasoning is unchanged and is why this is a field of its\n // own rather than a reuse of the goods table. A service is not goods:\n // whether one is taxable is jurisdiction-specific and frequently the\n // opposite answer, so the AGL-285 `rates[]` are still never read here\n // — a test in `server-booking-tax.spec.ts` pins that with a fully\n // configured sales-tax store. Stripe Tax is still never asked either:\n // it has no service tax code from this handler and would compute a\n // goods rate against AGLYN's registrations (AGL-1904).\n //\n // What changed is that the merchant now has somewhere to answer. A\n // service business is one of the three named ICPs and in many states\n // their services ARE taxable, so \"Aglyn does not compute it\" could only\n // ever be a holding position. They type the rate, we compute it, charge\n // it, record it and stamp the regime; the settings card states plainly\n // that determining what is owed and to whom is theirs. Aglyn takes no\n // tax position, and the existence of a separate, blank-by-default field\n // is also AGL-2000's second reason answered — it is the merchant\n // saying, explicitly, that they mean this to cover bookings.\n //\n // DEFAULT OFF, and load-bearing: an absent, zero, negative or\n // out-of-range rate resolves to zero, so no existing merchant's charge\n // moves because this shipped.\n const chargeCents = Math.round(priceUsd * 100)\n // Asked of the plugin that owns the merchant's tax rule, which throws\n // rather than answer zero if none is loaded: an untaxed charge recorded\n // as untaxed is the failure nobody sees until the merchant owes it.\n serviceTax = pluginTaxProfile().flatTax(\n serviceRate,\n chargeCents,\n 'Service tax',\n )\n // THE TWO FEE BASES ARE NOW DIFFERENT NUMBERS (AGL-2028). The take is\n // computed on the SERVICE, never on the state's money — AGL-2317's rule\n // — while Stripe's card cost is debited from the platform balance on\n // the WHOLE charge and so is passed through on the whole charge\n // (AGL-2152). The comment above already promised this: \"a fee derived\n // from `priceUsd` stays off the tax the moment tax is added\". This is\n // the moment.\n //\n // A DIRECT charge passes no card cost through: Stripe bills the seller\n // its own fee and charges the platform nothing for the sale, so the\n // application fee is the take alone.\n feeCents = resolveTransactionFeeCents(\n ownerOrg as never,\n 'service',\n chargeCents,\n chargeCents + serviceTax.taxCents,\n chargeModel === 'direct' ? { direct: true } : {},\n )\n }\n\n // Transaction: re-read overlapping bookings and validate the slot so\n // two simultaneous requests cannot double-book.\n const bookingId = await firestore.runTransaction(async (transaction) => {\n const overlapping = await transaction.get(\n bookingsRef\n .where('serviceId', '==', serviceId)\n .where('startsAtMs', '>=', startsAtMs - 24 * 60 * 60_000)\n .limit(500),\n )\n const booked: BookedInterval[] = overlapping.docs\n .filter(\n (doc) =>\n doc.get('status') !== 'canceled' &&\n // Expired payment holds release the slot (AGL-170).\n !(\n doc.get('status') === 'pendingPayment' &&\n Number(doc.get('expiresAtMs') ?? 0) < Date.now()\n ),\n )\n .map((doc) => ({\n startsAtMs: Number(doc.get('startsAtMs') ?? 0),\n endsAtMs: Number(doc.get('endsAtMs') ?? 0),\n }))\n if (!isSlotOpen(service, startsAtMs, booked)) {\n throw Object.assign(new Error('Slot unavailable'), { code: 409 })\n }\n const bookingRef = bookingsRef.doc()\n const record = {\n serviceId,\n serviceName: service.name ?? '',\n name,\n email,\n ...(phone ? { phone } : {}),\n ...(address ? { address } : {}),\n startsAtMs,\n endsAtMs,\n timezone,\n status: paid ? 'pendingPayment' : 'confirmed',\n ...(paid && { expiresAtMs: Date.now() + 15 * 60_000 }),\n ...(crmRef ? { crmRef: formatBookingRecordRef(crmRef) } : {}),\n // WHERE THE CHARGE LIVES, for a direct one: a refund has to be made on\n // the seller's account, and the booking is what the refund reads.\n // Absent on a destination booking, which is the platform's charge.\n ...(paid && chargeModel === 'direct'\n ? { chargeModel: 'direct', stripeAccountId: chargeAccountId }\n : {}),\n }\n transaction.set(bookingRef, { ...record, createdAt: FieldValue.serverTimestamp() })\n // A free booking is confirmed as it is made (AGL-3643); a paid one\n // raises `booking.created` from the payment webhook instead.\n if (!paid) {\n const nowMs = Date.now()\n stageBookingEvent(transaction, firestore, {\n event: 'booking.created',\n hostId,\n bookingId: bookingRef.id,\n booking: { ...record, createdAt: nowMs },\n nowMs,\n })\n }\n return bookingRef.id\n })\n\n /*\n * WHERE THE VISITOR ARRIVED FROM, RESOLVED ONCE FOR THE WHOLE BOOKING.\n *\n * A booking is an identify moment: the visitor was anonymous while they\n * browsed and picked a slot, and this request is the first thing that\n * names them. The plugin that credits outcomes\n * (`plugin-conversion-credit`) is asked with what their device carried\n * and the address they just typed, and decides what earns the credit.\n *\n * Resolved once and handed to the booking record, the contact and the\n * lead below, so the lookup is paid once for the whole request and the\n * three records cannot be credited to different arrivals.\n */\n const bookedAtMs = Date.now()\n const arrival = await resolveConversionTouch({\n hostId,\n wire: req.body?.campaignTouch,\n email,\n atMs: bookedAtMs,\n })\n void creditConversion({\n hostId,\n kind: 'booking',\n refId: bookingId,\n touch: arrival,\n convertedAtMs: bookedAtMs,\n })\n\n /*\n * Contacts ingestion (AGL-197) — booking requests identify a person —\n * reported to whichever plugin keeps people rather than written by this\n * one (AGL-3080). Bookings knows it just met somebody; what a person\n * record is belongs to the plugin that models it, and a workspace that\n * keeps none is a quiet, correct answer here.\n */\n /*\n * A booking request is a LEAD SURFACE (AGL-3232): interest, not a sale\n * — no money has moved, and the payment webhook is the door that makes\n * a customer. The record system files the person as a lead, or lands\n * the request on the contact the workspace already holds for the\n * address; which record, and the lead's ceiling and dedupe, are its to\n * decide. Awaited rather than voided so the lead is there before the\n * response, as it was when this door wrote it itself; the seam never\n * throws, so a refused capture still cannot fail the booking.\n */\n await recordCapturedContact({\n /*\n * Not resolved here. The record system keys a person on the SITE they\n * were met on, so this costs the capture nothing — and resolving it\n * would put a Firestore read in front of the writer, which is the one\n * thing `recordCapturedContact` asks a door not to do.\n */\n orgId: '',\n hostId,\n identity: { email, name: name || undefined },\n interaction: {\n source: 'booking',\n refId: bookingId,\n summary: `Booked \"${String(service.name ?? 'a service').slice(0, 60)}\"`,\n },\n surface: 'lead',\n // The phone the booker gave (AGL-3493), onto the person only where\n // the record holds none: a number somebody typed on the record, or\n // gave the business before, is not replaced by one typed into a\n // booking form. The address is the JOB's, not the person's, and\n // rides the meeting below instead.\n ...(phone ? { profileFill: { phone } } : {}),\n ...(marketingConsent ? { marketingConsent: true } : {}),\n // Where the visitor ARRIVED from — a fact about this visit and not\n // about the person, which is what `detail` carries.\n ...(arrival ? { detail: { [CONVERSION_TOUCH_DETAIL]: arrival } } : {}),\n })\n\n if (paid) {\n // The site's own origin, never a header's say-so (AGL-3363): a\n // caller writes `Origin` and `Host`, and Stripe sends the payer here.\n const origin = siteReturnOrigin({\n candidates: [\n typeof req.headers.origin === 'string' ? req.headers.origin : '',\n `https://${req.headers.host}`,\n ],\n site: hostSnapshot.data?.() as SiteReturnHost | undefined,\n requestHost: String(req.headers.host ?? ''),\n })\n // TAX ON A PAID BOOKING: the merchant's own service rate, resolved\n // above and default OFF (AGL-2028, answering AGL-2000).\n //\n // The rate rides as an ORDINARY product line Stripe is never told is\n // tax — the AGL-1711 construction every other manual rate in this\n // repo uses. That is what makes the derived `taxMode` read `manual`:\n // the figure is the merchant's own, from their own rate, and is never\n // computed against Aglyn's registrations the way `automatic_tax` would\n // be (AGL-1904). Absent entirely when no rate is set, so a default\n // store's session carries no tax parameter of any kind — the property\n // `server-booking-tax.spec.ts` asserts over the whole emitted body.\n //\n // The sale is recorded either way: `booking-payment` has been in\n // `storefront-tax-record.ts`'s SESSION_TYPES since AGL-2000, so an\n // untaxed booking still files a row reading `taxMode: 'none'` and a\n // taxed one files `manual` with the figure, both with no further\n // wiring.\n const params = new URLSearchParams({\n mode: 'payment',\n // 3-D Secure, from the one seam every card payment shares (AGL-3360).\n ...checkoutSessionCardAuthenticationParams('payment'),\n 'line_items[0][quantity]': '1',\n 'line_items[0][price_data][currency]': 'usd',\n 'line_items[0][price_data][unit_amount]': String(\n Math.round(priceUsd * 100),\n ),\n 'line_items[0][price_data][product_data][name]': String(\n service.name ?? 'Booking',\n ).slice(0, 120),\n ...(serviceTax.taxCents > 0\n ? {\n 'line_items[1][quantity]': '1',\n 'line_items[1][price_data][currency]': 'usd',\n 'line_items[1][price_data][unit_amount]': String(\n serviceTax.taxCents,\n ),\n 'line_items[1][price_data][product_data][name]': serviceTax.label,\n }\n : {}),\n // A DIRECT charge is the seller's money by where the session lives\n // (the `Stripe-Account` header below), so it carries no\n // `transfer_data`, only Aglyn's take as the application fee.\n ...(chargeModel === 'direct'\n ? directChargeParams(feeCents)\n : {\n // Destination charge to the MERCHANT's connected account (AGL-2315).\n // Unconditional: `transfer_data[destination]` is what makes this the\n // merchant's money, and it is required on every paid booking whatever\n // the take rate. Only the fee below is conditional.\n 'payment_intent_data[transfer_data][destination]': chargeAccountId,\n ...(feeCents > 0\n ? { 'payment_intent_data[application_fee_amount]': String(feeCents) }\n : {}),\n }),\n // `{CHECKOUT_SESSION_ID}` is Stripe's own template token, substituted\n // on the redirect (AGL-2481). Without it the guest came back holding\n // the word `paid` and nothing else — no id, no amount — so the\n // merchant-side `purchase` had nothing to look itself up by and could\n // not have stated what was actually charged. The id is safe in the\n // URL: Stripe hands it only to the payer, and\n // `booking-analytics.ts` scopes it to the host and answers with a\n // projection rather than the booking document.\n success_url: `${origin}/?booking=paid&session_id={CHECKOUT_SESSION_ID}`,\n cancel_url: `${origin}/?booking=canceled`,\n customer_email: email,\n 'metadata[type]': 'booking-payment',\n 'metadata[hostId]': hostId,\n 'metadata[bookingId]': bookingId,\n // The fee actually charged, recorded on the session exactly as every\n // sibling path records it — the figure a refund reverses and the\n // figure a reconciliation reads. `'0'` on a 0%-fee tier is a real\n // answer, not a missing one.\n 'metadata[feeCents]': String(feeCents),\n // The only witness to the tax (AGL-2028). By the construction above\n // Stripe does not know the second line is tax and reports\n // `total_details.amount_tax: 0`, so the session's own metadata is\n // what `storefront-tax-record.ts` and the confirmation webhook read\n // to record the figure and derive the regime — exactly as\n // `checkout.ts` stamps it for a buy-now sale. Absent when there is no\n // tax, never a reassuring `'0'`: absent and zero are different facts.\n ...(serviceTax.taxCents > 0\n ? {\n 'metadata[taxCents]': String(serviceTax.taxCents),\n 'metadata[taxPct]': String(serviceTax.pct),\n }\n : {}),\n // Tells the webhook and the refund that this session, and the charge\n // it makes, live on the seller's account. Absent on a destination one.\n ...(chargeModel === 'direct' ? { 'metadata[chargeModel]': 'direct' } : {}),\n expires_at: String(Math.floor(Date.now() / 1000) + 30 * 60),\n })\n // No buy-now-pay-later on a booking (AGL-4198), so the fee above,\n // priced at the card rate, covers whatever the guest pays with.\n excludeBuyNowPayLater(params)\n const stripeResponse = await fetch(\n 'https://api.stripe.com/v1/checkout/sessions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n // AGL-2147. This was the ONE session-creating path in the repo\n // with no idempotency key: console checkout, enterprise billing,\n // marketplace checkout, and commerce's checkout / cart-checkout /\n // draft-order / reservation / POS paths all carry one, and this\n // takes a card payment exactly as they do.\n //\n // Keyed on the BOOKING, not on a client-minted header: the\n // transaction above mints a fresh `bookingId` per attempt, so it\n // already names this attempt uniquely and needs no widget change\n // to supply. That also sidesteps Stripe's 24h key expiry — a key\n // reused across attempts eventually replays a session that has\n // since expired (these are opened with a 30-minute `expires_at`),\n // handing the guest a dead checkout page instead of a new one.\n //\n // What it closes: a retried POST after Stripe has already created\n // the session but before its response arrived. Without the key\n // that opens a SECOND payable session against one held slot, and\n // a guest who pays both is charged twice for one appointment.\n 'Idempotency-Key': `booking-${bookingId}`,\n // A direct charge's session is opened ON the seller's account.\n ...connectedAccountHeader(chargeModel, chargeAccountId),\n },\n body: params.toString(),\n },\n )\n const session = (await stripeResponse.json()) as {\n url?: string\n error?: unknown\n }\n if (!stripeResponse.ok || !session.url) {\n console.error('Stripe booking checkout error', session.error)\n // Release the hold so the slot isn't stuck for 15 minutes.\n await bookingsRef\n .doc(bookingId)\n .set({ status: 'canceled' }, { merge: true })\n .catch(() => undefined)\n return res.status(502).json({ error: 'Payment setup failed' })\n }\n // The lead landed above; the confirmation email and the managers'\n // notification go out from the payment webhook.\n return res\n .status(200)\n .json({ bookingId, startsAtMs, endsAtMs, checkoutUrl: session.url })\n }\n\n // Event trigger (AGL-128/148/159).\n // In-app notification to the site's managers (AGL-259): who booked what,\n // and when, in the booking's own zone and naming it (AGL-3432), and the\n // phone and address the service asked for (AGL-3493) — the two things\n // an on-site service needs before it can do anything with the booking.\n void notifyHostManagers(hostId, {\n type: 'content.booking',\n title: 'New booking on {site}',\n body:\n `${name} (${email}) booked ${String(service.name ?? 'a service')} ` +\n `on {site} for ${when} (${timezone}).` +\n (contactLines.length ? ` ${contactLines.join('. ')}.` : ''),\n link: `/${hostId}/bookings`,\n })\n const { alerts } = await emitHostEvent(\n hostId,\n 'booking',\n { serviceName: service.name ?? '', email, startsAtMs },\n // The visitor who booked (AGL-3376).\n { actor: { kind: 'visitor', email } },\n )\n\n // Env-gated confirmation email (same provider as AGL-98).\n if (isEmailConfigured()) {\n const fallbackText =\n `Hi ${name},\\n\\nYour booking for \"${service.name}\" is ` +\n `confirmed for ${when} (${timezone}).\\n\\n` +\n `Reference: ${bookingId}`\n // Site-owner-designed template when published (AGL-770); null keeps the\n // built-in copy above.\n const designed = await renderHostEmailWithTokens(\n firestore,\n hostId,\n 'booking-confirmed',\n {\n name: String(name ?? ''),\n 'service.name': String(service.name ?? ''),\n when,\n timezone,\n // A free booking charged nothing: empty, so the line is left out.\n 'booking.payment': '',\n 'booking.ref': String(bookingId),\n },\n )\n // White-label sender identity (White-Label Phase 3): the store's brand\n // via the one shared resolver, from the owning org doc.\n const branding = resolveBrandingProfile(\n (await getOrgForHost(hostId).catch(() => null))?.org as never,\n )\n const confirmation = await sendEmail({\n to: email,\n subject: designed?.subject ?? `Booking confirmed: ${service.name}`,\n text: designed?.text || fallbackText,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(hostId),\n audience: 'tenant',\n context: 'booking confirmation',\n // Owed to the recipient by their own booking: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'booking',\n })\n // Cost meter (AGL-1438), for a message that LEFT (AGL-4227): one the\n // workspace's email limit or the provider refused is not a cost, and\n // counting it would show the owner mail their customer never got.\n if (confirmation?.sent) await meterHostEmail(hostId)\n }\n\n // THE RECORD'S MEETING (AGL-2660). A free booking is confirmed right\n // here, so this is where it reaches the CRM: the meeting on the\n // record's timeline and, when the service asks, the follow-up task. A\n // paid booking waits for the webhook, which files it once the charge\n // has cleared. Awaited, because a route handler is frozen the moment\n // it answers (AGL-2327) — and never thrown: the slot is the guest's\n // whatever the CRM did.\n await fileBookingOnCrm(firestore, {\n hostId,\n bookingId,\n booking: {\n serviceId,\n serviceName: service.name ?? '',\n email,\n ...(phone ? { phone } : {}),\n ...(address ? { address } : {}),\n startsAtMs,\n endsAtMs,\n ...(crmRef ? { crmRef: formatBookingRecordRef(crmRef) } : {}),\n },\n service,\n })\n\n return res.status(200).json({ bookingId, startsAtMs, endsAtMs, alerts })\n } catch (error: unknown) {\n if ((error as { code?: number })?.code === 409) {\n return res\n .status(409)\n .json({ error: 'That time was just taken — pick another slot' })\n }\n console.error(error)\n return res.status(500).json({ error: 'Booking failed' })\n }\n}\n\n/**\n * One reminder pass (AGL-160), extracted from its HTTP door in AGL-2431.\n *\n * Finds confirmed bookings starting 23–25 hours out (collection-group query,\n * so one call covers every host), emails each visitor through the env-gated\n * Resend path, and stamps `reminderSentAt` so re-runs are idempotent.\n *\n * WHY THIS IS A FUNCTION NOW. It only ever existed as `POST bookings/reminders`\n * behind `x-cron-secret`, and nothing anywhere POSTed to it — not\n * `scheduled-crons.yml`, not `vercel.json` (which has no `crons` key), not\n * `registerPluginJob`. The route's own docblock said \"invoke hourly from the\n * scheduler\" for as long as it has existed. It never ran, for anyone. Same\n * shape as the two commerce beats in AGL-2227, one plugin over.\n */\nexport async function scanBookingReminders(\n /** The lockdown gate, injected by the caller (AGL-2495). Not optional. */\n gate: PluginJobHostGate,\n): Promise<{\n scanned: number\n sent: number\n skipped: number\n skippedLocked: number\n}> {\n const firestore = firebaseAdmin.app().firestore()\n // ONE instant for the query bounds and for the per-booking predicate. Two\n // `Date.now()` calls would put a booking sitting on an edge inside the\n // query and outside the test, so the pass would fetch it, skip it, and\n // report a `skipped` the console could not explain.\n const nowMs = Date.now()\n const windowStart = nowMs + REMINDER_WINDOW_START_HOURS * 60 * 60 * 1000\n const windowEnd = nowMs + REMINDER_WINDOW_END_HOURS * 60 * 60 * 1000\n const upcoming = await firestore\n .collectionGroup('bookings')\n .where('startsAtMs', '>=', windowStart)\n .where('startsAtMs', '<=', windowEnd)\n .limit(500)\n .get()\n\n let sent = 0\n let skipped = 0\n let skippedLocked = 0\n // Resolve each host's designed reminder template once per run (AGL-770),\n // not once per booking — a busy site has many bookings in the window.\n const templateCache = new Map<string, LoadedHostEmailWithTokens | null>()\n // White-label brand per host (White-Label Phase 3): resolved once per host\n // from the owning org doc through the one shared resolver, so a reminder\n // reads as the store's brand.\n const brandingByHost = new Map<\n string,\n ReturnType<typeof resolveBrandingProfile>\n >()\n /*\n * One identity resolution per SITE, not per booking.\n *\n * The same reason the branding and template maps above exist: this sweep\n * runs across every site, and an uncached resolution would be two Firestore\n * reads per reminder rather than per host. Scoped to the run, so a domain\n * un-verified between runs is picked up on the next one.\n */\n const identityByHost = new Map<\n string,\n Awaited<ReturnType<typeof hostSendingIdentity>>\n >()\n // The zone for a booking that predates storing one (AGL-3432), resolved\n // once per service for the whole run.\n const zoneByService = new Map<string, Promise<string>>()\n for (const doc of upcoming.docs) {\n const data = doc.data()\n // The shared predicate, not a local copy of it (AGL-2431): the console\n // card counts what is waiting with this same function, so the number a\n // merchant reads is the number this loop will act on.\n if (!isBookingReminderDue(data as never, nowMs)) {\n skipped += 1\n continue\n }\n // bookings live at hosts/{hostId}/bookings/{id}, so the grandparent is\n // the host.\n const hostId = doc.ref.parent.parent?.id ?? ''\n // LOCKDOWN (AGL-2495), ahead of the send, the meter and the\n // `reminderSentAt` stamp — the three things this loop does, all of them\n // for the host. Counted separately from `skipped` on purpose: `skipped`\n // means \"this booking was not due\", and folding a locked site into it\n // would make a suspended merchant's silence read as an ordinary quiet\n // hour on the console card that shows these numbers.\n //\n // SKIPPED, NOT DROPPED: `reminderSentAt` is what retires a booking from\n // this pass, and it is stamped only on a successful send. An unstamped\n // booking is re-scanned hourly — though unlike the other five, this one\n // has a real deadline: the 23–25h window closes. A reminder whose window\n // passed under a lock is genuinely lost, and that is the correct\n // outcome, not a defect to engineer around. A site under takedown should\n // not be mailing its customers, and a reminder that arrives after the\n // appointment is worse than none.\n if (await gate.isLocked(hostId)) {\n skippedLocked += 1\n continue\n }\n // The booking's own zone, named beside the time (AGL-3432). A formatter\n // with no zone reads in the server's — UTC — and states the wrong hour.\n const timezone = await bookingTimeZoneFor(\n firestore,\n hostId,\n data,\n zoneByService,\n )\n const when = formatBookingWhen(Number(data['startsAtMs']), timezone)\n let loaded = templateCache.get(hostId)\n if (loaded === undefined) {\n loaded = hostId\n ? await // The template, or the built-in copy in the site's header and\n // footer, once per site for the whole batch (AGL-3287, AGL-3370).\n loadHostEmailWithTokens(firestore, hostId, 'booking-reminder')\n : null\n templateCache.set(hostId, loaded)\n brandingByHost.set(\n hostId,\n resolveBrandingProfile(\n (hostId\n ? await getOrgForHost(hostId).catch(() => null)\n : null\n )?.org as never,\n ),\n )\n }\n const serviceName = String(data['serviceName'] ?? 'your booking')\n const designed = loaded\n ? renderLoadedHostEmailWithTokens(\n loaded,\n {\n name: String(data['name'] ?? ''),\n 'service.name': serviceName,\n when,\n timezone,\n },\n )\n : null\n const result = await sendEmail({\n to: String(data['email']),\n subject: designed?.subject ?? `Reminder: ${serviceName} tomorrow`,\n text:\n designed?.text ||\n `Hi ${data['name'] ?? ''},\\n\\nA reminder that \"${serviceName}\" is ` +\n `scheduled for ${when} (${timezone}).\\n\\nReference: ${doc.id}`,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: brandingByHost.get(hostId)?.fromName,\n sendingIdentity: await hostSendingIdentity(hostId, identityByHost),\n audience: 'tenant',\n context: 'booking reminder',\n // Owed to the recipient by their own booking: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'booking',\n })\n if (result.sent) {\n // Cost meter (AGL-1438). Transactional: a reminder a quota refused is\n // a missed appointment for the site's own customer.\n await meterHostEmail(hostId)\n sent += 1\n await doc.ref\n .set(\n {\n reminderSentAt:\n firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n .catch(() => undefined)\n }\n }\n return { scanned: upcoming.size, sent, skipped, skippedLocked }\n}\n\n/**\n * The reminder beat (AGL-2431).\n *\n * MODULE SCOPE, like `expire-stale-holds` above and the three commerce beats:\n * the runner route reaches jobs through `ensureAll(['tenantApi'])`, so a\n * registration inside a `register*` function would depend on which entry\n * point happened to be loaded — the AGL-2227 lesson.\n *\n * HOURLY, matching the window's own resolution. The scan mails a two-hour\n * band 23–25h out, so a beat faster than the band buys nothing; a beat slower\n * than 2h could step over the band entirely and skip a day's reminders. An\n * hour sits inside that with room, and the pass is bounded (500 docs) and\n * idempotent — `reminderSentAt` is stamped on send — so an overlapping or\n * repeated beat cannot double-mail anybody.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'booking-reminders',\n intervalMinutes: 60,\n description: 'Email a 24-hour reminder for each upcoming confirmed booking.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n // Quietly, not as an error: email is optional per deployment, and a beat\n // that logs hourly on a self-host without Resend buries everything else.\n if (!isEmailConfigured()) return\n const { sent } = await scanBookingReminders(gate)\n if (sent) console.info(`bookings: sent ${sent} booking reminders`)\n },\n})\n\n/**\n * The manual door, kept for ops (AGL-2431): the scheduling now lives in the\n * `booking-reminders` job above, and this stays so a pass can be forced\n * without waiting for the beat.\n */\nconst remindersHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const cronSecret = process.env.CRON_SECRET\n if (!cronSecret) {\n return res\n .status(501)\n .json({ error: 'Reminders are not configured (CRON_SECRET).' })\n }\n if (req.headers['x-cron-secret'] !== cronSecret) {\n return res.status(401).json({ error: 'Unauthenticated' })\n }\n if (!isEmailConfigured()) {\n return res.status(501).json({\n error: 'Reminders are not configured (RESEND_API_KEY, USAGE_EMAIL_FROM).',\n })\n }\n try {\n // The manual door asks the same question the beat does (AGL-2495).\n return res.status(200).json(await scanBookingReminders(siteLockdownJobGate()))\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Reminders failed' })\n }\n}\n\n/** Registers the bookings plugin's public (site-facing) API routes (AGL-396). */\nexport function registerBookingsApi(): void {\n registerPluginApiRoute('bookings/slots', slotsHandler)\n // A deposit opens a Stripe Checkout Session for whoever books, so the\n // dispatcher holds this door to the card-testing counters (AGL-3363).\n registerPluginApiRoute('bookings/book', bookHandler, { cardPayment: true })\n}\n\n/** Registers the bookings plugin's console-side API routes (AGL-396). */\nexport function registerBookingsConsoleApi(): void {\n registerPluginApiRoute('bookings/reminders', remindersHandler)\n // Refunding a paid booking (AGL-2315). Console-side, because it is\n // site-admin-gated and moves money — never a site-facing route.\n registerPluginApiRoute('bookings/refund', bookingRefundHandler)\n // Paying for a booking at the counter, on the native Aglyn POS app's reader\n // (AGL-3618). Staff-gated like a refund, and it moves money the same way.\n registerPluginApiRoute('bookings/in-person-payment', bookingInPersonPaymentHandler)\n // Checking a guest in and moving a booking (AGL-3621), for the site's\n // team in the native Aglyn app: member routes, one transaction each.\n registerPluginApiRoute('bookings/check-in', createBookingCheckInHandler(bookingManageDeps()))\n registerPluginApiRoute('bookings/reschedule', createBookingRescheduleHandler(bookingManageDeps()))\n // Canceling a booking with no money on it (AGL-3643): the console's cancel\n // for a free booking, so the cancel reaches the plugins listening for it.\n registerPluginApiRoute('bookings/cancel', createBookingCancelHandler(bookingManageDeps()))\n // The merchant-side `purchase` lookup (AGL-2481). A public, unauthenticated\n // read like `bookings/slots`, authorised by the unguessable Stripe session\n // id and answering with a projection that carries no guest identity.\n registerPluginApiRoute('bookings/booking-analytics', bookingAnalyticsHandler)\n // Paid-booking confirmation rides the platform Stripe webhook (AGL-418).\n registerBillingWebhookHandler(bookingsBillingWebhookHandler)\n // Bookings by service as a figure table (AGL-2915), for the AI plugin's\n // insights to read by id; the console runs insight jobs.\n registerBookingFigureReader(() => firebaseAdmin.app().firestore())\n // A draft service another plugin asks for by name (AGL-3616) — an AI build\n // setting a site up from a brief. The console runs AI jobs (AGL-3026).\n registerBookingServiceDraftWriter()\n // …and the operation an AI build plans for it, which that writer executes.\n registerBookingServiceAiCapability()\n}\n"],"names":["siteReturnOrigin","excludeBuyNowPayLater","checkEntitlement","registerPluginConfigSchema","registerPluginJob","resolveBrandingProfile","resolveTransactionFeeCents","siteLockdownJobGate","loadHostEmailWithTokens","renderLoadedHostEmailWithTokens","BOOKING_MAX_DAYS_AHEAD","bookingChargeUsd","bookingContactAsks","bookingPriceDisplay","bookingContactLines","readBookingContactFields","bookingServiceIsOffered","bookingTimeZone","computeOpenSlotPage","formatBookingWhen","isBookingReminderDue","isSlotOpen","REMINDER_WINDOW_END_HOURS","REMINDER_WINDOW_START_HOURS","bookingTimeZoneFor","registerBillingWebhookHandler","registerPluginApiRoute","pluginTaxProfile","BUNDLE_ID","BOOKINGS_CONFIG_SCHEMA","bookingsBillingWebhookHandler","bookingAnalyticsHandler","registerBookingFigureReader","registerBookingServiceAiCapability","registerBookingServiceDraftWriter","bookingRefundHandler","stageBookingEvent","bookingInPersonPaymentHandler","bookingManageDeps","createBookingCheckInHandler","createBookingCancelHandler","createBookingRescheduleHandler","formatBookingRecordRef","parseBookingRecordRef","fileBookingOnCrm","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","cutoff","Date","now","snapshot","firebaseAdmin","app","firestore","collectionGroup","where","limit","get","lapsed","doc","docs","hostId","ref","parent","id","isLocked","set","status","merge","console","info","getOrgForHost","meterHostEmail","notifyHostManagers","getPluginConfig","resolveOrgIdForHost","renderHostEmailWithTokens","hostSendingIdentity","connectedAccountHeader","directChargeParams","merchantAccountIsReady","saleChargeModel","checkoutSessionCardAuthenticationParams","emitHostEvent","recordCapturedContact","CONVERSION_TOUCH_DETAIL","creditConversion","resolveConversionTouch","isEmailConfigured","sendEmail","FieldValue","NO_CLIENT_ADDRESS_BUCKET","readClientIp","BOOKING_EMAIL_PATTERN","recentBookingIpHits","Map","BOOKING_RATE_WINDOW_MS","BOOKING_RATE_MAX","bookingRateLimited","ip","hits","filter","t","push","length","slotsHandler","req","res","method","json","error","String","query","serviceId","config","service","hostRef","collection","services","data","map","$id","durationMinutes","Number","priceUsd","priceDisplay","askPhone","phone","askAddress","address","serviceSnapshot","nowMs","maxDaysAhead","toMs","askedFromMs","fromMs","isFinite","Math","min","max","bookedSnapshot","booked","startsAtMs","endsAtMs","slots","nextFromMs","timezone","horizonDays","bookHandler","body","trim","slice","email","toLowerCase","marketingConsent","crmRef","test","headers","remoteAddress","socket","hostSnapshot","Promise","all","exists","contact","fields","contactLines","ownerOrg","org","durationMs","round","bookingsRef","host","when","paid","process","env","STRIPE_SECRET_KEY","chargeAccountId","chargeModel","feeCents","serviceTax","taxCents","label","pct","ownerUid","ownerProfile","serviceRate","resolve","flatRate","accountId","chargesEnabled","accountLivemode","subject","chargeCents","flatTax","direct","bookingId","runTransaction","transaction","overlapping","Object","assign","Error","code","bookingRef","record","serviceName","expiresAtMs","stripeAccountId","createdAt","serverTimestamp","event","booking","bookedAtMs","arrival","wire","campaignTouch","atMs","kind","refId","touch","convertedAtMs","orgId","identity","undefined","interaction","source","summary","surface","profileFill","detail","origin","candidates","site","requestHost","params","URLSearchParams","mode","success_url","cancel_url","customer_email","expires_at","floor","stripeResponse","fetch","Authorization","toString","session","ok","url","catch","checkoutUrl","type","title","join","link","alerts","actor","fallbackText","designed","branding","confirmation","to","text","html","fromName","sendingIdentity","audience","context","owedFor","sent","scanBookingReminders","windowStart","windowEnd","upcoming","skipped","skippedLocked","templateCache","brandingByHost","identityByHost","zoneByService","loaded","result","reminderSentAt","scanned","size","remindersHandler","cronSecret","CRON_SECRET","registerBookingsApi","cardPayment","registerBookingsConsoleApi"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAEEA,gBAAgB,QACX,yCAAwC;AAC/C,SAASC,qBAAqB,QAAQ,2CAA0C;AAChF,SAASC,gBAAgB,EAEvBC,0BAA0B,EAC1BC,iBAAiB,EACjBC,sBAAsB,EACtBC,0BAA0B,QACrB,sBAAqB;AAC5B,wEAAwE;AACxE,2EAA2E;AAC3E,0EAA0E;AAC1E,0BAA0B;AAC1B,SAASC,mBAAmB,QAAQ,wDAAuD;AAC3F,SACEC,uBAAuB,EACvBC,+BAA+B,QAE1B,oDAAmD;AAC1D,SAA8BC,sBAAsB,EAAEC,gBAAgB,EAAEC,kBAAkB,EAAEC,mBAAmB,EAAEC,mBAAmB,EAAEC,wBAAwB,EAAEC,uBAAuB,EAAEC,eAAe,EAAEC,mBAAmB,EAAEC,iBAAiB,EAA2BC,oBAAoB,EAAEC,UAAU,EAAEC,y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