@aglyn/plugins-commerce 1.31.0 → 1.33.0

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 (123) hide show
  1. package/README.md +4 -0
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +35 -15
  4. package/src/lib/components/cart.js.map +1 -1
  5. package/src/lib/components/commerce-console-page.js +6 -0
  6. package/src/lib/components/commerce-console-page.js.map +1 -1
  7. package/src/lib/components/console/currencies-card.component.d.ts +21 -0
  8. package/src/lib/components/console/currencies-card.component.js +408 -0
  9. package/src/lib/components/console/currencies-card.component.js.map +1 -0
  10. package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
  11. package/src/lib/components/console/product-add-ons-fields.component.js +74 -2
  12. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  13. package/src/lib/components/console/product-editor-dialog.component.js +42 -1
  14. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  15. package/src/lib/components/console/product-fixed-prices-fields.component.d.ts +25 -0
  16. package/src/lib/components/console/product-fixed-prices-fields.component.js +112 -0
  17. package/src/lib/components/console/product-fixed-prices-fields.component.js.map +1 -0
  18. package/src/lib/components/console/reservations-card.component.js +32 -15
  19. package/src/lib/components/console/reservations-card.component.js.map +1 -1
  20. package/src/lib/components/console/shipping-settings-card.component.js +337 -10
  21. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  22. package/src/lib/components/console/store-settings-card.component.js +1 -1
  23. package/src/lib/components/console/store-settings-card.component.js.map +1 -1
  24. package/src/lib/components/console/use-currency-setup.d.ts +20 -0
  25. package/src/lib/components/console/use-currency-setup.js +61 -0
  26. package/src/lib/components/console/use-currency-setup.js.map +1 -0
  27. package/src/lib/components/currency-selector.d.ts +36 -0
  28. package/src/lib/components/currency-selector.js +157 -0
  29. package/src/lib/components/currency-selector.js.map +1 -0
  30. package/src/lib/components/product-add-ons.d.ts +9 -1
  31. package/src/lib/components/product-add-ons.js +8 -4
  32. package/src/lib/components/product-add-ons.js.map +1 -1
  33. package/src/lib/components/product-choice-cards.d.ts +13 -1
  34. package/src/lib/components/product-choice-cards.js +5 -4
  35. package/src/lib/components/product-choice-cards.js.map +1 -1
  36. package/src/lib/components/product-detail.d.ts +8 -0
  37. package/src/lib/components/product-detail.js +38 -11
  38. package/src/lib/components/product-detail.js.map +1 -1
  39. package/src/lib/components/product-grid.d.ts +2 -0
  40. package/src/lib/components/product-grid.js +22 -9
  41. package/src/lib/components/product-grid.js.map +1 -1
  42. package/src/lib/components/related-products.js +6 -2
  43. package/src/lib/components/related-products.js.map +1 -1
  44. package/src/lib/components/shopper-currency.d.ts +108 -0
  45. package/src/lib/components/shopper-currency.js +262 -0
  46. package/src/lib/components/shopper-currency.js.map +1 -0
  47. package/src/lib/components/wishlist.js +7 -1
  48. package/src/lib/components/wishlist.js.map +1 -1
  49. package/src/lib/declarations.server.js +39 -0
  50. package/src/lib/declarations.server.js.map +1 -1
  51. package/src/lib/model/commerce-currency-setup.d.ts +79 -0
  52. package/src/lib/model/commerce-currency-setup.js +124 -0
  53. package/src/lib/model/commerce-currency-setup.js.map +1 -0
  54. package/src/lib/model/commerce-currency.d.ts +215 -0
  55. package/src/lib/model/commerce-currency.js +511 -0
  56. package/src/lib/model/commerce-currency.js.map +1 -0
  57. package/src/lib/model/commerce-orders.d.ts +17 -0
  58. package/src/lib/model/commerce-orders.js +10 -5
  59. package/src/lib/model/commerce-orders.js.map +1 -1
  60. package/src/lib/model/commerce-record-routes.js +26 -1
  61. package/src/lib/model/commerce-record-routes.js.map +1 -1
  62. package/src/lib/model/commerce-reservations.d.ts +6 -0
  63. package/src/lib/model/commerce-reservations.js.map +1 -1
  64. package/src/lib/model/commerce-shipping.d.ts +66 -11
  65. package/src/lib/model/commerce-shipping.js +91 -7
  66. package/src/lib/model/commerce-shipping.js.map +1 -1
  67. package/src/lib/model/commerce.d.ts +6 -0
  68. package/src/lib/model/commerce.js.map +1 -1
  69. package/src/lib/model/index.d.ts +2 -0
  70. package/src/lib/model/index.js +2 -0
  71. package/src/lib/model/index.js.map +1 -1
  72. package/src/lib/model/order-figures.js +9 -2
  73. package/src/lib/model/order-figures.js.map +1 -1
  74. package/src/lib/model/product-modifiers.d.ts +5 -0
  75. package/src/lib/model/product-modifiers.js.map +1 -1
  76. package/src/lib/model/store-setup-content.js +23 -2
  77. package/src/lib/model/store-setup-content.js.map +1 -1
  78. package/src/lib/server/billing-webhook.js +37 -24
  79. package/src/lib/server/billing-webhook.js.map +1 -1
  80. package/src/lib/server/carrier-shipping.d.ts +2 -0
  81. package/src/lib/server/carrier-shipping.js +8 -4
  82. package/src/lib/server/carrier-shipping.js.map +1 -1
  83. package/src/lib/server/cart-checkout.js +74 -13
  84. package/src/lib/server/cart-checkout.js.map +1 -1
  85. package/src/lib/server/cart.d.ts +12 -0
  86. package/src/lib/server/cart.js +50 -4
  87. package/src/lib/server/cart.js.map +1 -1
  88. package/src/lib/server/catalog.d.ts +5 -0
  89. package/src/lib/server/catalog.js +7 -0
  90. package/src/lib/server/catalog.js.map +1 -1
  91. package/src/lib/server/checkout.js +53 -12
  92. package/src/lib/server/checkout.js.map +1 -1
  93. package/src/lib/server/currency.d.ts +93 -0
  94. package/src/lib/server/currency.js +182 -0
  95. package/src/lib/server/currency.js.map +1 -0
  96. package/src/lib/server/order-notifications.js +4 -2
  97. package/src/lib/server/order-notifications.js.map +1 -1
  98. package/src/lib/server/product.d.ts +9 -0
  99. package/src/lib/server/product.js +12 -0
  100. package/src/lib/server/product.js.map +1 -1
  101. package/src/lib/server/refund.js +3 -3
  102. package/src/lib/server/refund.js.map +1 -1
  103. package/src/lib/server/site-chat-tools.d.ts +22 -0
  104. package/src/lib/server/site-chat-tools.js +369 -0
  105. package/src/lib/server/site-chat-tools.js.map +1 -0
  106. package/src/lib/server/site-chat-visitor.d.ts +24 -0
  107. package/src/lib/server/site-chat-visitor.js +39 -0
  108. package/src/lib/server/site-chat-visitor.js.map +1 -0
  109. package/src/lib/server/site-offers.d.ts +31 -0
  110. package/src/lib/server/site-offers.js +91 -0
  111. package/src/lib/server/site-offers.js.map +1 -0
  112. package/src/lib/server/stays-site-search.d.ts +20 -0
  113. package/src/lib/server/stays-site-search.js +78 -0
  114. package/src/lib/server/stays-site-search.js.map +1 -0
  115. package/src/lib/server.js +20 -0
  116. package/src/lib/server.js.map +1 -1
  117. package/src/lib/site-chat-tool-definitions.d.ts +26 -0
  118. package/src/lib/site-chat-tool-definitions.js +141 -0
  119. package/src/lib/site-chat-tool-definitions.js.map +1 -0
  120. package/src/lib/site.js +8 -0
  121. package/src/lib/site.js.map +1 -1
  122. package/src/lib/subprocessors.js +7 -0
  123. package/src/lib/subprocessors.js.map +1 -1
