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

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 (87) hide show
  1. package/README.md +2 -2
  2. package/package.json +13 -13
  3. package/src/lib/components/commerce-console-page.js +29 -2
  4. package/src/lib/components/commerce-console-page.js.map +1 -1
  5. package/src/lib/components/console/commerce-analytics-card.component.js +4 -2
  6. package/src/lib/components/console/commerce-analytics-card.component.js.map +1 -1
  7. package/src/lib/components/console/host-orders-card.component.js +5 -1
  8. package/src/lib/components/console/host-orders-card.component.js.map +1 -1
  9. package/src/lib/components/console/host-quotes-card.component.d.ts +34 -0
  10. package/src/lib/components/console/host-quotes-card.component.js +247 -0
  11. package/src/lib/components/console/host-quotes-card.component.js.map +1 -0
  12. package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js +33 -28
  13. package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js.map +1 -1
  14. package/src/lib/components/console/quote-editor-dialog.component.d.ts +45 -0
  15. package/src/lib/components/console/quote-editor-dialog.component.js +1266 -0
  16. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -0
  17. package/src/lib/components/console/quote-pay-link.component.d.ts +38 -0
  18. package/src/lib/components/console/quote-pay-link.component.js +213 -0
  19. package/src/lib/components/console/quote-pay-link.component.js.map +1 -0
  20. package/src/lib/components/console/quote-settings-card.component.d.ts +29 -0
  21. package/src/lib/components/console/quote-settings-card.component.js +121 -0
  22. package/src/lib/components/console/quote-settings-card.component.js.map +1 -0
  23. package/src/lib/components/console/tax-settings-card.component.js +4 -1
  24. package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
  25. package/src/lib/components/quote-page-body.d.ts +33 -0
  26. package/src/lib/components/quote-page-body.js +696 -0
  27. package/src/lib/components/quote-page-body.js.map +1 -0
  28. package/src/lib/components/quote-page.d.ts +29 -0
  29. package/src/lib/components/quote-page.js +96 -0
  30. package/src/lib/components/quote-page.js.map +1 -0
  31. package/src/lib/components/storefront-payment-element.d.ts +7 -1
  32. package/src/lib/components/storefront-payment-element.js +8 -3
  33. package/src/lib/components/storefront-payment-element.js.map +1 -1
  34. package/src/lib/constants/orders-list-query.js +6 -1
  35. package/src/lib/constants/orders-list-query.js.map +1 -1
  36. package/src/lib/constants/quote-page.d.ts +30 -0
  37. package/src/lib/constants/quote-page.js +35 -0
  38. package/src/lib/constants/quote-page.js.map +1 -0
  39. package/src/lib/model/commerce-orders.d.ts +25 -2
  40. package/src/lib/model/commerce-orders.js +10 -1
  41. package/src/lib/model/commerce-orders.js.map +1 -1
  42. package/src/lib/model/commerce-quote-pay.d.ts +229 -0
  43. package/src/lib/model/commerce-quote-pay.js +393 -0
  44. package/src/lib/model/commerce-quote-pay.js.map +1 -0
  45. package/src/lib/model/commerce-quotes.d.ts +279 -0
  46. package/src/lib/model/commerce-quotes.js +522 -0
  47. package/src/lib/model/commerce-quotes.js.map +1 -0
  48. package/src/lib/model/index.d.ts +2 -0
  49. package/src/lib/model/index.js +2 -0
  50. package/src/lib/model/index.js.map +1 -1
  51. package/src/lib/model/plugin-permissions.d.ts +1 -1
  52. package/src/lib/model/plugin-permissions.js +20 -0
  53. package/src/lib/model/plugin-permissions.js.map +1 -1
  54. package/src/lib/server/api-v1/orders-and-products.js +6 -2
  55. package/src/lib/server/api-v1/orders-and-products.js.map +1 -1
  56. package/src/lib/server/billing-webhook.js +127 -52
  57. package/src/lib/server/billing-webhook.js.map +1 -1
  58. package/src/lib/server/checkout-session-expiry.d.ts +36 -0
  59. package/src/lib/server/checkout-session-expiry.js +63 -0
  60. package/src/lib/server/checkout-session-expiry.js.map +1 -0
  61. package/src/lib/server/draft-order.js +16 -8
  62. package/src/lib/server/draft-order.js.map +1 -1
  63. package/src/lib/server/person-eraser.d.ts +7 -0
  64. package/src/lib/server/person-eraser.js +24 -2
  65. package/src/lib/server/person-eraser.js.map +1 -1
  66. package/src/lib/server/pos-return.js +3 -1
  67. package/src/lib/server/pos-return.js.map +1 -1
  68. package/src/lib/server/quote-link-token.d.ts +39 -0
  69. package/src/lib/server/quote-link-token.js +97 -0
  70. package/src/lib/server/quote-link-token.js.map +1 -0
  71. package/src/lib/server/quote-pay.d.ts +83 -0
  72. package/src/lib/server/quote-pay.js +606 -0
  73. package/src/lib/server/quote-pay.js.map +1 -0
  74. package/src/lib/server/quote.d.ts +49 -0
  75. package/src/lib/server/quote.js +513 -0
  76. package/src/lib/server/quote.js.map +1 -0
  77. package/src/lib/server/related.js +2 -0
  78. package/src/lib/server/related.js.map +1 -1
  79. package/src/lib/server/site-page-resolver.d.ts +2 -0
  80. package/src/lib/server/site-page-resolver.js +75 -0
  81. package/src/lib/server/site-page-resolver.js.map +1 -1
  82. package/src/lib/server.js +14 -0
  83. package/src/lib/server.js.map +1 -1
  84. package/src/lib/site.js +6 -0
  85. package/src/lib/site.js.map +1 -1
  86. package/src/lib/transfer/tracking.server.js +6 -0
  87. package/src/lib/transfer/tracking.server.js.map +1 -1
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * Closing a Checkout Session so it can no longer be paid, and saying what it
19
+ * was (AGL-4094).
20
+ *
21
+ * Stripe answers 200 to `expire` for a session that was open, and 400 for one
22
+ * that is not — already expired, or already PAID. Those two must not be read
23
+ * alike: a caller about to open a fresh session for the same quote has to
24
+ * know that the old one was paid a moment ago, or it hands the customer a
25
+ * second way to pay. So a refused expiry reads the session back and answers
26
+ * its status.
27
+ *
28
+ * - `expired`: it can no longer be paid (it was open and is now closed, or it
29
+ * had expired already).
30
+ * - `complete`: it was paid; the webhook has, or will, record it.
31
+ * - `missing`: Stripe does not know it (another mode's id, or never created).
32
+ * - `open`: it could not be closed and may still be paid. The caller treats
33
+ * this as a failure to retry, never as closed.
34
+ */
35
+ export type CheckoutSessionExpiry = 'expired' | 'complete' | 'missing' | 'open';
36
+ export declare function expireCheckoutSession(sessionId: string): Promise<CheckoutSessionExpiry>;
@@ -0,0 +1,63 @@
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
+ * Closing a Checkout Session so it can no longer be paid, and saying what it
18
+ * was (AGL-4094).
19
+ *
20
+ * Stripe answers 200 to `expire` for a session that was open, and 400 for one
21
+ * that is not — already expired, or already PAID. Those two must not be read
22
+ * alike: a caller about to open a fresh session for the same quote has to
23
+ * know that the old one was paid a moment ago, or it hands the customer a
24
+ * second way to pay. So a refused expiry reads the session back and answers
25
+ * its status.
26
+ *
27
+ * - `expired`: it can no longer be paid (it was open and is now closed, or it
28
+ * had expired already).
29
+ * - `complete`: it was paid; the webhook has, or will, record it.
30
+ * - `missing`: Stripe does not know it (another mode's id, or never created).
31
+ * - `open`: it could not be closed and may still be paid. The caller treats
32
+ * this as a failure to retry, never as closed.
33
+ */ const SESSION_ID = /^cs_(test|live)_[A-Za-z0-9]{8,255}$/;
34
+ export async function expireCheckoutSession(sessionId) {
35
+ var _process_env_STRIPE_SECRET_KEY;
36
+ if (!SESSION_ID.test(String(sessionId != null ? sessionId : ''))) return 'missing';
37
+ const secretKey = String((_process_env_STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY) != null ? _process_env_STRIPE_SECRET_KEY : '').trim();
38
+ if (!secretKey) return 'open';
39
+ const headers = {
40
+ Authorization: `Bearer ${secretKey}`,
41
+ 'Content-Type': 'application/x-www-form-urlencoded'
42
+ };
43
+ try {
44
+ const expired = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}/expire`, {
45
+ method: 'POST',
46
+ headers
47
+ });
48
+ if (expired.ok) return 'expired';
49
+ const read = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}`, {
50
+ headers
51
+ });
52
+ if (read.status === 404) return 'missing';
53
+ if (!read.ok) return 'open';
54
+ const session = await read.json().catch(()=>({}));
55
+ if (session.status === 'complete') return 'complete';
56
+ if (session.status === 'expired') return 'expired';
57
+ return 'open';
58
+ } catch (unused) {
59
+ return 'open';
60
+ }
61
+ }
62
+
63
+ //# sourceMappingURL=checkout-session-expiry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/checkout-session-expiry.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Closing a Checkout Session so it can no longer be paid, and saying what it\n * was (AGL-4094).\n *\n * Stripe answers 200 to `expire` for a session that was open, and 400 for one\n * that is not — already expired, or already PAID. Those two must not be read\n * alike: a caller about to open a fresh session for the same quote has to\n * know that the old one was paid a moment ago, or it hands the customer a\n * second way to pay. So a refused expiry reads the session back and answers\n * its status.\n *\n * - `expired`: it can no longer be paid (it was open and is now closed, or it\n * had expired already).\n * - `complete`: it was paid; the webhook has, or will, record it.\n * - `missing`: Stripe does not know it (another mode's id, or never created).\n * - `open`: it could not be closed and may still be paid. The caller treats\n * this as a failure to retry, never as closed.\n */\nexport type CheckoutSessionExpiry = 'expired' | 'complete' | 'missing' | 'open'\n\nconst SESSION_ID = /^cs_(test|live)_[A-Za-z0-9]{8,255}$/\n\nexport async function expireCheckoutSession(sessionId: string): Promise<CheckoutSessionExpiry> {\n if (!SESSION_ID.test(String(sessionId ?? ''))) return 'missing'\n const secretKey = String(process.env.STRIPE_SECRET_KEY ?? '').trim()\n if (!secretKey) return 'open'\n const headers = {\n Authorization: `Bearer ${secretKey}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n try {\n const expired = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}/expire`, {\n method: 'POST',\n headers,\n })\n if (expired.ok) return 'expired'\n const read = await fetch(`https://api.stripe.com/v1/checkout/sessions/${sessionId}`, { headers })\n if (read.status === 404) return 'missing'\n if (!read.ok) return 'open'\n const session = (await read.json().catch(() => ({}))) as { status?: string }\n if (session.status === 'complete') return 'complete'\n if (session.status === 'expired') return 'expired'\n return 'open'\n } catch {\n return 'open'\n }\n}\n"],"names":["SESSION_ID","expireCheckoutSession","sessionId","process","test","String","secretKey","env","STRIPE_SECRET_KEY","trim","headers","Authorization","expired","fetch","method","ok","read","status","session","json","catch"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;CAiBC,GAGD,MAAMA,aAAa;AAEnB,OAAO,eAAeC,sBAAsBC,SAAiB;QAElCC;IADzB,IAAI,CAACH,WAAWI,IAAI,CAACC,OAAOH,oBAAAA,YAAa,MAAM,OAAO;IACtD,MAAMI,YAAYD,QAAOF,iCAAAA,QAAQI,GAAG,CAACC,iBAAiB,YAA7BL,iCAAiC,IAAIM,IAAI;IAClE,IAAI,CAACH,WAAW,OAAO;IACvB,MAAMI,UAAU;QACdC,eAAe,CAAC,OAAO,EAAEL,WAAW;QACpC,gBAAgB;IAClB;IACA,IAAI;QACF,MAAMM,UAAU,MAAMC,MAAM,CAAC,4CAA4C,EAAEX,UAAU,OAAO,CAAC,EAAE;YAC7FY,QAAQ;YACRJ;QACF;QACA,IAAIE,QAAQG,EAAE,EAAE,OAAO;QACvB,MAAMC,OAAO,MAAMH,MAAM,CAAC,4CAA4C,EAAEX,WAAW,EAAE;YAAEQ;QAAQ;QAC/F,IAAIM,KAAKC,MAAM,KAAK,KAAK,OAAO;QAChC,IAAI,CAACD,KAAKD,EAAE,EAAE,OAAO;QACrB,MAAMG,UAAW,MAAMF,KAAKG,IAAI,GAAGC,KAAK,CAAC,IAAO,CAAA,CAAC,CAAA;QACjD,IAAIF,QAAQD,MAAM,KAAK,YAAY,OAAO;QAC1C,IAAIC,QAAQD,MAAM,KAAK,WAAW,OAAO;QACzC,OAAO;IACT,EAAE,eAAM;QACN,OAAO;IACT;AACF"}
@@ -23,6 +23,7 @@ import { merchantAccountIsReady } from "@aglyn/tenant-data-admin/server/payment-
23
23
  import { checkoutSessionCardAuthenticationParams } from "@aglyn/tenant-data-admin/server/stripe-card-authentication";
