@aglyn/plugins-bookings 1.0.0-beta.219 → 1.0.0-beta.220
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 +12 -12
- package/src/lib/components/book-meeting-action.d.ts +7 -4
- package/src/lib/components/book-meeting-action.js +2 -2
- package/src/lib/components/book-meeting-action.js.map +1 -1
- package/src/lib/components/booking.js +10 -10
- package/src/lib/components/booking.js.map +1 -1
- package/src/lib/model/booking-record.d.ts +74 -0
- package/src/lib/model/booking-record.js +131 -0
- package/src/lib/model/booking-record.js.map +1 -0
- package/src/lib/model/booking-time.d.ts +60 -0
- package/src/lib/model/booking-time.js +65 -0
- package/src/lib/model/booking-time.js.map +1 -0
- package/src/lib/model/bookings-record-routes.d.ts +15 -0
- package/src/lib/model/bookings-record-routes.js +1 -1
- package/src/lib/model/bookings-record-routes.js.map +1 -1
- package/src/lib/model/bookings-search-sources.js +4 -2
- package/src/lib/model/bookings-search-sources.js.map +1 -1
- package/src/lib/model/bookings.d.ts +4 -4
- package/src/lib/model/bookings.js +3 -3
- package/src/lib/model/bookings.js.map +1 -1
- package/src/lib/model/index.d.ts +2 -0
- package/src/lib/model/index.js +2 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/server/billing-webhook.js +18 -9
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/booking-crm.d.ts +40 -24
- package/src/lib/server/booking-crm.js +84 -26
- package/src/lib/server/booking-crm.js.map +1 -1
- package/src/lib/server/booking-time-zone.d.ts +32 -0
- package/src/lib/server/booking-time-zone.js +59 -0
- package/src/lib/server/booking-time-zone.js.map +1 -0
- package/src/lib/server.js +46 -35
- package/src/lib/server.js.map +1 -1
- package/src/lib/tenant-emails.js +19 -4
- package/src/lib/tenant-emails.js.map +1 -1
|
@@ -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 { captureHostContact } from '@aglyn/tenant-runtime'\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'\n\n/**\n * Paid-booking section of the platform Stripe webhook (AGL-170/418):\n * payment confirms the pendingPayment hold — relocated verbatim from the\n * console route; registered via registerBookingsConsoleApi.\n */\n/** gRPC `Status.FAILED_PRECONDITION` — Firestore's \"this query needs an index\". */\nconst GRPC_FAILED_PRECONDITION = 9\n\n/**\n * The booking a charge paid for, found by the `paymentIntentId` the paid\n * handler below records (AGL-2315), or null. A missing collection-group\n * index is logged and answered null rather than thrown: no redelivery can\n * fix it, and the dispute then reaches staff through the route's\n * unattributed-dispute alert instead of vanishing.\n */\nasync function findBookingForPayment(\n paymentIntentId: string,\n): Promise<FirebaseFirestore.QueryDocumentSnapshot | null> {\n if (!paymentIntentId) return null\n const matches = await firebaseAdmin\n .app()\n .firestore()\n .collectionGroup('bookings')\n .where('paymentIntentId', '==', paymentIntentId)\n .limit(2)\n .get()\n .catch((error: { code?: number }) => {\n if (error?.code !== GRPC_FAILED_PRECONDITION) throw error\n console.error(\n 'Booking payment lookup needs the collection-group index on ' +\n 'bookings.paymentIntentId (AGL-3360)',\n error,\n )\n return null\n })\n // One payment intent pays one booking; two is corrupt data, and stamping\n // an arbitrary one would tell the wrong merchant.\n return matches && matches.docs.length === 1 ? matches.docs[0] : null\n}\n\n/** What a booking records once its lost dispute's reversal is settled. */\ninterface BookingDisputeReversal {\n disputeId: string\n reversedTransferCents: number\n transferReversalId?: string\n /** Why nothing was pulled back, when nothing was. */\n failedReason?: TransferReversalFailure\n owedCents?: number\n atMs: number\n}\n\n/**\n * The merchant's share of a LOST booking dispute, pulled back from the\n * connected account (AGL-3363), by the AGL-1794 policy a store order follows:\n * the Stripe half is the shared `reverseDestinationTransfer`, this is only\n * the booking's own record.\n *\n * IDEMPOTENT BY THE BOOKING: `disputeReversal` for this dispute, present,\n * means settled and a redelivery returns before any Stripe call. A delivery\n * that died after the POST is healed by the seam adopting the reversal the\n * transfer already carries. A transient Stripe failure THROWS (the seam\n * does), leaving the marker unset so Stripe's redelivery retries it. A final\n * failure is settled with its reason and the owed amount, so it is findable.\n *\n * `cents` is non-zero only for the delivery that wrote the reversal, which\n * is the one that tells the merchant.\n */\nasync function reverseBookingSellerShare(\n bookingRef: FirebaseFirestore.DocumentReference,\n dispute: any,\n): Promise<{ cents: number; settled: 'reversed' | 'failed' | 'pending' }> {\n const disputeId = String(dispute?.id ?? '')\n const amountCents = Math.max(0, Math.round(Number(dispute?.amount ?? 0)))\n if (!disputeId || !(amountCents > 0)) return { cents: 0, settled: 'failed' }\n const firestore = firebaseAdmin.app().firestore()\n const prior = (await bookingRef.get()).get('disputeReversal') as\n | BookingDisputeReversal\n | undefined\n if (prior?.disputeId === disputeId) {\n return { cents: 0, settled: prior.failedReason ? 'failed' : 'reversed' }\n }\n const outcome = await reverseDestinationTransfer({\n kind: 'dispute',\n id: disputeId,\n amountCents,\n chargeId:\n typeof dispute?.charge === 'string' ? dispute.charge : String(dispute?.charge?.id ?? ''),\n metadata: { bookingId: bookingRef.id },\n })\n if (outcome.kind === 'skipped') {\n console.error('Booking transfer reversal skipped: STRIPE_SECRET_KEY is not set (AGL-3363)')\n return { cents: 0, settled: 'pending' }\n }\n const record: BookingDisputeReversal =\n outcome.kind === 'reversed'\n ? {\n disputeId,\n reversedTransferCents: outcome.cents,\n ...(outcome.reversalId ? { transferReversalId: outcome.reversalId } : {}),\n atMs: Date.now(),\n }\n : {\n disputeId,\n reversedTransferCents: 0,\n failedReason: outcome.reason,\n ...(outcome.owedCents != null ? { owedCents: outcome.owedCents } : {}),\n atMs: Date.now(),\n }\n if (outcome.kind === 'not-reversed') {\n console.error('Booking seller share NOT reversed — recorded on the booking', {\n bookingId: bookingRef.id,\n disputeId,\n reason: outcome.reason,\n })\n }\n const wrote = await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n if (!fresh.exists) return false\n const current = fresh.get('disputeReversal') as BookingDisputeReversal | undefined\n if (current?.disputeId === disputeId) return false\n transaction.set(bookingRef, { disputeReversal: record }, { merge: true })\n return true\n })\n return {\n cents: wrote && outcome.kind === 'reversed' ? outcome.cents : 0,\n settled: outcome.kind === 'reversed' ? 'reversed' : 'failed',\n }\n}\n\nexport const bookingsBillingWebhookHandler: BillingWebhookHandler = async ({\n type,\n object,\n}) => {\n // Fraud signals on a paid booking (AGL-3360): an issuer's early fraud\n // warning, a Radar review, or a dispute. Booking deposits never heard\n // about any of them, so the merchant learned of a chargeback from Stripe\n // alone. The signal now lands on the BOOKING, through the shared\n // `paymentRisk` shape every plugin stamps, and the site's managers are\n // told once. Nothing is refunded or canceled: the merchant decides.\n const risk = paymentRiskEventFrom(type, object)\n if (risk) {\n const booking = await findBookingForPayment(risk.paymentIntentId)\n if (!booking) return\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n await recordPaymentRiskOnRecord(\n {\n ref: booking.ref,\n signal: risk.signal,\n hostId,\n subjectLabel: `the booking for ${String(booking.get('serviceName') ?? booking.id)}`,\n link: `/${hostId}/bookings`,\n notificationType: 'content.booking',\n amount: Number.isFinite(Number(booking.get('paidAmountCents')))\n ? `$${(Number(booking.get('paidAmountCents')) / 100).toFixed(2)}`\n : null,\n evidenceDueByMs:\n Number((object as { evidence_details?: { due_by?: unknown } })?.evidence_details?.due_by ?? 0) * 1000 || null,\n },\n { firestore: firebaseAdmin.app().firestore(), notifyRisk: notifyRiskEvent },\n )\n return { claimed: true, hostId }\n }\n // A dispute's outcome, on the signal `created` stamped. A LOST one pulls\n // the merchant's share back from the connected account (AGL-3363), through\n // the same seam a lost store order uses, so the platform no longer absorbs\n // a booking chargeback. Claimed when the share came back; a reversal that\n // could not be made stays unclaimed, so the route's unattributed-dispute\n // alert still tells staff about money nothing recovered.\n if (type === 'charge.dispute.closed') {\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const booking = await findBookingForPayment(paymentIntentId)\n if (!booking) return\n const outcome = String(object?.status ?? '')\n await settlePaymentRiskDisputeOnRecord(\n booking.ref,\n String(object?.id ?? ''),\n outcome,\n { firestore: firebaseAdmin.app().firestore() },\n )\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n if (outcome !== 'lost') return { claimed: true, hostId }\n const recovered = await reverseBookingSellerShare(booking.ref, object)\n if (recovered.cents > 0 && hostId) {\n await notifyHostManagers(hostId, {\n type: 'content.booking',\n title: `Payout adjusted — $${(recovered.cents / 100).toFixed(2)} recovered for a lost chargeback`,\n body:\n `A booking deposit was charged back and the dispute was lost, so the amount ` +\n `transferred to you for it has been reversed. If your balance does not cover ` +\n `it, Stripe recovers the remainder from your future payouts.`,\n link: `/${hostId}/bookings`,\n })\n }\n return recovered.settled === 'reversed' ? { claimed: true, hostId } : undefined\n }\n // Paid bookings (AGL-170): payment confirms the pendingPayment hold.\n if (\n type === 'checkout.session.completed' &&\n object?.metadata?.type === 'booking-payment' &&\n object?.payment_status === 'paid'\n ) {\n const { hostId, bookingId } = object.metadata ?? {}\n if (hostId && bookingId) {\n const firestore = firebaseAdmin.app().firestore()\n const bookingRef = firestore\n .collection('hosts')\n .doc(String(hostId))\n .collection('bookings')\n .doc(String(bookingId))\n // WHAT THE CLIENT HANDED OVER, ALL OF IT. Tax included: this is the\n // ceiling `refund.ts` reverses against, and the client paid the tax\n // too — a net figure here would strand part of a refund.\n const paidAmountCents = Math.max(\n 0,\n Math.round(Number(object?.amount_total ?? 0)),\n )\n // THE MERCHANT'S SERVICE TAX, SEPARATED OUT (AGL-2028).\n //\n // `server.ts` charges the merchant's own service rate as an ordinary\n // `line_items[1]` Stripe is never told is tax (the AGL-1711\n // construction, which is what keeps the figure the MERCHANT's rather\n // than something computed against Aglyn's registrations). So\n // `amount_total` is service-plus-tax while Stripe's own tax fields\n // read zero, and the session's metadata is the only witness — exactly\n // as it is for a buy-now sale.\n const taxCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.taxCents ?? 0)),\n )\n // The merchant's REVENUE, which is the charge less the tax. Used for\n // the contact's lifetime value below: tax is collected on behalf of\n // an authority and is not money the business earned, so counting it\n // would over-state every service client's worth.\n const serviceCents = Math.max(0, paidAmountCents - taxCents)\n // WHAT A REFUND WILL NEED (AGL-2315). A paid booking is now a\n // destination charge to the merchant's connected account, and\n // reversing one requires the PaymentIntent — which lives only on this\n // event. The booking document recorded `paidAmountCents` and nothing\n // that identifies the charge, so a refund had no handle to pull and\n // the information was gone the moment the webhook returned. Unlike\n // most gaps this one cannot be backfilled from our own data later:\n // every booking taken before this line landed can only be refunded by\n // hand in the Stripe dashboard.\n //\n // `feeCents` is Aglyn's cut as CHARGED, read back off the session's\n // own metadata rather than re-derived from the org at refund time. The\n // rate follows the plan (AGL-2289's rule) and the plan moves, so\n // re-resolving it during a refund would reverse a share that was never\n // taken. `'0'` is a real recorded answer on the 0%-rate tiers.\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const chargedFeeCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.feeCents ?? 0)),\n )\n // Redelivery guard (AGL-1755), the AGL-1748 shape. This was an\n // unconditional merge-set with no status check at all — idempotent\n // only by accident, because every value it wrote was fixed. A\n // redelivery re-sent the guest's confirmation and re-metered it, and\n // the moment this handler carries money to a contact the accident stops\n // holding: `purchaseCents` is a `FieldValue.increment`, so every retry\n // would inflate the customer's lifetime value.\n //\n // Keyed on the STATUS, not on the document existing: `server.ts` writes\n // the booking as `pendingPayment` BEFORE it opens the Stripe session,\n // so existence is guaranteed by the time any event arrives and proves\n // nothing — the AGL-1748 reasoning, not AGL-1732's `checkoutSessionId`\n // key, which existed because a sibling event wrote the same path.\n //\n // The key is \"not yet confirmed\" rather than \"is pendingPayment\" on\n // purpose. The lapsed-hold sweeper in `server.ts` cancels a\n // `pendingPayment` booking after 24h, and refusing a payment that\n // landed anyway would take the money and record nothing; `confirmed` is\n // reachable for a PAID booking only by this handler having already run,\n // so it is an exact \"already processed\" test. The existence check is\n // new and deliberate: the old merge-set would CREATE a stub booking\n // from a metadata `bookingId` that pointed at nothing.\n let booking: Record<string, any> = {}\n const confirmedNow = await firestore.runTransaction(\n async (transaction) => {\n const snapshot = await transaction.get(bookingRef)\n if (!snapshot.exists) return false\n if (snapshot.get('status') === 'confirmed') return false\n // \"Already processed\" is WIDER than `confirmed` once money can\n // flow back out (AGL-2315). A refunded booking is moved off\n // `confirmed`, so a redelivery arriving afterwards would otherwise\n // read as unprocessed and re-confirm an appointment the merchant\n // has already cancelled and refunded — re-sending the guest a\n // confirmation for it and re-metering the email. Any evidence this\n // handler has run before is the real test, and a refund counter or\n // a recorded PaymentIntent is exactly that evidence.\n if (\n Number(snapshot.get('refundedCents') ?? 0) > 0 ||\n snapshot.get('paymentIntentId')\n ) {\n return false\n }\n booking = (snapshot.data() as any) ?? {}\n transaction.set(\n bookingRef,\n {\n status: 'confirmed',\n paidAmountCents,\n // WHICH TAX REGIME THIS BOOKING CARRIED (AGL-2028), on the\n // document the merchant reads — the stamp every other\n // storefront money door already carries (AGL-2451).\n //\n // DERIVED from the one shared derivation, never a constant.\n // A hand-written \"manual when the metadata says so\" would be\n // a second rule that can drift from the `storefrontTaxCollected`\n // row filed for the same Stripe id, which is the exact\n // disagreement AGL-2451 exists to prevent.\n //\n // TWO-ARGUMENT, because the manual line makes Stripe report\n // `total_details.amount_tax: 0` on a booking that really did\n // charge the client tax; the one-argument form would stamp\n // `none` on precisely those. `absent` remains a fourth state\n // meaning \"recorded before this shipped\".\n taxMode: pluginTaxProfile().taxModeOf(object, taxCents),\n // The figure itself. Absent rather than a defaulted `0` — a\n // zero written through `merge` is the AGL-1758 shape, and\n // this handler can re-enter (see the widened guard above).\n ...(taxCents > 0 ? { taxCents } : {}),\n // The refund handles (AGL-2315). Written inside the same\n // transaction as the status, so a booking can never read\n // `confirmed` while the means to refund it are missing.\n ...(paymentIntentId ? { paymentIntentId } : {}),\n feeCents: chargedFeeCents,\n // WHICH CHECKOUT PAID FOR THIS (AGL-2481). The guest's browser\n // comes back from Stripe holding a session id and nothing\n // else — a booking id was never in the return URL — so this is\n // what lets `booking-analytics.ts` answer \"what did I just\n // buy?\" for the merchant-side `purchase`, and it is written\n // here because the session id first exists on this event.\n //\n // Inside the transaction with the status on purpose: the\n // lookup refuses anything that is not `confirmed`, so a\n // booking can never be findable by session id while reading as\n // unpaid.\n ...(object?.id ? { checkoutSessionId: String(object.id) } : {}),\n // NOTE the absent `refundedCents: 0`. Seeding it here would be\n // the AGL-1758 shape: a defaulted field written through\n // `merge` destroying the real one. This handler can re-enter\n // after a refund has already accumulated a counter (see the\n // widened guard above), and a zero written back over it would\n // re-open the full amount for refunding a second time. Absent\n // IS zero — every reader coerces with `?? 0`.\n expiresAtMs: firebaseAdmin.firestore.FieldValue.delete(),\n confirmedAt:\n firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n 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 captureHostContact({\n hostId: String(hostId),\n email: booking['email'],\n ...(booking['name'] ? { name: String(booking['name']) } : {}),\n source: 'booking',\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 initialLifecycleStage: '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 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 // 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 when = new Date(\n Number(booking['startsAtMs']),\n ).toLocaleString('en-US', {\n dateStyle: 'full',\n timeStyle: 'short',\n })\n const fallbackText =\n `Hi ${booking['name'] ?? ''},\\n\\nPayment received — ` +\n `\"${booking['serviceName'] ?? 'your booking'}\" is ` +\n `confirmed for ${when}.\\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: String(booking['timezone'] ?? ''),\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","captureHostContact","bookingPlatformNetCents","shouldSendBookingPlatformPurchase","sendEmail","pluginTaxProfile","fileBookingOnCrm","GRPC_FAILED_PRECONDITION","findBookingForPayment","paymentIntentId","matches","app","firestore","collectionGroup","where","limit","get","catch","error","code","console","docs","length","reverseBookingSellerShare","bookingRef","dispute","disputeId","String","id","amountCents","Math","max","round","Number","amount","cents","settled","prior","failedReason","outcome","kind","chargeId","charge","metadata","bookingId","record","reversedTransferCents","reversalId","transferReversalId","atMs","Date","now","reason","owedCents","wrote","runTransaction","transaction","fresh","exists","current","set","disputeReversal","merge","bookingsBillingWebhookHandler","type","object","risk","booking","hostId","ref","parent","signal","subjectLabel","link","notificationType","isFinite","toFixed","evidenceDueByMs","evidence_details","due_by","notifyRisk","claimed","payment_intent","status","recovered","title","body","undefined","payment_status","collection","doc","paidAmountCents","amount_total","taxCents","serviceCents","chargedFeeCents","feeCents","confirmedNow","snapshot","data","taxMode","taxModeOf","checkoutSessionId","expiresAtMs","FieldValue","delete","confirmedAt","serverTimestamp","netCents","transactionId","value","currency","items","item_id","item_name","item_category","price","quantity","clientId","ga_client_id","stripeCustomerId","customer","customer_details","email","name","source","initialLifecycleStage","purchaseCents","interaction","refId","summary","slice","when","toLocaleString","dateStyle","timeStyle","fallbackText","designed","timezone","branding","org","to","subject","text","html","fromName","sendingIdentity","audience","context","owedFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,8EAA8E;AAC9E,4EAA4E;AAC5E,oDAAoD;AACpD,SAASA,KAAK,QAAQ,cAAa;AAGnC,SAASC,sBAAsB,QAAQ,sBAAqB;AAC5D,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,kBAAkB,EAClBC,eAAe,EACfC,yBAAyB,EACzBC,eAAe,QACV,2BAA0B;AACjC,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SACEC,yBAAyB,EACzBC,gCAAgC,QAC3B,sDAAqD;AAC5D,SACEC,0BAA0B,QAErB,2DAA0D;AACjE,SAASC,kBAAkB,QAAQ,wBAAuB;AAC1D,SACEC,uBAAuB,EACvBC,iCAAiC,QAC5B,yCAAqC;AAC5C,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,g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C,cAAc,YAAtBA,wBAA0B,IAAI;oBACtD4E,MAAMN,CAAAA,4BAAAA,SAAUM,IAAI,KAAIP;mBACpBC,CAAAA,4BAAAA,SAAUO,IAAI,IAAG;oBAAEA,MAAMP,SAASO,IAAI;gBAAC,IAAI,CAAC;oBAChDC,UAAUN,SAASM,QAAQ;oBAC3BC,iBAAiB,MAAM3J,oBAAoBoC,OAAOyC;oBAClD+E,UAAU;oBACVC,SAAS;oBACT,2DAA2D;oBAC3D,gDAAgD;oBAChDC,SAAS;;gBAEX,yDAAyD;gBACzD,6CAA6C;gBAC7C,MAAM7J,eAAemC,OAAOyC;YAC9B;QACF;IACF;AACJ,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/billing-webhook.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// `after()`, never a bare `void promise` (AGL-2327). This handler runs inside\n// the console's `/api/billing/webhook` invocation, which AGL-1133 measured on\n// production is frozen the moment the response is sent — so fire-and-forget\n// work scheduled any other way simply does not run.\nimport { after } from 'next/server'\n\nimport type { BillingWebhookHandler } from '@aglyn/aglyn/server'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n notifyHostManagers,\n notifyRiskEvent,\n renderHostEmailWithTokens,\n sendGa4Purchase,\n} from '@aglyn/tenant-data-admin'\nimport { paymentRiskEventFrom } from '@aglyn/aglyn/app-utils/payment-risk'\nimport {\n recordPaymentRiskOnRecord,\n settlePaymentRiskDisputeOnRecord,\n} from '@aglyn/tenant-data-admin/server/payment-risk-record'\nimport {\n reverseDestinationTransfer,\n type TransferReversalFailure,\n} from '@aglyn/tenant-data-admin/server/stripe-transfer-reversal'\nimport { captureHostContact } from '@aglyn/tenant-runtime'\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 { bookingTimeZoneFor } from './booking-time-zone'\nimport { formatBookingWhen } from '../model/booking-time'\n\n/**\n * Paid-booking section of the platform Stripe webhook (AGL-170/418):\n * payment confirms the pendingPayment hold — relocated verbatim from the\n * console route; registered via registerBookingsConsoleApi.\n */\n/** gRPC `Status.FAILED_PRECONDITION` — Firestore's \"this query needs an index\". */\nconst GRPC_FAILED_PRECONDITION = 9\n\n/**\n * The booking a charge paid for, found by the `paymentIntentId` the paid\n * handler below records (AGL-2315), or null. A missing collection-group\n * index is logged and answered null rather than thrown: no redelivery can\n * fix it, and the dispute then reaches staff through the route's\n * unattributed-dispute alert instead of vanishing.\n */\nasync function findBookingForPayment(\n paymentIntentId: string,\n): Promise<FirebaseFirestore.QueryDocumentSnapshot | null> {\n if (!paymentIntentId) return null\n const matches = await firebaseAdmin\n .app()\n .firestore()\n .collectionGroup('bookings')\n .where('paymentIntentId', '==', paymentIntentId)\n .limit(2)\n .get()\n .catch((error: { code?: number }) => {\n if (error?.code !== GRPC_FAILED_PRECONDITION) throw error\n console.error(\n 'Booking payment lookup needs the collection-group index on ' +\n 'bookings.paymentIntentId (AGL-3360)',\n error,\n )\n return null\n })\n // One payment intent pays one booking; two is corrupt data, and stamping\n // an arbitrary one would tell the wrong merchant.\n return matches && matches.docs.length === 1 ? matches.docs[0] : null\n}\n\n/** What a booking records once its lost dispute's reversal is settled. */\ninterface BookingDisputeReversal {\n disputeId: string\n reversedTransferCents: number\n transferReversalId?: string\n /** Why nothing was pulled back, when nothing was. */\n failedReason?: TransferReversalFailure\n owedCents?: number\n atMs: number\n}\n\n/**\n * The merchant's share of a LOST booking dispute, pulled back from the\n * connected account (AGL-3363), by the AGL-1794 policy a store order follows:\n * the Stripe half is the shared `reverseDestinationTransfer`, this is only\n * the booking's own record.\n *\n * IDEMPOTENT BY THE BOOKING: `disputeReversal` for this dispute, present,\n * means settled and a redelivery returns before any Stripe call. A delivery\n * that died after the POST is healed by the seam adopting the reversal the\n * transfer already carries. A transient Stripe failure THROWS (the seam\n * does), leaving the marker unset so Stripe's redelivery retries it. A final\n * failure is settled with its reason and the owed amount, so it is findable.\n *\n * `cents` is non-zero only for the delivery that wrote the reversal, which\n * is the one that tells the merchant.\n */\nasync function reverseBookingSellerShare(\n bookingRef: FirebaseFirestore.DocumentReference,\n dispute: any,\n): Promise<{ cents: number; settled: 'reversed' | 'failed' | 'pending' }> {\n const disputeId = String(dispute?.id ?? '')\n const amountCents = Math.max(0, Math.round(Number(dispute?.amount ?? 0)))\n if (!disputeId || !(amountCents > 0)) return { cents: 0, settled: 'failed' }\n const firestore = firebaseAdmin.app().firestore()\n const prior = (await bookingRef.get()).get('disputeReversal') as\n | BookingDisputeReversal\n | undefined\n if (prior?.disputeId === disputeId) {\n return { cents: 0, settled: prior.failedReason ? 'failed' : 'reversed' }\n }\n const outcome = await reverseDestinationTransfer({\n kind: 'dispute',\n id: disputeId,\n amountCents,\n chargeId:\n typeof dispute?.charge === 'string' ? dispute.charge : String(dispute?.charge?.id ?? ''),\n metadata: { bookingId: bookingRef.id },\n })\n if (outcome.kind === 'skipped') {\n console.error('Booking transfer reversal skipped: STRIPE_SECRET_KEY is not set (AGL-3363)')\n return { cents: 0, settled: 'pending' }\n }\n const record: BookingDisputeReversal =\n outcome.kind === 'reversed'\n ? {\n disputeId,\n reversedTransferCents: outcome.cents,\n ...(outcome.reversalId ? { transferReversalId: outcome.reversalId } : {}),\n atMs: Date.now(),\n }\n : {\n disputeId,\n reversedTransferCents: 0,\n failedReason: outcome.reason,\n ...(outcome.owedCents != null ? { owedCents: outcome.owedCents } : {}),\n atMs: Date.now(),\n }\n if (outcome.kind === 'not-reversed') {\n console.error('Booking seller share NOT reversed — recorded on the booking', {\n bookingId: bookingRef.id,\n disputeId,\n reason: outcome.reason,\n })\n }\n const wrote = await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n if (!fresh.exists) return false\n const current = fresh.get('disputeReversal') as BookingDisputeReversal | undefined\n if (current?.disputeId === disputeId) return false\n transaction.set(bookingRef, { disputeReversal: record }, { merge: true })\n return true\n })\n return {\n cents: wrote && outcome.kind === 'reversed' ? outcome.cents : 0,\n settled: outcome.kind === 'reversed' ? 'reversed' : 'failed',\n }\n}\n\nexport const bookingsBillingWebhookHandler: BillingWebhookHandler = async ({\n type,\n object,\n}) => {\n // Fraud signals on a paid booking (AGL-3360): an issuer's early fraud\n // warning, a Radar review, or a dispute. Booking deposits never heard\n // about any of them, so the merchant learned of a chargeback from Stripe\n // alone. The signal now lands on the BOOKING, through the shared\n // `paymentRisk` shape every plugin stamps, and the site's managers are\n // told once. Nothing is refunded or canceled: the merchant decides.\n const risk = paymentRiskEventFrom(type, object)\n if (risk) {\n const booking = await findBookingForPayment(risk.paymentIntentId)\n if (!booking) return\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n await recordPaymentRiskOnRecord(\n {\n ref: booking.ref,\n signal: risk.signal,\n hostId,\n subjectLabel: `the booking for ${String(booking.get('serviceName') ?? booking.id)}`,\n link: `/${hostId}/bookings`,\n notificationType: 'content.booking',\n amount: Number.isFinite(Number(booking.get('paidAmountCents')))\n ? `$${(Number(booking.get('paidAmountCents')) / 100).toFixed(2)}`\n : null,\n evidenceDueByMs:\n Number((object as { evidence_details?: { due_by?: unknown } })?.evidence_details?.due_by ?? 0) * 1000 || null,\n },\n { firestore: firebaseAdmin.app().firestore(), notifyRisk: notifyRiskEvent },\n )\n return { claimed: true, hostId }\n }\n // A dispute's outcome, on the signal `created` stamped. A LOST one pulls\n // the merchant's share back from the connected account (AGL-3363), through\n // the same seam a lost store order uses, so the platform no longer absorbs\n // a booking chargeback. Claimed when the share came back; a reversal that\n // could not be made stays unclaimed, so the route's unattributed-dispute\n // alert still tells staff about money nothing recovered.\n if (type === 'charge.dispute.closed') {\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const booking = await findBookingForPayment(paymentIntentId)\n if (!booking) return\n const outcome = String(object?.status ?? '')\n await settlePaymentRiskDisputeOnRecord(\n booking.ref,\n String(object?.id ?? ''),\n outcome,\n { firestore: firebaseAdmin.app().firestore() },\n )\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n if (outcome !== 'lost') return { claimed: true, hostId }\n const recovered = await reverseBookingSellerShare(booking.ref, object)\n if (recovered.cents > 0 && hostId) {\n const recoveredText = `$${(recovered.cents / 100).toFixed(2)}`\n const guest = String(booking.get('name') ?? '').trim()\n const service = String(booking.get('serviceName') ?? '').trim() || 'a service'\n await notifyHostManagers(hostId, {\n type: 'content.booking',\n title: `Payout adjusted — ${recoveredText} recovered for a lost chargeback`,\n body:\n `${guest ? `${guest}'s payment` : 'A payment'} for ${service} on ` +\n `{site} was charged back and the dispute was lost, so ` +\n `the ${recoveredText} transferred to you for it has been taken back. ` +\n `If your balance does not cover it, Stripe recovers the rest from ` +\n `your future payouts.`,\n link: `/${hostId}/bookings`,\n })\n }\n return recovered.settled === 'reversed' ? { claimed: true, hostId } : undefined\n }\n // Paid bookings (AGL-170): payment confirms the pendingPayment hold.\n if (\n type === 'checkout.session.completed' &&\n object?.metadata?.type === 'booking-payment' &&\n object?.payment_status === 'paid'\n ) {\n const { hostId, bookingId } = object.metadata ?? {}\n if (hostId && bookingId) {\n const firestore = firebaseAdmin.app().firestore()\n const bookingRef = firestore\n .collection('hosts')\n .doc(String(hostId))\n .collection('bookings')\n .doc(String(bookingId))\n // WHAT THE CLIENT HANDED OVER, ALL OF IT. Tax included: this is the\n // ceiling `refund.ts` reverses against, and the client paid the tax\n // too — a net figure here would strand part of a refund.\n const paidAmountCents = Math.max(\n 0,\n Math.round(Number(object?.amount_total ?? 0)),\n )\n // THE MERCHANT'S SERVICE TAX, SEPARATED OUT (AGL-2028).\n //\n // `server.ts` charges the merchant's own service rate as an ordinary\n // `line_items[1]` Stripe is never told is tax (the AGL-1711\n // construction, which is what keeps the figure the MERCHANT's rather\n // than something computed against Aglyn's registrations). So\n // `amount_total` is service-plus-tax while Stripe's own tax fields\n // read zero, and the session's metadata is the only witness — exactly\n // as it is for a buy-now sale.\n const taxCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.taxCents ?? 0)),\n )\n // The merchant's REVENUE, which is the charge less the tax. Used for\n // the contact's lifetime value below: tax is collected on behalf of\n // an authority and is not money the business earned, so counting it\n // would over-state every service client's worth.\n const serviceCents = Math.max(0, paidAmountCents - taxCents)\n // WHAT A REFUND WILL NEED (AGL-2315). A paid booking is now a\n // destination charge to the merchant's connected account, and\n // reversing one requires the PaymentIntent — which lives only on this\n // event. The booking document recorded `paidAmountCents` and nothing\n // that identifies the charge, so a refund had no handle to pull and\n // the information was gone the moment the webhook returned. Unlike\n // most gaps this one cannot be backfilled from our own data later:\n // every booking taken before this line landed can only be refunded by\n // hand in the Stripe dashboard.\n //\n // `feeCents` is Aglyn's cut as CHARGED, read back off the session's\n // own metadata rather than re-derived from the org at refund time. The\n // rate follows the plan (AGL-2289's rule) and the plan moves, so\n // re-resolving it during a refund would reverse a share that was never\n // taken. `'0'` is a real recorded answer on the 0%-rate tiers.\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const chargedFeeCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.feeCents ?? 0)),\n )\n // Redelivery guard (AGL-1755), the AGL-1748 shape. This was an\n // unconditional merge-set with no status check at all — idempotent\n // only by accident, because every value it wrote was fixed. A\n // redelivery re-sent the guest's confirmation and re-metered it, and\n // the moment this handler carries money to a contact the accident stops\n // holding: `purchaseCents` is a `FieldValue.increment`, so every retry\n // would inflate the customer's lifetime value.\n //\n // Keyed on the STATUS, not on the document existing: `server.ts` writes\n // the booking as `pendingPayment` BEFORE it opens the Stripe session,\n // so existence is guaranteed by the time any event arrives and proves\n // nothing — the AGL-1748 reasoning, not AGL-1732's `checkoutSessionId`\n // key, which existed because a sibling event wrote the same path.\n //\n // The key is \"not yet confirmed\" rather than \"is pendingPayment\" on\n // purpose. The lapsed-hold sweeper in `server.ts` cancels a\n // `pendingPayment` booking after 24h, and refusing a payment that\n // landed anyway would take the money and record nothing; `confirmed` is\n // reachable for a PAID booking only by this handler having already run,\n // so it is an exact \"already processed\" test. The existence check is\n // new and deliberate: the old merge-set would CREATE a stub booking\n // from a metadata `bookingId` that pointed at nothing.\n let booking: Record<string, any> = {}\n const confirmedNow = await firestore.runTransaction(\n async (transaction) => {\n const snapshot = await transaction.get(bookingRef)\n if (!snapshot.exists) return false\n if (snapshot.get('status') === 'confirmed') return false\n // \"Already processed\" is WIDER than `confirmed` once money can\n // flow back out (AGL-2315). A refunded booking is moved off\n // `confirmed`, so a redelivery arriving afterwards would otherwise\n // read as unprocessed and re-confirm an appointment the merchant\n // has already cancelled and refunded — re-sending the guest a\n // confirmation for it and re-metering the email. Any evidence this\n // handler has run before is the real test, and a refund counter or\n // a recorded PaymentIntent is exactly that evidence.\n if (\n Number(snapshot.get('refundedCents') ?? 0) > 0 ||\n snapshot.get('paymentIntentId')\n ) {\n return false\n }\n booking = (snapshot.data() as any) ?? {}\n transaction.set(\n bookingRef,\n {\n status: 'confirmed',\n paidAmountCents,\n // WHICH TAX REGIME THIS BOOKING CARRIED (AGL-2028), on the\n // document the merchant reads — the stamp every other\n // storefront money door already carries (AGL-2451).\n //\n // DERIVED from the one shared derivation, never a constant.\n // A hand-written \"manual when the metadata says so\" would be\n // a second rule that can drift from the `storefrontTaxCollected`\n // row filed for the same Stripe id, which is the exact\n // disagreement AGL-2451 exists to prevent.\n //\n // TWO-ARGUMENT, because the manual line makes Stripe report\n // `total_details.amount_tax: 0` on a booking that really did\n // charge the client tax; the one-argument form would stamp\n // `none` on precisely those. `absent` remains a fourth state\n // meaning \"recorded before this shipped\".\n taxMode: pluginTaxProfile().taxModeOf(object, taxCents),\n // The figure itself. Absent rather than a defaulted `0` — a\n // zero written through `merge` is the AGL-1758 shape, and\n // this handler can re-enter (see the widened guard above).\n ...(taxCents > 0 ? { taxCents } : {}),\n // The refund handles (AGL-2315). Written inside the same\n // transaction as the status, so a booking can never read\n // `confirmed` while the means to refund it are missing.\n ...(paymentIntentId ? { paymentIntentId } : {}),\n feeCents: chargedFeeCents,\n // WHICH CHECKOUT PAID FOR THIS (AGL-2481). The guest's browser\n // comes back from Stripe holding a session id and nothing\n // else — a booking id was never in the return URL — so this is\n // what lets `booking-analytics.ts` answer \"what did I just\n // buy?\" for the merchant-side `purchase`, and it is written\n // here because the session id first exists on this event.\n //\n // Inside the transaction with the status on purpose: the\n // lookup refuses anything that is not `confirmed`, so a\n // booking can never be findable by session id while reading as\n // unpaid.\n ...(object?.id ? { checkoutSessionId: String(object.id) } : {}),\n // NOTE the absent `refundedCents: 0`. Seeding it here would be\n // the AGL-1758 shape: a defaulted field written through\n // `merge` destroying the real one. This handler can re-enter\n // after a refund has already accumulated a counter (see the\n // widened guard above), and a zero written back over it would\n // re-open the full amount for refunding a second time. Absent\n // IS zero — every reader coerces with `?? 0`.\n expiresAtMs: firebaseAdmin.firestore.FieldValue.delete(),\n confirmedAt:\n firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n 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 captureHostContact({\n hostId: String(hostId),\n email: booking['email'],\n ...(booking['name'] ? { name: String(booking['name']) } : {}),\n source: 'booking',\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 initialLifecycleStage: '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 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 // Confirmation email now that payment cleared (env-gated inside\n // sendEmail, which no-ops when Resend isn't configured).\n if (booking['email']) {\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 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","captureHostContact","bookingPlatformNetCents","shouldSendBookingPlatformPurchase","sendEmail","pluginTaxProfile","fileBookingOnCrm","bookingTimeZoneFor","formatBookingWhen","GRPC_FAILED_PRECONDITION","findBookingForPayment","paymentIntentId","matches","app","firestore","collectionGroup","where","limit","get","catch","error","code","console","docs","length","reverseBookingSellerShare","bookingRef","dispute","disputeId","String","id","amountCents","Math","max","round","Number","amount","cents","settled","prior","failedReason","outcome","kind","chargeId","charge","metadata","bookingId","record","reversedTransferCents","reversalId","transferReversalId","atMs","Date","now","reason","owedCents","wrote","runTransaction","transaction","fresh","exists","current","set","disputeReversal","merge","bookingsBillingWebhookHandler","type","object","risk","booking","hostId","ref","parent","signal","subjectLabel","link","notificationType","isFinite","toFixed","evidenceDueByMs","evidence_details","due_by","notifyRisk","claimed","payment_intent","status","recovered","recoveredText","guest","trim","service","title","body","undefined","payment_status","collection","doc","paidAmountCents","amount_total","taxCents","serviceCents","chargedFeeCents","feeCents","confirmedNow","snapshot","data","taxMode","taxModeOf","checkoutSessionId","expiresAtMs","FieldValue","delete","confirmedAt","serverTimestamp","netCents","transactionId","value","currency","items","item_id","item_name","item_category","price","quantity","clientId","ga_client_id","stripeCustomerId","customer","customer_details","email","name","source","initialLifecycleStage","purchaseCents","interaction","refId","summary","slice","timezone","when","paid","fallbackText","designed","branding","org","to","subject","text","html","fromName","sendingIdentity","audience","context","owedFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,8EAA8E;AAC9E,4EAA4E;AAC5E,oDAAoD;AACpD,SAASA,KAAK,QAAQ,cAAa;AAGnC,SAASC,sBAAsB,QAAQ,sBAAqB;AAC5D,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,kBAAkB,EAClBC,eAAe,EACfC,yBAAyB,EACzBC,eAAe,QACV,2BAA0B;AACjC,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SACEC,yBAAyB,EACzBC,gCAAgC,QAC3B,sDAAqD;AAC5D,SACEC,0BAA0B,QAErB,2DAA0D;AACjE,SAASC,kBAAkB,QAAQ,wBAAuB;AAC1D,SACEC,uBAAuB,EACvBC,iCAAiC,QAC5B,yCAAqC;AAC5C,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,gBAAgB,QAAQ,iDAAgD;AACjF,SAASC,gBAAgB,QAAQ,mBAAe;AAChD,SAASC,kBAAkB,QAAQ,yBAAqB;AACxD,SAASC,iBAAiB,QAAQ,2BAAuB;AAEzD;;;;CAIC,GACD,iFAAiF,GACjF,MAAMC,2BAA2B;AAEjC;;;;;;CAMC,GACD,eAAeC,sBACbC,eAAuB;IAEvB,IAAI,CAACA,iBAAiB,OAAO;IAC7B,MAAMC,UAAU,MAAMvB,cACnBwB,GAAG,GACHC,SAAS,GACTC,eAAe,CAAC,YA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Ae/G,OAAOiB;gBACxB;gBAEF,kEAAkE;gBAClE,qEAAqE;gBACrE,MAAMiG,WAAW3J,wBACd,QAAA,MAAME,cAAcuC,OAAOyC,SAASnD,KAAK,CAAC,IAAM,0BAAjD,AAAC,MAAwD6H,GAAG;gBAE9D,MAAM5I,UAAU;oBACd6I,IAAIpH,OAAOwC,OAAO,CAAC,QAAQ;oBAC3B6E,OAAO,YACLJ,4BAAAA,SAAUI,OAAO,qBACjB,CAAC,mBAAmB,GAAE7E,wBAAAA,OAAO,CAAC,cAAc,YAAtBA,wBAA0B,IAAI;oBACtD8E,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,MAAM/J,oBAAoBsC,OAAOyC;oBAClDiF,UAAU;oBACVC,SAAS;oBACT,2DAA2D;oBAC3D,gDAAgD;oBAChDC,SAAS;;gBAEX,yDAAyD;gBACzD,6CAA6C;gBAC7C,MAAMjK,eAAeqC,OAAOyC;YAC9B;QACF;IACF;AACJ,EAAC"}
|
|
@@ -1,33 +1,49 @@
|
|
|
1
|
-
|
|
2
|
-
* @license
|
|
3
|
-
* Copyright 2026 Aglyn LLC
|
|
4
|
-
*
|
|
5
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
-
* you may not use this file except in compliance with the License.
|
|
7
|
-
* You may obtain a copy of the License at
|
|
8
|
-
*
|
|
9
|
-
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
-
*
|
|
11
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
-
* See the License for the specific language governing permissions and
|
|
15
|
-
* limitations under the License.
|
|
16
|
-
*/
|
|
17
|
-
import { type CrmBookingRecordOutcome } from '@aglyn/tenant-data-admin/server/crm-booking-activity';
|
|
1
|
+
import { type PluginRecordWrite } from '@aglyn/aglyn/plugin-manager/plugin-record-timeline';
|
|
18
2
|
import type { HostBookingService } from '../model';
|
|
3
|
+
/** What became of a booking's filing on the workspace's records. */
|
|
4
|
+
export type BookingRecordOutcome = {
|
|
5
|
+
filed: false;
|
|
6
|
+
reason:
|
|
7
|
+
/** No plugin keeps records for this workspace. */
|
|
8
|
+
'no-record-system'
|
|
9
|
+
/** The plugin that keeps records does not run on this site. */
|
|
10
|
+
| 'record-system-off'
|
|
11
|
+
/** The service asks for neither a meeting nor a follow-up. */
|
|
12
|
+
| 'nothing-to-file'
|
|
13
|
+
/** A read threw before anything was asked; logged. */
|
|
14
|
+
| 'failed';
|
|
15
|
+
} | {
|
|
16
|
+
filed: true;
|
|
17
|
+
/** The record system's answer for the meeting, or `null` when none was asked for. */
|
|
18
|
+
meeting: PluginRecordWrite | null;
|
|
19
|
+
/** Its answer for the follow-up, or `null` when the service asks for none. */
|
|
20
|
+
followUp: PluginRecordWrite | null;
|
|
21
|
+
};
|
|
19
22
|
/**
|
|
20
|
-
* THE BOOKING'S WAY BACK TO THE
|
|
23
|
+
* THE BOOKING'S WAY BACK TO THE RECORD IT CAME FROM (AGL-2660).
|
|
21
24
|
*
|
|
22
25
|
* Two doors write a confirmed booking: the create route, for a free
|
|
23
26
|
* service, and the payment webhook, for a paid one once the charge clears.
|
|
24
27
|
* Both call this with what they hold — the row as written and, when they
|
|
25
|
-
* already read it, the service — and it
|
|
26
|
-
* the
|
|
28
|
+
* already read it, the service — and it files what the service asks for on
|
|
29
|
+
* the workspace's records, through the core's record-timeline seam:
|
|
30
|
+
*
|
|
31
|
+
* - a `meeting` entry at the slot, naming the service and the time in the
|
|
32
|
+
* service's own zone, unless the service switched it off;
|
|
33
|
+
* - a follow-up task one business day after the slot, for whoever holds
|
|
34
|
+
* the record, when the service asks for one.
|
|
35
|
+
*
|
|
36
|
+
* The record is the record system's to find: the one the booking link was
|
|
37
|
+
* dropped from (`crmRef`, carried back as it was handed over), otherwise the
|
|
38
|
+
* person at the booker's address, as this site sees them. Both entries are
|
|
39
|
+
* keyed by the booking, so the webhook's redeliveries and a second door file
|
|
40
|
+
* nothing twice; a full activity log refuses the meeting and still takes the
|
|
41
|
+
* follow-up. Nothing is filed on a site that has switched the record system
|
|
42
|
+
* off, and the record system refuses a plan without it.
|
|
27
43
|
*
|
|
28
|
-
* **Never throws**: the guest has their slot whatever the
|
|
29
|
-
* failure here is an outcome the caller may log, never an error into
|
|
30
|
-
* request or the webhook.
|
|
44
|
+
* **Never throws**: the guest has their slot whatever the record system did,
|
|
45
|
+
* so a failure here is an outcome the caller may log, never an error into
|
|
46
|
+
* the request or the webhook.
|
|
31
47
|
*/
|
|
32
48
|
export declare function fileBookingOnCrm(firestore: FirebaseFirestore.Firestore, input: {
|
|
33
49
|
hostId: string;
|
|
@@ -36,4 +52,4 @@ export declare function fileBookingOnCrm(firestore: FirebaseFirestore.Firestore,
|
|
|
36
52
|
booking: Record<string, unknown>;
|
|
37
53
|
/** The service, when the caller already read it. Read here otherwise. */
|
|
38
54
|
service?: HostBookingService | null;
|
|
39
|
-
}): Promise<
|
|
55
|
+
}): Promise<BookingRecordOutcome>;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
1
2
|
/**
|
|
2
3
|
* @license
|
|
3
4
|
* Copyright 2026 Aglyn LLC
|
|
@@ -13,50 +14,107 @@
|
|
|
13
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
15
|
* See the License for the specific language governing permissions and
|
|
15
16
|
* limitations under the License.
|
|
16
|
-
*/ import {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
import {
|
|
17
|
+
*/ import { isHostPluginEnabled } from "@aglyn/aglyn/plugin-manager/enabled-plugins";
|
|
18
|
+
import { pluginRecordTimelineWriter } from "@aglyn/aglyn/plugin-manager/plugin-record-timeline";
|
|
19
|
+
import { getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
20
|
+
import { BUNDLE_ID } from "../constants/bundle-common.js";
|
|
21
|
+
import { bookingFollowUpDueMs, bookingFollowUpTitle, bookingMeetingBody, parseBookingRecordRef } from "../model/booking-record.js";
|
|
20
22
|
/**
|
|
21
|
-
* THE BOOKING'S WAY BACK TO THE
|
|
23
|
+
* THE BOOKING'S WAY BACK TO THE RECORD IT CAME FROM (AGL-2660).
|
|
22
24
|
*
|
|
23
25
|
* Two doors write a confirmed booking: the create route, for a free
|
|
24
26
|
* service, and the payment webhook, for a paid one once the charge clears.
|
|
25
27
|
* Both call this with what they hold — the row as written and, when they
|
|
26
|
-
* already read it, the service — and it
|
|
27
|
-
* the
|
|
28
|
+
* already read it, the service — and it files what the service asks for on
|
|
29
|
+
* the workspace's records, through the core's record-timeline seam:
|
|
28
30
|
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
31
|
+
* - a `meeting` entry at the slot, naming the service and the time in the
|
|
32
|
+
* service's own zone, unless the service switched it off;
|
|
33
|
+
* - a follow-up task one business day after the slot, for whoever holds
|
|
34
|
+
* the record, when the service asks for one.
|
|
35
|
+
*
|
|
36
|
+
* The record is the record system's to find: the one the booking link was
|
|
37
|
+
* dropped from (`crmRef`, carried back as it was handed over), otherwise the
|
|
38
|
+
* person at the booker's address, as this site sees them. Both entries are
|
|
39
|
+
* keyed by the booking, so the webhook's redeliveries and a second door file
|
|
40
|
+
* nothing twice; a full activity log refuses the meeting and still takes the
|
|
41
|
+
* follow-up. Nothing is filed on a site that has switched the record system
|
|
42
|
+
* off, and the record system refuses a plan without it.
|
|
43
|
+
*
|
|
44
|
+
* **Never throws**: the guest has their slot whatever the record system did,
|
|
45
|
+
* so a failure here is an outcome the caller may log, never an error into
|
|
46
|
+
* the request or the webhook.
|
|
32
47
|
*/ export async function fileBookingOnCrm(firestore, input) {
|
|
33
48
|
const { hostId, bookingId, booking } = input;
|
|
34
49
|
try {
|
|
35
|
-
var _booking_serviceId, _data,
|
|
50
|
+
var _booking_serviceId, _data, _ref, _ref1, _booking_startsAtMs, _booking_endsAtMs, _booking_email;
|
|
51
|
+
const records = pluginRecordTimelineWriter();
|
|
52
|
+
if (!records) return {
|
|
53
|
+
filed: false,
|
|
54
|
+
reason: 'no-record-system'
|
|
55
|
+
};
|
|
36
56
|
const owner = await getOrgForHost(hostId);
|
|
37
57
|
if (!(owner == null ? void 0 : owner.orgId)) return {
|
|
38
58
|
filed: false,
|
|
39
59
|
reason: 'failed'
|
|
40
60
|
};
|
|
61
|
+
const hostRef = firestore.collection('hosts').doc(hostId);
|
|
62
|
+
const host = (await hostRef.get()).data();
|
|
63
|
+
if (!isHostPluginEnabled(owner.org, host != null ? host : null, records.pluginId)) {
|
|
64
|
+
return {
|
|
65
|
+
filed: false,
|
|
66
|
+
reason: 'record-system-off'
|
|
67
|
+
};
|
|
68
|
+
}
|
|
41
69
|
const serviceId = String((_booking_serviceId = booking['serviceId']) != null ? _booking_serviceId : '');
|
|
42
|
-
const service = input.service !== undefined ? input.service : serviceId ? (_data = (await
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
70
|
+
const service = input.service !== undefined ? input.service : serviceId ? (_data = (await hostRef.collection('services').doc(serviceId).get()).data()) != null ? _data : null : null;
|
|
71
|
+
const wantsMeeting = (service == null ? void 0 : service.crmMeetingActivity) !== false;
|
|
72
|
+
const wantsFollowUp = (service == null ? void 0 : service.crmFollowUpTask) === true;
|
|
73
|
+
if (!wantsMeeting && !wantsFollowUp) return {
|
|
74
|
+
filed: false,
|
|
75
|
+
reason: 'nothing-to-file'
|
|
76
|
+
};
|
|
77
|
+
const serviceName = String((_ref = (_ref1 = service == null ? void 0 : service.name) != null ? _ref1 : booking['serviceName']) != null ? _ref : '').trim();
|
|
78
|
+
const timezone = (service == null ? void 0 : service.timezone) || undefined;
|
|
79
|
+
const startsAtMs = Number((_booking_startsAtMs = booking['startsAtMs']) != null ? _booking_startsAtMs : 0);
|
|
80
|
+
const endsAtMs = Number((_booking_endsAtMs = booking['endsAtMs']) != null ? _booking_endsAtMs : 0);
|
|
81
|
+
const context = {
|
|
46
82
|
orgId: owner.orgId,
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
email: String((_booking_email = booking['email']) != null ? _booking_email : ''),
|
|
52
|
-
startsAtMs: Number((_booking_startsAtMs = booking['startsAtMs']) != null ? _booking_startsAtMs : 0),
|
|
53
|
-
endsAtMs: Number((_booking_endsAtMs = booking['endsAtMs']) != null ? _booking_endsAtMs : 0),
|
|
54
|
-
crmRef: typeof booking['crmRef'] === 'string' ? booking['crmRef'] : null
|
|
83
|
+
hostId,
|
|
84
|
+
link: {
|
|
85
|
+
record: parseBookingRecordRef(booking['crmRef']),
|
|
86
|
+
email: String((_booking_email = booking['email']) != null ? _booking_email : '')
|
|
55
87
|
},
|
|
56
|
-
|
|
57
|
-
}
|
|
88
|
+
sourcePluginId: BUNDLE_ID
|
|
89
|
+
};
|
|
90
|
+
const meeting = wantsMeeting ? await records.writer.logActivity(_extends({}, context, {
|
|
91
|
+
kind: 'meeting',
|
|
92
|
+
// When it HAPPENS, which is the slot — not when it was booked.
|
|
93
|
+
atMs: startsAtMs,
|
|
94
|
+
body: bookingMeetingBody({
|
|
95
|
+
serviceName,
|
|
96
|
+
startsAtMs,
|
|
97
|
+
timezone
|
|
98
|
+
}),
|
|
99
|
+
byUid: '',
|
|
100
|
+
dedupeKey: `booking:${bookingId}`
|
|
101
|
+
})) : null;
|
|
102
|
+
const followUp = wantsFollowUp ? await records.writer.createTask(_extends({}, context, {
|
|
103
|
+
dedupeKey: `booking-follow-up:${bookingId}`,
|
|
104
|
+
title: bookingFollowUpTitle(serviceName),
|
|
105
|
+
kind: 'todo',
|
|
106
|
+
dueAtMs: bookingFollowUpDueMs(endsAtMs, timezone),
|
|
107
|
+
// Whoever holds the record the booking lands on.
|
|
108
|
+
assigneeUid: null,
|
|
109
|
+
createdByUid: ''
|
|
110
|
+
})) : null;
|
|
111
|
+
return {
|
|
112
|
+
filed: true,
|
|
113
|
+
meeting,
|
|
114
|
+
followUp
|
|
115
|
+
};
|
|
58
116
|
} catch (error) {
|
|
59
|
-
console.error('[bookings] the
|
|
117
|
+
console.error('[bookings] the booking could not be filed on its record', hostId, bookingId, error);
|
|
60
118
|
return {
|
|
61
119
|
filed: false,
|
|
62
120
|
reason: 'failed'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/booking-crm.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 { getOrgForHost } from '@aglyn/tenant-data-admin'\
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/booking-crm.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 */\nimport { isHostPluginEnabled } from '@aglyn/aglyn/plugin-manager/enabled-plugins'\nimport {\n pluginRecordTimelineWriter,\n type PluginRecordWrite,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-timeline'\nimport { getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n bookingFollowUpDueMs,\n bookingFollowUpTitle,\n bookingMeetingBody,\n parseBookingRecordRef,\n} from '../model/booking-record'\nimport type { HostBookingService } from '../model'\n\n/** What became of a booking's filing on the workspace's records. */\nexport type BookingRecordOutcome =\n | {\n filed: false\n reason:\n /** No plugin keeps records for this workspace. */\n | 'no-record-system'\n /** The plugin that keeps records does not run on this site. */\n | 'record-system-off'\n /** The service asks for neither a meeting nor a follow-up. */\n | 'nothing-to-file'\n /** A read threw before anything was asked; logged. */\n | 'failed'\n }\n | {\n filed: true\n /** The record system's answer for the meeting, or `null` when none was asked for. */\n meeting: PluginRecordWrite | null\n /** Its answer for the follow-up, or `null` when the service asks for none. */\n followUp: PluginRecordWrite | null\n }\n\n/**\n * THE BOOKING'S WAY BACK TO THE RECORD IT CAME FROM (AGL-2660).\n *\n * Two doors write a confirmed booking: the create route, for a free\n * service, and the payment webhook, for a paid one once the charge clears.\n * Both call this with what they hold — the row as written and, when they\n * already read it, the service — and it files what the service asks for on\n * the workspace's records, through the core's record-timeline seam:\n *\n * - a `meeting` entry at the slot, naming the service and the time in the\n * service's own zone, unless the service switched it off;\n * - a follow-up task one business day after the slot, for whoever holds\n * the record, when the service asks for one.\n *\n * The record is the record system's to find: the one the booking link was\n * dropped from (`crmRef`, carried back as it was handed over), otherwise the\n * person at the booker's address, as this site sees them. Both entries are\n * keyed by the booking, so the webhook's redeliveries and a second door file\n * nothing twice; a full activity log refuses the meeting and still takes the\n * follow-up. Nothing is filed on a site that has switched the record system\n * off, and the record system refuses a plan without it.\n *\n * **Never throws**: the guest has their slot whatever the record system did,\n * so a failure here is an outcome the caller may log, never an error into\n * the request or the webhook.\n */\nexport async function fileBookingOnCrm(\n firestore: FirebaseFirestore.Firestore,\n input: {\n hostId: string\n bookingId: string\n /** The booking row as written — or as read back by the webhook. */\n booking: Record<string, unknown>\n /** The service, when the caller already read it. Read here otherwise. */\n service?: HostBookingService | null\n },\n): Promise<BookingRecordOutcome> {\n const { hostId, bookingId, booking } = input\n try {\n const records = pluginRecordTimelineWriter()\n if (!records) return { filed: false, reason: 'no-record-system' }\n const owner = await getOrgForHost(hostId)\n if (!owner?.orgId) return { filed: false, reason: 'failed' }\n const hostRef = firestore.collection('hosts').doc(hostId)\n const host = (await hostRef.get()).data() as\n | { disabledPlugins?: string[]; enabledPlugins?: string[] }\n | undefined\n if (!isHostPluginEnabled(owner.org as never, host ?? null, records.pluginId)) {\n return { filed: false, reason: 'record-system-off' }\n }\n const serviceId = String(booking['serviceId'] ?? '')\n const service =\n input.service !== undefined\n ? input.service\n : serviceId\n ? ((await hostRef.collection('services').doc(serviceId).get()).data() as\n | HostBookingService\n | undefined) ?? null\n : null\n const wantsMeeting = service?.crmMeetingActivity !== false\n const wantsFollowUp = service?.crmFollowUpTask === true\n if (!wantsMeeting && !wantsFollowUp) return { filed: false, reason: 'nothing-to-file' }\n\n const serviceName = String(service?.name ?? booking['serviceName'] ?? '').trim()\n const timezone = service?.timezone || undefined\n const startsAtMs = Number(booking['startsAtMs'] ?? 0)\n const endsAtMs = Number(booking['endsAtMs'] ?? 0)\n const context = {\n orgId: owner.orgId,\n hostId,\n link: {\n record: parseBookingRecordRef(booking['crmRef']),\n email: String(booking['email'] ?? ''),\n },\n sourcePluginId: BUNDLE_ID,\n }\n\n const meeting = wantsMeeting\n ? await records.writer.logActivity({\n ...context,\n kind: 'meeting',\n // When it HAPPENS, which is the slot — not when it was booked.\n atMs: startsAtMs,\n body: bookingMeetingBody({ serviceName, startsAtMs, timezone }),\n byUid: '',\n dedupeKey: `booking:${bookingId}`,\n })\n : null\n const followUp = wantsFollowUp\n ? await records.writer.createTask({\n ...context,\n dedupeKey: `booking-follow-up:${bookingId}`,\n title: bookingFollowUpTitle(serviceName),\n kind: 'todo',\n dueAtMs: bookingFollowUpDueMs(endsAtMs, timezone),\n // Whoever holds the record the booking lands on.\n assigneeUid: null,\n createdByUid: '',\n })\n : null\n return { filed: true, meeting, followUp }\n } catch (error) {\n console.error('[bookings] the booking could not be filed on its record', hostId, bookingId, error)\n return { filed: false, reason: 'failed' }\n }\n}\n"],"names":["isHostPluginEnabled","pluginRecordTimelineWriter","getOrgForHost","BUNDLE_ID","bookingFollowUpDueMs","bookingFollowUpTitle","bookingMeetingBody","parseBookingRecordRef","fileBookingOnCrm","firestore","input","hostId","bookingId","booking","service","records","filed","reason","owner","orgId","hostRef","collection","doc","host","get","data","org","pluginId","serviceId","String","undefined","wantsMeeting","crmMeetingActivity","wantsFollowUp","crmFollowUpTask","serviceName","name","trim","timezone","startsAtMs","Number","endsAtMs","context","link","record","email","sourcePluginId","meeting","writer","logActivity","kind","atMs","body","byUid","dedupeKey","followUp","createTask","title","dueAtMs","assigneeUid","createdByUid","error","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GACD,SAASA,mBAAmB,QAAQ,8CAA6C;AACjF,SACEC,0BAA0B,QAErB,qDAAoD;AAC3D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,oBAAoB,EACpBC,oBAAoB,EACpBC,kBAAkB,EAClBC,qBAAqB,QAChB,6BAAyB;AAyBhC;;;;;;;;;;;;;;;;;;;;;;;;;CAyBC,GACD,OAAO,eAAeC,iBACpBC,SAAsC,EACtCC,KAOC;IAED,MAAM,EAAEC,MAAM,EAAEC,SAAS,EAAEC,OAAO,EAAE,GAAGH;IACvC,IAAI;YAYuBG,oBAKhB,OAQkBC,aAEDD,qBACFA,mBAMNA;QAjClB,MAAME,UAAUd;QAChB,IAAI,CAACc,SAAS,OAAO;YAAEC,OAAO;YAAOC,QAAQ;QAAmB;QAChE,MAAMC,QAAQ,MAAMhB,cAAcS;QAClC,IAAI,EAACO,yBAAAA,MAAOC,KAAK,GAAE,OAAO;YAAEH,OAAO;YAAOC,QAAQ;QAAS;QAC3D,MAAM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B;YACpC;YACAiC,gBAAgB3C;QAClB;QAEA,MAAM4C,UAAUhB,eACZ,MAAMhB,QAAQiC,MAAM,CAACC,WAAW,CAAC,aAC5BP;YACHQ,MAAM;YACN,+DAA+D;YAC/DC,MAAMZ;YACNa,MAAM9C,mBAAmB;gBAAE6B;gBAAaI;gBAAYD;YAAS;YAC7De,OAAO;YACPC,WAAW,CAAC,QAAQ,EAAE1C,WAAW;cAEnC;QACJ,MAAM2C,WAAWtB,gBACb,MAAMlB,QAAQiC,MAAM,CAACQ,UAAU,CAAC,aAC3Bd;YACHY,WAAW,CAAC,kBAAkB,EAAE1C,WAAW;YAC3C6C,OAAOpD,qBAAqB8B;YAC5Be,MAAM;YACNQ,SAAStD,qBAAqBqC,UAAUH;YACxC,iDAAiD;YACjDqB,aAAa;YACbC,cAAc;cAEhB;QACJ,OAAO;YAAE5C,OAAO;YAAM+B;YAASQ;QAAS;IAC1C,EAAE,OAAOM,OAAO;QACdC,QAAQD,KAAK,CAAC,2DAA2DlD,QAAQC,WAAWiD;QAC5F,OAAO;YAAE7C,OAAO;YAAOC,QAAQ;QAAS;IAC1C;AACF"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* The zone a stored booking's time is told in (AGL-3432).
|
|
19
|
+
*
|
|
20
|
+
* A booking records the zone it was made in, and that answer costs nothing.
|
|
21
|
+
* One written before the zone was stored carries none, so it is resolved the
|
|
22
|
+
* way the booking route resolves a new one — the service's zone, then the
|
|
23
|
+
* site's, then the workspace's — at the cost of one read each, once per
|
|
24
|
+
* service when the caller passes a `cache` for a batch.
|
|
25
|
+
*
|
|
26
|
+
* Never throws: a read that fails tells the time in UTC, which the caller
|
|
27
|
+
* names, rather than holding back a confirmation or a reminder.
|
|
28
|
+
*/
|
|
29
|
+
export declare function bookingTimeZoneFor(firestore: FirebaseFirestore.Firestore, hostId: string, booking: {
|
|
30
|
+
timezone?: unknown;
|
|
31
|
+
serviceId?: unknown;
|
|
32
|
+
}, cache?: Map<string, Promise<string>>): Promise<string>;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
17
|
+
import { bookingTimeZone, storedBookingTimeZone } from "../model/booking-time.js";
|
|
18
|
+
/**
|
|
19
|
+
* The zone a stored booking's time is told in (AGL-3432).
|
|
20
|
+
*
|
|
21
|
+
* A booking records the zone it was made in, and that answer costs nothing.
|
|
22
|
+
* One written before the zone was stored carries none, so it is resolved the
|
|
23
|
+
* way the booking route resolves a new one — the service's zone, then the
|
|
24
|
+
* site's, then the workspace's — at the cost of one read each, once per
|
|
25
|
+
* service when the caller passes a `cache` for a batch.
|
|
26
|
+
*
|
|
27
|
+
* Never throws: a read that fails tells the time in UTC, which the caller
|
|
28
|
+
* names, rather than holding back a confirmation or a reminder.
|
|
29
|
+
*/ export function bookingTimeZoneFor(firestore, hostId, booking, cache) {
|
|
30
|
+
var _booking_serviceId;
|
|
31
|
+
const stored = storedBookingTimeZone(booking);
|
|
32
|
+
if (stored) return Promise.resolve(stored);
|
|
33
|
+
const serviceId = String((_booking_serviceId = booking.serviceId) != null ? _booking_serviceId : '');
|
|
34
|
+
const key = `${hostId}/${serviceId}`;
|
|
35
|
+
const cached = cache == null ? void 0 : cache.get(key);
|
|
36
|
+
if (cached) return cached;
|
|
37
|
+
const resolved = (async ()=>{
|
|
38
|
+
try {
|
|
39
|
+
var _ref;
|
|
40
|
+
const hostRef = firestore.collection('hosts').doc(hostId);
|
|
41
|
+
const [host, service, owner] = await Promise.all([
|
|
42
|
+
hostRef.get(),
|
|
43
|
+
serviceId ? hostRef.collection('services').doc(serviceId).get() : Promise.resolve(null),
|
|
44
|
+
getOrgForHost(hostId).catch(()=>null)
|
|
45
|
+
]);
|
|
46
|
+
return bookingTimeZone({
|
|
47
|
+
service: service == null ? void 0 : service.data(),
|
|
48
|
+
host: host.data(),
|
|
49
|
+
org: (_ref = owner == null ? void 0 : owner.org) != null ? _ref : null
|
|
50
|
+
});
|
|
51
|
+
} catch (unused) {
|
|
52
|
+
return 'UTC';
|
|
53
|
+
}
|
|
54
|
+
})();
|
|
55
|
+
cache == null ? void 0 : cache.set(key, resolved);
|
|
56
|
+
return resolved;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
//# sourceMappingURL=booking-time-zone.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/booking-time-zone.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 { getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { bookingTimeZone, storedBookingTimeZone } from '../model/booking-time'\n\n/**\n * The zone a stored booking's time is told in (AGL-3432).\n *\n * A booking records the zone it was made in, and that answer costs nothing.\n * One written before the zone was stored carries none, so it is resolved the\n * way the booking route resolves a new one — the service's zone, then the\n * site's, then the workspace's — at the cost of one read each, once per\n * service when the caller passes a `cache` for a batch.\n *\n * Never throws: a read that fails tells the time in UTC, which the caller\n * names, rather than holding back a confirmation or a reminder.\n */\nexport function bookingTimeZoneFor(\n firestore: FirebaseFirestore.Firestore,\n hostId: string,\n booking: { timezone?: unknown; serviceId?: unknown },\n cache?: Map<string, Promise<string>>,\n): Promise<string> {\n const stored = storedBookingTimeZone(booking)\n if (stored) return Promise.resolve(stored)\n const serviceId = String(booking.serviceId ?? '')\n const key = `${hostId}/${serviceId}`\n const cached = cache?.get(key)\n if (cached) return cached\n const resolved = (async () => {\n try {\n const hostRef = firestore.collection('hosts').doc(hostId)\n const [host, service, owner] = await Promise.all([\n hostRef.get(),\n serviceId\n ? hostRef.collection('services').doc(serviceId).get()\n : Promise.resolve(null),\n getOrgForHost(hostId).catch(() => null),\n ])\n return bookingTimeZone({\n service: service?.data() as { timezone?: unknown } | undefined,\n host: host.data() as { timeZone?: string } | undefined,\n org: (owner?.org ?? null) as { timeZone?: string } | null,\n })\n } catch {\n return 'UTC'\n }\n })()\n cache?.set(key, resolved)\n return resolved\n}\n"],"names":["getOrgForHost","bookingTimeZone","storedBookingTimeZone","bookingTimeZoneFor","firestore","hostId","booking","cache","stored","Promise","resolve","serviceId","String","key","cached","get","resolved","hostRef","collection","doc","host","service","owner","all","catch","data","org","set"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,eAAe,EAAEC,qBAAqB,QAAQ,2BAAuB;AAE9E;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,mBACdC,SAAsC,EACtCC,MAAc,EACdC,OAAoD,EACpDC,KAAoC;QAIXD;IAFzB,MAAME,SAASN,sBAAsBI;IACrC,IAAIE,QAAQ,OAAOC,QAAQC,OAAO,CAACF;IACnC,MAAMG,YAAYC,QAAON,qBAAAA,QAAQK,SAAS,YAAjBL,qBAAqB;IAC9C,MAAMO,MAAM,GAAGR,OAAO,CAAC,EAAEM,WAAW;IACpC,MAAMG,SAASP,yBAAAA,MAAOQ,GAAG,CAACF;IAC1B,IAAIC,QAAQ,OAAOA;IACnB,MAAME,WAAW,AAAC,CAAA;QAChB,IAAI;;YACF,MAAMC,UAAUb,UAAUc,UAAU,CAAC,SAASC,GAAG,CAACd;YAClD,MAAM,CAACe,MAAMC,SAASC,MAAM,GAAG,MAAMb,QAAQc,GAAG,CAAC;gBAC/CN,QAAQF,GAAG;gBACXJ,YACIM,QAAQC,UAAU,CAAC,YAAYC,GAAG,CAACR,WAAWI,GAAG,KACjDN,QAAQC,OAAO,CAAC;gBACpBV,cAAcK,QAAQmB,KAAK,CAAC,IAAM;aACnC;YACD,OAAOvB,gBAAgB;gBACrBoB,OAAO,EAAEA,2BAAAA,QAASI,IAAI;gBACtBL,MAAMA,KAAKK,IAAI;gBACfC,GAAG,UAAGJ,yBAAAA,MAAOI,GAAG,mBAAI;YACtB;QACF,EAAE,eAAM;YACN,OAAO;QACT;IACF,CAAA;IACAnB,yBAAAA,MAAOoB,GAAG,CAACd,KAAKG;IAChB,OAAOA;AACT"}
|