@aglyn/plugins-commerce 1.14.0 → 1.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/account-subscriptions.d.ts +51 -0
- package/src/lib/components/account-subscriptions.js +168 -0
- package/src/lib/components/account-subscriptions.js.map +1 -0
- package/src/lib/components/account.js +12 -48
- package/src/lib/components/account.js.map +1 -1
- package/src/lib/components/cart.js +38 -9
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/commerce-console-page.js +6 -0
- package/src/lib/components/commerce-console-page.js.map +1 -1
- package/src/lib/components/commerce-console-sections.d.ts +1 -1
- package/src/lib/components/commerce-console-sections.js +5 -0
- package/src/lib/components/commerce-console-sections.js.map +1 -1
- package/src/lib/components/console/paid-media.d.ts +1 -0
- package/src/lib/components/console/paid-media.js +15 -4
- package/src/lib/components/console/paid-media.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +1 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
- package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
- package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
- package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
- package/src/lib/components/console/pos-cellular-control.component.js +5 -5
- package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
- package/src/lib/components/console/pos-devices-card.component.js +2 -2
- package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
- package/src/lib/components/console/pos-hardware-card.component.js +77 -8
- package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
- package/src/lib/components/console/pos-page.component.js +19 -2
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +21 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
- package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
- package/src/lib/components/console/subscriptions-card.component.js +282 -0
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
- package/src/lib/components/hardware-terms-consent.d.ts +22 -0
- package/src/lib/components/hardware-terms-consent.js +85 -0
- package/src/lib/components/hardware-terms-consent.js.map +1 -0
- package/src/lib/components/product-detail.js +32 -8
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/quote-page-body.js +7 -3
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/related-products.js +6 -3
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/storefront-payment-element.d.ts +7 -1
- package/src/lib/components/storefront-payment-element.js +11 -7
- package/src/lib/components/storefront-payment-element.js.map +1 -1
- package/src/lib/constants/operator-alerts.d.ts +1 -1
- package/src/lib/constants/operator-alerts.js +4 -4
- package/src/lib/constants/operator-alerts.js.map +1 -1
- package/src/lib/model/commerce-orders.d.ts +6 -2
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-payment-methods.d.ts +27 -16
- package/src/lib/model/commerce-payment-methods.js +11 -83
- package/src/lib/model/commerce-payment-methods.js.map +1 -1
- package/src/lib/model/commerce.d.ts +6 -0
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/paid-media.d.ts +8 -0
- package/src/lib/model/paid-media.js +13 -0
- package/src/lib/model/paid-media.js.map +1 -1
- package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
- package/src/lib/model/pos-hardware-in-person.js +52 -20
- package/src/lib/model/pos-hardware-in-person.js.map +1 -1
- package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
- package/src/lib/model/pos-hardware-tax-summary.js +2 -1
- package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
- package/src/lib/model/pos-hardware-terms.d.ts +37 -2
- package/src/lib/model/pos-hardware-terms.js +68 -3
- package/src/lib/model/pos-hardware-terms.js.map +1 -1
- package/src/lib/model/pos-hardware.d.ts +101 -15
- package/src/lib/model/pos-hardware.js +128 -18
- package/src/lib/model/pos-hardware.js.map +1 -1
- package/src/lib/model/pos-reader-splash.js +2 -2
- package/src/lib/model/pos-reader-splash.js.map +1 -1
- package/src/lib/model/product-write.d.ts +3 -0
- package/src/lib/model/subscription-view.d.ts +90 -0
- package/src/lib/model/subscription-view.js +176 -0
- package/src/lib/model/subscription-view.js.map +1 -0
- package/src/lib/server/billing-webhook.d.ts +27 -6
- package/src/lib/server/billing-webhook.js +271 -81
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +4 -3
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/cart-checkout.js +105 -23
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.js +15 -3
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/catalog.js +58 -22
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout-session-expiry.d.ts +1 -1
- package/src/lib/server/checkout-session-expiry.js +19 -5
- package/src/lib/server/checkout-session-expiry.js.map +1 -1
- package/src/lib/server/checkout-status.js +4 -3
- package/src/lib/server/checkout-status.js.map +1 -1
- package/src/lib/server/checkout.js +98 -26
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect.js +42 -11
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/draft-order.js +36 -7
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/manual-tax-rate.d.ts +11 -3
- package/src/lib/server/manual-tax-rate.js +10 -6
- package/src/lib/server/manual-tax-rate.js.map +1 -1
- package/src/lib/server/membership-account.d.ts +22 -0
- package/src/lib/server/membership-account.js +52 -8
- package/src/lib/server/membership-account.js.map +1 -1
- package/src/lib/server/native-checkout.d.ts +10 -3
- package/src/lib/server/native-checkout.js +8 -3
- package/src/lib/server/native-checkout.js.map +1 -1
- package/src/lib/server/payment-method-domains.d.ts +50 -9
- package/src/lib/server/payment-method-domains.js +150 -51
- package/src/lib/server/payment-method-domains.js.map +1 -1
- package/src/lib/server/payment-methods.js +3 -2
- package/src/lib/server/payment-methods.js.map +1 -1
- package/src/lib/server/pos-auth.d.ts +3 -3
- package/src/lib/server/pos-auth.js +3 -3
- package/src/lib/server/pos-auth.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.js +1 -1
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular-notify.js +1 -1
- package/src/lib/server/pos-cellular-notify.js.map +1 -1
- package/src/lib/server/pos-cellular.js +1 -1
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-hardware-admin.js +86 -13
- package/src/lib/server/pos-hardware-admin.js.map +1 -1
- package/src/lib/server/pos-hardware-attach.js +5 -5
- package/src/lib/server/pos-hardware-attach.js.map +1 -1
- package/src/lib/server/pos-hardware-cancel.js +65 -0
- package/src/lib/server/pos-hardware-cancel.js.map +1 -1
- package/src/lib/server/pos-hardware-closure-notices.js +2 -5
- package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
- package/src/lib/server/pos-hardware-closure.js +5 -8
- package/src/lib/server/pos-hardware-closure.js.map +1 -1
- package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
- package/src/lib/server/pos-hardware-in-person.js +72 -17
- package/src/lib/server/pos-hardware-in-person.js.map +1 -1
- package/src/lib/server/pos-hardware-notify.d.ts +2 -0
- package/src/lib/server/pos-hardware-notify.js +30 -5
- package/src/lib/server/pos-hardware-notify.js.map +1 -1
- package/src/lib/server/pos-hardware-readers.d.ts +25 -0
- package/src/lib/server/pos-hardware-readers.js +206 -85
- package/src/lib/server/pos-hardware-readers.js.map +1 -1
- package/src/lib/server/pos-hardware-returns.d.ts +8 -3
- package/src/lib/server/pos-hardware-returns.js +39 -7
- package/src/lib/server/pos-hardware-returns.js.map +1 -1
- package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
- package/src/lib/server/pos-hardware-sale-fields.js +114 -1
- package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
- package/src/lib/server/pos-hardware-sale.d.ts +2 -0
- package/src/lib/server/pos-hardware-sale.js +1 -0
- package/src/lib/server/pos-hardware-sale.js.map +1 -1
- package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
- package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
- package/src/lib/server/pos-hardware-webhook.js +16 -3
- package/src/lib/server/pos-hardware-webhook.js.map +1 -1
- package/src/lib/server/pos-hardware.d.ts +14 -3
- package/src/lib/server/pos-hardware.js +83 -18
- package/src/lib/server/pos-hardware.js.map +1 -1
- package/src/lib/server/pos-ops-routes.js +2 -10
- package/src/lib/server/pos-ops-routes.js.map +1 -1
- package/src/lib/server/pos-order.js +5 -1
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +7 -7
- package/src/lib/server/pos-stripe.js +15 -13
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal.js +11 -3
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +23 -1
- package/src/lib/server/quote-pay.js +111 -27
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote.d.ts +2 -1
- package/src/lib/server/quote.js +12 -11
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +13 -6
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/related.js +10 -3
- package/src/lib/server/related.js.map +1 -1
- package/src/lib/server/reserve.js +19 -6
- package/src/lib/server/reserve.js.map +1 -1
- package/src/lib/server/revenue-source.d.ts +6 -0
- package/src/lib/server/revenue-source.js +25 -9
- package/src/lib/server/revenue-source.js.map +1 -1
- package/src/lib/server/seller-stripe-account.d.ts +45 -0
- package/src/lib/server/seller-stripe-account.js +99 -0
- package/src/lib/server/seller-stripe-account.js.map +1 -0
- package/src/lib/server/storefront-tax-record.js +6 -1
- package/src/lib/server/storefront-tax-record.js.map +1 -1
- package/src/lib/server/storefront-tax.d.ts +33 -2
- package/src/lib/server/storefront-tax.js +39 -3
- package/src/lib/server/storefront-tax.js.map +1 -1
- package/src/lib/server/stream.d.ts +2 -0
- package/src/lib/server/stream.js +22 -2
- package/src/lib/server/stream.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +15 -0
- package/src/lib/server/stripe-refund.js +54 -26
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server/subscription-portal.js +8 -3
- package/src/lib/server/subscription-portal.js.map +1 -1
- package/src/lib/server/tax-return-source.js +5 -1
- package/src/lib/server/tax-return-source.js.map +1 -1
- package/src/lib/server.js +2 -2
- package/src/lib/server.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/reserve.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 { readSiteReturnHost, siteReturnUrl } from '@aglyn/aglyn/app-utils/site-return-url'\nimport type { AttemptClaim, PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { claimAttempt } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { merchantAccountIsReady } from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { checkoutSessionCardAuthenticationParams } from '@aglyn/tenant-data-admin/server/stripe-card-authentication'\nimport {\n readLiveReservations,\n reservationAvailabilityQuery,\n reservationsOnPlan,\n} from './reservation-availability-query'\n\n/**\n * Reserve a stay (AGL-310): server-side quote + availability check,\n * pending reservation doc, then a Stripe session for the deposit (or\n * full amount) on the merchant's account. Webhook completion confirms\n * the reservation; abandoned pending holds expire after 30 minutes and\n * stop blocking the calendar.\n */\nexport const reserveHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const resourceId = String(body.resourceId ?? '')\n const checkInDayMs = CommerceModel.toDayMs(Number(body.checkInDayMs ?? 0))\n const checkOutDayMs = CommerceModel.toDayMs(Number(body.checkOutDayMs ?? 0))\n const guestName = String(body.guestName ?? '').trim().slice(0, 120)\n const guestEmail = String(body.guestEmail ?? '').trim().toLowerCase().slice(0, 120)\n // How many guests the stay is for (AGL-4043): optional, checked against\n // what the resource sleeps once it is read.\n const guestsAsked = body.guests === undefined || body.guests === null || body.guests === '' ? undefined : Number(body.guests)\n // One reservation attempt, minted by the widget (AGL-1697). Node lowercases\n // incoming headers, but read both spellings — the plugin API request type\n // makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n ).trim().slice(0, 200)\n if (!hostId || !resourceId || !checkInDayMs || !checkOutDayMs) {\n return res.status(400).json({ error: 'Missing reservation details' })\n }\n\n let claim: AttemptClaim | null = null\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n // Owner + payment readiness, HOISTED above the claim (AGL-1697): both are\n // deterministic refusals a merchant fixes out of band, and neither should\n // burn the guest's attempt key.\n const ownerOrg = await getOrgForHost(hostId)\n // Plan gate, re-asked per request exactly as the storefront checkout\n // asks it (AGL-1873, the AGL-481 pattern): a lapsed org's storefront\n // must not keep taking reservation deposits — at the free plan's 0%\n // transaction fee — through the one shopper-facing commerce door that\n // skipped the entitlement. Deterministic and merchant-side, so it sits\n // here above the claim with the readiness check.\n if (!reservationsOnPlan(ownerOrg?.org)) {\n return res.status(403).json({ error: 'Reservations are not enabled' })\n }\n const ownerId = ownerOrg?.org?.ownerUid\n const ownerProfile = ownerId\n ? await firestore.collection('profiles').doc(String(ownerId)).get()\n : null\n const accountId = ownerProfile?.get('stripeAccountId')\n if (\n !merchantAccountIsReady(\n {\n accountId,\n chargesEnabled: ownerProfile?.get('stripeChargesEnabled'),\n accountLivemode: ownerProfile?.get('stripeAccountLivemode'),\n },\n { subject: `reserve host ${hostId}` },\n )\n ) {\n return res.status(409).json({ error: 'Payments are not set up yet' })\n }\n\n // The claim sits ABOVE the availability read, and that placement is the\n // fix for this handler's particular lie (AGL-1697): a retried attempt used\n // to collide with its OWN 30-minute pending hold and be told \"Those dates\n // just sold out\" — about dates the guest was holding — where the correct\n // answer was the original session URL. Replaying here means the retry\n // never reaches the availability check at all. Every refusal below the\n // claim releases it, because each is deterministic and retryable.\n const claimed = await claimAttempt(firestore, {\n kind: 'commerce-reserve',\n scopeId: hostId,\n orgId: String(ownerOrg?.org?.id ?? ''),\n key: idempotencyKey,\n busyMessage: 'This reservation is already being processed',\n })\n if ('replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n claim = claimed.claim\n\n // ONLY STAYS THAT COULD STILL OVERLAP, NEAREST FIRST (AGL-2159).\n //\n // This was `.where('resourceId','==',resourceId).limit(500)` with no\n // ordering, so Firestore returned 500 documents in `__name__` order — an\n // arbitrary slice of the resource's ENTIRE booking history. Every stay the\n // resource has ever had competed for those 500 slots on equal terms with\n // the ones that matter, so a cottage that had taken 500 bookings began\n // silently dropping LIVE reservations out of its own availability check\n // and confirming a second guest into an occupied room. Nothing about that\n // failure is visible: `isRangeAvailable` is handed a short list and\n // answers, correctly, that the range is free.\n //\n // `checkOutDayMs > checkInDayMs` is the one inequality that removes the\n // whole of the past — a stay that ended before the requested arrival\n // cannot overlap it — and ordering by the same field puts the stays\n // nearest the requested window at the front of the limit rather than\n // whichever ones happen to sort early by id. Needs the composite index\n // `reservations (resourceId ASC, checkOutDayMs ASC)`, added to\n // `cloud/firebase-firestore.indexes.json` and pinned by\n // `reserve-availability-indexes.spec.ts` — an equality plus an `orderBy`\n // on a second field is exactly the shape that reads as free and is not\n // (AGL-1793), and here a missing index throws rather than under-reporting.\n //\n // RESIDUAL, stated: the cap can still bite when a single resource holds\n // more than 500 stays that all end between the requested arrival and the\n // end of a genuinely overlapping one. That is a far narrower window than\n // \"500 bookings in this resource's lifetime\", but it is not zero, and the\n // sweep that would keep expired `pending` holds from filling those slots\n // is a scheduled job this change does not add (see the commit).\n //\n // The query itself lives in `reservation-availability-query.ts`, shared\n // with the staff walk-in route (AGL-4046) so both doors ask one question.\n const availabilityQuery = reservationAvailabilityQuery(\n hostRef.collection('reservations'),\n resourceId,\n checkInDayMs,\n )\n const [resourceSnapshot, reservationsSnapshot, storeSnapshot] =\n await Promise.all([\n hostRef.collection('resources').doc(resourceId).get(),\n availabilityQuery.get(),\n // The merchant's own lodging rate (AGL-1969). Read in the SAME round\n // trip as the availability query rather than as a fourth sequential\n // await — this path already runs three reads before it can answer, and\n // a tax lookup is not a reason to make a guest wait for a fourth.\n hostRef.collection('settings').doc('store').get(),\n ])\n const resource = resourceSnapshot.data() as CommerceModel.HostResource | undefined\n if (!resource) {\n await claim.release()\n return res.status(404).json({ error: 'Unknown resource' })\n }\n\n // Pending holds block for 30 minutes only, so abandoned checkouts\n // release the dates. The lapse itself lives in\n // `reservationHoldsDates`, which `isRangeAvailable` applies — this reads\n // the fields that rule needs and leaves the rule to the model, so the\n // storefront's date-picker cannot answer a different question from the\n // door that takes the money.\n //\n // Extracted so the pre-read below and the re-read inside the booking\n // transaction cannot drift apart (AGL-2450). Two copies of a filter that\n // decides whether a room is free is exactly the shape where one of them\n // quietly stops matching the other.\n // The staff walk-in route reads through the same helper (AGL-4046).\n const readLive = readLiveReservations\n const now = Date.now()\n const live = readLive(reservationsSnapshot)\n if (\n !CommerceModel.isRangeAvailable(\n resource,\n live,\n checkInDayMs,\n checkOutDayMs,\n now,\n )\n ) {\n // A GENUINE sold-out (a keyed retry replayed before reaching here). The\n // guest picks other dates or the blocking stay is cancelled; either way\n // the key must survive the refusal.\n await claim.release()\n return res.status(409).json({ error: 'Those dates just sold out' })\n }\n const quote = CommerceModel.computeReservationQuote(\n resource,\n checkInDayMs,\n checkOutDayMs,\n )\n if (quote.problem) {\n await claim.release()\n return res.status(400).json({ error: quote.problem })\n }\n const guestsProblem = CommerceModel.reservationGuestsProblem(guestsAsked, resource)\n if (guestsProblem) {\n await claim.release()\n return res.status(400).json({ error: guestsProblem })\n }\n\n const chargeCents = quote.depositCents || quote.totalCents\n\n // NO DISCOUNT IS APPLIED HERE, AND THAT IS AN OPEN QUESTION RATHER THAN AN\n // OVERSIGHT (AGL-305).\n //\n // `hosts/{hostId}/discounts` reaches the cart, buy-now, the draft-order\n // payment link and the register. This door was deliberately left out,\n // because unlike those four it does not take a payment for goods — it takes\n // a DEPOSIT against a stay that is settled later, and \"apply 10% off\" has\n // three different meanings against that shape:\n //\n // 1. Discount the STAY. `quote.totalCents` falls, the deposit falls with\n // it because it is a percentage of the subtotal, and the balance falls\n // too. This is the only reading that is actually a discount on the\n // booking — and it reprices a merchant's lodging inventory from a\n // storefront promo code, which is a larger claim than any of the four\n // goods doors makes.\n // 2. Discount the DEPOSIT only. Strictly worse than doing nothing: the\n // balance is computed downstream as `totalCents - paidCents`, so every\n // cent taken off at booking is billed straight back at check-out. The\n // guest would be shown a discount and then charged for it, which is\n // the silent-reversal shape this codebase refuses elsewhere.\n // 3. Discount the BALANCE. Nothing visible at booking; the guest finds\n // out at the register. A promotion nobody can see when they buy is not\n // a promotion.\n //\n // What makes this a product decision and not an implementation one is that\n // the balance is not collected by any door this repo can teach. It is read\n // off the console's reservations card as `totalCents - paidCents` and\n // collected BY A HUMAN at the till, so option 1 is the only one that\n // survives the hand-off — and it survives it by changing the stay's stored\n // price, which is the merchant's revenue basis and what their analytics,\n // their folio and their register all read.\n //\n // The tax makes it sharper still. `lodgingTax` below is an occupancy rate,\n // not a sales rate, and its basis here is already a STATED LIMITATION — it\n // is charged on what is collected (the deposit) rather than on the stay.\n // Layering a discount on top asks whether occupancy tax is owed on the\n // discounted room rate or the gross one, which differs by jurisdiction, is\n // the merchant's own regime to answer, and is not a question this handler\n // can decide from a promo code.\n //\n // So: refusing to guess. A shopper who types a code here is not told it\n // worked — this path never reads one, so there is nothing to fall through\n // silently, which is the failure mode that mattered. When the owner picks\n // a reading, option 1 is the one the machinery already supports: reduce\n // `quote.subtotalCents` before the deposit is derived from it, and the\n // deposit, the balance, the fee and the tax all follow without further\n // change.\n\n // LODGING TAX: the MERCHANT'S OWN RATE, off unless they set one\n // (AGL-1969, answering the decision AGL-1953 recorded here).\n //\n // What this path used to do, and why it was only ever a holding position:\n // it computed no tax in either store mode, on two stated grounds. The\n // first is still true and is the reason for the shape below — a stay is\n // not goods. The AGL-285 zone editor configures a SALES rate, lodging is\n // an occupancy/hotel regime with its own rates, its own registration and\n // its own return, and reading `rates[]` for a night would be confidently\n // wrong rather than merely absent. Stripe Tax has the mirror problem: it\n // needs a lodging tax code this handler does not send, so\n // `automatic_tax` here would compute a goods rate on a room. Neither of\n // those changes, and neither is used.\n //\n // What DID change is that the merchant now has a field of their own to\n // answer in (`tax.lodging`), so \"Aglyn does not know the right number\"\n // stops being a reason to collect nothing. They type the rate, we compute\n // it, charge it, record it and stamp the regime; the settings card states\n // plainly that determining what is owed and to whom is theirs. Aglyn\n // takes no tax position here — this is the manual LODGING rate, which\n // never touches Aglyn's registrations.\n //\n // ⚠️ This comment used to say \"Terms §10.3 ... untouched by this\". §10.3\n // CHANGED on 2026-08-24 (AGL-1956): Aglyn accepts marketplace-facilitator\n // status and new §10.7 makes storefront sales tax Aglyn's where it has a\n // collection obligation. Lodging tax is still the merchant's, so this\n // handler is unaffected — but §10.3 is no longer the authority for that.\n //\n // DEFAULT OFF, and that is load-bearing: `resolveFlatTaxCents` answers\n // zero for an absent, zero, negative or out-of-range rate, so no existing\n // reservation's charge moves because this shipped.\n //\n // THE BASIS IS WHAT IS CHARGED, AND THAT IS A STATED LIMITATION RATHER\n // THAN AN ANSWER. `chargeCents` is `depositCents || totalCents`, so on a\n // deposit-taking resource the tax collected here is the rate on the\n // DEPOSIT, not on the stay. Whether a given jurisdiction wants occupancy\n // tax on the full stay at booking, on the deposit only, or on redemption\n // at check-out is a tax question, it differs by jurisdiction, and this\n // code deliberately does NOT decide it — the amount the platform actually\n // moves is the only basis available to it, the settings card says so in\n // the merchant's own view, and the residual is on AGL-1969.\n const taxSettings = ((storeSnapshot.data() as any)?.tax ??\n {}) as CommerceModel.TaxSettings\n const lodgingTax = CommerceModel.resolveFlatTaxCents(\n taxSettings.lodging,\n chargeCents,\n 'Lodging tax',\n )\n\n // Platform take PLUS Stripe's card cost at cost (AGL-2152). This is a\n // destination charge, so Stripe debits its percentage plus 30¢ from the\n // PLATFORM's balance; with the old take-only figure every tier carrying a\n // 0% service rate paid Aglyn nothing and cost it that fee on each\n // reservation.\n //\n // THE TWO BASES ARE NOW DIFFERENT NUMBERS (AGL-1969), and the split is\n // AGL-2317's rule: the platform take is computed on the ITEMS — the stay\n // — while Stripe's cost is passed through on the WHOLE charge, because\n // that is what Stripe actually debits. Taking a percentage of the lodging\n // tax would be taking a cut of the state's money, which no storefront\n // path does. The previous single-argument form is what made this a real\n // risk: it read as \"the fee base is the charge\" and would have silently\n // started taxing the tax the moment a tax line appeared.\n const feeCents = Aglyn.resolveTransactionFeeCents(\n ownerOrg?.org as any,\n 'service',\n chargeCents,\n chargeCents + lodgingTax.taxCents,\n )\n\n // THE HOLD IS TAKEN IN A TRANSACTION (AGL-2450).\n //\n // The check above is a fast refusal on a stale read, and on its own that is\n // all it ever was: the availability query ran, the quote and the fee were\n // computed, and only then did the hold land — so two guests requesting the\n // same dates both read a reservation set that lacked the other's booking,\n // both passed, and both got a `pending` row and a real payment. Nothing\n // downstream caught it. The webhook's transaction guards double-CONFIRMATION\n // of one booking against Stripe redelivery; it never re-asks availability,\n // so both holds confirmed cleanly into two guests in one room.\n //\n // `claimAttempt` does not help either, and it is worth being explicit about\n // why: it is keyed on the guest's own `Idempotency-Key`, so it dedupes\n // retries of ONE attempt. Two different guests carry two different keys and\n // never contend.\n //\n // Re-asking inside the transaction that writes is the whole guard — the\n // same shape as `decrementVariantStock` (AGL-2320), and easier to justify\n // here: the conflicting write lands BEFORE Stripe is contacted, so this\n // door can legitimately refuse rather than take the money and withhold the\n // room.\n //\n // The same re-read is what keeps a several-unit resource (AGL-4044) from\n // selling its last unit twice: `isRangeAvailable` counts the stays on\n // each night against `resource.units`, so two guests racing for the last\n // RV hookup both read eleven of twelve taken, and the loser's transaction\n // re-runs on the winner's write, counts twelve, and refuses.\n const reservationRef = hostRef.collection('reservations').doc()\n const booked = await firestore.runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(availabilityQuery)\n // Re-timed, not reusing `now`: a transaction that retries under\n // contention may run appreciably later, and the 30-minute pending window\n // has to be measured from when this attempt actually commits.\n if (\n !CommerceModel.isRangeAvailable(\n resource,\n readLive(fresh),\n checkInDayMs,\n checkOutDayMs,\n Date.now(),\n )\n ) {\n return false\n }\n // `create()`, not `set()`: the ref is freshly minted, so an id collision\n // is a bug rather than an overwrite to absorb silently.\n transaction.create(reservationRef, {\n resourceId,\n status: 'pending',\n checkInDayMs,\n checkOutDayMs,\n guestName: guestName || null,\n guestEmail: guestEmail || null,\n ...(guestsAsked !== undefined ? { guests: guestsAsked } : {}),\n nights: quote.nights,\n totalCents: quote.totalCents,\n depositCents: quote.depositCents,\n paidCents: 0,\n createdAtMs: now,\n } satisfies CommerceModel.HostReservation)\n return true\n })\n if (!booked) {\n // Lost the race for these dates. Same refusal as the pre-read's, and the\n // key survives it for the same reason: the guest picks other dates or the\n // blocking stay is cancelled.\n await claim.release()\n return res.status(409).json({ error: 'Those dates just sold out' })\n }\n\n // The site's own page, never a header's say-so (AGL-3363): a caller\n // writes `Referer` and `Host`, and this URL is where Stripe sends the\n // payer — and what the receipt's download links are built from.\n const backUrl = siteReturnUrl({\n candidates: [String(req.headers.referer ?? ''), `https://${req.headers.host}`],\n site: await readSiteReturnHost(hostRef),\n requestHost: String(req.headers.host ?? ''),\n })\n const separator = backUrl.includes('?') ? '&' : '?'\n const params = new URLSearchParams({\n mode: 'payment',\n // 3-D Secure, from the one seam every card payment shares (AGL-3360).\n ...checkoutSessionCardAuthenticationParams('payment'),\n 'line_items[0][quantity]': '1',\n 'line_items[0][price_data][currency]': 'usd',\n 'line_items[0][price_data][unit_amount]': String(chargeCents),\n 'line_items[0][price_data][product_data][name]': `${resource.name} — ${\n quote.nights\n } night${quote.nights === 1 ? '' : 's'}${\n quote.depositCents && quote.depositCents < quote.totalCents\n ? ' (deposit)'\n : ''\n }`.slice(0, 120),\n // The merchant's lodging tax as an ORDINARY product line Stripe is\n // never told is tax — the AGL-1711 construction every other manual rate\n // rides. That is what makes the derived `taxMode` read `manual`: the\n // figure is the merchant's own, computed from their own rate, and never\n // against Aglyn's registrations the way `automatic_tax` would be\n // (AGL-1904). Absent entirely when no rate is set, so a default store's\n // session carries no tax parameter of any kind.\n ...(lodgingTax.taxCents > 0\n ? {\n 'line_items[1][quantity]': '1',\n 'line_items[1][price_data][currency]': 'usd',\n 'line_items[1][price_data][unit_amount]': String(\n lodgingTax.taxCents,\n ),\n 'line_items[1][price_data][product_data][name]': lodgingTax.label,\n }\n : {}),\n ...(feeCents > 0\n ? { 'payment_intent_data[application_fee_amount]': String(feeCents) }\n : {}),\n 'payment_intent_data[transfer_data][destination]': String(accountId),\n ...(guestEmail ? { customer_email: guestEmail } : {}),\n success_url: `${backUrl}${separator}reserved=1`,\n cancel_url: `${backUrl}${separator}reserved=0`,\n 'metadata[type]': 'commerce-reservation',\n 'metadata[hostId]': hostId,\n 'metadata[reservationId]': reservationRef.id,\n 'metadata[feeCents]': String(feeCents),\n // The only witness to the tax (AGL-1969). By the construction above\n // Stripe does not know the second line is tax, so it reports\n // `total_details.amount_tax: 0` — the session's own metadata is what\n // `storefront-tax-record.ts` and the confirmation branch read to record\n // the figure and derive the regime, exactly as `checkout.ts` stamps it\n // for a buy-now sale. Absent when there is no tax, never a reassuring\n // `'0'`: absent and zero are different facts on a back-book question.\n ...(lodgingTax.taxCents > 0\n ? {\n 'metadata[taxCents]': String(lodgingTax.taxCents),\n 'metadata[taxPct]': String(lodgingTax.pct),\n }\n : {}),\n })\n // The merchant's payment method choices hold for a stay too (AGL-3629).\n CommerceModel.appendStorefrontPaymentMethodParams(\n params,\n CommerceModel.resolveStorefrontPaymentMethodControls(\n CommerceModel.normalizeStorefrontPaymentMethodSettings(\n storeSnapshot.get('paymentMethods'),\n ),\n ),\n )\n const response = await fetch(\n 'https://api.stripe.com/v1/checkout/sessions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n // The half that costs real money (AGL-1697). Stripe replays the\n // existing session for a repeated key instead of opening a second\n // one, covering the window where the claim is written but the\n // response never arrives.\n ...(claim.stripeKey ? { 'Idempotency-Key': claim.stripeKey } : {}),\n },\n body: params.toString(),\n },\n )\n const session = (await response.json()) as { url?: string; error?: any }\n if (!response.ok || !session.url) {\n console.error('Stripe reservation error', session.error)\n await reservationRef.delete().catch(() => undefined)\n // The hold is rolled back, so the key must come back too — the guest\n // presses the same button and the retry re-derives the same digest,\n // which Stripe replays if the session did get created.\n await claim.release()\n return res.status(502).json({ error: 'Payment setup failed' })\n }\n const payload = { url: session.url }\n await claim.record(200, payload)\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n // Release on the way out so a transient failure does not strand the key\n // (AGL-1691's rule): the hold may or may not have landed, and it expires\n // in 30 minutes either way.\n await claim?.release()\n return res.status(500).json({ error: 'Reservation failed' })\n }\n}\n"],"names":["readSiteReturnHost","siteReturnUrl","Aglyn","CommerceModel","claimAttempt","firebaseAdmin","getOrgForHost","merchantAccountIsReady","checkoutSessionCardAuthenticationParams","readLiveReservations","reservationAvailabilityQuery","reservationsOnPlan","reserveHandler","req","res","body","method","status","json","error","process","env","STRIPE_SECRET_KEY","JSON","parse","hostId","String","resourceId","checkInDayMs","toDayMs","Number","checkOutDayMs","guestName","trim","slice","guestEmail","toLowerCase","guestsAsked","guests","undefined","idempotencyKey","headers","claim","ownerOrg","storeSnapshot","firestore","app","hostRef","collection","doc","org","ownerId","ownerUid","ownerProfile","get","accountId","chargesEnabled","accountLivemode","subject","claimed","kind","scopeId","orgId","id","key","busyMessage","replay","availabilityQuery","resourceSnapshot","reservationsSnapshot","Promise","all","resource","data","release","readLive","now","Date","live","isRangeAvailable","quote","computeReservationQuote","problem","guestsProblem","reservationGuestsProblem","chargeCents","depositCents","totalCents","taxSettings","tax","lodgingTax","resolveFlatTaxCents","lodging","feeCents","resolveTransactionFeeCents","taxCents","reservationRef","booked","runTransaction","transaction","fresh","create","nights","paidCents","createdAtMs","backUrl","candidates","referer","host","site","requestHost","separator","includes","params","URLSearchParams","mode","name","label","customer_email","success_url","cancel_url","pct","appendStorefrontPaymentMethodParams","resolveStorefrontPaymentMethodControls","normalizeStorefrontPaymentMethodSettings","response","fetch","Authorization","stripeKey","toString","session","ok","url","console","delete","catch","payload","record"],"mapp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AO,EAAE3G,QAAQC,GAAG,CAACC,iBAAiB,EAAE;gBACxD,gBAAgB;eAKZoB,MAAMsF,SAAS,GAAG;gBAAE,mBAAmBtF,MAAMsF,SAAS;YAAC,IAAI,CAAC;YAElEjH,MAAMkG,OAAOgB,QAAQ;QACvB;QAEF,MAAMC,UAAW,MAAML,SAAS3G,IAAI;QACpC,IAAI,CAAC2G,SAASM,EAAE,IAAI,CAACD,QAAQE,GAAG,EAAE;YAChCC,QAAQlH,KAAK,CAAC,4BAA4B+G,QAAQ/G,KAAK;YACvD,MAAM6E,eAAesC,MAAM,GAAGC,KAAK,CAAC,IAAMhG;YAC1C,qEAAqE;YACrE,oEAAoE;YACpE,uDAAuD;YACvD,MAAMG,MAAMgC,OAAO;YACnB,OAAO5D,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAAuB;QAC9D;QACA,MAAMqH,UAAU;YAAEJ,KAAKF,QAAQE,GAAG;QAAC;QACnC,MAAM1F,MAAM+F,MAAM,CAAC,KAAKD;QACxB,OAAO1H,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAACsH;IAC9B,EAAE,OAAOrH,OAAO;QACdkH,QAAQlH,KAAK,CAACA;QACd,wEAAwE;QACxE,yEAAyE;QACzE,4BAA4B;QAC5B,OAAMuB,yBAAAA,MAAOgC,OAAO;QACpB,OAAO5D,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/reserve.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 { readSiteReturnHost, siteReturnUrl } from '@aglyn/aglyn/app-utils/site-return-url'\nimport type { AttemptClaim, PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { claimAttempt } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport {\n connectedAccountHeader,\n directChargeParams,\n merchantAccountIsReady,\n saleChargeModel,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { checkoutSessionCardAuthenticationParams } from '@aglyn/tenant-data-admin/server/stripe-card-authentication'\nimport {\n readLiveReservations,\n reservationAvailabilityQuery,\n reservationsOnPlan,\n} from './reservation-availability-query'\n\n/**\n * Reserve a stay (AGL-310): server-side quote + availability check,\n * pending reservation doc, then a Stripe session for the deposit (or\n * full amount) on the merchant's account. Webhook completion confirms\n * the reservation; abandoned pending holds expire after 30 minutes and\n * stop blocking the calendar.\n */\nexport const reserveHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const resourceId = String(body.resourceId ?? '')\n const checkInDayMs = CommerceModel.toDayMs(Number(body.checkInDayMs ?? 0))\n const checkOutDayMs = CommerceModel.toDayMs(Number(body.checkOutDayMs ?? 0))\n const guestName = String(body.guestName ?? '').trim().slice(0, 120)\n const guestEmail = String(body.guestEmail ?? '').trim().toLowerCase().slice(0, 120)\n // How many guests the stay is for (AGL-4043): optional, checked against\n // what the resource sleeps once it is read.\n const guestsAsked = body.guests === undefined || body.guests === null || body.guests === '' ? undefined : Number(body.guests)\n // One reservation attempt, minted by the widget (AGL-1697). Node lowercases\n // incoming headers, but read both spellings — the plugin API request type\n // makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n ).trim().slice(0, 200)\n if (!hostId || !resourceId || !checkInDayMs || !checkOutDayMs) {\n return res.status(400).json({ error: 'Missing reservation details' })\n }\n\n let claim: AttemptClaim | null = null\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n // Owner + payment readiness, HOISTED above the claim (AGL-1697): both are\n // deterministic refusals a merchant fixes out of band, and neither should\n // burn the guest's attempt key.\n const ownerOrg = await getOrgForHost(hostId)\n // Plan gate, re-asked per request exactly as the storefront checkout\n // asks it (AGL-1873, the AGL-481 pattern): a lapsed org's storefront\n // must not keep taking reservation deposits — at the free plan's 0%\n // transaction fee — through the one shopper-facing commerce door that\n // skipped the entitlement. Deterministic and merchant-side, so it sits\n // here above the claim with the readiness check.\n if (!reservationsOnPlan(ownerOrg?.org)) {\n return res.status(403).json({ error: 'Reservations are not enabled' })\n }\n const ownerId = ownerOrg?.org?.ownerUid\n const ownerProfile = ownerId\n ? await firestore.collection('profiles').doc(String(ownerId)).get()\n : null\n const accountId = ownerProfile?.get('stripeAccountId')\n if (\n !merchantAccountIsReady(\n {\n accountId,\n chargesEnabled: ownerProfile?.get('stripeChargesEnabled'),\n accountLivemode: ownerProfile?.get('stripeAccountLivemode'),\n },\n { subject: `reserve host ${hostId}` },\n )\n ) {\n return res.status(409).json({ error: 'Payments are not set up yet' })\n }\n // A DIRECT charge takes the deposit ON the seller's own Stripe account\n // (`Stripe-Account`), with Aglyn's take as the application fee; the\n // destination path below is unchanged for every other seller.\n const chargeModel = saleChargeModel(ownerProfile?.get('stripeChargeModel'))\n const direct = chargeModel === 'direct'\n const onAccount = connectedAccountHeader(chargeModel, accountId)\n\n // The claim sits ABOVE the availability read, and that placement is the\n // fix for this handler's particular lie (AGL-1697): a retried attempt used\n // to collide with its OWN 30-minute pending hold and be told \"Those dates\n // just sold out\" — about dates the guest was holding — where the correct\n // answer was the original session URL. Replaying here means the retry\n // never reaches the availability check at all. Every refusal below the\n // claim releases it, because each is deterministic and retryable.\n const claimed = await claimAttempt(firestore, {\n kind: 'commerce-reserve',\n scopeId: hostId,\n orgId: String(ownerOrg?.org?.id ?? ''),\n key: idempotencyKey,\n busyMessage: 'This reservation is already being processed',\n })\n if ('replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n claim = claimed.claim\n\n // ONLY STAYS THAT COULD STILL OVERLAP, NEAREST FIRST (AGL-2159).\n //\n // This was `.where('resourceId','==',resourceId).limit(500)` with no\n // ordering, so Firestore returned 500 documents in `__name__` order — an\n // arbitrary slice of the resource's ENTIRE booking history. Every stay the\n // resource has ever had competed for those 500 slots on equal terms with\n // the ones that matter, so a cottage that had taken 500 bookings began\n // silently dropping LIVE reservations out of its own availability check\n // and confirming a second guest into an occupied room. Nothing about that\n // failure is visible: `isRangeAvailable` is handed a short list and\n // answers, correctly, that the range is free.\n //\n // `checkOutDayMs > checkInDayMs` is the one inequality that removes the\n // whole of the past — a stay that ended before the requested arrival\n // cannot overlap it — and ordering by the same field puts the stays\n // nearest the requested window at the front of the limit rather than\n // whichever ones happen to sort early by id. Needs the composite index\n // `reservations (resourceId ASC, checkOutDayMs ASC)`, added to\n // `cloud/firebase-firestore.indexes.json` and pinned by\n // `reserve-availability-indexes.spec.ts` — an equality plus an `orderBy`\n // on a second field is exactly the shape that reads as free and is not\n // (AGL-1793), and here a missing index throws rather than under-reporting.\n //\n // RESIDUAL, stated: the cap can still bite when a single resource holds\n // more than 500 stays that all end between the requested arrival and the\n // end of a genuinely overlapping one. That is a far narrower window than\n // \"500 bookings in this resource's lifetime\", but it is not zero, and the\n // sweep that would keep expired `pending` holds from filling those slots\n // is a scheduled job this change does not add (see the commit).\n //\n // The query itself lives in `reservation-availability-query.ts`, shared\n // with the staff walk-in route (AGL-4046) so both doors ask one question.\n const availabilityQuery = reservationAvailabilityQuery(\n hostRef.collection('reservations'),\n resourceId,\n checkInDayMs,\n )\n const [resourceSnapshot, reservationsSnapshot, storeSnapshot] =\n await Promise.all([\n hostRef.collection('resources').doc(resourceId).get(),\n availabilityQuery.get(),\n // The merchant's own lodging rate (AGL-1969). Read in the SAME round\n // trip as the availability query rather than as a fourth sequential\n // await — this path already runs three reads before it can answer, and\n // a tax lookup is not a reason to make a guest wait for a fourth.\n hostRef.collection('settings').doc('store').get(),\n ])\n const resource = resourceSnapshot.data() as CommerceModel.HostResource | undefined\n if (!resource) {\n await claim.release()\n return res.status(404).json({ error: 'Unknown resource' })\n }\n\n // Pending holds block for 30 minutes only, so abandoned checkouts\n // release the dates. The lapse itself lives in\n // `reservationHoldsDates`, which `isRangeAvailable` applies — this reads\n // the fields that rule needs and leaves the rule to the model, so the\n // storefront's date-picker cannot answer a different question from the\n // door that takes the money.\n //\n // Extracted so the pre-read below and the re-read inside the booking\n // transaction cannot drift apart (AGL-2450). Two copies of a filter that\n // decides whether a room is free is exactly the shape where one of them\n // quietly stops matching the other.\n // The staff walk-in route reads through the same helper (AGL-4046).\n const readLive = readLiveReservations\n const now = Date.now()\n const live = readLive(reservationsSnapshot)\n if (\n !CommerceModel.isRangeAvailable(\n resource,\n live,\n checkInDayMs,\n checkOutDayMs,\n now,\n )\n ) {\n // A GENUINE sold-out (a keyed retry replayed before reaching here). The\n // guest picks other dates or the blocking stay is cancelled; either way\n // the key must survive the refusal.\n await claim.release()\n return res.status(409).json({ error: 'Those dates just sold out' })\n }\n const quote = CommerceModel.computeReservationQuote(\n resource,\n checkInDayMs,\n checkOutDayMs,\n )\n if (quote.problem) {\n await claim.release()\n return res.status(400).json({ error: quote.problem })\n }\n const guestsProblem = CommerceModel.reservationGuestsProblem(guestsAsked, resource)\n if (guestsProblem) {\n await claim.release()\n return res.status(400).json({ error: guestsProblem })\n }\n\n const chargeCents = quote.depositCents || quote.totalCents\n\n // NO DISCOUNT IS APPLIED HERE, AND THAT IS AN OPEN QUESTION RATHER THAN AN\n // OVERSIGHT (AGL-305).\n //\n // `hosts/{hostId}/discounts` reaches the cart, buy-now, the draft-order\n // payment link and the register. This door was deliberately left out,\n // because unlike those four it does not take a payment for goods — it takes\n // a DEPOSIT against a stay that is settled later, and \"apply 10% off\" has\n // three different meanings against that shape:\n //\n // 1. Discount the STAY. `quote.totalCents` falls, the deposit falls with\n // it because it is a percentage of the subtotal, and the balance falls\n // too. This is the only reading that is actually a discount on the\n // booking — and it reprices a merchant's lodging inventory from a\n // storefront promo code, which is a larger claim than any of the four\n // goods doors makes.\n // 2. Discount the DEPOSIT only. Strictly worse than doing nothing: the\n // balance is computed downstream as `totalCents - paidCents`, so every\n // cent taken off at booking is billed straight back at check-out. The\n // guest would be shown a discount and then charged for it, which is\n // the silent-reversal shape this codebase refuses elsewhere.\n // 3. Discount the BALANCE. Nothing visible at booking; the guest finds\n // out at the register. A promotion nobody can see when they buy is not\n // a promotion.\n //\n // What makes this a product decision and not an implementation one is that\n // the balance is not collected by any door this repo can teach. It is read\n // off the console's reservations card as `totalCents - paidCents` and\n // collected BY A HUMAN at the till, so option 1 is the only one that\n // survives the hand-off — and it survives it by changing the stay's stored\n // price, which is the merchant's revenue basis and what their analytics,\n // their folio and their register all read.\n //\n // The tax makes it sharper still. `lodgingTax` below is an occupancy rate,\n // not a sales rate, and its basis here is already a STATED LIMITATION — it\n // is charged on what is collected (the deposit) rather than on the stay.\n // Layering a discount on top asks whether occupancy tax is owed on the\n // discounted room rate or the gross one, which differs by jurisdiction, is\n // the merchant's own regime to answer, and is not a question this handler\n // can decide from a promo code.\n //\n // So: refusing to guess. A shopper who types a code here is not told it\n // worked — this path never reads one, so there is nothing to fall through\n // silently, which is the failure mode that mattered. When the owner picks\n // a reading, option 1 is the one the machinery already supports: reduce\n // `quote.subtotalCents` before the deposit is derived from it, and the\n // deposit, the balance, the fee and the tax all follow without further\n // change.\n\n // LODGING TAX: the MERCHANT'S OWN RATE, off unless they set one\n // (AGL-1969, answering the decision AGL-1953 recorded here).\n //\n // What this path used to do, and why it was only ever a holding position:\n // it computed no tax in either store mode, on two stated grounds. The\n // first is still true and is the reason for the shape below — a stay is\n // not goods. The AGL-285 zone editor configures a SALES rate, lodging is\n // an occupancy/hotel regime with its own rates, its own registration and\n // its own return, and reading `rates[]` for a night would be confidently\n // wrong rather than merely absent. Stripe Tax has the mirror problem: it\n // needs a lodging tax code this handler does not send, so\n // `automatic_tax` here would compute a goods rate on a room. Neither of\n // those changes, and neither is used.\n //\n // What DID change is that the merchant now has a field of their own to\n // answer in (`tax.lodging`), so \"Aglyn does not know the right number\"\n // stops being a reason to collect nothing. They type the rate, we compute\n // it, charge it, record it and stamp the regime; the settings card states\n // plainly that determining what is owed and to whom is theirs. Aglyn\n // takes no tax position here — this is the manual LODGING rate, which\n // never touches Aglyn's registrations.\n //\n // ⚠️ This comment used to say \"Terms §10.3 ... untouched by this\". §10.3\n // CHANGED on 2026-08-24 (AGL-1956): Aglyn accepts marketplace-facilitator\n // status and new §10.7 makes storefront sales tax Aglyn's where it has a\n // collection obligation. Lodging tax is still the merchant's, so this\n // handler is unaffected — but §10.3 is no longer the authority for that.\n //\n // DEFAULT OFF, and that is load-bearing: `resolveFlatTaxCents` answers\n // zero for an absent, zero, negative or out-of-range rate, so no existing\n // reservation's charge moves because this shipped.\n //\n // THE BASIS IS WHAT IS CHARGED, AND THAT IS A STATED LIMITATION RATHER\n // THAN AN ANSWER. `chargeCents` is `depositCents || totalCents`, so on a\n // deposit-taking resource the tax collected here is the rate on the\n // DEPOSIT, not on the stay. Whether a given jurisdiction wants occupancy\n // tax on the full stay at booking, on the deposit only, or on redemption\n // at check-out is a tax question, it differs by jurisdiction, and this\n // code deliberately does NOT decide it — the amount the platform actually\n // moves is the only basis available to it, the settings card says so in\n // the merchant's own view, and the residual is on AGL-1969.\n const taxSettings = ((storeSnapshot.data() as any)?.tax ??\n {}) as CommerceModel.TaxSettings\n const lodgingTax = CommerceModel.resolveFlatTaxCents(\n taxSettings.lodging,\n chargeCents,\n 'Lodging tax',\n )\n\n // Platform take PLUS Stripe's card cost at cost (AGL-2152). This is a\n // destination charge, so Stripe debits its percentage plus 30¢ from the\n // PLATFORM's balance; with the old take-only figure every tier carrying a\n // 0% service rate paid Aglyn nothing and cost it that fee on each\n // reservation.\n //\n // THE TWO BASES ARE NOW DIFFERENT NUMBERS (AGL-1969), and the split is\n // AGL-2317's rule: the platform take is computed on the ITEMS — the stay\n // — while Stripe's cost is passed through on the WHOLE charge, because\n // that is what Stripe actually debits. Taking a percentage of the lodging\n // tax would be taking a cut of the state's money, which no storefront\n // path does. The previous single-argument form is what made this a real\n // risk: it read as \"the fee base is the charge\" and would have silently\n // started taxing the tax the moment a tax line appeared.\n //\n // A direct charge's fee is the take alone: Stripe bills the seller its\n // own card fee and charges the platform nothing for the deposit.\n const feeCents = Aglyn.resolveTransactionFeeCents(\n ownerOrg?.org as any,\n 'service',\n chargeCents,\n chargeCents + lodgingTax.taxCents,\n direct ? { direct: true } : {},\n )\n\n // THE HOLD IS TAKEN IN A TRANSACTION (AGL-2450).\n //\n // The check above is a fast refusal on a stale read, and on its own that is\n // all it ever was: the availability query ran, the quote and the fee were\n // computed, and only then did the hold land — so two guests requesting the\n // same dates both read a reservation set that lacked the other's booking,\n // both passed, and both got a `pending` row and a real payment. Nothing\n // downstream caught it. The webhook's transaction guards double-CONFIRMATION\n // of one booking against Stripe redelivery; it never re-asks availability,\n // so both holds confirmed cleanly into two guests in one room.\n //\n // `claimAttempt` does not help either, and it is worth being explicit about\n // why: it is keyed on the guest's own `Idempotency-Key`, so it dedupes\n // retries of ONE attempt. Two different guests carry two different keys and\n // never contend.\n //\n // Re-asking inside the transaction that writes is the whole guard — the\n // same shape as `decrementVariantStock` (AGL-2320), and easier to justify\n // here: the conflicting write lands BEFORE Stripe is contacted, so this\n // door can legitimately refuse rather than take the money and withhold the\n // room.\n //\n // The same re-read is what keeps a several-unit resource (AGL-4044) from\n // selling its last unit twice: `isRangeAvailable` counts the stays on\n // each night against `resource.units`, so two guests racing for the last\n // RV hookup both read eleven of twelve taken, and the loser's transaction\n // re-runs on the winner's write, counts twelve, and refuses.\n const reservationRef = hostRef.collection('reservations').doc()\n const booked = await firestore.runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(availabilityQuery)\n // Re-timed, not reusing `now`: a transaction that retries under\n // contention may run appreciably later, and the 30-minute pending window\n // has to be measured from when this attempt actually commits.\n if (\n !CommerceModel.isRangeAvailable(\n resource,\n readLive(fresh),\n checkInDayMs,\n checkOutDayMs,\n Date.now(),\n )\n ) {\n return false\n }\n // `create()`, not `set()`: the ref is freshly minted, so an id collision\n // is a bug rather than an overwrite to absorb silently.\n transaction.create(reservationRef, {\n resourceId,\n status: 'pending',\n checkInDayMs,\n checkOutDayMs,\n guestName: guestName || null,\n guestEmail: guestEmail || null,\n ...(guestsAsked !== undefined ? { guests: guestsAsked } : {}),\n nights: quote.nights,\n totalCents: quote.totalCents,\n depositCents: quote.depositCents,\n paidCents: 0,\n createdAtMs: now,\n } satisfies CommerceModel.HostReservation)\n return true\n })\n if (!booked) {\n // Lost the race for these dates. Same refusal as the pre-read's, and the\n // key survives it for the same reason: the guest picks other dates or the\n // blocking stay is cancelled.\n await claim.release()\n return res.status(409).json({ error: 'Those dates just sold out' })\n }\n\n // The site's own page, never a header's say-so (AGL-3363): a caller\n // writes `Referer` and `Host`, and this URL is where Stripe sends the\n // payer — and what the receipt's download links are built from.\n const backUrl = siteReturnUrl({\n candidates: [String(req.headers.referer ?? ''), `https://${req.headers.host}`],\n site: await readSiteReturnHost(hostRef),\n requestHost: String(req.headers.host ?? ''),\n })\n const separator = backUrl.includes('?') ? '&' : '?'\n const params = new URLSearchParams({\n mode: 'payment',\n // 3-D Secure, from the one seam every card payment shares (AGL-3360).\n ...checkoutSessionCardAuthenticationParams('payment'),\n 'line_items[0][quantity]': '1',\n 'line_items[0][price_data][currency]': 'usd',\n 'line_items[0][price_data][unit_amount]': String(chargeCents),\n 'line_items[0][price_data][product_data][name]': `${resource.name} — ${\n quote.nights\n } night${quote.nights === 1 ? '' : 's'}${\n quote.depositCents && quote.depositCents < quote.totalCents\n ? ' (deposit)'\n : ''\n }`.slice(0, 120),\n // The merchant's lodging tax as an ORDINARY product line Stripe is\n // never told is tax — the AGL-1711 construction every other manual rate\n // rides. That is what makes the derived `taxMode` read `manual`: the\n // figure is the merchant's own, computed from their own rate, and never\n // against Aglyn's registrations the way `automatic_tax` would be\n // (AGL-1904). Absent entirely when no rate is set, so a default store's\n // session carries no tax parameter of any kind.\n ...(lodgingTax.taxCents > 0\n ? {\n 'line_items[1][quantity]': '1',\n 'line_items[1][price_data][currency]': 'usd',\n 'line_items[1][price_data][unit_amount]': String(\n lodgingTax.taxCents,\n ),\n 'line_items[1][price_data][product_data][name]': lodgingTax.label,\n }\n : {}),\n // A direct charge is the seller's money from the start: the fee is the\n // whole split and nothing is transferred.\n ...(direct\n ? directChargeParams(feeCents)\n : {\n ...(feeCents > 0\n ? { 'payment_intent_data[application_fee_amount]': String(feeCents) }\n : {}),\n 'payment_intent_data[transfer_data][destination]': String(accountId),\n }),\n ...(guestEmail ? { customer_email: guestEmail } : {}),\n success_url: `${backUrl}${separator}reserved=1`,\n cancel_url: `${backUrl}${separator}reserved=0`,\n 'metadata[type]': 'commerce-reservation',\n 'metadata[hostId]': hostId,\n 'metadata[reservationId]': reservationRef.id,\n 'metadata[feeCents]': String(feeCents),\n // What the webhook, refunds and reports read to find the payment on\n // the seller's account rather than the platform's.\n ...(direct ? { 'metadata[chargeModel]': 'direct' } : {}),\n // The only witness to the tax (AGL-1969). By the construction above\n // Stripe does not know the second line is tax, so it reports\n // `total_details.amount_tax: 0` — the session's own metadata is what\n // `storefront-tax-record.ts` and the confirmation branch read to record\n // the figure and derive the regime, exactly as `checkout.ts` stamps it\n // for a buy-now sale. Absent when there is no tax, never a reassuring\n // `'0'`: absent and zero are different facts on a back-book question.\n ...(lodgingTax.taxCents > 0\n ? {\n 'metadata[taxCents]': String(lodgingTax.taxCents),\n 'metadata[taxPct]': String(lodgingTax.pct),\n }\n : {}),\n })\n // The merchant's payment method choices hold for a stay too (AGL-3629).\n CommerceModel.appendStorefrontPaymentMethodParams(\n params,\n CommerceModel.resolveStorefrontPaymentMethodControls(\n CommerceModel.normalizeStorefrontPaymentMethodSettings(\n storeSnapshot.get('paymentMethods'),\n ),\n ),\n )\n const response = await fetch(\n 'https://api.stripe.com/v1/checkout/sessions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n // The half that costs real money (AGL-1697). Stripe replays the\n // existing session for a repeated key instead of opening a second\n // one, covering the window where the claim is written but the\n // response never arrives.\n ...(claim.stripeKey ? { 'Idempotency-Key': claim.stripeKey } : {}),\n ...onAccount,\n },\n body: params.toString(),\n },\n )\n const session = (await response.json()) as { url?: string; error?: any }\n if (!response.ok || !session.url) {\n console.error('Stripe reservation error', session.error)\n await reservationRef.delete().catch(() => undefined)\n // The hold is rolled back, so the key must come back too — the guest\n // presses the same button and the retry re-derives the same digest,\n // which Stripe replays if the session did get created.\n await claim.release()\n return res.status(502).json({ error: 'Payment setup failed' })\n }\n const payload = { url: session.url }\n await claim.record(200, payload)\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n // Release on the way out so a transient failure does not strand the key\n // (AGL-1691's rule): the hold may or may not have landed, and it expires\n // in 30 minutes either way.\n await claim?.release()\n return res.status(500).json({ error: 'Reservation failed' })\n }\n}\n"],"names":["readSiteReturnHost","siteReturnUrl","Aglyn","CommerceModel","claimAttempt","firebaseAdmin","getOrgForHost","connectedAccountHeader","directChargeParams","merchantAccountIsReady","saleChargeModel","checkoutSessionCardAuthenticationParams","readLiveReservations","reservationAvailabilityQuery","reservationsOnPlan","reserveHandler","req","res","body","method","status","json","error","process","env","STRIPE_SECRET_KEY","JSON","parse","hostId","String","resourceId","checkInDayMs","toDayMs","Number","checkOutDayMs","guestName","trim","slice","guestEmail","toLowerCase","guestsAsked","guests","undefined","idempotencyKey","headers","claim","ownerOrg","storeSnapshot","firestore","app","hostRef","collection","doc","org","ownerId","ownerUid","ownerProfile","get","accountId","chargesEnabled","accountLivemode","subject","chargeModel","direct","onAccount","claimed","kind","scopeId","orgId","id","key","busyMessage","replay","availabilityQuery","resourceSnapshot","reservationsSnapshot","Promise","all","resource","data","release","readLive","now","Date","live","isRangeAvailable","quote","computeReservationQuote","problem","guestsProblem","reservationGuestsProblem","chargeCents","depositCents","totalCents","taxSettings","tax","lodgingTax","resolveFlatTaxCents","lodging","feeCents","resolveTransactionFeeCents","taxCents","reservationRef","booked","runTransaction","transaction","fresh","create","nights","paidCents","createdAtMs","backUrl","candidates","referer","host","site","requestHost","separator","includes","params","URLSearchParams","mode","name","label","customer_email","success_url","cancel_url","pct","appendStorefrontPaymentMethodParams","resolveStorefrontPaymentMethodControls","normalizeStorefrontPaymentMethodSettings","response","fetch","Authorization","stripeKey","toString","session","ok","url","console","delete","catch","payload","record"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,EAAEC,aAAa,QAAQ,yCAAwC;AAE1F,YAAYC,WAAW,sBAAqB;AAC5C,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,YAAY,QAAQ,sBAAqB;AAClD,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,sBAAsB,EACtBC,eAAe,QACV,mDAAkD;AACzD,SAASC,uCAAuC,QAAQ,6DAA4D;AACpH,SACEC,oBAAoB,EACpBC,4BAA4B,EAC5BC,kBAAkB,QACb,sCAAkC;AAEzC;;;;;;CAMC,GACD,OAAO,MAAMC,iBAAmC,OAAOC,KAAKC;QAQDD,WACnCE,cACIA,kBACwBA,oBACCA,qBAC1BA,iBACCA,kBAQxBF,MAAAA;IArBF,IAAIA,IAAIG,MAAM,KAAK,QAAQ;QACzB,OAAOF,IAA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UAAW,MAAML,SAAS9G,IAAI;QACpC,IAAI,CAAC8G,SAASM,EAAE,IAAI,CAACD,QAAQE,GAAG,EAAE;YAChCC,QAAQrH,KAAK,CAAC,4BAA4BkH,QAAQlH,KAAK;YACvD,MAAMgF,eAAesC,MAAM,GAAGC,KAAK,CAAC,IAAMnG;YAC1C,qEAAqE;YACrE,oEAAoE;YACpE,uDAAuD;YACvD,MAAMG,MAAMmC,OAAO;YACnB,OAAO/D,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAAuB;QAC9D;QACA,MAAMwH,UAAU;YAAEJ,KAAKF,QAAQE,GAAG;QAAC;QACnC,MAAM7F,MAAMkG,MAAM,CAAC,KAAKD;QACxB,OAAO7H,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAACyH;IAC9B,EAAE,OAAOxH,OAAO;QACdqH,QAAQrH,KAAK,CAACA;QACd,wEAAwE;QACxE,yEAAyE;QACzE,4BAA4B;QAC5B,OAAMuB,yBAAAA,MAAOmC,OAAO;QACpB,OAAO/D,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;AACF,EAAC"}
|
|
@@ -33,6 +33,12 @@ export interface CommerceOrderRowInput {
|
|
|
33
33
|
subscriptionId?: unknown;
|
|
34
34
|
/** Merchant refunds AND chargebacks both land here (`refund.ts`). */
|
|
35
35
|
refundedCents?: unknown;
|
|
36
|
+
/**
|
|
37
|
+
* `'direct'` for a sale made on the seller's own Stripe account, where the
|
|
38
|
+
* fee is the take with no processing pass-through (see the module note).
|
|
39
|
+
* Absent on every destination sale.
|
|
40
|
+
*/
|
|
41
|
+
chargeModel?: unknown;
|
|
36
42
|
/**
|
|
37
43
|
* WHICH storefront the order belongs to — the attribution key.
|
|
38
44
|
*
|
|
@@ -35,7 +35,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
35
35
|
* it would report the 30¢ Stripe just took as money the platform made.
|
|
36
36
|
*
|
|
37
37
|
* So the pass-through is recomputed with the SAME helper the fee was charged
|
|
38
|
-
* from (`
|
|
38
|
+
* from (`salePlatformCostCents`) and subtracted. Both halves are
|
|
39
39
|
* reported, because "we collected X of which Y was Stripe's" is the sentence a
|
|
40
40
|
* margin figure needs.
|
|
41
41
|
*
|
|
@@ -63,8 +63,18 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
63
63
|
* and the clamp reports its take as zero. One cycle per legacy subscription,
|
|
64
64
|
* and the count beside the figure is how a reader sees how much of the book
|
|
65
65
|
* that is.
|
|
66
|
+
*
|
|
67
|
+
* ## Direct charges: the fee IS the take
|
|
68
|
+
*
|
|
69
|
+
* A seller on its own full Stripe account sells by DIRECT charge (the order
|
|
70
|
+
* carries `chargeModel: 'direct'`, stamped by the webhook). Stripe bills that
|
|
71
|
+
* seller its own processing and charges the platform nothing for the sale,
|
|
72
|
+
* so the application fee is the plan's take alone and there is no
|
|
73
|
+
* pass-through to subtract: on those orders the whole fee is commission. The
|
|
74
|
+
* shopper's tax on a direct sale is the seller's and never reaches this
|
|
75
|
+
* report, which counts only the fee.
|
|
66
76
|
*/ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
67
|
-
import {
|
|
77
|
+
import { salePlatformCostCents } from "@aglyn/aglyn/server";
|
|
68
78
|
import { PLATFORM_BRAND_NAME } from "@aglyn/aglyn/app-utils/platform-brand";
|
|
69
79
|
import { stripeIdIsTestMode } from "@aglyn/aglyn/app-utils/stripe-deployment-mode";
|
|
70
80
|
import { groupRevenueAttribution } from "@aglyn/aglyn/plugin-manager/plugin-revenue-sources";
|
|
@@ -139,10 +149,16 @@ export function commerceSettledSummary(rows, truncated = false) {
|
|
|
139
149
|
};
|
|
140
150
|
}
|
|
141
151
|
// Every fee bundles the recovery — a one-time sale's in cents, a
|
|
142
|
-
// subscription cycle's as a rate (AGL-2655).
|
|
143
|
-
//
|
|
144
|
-
//
|
|
145
|
-
|
|
152
|
+
// subscription cycle's as a rate (AGL-2655). Since AGL-4198 the take also
|
|
153
|
+
// pays Stripe's payout charge first, so what the platform keeps is the fee
|
|
154
|
+
// less everything Stripe charges it for the sale, not less the card alone.
|
|
155
|
+
// Clamped to the fee itself: the recomputed cost can exceed a fee charged
|
|
156
|
+
// under an older rate, and a negative take would subtract from another
|
|
157
|
+
// order's real margin.
|
|
158
|
+
//
|
|
159
|
+
// A direct charge costs the platform nothing at Stripe, so its fee is
|
|
160
|
+
// already the bare take.
|
|
161
|
+
const passThrough = (row == null ? void 0 : row.chargeModel) === 'direct' ? 0 : Math.min(fee, salePlatformCostCents(gross));
|
|
146
162
|
const take = fee - passThrough;
|
|
147
163
|
const refunded = Math.min(gross, Math.max(0, cents(row == null ? void 0 : row.refundedCents)));
|
|
148
164
|
const takeRefunded = gross > 0 ? Math.round(refunded * take / gross) : 0;
|
|
@@ -198,7 +214,7 @@ export function commerceSettledSummary(rows, truncated = false) {
|
|
|
198
214
|
label: 'Storefront sales (shopper gross)',
|
|
199
215
|
cents: settled.grossCents,
|
|
200
216
|
deduction: false,
|
|
201
|
-
note: 'The merchant’s. It transfers straight to their connected account ' + 'and is shown only for scale.'
|
|
217
|
+
note: 'The merchant’s. It transfers straight to their connected account ' + '(or, on a direct charge, settles there to begin with), tax ' + 'included, and is shown only for scale.'
|
|
202
218
|
},
|
|
203
219
|
{
|
|
204
220
|
label: 'Storefront platform fee collected',
|
|
@@ -207,10 +223,10 @@ export function commerceSettledSummary(rows, truncated = false) {
|
|
|
207
223
|
note: `Not all ${brand}’s — see the next line.`
|
|
208
224
|
},
|
|
209
225
|
{
|
|
210
|
-
label: '— less card processing passed through at cost',
|
|
226
|
+
label: '— less card processing and payouts passed through at cost',
|
|
211
227
|
cents: settled.processingPassThroughCents,
|
|
212
228
|
deduction: true,
|
|
213
|
-
note: `Stripe’s. On a destination charge Stripe debits ${brand}’s balance for processing, and this half of the fee recovers exactly that. It is a recovery, not earnings, and reporting it as revenue would overstate every storefront sale.`
|
|
229
|
+
note: `Stripe’s. On a destination charge Stripe debits ${brand}’s balance for processing, and this half of the fee recovers exactly that. It is a recovery, not earnings, and reporting it as revenue would overstate every storefront sale. A direct charge has none: Stripe bills the seller, so its whole fee is the take.`
|
|
214
230
|
}
|
|
215
231
|
],
|
|
216
232
|
notes: Number((_settled_subscriptionOrders = settled.subscriptionOrders) != null ? _settled_subscriptionOrders : 0) > 0 ? [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/revenue-source.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The storefront's take on the operator's revenue report (AGL-2486, AGL-3080).\n *\n * Answered through the platform's revenue source contract\n * (`@aglyn/aglyn/plugin-manager/plugin-revenue-sources`). The report folds the\n * operator's own invoices; this is what storefront orders earned it — and the\n * one figure on that page most likely to be reported wrongly.\n *\n * An order's `feeCents` is the Connect `application_fee_amount`, which since\n * AGL-2152 is the advertised take PLUS Stripe's processing cost:\n *\n * fee = take%(goods) + processing%(charge) + 30¢\n *\n * Every storefront charge is a DESTINATION charge, so Stripe moves the whole\n * amount to the merchant and debits its processing fee from the PLATFORM's\n * balance; the pass-through half of that fee exists purely to recover a cost\n * the platform has already paid. Reporting `feeCents` as earnings would\n * overstate the margin on every single storefront sale — and on a small order\n * it would report the 30¢ Stripe just took as money the platform made.\n *\n * So the pass-through is recomputed with the SAME helper the fee was charged\n * from (`saleProcessingCostCents`) and subtracted. Both halves are\n * reported, because \"we collected X of which Y was Stripe's\" is the sentence a\n * margin figure needs.\n *\n * The recomputation is an estimate in one direction only: it re-derives the\n * cost from the stored charge amount rather than reading Stripe's actual\n * balance-transaction fee, and it prices it at the DEAREST enabled payment\n * method's rate (BNPL, 6%) because that is the rate the fee was charged at.\n * A card-family order really costs 2.9%, so on those orders this subtracts\n * more than Stripe took and the take is UNDERSTATED — the safe direction, and\n * stated on the page rather than left to be discovered.\n *\n * ## Subscription cycles, and the one cycle this understates\n *\n * A storefront SUBSCRIPTION cycle carries a `subscriptionId`. Since AGL-2655\n * its fee carries the same pass-through, folded into\n * `application_fee_percent` as a rate because a Stripe subscription cannot\n * express a fixed 30¢ — so it is netted out here exactly as a one-time sale's\n * is. The percent is sized on the recurring goods and the recomputed cost here\n * is sized on the whole amount paid, tax included, so a taxed cycle subtracts\n * slightly more than was recovered: understated, the safe direction.\n *\n * A subscription sold before the pass-through existed is carried onto it by\n * the renewal re-price (AGL-2289) at its next paid invoice — but THAT invoice\n * was billed at the bare take, so its row's `feeCents` holds no pass-through\n * and the clamp reports its take as zero. One cycle per legacy subscription,\n * and the count beside the figure is how a reader sees how much of the book\n * that is.\n */\n\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { saleProcessingCostCents } from '@aglyn/aglyn/server'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { stripeIdIsTestMode } from '@aglyn/aglyn/app-utils/stripe-deployment-mode'\nimport {\n groupRevenueAttribution,\n type RevenueAttribution,\n type RevenueSource,\n type RevenueSourceAnswer,\n} from '@aglyn/aglyn/plugin-manager/plugin-revenue-sources'\n\n/** One `hosts/{hostId}/orders/{orderId}` row — a storefront sale. */\nexport interface CommerceOrderRowInput {\n id: string\n /** What the shopper paid, tax and shipping included. */\n amountCents?: unknown\n /**\n * The Connect `application_fee_amount`: the platform's advertised take PLUS\n * Stripe's processing cost passed through at cost (AGL-2152). NOT margin —\n * see the module note.\n */\n feeCents?: unknown\n /**\n * Present ONLY on a storefront SUBSCRIPTION renewal, and it changes how\n * `feeCents` must be read — see the module note.\n */\n subscriptionId?: unknown\n /** Merchant refunds AND chargebacks both land here (`refund.ts`). */\n refundedCents?: unknown\n /**\n * WHICH storefront the order belongs to — the attribution key.\n *\n * Orders live at `hosts/{hostId}/orders/{orderId}`, so this is lifted from\n * the document PATH by the reader rather than read from a field. It costs no\n * extra read and cannot disagree with where the document actually is.\n */\n hostId?: unknown\n createdAt?: unknown\n /**\n * Whether Stripe moved real money, stamped from `event.livemode` by the\n * webhook. Authoritative when present, and absent on every order written\n * before that stamp shipped — which is why {@link isTestModeOrderRow} falls\n * back to the id below rather than treating absence as an answer.\n */\n livemode?: unknown\n /**\n * The Checkout Session that produced the order. It carries its own mode\n * (`cs_test_…`), which a subscription renewal's invoice id does not — so\n * this is the fallback discriminator for rows predating `livemode`.\n */\n checkoutSessionId?: unknown\n}\n\nexport interface CommerceSettled {\n transactionCount: number\n /** Shopper spend across storefronts. Overwhelmingly the merchant's. */\n grossCents: number\n /** The whole `application_fee_amount` the platform collected. NOT margin. */\n applicationFeeCents: number\n /** Stripe's processing cost this recovered, at cost. Subtracted, never earnings. */\n processingPassThroughCents: number\n /** Application fee minus the pass-through: the advertised take. */\n commissionCents: number\n /** Take handed back with refunds and chargebacks, pro-rata. */\n commissionRefundedCents: number\n /** Take net of reversals. */\n commissionNetCents: number\n /**\n * Storefront SUBSCRIPTION cycles in this period. Counted because a cycle\n * billed before its subscription was re-priced onto the pass-through\n * reports no take at all — see the module note.\n */\n subscriptionOrders: number\n /**\n * The sweep hit its ceiling, so every figure above is a LOWER BOUND and must\n * not be quoted as a total. Narrow the period instead.\n */\n truncated: boolean\n}\n\n/** Cents from anything, defaulting to 0 rather than NaN. */\nfunction cents(value: unknown): number {\n const parsed = Number(value ?? 0)\n return Number.isFinite(parsed) ? Math.round(parsed) : 0\n}\n\n/**\n * Whether this order row was a test-mode rehearsal.\n *\n * A recorded `livemode` wins, and the session id's prefix is the fallback for\n * rows written before anything recorded it. An order with neither signal is\n * LIVE: a POS cash sale carries no Stripe session at all, and answering \"test\"\n * for anything unidentifiable would erase genuine revenue from the report.\n */\nfunction isTestModeOrderRow(row: CommerceOrderRowInput): boolean {\n if (typeof row.livemode === 'boolean') return !row.livemode\n return stripeIdIsTestMode(row.checkoutSessionId ?? row.id)\n}\n\nexport function commerceSettledSummary(\n rows: readonly CommerceOrderRowInput[],\n truncated = false,\n): CommerceSettled {\n const out: CommerceSettled = {\n transactionCount: 0,\n grossCents: 0,\n applicationFeeCents: 0,\n processingPassThroughCents: 0,\n commissionCents: 0,\n commissionRefundedCents: 0,\n commissionNetCents: 0,\n subscriptionOrders: 0,\n truncated: truncated === true,\n }\n for (const row of rows ?? []) {\n // A REHEARSAL IS NOT REVENUE. A smoke-test checkout writes a real order\n // document — Stripe never moved money for it, and its session id says so.\n // Skipped ENTIRELY rather than counted at zero, because `transactionCount`\n // is read as \"how many sales\", and a rehearsal is not one.\n if (isTestModeOrderRow(row)) continue\n const split = commerceOrderTake(row)\n out.transactionCount += 1\n out.grossCents += split.gross\n out.applicationFeeCents += split.fee\n if (split.isSubscriptionOrder) out.subscriptionOrders += 1\n out.processingPassThroughCents += split.passThrough\n out.commissionCents += split.take\n out.commissionRefundedCents += split.takeRefunded\n out.commissionNetCents += split.takeNet\n }\n return out\n}\n\n/**\n * One storefront order's take, in ONE place.\n *\n * Shared with the per-host attribution so a host table cannot sum to\n * something other than the storefront line above it.\n *\n * A zero-fee order contributes its gross and its count and nothing else —\n * there is no take to attribute, and inventing one from the gross would\n * report a merchant's money as the platform's.\n */\nexport function commerceOrderTake(row: CommerceOrderRowInput | null): {\n gross: number\n fee: number\n isSubscriptionOrder: boolean\n passThrough: number\n take: number\n takeRefunded: number\n takeNet: number\n} {\n const gross = cents(row?.amountCents)\n const fee = Math.max(0, cents(row?.feeCents))\n const isSubscriptionOrder =\n typeof row?.subscriptionId === 'string' && row.subscriptionId.length > 0\n if (fee <= 0) {\n return {\n gross,\n fee,\n isSubscriptionOrder,\n passThrough: 0,\n take: 0,\n takeRefunded: 0,\n takeNet: 0,\n }\n }\n // Every fee bundles the recovery — a one-time sale's in cents, a\n // subscription cycle's as a rate (AGL-2655). Clamped to the fee itself: the\n // recomputed cost can exceed a fee charged under an older rate, and a\n // negative take would subtract from another order's real margin.\n const passThrough = Math.min(fee, saleProcessingCostCents(gross))\n const take = fee - passThrough\n const refunded = Math.min(gross, Math.max(0, cents(row?.refundedCents)))\n const takeRefunded = gross > 0 ? Math.round((refunded * take) / gross) : 0\n return {\n gross,\n fee,\n isSubscriptionOrder,\n passThrough,\n take,\n takeRefunded,\n takeNet: take - takeRefunded,\n }\n}\n\n/**\n * Storefront take by HOST.\n *\n * By host and not by org on purpose: one org can run several storefronts, and\n * \"which store earns\" is the question a per-org roll-up destroys.\n */\nexport function commerceHostAttribution(\n rows: readonly CommerceOrderRowInput[],\n limit = 100,\n): RevenueAttribution {\n return groupRevenueAttribution(\n (rows ?? []).map((row) => {\n const split = commerceOrderTake(row)\n return {\n key: String(row?.hostId ?? ''),\n detail: '',\n gain: split.takeNet,\n loss: split.takeRefunded,\n }\n }),\n limit,\n 'Host not recorded',\n )\n}\n\n/**\n * The storefront's answer for one period, from figures already folded. Pure,\n * so what the report prints can be proved from fixtures.\n *\n * `failed` is a sweep that could not run — a collection-group index this\n * deployment has not built answers FAILED_PRECONDITION — and it is reported as\n * a failure with figures of zero, never as a cap: \"we read part of it\" and \"we\n * read none of it\" have different remedies.\n */\nexport function commerceRevenueAnswer(read: {\n settled: CommerceSettled\n byHost: RevenueAttribution\n failed: boolean\n}): RevenueSourceAnswer {\n const brand = PLATFORM_BRAND_NAME\n const { settled } = read\n return {\n id: 'commerce',\n name: 'storefront orders',\n earned: {\n label: 'Storefront commission',\n cents: Number(settled.commissionNetCents ?? 0),\n note:\n 'The advertised take on merchant storefront sales, net of refunds — ' +\n 'with Stripe’s card processing removed. The platform fee charged on a ' +\n 'storefront sale bundles that processing cost and passes it through at ' +\n 'cost; it is a recovery, not earnings.',\n },\n grossToNet: [\n {\n label: 'Storefront sales (shopper gross)',\n cents: settled.grossCents,\n deduction: false,\n note:\n 'The merchant’s. It transfers straight to their connected account ' +\n 'and is shown only for scale.',\n },\n {\n label: 'Storefront platform fee collected',\n cents: settled.applicationFeeCents,\n deduction: false,\n note: `Not all ${brand}’s — see the next line.`,\n },\n {\n label: '— less card processing passed through at cost',\n cents: settled.processingPassThroughCents,\n deduction: true,\n note: `Stripe’s. On a destination charge Stripe debits ${brand}’s balance for processing, and this half of the fee recovers exactly that. It is a recovery, not earnings, and reporting it as revenue would overstate every storefront sale.`,\n },\n ],\n notes:\n Number(settled.subscriptionOrders ?? 0) > 0\n ? [\n {\n label: `${settled.subscriptionOrders} storefront subscription cycles — one billed before its re-price reports no take`,\n tone: 'warning',\n },\n ]\n : [],\n attribution: [\n {\n id: 'byHost',\n heading: 'Storefront take by host',\n unit: 'Storefront',\n countLabel: 'Orders',\n empty: `No storefront order settled in this period. Note this is ${brand}'s take only — the shopper's spend is the merchant's money and is never counted here.`,\n chartEmpty: 'No storefront earned a take in this period — nothing to plot yet.',\n ...read.byHost,\n },\n ],\n attributionNote:\n \"Storefront figures above are the advertised take with Stripe's \" +\n 'processing cost already subtracted, on the basis stated in “Gross ' +\n 'versus net” below. Attribution is by host rather than by org because ' +\n 'one org can run several storefronts, and rolling them up destroys the ' +\n 'question.',\n truncated: settled.truncated,\n failure: read.failed\n ? {\n title: 'Storefront orders could not be read',\n detail:\n 'The storefront commission below reads $0 because the query ' +\n 'failed, not because there were no sales. The sweep needs the ' +\n 'COLLECTION_GROUP index on orders.createdAtMs — check it is still ' +\n 'declared in the Firestore index config and actually deployed, ' +\n 'since indexes ship separately from the app.',\n }\n : null,\n summary: settled,\n }\n}\n\n/**\n * The storefront's source, registered on the console's API surface: the\n * staff revenue report awaits that surface before it asks.\n */\nexport const commerceRevenueSource: RevenueSource = {\n async read(request) {\n const firestore = firebaseAdmin.app().firestore()\n // Storefront orders live per host (`hosts/{hostId}/orders`), so this is a\n // collection-GROUP range — ranged on `createdAtMs`, the NUMBER, and not on\n // the `createdAt` Timestamp beside it. A collection-group range needs a\n // COLLECTION_GROUP-scoped single-field index — Firestore's automatic ones\n // are COLLECTION scope only — and the index that is declared and deployed\n // is on `createdAtMs` (AGL-1793). The `createdAt` form answers\n // FAILED_PRECONDITION on every request, which is how the report once read\n // $0 for every storefront.\n let swept: {\n docs: FirebaseFirestore.QueryDocumentSnapshot[]\n truncated: boolean\n } | null\n try {\n swept = await request.sweep<FirebaseFirestore.QueryDocumentSnapshot>(\n firestore\n .collectionGroup('orders')\n .where('createdAtMs', '>=', request.start.getTime())\n .where('createdAtMs', '<', request.end.getTime()),\n 'createdAtMs',\n )\n } catch {\n swept = null\n }\n const rows: CommerceOrderRowInput[] = (swept?.docs ?? []).map((doc) => ({\n id: doc.id,\n // The storefront that earned the take is in the PATH.\n hostId: doc.ref.parent.parent?.id ?? '',\n ...(doc.data() as object),\n }))\n const settled = commerceSettledSummary(rows, swept?.truncated === true)\n const byHost = commerceHostAttribution(rows, request.attributionLimit)\n await request.nameRows(byHost.rows, {\n collection: 'hosts',\n nameField: 'displayName',\n detailField: 'subdomain',\n })\n return commerceRevenueAnswer({ settled, byHost, failed: swept === null })\n },\n}\n"],"names":["firebaseAdmin","saleProcessingCostCents","PLATFORM_BRAND_NAME","stripeIdIsTestMode","groupRevenueAttribution","cents","value","parsed","Number","isFinite","Math","round","isTestModeOrderRow","row","livemode","checkoutSessionId","id","commerceSettledSummary","rows","truncated","out","transactionCount","grossCents","applicationFeeCents","processingPassThroughCents","commissionCents","commissionRefundedCents","commissionNetCents","subscriptionOrders","split","commerceOrderTake","gross","fee","isSubscriptionOrder","passThrough","take","takeRefunded","takeNet","amountCents","max","feeCents","subscriptionId","length","min","refunded","refundedCents","commerceHostAttribution","limit","map","key","String","hostId","detail","gain","loss","commerceRevenueAnswer","read","settled","brand","name","earned","label","note","grossToNet","deduction","notes","tone","attribution","heading","unit","countLabel","empty","chartEmpty","byHost","attributionNote","failure","failed","title","summary","commerceRevenueSource","request","firestore","app","swept","sweep","collectionGroup","where","start","getTime","end","docs","doc","ref","parent","data","attributionLimit","nameRows","collection","nameField","detailField"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiDC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,uBAAuB,QAAQ,sBAAqB;AAC7D,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,kBAAkB,QAAQ,gDAA+C;AAClF,SACEC,uBAAuB,QAIlB,qDAAoD;AAuE3D,0DAA0D,GAC1D,SAASC,MAAMC,KAAc;IAC3B,MAAMC,SAASC,OAAOF,gBAAAA,QAAS;IAC/B,OAAOE,OAAOC,QAAQ,CAACF,UAAUG,KAAKC,KAAK,CAACJ,UAAU;AACxD;AAEA;;;;;;;CAOC,GACD,SAASK,mBAAmBC,GAA0B;QAE1BA;IAD1B,IAAI,OAAOA,IAAIC,QAAQ,KAAK,WAAW,OAAO,CAACD,IAAIC,QAAQ;IAC3D,OAAOX,oBAAmBU,yBAAAA,IAAIE,iBAAiB,YAArBF,yBAAyBA,IAAIG,EAAE;AAC3D;AAEA,OAAO,SAASC,uBACdC,IAAsC,EACtCC,YAAY,KAAK;IAEjB,MAAMC,MAAuB;QAC3BC,kBAAkB;QAClBC,YAAY;QACZC,qBAAqB;QACrBC,4BAA4B;QAC5BC,iBAAiB;QACjBC,yBAAyB;QACzBC,oBAAoB;QACpBC,oBAAoB;QACpBT,WAAWA,cAAc;IAC3B;IACA,KAAK,MAAMN,OAAOK,eAAAA,OAAQ,EAAE,CAAE;QAC5B,wEAAwE;QACxE,0EAA0E;QAC1E,2EAA2E;QAC3E,2DAA2D;QAC3D,IAAIN,mBAAmBC,MAAM;QAC7B,MAAMgB,QAAQC,kBAAkBjB;QAChCO,IAAIC,gBAAgB,IAAI;QACxBD,IAAIE,UAAU,IAAIO,MAAME,KAAK;QA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5C,sBAAsB;YAAEE;YAASgB;YAAQG,QAAQO,UAAU;QAAK;IACzE;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/revenue-source.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * The storefront's take on the operator's revenue report (AGL-2486, AGL-3080).\n *\n * Answered through the platform's revenue source contract\n * (`@aglyn/aglyn/plugin-manager/plugin-revenue-sources`). The report folds the\n * operator's own invoices; this is what storefront orders earned it — and the\n * one figure on that page most likely to be reported wrongly.\n *\n * An order's `feeCents` is the Connect `application_fee_amount`, which since\n * AGL-2152 is the advertised take PLUS Stripe's processing cost:\n *\n * fee = take%(goods) + processing%(charge) + 30¢\n *\n * Every storefront charge is a DESTINATION charge, so Stripe moves the whole\n * amount to the merchant and debits its processing fee from the PLATFORM's\n * balance; the pass-through half of that fee exists purely to recover a cost\n * the platform has already paid. Reporting `feeCents` as earnings would\n * overstate the margin on every single storefront sale — and on a small order\n * it would report the 30¢ Stripe just took as money the platform made.\n *\n * So the pass-through is recomputed with the SAME helper the fee was charged\n * from (`salePlatformCostCents`) and subtracted. Both halves are\n * reported, because \"we collected X of which Y was Stripe's\" is the sentence a\n * margin figure needs.\n *\n * The recomputation is an estimate in one direction only: it re-derives the\n * cost from the stored charge amount rather than reading Stripe's actual\n * balance-transaction fee, and it prices it at the DEAREST enabled payment\n * method's rate (BNPL, 6%) because that is the rate the fee was charged at.\n * A card-family order really costs 2.9%, so on those orders this subtracts\n * more than Stripe took and the take is UNDERSTATED — the safe direction, and\n * stated on the page rather than left to be discovered.\n *\n * ## Subscription cycles, and the one cycle this understates\n *\n * A storefront SUBSCRIPTION cycle carries a `subscriptionId`. Since AGL-2655\n * its fee carries the same pass-through, folded into\n * `application_fee_percent` as a rate because a Stripe subscription cannot\n * express a fixed 30¢ — so it is netted out here exactly as a one-time sale's\n * is. The percent is sized on the recurring goods and the recomputed cost here\n * is sized on the whole amount paid, tax included, so a taxed cycle subtracts\n * slightly more than was recovered: understated, the safe direction.\n *\n * A subscription sold before the pass-through existed is carried onto it by\n * the renewal re-price (AGL-2289) at its next paid invoice — but THAT invoice\n * was billed at the bare take, so its row's `feeCents` holds no pass-through\n * and the clamp reports its take as zero. One cycle per legacy subscription,\n * and the count beside the figure is how a reader sees how much of the book\n * that is.\n *\n * ## Direct charges: the fee IS the take\n *\n * A seller on its own full Stripe account sells by DIRECT charge (the order\n * carries `chargeModel: 'direct'`, stamped by the webhook). Stripe bills that\n * seller its own processing and charges the platform nothing for the sale,\n * so the application fee is the plan's take alone and there is no\n * pass-through to subtract: on those orders the whole fee is commission. The\n * shopper's tax on a direct sale is the seller's and never reaches this\n * report, which counts only the fee.\n */\n\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { salePlatformCostCents } from '@aglyn/aglyn/server'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { stripeIdIsTestMode } from '@aglyn/aglyn/app-utils/stripe-deployment-mode'\nimport {\n groupRevenueAttribution,\n type RevenueAttribution,\n type RevenueSource,\n type RevenueSourceAnswer,\n} from '@aglyn/aglyn/plugin-manager/plugin-revenue-sources'\n\n/** One `hosts/{hostId}/orders/{orderId}` row — a storefront sale. */\nexport interface CommerceOrderRowInput {\n id: string\n /** What the shopper paid, tax and shipping included. */\n amountCents?: unknown\n /**\n * The Connect `application_fee_amount`: the platform's advertised take PLUS\n * Stripe's processing cost passed through at cost (AGL-2152). NOT margin —\n * see the module note.\n */\n feeCents?: unknown\n /**\n * Present ONLY on a storefront SUBSCRIPTION renewal, and it changes how\n * `feeCents` must be read — see the module note.\n */\n subscriptionId?: unknown\n /** Merchant refunds AND chargebacks both land here (`refund.ts`). */\n refundedCents?: unknown\n /**\n * `'direct'` for a sale made on the seller's own Stripe account, where the\n * fee is the take with no processing pass-through (see the module note).\n * Absent on every destination sale.\n */\n chargeModel?: unknown\n /**\n * WHICH storefront the order belongs to — the attribution key.\n *\n * Orders live at `hosts/{hostId}/orders/{orderId}`, so this is lifted from\n * the document PATH by the reader rather than read from a field. It costs no\n * extra read and cannot disagree with where the document actually is.\n */\n hostId?: unknown\n createdAt?: unknown\n /**\n * Whether Stripe moved real money, stamped from `event.livemode` by the\n * webhook. Authoritative when present, and absent on every order written\n * before that stamp shipped — which is why {@link isTestModeOrderRow} falls\n * back to the id below rather than treating absence as an answer.\n */\n livemode?: unknown\n /**\n * The Checkout Session that produced the order. It carries its own mode\n * (`cs_test_…`), which a subscription renewal's invoice id does not — so\n * this is the fallback discriminator for rows predating `livemode`.\n */\n checkoutSessionId?: unknown\n}\n\nexport interface CommerceSettled {\n transactionCount: number\n /** Shopper spend across storefronts. Overwhelmingly the merchant's. */\n grossCents: number\n /** The whole `application_fee_amount` the platform collected. NOT margin. */\n applicationFeeCents: number\n /** Stripe's processing cost this recovered, at cost. Subtracted, never earnings. */\n processingPassThroughCents: number\n /** Application fee minus the pass-through: the advertised take. */\n commissionCents: number\n /** Take handed back with refunds and chargebacks, pro-rata. */\n commissionRefundedCents: number\n /** Take net of reversals. */\n commissionNetCents: number\n /**\n * Storefront SUBSCRIPTION cycles in this period. Counted because a cycle\n * billed before its subscription was re-priced onto the pass-through\n * reports no take at all — see the module note.\n */\n subscriptionOrders: number\n /**\n * The sweep hit its ceiling, so every figure above is a LOWER BOUND and must\n * not be quoted as a total. Narrow the period instead.\n */\n truncated: boolean\n}\n\n/** Cents from anything, defaulting to 0 rather than NaN. */\nfunction cents(value: unknown): number {\n const parsed = Number(value ?? 0)\n return Number.isFinite(parsed) ? Math.round(parsed) : 0\n}\n\n/**\n * Whether this order row was a test-mode rehearsal.\n *\n * A recorded `livemode` wins, and the session id's prefix is the fallback for\n * rows written before anything recorded it. An order with neither signal is\n * LIVE: a POS cash sale carries no Stripe session at all, and answering \"test\"\n * for anything unidentifiable would erase genuine revenue from the report.\n */\nfunction isTestModeOrderRow(row: CommerceOrderRowInput): boolean {\n if (typeof row.livemode === 'boolean') return !row.livemode\n return stripeIdIsTestMode(row.checkoutSessionId ?? row.id)\n}\n\nexport function commerceSettledSummary(\n rows: readonly CommerceOrderRowInput[],\n truncated = false,\n): CommerceSettled {\n const out: CommerceSettled = {\n transactionCount: 0,\n grossCents: 0,\n applicationFeeCents: 0,\n processingPassThroughCents: 0,\n commissionCents: 0,\n commissionRefundedCents: 0,\n commissionNetCents: 0,\n subscriptionOrders: 0,\n truncated: truncated === true,\n }\n for (const row of rows ?? []) {\n // A REHEARSAL IS NOT REVENUE. A smoke-test checkout writes a real order\n // document — Stripe never moved money for it, and its session id says so.\n // Skipped ENTIRELY rather than counted at zero, because `transactionCount`\n // is read as \"how many sales\", and a rehearsal is not one.\n if (isTestModeOrderRow(row)) continue\n const split = commerceOrderTake(row)\n out.transactionCount += 1\n out.grossCents += split.gross\n out.applicationFeeCents += split.fee\n if (split.isSubscriptionOrder) out.subscriptionOrders += 1\n out.processingPassThroughCents += split.passThrough\n out.commissionCents += split.take\n out.commissionRefundedCents += split.takeRefunded\n out.commissionNetCents += split.takeNet\n }\n return out\n}\n\n/**\n * One storefront order's take, in ONE place.\n *\n * Shared with the per-host attribution so a host table cannot sum to\n * something other than the storefront line above it.\n *\n * A zero-fee order contributes its gross and its count and nothing else —\n * there is no take to attribute, and inventing one from the gross would\n * report a merchant's money as the platform's.\n */\nexport function commerceOrderTake(row: CommerceOrderRowInput | null): {\n gross: number\n fee: number\n isSubscriptionOrder: boolean\n passThrough: number\n take: number\n takeRefunded: number\n takeNet: number\n} {\n const gross = cents(row?.amountCents)\n const fee = Math.max(0, cents(row?.feeCents))\n const isSubscriptionOrder =\n typeof row?.subscriptionId === 'string' && row.subscriptionId.length > 0\n if (fee <= 0) {\n return {\n gross,\n fee,\n isSubscriptionOrder,\n passThrough: 0,\n take: 0,\n takeRefunded: 0,\n takeNet: 0,\n }\n }\n // Every fee bundles the recovery — a one-time sale's in cents, a\n // subscription cycle's as a rate (AGL-2655). Since AGL-4198 the take also\n // pays Stripe's payout charge first, so what the platform keeps is the fee\n // less everything Stripe charges it for the sale, not less the card alone.\n // Clamped to the fee itself: the recomputed cost can exceed a fee charged\n // under an older rate, and a negative take would subtract from another\n // order's real margin.\n //\n // A direct charge costs the platform nothing at Stripe, so its fee is\n // already the bare take.\n const passThrough =\n row?.chargeModel === 'direct' ? 0 : Math.min(fee, salePlatformCostCents(gross))\n const take = fee - passThrough\n const refunded = Math.min(gross, Math.max(0, cents(row?.refundedCents)))\n const takeRefunded = gross > 0 ? Math.round((refunded * take) / gross) : 0\n return {\n gross,\n fee,\n isSubscriptionOrder,\n passThrough,\n take,\n takeRefunded,\n takeNet: take - takeRefunded,\n }\n}\n\n/**\n * Storefront take by HOST.\n *\n * By host and not by org on purpose: one org can run several storefronts, and\n * \"which store earns\" is the question a per-org roll-up destroys.\n */\nexport function commerceHostAttribution(\n rows: readonly CommerceOrderRowInput[],\n limit = 100,\n): RevenueAttribution {\n return groupRevenueAttribution(\n (rows ?? []).map((row) => {\n const split = commerceOrderTake(row)\n return {\n key: String(row?.hostId ?? ''),\n detail: '',\n gain: split.takeNet,\n loss: split.takeRefunded,\n }\n }),\n limit,\n 'Host not recorded',\n )\n}\n\n/**\n * The storefront's answer for one period, from figures already folded. Pure,\n * so what the report prints can be proved from fixtures.\n *\n * `failed` is a sweep that could not run — a collection-group index this\n * deployment has not built answers FAILED_PRECONDITION — and it is reported as\n * a failure with figures of zero, never as a cap: \"we read part of it\" and \"we\n * read none of it\" have different remedies.\n */\nexport function commerceRevenueAnswer(read: {\n settled: CommerceSettled\n byHost: RevenueAttribution\n failed: boolean\n}): RevenueSourceAnswer {\n const brand = PLATFORM_BRAND_NAME\n const { settled } = read\n return {\n id: 'commerce',\n name: 'storefront orders',\n earned: {\n label: 'Storefront commission',\n cents: Number(settled.commissionNetCents ?? 0),\n note:\n 'The advertised take on merchant storefront sales, net of refunds — ' +\n 'with Stripe’s card processing removed. The platform fee charged on a ' +\n 'storefront sale bundles that processing cost and passes it through at ' +\n 'cost; it is a recovery, not earnings.',\n },\n grossToNet: [\n {\n label: 'Storefront sales (shopper gross)',\n cents: settled.grossCents,\n deduction: false,\n note:\n 'The merchant’s. It transfers straight to their connected account ' +\n '(or, on a direct charge, settles there to begin with), tax ' +\n 'included, and is shown only for scale.',\n },\n {\n label: 'Storefront platform fee collected',\n cents: settled.applicationFeeCents,\n deduction: false,\n note: `Not all ${brand}’s — see the next line.`,\n },\n {\n label: '— less card processing and payouts passed through at cost',\n cents: settled.processingPassThroughCents,\n deduction: true,\n note: `Stripe’s. On a destination charge Stripe debits ${brand}’s balance for processing, and this half of the fee recovers exactly that. It is a recovery, not earnings, and reporting it as revenue would overstate every storefront sale. A direct charge has none: Stripe bills the seller, so its whole fee is the take.`,\n },\n ],\n notes:\n Number(settled.subscriptionOrders ?? 0) > 0\n ? [\n {\n label: `${settled.subscriptionOrders} storefront subscription cycles — one billed before its re-price reports no take`,\n tone: 'warning',\n },\n ]\n : [],\n attribution: [\n {\n id: 'byHost',\n heading: 'Storefront take by host',\n unit: 'Storefront',\n countLabel: 'Orders',\n empty: `No storefront order settled in this period. Note this is ${brand}'s take only — the shopper's spend is the merchant's money and is never counted here.`,\n chartEmpty: 'No storefront earned a take in this period — nothing to plot yet.',\n ...read.byHost,\n },\n ],\n attributionNote:\n \"Storefront figures above are the advertised take with Stripe's \" +\n 'processing cost already subtracted, on the basis stated in “Gross ' +\n 'versus net” below. Attribution is by host rather than by org because ' +\n 'one org can run several storefronts, and rolling them up destroys the ' +\n 'question.',\n truncated: settled.truncated,\n failure: read.failed\n ? {\n title: 'Storefront orders could not be read',\n detail:\n 'The storefront commission below reads $0 because the query ' +\n 'failed, not because there were no sales. The sweep needs the ' +\n 'COLLECTION_GROUP index on orders.createdAtMs — check it is still ' +\n 'declared in the Firestore index config and actually deployed, ' +\n 'since indexes ship separately from the app.',\n }\n : null,\n summary: settled,\n }\n}\n\n/**\n * The storefront's source, registered on the console's API surface: the\n * staff revenue report awaits that surface before it asks.\n */\nexport const commerceRevenueSource: RevenueSource = {\n async read(request) {\n const firestore = firebaseAdmin.app().firestore()\n // Storefront orders live per host (`hosts/{hostId}/orders`), so this is a\n // collection-GROUP range — ranged on `createdAtMs`, the NUMBER, and not on\n // the `createdAt` Timestamp beside it. A collection-group range needs a\n // COLLECTION_GROUP-scoped single-field index — Firestore's automatic ones\n // are COLLECTION scope only — and the index that is declared and deployed\n // is on `createdAtMs` (AGL-1793). The `createdAt` form answers\n // FAILED_PRECONDITION on every request, which is how the report once read\n // $0 for every storefront.\n let swept: {\n docs: FirebaseFirestore.QueryDocumentSnapshot[]\n truncated: boolean\n } | null\n try {\n swept = await request.sweep<FirebaseFirestore.QueryDocumentSnapshot>(\n firestore\n .collectionGroup('orders')\n .where('createdAtMs', '>=', request.start.getTime())\n .where('createdAtMs', '<', request.end.getTime()),\n 'createdAtMs',\n )\n } catch {\n swept = null\n }\n const rows: CommerceOrderRowInput[] = (swept?.docs ?? []).map((doc) => ({\n id: doc.id,\n // The storefront that earned the take is in the PATH.\n hostId: doc.ref.parent.parent?.id ?? '',\n ...(doc.data() as object),\n }))\n const settled = commerceSettledSummary(rows, swept?.truncated === true)\n const byHost = commerceHostAttribution(rows, request.attributionLimit)\n await request.nameRows(byHost.rows, {\n collection: 'hosts',\n nameField: 'displayName',\n detailField: 'subdomain',\n })\n return commerceRevenueAnswer({ settled, byHost, failed: swept === null })\n },\n}\n"],"names":["firebaseAdmin","salePlatformCostCents","PLATFORM_BRAND_NAME","stripeIdIsTestMode","groupRevenueAttribution","cents","value","parsed","Number","isFinite","Math","round","isTestModeOrderRow","row","livemode","checkoutSessionId","id","commerceSettledSummary","rows","truncated","out","transactionCount","grossCents","applicationFeeCents","processingPassThroughCents","commissionCents","commissionRefundedCents","commissionNetCents","subscriptionOrders","split","commerceOrderTake","gross","fee","isSubscriptionOrder","passThrough","take","takeRefunded","takeNet","amountCents","max","feeCents","subscriptionId","length","chargeModel","min","refunded","refundedCents","commerceHostAttribution","limit","map","key","String","hostId","detail","gain","loss","commerceRevenueAnswer","read","settled","brand","name","earned","label","note","grossToNet","deduction","notes","tone","attribution","heading","unit","countLabel","empty","chartEmpty","byHost","attributionNote","failure","failed","title","summary","commerceRevenueSource","request","firestore","app","swept","sweep","collectionGroup","where","start","getTime","end","docs","doc","ref","parent","data","attributionLimit","nameRows","collection","nameField","detailField"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2DC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AACxD,SAASC,qBAAqB,QAAQ,sBAAqB;AAC3D,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,kBAAkB,QAAQ,gDAA+C;AAClF,SACEC,uBAAuB,QAIlB,qDAAoD;AA6E3D,0DAA0D,GAC1D,SAASC,MAAMC,KAAc;IAC3B,MAAMC,SAASC,OAAOF,gBAAAA,QAAS;IAC/B,OAAOE,OAAOC,QAAQ,CAACF,UAAUG,KAAKC,KAAK,CAACJ,UAAU;AACxD;AAEA;;;;;;;CAOC,GACD,SAASK,mBAAmBC,GAA0B;QAE1BA;IAD1B,IAAI,OAAOA,IAAIC,QAAQ,KAAK,WAAW,OAAO,CAACD,IAAIC,QAAQ;IAC3D,OAAOX,oBAAmBU,yBAAAA,IAAIE,iBAAiB,YAArBF,yBAAyBA,IAAIG,EAAE;AAC3D;AAEA,OAAO,SAASC,uBACdC,IAAsC,EACtCC,YAAY,KAAK;IAEjB,MAAMC,MAAuB;QAC3BC,kB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QACV;QACA,MAAMlE,OAAgC,SAACkE,yBAAAA,MAAOO,IAAI,mBAAI,EAAE,EAAE1C,GAAG,CAAC,CAAC2C;;gBAGrDA;mBAH8D;gBACtE5E,IAAI4E,IAAI5E,EAAE;gBACV,sDAAsD;gBACtDoC,MAAM,WAAEwC,yBAAAA,IAAIC,GAAG,CAACC,MAAM,CAACA,MAAM,qBAArBF,uBAAuB5E,EAAE,mBAAI;eACjC4E,IAAIG,IAAI;;QAEd,MAAMrC,UAAUzC,uBAAuBC,MAAMkE,CAAAA,yBAAAA,MAAOjE,SAAS,MAAK;QAClE,MAAMuD,SAAS3B,wBAAwB7B,MAAM+D,QAAQe,gBAAgB;QACrE,MAAMf,QAAQgB,QAAQ,CAACvB,OAAOxD,IAAI,EAAE;YAClCgF,YAAY;YACZC,WAAW;YACXC,aAAa;QACf;QACA,OAAO5C,sBAAsB;YAAEE;YAASgB;YAAQG,QAAQO,UAAU;QAAK;IACzE;AACF,EAAC"}
|
|
@@ -0,0 +1,45 @@
|
|
|
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
|
+
/** The seller's account when the site sells by direct charges, else null. */
|
|
18
|
+
export declare function directSellerAccountForHost(hostId: string): Promise<string | null>;
|
|
19
|
+
/**
|
|
20
|
+
* `fetch` against the Stripe API on the seller's account first, then on the
|
|
21
|
+
* platform when the seller's account does not know the object. With no
|
|
22
|
+
* seller account it is a plain platform call.
|
|
23
|
+
*/
|
|
24
|
+
export declare function fetchOnSellerThenPlatform(url: string, init: RequestInit & {
|
|
25
|
+
headers?: Record<string, string>;
|
|
26
|
+
}, sellerAccount: string | null | undefined): Promise<Response>;
|
|
27
|
+
/** Whether a Stripe object says it was sold by direct charge. */
|
|
28
|
+
export declare function isDirectChargeObject(object: any): boolean;
|
|
29
|
+
/**
|
|
30
|
+
* What a shopper is told when a direct-charge store chose Stripe Tax but has
|
|
31
|
+
* not finished setting it up on its own Stripe account. Refused rather than
|
|
32
|
+
* sold untaxed, the same doctrine as an unfinished tax settings card
|
|
33
|
+
* (AGL-2145): the store decided to collect, so a zero-tax sale would be wrong.
|
|
34
|
+
*/
|
|
35
|
+
export declare const SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE = "This store is finishing its sales tax setup. Please try again later.";
|
|
36
|
+
/**
|
|
37
|
+
* Whether the seller's own Stripe Tax is set up (head office, preset tax
|
|
38
|
+
* code, at least one registration): Stripe's `tax/settings` status on their
|
|
39
|
+
* account. A direct-charge session asks for `automatic_tax` only when it is,
|
|
40
|
+
* because on an account without it Stripe refuses the session and the
|
|
41
|
+
* shopper is told checkout failed. Not set up means the seller has chosen not
|
|
42
|
+
* to collect through Stripe Tax yet: their tax, their call. Any failure to
|
|
43
|
+
* read reads as not set up, the answer that never blocks a sale.
|
|
44
|
+
*/
|
|
45
|
+
export declare function sellerStripeTaxActive(sellerAccount: string): Promise<boolean>;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
/**
|
|
3
|
+
* @license
|
|
4
|
+
* Copyright 2026 Aglyn LLC
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/ import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
18
|
+
import { saleChargeModel } from "@aglyn/tenant-data-admin/server/payment-provider";
|
|
19
|
+
/*==========================================
|
|
20
|
+
* WHERE A SITE SALE'S STRIPE OBJECTS LIVE
|
|
21
|
+
*
|
|
22
|
+
* A direct-charge sale's session, payment intent, customer and subscription
|
|
23
|
+
* live on the SELLER's connected account, and Stripe answers 404 for them on
|
|
24
|
+
* the platform. The routes that come back to a sale later (the return page's
|
|
25
|
+
* status read, a cancel, a refund lookup, the subscriber portal) only hold an
|
|
26
|
+
* id, so they ask the site which account sells for it, try that account
|
|
27
|
+
* first, and fall back to the platform on a 404. The fallback is what keeps
|
|
28
|
+
* the sales that stay on the platform readable from the same route: Aglyn's
|
|
29
|
+
* own card-reader hardware, and anything sold before the seller switched.
|
|
30
|
+
*=========================================*/ /** The seller's account when the site sells by direct charges, else null. */ export async function directSellerAccountForHost(hostId) {
|
|
31
|
+
if (!hostId) return null;
|
|
32
|
+
try {
|
|
33
|
+
var _ref, _profile_get;
|
|
34
|
+
var _ownerOrg_org;
|
|
35
|
+
const ownerOrg = await getOrgForHost(hostId);
|
|
36
|
+
const ownerUid = String((_ref = ownerOrg == null ? void 0 : (_ownerOrg_org = ownerOrg.org) == null ? void 0 : _ownerOrg_org.ownerUid) != null ? _ref : '');
|
|
37
|
+
if (!ownerUid) return null;
|
|
38
|
+
const profile = await firebaseAdmin.app().firestore().collection('profiles').doc(ownerUid).get();
|
|
39
|
+
const accountId = String((_profile_get = profile.get('stripeAccountId')) != null ? _profile_get : '').trim();
|
|
40
|
+
if (!accountId) return null;
|
|
41
|
+
return saleChargeModel(profile.get('stripeChargeModel')) === 'direct' ? accountId : null;
|
|
42
|
+
} catch (unused) {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* `fetch` against the Stripe API on the seller's account first, then on the
|
|
48
|
+
* platform when the seller's account does not know the object. With no
|
|
49
|
+
* seller account it is a plain platform call.
|
|
50
|
+
*/ export async function fetchOnSellerThenPlatform(url, init, sellerAccount) {
|
|
51
|
+
var _init_headers;
|
|
52
|
+
if (!sellerAccount) return fetch(url, init);
|
|
53
|
+
const onSeller = await fetch(url, _extends({}, init, {
|
|
54
|
+
headers: _extends({}, (_init_headers = init.headers) != null ? _init_headers : {}, {
|
|
55
|
+
'Stripe-Account': sellerAccount
|
|
56
|
+
})
|
|
57
|
+
}));
|
|
58
|
+
if (onSeller.status !== 404) return onSeller;
|
|
59
|
+
return fetch(url, init);
|
|
60
|
+
}
|
|
61
|
+
/** Whether a Stripe object says it was sold by direct charge. */ export function isDirectChargeObject(object) {
|
|
62
|
+
var _ref, _ref1, _ref2;
|
|
63
|
+
var _object_metadata, _object_subscription_details_metadata, _object_subscription_details, _object_parent_subscription_details_metadata, _object_parent_subscription_details, _object_parent;
|
|
64
|
+
return String((_ref = (_ref1 = (_ref2 = object == null ? void 0 : (_object_metadata = object.metadata) == null ? void 0 : _object_metadata.chargeModel) != null ? _ref2 : object == null ? void 0 : (_object_subscription_details = object.subscription_details) == null ? void 0 : (_object_subscription_details_metadata = _object_subscription_details.metadata) == null ? void 0 : _object_subscription_details_metadata.chargeModel) != null ? _ref1 : object == null ? void 0 : (_object_parent = object.parent) == null ? void 0 : (_object_parent_subscription_details = _object_parent.subscription_details) == null ? void 0 : (_object_parent_subscription_details_metadata = _object_parent_subscription_details.metadata) == null ? void 0 : _object_parent_subscription_details_metadata.chargeModel) != null ? _ref : '') === 'direct';
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* What a shopper is told when a direct-charge store chose Stripe Tax but has
|
|
68
|
+
* not finished setting it up on its own Stripe account. Refused rather than
|
|
69
|
+
* sold untaxed, the same doctrine as an unfinished tax settings card
|
|
70
|
+
* (AGL-2145): the store decided to collect, so a zero-tax sale would be wrong.
|
|
71
|
+
*/ export const SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE = 'This store is finishing its sales tax setup. Please try again later.';
|
|
72
|
+
/**
|
|
73
|
+
* Whether the seller's own Stripe Tax is set up (head office, preset tax
|
|
74
|
+
* code, at least one registration): Stripe's `tax/settings` status on their
|
|
75
|
+
* account. A direct-charge session asks for `automatic_tax` only when it is,
|
|
76
|
+
* because on an account without it Stripe refuses the session and the
|
|
77
|
+
* shopper is told checkout failed. Not set up means the seller has chosen not
|
|
78
|
+
* to collect through Stripe Tax yet: their tax, their call. Any failure to
|
|
79
|
+
* read reads as not set up, the answer that never blocks a sale.
|
|
80
|
+
*/ export async function sellerStripeTaxActive(sellerAccount) {
|
|
81
|
+
var _process_env_STRIPE_SECRET_KEY;
|
|
82
|
+
const key = String((_process_env_STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY) != null ? _process_env_STRIPE_SECRET_KEY : '').trim();
|
|
83
|
+
if (!key || !sellerAccount) return false;
|
|
84
|
+
try {
|
|
85
|
+
const response = await fetch('https://api.stripe.com/v1/tax/settings', {
|
|
86
|
+
headers: {
|
|
87
|
+
Authorization: `Bearer ${key}`,
|
|
88
|
+
'Stripe-Account': sellerAccount
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
if (!response.ok) return false;
|
|
92
|
+
const settings = await response.json().catch(()=>null);
|
|
93
|
+
return (settings == null ? void 0 : settings.status) === 'active';
|
|
94
|
+
} catch (unused) {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
//# sourceMappingURL=seller-stripe-account.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/seller-stripe-account.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { saleChargeModel } from '@aglyn/tenant-data-admin/server/payment-provider'\n\n/*==========================================\n * WHERE A SITE SALE'S STRIPE OBJECTS LIVE\n *\n * A direct-charge sale's session, payment intent, customer and subscription\n * live on the SELLER's connected account, and Stripe answers 404 for them on\n * the platform. The routes that come back to a sale later (the return page's\n * status read, a cancel, a refund lookup, the subscriber portal) only hold an\n * id, so they ask the site which account sells for it, try that account\n * first, and fall back to the platform on a 404. The fallback is what keeps\n * the sales that stay on the platform readable from the same route: Aglyn's\n * own card-reader hardware, and anything sold before the seller switched.\n *=========================================*/\n\n/** The seller's account when the site sells by direct charges, else null. */\nexport async function directSellerAccountForHost(\n hostId: string,\n): Promise<string | null> {\n if (!hostId) return null\n try {\n const ownerOrg = await getOrgForHost(hostId)\n const ownerUid = String(ownerOrg?.org?.ownerUid ?? '')\n if (!ownerUid) return null\n const profile = await firebaseAdmin\n .app()\n .firestore()\n .collection('profiles')\n .doc(ownerUid)\n .get()\n const accountId = String(profile.get('stripeAccountId') ?? '').trim()\n if (!accountId) return null\n return saleChargeModel(profile.get('stripeChargeModel')) === 'direct'\n ? accountId\n : null\n } catch {\n return null\n }\n}\n\n/**\n * `fetch` against the Stripe API on the seller's account first, then on the\n * platform when the seller's account does not know the object. With no\n * seller account it is a plain platform call.\n */\nexport async function fetchOnSellerThenPlatform(\n url: string,\n init: RequestInit & { headers?: Record<string, string> },\n sellerAccount: string | null | undefined,\n): Promise<Response> {\n if (!sellerAccount) return fetch(url, init)\n const onSeller = await fetch(url, {\n ...init,\n headers: { ...(init.headers ?? {}), 'Stripe-Account': sellerAccount },\n })\n if (onSeller.status !== 404) return onSeller\n return fetch(url, init)\n}\n\n/** Whether a Stripe object says it was sold by direct charge. */\nexport function isDirectChargeObject(object: any): boolean {\n return (\n String(\n object?.metadata?.chargeModel ??\n object?.subscription_details?.metadata?.chargeModel ??\n object?.parent?.subscription_details?.metadata?.chargeModel ??\n '',\n ) === 'direct'\n )\n}\n\n/**\n * What a shopper is told when a direct-charge store chose Stripe Tax but has\n * not finished setting it up on its own Stripe account. Refused rather than\n * sold untaxed, the same doctrine as an unfinished tax settings card\n * (AGL-2145): the store decided to collect, so a zero-tax sale would be wrong.\n */\nexport const SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE =\n 'This store is finishing its sales tax setup. Please try again later.'\n\n/**\n * Whether the seller's own Stripe Tax is set up (head office, preset tax\n * code, at least one registration): Stripe's `tax/settings` status on their\n * account. A direct-charge session asks for `automatic_tax` only when it is,\n * because on an account without it Stripe refuses the session and the\n * shopper is told checkout failed. Not set up means the seller has chosen not\n * to collect through Stripe Tax yet: their tax, their call. Any failure to\n * read reads as not set up, the answer that never blocks a sale.\n */\nexport async function sellerStripeTaxActive(\n sellerAccount: string,\n): Promise<boolean> {\n const key = String(process.env.STRIPE_SECRET_KEY ?? '').trim()\n if (!key || !sellerAccount) return false\n try {\n const response = await fetch('https://api.stripe.com/v1/tax/settings', {\n headers: { Authorization: `Bearer ${key}`, 'Stripe-Account': sellerAccount },\n })\n if (!response.ok) return false\n const settings = (await response.json().catch(() => null)) as {\n status?: string\n } | null\n return settings?.status === 'active'\n } catch {\n return false\n }\n}\n"],"names":["firebaseAdmin","getOrgForHost","saleChargeModel","directSellerAccountForHost","hostId","profile","ownerOrg","ownerUid","String","org","app","firestore","collection","doc","get","accountId","trim","fetchOnSellerThenPlatform","url","init","sellerAccount","fetch","onSeller","headers","status","isDirectChargeObject","object","metadata","chargeModel","subscription_details","parent","SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE","sellerStripeTaxActive","process","key","env","STRIPE_SECRET_KEY","response","Authorization","ok","settings","json","catch"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,eAAe,QAAQ,mDAAkD;AAElF;;;;;;;;;;;2CAW2C,GAE3C,2EAA2E,GAC3E,OAAO,eAAeC,2BACpBC,MAAc;IAEd,IAAI,CAACA,QAAQ,OAAO;IACpB,IAAI;kBAUuBC;YARDC;QADxB,MAAMA,WAAW,MAAML,cAAcG;QACrC,MAAMG,WAAWC,eAAOF,6BAAAA,gBAAAA,SAAUG,GAAG,qBAAbH,cAAeC,QAAQ,mBAAI;QACnD,IAAI,CAACA,UAAU,OAAO;QACtB,MAAMF,UAAU,MAAML,cACnBU,GAAG,GACHC,SAAS,GACTC,UAAU,CAAC,YACXC,GAAG,CAACN,UACJO,GAAG;QACN,MAAMC,YAAYP,QAAOH,eAAAA,QAAQS,GAAG,CAAC,8BAAZT,eAAkC,IAAIW,IAAI;QACnE,IAAI,CAACD,WAAW,OAAO;QACvB,OAAOb,gBAAgBG,QAAQS,GAAG,CAAC,0BAA0B,WACzDC,YACA;IACN,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA;;;;CAIC,GACD,OAAO,eAAeE,0BACpBC,GAAW,EACXC,IAAwD,EACxDC,aAAwC;QAKvBD;IAHjB,IAAI,CAACC,eAAe,OAAOC,MAAMH,KAAKC;IACtC,MAAMG,WAAW,MAAMD,MAAMH,KAAK,aAC7BC;QACHI,SAAS,cAAMJ,gBAAAA,KAAKI,OAAO,YAAZJ,gBAAgB,CAAC;YAAI,kBAAkBC;;;IAExD,IAAIE,SAASE,MAAM,KAAK,KAAK,OAAOF;IACpC,OAAOD,MAAMH,KAAKC;AACpB;AAEA,+DAA+D,GAC/D,OAAO,SAASM,qBAAqBC,MAAW;QAG1CA,MAAAA;QAAAA,kBACEA,uCAAAA,8BACAA,8CAAAA,qCAAAA;IAJN,OACElB,QACEkB,QAAAA,iBAAAA,2BAAAA,mBAAAA,OAAQC,QAAQ,qBAAhBD,iBAAkBE,WAAW,oBAC3BF,2BAAAA,+BAAAA,OAAQG,oBAAoB,sBAA5BH,wCAAAA,6BAA8BC,QAAQ,qBAAtCD,sCAAwCE,WAAW,YADrDF,QAEEA,2BAAAA,iBAAAA,OAAQI,MAAM,sBAAdJ,sCAAAA,eAAgBG,oBAAoB,sBAApCH,+CAAAA,oCAAsCC,QAAQ,qBAA9CD,6CAAgDE,WAAW,YAF7DF,OAGE,QACE;AAEV;AAEA;;;;;CAKC,GACD,OAAO,MAAMK,uCACX,uEAAsE;AAExE;;;;;;;;CAQC,GACD,OAAO,eAAeC,sBACpBZ,aAAqB;QAEFa;IAAnB,MAAMC,MAAM1B,QAAOyB,iCAAAA,QAAQE,GAAG,CAACC,iBAAiB,YAA7BH,iCAAiC,IAAIjB,IAAI;IAC5D,IAAI,CAACkB,OAAO,CAACd,eAAe,OAAO;IACnC,IAAI;QACF,MAAMiB,WAAW,MAAMhB,MAAM,0CAA0C;YACrEE,SAAS;gBAAEe,eAAe,CAAC,OAAO,EAAEJ,KAAK;gBAAE,kBAAkBd;YAAc;QAC7E;QACA,IAAI,CAACiB,SAASE,EAAE,EAAE,OAAO;QACzB,MAAMC,WAAY,MAAMH,SAASI,IAAI,GAAGC,KAAK,CAAC,IAAM;QAGpD,OAAOF,CAAAA,4BAAAA,SAAUhB,MAAM,MAAK;IAC9B,EAAE,eAAM;QACN,OAAO;IACT;AACF"}
|
|
@@ -14,7 +14,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
|
-
*/ import {
|
|
17
|
+
*/ import { isDirectChargeObject } from "./seller-stripe-account.js";
|
|
18
|
+
import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
18
19
|
import { storefrontTaxRow } from "./storefront-tax.js";
|
|
19
20
|
/**
|
|
20
21
|
* Writes `storefrontTaxCollected/{stripeId}` for every storefront sale that
|
|
@@ -139,6 +140,10 @@ function metadataTypeOf(object) {
|
|
|
139
140
|
try {
|
|
140
141
|
var _ref, _ref1;
|
|
141
142
|
var _this;
|
|
143
|
+
// A DIRECT-charge sale is the seller's own: the seller collected the tax
|
|
144
|
+
// against their own registrations and files it. It is not a facilitated
|
|
145
|
+
// sale and has no place in Aglyn's return.
|
|
146
|
+
if (isDirectChargeObject(object)) return null;
|
|
142
147
|
const metadataType = metadataTypeOf(object);
|
|
143
148
|
const hostId = hostIdOf(object);
|
|
144
149
|
if (!hostId) return null;
|