@@ -47,6 +47,8 @@ import * as CommerceModel from '../model';
47
47
  export interface CarrierShippingCart {
48
48
  subtotalCents: number;
49
49
  totalGrams: number;
50
+ /** The items subtotal in the shopper's currency, for a rate's own bound there (AGL-4255). */
51
+ shopperSubtotal?: CommerceModel.ShippingCart['shopperSubtotal'];
50
52
  /** One parcel's dimensions, when the cart is one product that has them. */
51
53
  parcel?: Omit<PluginShippingParcel, 'weightGrams'>;
52
54
  }
@@ -29,10 +29,12 @@ import * as CommerceModel from "../model/index.js";
29
29
  */ export async function planCheckoutShippingWithCarriers(input) {
30
30
  var _input_currency, _cart_parcel, _input_timeoutMs;
31
31
  const { settings, cart } = input;
32
- const tablePlan = ()=>CommerceModel.planCheckoutShipping(settings, {
32
+ const tablePlan = ()=>CommerceModel.planCheckoutShipping(settings, _extends({
33
33
  subtotalCents: cart.subtotalCents,
34
34
  totalGrams: cart.totalGrams
35
- }, input.destination.country);
35
+ }, cart.shopperSubtotal ? {
36
+ shopperSubtotal: cart.shopperSubtotal
37
+ } : {}), input.destination.country);
36
38
  if (!CommerceModel.hasCarrierRates(settings)) return tablePlan();
37
39
  const quoter = pluginShippingRateQuoter();
38
40
  if (!quoter) return tablePlan();
@@ -107,10 +109,12 @@ import * as CommerceModel from "../model/index.js";
107
109
  // carrier rate replaced now that it has quotes.
108
110
  const table = CommerceModel.resolveCheckoutShippingOptions(settings, [
109
111
  country
110
- ], {
112
+ ], _extends({
111
113
  subtotalCents: cart.subtotalCents,
112
114
  totalGrams: cart.totalGrams
113
- }).filter((option)=>!hidden.has(option.rateId));
115
+ }, cart.shopperSubtotal ? {
116
+ shopperSubtotal: cart.shopperSubtotal
117
+ } : {})).filter((option)=>!hidden.has(option.rateId));
114
118
  // One option per name: two carrier rates quoting the same service keep the
115
119
  // cheaper, so a shopper never sees the same service twice.
