@aglyn/plugins-bookings 1.0.0-beta.231 → 1.0.0-beta.232
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/README.md +3 -1
- package/package.json +11 -11
- package/src/lib/components/bookings-console-page.js +30 -4
- package/src/lib/components/bookings-console-page.js.map +1 -1
- package/src/lib/declarations.console-server.d.ts +3 -0
- package/src/lib/declarations.console-server.js +20 -0
- package/src/lib/declarations.console-server.js.map +1 -1
- package/src/lib/model/booking-events.d.ts +52 -0
- package/src/lib/model/booking-events.js +53 -0
- package/src/lib/model/booking-events.js.map +1 -0
- package/src/lib/model/booking-manage.d.ts +7 -0
- package/src/lib/model/booking-manage.js +14 -0
- package/src/lib/model/booking-manage.js.map +1 -1
- package/src/lib/model/booking-view.d.ts +63 -0
- package/src/lib/model/booking-view.js +70 -0
- package/src/lib/model/booking-view.js.map +1 -0
- package/src/lib/server/api-v1/bookings.d.ts +33 -0
- package/src/lib/server/api-v1/bookings.js +103 -0
- package/src/lib/server/api-v1/bookings.js.map +1 -0
- package/src/lib/server/api-v1/openapi.d.ts +22 -0
- package/src/lib/server/api-v1/openapi.js +107 -0
- package/src/lib/server/api-v1/openapi.js.map +1 -0
- package/src/lib/server/billing-webhook.js +17 -0
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/booking-events.d.ts +40 -0
- package/src/lib/server/booking-events.js +50 -0
- package/src/lib/server/booking-events.js.map +1 -0
- package/src/lib/server/booking-manage.d.ts +16 -0
- package/src/lib/server/booking-manage.js +76 -2
- package/src/lib/server/booking-manage.js.map +1 -1
- package/src/lib/server/refund.js +17 -1
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server.js +22 -3
- package/src/lib/server.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 recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport {\n bookingPlatformNetCents,\n shouldSendBookingPlatformPurchase,\n} from '../model/booking-purchase-analytics'\nimport { sendEmail } from '@aglyn/shared-util-email'\nimport { pluginTaxProfile } from '@aglyn/aglyn/plugin-manager/plugin-tax-profile'\nimport { fileBookingOnCrm } from './booking-crm'\nimport { bookingTimeZoneFor } from './booking-time-zone'\nimport { formatBookingWhen } from '../model/booking-time'\nimport {\n bookingContactLines,\n readBookingPhone,\n} from '../model/booking-contact-fields'\n\n/**\n * Paid-booking section of the platform Stripe webhook (AGL-170/418):\n * payment confirms the pendingPayment hold — relocated verbatim from the\n * console route; registered via registerBookingsConsoleApi.\n */\n/** gRPC `Status.FAILED_PRECONDITION` — Firestore's \"this query needs an index\". */\nconst GRPC_FAILED_PRECONDITION = 9\n\n/**\n * The booking a charge paid for, found by the `paymentIntentId` the paid\n * handler below records (AGL-2315), or null. A missing collection-group\n * index is logged and answered null rather than thrown: no redelivery can\n * fix it, and the dispute then reaches staff through the route's\n * unattributed-dispute alert instead of vanishing.\n */\nasync function findBookingForPayment(\n paymentIntentId: string,\n): Promise<FirebaseFirestore.QueryDocumentSnapshot | null> {\n if (!paymentIntentId) return null\n const matches = await firebaseAdmin\n .app()\n .firestore()\n .collectionGroup('bookings')\n .where('paymentIntentId', '==', paymentIntentId)\n .limit(2)\n .get()\n .catch((error: { code?: number }) => {\n if (error?.code !== GRPC_FAILED_PRECONDITION) throw error\n console.error(\n 'Booking payment lookup needs the collection-group index on ' +\n 'bookings.paymentIntentId (AGL-3360)',\n error,\n )\n return null\n })\n // One payment intent pays one booking; two is corrupt data, and stamping\n // an arbitrary one would tell the wrong merchant.\n return matches && matches.docs.length === 1 ? matches.docs[0] : null\n}\n\n/** What a booking records once its lost dispute's reversal is settled. */\ninterface BookingDisputeReversal {\n disputeId: string\n reversedTransferCents: number\n transferReversalId?: string\n /** Why nothing was pulled back, when nothing was. */\n failedReason?: TransferReversalFailure\n owedCents?: number\n atMs: number\n}\n\n/**\n * The merchant's share of a LOST booking dispute, pulled back from the\n * connected account (AGL-3363), by the AGL-1794 policy a store order follows:\n * the Stripe half is the shared `reverseDestinationTransfer`, this is only\n * the booking's own record.\n *\n * IDEMPOTENT BY THE BOOKING: `disputeReversal` for this dispute, present,\n * means settled and a redelivery returns before any Stripe call. A delivery\n * that died after the POST is healed by the seam adopting the reversal the\n * transfer already carries. A transient Stripe failure THROWS (the seam\n * does), leaving the marker unset so Stripe's redelivery retries it. A final\n * failure is settled with its reason and the owed amount, so it is findable.\n *\n * `cents` is non-zero only for the delivery that wrote the reversal, which\n * is the one that tells the merchant.\n */\nasync function reverseBookingSellerShare(\n bookingRef: FirebaseFirestore.DocumentReference,\n dispute: any,\n): Promise<{ cents: number; settled: 'reversed' | 'failed' | 'pending' }> {\n const disputeId = String(dispute?.id ?? '')\n const amountCents = Math.max(0, Math.round(Number(dispute?.amount ?? 0)))\n if (!disputeId || !(amountCents > 0)) return { cents: 0, settled: 'failed' }\n const firestore = firebaseAdmin.app().firestore()\n const prior = (await bookingRef.get()).get('disputeReversal') as\n | BookingDisputeReversal\n | undefined\n if (prior?.disputeId === disputeId) {\n return { cents: 0, settled: prior.failedReason ? 'failed' : 'reversed' }\n }\n const outcome = await reverseDestinationTransfer({\n kind: 'dispute',\n id: disputeId,\n amountCents,\n chargeId:\n typeof dispute?.charge === 'string' ? dispute.charge : String(dispute?.charge?.id ?? ''),\n metadata: { bookingId: bookingRef.id },\n })\n if (outcome.kind === 'skipped') {\n console.error('Booking transfer reversal skipped: STRIPE_SECRET_KEY is not set (AGL-3363)')\n return { cents: 0, settled: 'pending' }\n }\n const record: BookingDisputeReversal =\n outcome.kind === 'reversed'\n ? {\n disputeId,\n reversedTransferCents: outcome.cents,\n ...(outcome.reversalId ? { transferReversalId: outcome.reversalId } : {}),\n atMs: Date.now(),\n }\n : {\n disputeId,\n reversedTransferCents: 0,\n failedReason: outcome.reason,\n ...(outcome.owedCents != null ? { owedCents: outcome.owedCents } : {}),\n atMs: Date.now(),\n }\n if (outcome.kind === 'not-reversed') {\n console.error('Booking seller share NOT reversed — recorded on the booking', {\n bookingId: bookingRef.id,\n disputeId,\n reason: outcome.reason,\n })\n }\n const wrote = await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n if (!fresh.exists) return false\n const current = fresh.get('disputeReversal') as BookingDisputeReversal | undefined\n if (current?.disputeId === disputeId) return false\n transaction.set(bookingRef, { disputeReversal: record }, { merge: true })\n return true\n })\n return {\n cents: wrote && outcome.kind === 'reversed' ? outcome.cents : 0,\n settled: outcome.kind === 'reversed' ? 'reversed' : 'failed',\n }\n}\n\nexport const bookingsBillingWebhookHandler: BillingWebhookHandler = async ({\n type,\n object,\n}) => {\n // Fraud signals on a paid booking (AGL-3360): an issuer's early fraud\n // warning, a Radar review, or a dispute. Booking deposits never heard\n // about any of them, so the merchant learned of a chargeback from Stripe\n // alone. The signal now lands on the BOOKING, through the shared\n // `paymentRisk` shape every plugin stamps, and the site's managers are\n // told once. Nothing is refunded or canceled: the merchant decides.\n const risk = paymentRiskEventFrom(type, object)\n if (risk) {\n const booking = await findBookingForPayment(risk.paymentIntentId)\n if (!booking) return\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n await recordPaymentRiskOnRecord(\n {\n ref: booking.ref,\n signal: risk.signal,\n hostId,\n subjectLabel: `the booking for ${String(booking.get('serviceName') ?? booking.id)}`,\n link: `/${hostId}/bookings`,\n notificationType: 'content.booking',\n amount: Number.isFinite(Number(booking.get('paidAmountCents')))\n ? `$${(Number(booking.get('paidAmountCents')) / 100).toFixed(2)}`\n : null,\n evidenceDueByMs:\n Number((object as { evidence_details?: { due_by?: unknown } })?.evidence_details?.due_by ?? 0) * 1000 || null,\n },\n { firestore: firebaseAdmin.app().firestore(), notifyRisk: notifyRiskEvent },\n )\n return { claimed: true, hostId }\n }\n // A dispute's outcome, on the signal `created` stamped. A LOST one pulls\n // the merchant's share back from the connected account (AGL-3363), through\n // the same seam a lost store order uses, so the platform no longer absorbs\n // a booking chargeback. Claimed when the share came back; a reversal that\n // could not be made stays unclaimed, so the route's unattributed-dispute\n // alert still tells staff about money nothing recovered.\n if (type === 'charge.dispute.closed') {\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const booking = await findBookingForPayment(paymentIntentId)\n if (!booking) return\n const outcome = String(object?.status ?? '')\n await settlePaymentRiskDisputeOnRecord(\n booking.ref,\n String(object?.id ?? ''),\n outcome,\n { firestore: firebaseAdmin.app().firestore() },\n )\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n if (outcome !== 'lost') return { claimed: true, hostId }\n const recovered = await reverseBookingSellerShare(booking.ref, object)\n if (recovered.cents > 0 && hostId) {\n const recoveredText = `$${(recovered.cents / 100).toFixed(2)}`\n const guest = String(booking.get('name') ?? '').trim()\n const service = String(booking.get('serviceName') ?? '').trim() || 'a service'\n await notifyHostManagers(hostId, {\n type: 'content.booking',\n title: `Payout adjusted — ${recoveredText} recovered for a lost chargeback`,\n body:\n `${guest ? `${guest}'s payment` : 'A payment'} for ${service} on ` +\n `{site} was charged back and the dispute was lost, so ` +\n `the ${recoveredText} transferred to you for it has been taken back. ` +\n `If your balance does not cover it, Stripe recovers the rest from ` +\n `your future payouts.`,\n link: `/${hostId}/bookings`,\n })\n }\n return recovered.settled === 'reversed' ? { claimed: true, hostId } : undefined\n }\n // Paid bookings (AGL-170): payment confirms the pendingPayment hold.\n if (\n type === 'checkout.session.completed' &&\n object?.metadata?.type === 'booking-payment' &&\n object?.payment_status === 'paid'\n ) {\n const { hostId, bookingId } = object.metadata ?? {}\n if (hostId && bookingId) {\n const firestore = firebaseAdmin.app().firestore()\n const bookingRef = firestore\n .collection('hosts')\n .doc(String(hostId))\n .collection('bookings')\n .doc(String(bookingId))\n // WHAT THE CLIENT HANDED OVER, ALL OF IT. Tax included: this is the\n // ceiling `refund.ts` reverses against, and the client paid the tax\n // too — a net figure here would strand part of a refund.\n const paidAmountCents = Math.max(\n 0,\n Math.round(Number(object?.amount_total ?? 0)),\n )\n // THE MERCHANT'S SERVICE TAX, SEPARATED OUT (AGL-2028).\n //\n // `server.ts` charges the merchant's own service rate as an ordinary\n // `line_items[1]` Stripe is never told is tax (the AGL-1711\n // construction, which is what keeps the figure the MERCHANT's rather\n // than something computed against Aglyn's registrations). So\n // `amount_total` is service-plus-tax while Stripe's own tax fields\n // read zero, and the session's metadata is the only witness — exactly\n // as it is for a buy-now sale.\n const taxCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.taxCents ?? 0)),\n )\n // The merchant's REVENUE, which is the charge less the tax. Used for\n // the contact's lifetime value below: tax is collected on behalf of\n // an authority and is not money the business earned, so counting it\n // would over-state every service client's worth.\n const serviceCents = Math.max(0, paidAmountCents - taxCents)\n // WHAT A REFUND WILL NEED (AGL-2315). A paid booking is now a\n // destination charge to the merchant's connected account, and\n // reversing one requires the PaymentIntent — which lives only on this\n // event. The booking document recorded `paidAmountCents` and nothing\n // that identifies the charge, so a refund had no handle to pull and\n // the information was gone the moment the webhook returned. Unlike\n // most gaps this one cannot be backfilled from our own data later:\n // every booking taken before this line landed can only be refunded by\n // hand in the Stripe dashboard.\n //\n // `feeCents` is Aglyn's cut as CHARGED, read back off the session's\n // own metadata rather than re-derived from the org at refund time. The\n // rate follows the plan (AGL-2289's rule) and the plan moves, so\n // re-resolving it during a refund would reverse a share that was never\n // taken. `'0'` is a real recorded answer on the 0%-rate tiers.\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const chargedFeeCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.feeCents ?? 0)),\n )\n // Redelivery guard (AGL-1755), the AGL-1748 shape. This was an\n // unconditional merge-set with no status check at all — idempotent\n // only by accident, because every value it wrote was fixed. A\n // redelivery re-sent the guest's confirmation and re-metered it, and\n // the moment this handler carries money to a contact the accident stops\n // holding: `purchaseCents` is a `FieldValue.increment`, so every retry\n // would inflate the customer's lifetime value.\n //\n // Keyed on the STATUS, not on the document existing: `server.ts` writes\n // the booking as `pendingPayment` BEFORE it opens the Stripe session,\n // so existence is guaranteed by the time any event arrives and proves\n // nothing — the AGL-1748 reasoning, not AGL-1732's `checkoutSessionId`\n // key, which existed because a sibling event wrote the same path.\n //\n // The key is \"not yet confirmed\" rather than \"is pendingPayment\" on\n // purpose. The lapsed-hold sweeper in `server.ts` cancels a\n // `pendingPayment` booking after 24h, and refusing a payment that\n // landed anyway would take the money and record nothing; `confirmed` is\n // reachable for a PAID booking only by this handler having already run,\n // so it is an exact \"already processed\" test. The existence check is\n // new and deliberate: the old merge-set would CREATE a stub booking\n // from a metadata `bookingId` that pointed at nothing.\n let booking: Record<string, any> = {}\n const confirmedNow = await firestore.runTransaction(\n async (transaction) => {\n const snapshot = await transaction.get(bookingRef)\n if (!snapshot.exists) return false\n if (snapshot.get('status') === 'confirmed') return false\n // \"Already processed\" is WIDER than `confirmed` once money can\n // flow back out (AGL-2315). A refunded booking is moved off\n // `confirmed`, so a redelivery arriving afterwards would otherwise\n // read as unprocessed and re-confirm an appointment the merchant\n // has already cancelled and refunded — re-sending the guest a\n // confirmation for it and re-metering the email. Any evidence this\n // handler has run before is the real test, and a refund counter or\n // a recorded PaymentIntent is exactly that evidence.\n if (\n Number(snapshot.get('refundedCents') ?? 0) > 0 ||\n snapshot.get('paymentIntentId')\n ) {\n return false\n }\n booking = (snapshot.data() as any) ?? {}\n transaction.set(\n bookingRef,\n {\n status: 'confirmed',\n paidAmountCents,\n // WHICH TAX REGIME THIS BOOKING CARRIED (AGL-2028), on the\n // document the merchant reads — the stamp every other\n // storefront money door already carries (AGL-2451).\n //\n // DERIVED from the one shared derivation, never a constant.\n // A hand-written \"manual when the metadata says so\" would be\n // a second rule that can drift from the `storefrontTaxCollected`\n // row filed for the same Stripe id, which is the exact\n // disagreement AGL-2451 exists to prevent.\n //\n // TWO-ARGUMENT, because the manual line makes Stripe report\n // `total_details.amount_tax: 0` on a booking that really did\n // charge the client tax; the one-argument form would stamp\n // `none` on precisely those. `absent` remains a fourth state\n // meaning \"recorded before this shipped\".\n taxMode: pluginTaxProfile().taxModeOf(object, taxCents),\n // The figure itself. Absent rather than a defaulted `0` — a\n // zero written through `merge` is the AGL-1758 shape, and\n // this handler can re-enter (see the widened guard above).\n ...(taxCents > 0 ? { taxCents } : {}),\n // The refund handles (AGL-2315). Written inside the same\n // transaction as the status, so a booking can never read\n // `confirmed` while the means to refund it are missing.\n ...(paymentIntentId ? { paymentIntentId } : {}),\n feeCents: chargedFeeCents,\n // WHICH CHECKOUT PAID FOR THIS (AGL-2481). The guest's browser\n // comes back from Stripe holding a session id and nothing\n // else — a booking id was never in the return URL — so this is\n // what lets `booking-analytics.ts` answer \"what did I just\n // buy?\" for the merchant-side `purchase`, and it is written\n // here because the session id first exists on this event.\n //\n // Inside the transaction with the status on purpose: the\n // lookup refuses anything that is not `confirmed`, so a\n // booking can never be findable by session id while reading as\n // unpaid.\n ...(object?.id ? { checkoutSessionId: String(object.id) } : {}),\n // NOTE the absent `refundedCents: 0`. Seeding it here would be\n // the AGL-1758 shape: a defaulted field written through\n // `merge` destroying the real one. This handler can re-enter\n // after a refund has already accumulated a counter (see the\n // widened guard above), and a zero written back over it would\n // re-open the full amount for refunding a second time. Absent\n // IS zero — every reader coerces with `?? 0`.\n expiresAtMs: firebaseAdmin.firestore.FieldValue.delete(),\n confirmedAt:\n firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n return true\n },\n )\n if (!confirmedNow) return\n // THE RECORD'S MEETING (AGL-2660). Payment is what confirms a paid\n // booking, so this is where it reaches the CRM: the meeting on the\n // record's timeline and, when the service asks, the follow-up task.\n // Inside the idempotency gate for the same reason the GA4 purchase\n // below is — a redelivery must not file a second meeting — and\n // through `after()` for the same reason too: this invocation is\n // frozen the moment the response is sent (AGL-2327). Never thrown:\n // the writer swallows its own failures, and the catch is for the\n // scheduling itself.\n after(() =>\n fileBookingOnCrm(firestore, {\n hostId: String(hostId),\n bookingId: String(bookingId),\n booking,\n }).catch(() => undefined),\n )\n // AGLYN'S REVENUE ON THIS BOOKING (AGL-2481) — into OUR GA4 property.\n //\n // ## Why it is inside the idempotency gate rather than beside it\n //\n // This sits AFTER `if (!confirmedNow) return` and that placement is the\n // whole guard. Stripe redelivers `checkout.session.completed` for up to\n // three days after any 500, and this endpoint 500s on purpose; a\n // redelivery re-enters this handler, the transaction above sees a\n // `confirmed` status (or a refund counter, or a recorded PaymentIntent)\n // and answers false, and everything below — the contact, the email, and\n // now this — is skipped. A `purchase` fired before that gate, or beside\n // it, would inflate our own reported revenue by the redelivery rate.\n //\n // `transaction_id` is the checkout session id, which is the same key\n // the guard turns on, so GA4's own de-duplication is a second\n // independent line of defence: even if the Firestore guard were ever\n // bypassed, GA would collapse the repeats.\n //\n // ## Platform NET, and the fee is the measured one\n //\n // `value` is our fee and not the $95 the guest paid — the AGL-1639\n // settlement. This is our property, the subscription and marketplace\n // `purchase` events in it already mean \"what Aglyn was paid\", and a\n // gross booking figure sitting beside them would make every combined\n // total, ARPA and revenue audience wrong. The merchant's own gross goes\n // to the MERCHANT's property, client-side, and the two never meet.\n //\n // The figure comes off the session's `metadata.feeCents` — the fee\n // Stripe actually charged as `application_fee_amount` — never from the\n // plan's rate re-applied here. See `bookingPlatformNetCents`.\n //\n // ## Scheduling and failure posture\n //\n // `after()`, never a bare `void` (AGL-2327/AGL-2346): this runs inside\n // the console's `/api/billing/webhook` invocation, which is frozen the\n // moment the response is sent, so fire-and-forget work scheduled any\n // other way simply does not run — the exact way marketplace revenue\n // reported to nothing. And `.catch()`, because a throw here would\n // un-claim the Stripe event and turn a missed analytics hit into a\n // repeated billing side effect.\n if (shouldSendBookingPlatformPurchase(object)) {\n const netCents = bookingPlatformNetCents(object)\n after(() =>\n sendGa4Purchase({\n transactionId: String(object?.id ?? ''),\n value: netCents / 100,\n currency: String(object?.currency ?? 'usd'),\n items: [\n {\n // Ids only, no merchant free text. A service name is\n // merchant-authored and one edit away from carrying a\n // person's name into a dimension in OUR property; the id\n // already identifies it. The merchant's own property gets\n // the name, because there it is their own content.\n item_id: String(booking['serviceId'] ?? bookingId),\n item_name: String(booking['serviceId'] ?? bookingId),\n item_category: 'booking',\n // GA expects the items to sum to `value`; one item, one\n // price, and that price is our fee — not the service's.\n price: netCents / 100,\n quantity: 1,\n },\n ],\n // Booking sessions carry no `ga_client_id` today — nothing\n // captures one on a tenant site — so this is read for the day\n // one is stamped and the seed below is what actually resolves.\n clientId: object?.metadata?.ga_client_id,\n // ONE PAYING GUEST, ONE SYNTHETIC USER. Seeded from Stripe's\n // customer where there is one, and otherwise from the guest's\n // email, which `server.ts` passes as `customer_email` and Stripe\n // echoes on `customer_details`. The seed is hashed inside\n // `synthesizeClientId` and never transmitted.\n //\n // The booking id is the LAST resort deliberately: it is unique\n // per appointment, so seeding from it would turn a regular\n // client into a crowd of one-purchase strangers and make ARPA\n // nonsense — precisely what that helper's determinism exists to\n // prevent. Without any seed at all `sendGa4Purchase` returns\n // `no-client-id` and the event is silently never sent, which is\n // the void this whole change exists to close.\n stripeCustomerId:\n String(object?.customer ?? '') ||\n String(object?.customer_details?.email ?? '') ||\n String(bookingId),\n }).catch(() => undefined),\n )\n }\n // Contacts ingestion (AGL-1755). `server.ts` captures the contact at\n // REQUEST time, which is the right place — the booking is written\n // `pendingPayment` and at that moment no money has moved, so passing an\n // amount there would be a lie. But payment completes HERE, and this\n // handler never returned to the contact, so a paid booking's money\n // reached the booking document and nothing else. The same structural\n // shape as AGL-1748's draft branch: the completion handler does\n // everything except the contact.\n //\n // `source` stays `'booking'` — the same source the request-time capture\n // used — so the `sources` map still says where this person came from\n // and no schema change is needed to keep service revenue\n // distinguishable from product revenue. The second interaction is\n // deliberate rather than a duplicate: \"Booked X\" and \"Paid for X\" are\n // two real events, and `mergeContactInteraction` does not dedupe on\n // `refId`.\n //\n // The amount is `amount_total`, the money that moved, per AGL-1698 and\n // AGL-1711 — the booking document stores no price to re-derive it from.\n if (booking['email']) {\n void recordCapturedContact({\n orgId: '',\n hostId: String(hostId),\n identity: {\n email: booking['email'],\n ...(booking['name'] ? { name: String(booking['name']) } : {}),\n },\n // Paid, so a relationship (AGL-3232): the lead the request-time\n // capture filed for the address is closed onto the contact.\n surface: 'relationship',\n // The phone the booking form asked for (AGL-3493), onto the\n // contact only where it holds none — as the request-time\n // capture put it on the lead.\n ...(readBookingPhone(booking['phone'])\n ? { profileFill: { phone: readBookingPhone(booking['phone']) } }\n : {}),\n // Paid, so a customer (AGL-2612) — the request-time capture\n // said `lead`, and this is the door that has seen the money.\n lifecycleFloor: 'customer',\n // The SERVICE, not the charge (AGL-2028). `amount_total` now\n // includes the merchant's service tax where they set one, and\n // tax is collected for an authority rather than earned — booking\n // it as lifetime value would over-state what every service\n // client is worth. Identical to `paidAmountCents` on the default\n // store, which sets no rate.\n ...(serviceCents > 0 ? { purchaseCents: serviceCents } : {}),\n interaction: {\n source: 'booking',\n refId: String(bookingId),\n summary: `Paid for \"${String(\n booking['serviceName'] ?? 'a service',\n ).slice(0, 60)}\" ($${(serviceCents / 100).toFixed(2)})`,\n },\n })\n }\n // In the booking's own zone, and named (AGL-3432): a formatter with\n // no zone reads in the server's — UTC — and tells a paying guest the\n // wrong hour, and an empty zone prints \"()\".\n const timezone = await bookingTimeZoneFor(\n firestore,\n String(hostId),\n booking,\n )\n const when = formatBookingWhen(Number(booking['startsAtMs']), timezone)\n const paid = `$${(paidAmountCents / 100).toFixed(2)}`\n // The site's managers hear of a PAID booking too (AGL-3500): the\n // free path tells them when the request lands, and a paid one is\n // only a booking once this event has cleared the charge, so this is\n // its moment. Who, what, when, what was paid, and the phone and\n // address the service asked for.\n const contactLines = bookingContactLines(booking)\n void notifyHostManagers(String(hostId), {\n type: 'content.booking',\n title: 'New booking on {site}',\n body:\n `${String(booking['name'] ?? '') || 'A guest'}` +\n (booking['email'] ? ` (${String(booking['email'])})` : '') +\n ` booked ${String(booking['serviceName'] ?? '') || 'a service'} ` +\n `on {site} for ${when} (${timezone}). ${paid} was paid.` +\n (contactLines.length ? ` ${contactLines.join('. ')}.` : ''),\n link: `/${hostId}/bookings`,\n })\n // Confirmation email now that payment cleared (env-gated inside\n // sendEmail, which no-ops when Resend isn't configured).\n if (booking['email']) {\n const fallbackText =\n `Hi ${booking['name'] ?? ''},\\n\\nPayment received — ` +\n `\"${booking['serviceName'] ?? 'your booking'}\" is ` +\n `confirmed for ${when} (${timezone}). You paid ${paid}.` +\n `\\n\\nReference: ${bookingId}`\n // Site-owner-designed template when published (AGL-770); null keeps\n // the built-in copy.\n const designed = await renderHostEmailWithTokens(\n firebaseAdmin.app().firestore(),\n String(hostId),\n 'booking-confirmed',\n {\n name: String(booking['name'] ?? ''),\n 'service.name': String(booking['serviceName'] ?? ''),\n when,\n timezone,\n 'booking.payment': `You paid ${paid}.`,\n 'booking.ref': String(bookingId),\n },\n )\n // White-label sender identity (White-Label Phase 3), matching the\n // free-booking path — the store's brand via the one shared resolver.\n const branding = resolveBrandingProfile(\n (await getOrgForHost(String(hostId)).catch(() => null))?.org as never,\n )\n await sendEmail({\n to: String(booking['email']),\n subject:\n designed?.subject ??\n `Booking confirmed: ${booking['serviceName'] ?? ''}`,\n text: designed?.text || fallbackText,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(String(hostId)),\n audience: 'tenant',\n context: 'paid booking confirmation',\n // Owed to the recipient by their own booking: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'booking',\n })\n // Cost meter (AGL-1438), matching the free-booking path.\n // Transactional: the guest has already paid.\n await meterHostEmail(String(hostId))\n }\n }\n }\n}\n"],"names":["after","resolveBrandingProfile","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","notifyHostManagers","notifyRiskEvent","renderHostEmailWithTokens","sendGa4Purchase","paymentRiskEventFrom","recordPaymentRiskOnRecord","settlePaymentRiskDisputeOnRecord","reverseDestinationTransfer","recordCapturedContact","bookingPlatformNetCents","shouldSendBookingPlatformPurchase","sendEmail","pluginTaxProfile","fileBookingOnCrm","bookingTimeZoneFor","formatBookingWhen","bookingContactLines","readBookingPhone","GRPC_FAILED_PRECONDITION","findBookingForPayment","paymentIntentId","matches","app","firestore","collectionGroup","where","limit","get","catch","error","code","console","docs","length","reverseBookingSellerShare","bookingRef","dispute","disputeId","String","id","amountCents","Math","max","round","Number","amount","cents","settled","prior","failedReason","outcome","kind","chargeId","charge","metadata","bookingId","record","reversedTransferCents","reversalId","transferReversalId","atMs","Date","now","reason","owedCents","wrote","runTransaction","transaction","fresh","exists","current","set","disputeReversal","merge","bookingsBillingWebhookHandler","type","object","risk","booking","hostId","ref","parent","signal","subjectLabel","link","notificationType","isFinite","toFixed","evidenceDueByMs","evidence_details","due_by","notifyRisk","claimed","payment_intent","status","recovered","recoveredText","guest","trim","service","title","body","undefined","payment_status","collection","doc","paidAmountCents","amount_total","taxCents","serviceCents","chargedFeeCents","feeCents","confirmedNow","snapshot","data","taxMode","taxModeOf","checkoutSessionId","expiresAtMs","FieldValue","delete","confirmedAt","serverTimestamp","netCents","transactionId","value","currency","items","item_id","item_name","item_category","price","quantity","clientId","ga_client_id","stripeCustomerId","customer","customer_details","email","orgId","identity","name","surface","profileFill","phone","lifecycleFloor","purchaseCents","interaction","source","refId","summary","slice","timezone","when","paid","contactLines","join","fallbackText","designed","branding","org","to","subject","text","html","fromName","sendingIdentity","audience","context","owedFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,8EAA8E;AAC9E,4EAA4E;AAC5E,oDAAoD;AACpD,SAASA,KAAK,QAAQ,cAAa;AAGnC,SAASC,sBAAsB,QAAQ,sBAAqB;AAC5D,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,kBAAkB,EAClBC,eAAe,EACfC,yBAAyB,EACzBC,eAAe,QACV,2BAA0B;AACjC,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SACEC,yBAAyB,EACzBC,gCAAgC,QAC3B,sDAAqD;AAC5D,SACEC,0BAA0B,QAErB,2DAA0D;AACjE,OAAOC,2BAA2B,sDAAqD;AACvF,SACEC,uBAAuB,EACvBC,iCAAiC,QAC5B,yCAAqC;AAC5C,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,gBAAgB,QAAQ,iDAAgD;AACjF,SAASC,gBAAgB,QAAQ,mBAAe;AAChD,SAASC,kBAAkB,QAAQ,yBAAqB;AACxD,SAASC,iBAAiB,QAAQ,2BAAuB;A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;gBAClE,qEAAqE;gBACrE,MAAMwG,WAAWpK,wBACd,QAAA,MAAME,cAAcyC,OAAOyC,SAASnD,KAAK,CAAC,IAAM,0BAAjD,AAAC,MAAwDoI,GAAG;gBAE9D,MAAMrJ,UAAU;oBACdsJ,IAAI3H,OAAOwC,OAAO,CAAC,QAAQ;oBAC3BoF,OAAO,YACLJ,4BAAAA,SAAUI,OAAO,qBACjB,CAAC,mBAAmB,GAAEpF,wBAAAA,OAAO,CAAC,cAAc,YAAtBA,wBAA0B,IAAI;oBACtDqF,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,MAAMxK,oBAAoBwC,OAAOyC;oBAClDwF,UAAU;oBACVC,SAAS;oBACT,2DAA2D;oBAC3D,gDAAgD;oBAChDC,SAAS;;gBAEX,yDAAyD;gBACzD,6CAA6C;gBAC7C,MAAM1K,eAAeuC,OAAOyC;YAC9B;QACF;IACF;AACJ,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/billing-webhook.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// `after()`, never a bare `void promise` (AGL-2327). This handler runs inside\n// the console's `/api/billing/webhook` invocation, which AGL-1133 measured on\n// production is frozen the moment the response is sent — so fire-and-forget\n// work scheduled any other way simply does not run.\nimport { after } from 'next/server'\n\nimport type { BillingWebhookHandler } from '@aglyn/aglyn/server'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/server'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n notifyHostManagers,\n notifyRiskEvent,\n renderHostEmailWithTokens,\n sendGa4Purchase,\n} from '@aglyn/tenant-data-admin'\nimport { paymentRiskEventFrom } from '@aglyn/aglyn/app-utils/payment-risk'\nimport {\n recordPaymentRiskOnRecord,\n settlePaymentRiskDisputeOnRecord,\n} from '@aglyn/tenant-data-admin/server/payment-risk-record'\nimport {\n reverseDestinationTransfer,\n type TransferReversalFailure,\n} from '@aglyn/tenant-data-admin/server/stripe-transfer-reversal'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport {\n bookingPlatformNetCents,\n shouldSendBookingPlatformPurchase,\n} from '../model/booking-purchase-analytics'\nimport { sendEmail } from '@aglyn/shared-util-email'\nimport { pluginTaxProfile } from '@aglyn/aglyn/plugin-manager/plugin-tax-profile'\nimport { fileBookingOnCrm } from './booking-crm'\nimport { stageBookingEvent } from './booking-events'\nimport { bookingTimeZoneFor } from './booking-time-zone'\nimport { formatBookingWhen } from '../model/booking-time'\nimport {\n bookingContactLines,\n readBookingPhone,\n} from '../model/booking-contact-fields'\n\n/**\n * Paid-booking section of the platform Stripe webhook (AGL-170/418):\n * payment confirms the pendingPayment hold — relocated verbatim from the\n * console route; registered via registerBookingsConsoleApi.\n */\n/** gRPC `Status.FAILED_PRECONDITION` — Firestore's \"this query needs an index\". */\nconst GRPC_FAILED_PRECONDITION = 9\n\n/**\n * The booking a charge paid for, found by the `paymentIntentId` the paid\n * handler below records (AGL-2315), or null. A missing collection-group\n * index is logged and answered null rather than thrown: no redelivery can\n * fix it, and the dispute then reaches staff through the route's\n * unattributed-dispute alert instead of vanishing.\n */\nasync function findBookingForPayment(\n paymentIntentId: string,\n): Promise<FirebaseFirestore.QueryDocumentSnapshot | null> {\n if (!paymentIntentId) return null\n const matches = await firebaseAdmin\n .app()\n .firestore()\n .collectionGroup('bookings')\n .where('paymentIntentId', '==', paymentIntentId)\n .limit(2)\n .get()\n .catch((error: { code?: number }) => {\n if (error?.code !== GRPC_FAILED_PRECONDITION) throw error\n console.error(\n 'Booking payment lookup needs the collection-group index on ' +\n 'bookings.paymentIntentId (AGL-3360)',\n error,\n )\n return null\n })\n // One payment intent pays one booking; two is corrupt data, and stamping\n // an arbitrary one would tell the wrong merchant.\n return matches && matches.docs.length === 1 ? matches.docs[0] : null\n}\n\n/** What a booking records once its lost dispute's reversal is settled. */\ninterface BookingDisputeReversal {\n disputeId: string\n reversedTransferCents: number\n transferReversalId?: string\n /** Why nothing was pulled back, when nothing was. */\n failedReason?: TransferReversalFailure\n owedCents?: number\n atMs: number\n}\n\n/**\n * The merchant's share of a LOST booking dispute, pulled back from the\n * connected account (AGL-3363), by the AGL-1794 policy a store order follows:\n * the Stripe half is the shared `reverseDestinationTransfer`, this is only\n * the booking's own record.\n *\n * IDEMPOTENT BY THE BOOKING: `disputeReversal` for this dispute, present,\n * means settled and a redelivery returns before any Stripe call. A delivery\n * that died after the POST is healed by the seam adopting the reversal the\n * transfer already carries. A transient Stripe failure THROWS (the seam\n * does), leaving the marker unset so Stripe's redelivery retries it. A final\n * failure is settled with its reason and the owed amount, so it is findable.\n *\n * `cents` is non-zero only for the delivery that wrote the reversal, which\n * is the one that tells the merchant.\n */\nasync function reverseBookingSellerShare(\n bookingRef: FirebaseFirestore.DocumentReference,\n dispute: any,\n): Promise<{ cents: number; settled: 'reversed' | 'failed' | 'pending' }> {\n const disputeId = String(dispute?.id ?? '')\n const amountCents = Math.max(0, Math.round(Number(dispute?.amount ?? 0)))\n if (!disputeId || !(amountCents > 0)) return { cents: 0, settled: 'failed' }\n const firestore = firebaseAdmin.app().firestore()\n const prior = (await bookingRef.get()).get('disputeReversal') as\n | BookingDisputeReversal\n | undefined\n if (prior?.disputeId === disputeId) {\n return { cents: 0, settled: prior.failedReason ? 'failed' : 'reversed' }\n }\n const outcome = await reverseDestinationTransfer({\n kind: 'dispute',\n id: disputeId,\n amountCents,\n chargeId:\n typeof dispute?.charge === 'string' ? dispute.charge : String(dispute?.charge?.id ?? ''),\n metadata: { bookingId: bookingRef.id },\n })\n if (outcome.kind === 'skipped') {\n console.error('Booking transfer reversal skipped: STRIPE_SECRET_KEY is not set (AGL-3363)')\n return { cents: 0, settled: 'pending' }\n }\n const record: BookingDisputeReversal =\n outcome.kind === 'reversed'\n ? {\n disputeId,\n reversedTransferCents: outcome.cents,\n ...(outcome.reversalId ? { transferReversalId: outcome.reversalId } : {}),\n atMs: Date.now(),\n }\n : {\n disputeId,\n reversedTransferCents: 0,\n failedReason: outcome.reason,\n ...(outcome.owedCents != null ? { owedCents: outcome.owedCents } : {}),\n atMs: Date.now(),\n }\n if (outcome.kind === 'not-reversed') {\n console.error('Booking seller share NOT reversed — recorded on the booking', {\n bookingId: bookingRef.id,\n disputeId,\n reason: outcome.reason,\n })\n }\n const wrote = await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n if (!fresh.exists) return false\n const current = fresh.get('disputeReversal') as BookingDisputeReversal | undefined\n if (current?.disputeId === disputeId) return false\n transaction.set(bookingRef, { disputeReversal: record }, { merge: true })\n return true\n })\n return {\n cents: wrote && outcome.kind === 'reversed' ? outcome.cents : 0,\n settled: outcome.kind === 'reversed' ? 'reversed' : 'failed',\n }\n}\n\nexport const bookingsBillingWebhookHandler: BillingWebhookHandler = async ({\n type,\n object,\n}) => {\n // Fraud signals on a paid booking (AGL-3360): an issuer's early fraud\n // warning, a Radar review, or a dispute. Booking deposits never heard\n // about any of them, so the merchant learned of a chargeback from Stripe\n // alone. The signal now lands on the BOOKING, through the shared\n // `paymentRisk` shape every plugin stamps, and the site's managers are\n // told once. Nothing is refunded or canceled: the merchant decides.\n const risk = paymentRiskEventFrom(type, object)\n if (risk) {\n const booking = await findBookingForPayment(risk.paymentIntentId)\n if (!booking) return\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n await recordPaymentRiskOnRecord(\n {\n ref: booking.ref,\n signal: risk.signal,\n hostId,\n subjectLabel: `the booking for ${String(booking.get('serviceName') ?? booking.id)}`,\n link: `/${hostId}/bookings`,\n notificationType: 'content.booking',\n amount: Number.isFinite(Number(booking.get('paidAmountCents')))\n ? `$${(Number(booking.get('paidAmountCents')) / 100).toFixed(2)}`\n : null,\n evidenceDueByMs:\n Number((object as { evidence_details?: { due_by?: unknown } })?.evidence_details?.due_by ?? 0) * 1000 || null,\n },\n { firestore: firebaseAdmin.app().firestore(), notifyRisk: notifyRiskEvent },\n )\n return { claimed: true, hostId }\n }\n // A dispute's outcome, on the signal `created` stamped. A LOST one pulls\n // the merchant's share back from the connected account (AGL-3363), through\n // the same seam a lost store order uses, so the platform no longer absorbs\n // a booking chargeback. Claimed when the share came back; a reversal that\n // could not be made stays unclaimed, so the route's unattributed-dispute\n // alert still tells staff about money nothing recovered.\n if (type === 'charge.dispute.closed') {\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const booking = await findBookingForPayment(paymentIntentId)\n if (!booking) return\n const outcome = String(object?.status ?? '')\n await settlePaymentRiskDisputeOnRecord(\n booking.ref,\n String(object?.id ?? ''),\n outcome,\n { firestore: firebaseAdmin.app().firestore() },\n )\n const hostId = String(booking.ref.parent.parent?.id ?? '')\n if (outcome !== 'lost') return { claimed: true, hostId }\n const recovered = await reverseBookingSellerShare(booking.ref, object)\n if (recovered.cents > 0 && hostId) {\n const recoveredText = `$${(recovered.cents / 100).toFixed(2)}`\n const guest = String(booking.get('name') ?? '').trim()\n const service = String(booking.get('serviceName') ?? '').trim() || 'a service'\n await notifyHostManagers(hostId, {\n type: 'content.booking',\n title: `Payout adjusted — ${recoveredText} recovered for a lost chargeback`,\n body:\n `${guest ? `${guest}'s payment` : 'A payment'} for ${service} on ` +\n `{site} was charged back and the dispute was lost, so ` +\n `the ${recoveredText} transferred to you for it has been taken back. ` +\n `If your balance does not cover it, Stripe recovers the rest from ` +\n `your future payouts.`,\n link: `/${hostId}/bookings`,\n })\n }\n return recovered.settled === 'reversed' ? { claimed: true, hostId } : undefined\n }\n // Paid bookings (AGL-170): payment confirms the pendingPayment hold.\n if (\n type === 'checkout.session.completed' &&\n object?.metadata?.type === 'booking-payment' &&\n object?.payment_status === 'paid'\n ) {\n const { hostId, bookingId } = object.metadata ?? {}\n if (hostId && bookingId) {\n const firestore = firebaseAdmin.app().firestore()\n const bookingRef = firestore\n .collection('hosts')\n .doc(String(hostId))\n .collection('bookings')\n .doc(String(bookingId))\n // WHAT THE CLIENT HANDED OVER, ALL OF IT. Tax included: this is the\n // ceiling `refund.ts` reverses against, and the client paid the tax\n // too — a net figure here would strand part of a refund.\n const paidAmountCents = Math.max(\n 0,\n Math.round(Number(object?.amount_total ?? 0)),\n )\n // THE MERCHANT'S SERVICE TAX, SEPARATED OUT (AGL-2028).\n //\n // `server.ts` charges the merchant's own service rate as an ordinary\n // `line_items[1]` Stripe is never told is tax (the AGL-1711\n // construction, which is what keeps the figure the MERCHANT's rather\n // than something computed against Aglyn's registrations). So\n // `amount_total` is service-plus-tax while Stripe's own tax fields\n // read zero, and the session's metadata is the only witness — exactly\n // as it is for a buy-now sale.\n const taxCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.taxCents ?? 0)),\n )\n // The merchant's REVENUE, which is the charge less the tax. Used for\n // the contact's lifetime value below: tax is collected on behalf of\n // an authority and is not money the business earned, so counting it\n // would over-state every service client's worth.\n const serviceCents = Math.max(0, paidAmountCents - taxCents)\n // WHAT A REFUND WILL NEED (AGL-2315). A paid booking is now a\n // destination charge to the merchant's connected account, and\n // reversing one requires the PaymentIntent — which lives only on this\n // event. The booking document recorded `paidAmountCents` and nothing\n // that identifies the charge, so a refund had no handle to pull and\n // the information was gone the moment the webhook returned. Unlike\n // most gaps this one cannot be backfilled from our own data later:\n // every booking taken before this line landed can only be refunded by\n // hand in the Stripe dashboard.\n //\n // `feeCents` is Aglyn's cut as CHARGED, read back off the session's\n // own metadata rather than re-derived from the org at refund time. The\n // rate follows the plan (AGL-2289's rule) and the plan moves, so\n // re-resolving it during a refund would reverse a share that was never\n // taken. `'0'` is a real recorded answer on the 0%-rate tiers.\n const paymentIntentId =\n typeof object?.payment_intent === 'string'\n ? object.payment_intent\n : String(object?.payment_intent?.id ?? '')\n const chargedFeeCents = Math.max(\n 0,\n Math.round(Number(object?.metadata?.feeCents ?? 0)),\n )\n // Redelivery guard (AGL-1755), the AGL-1748 shape. This was an\n // unconditional merge-set with no status check at all — idempotent\n // only by accident, because every value it wrote was fixed. A\n // redelivery re-sent the guest's confirmation and re-metered it, and\n // the moment this handler carries money to a contact the accident stops\n // holding: `purchaseCents` is a `FieldValue.increment`, so every retry\n // would inflate the customer's lifetime value.\n //\n // Keyed on the STATUS, not on the document existing: `server.ts` writes\n // the booking as `pendingPayment` BEFORE it opens the Stripe session,\n // so existence is guaranteed by the time any event arrives and proves\n // nothing — the AGL-1748 reasoning, not AGL-1732's `checkoutSessionId`\n // key, which existed because a sibling event wrote the same path.\n //\n // The key is \"not yet confirmed\" rather than \"is pendingPayment\" on\n // purpose. The lapsed-hold sweeper in `server.ts` cancels a\n // `pendingPayment` booking after 24h, and refusing a payment that\n // landed anyway would take the money and record nothing; `confirmed` is\n // reachable for a PAID booking only by this handler having already run,\n // so it is an exact \"already processed\" test. The existence check is\n // new and deliberate: the old merge-set would CREATE a stub booking\n // from a metadata `bookingId` that pointed at nothing.\n let booking: Record<string, any> = {}\n const confirmedNow = await firestore.runTransaction(\n async (transaction) => {\n const snapshot = await transaction.get(bookingRef)\n if (!snapshot.exists) return false\n if (snapshot.get('status') === 'confirmed') return false\n // \"Already processed\" is WIDER than `confirmed` once money can\n // flow back out (AGL-2315). A refunded booking is moved off\n // `confirmed`, so a redelivery arriving afterwards would otherwise\n // read as unprocessed and re-confirm an appointment the merchant\n // has already cancelled and refunded — re-sending the guest a\n // confirmation for it and re-metering the email. Any evidence this\n // handler has run before is the real test, and a refund counter or\n // a recorded PaymentIntent is exactly that evidence.\n if (\n Number(snapshot.get('refundedCents') ?? 0) > 0 ||\n snapshot.get('paymentIntentId')\n ) {\n return false\n }\n booking = (snapshot.data() as any) ?? {}\n transaction.set(\n bookingRef,\n {\n status: 'confirmed',\n paidAmountCents,\n // WHICH TAX REGIME THIS BOOKING CARRIED (AGL-2028), on the\n // document the merchant reads — the stamp every other\n // storefront money door already carries (AGL-2451).\n //\n // DERIVED from the one shared derivation, never a constant.\n // A hand-written \"manual when the metadata says so\" would be\n // a second rule that can drift from the `storefrontTaxCollected`\n // row filed for the same Stripe id, which is the exact\n // disagreement AGL-2451 exists to prevent.\n //\n // TWO-ARGUMENT, because the manual line makes Stripe report\n // `total_details.amount_tax: 0` on a booking that really did\n // charge the client tax; the one-argument form would stamp\n // `none` on precisely those. `absent` remains a fourth state\n // meaning \"recorded before this shipped\".\n taxMode: pluginTaxProfile().taxModeOf(object, taxCents),\n // The figure itself. Absent rather than a defaulted `0` — a\n // zero written through `merge` is the AGL-1758 shape, and\n // this handler can re-enter (see the widened guard above).\n ...(taxCents > 0 ? { taxCents } : {}),\n // The refund handles (AGL-2315). Written inside the same\n // transaction as the status, so a booking can never read\n // `confirmed` while the means to refund it are missing.\n ...(paymentIntentId ? { paymentIntentId } : {}),\n feeCents: chargedFeeCents,\n // WHICH CHECKOUT PAID FOR THIS (AGL-2481). The guest's browser\n // comes back from Stripe holding a session id and nothing\n // else — a booking id was never in the return URL — so this is\n // what lets `booking-analytics.ts` answer \"what did I just\n // buy?\" for the merchant-side `purchase`, and it is written\n // here because the session id first exists on this event.\n //\n // Inside the transaction with the status on purpose: the\n // lookup refuses anything that is not `confirmed`, so a\n // booking can never be findable by session id while reading as\n // unpaid.\n ...(object?.id ? { checkoutSessionId: String(object.id) } : {}),\n // NOTE the absent `refundedCents: 0`. Seeding it here would be\n // the AGL-1758 shape: a defaulted field written through\n // `merge` destroying the real one. This handler can re-enter\n // after a refund has already accumulated a counter (see the\n // widened guard above), and a zero written back over it would\n // re-open the full amount for refunding a second time. Absent\n // IS zero — every reader coerces with `?? 0`.\n expiresAtMs: firebaseAdmin.firestore.FieldValue.delete(),\n confirmedAt:\n firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n },\n { merge: true },\n )\n // The booking is confirmed now, in this transaction (AGL-3643).\n const nowMs = Date.now()\n stageBookingEvent(transaction, firestore, {\n event: 'booking.created',\n hostId: String(hostId),\n bookingId: String(bookingId),\n booking: {\n ...booking,\n status: 'confirmed',\n paidAmountCents,\n ...(taxCents > 0 ? { taxCents } : {}),\n expiresAtMs: null,\n },\n nowMs,\n })\n return true\n },\n )\n if (!confirmedNow) return\n // THE RECORD'S MEETING (AGL-2660). Payment is what confirms a paid\n // booking, so this is where it reaches the CRM: the meeting on the\n // record's timeline and, when the service asks, the follow-up task.\n // Inside the idempotency gate for the same reason the GA4 purchase\n // below is — a redelivery must not file a second meeting — and\n // through `after()` for the same reason too: this invocation is\n // frozen the moment the response is sent (AGL-2327). Never thrown:\n // the writer swallows its own failures, and the catch is for the\n // scheduling itself.\n after(() =>\n fileBookingOnCrm(firestore, {\n hostId: String(hostId),\n bookingId: String(bookingId),\n booking,\n }).catch(() => undefined),\n )\n // AGLYN'S REVENUE ON THIS BOOKING (AGL-2481) — into OUR GA4 property.\n //\n // ## Why it is inside the idempotency gate rather than beside it\n //\n // This sits AFTER `if (!confirmedNow) return` and that placement is the\n // whole guard. Stripe redelivers `checkout.session.completed` for up to\n // three days after any 500, and this endpoint 500s on purpose; a\n // redelivery re-enters this handler, the transaction above sees a\n // `confirmed` status (or a refund counter, or a recorded PaymentIntent)\n // and answers false, and everything below — the contact, the email, and\n // now this — is skipped. A `purchase` fired before that gate, or beside\n // it, would inflate our own reported revenue by the redelivery rate.\n //\n // `transaction_id` is the checkout session id, which is the same key\n // the guard turns on, so GA4's own de-duplication is a second\n // independent line of defence: even if the Firestore guard were ever\n // bypassed, GA would collapse the repeats.\n //\n // ## Platform NET, and the fee is the measured one\n //\n // `value` is our fee and not the $95 the guest paid — the AGL-1639\n // settlement. This is our property, the subscription and marketplace\n // `purchase` events in it already mean \"what Aglyn was paid\", and a\n // gross booking figure sitting beside them would make every combined\n // total, ARPA and revenue audience wrong. The merchant's own gross goes\n // to the MERCHANT's property, client-side, and the two never meet.\n //\n // The figure comes off the session's `metadata.feeCents` — the fee\n // Stripe actually charged as `application_fee_amount` — never from the\n // plan's rate re-applied here. See `bookingPlatformNetCents`.\n //\n // ## Scheduling and failure posture\n //\n // `after()`, never a bare `void` (AGL-2327/AGL-2346): this runs inside\n // the console's `/api/billing/webhook` invocation, which is frozen the\n // moment the response is sent, so fire-and-forget work scheduled any\n // other way simply does not run — the exact way marketplace revenue\n // reported to nothing. And `.catch()`, because a throw here would\n // un-claim the Stripe event and turn a missed analytics hit into a\n // repeated billing side effect.\n if (shouldSendBookingPlatformPurchase(object)) {\n const netCents = bookingPlatformNetCents(object)\n after(() =>\n sendGa4Purchase({\n transactionId: String(object?.id ?? ''),\n value: netCents / 100,\n currency: String(object?.currency ?? 'usd'),\n items: [\n {\n // Ids only, no merchant free text. A service name is\n // merchant-authored and one edit away from carrying a\n // person's name into a dimension in OUR property; the id\n // already identifies it. The merchant's own property gets\n // the name, because there it is their own content.\n item_id: String(booking['serviceId'] ?? bookingId),\n item_name: String(booking['serviceId'] ?? bookingId),\n item_category: 'booking',\n // GA expects the items to sum to `value`; one item, one\n // price, and that price is our fee — not the service's.\n price: netCents / 100,\n quantity: 1,\n },\n ],\n // Booking sessions carry no `ga_client_id` today — nothing\n // captures one on a tenant site — so this is read for the day\n // one is stamped and the seed below is what actually resolves.\n clientId: object?.metadata?.ga_client_id,\n // ONE PAYING GUEST, ONE SYNTHETIC USER. Seeded from Stripe's\n // customer where there is one, and otherwise from the guest's\n // email, which `server.ts` passes as `customer_email` and Stripe\n // echoes on `customer_details`. The seed is hashed inside\n // `synthesizeClientId` and never transmitted.\n //\n // The booking id is the LAST resort deliberately: it is unique\n // per appointment, so seeding from it would turn a regular\n // client into a crowd of one-purchase strangers and make ARPA\n // nonsense — precisely what that helper's determinism exists to\n // prevent. Without any seed at all `sendGa4Purchase` returns\n // `no-client-id` and the event is silently never sent, which is\n // the void this whole change exists to close.\n stripeCustomerId:\n String(object?.customer ?? '') ||\n String(object?.customer_details?.email ?? '') ||\n String(bookingId),\n }).catch(() => undefined),\n )\n }\n // Contacts ingestion (AGL-1755). `server.ts` captures the contact at\n // REQUEST time, which is the right place — the booking is written\n // `pendingPayment` and at that moment no money has moved, so passing an\n // amount there would be a lie. But payment completes HERE, and this\n // handler never returned to the contact, so a paid booking's money\n // reached the booking document and nothing else. The same structural\n // shape as AGL-1748's draft branch: the completion handler does\n // everything except the contact.\n //\n // `source` stays `'booking'` — the same source the request-time capture\n // used — so the `sources` map still says where this person came from\n // and no schema change is needed to keep service revenue\n // distinguishable from product revenue. The second interaction is\n // deliberate rather than a duplicate: \"Booked X\" and \"Paid for X\" are\n // two real events, and `mergeContactInteraction` does not dedupe on\n // `refId`.\n //\n // The amount is `amount_total`, the money that moved, per AGL-1698 and\n // AGL-1711 — the booking document stores no price to re-derive it from.\n if (booking['email']) {\n void recordCapturedContact({\n orgId: '',\n hostId: String(hostId),\n identity: {\n email: booking['email'],\n ...(booking['name'] ? { name: String(booking['name']) } : {}),\n },\n // Paid, so a relationship (AGL-3232): the lead the request-time\n // capture filed for the address is closed onto the contact.\n surface: 'relationship',\n // The phone the booking form asked for (AGL-3493), onto the\n // contact only where it holds none — as the request-time\n // capture put it on the lead.\n ...(readBookingPhone(booking['phone'])\n ? { profileFill: { phone: readBookingPhone(booking['phone']) } }\n : {}),\n // Paid, so a customer (AGL-2612) — the request-time capture\n // said `lead`, and this is the door that has seen the money.\n lifecycleFloor: 'customer',\n // The SERVICE, not the charge (AGL-2028). `amount_total` now\n // includes the merchant's service tax where they set one, and\n // tax is collected for an authority rather than earned — booking\n // it as lifetime value would over-state what every service\n // client is worth. Identical to `paidAmountCents` on the default\n // store, which sets no rate.\n ...(serviceCents > 0 ? { purchaseCents: serviceCents } : {}),\n interaction: {\n source: 'booking',\n refId: String(bookingId),\n summary: `Paid for \"${String(\n booking['serviceName'] ?? 'a service',\n ).slice(0, 60)}\" ($${(serviceCents / 100).toFixed(2)})`,\n },\n })\n }\n // In the booking's own zone, and named (AGL-3432): a formatter with\n // no zone reads in the server's — UTC — and tells a paying guest the\n // wrong hour, and an empty zone prints \"()\".\n const timezone = await bookingTimeZoneFor(\n firestore,\n String(hostId),\n booking,\n )\n const when = formatBookingWhen(Number(booking['startsAtMs']), timezone)\n const paid = `$${(paidAmountCents / 100).toFixed(2)}`\n // The site's managers hear of a PAID booking too (AGL-3500): the\n // free path tells them when the request lands, and a paid one is\n // only a booking once this event has cleared the charge, so this is\n // its moment. Who, what, when, what was paid, and the phone and\n // address the service asked for.\n const contactLines = bookingContactLines(booking)\n void notifyHostManagers(String(hostId), {\n type: 'content.booking',\n title: 'New booking on {site}',\n body:\n `${String(booking['name'] ?? '') || 'A guest'}` +\n (booking['email'] ? ` (${String(booking['email'])})` : '') +\n ` booked ${String(booking['serviceName'] ?? '') || 'a service'} ` +\n `on {site} for ${when} (${timezone}). ${paid} was paid.` +\n (contactLines.length ? ` ${contactLines.join('. ')}.` : ''),\n link: `/${hostId}/bookings`,\n })\n // Confirmation email now that payment cleared (env-gated inside\n // sendEmail, which no-ops when Resend isn't configured).\n if (booking['email']) {\n const fallbackText =\n `Hi ${booking['name'] ?? ''},\\n\\nPayment received — ` +\n `\"${booking['serviceName'] ?? 'your booking'}\" is ` +\n `confirmed for ${when} (${timezone}). You paid ${paid}.` +\n `\\n\\nReference: ${bookingId}`\n // Site-owner-designed template when published (AGL-770); null keeps\n // the built-in copy.\n const designed = await renderHostEmailWithTokens(\n firebaseAdmin.app().firestore(),\n String(hostId),\n 'booking-confirmed',\n {\n name: String(booking['name'] ?? ''),\n 'service.name': String(booking['serviceName'] ?? ''),\n when,\n timezone,\n 'booking.payment': `You paid ${paid}.`,\n 'booking.ref': String(bookingId),\n },\n )\n // White-label sender identity (White-Label Phase 3), matching the\n // free-booking path — the store's brand via the one shared resolver.\n const branding = resolveBrandingProfile(\n (await getOrgForHost(String(hostId)).catch(() => null))?.org as never,\n )\n await sendEmail({\n to: String(booking['email']),\n subject:\n designed?.subject ??\n `Booking confirmed: ${booking['serviceName'] ?? ''}`,\n text: designed?.text || fallbackText,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(String(hostId)),\n audience: 'tenant',\n context: 'paid booking confirmation',\n // Owed to the recipient by their own booking: the phishing\n // screen's soft rules never hold it (AGL-3356).\n owedFor: 'booking',\n })\n // Cost meter (AGL-1438), matching the free-booking path.\n // Transactional: the guest has already paid.\n await meterHostEmail(String(hostId))\n }\n }\n }\n}\n"],"names":["after","resolveBrandingProfile","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","notifyHostManagers","notifyRiskEvent","renderHostEmailWithTokens","sendGa4Purchase","paymentRiskEventFrom","recordPaymentRiskOnRecord","settlePaymentRiskDisputeOnRecord","reverseDestinationTransfer","recordCapturedContact","bookingPlatformNetCents","shouldSendBookingPlatformPurchase","sendEmail","pluginTaxProfile","fileBookingOnCrm","stageBookingEvent","bookingTimeZoneFor","formatBookingWhen","bookingContactLines","readBookingPhone","GRPC_FAILED_PRECONDITION","findBookingForPayment","paymentIntentId","matches","app","firestore","collectionGroup","where","limit","get","catch","error","code","console","docs","length","reverseBookingSellerShare","bookingRef","dispute","disputeId","String","id","amountCents","Math","max","round","Number","amount","cents","settled","prior","failedReason","outcome","kind","chargeId","charge","metadata","bookingId","record","reversedTransferCents","reversalId","transferReversalId","atMs","Date","now","reason","owedCents","wrote","runTransaction","transaction","fresh","exists","current","set","disputeReversal","merge","bookingsBillingWebhookHandler","type","object","risk","booking","hostId","ref","parent","signal","subjectLabel","link","notificationType","isFinite","toFixed","evidenceDueByMs","evidence_details","due_by","notifyRisk","claimed","payment_intent","status","recovered","recoveredText","guest","trim","service","title","body","undefined","payment_status","collection","doc","paidAmountCents","amount_total","taxCents","serviceCents","chargedFeeCents","feeCents","confirmedNow","snapshot","data","taxMode","taxModeOf","checkoutSessionId","expiresAtMs","FieldValue","delete","confirmedAt","serverTimestamp","nowMs","event","netCents","transactionId","value","currency","items","item_id","item_name","item_category","price","quantity","clientId","ga_client_id","stripeCustomerId","customer","customer_details","email","orgId","identity","name","surface","profileFill","phone","lifecycleFloor","purchaseCents","interaction","source","refId","summary","slice","timezone","when","paid","contactLines","join","fallbackText","designed","branding","org","to","subject","text","html","fromName","sendingIdentity","audience","context","owedFor"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,8EAA8E;AAC9E,4EAA4E;AAC5E,oDAAoD;AACpD,SAASA,KAAK,QAAQ,cAAa;AAGnC,SAASC,sBAAsB,QAAQ,sBAAqB;AAC5D,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,kBAAkB,EAClBC,eAAe,EACfC,yBAAyB,EACzBC,eAAe,QACV,2BAA0B;AACjC,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SACEC,yBAAyB,EACzBC,gCAAgC,QAC3B,sDAAqD;AAC5D,SACEC,0BAA0B,QAErB,2DAA0D;AACjE,OAAOC,2BAA2B,sDAAqD;AACvF,SACEC,uBAAuB,EACvBC,iCAAiC,QAC5B,yCAAqC;AAC5C,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,gBAAgB,QAAQ,iDAAgD;AACjF,SAASC,gBAAgB,QAAQ,mBAAe;AAChD,SAASC,iBAAiB,QAAQ,sBAAkB;AACpD,SAASC,kBAAkB,QAAQ,yBAAqB;AACxD,SAASC,iBAAiB,QAAQ,2BAAuB;AACzD,SACEC,mBAAmB,EACnBC,gBAAgB,QACX,qCAAiC;AAExC;;;;CAIC,GACD,iFAAiF,GACjF,MAAMC,2BAA2B;AAEjC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C,QAAOwC,wBAAAA,OAAO,CAAC,cAAc,YAAtBA,wBAA0B;oBACjD6E;oBACAD;oBACA,mBAAmB,CAAC,SAAS,EAAEE,KAAK,CAAC,CAAC;oBACtC,eAAetH,OAAOiB;gBACxB;gBAEF,kEAAkE;gBAClE,qEAAqE;gBACrE,MAAM0G,WAAWvK,wBACd,QAAA,MAAME,cAAc0C,OAAOyC,SAASnD,KAAK,CAAC,IAAM,0BAAjD,AAAC,MAAwDsI,GAAG;gBAE9D,MAAMxJ,UAAU;oBACdyJ,IAAI7H,OAAOwC,OAAO,CAAC,QAAQ;oBAC3BsF,OAAO,YACLJ,4BAAAA,SAAUI,OAAO,qBACjB,CAAC,mBAAmB,GAAEtF,wBAAAA,OAAO,CAAC,cAAc,YAAtBA,wBAA0B,IAAI;oBACtDuF,MAAML,CAAAA,4BAAAA,SAAUK,IAAI,KAAIN;mBACpBC,CAAAA,4BAAAA,SAAUM,IAAI,IAAG;oBAAEA,MAAMN,SAASM,IAAI;gBAAC,IAAI,CAAC;oBAChDC,UAAUN,SAASM,QAAQ;oBAC3BC,iBAAiB,MAAM3K,oBAAoByC,OAAOyC;oBAClD0F,UAAU;oBACVC,SAAS;oBACT,2DAA2D;oBAC3D,gDAAgD;oBAChDC,SAAS;;gBAEX,yDAAyD;gBACzD,6CAA6C;gBAC7C,MAAM7K,eAAewC,OAAOyC;YAC9B;QACF;IACF;AACJ,EAAC"}
|
|
@@ -0,0 +1,40 @@
|
|
|
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 PluginEventWriter } from '@aglyn/tenant-data-admin/server/plugin-event-outbox';
|
|
18
|
+
import { type BookingEventName } from '../model/booking-events';
|
|
19
|
+
/**
|
|
20
|
+
* Raising the booking events (AGL-3643). See `model/booking-events.ts` for
|
|
21
|
+
* what each means. A raiser with a transaction stages its event in it, so
|
|
22
|
+
* the event exists exactly when the fact does; one without raises it after
|
|
23
|
+
* the write, keyed, so a retried request raises it once.
|
|
24
|
+
*/
|
|
25
|
+
export interface BookingEventInput {
|
|
26
|
+
event: BookingEventName;
|
|
27
|
+
hostId: string;
|
|
28
|
+
bookingId: string;
|
|
29
|
+
/** The booking AS WRITTEN: the stored fields with this change applied. */
|
|
30
|
+
booking: Record<string, unknown>;
|
|
31
|
+
nowMs?: number;
|
|
32
|
+
}
|
|
33
|
+
/** Stages the event inside the caller's transaction or batch. */
|
|
34
|
+
export declare function stageBookingEvent(writer: PluginEventWriter, firestore: FirebaseFirestore.Firestore, input: BookingEventInput): string;
|
|
35
|
+
/**
|
|
36
|
+
* Raises the event after the fact is written. Never throws: the booking has
|
|
37
|
+
* already changed, and a lost event is logged by the outbox rather than
|
|
38
|
+
* failing the guest's or the team's request.
|
|
39
|
+
*/
|
|
40
|
+
export declare function raiseBookingEvent(firestore: FirebaseFirestore.Firestore, input: BookingEventInput): Promise<void>;
|
|
@@ -0,0 +1,50 @@
|
|
|
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 { raisePluginEvent, stagePluginEvent } from "@aglyn/tenant-data-admin/server/plugin-event-outbox";
|
|
17
|
+
import { BUNDLE_ID } from "../constants/bundle-common.js";
|
|
18
|
+
import { bookingEventKey } from "../model/booking-events.js";
|
|
19
|
+
import { bookingViewFromData } from "../model/booking-view.js";
|
|
20
|
+
function requestFor(input) {
|
|
21
|
+
var _input_nowMs, _input_booking_startsAtMs;
|
|
22
|
+
const nowMs = (_input_nowMs = input.nowMs) != null ? _input_nowMs : Date.now();
|
|
23
|
+
const payload = {
|
|
24
|
+
booking: bookingViewFromData(input.bookingId, input.booking, nowMs)
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
event: input.event,
|
|
28
|
+
pluginId: BUNDLE_ID,
|
|
29
|
+
hostId: input.hostId,
|
|
30
|
+
payload,
|
|
31
|
+
key: bookingEventKey(input.event, input.bookingId, Number((_input_booking_startsAtMs = input.booking['startsAtMs']) != null ? _input_booking_startsAtMs : 0)),
|
|
32
|
+
occurredAtMs: nowMs
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** Stages the event inside the caller's transaction or batch. */ export function stageBookingEvent(writer, firestore, input) {
|
|
36
|
+
return stagePluginEvent(writer, firestore, requestFor(input), input.nowMs);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Raises the event after the fact is written. Never throws: the booking has
|
|
40
|
+
* already changed, and a lost event is logged by the outbox rather than
|
|
41
|
+
* failing the guest's or the team's request.
|
|
42
|
+
*/ export async function raiseBookingEvent(firestore, input) {
|
|
43
|
+
try {
|
|
44
|
+
await raisePluginEvent(firestore, requestFor(input), input.nowMs);
|
|
45
|
+
} catch (error) {
|
|
46
|
+
console.error('[bookings] event not raised', input.event, input.hostId, input.bookingId, error);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
//# sourceMappingURL=booking-events.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/booking-events.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n raisePluginEvent,\n stagePluginEvent,\n type PluginEventWriter,\n} from '@aglyn/tenant-data-admin/server/plugin-event-outbox'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { bookingEventKey, type BookingEventName, type BookingEventPayload } from '../model/booking-events'\nimport { bookingViewFromData } from '../model/booking-view'\n\n/**\n * Raising the booking events (AGL-3643). See `model/booking-events.ts` for\n * what each means. A raiser with a transaction stages its event in it, so\n * the event exists exactly when the fact does; one without raises it after\n * the write, keyed, so a retried request raises it once.\n */\n\nexport interface BookingEventInput {\n event: BookingEventName\n hostId: string\n bookingId: string\n /** The booking AS WRITTEN: the stored fields with this change applied. */\n booking: Record<string, unknown>\n nowMs?: number\n}\n\nfunction requestFor(input: BookingEventInput) {\n const nowMs = input.nowMs ?? Date.now()\n const payload: BookingEventPayload = { booking: bookingViewFromData(input.bookingId, input.booking, nowMs) }\n return {\n event: input.event,\n pluginId: BUNDLE_ID,\n hostId: input.hostId,\n payload,\n key: bookingEventKey(input.event, input.bookingId, Number(input.booking['startsAtMs'] ?? 0)),\n occurredAtMs: nowMs,\n }\n}\n\n/** Stages the event inside the caller's transaction or batch. */\nexport function stageBookingEvent(\n writer: PluginEventWriter,\n firestore: FirebaseFirestore.Firestore,\n input: BookingEventInput,\n): string {\n return stagePluginEvent(writer, firestore, requestFor(input), input.nowMs)\n}\n\n/**\n * Raises the event after the fact is written. Never throws: the booking has\n * already changed, and a lost event is logged by the outbox rather than\n * failing the guest's or the team's request.\n */\nexport async function raiseBookingEvent(\n firestore: FirebaseFirestore.Firestore,\n input: BookingEventInput,\n): Promise<void> {\n try {\n await raisePluginEvent(firestore, requestFor(input), input.nowMs)\n } catch (error) {\n console.error('[bookings] event not raised', input.event, input.hostId, input.bookingId, error)\n }\n}\n"],"names":["raisePluginEvent","stagePluginEvent","BUNDLE_ID","bookingEventKey","bookingViewFromData","requestFor","input","nowMs","Date","now","payload","booking","bookingId","event","pluginId","hostId","key","Number","occurredAtMs","stageBookingEvent","writer","firestore","raiseBookingEvent","error","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,gBAAgB,QAEX,sDAAqD;AAC5D,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SAASC,eAAe,QAAyD,6BAAyB;AAC1G,SAASC,mBAAmB,QAAQ,2BAAuB;AAkB3D,SAASC,WAAWC,KAAwB;QAC5BA,cAO8CA;IAP5D,MAAMC,SAAQD,eAAAA,MAAMC,KAAK,YAAXD,eAAeE,KAAKC,GAAG;IACrC,MAAMC,UAA+B;QAAEC,SAASP,oBAAoBE,MAAMM,SAAS,EAAEN,MAAMK,OAAO,EAAEJ;IAAO;IAC3G,OAAO;QACLM,OAAOP,MAAMO,KAAK;QAClBC,UAAUZ;QACVa,QAAQT,MAAMS,MAAM;QACpBL;QACAM,KAAKb,gBAAgBG,MAAMO,KAAK,EAAEP,MAAMM,SAAS,EAAEK,QAAOX,4BAAAA,MAAMK,OAAO,CAAC,aAAa,YAA3BL,4BAA+B;QACzFY,cAAcX;IAChB;AACF;AAEA,+DAA+D,GAC/D,OAAO,SAASY,kBACdC,MAAyB,EACzBC,SAAsC,EACtCf,KAAwB;IAExB,OAAOL,iBAAiBmB,QAAQC,WAAWhB,WAAWC,QAAQA,MAAMC,KAAK;AAC3E;AAEA;;;;CAIC,GACD,OAAO,eAAee,kBACpBD,SAAsC,EACtCf,KAAwB;IAExB,IAAI;QACF,MAAMN,iBAAiBqB,WAAWhB,WAAWC,QAAQA,MAAMC,KAAK;IAClE,EAAE,OAAOgB,OAAO;QACdC,QAAQD,KAAK,CAAC,+BAA+BjB,MAAMO,KAAK,EAAEP,MAAMS,MAAM,EAAET,MAAMM,SAAS,EAAEW;IAC3F;AACF"}
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import type { PluginApiHandler } from '@aglyn/aglyn/app-utils/api-plugins';
|
|
18
18
|
import { type HostBookingService } from '../model/bookings';
|
|
19
|
+
import { type BookingEventInput } from './booking-events';
|
|
19
20
|
/** The Firestore surface these routes use: the Admin SDK's, narrowed so a spec can hand in a double. */
|
|
20
21
|
export interface ManageDocSnapshot {
|
|
21
22
|
readonly exists: boolean;
|
|
@@ -65,12 +66,27 @@ export interface BookingManageDeps {
|
|
|
65
66
|
timeZoneFor: (hostId: string, service: HostBookingService | undefined) => Promise<string>;
|
|
66
67
|
notifyRescheduled: (notice: RescheduleNotice) => Promise<void>;
|
|
67
68
|
now: () => number;
|
|
69
|
+
/**
|
|
70
|
+
* Raises a booking event once the change is written (AGL-3643): the move,
|
|
71
|
+
* the cancel. Never throws. Absent, nothing is raised.
|
|
72
|
+
*/
|
|
73
|
+
raiseEvent?: (input: BookingEventInput) => Promise<void>;
|
|
68
74
|
}
|
|
69
75
|
/** Field the booking stamps when the guest arrives. */
|
|
70
76
|
export declare const CHECKED_IN_AT = "checkedInAtMs";
|
|
71
77
|
export declare const CHECKED_IN_BY = "checkedInBy";
|
|
72
78
|
export declare function createBookingCheckInHandler(deps: BookingManageDeps): PluginApiHandler;
|
|
73
79
|
export declare function createBookingRescheduleHandler(deps: BookingManageDeps): PluginApiHandler;
|
|
80
|
+
/**
|
|
81
|
+
* Canceling a booking that has no money on it (AGL-3643): a free booking, or
|
|
82
|
+
* a paid one already refunded in full. The site's team used to write
|
|
83
|
+
* `status: 'canceled'` straight from the console; a route is where the
|
|
84
|
+
* cancel can be told to the plugins that listen for it (`booking.canceled`),
|
|
85
|
+
* and where the rule that a paid booking cancels through its refund is held
|
|
86
|
+
* rather than trusted to the screen. One transaction: a booking checked in
|
|
87
|
+
* or paid a moment ago is refused, and canceling it twice changes nothing.
|
|
88
|
+
*/
|
|
89
|
+
export declare function createBookingCancelHandler(deps: BookingManageDeps): PluginApiHandler;
|
|
74
90
|
/** The email that tells a guest their booking moved, as the confirmation is sent. */
|
|
75
91
|
export declare function sendRescheduledNotice(notice: RescheduleNotice): Promise<void>;
|
|
76
92
|
/** The production wiring: the Admin SDK, the site lockdown verdict and the real send. */
|
|
@@ -19,10 +19,11 @@ import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
|
|
|
19
19
|
import { firebaseAdmin, getOrgForHost, hostSendingIdentity, meterHostEmail, renderHostEmailWithTokens } from "@aglyn/tenant-data-admin";
|
|
20
20
|
import { getSiteLockdown } from "@aglyn/tenant-data-admin/server/tenant-write-lockdown";
|
|
21
21
|
import { resolveBrandingProfile } from "@aglyn/aglyn/server";
|
|
22
|
-
import { bookingDurationMs, checkInRefusal, rescheduleRefusal } from "../model/booking-manage.js";
|
|
22
|
+
import { bookingDurationMs, bookingState, cancelRefusal, checkInRefusal, rescheduleRefusal } from "../model/booking-manage.js";
|
|
23
23
|
import { isSlotOpen } from "../model/bookings.js";
|
|
24
24
|
import { bookingTimeZone, formatBookingWhen, storedBookingTimeZone } from "../model/booking-time.js";
|
|
25
25
|
import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
|
|
26
|
+
import { raiseBookingEvent } from "./booking-events.js";
|
|
26
27
|
/** Field the booking stamps when the guest arrives. */ export const CHECKED_IN_AT = 'checkedInAtMs';
|
|
27
28
|
export const CHECKED_IN_BY = 'checkedInBy';
|
|
28
29
|
let Refusal = class Refusal extends Error {
|
|
@@ -215,6 +216,17 @@ export function createBookingRescheduleHandler(deps) {
|
|
|
215
216
|
notified: false
|
|
216
217
|
});
|
|
217
218
|
}
|
|
219
|
+
// Keyed by the booking and its new time: a retried move raises it once.
|
|
220
|
+
await (deps.raiseEvent == null ? void 0 : deps.raiseEvent.call(deps, {
|
|
221
|
+
event: 'booking.rescheduled',
|
|
222
|
+
hostId,
|
|
223
|
+
bookingId,
|
|
224
|
+
booking: _extends({}, moved.booking, {
|
|
225
|
+
startsAtMs,
|
|
226
|
+
endsAtMs: moved.endsAtMs,
|
|
227
|
+
rescheduledFromMs: moved.previousStartsAtMs
|
|
228
|
+
})
|
|
229
|
+
}));
|
|
218
230
|
const to = String((_moved_booking_email = moved.booking['email']) != null ? _moved_booking_email : '').trim();
|
|
219
231
|
let notified = false;
|
|
220
232
|
if (to) {
|
|
@@ -251,6 +263,67 @@ export function createBookingRescheduleHandler(deps) {
|
|
|
251
263
|
}
|
|
252
264
|
};
|
|
253
265
|
}
|
|
266
|
+
/**
|
|
267
|
+
* Canceling a booking that has no money on it (AGL-3643): a free booking, or
|
|
268
|
+
* a paid one already refunded in full. The site's team used to write
|
|
269
|
+
* `status: 'canceled'` straight from the console; a route is where the
|
|
270
|
+
* cancel can be told to the plugins that listen for it (`booking.canceled`),
|
|
271
|
+
* and where the rule that a paid booking cancels through its refund is held
|
|
272
|
+
* rather than trusted to the screen. One transaction: a booking checked in
|
|
273
|
+
* or paid a moment ago is refused, and canceling it twice changes nothing.
|
|
274
|
+
*/ export function createBookingCancelHandler(deps) {
|
|
275
|
+
return async (req, res)=>{
|
|
276
|
+
var _body_hostId, _body_bookingId;
|
|
277
|
+
if (req.method !== 'POST') return res.status(405).json({
|
|
278
|
+
error: 'Method not allowed'
|
|
279
|
+
});
|
|
280
|
+
const body = bodyOf(req);
|
|
281
|
+
const hostId = String((_body_hostId = body['hostId']) != null ? _body_hostId : '');
|
|
282
|
+
const bookingId = String((_body_bookingId = body['bookingId']) != null ? _body_bookingId : '');
|
|
283
|
+
if (!hostId || !bookingId) return res.status(400).json({
|
|
284
|
+
error: 'Missing hostId or bookingId'
|
|
285
|
+
});
|
|
286
|
+
try {
|
|
287
|
+
const { uid } = await authorize(deps, req, hostId);
|
|
288
|
+
const firestore = deps.firestore();
|
|
289
|
+
const ref = firestore.doc(`hosts/${hostId}/bookings/${bookingId}`);
|
|
290
|
+
const canceled = await firestore.runTransaction(async (transaction)=>{
|
|
291
|
+
var _snapshot_data;
|
|
292
|
+
const snapshot = await transaction.get(ref);
|
|
293
|
+
if (!snapshot.exists) throw new Refusal(404, 'Unknown booking');
|
|
294
|
+
const booking = (_snapshot_data = snapshot.data()) != null ? _snapshot_data : {};
|
|
295
|
+
const nowMs = deps.now();
|
|
296
|
+
const refusal = cancelRefusal(booking, nowMs);
|
|
297
|
+
if (refusal) throw new Refusal(409, refusal);
|
|
298
|
+
// Already canceled: a retried tap writes nothing and tells no one twice.
|
|
299
|
+
if (bookingState(booking, nowMs) === 'canceled') return null;
|
|
300
|
+
transaction.update(ref, {
|
|
301
|
+
status: 'canceled',
|
|
302
|
+
canceledAtMs: nowMs,
|
|
303
|
+
canceledBy: uid
|
|
304
|
+
});
|
|
305
|
+
return _extends({}, booking, {
|
|
306
|
+
status: 'canceled',
|
|
307
|
+
canceledAtMs: nowMs
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
if (canceled) {
|
|
311
|
+
await (deps.raiseEvent == null ? void 0 : deps.raiseEvent.call(deps, {
|
|
312
|
+
event: 'booking.canceled',
|
|
313
|
+
hostId,
|
|
314
|
+
bookingId,
|
|
315
|
+
booking: canceled
|
|
316
|
+
}));
|
|
317
|
+
}
|
|
318
|
+
return res.status(200).json({
|
|
319
|
+
ok: true,
|
|
320
|
+
canceled: true
|
|
321
|
+
});
|
|
322
|
+
} catch (error) {
|
|
323
|
+
return answer(res, error);
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
}
|
|
254
327
|
/** The email that tells a guest their booking moved, as the confirmation is sent. */ export async function sendRescheduledNotice(notice) {
|
|
255
328
|
var _ref;
|
|
256
329
|
var _this;
|
|
@@ -299,7 +372,8 @@ export function createBookingRescheduleHandler(deps) {
|
|
|
299
372
|
});
|
|
300
373
|
},
|
|
301
374
|
notifyRescheduled: sendRescheduledNotice,
|
|
302
|
-
now: ()=>Date.now()
|
|
375
|
+
now: ()=>Date.now(),
|
|
376
|
+
raiseEvent: (input)=>raiseBookingEvent(firebaseAdmin.app().firestore(), input)
|
|
303
377
|
};
|
|
304
378
|
}
|
|
305
379
|
|