@aglyn/plugins-commerce 1.30.0 → 1.32.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 (132) hide show
  1. package/README.md +4 -0
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +46 -20
  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 +47 -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/product-traffic-card.component.d.ts +24 -0
  19. package/src/lib/components/console/product-traffic-card.component.js +172 -0
  20. package/src/lib/components/console/product-traffic-card.component.js.map +1 -0
  21. package/src/lib/components/console/products-hub-card.component.js +181 -59
  22. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  23. package/src/lib/components/console/reservations-card.component.js +32 -15
  24. package/src/lib/components/console/reservations-card.component.js.map +1 -1
  25. package/src/lib/components/console/shipping-settings-card.component.js +131 -10
  26. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  27. package/src/lib/components/console/store-settings-card.component.js +1 -1
  28. package/src/lib/components/console/store-settings-card.component.js.map +1 -1
  29. package/src/lib/components/console/use-currency-setup.d.ts +20 -0
  30. package/src/lib/components/console/use-currency-setup.js +61 -0
  31. package/src/lib/components/console/use-currency-setup.js.map +1 -0
  32. package/src/lib/components/currency-selector.d.ts +36 -0
  33. package/src/lib/components/currency-selector.js +157 -0
  34. package/src/lib/components/currency-selector.js.map +1 -0
  35. package/src/lib/components/product-add-ons.d.ts +9 -1
  36. package/src/lib/components/product-add-ons.js +8 -4
  37. package/src/lib/components/product-add-ons.js.map +1 -1
  38. package/src/lib/components/product-choice-cards.d.ts +13 -1
  39. package/src/lib/components/product-choice-cards.js +5 -4
  40. package/src/lib/components/product-choice-cards.js.map +1 -1
  41. package/src/lib/components/product-detail.d.ts +8 -0
  42. package/src/lib/components/product-detail.js +38 -11
  43. package/src/lib/components/product-detail.js.map +1 -1
  44. package/src/lib/components/product-grid.d.ts +2 -0
  45. package/src/lib/components/product-grid.js +22 -9
  46. package/src/lib/components/product-grid.js.map +1 -1
  47. package/src/lib/components/related-products.js +6 -2
  48. package/src/lib/components/related-products.js.map +1 -1
  49. package/src/lib/components/shopper-currency.d.ts +108 -0
  50. package/src/lib/components/shopper-currency.js +262 -0
  51. package/src/lib/components/shopper-currency.js.map +1 -0
  52. package/src/lib/components/wishlist.js +7 -1
  53. package/src/lib/components/wishlist.js.map +1 -1
  54. package/src/lib/declarations.server.js +39 -0
  55. package/src/lib/declarations.server.js.map +1 -1
  56. package/src/lib/model/commerce-currency-setup.d.ts +79 -0
  57. package/src/lib/model/commerce-currency-setup.js +124 -0
  58. package/src/lib/model/commerce-currency-setup.js.map +1 -0
  59. package/src/lib/model/commerce-currency.d.ts +215 -0
  60. package/src/lib/model/commerce-currency.js +511 -0
  61. package/src/lib/model/commerce-currency.js.map +1 -0
  62. package/src/lib/model/commerce-orders.d.ts +17 -0
  63. package/src/lib/model/commerce-orders.js +10 -5
  64. package/src/lib/model/commerce-orders.js.map +1 -1
  65. package/src/lib/model/commerce-record-routes.js +56 -0
  66. package/src/lib/model/commerce-record-routes.js.map +1 -1
  67. package/src/lib/model/commerce-reservations.d.ts +6 -0
  68. package/src/lib/model/commerce-reservations.js.map +1 -1
  69. package/src/lib/model/commerce-shipping.d.ts +61 -17
  70. package/src/lib/model/commerce-shipping.js +346 -32
  71. package/src/lib/model/commerce-shipping.js.map +1 -1
  72. package/src/lib/model/commerce.d.ts +6 -0
  73. package/src/lib/model/commerce.js.map +1 -1
  74. package/src/lib/model/index.d.ts +2 -0
  75. package/src/lib/model/index.js +2 -0
  76. package/src/lib/model/index.js.map +1 -1
  77. package/src/lib/model/order-figures.js +9 -2
  78. package/src/lib/model/order-figures.js.map +1 -1
  79. package/src/lib/model/product-modifiers.d.ts +5 -0
  80. package/src/lib/model/product-modifiers.js.map +1 -1
  81. package/src/lib/model/product-write.d.ts +10 -1
  82. package/src/lib/model/product-write.js +13 -2
  83. package/src/lib/model/product-write.js.map +1 -1
  84. package/src/lib/server/billing-webhook.js +37 -24
  85. package/src/lib/server/billing-webhook.js.map +1 -1
  86. package/src/lib/server/carrier-shipping.js +3 -2
  87. package/src/lib/server/carrier-shipping.js.map +1 -1
  88. package/src/lib/server/cart-checkout.js +77 -15
  89. package/src/lib/server/cart-checkout.js.map +1 -1
  90. package/src/lib/server/cart.d.ts +12 -0
  91. package/src/lib/server/cart.js +52 -6
  92. package/src/lib/server/cart.js.map +1 -1
  93. package/src/lib/server/catalog.d.ts +5 -0
  94. package/src/lib/server/catalog.js +7 -0
  95. package/src/lib/server/catalog.js.map +1 -1
  96. package/src/lib/server/checkout.js +54 -16
  97. package/src/lib/server/checkout.js.map +1 -1
  98. package/src/lib/server/currency.d.ts +93 -0
  99. package/src/lib/server/currency.js +182 -0
  100. package/src/lib/server/currency.js.map +1 -0
  101. package/src/lib/server/draft-order.js +3 -3
  102. package/src/lib/server/draft-order.js.map +1 -1
  103. package/src/lib/server/order-notifications.js +4 -2
  104. package/src/lib/server/order-notifications.js.map +1 -1
  105. package/src/lib/server/product.d.ts +9 -0
  106. package/src/lib/server/product.js +12 -0
  107. package/src/lib/server/product.js.map +1 -1
  108. package/src/lib/server/products-write.js +10 -2
  109. package/src/lib/server/products-write.js.map +1 -1
  110. package/src/lib/server/refund.js +3 -3
  111. package/src/lib/server/refund.js.map +1 -1
  112. package/src/lib/server/site-chat-tools.d.ts +22 -0
  113. package/src/lib/server/site-chat-tools.js +369 -0
  114. package/src/lib/server/site-chat-tools.js.map +1 -0
  115. package/src/lib/server/site-chat-visitor.d.ts +24 -0
  116. package/src/lib/server/site-chat-visitor.js +39 -0
  117. package/src/lib/server/site-chat-visitor.js.map +1 -0
  118. package/src/lib/server/site-offers.d.ts +31 -0
  119. package/src/lib/server/site-offers.js +91 -0
  120. package/src/lib/server/site-offers.js.map +1 -0
  121. package/src/lib/server/stays-site-search.d.ts +20 -0
  122. package/src/lib/server/stays-site-search.js +78 -0
  123. package/src/lib/server/stays-site-search.js.map +1 -0
  124. package/src/lib/server.js +20 -0
  125. package/src/lib/server.js.map +1 -1
  126. package/src/lib/site-chat-tool-definitions.d.ts +26 -0
  127. package/src/lib/site-chat-tool-definitions.js +141 -0
  128. package/src/lib/site-chat-tool-definitions.js.map +1 -0
  129. package/src/lib/site.js +8 -0
  130. package/src/lib/site.js.map +1 -1
  131. package/src/lib/subprocessors.js +7 -0
  132. package/src/lib/subprocessors.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/product-modifiers.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 * REGISTER MODIFIERS AND QUICK KEYS (AGL-3607).\n *\n * A modifier is a choice added to an item as it is rung up — \"Oat milk\",\n * \"Extra shot +$0.75\", \"No onions\" — that is not a stocked variant. Groups\n * live on the product (`modifierGroups`); the register sends the chosen\n * option ids with each line and the SERVER prices them from the product\n * document, so a register never names what a modifier costs.\n *\n * A chosen modifier is folded into the line's `variantLabel` as well as kept\n * structured in `modifiers`: every receipt, email, order view and export\n * already prints the label, so the choice reaches all of them without each\n * learning a new field.\n *\n * ADD-ONS ON THE WEBSITE (AGL-4100). A group switched to \"Show on the\n * website\" (`online`) is offered on the product's page too, and a cart line,\n * Buy now and the order carry its picks the same way: ids from the shopper,\n * prices from the product. A choice may cost more on one variant than\n * another (`priceCentsByVariant`), which is how one page sells a canopy whose\n * walls cost more at a larger size without a variant for every combination.\n *\n * THE PRODUCT BUILDER (AGL-4205). A choice may carry a picture and a short\n * note, which a product page set to show its choices as picture cards draws\n * on the choice's card. A choice that lists what it `includes` is a combo:\n * one price for a bundle (\"Weekend kit: 4 walls, 4 weights, a bag\"), and the\n * card folds its contents out. Display only: a combo is priced and sold as\n * the one choice it is.\n *\n * WRITE-INS (write-ins). A group of `kind: 'text'` asks the\n * shopper to type an answer instead of picking one: the name and number\n * printed on a sign, an engraving, a cake message. It holds exactly one option, which carries what a\n * filled answer adds to the price (by variant too) and its helper note, so\n * pricing, ids and every path that carries picks stay the same; the pick\n * adds the `text`. The answer is checked and cleaned on the server like any\n * pick ({@link cleanWriteIn}) and prints on the line as \"Engraving: For\n * Sam\". With write-ins and required size groups, one variant sells a set\n * of pieces in any combination of sizes, with no cap on combinations.\n *=========================================*/\n\n/** One choice in a modifier group. `priceCents` is added to the item, 0 for free. */\nexport interface ProductModifierOption {\n id: string\n name: string\n priceCents: number\n /**\n * What the choice adds on one variant, keyed by variant id (AGL-4100):\n * walls cost more on a larger canopy. A variant not listed pays\n * `priceCents`. Read through {@link modifierOptionPriceCents}.\n */\n priceCentsByVariant?: Record<string, number>\n /** A picture of the choice, from the media library, for its card (AGL-4205). */\n imageUrl?: string\n /** A short line under the choice on its card (AGL-4205): \"Blocks wind on one side\". */\n note?: string\n /**\n * What a combo holds (AGL-4205), one item per entry: \"Full wall ×2\". A\n * choice with any is shown as a combo whose contents fold out.\n */\n includes?: string[]\n}\n\n/**\n * A set of choices offered together (\"Milk\", \"Add-ons\"). `min` of 1 or more\n * makes it required; `max` caps how many can be picked (1 = pick one).\n */\nexport interface ProductModifierGroup {\n id: string\n name: string\n min: number\n max: number\n options: ProductModifierOption[]\n /**\n * `'text'` makes the group a write-in: the shopper types the answer (a\n * name, a number) into one field. Absent is a group of choices. A write-in\n * holds exactly one option, which names it and prices it.\n */\n kind?: ProductModifierGroupKind\n /** A write-in's longest answer, 1 to {@link MAX_WRITE_IN_LENGTH}; {@link DEFAULT_WRITE_IN_LENGTH} when absent. */\n maxLength?: number\n /** A write-in that takes digits only, such as a number. */\n digitsOnly?: boolean\n /**\n * Print the group's name before the choice on the order, receipt and\n * emails (\"Size: M\"), for choices that do not say what they are on\n * their own. A write-in always prints its name.\n */\n nameOnOrder?: boolean\n /**\n * Offered on the product's page on the website as well as at the register\n * (AGL-4100), \"Show on the website\". Absent reads as register only, so a\n * group made before the switch changes nothing on a live store; the\n * console makes new groups with it on.\n */\n online?: boolean\n}\n\n/** What a group is: choices to pick from, or a write-in the shopper types. */\nexport type ProductModifierGroupKind = 'text'\n\n/** A modifier as the order line keeps it: names and price as sold. */\nexport interface OrderLineModifier {\n groupId: string\n optionId: string\n group: string\n name: string\n priceCents: number\n /** A write-in's answer as sold, such as the text to engrave. */\n text?: string\n /** The group's name prints before the choice on the line (\"Size: M\"). */\n nameOnOrder?: boolean\n}\n\n/** What the register sends for a line: the option ids it picked, nothing priced. */\nexport interface ModifierSelection {\n groupId: string\n optionId: string\n /** A write-in's answer, as typed; the server cleans and checks it. */\n text?: string\n}\n\nexport const POS_MAX_MODIFIER_GROUPS = 10\nexport const POS_MAX_MODIFIER_OPTIONS = 20\n/** $1,000 on one modifier: anything larger is a product, not an add-on. */\nexport const POS_MAX_MODIFIER_PRICE_CENTS = 100_000\n/** The longest answer a write-in can take: a name or a short message fits well inside. */\nexport const MAX_WRITE_IN_LENGTH = 40\n/** A write-in's length when the merchant sets none. */\nexport const DEFAULT_WRITE_IN_LENGTH = 20\n/** How much of a typed answer is carried before its group checks it. */\nconst WRITE_IN_INPUT_BOUND = 200\n\n/** Whether a group is a write-in the shopper types. */\nexport function modifierGroupIsWriteIn(group: Pick<ProductModifierGroup, 'kind'> | null | undefined): boolean {\n return group?.kind === 'text'\n}\n\n/** A write-in's longest answer. */\nexport function writeInMaxLength(group: Pick<ProductModifierGroup, 'maxLength'>): number {\n const length = group.maxLength\n return typeof length === 'number' && Number.isInteger(length) && length >= 1 && length <= MAX_WRITE_IN_LENGTH\n ? length\n : DEFAULT_WRITE_IN_LENGTH\n}\n\n/**\n * A write-in's answer cleaned for the order: control characters and runs of\n * spaces gone, trimmed, cut at the group's length. Empty when nothing is left.\n * Without a group the answer is only bounded, so a too-long one still reaches\n * the check that names it.\n */\nexport function cleanWriteIn(raw: unknown, group?: Pick<ProductModifierGroup, 'maxLength'> | null): string {\n if (typeof raw !== 'string') return ''\n const limit = group ? writeInMaxLength(group) : WRITE_IN_INPUT_BOUND\n const flat = raw\n // eslint-disable-next-line no-control-regex\n .replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n return Array.from(flat).slice(0, limit).join('').trim()\n}\n\n/** Why a write-in's answer cannot be sold, or null when it can. An empty answer is the minimum's business. */\nexport function writeInProblem(\n group: Pick<ProductModifierGroup, 'name' | 'maxLength' | 'digitsOnly'>,\n raw: unknown,\n): string | null {\n const typed = cleanWriteIn(raw)\n if (!typed) return null\n const limit = writeInMaxLength(group)\n if (Array.from(typed).length > limit) return `${group.name} takes up to ${limit} characters.`\n if (group.digitsOnly && !/^[0-9]+$/.test(typed)) return `${group.name} takes numbers only.`\n return null\n}\n/** Whether a choice is a combo: it lists what it includes (AGL-4205). */\nexport function modifierOptionIsCombo(option: Pick<ProductModifierOption, 'includes'>): boolean {\n return (\n Array.isArray(option.includes) &&\n option.includes.length > 0 &&\n option.includes.every((item) => typeof item === 'string')\n )\n}\n\nfunction modifierPriceIsValid(price: unknown): boolean {\n return (\n typeof price === 'number' &&\n Number.isInteger(price) &&\n price >= 0 &&\n price <= POS_MAX_MODIFIER_PRICE_CENTS\n )\n}\n\n/** Why a product's modifier groups cannot be saved, or null when they can. */\nexport function modifierGroupsProblem(groups: unknown): string | null {\n if (groups == null) return null\n if (!Array.isArray(groups)) return 'Modifiers must be a list'\n if (groups.length > POS_MAX_MODIFIER_GROUPS) {\n return `At most ${POS_MAX_MODIFIER_GROUPS} modifier groups per product`\n }\n const groupIds = new Set<string>()\n for (const group of groups as ProductModifierGroup[]) {\n if (!group?.id || groupIds.has(group.id)) return 'Modifier groups need unique ids'\n groupIds.add(group.id)\n if (!String(group.name ?? '').trim()) return 'Name every modifier group'\n const options = Array.isArray(group.options) ? group.options : []\n if (group.kind != null && group.kind !== 'text') return `“${group.name}” is a list of choices or a write-in`\n if (group.kind === 'text') {\n if (options.length !== 1) return `“${group.name}” is a write-in and holds one field`\n if (group.max !== 1 || (group.min !== 0 && group.min !== 1)) {\n return `“${group.name}” is a write-in: required or not, one answer`\n }\n if (\n group.maxLength != null &&\n (!Number.isInteger(group.maxLength) || group.maxLength < 1 || group.maxLength > MAX_WRITE_IN_LENGTH)\n ) {\n return `“${group.name}” takes 1 to ${MAX_WRITE_IN_LENGTH} characters`\n }\n if (group.digitsOnly != null && typeof group.digitsOnly !== 'boolean') {\n return `“${group.name}” takes numbers only or any text`\n }\n }\n if (group.nameOnOrder != null && typeof group.nameOnOrder !== 'boolean') {\n return `“${group.name}” prints its name on the order or not`\n }\n if (options.length === 0) return `Add a choice to “${group.name}”`\n if (options.length > POS_MAX_MODIFIER_OPTIONS) {\n return `“${group.name}” has more than ${POS_MAX_MODIFIER_OPTIONS} choices`\n }\n const optionIds = new Set<string>()\n for (const option of options) {\n if (!option?.id || optionIds.has(option.id)) return 'Modifier choices need unique ids'\n optionIds.add(option.id)\n if (!String(option.name ?? '').trim()) return `Name every choice in “${group.name}”`\n const price = option.priceCents\n if (!modifierPriceIsValid(price)) {\n return `“${option.name}” needs a price of $0 to $1,000`\n }\n const byVariant = option.priceCentsByVariant\n if (byVariant != null) {\n if (typeof byVariant !== 'object' || Array.isArray(byVariant)) {\n return `“${option.name}” has prices that are not a list by option`\n }\n if (Object.values(byVariant).some((cents) => !modifierPriceIsValid(cents))) {\n return `“${option.name}” needs a price of $0 to $1,000 for each option it is priced by`\n }\n }\n }\n if (group.online != null && typeof group.online !== 'boolean') {\n return `“${group.name}” is shown on the website or not`\n }\n const { min, max } = group\n if (!Number.isInteger(min) || min < 0) return `“${group.name}” needs a minimum of 0 or more`\n if (!Number.isInteger(max) || max < 1 || max > options.length) {\n return `“${group.name}” allows 1 to ${options.length} choices`\n }\n if (min > max) return `“${group.name}” requires more choices than it allows`\n }\n return null\n}\n\n/** How a variant is named in a choice's price list, in the editor and in an import file. */\nexport function variantPriceLabel(variant: { options?: Record<string, string> }): string {\n const values = Object.values(variant.options ?? {}).filter(Boolean)\n return values.length ? values.join(' / ') : 'Default'\n}\n\n/** The product's groups, or none when they are missing or malformed. */\nexport function productModifierGroups(product: {\n modifierGroups?: unknown\n}): ProductModifierGroup[] {\n const groups = product?.modifierGroups\n if (!Array.isArray(groups) || modifierGroupsProblem(groups)) return []\n return groups as ProductModifierGroup[]\n}\n\n/** Whether a group must be answered before the item can be added. */\nexport function modifierGroupRequired(group: ProductModifierGroup): boolean {\n return group.min > 0\n}\n\n/**\n * The groups the product's page on the website offers (AGL-4100): those\n * switched to \"Show on the website\". A register-only group is never sent to\n * a shopper, never asked of one and never priced on an online order.\n */\nexport function websiteModifierGroups(product: { modifierGroups?: unknown }): ProductModifierGroup[] {\n return productModifierGroups(product).filter((group) => group.online === true)\n}\n\n/** Whether the website must ask a shopper a choice before the item goes in a cart. */\nexport function websiteModifiersRequired(product: { modifierGroups?: unknown }): boolean {\n return websiteModifierGroups(product).some(modifierGroupRequired)\n}\n\n/**\n * What one choice adds to one unit of the picked variant (AGL-4100): its\n * price on that variant where it has one, else its own price.\n */\nexport function modifierOptionPriceCents(\n option: Pick<ProductModifierOption, 'priceCents' | 'priceCentsByVariant'>,\n variantId?: string | null,\n): number {\n const byVariant = variantId ? option.priceCentsByVariant?.[variantId] : undefined\n return typeof byVariant === 'number' && Number.isFinite(byVariant) ? byVariant : option.priceCents\n}\n\n/** A line's chosen modifiers, priced. */\nexport interface ResolvedLineModifiers {\n ok: boolean\n /** The chosen modifiers, in group order; empty when not `ok`. */\n modifiers: OrderLineModifier[]\n /** What they add to one unit, in cents. */\n extraCents: number\n /** What to fix, when not `ok`. */\n error?: string\n}\n\n/** The picks a request names, as ids only, bounded; nothing for a value that is not a list. */\nexport function modifierSelectionFrom(raw: unknown): ModifierSelection[] {\n return (Array.isArray(raw) ? raw : [])\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map((entry: any): ModifierSelection => {\n const pick: ModifierSelection = {\n groupId: String(entry?.groupId ?? ''),\n optionId: String(entry?.optionId ?? ''),\n }\n // A write-in's answer, bounded here and checked against its group when priced.\n const text = cleanWriteIn(entry?.text)\n if (text) pick.text = text\n return pick\n })\n}\n\n/** A pick as the order keeps it: a choice, or a write-in with its answer. */\nfunction soldModifier(\n group: ProductModifierGroup,\n option: ProductModifierOption,\n variantId: string | null | undefined,\n text: string | undefined,\n): OrderLineModifier {\n return {\n groupId: group.id,\n optionId: option.id,\n group: group.name,\n name: option.name,\n priceCents: modifierOptionPriceCents(option, variantId),\n ...(text ? { text } : {}),\n ...(group.nameOnOrder === true ? { nameOnOrder: true } : {}),\n }\n}\n\n/**\n * Prices a line's chosen modifiers from the PRODUCT, in group order, and\n * checks every group's minimum and maximum. Unknown ids, a repeated choice\n * and a group answered past its maximum are refused with what to fix.\n *\n * `variantId` is the variant the line sells (AGL-4100): a choice priced by\n * variant adds its price on that one. Without it every choice adds its own\n * `priceCents`, as it always did.\n */\nexport function resolveLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n const refuse = (error: string): ResolvedLineModifiers => ({\n ok: false,\n modifiers: [],\n extraCents: 0,\n error,\n })\n const groups = productModifierGroups(product)\n const picks = modifierSelectionFrom(raw)\n const seen = new Set<string>()\n for (const pick of picks) {\n const key = `${pick.groupId}:${pick.optionId}`\n if (seen.has(key)) return refuse(`A choice on ${product.name} was picked twice.`)\n seen.add(key)\n const group = groups.find((entry) => entry.id === pick.groupId)\n if (!group || !group.options.some((option) => option.id === pick.optionId)) {\n return refuse(`A choice on ${product.name} is no longer offered. Remove it and add it again.`)\n }\n }\n const modifiers: OrderLineModifier[] = []\n for (const group of groups) {\n if (modifierGroupIsWriteIn(group)) {\n // A write-in (write-ins): its answer is checked, cleaned and kept.\n const option = group.options[0]\n const pick = picks.find((entry) => entry.groupId === group.id && entry.optionId === option.id)\n const problem = writeInProblem(group, pick?.text)\n if (problem) return refuse(`${problem} (${product.name})`)\n const text = cleanWriteIn(pick?.text, group)\n if (!text) {\n if (group.min > 0) return refuse(`Fill in ${group.name.toLowerCase()} for ${product.name}.`)\n continue\n }\n modifiers.push(soldModifier(group, option, variantId, text))\n continue\n }\n const chosen = group.options.filter((option) =>\n picks.some((pick) => pick.groupId === group.id && pick.optionId === option.id),\n )\n if (chosen.length < group.min) {\n return refuse(`Choose ${group.name.toLowerCase()} for ${product.name}.`)\n }\n if (chosen.length > group.max) {\n return refuse(`Choose at most ${group.max} for ${group.name.toLowerCase()} on ${product.name}.`)\n }\n for (const option of chosen) modifiers.push(soldModifier(group, option, variantId, undefined))\n }\n return {\n ok: true,\n modifiers,\n extraCents: modifiers.reduce((sum, modifier) => sum + modifier.priceCents, 0),\n }\n}\n\n/**\n * {@link resolveLineModifiers} for a sale made online (AGL-4100): only the\n * groups shown on the website are offered, asked or priced. A register-only\n * group, required or not, is not the shopper's to answer.\n */\nexport function resolveWebsiteLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n return resolveLineModifiers(\n { name: product.name, modifierGroups: websiteModifierGroups(product) },\n raw,\n variantId,\n )\n}\n\n/**\n * The modifiers a PAID line names, for its order record (AGL-4100): every\n * pick the product still offers, in group order, priced as it is now, with no\n * minimum or maximum asked. The money was taken when the sale was priced;\n * a choice the merchant removed since is left off the record, never a reason\n * to lose the order.\n */\nexport function soldLineModifiers(\n product: { modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): OrderLineModifier[] {\n const picks = modifierSelectionFrom(raw)\n const modifiers: OrderLineModifier[] = []\n for (const group of productModifierGroups(product)) {\n const writeIn = modifierGroupIsWriteIn(group)\n for (const option of group.options) {\n const pick = picks.find((entry) => entry.groupId === group.id && entry.optionId === option.id)\n if (!pick) continue\n const text = writeIn ? cleanWriteIn(pick.text, group) : undefined\n if (writeIn && !text) continue\n modifiers.push(soldModifier(group, option, variantId, text))\n }\n }\n return modifiers\n}\n\n/**\n * What a shopper is told about a cart line whose add-ons no longer answer\n * the product (AGL-4100): the resolver's reason, and how to put it right.\n */\nexport function cartLineModifierProblem(error: string | undefined): string {\n const reason = String(error ?? '').trim() || 'The choices on this item have changed.'\n return /Remove it and add it again/.test(reason)\n ? reason\n : `${reason} Remove it and add it again from its page.`\n}\n\n/** The picks a priced line keeps: ids only, in the product's group order. */\nexport function modifierSelectionOf(\n modifiers: readonly (Pick<OrderLineModifier, 'groupId' | 'optionId'> & { text?: string })[],\n): ModifierSelection[] {\n return modifiers.map((modifier) => ({\n groupId: modifier.groupId,\n optionId: modifier.optionId,\n ...(modifier.text ? { text: modifier.text } : {}),\n }))\n}\n\n/**\n * The picks as one metadata value (AGL-4100), for a payment processor that\n * holds strings only: `[[\"group\",\"option\"],…]`. Empty for no picks.\n */\nexport function encodeModifierSelection(selection: readonly ModifierSelection[] | undefined): string {\n if (!selection?.length) return ''\n // A write-in's answer rides as a third entry: `[[\"group\",\"option\",\"For Sam\"],…]`.\n return JSON.stringify(\n selection.map((pick) => (pick.text ? [pick.groupId, pick.optionId, pick.text] : [pick.groupId, pick.optionId])),\n )\n}\n\n/** {@link encodeModifierSelection} read back; nothing for a value it did not write. */\nexport function decodeModifierSelection(value: unknown): ModifierSelection[] {\n if (typeof value !== 'string' || !value) return []\n try {\n const parsed: unknown = JSON.parse(value)\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter(\n (pair): pair is [string, string, unknown?] =>\n Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string',\n )\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map(([groupId, optionId, typed]) => {\n const text = cleanWriteIn(typed)\n return text ? { groupId, optionId, text } : { groupId, optionId }\n })\n } catch {\n return []\n }\n}\n\n/** A modifier as {@link modifierLineText} reads it. */\nexport type PrintedModifier = Pick<OrderLineModifier, 'name'> &\n Partial<Pick<OrderLineModifier, 'group' | 'text' | 'nameOnOrder'>>\n\n/**\n * How one modifier prints on a line: its name (`Oat milk`), its group and\n * name when the group asks for it (`Size: M`), or a write-in's name\n * and answer (`Engraving: For Sam`).\n */\nexport function modifierLineText(modifier: PrintedModifier): string {\n if (modifier.text) return `${modifier.group || modifier.name}: ${modifier.text}`\n if (modifier.nameOnOrder && modifier.group) return `${modifier.group}: ${modifier.name}`\n return modifier.name\n}\n\n/** The label a line prints: the variant, then each modifier (`Large / Oat milk, Extra shot`). */\nexport function lineLabelWithModifiers(variantLabel: string | undefined, modifiers: readonly PrintedModifier[]): string {\n const added = modifiers.map(modifierLineText).join(', ')\n return [variantLabel, added].filter(Boolean).join(' / ')\n}\n\n/** Two lines merge only when they are the same item with the same choices. */\nexport function modifierSelectionKey(selection: readonly ModifierSelection[] | undefined): string {\n return [...(selection ?? [])]\n .map((pick) => (pick.text ? `${pick.groupId}:${pick.optionId}=${pick.text}` : `${pick.groupId}:${pick.optionId}`))\n .sort()\n .join('|')\n}\n"],"names":["POS_MAX_MODIFIER_GROUPS","POS_MAX_MODIFIER_OPTIONS","POS_MAX_MODIFIER_PRICE_CENTS","MAX_WRITE_IN_LENGTH","DEFAULT_WRITE_IN_LENGTH","WRITE_IN_INPUT_BOUND","modifierGroupIsWriteIn","group","kind","writeInMaxLength","length","maxLength","Number","isInteger","cleanWriteIn","raw","limit","flat","replace","trim","Array","from","slice","join","writeInProblem","typed","name","digitsOnly","test","modifierOptionIsCombo","option","isArray","includes","every","item","modifierPriceIsValid","price","modifierGroupsProblem","groups","groupIds","Set","id","has","add","String","options","max","min","nameOnOrder","optionIds","priceCents","byVariant","priceCentsByVariant","Object","values","some","cents","online","variantPriceLabel","variant","filter","Boolean","productModifierGroups","product","modifierGroups","modifierGroupRequired","websiteModifierGroups","websiteModifiersRequired","modifierOptionPriceCents","variantId","undefined","isFinite","modifierSelectionFrom","map","entry","pick","groupId","optionId","text","soldModifier","resolveLineModifiers","refuse","error","ok","modifiers","extraCents","picks","seen","key","find","problem","toLowerCase","push","chosen","reduce","sum","modifier","resolveWebsiteLineModifiers","soldLineModifiers","writeIn","cartLineModifierProblem","reason","modifierSelectionOf","encodeModifierSelection","selection","JSON","stringify","decodeModifierSelection","value","parsed","parse","pair","modifierLineText","lineLabelWithModifiers","variantLabel","added","modifierSelectionKey","sort"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAqC2C,GAE3C,mFAAmF;AAiFnF,OAAO,MAAMA,0BAA0B,GAAE;AACzC,OAAO,MAAMC,2BAA2B,GAAE;AAC1C,yEAAyE,GACzE,OAAO,MAAMC,+BAA+B,OAAO;AACnD,wFAAwF,GACxF,OAAO,MAAMC,sBAAsB,GAAE;AACrC,qDAAqD,GACrD,OAAO,MAAMC,0BAA0B,GAAE;AACzC,sEAAsE,GACtE,MAAMC,uBAAuB;AAE7B,qDAAqD,GACrD,OAAO,SAASC,uBA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ACF;AAMA;;;;CAIC,GACD,OAAO,SAASmC,iBAAiBhB,QAAyB;IACxD,IAAIA,SAASlB,IAAI,EAAE,OAAO,GAAGkB,SAASzF,KAAK,IAAIyF,SAAStE,IAAI,CAAC,EAAE,EAAEsE,SAASlB,IAAI,EAAE;IAChF,IAAIkB,SAAShD,WAAW,IAAIgD,SAASzF,KAAK,EAAE,OAAO,GAAGyF,SAASzF,KAAK,CAAC,EAAE,EAAEyF,SAAStE,IAAI,EAAE;IACxF,OAAOsE,SAAStE,IAAI;AACtB;AAEA,+FAA+F,GAC/F,OAAO,SAASuF,uBAAuBC,YAAgC,EAAE9B,SAAqC;IAC5G,MAAM+B,QAAQ/B,UAAUX,GAAG,CAACuC,kBAAkBzF,IAAI,CAAC;IACnD,OAAO;QAAC2F;QAAcC;KAAM,CAACvD,MAAM,CAACC,SAAStC,IAAI,CAAC;AACpD;AAEA,4EAA4E,GAC5E,OAAO,SAAS6F,qBAAqBZ,SAAmD;IACtF,OAAO;WAAKA,oBAAAA,YAAa,EAAE;KAAE,CAC1B/B,GAAG,CAAC,CAACE,OAAUA,KAAKG,IAAI,GAAG,GAAGH,KAAKC,OAAO,CAAC,CAAC,EAAED,KAAKE,QAAQ,CAAC,CAAC,EAAEF,KAAKG,IAAI,EAAE,GAAG,GAAGH,KAAKC,OAAO,CAAC,CAAC,EAAED,KAAKE,QAAQ,EAAE,EAC/GwC,IAAI,GACJ9F,IAAI,CAAC;AACV"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/product-modifiers.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 * REGISTER MODIFIERS AND QUICK KEYS (AGL-3607).\n *\n * A modifier is a choice added to an item as it is rung up — \"Oat milk\",\n * \"Extra shot +$0.75\", \"No onions\" — that is not a stocked variant. Groups\n * live on the product (`modifierGroups`); the register sends the chosen\n * option ids with each line and the SERVER prices them from the product\n * document, so a register never names what a modifier costs.\n *\n * A chosen modifier is folded into the line's `variantLabel` as well as kept\n * structured in `modifiers`: every receipt, email, order view and export\n * already prints the label, so the choice reaches all of them without each\n * learning a new field.\n *\n * ADD-ONS ON THE WEBSITE (AGL-4100). A group switched to \"Show on the\n * website\" (`online`) is offered on the product's page too, and a cart line,\n * Buy now and the order carry its picks the same way: ids from the shopper,\n * prices from the product. A choice may cost more on one variant than\n * another (`priceCentsByVariant`), which is how one page sells a canopy whose\n * walls cost more at a larger size without a variant for every combination.\n *\n * THE PRODUCT BUILDER (AGL-4205). A choice may carry a picture and a short\n * note, which a product page set to show its choices as picture cards draws\n * on the choice's card. A choice that lists what it `includes` is a combo:\n * one price for a bundle (\"Weekend kit: 4 walls, 4 weights, a bag\"), and the\n * card folds its contents out. Display only: a combo is priced and sold as\n * the one choice it is.\n *\n * WRITE-INS (write-ins). A group of `kind: 'text'` asks the\n * shopper to type an answer instead of picking one: the name and number\n * printed on a sign, an engraving, a cake message. It holds exactly one option, which carries what a\n * filled answer adds to the price (by variant too) and its helper note, so\n * pricing, ids and every path that carries picks stay the same; the pick\n * adds the `text`. The answer is checked and cleaned on the server like any\n * pick ({@link cleanWriteIn}) and prints on the line as \"Engraving: For\n * Sam\". With write-ins and required size groups, one variant sells a set\n * of pieces in any combination of sizes, with no cap on combinations.\n *=========================================*/\n\n/** One choice in a modifier group. `priceCents` is added to the item, 0 for free. */\nexport interface ProductModifierOption {\n id: string\n name: string\n priceCents: number\n /**\n * What the choice adds on one variant, keyed by variant id (AGL-4100):\n * walls cost more on a larger canopy. A variant not listed pays\n * `priceCents`. Read through {@link modifierOptionPriceCents}.\n */\n priceCentsByVariant?: Record<string, number>\n /**\n * What the choice adds in another currency the store sells in (AGL-4248),\n * minor units keyed by ISO code. A currency not listed converts.\n */\n fixedPriceCents?: Record<string, number>\n /** A picture of the choice, from the media library, for its card (AGL-4205). */\n imageUrl?: string\n /** A short line under the choice on its card (AGL-4205): \"Blocks wind on one side\". */\n note?: string\n /**\n * What a combo holds (AGL-4205), one item per entry: \"Full wall ×2\". A\n * choice with any is shown as a combo whose contents fold out.\n */\n includes?: string[]\n}\n\n/**\n * A set of choices offered together (\"Milk\", \"Add-ons\"). `min` of 1 or more\n * makes it required; `max` caps how many can be picked (1 = pick one).\n */\nexport interface ProductModifierGroup {\n id: string\n name: string\n min: number\n max: number\n options: ProductModifierOption[]\n /**\n * `'text'` makes the group a write-in: the shopper types the answer (a\n * name, a number) into one field. Absent is a group of choices. A write-in\n * holds exactly one option, which names it and prices it.\n */\n kind?: ProductModifierGroupKind\n /** A write-in's longest answer, 1 to {@link MAX_WRITE_IN_LENGTH}; {@link DEFAULT_WRITE_IN_LENGTH} when absent. */\n maxLength?: number\n /** A write-in that takes digits only, such as a number. */\n digitsOnly?: boolean\n /**\n * Print the group's name before the choice on the order, receipt and\n * emails (\"Size: M\"), for choices that do not say what they are on\n * their own. A write-in always prints its name.\n */\n nameOnOrder?: boolean\n /**\n * Offered on the product's page on the website as well as at the register\n * (AGL-4100), \"Show on the website\". Absent reads as register only, so a\n * group made before the switch changes nothing on a live store; the\n * console makes new groups with it on.\n */\n online?: boolean\n}\n\n/** What a group is: choices to pick from, or a write-in the shopper types. */\nexport type ProductModifierGroupKind = 'text'\n\n/** A modifier as the order line keeps it: names and price as sold. */\nexport interface OrderLineModifier {\n groupId: string\n optionId: string\n group: string\n name: string\n priceCents: number\n /** A write-in's answer as sold, such as the text to engrave. */\n text?: string\n /** The group's name prints before the choice on the line (\"Size: M\"). */\n nameOnOrder?: boolean\n}\n\n/** What the register sends for a line: the option ids it picked, nothing priced. */\nexport interface ModifierSelection {\n groupId: string\n optionId: string\n /** A write-in's answer, as typed; the server cleans and checks it. */\n text?: string\n}\n\nexport const POS_MAX_MODIFIER_GROUPS = 10\nexport const POS_MAX_MODIFIER_OPTIONS = 20\n/** $1,000 on one modifier: anything larger is a product, not an add-on. */\nexport const POS_MAX_MODIFIER_PRICE_CENTS = 100_000\n/** The longest answer a write-in can take: a name or a short message fits well inside. */\nexport const MAX_WRITE_IN_LENGTH = 40\n/** A write-in's length when the merchant sets none. */\nexport const DEFAULT_WRITE_IN_LENGTH = 20\n/** How much of a typed answer is carried before its group checks it. */\nconst WRITE_IN_INPUT_BOUND = 200\n\n/** Whether a group is a write-in the shopper types. */\nexport function modifierGroupIsWriteIn(group: Pick<ProductModifierGroup, 'kind'> | null | undefined): boolean {\n return group?.kind === 'text'\n}\n\n/** A write-in's longest answer. */\nexport function writeInMaxLength(group: Pick<ProductModifierGroup, 'maxLength'>): number {\n const length = group.maxLength\n return typeof length === 'number' && Number.isInteger(length) && length >= 1 && length <= MAX_WRITE_IN_LENGTH\n ? length\n : DEFAULT_WRITE_IN_LENGTH\n}\n\n/**\n * A write-in's answer cleaned for the order: control characters and runs of\n * spaces gone, trimmed, cut at the group's length. Empty when nothing is left.\n * Without a group the answer is only bounded, so a too-long one still reaches\n * the check that names it.\n */\nexport function cleanWriteIn(raw: unknown, group?: Pick<ProductModifierGroup, 'maxLength'> | null): string {\n if (typeof raw !== 'string') return ''\n const limit = group ? writeInMaxLength(group) : WRITE_IN_INPUT_BOUND\n const flat = raw\n // eslint-disable-next-line no-control-regex\n .replace(/[\\u0000-\\u001f\\u007f-\\u009f\\u2028\\u2029]/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim()\n return Array.from(flat).slice(0, limit).join('').trim()\n}\n\n/** Why a write-in's answer cannot be sold, or null when it can. An empty answer is the minimum's business. */\nexport function writeInProblem(\n group: Pick<ProductModifierGroup, 'name' | 'maxLength' | 'digitsOnly'>,\n raw: unknown,\n): string | null {\n const typed = cleanWriteIn(raw)\n if (!typed) return null\n const limit = writeInMaxLength(group)\n if (Array.from(typed).length > limit) return `${group.name} takes up to ${limit} characters.`\n if (group.digitsOnly && !/^[0-9]+$/.test(typed)) return `${group.name} takes numbers only.`\n return null\n}\n/** Whether a choice is a combo: it lists what it includes (AGL-4205). */\nexport function modifierOptionIsCombo(option: Pick<ProductModifierOption, 'includes'>): boolean {\n return (\n Array.isArray(option.includes) &&\n option.includes.length > 0 &&\n option.includes.every((item) => typeof item === 'string')\n )\n}\n\nfunction modifierPriceIsValid(price: unknown): boolean {\n return (\n typeof price === 'number' &&\n Number.isInteger(price) &&\n price >= 0 &&\n price <= POS_MAX_MODIFIER_PRICE_CENTS\n )\n}\n\n/** Why a product's modifier groups cannot be saved, or null when they can. */\nexport function modifierGroupsProblem(groups: unknown): string | null {\n if (groups == null) return null\n if (!Array.isArray(groups)) return 'Modifiers must be a list'\n if (groups.length > POS_MAX_MODIFIER_GROUPS) {\n return `At most ${POS_MAX_MODIFIER_GROUPS} modifier groups per product`\n }\n const groupIds = new Set<string>()\n for (const group of groups as ProductModifierGroup[]) {\n if (!group?.id || groupIds.has(group.id)) return 'Modifier groups need unique ids'\n groupIds.add(group.id)\n if (!String(group.name ?? '').trim()) return 'Name every modifier group'\n const options = Array.isArray(group.options) ? group.options : []\n if (group.kind != null && group.kind !== 'text') return `“${group.name}” is a list of choices or a write-in`\n if (group.kind === 'text') {\n if (options.length !== 1) return `“${group.name}” is a write-in and holds one field`\n if (group.max !== 1 || (group.min !== 0 && group.min !== 1)) {\n return `“${group.name}” is a write-in: required or not, one answer`\n }\n if (\n group.maxLength != null &&\n (!Number.isInteger(group.maxLength) || group.maxLength < 1 || group.maxLength > MAX_WRITE_IN_LENGTH)\n ) {\n return `“${group.name}” takes 1 to ${MAX_WRITE_IN_LENGTH} characters`\n }\n if (group.digitsOnly != null && typeof group.digitsOnly !== 'boolean') {\n return `“${group.name}” takes numbers only or any text`\n }\n }\n if (group.nameOnOrder != null && typeof group.nameOnOrder !== 'boolean') {\n return `“${group.name}” prints its name on the order or not`\n }\n if (options.length === 0) return `Add a choice to “${group.name}”`\n if (options.length > POS_MAX_MODIFIER_OPTIONS) {\n return `“${group.name}” has more than ${POS_MAX_MODIFIER_OPTIONS} choices`\n }\n const optionIds = new Set<string>()\n for (const option of options) {\n if (!option?.id || optionIds.has(option.id)) return 'Modifier choices need unique ids'\n optionIds.add(option.id)\n if (!String(option.name ?? '').trim()) return `Name every choice in “${group.name}”`\n const price = option.priceCents\n if (!modifierPriceIsValid(price)) {\n return `“${option.name}” needs a price of $0 to $1,000`\n }\n const byVariant = option.priceCentsByVariant\n if (byVariant != null) {\n if (typeof byVariant !== 'object' || Array.isArray(byVariant)) {\n return `“${option.name}” has prices that are not a list by option`\n }\n if (Object.values(byVariant).some((cents) => !modifierPriceIsValid(cents))) {\n return `“${option.name}” needs a price of $0 to $1,000 for each option it is priced by`\n }\n }\n }\n if (group.online != null && typeof group.online !== 'boolean') {\n return `“${group.name}” is shown on the website or not`\n }\n const { min, max } = group\n if (!Number.isInteger(min) || min < 0) return `“${group.name}” needs a minimum of 0 or more`\n if (!Number.isInteger(max) || max < 1 || max > options.length) {\n return `“${group.name}” allows 1 to ${options.length} choices`\n }\n if (min > max) return `“${group.name}” requires more choices than it allows`\n }\n return null\n}\n\n/** How a variant is named in a choice's price list, in the editor and in an import file. */\nexport function variantPriceLabel(variant: { options?: Record<string, string> }): string {\n const values = Object.values(variant.options ?? {}).filter(Boolean)\n return values.length ? values.join(' / ') : 'Default'\n}\n\n/** The product's groups, or none when they are missing or malformed. */\nexport function productModifierGroups(product: {\n modifierGroups?: unknown\n}): ProductModifierGroup[] {\n const groups = product?.modifierGroups\n if (!Array.isArray(groups) || modifierGroupsProblem(groups)) return []\n return groups as ProductModifierGroup[]\n}\n\n/** Whether a group must be answered before the item can be added. */\nexport function modifierGroupRequired(group: ProductModifierGroup): boolean {\n return group.min > 0\n}\n\n/**\n * The groups the product's page on the website offers (AGL-4100): those\n * switched to \"Show on the website\". A register-only group is never sent to\n * a shopper, never asked of one and never priced on an online order.\n */\nexport function websiteModifierGroups(product: { modifierGroups?: unknown }): ProductModifierGroup[] {\n return productModifierGroups(product).filter((group) => group.online === true)\n}\n\n/** Whether the website must ask a shopper a choice before the item goes in a cart. */\nexport function websiteModifiersRequired(product: { modifierGroups?: unknown }): boolean {\n return websiteModifierGroups(product).some(modifierGroupRequired)\n}\n\n/**\n * What one choice adds to one unit of the picked variant (AGL-4100): its\n * price on that variant where it has one, else its own price.\n */\nexport function modifierOptionPriceCents(\n option: Pick<ProductModifierOption, 'priceCents' | 'priceCentsByVariant'>,\n variantId?: string | null,\n): number {\n const byVariant = variantId ? option.priceCentsByVariant?.[variantId] : undefined\n return typeof byVariant === 'number' && Number.isFinite(byVariant) ? byVariant : option.priceCents\n}\n\n/** A line's chosen modifiers, priced. */\nexport interface ResolvedLineModifiers {\n ok: boolean\n /** The chosen modifiers, in group order; empty when not `ok`. */\n modifiers: OrderLineModifier[]\n /** What they add to one unit, in cents. */\n extraCents: number\n /** What to fix, when not `ok`. */\n error?: string\n}\n\n/** The picks a request names, as ids only, bounded; nothing for a value that is not a list. */\nexport function modifierSelectionFrom(raw: unknown): ModifierSelection[] {\n return (Array.isArray(raw) ? raw : [])\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map((entry: any): ModifierSelection => {\n const pick: ModifierSelection = {\n groupId: String(entry?.groupId ?? ''),\n optionId: String(entry?.optionId ?? ''),\n }\n // A write-in's answer, bounded here and checked against its group when priced.\n const text = cleanWriteIn(entry?.text)\n if (text) pick.text = text\n return pick\n })\n}\n\n/** A pick as the order keeps it: a choice, or a write-in with its answer. */\nfunction soldModifier(\n group: ProductModifierGroup,\n option: ProductModifierOption,\n variantId: string | null | undefined,\n text: string | undefined,\n): OrderLineModifier {\n return {\n groupId: group.id,\n optionId: option.id,\n group: group.name,\n name: option.name,\n priceCents: modifierOptionPriceCents(option, variantId),\n ...(text ? { text } : {}),\n ...(group.nameOnOrder === true ? { nameOnOrder: true } : {}),\n }\n}\n\n/**\n * Prices a line's chosen modifiers from the PRODUCT, in group order, and\n * checks every group's minimum and maximum. Unknown ids, a repeated choice\n * and a group answered past its maximum are refused with what to fix.\n *\n * `variantId` is the variant the line sells (AGL-4100): a choice priced by\n * variant adds its price on that one. Without it every choice adds its own\n * `priceCents`, as it always did.\n */\nexport function resolveLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n const refuse = (error: string): ResolvedLineModifiers => ({\n ok: false,\n modifiers: [],\n extraCents: 0,\n error,\n })\n const groups = productModifierGroups(product)\n const picks = modifierSelectionFrom(raw)\n const seen = new Set<string>()\n for (const pick of picks) {\n const key = `${pick.groupId}:${pick.optionId}`\n if (seen.has(key)) return refuse(`A choice on ${product.name} was picked twice.`)\n seen.add(key)\n const group = groups.find((entry) => entry.id === pick.groupId)\n if (!group || !group.options.some((option) => option.id === pick.optionId)) {\n return refuse(`A choice on ${product.name} is no longer offered. Remove it and add it again.`)\n }\n }\n const modifiers: OrderLineModifier[] = []\n for (const group of groups) {\n if (modifierGroupIsWriteIn(group)) {\n // A write-in (write-ins): its answer is checked, cleaned and kept.\n const option = group.options[0]\n const pick = picks.find((entry) => entry.groupId === group.id && entry.optionId === option.id)\n const problem = writeInProblem(group, pick?.text)\n if (problem) return refuse(`${problem} (${product.name})`)\n const text = cleanWriteIn(pick?.text, group)\n if (!text) {\n if (group.min > 0) return refuse(`Fill in ${group.name.toLowerCase()} for ${product.name}.`)\n continue\n }\n modifiers.push(soldModifier(group, option, variantId, text))\n continue\n }\n const chosen = group.options.filter((option) =>\n picks.some((pick) => pick.groupId === group.id && pick.optionId === option.id),\n )\n if (chosen.length < group.min) {\n return refuse(`Choose ${group.name.toLowerCase()} for ${product.name}.`)\n }\n if (chosen.length > group.max) {\n return refuse(`Choose at most ${group.max} for ${group.name.toLowerCase()} on ${product.name}.`)\n }\n for (const option of chosen) modifiers.push(soldModifier(group, option, variantId, undefined))\n }\n return {\n ok: true,\n modifiers,\n extraCents: modifiers.reduce((sum, modifier) => sum + modifier.priceCents, 0),\n }\n}\n\n/**\n * {@link resolveLineModifiers} for a sale made online (AGL-4100): only the\n * groups shown on the website are offered, asked or priced. A register-only\n * group, required or not, is not the shopper's to answer.\n */\nexport function resolveWebsiteLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n return resolveLineModifiers(\n { name: product.name, modifierGroups: websiteModifierGroups(product) },\n raw,\n variantId,\n )\n}\n\n/**\n * The modifiers a PAID line names, for its order record (AGL-4100): every\n * pick the product still offers, in group order, priced as it is now, with no\n * minimum or maximum asked. The money was taken when the sale was priced;\n * a choice the merchant removed since is left off the record, never a reason\n * to lose the order.\n */\nexport function soldLineModifiers(\n product: { modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): OrderLineModifier[] {\n const picks = modifierSelectionFrom(raw)\n const modifiers: OrderLineModifier[] = []\n for (const group of productModifierGroups(product)) {\n const writeIn = modifierGroupIsWriteIn(group)\n for (const option of group.options) {\n const pick = picks.find((entry) => entry.groupId === group.id && entry.optionId === option.id)\n if (!pick) continue\n const text = writeIn ? cleanWriteIn(pick.text, group) : undefined\n if (writeIn && !text) continue\n modifiers.push(soldModifier(group, option, variantId, text))\n }\n }\n return modifiers\n}\n\n/**\n * What a shopper is told about a cart line whose add-ons no longer answer\n * the product (AGL-4100): the resolver's reason, and how to put it right.\n */\nexport function cartLineModifierProblem(error: string | undefined): string {\n const reason = String(error ?? '').trim() || 'The choices on this item have changed.'\n return /Remove it and add it again/.test(reason)\n ? reason\n : `${reason} Remove it and add it again from its page.`\n}\n\n/** The picks a priced line keeps: ids only, in the product's group order. */\nexport function modifierSelectionOf(\n modifiers: readonly (Pick<OrderLineModifier, 'groupId' | 'optionId'> & { text?: string })[],\n): ModifierSelection[] {\n return modifiers.map((modifier) => ({\n groupId: modifier.groupId,\n optionId: modifier.optionId,\n ...(modifier.text ? { text: modifier.text } : {}),\n }))\n}\n\n/**\n * The picks as one metadata value (AGL-4100), for a payment processor that\n * holds strings only: `[[\"group\",\"option\"],…]`. Empty for no picks.\n */\nexport function encodeModifierSelection(selection: readonly ModifierSelection[] | undefined): string {\n if (!selection?.length) return ''\n // A write-in's answer rides as a third entry: `[[\"group\",\"option\",\"For Sam\"],…]`.\n return JSON.stringify(\n selection.map((pick) => (pick.text ? [pick.groupId, pick.optionId, pick.text] : [pick.groupId, pick.optionId])),\n )\n}\n\n/** {@link encodeModifierSelection} read back; nothing for a value it did not write. */\nexport function decodeModifierSelection(value: unknown): ModifierSelection[] {\n if (typeof value !== 'string' || !value) return []\n try {\n const parsed: unknown = JSON.parse(value)\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter(\n (pair): pair is [string, string, unknown?] =>\n Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string',\n )\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map(([groupId, optionId, typed]) => {\n const text = cleanWriteIn(typed)\n return text ? { groupId, optionId, text } : { groupId, optionId }\n })\n } catch {\n return []\n }\n}\n\n/** A modifier as {@link modifierLineText} reads it. */\nexport type PrintedModifier = Pick<OrderLineModifier, 'name'> &\n Partial<Pick<OrderLineModifier, 'group' | 'text' | 'nameOnOrder'>>\n\n/**\n * How one modifier prints on a line: its name (`Oat milk`), its group and\n * name when the group asks for it (`Size: M`), or a write-in's name\n * and answer (`Engraving: For Sam`).\n */\nexport function modifierLineText(modifier: PrintedModifier): string {\n if (modifier.text) return `${modifier.group || modifier.name}: ${modifier.text}`\n if (modifier.nameOnOrder && modifier.group) return `${modifier.group}: ${modifier.name}`\n return modifier.name\n}\n\n/** The label a line prints: the variant, then each modifier (`Large / Oat milk, Extra shot`). */\nexport function lineLabelWithModifiers(variantLabel: string | undefined, modifiers: readonly PrintedModifier[]): string {\n const added = modifiers.map(modifierLineText).join(', ')\n return [variantLabel, added].filter(Boolean).join(' / ')\n}\n\n/** Two lines merge only when they are the same item with the same choices. */\nexport function modifierSelectionKey(selection: readonly ModifierSelection[] | undefined): string {\n return [...(selection ?? [])]\n .map((pick) => (pick.text ? `${pick.groupId}:${pick.optionId}=${pick.text}` : `${pick.groupId}:${pick.optionId}`))\n .sort()\n .join('|')\n}\n"],"names":["POS_MAX_MODIFIER_GROUPS","POS_MAX_MODIFIER_OPTIONS","POS_MAX_MODIFIER_PRICE_CENTS","MAX_WRITE_IN_LENGTH","DEFAULT_WRITE_IN_LENGTH","WRITE_IN_INPUT_BOUND","modifierGroupIsWriteIn","group","kind","writeInMaxLength","length","maxLength","Number","isInteger","cleanWriteIn","raw","limit","flat","replace","trim","Array","from","slice","join","writeInProblem","typed","name","digitsOnly","test","modifierOptionIsCombo","option","isArray","includes","every","item","modifierPriceIsValid","price","modifierGroupsProblem","groups","groupIds","Set","id","has","add","String","options","max","min","nameOnOrder","optionIds","priceCents","byVariant","priceCentsByVariant","Object","values","some","cents","online","variantPriceLabel","variant","filter","Boolean","productModifierGroups","product","modifierGroups","modifierGroupRequired","websiteModifierGroups","websiteModifiersRequired","modifierOptionPriceCents","variantId","undefined","isFinite","modifierSelectionFrom","map","entry","pick","groupId","optionId","text","soldModifier","resolveLineModifiers","refuse","error","ok","modifiers","extraCents","picks","seen","key","find","problem","toLowerCase","push","chosen","reduce","sum","modifier","resolveWebsiteLineModifiers","soldLineModifiers","writeIn","cartLineModifierProblem","reason","modifierSelectionOf","encodeModifierSelection","selection","JSON","stringify","decodeModifierSelection","value","parsed","parse","pair","modifierLineText","lineLabelWithModifiers","variantLabel","added","modifierSelectionKey","sort"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAqC2C,GAE3C,mFAAmF;AAsFnF,OAAO,MAAMA,0BAA0B,GAAE;AACzC,OAAO,MAAM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CAAC,GAAGtB,0BAA0BC,0BACnCwE,GAAG,CAAC,CAAC,CAACG,SAASC,UAAUpD,MAAM;YAC9B,MAAMqD,OAAOhE,aAAaW;YAC1B,OAAOqD,OAAO;gBAAEF;gBAASC;gBAAUC;YAAK,IAAI;gBAAEF;gBAASC;YAAS;QAClE;IACJ,EAAE,eAAM;QACN,OAAO,EAAE;IACX;AACF;AAMA;;;;CAIC,GACD,OAAO,SAASmC,iBAAiBhB,QAAyB;IACxD,IAAIA,SAASlB,IAAI,EAAE,OAAO,GAAGkB,SAASzF,KAAK,IAAIyF,SAAStE,IAAI,CAAC,EAAE,EAAEsE,SAASlB,IAAI,EAAE;IAChF,IAAIkB,SAAShD,WAAW,IAAIgD,SAASzF,KAAK,EAAE,OAAO,GAAGyF,SAASzF,KAAK,CAAC,EAAE,EAAEyF,SAAStE,IAAI,EAAE;IACxF,OAAOsE,SAAStE,IAAI;AACtB;AAEA,+FAA+F,GAC/F,OAAO,SAASuF,uBAAuBC,YAAgC,EAAE9B,SAAqC;IAC5G,MAAM+B,QAAQ/B,UAAUX,GAAG,CAACuC,kBAAkBzF,IAAI,CAAC;IACnD,OAAO;QAAC2F;QAAcC;KAAM,CAACvD,MAAM,CAACC,SAAStC,IAAI,CAAC;AACpD;AAEA,4EAA4E,GAC5E,OAAO,SAAS6F,qBAAqBZ,SAAmD;IACtF,OAAO;WAAKA,oBAAAA,YAAa,EAAE;KAAE,CAC1B/B,GAAG,CAAC,CAACE,OAAUA,KAAKG,IAAI,GAAG,GAAGH,KAAKC,OAAO,CAAC,CAAC,EAAED,KAAKE,QAAQ,CAAC,CAAC,EAAEF,KAAKG,IAAI,EAAE,GAAG,GAAGH,KAAKC,OAAO,CAAC,CAAC,EAAED,KAAKE,QAAQ,EAAE,EAC/GwC,IAAI,GACJ9F,IAAI,CAAC;AACV"}
@@ -210,11 +210,21 @@ export declare function productDuplicateSlugBase(slug: string | undefined, name:
210
210
  * source's would sort and find it by the source's name) and stock fields, and
211
211
  * not the source's SKU and barcode keys, which are derived again from its
212
212
  * variants. The caller adds the claimed `slug`'s smart-collection membership.
213
+ *
214
+ * Everything the merchant made is copied: options, every variant, add-ons and
215
+ * write-ins (`modifierGroups`), photos, SEO, categories, tags. The source's
216
+ * OWN bookkeeping is not: the checkout holds on its stock (`stockHolds`, which
217
+ * no checkout of the copy would ever release), its soft delete, and who made
218
+ * it and when, which the create stamps afresh.
213
219
  */
214
220
  export declare function productDuplicateFields(product: HostProduct & {
215
221
  $id?: string;
216
222
  skus?: string[];
217
223
  barcodes?: string[];
224
+ stockHolds?: unknown;
225
+ createdAt?: unknown;
226
+ updatedAt?: unknown;
227
+ createdBy?: unknown;
218
228
  }, slug: string, nowMs: number): {
219
229
  slug: string;
220
230
  status: "draft";
@@ -275,7 +285,6 @@ export declare function productDuplicateFields(product: HostProduct & {
275
285
  offerOnKiosk?: boolean;
276
286
  hardwareSku?: string;
277
287
  checkIn?: import("./commerce-check-in-product").ProductCheckIn;
278
- deletedAt?: number | null;
279
288
  priceUsd?: number;
280
289
  imageUrl?: string;
281
290
  };
@@ -155,11 +155,22 @@ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_wi
155
155
  * source's would sort and find it by the source's name) and stock fields, and
156
156
  * not the source's SKU and barcode keys, which are derived again from its
157
157
  * variants. The caller adds the claimed `slug`'s smart-collection membership.
158
+ *
159
+ * Everything the merchant made is copied: options, every variant, add-ons and
160
+ * write-ins (`modifierGroups`), photos, SEO, categories, tags. The source's
161
+ * OWN bookkeeping is not: the checkout holds on its stock (`stockHolds`, which
162
+ * no checkout of the copy would ever release), its soft delete, and who made
163
+ * it and when, which the create stamps afresh.
158
164
  */ export function productDuplicateFields(product, slug, nowMs) {
159
- const { $id: _sourceId, skus: _skus, barcodes: _barcodes } = product, copy = _object_without_properties_loose(product, [
165
+ const { $id: _sourceId, skus: _skus, barcodes: _barcodes, stockHolds: _stockHolds, createdAt: _createdAt, updatedAt: _updatedAt, createdBy: _createdBy, deletedAt: _deletedAt } = product, copy = _object_without_properties_loose(product, [
160
166
  "$id",
161
167
  "skus",
162
- "barcodes"
168
+ "barcodes",
169
+ "stockHolds",
170
+ "createdAt",
171
+ "updatedAt",
172
+ "createdBy",
173
+ "deletedAt"
163
174
  ]);
164
175
  return _extends({}, copy, productSearchFields({
165
176
  name: productDuplicateName(product.name),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/product-write.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 adjustVariantInventory,\n COMMERCE_DEFAULT_PRICE_USD,\n commerceSlug,\n expandVariantMatrix,\n type HostProduct,\n type ProductOption,\n type ProductVariant,\n type InventoryAdjustment,\n type InventoryAdjustmentReason,\n productSearchFields,\n productStockFields,\n type SmartCollectionRules,\n variantHasPrice,\n} from './commerce'\n\n/*\n * WHAT A PRODUCT SAVE AND A STOCK ADJUSTMENT WRITE, worked out once.\n *\n * The console's product editor and its Adjust stock dialog compute these\n * fields in the browser before their Firestore writes; the native apps save\n * through `commerce/products/save` and `commerce/products/stock`, which run\n * this same code on the server. One computation, so a product saved from a\n * phone carries exactly the search keys, stock verdict, price, image and\n * smart-collection membership the console would have written.\n */\n\n/** The longest product name a save keeps: {@link productSaveFields} cuts a longer one here. */\nexport const PRODUCT_NAME_MAX_LENGTH = 120\n\n/** A product as the editor holds it: the stored fields plus keys the listener or a seed may carry. */\nexport type EditedProduct = HostProduct & {\n $id?: string\n skus?: string[]\n barcodes?: string[]\n stockHolds?: Record<string, unknown>\n}\n\n/**\n * The fields a product save writes, before its collection membership and its\n * timestamps: the product as edited, with\n *\n * - `$id` dropped (AGL-1374): the listener's synthetic key, never a field;\n * - the seed's `skus` / `barcodes` dropped (AGL-3321): `productSearchFields`\n * omits each when no variant has one, so a seeded copy would outlive the\n * last SKU;\n * - the trimmed name with the search keys derived from it, together, so the\n * two cannot drift (AGL-2501);\n * - a slug, the primary variant's price, the stock fields, the first image\n * and `updatedAtMs`.\n */\nexport function productSaveFields(current: EditedProduct, nowMs: number) {\n const {\n $id: _syntheticId,\n skus: _seededSkus,\n barcodes: _seededBarcodes,\n // A sample the merchant saves is theirs now (AGL-4065).\n sample: _sample,\n ...currentFields\n } = current\n const primaryVariant = current.variants[0]\n return {\n ...currentFields,\n ...productSearchFields({\n name: current.name.trim().slice(0, PRODUCT_NAME_MAX_LENGTH),\n variants: current.variants,\n }),\n slug: current.slug || commerceSlug(current.name),\n // The legacy flat price, only where there is one (AGL-3676): an owner\n // may save a product before pricing it, and an unpriced product is not\n // a free one. `null` rather than absent, so an edit's full replace and\n // the native save write the same field.\n priceUsd: variantHasPrice(primaryVariant) ? primaryVariant.priceUsd : null,\n ...productStockFields({\n variants: current.variants,\n oversellPolicy: current.oversellPolicy,\n }),\n imageUrl: current.mediaUrls?.[0] ?? current.imageUrl ?? null,\n updatedAtMs: nowMs,\n }\n}\n\n/**\n * A product nobody has saved yet, as the editor starts one: a draft, at the\n * default price (AGL-3676), for the owner to change or clear.\n */\nexport function blankProductDraft(): HostProduct {\n return {\n name: '',\n slug: '',\n type: 'physical',\n status: 'draft',\n variants: [{ id: 'default', priceUsd: COMMERCE_DEFAULT_PRICE_USD }],\n }\n}\n\n/** Stable key for matching variants across matrix regenerations. */\nexport function variantComboKey(options: Record<string, string> | undefined): string {\n return Object.entries(options ?? {})\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, value]) => `${name}:${value}`)\n .join('|')\n}\n\n/**\n * The variants a change of option VALUES makes, as the editor rebuilds them:\n * one per combination of `options`, each an existing variant with the same\n * selections where there is one (so its id, price, SKU and stock survive the\n * change), and otherwise a new variant at the first variant's price (none\n * where it has none, the default on a product with no variant yet) and stock.\n *\n * Ask {@link variantMatrixProblem} first: past the ceiling the editor keeps\n * the variants as they are and refuses the save (AGL-4100). A rename is not\n * a change of values; it goes through `renameProductOptions` (AGL-3066).\n */\nexport function variantsForOptions(\n at: Pick<HostProduct, 'variants'>,\n options: ProductOption[],\n nowMs: number,\n): ProductVariant[] {\n const previous = new Map(at.variants.map((variant) => [variantComboKey(variant.options), variant]))\n const fallback = at.variants[0]\n return expandVariantMatrix(options).map(\n (combo, comboIndex) =>\n previous.get(variantComboKey(combo)) ??\n // An unpriced variant is stored with no `priceUsd` (AGL-3676), as a\n // proposed product's are; the type names the priced shape.\n ({\n id: `v${nowMs.toString(36)}${comboIndex}`,\n options: combo,\n ...(fallback\n ? variantHasPrice(fallback)\n ? { priceUsd: fallback.priceUsd }\n : {}\n : { priceUsd: COMMERCE_DEFAULT_PRICE_USD }),\n inventory: fallback?.inventory ?? null,\n } as ProductVariant),\n )\n}\n\n/** What the smart-collection rules are matched against: the saved name with the product's own facts. */\nexport function productMembershipInput(\n fields: { name: string },\n current: Pick<HostProduct, 'type' | 'tags' | 'categoryIds' | 'variants'>,\n) {\n return {\n name: fields.name,\n type: current.type,\n tags: current.tags,\n categoryIds: current.categoryIds,\n variants: current.variants,\n }\n}\n\n/**\n * An EDIT's replacing write, without its membership and server timestamp:\n * live stock holds are not the editor's to write (AGL-2356), so the seed's\n * are dropped and the stored ones carried; the product stays live\n * (`deletedAt: null`, AGL-3321).\n */\nexport function productEditWrite(\n fields: ReturnType<typeof productSaveFields>,\n liveHolds: Record<string, unknown> | null | undefined,\n) {\n const { stockHolds: _seededHolds, ...withoutHolds } = fields as typeof fields & {\n stockHolds?: Record<string, unknown>\n }\n return {\n ...withoutHolds,\n ...(liveHolds ? { stockHolds: liveHolds } : {}),\n deletedAt: null,\n }\n}\n\n/** A duplicate's name: the source's, marked as a copy. */\nexport function productDuplicateName(name: string): string {\n return `${name} (copy)`\n}\n\n/** The slug a duplicate starts from, before the store is asked which are taken. */\nexport function productDuplicateSlugBase(slug: string | undefined, name: string): string {\n return commerceSlug(`${slug || commerceSlug(name)}-copy`)\n}\n\n/**\n * What Duplicate writes (the products list's Duplicate, AGL-3321): the source\n * as a draft under the copy's name, with the COPY's search keys (spreading the\n * source's would sort and find it by the source's name) and stock fields, and\n * not the source's SKU and barcode keys, which are derived again from its\n * variants. The caller adds the claimed `slug`'s smart-collection membership.\n */\nexport function productDuplicateFields(\n product: HostProduct & { $id?: string; skus?: string[]; barcodes?: string[] },\n slug: string,\n nowMs: number,\n) {\n const { $id: _sourceId, skus: _skus, barcodes: _barcodes, ...copy } = product\n return {\n ...copy,\n ...productSearchFields({ name: productDuplicateName(product.name), variants: product.variants }),\n ...productStockFields(product),\n slug,\n status: 'draft' as const,\n createdAtMs: nowMs,\n updatedAtMs: nowMs,\n }\n}\n\n/** A smart collection as `hosts/{hostId}/collections` stores it, as the membership rules read it. */\nexport function smartCollectionRulesOf(id: string, data: Record<string, unknown>): SmartCollectionRules {\n return {\n id,\n rules: (data['rules'] as SmartCollectionRules['rules']) ?? [],\n matchAll: data['matchAll'] as boolean | undefined,\n }\n}\n\n/** One stock adjustment, as the Adjust stock dialog asks for it. */\nexport interface StockAdjustment {\n variantId: string\n delta: number\n reason: InventoryAdjustmentReason\n locationId?: string\n}\n\n/**\n * The product update and the ledger row one stock adjustment writes: the\n * variants with the count moved, the stock fields that move with it\n * (AGL-3321), and the same `inventoryAdjustments` row the sale webhook writes\n * (AGL-281). A zero or non-numeric delta writes nothing.\n */\nexport function stockAdjustmentWrite(\n product: HostProduct,\n productId: string,\n adjustment: StockAdjustment,\n nowMs: number,\n): { update: Record<string, unknown>; ledger: InventoryAdjustment } | null {\n const delta = Math.round(Number(adjustment.delta))\n if (!delta) return null\n const variants = adjustVariantInventory(product, adjustment.variantId, delta, adjustment.locationId || undefined)\n return {\n update: {\n variants,\n ...productStockFields({ ...product, variants }),\n updatedAtMs: nowMs,\n },\n ledger: {\n productId,\n variantId: adjustment.variantId,\n delta,\n reason: adjustment.reason,\n ...(adjustment.locationId ? { locationId: adjustment.locationId } : {}),\n atMs: nowMs,\n },\n }\n}\n"],"names":["adjustVariantInventory","COMMERCE_DEFAULT_PRICE_USD","commerceSlug","expandVariantMatrix","productSearchFields","productStockFields","variantHasPrice","PRODUCT_NAME_MAX_LENGTH","productSaveFields","current","nowMs","$id","_syntheticId","skus","_seededSkus","barcodes","_seededBarcodes","sample","_sample","currentFields","primaryVariant","variants","name","trim","slice","slug","priceUsd","oversellPolicy","imageUrl","mediaUrls","updatedAtMs","blankProductDraft","type","status","id","variantComboKey","options","Object","entries","sort","a","b","localeCompare","map","value","join","variantsForOptions","at","previous","Map","variant","fallback","combo","comboIndex","get","toString","inventory","productMembershipInput","fields","tags","categoryIds","productEditWrite","liveHolds","stockHolds","_seededHolds","withoutHolds","deletedAt","productDuplicateName","productDuplicateSlugBase","productDuplicateFields","product","_sourceId","_skus","_barcodes","copy","createdAtMs","smartCollectionRulesOf","data","rules","matchAll","stockAdjustmentWrite","productId","adjustment","delta","Math","round","Number","variantId","locationId","undefined","update","ledger","reason","atMs"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,0BAA0B,EAC1BC,YAAY,EACZC,mBAAmB,EAMnBC,mBAAmB,EACnBC,kBAAkB,EAElBC,eAAe,QACV,gBAAY;AAEnB;;;;;;;;;CASC,GAED,6FAA6F,GAC7F,OAAO,MAAMC,0BAA0B,IAAG;AAU1C;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,kBAAkBC,OAAsB,EAAEC,KAAa;QA0BzDD;QAAAA;IAzBZ,MAAM,EACJE,KAAKC,YAAY,EACjBC,MAAMC,WAAW,EACjBC,UAAUC,eAAe,EACzB,wDAAwD;IACxDC,QAAQC,OAAO,EAEhB,GAAGT,SADCU,iDACDV;;;;;;IACJ,MAAMW,iB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Y,EACZf,KAAa;IAEb,MAAM,EAAEC,KAAK4D,SAAS,EAAE1D,MAAM2D,KAAK,EAAEzD,UAAU0D,SAAS,EAAW,GAAGH,SAATI,wCAASJ;;;;;IACtE,OAAO,aACFI,MACAtE,oBAAoB;QAAEkB,MAAM6C,qBAAqBG,QAAQhD,IAAI;QAAGD,UAAUiD,QAAQjD,QAAQ;IAAC,IAC3FhB,mBAAmBiE;QACtB7C;QACAQ,QAAQ;QACR0C,aAAajE;QACboB,aAAapB;;AAEjB;AAEA,mGAAmG,GACnG,OAAO,SAASkE,uBAAuB1C,EAAU,EAAE2C,IAA6B;QAGpEA;IAFV,OAAO;QACL3C;QACA4C,KAAK,GAAGD,cAAAA,IAAI,CAAC,QAAQ,YAAbA,cAAmD,EAAE;QAC7DE,UAAUF,IAAI,CAAC,WAAW;IAC5B;AACF;AAUA;;;;;CAKC,GACD,OAAO,SAASG,qBACdV,OAAoB,EACpBW,SAAiB,EACjBC,UAA2B,EAC3BxE,KAAa;IAEb,MAAMyE,QAAQC,KAAKC,KAAK,CAACC,OAAOJ,WAAWC,KAAK;IAChD,IAAI,CAACA,OAAO,OAAO;IACnB,MAAM9D,WAAWrB,uBAAuBsE,SAASY,WAAWK,SAAS,EAAEJ,OAAOD,WAAWM,UAAU,IAAIC;IACvG,OAAO;QACLC,QAAQ;YACNrE;WACGhB,mBAAmB,aAAKiE;YAASjD;;YACpCS,aAAapB;;QAEfiF,QAAQ;YACNV;YACAM,WAAWL,WAAWK,SAAS;YAC/BJ;YACAS,QAAQV,WAAWU,MAAM;WACrBV,WAAWM,UAAU,GAAG;YAAEA,YAAYN,WAAWM,UAAU;QAAC,IAAI,CAAC;YACrEK,MAAMnF;;IAEV;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/product-write.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 adjustVariantInventory,\n COMMERCE_DEFAULT_PRICE_USD,\n commerceSlug,\n expandVariantMatrix,\n type HostProduct,\n type ProductOption,\n type ProductVariant,\n type InventoryAdjustment,\n type InventoryAdjustmentReason,\n productSearchFields,\n productStockFields,\n type SmartCollectionRules,\n variantHasPrice,\n} from './commerce'\n\n/*\n * WHAT A PRODUCT SAVE AND A STOCK ADJUSTMENT WRITE, worked out once.\n *\n * The console's product editor and its Adjust stock dialog compute these\n * fields in the browser before their Firestore writes; the native apps save\n * through `commerce/products/save` and `commerce/products/stock`, which run\n * this same code on the server. One computation, so a product saved from a\n * phone carries exactly the search keys, stock verdict, price, image and\n * smart-collection membership the console would have written.\n */\n\n/** The longest product name a save keeps: {@link productSaveFields} cuts a longer one here. */\nexport const PRODUCT_NAME_MAX_LENGTH = 120\n\n/** A product as the editor holds it: the stored fields plus keys the listener or a seed may carry. */\nexport type EditedProduct = HostProduct & {\n $id?: string\n skus?: string[]\n barcodes?: string[]\n stockHolds?: Record<string, unknown>\n}\n\n/**\n * The fields a product save writes, before its collection membership and its\n * timestamps: the product as edited, with\n *\n * - `$id` dropped (AGL-1374): the listener's synthetic key, never a field;\n * - the seed's `skus` / `barcodes` dropped (AGL-3321): `productSearchFields`\n * omits each when no variant has one, so a seeded copy would outlive the\n * last SKU;\n * - the trimmed name with the search keys derived from it, together, so the\n * two cannot drift (AGL-2501);\n * - a slug, the primary variant's price, the stock fields, the first image\n * and `updatedAtMs`.\n */\nexport function productSaveFields(current: EditedProduct, nowMs: number) {\n const {\n $id: _syntheticId,\n skus: _seededSkus,\n barcodes: _seededBarcodes,\n // A sample the merchant saves is theirs now (AGL-4065).\n sample: _sample,\n ...currentFields\n } = current\n const primaryVariant = current.variants[0]\n return {\n ...currentFields,\n ...productSearchFields({\n name: current.name.trim().slice(0, PRODUCT_NAME_MAX_LENGTH),\n variants: current.variants,\n }),\n slug: current.slug || commerceSlug(current.name),\n // The legacy flat price, only where there is one (AGL-3676): an owner\n // may save a product before pricing it, and an unpriced product is not\n // a free one. `null` rather than absent, so an edit's full replace and\n // the native save write the same field.\n priceUsd: variantHasPrice(primaryVariant) ? primaryVariant.priceUsd : null,\n ...productStockFields({\n variants: current.variants,\n oversellPolicy: current.oversellPolicy,\n }),\n imageUrl: current.mediaUrls?.[0] ?? current.imageUrl ?? null,\n updatedAtMs: nowMs,\n }\n}\n\n/**\n * A product nobody has saved yet, as the editor starts one: a draft, at the\n * default price (AGL-3676), for the owner to change or clear.\n */\nexport function blankProductDraft(): HostProduct {\n return {\n name: '',\n slug: '',\n type: 'physical',\n status: 'draft',\n variants: [{ id: 'default', priceUsd: COMMERCE_DEFAULT_PRICE_USD }],\n }\n}\n\n/** Stable key for matching variants across matrix regenerations. */\nexport function variantComboKey(options: Record<string, string> | undefined): string {\n return Object.entries(options ?? {})\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, value]) => `${name}:${value}`)\n .join('|')\n}\n\n/**\n * The variants a change of option VALUES makes, as the editor rebuilds them:\n * one per combination of `options`, each an existing variant with the same\n * selections where there is one (so its id, price, SKU and stock survive the\n * change), and otherwise a new variant at the first variant's price (none\n * where it has none, the default on a product with no variant yet) and stock.\n *\n * Ask {@link variantMatrixProblem} first: past the ceiling the editor keeps\n * the variants as they are and refuses the save (AGL-4100). A rename is not\n * a change of values; it goes through `renameProductOptions` (AGL-3066).\n */\nexport function variantsForOptions(\n at: Pick<HostProduct, 'variants'>,\n options: ProductOption[],\n nowMs: number,\n): ProductVariant[] {\n const previous = new Map(at.variants.map((variant) => [variantComboKey(variant.options), variant]))\n const fallback = at.variants[0]\n return expandVariantMatrix(options).map(\n (combo, comboIndex) =>\n previous.get(variantComboKey(combo)) ??\n // An unpriced variant is stored with no `priceUsd` (AGL-3676), as a\n // proposed product's are; the type names the priced shape.\n ({\n id: `v${nowMs.toString(36)}${comboIndex}`,\n options: combo,\n ...(fallback\n ? variantHasPrice(fallback)\n ? { priceUsd: fallback.priceUsd }\n : {}\n : { priceUsd: COMMERCE_DEFAULT_PRICE_USD }),\n inventory: fallback?.inventory ?? null,\n } as ProductVariant),\n )\n}\n\n/** What the smart-collection rules are matched against: the saved name with the product's own facts. */\nexport function productMembershipInput(\n fields: { name: string },\n current: Pick<HostProduct, 'type' | 'tags' | 'categoryIds' | 'variants'>,\n) {\n return {\n name: fields.name,\n type: current.type,\n tags: current.tags,\n categoryIds: current.categoryIds,\n variants: current.variants,\n }\n}\n\n/**\n * An EDIT's replacing write, without its membership and server timestamp:\n * live stock holds are not the editor's to write (AGL-2356), so the seed's\n * are dropped and the stored ones carried; the product stays live\n * (`deletedAt: null`, AGL-3321).\n */\nexport function productEditWrite(\n fields: ReturnType<typeof productSaveFields>,\n liveHolds: Record<string, unknown> | null | undefined,\n) {\n const { stockHolds: _seededHolds, ...withoutHolds } = fields as typeof fields & {\n stockHolds?: Record<string, unknown>\n }\n return {\n ...withoutHolds,\n ...(liveHolds ? { stockHolds: liveHolds } : {}),\n deletedAt: null,\n }\n}\n\n/** A duplicate's name: the source's, marked as a copy. */\nexport function productDuplicateName(name: string): string {\n return `${name} (copy)`\n}\n\n/** The slug a duplicate starts from, before the store is asked which are taken. */\nexport function productDuplicateSlugBase(slug: string | undefined, name: string): string {\n return commerceSlug(`${slug || commerceSlug(name)}-copy`)\n}\n\n/**\n * What Duplicate writes (the products list's Duplicate, AGL-3321): the source\n * as a draft under the copy's name, with the COPY's search keys (spreading the\n * source's would sort and find it by the source's name) and stock fields, and\n * not the source's SKU and barcode keys, which are derived again from its\n * variants. The caller adds the claimed `slug`'s smart-collection membership.\n *\n * Everything the merchant made is copied: options, every variant, add-ons and\n * write-ins (`modifierGroups`), photos, SEO, categories, tags. The source's\n * OWN bookkeeping is not: the checkout holds on its stock (`stockHolds`, which\n * no checkout of the copy would ever release), its soft delete, and who made\n * it and when, which the create stamps afresh.\n */\nexport function productDuplicateFields(\n product: HostProduct & {\n $id?: string\n skus?: string[]\n barcodes?: string[]\n stockHolds?: unknown\n createdAt?: unknown\n updatedAt?: unknown\n createdBy?: unknown\n },\n slug: string,\n nowMs: number,\n) {\n const {\n $id: _sourceId,\n skus: _skus,\n barcodes: _barcodes,\n stockHolds: _stockHolds,\n createdAt: _createdAt,\n updatedAt: _updatedAt,\n createdBy: _createdBy,\n deletedAt: _deletedAt,\n ...copy\n } = product\n return {\n ...copy,\n ...productSearchFields({ name: productDuplicateName(product.name), variants: product.variants }),\n ...productStockFields(product),\n slug,\n status: 'draft' as const,\n createdAtMs: nowMs,\n updatedAtMs: nowMs,\n }\n}\n\n/** A smart collection as `hosts/{hostId}/collections` stores it, as the membership rules read it. */\nexport function smartCollectionRulesOf(id: string, data: Record<string, unknown>): SmartCollectionRules {\n return {\n id,\n rules: (data['rules'] as SmartCollectionRules['rules']) ?? [],\n matchAll: data['matchAll'] as boolean | undefined,\n }\n}\n\n/** One stock adjustment, as the Adjust stock dialog asks for it. */\nexport interface StockAdjustment {\n variantId: string\n delta: number\n reason: InventoryAdjustmentReason\n locationId?: string\n}\n\n/**\n * The product update and the ledger row one stock adjustment writes: the\n * variants with the count moved, the stock fields that move with it\n * (AGL-3321), and the same `inventoryAdjustments` row the sale webhook writes\n * (AGL-281). A zero or non-numeric delta writes nothing.\n */\nexport function stockAdjustmentWrite(\n product: HostProduct,\n productId: string,\n adjustment: StockAdjustment,\n nowMs: number,\n): { update: Record<string, unknown>; ledger: InventoryAdjustment } | null {\n const delta = Math.round(Number(adjustment.delta))\n if (!delta) return null\n const variants = adjustVariantInventory(product, adjustment.variantId, delta, adjustment.locationId || undefined)\n return {\n update: {\n variants,\n ...productStockFields({ ...product, variants }),\n updatedAtMs: nowMs,\n },\n ledger: {\n productId,\n variantId: adjustment.variantId,\n delta,\n reason: adjustment.reason,\n ...(adjustment.locationId ? { locationId: adjustment.locationId } : {}),\n atMs: nowMs,\n },\n }\n}\n"],"names":["adjustVariantInventory","COMMERCE_DEFAULT_PRICE_USD","commerceSlug","expandVariantMatrix","productSearchFields","productStockFields","variantHasPrice","PRODUCT_NAME_MAX_LENGTH","productSaveFields","current","nowMs","$id","_syntheticId","skus","_seededSkus","barcodes","_seededBarcodes","sample","_sample","currentFields","primaryVariant","variants","name","trim","slice","slug","priceUsd","oversellPolicy","imageUrl","mediaUrls","updatedAtMs","blankProductDraft","type","status","id","variantComboKey","options","Object","entries","sort","a","b","localeCompare","map","value","join","variantsForOptions","at","previous","Map","variant","fallback","combo","comboIndex","get","toString","inventory","productMembershipInput","fields","tags","categoryIds","productEditWrite","liveHolds","stockHolds","_seededHolds","withoutHolds","deletedAt","productDuplicateName","productDuplicateSlugBase","productDuplicateFields","product","_sourceId","_skus","_barcodes","_stockHolds","createdAt","_createdAt","updatedAt","_updatedAt","createdBy","_createdBy","_deletedAt","copy","createdAtMs","smartCollectionRulesOf","data","rules","matchAll","stockAdjustmentWrite","productId","adjustment","delta","Math","round","Number","variantId","locationId","undefined","update","ledger","reason","atMs"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,0BAA0B,EAC1BC,YAAY,EACZC,mBAAmB,EAMnBC,mBAAmB,EACnBC,kBAAkB,EAElBC,eAAe,QACV,gBAAY;AAEnB;;;;;;;;;CASC,GAED,6FAA6F,GAC7F,OAAO,MAAMC,0BAA0B,IAAG;AAU1C;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,kBAAkBC,OAAsB,EAAEC,KAAa;QA0BzDD;QAAAA;IAzBZ,MAAM,EACJE,KAAKC,YAAY,EACjBC,MAAMC,WAAW,EACjBC,UAAUC,eAAe,EACzB,wDAAwD;IACxDC,QAAQC,OAAO,EAEhB,GAAGT,SADCU,iDACDV;;;;;;IACJ,MAAMW,iBAA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
430
  transaction.set(orderRef, {
431
431
  externalRefundedCents: externalCents + newCents,
432
- timeline: CommerceModel.appendOrderEvent(order, 'refund', `$${(newCents / 100).toFixed(2)} refunded outside the dashboard (in Stripe)`)
432
+ timeline: CommerceModel.appendOrderEvent(order, 'refund', `${CommerceModel.saleMoneyText(newCents, order.currency)} refunded outside the dashboard (in Stripe)`)
433
433
  }, {
434
434
  merge: true
435
435
  });
@@ -1826,6 +1826,12 @@ async function findOrderForDispute(paymentIntentId) {
1826
1826
  }
1827
1827
  export const commerceBillingWebhookHandler = async ({ type, object, event, requestHost })=>{
1828
1828
  var _object_metadata, _object_metadata1, _object_metadata2, _object_metadata3, _object_metadata4;
1829
+ // The money of THIS sale in the currency it was charged in (AGL-4248): a
1830
+ // session or charge names it. A USD sale reads exactly as it always has.
1831
+ const saleMoney = (cents)=>{
1832
+ var _ref;
1833
+ return CommerceModel.saleMoneyText(cents, String((_ref = object == null ? void 0 : object.currency) != null ? _ref : 'usd'));
1834
+ };
1829
1835
  // THE MERCHANT'S PAYMENT ACCOUNT CHANGED. Every commerce money route —
1830
1836
  // checkout, cart checkout, draft orders, reservations, POS — gates the sale
1831
1837
  // on the readiness the connect route CACHED on the merchant's profile
@@ -3049,8 +3055,11 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3049
3055
  } : {}, {
3050
3056
  quantity: line.quantity
3051
3057
  }));
3052
- const lineItems = cart.lines.map((line)=>{
3053
- var _variant_options, _variant_options1, _ref;
3058
+ // The units the shopper was charged, in cart order, when the
3059
+ // checkout charged in another currency than the store's (AGL-4248).
3060
+ const chargedUnits = CommerceModel.decodeChargeUnitsMetadata(object == null ? void 0 : object.metadata);
3061
+ const lineItems = cart.lines.map((line, lineIndex)=>{
3062
+ var _variant_options, _variant_options1, _ref, _ref1;
3054
3063
  const product = productsById.get(line.productId);
3055
3064
  if (!product) return null;
3056
3065
  const variant = line.variantId ? product.variants.find((item)=>item.id === line.variantId) : product.variants[0];
@@ -3082,7 +3091,9 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3082
3091
  supplierId: product.supplierId
3083
3092
  } : {}, {
3084
3093
  quantity: line.quantity,
3085
- unitAmountCents: Math.round(Number((_ref = variant == null ? void 0 : variant.priceUsd) != null ? _ref : 0) * 100) + extraCents
3094
+ // The unit the shopper was charged, when the checkout charged in
3095
+ // another currency than the store's (AGL-4248).
3096
+ unitAmountCents: (_ref = chargedUnits == null ? void 0 : chargedUnits[lineIndex]) != null ? _ref : Math.round(Number((_ref1 = variant == null ? void 0 : variant.priceUsd) != null ? _ref1 : 0) * 100) + extraCents
3086
3097
  });
3087
3098
  }).filter(Boolean);
3088
3099
  const shipping = (_ref40 = object == null ? void 0 : object.shipping_details) != null ? _ref40 : object == null ? void 0 : object.customer_details;
@@ -3134,8 +3145,8 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3134
3145
  }
3135
3146
  });
3136
3147
  const created = await firestore.runTransaction(async (transaction)=>{
3137
- var _counter_get, _ref, _ref1, _ref2, _ref3, _ref4, _ref5;
3138
- var _object_metadata, _object_metadata1, _object_metadata2, _object_customer_details, _object_customer_details1;
3148
+ var _counter_get, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8;
3149
+ var _object_metadata, _object_metadata1, _object_metadata2, _object_metadata3, _object_metadata4, _object_customer_details, _object_customer_details1;
3139
3150
  const [existing, counter] = await Promise.all([
3140
3151
  transaction.get(orderRef),
3141
3152
  transaction.get(counterRef)
@@ -3182,8 +3193,9 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3182
3193
  // to be dropped here, storing `shippingCents: 0` on every online
3183
3194
  // order while the shopper's shipping sat inside `amount_total`.
3184
3195
  const totals = CommerceModel.computeCheckoutSessionTotals(lineItems, object, {
3185
- feeCents: Number(feeCents != null ? feeCents : 0),
3186
- extrasCents: checkoutExtrasCents(cartExtras)
3196
+ // The take as charged, in the charge currency (AGL-4248).
3197
+ feeCents: Number((_ref = (_ref1 = object == null ? void 0 : (_object_metadata = object.metadata) == null ? void 0 : _object_metadata.chargeFeeCents) != null ? _ref1 : feeCents) != null ? _ref : 0),
3198
+ extrasCents: Number((_ref2 = object == null ? void 0 : (_object_metadata1 = object.metadata) == null ? void 0 : _object_metadata1.chargeExtrasCents) != null ? _ref2 : checkoutExtrasCents(cartExtras))
3187
3199
  });
3188
3200
  // With the fields the orders list queries by (AGL-3321).
3189
3201
  transaction.set(orderRef, CommerceModel.withOrderListFields(orderRef.id, _extends({
@@ -3192,13 +3204,13 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3192
3204
  channel: 'online',
3193
3205
  lineItems,
3194
3206
  totals
3195
- }, cartExtras.length ? {
3207
+ }, CommerceModel.orderCurrencyFields(object, totals), cartExtras.length ? {
3196
3208
  extras: cartExtras
3197
3209
  } : {}, creditSold ? {
3198
3210
  credits: [
3199
3211
  creditSold
3200
3212
  ]
3201
- } : {}, (object == null ? void 0 : (_object_metadata = object.metadata) == null ? void 0 : _object_metadata.giftCardCode) && Number(object == null ? void 0 : (_object_metadata1 = object.metadata) == null ? void 0 : _object_metadata1.giftCardCents) > 0 ? {
3213
+ } : {}, (object == null ? void 0 : (_object_metadata2 = object.metadata) == null ? void 0 : _object_metadata2.giftCardCode) && Number(object == null ? void 0 : (_object_metadata3 = object.metadata) == null ? void 0 : _object_metadata3.giftCardCents) > 0 ? {
3202
3214
  giftCardRedeemedCents: Math.round(Number(object.metadata.giftCardCents))
3203
3215
  } : {}, {
3204
3216
  // WHICH TAX THIS SALE CARRIED (AGL-2451). `totals.taxCents` above
@@ -3208,7 +3220,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3208
3220
  // the order and the filed row cannot disagree. A manual cart's tax
3209
3221
  // rides a real Stripe Tax Rate since AGL-1953 and therefore has a
3210
3222
  // populated breakdown — the flag is what tells the two apart.
3211
- taxMode: storefrontTaxModeOf(object, Number((_ref = object == null ? void 0 : (_object_metadata2 = object.metadata) == null ? void 0 : _object_metadata2.taxCents) != null ? _ref : 0))
3223
+ taxMode: storefrontTaxModeOf(object, Number((_ref3 = object == null ? void 0 : (_object_metadata4 = object.metadata) == null ? void 0 : _object_metadata4.taxCents) != null ? _ref3 : 0))
3212
3224
  }, taxEngineStampFromMetadata(object == null ? void 0 : object.metadata), {
3213
3225
  timeline: [
3214
3226
  {
@@ -3233,19 +3245,19 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3233
3245
  }, unresolvedLines.length ? {
3234
3246
  unresolvedLines
3235
3247
  } : {}, {
3236
- paymentIntentId: String((_ref1 = object == null ? void 0 : object.payment_intent) != null ? _ref1 : '') || null,
3248
+ paymentIntentId: String((_ref4 = object == null ? void 0 : object.payment_intent) != null ? _ref4 : '') || null,
3237
3249
  checkoutSessionId: String(object.id)
3238
3250
  }, typeof (event == null ? void 0 : event.livemode) === 'boolean' ? {
3239
3251
  livemode: event.livemode
3240
3252
  } : {}, directFields, {
3241
- customerName: (_ref2 = object == null ? void 0 : (_object_customer_details = object.customer_details) == null ? void 0 : _object_customer_details.name) != null ? _ref2 : null,
3242
- customerEmail: (_ref3 = object == null ? void 0 : (_object_customer_details1 = object.customer_details) == null ? void 0 : _object_customer_details1.email) != null ? _ref3 : null
3253
+ customerName: (_ref5 = object == null ? void 0 : (_object_customer_details = object.customer_details) == null ? void 0 : _object_customer_details.name) != null ? _ref5 : null,
3254
+ customerEmail: (_ref6 = object == null ? void 0 : (_object_customer_details1 = object.customer_details) == null ? void 0 : _object_customer_details1.email) != null ? _ref6 : null
3243
3255
  }, (shipping == null ? void 0 : shipping.address) && (cartLocalFulfillment == null ? void 0 : cartLocalFulfillment.fields.fulfillmentMethod) !== 'pickup' ? {
3244
3256
  shippingAddress: stripeOrderAddress(shipping == null ? void 0 : shipping.name, shipping.address)
3245
- } : {}, (_ref4 = cartLocalFulfillment == null ? void 0 : cartLocalFulfillment.fields) != null ? _ref4 : {}, couponCode ? {
3257
+ } : {}, (_ref7 = cartLocalFulfillment == null ? void 0 : cartLocalFulfillment.fields) != null ? _ref7 : {}, couponCode ? {
3246
3258
  couponCode
3247
3259
  } : {}, {
3248
- amountCents: Number((_ref5 = object == null ? void 0 : object.amount_total) != null ? _ref5 : 0),
3260
+ amountCents: Number((_ref8 = object == null ? void 0 : object.amount_total) != null ? _ref8 : 0),
3249
3261
  feeCents: Number(feeCents != null ? feeCents : 0)
3250
3262
  }, cartHardware, {
3251
3263
  createdAtMs: Date.now(),
@@ -3378,7 +3390,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3378
3390
  var _ref47, _ref48, _ref49, _ref50, _ref51;
3379
3391
  const receiptSettings = await hostRef.collection('settings').doc('store').get().catch(()=>null);
3380
3392
  const receiptFooter = String((_ref47 = receiptSettings == null ? void 0 : receiptSettings.get('receiptFooter')) != null ? _ref47 : '');
3381
- const linesText = lineItems.map((line)=>`${line.quantity}× ${line.name}${line.variantLabel ? ` (${line.variantLabel})` : ''} — $${(line.unitAmountCents * line.quantity / 100).toFixed(2)}`).concat(// Optional lines the buyer took (AGL-3635), as charged.
3393
+ const linesText = lineItems.map((line)=>`${line.quantity}× ${line.name}${line.variantLabel ? ` (${line.variantLabel})` : ''} — ${saleMoney(line.unitAmountCents * line.quantity)}`).concat(// Optional lines the buyer took (AGL-3635), as charged.
3382
3394
  cartExtras.map((extra)=>`${extra.label} — $${(extra.amountCents / 100).toFixed(2)}`)).join('\n');
3383
3395
  // The keys assigned above the gate (AGL-2149); the receipt only
3384
3396
  // reports them.
@@ -3394,7 +3406,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3394
3406
  const downloadToken = mintDownloadToken(hostId, String(object.id));
3395
3407
  const siteOrigin = String((_ref48 = object == null ? void 0 : object.success_url) != null ? _ref48 : '').replace(/\/\?.*$|\?.*$/, '');
3396
3408
  const downloadLines = lineItems.filter((line)=>line.productType === 'digital').map((line)=>`Download ${line.name}: ${siteOrigin}/api/commerce/download` + `?hostId=${hostId}&orderId=${object.id}` + `&productId=${line.productId}&token=${downloadToken}`).join('\n');
3397
- const orderTotal = `$${(Number((_ref49 = object == null ? void 0 : object.amount_total) != null ? _ref49 : 0) / 100).toFixed(2)}`;
3409
+ const orderTotal = saleMoney(Number((_ref49 = object == null ? void 0 : object.amount_total) != null ? _ref49 : 0));
3398
3410
  // Where to collect it, or when it is coming (AGL-3624).
3399
3411
  const fulfillmentText = (_ref50 = cartLocalFulfillment == null ? void 0 : cartLocalFulfillment.summary) != null ? _ref50 : '';
3400
3412
  const orderSummary = [
@@ -3499,7 +3511,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3499
3511
  // reason. The hold refuses the SECOND shopper; it never gates the
3500
3512
  // first one's goods.
3501
3513
  await releaseStockHold(hostRef, String((_ref41 = (_object_metadata21 = object.metadata) == null ? void 0 : _object_metadata21.stockHoldKey) != null ? _ref41 : ''));
3502
- const cartOrderTotal = `$${(Number((_ref42 = object == null ? void 0 : object.amount_total) != null ? _ref42 : 0) / 100).toFixed(2)}`;
3514
+ const cartOrderTotal = saleMoney(Number((_ref42 = object == null ? void 0 : object.amount_total) != null ? _ref42 : 0));
3503
3515
  const cartUnits = lineItems.reduce((sum, line)=>sum + line.quantity, 0);
3504
3516
  void notifyHostManagers(String(hostId), {
3505
3517
  type: 'content.order',
@@ -3536,7 +3548,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
3536
3548
  interaction: {
3537
3549
  source: 'order',
3538
3550
  refId: String(object.id),
3539
- summary: `Placed an order ($${(Number((_ref45 = object == null ? void 0 : object.amount_total) != null ? _ref45 : 0) / 100).toFixed(2)})`
3551
+ summary: `Placed an order (${saleMoney(Number((_ref45 = object == null ? void 0 : object.amount_total) != null ? _ref45 : 0))})`
3540
3552
  }
3541
3553
  }));
3542
3554
  if (couponCode) {
@@ -4358,7 +4370,8 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
4358
4370
  status: 'paid',
4359
4371
  channel: 'online',
4360
4372
  lineItems: buyNowLineItems,
4361
- totals: buyNowTotals,
4373
+ totals: buyNowTotals
4374
+ }, CommerceModel.orderCurrencyFields(object, buyNowTotals), {
4362
4375
  // WHICH TAX THIS SALE CARRIED (AGL-2451). Buy-now's manual tax
4363
4376
  // goes over as an ordinary `line_items[1]` Stripe is never told is
4364
4377
  // tax (AGL-1711), so the session reports `amount_tax: 0` and
@@ -4418,7 +4431,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
4418
4431
  // In-app order notification (wave v6): host managers see sales
4419
4432
  // in the bell, not just the owner's email: what came in, from whom
4420
4433
  // and where (AGL-3432).
4421
- const buyNowTotal = `$${(Number((_ref81 = object == null ? void 0 : object.amount_total) != null ? _ref81 : 0) / 100).toFixed(2)}`;
4434
+ const buyNowTotal = saleMoney(Number((_ref81 = object == null ? void 0 : object.amount_total) != null ? _ref81 : 0));
4422
4435
  void notifyHostManagers(String(hostId), {
4423
4436
  type: 'content.order',
4424
4437
  title: `New order on {site} — ${buyNowTotal}`,
@@ -4576,7 +4589,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
4576
4589
  interaction: {
4577
4590
  source: 'order',
4578
4591
  refId: String(object.id),
4579
- summary: `Placed an order ($${(Number((_ref84 = object == null ? void 0 : object.amount_total) != null ? _ref84 : 0) / 100).toFixed(2)})`
4592
+ summary: `Placed an order (${saleMoney(Number((_ref84 = object == null ? void 0 : object.amount_total) != null ? _ref84 : 0))})`
4580
4593
  }
4581
4594
  });
4582
4595
  const productRef = hostRef.collection('products').doc(String(productId));
@@ -4851,7 +4864,7 @@ export const commerceBillingWebhookHandler = async ({ type, object, event, reque
4851
4864
  hostId,
4852
4865
  subjectLabel: `order ${CommerceModel.formatOrderNumber(order, snapshot.id)}`,
4853
4866
  // The notice names the sum in question, as the dispute's does.
4854
- amount: orderCents > 0 ? `$${(orderCents / 100).toFixed(2)}` : null,
4867
+ amount: orderCents > 0 ? CommerceModel.saleMoneyText(orderCents, order.currency) : null,
4855
4868
  // The Orders section of the Products hub, with this order's dialog
4856
4869
  // open — where Refund lives (`siteRecordLinks().order`).
4857
4870
  link: `/${hostId}/products/orders?order=${encodeURIComponent(snapshot.id)}`,