24
24
  import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
25
25
  import { resolveManualTaxRateId } from "./manual-tax-rate.js";
26
+ import { orderStatusUrl } from "./order-status-token.js";
26
27
  import { holdPromotionSlot, promotionHoldKey } from "./promotion-hold.js";
27
28
  import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
28
29
  /**
@@ -158,12 +159,14 @@ import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
158
159
  error: 'Payments are not set up yet'
159
160
  });
160
161
  }
161
- // Stripe returns the merchant to the console Products page. This was
162
- // `/{hostDocId}/products`, the pre-AGL-621/622 shape, so paying (or
163
- // cancelling) a draft order landed on a 404 (AGL-685). Console products
164
- // is the plugin route keyed by org slug + host SUBDOMAIN; server code
165
- // cannot call useConsoleHostRoute, so resolve them here. Without both,
166
- // fall back to the origin root rather than a fabricated dead path.
162
+ // Where Stripe returns the BUYER is the business's own site (AGL-4094):
163
+ // the order's status page after paying, the site's home after backing
164
+ // out — see the params below. The console Products page is only the
165
+ // fallback for a site with no public address or no signing secret, which
166
+ // no published site lacks. Console products is the plugin route keyed by
167
+ // org slug + host SUBDOMAIN; server code cannot call
168
+ // useConsoleHostRoute, so resolve them here. Without both, fall back to
169
+ // the origin root rather than a fabricated dead path.
167
170
  const consoleSubdomain = (await firestore.collection('hostIndex').doc(hostId).get()).get('subdomain');
168
171
  const consoleOrgSlug = ownerOrg == null ? void 0 : (_ownerOrg_org1 = ownerOrg.org) == null ? void 0 : _ownerOrg_org1.slug;
169
172
  // The console's own host, as the POS door reads it — never the `Origin`
@@ -625,6 +628,11 @@ import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
625
628
  });
626
629
  }
627
630
  }
631
+ // The buyer's way back, on the business's site: the order's status page
632
+ // (which reads the paid state from the server) and the site's home.
633
+ const siteData = hostSnapshot.data();
634
+ const buyerStatusUrl = orderStatusUrl(siteData, hostId, orderRef.id);
635
+ const buyerSiteUrl = buyerStatusUrl ? `${new URL(buyerStatusUrl).origin}/` : '';
628
636
  const params = new URLSearchParams(_extends({
629
637
  mode: 'payment'
630
638
  }, checkoutSessionCardAuthenticationParams('payment'), useStripeTax ? {
@@ -648,8 +656,8 @@ import { buildRoute, claimAttempt, Route } from "@aglyn/aglyn/server";
648
656
  }), email ? {
649
657
  customer_email: email
650
658
  } : {}, {
651
- success_url: `${consoleProductsUrl}?draft=paid`,
652
- cancel_url: `${consoleProductsUrl}?draft=canceled`,
659
+ success_url: buyerStatusUrl != null ? buyerStatusUrl : `${consoleProductsUrl}?draft=paid`,
660
+ cancel_url: buyerSiteUrl || `${consoleProductsUrl}?draft=canceled`,
653
661
  'metadata[type]': 'commerce-draft',
654
662
  'metadata[hostId]': hostId,
655
663
  'metadata[orderId]': orderRef.id,
@@ -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 {\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 // Stripe returns the merchant to the console Products page. This was\n // `/{hostDocId}/products`, the pre-AGL-621/622 shape, so paying (or\n // cancelling) a draft order landed on a 404 (AGL-685). Console products\n // is the plugin route keyed by org slug + host SUBDOMAIN; server code\n // cannot call useConsoleHostRoute, so resolve them here. Without both,\n // fall back to 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 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: `${consoleProductsUrl}?draft=paid`,\n cancel_url: `${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","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","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,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,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,IAAI,CAACC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAOR,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA+B;IACtE;IACA,MAAMI,gBAAgBC,QAAOX,6BAAAA,IAAIY,OAAO,CAACF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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 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;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C,GAAG,EAAE;YAChCC,QAAQ7O,KAAK,CAAC,4BAA4B2O,QAAQ3O,KAAK;YACvD,MAAMqL,SAAS2B,MAAM,GAAGC,KAAK,CAAC,IAAMtM;YACpC,wEAAwE;YACxE,kEAAkE;YAClE,6DAA6D;YAC7D,MAAMmB;YACN,MAAMH,MAAMK,OAAO;YACnB,OAAOrC,IAAIG,MAAM,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"}
@@ -45,6 +45,13 @@ export interface CommercePersonEraserDeps {
45
45
  /** The patch that takes the buyer off one order, as it stands. */