116
120
  const byName = new Map();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/carrier-shipping.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n pluginShippingRateQuoter,\n quotePluginShippingRates,\n type PluginShippingParcel,\n} from '@aglyn/aglyn/plugin-manager/plugin-shipping-rates'\nimport * as CommerceModel from '../model'\n\n/**\n * LIVE CARRIER RATES AT CHECKOUT (AGL-3612): the `carrier` rate kind, priced\n * by asking core's `core.shipping-rate-quoter` — whichever plugin quotes\n * carriers — and never by importing it.\n *\n * ## Quoted before the session exists, on every door\n *\n * Stripe's hosted Checkout cannot change a session's shipping options once\n * the shopper types an address (\"The hosted page integration doesn't support\n * dynamically customizing shipping options\"), and the in-page form can only\n * by a server update after the fact — while this module's callers fix the\n * platform fee and the Connect transfer from the session's options at\n * creation. So the quote is taken BEFORE the session, against the\n * destination the shopper declares (country and postal code), and the\n * session is then restricted to that country exactly as a zone rate is\n * (AGL-1721). The same code serves cart checkout, buy-now and a draft\n * order's link, hosted and in-page, and the fee arithmetic downstream sees\n * ordinary options.\n *\n * ## The fallback is the merchant's own\n *\n * No quoter, a quoter not available for this site, or a quote that fails or\n * takes longer than {@link CommerceModel.CARRIER_QUOTE_TIMEOUT_MS}: the plan\n * is exactly the one {@link CommerceModel.planCheckoutShipping} makes from\n * the table, where a carrier rate offers nothing and its fallback rate is\n * offered. A store with no carrier rate never reaches the quoter at all, so\n * its sessions are byte-identical to the ones before this existed.\n */\n\nexport interface CarrierShippingCart {\n subtotalCents: number\n totalGrams: number\n /** One parcel's dimensions, when the cart is one product that has them. */\n parcel?: Omit<PluginShippingParcel, 'weightGrams'>\n}\n\nexport interface CarrierShippingDestination {\n country?: unknown\n postalCode?: unknown\n state?: unknown\n city?: unknown\n}\n\n/** A postal code a shopper declared, trimmed and bounded, or `undefined`. */\nexport function normalizeCheckoutPostalCode(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const code = value.trim().toUpperCase().slice(0, 12)\n return /^[A-Z0-9][A-Z0-9 -]{1,11}$/.test(code) ? code : undefined\n}\n\nexport type CarrierShippingPlan = CommerceModel.CheckoutShippingPlan & {\n /** Set when the plan offers live quotes: the postal code they were priced for. */\n quotedPostalCode?: string\n /**\n * The destination's zone prices by carrier and the store can quote, but the\n * shopper has not said where in the country: ask for a postal code.\n */\n needsPostalCode?: boolean\n}\n\n/** What a shopper is told when a postal code is needed. */\nexport const CARRIER_POSTAL_CODE_MESSAGE = 'Enter the postal code you’re shipping to.'\n\n/**\n * The shipping half of a session for a store that may price by carrier.\n * See the module comment; `planCheckoutShipping` is the whole answer for any\n * store without a carrier rate.\n */\nexport async function planCheckoutShippingWithCarriers(input: {\n hostId: string\n settings: CommerceModel.ShippingSettings | undefined\n cart: CarrierShippingCart\n destination: CarrierShippingDestination\n currency?: string\n timeoutMs?: number\n}): Promise<CarrierShippingPlan> {\n const { settings, cart } = input\n const tablePlan = () =>\n CommerceModel.planCheckoutShipping(\n settings,\n { subtotalCents: cart.subtotalCents, totalGrams: cart.totalGrams },\n input.destination.country,\n )\n if (!CommerceModel.hasCarrierRates(settings)) return tablePlan()\n const quoter = pluginShippingRateQuoter()\n if (!quoter) return tablePlan()\n const available = await quoter.available(input.hostId).catch(() => false)\n if (!available) return tablePlan()\n\n const countries = CommerceModel.checkoutShippingCountries(settings)\n const country = CommerceModel.normalizeCheckoutShippingCountry(input.destination.country, countries)\n if (!country) {\n // Carrier prices differ by address by construction, so a session that\n // does not know the destination cannot be honest about any of them.\n return { countries, options: [], refusal: 'destination-required' }\n }\n const carrierRates = CommerceModel.carrierRatesFor(settings, country)\n if (!carrierRates.length) return tablePlan()\n const postalCode = normalizeCheckoutPostalCode(input.destination.postalCode)\n if (!postalCode) {\n return {\n countries: [country],\n options: [],\n refusal: 'destination-required',\n needsPostalCode: true,\n }\n }\n\n const currency = String(input.currency ?? 'usd').toLowerCase()\n const quotes = await quotePluginShippingRates(\n {\n hostId: input.hostId,\n to: {\n country,\n postalCode,\n ...(typeof input.destination.state === 'string' && input.destination.state.trim()\n ? { state: input.destination.state.trim().slice(0, 40) }\n : {}),\n ...(typeof input.destination.city === 'string' && input.destination.city.trim()\n ? { city: input.destination.city.trim().slice(0, 80) }\n : {}),\n },\n parcels: [{ weightGrams: Math.max(0, Math.round(cart.totalGrams)), ...(cart.parcel ?? {}) }],\n currency,\n valueCents: Math.max(0, Math.round(cart.subtotalCents)),\n },\n { timeoutMs: input.timeoutMs ?? CommerceModel.CARRIER_QUOTE_TIMEOUT_MS },\n )\n if (!quotes || !quotes.length) return tablePlan()\n\n const quoted: CommerceModel.ResolvedShippingRate[] = []\n const hidden = new Set<string>()\n for (const rate of carrierRates) {\n const services = (rate.carrier?.services ?? []).map((key) => key.toLowerCase())\n const offered = quotes.filter(\n (quote) => quote.currency === currency && (!services.length || services.includes(quote.serviceKey.toLowerCase())),\n )\n if (!offered.length) continue\n if (rate.carrier?.fallbackRateId) hidden.add(rate.carrier.fallbackRateId)\n for (const quote of offered) {\n quoted.push({\n rateId: CommerceModel.carrierOptionRateId(rate.id, quote.serviceKey),\n name: (quote.estimatedDays\n ? `${quote.label} (${quote.estimatedDays} business day${quote.estimatedDays === 1 ? '' : 's'})`\n : quote.label\n ).slice(0, 100),\n amountCents: CommerceModel.carrierOptionAmountCents(quote.amountCents, rate.carrier),\n })\n }\n }\n if (!quoted.length) return tablePlan()\n\n // The table's own options for this destination stay — a flat rate the\n // merchant offers beside carriers, local pickup — less any fallback a\n // carrier rate replaced now that it has quotes.\n const table = CommerceModel.resolveCheckoutShippingOptions(\n settings,\n [country],\n { subtotalCents: cart.subtotalCents, totalGrams: cart.totalGrams },\n ).filter((option) => !hidden.has(option.rateId))\n // One option per name: two carrier rates quoting the same service keep the\n // cheaper, so a shopper never sees the same service twice.\n const byName = new Map<string, CommerceModel.ResolvedShippingRate>()\n for (const option of [...table, ...quoted]) {\n const existing = byName.get(option.name)\n if (!existing || option.amountCents < existing.amountCents) byName.set(option.name, option)\n }\n const options = [...byName.values()]\n .sort((a, b) => a.amountCents - b.amountCents || a.rateId.localeCompare(b.rateId))\n .slice(0, CommerceModel.MAX_CHECKOUT_SHIPPING_OPTIONS)\n return { countries: [country], options, quotedPostalCode: postalCode }\n}\n"],"names":["pluginShippingRateQuoter","quotePluginShippingRates","CommerceModel","normalizeCheckoutPostalCode","value","undefined","code","trim","toUpperCase","slice","test","CARRIER_POSTAL_CODE_MESSAGE","planCheckoutShippingWithCarriers","input","cart","settings","tablePlan","planCheckoutShipping","subtotalCents","totalGrams","destination","country","hasCarrierRates","quoter","available","hostId","catch","countries","checkoutShippingCountries","normalizeCheckoutShippingCountry","options","refusal","carrierRates","carrierRatesFor","length","postalCode","needsPostalCode","currency","String","toLowerCase","quotes","to","state","city","parcels","weightGrams","Math","max","round","parcel","valueCents","timeoutMs","CARRIER_QUOTE_TIMEOUT_MS","quoted","hidden","Set","rate","services","carrier","map","key","offered","filter","quote","includes","serviceKey","fallbackRateId","add","push","rateId","carrierOptionRateId","id","name","estimatedDays","label","amountCents","carrierOptionAmountCents","table","resolveCheckoutShippingOptions","option","has","byName","Map","existing","get","set","values","sort","a","b","localeCompare","MAX_CHECKOUT_SHIPPING_OPTIONS","quotedPostalCode"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wBAAwB,EACxBC,wBAAwB,QAEnB,oDAAmD;AAC1D,YAAYC,mBAAmB,oBAAU;AA6CzC,2EAA2E,GAC3E,OAAO,SAASC,4BAA4BC,KAAc;IACxD,IAAI,OAAOA,UAAU,UAAU,OAAOC;IACtC,MAAMC,OAAOF,MAAMG,IAAI,GAAGC,WAAW,GAAGC,KAAK,CAAC,GAAG;IACjD,OAAO,6BAA6BC,IAAI,CAACJ,QAAQA,OAAOD;AAC1D;AAYA,yDAAyD,GACzD,OAAO,MAAMM,8BAA8B,4CAA2C;AAEtF;;;;CAIC,GACD,OAAO,eAAeC,iCAAiCC,KAOtD;QAiCyBA,iBAcmDC,cAI5DD;IAlDf,MAAM,EAAEE,QAAQ,EAAED,IAAI,EAAE,GAAGD;IAC3B,MAAMG,YAAY,IAChBd,cAAce,oBAAoB,CAChCF,UACA;YAAEG,eAAeJ,KAAKI,aAAa;YAAEC,YAAYL,KAAKK,UAAU;QAAC,GACjEN,MAAMO,WAAW,CAACC,OAAO;IAE7B,IAAI,CAACnB,cAAcoB,eAAe,CAACP,WAAW,OAAOC;IACrD,MAAMO,SAASvB;IACf,IAAI,CAACuB,QAAQ,OAAOP;IACpB,MAAMQ,YAAY,MAAMD,OAAOC,SAAS,CAACX,MAAMY,MAAM,EAAEC,KAAK,CAAC,IAAM;IACnE,IAAI,CAACF,WAAW,OAAOR;IAEvB,MAAMW,YAAYzB,cAAc0B,yBAAyB,CAACb;IAC1D,MAAMM,UAAUnB,cAAc2B,gCAAgC,CAAChB,MAAMO,WAAW,CAACC,OAAO,EAAEM;IAC1F,IAAI,CAACN,SAAS;QACZ,sEAAsE;QACtE,oEAAoE;QACpE,OAAO;YA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AeJ,KAAKI,aAAa;QAAEC,YAAYL,KAAKK,UAAU;IAAC,GACjE2C,MAAM,CAAC,CAACiB,SAAW,CAACzB,OAAO0B,GAAG,CAACD,OAAOV,MAAM;IAC9C,2EAA2E;IAC3E,2DAA2D;IAC3D,MAAMY,SAAS,IAAIC;IACnB,KAAK,MAAMH,UAAU;WAAIF;WAAUxB;KAAO,CAAE;QAC1C,MAAM8B,WAAWF,OAAOG,GAAG,CAACL,OAAOP,IAAI;QACvC,IAAI,CAACW,YAAYJ,OAAOJ,WAAW,GAAGQ,SAASR,WAAW,EAAEM,OAAOI,GAAG,CAACN,OAAOP,IAAI,EAAEO;IACtF;IACA,MAAMjD,UAAU;WAAImD,OAAOK,MAAM;KAAG,CACjCC,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEb,WAAW,GAAGc,EAAEd,WAAW,IAAIa,EAAEnB,MAAM,CAACqB,aAAa,CAACD,EAAEpB,MAAM,GAC/E5D,KAAK,CAAC,GAAGP,cAAcyF,6BAA6B;IACvD,OAAO;QAAEhE,WAAW;YAACN;SAAQ;QAAES;QAAS8D,kBAAkBzD;IAAW;AACvE"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/carrier-shipping.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n pluginShippingRateQuoter,\n quotePluginShippingRates,\n type PluginShippingParcel,\n} from '@aglyn/aglyn/plugin-manager/plugin-shipping-rates'\nimport * as CommerceModel from '../model'\n\n/**\n * LIVE CARRIER RATES AT CHECKOUT (AGL-3612): the `carrier` rate kind, priced\n * by asking core's `core.shipping-rate-quoter` — whichever plugin quotes\n * carriers — and never by importing it.\n *\n * ## Quoted before the session exists, on every door\n *\n * Stripe's hosted Checkout cannot change a session's shipping options once\n * the shopper types an address (\"The hosted page integration doesn't support\n * dynamically customizing shipping options\"), and the in-page form can only\n * by a server update after the fact — while this module's callers fix the\n * platform fee and the Connect transfer from the session's options at\n * creation. So the quote is taken BEFORE the session, against the\n * destination the shopper declares (country and postal code), and the\n * session is then restricted to that country exactly as a zone rate is\n * (AGL-1721). The same code serves cart checkout, buy-now and a draft\n * order's link, hosted and in-page, and the fee arithmetic downstream sees\n * ordinary options.\n *\n * ## The fallback is the merchant's own\n *\n * No quoter, a quoter not available for this site, or a quote that fails or\n * takes longer than {@link CommerceModel.CARRIER_QUOTE_TIMEOUT_MS}: the plan\n * is exactly the one {@link CommerceModel.planCheckoutShipping} makes from\n * the table, where a carrier rate offers nothing and its fallback rate is\n * offered. A store with no carrier rate never reaches the quoter at all, so\n * its sessions are byte-identical to the ones before this existed.\n */\n\nexport interface CarrierShippingCart {\n subtotalCents: number\n totalGrams: number\n /** The items subtotal in the shopper's currency, for a rate's own bound there (AGL-4255). */\n shopperSubtotal?: CommerceModel.ShippingCart['shopperSubtotal']\n /** One parcel's dimensions, when the cart is one product that has them. */\n parcel?: Omit<PluginShippingParcel, 'weightGrams'>\n}\n\nexport interface CarrierShippingDestination {\n country?: unknown\n postalCode?: unknown\n state?: unknown\n city?: unknown\n}\n\n/** A postal code a shopper declared, trimmed and bounded, or `undefined`. */\nexport function normalizeCheckoutPostalCode(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined\n const code = value.trim().toUpperCase().slice(0, 12)\n return /^[A-Z0-9][A-Z0-9 -]{1,11}$/.test(code) ? code : undefined\n}\n\nexport type CarrierShippingPlan = CommerceModel.CheckoutShippingPlan & {\n /** Set when the plan offers live quotes: the postal code they were priced for. */\n quotedPostalCode?: string\n /**\n * The destination's zone prices by carrier and the store can quote, but the\n * shopper has not said where in the country: ask for a postal code.\n */\n needsPostalCode?: boolean\n}\n\n/** What a shopper is told when a postal code is needed. */\nexport const CARRIER_POSTAL_CODE_MESSAGE = 'Enter the postal code you’re shipping to.'\n\n/**\n * The shipping half of a session for a store that may price by carrier.\n * See the module comment; `planCheckoutShipping` is the whole answer for any\n * store without a carrier rate.\n */\nexport async function planCheckoutShippingWithCarriers(input: {\n hostId: string\n settings: CommerceModel.ShippingSettings | undefined\n cart: CarrierShippingCart\n destination: CarrierShippingDestination\n currency?: string\n timeoutMs?: number\n}): Promise<CarrierShippingPlan> {\n const { settings, cart } = input\n const tablePlan = () =>\n CommerceModel.planCheckoutShipping(\n settings,\n {\n subtotalCents: cart.subtotalCents,\n totalGrams: cart.totalGrams,\n ...(cart.shopperSubtotal ? { shopperSubtotal: cart.shopperSubtotal } : {}),\n },\n input.destination.country,\n )\n if (!CommerceModel.hasCarrierRates(settings)) return tablePlan()\n const quoter = pluginShippingRateQuoter()\n if (!quoter) return tablePlan()\n const available = await quoter.available(input.hostId).catch(() => false)\n if (!available) return tablePlan()\n\n const countries = CommerceModel.checkoutShippingCountries(settings)\n const country = CommerceModel.normalizeCheckoutShippingCountry(input.destination.country, countries)\n if (!country) {\n // Carrier prices differ by address by construction, so a session that\n // does not know the destination cannot be honest about any of them.\n return { countries, options: [], refusal: 'destination-required' }\n }\n const carrierRates = CommerceModel.carrierRatesFor(settings, country)\n if (!carrierRates.length) return tablePlan()\n const postalCode = normalizeCheckoutPostalCode(input.destination.postalCode)\n if (!postalCode) {\n return {\n countries: [country],\n options: [],\n refusal: 'destination-required',\n needsPostalCode: true,\n }\n }\n\n const currency = String(input.currency ?? 'usd').toLowerCase()\n const quotes = await quotePluginShippingRates(\n {\n hostId: input.hostId,\n to: {\n country,\n postalCode,\n ...(typeof input.destination.state === 'string' && input.destination.state.trim()\n ? { state: input.destination.state.trim().slice(0, 40) }\n : {}),\n ...(typeof input.destination.city === 'string' && input.destination.city.trim()\n ? { city: input.destination.city.trim().slice(0, 80) }\n : {}),\n },\n parcels: [{ weightGrams: Math.max(0, Math.round(cart.totalGrams)), ...(cart.parcel ?? {}) }],\n currency,\n valueCents: Math.max(0, Math.round(cart.subtotalCents)),\n },\n { timeoutMs: input.timeoutMs ?? CommerceModel.CARRIER_QUOTE_TIMEOUT_MS },\n )\n if (!quotes || !quotes.length) return tablePlan()\n\n const quoted: CommerceModel.ResolvedShippingRate[] = []\n const hidden = new Set<string>()\n for (const rate of carrierRates) {\n const services = (rate.carrier?.services ?? []).map((key) => key.toLowerCase())\n const offered = quotes.filter(\n (quote) => quote.currency === currency && (!services.length || services.includes(quote.serviceKey.toLowerCase())),\n )\n if (!offered.length) continue\n if (rate.carrier?.fallbackRateId) hidden.add(rate.carrier.fallbackRateId)\n for (const quote of offered) {\n quoted.push({\n rateId: CommerceModel.carrierOptionRateId(rate.id, quote.serviceKey),\n name: (quote.estimatedDays\n ? `${quote.label} (${quote.estimatedDays} business day${quote.estimatedDays === 1 ? '' : 's'})`\n : quote.label\n ).slice(0, 100),\n amountCents: CommerceModel.carrierOptionAmountCents(quote.amountCents, rate.carrier),\n })\n }\n }\n if (!quoted.length) return tablePlan()\n\n // The table's own options for this destination stay — a flat rate the\n // merchant offers beside carriers, local pickup — less any fallback a\n // carrier rate replaced now that it has quotes.\n const table = CommerceModel.resolveCheckoutShippingOptions(\n settings,\n [country],\n {\n subtotalCents: cart.subtotalCents,\n totalGrams: cart.totalGrams,\n ...(cart.shopperSubtotal ? { shopperSubtotal: cart.shopperSubtotal } : {}),\n },\n ).filter((option) => !hidden.has(option.rateId))\n // One option per name: two carrier rates quoting the same service keep the\n // cheaper, so a shopper never sees the same service twice.\n const byName = new Map<string, CommerceModel.ResolvedShippingRate>()\n for (const option of [...table, ...quoted]) {\n const existing = byName.get(option.name)\n if (!existing || option.amountCents < existing.amountCents) byName.set(option.name, option)\n }\n const options = [...byName.values()]\n .sort((a, b) => a.amountCents - b.amountCents || a.rateId.localeCompare(b.rateId))\n .slice(0, CommerceModel.MAX_CHECKOUT_SHIPPING_OPTIONS)\n return { countries: [country], options, quotedPostalCode: postalCode }\n}\n"],"names":["pluginShippingRateQuoter","quotePluginShippingRates","CommerceModel","normalizeCheckoutPostalCode","value","undefined","code","trim","toUpperCase","slice","test","CARRIER_POSTAL_CODE_MESSAGE","planCheckoutShippingWithCarriers","input","cart","settings","tablePlan","planCheckoutShipping","subtotalCents","totalGrams","shopperSubtotal","destination","country","hasCarrierRates","quoter","available","hostId","catch","countries","checkoutShippingCountries","normalizeCheckoutShippingCountry","options","refusal","carrierRates","carrierRatesFor","length","postalCode","needsPostalCode","currency","String","toLowerCase","quotes","to","state","city","parcels","weightGrams","Math","max","round","parcel","valueCents","timeoutMs","CARRIER_QUOTE_TIMEOUT_MS","quoted","hidden","Set","rate","services","carrier","map","key","offered","filter","quote","includes","serviceKey","fallbackRateId","add","push","rateId","carrierOptionRateId","id","name","estimatedDays","label","amountCents","carrierOptionAmountCents","table","resolveCheckoutShippingOptions","option","has","byName","Map","existing","get","set","values","sort","a","b","localeCompare","MAX_CHECKOUT_SHIPPING_OPTIONS","quotedPostalCode"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wBAAwB,EACxBC,wBAAwB,QAEnB,oDAAmD;AAC1D,YAAYC,mBAAmB,oBAAU;AA+CzC,2EAA2E,GAC3E,OAAO,SAASC,4BAA4BC,KAAc;IACxD,IAAI,OAAOA,UAAU,UAAU,OAAOC;IACtC,MAAMC,OAAOF,MAAMG,IAAI,GAAGC,WAAW,GAAGC,KAAK,CAAC,GAAG;IACjD,OAAO,6BAA6BC,IAAI,CAACJ,QAAQA,OAAOD;AAC1D;AAYA,yDAAyD,GACzD,OAAO,MAAMM,8BAA8B,4CAA2C;AAEtF;;;;CAIC,GACD,OAAO,eAAeC,iCAAiCC,KAOtD;QAqCyBA,iBAcmDC,cAI5DD;IAtDf,MAAM,EAAEE,QAAQ,EAAED,IAAI,EAAE,GAAGD;IAC3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AEd,WAAW,IAAIa,EAAEnB,MAAM,CAACqB,aAAa,CAACD,EAAEpB,MAAM,GAC/E7D,KAAK,CAAC,GAAGP,cAAc0F,6BAA6B;IACvD,OAAO;QAAEhE,WAAW;YAACN;SAAQ;QAAES;QAAS8D,kBAAkBzD;IAAW;AACvE"}
@@ -43,6 +43,7 @@ import { appendLocalFulfillmentMetadata, localFulfillmentLocationId, localStockR
43
43
  import { applyNativeCheckoutParams, nativeCheckoutStripeHeaders, readCheckoutSessionPayload, resolveNativeCheckoutMode } from "./native-checkout.js";
44
44
  import { ensureCheckoutDomain } from "./payment-method-domains.js";
45
45
  import { raiseCheckoutStarted } from "./order-events.js";
46
+ import { checkoutAmountMinor, checkoutLineMinor, loadFxRates, resolveCheckoutCurrency, storeCurrencyContextFrom, stripeCurrency } from "./currency.js";
46
47
  import { checkoutExtrasCents, encodeCheckoutExtrasMetadata, readChosenCheckoutExtras } from "@aglyn/aglyn/plugin-manager/plugin-checkout-extras";
47
48
  import { quoteCartExtras } from "./checkout-extras.js";
48
49
  import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCreditMetadata, normalizeCheckoutCreditAccount, normalizeCheckoutCreditCode } from "@aglyn/aglyn/plugin-manager/plugin-checkout-credits";
@@ -173,6 +174,27 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
173
174
  snapshot.id,
174
175
  snapshot.exists ? CommerceModel.liftLegacyProduct(snapshot.data()) : null
175
176
  ]));
