@aglyn/plugins-commerce 1.0.0-beta.289 → 1.0.0-beta.291

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.
Files changed (140) hide show
  1. package/README.md +4 -2
  2. package/package.json +13 -13
  3. package/src/lib/components/commerce-console-page.js +2 -1
  4. package/src/lib/components/commerce-console-page.js.map +1 -1
  5. package/src/lib/components/console/commerce-pdf-download.d.ts +30 -0
  6. package/src/lib/components/console/commerce-pdf-download.js +53 -0
  7. package/src/lib/components/console/commerce-pdf-download.js.map +1 -0
  8. package/src/lib/components/console/host-orders-card.component.d.ts +6 -0
  9. package/src/lib/components/console/host-orders-card.component.js +3 -2
  10. package/src/lib/components/console/host-orders-card.component.js.map +1 -1
  11. package/src/lib/components/console/host-quotes-card.component.js +20 -4
  12. package/src/lib/components/console/host-quotes-card.component.js.map +1 -1
  13. package/src/lib/components/console/invoice-send.component.d.ts +44 -0
  14. package/src/lib/components/console/invoice-send.component.js +237 -0
  15. package/src/lib/components/console/invoice-send.component.js.map +1 -0
  16. package/src/lib/components/console/order-detail-dialog.component.d.ts +5 -0
  17. package/src/lib/components/console/order-detail-dialog.component.js +9 -2
  18. package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
  19. package/src/lib/components/console/order-invoice.component.d.ts +15 -4
  20. package/src/lib/components/console/order-invoice.component.js +93 -12
  21. package/src/lib/components/console/order-invoice.component.js.map +1 -1
  22. package/src/lib/components/console/quote-editor-dialog.component.d.ts +29 -0
  23. package/src/lib/components/console/quote-editor-dialog.component.js +154 -5
  24. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  25. package/src/lib/components/console/quote-proofs.component.d.ts +48 -0
  26. package/src/lib/components/console/quote-proofs.component.js +694 -0
  27. package/src/lib/components/console/quote-proofs.component.js.map +1 -0
  28. package/src/lib/components/console/quote-send.component.d.ts +42 -0
  29. package/src/lib/components/console/quote-send.component.js +307 -0
  30. package/src/lib/components/console/quote-send.component.js.map +1 -0
  31. package/src/lib/components/console/quote-start.component.d.ts +45 -0
  32. package/src/lib/components/console/quote-start.component.js +182 -0
  33. package/src/lib/components/console/quote-start.component.js.map +1 -0
  34. package/src/lib/components/product-options-field-body.d.ts +44 -0
  35. package/src/lib/components/product-options-field-body.js +260 -0
  36. package/src/lib/components/product-options-field-body.js.map +1 -0
  37. package/src/lib/components/product-options-field.d.ts +32 -0
  38. package/src/lib/components/product-options-field.js +128 -0
  39. package/src/lib/components/product-options-field.js.map +1 -0
  40. package/src/lib/components/quote-page-body.js +67 -20
  41. package/src/lib/components/quote-page-body.js.map +1 -1
  42. package/src/lib/components/quote-proof-panel.d.ts +42 -0
  43. package/src/lib/components/quote-proof-panel.js +436 -0
  44. package/src/lib/components/quote-proof-panel.js.map +1 -0
  45. package/src/lib/model/commerce-invoices.d.ts +132 -0
  46. package/src/lib/model/commerce-invoices.js +332 -0
  47. package/src/lib/model/commerce-invoices.js.map +1 -0
  48. package/src/lib/model/commerce-orders.d.ts +29 -2
  49. package/src/lib/model/commerce-orders.js.map +1 -1
  50. package/src/lib/model/commerce-product-field.d.ts +23 -0
  51. package/src/lib/model/commerce-product-field.js +26 -0
  52. package/src/lib/model/commerce-product-field.js.map +1 -0
  53. package/src/lib/model/commerce-quote-email.d.ts +67 -0
  54. package/src/lib/model/commerce-quote-email.js +154 -0
  55. package/src/lib/model/commerce-quote-email.js.map +1 -0
  56. package/src/lib/model/commerce-quote-pay.d.ts +76 -6
  57. package/src/lib/model/commerce-quote-pay.js +105 -39
  58. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  59. package/src/lib/model/commerce-quote-proofs.d.ts +159 -0
  60. package/src/lib/model/commerce-quote-proofs.js +348 -0
  61. package/src/lib/model/commerce-quote-proofs.js.map +1 -0
  62. package/src/lib/model/commerce-quote-request.d.ts +93 -0
  63. package/src/lib/model/commerce-quote-request.js +207 -0
  64. package/src/lib/model/commerce-quote-request.js.map +1 -0
  65. package/src/lib/model/commerce-quotes.d.ts +140 -3
  66. package/src/lib/model/commerce-quotes.js.map +1 -1
  67. package/src/lib/model/index.d.ts +4 -0
  68. package/src/lib/model/index.js +4 -0
  69. package/src/lib/model/index.js.map +1 -1
  70. package/src/lib/plugin.js +19 -0
  71. package/src/lib/plugin.js.map +1 -1
  72. package/src/lib/server/billing-webhook.js +115 -70
  73. package/src/lib/server/billing-webhook.js.map +1 -1
  74. package/src/lib/server/commerce-pdf.d.ts +104 -0
  75. package/src/lib/server/commerce-pdf.js +310 -0
  76. package/src/lib/server/commerce-pdf.js.map +1 -0
  77. package/src/lib/server/draft-order.js +23 -3
  78. package/src/lib/server/draft-order.js.map +1 -1
  79. package/src/lib/server/invoice-email.d.ts +76 -0
  80. package/src/lib/server/invoice-email.js +183 -0
  81. package/src/lib/server/invoice-email.js.map +1 -0
  82. package/src/lib/server/order-invoice-send.d.ts +43 -0
  83. package/src/lib/server/order-invoice-send.js +218 -0
  84. package/src/lib/server/order-invoice-send.js.map +1 -0
  85. package/src/lib/server/order-print.d.ts +6 -0
  86. package/src/lib/server/order-print.js +22 -5
  87. package/src/lib/server/order-print.js.map +1 -1
  88. package/src/lib/server/order-status.d.ts +11 -0
  89. package/src/lib/server/order-status.js +44 -8
  90. package/src/lib/server/order-status.js.map +1 -1
  91. package/src/lib/server/pdf-response.d.ts +31 -0
  92. package/src/lib/server/pdf-response.js +30 -0
  93. package/src/lib/server/pdf-response.js.map +1 -0
  94. package/src/lib/server/person-eraser.d.ts +3 -2
  95. package/src/lib/server/person-eraser.js +25 -6
  96. package/src/lib/server/person-eraser.js.map +1 -1
  97. package/src/lib/server/pos-reader-splash.d.ts +2 -18
  98. package/src/lib/server/pos-reader-splash.js +8 -93
  99. package/src/lib/server/pos-reader-splash.js.map +1 -1
  100. package/src/lib/server/quote-email.d.ts +85 -0
  101. package/src/lib/server/quote-email.js +211 -0
  102. package/src/lib/server/quote-email.js.map +1 -0
  103. package/src/lib/server/quote-link-token.d.ts +11 -0
  104. package/src/lib/server/quote-link-token.js +21 -0
  105. package/src/lib/server/quote-link-token.js.map +1 -1
  106. package/src/lib/server/quote-pay.d.ts +38 -6
  107. package/src/lib/server/quote-pay.js +115 -53
  108. package/src/lib/server/quote-pay.js.map +1 -1
  109. package/src/lib/server/quote-proofs.d.ts +51 -0
  110. package/src/lib/server/quote-proofs.js +500 -0
  111. package/src/lib/server/quote-proofs.js.map +1 -0
  112. package/src/lib/server/quote-uploads.d.ts +33 -0
  113. package/src/lib/server/quote-uploads.js +29 -0
  114. package/src/lib/server/quote-uploads.js.map +1 -0
  115. package/src/lib/server/quote.d.ts +25 -0
  116. package/src/lib/server/quote.js +638 -8
  117. package/src/lib/server/quote.js.map +1 -1
  118. package/src/lib/server/site-image-source.d.ts +38 -0
  119. package/src/lib/server/site-image-source.js +130 -0
  120. package/src/lib/server/site-image-source.js.map +1 -0
  121. package/src/lib/server/site-page-resolver.js +2 -1
  122. package/src/lib/server/site-page-resolver.js.map +1 -1
  123. package/src/lib/server.js +24 -1
  124. package/src/lib/server.js.map +1 -1
  125. package/src/lib/site.js +8 -0
  126. package/src/lib/site.js.map +1 -1
  127. package/src/lib/tenant-emails.js +243 -0
  128. package/src/lib/tenant-emails.js.map +1 -1
  129. package/src/lib/utils/commerce-document-pdf.d.ts +82 -0
  130. package/src/lib/utils/commerce-document-pdf.js +613 -0
  131. package/src/lib/utils/commerce-document-pdf.js.map +1 -0
  132. package/src/lib/utils/invoice-email-content.d.ts +45 -0
  133. package/src/lib/utils/invoice-email-content.js +126 -0
  134. package/src/lib/utils/invoice-email-content.js.map +1 -0
  135. package/src/lib/utils/order-invoice.d.ts +52 -3
  136. package/src/lib/utils/order-invoice.js +124 -64
  137. package/src/lib/utils/order-invoice.js.map +1 -1
  138. package/src/lib/utils/quote-email-content.d.ts +62 -0
  139. package/src/lib/utils/quote-email-content.js +154 -0
  140. package/src/lib/utils/quote-email-content.js.map +1 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/draft-order.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 { holdsCommerceSiteKey } from './commerce-site-keys'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\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 planCheckoutShippingWithCarriers,\n type CarrierShippingPlan,\n} from './carrier-shipping'\nimport { resolveManualTaxRateId } from './manual-tax-rate'\nimport { orderStatusUrl } from './order-status-token'\nimport {\n type PromotionSlotHold,\n holdPromotionSlot,\n promotionHoldKey,\n} from './promotion-hold'\nimport {\n buildRoute,\n claimAttempt,\n Route,\n type AttemptClaim,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\n\n/**\n * Draft orders (AGL-287, Shopify parity): a manager builds an order in\n * the console and sends the buyer a payment link. Creates the order doc\n * (status `pending`, channel `draft`) with a sequential number, then a\n * Stripe Checkout session on the merchant's connected account whose\n * webhook completion flips the SAME doc to `paid`\n * (metadata type `commerce-draft`).\n */\nexport const draftOrderHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const productId = String(body.productId ?? '')\n const variantId = String(body.variantId ?? '')\n const quantity = Math.max(1, Math.min(99, Math.round(Number(body.quantity ?? 1))))\n const email = String(body.email ?? '').trim()\n // A code the MERCHANT types while composing the order (AGL-305). The\n // storefront doors read this same field name, so one resolver answers it the\n // same way whoever pressed the button.\n const couponCode = String(body.couponCode ?? '').trim()\n // One draft attempt, minted by the console dialog (AGL-1697). Node\n // lowercases incoming headers, but read both spellings — the plugin API\n // request type makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n ).trim().slice(0, 200)\n if (!hostId || !productId) {\n return res.status(400).json({ error: 'Missing hostId or productId' })\n }\n\n let claim: AttemptClaim | null = null\n /**\n * The redemption slot this attempt reserved (AGL-305), hoisted so every\n * refusal below the claim — and the catch — can hand it back. A throw after\n * the hold is placed is exactly the case where a slot would otherwise stand\n * invisibly against the merchant's cap until its TTL lapsed, and this path\n * rolls its order document back on two of those refusals already.\n */\n let discountSlot: PromotionSlotHold | null = null\n let discountHoldKey = ''\n const releaseDiscountSlot = async (): Promise<void> => {\n const slot = discountSlot\n discountSlot = null\n discountHoldKey = ''\n if (slot) await slot.release()\n }\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // AN ALLOWLIST (AGL-2262), matching `cancel-order.ts`, `fulfill-order.ts`\n // and the Firestore rules, whose host-write predicate is\n // `hostMemberRole(hostId) in ['admin','editor']`. The old\n // `!role || role === 'viewer'` denylist caught the stranger but admitted\n // every OTHER string — a legacy value, a typo, any role added later — on\n // the one route that mints a live Stripe payment link. `HostAccessRole`\n // has since grown an `author` (AGL-2334), which this allowlist refuses on\n // purpose — an author edits content and does not mint payment links — and\n // which the old denylist would have admitted. That is the allowlist form\n // earning its keep on a union that changed under it.\n // \"Manage orders\" (`commerce.orders`, AGL-4047), whose preset is the site's Admin\n // and Editor this asked for, read as the rules would read it.\n if (!holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')) {\n return res.status(403).json({ error: commerceSitePermissionRefusal('commerce.orders') })\n }\n const productSnapshot = await hostRef\n .collection('products')\n .doc(productId)\n .get()\n const raw = productSnapshot.data() as any\n if (!raw || raw.deletedAt) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n const product = CommerceModel.liftLegacyProduct(raw)\n const variant = variantId\n ? product.variants.find((item) => item.id === variantId)\n : product.variants[0]\n if (!variant) return res.status(404).json({ error: 'Unknown variant' })\n // A variant with no price yet (AGL-2916) cannot be invoiced: the link\n // would ask for nothing, or for no amount at all.\n if (!CommerceModel.variantHasPrice(variant)) {\n return res.status(400).json({ error: `Set a price for ${product.name} before selling it.` })\n }\n\n // Merchant account like the storefront checkout (AGL-284).\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 free or lapsed org must not\n // keep minting payment links — at the free plan's 0% transaction fee —\n // through the one commerce door that skipped the entitlement. Sits\n // ABOVE the attempt claim with the other deterministic refusals, so it\n // never burns the merchant's idempotency key.\n if (!Aglyn.checkEntitlement(ownerOrg?.org as any, 'commerce')) {\n return res.status(403).json({ error: 'Selling is 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: `draft order host ${hostId}` },\n )\n ) {\n return res.status(409).json({ error: 'Payments are not set up yet' })\n }\n\n // Where Stripe returns the BUYER is the business's own site (AGL-4094):\n // the order's status page after paying, the site's home after backing\n // out — see the params below. The console Products page is only the\n // fallback for a site with no public address or no signing secret, which\n // no published site lacks. Console products is the plugin route keyed by\n // org slug + host SUBDOMAIN; server code cannot call\n // useConsoleHostRoute, so resolve them here. Without both, fall back to\n // the origin root rather than a fabricated dead path.\n const consoleSubdomain = (\n await firestore.collection('hostIndex').doc(hostId).get()\n ).get('subdomain') as string | undefined\n const consoleOrgSlug = ownerOrg?.org?.slug as string | undefined\n // The console's own host, as the POS door reads it — never the `Origin`\n // header (AGL-3363). The CUSTOMER lands here after paying the link, so a\n // caller-written origin would send a merchant's customer anywhere.\n const origin = `https://${req.headers.host}`\n const consoleProductsUrl =\n consoleOrgSlug && consoleSubdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, {\n orgSlug: consoleOrgSlug,\n host: consoleSubdomain,\n pluginSlug: 'products',\n })}`\n : origin\n\n // WHAT THE COUNT SAYS, said out loud (AGL-2452).\n //\n // This handler contained no `canPurchase` and no `stockShortfall` — no\n // reference to inventory of any kind. It is the door that mints a LIVE,\n // payable Stripe link, and it would mint one for a sold-out variant whose\n // merchant had chosen `oversellPolicy: 'deny'`, with the `commerce-draft`\n // webhook branch then completing it into a `paid` order. `pos-order.ts`'s\n // own comment asserts \"every storefront door gates on it\"; that claim was\n // false for this one.\n //\n // WARN, NEVER BLOCK, matching the register (AGL-2357, the decision).\n // Both of these are MERCHANT-initiated doors rather than shopper-initiated\n // ones — the merchant may well be taking a deliberate pre-order or\n // backorder — so a stale count must not refuse a sale the merchant means to\n // make. What the merchant is entitled to is to be TOLD, which is the part\n // that was missing entirely. The refusal variant is a separate decision and\n // is not taken here.\n //\n // Computed from the SERVER's product document, and reported on the same\n // `stockWarnings` key and in the same `StockShortfall` shape the register\n // already returns, so one console surface can read either door.\n const shortfall = CommerceModel.stockShortfall(\n product,\n variantId || product.variants[0]?.id,\n quantity,\n )\n const stockWarnings: CommerceModel.StockShortfall[] = shortfall\n ? [\n {\n productId,\n ...(variantId ? { variantId } : {}),\n name: product.name,\n requested: quantity,\n available: shortfall.available,\n },\n ]\n : []\n\n const unitAmountCents = Math.round(Number(variant.priceUsd) * 100)\n const lineItems: CommerceModel.OrderLineItem[] = [\n {\n productId,\n ...(variantId ? { variantId } : {}),\n name: product.name,\n ...(variant.sku ? { sku: variant.sku } : {}),\n productType: product.type,\n quantity,\n unitAmountCents,\n },\n ]\n const itemsCents = unitAmountCents * quantity\n // THE DISCOUNTS HUB, ON THIS PATH TOO (AGL-305).\n //\n // `hosts/{hostId}/discounts` reached the cart and buy-now and stopped\n // there, so a store running \"Summer sale, 10% off\" sold at 10% off through\n // both storefront doors and at FULL price the moment the merchant invoiced\n // the same buyer for the same goods through a payment link. No code has to\n // be typed for that gap to open: an automatic promotion applies itself on\n // the storefront and applied itself nowhere here, so the merchant's own\n // payment link quietly undercut — and here overcharged against — their own\n // advertised price.\n //\n // Resolved through the SAME `resolveDiscount` the other doors use, so one\n // code cannot mean two amounts.\n //\n // RESOLVED BEFORE THE TAX BLOCK BELOW, and that ordering is the whole\n // point rather than a convenience: the manual rate is computed against\n // `chargedItemsCents`, so the discount lands BEFORE tax and the taxable\n // base is the discounted one. It has to be — the session applies that same\n // rate as `line_items[0][tax_rates][0]`, which Stripe evaluates against the\n // line amount it actually charges. Reducing the line while taxing the list\n // price would make our stored `taxCents` disagree with the tax Stripe\n // collects, on every discounted draft.\n const draftDiscountLines = [{ productId, amountCents: itemsCents }]\n const hubDiscounts = await hostRef.collection('discounts').limit(100).get()\n const resolvedDiscount = CommerceModel.resolveDiscount(\n hubDiscounts.docs.map((docSnapshot) => ({\n ...(docSnapshot.data() as CommerceModel.HostDiscount),\n $id: docSnapshot.id,\n })),\n {\n ...(couponCode ? { code: couponCode } : {}),\n subtotalCents: itemsCents,\n productIds: [productId],\n lines: draftDiscountLines,\n },\n )\n // Above the claim and above the order write with every other deterministic\n // refusal, so a merchant who fixes the code and presses Send again strands\n // no `pending` draft and burns no key. A code that RESOLVES but confers\n // nothing leaves through here too — `codeProblem` carries the benefit's own\n // reason — which is what stops this door repeating the defect that charged\n // full shipping on a free-shipping code.\n if (resolvedDiscount?.codeProblem) {\n return res.status(400).json({ error: resolvedDiscount.codeProblem })\n }\n const appliedDiscountId =\n resolvedDiscount && resolvedDiscount.benefit.kind !== 'none'\n ? resolvedDiscount.discountId\n : ''\n const discountCents = appliedDiscountId ? resolvedDiscount!.discountCents : 0\n // Stripe's charge minimum is 50¢ — never price a payment link below it,\n // the same floor buy-now applies.\n const chargedItemsCents = discountCents\n ? Math.max(50, itemsCents - discountCents)\n : itemsCents\n // What was ACTUALLY taken off, after that floor. The stored totals record\n // this rather than the resolver's figure, so the parts sum to the total on\n // a draft the floor moved.\n const appliedDiscountCents = itemsCents - chargedItemsCents\n // The fee and `totals` are both built BELOW the shipping plan (AGL-2152):\n // Stripe's card cost rides the whole payment-link total, so neither can be\n // known until the tax (AGL-1953) and the shipping options are.\n\n // Shipping (AGL-1792), from the same settings document the two storefront\n // paths read. This handler contained no `shipping` string at all: a\n // merchant who configured zones and rates collected them on a cart\n // (AGL-1707) and on buy-now (AGL-1720), and nothing when they invoiced the\n // same buyer for the same parcel through a payment link. The session\n // collected no address either, so the merchant was not even told where to\n // send it — the webhook records one now that Stripe is asked for it.\n //\n // The premise AGL-1792 filed this under was that \"the destination IS known\n // — the merchant typed it\". It is not: the draft dialog collects a product,\n // a variant, a quantity and an email, and this handler reads exactly those.\n // So the destination is as unknown here as it is in the cart, and the same\n // asking machinery applies rather than none of it.\n //\n // CONDITIONAL on the product being physical, exactly as buy-now is: this\n // dialog invoices downloads and consulting too, and charging that buyer\n // postage would be worse than the bug. A missing `type` reads as physical,\n // matching the fee ladder above — the two reads must not disagree about\n // what a part-migrated doc is. The one-time condition buy-now also carries\n // is structural here: this path only ever builds `mode: 'payment'`.\n //\n // RESOLVED BEFORE THE ORDER DOCUMENT, because the plan can refuse and the\n // order is written before Stripe is called. Refusing after it would strand\n // a `pending` draft on the merchant's orders list for every attempt —\n // this path's version of the orphaned coupon AGL-1721 kept out of the cart.\n const storeSettings = await hostRef\n .collection('settings')\n .doc('store')\n .get()\n const shippingSettings = storeSettings.get('shipping') as\n CommerceModel.ShippingSettings | undefined\n\n // Taxes (AGL-1953), from the same settings document. This handler had no\n // tax code at all in either mode, so a merchant who invoiced a buyer for\n // the same product they sell on the storefront charged them no tax — the\n // cart's defect, one door over, and worse here because the merchant\n // composed this order deliberately and would reasonably assume it matched\n // their store.\n //\n // Origin-based, exactly as buy-now and the cart resolve it. The AGL-1792\n // note above already established the premise: this dialog collects a\n // product, a variant, a quantity and an email, so the DESTINATION is as\n // unknown here as it is in the cart.\n //\n // Computed pure and BEFORE the claim so the stored totals can carry it;\n // the Stripe object it needs is minted below the point of no return.\n const taxSettings = (storeSettings.get('tax') ?? {}) as CommerceModel.TaxSettings\n // AGL-1999: an unset tax mode is NOT a decision, and it must not sell.\n // `mode` was `undefined` for every store whose owner never opened the\n // Taxes card — the default state of every new storefront — and each\n // branch below tested for a specific string, so no branch was taken, no\n // tax was computed, and the shopper was charged an untaxed total. See\n // `commerce-tax-decision.ts` for why refusing beats defaulting to either\n // mode. `mode: 'none'` is the explicit opt-out and passes straight\n // through.\n const taxDecision = CommerceModel.storefrontTaxDecision({\n settings: taxSettings,\n taxExempt: product.taxExempt,\n })\n if (taxDecision.kind === 'undecided') {\n return res\n .status(409)\n .json({ error: CommerceModel.STOREFRONT_TAX_UNDECIDED_MESSAGE })\n }\n const taxMisconfigured =\n CommerceModel.storefrontTaxMisconfiguration(taxSettings)\n if (taxMisconfigured) {\n // AGL-2145: the merchant DECIDED to collect and the sale would have\n // charged zero anyway — an unfinished settings card, not a\n // jurisdiction miss. Refused in the same words and the same place as\n // the undecided case above.\n return res.status(409).json({ error: taxMisconfigured })\n }\n const useStripeTax = taxDecision.kind === 'stripe-automatic'\n const manualRate =\n taxDecision.kind === 'manual' &&\n !taxSettings.pricesIncludeTax\n ? CommerceModel.resolveTaxRate(taxSettings, taxSettings.origin ?? {})\n : null\n // THE DISCOUNTED BASE (AGL-305). `chargedItemsCents` is what the line\n // will actually be worth, and the session applies this same rate to that\n // line as a Stripe Tax Rate — so taxing `itemsCents` here would record a\n // figure Stripe never charges.\n const taxCents = manualRate\n ? CommerceModel.computeTaxCents(chargedItemsCents, manualRate.pct)\n : 0\n // Stripe Tax mode leaves this 0 at composition time and the webhook folds\n // the computed figure in — the same additive shape AGL-1792 used for\n // shipping, and for the same reason: only Stripe knows it.\n // Live carrier rates (AGL-3612), quoted for the destination the manager\n // names; see `carrier-shipping.ts`.\n const shippingPlan: CarrierShippingPlan =\n (product.type ?? 'physical') === 'physical'\n ? await planCheckoutShippingWithCarriers({\n hostId,\n settings: shippingSettings,\n cart: {\n subtotalCents: itemsCents,\n totalGrams:\n Math.max(0, Number(variant.weightGrams ?? 0)) * quantity,\n ...(quantity === 1 ? { parcel: CommerceModel.productParcelDimensions(product) } : {}),\n },\n destination: {\n country: body.shippingCountry,\n postalCode: body.shippingPostalCode,\n },\n })\n : { countries: CommerceModel.CHECKOUT_SHIPPING_COUNTRIES, options: [] }\n if (shippingPlan.needsPostalCode) {\n return res.status(400).json({\n error: 'Enter the postal code this order ships to.',\n needsShippingCountry: true,\n needsShippingPostalCode: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n if (shippingPlan.refusal === 'destination-required') {\n return res.status(400).json({\n error: 'Choose where this order ships to.',\n needsShippingCountry: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n if (shippingPlan.refusal === 'destination-unserved') {\n const declared = CommerceModel.normalizeCheckoutShippingCountry(\n body.shippingCountry,\n )\n return res.status(409).json({\n error: `This store does not ship to ${\n CommerceModel.CHECKOUT_SHIPPING_COUNTRY_NAMES[declared as string] ??\n 'that country'\n }.`,\n needsShippingCountry: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n // No rate of the merchant's reaches this order (AGL-2232). Above the\n // order write and the payment link, like every other refusal here, so a\n // manager who fixes the tier table and presses Send again strands nothing.\n if (shippingPlan.refusal === 'cart-unpriceable') {\n return res\n .status(409)\n .json({ error: CommerceModel.CART_UNPRICEABLE_SHIPPING_MESSAGE })\n }\n // FREE SHIPPING IS A ZEROED RATE, NOT A REDUCTION (AGL-305), the same\n // construction the cart uses and for the same reason: nothing has picked a\n // rate yet, so there is no amount to take off. The buyer chooses after the\n // link is minted, so the only exact answer is to offer every rate at zero.\n //\n // Every rate rather than the cheapest, because `free_shipping` carries no\n // field naming one — and zeroing them all keeps the fee, the transfer floor\n // and the ceiling below honest, since all three read these same options.\n //\n // Derived from `shippingPlan.options` and read EVERYWHERE below in its\n // place; a reader that reached past this to `shippingPlan.options` would\n // price carriage the buyer is not being charged for.\n const shippingOptions =\n resolvedDiscount?.freeShipping === true\n ? shippingPlan.options.map((option) => ({ ...option, amountCents: 0 }))\n : shippingPlan.options\n\n // THE PLATFORM FEE (AGL-2152) — the advertised take PLUS Stripe's card\n // cost, passed through at cost. A payment link is a destination charge, so\n // Stripe debits 2.9% + 30¢ from the PLATFORM's balance; the old take-only\n // figure meant every tier carrying a 0% rate invoiced a buyer at a loss to\n // Aglyn, and Starter's 2% is below 2.9% so it lost money at every size too.\n //\n // `?? 'physical'` (AGL-2251), matching `checkout.ts` and the cart. Without\n // it a product doc carrying no `type` fell to `resolveTransactionFeePct`'s\n // digital branch, so a merchant's payment link took a different cut of the\n // same product than their storefront did.\n //\n // The base is the whole card total: the goods, the manual tax line, and the DEAREST shipping\n // option the link offers (the buyer picks after the link is minted and\n // `application_fee_amount` is fixed at creation, so reaching for the\n // cheapest would put the difference back on Aglyn). A store on Stripe Tax\n // is the one residual — that tax is computed inside Stripe afterwards.\n const shippingCeilingCents = shippingOptions.reduce(\n (most, option) =>\n Math.max(most, Math.max(0, Number(option.amountCents ?? 0))),\n 0,\n )\n // Both bases are the DISCOUNTED goods (AGL-305). The platform take is a\n // cut of what the merchant actually sells for, and Stripe's card cost is\n // passed through on what the card actually runs for — reading `itemsCents`\n // here would invoice the merchant a fee on money nobody paid.\n const feeCents = Aglyn.resolveTransactionFeeCents(\n ownerOrg?.org as any,\n product.type ?? 'physical',\n chargedItemsCents,\n chargedItemsCents + taxCents + shippingCeilingCents,\n )\n // Stripe Tax mode leaves the tax 0 at composition time and the webhook\n // folds the computed figure in — the same additive shape AGL-1792 used for\n // shipping, and for the same reason: only Stripe knows it.\n const totals = CommerceModel.computeOrderTotals(lineItems, {\n feeCents,\n taxCents,\n // The line item still carries the LIST price, so the discount has to be\n // a named part of the totals or `itemsCents - discountCents + tax` would\n // not be the number on the payment link.\n discountCents: appliedDiscountCents,\n })\n\n // THE LINK CHARGES `chargedItemsCents`, EXACTLY (the AGL-2159 construction,\n // reused here because this path grew the same problem the moment it grew a\n // discount).\n //\n // A Stripe line is `quantity` units at ONE integer `unit_amount`, so it can\n // only express totals divisible by `quantity` — and a percentage discount\n // does not respect that. Dividing and multiplying back misses the intended\n // total by up to `quantity / 2` cents in either direction, which on this\n // path is worse than on buy-now: the frozen `totals` above are written to\n // the order document BEFORE the session is minted, so a link that charged\n // a different number would leave the merchant's own books disagreeing with\n // what their buyer paid, permanently and silently.\n //\n // So when the total does not divide evenly, the line becomes ONE unit at\n // the exact total with the count moved into the display name. The real\n // quantity is carried by the order document's line item, which is\n // untouched, so nothing downstream can tell the difference.\n //\n // The even case — every undiscounted draft, and most discounted ones —\n // keeps the per-unit shape byte for byte.\n const evenUnitAmountCents = Math.floor(chargedItemsCents / quantity)\n const remainderCents = chargedItemsCents - evenUnitAmountCents * quantity\n const chargedQuantity = remainderCents === 0 ? quantity : 1\n const chargedUnitAmountCents =\n remainderCents === 0 ? evenUnitAmountCents : chargedItemsCents\n const chargedLineName = `${product.name}${\n remainderCents === 0 ? '' : ` × ${quantity}`\n }`.slice(0, 120)\n\n // Point of no return (AGL-1697): everything past here writes an order and\n // mints a live payment link. Every deterministic refusal — unknown\n // product, payments not set up, the shipping-destination ask — sits above\n // this line, so none of them burns the key: the merchant fixes the input\n // and presses the same button. Before the claim, a double-submit minted a\n // SECOND order doc, burned a second sequential number, and returned two\n // live payment links bound to different orders, both payable.\n const claimed = await claimAttempt(firestore, {\n kind: 'commerce-draft',\n scopeId: hostId,\n orgId: String(ownerOrg?.org?.id ?? ''),\n key: idempotencyKey,\n busyMessage: 'This draft order is already being created',\n })\n if ('replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n claim = claimed.claim\n\n // THE REDEMPTION SLOT IS RESERVED HERE (AGL-305), on the same terms the\n // storefront doors reserve it.\n //\n // A payment link lives until the buyer pays it, so between this handler and\n // the `commerce-draft` webhook branch that settles the slot there is a\n // window measured in days — far wider than a Checkout Session's. Reading\n // `redemptions` and hoping would let a merchant mint ten links against a\n // cap of one and have all ten pay.\n //\n // BELOW the claim because the hold is keyed by the attempt: a retry of one\n // attempt must be able to re-claim the slot it already holds rather than be\n // refused by it. An uncapped promotion writes nothing and returns an empty\n // `holdKey`, which is what tells the webhook to fall back to the plain\n // increment.\n if (appliedDiscountId) {\n const slot = await holdPromotionSlot({\n firestore,\n ref: hostRef.collection('discounts').doc(appliedDiscountId),\n holdKey: promotionHoldKey(claimed.claim.stripeKey),\n label: `draft discount ${appliedDiscountId}`,\n })\n if (!slot.ok) {\n // Refused rather than quietly repriced, and that is deliberate for the\n // AUTOMATIC case too: the merchant composed this order at a price the\n // promotion was part of, and minting the link at full price would\n // invoice their buyer more than the store advertises without saying so.\n // Nothing has been written yet, so the key goes back and the retry\n // prices correctly — `resolveDiscount` counts live holds and simply\n // stops offering an exhausted promotion.\n await claim.release()\n return res.status(409).json({\n error:\n couponCode && resolvedDiscount?.discount.code\n ? CommerceModel.PROMOTION_EXHAUSTED_MESSAGE\n : CommerceModel.PROMOTION_UNAVAILABLE_MESSAGE,\n })\n }\n if (slot.holdKey) {\n discountSlot = slot\n discountHoldKey = slot.holdKey\n }\n }\n\n // Order doc first (transactional number), then the payment link.\n const orderRef = hostRef.collection('orders').doc()\n const counterRef = hostRef.collection('counters').doc('orders')\n await firestore.runTransaction(async (transaction) => {\n const counter = await transaction.get(counterRef)\n const number = Number(counter.get('next') ?? 1)\n transaction.set(counterRef, { next: number + 1 }, { merge: true })\n // With the fields the orders list queries by (AGL-3321).\n transaction.set(orderRef, CommerceModel.withOrderListFields(orderRef.id, {\n number,\n status: 'pending',\n channel: 'draft',\n lineItems,\n totals,\n // WHICH TAX REGIME THIS ORDER IS COMPOSED UNDER (AGL-2451), from the\n // decision taken above rather than from the frozen `taxCents` — a\n // Stripe Tax draft freezes 0 there and only the paid session knows the\n // figure, so a mode read back off the amount would call it `none`.\n //\n // Stamped at composition so a draft that is never paid still says what\n // it was priced under, and RESTATED by the `commerce-draft` webhook\n // branch from the session that actually charged it. The webhook's is\n // authoritative — it has Stripe's computed tax in hand — and for a\n // manual draft the two agree by construction.\n taxMode: CommerceModel.storefrontTaxModeForDecision(\n taxDecision,\n taxCents,\n ),\n customerEmail: email || null,\n timeline: [\n {\n atMs: Date.now(),\n event: 'draft',\n detail: `Draft created by ${decoded.email ?? decoded.uid}`,\n },\n ],\n createdAtMs: Date.now(),\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n }))\n })\n\n // The tax rate is minted here, BELOW the claim, because it creates a real\n // Stripe object (AGL-1953). Cached per host, so it is usually a read.\n let draftTaxRateId = ''\n if (taxCents > 0 && manualRate) {\n draftTaxRateId =\n (await resolveManualTaxRateId({\n hostRef,\n taxPct: manualRate.pct,\n taxLabel: manualRate.label || `Tax (${manualRate.pct}%)`,\n ...(claim.stripeKey\n ? { headers: { 'Idempotency-Key': `${claim.stripeKey}-tax-rate` } }\n : {}),\n })) ?? ''\n if (!draftTaxRateId) {\n // A VISIBLE refusal rather than an untaxed payment link — the silent\n // under-collection is the defect. The order doc is rolled back the\n // same way the session failure below rolls it back.\n await orderRef.delete().catch(() => undefined)\n await releaseDiscountSlot()\n await claim.release()\n return res.status(502).json({ error: 'Payment link creation failed' })\n }\n }\n // The buyer's way back, on the business's site: the order's status page\n // (which reads the paid state from the server) and the site's home.\n const siteData = hostSnapshot.data() as { cname?: unknown; subdomain?: unknown } | undefined\n const buyerStatusUrl = orderStatusUrl(siteData, hostId, orderRef.id)\n const buyerSiteUrl = buyerStatusUrl ? `${new URL(buyerStatusUrl).origin}/` : ''\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 ...(useStripeTax ? { 'automatic_tax[enabled]': 'true' } : {}),\n ...(draftTaxRateId ? { 'line_items[0][tax_rates][0]': draftTaxRateId } : {}),\n 'line_items[0][quantity]': String(chargedQuantity),\n 'line_items[0][price_data][currency]': 'usd',\n 'line_items[0][price_data][unit_amount]': String(chargedUnitAmountCents),\n 'line_items[0][price_data][product_data][name]': chargedLineName,\n // THE CONNECT SPLIT (AGL-1956). A Stripe Tax payment link computes its\n // tax against AGLYN's registrations and Aglyn remits it (AGL-1904), so\n // the merchant gets a FIXED `transfer_data[amount]` and no\n // `application_fee_amount`: the fee form transfers `amount_total − fee`,\n // and `amount_total` includes that tax. A manual-rate or untaxed link is\n // unchanged. See `commerce-connect-transfer.ts`.\n ...CommerceModel.destinationChargeParams({\n accountId: String(accountId),\n feeCents,\n taxOwner: useStripeTax ? 'platform' : 'merchant',\n // The DISCOUNTED goods (AGL-305): this is what the merchant is\n // transferred, and paying out the list price on a discounted link\n // would move money Stripe never collected.\n merchantGoodsCents: chargedItemsCents,\n shippingFloorCents: CommerceModel.shippingFloorCents(shippingOptions),\n }),\n ...(email ? { customer_email: email } : {}),\n success_url: buyerStatusUrl ?? `${consoleProductsUrl}?draft=paid`,\n cancel_url: buyerSiteUrl || `${consoleProductsUrl}?draft=canceled`,\n 'metadata[type]': 'commerce-draft',\n 'metadata[hostId]': hostId,\n 'metadata[orderId]': orderRef.id,\n 'metadata[productId]': productId,\n ...(variantId ? { 'metadata[variantId]': variantId } : {}),\n 'metadata[feeCents]': String(feeCents),\n ...(shippingPlan.quotedPostalCode\n ? { 'metadata[shippingQuotePostalCode]': shippingPlan.quotedPostalCode }\n : {}),\n // WHAT THE WEBHOOK SETTLES (AGL-305), in the field names the\n // `checkout.session.completed` branch already reads for the cart. The\n // hold key's ABSENCE is what tells it to fall back to the unconditional\n // increment, which is right for an uncapped promotion.\n ...(appliedDiscountId\n ? { 'metadata[discountId]': appliedDiscountId }\n : {}),\n ...(discountHoldKey ? { 'metadata[discountHoldKey]': discountHoldKey } : {}),\n // See the AGL-1956 note in `checkout.ts` — recorded only on the shape\n // where the merchant's payout is no longer the whole charge.\n ...(useStripeTax\n ? {\n 'metadata[transferCents]': String(\n CommerceModel.platformLiableTransferCents({\n feeCents,\n merchantGoodsCents: chargedItemsCents,\n shippingFloorCents:\n CommerceModel.shippingFloorCents(shippingOptions),\n }),\n ),\n 'metadata[transferShippingCents]': String(\n CommerceModel.shippingFloorCents(shippingOptions),\n ),\n }\n : {}),\n })\n // Both keys or neither (AGL-1720's rule, inherited). Stripe will not apply\n // a shipping rate without an address to ship to, and a merchant who\n // configured nothing plans to no options and so gets neither — a payment\n // link byte-identical to the one this handler built before shipping\n // existed on it.\n if (shippingOptions.length > 0) {\n CommerceModel.appendShippingAddressCollectionParams(\n params,\n shippingPlan.countries,\n )\n CommerceModel.appendCheckoutShippingParams(params, shippingOptions)\n }\n // The payment methods the merchant switched off reach the payment link\n // too (AGL-3629). A hosted Stripe page shows Apple Pay and Google Pay by\n // device and cannot hide them per merchant; everything else follows.\n CommerceModel.appendStorefrontPaymentMethodParams(\n params,\n CommerceModel.resolveStorefrontPaymentMethodControls(\n CommerceModel.normalizeStorefrontPaymentMethodSettings(\n storeSettings.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 is a live payment link (AGL-1697). Stripe replays\n // the existing session for a repeated key instead of opening a\n // second one on the merchant's account, which covers the window\n // where our claim is written but the response never arrives.\n ...(claim.stripeKey ? { 'Idempotency-Key': claim.stripeKey } : {}),\n },\n body: params.toString(),\n },\n )\n const session = (await response.json()) as {\n url?: string\n id?: string\n error?: any\n }\n if (!response.ok || !session.url) {\n console.error('Stripe draft-order error', session.error)\n await orderRef.delete().catch(() => undefined)\n // The draft did not happen — hand the key back rather than locking this\n // dialog out over one flaky moment. The retry re-derives the SAME\n // digest, so if Stripe did create the session it replays it.\n await releaseDiscountSlot()\n await claim.release()\n return res.status(502).json({ error: 'Payment link creation failed' })\n }\n await orderRef.set(\n { checkoutSessionId: session.id, paymentLinkUrl: session.url },\n { merge: true },\n )\n // Spread on the same terms as the register's: present only when there is\n // something to say, so a caller can test the key rather than a length.\n const payload = {\n orderId: orderRef.id,\n url: session.url,\n ...(stockWarnings.length > 0 ? { stockWarnings } : {}),\n }\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 order write may or may not have landed; the\n // merchant reconciles from the orders list, the same position they were\n // in before this endpoint had a claim at all. The redemption slot goes\n // back for the same reason — a throw is the one path that would otherwise\n // leave it standing against the cap until its TTL lapsed.\n await releaseDiscountSlot()\n await claim?.release()\n return res.status(500).json({ error: 'Draft order failed' })\n }\n}\n"],"names":["holdsCommerceSiteKey","commerceSitePermissionRefusal","Aglyn","CommerceModel","firebaseAdmin","getOrgForHost","merchantAccountIsReady","checkoutSessionCardAuthenticationParams","planCheckoutShippingWithCarriers","resolveManualTaxRateId","orderStatusUrl","holdPromotionSlot","promotionHoldKey","buildRoute","claimAttempt","Route","draftOrderHandler","req","res","body","method","status","json","error","process","env","STRIPE_SECRET_KEY","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","productId","variantId","quantity","Math","max","min","round","Number","email","trim","couponCode","idempotencyKey","claim","discountSlot","discountHoldKey","releaseDiscountSlot","slot","release","storeSettings","taxSettings","product","variant","ownerOrg","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","productSnapshot","raw","data","deletedAt","liftLegacyProduct","variants","find","item","id","variantHasPrice","name","checkEntitlement","org","ownerId","ownerUid","ownerProfile","accountId","chargesEnabled","accountLivemode","subject","consoleSubdomain","consoleOrgSlug","slug","origin","host","consoleProductsUrl","HOST_PLUGIN","orgSlug","pluginSlug","shortfall","stockShortfall","stockWarnings","requested","available","unitAmountCents","priceUsd","lineItems","sku","productType","type","itemsCents","draftDiscountLines","amountCents","hubDiscounts","limit","resolvedDiscount","resolveDiscount","docs","map","docSnapshot","$id","code","subtotalCents","productIds","lines","codeProblem","appliedDiscountId","benefit","kind","discountId","discountCents","chargedItemsCents","appliedDiscountCents","shippingSettings","taxDecision","storefrontTaxDecision","settings","taxExempt","STOREFRONT_TAX_UNDECIDED_MESSAGE","taxMisconfigured","storefrontTaxMisconfiguration","useStripeTax","manualRate","pricesIncludeTax","resolveTaxRate","taxCents","computeTaxCents","pct","shippingPlan","cart","totalGrams","weightGrams","parcel","productParcelDimensions","destination","country","shippingCountry","postalCode","shippingPostalCode","countries","CHECKOUT_SHIPPING_COUNTRIES","options","needsPostalCode","needsShippingCountry","needsShippingPostalCode","shippingCountries","refusal","declared","normalizeCheckoutShippingCountry","CHECKOUT_SHIPPING_COUNTRY_NAMES","CART_UNPRICEABLE_SHIPPING_MESSAGE","shippingOptions","freeShipping","option","shippingCeilingCents","reduce","most","feeCents","resolveTransactionFeeCents","totals","computeOrderTotals","evenUnitAmountCents","floor","remainderCents","chargedQuantity","chargedUnitAmountCents","chargedLineName","claimed","scopeId","orgId","key","busyMessage","replay","ref","holdKey","stripeKey","label","ok","discount","PROMOTION_EXHAUSTED_MESSAGE","PROMOTION_UNAVAILABLE_MESSAGE","orderRef","counterRef","runTransaction","transaction","counter","number","set","next","merge","withOrderListFields","channel","taxMode","storefrontTaxModeForDecision","customerEmail","timeline","atMs","Date","now","event","detail","createdAtMs","createdAt","FieldValue","serverTimestamp","draftTaxRateId","taxPct","taxLabel","delete","catch","siteData","buyerStatusUrl","buyerSiteUrl","URL","params","URLSearchParams","mode","destinationChargeParams","taxOwner","merchantGoodsCents","shippingFloorCents","customer_email","success_url","cancel_url","quotedPostalCode","platformLiableTransferCents","appendShippingAddressCollectionParams","appendCheckoutShippingParams","appendStorefrontPaymentMethodParams","resolveStorefrontPaymentMethodControls","normalizeStorefrontPaymentMethodSettings","response","fetch","Authorization","toString","session","url","console","checkoutSessionId","paymentLinkUrl","payload","orderId","record"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,6BAA6B,QAAQ,iCAA6B;AAC3E,YAAYC,WAAW,sBAAqB;AAC5C,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SAASC,uCAAuC,QAAQ,6DAA4D;AACpH,SACEC,gCAAgC,QAE3B,wBAAoB;AAC3B,SAASC,sBAAsB,QAAQ,uBAAmB;AAC1D,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SAEEC,iBAAiB,EACjBC,gBAAgB,QACX,sBAAkB;AACzB,SACEC,UAAU,EACVC,YAAY,EACZC,KAAK,QAGA,sBAAqB;AAE5B;;;;;;;CAOC,GACD,OAAO,MAAMC,oBAAsC,OAAOC,KAAKC;QAOhCD,4BAM4BA,WACnCE,cACGA,iBACAA,iBACmCA,gBACvCA,aAIKA,kBAKxBF,MAAAA;IA1BF,IAAIA,IAAIG,MAAM,KAAK,QAAQ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,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAA+B;QACtE;QACA,MAAMqL,SAASM,GAAG,CAChB;YAAEmD,mBAAmBH,QAAQjL,EAAE;YAAEqL,gBAAgBJ,QAAQC,GAAG;QAAC,GAC7D;YAAE/C,OAAO;QAAK;QAEhB,yEAAyE;QACzE,uEAAuE;QACvE,MAAMmD,UAAU;YACdC,SAAS5D,SAAS3H,EAAE;YACpBkL,KAAKD,QAAQC,GAAG;WACZ3J,cAAcvE,MAAM,GAAG,IAAI;YAAEuE;QAAc,IAAI,CAAC;QAEtD,MAAMtD,MAAMuN,MAAM,CAAC,KAAKF;QACxB,OAAOrP,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAACiP;IAC9B,EAAE,OAAOhP,OAAO;QACd6O,QAAQ7O,KAAK,CAACA;QACd,wEAAwE;QACxE,qEAAqE;QACrE,wEAAwE;QACxE,uEAAuE;QACvE,0EAA0E;QAC1E,0DAA0D;QAC1D,MAAM8B;QACN,OAAMH,yBAAAA,MAAOK,OAAO;QACpB,OAAOrC,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/draft-order.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 { holdsCommerceSiteKey } from './commerce-site-keys'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\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 planCheckoutShippingWithCarriers,\n type CarrierShippingPlan,\n} from './carrier-shipping'\nimport { resolveManualTaxRateId } from './manual-tax-rate'\nimport { orderStatusUrl } from './order-status-token'\nimport {\n type PromotionSlotHold,\n holdPromotionSlot,\n promotionHoldKey,\n} from './promotion-hold'\nimport {\n buildRoute,\n claimAttempt,\n Route,\n type AttemptClaim,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\n\n/**\n * Draft orders (AGL-287, Shopify parity): a manager builds an order in\n * the console and sends the buyer a payment link. Creates the order doc\n * (status `pending`, channel `draft`) with a sequential number, then a\n * Stripe Checkout session on the merchant's connected account whose\n * webhook completion flips the SAME doc to `paid`\n * (metadata type `commerce-draft`).\n */\nexport const draftOrderHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const productId = String(body.productId ?? '')\n const variantId = String(body.variantId ?? '')\n const quantity = Math.max(1, Math.min(99, Math.round(Number(body.quantity ?? 1))))\n const email = String(body.email ?? '').trim()\n // A code the MERCHANT types while composing the order (AGL-305). The\n // storefront doors read this same field name, so one resolver answers it the\n // same way whoever pressed the button.\n const couponCode = String(body.couponCode ?? '').trim()\n // One draft attempt, minted by the console dialog (AGL-1697). Node\n // lowercases incoming headers, but read both spellings — the plugin API\n // request type makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n ).trim().slice(0, 200)\n if (!hostId || !productId) {\n return res.status(400).json({ error: 'Missing hostId or productId' })\n }\n\n let claim: AttemptClaim | null = null\n /**\n * The redemption slot this attempt reserved (AGL-305), hoisted so every\n * refusal below the claim — and the catch — can hand it back. A throw after\n * the hold is placed is exactly the case where a slot would otherwise stand\n * invisibly against the merchant's cap until its TTL lapsed, and this path\n * rolls its order document back on two of those refusals already.\n */\n let discountSlot: PromotionSlotHold | null = null\n let discountHoldKey = ''\n const releaseDiscountSlot = async (): Promise<void> => {\n const slot = discountSlot\n discountSlot = null\n discountHoldKey = ''\n if (slot) await slot.release()\n }\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // AN ALLOWLIST (AGL-2262), matching `cancel-order.ts`, `fulfill-order.ts`\n // and the Firestore rules, whose host-write predicate is\n // `hostMemberRole(hostId) in ['admin','editor']`. The old\n // `!role || role === 'viewer'` denylist caught the stranger but admitted\n // every OTHER string — a legacy value, a typo, any role added later — on\n // the one route that mints a live Stripe payment link. `HostAccessRole`\n // has since grown an `author` (AGL-2334), which this allowlist refuses on\n // purpose — an author edits content and does not mint payment links — and\n // which the old denylist would have admitted. That is the allowlist form\n // earning its keep on a union that changed under it.\n // \"Manage orders\" (`commerce.orders`, AGL-4047), whose preset is the site's Admin\n // and Editor this asked for, read as the rules would read it.\n if (!holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')) {\n return res.status(403).json({ error: commerceSitePermissionRefusal('commerce.orders') })\n }\n const productSnapshot = await hostRef\n .collection('products')\n .doc(productId)\n .get()\n const raw = productSnapshot.data() as any\n if (!raw || raw.deletedAt) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n const product = CommerceModel.liftLegacyProduct(raw)\n const variant = variantId\n ? product.variants.find((item) => item.id === variantId)\n : product.variants[0]\n if (!variant) return res.status(404).json({ error: 'Unknown variant' })\n // A variant with no price yet (AGL-2916) cannot be invoiced: the link\n // would ask for nothing, or for no amount at all.\n if (!CommerceModel.variantHasPrice(variant)) {\n return res.status(400).json({ error: `Set a price for ${product.name} before selling it.` })\n }\n\n // Merchant account like the storefront checkout (AGL-284).\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 free or lapsed org must not\n // keep minting payment links — at the free plan's 0% transaction fee —\n // through the one commerce door that skipped the entitlement. Sits\n // ABOVE the attempt claim with the other deterministic refusals, so it\n // never burns the merchant's idempotency key.\n if (!Aglyn.checkEntitlement(ownerOrg?.org as any, 'commerce')) {\n return res.status(403).json({ error: 'Selling is 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: `draft order host ${hostId}` },\n )\n ) {\n return res.status(409).json({ error: 'Payments are not set up yet' })\n }\n\n // Where Stripe returns the BUYER is the business's own site (AGL-4094):\n // the order's status page after paying, the site's home after backing\n // out — see the params below. The console Products page is only the\n // fallback for a site with no public address or no signing secret, which\n // no published site lacks. Console products is the plugin route keyed by\n // org slug + host SUBDOMAIN; server code cannot call\n // useConsoleHostRoute, so resolve them here. Without both, fall back to\n // the origin root rather than a fabricated dead path.\n const consoleSubdomain = (\n await firestore.collection('hostIndex').doc(hostId).get()\n ).get('subdomain') as string | undefined\n const consoleOrgSlug = ownerOrg?.org?.slug as string | undefined\n // The console's own host, as the POS door reads it — never the `Origin`\n // header (AGL-3363). The CUSTOMER lands here after paying the link, so a\n // caller-written origin would send a merchant's customer anywhere.\n const origin = `https://${req.headers.host}`\n const consoleProductsUrl =\n consoleOrgSlug && consoleSubdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, {\n orgSlug: consoleOrgSlug,\n host: consoleSubdomain,\n pluginSlug: 'products',\n })}`\n : origin\n\n // WHAT THE COUNT SAYS, said out loud (AGL-2452).\n //\n // This handler contained no `canPurchase` and no `stockShortfall` — no\n // reference to inventory of any kind. It is the door that mints a LIVE,\n // payable Stripe link, and it would mint one for a sold-out variant whose\n // merchant had chosen `oversellPolicy: 'deny'`, with the `commerce-draft`\n // webhook branch then completing it into a `paid` order. `pos-order.ts`'s\n // own comment asserts \"every storefront door gates on it\"; that claim was\n // false for this one.\n //\n // WARN, NEVER BLOCK, matching the register (AGL-2357, the decision).\n // Both of these are MERCHANT-initiated doors rather than shopper-initiated\n // ones — the merchant may well be taking a deliberate pre-order or\n // backorder — so a stale count must not refuse a sale the merchant means to\n // make. What the merchant is entitled to is to be TOLD, which is the part\n // that was missing entirely. The refusal variant is a separate decision and\n // is not taken here.\n //\n // Computed from the SERVER's product document, and reported on the same\n // `stockWarnings` key and in the same `StockShortfall` shape the register\n // already returns, so one console surface can read either door.\n const shortfall = CommerceModel.stockShortfall(\n product,\n variantId || product.variants[0]?.id,\n quantity,\n )\n const stockWarnings: CommerceModel.StockShortfall[] = shortfall\n ? [\n {\n productId,\n ...(variantId ? { variantId } : {}),\n name: product.name,\n requested: quantity,\n available: shortfall.available,\n },\n ]\n : []\n\n const unitAmountCents = Math.round(Number(variant.priceUsd) * 100)\n const lineItems: CommerceModel.OrderLineItem[] = [\n {\n productId,\n ...(variantId ? { variantId } : {}),\n name: product.name,\n ...(variant.sku ? { sku: variant.sku } : {}),\n productType: product.type,\n quantity,\n unitAmountCents,\n },\n ]\n const itemsCents = unitAmountCents * quantity\n // THE DISCOUNTS HUB, ON THIS PATH TOO (AGL-305).\n //\n // `hosts/{hostId}/discounts` reached the cart and buy-now and stopped\n // there, so a store running \"Summer sale, 10% off\" sold at 10% off through\n // both storefront doors and at FULL price the moment the merchant invoiced\n // the same buyer for the same goods through a payment link. No code has to\n // be typed for that gap to open: an automatic promotion applies itself on\n // the storefront and applied itself nowhere here, so the merchant's own\n // payment link quietly undercut — and here overcharged against — their own\n // advertised price.\n //\n // Resolved through the SAME `resolveDiscount` the other doors use, so one\n // code cannot mean two amounts.\n //\n // RESOLVED BEFORE THE TAX BLOCK BELOW, and that ordering is the whole\n // point rather than a convenience: the manual rate is computed against\n // `chargedItemsCents`, so the discount lands BEFORE tax and the taxable\n // base is the discounted one. It has to be — the session applies that same\n // rate as `line_items[0][tax_rates][0]`, which Stripe evaluates against the\n // line amount it actually charges. Reducing the line while taxing the list\n // price would make our stored `taxCents` disagree with the tax Stripe\n // collects, on every discounted draft.\n const draftDiscountLines = [{ productId, amountCents: itemsCents }]\n const hubDiscounts = await hostRef.collection('discounts').limit(100).get()\n const resolvedDiscount = CommerceModel.resolveDiscount(\n hubDiscounts.docs.map((docSnapshot) => ({\n ...(docSnapshot.data() as CommerceModel.HostDiscount),\n $id: docSnapshot.id,\n })),\n {\n ...(couponCode ? { code: couponCode } : {}),\n subtotalCents: itemsCents,\n productIds: [productId],\n lines: draftDiscountLines,\n },\n )\n // Above the claim and above the order write with every other deterministic\n // refusal, so a merchant who fixes the code and presses Send again strands\n // no `pending` draft and burns no key. A code that RESOLVES but confers\n // nothing leaves through here too — `codeProblem` carries the benefit's own\n // reason — which is what stops this door repeating the defect that charged\n // full shipping on a free-shipping code.\n if (resolvedDiscount?.codeProblem) {\n return res.status(400).json({ error: resolvedDiscount.codeProblem })\n }\n const appliedDiscountId =\n resolvedDiscount && resolvedDiscount.benefit.kind !== 'none'\n ? resolvedDiscount.discountId\n : ''\n const discountCents = appliedDiscountId ? resolvedDiscount!.discountCents : 0\n // Stripe's charge minimum is 50¢ — never price a payment link below it,\n // the same floor buy-now applies.\n const chargedItemsCents = discountCents\n ? Math.max(50, itemsCents - discountCents)\n : itemsCents\n // What was ACTUALLY taken off, after that floor. The stored totals record\n // this rather than the resolver's figure, so the parts sum to the total on\n // a draft the floor moved.\n const appliedDiscountCents = itemsCents - chargedItemsCents\n // The fee and `totals` are both built BELOW the shipping plan (AGL-2152):\n // Stripe's card cost rides the whole payment-link total, so neither can be\n // known until the tax (AGL-1953) and the shipping options are.\n\n // Shipping (AGL-1792), from the same settings document the two storefront\n // paths read. This handler contained no `shipping` string at all: a\n // merchant who configured zones and rates collected them on a cart\n // (AGL-1707) and on buy-now (AGL-1720), and nothing when they invoiced the\n // same buyer for the same parcel through a payment link. The session\n // collected no address either, so the merchant was not even told where to\n // send it — the webhook records one now that Stripe is asked for it.\n //\n // The premise AGL-1792 filed this under was that \"the destination IS known\n // — the merchant typed it\". It is not: the draft dialog collects a product,\n // a variant, a quantity and an email, and this handler reads exactly those.\n // So the destination is as unknown here as it is in the cart, and the same\n // asking machinery applies rather than none of it.\n //\n // CONDITIONAL on the product being physical, exactly as buy-now is: this\n // dialog invoices downloads and consulting too, and charging that buyer\n // postage would be worse than the bug. A missing `type` reads as physical,\n // matching the fee ladder above — the two reads must not disagree about\n // what a part-migrated doc is. The one-time condition buy-now also carries\n // is structural here: this path only ever builds `mode: 'payment'`.\n //\n // RESOLVED BEFORE THE ORDER DOCUMENT, because the plan can refuse and the\n // order is written before Stripe is called. Refusing after it would strand\n // a `pending` draft on the merchant's orders list for every attempt —\n // this path's version of the orphaned coupon AGL-1721 kept out of the cart.\n const storeSettings = await hostRef\n .collection('settings')\n .doc('store')\n .get()\n const shippingSettings = storeSettings.get('shipping') as\n CommerceModel.ShippingSettings | undefined\n\n // Taxes (AGL-1953), from the same settings document. This handler had no\n // tax code at all in either mode, so a merchant who invoiced a buyer for\n // the same product they sell on the storefront charged them no tax — the\n // cart's defect, one door over, and worse here because the merchant\n // composed this order deliberately and would reasonably assume it matched\n // their store.\n //\n // Origin-based, exactly as buy-now and the cart resolve it. The AGL-1792\n // note above already established the premise: this dialog collects a\n // product, a variant, a quantity and an email, so the DESTINATION is as\n // unknown here as it is in the cart.\n //\n // Computed pure and BEFORE the claim so the stored totals can carry it;\n // the Stripe object it needs is minted below the point of no return.\n const taxSettings = (storeSettings.get('tax') ?? {}) as CommerceModel.TaxSettings\n // AGL-1999: an unset tax mode is NOT a decision, and it must not sell.\n // `mode` was `undefined` for every store whose owner never opened the\n // Taxes card — the default state of every new storefront — and each\n // branch below tested for a specific string, so no branch was taken, no\n // tax was computed, and the shopper was charged an untaxed total. See\n // `commerce-tax-decision.ts` for why refusing beats defaulting to either\n // mode. `mode: 'none'` is the explicit opt-out and passes straight\n // through.\n const taxDecision = CommerceModel.storefrontTaxDecision({\n settings: taxSettings,\n taxExempt: product.taxExempt,\n })\n if (taxDecision.kind === 'undecided') {\n return res\n .status(409)\n .json({ error: CommerceModel.STOREFRONT_TAX_UNDECIDED_MESSAGE })\n }\n const taxMisconfigured =\n CommerceModel.storefrontTaxMisconfiguration(taxSettings)\n if (taxMisconfigured) {\n // AGL-2145: the merchant DECIDED to collect and the sale would have\n // charged zero anyway — an unfinished settings card, not a\n // jurisdiction miss. Refused in the same words and the same place as\n // the undecided case above.\n return res.status(409).json({ error: taxMisconfigured })\n }\n const useStripeTax = taxDecision.kind === 'stripe-automatic'\n const manualRate =\n taxDecision.kind === 'manual' &&\n !taxSettings.pricesIncludeTax\n ? CommerceModel.resolveTaxRate(taxSettings, taxSettings.origin ?? {})\n : null\n // THE DISCOUNTED BASE (AGL-305). `chargedItemsCents` is what the line\n // will actually be worth, and the session applies this same rate to that\n // line as a Stripe Tax Rate — so taxing `itemsCents` here would record a\n // figure Stripe never charges.\n const taxCents = manualRate\n ? CommerceModel.computeTaxCents(chargedItemsCents, manualRate.pct)\n : 0\n // Stripe Tax mode leaves this 0 at composition time and the webhook folds\n // the computed figure in — the same additive shape AGL-1792 used for\n // shipping, and for the same reason: only Stripe knows it.\n // Live carrier rates (AGL-3612), quoted for the destination the manager\n // names; see `carrier-shipping.ts`.\n const shippingPlan: CarrierShippingPlan =\n (product.type ?? 'physical') === 'physical'\n ? await planCheckoutShippingWithCarriers({\n hostId,\n settings: shippingSettings,\n cart: {\n subtotalCents: itemsCents,\n totalGrams:\n Math.max(0, Number(variant.weightGrams ?? 0)) * quantity,\n ...(quantity === 1 ? { parcel: CommerceModel.productParcelDimensions(product) } : {}),\n },\n destination: {\n country: body.shippingCountry,\n postalCode: body.shippingPostalCode,\n },\n })\n : { countries: CommerceModel.CHECKOUT_SHIPPING_COUNTRIES, options: [] }\n if (shippingPlan.needsPostalCode) {\n return res.status(400).json({\n error: 'Enter the postal code this order ships to.',\n needsShippingCountry: true,\n needsShippingPostalCode: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n if (shippingPlan.refusal === 'destination-required') {\n return res.status(400).json({\n error: 'Choose where this order ships to.',\n needsShippingCountry: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n if (shippingPlan.refusal === 'destination-unserved') {\n const declared = CommerceModel.normalizeCheckoutShippingCountry(\n body.shippingCountry,\n )\n return res.status(409).json({\n error: `This store does not ship to ${\n CommerceModel.CHECKOUT_SHIPPING_COUNTRY_NAMES[declared as string] ??\n 'that country'\n }.`,\n needsShippingCountry: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n })\n }\n // No rate of the merchant's reaches this order (AGL-2232). Above the\n // order write and the payment link, like every other refusal here, so a\n // manager who fixes the tier table and presses Send again strands nothing.\n if (shippingPlan.refusal === 'cart-unpriceable') {\n return res\n .status(409)\n .json({ error: CommerceModel.CART_UNPRICEABLE_SHIPPING_MESSAGE })\n }\n // FREE SHIPPING IS A ZEROED RATE, NOT A REDUCTION (AGL-305), the same\n // construction the cart uses and for the same reason: nothing has picked a\n // rate yet, so there is no amount to take off. The buyer chooses after the\n // link is minted, so the only exact answer is to offer every rate at zero.\n //\n // Every rate rather than the cheapest, because `free_shipping` carries no\n // field naming one — and zeroing them all keeps the fee, the transfer floor\n // and the ceiling below honest, since all three read these same options.\n //\n // Derived from `shippingPlan.options` and read EVERYWHERE below in its\n // place; a reader that reached past this to `shippingPlan.options` would\n // price carriage the buyer is not being charged for.\n const shippingOptions =\n resolvedDiscount?.freeShipping === true\n ? shippingPlan.options.map((option) => ({ ...option, amountCents: 0 }))\n : shippingPlan.options\n\n // THE PLATFORM FEE (AGL-2152) — the advertised take PLUS Stripe's card\n // cost, passed through at cost. A payment link is a destination charge, so\n // Stripe debits 2.9% + 30¢ from the PLATFORM's balance; the old take-only\n // figure meant every tier carrying a 0% rate invoiced a buyer at a loss to\n // Aglyn, and Starter's 2% is below 2.9% so it lost money at every size too.\n //\n // `?? 'physical'` (AGL-2251), matching `checkout.ts` and the cart. Without\n // it a product doc carrying no `type` fell to `resolveTransactionFeePct`'s\n // digital branch, so a merchant's payment link took a different cut of the\n // same product than their storefront did.\n //\n // The base is the whole card total: the goods, the manual tax line, and the DEAREST shipping\n // option the link offers (the buyer picks after the link is minted and\n // `application_fee_amount` is fixed at creation, so reaching for the\n // cheapest would put the difference back on Aglyn). A store on Stripe Tax\n // is the one residual — that tax is computed inside Stripe afterwards.\n const shippingCeilingCents = shippingOptions.reduce(\n (most, option) =>\n Math.max(most, Math.max(0, Number(option.amountCents ?? 0))),\n 0,\n )\n // Both bases are the DISCOUNTED goods (AGL-305). The platform take is a\n // cut of what the merchant actually sells for, and Stripe's card cost is\n // passed through on what the card actually runs for — reading `itemsCents`\n // here would invoice the merchant a fee on money nobody paid.\n const feeCents = Aglyn.resolveTransactionFeeCents(\n ownerOrg?.org as any,\n product.type ?? 'physical',\n chargedItemsCents,\n chargedItemsCents + taxCents + shippingCeilingCents,\n )\n // Stripe Tax mode leaves the tax 0 at composition time and the webhook\n // folds the computed figure in — the same additive shape AGL-1792 used for\n // shipping, and for the same reason: only Stripe knows it.\n const totals = CommerceModel.computeOrderTotals(lineItems, {\n feeCents,\n taxCents,\n // The line item still carries the LIST price, so the discount has to be\n // a named part of the totals or `itemsCents - discountCents + tax` would\n // not be the number on the payment link.\n discountCents: appliedDiscountCents,\n })\n\n // THE LINK CHARGES `chargedItemsCents`, EXACTLY (the AGL-2159 construction,\n // reused here because this path grew the same problem the moment it grew a\n // discount).\n //\n // A Stripe line is `quantity` units at ONE integer `unit_amount`, so it can\n // only express totals divisible by `quantity` — and a percentage discount\n // does not respect that. Dividing and multiplying back misses the intended\n // total by up to `quantity / 2` cents in either direction, which on this\n // path is worse than on buy-now: the frozen `totals` above are written to\n // the order document BEFORE the session is minted, so a link that charged\n // a different number would leave the merchant's own books disagreeing with\n // what their buyer paid, permanently and silently.\n //\n // So when the total does not divide evenly, the line becomes ONE unit at\n // the exact total with the count moved into the display name. The real\n // quantity is carried by the order document's line item, which is\n // untouched, so nothing downstream can tell the difference.\n //\n // The even case — every undiscounted draft, and most discounted ones —\n // keeps the per-unit shape byte for byte.\n const evenUnitAmountCents = Math.floor(chargedItemsCents / quantity)\n const remainderCents = chargedItemsCents - evenUnitAmountCents * quantity\n const chargedQuantity = remainderCents === 0 ? quantity : 1\n const chargedUnitAmountCents =\n remainderCents === 0 ? evenUnitAmountCents : chargedItemsCents\n const chargedLineName = `${product.name}${\n remainderCents === 0 ? '' : ` × ${quantity}`\n }`.slice(0, 120)\n\n // Point of no return (AGL-1697): everything past here writes an order and\n // mints a live payment link. Every deterministic refusal — unknown\n // product, payments not set up, the shipping-destination ask — sits above\n // this line, so none of them burns the key: the merchant fixes the input\n // and presses the same button. Before the claim, a double-submit minted a\n // SECOND order doc, burned a second sequential number, and returned two\n // live payment links bound to different orders, both payable.\n const claimed = await claimAttempt(firestore, {\n kind: 'commerce-draft',\n scopeId: hostId,\n orgId: String(ownerOrg?.org?.id ?? ''),\n key: idempotencyKey,\n busyMessage: 'This draft order is already being created',\n })\n if ('replay' in claimed) {\n return res.status(claimed.replay.status).json(claimed.replay.body)\n }\n claim = claimed.claim\n\n // THE REDEMPTION SLOT IS RESERVED HERE (AGL-305), on the same terms the\n // storefront doors reserve it.\n //\n // A payment link lives until the buyer pays it, so between this handler and\n // the `commerce-draft` webhook branch that settles the slot there is a\n // window measured in days — far wider than a Checkout Session's. Reading\n // `redemptions` and hoping would let a merchant mint ten links against a\n // cap of one and have all ten pay.\n //\n // BELOW the claim because the hold is keyed by the attempt: a retry of one\n // attempt must be able to re-claim the slot it already holds rather than be\n // refused by it. An uncapped promotion writes nothing and returns an empty\n // `holdKey`, which is what tells the webhook to fall back to the plain\n // increment.\n if (appliedDiscountId) {\n const slot = await holdPromotionSlot({\n firestore,\n ref: hostRef.collection('discounts').doc(appliedDiscountId),\n holdKey: promotionHoldKey(claimed.claim.stripeKey),\n label: `draft discount ${appliedDiscountId}`,\n })\n if (!slot.ok) {\n // Refused rather than quietly repriced, and that is deliberate for the\n // AUTOMATIC case too: the merchant composed this order at a price the\n // promotion was part of, and minting the link at full price would\n // invoice their buyer more than the store advertises without saying so.\n // Nothing has been written yet, so the key goes back and the retry\n // prices correctly — `resolveDiscount` counts live holds and simply\n // stops offering an exhausted promotion.\n await claim.release()\n return res.status(409).json({\n error:\n couponCode && resolvedDiscount?.discount.code\n ? CommerceModel.PROMOTION_EXHAUSTED_MESSAGE\n : CommerceModel.PROMOTION_UNAVAILABLE_MESSAGE,\n })\n }\n if (slot.holdKey) {\n discountSlot = slot\n discountHoldKey = slot.holdKey\n }\n }\n\n // Order doc first (transactional number), then the payment link.\n const orderRef = hostRef.collection('orders').doc()\n const counterRef = hostRef.collection('counters').doc('orders')\n await firestore.runTransaction(async (transaction) => {\n const counter = await transaction.get(counterRef)\n const number = Number(counter.get('next') ?? 1)\n transaction.set(counterRef, { next: number + 1 }, { merge: true })\n // With the fields the orders list queries by (AGL-3321).\n transaction.set(orderRef, CommerceModel.withOrderListFields(orderRef.id, {\n number,\n status: 'pending',\n channel: 'draft',\n lineItems,\n totals,\n // WHICH TAX REGIME THIS ORDER IS COMPOSED UNDER (AGL-2451), from the\n // decision taken above rather than from the frozen `taxCents` — a\n // Stripe Tax draft freezes 0 there and only the paid session knows the\n // figure, so a mode read back off the amount would call it `none`.\n //\n // Stamped at composition so a draft that is never paid still says what\n // it was priced under, and RESTATED by the `commerce-draft` webhook\n // branch from the session that actually charged it. The webhook's is\n // authoritative — it has Stripe's computed tax in hand — and for a\n // manual draft the two agree by construction.\n taxMode: CommerceModel.storefrontTaxModeForDecision(\n taxDecision,\n taxCents,\n ),\n customerEmail: email || null,\n // WHAT ITS INVOICE'S LASTING PAY LINK CHARGES LATER (AGL-4099). The\n // session below lapses in a day; an invoice for this draft opens a\n // fresh one from the stored order whenever the buyer presses Pay, and\n // offers the same shipping rates this link does, and counts the same\n // promotion once paid. Stored even when there are no rates, so an\n // invoice can tell \"ships nothing\" from a draft made before this.\n draftShipping: {\n countries: shippingOptions.length > 0 ? Array.from(shippingPlan.countries ?? []) : [],\n options: shippingOptions.map((option) => ({\n rateId: String(option.rateId ?? ''),\n name: String(option.name ?? ''),\n amountCents: Math.max(0, Math.round(Number(option.amountCents ?? 0))),\n })),\n },\n ...(appliedDiscountId ? { discountId: appliedDiscountId } : {}),\n timeline: [\n {\n atMs: Date.now(),\n event: 'draft',\n detail: `Draft created by ${decoded.email ?? decoded.uid}`,\n },\n ],\n createdAtMs: Date.now(),\n createdAt: firebaseAdmin.firestore.FieldValue.serverTimestamp(),\n }))\n })\n\n // The tax rate is minted here, BELOW the claim, because it creates a real\n // Stripe object (AGL-1953). Cached per host, so it is usually a read.\n let draftTaxRateId = ''\n if (taxCents > 0 && manualRate) {\n draftTaxRateId =\n (await resolveManualTaxRateId({\n hostRef,\n taxPct: manualRate.pct,\n taxLabel: manualRate.label || `Tax (${manualRate.pct}%)`,\n ...(claim.stripeKey\n ? { headers: { 'Idempotency-Key': `${claim.stripeKey}-tax-rate` } }\n : {}),\n })) ?? ''\n if (!draftTaxRateId) {\n // A VISIBLE refusal rather than an untaxed payment link — the silent\n // under-collection is the defect. The order doc is rolled back the\n // same way the session failure below rolls it back.\n await orderRef.delete().catch(() => undefined)\n await releaseDiscountSlot()\n await claim.release()\n return res.status(502).json({ error: 'Payment link creation failed' })\n }\n }\n // The buyer's way back, on the business's site: the order's status page\n // (which reads the paid state from the server) and the site's home.\n const siteData = hostSnapshot.data() as { cname?: unknown; subdomain?: unknown } | undefined\n const buyerStatusUrl = orderStatusUrl(siteData, hostId, orderRef.id)\n const buyerSiteUrl = buyerStatusUrl ? `${new URL(buyerStatusUrl).origin}/` : ''\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 ...(useStripeTax ? { 'automatic_tax[enabled]': 'true' } : {}),\n ...(draftTaxRateId ? { 'line_items[0][tax_rates][0]': draftTaxRateId } : {}),\n 'line_items[0][quantity]': String(chargedQuantity),\n 'line_items[0][price_data][currency]': 'usd',\n 'line_items[0][price_data][unit_amount]': String(chargedUnitAmountCents),\n 'line_items[0][price_data][product_data][name]': chargedLineName,\n // THE CONNECT SPLIT (AGL-1956). A Stripe Tax payment link computes its\n // tax against AGLYN's registrations and Aglyn remits it (AGL-1904), so\n // the merchant gets a FIXED `transfer_data[amount]` and no\n // `application_fee_amount`: the fee form transfers `amount_total − fee`,\n // and `amount_total` includes that tax. A manual-rate or untaxed link is\n // unchanged. See `commerce-connect-transfer.ts`.\n ...CommerceModel.destinationChargeParams({\n accountId: String(accountId),\n feeCents,\n taxOwner: useStripeTax ? 'platform' : 'merchant',\n // The DISCOUNTED goods (AGL-305): this is what the merchant is\n // transferred, and paying out the list price on a discounted link\n // would move money Stripe never collected.\n merchantGoodsCents: chargedItemsCents,\n shippingFloorCents: CommerceModel.shippingFloorCents(shippingOptions),\n }),\n ...(email ? { customer_email: email } : {}),\n success_url: buyerStatusUrl ?? `${consoleProductsUrl}?draft=paid`,\n cancel_url: buyerSiteUrl || `${consoleProductsUrl}?draft=canceled`,\n 'metadata[type]': 'commerce-draft',\n 'metadata[hostId]': hostId,\n 'metadata[orderId]': orderRef.id,\n 'metadata[productId]': productId,\n ...(variantId ? { 'metadata[variantId]': variantId } : {}),\n 'metadata[feeCents]': String(feeCents),\n ...(shippingPlan.quotedPostalCode\n ? { 'metadata[shippingQuotePostalCode]': shippingPlan.quotedPostalCode }\n : {}),\n // WHAT THE WEBHOOK SETTLES (AGL-305), in the field names the\n // `checkout.session.completed` branch already reads for the cart. The\n // hold key's ABSENCE is what tells it to fall back to the unconditional\n // increment, which is right for an uncapped promotion.\n ...(appliedDiscountId\n ? { 'metadata[discountId]': appliedDiscountId }\n : {}),\n ...(discountHoldKey ? { 'metadata[discountHoldKey]': discountHoldKey } : {}),\n // See the AGL-1956 note in `checkout.ts` — recorded only on the shape\n // where the merchant's payout is no longer the whole charge.\n ...(useStripeTax\n ? {\n 'metadata[transferCents]': String(\n CommerceModel.platformLiableTransferCents({\n feeCents,\n merchantGoodsCents: chargedItemsCents,\n shippingFloorCents:\n CommerceModel.shippingFloorCents(shippingOptions),\n }),\n ),\n 'metadata[transferShippingCents]': String(\n CommerceModel.shippingFloorCents(shippingOptions),\n ),\n }\n : {}),\n })\n // Both keys or neither (AGL-1720's rule, inherited). Stripe will not apply\n // a shipping rate without an address to ship to, and a merchant who\n // configured nothing plans to no options and so gets neither — a payment\n // link byte-identical to the one this handler built before shipping\n // existed on it.\n if (shippingOptions.length > 0) {\n CommerceModel.appendShippingAddressCollectionParams(\n params,\n shippingPlan.countries,\n )\n CommerceModel.appendCheckoutShippingParams(params, shippingOptions)\n }\n // The payment methods the merchant switched off reach the payment link\n // too (AGL-3629). A hosted Stripe page shows Apple Pay and Google Pay by\n // device and cannot hide them per merchant; everything else follows.\n CommerceModel.appendStorefrontPaymentMethodParams(\n params,\n CommerceModel.resolveStorefrontPaymentMethodControls(\n CommerceModel.normalizeStorefrontPaymentMethodSettings(\n storeSettings.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 is a live payment link (AGL-1697). Stripe replays\n // the existing session for a repeated key instead of opening a\n // second one on the merchant's account, which covers the window\n // where our claim is written but the response never arrives.\n ...(claim.stripeKey ? { 'Idempotency-Key': claim.stripeKey } : {}),\n },\n body: params.toString(),\n },\n )\n const session = (await response.json()) as {\n url?: string\n id?: string\n error?: any\n }\n if (!response.ok || !session.url) {\n console.error('Stripe draft-order error', session.error)\n await orderRef.delete().catch(() => undefined)\n // The draft did not happen — hand the key back rather than locking this\n // dialog out over one flaky moment. The retry re-derives the SAME\n // digest, so if Stripe did create the session it replays it.\n await releaseDiscountSlot()\n await claim.release()\n return res.status(502).json({ error: 'Payment link creation failed' })\n }\n await orderRef.set(\n { checkoutSessionId: session.id, paymentLinkUrl: session.url },\n { merge: true },\n )\n // Spread on the same terms as the register's: present only when there is\n // something to say, so a caller can test the key rather than a length.\n const payload = {\n orderId: orderRef.id,\n url: session.url,\n ...(stockWarnings.length > 0 ? { stockWarnings } : {}),\n }\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 order write may or may not have landed; the\n // merchant reconciles from the orders list, the same position they were\n // in before this endpoint had a claim at all. The redemption slot goes\n // back for the same reason — a throw is the one path that would otherwise\n // leave it standing against the cap until its TTL lapsed.\n await releaseDiscountSlot()\n await claim?.release()\n return res.status(500).json({ error: 'Draft order failed' })\n }\n}\n"],"names":["holdsCommerceSiteKey","commerceSitePermissionRefusal","Aglyn","CommerceModel","firebaseAdmin","getOrgForHost","merchantAccountIsReady","checkoutSessionCardAuthenticationParams","planCheckoutShippingWithCarriers","resolveManualTaxRateId","orderStatusUrl","holdPromotionSlot","promotionHoldKey","buildRoute","claimAttempt","Route","draftOrderHandler","req","res","body","method","status","json","error","process","env","STRIPE_SECRET_KEY","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","productId","variantId","quantity","Math","max","min","round","Number","email","trim","couponCode","idempotencyKey","claim","discountSlot","discountHoldKey","releaseDiscountSlot","slot","release","storeSettings","taxSettings","product","variant","ownerOrg","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","productSnapshot","raw","data","deletedAt","liftLegacyProduct","variants","find","item","id","variantHasPrice","name","checkEntitlement","org","ownerId","ownerUid","ownerProfile","accountId","chargesEnabled","accountLivemode","subject","consoleSubdomain","consoleOrgSlug","slug","origin","host","consoleProductsUrl","HOST_PLUGIN","orgSlug","pluginSlug","shortfall","stockShortfall","stockWarnings","requested","available","unitAmountCents","priceUsd","lineItems","sku","productType","type","itemsCents","draftDiscountLines","amountCents","hubDiscounts","limit","resolvedDiscount","resolveDiscount","docs","map","docSnapshot","$id","code","subtotalCents","productIds","lines","codeProblem","appliedDiscountId","benefit","kind","discountId","discountCents","chargedItemsCents","appliedDiscountCents","shippingSettings","taxDecision","storefrontTaxDecision","settings","taxExempt","STOREFRONT_TAX_UNDECIDED_MESSAGE","taxMisconfigured","storefrontTaxMisconfiguration","useStripeTax","manualRate","pricesIncludeTax","resolveTaxRate","taxCents","computeTaxCents","pct","shippingPlan","cart","totalGrams","weightGrams","parcel","productParcelDimensions","destination","country","shippingCountry","postalCode","shippingPostalCode","countries","CHECKOUT_SHIPPING_COUNTRIES","options","needsPostalCode","needsShippingCountry","needsShippingPostalCode","shippingCountries","refusal","declared","normalizeCheckoutShippingCountry","CHECKOUT_SHIPPING_COUNTRY_NAMES","CART_UNPRICEABLE_SHIPPING_MESSAGE","shippingOptions","freeShipping","option","shippingCeilingCents","reduce","most","feeCents","resolveTransactionFeeCents","totals","computeOrderTotals","evenUnitAmountCents","floor","remainderCents","chargedQuantity","chargedUnitAmountCents","chargedLineName","claimed","scopeId","orgId","key","busyMessage","replay","ref","holdKey","stripeKey","label","ok","discount","PROMOTION_EXHAUSTED_MESSAGE","PROMOTION_UNAVAILABLE_MESSAGE","orderRef","counterRef","runTransaction","transaction","counter","number","set","next","merge","withOrderListFields","channel","taxMode","storefrontTaxModeForDecision","customerEmail","draftShipping","Array","from","rateId","timeline","atMs","Date","now","event","detail","createdAtMs","createdAt","FieldValue","serverTimestamp","draftTaxRateId","taxPct","taxLabel","delete","catch","siteData","buyerStatusUrl","buyerSiteUrl","URL","params","URLSearchParams","mode","destinationChargeParams","taxOwner","merchantGoodsCents","shippingFloorCents","customer_email","success_url","cancel_url","quotedPostalCode","platformLiableTransferCents","appendShippingAddressCollectionParams","appendCheckoutShippingParams","appendStorefrontPaymentMethodParams","resolveStorefrontPaymentMethodControls","normalizeStorefrontPaymentMethodSettings","response","fetch","Authorization","toString","session","url","console","checkoutSessionId","paymentLinkUrl","payload","orderId","record"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,6BAA6B,QAAQ,iCAA6B;AAC3E,YAAYC,WAAW,sBAAqB;AAC5C,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SAASC,uCAAuC,QAAQ,6DAA4D;AACpH,SACEC,gCAAgC,QAE3B,wBAAoB;AAC3B,SAASC,sBAAsB,QAAQ,uBAAmB;AAC1D,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SAEEC,iBAAiB,EACjBC,gBAAgB,QACX,sBAAkB;AACzB,SACEC,UAAU,EACVC,YAAY,EACZC,KAAK,QAGA,sBAAqB;AAE5B;;;;;;;CAOC,GACD,OAAO,MAAMC,oBAAsC,OAAOC,KAAKC;QAOhCD,4BAM4BA,WACnCE,cACGA,iBACAA,iBACmCA,gBACvCA,aAIKA,kBAKxBF,MAAAA;IA1BF,IAAIA,IAAIG,MAAM,KAAK,QAAQ;QACzB,OAAOF,IAA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BAAAA,MAAOK,OAAO;QACpB,OAAOrC,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;AACF,EAAC"}
@@ -0,0 +1,76 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type RenderedHostEmail, type SendEmailOptions, type SendEmailResult, type SendingIdentityVerdict } from '@aglyn/shared-util-email';
18
+ import * as CommerceModel from '../model';
19
+ import type { orderInvoicePdfFile } from './commerce-pdf';
20
+ import type { CommercePdfFile } from './pdf-response';
21
+ /** What the route hands over for one send. */
22
+ export interface InvoiceDeliveryInput {
23
+ hostId: string;
24
+ orderId: string;
25
+ order: CommerceModel.HostOrder;
26
+ host: Record<string, unknown>;
27
+ store: Record<string, unknown> | null;
28
+ owner: {
29
+ id?: string;
30
+ org?: unknown;
31
+ } | null;
32
+ to: string;
33
+ /** The subject as typed; empty takes the default. */
34
+ subject: string;
35
+ message: string;
36
+ /** The order's pay link, for an invoice still to be paid; null for a paid one. */
37
+ payUrl: string | null;
38
+ /** The sending member's email: the Reply-To when the site has no contact email. */
39
+ senderEmail: string | null;
40
+ atMs: number;
41
+ }
42
+ export type InvoiceDeliveryResult = {
43
+ sent: true;
44
+ messageId: string;
45
+ providerId: string | null;
46
+ subject: string;
47
+ replyTo: string | null;
48
+ thread: CommerceModel.QuoteEmailThread;
49
+ paid: boolean;
50
+ totalCents: number;
51
+ } | {
52
+ sent: false;
53
+ status: number;
54
+ error: string;
55
+ };
56
+ /** The calls the send makes, injectable for specs. */
57
+ export interface InvoiceMailerDeps {
58
+ configured(): boolean;
59
+ sendingIdentity(hostId: string): Promise<SendingIdentityVerdict>;
60
+ render(hostId: string, key: string, tokens: Record<string, string>): Promise<RenderedHostEmail | null>;
61
+ /** The invoice's PDF; loads the PDF writer and sharp only here. */
62
+ invoicePdf(input: Parameters<typeof orderInvoicePdfFile>[0]): Promise<CommercePdfFile>;
63
+ send(options: SendEmailOptions): Promise<SendEmailResult>;
64
+ meter(hostId: string): Promise<void>;
65
+ /** The bounce and complaint list only: an invoice is transactional. */
66
+ suppression(email: string): Promise<'suppressed-platform' | null>;
67
+ }
68
+ export declare function defaultInvoiceMailerDeps(): InvoiceMailerDeps;
69
+ /** What the console's Send invoice reaches: whether mail can go, whether this address may be mailed, and the send. */
70
+ export interface InvoiceMailer {
71
+ configured(): boolean;
72
+ suppression(email: string): Promise<'suppressed-platform' | null>;
73
+ deliver(input: InvoiceDeliveryInput): Promise<InvoiceDeliveryResult>;
74
+ }
75
+ /** The invoice email, said and sent. */
76
+ export declare function invoiceMailer(deps?: InvoiceMailerDeps): InvoiceMailer;
@@ -0,0 +1,183 @@
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 { resolveSiteTimeZone } from "@aglyn/aglyn/app-utils/collection-entry-date";
18
+ import { resolveBrandingProfile } from "@aglyn/aglyn/app-utils/plan-entitlements";
19
+ import { emailThreadAfterSend, isEmailConfigured, mintEmailMessageId, nextThreadHeaders, readEmailThread, sendEmail } from "@aglyn/shared-util-email";
20
+ import { firebaseAdmin, hostSendingIdentity, meterHostEmail, renderHostEmailWithTokens, transactionalAddressSuppression } from "@aglyn/tenant-data-admin";
21
+ import * as CommerceModel from "../model/index.js";
22
+ import { INVOICE_EMAIL_KEY, invoiceEmailContent } from "../utils/invoice-email-content.js";
23
+ import { quoteBusinessName, quoteReplyTo } from "./quote-email.js";
24
+ export function defaultInvoiceMailerDeps() {
25
+ const firestore = ()=>firebaseAdmin.app().firestore();
26
+ return {
27
+ configured: ()=>isEmailConfigured(),
28
+ sendingIdentity: (hostId)=>hostSendingIdentity(hostId),
29
+ render: (hostId, key, tokens)=>renderHostEmailWithTokens(firestore(), hostId, key, tokens),
30
+ invoicePdf: async (input)=>(await import("./commerce-pdf.js")).orderInvoicePdfFile(input),
31
+ send: (options)=>sendEmail(options),
32
+ meter: async (hostId)=>{
33
+ await meterHostEmail(hostId);
34
+ },
35
+ suppression: (email)=>transactionalAddressSuppression(email)
36
+ };
37
+ }
38
+ /** A refused send in the words the console shows. */ function refusalOf(result) {
39
+ switch(result.reason){
40
+ case 'unconfigured':
41
+ return {
42
+ status: 503,
43
+ error: 'Email isn’t set up here, so the invoice wasn’t sent.'
44
+ };
45
+ case 'rate-limited':
46
+ return {
47
+ status: 429,
48
+ error: 'Too many emails are going out right now. Try again in a minute.'
49
+ };
50
+ case 'suppressed':
51
+ case 'undeliverable':
52
+ return {
53
+ status: 409,
54
+ error: 'This address can’t receive email, so the invoice wasn’t sent.'
55
+ };
56
+ case 'unverified-domain':
57
+ return {
58
+ status: 409,
59
+ error: 'This site’s sending domain isn’t verified, so the invoice wasn’t sent. Check Email settings.'
60
+ };
61
+ case 'suspended':
62
+ return {
63
+ status: 423,
64
+ error: 'This site can’t send email right now, so the invoice wasn’t sent.'
65
+ };
66
+ case 'held-for-review':
67
+ return {
68
+ status: 409,
69
+ error: `The email was held for review, so it hasn’t gone out yet.${result.detail ? ` ${result.detail}` : ''}`
70
+ };
71
+ default:
72
+ return {
73
+ status: 502,
74
+ error: 'The invoice email could not be sent. Try again.'
75
+ };
76
+ }
77
+ }
78
+ /** The invoice email, said and sent. */ export function invoiceMailer(deps = defaultInvoiceMailerDeps()) {
79
+ return {
80
+ configured: ()=>deps.configured(),
81
+ suppression: (email)=>deps.suppression(email),
82
+ deliver: async (input)=>{
83
+ var _ref, _ref1, _host_cname, _result_id;
84
+ var _input_owner, _input_store, _input_owner1;
85
+ const { hostId, orderId, order, host } = input;
86
+ const businessName = quoteBusinessName(host);
87
+ const subject = input.subject || CommerceModel.invoiceEmailDefaultSubject(order, businessName, orderId);
88
+ const identity = await deps.sendingIdentity(hostId);
89
+ const org = (_ref = (_input_owner = input.owner) == null ? void 0 : _input_owner.org) != null ? _ref : null;
90
+ const content = invoiceEmailContent({
91
+ order,
92
+ orderId,
93
+ businessName,
94
+ currency: String((_ref1 = (_input_store = input.store) == null ? void 0 : _input_store['currency']) != null ? _ref1 : 'USD'),
95
+ subject,
96
+ message: input.message,
97
+ payUrl: input.payUrl,
98
+ timeZone: resolveSiteTimeZone(org, host)
99
+ });
100
+ // The PDF is what the email says is attached; without it nothing goes.
101
+ let pdf;
102
+ try {
103
+ pdf = await deps.invoicePdf({
104
+ hostId,
105
+ orderId,
106
+ order,
107
+ host,
108
+ store: input.store,
109
+ owner: input.owner,
110
+ payUrl: content.paid ? null : input.payUrl
111
+ });
112
+ } catch (error) {
113
+ console.error('[commerce/invoice-email] the PDF could not be made', {
114
+ hostId,
115
+ orderId,
116
+ error
117
+ });
118
+ return {
119
+ sent: false,
120
+ status: 500,
121
+ error: 'The invoice’s PDF could not be made, so nothing was sent. Try again.'
122
+ };
123
+ }
124
+ const rendered = await deps.render(hostId, INVOICE_EMAIL_KEY, content.tokens);
125
+ const thread = readEmailThread(CommerceModel.invoiceEmailThread(order));
126
+ const siteHost = String((_host_cname = host['cname']) != null ? _host_cname : '').trim() || null;
127
+ const messageId = mintEmailMessageId([
128
+ identity == null ? void 0 : identity.domain,
129
+ identity == null ? void 0 : identity.from,
130
+ siteHost
131
+ ], {
132
+ label: 'invoice',
133
+ atMs: input.atMs
134
+ });
135
+ const replyTo = quoteReplyTo(host, input.senderEmail);
136
+ const result = await deps.send(_extends({
137
+ to: input.to,
138
+ // The subject as sent, whatever a design's own says: it is what keeps
139
+ // the conversation together, and it was typed for this send.
140
+ subject,
141
+ text: (rendered == null ? void 0 : rendered.text) || content.text
142
+ }, (rendered == null ? void 0 : rendered.html) ? {
143
+ html: rendered.html
144
+ } : {}, {
145
+ headers: nextThreadHeaders(thread, messageId)
146
+ }, replyTo ? {
147
+ replyTo
148
+ } : {}, {
149
+ fromName: resolveBrandingProfile((_input_owner1 = input.owner) == null ? void 0 : _input_owner1.org).fromName,
150
+ sendingIdentity: identity,
151
+ audience: 'tenant',
152
+ context: 'invoice',
153
+ attachments: [
154
+ {
155
+ filename: pdf.filename,
156
+ contentType: 'application/pdf',
157
+ content: Buffer.from(pdf.bytes).toString('base64')
158
+ }
159
+ ]
160
+ }));
161
+ if (!result.sent) return _extends({
162
+ sent: false
163
+ }, refusalOf(result));
164
+ // Cost meter (AGL-1438), as every transactional site email.
165
+ await deps.meter(hostId).catch((error)=>console.error('[commerce/invoice-email] not metered', error));
166
+ return {
167
+ sent: true,
168
+ messageId,
169
+ providerId: (_result_id = result.id) != null ? _result_id : null,
170
+ subject,
171
+ replyTo,
172
+ thread: emailThreadAfterSend(thread, {
173
+ messageId,
174
+ subject
175
+ }),
176
+ paid: content.paid,
177
+ totalCents: content.totalCents
178
+ };
179
+ }
180
+ };
181
+ }
182
+
183
+ //# sourceMappingURL=invoice-email.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/invoice-email.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 { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n emailThreadAfterSend,\n isEmailConfigured,\n mintEmailMessageId,\n nextThreadHeaders,\n readEmailThread,\n sendEmail,\n type RenderedHostEmail,\n type SendEmailOptions,\n type SendEmailResult,\n type SendingIdentityVerdict,\n} from '@aglyn/shared-util-email'\nimport {\n firebaseAdmin,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n transactionalAddressSuppression,\n} from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { INVOICE_EMAIL_KEY, invoiceEmailContent } from '../utils/invoice-email-content'\nimport type { orderInvoicePdfFile } from './commerce-pdf'\nimport type { CommercePdfFile } from './pdf-response'\nimport { quoteBusinessName, quoteReplyTo } from './quote-email'\n\n/*==========================================\n * SENDING THE INVOICE EMAIL (AGL-4099). Loaded only by the console's Send\n * invoice (`POST commerce/order-invoice-send`), so the renderer, the PDF\n * writer and sharp stay out of every other request.\n *\n * One email, the `order-invoice` catalog key in the site's theme and its\n * header and footer (or the site's own design of it), with the invoice's PDF\n * attached, sent as the quote email is (`quote-email.ts`):\n *\n * - FROM the site's sending identity, under the site's name;\n * - REPLY-TO the site's contact email, else the person sending;\n * - IN THE CUSTOMER'S CONVERSATION: a quote's invoice replies into the\n * quote's conversation (`quote.emailThread`: its emails, or a request's\n * confirmation before them), and any other order's into its own\n * (`emailThread`), which its first invoice starts;\n * - METERED as a site's transactional email;\n * - REFUSED only for an address that bounced for good or reported mail as\n * spam: an invoice is transactional, as a receipt is.\n *\n * The route decides everything about the order (who may send, the link,\n * whether it can be paid); this module only says the email and sends it.\n *=========================================*/\n\n/** What the route hands over for one send. */\nexport interface InvoiceDeliveryInput {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n host: Record<string, unknown>\n store: Record<string, unknown> | null\n owner: { id?: string; org?: unknown } | null\n to: string\n /** The subject as typed; empty takes the default. */\n subject: string\n message: string\n /** The order's pay link, for an invoice still to be paid; null for a paid one. */\n payUrl: string | null\n /** The sending member's email: the Reply-To when the site has no contact email. */\n senderEmail: string | null\n atMs: number\n}\n\nexport type InvoiceDeliveryResult =\n | {\n sent: true\n messageId: string\n providerId: string | null\n subject: string\n replyTo: string | null\n thread: CommerceModel.QuoteEmailThread\n paid: boolean\n totalCents: number\n }\n | { sent: false; status: number; error: string }\n\n/** The calls the send makes, injectable for specs. */\nexport interface InvoiceMailerDeps {\n configured(): boolean\n sendingIdentity(hostId: string): Promise<SendingIdentityVerdict>\n render(hostId: string, key: string, tokens: Record<string, string>): Promise<RenderedHostEmail | null>\n /** The invoice's PDF; loads the PDF writer and sharp only here. */\n invoicePdf(input: Parameters<typeof orderInvoicePdfFile>[0]): Promise<CommercePdfFile>\n send(options: SendEmailOptions): Promise<SendEmailResult>\n meter(hostId: string): Promise<void>\n /** The bounce and complaint list only: an invoice is transactional. */\n suppression(email: string): Promise<'suppressed-platform' | null>\n}\n\nexport function defaultInvoiceMailerDeps(): InvoiceMailerDeps {\n const firestore = () => firebaseAdmin.app().firestore()\n return {\n configured: () => isEmailConfigured(),\n sendingIdentity: (hostId) => hostSendingIdentity(hostId),\n render: (hostId, key, tokens) => renderHostEmailWithTokens(firestore(), hostId, key, tokens),\n invoicePdf: async (input) => (await import('./commerce-pdf')).orderInvoicePdfFile(input),\n send: (options) => sendEmail(options),\n meter: async (hostId) => {\n await meterHostEmail(hostId)\n },\n suppression: (email) => transactionalAddressSuppression(email),\n }\n}\n\n/** What the console's Send invoice reaches: whether mail can go, whether this address may be mailed, and the send. */\nexport interface InvoiceMailer {\n configured(): boolean\n suppression(email: string): Promise<'suppressed-platform' | null>\n deliver(input: InvoiceDeliveryInput): Promise<InvoiceDeliveryResult>\n}\n\n/** A refused send in the words the console shows. */\nfunction refusalOf(result: Extract<SendEmailResult, { sent: false }>): { status: number; error: string } {\n switch (result.reason) {\n case 'unconfigured':\n return { status: 503, error: 'Email isn’t set up here, so the invoice wasn’t sent.' }\n case 'rate-limited':\n return { status: 429, error: 'Too many emails are going out right now. Try again in a minute.' }\n case 'suppressed':\n case 'undeliverable':\n return { status: 409, error: 'This address can’t receive email, so the invoice wasn’t sent.' }\n case 'unverified-domain':\n return { status: 409, error: 'This site’s sending domain isn’t verified, so the invoice wasn’t sent. Check Email settings.' }\n case 'suspended':\n return { status: 423, error: 'This site can’t send email right now, so the invoice wasn’t sent.' }\n case 'held-for-review':\n return { status: 409, error: `The email was held for review, so it hasn’t gone out yet.${result.detail ? ` ${result.detail}` : ''}` }\n default:\n return { status: 502, error: 'The invoice email could not be sent. Try again.' }\n }\n}\n\n/** The invoice email, said and sent. */\nexport function invoiceMailer(deps: InvoiceMailerDeps = defaultInvoiceMailerDeps()): InvoiceMailer {\n return {\n configured: () => deps.configured(),\n suppression: (email) => deps.suppression(email),\n deliver: async (input) => {\n const { hostId, orderId, order, host } = input\n const businessName = quoteBusinessName(host)\n const subject = input.subject || CommerceModel.invoiceEmailDefaultSubject(order, businessName, orderId)\n const identity = await deps.sendingIdentity(hostId)\n const org = (input.owner?.org ?? null) as { timeZone?: string } | null\n const content = invoiceEmailContent({\n order,\n orderId,\n businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n subject,\n message: input.message,\n payUrl: input.payUrl,\n timeZone: resolveSiteTimeZone(org, host as { timeZone?: string }),\n })\n\n // The PDF is what the email says is attached; without it nothing goes.\n let pdf: CommercePdfFile\n try {\n pdf = await deps.invoicePdf({\n hostId,\n orderId,\n order,\n host,\n store: input.store,\n owner: input.owner,\n payUrl: content.paid ? null : input.payUrl,\n })\n } catch (error) {\n console.error('[commerce/invoice-email] the PDF could not be made', { hostId, orderId, error })\n return { sent: false, status: 500, error: 'The invoice’s PDF could not be made, so nothing was sent. Try again.' }\n }\n\n const rendered = await deps.render(hostId, INVOICE_EMAIL_KEY, content.tokens)\n const thread = readEmailThread(CommerceModel.invoiceEmailThread(order))\n const siteHost = String(host['cname'] ?? '').trim() || null\n const messageId = mintEmailMessageId([identity?.domain, identity?.from, siteHost], {\n label: 'invoice',\n atMs: input.atMs,\n })\n const replyTo = quoteReplyTo(host, input.senderEmail)\n\n const result = await deps.send({\n to: input.to,\n // The subject as sent, whatever a design's own says: it is what keeps\n // the conversation together, and it was typed for this send.\n subject,\n text: rendered?.text || content.text,\n ...(rendered?.html ? { html: rendered.html } : {}),\n headers: nextThreadHeaders(thread, messageId),\n ...(replyTo ? { replyTo } : {}),\n fromName: resolveBrandingProfile(input.owner?.org as never).fromName,\n sendingIdentity: identity,\n audience: 'tenant',\n context: 'invoice',\n attachments: [\n {\n filename: pdf.filename,\n contentType: 'application/pdf',\n content: Buffer.from(pdf.bytes).toString('base64'),\n },\n ],\n })\n if (!result.sent) return { sent: false, ...refusalOf(result as Extract<SendEmailResult, { sent: false }>) }\n // Cost meter (AGL-1438), as every transactional site email.\n await deps.meter(hostId).catch((error) => console.error('[commerce/invoice-email] not metered', error))\n return {\n sent: true,\n messageId,\n providerId: (result as Extract<SendEmailResult, { sent: true }>).id ?? null,\n subject,\n replyTo,\n thread: emailThreadAfterSend(thread, { messageId, subject }),\n paid: content.paid,\n totalCents: content.totalCents,\n }\n },\n }\n}\n"],"names":["resolveSiteTimeZone","resolveBrandingProfile","emailThreadAfterSend","isEmailConfigured","mintEmailMessageId","nextThreadHeaders","readEmailThread","sendEmail","firebaseAdmin","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","transactionalAddressSuppression","CommerceModel","INVOICE_EMAIL_KEY","invoiceEmailContent","quoteBusinessName","quoteReplyTo","defaultInvoiceMailerDeps","firestore","app","configured","sendingIdentity","hostId","render","key","tokens","invoicePdf","input","orderInvoicePdfFile","send","options","meter","suppression","email","refusalOf","result","reason","status","error","detail","invoiceMailer","deps","deliver","host","orderId","order","businessName","subject","invoiceEmailDefaultSubject","identity","org","owner","content","currency","String","store","message","payUrl","timeZone","pdf","paid","console","sent","rendered","thread","invoiceEmailThread","siteHost","trim","messageId","domain","from","label","atMs","replyTo","senderEmail","to","text","html","headers","fromName","audience","context","attachments","filename","contentType","Buffer","bytes","toString","catch","providerId","id","totalCents"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SACEC,oBAAoB,EACpBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,EACjBC,eAAe,EACfC,SAAS,QAKJ,2BAA0B;AACjC,SACEC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,EACzBC,+BAA+B,QAC1B,2BAA0B;AACjC,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,iBAAiB,EAAEC,mBAAmB,QAAQ,oCAAgC;AAGvF,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,mBAAe;AAsE/D,OAAO,SAASC;IACd,MAAMC,YAAY,IAAMX,cAAcY,GAAG,GAAGD,SAAS;IACrD,OAAO;QACLE,YAAY,IAAMlB;QAClBmB,iBAAiB,CAACC,SAAWd,oBAAoBc;QACjDC,QAAQ,CAACD,QAAQE,KAAKC,SAAWf,0BAA0BQ,aAAaI,QAAQE,KAAKC;QACrFC,YAAY,OAAOC,QAAU,AAAC,CAAA,MAAM,MAAM,CAAC,oBAAgB,EAAGC,mBAAmB,CAACD;QAClFE,MAAM,CAACC,UAAYxB,UAAUwB;QAC7BC,OAAO,OAAOT;YACZ,MAAMb,eAAea;QACvB;QACAU,aAAa,CAACC,QAAUtB,gCAAgCsB;IAC1D;AACF;AASA,mDAAmD,GACnD,SAASC,UAAUC,MAAiD;IAClE,OAAQA,OAAOC,MAA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