46
46
  export declare function erasedOrderPatch(data: FirebaseFirestore.DocumentData | undefined, now: number): Record<string, unknown>;
47
47
  /** The patch that takes the customer off one check-in at the window (AGL-4043). */
48
+ /**
49
+ * A quote's customer, erased (AGL-4093). An unpaid quote keeps its customer
50
+ * in its `quote` section rather than on the order's own fields, so it is
51
+ * found by `quote.customer.emailLower` and loses the person and both
52
+ * addresses; its lines and totals stay, as an order's do.
53
+ */
54
+ export declare function erasedQuotePatch(data: FirebaseFirestore.DocumentData | undefined, now: number): Record<string, unknown>;
48
55
  export declare function erasedCheckInPatch(data: FirebaseFirestore.DocumentData | undefined, now: number): Record<string, unknown>;
49
56
  export declare function createCommercePersonEraser(deps: CommercePersonEraserDeps): PluginPersonEraser;
50
57
  /** The eraser over the platform's own Firestore, as the declarations register it. */
@@ -18,6 +18,7 @@ import { updateWhereEquals } from "@aglyn/tenant-data-admin/server/paged-sweeps"
18
18
  import { FieldValue } from "firebase-admin/firestore";
19
19
  import { firebaseAdmin } from "@aglyn/tenant-data-admin/server/firebase-admin";