177
+ /**
178
+ * The currency the shopper is charged in (AGL-4248). Everything below is
179
+ * priced and checked in the store currency as before; only the amounts
180
+ * handed to Stripe are converted, at the emission. A direct sale only: a
181
+ * destination sale's split and platform tax are store-currency figures.
182
+ * A cart that sells a gift card stays in the store currency, because a
183
+ * card's balance is.
184
+ */ let checkoutCurrency;
185
+ if (body.currency && direct) {
186
+ const currencyStore = await hostRef.collection('settings').doc('store').get();
187
+ const resolved = resolveCheckoutCurrency(storeCurrencyContextFrom(currencyStore.data(), await loadFxRates()), body.currency);
188
+ const sellsGiftCard = cart.lines.some((line)=>{
189
+ var _productsById_get;
190
+ return (_productsById_get = productsById.get(line.productId)) == null ? void 0 : _productsById_get.giftCard;
191
+ });
192
+ if (resolved.foreign && !sellsGiftCard) checkoutCurrency = resolved;
193
+ }
194
+ const chargeCurrency = checkoutCurrency ? stripeCurrency(checkoutCurrency) : 'usd';
195
+ /** The goods in the charge currency, as Stripe will total them. */ let itemsChargeMinor = 0;
196
+ /** Each line's store-currency unit, for the tax engine (it prices in the store currency). */ const baseUnitByIndex = new Map();
197
+ /** Each line's charge-currency unit, in cart order, for the order the webhook writes. */ const chargeUnits = [];
176
198
  let itemsCents = 0;
