@aglyn/plugins-commerce 1.31.0 → 1.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/package.json +13 -13
- package/src/lib/components/cart.js +35 -15
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/commerce-console-page.js +6 -0
- package/src/lib/components/commerce-console-page.js.map +1 -1
- package/src/lib/components/console/currencies-card.component.d.ts +21 -0
- package/src/lib/components/console/currencies-card.component.js +408 -0
- package/src/lib/components/console/currencies-card.component.js.map +1 -0
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
- package/src/lib/components/console/product-add-ons-fields.component.js +74 -2
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +42 -1
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/product-fixed-prices-fields.component.d.ts +25 -0
- package/src/lib/components/console/product-fixed-prices-fields.component.js +112 -0
- package/src/lib/components/console/product-fixed-prices-fields.component.js.map +1 -0
- package/src/lib/components/console/reservations-card.component.js +32 -15
- package/src/lib/components/console/reservations-card.component.js.map +1 -1
- package/src/lib/components/console/shipping-settings-card.component.js +337 -10
- package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
- package/src/lib/components/console/store-settings-card.component.js +1 -1
- package/src/lib/components/console/store-settings-card.component.js.map +1 -1
- package/src/lib/components/console/use-currency-setup.d.ts +20 -0
- package/src/lib/components/console/use-currency-setup.js +61 -0
- package/src/lib/components/console/use-currency-setup.js.map +1 -0
- package/src/lib/components/currency-selector.d.ts +36 -0
- package/src/lib/components/currency-selector.js +157 -0
- package/src/lib/components/currency-selector.js.map +1 -0
- package/src/lib/components/product-add-ons.d.ts +9 -1
- package/src/lib/components/product-add-ons.js +8 -4
- package/src/lib/components/product-add-ons.js.map +1 -1
- package/src/lib/components/product-choice-cards.d.ts +13 -1
- package/src/lib/components/product-choice-cards.js +5 -4
- package/src/lib/components/product-choice-cards.js.map +1 -1
- package/src/lib/components/product-detail.d.ts +8 -0
- package/src/lib/components/product-detail.js +38 -11
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.d.ts +2 -0
- package/src/lib/components/product-grid.js +22 -9
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/related-products.js +6 -2
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/shopper-currency.d.ts +108 -0
- package/src/lib/components/shopper-currency.js +262 -0
- package/src/lib/components/shopper-currency.js.map +1 -0
- package/src/lib/components/wishlist.js +7 -1
- package/src/lib/components/wishlist.js.map +1 -1
- package/src/lib/declarations.server.js +39 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/model/commerce-currency-setup.d.ts +79 -0
- package/src/lib/model/commerce-currency-setup.js +124 -0
- package/src/lib/model/commerce-currency-setup.js.map +1 -0
- package/src/lib/model/commerce-currency.d.ts +215 -0
- package/src/lib/model/commerce-currency.js +511 -0
- package/src/lib/model/commerce-currency.js.map +1 -0
- package/src/lib/model/commerce-orders.d.ts +17 -0
- package/src/lib/model/commerce-orders.js +10 -5
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-record-routes.js +26 -1
- package/src/lib/model/commerce-record-routes.js.map +1 -1
- package/src/lib/model/commerce-reservations.d.ts +6 -0
- package/src/lib/model/commerce-reservations.js.map +1 -1
- package/src/lib/model/commerce-shipping.d.ts +66 -11
- package/src/lib/model/commerce-shipping.js +91 -7
- package/src/lib/model/commerce-shipping.js.map +1 -1
- package/src/lib/model/commerce.d.ts +6 -0
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +2 -0
- package/src/lib/model/index.js +2 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/order-figures.js +9 -2
- package/src/lib/model/order-figures.js.map +1 -1
- package/src/lib/model/product-modifiers.d.ts +5 -0
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/model/store-setup-content.js +23 -2
- package/src/lib/model/store-setup-content.js.map +1 -1
- package/src/lib/server/billing-webhook.js +37 -24
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/carrier-shipping.d.ts +2 -0
- package/src/lib/server/carrier-shipping.js +8 -4
- package/src/lib/server/carrier-shipping.js.map +1 -1
- package/src/lib/server/cart-checkout.js +74 -13
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.d.ts +12 -0
- package/src/lib/server/cart.js +50 -4
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/catalog.d.ts +5 -0
- package/src/lib/server/catalog.js +7 -0
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout.js +53 -12
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/currency.d.ts +93 -0
- package/src/lib/server/currency.js +182 -0
- package/src/lib/server/currency.js.map +1 -0
- package/src/lib/server/order-notifications.js +4 -2
- package/src/lib/server/order-notifications.js.map +1 -1
- package/src/lib/server/product.d.ts +9 -0
- package/src/lib/server/product.js +12 -0
- package/src/lib/server/product.js.map +1 -1
- package/src/lib/server/refund.js +3 -3
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/site-chat-tools.d.ts +22 -0
- package/src/lib/server/site-chat-tools.js +369 -0
- package/src/lib/server/site-chat-tools.js.map +1 -0
- package/src/lib/server/site-chat-visitor.d.ts +24 -0
- package/src/lib/server/site-chat-visitor.js +39 -0
- package/src/lib/server/site-chat-visitor.js.map +1 -0
- package/src/lib/server/site-offers.d.ts +31 -0
- package/src/lib/server/site-offers.js +91 -0
- package/src/lib/server/site-offers.js.map +1 -0
- package/src/lib/server/stays-site-search.d.ts +20 -0
- package/src/lib/server/stays-site-search.js +78 -0
- package/src/lib/server/stays-site-search.js.map +1 -0
- package/src/lib/server.js +20 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/site-chat-tool-definitions.d.ts +26 -0
- package/src/lib/site-chat-tool-definitions.js +141 -0
- package/src/lib/site-chat-tool-definitions.js.map +1 -0
- package/src/lib/site.js +8 -0
- package/src/lib/site.js.map +1 -1
- package/src/lib/subprocessors.js +7 -0
- 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,uBAAuBC,KAA4D;IACjG,OAAOA,CAAAA,yBAAAA,MAAOC,IAAI,MAAK;AACzB;AAEA,iCAAiC,GACjC,OAAO,SAASC,iBAAiBF,KAA8C;IAC7E,MAAMG,SAASH,MAAMI,SAAS;IAC9B,OAAO,OAAOD,WAAW,YAAYE,OAAOC,SAAS,CAACH,WAAWA,UAAU,KAAKA,UAAUP,sBACtFO,SACAN;AACN;AAEA;;;;;CAKC,GACD,OAAO,SAASU,aAAaC,GAAY,EAAER,KAAsD;IAC/F,IAAI,OAAOQ,QAAQ,UAAU,OAAO;IACpC,MAAMC,QAAQT,QAAQE,iBAAiBF,SAASF;IAChD,MAAMY,OAAOF,GACX,4CAA4C;KAC3CG,OAAO,CAAC,6CAA6C,KACrDA,OAAO,CAAC,QAAQ,KAChBC,IAAI;IACP,OAAOC,MAAMC,IAAI,CAACJ,MAAMK,KAAK,CAAC,GAAGN,OAAOO,IAAI,CAAC,IAAIJ,IAAI;AACvD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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,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,uBAAuBC,KAA4D;IACjG,OAAOA,CAAAA,yBAAAA,MAAOC,IAAI,MAAK;AACzB;AAEA,iCAAiC,GACjC,OAAO,SAASC,iBAAiBF,KAA8C;IAC7E,MAAMG,SAASH,MAAMI,SAAS;IAC9B,OAAO,OAAOD,WAAW,YAAYE,OAAOC,SAAS,CAACH,WAAWA,UAAU,KAAKA,UAAUP,sBACtFO,SACAN;AACN;AAEA;;;;;CAKC,GACD,OAAO,SAASU,aAAaC,GAAY,EAAER,KAAsD;IAC/F,IAAI,OAAOQ,QAAQ,UAAU,OAAO;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/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"}
|
|
@@ -16,7 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { invalidOpeningHoursLines } from "@aglyn/aglyn/app-utils/local-business";
|
|
18
18
|
import { COMMERCE_MAX_PRICE_USD } from "./commerce.js";
|
|
19
|
-
import { summarizeShippingCoverage } from "./commerce-shipping.js";
|
|
19
|
+
import { summarizeShippingCoverage, describeRateConditions } from "./commerce-shipping.js";
|
|
20
20
|
import { storefrontTaxMisconfiguration } from "./commerce-tax-decision.js";
|
|
21
21
|
import { LOCAL_DELIVERY_POSTCODES_MAX, LOCAL_DELIVERY_ZONES_MAX, PICKUP_HOURS_MAX, PICKUP_INSTRUCTIONS_MAX, localDeliveryProblems, normalizeLocalDeliverySettings, normalizePickupSettings } from "./local-fulfillment-settings.js";
|
|
22
22
|
/*==========================================
|
|
@@ -444,6 +444,10 @@ function findLocation(locations, phrase) {
|
|
|
444
444
|
return found[0];
|
|
445
445
|
}
|
|
446
446
|
function rateSummary(rate) {
|
|
447
|
+
const conditions = describeRateConditions(rate);
|
|
448
|
+
return conditions ? `${rateKindSummary(rate)} (${conditions.toLowerCase()})` : rateKindSummary(rate);
|
|
449
|
+
}
|
|
450
|
+
function rateKindSummary(rate) {
|
|
447
451
|
switch(rate.kind){
|
|
448
452
|
case 'flat':
|
|
449
453
|
return rate.amountCents ? `${usd(rate.amountCents)} flat` : 'free';
|
|
@@ -460,6 +464,16 @@ function rateSummary(rate) {
|
|
|
460
464
|
return rate.kind;
|
|
461
465
|
}
|
|
462
466
|
}
|
|
467
|
+
const RATE_KEPT_FIELDS = [
|
|
468
|
+
'minSubtotalCents',
|
|
469
|
+
'maxSubtotalCents',
|
|
470
|
+
'minSubtotalByCurrency',
|
|
471
|
+
'maxSubtotalByCurrency',
|
|
472
|
+
'minGrams',
|
|
473
|
+
'maxGrams',
|
|
474
|
+
'amountsByCurrency',
|
|
475
|
+
'freeOverByCurrency'
|
|
476
|
+
];
|
|
463
477
|
function applyShipping(state, change, ids) {
|
|
464
478
|
var _state_settings_shipping, _current_zones, _current_rates, _ref, _ref1;
|
|
465
479
|
const current = (_state_settings_shipping = state.settings['shipping']) != null ? _state_settings_shipping : {};
|
|
@@ -539,7 +553,14 @@ function applyShipping(state, change, ids) {
|
|
|
539
553
|
return fail(409, `"${existing.name}" is a carrier rate; change it in Shipping settings`);
|
|
540
554
|
}
|
|
541
555
|
const kind = change.kind;
|
|
542
|
-
|
|
556
|
+
// What this change does not speak to stays as the merchant set it: the
|
|
557
|
+
// rate's conditions (AGL-4255) and its figures in other currencies
|
|
558
|
+
// (AGL-4248).
|
|
559
|
+
const kept = {};
|
|
560
|
+
for (const key of RATE_KEPT_FIELDS){
|
|
561
|
+
if ((existing == null ? void 0 : existing[key]) !== undefined) kept[key] = existing[key];
|
|
562
|
+
}
|
|
563
|
+
const rate = _extends({}, kept, {
|
|
543
564
|
id: (_ref = existing == null ? void 0 : existing.id) != null ? _ref : ids.rateId,
|
|
544
565
|
zoneId,
|
|
545
566
|
name: change.rateName,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/store-setup-content.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 { invalidOpeningHoursLines } from '@aglyn/aglyn/app-utils/local-business'\nimport { COMMERCE_MAX_PRICE_USD } from './commerce'\nimport {\n summarizeShippingCoverage,\n type ShippingRate,\n type ShippingSettings,\n type ShippingTier,\n type ShippingZone,\n} from './commerce-shipping'\nimport type { TaxRate, TaxSettings } from './commerce-tax'\nimport { storefrontTaxMisconfiguration } from './commerce-tax-decision'\nimport {\n LOCAL_DELIVERY_POSTCODES_MAX,\n LOCAL_DELIVERY_ZONES_MAX,\n PICKUP_HOURS_MAX,\n PICKUP_INSTRUCTIONS_MAX,\n localDeliveryProblems,\n normalizeLocalDeliverySettings,\n normalizePickupSettings,\n type LocalDeliverySettings,\n type LocalDeliveryZone,\n} from './local-fulfillment-settings'\nimport type { PickupLocationSettings } from './order-local-fulfillment'\n\n/*==========================================\n * STORE SETUP AN AI BUILD CHANGES (AGL-3749)\n *\n * One change to the store's shipping, pickup, local delivery or tax settings,\n * as the `store-settings` writer receives it, and the pure step that turns\n * the settings a site has into the settings it has after the change.\n *\n * Every field is one the console's cards already save, in the shape they\n * save it:\n *\n * - `shipping`: a zone (`settings/store.shipping.zones`) and one rate in it\n * (`.rates`), priced flat, free over a subtotal, or by subtotal or weight\n * tiers — the Shipping card's four kinds. Carrier rates are not offered:\n * they quote through a carrier account a person connects.\n * - `pickup`: the store-wide \"Offer free local pickup\" switch\n * (`shipping.localPickup`), or pickup at one of the store's inventory\n * locations (`locations/{id}.pickup`), as the Inventory locations card\n * saves it. A location is found, never created.\n * - `local-delivery`: the Local delivery card's settings\n * (`settings/store.localDelivery`) with postal-code zones. Distance zones\n * need the store placed on a map first, which is the card's to do.\n * - `tax`: how the store handles sales tax (`settings/store.tax.mode`),\n * whether prices include it, the store origin and manual rates. The\n * lodging and service rates are kept as they are.\n *\n * Nothing here names a price or a rate the change did not carry: a blank\n * flat rate charges nothing at checkout, so a flat or free-over rate needs\n * its amount, and a tax rate needs its percentage. Pure.\n *=========================================*/\n\n/** The resource the writer is registered under; the commerce record route `store-settings` links it. */\nexport const STORE_SETUP_RESOURCE = 'store-settings'\n\nexport const STORE_SETUP_SECTIONS = ['shipping', 'pickup', 'local-delivery', 'tax'] as const\nexport type StoreSetupSection = (typeof STORE_SETUP_SECTIONS)[number]\n\n/** The rate kinds an AI change may set: every kind of the Shipping card except carrier rates. */\nexport const STORE_SHIPPING_AI_KINDS = ['flat', 'free_over', 'price_tiers', 'weight_tiers'] as const\nexport type StoreShippingAiKind = (typeof STORE_SHIPPING_AI_KINDS)[number]\n\nexport const STORE_SHIPPING_ACTIONS = ['set', 'remove'] as const\nexport const STORE_TAX_MODES = ['manual', 'stripe', 'none'] as const\n\nexport const STORE_SETUP_NAME_MAX = 80\nexport const STORE_SETUP_COUNTRIES_MAX = 60\nexport const STORE_SHIPPING_TIERS_MAX = 10\nexport const STORE_SETUP_LOCATION_MAX = 80\nexport const STORE_TAX_LABEL_MAX = 60\n/** Grams; the heaviest tier a weight table may name (1,000 kg). */\nexport const STORE_SHIPPING_MAX_GRAMS = 1_000_000\n/** Two weeks, the longest preparation or lead time the cards keep. */\nexport const STORE_SETUP_MAX_MINUTES = 14 * 24 * 60\n\nexport interface StoreShippingChange {\n section: 'shipping'\n action: 'set' | 'remove'\n zoneName: string\n countries?: string[]\n rateName?: string\n kind?: StoreShippingAiKind\n amountCents?: number\n freeOverCents?: number\n tiers?: ShippingTier[]\n}\n\nexport interface StorePickupChange {\n section: 'pickup'\n /** An inventory location's name, city or address; absent = the store-wide switch. */\n location?: string\n enabled: boolean\n hours?: string\n instructions?: string\n readyWithinMinutes?: number\n}\n\nexport interface StoreLocalDeliveryChange {\n section: 'local-delivery'\n enabled: boolean\n country?: string\n location?: string\n zoneName?: string\n postcodes?: string[]\n feeCents?: number\n minimumCents?: number\n freeOverCents?: number\n removeZone?: boolean\n windows?: string\n leadTimeMinutes?: number\n daysAhead?: number\n instructions?: string\n}\n\nexport interface StoreTaxChange {\n section: 'tax'\n mode?: 'manual' | 'stripe' | 'none'\n pricesIncludeTax?: boolean\n originCountry?: string\n originState?: string\n rateCountry?: string\n rateState?: string\n ratePct?: number\n rateLabel?: string\n removeRate?: boolean\n}\n\nexport type StoreSetupChange = StoreShippingChange | StorePickupChange | StoreLocalDeliveryChange | StoreTaxChange\n\nexport type StoreSetupRead = { ok: true; value: StoreSetupChange } | { ok: false; problems: string[] }\n\nconst COUNTRY = /^[A-Z]{2}$/\nconst STATE = /^[A-Z0-9]{1,3}$/\n\ntype Raw = Readonly<Record<string, unknown>>\n\nconst has = (raw: Raw, key: string) => raw[key] !== undefined && raw[key] !== null && raw[key] !== ''\n\nfunction text(raw: Raw, key: string, max: number, problems: string[]): string | undefined {\n if (!has(raw, key)) return undefined\n const value = raw[key]\n if (typeof value !== 'string') {\n problems.push(`\"${key}\" must be text`)\n return undefined\n }\n const trimmed = value.trim()\n if (trimmed.length > max) problems.push(`\"${key}\" must be at most ${max} characters`)\n return trimmed || undefined\n}\n\nfunction bool(raw: Raw, key: string, problems: string[]): boolean | undefined {\n if (!has(raw, key)) return undefined\n if (typeof raw[key] !== 'boolean') {\n problems.push(`\"${key}\" must be true or false`)\n return undefined\n }\n return raw[key] as boolean\n}\n\nfunction number(raw: Raw, key: string, min: number, max: number, problems: string[]): number | undefined {\n if (!has(raw, key)) return undefined\n const value = raw[key]\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n problems.push(`\"${key}\" must be a number`)\n return undefined\n }\n if (value < min || value > max) {\n problems.push(`\"${key}\" must be between ${min} and ${max}`)\n return undefined\n }\n return value\n}\n\nfunction minutes(raw: Raw, key: string, problems: string[]): number | undefined {\n const value = number(raw, key, 0, STORE_SETUP_MAX_MINUTES, problems)\n return value === undefined ? undefined : Math.round(value)\n}\n\n/** Dollars to the cents the settings store. */\nfunction cents(raw: Raw, key: string, problems: string[]): number | undefined {\n const value = number(raw, key, 0, COMMERCE_MAX_PRICE_USD, problems)\n return value === undefined ? undefined : Math.round(value * 100)\n}\n\nfunction list(raw: Raw, key: string, max: number, problems: string[]): string[] | undefined {\n if (!has(raw, key)) return undefined\n const value = raw[key]\n if (!Array.isArray(value) || value.some((one) => typeof one !== 'string')) {\n problems.push(`\"${key}\" must be a list of text`)\n return undefined\n }\n const items = (value as string[]).map((one) => one.trim()).filter(Boolean)\n if (items.length > max) problems.push(`\"${key}\" must hold at most ${max}`)\n return items\n}\n\nfunction countryCode(raw: Raw, key: string, problems: string[]): string | undefined {\n const value = text(raw, key, 2, problems)?.toUpperCase()\n if (value !== undefined && !COUNTRY.test(value)) problems.push(`\"${key}\" must be a two-letter country code like US`)\n return value\n}\n\nfunction stateCode(raw: Raw, key: string, problems: string[]): string | undefined {\n const value = text(raw, key, 3, problems)?.toUpperCase()\n if (value !== undefined && !STATE.test(value)) problems.push(`\"${key}\" must be a state or region code like TX`)\n return value\n}\n\n/** Opening-hours lines; a `;` separates lines as a newline does. */\nfunction hoursText(raw: Raw, key: string, problems: string[]): string | undefined {\n const value = text(raw, key, PICKUP_HOURS_MAX, problems)\n if (value === undefined) return undefined\n const lines = value\n .split(/\\s*(?:;|\\r?\\n)\\s*/)\n .filter(Boolean)\n .join('\\n')\n const bad = invalidOpeningHoursLines(lines)\n if (bad.length) {\n problems.push(`\"${key}\" must be lines like \"Mo-Fr 09:00-17:00\" or \"Sa 10:00-14:00\"`)\n }\n return lines\n}\n\n/** \"50:5\" → up to 50 (dollars, or grams for weight) costs $5. */\nfunction tiersOf(raw: Raw, kind: StoreShippingAiKind | undefined, problems: string[]): ShippingTier[] | undefined {\n const entries = list(raw, 'tiers', STORE_SHIPPING_TIERS_MAX, problems)\n if (entries === undefined) return undefined\n const weight = kind === 'weight_tiers'\n const tiers: ShippingTier[] = []\n for (const entry of entries) {\n const match = /^\\s*\\$?([0-9]+(?:\\.[0-9]+)?)\\s*(?:g)?\\s*:\\s*\\$?([0-9]+(?:\\.[0-9]+)?)\\s*$/.exec(entry)\n const upTo = match ? Number(match[1]) : NaN\n const amount = match ? Number(match[2]) : NaN\n if (!match || !(upTo > 0) || amount > COMMERCE_MAX_PRICE_USD || (weight && upTo > STORE_SHIPPING_MAX_GRAMS)) {\n problems.push(`\"tiers\" holds \"${entry}\", which is not \"up to:price\" like \"50:5\"`)\n return undefined\n }\n tiers.push({ upTo: weight ? Math.round(upTo) : Math.round(upTo * 100), amountCents: Math.round(amount * 100) })\n }\n tiers.sort((a, b) => a.upTo - b.upTo)\n if (tiers.some((tier, index) => index > 0 && tier.upTo === tiers[index - 1].upTo)) {\n problems.push('\"tiers\" names the same limit twice')\n }\n return tiers\n}\n\nconst KNOWN: Record<StoreSetupSection, readonly string[]> = {\n shipping: ['action', 'zoneName', 'countries', 'rateName', 'kind', 'amountUsd', 'freeOverUsd', 'tiers'],\n pickup: ['location', 'enabled', 'hours', 'instructions', 'readyWithinMinutes'],\n 'local-delivery': [\n 'enabled',\n 'country',\n 'location',\n 'zoneName',\n 'postcodes',\n 'feeUsd',\n 'minimumUsd',\n 'freeOverUsd',\n 'removeZone',\n 'windows',\n 'leadTimeMinutes',\n 'daysAhead',\n 'instructions',\n ],\n tax: [\n 'mode',\n 'pricesIncludeTax',\n 'originCountry',\n 'originState',\n 'rateCountry',\n 'rateState',\n 'ratePercent',\n 'rateLabel',\n 'removeRate',\n ],\n}\n\nfunction readShipping(raw: Raw, problems: string[]): StoreShippingChange {\n const action = has(raw, 'action') ? raw['action'] : 'set'\n if (!STORE_SHIPPING_ACTIONS.includes(action as never)) problems.push('\"action\" must be set or remove')\n const zoneName = text(raw, 'zoneName', STORE_SETUP_NAME_MAX, problems)\n if (!zoneName) problems.push('\"zoneName\" is required: the shipping zone, like \"United States\"')\n const countries = list(raw, 'countries', STORE_SETUP_COUNTRIES_MAX, problems)?.map((code) => code.toUpperCase())\n for (const code of countries ?? []) {\n if (code !== '*' && !COUNTRY.test(code)) {\n problems.push(`\"countries\" holds \"${code}\", which is not a two-letter country code or *`)\n break\n }\n }\n const rateName = text(raw, 'rateName', STORE_SETUP_NAME_MAX, problems)\n const kind = has(raw, 'kind') ? (raw['kind'] as StoreShippingAiKind) : undefined\n if (kind !== undefined && !STORE_SHIPPING_AI_KINDS.includes(kind)) {\n problems.push(`\"kind\" must be one of ${STORE_SHIPPING_AI_KINDS.join(', ')}`)\n }\n const amountCents = cents(raw, 'amountUsd', problems)\n const freeOverCents = cents(raw, 'freeOverUsd', problems)\n const tiers = tiersOf(raw, kind, problems)\n if (action === 'set') {\n // A rate with no name is dropped at checkout (AGL-1791), and a blank\n // amount charges nothing: both are the person's to state.\n if (!rateName) problems.push('\"rateName\" is required: what the shopper sees, like \"Standard\"')\n if (!kind) problems.push('\"kind\" is required')\n if ((kind === 'flat' || kind === 'free_over') && amountCents === undefined) {\n problems.push(`\"amountUsd\" is required for a ${kind === 'flat' ? 'flat' : 'free-over'} rate`)\n }\n if (kind === 'free_over' && !freeOverCents) problems.push('\"freeOverUsd\" is required for a free-over rate')\n if ((kind === 'price_tiers' || kind === 'weight_tiers') && !tiers?.length) {\n problems.push('\"tiers\" is required for a tiered rate')\n }\n }\n return {\n section: 'shipping',\n action: action as StoreShippingChange['action'],\n zoneName: zoneName ?? '',\n ...(countries ? { countries } : {}),\n ...(rateName ? { rateName } : {}),\n ...(kind ? { kind } : {}),\n ...(amountCents !== undefined ? { amountCents } : {}),\n ...(freeOverCents !== undefined ? { freeOverCents } : {}),\n ...(tiers ? { tiers } : {}),\n }\n}\n\nfunction readPickup(raw: Raw, problems: string[]): StorePickupChange {\n const location = text(raw, 'location', STORE_SETUP_LOCATION_MAX, problems)\n const hours = hoursText(raw, 'hours', problems)\n const instructions = text(raw, 'instructions', PICKUP_INSTRUCTIONS_MAX, problems)\n const readyWithinMinutes = minutes(raw, 'readyWithinMinutes', problems)\n if (!location && (hours !== undefined || instructions !== undefined || readyWithinMinutes !== undefined)) {\n problems.push('Pickup hours, instructions and preparation time belong to a location: name the inventory location')\n }\n return {\n section: 'pickup',\n enabled: bool(raw, 'enabled', problems) ?? true,\n ...(location ? { location } : {}),\n ...(hours !== undefined ? { hours } : {}),\n ...(instructions !== undefined ? { instructions } : {}),\n ...(readyWithinMinutes !== undefined ? { readyWithinMinutes } : {}),\n }\n}\n\nfunction readLocalDelivery(raw: Raw, problems: string[]): StoreLocalDeliveryChange {\n const zoneName = text(raw, 'zoneName', STORE_SETUP_NAME_MAX, problems)\n const postcodes = list(raw, 'postcodes', LOCAL_DELIVERY_POSTCODES_MAX, problems)\n const feeCents = cents(raw, 'feeUsd', problems)\n const minimumCents = cents(raw, 'minimumUsd', problems)\n const freeOverCents = cents(raw, 'freeOverUsd', problems)\n const removeZone = bool(raw, 'removeZone', problems)\n if (!zoneName && (postcodes || feeCents !== undefined || minimumCents !== undefined || freeOverCents !== undefined || removeZone)) {\n problems.push('\"zoneName\" is required to add, change or remove a delivery zone')\n }\n const daysAhead = number(raw, 'daysAhead', 1, 30, problems)\n return {\n section: 'local-delivery',\n enabled: bool(raw, 'enabled', problems) ?? true,\n ...(has(raw, 'country') ? { country: countryCode(raw, 'country', problems) } : {}),\n ...(has(raw, 'location') ? { location: text(raw, 'location', STORE_SETUP_LOCATION_MAX, problems) } : {}),\n ...(zoneName ? { zoneName } : {}),\n ...(postcodes ? { postcodes } : {}),\n ...(feeCents !== undefined ? { feeCents } : {}),\n ...(minimumCents !== undefined ? { minimumCents } : {}),\n ...(freeOverCents !== undefined ? { freeOverCents } : {}),\n ...(removeZone ? { removeZone } : {}),\n ...(has(raw, 'windows') ? { windows: hoursText(raw, 'windows', problems) } : {}),\n ...(has(raw, 'leadTimeMinutes') ? { leadTimeMinutes: minutes(raw, 'leadTimeMinutes', problems) } : {}),\n ...(daysAhead !== undefined ? { daysAhead: Math.round(daysAhead) } : {}),\n ...(has(raw, 'instructions') ? { instructions: text(raw, 'instructions', PICKUP_INSTRUCTIONS_MAX, problems) } : {}),\n }\n}\n\nfunction readTax(raw: Raw, problems: string[]): StoreTaxChange {\n const mode = has(raw, 'mode') ? raw['mode'] : undefined\n if (mode !== undefined && !STORE_TAX_MODES.includes(mode as never)) {\n problems.push(`\"mode\" must be one of ${STORE_TAX_MODES.join(', ')}`)\n }\n const change: StoreTaxChange = {\n section: 'tax',\n ...(mode !== undefined ? { mode: mode as StoreTaxChange['mode'] } : {}),\n }\n const pricesIncludeTax = bool(raw, 'pricesIncludeTax', problems)\n if (pricesIncludeTax !== undefined) change.pricesIncludeTax = pricesIncludeTax\n const originCountry = countryCode(raw, 'originCountry', problems)\n if (originCountry) change.originCountry = originCountry\n const originState = stateCode(raw, 'originState', problems)\n if (originState) change.originState = originState\n const rateCountry = countryCode(raw, 'rateCountry', problems)\n if (rateCountry) change.rateCountry = rateCountry\n const rateState = stateCode(raw, 'rateState', problems)\n if (rateState) change.rateState = rateState\n if (has(raw, 'ratePercent')) {\n const value = raw['ratePercent']\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > 100) {\n problems.push('\"ratePercent\" must be a percentage above 0 and at most 100')\n } else change.ratePct = value\n }\n const rateLabel = text(raw, 'rateLabel', STORE_TAX_LABEL_MAX, problems)\n if (rateLabel) change.rateLabel = rateLabel\n const removeRate = bool(raw, 'removeRate', problems)\n if (removeRate) change.removeRate = true\n\n const touchesRate = change.ratePct !== undefined || change.removeRate || change.rateState || change.rateLabel\n if (touchesRate && !change.rateCountry) problems.push('\"rateCountry\" is required with a tax rate')\n if (change.rateCountry && change.ratePct === undefined && !change.removeRate) {\n // Never a rate the person did not state.\n problems.push('\"ratePercent\" is required with a tax rate: the percentage the request states')\n }\n if (change.ratePct !== undefined && change.removeRate) problems.push('Give \"ratePercent\" or \"removeRate\", not both')\n if (originState && !originCountry) problems.push('\"originCountry\" is required with \"originState\"')\n const said = Object.keys(change).filter((key) => key !== 'section')\n if (!said.length) {\n problems.push(\n 'Say how the store handles sales tax: manual rates (with the percentage), automatic calculation, or not collecting it',\n )\n }\n return change\n}\n\n/** Reads a change from content; the problems name what is wrong, in words a person reads. */\nexport function readStoreSetupChange(content: Raw): StoreSetupRead {\n const section = content['section'] as StoreSetupSection\n if (!STORE_SETUP_SECTIONS.includes(section)) {\n return { ok: false, problems: [`\"section\" must be one of ${STORE_SETUP_SECTIONS.join(', ')}`] }\n }\n const problems: string[] = []\n for (const key of Object.keys(content)) {\n if (key !== 'section' && !KNOWN[section].includes(key)) problems.push(`\"${key}\" is not a ${section} setting`)\n }\n const value =\n section === 'shipping'\n ? readShipping(content, problems)\n : section === 'pickup'\n ? readPickup(content, problems)\n : section === 'local-delivery'\n ? readLocalDelivery(content, problems)\n : readTax(content, problems)\n return problems.length ? { ok: false, problems } : { ok: true, value }\n}\n\n// ---------------------------------------------------------------------------\n// Applying a change\n// ---------------------------------------------------------------------------\n\n/** An inventory location as the writer reads it. */\nexport interface StoreSetupLocation {\n id: string\n name?: string\n address?: string\n city?: string\n pickup?: unknown\n}\n\n/** What the change writes: one map of the settings document, or one location's pickup. */\nexport type StoreSetupWrite =\n | { target: 'settings'; field: 'shipping' | 'localDelivery' | 'tax'; value: Record<string, unknown> }\n | { target: 'location'; locationId: string; value: PickupLocationSettings }\n\nexport type StoreSetupApplied =\n | {\n ok: true\n /** `null` when the settings already say what the change asks: nothing to write. */\n write: StoreSetupWrite | null\n /** One sentence on what the store now does. */\n summary: string\n /** What the person should know, in the console's words. */\n warnings: string[]\n }\n | { ok: false; status: 400 | 404 | 409; error: string }\n\nexport interface StoreSetupState {\n /** `hosts/{hostId}/settings/store`, or `{}`. */\n settings: Readonly<Record<string, unknown>>\n locations: readonly StoreSetupLocation[]\n}\n\n/** Ids for what a change creates, derived from the request so a retry makes the same ones. */\nexport interface StoreSetupIds {\n zoneId: string\n rateId: string\n}\n\nconst fail = (status: 400 | 404 | 409, error: string): StoreSetupApplied => ({ ok: false, status, error })\n\n/** Key-order-blind equality over plain JSON values. */\nexport function sameSetting(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (Array.isArray(a) || Array.isArray(b)) {\n return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((one, index) => sameSetting(one, b[index]))\n }\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n const left = Object.entries(a as Record<string, unknown>).filter(([, value]) => value !== undefined)\n const right = Object.entries(b as Record<string, unknown>).filter(([, value]) => value !== undefined)\n return left.length === right.length && left.every(([key, value]) => sameSetting(value, (b as Record<string, unknown>)[key]))\n }\n return false\n}\n\nconst lower = (value: unknown) => String(value ?? '').trim().toLowerCase()\nconst usd = (centsValue: number) => `$${(centsValue / 100).toFixed(centsValue % 100 ? 2 : 0)}`\nconst sameSet = (a: readonly string[], b: readonly string[]) =>\n a.length === b.length && [...a].sort().join(',') === [...b].sort().join(',')\n\n/** The store's locations a phrase names: by exact name first, then by city or address. */\nexport function matchStoreLocations(\n locations: readonly StoreSetupLocation[],\n phrase: string,\n): StoreSetupLocation[] {\n const wanted = lower(phrase)\n const byName = locations.filter((one) => lower(one.name) === wanted)\n if (byName.length) return byName\n return locations.filter(\n (one) => lower(one.city) === wanted || (wanted.length >= 3 && lower(one.address).includes(wanted)) || lower(one.name).includes(wanted),\n )\n}\n\nfunction findLocation(\n locations: readonly StoreSetupLocation[],\n phrase: string,\n): StoreSetupLocation | StoreSetupApplied {\n const found = matchStoreLocations(locations, phrase)\n if (!found.length) {\n return fail(\n 404,\n `The store has no inventory location matching \"${phrase}\". Add it under Products → Inventory locations, then ask again.`,\n )\n }\n if (found.length > 1) {\n return fail(409, `More than one location matches \"${phrase}\" (${found.map((one) => one.name || one.id).join(', ')}); say which`)\n }\n return found[0]\n}\n\nfunction rateSummary(rate: ShippingRate): string {\n switch (rate.kind) {\n case 'flat':\n return rate.amountCents ? `${usd(rate.amountCents)} flat` : 'free'\n case 'free_over':\n return `free over ${usd(rate.freeOverCents ?? 0)}, otherwise ${usd(rate.amountCents ?? 0)}`\n case 'price_tiers':\n return `${(rate.tiers ?? []).length} subtotal tiers`\n case 'weight_tiers':\n return `${(rate.tiers ?? []).length} weight tiers`\n default:\n return rate.kind\n }\n}\n\nfunction applyShipping(state: StoreSetupState, change: StoreShippingChange, ids: StoreSetupIds): StoreSetupApplied {\n const current = (state.settings['shipping'] ?? {}) as ShippingSettings\n const zones: ShippingZone[] = [...(current.zones ?? [])]\n const rates: ShippingRate[] = [...(current.rates ?? [])]\n const zoneIndex = (() => {\n const byName = zones.findIndex((zone) => lower(zone.name) === lower(change.zoneName))\n if (byName >= 0 || !change.countries?.length) return byName\n return zones.findIndex((zone) => sameSet((zone.countries ?? []).map((code) => String(code).trim().toUpperCase()), change.countries ?? []))\n })()\n const zone = zoneIndex >= 0 ? zones[zoneIndex] : undefined\n\n if (change.action === 'remove') {\n if (!zone) return { ok: true, write: null, summary: `There is no \"${change.zoneName}\" shipping zone.`, warnings: [] }\n if (change.rateName) {\n const kept = rates.filter((rate) => !(rate.zoneId === zone.id && lower(rate.name) === lower(change.rateName)))\n if (kept.length === rates.length) {\n return { ok: true, write: null, summary: `\"${zone.name}\" has no \"${change.rateName}\" rate.`, warnings: [] }\n }\n return shippingResult(current, { ...current, zones, rates: kept }, `Removed the \"${change.rateName}\" rate from ${zone.name}.`)\n }\n // The card's ✕ on a zone: the zone and its rates go together.\n return shippingResult(\n current,\n { ...current, zones: zones.filter((one) => one.id !== zone.id), rates: rates.filter((rate) => rate.zoneId !== zone.id) },\n `Removed the ${zone.name} shipping zone and its rates.`,\n )\n }\n\n let zoneId: string\n if (zone) {\n zoneId = zone.id\n if (change.countries?.length && !sameSet(zone.countries ?? [], change.countries)) {\n zones[zoneIndex] = { ...zone, countries: [...change.countries] }\n }\n } else {\n if (!change.countries?.length) {\n return fail(400, `Say which countries the new \"${change.zoneName}\" zone ships to (two-letter codes, or * for everywhere else)`)\n }\n zoneId = ids.zoneId\n zones.push({ id: zoneId, name: change.zoneName, countries: [...change.countries] })\n }\n const rateIndex = rates.findIndex((rate) => rate.zoneId === zoneId && lower(rate.name) === lower(change.rateName))\n const existing = rateIndex >= 0 ? rates[rateIndex] : undefined\n if (existing?.kind === 'carrier') {\n return fail(409, `\"${existing.name}\" is a carrier rate; change it in Shipping settings`)\n }\n const kind = change.kind as StoreShippingAiKind\n const rate: ShippingRate = {\n id: existing?.id ?? ids.rateId,\n zoneId,\n name: change.rateName as string,\n kind,\n ...(kind === 'flat' || kind === 'free_over' ? { amountCents: change.amountCents } : {}),\n ...(kind === 'free_over' ? { freeOverCents: change.freeOverCents } : {}),\n ...(kind === 'price_tiers' || kind === 'weight_tiers' ? { tiers: change.tiers } : {}),\n }\n if (rateIndex >= 0) rates[rateIndex] = rate\n else rates.push(rate)\n const zoneName = zone?.name ?? change.zoneName\n return shippingResult(current, { ...current, zones, rates }, `${zoneName}: \"${rate.name}\" is ${rateSummary(rate)}.`, rate)\n}\n\nfunction shippingResult(\n before: ShippingSettings,\n after: ShippingSettings,\n summary: string,\n changed?: ShippingRate,\n): StoreSetupApplied {\n const coverage = summarizeShippingCoverage(after)\n const warnings: string[] = []\n if (coverage.unserved.length && !coverage.shipsNowhere) {\n warnings.push(`Checkout turns away buyers in ${coverage.unserved.join(', ')}: no rate reaches them.`)\n }\n if (changed?.kind === 'price_tiers' || changed?.kind === 'weight_tiers') {\n warnings.push(`\"${changed.name}\" applies only up to its last tier; a larger or heavier order gets no rate from it.`)\n }\n return {\n ok: true,\n write: sameSetting(before, after) ? null : { target: 'settings', field: 'shipping', value: after as Record<string, unknown> },\n summary,\n warnings,\n }\n}\n\nfunction applyPickup(state: StoreSetupState, change: StorePickupChange): StoreSetupApplied {\n if (!change.location) {\n const current = (state.settings['shipping'] ?? {}) as ShippingSettings\n const after: ShippingSettings = { ...current, localPickup: change.enabled }\n return {\n ok: true,\n write: Boolean(current.localPickup) === change.enabled ? null : { target: 'settings', field: 'shipping', value: after as Record<string, unknown> },\n summary: change.enabled ? 'Checkout offers free local pickup.' : 'Checkout no longer offers free local pickup.',\n warnings: change.enabled ? ['Pickup is a collection choice; it does not widen where the store ships.'] : [],\n }\n }\n const found = findLocation(state.locations, change.location)\n if ('ok' in found) return found\n const before = normalizePickupSettings(found.pickup)\n const after = normalizePickupSettings({\n ...before,\n enabled: change.enabled,\n ...(change.hours !== undefined ? { hours: change.hours } : {}),\n ...(change.instructions !== undefined ? { instructions: change.instructions } : {}),\n ...(change.readyWithinMinutes !== undefined ? { readyWithinMinutes: change.readyWithinMinutes } : {}),\n })\n const name = found.name || 'the location'\n return {\n ok: true,\n write: sameSetting(before, after) ? null : { target: 'location', locationId: found.id, value: after },\n summary: after.enabled ? `Buyers can pick up orders at ${name}.` : `Pickup at ${name} is off.`,\n warnings: after.enabled && !after.hours ? [`${name} has no pickup hours yet; buyers are not told when to come.`] : [],\n }\n}\n\nfunction applyLocalDelivery(state: StoreSetupState, change: StoreLocalDeliveryChange, ids: StoreSetupIds): StoreSetupApplied {\n const before = normalizeLocalDeliverySettings(state.settings['localDelivery'])\n const after: LocalDeliverySettings = { ...before, zones: [...(before.zones ?? [])] }\n if (!after.zones?.length) delete after.zones\n if (change.enabled) after.enabled = true\n else delete after.enabled\n if (change.country) after.country = change.country\n if (change.location) {\n const found = findLocation(state.locations, change.location)\n if ('ok' in found) return found\n after.locationId = found.id\n }\n if (change.windows !== undefined) after.windows = change.windows\n if (change.leadTimeMinutes !== undefined) after.leadTimeMinutes = change.leadTimeMinutes\n if (change.daysAhead !== undefined) after.daysAhead = change.daysAhead\n if (change.instructions !== undefined) after.instructions = change.instructions\n if (change.zoneName) {\n const zones: LocalDeliveryZone[] = [...(after.zones ?? [])]\n const index = zones.findIndex((zone) => lower(zone.name) === lower(change.zoneName))\n if (change.removeZone) {\n if (index >= 0) zones.splice(index, 1)\n } else if (index >= 0) {\n const zone = zones[index]\n if (change.postcodes && zone.kind === 'radius') {\n return fail(409, `\"${zone.name}\" is a distance zone; change it under Local delivery`)\n }\n zones[index] = {\n ...zone,\n ...(change.postcodes ? { postcodes: change.postcodes } : {}),\n ...(change.feeCents !== undefined ? { feeCents: change.feeCents } : {}),\n ...(change.minimumCents !== undefined ? { minimumCents: change.minimumCents } : {}),\n ...(change.freeOverCents !== undefined ? { freeOverCents: change.freeOverCents } : {}),\n }\n } else {\n if (!change.postcodes?.length) return fail(400, `Say which postal codes the \"${change.zoneName}\" zone delivers to`)\n if (change.feeCents === undefined) return fail(400, `Say what delivery to \"${change.zoneName}\" costs (0 for free)`)\n if (zones.length >= LOCAL_DELIVERY_ZONES_MAX) return fail(409, `Local delivery holds at most ${LOCAL_DELIVERY_ZONES_MAX} zones`)\n zones.push({\n id: ids.zoneId,\n name: change.zoneName,\n kind: 'postcode',\n postcodes: change.postcodes,\n feeCents: change.feeCents,\n ...(change.minimumCents !== undefined ? { minimumCents: change.minimumCents } : {}),\n ...(change.freeOverCents !== undefined ? { freeOverCents: change.freeOverCents } : {}),\n })\n }\n after.zones = zones\n }\n const normalized = normalizeLocalDeliverySettings(after)\n const problems = localDeliveryProblems(normalized)\n if (problems.length) {\n return fail(400, `Local delivery can't be switched on yet: ${problems.join(' ')}`)\n }\n return {\n ok: true,\n write: sameSetting(before, normalized)\n ? null\n : { target: 'settings', field: 'localDelivery', value: normalized as Record<string, unknown> },\n summary: normalized.enabled\n ? `The store delivers locally to ${(normalized.zones ?? []).length} zone${(normalized.zones ?? []).length === 1 ? '' : 's'}.`\n : 'Local delivery is off.',\n warnings: normalized.enabled && !normalized.locationId ? ['No location is set for delivery orders to leave from.'] : [],\n }\n}\n\nconst TAX_MODE_WORDS: Record<string, string> = {\n manual: 'manual rates',\n stripe: 'automatic calculation',\n none: 'not collecting sales tax',\n}\n\nfunction applyTax(state: StoreSetupState, change: StoreTaxChange): StoreSetupApplied {\n const before = (state.settings['tax'] ?? {}) as TaxSettings\n const after: TaxSettings = { ...before }\n const settingRate = change.ratePct !== undefined\n if (change.mode) after.mode = change.mode\n else if (settingRate && after.mode === undefined) after.mode = 'manual'\n if (settingRate && after.mode !== 'manual') {\n return fail(\n 409,\n `This store uses ${TAX_MODE_WORDS[String(after.mode)] ?? 'another tax mode'}, so a manual rate would not apply. Ask to switch to manual rates as well.`,\n )\n }\n if (change.pricesIncludeTax !== undefined) after.pricesIncludeTax = change.pricesIncludeTax\n if (change.originCountry) {\n after.origin = {\n country: change.originCountry,\n ...(change.originState ? { state: change.originState } : {}),\n }\n }\n if (change.rateCountry) {\n const rates: TaxRate[] = [...(before.rates ?? [])]\n const index = rates.findIndex(\n (rate) =>\n String(rate.country ?? '').toUpperCase() === change.rateCountry &&\n String(rate.state ?? '').toUpperCase() === (change.rateState ?? ''),\n )\n if (change.removeRate) {\n if (index >= 0) rates.splice(index, 1)\n } else {\n const rate: TaxRate = {\n country: change.rateCountry,\n ...(change.rateState ? { state: change.rateState } : {}),\n pct: change.ratePct as number,\n ...(change.rateLabel ? { label: change.rateLabel } : index >= 0 && rates[index].label ? { label: rates[index].label } : {}),\n }\n if (index >= 0) rates[index] = rate\n else rates.push(rate)\n }\n after.rates = rates\n }\n // Manual mode with no origin refuses every sale (AGL-2145): never leave a store there.\n if (storefrontTaxMisconfiguration(after)) {\n return fail(400, 'Manual tax rates need the store’s address: say which country (and state) the store sells from.')\n }\n const warnings: string[] = []\n if (after.mode === 'manual' && !(after.rates ?? []).length) {\n warnings.push('No tax rate is set yet, so orders are charged no sales tax.')\n }\n if (after.mode === 'stripe') {\n warnings.push('Automatic tax is calculated per buyer location at checkout; the register cannot calculate it for in-person sales.')\n }\n const mode = TAX_MODE_WORDS[String(after.mode)] ?? 'undecided'\n const rateLine = settingRate\n ? ` ${change.ratePct}% for ${change.rateCountry}${change.rateState ? `-${change.rateState}` : ''}.`\n : ''\n return {\n ok: true,\n write: sameSetting(before, after) ? null : { target: 'settings', field: 'tax', value: after as Record<string, unknown> },\n summary: `Sales tax: ${mode}.${rateLine}`,\n warnings,\n }\n}\n\n/** The settings after a change, what to write, and what the person is told. */\nexport function applyStoreSetupChange(\n state: StoreSetupState,\n change: StoreSetupChange,\n ids: StoreSetupIds,\n): StoreSetupApplied {\n switch (change.section) {\n case 'shipping':\n return applyShipping(state, change, ids)\n case 'pickup':\n return applyPickup(state, change)\n case 'local-delivery':\n return applyLocalDelivery(state, change, ids)\n case 'tax':\n return applyTax(state, change)\n }\n}\n\n/** What a reader is told about a store's setup, for the writer's `read`. */\nexport function storeSetupFacts(settings: Readonly<Record<string, unknown>>): Record<string, unknown> {\n const shipping = (settings['shipping'] ?? {}) as ShippingSettings\n const tax = (settings['tax'] ?? {}) as TaxSettings\n const delivery = normalizeLocalDeliverySettings(settings['localDelivery'])\n return {\n shippingZones: (shipping.zones ?? []).length,\n shippingRates: (shipping.rates ?? []).length,\n localPickup: Boolean(shipping.localPickup),\n localDelivery: Boolean(delivery.enabled),\n taxMode: tax.mode ?? null,\n taxRates: (tax.rates ?? []).length,\n live: true,\n }\n}\n"],"names":["invalidOpeningHoursLines","COMMERCE_MAX_PRICE_USD","summarizeShippingCoverage","storefrontTaxMisconfiguration","LOCAL_DELIVERY_POSTCODES_MAX","LOCAL_DELIVERY_ZONES_MAX","PICKUP_HOURS_MAX","PICKUP_INSTRUCTIONS_MAX","localDeliveryProblems","normalizeLocalDeliverySettings","normalizePickupSettings","STORE_SETUP_RESOURCE","STORE_SETUP_SECTIONS","STORE_SHIPPING_AI_KINDS","STORE_SHIPPING_ACTIONS","STORE_TAX_MODES","STORE_SETUP_NAME_MAX","STORE_SETUP_COUNTRIES_MAX","STORE_SHIPPING_TIERS_MAX","STORE_SETUP_LOCATION_MAX","STORE_TAX_LABEL_MAX","STORE_SHIPPING_MAX_GRAMS","STORE_SETUP_MAX_MINUTES","COUNTRY","STATE","has","raw","key","undefined","text","max","problems","value","push","trimmed","trim","length","bool","number","min","Number","isFinite","minutes","Math","round","cents","list","Array","isArray","some","one","items","map","filter","Boolean","countryCode","toUpperCase","test","stateCode","hoursText","lines","split","join","bad","tiersOf","kind","entries","weight","tiers","entry","match","exec","upTo","NaN","amount","amountCents","sort","a","b","tier","index","KNOWN","shipping","pickup","tax","readShipping","action","includes","zoneName","countries","code","rateName","freeOverCents","section","readPickup","location","hours","instructions","readyWithinMinutes","enabled","readLocalDelivery","postcodes","feeCents","minimumCents","removeZone","daysAhead","country","windows","leadTimeMinutes","readTax","mode","change","pricesIncludeTax","originCountry","originState","rateCountry","rateState","ratePct","rateLabel","removeRate","touchesRate","said","Object","keys","readStoreSetupChange","content","ok","fail","status","error","sameSetting","every","left","right","lower","String","toLowerCase","usd","centsValue","toFixed","sameSet","matchStoreLocations","locations","phrase","wanted","byName","name","city","address","findLocation","found","id","rateSummary","rate","applyShipping","state","ids","current","settings","zones","rates","zoneIndex","findIndex","zone","write","summary","warnings","kept","zoneId","shippingResult","rateIndex","existing","rateId","before","after","changed","coverage","unserved","shipsNowhere","target","field","applyPickup","localPickup","locationId","applyLocalDelivery","normalized","splice","TAX_MODE_WORDS","manual","stripe","none","applyTax","settingRate","origin","pct","label","rateLine","applyStoreSetupChange","storeSetupFacts","delivery","shippingZones","shippingRates","localDelivery","taxMode","taxRates","live"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,wBAAwB,QAAQ,wCAAuC;AAChF,SAASC,sBAAsB,QAAQ,gBAAY;AACnD,SACEC,yBAAyB,QAKpB,yBAAqB;AAE5B,SAASC,6BAA6B,QAAQ,6BAAyB;AACvE,SACEC,4BAA4B,EAC5BC,wBAAwB,EACxBC,gBAAgB,EAChBC,uBAAuB,EACvBC,qBAAqB,EACrBC,8BAA8B,EAC9BC,uBAAuB,QAGlB,kCAA8B;AAGrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA4B2C,GAE3C,sGAAsG,GACtG,OAAO,MAAMC,uB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EAAE9C,MAAM;QAC5CqK,eAAe,EAACvH,kBAAAA,SAAS8E,KAAK,YAAd9E,kBAAkB,EAAE,EAAE9C,MAAM;QAC5CkJ,aAAahI,QAAQ4B,SAASoG,WAAW;QACzCoB,eAAepJ,QAAQiJ,SAASpG,OAAO;QACvCwG,OAAO,GAAEvH,YAAAA,IAAI0B,IAAI,YAAR1B,YAAY;QACrBwH,UAAU,EAACxH,aAAAA,IAAI4E,KAAK,YAAT5E,aAAa,EAAE,EAAEhD,MAAM;QAClCyK,MAAM;IACR;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/store-setup-content.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 { invalidOpeningHoursLines } from '@aglyn/aglyn/app-utils/local-business'\nimport { COMMERCE_MAX_PRICE_USD } from './commerce'\nimport {\n summarizeShippingCoverage,\n describeRateConditions,\n type ShippingRate,\n type ShippingSettings,\n type ShippingTier,\n type ShippingZone,\n} from './commerce-shipping'\nimport type { TaxRate, TaxSettings } from './commerce-tax'\nimport { storefrontTaxMisconfiguration } from './commerce-tax-decision'\nimport {\n LOCAL_DELIVERY_POSTCODES_MAX,\n LOCAL_DELIVERY_ZONES_MAX,\n PICKUP_HOURS_MAX,\n PICKUP_INSTRUCTIONS_MAX,\n localDeliveryProblems,\n normalizeLocalDeliverySettings,\n normalizePickupSettings,\n type LocalDeliverySettings,\n type LocalDeliveryZone,\n} from './local-fulfillment-settings'\nimport type { PickupLocationSettings } from './order-local-fulfillment'\n\n/*==========================================\n * STORE SETUP AN AI BUILD CHANGES (AGL-3749)\n *\n * One change to the store's shipping, pickup, local delivery or tax settings,\n * as the `store-settings` writer receives it, and the pure step that turns\n * the settings a site has into the settings it has after the change.\n *\n * Every field is one the console's cards already save, in the shape they\n * save it:\n *\n * - `shipping`: a zone (`settings/store.shipping.zones`) and one rate in it\n * (`.rates`), priced flat, free over a subtotal, or by subtotal or weight\n * tiers — the Shipping card's four kinds. Carrier rates are not offered:\n * they quote through a carrier account a person connects.\n * - `pickup`: the store-wide \"Offer free local pickup\" switch\n * (`shipping.localPickup`), or pickup at one of the store's inventory\n * locations (`locations/{id}.pickup`), as the Inventory locations card\n * saves it. A location is found, never created.\n * - `local-delivery`: the Local delivery card's settings\n * (`settings/store.localDelivery`) with postal-code zones. Distance zones\n * need the store placed on a map first, which is the card's to do.\n * - `tax`: how the store handles sales tax (`settings/store.tax.mode`),\n * whether prices include it, the store origin and manual rates. The\n * lodging and service rates are kept as they are.\n *\n * Nothing here names a price or a rate the change did not carry: a blank\n * flat rate charges nothing at checkout, so a flat or free-over rate needs\n * its amount, and a tax rate needs its percentage. Pure.\n *=========================================*/\n\n/** The resource the writer is registered under; the commerce record route `store-settings` links it. */\nexport const STORE_SETUP_RESOURCE = 'store-settings'\n\nexport const STORE_SETUP_SECTIONS = ['shipping', 'pickup', 'local-delivery', 'tax'] as const\nexport type StoreSetupSection = (typeof STORE_SETUP_SECTIONS)[number]\n\n/** The rate kinds an AI change may set: every kind of the Shipping card except carrier rates. */\nexport const STORE_SHIPPING_AI_KINDS = ['flat', 'free_over', 'price_tiers', 'weight_tiers'] as const\nexport type StoreShippingAiKind = (typeof STORE_SHIPPING_AI_KINDS)[number]\n\nexport const STORE_SHIPPING_ACTIONS = ['set', 'remove'] as const\nexport const STORE_TAX_MODES = ['manual', 'stripe', 'none'] as const\n\nexport const STORE_SETUP_NAME_MAX = 80\nexport const STORE_SETUP_COUNTRIES_MAX = 60\nexport const STORE_SHIPPING_TIERS_MAX = 10\nexport const STORE_SETUP_LOCATION_MAX = 80\nexport const STORE_TAX_LABEL_MAX = 60\n/** Grams; the heaviest tier a weight table may name (1,000 kg). */\nexport const STORE_SHIPPING_MAX_GRAMS = 1_000_000\n/** Two weeks, the longest preparation or lead time the cards keep. */\nexport const STORE_SETUP_MAX_MINUTES = 14 * 24 * 60\n\nexport interface StoreShippingChange {\n section: 'shipping'\n action: 'set' | 'remove'\n zoneName: string\n countries?: string[]\n rateName?: string\n kind?: StoreShippingAiKind\n amountCents?: number\n freeOverCents?: number\n tiers?: ShippingTier[]\n}\n\nexport interface StorePickupChange {\n section: 'pickup'\n /** An inventory location's name, city or address; absent = the store-wide switch. */\n location?: string\n enabled: boolean\n hours?: string\n instructions?: string\n readyWithinMinutes?: number\n}\n\nexport interface StoreLocalDeliveryChange {\n section: 'local-delivery'\n enabled: boolean\n country?: string\n location?: string\n zoneName?: string\n postcodes?: string[]\n feeCents?: number\n minimumCents?: number\n freeOverCents?: number\n removeZone?: boolean\n windows?: string\n leadTimeMinutes?: number\n daysAhead?: number\n instructions?: string\n}\n\nexport interface StoreTaxChange {\n section: 'tax'\n mode?: 'manual' | 'stripe' | 'none'\n pricesIncludeTax?: boolean\n originCountry?: string\n originState?: string\n rateCountry?: string\n rateState?: string\n ratePct?: number\n rateLabel?: string\n removeRate?: boolean\n}\n\nexport type StoreSetupChange = StoreShippingChange | StorePickupChange | StoreLocalDeliveryChange | StoreTaxChange\n\nexport type StoreSetupRead = { ok: true; value: StoreSetupChange } | { ok: false; problems: string[] }\n\nconst COUNTRY = /^[A-Z]{2}$/\nconst STATE = /^[A-Z0-9]{1,3}$/\n\ntype Raw = Readonly<Record<string, unknown>>\n\nconst has = (raw: Raw, key: string) => raw[key] !== undefined && raw[key] !== null && raw[key] !== ''\n\nfunction text(raw: Raw, key: string, max: number, problems: string[]): string | undefined {\n if (!has(raw, key)) return undefined\n const value = raw[key]\n if (typeof value !== 'string') {\n problems.push(`\"${key}\" must be text`)\n return undefined\n }\n const trimmed = value.trim()\n if (trimmed.length > max) problems.push(`\"${key}\" must be at most ${max} characters`)\n return trimmed || undefined\n}\n\nfunction bool(raw: Raw, key: string, problems: string[]): boolean | undefined {\n if (!has(raw, key)) return undefined\n if (typeof raw[key] !== 'boolean') {\n problems.push(`\"${key}\" must be true or false`)\n return undefined\n }\n return raw[key] as boolean\n}\n\nfunction number(raw: Raw, key: string, min: number, max: number, problems: string[]): number | undefined {\n if (!has(raw, key)) return undefined\n const value = raw[key]\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n problems.push(`\"${key}\" must be a number`)\n return undefined\n }\n if (value < min || value > max) {\n problems.push(`\"${key}\" must be between ${min} and ${max}`)\n return undefined\n }\n return value\n}\n\nfunction minutes(raw: Raw, key: string, problems: string[]): number | undefined {\n const value = number(raw, key, 0, STORE_SETUP_MAX_MINUTES, problems)\n return value === undefined ? undefined : Math.round(value)\n}\n\n/** Dollars to the cents the settings store. */\nfunction cents(raw: Raw, key: string, problems: string[]): number | undefined {\n const value = number(raw, key, 0, COMMERCE_MAX_PRICE_USD, problems)\n return value === undefined ? undefined : Math.round(value * 100)\n}\n\nfunction list(raw: Raw, key: string, max: number, problems: string[]): string[] | undefined {\n if (!has(raw, key)) return undefined\n const value = raw[key]\n if (!Array.isArray(value) || value.some((one) => typeof one !== 'string')) {\n problems.push(`\"${key}\" must be a list of text`)\n return undefined\n }\n const items = (value as string[]).map((one) => one.trim()).filter(Boolean)\n if (items.length > max) problems.push(`\"${key}\" must hold at most ${max}`)\n return items\n}\n\nfunction countryCode(raw: Raw, key: string, problems: string[]): string | undefined {\n const value = text(raw, key, 2, problems)?.toUpperCase()\n if (value !== undefined && !COUNTRY.test(value)) problems.push(`\"${key}\" must be a two-letter country code like US`)\n return value\n}\n\nfunction stateCode(raw: Raw, key: string, problems: string[]): string | undefined {\n const value = text(raw, key, 3, problems)?.toUpperCase()\n if (value !== undefined && !STATE.test(value)) problems.push(`\"${key}\" must be a state or region code like TX`)\n return value\n}\n\n/** Opening-hours lines; a `;` separates lines as a newline does. */\nfunction hoursText(raw: Raw, key: string, problems: string[]): string | undefined {\n const value = text(raw, key, PICKUP_HOURS_MAX, problems)\n if (value === undefined) return undefined\n const lines = value\n .split(/\\s*(?:;|\\r?\\n)\\s*/)\n .filter(Boolean)\n .join('\\n')\n const bad = invalidOpeningHoursLines(lines)\n if (bad.length) {\n problems.push(`\"${key}\" must be lines like \"Mo-Fr 09:00-17:00\" or \"Sa 10:00-14:00\"`)\n }\n return lines\n}\n\n/** \"50:5\" → up to 50 (dollars, or grams for weight) costs $5. */\nfunction tiersOf(raw: Raw, kind: StoreShippingAiKind | undefined, problems: string[]): ShippingTier[] | undefined {\n const entries = list(raw, 'tiers', STORE_SHIPPING_TIERS_MAX, problems)\n if (entries === undefined) return undefined\n const weight = kind === 'weight_tiers'\n const tiers: ShippingTier[] = []\n for (const entry of entries) {\n const match = /^\\s*\\$?([0-9]+(?:\\.[0-9]+)?)\\s*(?:g)?\\s*:\\s*\\$?([0-9]+(?:\\.[0-9]+)?)\\s*$/.exec(entry)\n const upTo = match ? Number(match[1]) : NaN\n const amount = match ? Number(match[2]) : NaN\n if (!match || !(upTo > 0) || amount > COMMERCE_MAX_PRICE_USD || (weight && upTo > STORE_SHIPPING_MAX_GRAMS)) {\n problems.push(`\"tiers\" holds \"${entry}\", which is not \"up to:price\" like \"50:5\"`)\n return undefined\n }\n tiers.push({ upTo: weight ? Math.round(upTo) : Math.round(upTo * 100), amountCents: Math.round(amount * 100) })\n }\n tiers.sort((a, b) => a.upTo - b.upTo)\n if (tiers.some((tier, index) => index > 0 && tier.upTo === tiers[index - 1].upTo)) {\n problems.push('\"tiers\" names the same limit twice')\n }\n return tiers\n}\n\nconst KNOWN: Record<StoreSetupSection, readonly string[]> = {\n shipping: ['action', 'zoneName', 'countries', 'rateName', 'kind', 'amountUsd', 'freeOverUsd', 'tiers'],\n pickup: ['location', 'enabled', 'hours', 'instructions', 'readyWithinMinutes'],\n 'local-delivery': [\n 'enabled',\n 'country',\n 'location',\n 'zoneName',\n 'postcodes',\n 'feeUsd',\n 'minimumUsd',\n 'freeOverUsd',\n 'removeZone',\n 'windows',\n 'leadTimeMinutes',\n 'daysAhead',\n 'instructions',\n ],\n tax: [\n 'mode',\n 'pricesIncludeTax',\n 'originCountry',\n 'originState',\n 'rateCountry',\n 'rateState',\n 'ratePercent',\n 'rateLabel',\n 'removeRate',\n ],\n}\n\nfunction readShipping(raw: Raw, problems: string[]): StoreShippingChange {\n const action = has(raw, 'action') ? raw['action'] : 'set'\n if (!STORE_SHIPPING_ACTIONS.includes(action as never)) problems.push('\"action\" must be set or remove')\n const zoneName = text(raw, 'zoneName', STORE_SETUP_NAME_MAX, problems)\n if (!zoneName) problems.push('\"zoneName\" is required: the shipping zone, like \"United States\"')\n const countries = list(raw, 'countries', STORE_SETUP_COUNTRIES_MAX, problems)?.map((code) => code.toUpperCase())\n for (const code of countries ?? []) {\n if (code !== '*' && !COUNTRY.test(code)) {\n problems.push(`\"countries\" holds \"${code}\", which is not a two-letter country code or *`)\n break\n }\n }\n const rateName = text(raw, 'rateName', STORE_SETUP_NAME_MAX, problems)\n const kind = has(raw, 'kind') ? (raw['kind'] as StoreShippingAiKind) : undefined\n if (kind !== undefined && !STORE_SHIPPING_AI_KINDS.includes(kind)) {\n problems.push(`\"kind\" must be one of ${STORE_SHIPPING_AI_KINDS.join(', ')}`)\n }\n const amountCents = cents(raw, 'amountUsd', problems)\n const freeOverCents = cents(raw, 'freeOverUsd', problems)\n const tiers = tiersOf(raw, kind, problems)\n if (action === 'set') {\n // A rate with no name is dropped at checkout (AGL-1791), and a blank\n // amount charges nothing: both are the person's to state.\n if (!rateName) problems.push('\"rateName\" is required: what the shopper sees, like \"Standard\"')\n if (!kind) problems.push('\"kind\" is required')\n if ((kind === 'flat' || kind === 'free_over') && amountCents === undefined) {\n problems.push(`\"amountUsd\" is required for a ${kind === 'flat' ? 'flat' : 'free-over'} rate`)\n }\n if (kind === 'free_over' && !freeOverCents) problems.push('\"freeOverUsd\" is required for a free-over rate')\n if ((kind === 'price_tiers' || kind === 'weight_tiers') && !tiers?.length) {\n problems.push('\"tiers\" is required for a tiered rate')\n }\n }\n return {\n section: 'shipping',\n action: action as StoreShippingChange['action'],\n zoneName: zoneName ?? '',\n ...(countries ? { countries } : {}),\n ...(rateName ? { rateName } : {}),\n ...(kind ? { kind } : {}),\n ...(amountCents !== undefined ? { amountCents } : {}),\n ...(freeOverCents !== undefined ? { freeOverCents } : {}),\n ...(tiers ? { tiers } : {}),\n }\n}\n\nfunction readPickup(raw: Raw, problems: string[]): StorePickupChange {\n const location = text(raw, 'location', STORE_SETUP_LOCATION_MAX, problems)\n const hours = hoursText(raw, 'hours', problems)\n const instructions = text(raw, 'instructions', PICKUP_INSTRUCTIONS_MAX, problems)\n const readyWithinMinutes = minutes(raw, 'readyWithinMinutes', problems)\n if (!location && (hours !== undefined || instructions !== undefined || readyWithinMinutes !== undefined)) {\n problems.push('Pickup hours, instructions and preparation time belong to a location: name the inventory location')\n }\n return {\n section: 'pickup',\n enabled: bool(raw, 'enabled', problems) ?? true,\n ...(location ? { location } : {}),\n ...(hours !== undefined ? { hours } : {}),\n ...(instructions !== undefined ? { instructions } : {}),\n ...(readyWithinMinutes !== undefined ? { readyWithinMinutes } : {}),\n }\n}\n\nfunction readLocalDelivery(raw: Raw, problems: string[]): StoreLocalDeliveryChange {\n const zoneName = text(raw, 'zoneName', STORE_SETUP_NAME_MAX, problems)\n const postcodes = list(raw, 'postcodes', LOCAL_DELIVERY_POSTCODES_MAX, problems)\n const feeCents = cents(raw, 'feeUsd', problems)\n const minimumCents = cents(raw, 'minimumUsd', problems)\n const freeOverCents = cents(raw, 'freeOverUsd', problems)\n const removeZone = bool(raw, 'removeZone', problems)\n if (!zoneName && (postcodes || feeCents !== undefined || minimumCents !== undefined || freeOverCents !== undefined || removeZone)) {\n problems.push('\"zoneName\" is required to add, change or remove a delivery zone')\n }\n const daysAhead = number(raw, 'daysAhead', 1, 30, problems)\n return {\n section: 'local-delivery',\n enabled: bool(raw, 'enabled', problems) ?? true,\n ...(has(raw, 'country') ? { country: countryCode(raw, 'country', problems) } : {}),\n ...(has(raw, 'location') ? { location: text(raw, 'location', STORE_SETUP_LOCATION_MAX, problems) } : {}),\n ...(zoneName ? { zoneName } : {}),\n ...(postcodes ? { postcodes } : {}),\n ...(feeCents !== undefined ? { feeCents } : {}),\n ...(minimumCents !== undefined ? { minimumCents } : {}),\n ...(freeOverCents !== undefined ? { freeOverCents } : {}),\n ...(removeZone ? { removeZone } : {}),\n ...(has(raw, 'windows') ? { windows: hoursText(raw, 'windows', problems) } : {}),\n ...(has(raw, 'leadTimeMinutes') ? { leadTimeMinutes: minutes(raw, 'leadTimeMinutes', problems) } : {}),\n ...(daysAhead !== undefined ? { daysAhead: Math.round(daysAhead) } : {}),\n ...(has(raw, 'instructions') ? { instructions: text(raw, 'instructions', PICKUP_INSTRUCTIONS_MAX, problems) } : {}),\n }\n}\n\nfunction readTax(raw: Raw, problems: string[]): StoreTaxChange {\n const mode = has(raw, 'mode') ? raw['mode'] : undefined\n if (mode !== undefined && !STORE_TAX_MODES.includes(mode as never)) {\n problems.push(`\"mode\" must be one of ${STORE_TAX_MODES.join(', ')}`)\n }\n const change: StoreTaxChange = {\n section: 'tax',\n ...(mode !== undefined ? { mode: mode as StoreTaxChange['mode'] } : {}),\n }\n const pricesIncludeTax = bool(raw, 'pricesIncludeTax', problems)\n if (pricesIncludeTax !== undefined) change.pricesIncludeTax = pricesIncludeTax\n const originCountry = countryCode(raw, 'originCountry', problems)\n if (originCountry) change.originCountry = originCountry\n const originState = stateCode(raw, 'originState', problems)\n if (originState) change.originState = originState\n const rateCountry = countryCode(raw, 'rateCountry', problems)\n if (rateCountry) change.rateCountry = rateCountry\n const rateState = stateCode(raw, 'rateState', problems)\n if (rateState) change.rateState = rateState\n if (has(raw, 'ratePercent')) {\n const value = raw['ratePercent']\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > 100) {\n problems.push('\"ratePercent\" must be a percentage above 0 and at most 100')\n } else change.ratePct = value\n }\n const rateLabel = text(raw, 'rateLabel', STORE_TAX_LABEL_MAX, problems)\n if (rateLabel) change.rateLabel = rateLabel\n const removeRate = bool(raw, 'removeRate', problems)\n if (removeRate) change.removeRate = true\n\n const touchesRate = change.ratePct !== undefined || change.removeRate || change.rateState || change.rateLabel\n if (touchesRate && !change.rateCountry) problems.push('\"rateCountry\" is required with a tax rate')\n if (change.rateCountry && change.ratePct === undefined && !change.removeRate) {\n // Never a rate the person did not state.\n problems.push('\"ratePercent\" is required with a tax rate: the percentage the request states')\n }\n if (change.ratePct !== undefined && change.removeRate) problems.push('Give \"ratePercent\" or \"removeRate\", not both')\n if (originState && !originCountry) problems.push('\"originCountry\" is required with \"originState\"')\n const said = Object.keys(change).filter((key) => key !== 'section')\n if (!said.length) {\n problems.push(\n 'Say how the store handles sales tax: manual rates (with the percentage), automatic calculation, or not collecting it',\n )\n }\n return change\n}\n\n/** Reads a change from content; the problems name what is wrong, in words a person reads. */\nexport function readStoreSetupChange(content: Raw): StoreSetupRead {\n const section = content['section'] as StoreSetupSection\n if (!STORE_SETUP_SECTIONS.includes(section)) {\n return { ok: false, problems: [`\"section\" must be one of ${STORE_SETUP_SECTIONS.join(', ')}`] }\n }\n const problems: string[] = []\n for (const key of Object.keys(content)) {\n if (key !== 'section' && !KNOWN[section].includes(key)) problems.push(`\"${key}\" is not a ${section} setting`)\n }\n const value =\n section === 'shipping'\n ? readShipping(content, problems)\n : section === 'pickup'\n ? readPickup(content, problems)\n : section === 'local-delivery'\n ? readLocalDelivery(content, problems)\n : readTax(content, problems)\n return problems.length ? { ok: false, problems } : { ok: true, value }\n}\n\n// ---------------------------------------------------------------------------\n// Applying a change\n// ---------------------------------------------------------------------------\n\n/** An inventory location as the writer reads it. */\nexport interface StoreSetupLocation {\n id: string\n name?: string\n address?: string\n city?: string\n pickup?: unknown\n}\n\n/** What the change writes: one map of the settings document, or one location's pickup. */\nexport type StoreSetupWrite =\n | { target: 'settings'; field: 'shipping' | 'localDelivery' | 'tax'; value: Record<string, unknown> }\n | { target: 'location'; locationId: string; value: PickupLocationSettings }\n\nexport type StoreSetupApplied =\n | {\n ok: true\n /** `null` when the settings already say what the change asks: nothing to write. */\n write: StoreSetupWrite | null\n /** One sentence on what the store now does. */\n summary: string\n /** What the person should know, in the console's words. */\n warnings: string[]\n }\n | { ok: false; status: 400 | 404 | 409; error: string }\n\nexport interface StoreSetupState {\n /** `hosts/{hostId}/settings/store`, or `{}`. */\n settings: Readonly<Record<string, unknown>>\n locations: readonly StoreSetupLocation[]\n}\n\n/** Ids for what a change creates, derived from the request so a retry makes the same ones. */\nexport interface StoreSetupIds {\n zoneId: string\n rateId: string\n}\n\nconst fail = (status: 400 | 404 | 409, error: string): StoreSetupApplied => ({ ok: false, status, error })\n\n/** Key-order-blind equality over plain JSON values. */\nexport function sameSetting(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (Array.isArray(a) || Array.isArray(b)) {\n return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((one, index) => sameSetting(one, b[index]))\n }\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n const left = Object.entries(a as Record<string, unknown>).filter(([, value]) => value !== undefined)\n const right = Object.entries(b as Record<string, unknown>).filter(([, value]) => value !== undefined)\n return left.length === right.length && left.every(([key, value]) => sameSetting(value, (b as Record<string, unknown>)[key]))\n }\n return false\n}\n\nconst lower = (value: unknown) => String(value ?? '').trim().toLowerCase()\nconst usd = (centsValue: number) => `$${(centsValue / 100).toFixed(centsValue % 100 ? 2 : 0)}`\nconst sameSet = (a: readonly string[], b: readonly string[]) =>\n a.length === b.length && [...a].sort().join(',') === [...b].sort().join(',')\n\n/** The store's locations a phrase names: by exact name first, then by city or address. */\nexport function matchStoreLocations(\n locations: readonly StoreSetupLocation[],\n phrase: string,\n): StoreSetupLocation[] {\n const wanted = lower(phrase)\n const byName = locations.filter((one) => lower(one.name) === wanted)\n if (byName.length) return byName\n return locations.filter(\n (one) => lower(one.city) === wanted || (wanted.length >= 3 && lower(one.address).includes(wanted)) || lower(one.name).includes(wanted),\n )\n}\n\nfunction findLocation(\n locations: readonly StoreSetupLocation[],\n phrase: string,\n): StoreSetupLocation | StoreSetupApplied {\n const found = matchStoreLocations(locations, phrase)\n if (!found.length) {\n return fail(\n 404,\n `The store has no inventory location matching \"${phrase}\". Add it under Products → Inventory locations, then ask again.`,\n )\n }\n if (found.length > 1) {\n return fail(409, `More than one location matches \"${phrase}\" (${found.map((one) => one.name || one.id).join(', ')}); say which`)\n }\n return found[0]\n}\n\nfunction rateSummary(rate: ShippingRate): string {\n const conditions = describeRateConditions(rate)\n return conditions ? `${rateKindSummary(rate)} (${conditions.toLowerCase()})` : rateKindSummary(rate)\n}\n\nfunction rateKindSummary(rate: ShippingRate): string {\n switch (rate.kind) {\n case 'flat':\n return rate.amountCents ? `${usd(rate.amountCents)} flat` : 'free'\n case 'free_over':\n return `free over ${usd(rate.freeOverCents ?? 0)}, otherwise ${usd(rate.amountCents ?? 0)}`\n case 'price_tiers':\n return `${(rate.tiers ?? []).length} subtotal tiers`\n case 'weight_tiers':\n return `${(rate.tiers ?? []).length} weight tiers`\n default:\n return rate.kind\n }\n}\n\nconst RATE_KEPT_FIELDS = [\n 'minSubtotalCents',\n 'maxSubtotalCents',\n 'minSubtotalByCurrency',\n 'maxSubtotalByCurrency',\n 'minGrams',\n 'maxGrams',\n 'amountsByCurrency',\n 'freeOverByCurrency',\n] as const satisfies readonly (keyof ShippingRate)[]\n\nfunction applyShipping(state: StoreSetupState, change: StoreShippingChange, ids: StoreSetupIds): StoreSetupApplied {\n const current = (state.settings['shipping'] ?? {}) as ShippingSettings\n const zones: ShippingZone[] = [...(current.zones ?? [])]\n const rates: ShippingRate[] = [...(current.rates ?? [])]\n const zoneIndex = (() => {\n const byName = zones.findIndex((zone) => lower(zone.name) === lower(change.zoneName))\n if (byName >= 0 || !change.countries?.length) return byName\n return zones.findIndex((zone) => sameSet((zone.countries ?? []).map((code) => String(code).trim().toUpperCase()), change.countries ?? []))\n })()\n const zone = zoneIndex >= 0 ? zones[zoneIndex] : undefined\n\n if (change.action === 'remove') {\n if (!zone) return { ok: true, write: null, summary: `There is no \"${change.zoneName}\" shipping zone.`, warnings: [] }\n if (change.rateName) {\n const kept = rates.filter((rate) => !(rate.zoneId === zone.id && lower(rate.name) === lower(change.rateName)))\n if (kept.length === rates.length) {\n return { ok: true, write: null, summary: `\"${zone.name}\" has no \"${change.rateName}\" rate.`, warnings: [] }\n }\n return shippingResult(current, { ...current, zones, rates: kept }, `Removed the \"${change.rateName}\" rate from ${zone.name}.`)\n }\n // The card's ✕ on a zone: the zone and its rates go together.\n return shippingResult(\n current,\n { ...current, zones: zones.filter((one) => one.id !== zone.id), rates: rates.filter((rate) => rate.zoneId !== zone.id) },\n `Removed the ${zone.name} shipping zone and its rates.`,\n )\n }\n\n let zoneId: string\n if (zone) {\n zoneId = zone.id\n if (change.countries?.length && !sameSet(zone.countries ?? [], change.countries)) {\n zones[zoneIndex] = { ...zone, countries: [...change.countries] }\n }\n } else {\n if (!change.countries?.length) {\n return fail(400, `Say which countries the new \"${change.zoneName}\" zone ships to (two-letter codes, or * for everywhere else)`)\n }\n zoneId = ids.zoneId\n zones.push({ id: zoneId, name: change.zoneName, countries: [...change.countries] })\n }\n const rateIndex = rates.findIndex((rate) => rate.zoneId === zoneId && lower(rate.name) === lower(change.rateName))\n const existing = rateIndex >= 0 ? rates[rateIndex] : undefined\n if (existing?.kind === 'carrier') {\n return fail(409, `\"${existing.name}\" is a carrier rate; change it in Shipping settings`)\n }\n const kind = change.kind as StoreShippingAiKind\n // What this change does not speak to stays as the merchant set it: the\n // rate's conditions (AGL-4255) and its figures in other currencies\n // (AGL-4248).\n const kept: Partial<ShippingRate> = {}\n for (const key of RATE_KEPT_FIELDS) {\n if (existing?.[key] !== undefined) (kept as Record<string, unknown>)[key] = existing[key]\n }\n const rate: ShippingRate = {\n ...kept,\n id: existing?.id ?? ids.rateId,\n zoneId,\n name: change.rateName as string,\n kind,\n ...(kind === 'flat' || kind === 'free_over' ? { amountCents: change.amountCents } : {}),\n ...(kind === 'free_over' ? { freeOverCents: change.freeOverCents } : {}),\n ...(kind === 'price_tiers' || kind === 'weight_tiers' ? { tiers: change.tiers } : {}),\n }\n if (rateIndex >= 0) rates[rateIndex] = rate\n else rates.push(rate)\n const zoneName = zone?.name ?? change.zoneName\n return shippingResult(current, { ...current, zones, rates }, `${zoneName}: \"${rate.name}\" is ${rateSummary(rate)}.`, rate)\n}\n\nfunction shippingResult(\n before: ShippingSettings,\n after: ShippingSettings,\n summary: string,\n changed?: ShippingRate,\n): StoreSetupApplied {\n const coverage = summarizeShippingCoverage(after)\n const warnings: string[] = []\n if (coverage.unserved.length && !coverage.shipsNowhere) {\n warnings.push(`Checkout turns away buyers in ${coverage.unserved.join(', ')}: no rate reaches them.`)\n }\n if (changed?.kind === 'price_tiers' || changed?.kind === 'weight_tiers') {\n warnings.push(`\"${changed.name}\" applies only up to its last tier; a larger or heavier order gets no rate from it.`)\n }\n return {\n ok: true,\n write: sameSetting(before, after) ? null : { target: 'settings', field: 'shipping', value: after as Record<string, unknown> },\n summary,\n warnings,\n }\n}\n\nfunction applyPickup(state: StoreSetupState, change: StorePickupChange): StoreSetupApplied {\n if (!change.location) {\n const current = (state.settings['shipping'] ?? {}) as ShippingSettings\n const after: ShippingSettings = { ...current, localPickup: change.enabled }\n return {\n ok: true,\n write: Boolean(current.localPickup) === change.enabled ? null : { target: 'settings', field: 'shipping', value: after as Record<string, unknown> },\n summary: change.enabled ? 'Checkout offers free local pickup.' : 'Checkout no longer offers free local pickup.',\n warnings: change.enabled ? ['Pickup is a collection choice; it does not widen where the store ships.'] : [],\n }\n }\n const found = findLocation(state.locations, change.location)\n if ('ok' in found) return found\n const before = normalizePickupSettings(found.pickup)\n const after = normalizePickupSettings({\n ...before,\n enabled: change.enabled,\n ...(change.hours !== undefined ? { hours: change.hours } : {}),\n ...(change.instructions !== undefined ? { instructions: change.instructions } : {}),\n ...(change.readyWithinMinutes !== undefined ? { readyWithinMinutes: change.readyWithinMinutes } : {}),\n })\n const name = found.name || 'the location'\n return {\n ok: true,\n write: sameSetting(before, after) ? null : { target: 'location', locationId: found.id, value: after },\n summary: after.enabled ? `Buyers can pick up orders at ${name}.` : `Pickup at ${name} is off.`,\n warnings: after.enabled && !after.hours ? [`${name} has no pickup hours yet; buyers are not told when to come.`] : [],\n }\n}\n\nfunction applyLocalDelivery(state: StoreSetupState, change: StoreLocalDeliveryChange, ids: StoreSetupIds): StoreSetupApplied {\n const before = normalizeLocalDeliverySettings(state.settings['localDelivery'])\n const after: LocalDeliverySettings = { ...before, zones: [...(before.zones ?? [])] }\n if (!after.zones?.length) delete after.zones\n if (change.enabled) after.enabled = true\n else delete after.enabled\n if (change.country) after.country = change.country\n if (change.location) {\n const found = findLocation(state.locations, change.location)\n if ('ok' in found) return found\n after.locationId = found.id\n }\n if (change.windows !== undefined) after.windows = change.windows\n if (change.leadTimeMinutes !== undefined) after.leadTimeMinutes = change.leadTimeMinutes\n if (change.daysAhead !== undefined) after.daysAhead = change.daysAhead\n if (change.instructions !== undefined) after.instructions = change.instructions\n if (change.zoneName) {\n const zones: LocalDeliveryZone[] = [...(after.zones ?? [])]\n const index = zones.findIndex((zone) => lower(zone.name) === lower(change.zoneName))\n if (change.removeZone) {\n if (index >= 0) zones.splice(index, 1)\n } else if (index >= 0) {\n const zone = zones[index]\n if (change.postcodes && zone.kind === 'radius') {\n return fail(409, `\"${zone.name}\" is a distance zone; change it under Local delivery`)\n }\n zones[index] = {\n ...zone,\n ...(change.postcodes ? { postcodes: change.postcodes } : {}),\n ...(change.feeCents !== undefined ? { feeCents: change.feeCents } : {}),\n ...(change.minimumCents !== undefined ? { minimumCents: change.minimumCents } : {}),\n ...(change.freeOverCents !== undefined ? { freeOverCents: change.freeOverCents } : {}),\n }\n } else {\n if (!change.postcodes?.length) return fail(400, `Say which postal codes the \"${change.zoneName}\" zone delivers to`)\n if (change.feeCents === undefined) return fail(400, `Say what delivery to \"${change.zoneName}\" costs (0 for free)`)\n if (zones.length >= LOCAL_DELIVERY_ZONES_MAX) return fail(409, `Local delivery holds at most ${LOCAL_DELIVERY_ZONES_MAX} zones`)\n zones.push({\n id: ids.zoneId,\n name: change.zoneName,\n kind: 'postcode',\n postcodes: change.postcodes,\n feeCents: change.feeCents,\n ...(change.minimumCents !== undefined ? { minimumCents: change.minimumCents } : {}),\n ...(change.freeOverCents !== undefined ? { freeOverCents: change.freeOverCents } : {}),\n })\n }\n after.zones = zones\n }\n const normalized = normalizeLocalDeliverySettings(after)\n const problems = localDeliveryProblems(normalized)\n if (problems.length) {\n return fail(400, `Local delivery can't be switched on yet: ${problems.join(' ')}`)\n }\n return {\n ok: true,\n write: sameSetting(before, normalized)\n ? null\n : { target: 'settings', field: 'localDelivery', value: normalized as Record<string, unknown> },\n summary: normalized.enabled\n ? `The store delivers locally to ${(normalized.zones ?? []).length} zone${(normalized.zones ?? []).length === 1 ? '' : 's'}.`\n : 'Local delivery is off.',\n warnings: normalized.enabled && !normalized.locationId ? ['No location is set for delivery orders to leave from.'] : [],\n }\n}\n\nconst TAX_MODE_WORDS: Record<string, string> = {\n manual: 'manual rates',\n stripe: 'automatic calculation',\n none: 'not collecting sales tax',\n}\n\nfunction applyTax(state: StoreSetupState, change: StoreTaxChange): StoreSetupApplied {\n const before = (state.settings['tax'] ?? {}) as TaxSettings\n const after: TaxSettings = { ...before }\n const settingRate = change.ratePct !== undefined\n if (change.mode) after.mode = change.mode\n else if (settingRate && after.mode === undefined) after.mode = 'manual'\n if (settingRate && after.mode !== 'manual') {\n return fail(\n 409,\n `This store uses ${TAX_MODE_WORDS[String(after.mode)] ?? 'another tax mode'}, so a manual rate would not apply. Ask to switch to manual rates as well.`,\n )\n }\n if (change.pricesIncludeTax !== undefined) after.pricesIncludeTax = change.pricesIncludeTax\n if (change.originCountry) {\n after.origin = {\n country: change.originCountry,\n ...(change.originState ? { state: change.originState } : {}),\n }\n }\n if (change.rateCountry) {\n const rates: TaxRate[] = [...(before.rates ?? [])]\n const index = rates.findIndex(\n (rate) =>\n String(rate.country ?? '').toUpperCase() === change.rateCountry &&\n String(rate.state ?? '').toUpperCase() === (change.rateState ?? ''),\n )\n if (change.removeRate) {\n if (index >= 0) rates.splice(index, 1)\n } else {\n const rate: TaxRate = {\n country: change.rateCountry,\n ...(change.rateState ? { state: change.rateState } : {}),\n pct: change.ratePct as number,\n ...(change.rateLabel ? { label: change.rateLabel } : index >= 0 && rates[index].label ? { label: rates[index].label } : {}),\n }\n if (index >= 0) rates[index] = rate\n else rates.push(rate)\n }\n after.rates = rates\n }\n // Manual mode with no origin refuses every sale (AGL-2145): never leave a store there.\n if (storefrontTaxMisconfiguration(after)) {\n return fail(400, 'Manual tax rates need the store’s address: say which country (and state) the store sells from.')\n }\n const warnings: string[] = []\n if (after.mode === 'manual' && !(after.rates ?? []).length) {\n warnings.push('No tax rate is set yet, so orders are charged no sales tax.')\n }\n if (after.mode === 'stripe') {\n warnings.push('Automatic tax is calculated per buyer location at checkout; the register cannot calculate it for in-person sales.')\n }\n const mode = TAX_MODE_WORDS[String(after.mode)] ?? 'undecided'\n const rateLine = settingRate\n ? ` ${change.ratePct}% for ${change.rateCountry}${change.rateState ? `-${change.rateState}` : ''}.`\n : ''\n return {\n ok: true,\n write: sameSetting(before, after) ? null : { target: 'settings', field: 'tax', value: after as Record<string, unknown> },\n summary: `Sales tax: ${mode}.${rateLine}`,\n warnings,\n }\n}\n\n/** The settings after a change, what to write, and what the person is told. */\nexport function applyStoreSetupChange(\n state: StoreSetupState,\n change: StoreSetupChange,\n ids: StoreSetupIds,\n): StoreSetupApplied {\n switch (change.section) {\n case 'shipping':\n return applyShipping(state, change, ids)\n case 'pickup':\n return applyPickup(state, change)\n case 'local-delivery':\n return applyLocalDelivery(state, change, ids)\n case 'tax':\n return applyTax(state, change)\n }\n}\n\n/** What a reader is told about a store's setup, for the writer's `read`. */\nexport function storeSetupFacts(settings: Readonly<Record<string, unknown>>): Record<string, unknown> {\n const shipping = (settings['shipping'] ?? {}) as ShippingSettings\n const tax = (settings['tax'] ?? {}) as TaxSettings\n const delivery = normalizeLocalDeliverySettings(settings['localDelivery'])\n return {\n shippingZones: (shipping.zones ?? []).length,\n shippingRates: (shipping.rates ?? []).length,\n localPickup: Boolean(shipping.localPickup),\n localDelivery: Boolean(delivery.enabled),\n taxMode: tax.mode ?? null,\n taxRates: (tax.rates ?? []).length,\n live: true,\n }\n}\n"],"names":["invalidOpeningHoursLines","COMMERCE_MAX_PRICE_USD","summarizeShippingCoverage","describeRateConditions","storefrontTaxMisconfiguration","LOCAL_DELIVERY_POSTCODES_MAX","LOCAL_DELIVERY_ZONES_MAX","PICKUP_HOURS_MAX","PICKUP_INSTRUCTIONS_MAX","localDeliveryProblems","normalizeLocalDeliverySettings","normalizePickupSettings","STORE_SETUP_RESOURCE","STORE_SETUP_SECTIONS","STORE_SHIPPING_AI_KINDS","STORE_SHIPPING_ACTIONS","STORE_TAX_MODES","STORE_SETUP_NAME_MAX","STORE_SETUP_COUNTRIES_MAX","STORE_SHIPPING_TIERS_MAX","STORE_SETUP_LOCATION_MAX","STORE_TAX_LABEL_MAX","STORE_SHIPPING_MAX_GRAMS","STORE_SETUP_MAX_MINUTES","COUNTRY","STATE","has","raw","key","undefined","text","max","problems","value","push","trimmed","trim","length","bool","number","min","Number","isFinite","minutes","Math","round","cents","list","Array","isArray","some","one","items","map","filter","Boolean","countryCode","toUpperCase","test","stateCode","hoursText","lines","split","join","bad","tiersOf","kind","entries","weight","tiers","entry","match","exec","upTo","NaN","amount","amountCents","sort","a","b","tier","index","KNOWN","shipping","pickup","tax","readShipping","action","includes","zoneName","countries","code","rateName","freeOverCents","section","readPickup","location","hours","instructions","readyWithinMinutes","enabled","readLocalDelivery","postcodes","feeCents","minimumCents","removeZone","daysAhead","country","windows","leadTimeMinutes","readTax","mode","change","pricesIncludeTax","originCountry","originState","rateCountry","rateState","ratePct","rateLabel","removeRate","touchesRate","said","Object","keys","readStoreSetupChange","content","ok","fail","status","error","sameSetting","every","left","right","lower","String","toLowerCase","usd","centsValue","toFixed","sameSet","matchStoreLocations","locations","phrase","wanted","byName","name","city","address","findLocation","found","id","rateSummary","rate","conditions","rateKindSummary","RATE_KEPT_FIELDS","applyShipping","state","ids","current","settings","zones","rates","zoneIndex","findIndex","zone","write","summary","warnings","kept","zoneId","shippingResult","rateIndex","existing","rateId","before","after","changed","coverage","unserved","shipsNowhere","target","field","applyPickup","localPickup","locationId","applyLocalDelivery","normalized","splice","TAX_MODE_WORDS","manual","stripe","none","applyTax","settingRate","origin","pct","label","rateLine","applyStoreSetupChange","storeSetupFacts","delivery","shippingZones","shippingRates","localDelivery","taxMode","taxRates","live"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,wBAAwB,QAAQ,wCAAuC;AAChF,SAASC,sBAAsB,QAAQ,gBAAY;AACnD,SACEC,yBAAyB,EACzBC,sBAAsB,QAKjB,yBAAqB;AAE5B,SAASC,6BAA6B,QAAQ,6BAAyB;AACvE,SACEC,4BAA4B,EAC5BC,wBAAwB,EACxBC,gBAAgB,EAChBC,uBAAuB,EACvBC,qBAAqB,EACrBC,8BAA8B,EAC9BC,uBAAuB,QAGlB,kCAA8B;AAGrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA4B2C,GAE3C,sGAAsG,GACtG,OAAO,MAAMC,uBAAuB,iBAAgB;AAEpD,OAAO,MAAMC,uBAAuB;IAAC;IAAY;IAAU;IAAkB;CAAM,CAAS;AAG5F,+FAA+F,GAC/F,OAAO,MAAMC,0BAA0B;IAAC;IAAQ;IAAa;IAAe;CAAe,CAAS;AAGpG,OAAO,MAAMC,yBAAyB;IAAC;IAAO;CAAS,CAAS;AAChE,OAAO,MAAMC,kBAAkB;IAAC;IAAU;IAAU;CAAO,CAAS;AAEpE,OAAO,MAAMC,uBAAuB,GAAE;AACtC,OAAO,MAAMC,4BAA4B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