20
20
  const LABEL = 'commerce person eraser';
21
+ /** Where a quote keeps its customer's address (`commerce-quotes.ts`). */ const QUOTE_EMAIL_FIELD = 'quote.customer.emailLower';
21
22
  /** The patch that takes the buyer off one order, as it stands. */ export function erasedOrderPatch(data, now) {
22
23
  const addressTokens = new Set(Array.isArray(data == null ? void 0 : data['customerEmailTokens']) ? data['customerEmailTokens'] : []);
23
24
  return _extends({
@@ -32,7 +33,24 @@ const LABEL = 'commerce person eraser';
32
33
  searchTokens: data['searchTokens'].filter((token)=>!addressTokens.has(token))
33
34
  } : {});
34
35
  }
35
- /** The patch that takes the customer off one check-in at the window (AGL-4043). */ export function erasedCheckInPatch(data, now) {
36
+ /** The patch that takes the customer off one check-in at the window (AGL-4043). */ /**
37
+ * A quote's customer, erased (AGL-4093). An unpaid quote keeps its customer
38
+ * in its `quote` section rather than on the order's own fields, so it is
39
+ * found by `quote.customer.emailLower` and loses the person and both
40
+ * addresses; its lines and totals stay, as an order's do.
41
+ */ export function erasedQuotePatch(data, now) {
42
+ var _ref;
43
+ const quote = (_ref = data == null ? void 0 : data['quote']) != null ? _ref : {};
44
+ return {
45
+ quote: _extends({}, quote, {
46
+ customer: {},
47
+ billTo: null,
48
+ shipTo: null
49
+ }),
50
+ customerErasedAtMs: now
51
+ };
52
+ }
53
+ export function erasedCheckInPatch(data, now) {
36
54
  var _ref, _ref1;
37
55
  // One key per order or stay, so the people one order brought still read
38
56
  // as one party, and as nobody's name.
@@ -54,6 +72,7 @@ export function createCommercePersonEraser(deps) {
54
72
  const hosts = await db.collection('hosts').where('orgId', '==', orgId).get();
55
73
  let orders = 0;
56
74
  let checkIns = 0;
75
+ let quotes = 0;
57
76
  const emailLower = email.trim().toLowerCase();
58
77
  for (const host of hosts.docs){
59
78
  const placed = host.ref.collection('orders');
@@ -61,14 +80,17 @@ export function createCommercePersonEraser(deps) {
61
80
  if (dryRun) {
62
81
  orders += (await placed.where('customerEmail', '==', email).get()).size;
63
82
  checkIns += (await checked.where('customerEmailLower', '==', emailLower).get()).size;
83
+ quotes += (await placed.where(QUOTE_EMAIL_FIELD, '==', emailLower).get()).size;
64
84
  continue;
65
85
  }
66
86
  checkIns += await updateWhereEquals(db, checked, 'customerEmailLower', emailLower, (data)=>erasedCheckInPatch(data, atMs), LABEL);
67
87
  orders += await updateWhereEquals(db, placed, 'customerEmail', email, (data)=>erasedOrderPatch(data, atMs), LABEL);
88
+ quotes += await updateWhereEquals(db, placed, QUOTE_EMAIL_FIELD, emailLower, (data)=>erasedQuotePatch(data, atMs), LABEL);
68
89
  }
69
90
  return {
70
91
  orders,
71
- checkIns
92
+ checkIns,
93
+ quotes
72
94
  };
73
95
  };
74
96
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/person-eraser.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 type {\n PluginPersonEraser,\n PluginPersonErasureReport,\n} from '@aglyn/aglyn/plugin-manager/plugin-person-erasure'\nimport { updateWhereEquals } from '@aglyn/tenant-data-admin/server/paged-sweeps'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\n\n/**\n * COMMERCE'S SHARE OF A PERSON ERASURE (AGL-2623, AGL-3080).\n *\n * An order is the merchant's record of a sale: the amounts, the line items\n * and the tax are theirs to keep and the law expects them kept. So the person\n * is taken OFF every order they placed on a site of the workspace — name,\n * email, both addresses — and a stamp says when; the order itself stays.\n *\n * The address also lives in what the orders list queries by (AGL-3321): its\n * lower-cased key, its search prefixes, and the quick search's token array,\n * which holds those prefixes beside the order number's and the item names'.\n * The first two go; the prefixes are taken back out of the third. A prefix\n * the number or an item name shares with the address goes with it — a search\n * for that prefix misses this order until the orders backfill restamps it —\n * and nothing left on the order answers to the address.\n *\n * A check-in at the window (AGL-4043) copies the buyer's name, address and\n * phone, so the same person is taken off each of theirs, by the stored\n * lower-cased address; the check-in itself — who was due, who checked them\n * in, the wristband — stays, as the order does.\n *\n * A DRY RUN counts the orders and check-ins and writes nothing.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface CommercePersonEraserDeps {\n firestore(): Firestore\n}\n\nconst LABEL = 'commerce person eraser'\n\n/** The patch that takes the buyer off one order, as it stands. */\nexport function erasedOrderPatch(\n data: FirebaseFirestore.DocumentData | undefined,\n now: number,\n): Record<string, unknown> {\n const addressTokens = new Set(\n Array.isArray(data?.['customerEmailTokens']) ? data['customerEmailTokens'] : [],\n )\n return {\n customerEmail: null,\n customerName: null,\n shippingAddress: FieldValue.delete(),\n billingAddress: FieldValue.delete(),\n customerErasedAtMs: now,\n customerEmailLower: null,\n customerEmailTokens: [],\n ...(Array.isArray(data?.['searchTokens'])\n ? {\n searchTokens: (data['searchTokens'] as unknown[]).filter(\n (token) => !addressTokens.has(token),\n ),\n }\n : {}),\n }\n}\n\n/** The patch that takes the customer off one check-in at the window (AGL-4043). */\nexport function erasedCheckInPatch(\n data: FirebaseFirestore.DocumentData | undefined,\n now: number,\n): Record<string, unknown> {\n // One key per order or stay, so the people one order brought still read\n // as one party, and as nobody's name.\n const source = String(data?.['orderId'] ?? data?.['reservationId'] ?? '')\n return {\n customerKey: `erased:${source}`,\n customerName: null,\n customerEmail: null,\n customerEmailLower: null,\n customerPhone: null,\n contactId: null,\n searchTokens: [],\n customerErasedAtMs: now,\n }\n}\n\nexport function createCommercePersonEraser(deps: CommercePersonEraserDeps): PluginPersonEraser {\n return async ({ orgId, email, dryRun, atMs }): Promise<PluginPersonErasureReport> => {\n const db = deps.firestore()\n const hosts = await db.collection('hosts').where('orgId', '==', orgId).get()\n let orders = 0\n let checkIns = 0\n const emailLower = email.trim().toLowerCase()\n for (const host of hosts.docs) {\n const placed = host.ref.collection('orders')\n const checked = host.ref.collection('checkIns')\n if (dryRun) {\n orders += (await placed.where('customerEmail', '==', email).get()).size\n checkIns += (await checked.where('customerEmailLower', '==', emailLower).get()).size\n continue\n }\n checkIns += await updateWhereEquals(\n db,\n checked,\n 'customerEmailLower',\n emailLower,\n (data) => erasedCheckInPatch(data, atMs),\n LABEL,\n )\n orders += await updateWhereEquals(\n db,\n placed,\n 'customerEmail',\n email,\n (data) => erasedOrderPatch(data, atMs),\n LABEL,\n )\n }\n return { orders, checkIns }\n }\n}\n\n/** The eraser over the platform's own Firestore, as the declarations register it. */\nexport const commercePersonEraser: PluginPersonEraser = (request) =>\n createCommercePersonEraser({ firestore: () => firebaseAdmin.app().firestore() })(request)\n"],"names":["updateWhereEquals","FieldValue","firebaseAdmin","LABEL","erasedOrderPatch","data","now","addressTokens","Set","Array","isArray","customerEmail","customerName","shippingAddress","delete","billingAddress","customerErasedAtMs","customerEmailLower","customerEmailTokens","searchTokens","filter","token","has","erasedCheckInPatch","source","String","customerKey","customerPhone","contactId","createCommercePersonEraser","deps","orgId","email","dryRun","atMs","db","firestore","hosts","collection","where","get","orders","checkIns","emailLower","trim","toLowerCase","host","docs","placed","ref","checked","size","commercePersonEraser","request","app"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAMD,SAASA,iBAAiB,QAAQ,+CAA8C;AAChF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,iDAAgD;AAgC9E,MAAMC,QAAQ;AAEd,gEAAgE,GAChE,OAAO,SAASC,iBACdC,IAAgD,EAChDC,GAAW;IAEX,MAAMC,gBAAgB,IAAIC,IACxBC,MAAMC,OAAO,CAACL,wBAAAA,IAAM,CAAC,sBAAsB,IAAIA,IAAI,CAAC,sBAAsB,GAAG,EAAE;IAEjF,OAAO;QACLM,eAAe;QACfC,cAAc;QACdC,iBAAiBZ,WAAWa,MAAM;QAClCC,gBAAgBd,WAAWa,MAAM;QACjCE,oBAAoBV;QACpBW,oBAAoB;QACpBC,qBAAqB,EAAE;OACnBT,MAAMC,OAAO,CAACL,wBAAAA,IAAM,CAAC,eAAe,IACpC;QACEc,cAAc,AAACd,IAAI,CAAC,eAAe,CAAee,MAAM,CACtD,CAACC,QAAU,CAACd,cAAce,GAAG,CAACD;IAElC,IACA,CAAC;AAET;AAEA,iFAAiF,GACjF,OAAO,SAASE,mBACdlB,IAAgD,EAChDC,GAAW;QAIWD;IAFtB,wEAAwE;IACxE,sCAAsC;IACtC,MAAMmB,SAASC,QAAOpB,gBAAAA,wBAAAA,IAAM,CAAC,UAAU,oBAAIA,wBAAAA,IAAM,CAAC,gBAAgB,YAA5CA,OAAgD;IACtE,OAAO;QACLqB,aAAa,CAAC,OAAO,EAAEF,QAAQ;QAC/BZ,cAAc;QACdD,eAAe;QACfM,oBAAoB;QACpBU,eAAe;QACfC,WAAW;QACXT,cAAc,EAAE;QAChBH,oBAAoBV;IACtB;AACF;AAEA,OAAO,SAASuB,2BAA2BC,IAA8B;IACvE,OAAO,OAAO,EAAEC,KAAK,EAAEC,KAAK,EAAEC,MAAM,EAAEC,IAAI,EAAE;QAC1C,MAAMC,KAAKL,KAAKM,SAAS;QACzB,MAAMC,QAAQ,MAAMF,GAAGG,UAAU,CAAC,SAASC,KAAK,CAAC,SAAS,MAAMR,OAAOS,GAAG;QAC1E,IAAIC,SAAS;QACb,IAAIC,WAAW;QACf,MAAMC,aAAaX,MAAMY,IAAI,GAAGC,WAAW;QAC3C,KAAK,MAAMC,QAAQT,MAAMU,IAAI,CAAE;YAC7B,MAAMC,SAASF,KAAKG,GAAG,CAACX,UAAU,CAAC;YACnC,MAAMY,UAAUJ,KAAKG,GAAG,CAACX,UAAU,CAAC;YACpC,IAAIL,QAAQ;gBACVQ,UAAU,AAAC,CAAA,MAAMO,OAAOT,KAAK,CAAC,iBAAiB,MAAMP,OAAOQ,GAAG,EAAC,EAAGW,IAAI;gBACvET,YAAY,AAAC,CAAA,MAAMQ,QAAQX,KAAK,CAAC,sBAAsB,MAAMI,YAAYH,GAAG,EAAC,EAAGW,IAAI;gBACpF;YACF;YACAT,YAAY,MAAM1C,kBAChBmC,IACAe,SACA,sBACAP,YACA,CAACtC,OAASkB,mBAAmBlB,MAAM6B,OACnC/B;YAEFsC,UAAU,MAAMzC,kBACdmC,IACAa,QACA,iBACAhB,OACA,CAAC3B,OAASD,iBAAiBC,MAAM6B,OACjC/B;QAEJ;QACA,OAAO;YAAEsC;YAAQC;QAAS;IAC5B;AACF;AAEA,mFAAmF,GACnF,OAAO,MAAMU,uBAA2C,CAACC,UACvDxB,2BAA2B;QAAEO,WAAW,IAAMlC,cAAcoD,GAAG,GAAGlB,SAAS;IAAG,GAAGiB,SAAQ"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/person-eraser.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 type {\n PluginPersonEraser,\n PluginPersonErasureReport,\n} from '@aglyn/aglyn/plugin-manager/plugin-person-erasure'\nimport { updateWhereEquals } from '@aglyn/tenant-data-admin/server/paged-sweeps'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\n\n/**\n * COMMERCE'S SHARE OF A PERSON ERASURE (AGL-2623, AGL-3080).\n *\n * An order is the merchant's record of a sale: the amounts, the line items\n * and the tax are theirs to keep and the law expects them kept. So the person\n * is taken OFF every order they placed on a site of the workspace — name,\n * email, both addresses — and a stamp says when; the order itself stays.\n *\n * The address also lives in what the orders list queries by (AGL-3321): its\n * lower-cased key, its search prefixes, and the quick search's token array,\n * which holds those prefixes beside the order number's and the item names'.\n * The first two go; the prefixes are taken back out of the third. A prefix\n * the number or an item name shares with the address goes with it — a search\n * for that prefix misses this order until the orders backfill restamps it —\n * and nothing left on the order answers to the address.\n *\n * A check-in at the window (AGL-4043) copies the buyer's name, address and\n * phone, so the same person is taken off each of theirs, by the stored\n * lower-cased address; the check-in itself — who was due, who checked them\n * in, the wristband — stays, as the order does.\n *\n * A DRY RUN counts the orders and check-ins and writes nothing.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\nexport interface CommercePersonEraserDeps {\n firestore(): Firestore\n}\n\nconst LABEL = 'commerce person eraser'\n\n/** Where a quote keeps its customer's address (`commerce-quotes.ts`). */\nconst QUOTE_EMAIL_FIELD = 'quote.customer.emailLower'\n\n/** The patch that takes the buyer off one order, as it stands. */\nexport function erasedOrderPatch(\n data: FirebaseFirestore.DocumentData | undefined,\n now: number,\n): Record<string, unknown> {\n const addressTokens = new Set(\n Array.isArray(data?.['customerEmailTokens']) ? data['customerEmailTokens'] : [],\n )\n return {\n customerEmail: null,\n customerName: null,\n shippingAddress: FieldValue.delete(),\n billingAddress: FieldValue.delete(),\n customerErasedAtMs: now,\n customerEmailLower: null,\n customerEmailTokens: [],\n ...(Array.isArray(data?.['searchTokens'])\n ? {\n searchTokens: (data['searchTokens'] as unknown[]).filter(\n (token) => !addressTokens.has(token),\n ),\n }\n : {}),\n }\n}\n\n/** The patch that takes the customer off one check-in at the window (AGL-4043). */\n/**\n * A quote's customer, erased (AGL-4093). An unpaid quote keeps its customer\n * in its `quote` section rather than on the order's own fields, so it is\n * found by `quote.customer.emailLower` and loses the person and both\n * addresses; its lines and totals stay, as an order's do.\n */\nexport function erasedQuotePatch(\n data: FirebaseFirestore.DocumentData | undefined,\n now: number,\n): Record<string, unknown> {\n const quote = (data?.['quote'] ?? {}) as Record<string, unknown>\n return {\n quote: { ...quote, customer: {}, billTo: null, shipTo: null },\n customerErasedAtMs: now,\n }\n}\n\nexport function erasedCheckInPatch(\n data: FirebaseFirestore.DocumentData | undefined,\n now: number,\n): Record<string, unknown> {\n // One key per order or stay, so the people one order brought still read\n // as one party, and as nobody's name.\n const source = String(data?.['orderId'] ?? data?.['reservationId'] ?? '')\n return {\n customerKey: `erased:${source}`,\n customerName: null,\n customerEmail: null,\n customerEmailLower: null,\n customerPhone: null,\n contactId: null,\n searchTokens: [],\n customerErasedAtMs: now,\n }\n}\n\nexport function createCommercePersonEraser(deps: CommercePersonEraserDeps): PluginPersonEraser {\n return async ({ orgId, email, dryRun, atMs }): Promise<PluginPersonErasureReport> => {\n const db = deps.firestore()\n const hosts = await db.collection('hosts').where('orgId', '==', orgId).get()\n let orders = 0\n let checkIns = 0\n let quotes = 0\n const emailLower = email.trim().toLowerCase()\n for (const host of hosts.docs) {\n const placed = host.ref.collection('orders')\n const checked = host.ref.collection('checkIns')\n if (dryRun) {\n orders += (await placed.where('customerEmail', '==', email).get()).size\n checkIns += (await checked.where('customerEmailLower', '==', emailLower).get()).size\n quotes += (await placed.where(QUOTE_EMAIL_FIELD, '==', emailLower).get()).size\n continue\n }\n checkIns += await updateWhereEquals(\n db,\n checked,\n 'customerEmailLower',\n emailLower,\n (data) => erasedCheckInPatch(data, atMs),\n LABEL,\n )\n orders += await updateWhereEquals(\n db,\n placed,\n 'customerEmail',\n email,\n (data) => erasedOrderPatch(data, atMs),\n LABEL,\n )\n quotes += await updateWhereEquals(\n db,\n placed,\n QUOTE_EMAIL_FIELD,\n emailLower,\n (data) => erasedQuotePatch(data, atMs),\n LABEL,\n )\n }\n return { orders, checkIns, quotes }\n }\n}\n\n/** The eraser over the platform's own Firestore, as the declarations register it. */\nexport const commercePersonEraser: PluginPersonEraser = (request) =>\n createCommercePersonEraser({ firestore: () => firebaseAdmin.app().firestore() })(request)\n"],"names":["updateWhereEquals","FieldValue","firebaseAdmin","LABEL","QUOTE_EMAIL_FIELD","erasedOrderPatch","data","now","addressTokens","Set","Array","isArray","customerEmail","customerName","shippingAddress","delete","billingAddress","customerErasedAtMs","customerEmailLower","customerEmailTokens","searchTokens","filter","token","has","erasedQuotePatch","quote","customer","billTo","shipTo","erasedCheckInPatch","source","String","customerKey","customerPhone","contactId","createCommercePersonEraser","deps","orgId","email","dryRun","atMs","db","firestore","hosts","collection","where","get","orders","checkIns","quotes","emailLower","trim","toLowerCase","host","docs","placed","ref","checked","size","commercePersonEraser","request","app"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAMD,SAASA,iBAAiB,QAAQ,+CAA8C;AAChF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAa,QAAQ,iDAAgD;AAgC9E,MAAMC,QAAQ;AAEd,uEAAuE,GACvE,MAAMC,oBAAoB;AAE1B,gEAAgE,GAChE,OAAO,SAASC,iBACdC,IAAgD,EAChDC,GAAW;IAEX,MAAMC,gBAAgB,IAAIC,IACxBC,MAAMC,OAAO,CAACL,wBAAAA,IAAM,CAAC,sBAAsB,IAAIA,IAAI,CAAC,sBAAsB,GAAG,EAAE;IAEjF,OAA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