177
199
  /** Per-line values for scoped discount pricing. */ const discountLines = [];
178
200
  // Gift-card value in the basket, for the cash-out ceiling (AGL-3363).
@@ -331,8 +353,19 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
331
353
  if (feePct > 0) feeApplies = true;
332
354
  feeCents += Math.round(unitCents * line.quantity * feePct / 100);
333
355
  params.set(`line_items[${index}][quantity]`, String(line.quantity));
334
- params.set(`line_items[${index}][price_data][currency]`, 'usd');
335
- params.set(`line_items[${index}][price_data][unit_amount]`, String(unitCents));
356
+ // The charge-currency unit: the variant's fixed price there or its
357
+ // store price converted, plus each add-on's (AGL-4248).
358
+ const chargeUnit = checkoutCurrency ? checkoutLineMinor(checkoutCurrency, product, variant, chosen.modifiers) : unitCents;
359
+ itemsChargeMinor += chargeUnit * line.quantity;
360
+ baseUnitByIndex.set(index, unitCents);
361
+ chargeUnits[index] = chargeUnit;
362
+ params.set(`line_items[${index}][price_data][currency]`, chargeCurrency);
363
+ params.set(`line_items[${index}][price_data][unit_amount]`, String(chargeUnit));
364
+ // Pinned whenever the charge is not in USD (AGL-1956 invariant 5):
365
+ // Stripe infers tax-inclusive pricing from some currencies otherwise.
366
+ if (checkoutCurrency) {
367
+ params.set(`line_items[${index}][price_data][tax_behavior]`, checkoutCurrency.entry.pricesIncludeTax ? 'inclusive' : 'exclusive');
368
+ }
336
369
  // The variant, then the add-ons, as the order line will print them.
337
370
  const lineLabel = CommerceModel.lineLabelWithModifiers(Object.keys((_variant_options = variant.options) != null ? _variant_options : {}).length ? Object.values((_variant_options1 = variant.options) != null ? _variant_options1 : {}).join(' / ') : undefined, chosen.modifiers);
338
371
  const lineName = `${product.name}${lineLabel ? ` (${lineLabel})` : ''}`;
@@ -458,10 +491,15 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
458
491
  } : hasPhysicalLine ? await planCheckoutShippingWithCarriers({
459
492
  hostId,
460
493
  settings: storeSettings.get('shipping'),
461
- cart: {
494
+ cart: _extends({
462
495
  subtotalCents: itemsCents,
463
496
  totalGrams
464
- },
497
+ }, checkoutCurrency ? {
498
+ shopperSubtotal: {
499
+ code: checkoutCurrency.code,
500
+ minor: itemsChargeMinor
501
+ }
502
+ } : {}),
465
503
  destination: {
466
504
  country: body.shippingCountry,
467
505
  postalCode: body.shippingPostalCode
@@ -549,8 +587,8 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
549
587
  chargedExtras.forEach((extra, offset)=>{
550
588
  const index = cart.lines.length + offset;
551
589
  params.set(`line_items[${index}][quantity]`, '1');
552
- params.set(`line_items[${index}][price_data][currency]`, 'usd');
553
- params.set(`line_items[${index}][price_data][unit_amount]`, String(extra.amountCents));
590
+ params.set(`line_items[${index}][price_data][currency]`, chargeCurrency);
591
+ params.set(`line_items[${index}][price_data][unit_amount]`, String(checkoutCurrency ? checkoutAmountMinor(checkoutCurrency, extra.amountCents) : extra.amountCents));
554
592
  params.set(`line_items[${index}][price_data][product_data][name]`, extra.label.slice(0, 120));
555
593
  params.set(`line_items[${index}][price_data][product_data][tax_code]`, 'txcd_00000000');
556
594
  });
@@ -993,10 +1031,12 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
993
1031
  headers: _extends({
994
1032
  Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
995
1033
  'Content-Type': 'application/x-www-form-urlencoded'
996
- }, stripeKeyHeader(creditHeldCents > 0 ? `coupon-c${creditHeldCents}` : 'coupon'), sellerAccountHeader),
1034
+ }, stripeKeyHeader(`${creditHeldCents > 0 ? `coupon-c${creditHeldCents}` : 'coupon'}${checkoutCurrency ? `-${chargeCurrency}` : ''}`), sellerAccountHeader),
997
1035
  body: new URLSearchParams({
998
- amount_off: String(Math.min(totalOffCents, itemsCents)),
999
- currency: 'usd',
1036
+ // In the charge currency, as the same share of the goods it is of
1037
+ // the store-currency goods, so a 10% discount stays 10% (AGL-4248).
1038
+ amount_off: String(checkoutCurrency ? Math.min(itemsChargeMinor, Math.round(Math.min(totalOffCents, itemsCents) * itemsChargeMinor / Math.max(1, itemsCents))) : Math.min(totalOffCents, itemsCents)),
1039
+ currency: chargeCurrency,
1000
1040
  duration: 'once'
1001
1041
  }).toString()
1002
1042
  }).then((response)=>response.json());
@@ -1051,8 +1091,8 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
1051
1091
  // this session exists. When the service does not answer, the store's
1052
1092
  // rate stands and the order says so.
1053
1093
  const cartEngineLines = cart.lines.map((line, index)=>{
1054
- var _params_get;
1055
- const unitCents = Number((_params_get = params.get(`line_items[${index}][price_data][unit_amount]`)) != null ? _params_get : NaN);
1094
+ var _baseUnitByIndex_get, _params_get;
1095
+ const unitCents = (_baseUnitByIndex_get = baseUnitByIndex.get(index)) != null ? _baseUnitByIndex_get : Number((_params_get = params.get(`line_items[${index}][price_data][unit_amount]`)) != null ? _params_get : NaN);
1056
1096
  return {
1057
1097
  index,
1058
1098
  line,
@@ -1123,7 +1163,13 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
1123
1163
  // destinations the declared rates were resolved for. The emission is
1124
1164
  // shared with buy-now (AGL-1720).
1125
1165
  CommerceModel.appendShippingAddressCollectionParams(params, shippingPlan.countries);
1126
- CommerceModel.appendCheckoutShippingParams(params, shippingOptions);
1166
+ CommerceModel.appendCheckoutShippingParams(params, checkoutCurrency ? CommerceModel.shippingOptionsInCurrency(shippingOptions, storeSettings.get('shipping'), {
1167
+ code: checkoutCurrency.code,
1168
+ subtotalMinor: itemsChargeMinor,
1169
+ convert: (cents, fixed)=>checkoutAmountMinor(checkoutCurrency, cents, fixed)
1170
+ }) : shippingOptions, chargeCurrency, (checkoutCurrency == null ? void 0 : checkoutCurrency.entry.pricesIncludeTax) ? {
1171
+ taxBehavior: 'inclusive'
1172
+ } : {});
1127
1173
  // Taxes (AGL-1953). This block used to be the `stripe` line alone, and a
1128
1174
  // `manual`-mode store — the mode the AGL-285 zone editor leaves a merchant
1129
1175
  // in by default — collected tax on a buy-now sale and NOTHING on a cart
@@ -1325,7 +1371,9 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
1325
1371
  // to hold back. The split is the take as `application_fee_amount`.
1326
1372
  const cartTaxOwner = !direct && taxDecision.kind === 'stripe-automatic' ? 'platform' : 'merchant';
1327
1373
  const cartShippingFloorCents = CommerceModel.shippingFloorCents(shippingOptions);
1328
- Object.entries(direct ? directChargeParams(feeCents) : CommerceModel.destinationChargeParams({
1374
+ Object.entries(direct ? directChargeParams(// The take in the charge currency (AGL-4248): Stripe reads
1375
+ // `application_fee_amount` in the session's currency.
1376
+ checkoutCurrency ? checkoutAmountMinor(checkoutCurrency, feeCents) : feeCents) : CommerceModel.destinationChargeParams({
1329
1377
  accountId: String(accountId),
1330
1378
  feeCents,
1331
1379
  taxOwner: cartTaxOwner,
@@ -1351,6 +1399,19 @@ import { boundedCreditCents, checkoutCreditProviderForCode, encodeCheckoutCredit
1351
1399
  params.set('metadata[hostId]', hostId);
1352
1400
  params.set('metadata[cartId]', cartId);
1353
1401
  params.set('metadata[feeCents]', String(Math.max(0, feeCents)));
1402
+ // What the order records about the currency (AGL-4248). `feeCents` above
1403
+ // stays the store-currency take; the order's figures are in the charge
1404
+ // currency, with the store-currency equivalents beside them.
1405
+ if (checkoutCurrency) {
1406
+ for (const [key, value] of Object.entries(CommerceModel.encodeChargeUnitsMetadata(chargeUnits))){
1407
+ params.set(`metadata[${key}]`, value);
1408
+ }
1409
+ params.set('metadata[chargeFeeCents]', String(checkoutAmountMinor(checkoutCurrency, Math.max(0, feeCents))));
1410
+ params.set('metadata[chargeExtrasCents]', String(chargedExtras.reduce((sum, extra)=>sum + checkoutAmountMinor(checkoutCurrency, extra.amountCents), 0)));
1411
+ params.set('metadata[currency]', chargeCurrency);
1412
+ params.set('metadata[baseCurrency]', checkoutCurrency.base.toLowerCase());
1413
+ params.set('metadata[fxRate]', String(checkoutCurrency.rate));
1414
+ }
1354
1415
  // Only on the shape where `transfer.amount` is no longer `charge.amount`,
1355
1416
  // so the merchant's actual payout stops being derivable from the charge
1356
1417
  // (AGL-1956). The shipping baseline is the other half: the difference