@aglyn/plugins-commerce 1.20.3 → 1.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/cart.js +106 -9
  3. package/src/lib/components/cart.js.map +1 -1
  4. package/src/lib/components/console/catalog-organization-card.component.js +81 -30
  5. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  6. package/src/lib/components/console/discounts-card.component.js +28 -3
  7. package/src/lib/components/console/discounts-card.component.js.map +1 -1
  8. package/src/lib/components/console/local-delivery-settings-card.component.js +23 -7
  9. package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -1
  10. package/src/lib/components/console/product-editor-dialog.component.js +61 -44
  11. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  12. package/src/lib/components/console/products-hub-card.component.js +32 -4
  13. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  14. package/src/lib/components/console/quote-settings-card.component.js +20 -6
  15. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  16. package/src/lib/components/console/reservations-card.component.js +28 -2
  17. package/src/lib/components/console/reservations-card.component.js.map +1 -1
  18. package/src/lib/components/console/return-settings-card.component.js +28 -15
  19. package/src/lib/components/console/return-settings-card.component.js.map +1 -1
  20. package/src/lib/components/console/shipping-settings-card.component.js +23 -8
  21. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  22. package/src/lib/components/console/store-settings-card.component.js +27 -11
  23. package/src/lib/components/console/store-settings-card.component.js.map +1 -1
  24. package/src/lib/components/console/suppliers-card.component.js +38 -13
  25. package/src/lib/components/console/suppliers-card.component.js.map +1 -1
  26. package/src/lib/components/console/tax-settings-card.component.js +25 -10
  27. package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
  28. package/src/lib/server/cart.js +57 -0
  29. package/src/lib/server/cart.js.map +1 -1
  30. package/src/lib/server/pos-terminal.js +2 -2
  31. package/src/lib/server/pos-terminal.js.map +1 -1
  32. package/src/lib/transfer/product-transfer.js +15 -1
  33. package/src/lib/transfer/product-transfer.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/transfer/product-transfer.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 { validateProductForSave } from '../model/product-card-rules'\nimport {\n buildTransferPlan,\n isBlankTransferValue,\n TRANSFER_SYSTEM_GROUP,\n TRANSFER_WARNING_CLASSES,\n type BuildTransferPlanInput,\n type DeriveProblemCode,\n type MatchKeySpec,\n type PlannedTransferRow,\n type RowMatchOutcome,\n type TransferAliasDictionary,\n type TransferField,\n type TransferFieldChange,\n type TransferFieldGroup,\n type TransferLockedRule,\n type TransferPlan,\n type TransferPlanRow,\n type TransferResourcePreset,\n type TransferWarning,\n type TransferWarningClass,\n type TransferWarningSample,\n} from '@aglyn/aglyn/data-transfer'\nimport type { PicklistSpec } from '@aglyn/aglyn/app-utils/picklists'\nimport {\n COMMERCE_MAX_VARIANTS,\n COMMERCE_SLUG_MAX_LENGTH,\n commerceSlug,\n productInventory,\n productPriceRange,\n variantMatrixProblem,\n type HostProduct,\n type ProductOption,\n type ProductStatus,\n type ProductType,\n type ProductVariant,\n} from '../model/commerce'\nimport {\n addOnCellOf,\n addOnVariantIds,\n checkInCellOf,\n checkInFromCell,\n modifierGroupsFromAddOnCell,\n readAddOnCell,\n readCheckInCell,\n writeAddOnCell,\n writeCheckInCell,\n} from './product-register-cells'\n\n/*\n * PRODUCTS ON THE TRANSFER FRAMEWORK (AGL-3531).\n *\n * ## One product, one row per variant\n *\n * A product's file is laid out the way storefront platforms lay theirs out:\n * a row per variant, the product's own fields (title, description, tags…)\n * on its first row, and every row carrying the product's handle. Images\n * follow the same convention — the first on the first row, the next on the\n * second, and rows of only a handle and an image when there are more images\n * than variants. So a store moving here from Shopify uploads its own export\n * as it is, and the Shopify preset writes one Shopify reads back.\n *\n * ## Rows fold into products\n *\n * The engine plans rows; a product is several. `planProductTransfer` (this\n * resource's `plan` hook) folds the rows of one handle into one product: the\n * first row decides whether the product is new or which one it is (by\n * handle, then SKU, then ID — the person's order), its product fields are\n * planned against the product, and every row's variant fields are planned\n * against the variant it names — by SKU, then by its option values, then the\n * single variant of a single-variant product. A match is UPDATED; the old\n * importer created a second product under a suffixed slug.\n *\n * Every row keeps its own verdict and diff, so the dry run shows what each\n * line of the file does, and the plan stashes what the apply needs on the\n * row (`commerce`): the product's id — minted here for a new one, so a retry\n * finds what it already wrote — the variant's, and for a new product the\n * whole document.\n *\n * ## Add-ons, check-in and quick keys\n *\n * The register's settings travel as plain cells (`product-register-cells.ts`).\n * A file without their columns never touches them, and an add-ons cell is\n * asked the questions the product editor's Save asks: `validateProductForSave` and\n * the 100-combination rule, `variantMatrixProblem`.\n *\n * ## What a file never sets\n *\n * Option names already on a product (renaming one moves every variant, which\n * the product editor does), stock kept by location (moved per location), and\n * the search, stock and collection keys every write derives.\n */\n\n/*==========================================\n * FIELDS\n *=========================================*/\n\n/** The field ids, as the catalog and every file name them. */\nexport const PRODUCT_FIELD = {\n handle: 'handle',\n title: 'title',\n description: 'description',\n kind: 'type',\n status: 'status',\n published: 'published',\n tags: 'tags',\n categories: 'categories',\n option1Name: 'option1Name',\n option2Name: 'option2Name',\n option3Name: 'option3Name',\n image: 'image',\n seoTitle: 'seoTitle',\n seoDescription: 'seoDescription',\n taxExempt: 'taxExempt',\n oversellPolicy: 'oversellPolicy',\n lowStockThreshold: 'lowStockThreshold',\n posQuickKey: 'posQuickKey',\n checkIn: 'checkIn',\n modifierGroups: 'modifierGroups',\n option1Value: 'option1Value',\n option2Value: 'option2Value',\n option3Value: 'option3Value',\n sku: 'sku',\n barcode: 'barcode',\n price: 'price',\n compareAtPrice: 'compareAtPrice',\n inventory: 'inventory',\n weightGrams: 'weightGrams',\n variantImage: 'variantImage',\n variantCheckIn: 'variantCheckIn',\n priceFrom: 'priceFrom',\n totalInventory: 'totalInventory',\n soldOut: 'soldOut',\n variantCount: 'variantCount',\n createdAt: 'createdAt',\n updatedAt: 'updatedAt',\n} as const\n\nconst F = PRODUCT_FIELD\n\n/** The picklists the product fields name. */\nexport const PRODUCT_KIND_PICKLIST = 'commerce.productKind'\nexport const PRODUCT_STATUS_PICKLIST = 'commerce.productStatus'\nexport const PRODUCT_OVERSELL_PICKLIST = 'commerce.oversellPolicy'\nexport const PRODUCT_CATEGORY_PICKLIST = 'commerce.categories'\n\nconst KIND_LABELS: Record<ProductType, string> = {\n physical: 'Physical',\n digital: 'Digital',\n service: 'Service',\n}\nconst STATUS_LABELS: Record<ProductStatus, string> = {\n active: 'Active',\n draft: 'Draft',\n archived: 'Archived',\n}\nconst OVERSELL_LABELS: Record<'deny' | 'backorder', string> = {\n deny: 'Stop selling',\n backorder: 'Keep selling',\n}\n\n/** A fixed list as the values step matches it: a file adds nothing to it. */\nfunction fixedList(labels: Record<string, string>, defaultValueId: string): PicklistSpec {\n return {\n restricted: true,\n standardValues: Object.entries(labels).map(([id, label]) => ({ id, label })),\n defaultValueId,\n }\n}\n\n/** The fixed lists products name, by picklist id. */\nexport const PRODUCT_FIXED_PICKLISTS: Readonly<Record<string, PicklistSpec>> = {\n [PRODUCT_KIND_PICKLIST]: fixedList(KIND_LABELS, 'physical'),\n [PRODUCT_STATUS_PICKLIST]: fixedList(STATUS_LABELS, 'active'),\n [PRODUCT_OVERSELL_PICKLIST]: fixedList(OVERSELL_LABELS, 'deny'),\n}\n\n/** The id a label of a fixed list names, by label or id in any case; `null` for none. */\nexport function fixedListId(picklistId: string, value: unknown): string | null {\n const spec = PRODUCT_FIXED_PICKLISTS[picklistId]\n const key = String(value ?? '').trim().toLowerCase()\n if (!spec || !key) return null\n const found = spec.standardValues.find(\n (entry) => entry.id.toLowerCase() === key || entry.label.toLowerCase() === key,\n )\n return found ? found.id : null\n}\n\n/** A fixed list's label for a stored id. */\nfunction fixedListLabel(picklistId: string, id: unknown): string | null {\n const spec = PRODUCT_FIXED_PICKLISTS[picklistId]\n return spec?.standardValues.find((entry) => entry.id === id)?.label ?? null\n}\n\nexport const PRODUCT_TRANSFER_GROUPS: readonly TransferFieldGroup[] = [\n { id: 'product', label: 'Product' },\n { id: 'variant', label: 'Variant' },\n { id: 'options', label: 'Options' },\n { id: 'media', label: 'Images' },\n { id: 'selling', label: 'Selling' },\n { id: 'seo', label: 'Search listing' },\n { id: 'computed', label: 'Computed' },\n]\n\n/** The fields a product's first row carries: the product's own. */\nexport const PRODUCT_LEVEL_FIELDS: readonly string[] = [\n F.handle,\n F.title,\n F.description,\n F.kind,\n F.status,\n F.published,\n F.tags,\n F.categories,\n F.option1Name,\n F.option2Name,\n F.option3Name,\n F.image,\n F.seoTitle,\n F.seoDescription,\n F.taxExempt,\n F.oversellPolicy,\n F.lowStockThreshold,\n F.posQuickKey,\n F.checkIn,\n F.modifierGroups,\n]\n\n/**\n * The product fields a file may give on any of a product's rows: one value\n * for the product, the first row's if it has one. A different value further\n * down is reported, never dropped without a word.\n */\nconst REGISTER_PRODUCT_FIELDS: readonly string[] = [F.posQuickKey, F.checkIn, F.modifierGroups]\n\n/** The fields every row carries for its own variant. */\nexport const VARIANT_LEVEL_FIELDS: readonly string[] = [\n F.option1Value,\n F.option2Value,\n F.option3Value,\n F.sku,\n F.barcode,\n F.price,\n F.compareAtPrice,\n F.inventory,\n F.weightGrams,\n F.variantImage,\n F.variantCheckIn,\n]\n\nconst OPTION_NAME_FIELDS = [F.option1Name, F.option2Name, F.option3Name] as const\nconst OPTION_VALUE_FIELDS = [F.option1Value, F.option2Value, F.option3Value] as const\n\n/** Every writable product field, in picker order. */\nexport const PRODUCT_STANDARD_FIELDS: readonly TransferField[] = [\n {\n id: F.handle,\n label: 'Handle',\n group: 'product',\n type: 'text',\n maxLength: 80,\n aliases: ['slug', 'url handle', 'product handle'],\n description: 'The product’s address, /products/<handle>. Rows with one handle are one product.',\n },\n {\n id: F.title,\n label: 'Title',\n group: 'product',\n type: 'text',\n aliases: ['name', 'product name', 'product title'],\n description: 'Needed for a new product.',\n },\n {\n id: F.description,\n label: 'Description',\n group: 'product',\n type: 'longText',\n aliases: ['body', 'body html', 'product description', 'description html'],\n },\n {\n id: F.kind,\n label: 'Kind',\n group: 'product',\n type: 'picklist',\n picklistId: PRODUCT_KIND_PICKLIST,\n aliases: ['product kind', 'type'],\n description: 'Physical, Digital or Service.',\n },\n {\n id: F.status,\n label: 'Status',\n group: 'product',\n type: 'picklist',\n picklistId: PRODUCT_STATUS_PICKLIST,\n aliases: ['product status'],\n description: 'Active, Draft or Archived.',\n },\n {\n id: F.published,\n label: 'Published',\n group: 'product',\n type: 'boolean',\n aliases: ['visible', 'online'],\n description: 'Read as the status when the file has no Status: yes is Active, no is Draft.',\n },\n {\n id: F.tags,\n label: 'Tags',\n group: 'product',\n type: 'text',\n aliases: ['tag', 'keywords'],\n description: 'Separated by commas; their case is kept, because collections match a tag exactly.',\n },\n {\n id: F.categories,\n label: 'Categories',\n group: 'product',\n type: 'multiPicklist',\n picklistId: PRODUCT_CATEGORY_PICKLIST,\n aliases: ['category', 'product categories'],\n description: 'By name. A name the site does not have can be added as a new category.',\n },\n { id: F.option1Name, label: 'Option 1 name', group: 'options', type: 'text', maxLength: 60 },\n { id: F.option1Value, label: 'Option 1 value', group: 'options', type: 'text', maxLength: 60 },\n { id: F.option2Name, label: 'Option 2 name', group: 'options', type: 'text', maxLength: 60 },\n { id: F.option2Value, label: 'Option 2 value', group: 'options', type: 'text', maxLength: 60 },\n { id: F.option3Name, label: 'Option 3 name', group: 'options', type: 'text', maxLength: 60 },\n { id: F.option3Value, label: 'Option 3 value', group: 'options', type: 'text', maxLength: 60 },\n {\n id: F.sku,\n label: 'SKU',\n group: 'variant',\n type: 'text',\n aliases: ['variant sku', 'stock keeping unit', 'item number'],\n },\n {\n id: F.barcode,\n label: 'Barcode',\n group: 'variant',\n type: 'text',\n aliases: ['variant barcode', 'gtin', 'upc', 'ean', 'isbn'],\n },\n {\n id: F.price,\n label: 'Price',\n group: 'variant',\n type: 'currency',\n aliases: ['variant price', 'price usd', 'unit price'],\n description: 'In US dollars. Needed for a new variant.',\n },\n {\n id: F.compareAtPrice,\n label: 'Compare-at price',\n group: 'variant',\n type: 'currency',\n aliases: ['variant compare at price', 'compare at price', 'was price', 'original price'],\n description: 'The strike-through price; above the price, or a product is refused.',\n },\n {\n id: F.inventory,\n label: 'Inventory',\n group: 'variant',\n type: 'integer',\n aliases: ['variant inventory qty', 'inventory quantity', 'quantity', 'stock', 'on hand'],\n description: 'Units in stock; blank is not counted. Stock kept by location is changed on the products page.',\n },\n {\n id: F.weightGrams,\n label: 'Weight (grams)',\n group: 'variant',\n type: 'number',\n aliases: ['variant grams', 'grams', 'weight'],\n },\n {\n id: F.variantImage,\n label: 'Variant image',\n group: 'variant',\n type: 'url',\n aliases: ['variant image url'],\n },\n {\n id: F.variantCheckIn,\n label: 'Variant check-in',\n group: 'variant',\n type: 'text',\n aliases: ['variant needs check-in', 'variant check in'],\n description: 'This variant’s own check-in, in the words of Check-in. Blank follows the product.',\n },\n {\n id: F.image,\n label: 'Image',\n group: 'media',\n type: 'url',\n aliases: ['image url', 'image src', 'photo', 'picture'],\n description: 'One image per row; the first row’s is the photo the storefront leads with.',\n },\n {\n id: F.seoTitle,\n label: 'SEO title',\n group: 'seo',\n type: 'text',\n aliases: ['meta title', 'page title', 'search title'],\n },\n {\n id: F.seoDescription,\n label: 'SEO description',\n group: 'seo',\n type: 'longText',\n aliases: ['meta description', 'search description'],\n },\n {\n id: F.taxExempt,\n label: 'Tax exempt',\n group: 'selling',\n type: 'boolean',\n aliases: ['tax free', 'no tax'],\n },\n {\n id: F.oversellPolicy,\n label: 'When sold out',\n group: 'selling',\n type: 'picklist',\n picklistId: PRODUCT_OVERSELL_PICKLIST,\n aliases: ['oversell policy', 'inventory policy', 'backorders'],\n description: 'Stop selling, or Keep selling as a backorder.',\n },\n {\n id: F.lowStockThreshold,\n label: 'Low stock alert at',\n group: 'selling',\n type: 'integer',\n aliases: ['low stock threshold', 'reorder point'],\n },\n {\n id: F.posQuickKey,\n label: 'Quick key',\n group: 'selling',\n type: 'boolean',\n aliases: ['quick key at the register', 'pos quick key', 'register quick key'],\n description: 'Yes shows the product under Quick keys on the register’s first screen.',\n },\n {\n id: F.checkIn,\n label: 'Check-in',\n group: 'selling',\n type: 'text',\n aliases: ['needs check-in', 'check in', 'checkin'],\n description: 'No or Yes. Yes can add how many people one item admits and asking the day: Yes, 4 people, ask which day.',\n },\n {\n id: F.modifierGroups,\n label: 'Add-ons',\n group: 'selling',\n type: 'longText',\n aliases: ['add ons', 'addons', 'modifiers', 'modifier groups'],\n description: 'Groups split by semicolons: Milk (at least 1): Whole, Oat +$0.75; Extras (at most 3, register only): Extra shot +$1.00.',\n },\n]\n\nexport const PRODUCT_DERIVED_FIELDS: readonly TransferField[] = [\n { id: F.priceFrom, label: 'Lowest price', group: 'computed', type: 'number' },\n { id: F.totalInventory, label: 'Total inventory', group: 'computed', type: 'integer' },\n { id: F.soldOut, label: 'Sold out', group: 'computed', type: 'boolean' },\n { id: F.variantCount, label: 'Variants', group: 'computed', type: 'integer' },\n]\n\nexport const PRODUCT_SYSTEM_FIELDS: readonly TransferField[] = [\n { id: F.createdAt, label: 'Created', group: TRANSFER_SYSTEM_GROUP.id, type: 'datetime' },\n { id: F.updatedAt, label: 'Updated', group: TRANSFER_SYSTEM_GROUP.id, type: 'datetime' },\n]\n\n/** Handle, then SKU, then the Aglyn ID. */\nexport const PRODUCT_MATCH_KEYS: readonly MatchKeySpec[] = [\n { fieldId: F.handle, normalizer: 'slug' },\n { fieldId: F.sku, normalizer: 'caseless' },\n { fieldId: 'id', normalizer: 'aglynId' },\n]\n\n/**\n * A product's handle and its option names are changed in the product editor,\n * never by a file: the handle is the product's address, and renaming an\n * option moves every variant. A file gives a new product both, and names an\n * option a product does not have yet.\n */\nexport const PRODUCT_LOCKED_RULES: readonly TransferLockedRule[] = [\n {\n fieldId: F.handle,\n reason:\n 'A product’s handle is its address; a file gives a new product one, and an existing product’s is changed in the product editor.',\n forced: { mode: 'fillBlanks', blank: 'leave' },\n },\n ...OPTION_NAME_FIELDS.map((fieldId) => ({\n fieldId,\n reason:\n 'An option a product already has is renamed in the product editor, where every variant moves with it; a file only names an option the product does not have yet.',\n forced: { mode: 'fillBlanks' as const, blank: 'leave' as const },\n })),\n]\n\n/*==========================================\n * THE SHOPIFY LAYOUT\n *=========================================*/\n\n/** Shopify's product CSV columns, by the field each one means. */\nexport const SHOPIFY_PRODUCT_COLUMNS: Readonly<Record<string, string>> = {\n [F.handle]: 'Handle',\n [F.title]: 'Title',\n [F.description]: 'Body (HTML)',\n [F.tags]: 'Tags',\n [F.published]: 'Published',\n [F.option1Name]: 'Option1 Name',\n [F.option1Value]: 'Option1 Value',\n [F.option2Name]: 'Option2 Name',\n [F.option2Value]: 'Option2 Value',\n [F.option3Name]: 'Option3 Name',\n [F.option3Value]: 'Option3 Value',\n [F.sku]: 'Variant SKU',\n [F.weightGrams]: 'Variant Grams',\n [F.inventory]: 'Variant Inventory Qty',\n [F.oversellPolicy]: 'Variant Inventory Policy',\n [F.price]: 'Variant Price',\n [F.compareAtPrice]: 'Variant Compare At Price',\n [F.barcode]: 'Variant Barcode',\n [F.image]: 'Image Src',\n [F.seoTitle]: 'SEO Title',\n [F.seoDescription]: 'SEO Description',\n [F.variantImage]: 'Variant Image',\n [F.status]: 'Status',\n}\n\n/** Shopify's export headers, so its file maps column for column. */\nexport const PRODUCT_ALIAS_DICTIONARIES: readonly TransferAliasDictionary[] = [\n {\n source: 'Shopify',\n aliases: Object.fromEntries(\n Object.entries(SHOPIFY_PRODUCT_COLUMNS).map(([fieldId, column]) => [fieldId, [column]]),\n ),\n },\n]\n\n/**\n * The Shopify preset: Shopify's product CSV columns, in Shopify's order and\n * under Shopify's names. Status is left out — Shopify reads it in lowercase\n * and Published says the same thing — and so is the kind, which Shopify's\n * \"Type\" does not mean.\n */\nexport const SHOPIFY_PRODUCT_PRESET: TransferResourcePreset = {\n id: 'shopify',\n label: 'Shopify',\n description: 'Shopify’s product CSV: its columns, its order and its names.',\n fieldIds: [\n F.handle,\n F.title,\n F.description,\n F.tags,\n F.published,\n F.option1Name,\n F.option1Value,\n F.option2Name,\n F.option2Value,\n F.option3Name,\n F.option3Value,\n F.sku,\n F.weightGrams,\n F.inventory,\n F.oversellPolicy,\n F.price,\n F.compareAtPrice,\n F.barcode,\n F.image,\n F.seoTitle,\n F.seoDescription,\n F.variantImage,\n ],\n headers: Object.fromEntries(\n Object.entries(SHOPIFY_PRODUCT_COLUMNS).filter(([fieldId]) => fieldId !== F.status),\n ),\n}\n\n/*==========================================\n * A PRODUCT AS RECORDS\n *=========================================*/\n\n/** Where a product's record keeps its variants, apart from its fields. */\nexport const PRODUCT_VARIANT_ORDER = '$variants'\n\n/** The record key one variant's values live under. */\nexport function productVariantKey(variantId: string): string {\n return `$variant:${variantId}`\n}\n\n/** A variant's values, as a file names them. */\nexport type VariantRecord = Record<string, unknown> & {\n /** Its stock is kept per location. */\n $byLocation?: boolean\n}\n\n/** A product as a stored document, the way every reader lifts one. */\ntype StoredProduct = Partial<HostProduct> & {\n createdAt?: unknown\n updatedAt?: unknown\n createdAtMs?: number\n updatedAtMs?: number\n}\n\nconst isoOf = (value: unknown, ms?: number): string | null => {\n const time =\n typeof ms === 'number'\n ? ms\n : value && typeof (value as { toMillis?: () => number }).toMillis === 'function'\n ? (value as { toMillis: () => number }).toMillis()\n : typeof value === 'number'\n ? value\n : null\n return time === null || !Number.isFinite(time) ? null : new Date(time).toISOString()\n}\n\n/** One variant as a file names it. */\nexport function variantRecord(variant: ProductVariant, options: readonly ProductOption[]): VariantRecord {\n const values: VariantRecord = {\n [F.sku]: variant.sku ?? null,\n [F.barcode]: variant.barcode ?? null,\n [F.price]: Number.isFinite(Number(variant.priceUsd)) ? Number(variant.priceUsd) : null,\n [F.compareAtPrice]: variant.compareAtPriceUsd ?? null,\n [F.inventory]: typeof variant.inventory === 'number' ? variant.inventory : null,\n [F.weightGrams]: variant.weightGrams ?? null,\n [F.variantImage]: variant.imageUrl ?? null,\n }\n OPTION_VALUE_FIELDS.forEach((fieldId, axis) => {\n const name = options[axis]?.name\n values[fieldId] = name ? (variant.options?.[name] ?? null) : null\n })\n if (variant.inventoryByLocation && Object.keys(variant.inventoryByLocation).length) values.$byLocation = true\n // Only when set: an undo snapshot written before this column compares equal.\n const checkIn = checkInCellOf(variant.checkIn)\n if (checkIn) values[F.variantCheckIn] = checkIn\n return values\n}\n\n/**\n * A product as one record: its fields by field id, and its variants under\n * {@link productVariantKey} in the order {@link PRODUCT_VARIANT_ORDER} lists\n * them. The lookup answers this shape, so the dry run's before → after and\n * undo's \"edited since\" both read a product the way a file names it.\n */\nexport function productRecord(\n stored: StoredProduct,\n categoryNames: ReadonlyMap<string, string> = new Map(),\n): Record<string, unknown> {\n const product = stored as HostProduct\n const options = product.options ?? []\n const variants = Array.isArray(product.variants) ? product.variants : []\n const [low] = variants.length ? productPriceRange(product) : [null]\n const total = variants.length ? productInventory(product) : null\n const record: Record<string, unknown> = {\n [F.handle]: product.slug ?? null,\n [F.title]: product.name ?? null,\n [F.description]: product.description ?? null,\n [F.kind]: fixedListLabel(PRODUCT_KIND_PICKLIST, product.type ?? 'physical'),\n [F.status]: fixedListLabel(PRODUCT_STATUS_PICKLIST, product.status ?? 'active'),\n [F.published]: (product.status ?? 'active') === 'active',\n [F.tags]: product.tags?.length ? product.tags.join(', ') : null,\n [F.categories]: (product.categoryIds ?? []).map((id) => categoryNames.get(id) ?? id),\n [F.image]: product.mediaUrls?.length ? [...product.mediaUrls] : product.imageUrl ? [product.imageUrl] : [],\n [F.seoTitle]: product.seo?.title ?? null,\n [F.seoDescription]: product.seo?.description ?? null,\n [F.taxExempt]: product.taxExempt ?? null,\n [F.oversellPolicy]: fixedListLabel(PRODUCT_OVERSELL_PICKLIST, product.oversellPolicy ?? 'deny'),\n [F.lowStockThreshold]: product.lowStockThreshold ?? null,\n [F.posQuickKey]: product.posQuickKey ?? null,\n [F.checkIn]: checkInCellOf(product.checkIn),\n [F.modifierGroups]: addOnCellOf(product.modifierGroups, variants),\n [F.priceFrom]: low,\n [F.totalInventory]: total,\n [F.soldOut]: total !== null && total <= 0 && product.oversellPolicy !== 'backorder',\n [F.variantCount]: variants.length,\n [F.createdAt]: isoOf(stored.createdAt, stored.createdAtMs),\n [F.updatedAt]: isoOf(stored.updatedAt, stored.updatedAtMs),\n [PRODUCT_VARIANT_ORDER]: variants.map((variant) => variant.id),\n }\n OPTION_NAME_FIELDS.forEach((fieldId, axis) => {\n record[fieldId] = options[axis]?.name ?? null\n })\n for (const variant of variants) record[productVariantKey(variant.id)] = variantRecord(variant, options)\n return record\n}\n\n/**\n * A product's rows in a file, holding only `fieldIds`: one per variant (and\n * per image past the variants), the product's own fields on the first, the\n * handle and the ID on every one.\n */\nexport function productExportRows(\n id: string,\n stored: StoredProduct,\n fieldIds: readonly string[],\n categoryNames: ReadonlyMap<string, string> = new Map(),\n): Array<Record<string, unknown>> {\n const record = productRecord(stored, categoryNames)\n const variantIds = record[PRODUCT_VARIANT_ORDER] as string[]\n const images = record[F.image] as string[]\n const count = Math.max(1, variantIds.length, images.length)\n const variantFields = new Set(VARIANT_LEVEL_FIELDS)\n const rows: Array<Record<string, unknown>> = []\n for (let index = 0; index < count; index += 1) {\n const variantId = variantIds[index]\n const variant = variantId ? (record[productVariantKey(variantId)] as VariantRecord) : null\n const row: Record<string, unknown> = {}\n for (const fieldId of fieldIds) {\n if (fieldId === 'id') row[fieldId] = id\n else if (fieldId === F.handle) row[fieldId] = record[F.handle]\n else if (fieldId === F.image) row[fieldId] = images[index] ?? null\n else if (variantFields.has(fieldId)) row[fieldId] = variant ? (variant[fieldId] ?? null) : null\n else row[fieldId] = index === 0 ? (record[fieldId] ?? null) : null\n }\n rows.push(row)\n }\n return rows\n}\n\n/** How many rows {@link productExportRows} writes for a product. */\nexport function productExportRowCount(stored: Pick<StoredProduct, 'variants' | 'mediaUrls' | 'imageUrl'>): number {\n const variants = Array.isArray(stored.variants) ? stored.variants.length : 0\n const images = stored.mediaUrls?.length ?? (stored.imageUrl ? 1 : 0)\n return Math.max(1, variants, images)\n}\n\n/*==========================================\n * THE PLAN\n *=========================================*/\n\n/** What a planned product row carries for the apply. */\nexport interface ProductRowPlan {\n /** The product the row writes: its id, or the id a new one is created under. */\n productId: string\n /** The file row carrying the product's own fields. */\n leader: number\n /**\n * `create` makes the product (its leader); `part` is a row folded into a\n * product the leader creates; `update` writes this row's changes into an\n * existing product.\n */\n role: 'create' | 'part' | 'update'\n /** The variant this row writes, when it writes one. */\n variant?: { id: string; isNew: boolean }\n /** On a new product's leader: the whole document's parts. */\n create?: {\n slug: string\n values: Record<string, unknown>\n variants: Array<{ id: string; values: Record<string, unknown> }>\n }\n /** Why the product this row belongs to cannot be stored, when it cannot. */\n problem?: string\n /**\n * On a first row whose add-ons are priced by variant: the variants by name\n * once every row is written, since a later row may be what adds one.\n */\n addOnVariants?: Record<string, string[]>\n}\n\n/** A planned row with what the apply needs. */\nexport type ProductPlannedRow = PlannedTransferRow & { commerce?: ProductRowPlan }\n\nexport interface ProductPlanContext {\n /** A new product's id. */\n newProductId(): string\n /** A new variant's id, unique within its product. */\n newVariantId(): string\n /** Whether a slug is held by a product already (deleted ones included). */\n slugTaken?(slug: string): boolean\n /** How many products the site may still create; unbounded when absent. */\n maxCreates?: number\n}\n\nconst text = (value: unknown): string => (value === null || value === undefined ? '' : String(value).trim())\n\n/** A money cell as US dollars: the derived amount, or the number as typed. */\nfunction dollars(value: unknown): { ok: true; value: number | null } | { ok: false; message: string } {\n if (value === null || value === undefined || value === '') return { ok: true, value: null }\n if (typeof value === 'number') return { ok: true, value }\n if (typeof value === 'object' && 'amountMinor' in (value as object)) {\n const amount = value as { amountMinor: number; currency: string }\n if (String(amount.currency).toUpperCase() !== 'USD') {\n return { ok: false, message: `Prices are in US dollars; ${amount.currency} is not converted.` }\n }\n return { ok: true, value: Math.round(Number(amount.amountMinor)) / 100 }\n }\n const number = Number(value)\n return Number.isFinite(number) ? { ok: true, value: number } : { ok: false, message: `\"${String(value)}\" is not a price.` }\n}\n\n/** The tags a cell names, in their own case. */\nexport function productTagList(value: unknown): string[] {\n const list = Array.isArray(value) ? value : String(value ?? '').split(',')\n const seen = new Set<string>()\n const out: string[] = []\n for (const raw of list) {\n const tag = String(raw).trim()\n if (!tag || seen.has(tag)) continue\n seen.add(tag)\n out.push(tag)\n }\n return out\n}\n\n/**\n * A row's values the way the plan compares them with a record: prices in\n * dollars, a fixed list's label checked, tags as one comma list, Published\n * read as the status. What cannot be read is dropped as a located problem.\n */\nfunction normalizeRow(row: TransferPlanRow): TransferPlanRow {\n const values: Record<string, unknown> = { ...row.values }\n const problems = [...(row.problems ?? [])]\n const drop = (fieldId: string, code: DeriveProblemCode, message: string) => {\n problems.push({ fieldId, raw: text(values[fieldId]), code, message })\n delete values[fieldId]\n }\n for (const fieldId of [F.price, F.compareAtPrice]) {\n if (!(fieldId in values)) continue\n const read = dollars(values[fieldId])\n if ('message' in read) drop(fieldId, 'invalidCurrency', read.message)\n else values[fieldId] = read.value\n }\n for (const [fieldId, picklistId] of [\n [F.kind, PRODUCT_KIND_PICKLIST],\n [F.status, PRODUCT_STATUS_PICKLIST],\n [F.oversellPolicy, PRODUCT_OVERSELL_PICKLIST],\n ] as const) {\n if (isBlankTransferValue(values[fieldId])) continue\n const id = fixedListId(picklistId, values[fieldId])\n if (id) values[fieldId] = fixedListLabel(picklistId, id)\n else drop(fieldId, 'invalidJson', `\"${text(values[fieldId])}\" is not one of ${PRODUCT_FIXED_PICKLISTS[picklistId]?.standardValues.map((entry) => entry.label).join(', ')}.`)\n }\n if (F.tags in values && !isBlankTransferValue(values[F.tags])) {\n values[F.tags] = productTagList(values[F.tags]).join(', ')\n }\n if (F.handle in values && !isBlankTransferValue(values[F.handle])) {\n const slug = commerceSlug(text(values[F.handle]))\n if (slug) values[F.handle] = slug\n else drop(F.handle, 'invalidUrl', `\"${text(values[F.handle])}\" has no letters or numbers to make a handle from.`)\n }\n for (const fieldId of [F.checkIn, F.variantCheckIn]) {\n if (isBlankTransferValue(values[fieldId])) continue\n const read = readCheckInCell(values[fieldId])\n if ('message' in read) drop(fieldId, 'invalidJson', read.message)\n else values[fieldId] = writeCheckInCell(read.value)\n }\n if (!isBlankTransferValue(values[F.modifierGroups])) {\n const read = readAddOnCell(values[F.modifierGroups])\n if ('message' in read) drop(F.modifierGroups, 'invalidJson', read.message)\n else values[F.modifierGroups] = writeAddOnCell(read.value)\n }\n if (F.published in values) {\n if (isBlankTransferValue(values[F.status]) && typeof values[F.published] === 'boolean') {\n values[F.status] = values[F.published] ? STATUS_LABELS.active : STATUS_LABELS.draft\n }\n delete values[F.published]\n }\n return { ...row, values, ...(problems.length ? { problems } : {}) }\n}\n\nconst pick = (values: Readonly<Record<string, unknown>>, fieldIds: readonly string[]): Record<string, unknown> => {\n const out: Record<string, unknown> = {}\n for (const fieldId of fieldIds) if (fieldId in values) out[fieldId] = values[fieldId]\n return out\n}\n\nconst hasAny = (values: Readonly<Record<string, unknown>>, fieldIds: readonly string[]): boolean =>\n fieldIds.some((fieldId) => !isBlankTransferValue(values[fieldId]))\n\n/** Which product a row belongs to in the file. */\nfunction groupKey(row: TransferPlanRow, position: number): string {\n const handle = text(row.values[F.handle])\n if (handle) return `h:${handle}`\n const id = text(row.values['id'])\n if (id) return `i:${id}`\n return `r:${position}`\n}\n\ninterface Group {\n key: string\n positions: number[]\n}\n\n/** Warnings, tallied the way the core tallies them, for what this plan adds and merges. */\nclass Tally {\n private readonly byClass = new Map<TransferWarningClass, TransferWarning & { rowSet: Set<number>; fieldSet: Set<string> }>()\n\n merge(warnings: readonly TransferWarning[]): void {\n for (const warning of warnings) {\n const entry = this.entry(warning.class, warning.requiresAcknowledgement)\n entry.count += warning.count\n for (const sample of warning.samples) {\n entry.rowSet.add(sample.row)\n if (entry.samples.length < 5) entry.samples.push(sample)\n }\n for (const fieldId of warning.fieldIds) entry.fieldSet.add(fieldId)\n entry.requiresAcknowledgement ||= warning.requiresAcknowledgement\n }\n }\n\n add(warningClass: TransferWarningClass, sample: TransferWarningSample): void {\n const entry = this.entry(warningClass, true)\n entry.count += 1\n entry.rowSet.add(sample.row)\n if (sample.fieldId) entry.fieldSet.add(sample.fieldId)\n if (entry.samples.length < 5) entry.samples.push(sample)\n }\n\n private entry(warningClass: TransferWarningClass, acknowledge: boolean) {\n let entry = this.byClass.get(warningClass)\n if (!entry) {\n entry = {\n class: warningClass,\n count: 0,\n rows: 0,\n fieldIds: [],\n samples: [],\n requiresAcknowledgement: acknowledge,\n rowSet: new Set(),\n fieldSet: new Set(),\n }\n this.byClass.set(warningClass, entry)\n }\n return entry\n }\n\n list(order: readonly TransferWarningClass[]): TransferWarning[] {\n return [...this.byClass.values()]\n .sort((a, b) => order.indexOf(a.class) - order.indexOf(b.class))\n .map(({ rowSet, fieldSet, ...warning }) => ({\n ...warning,\n rows: Math.max(rowSet.size, warning.rows),\n fieldIds: [...fieldSet],\n }))\n }\n}\n\n/** The order the core lists warning classes in. */\nconst WARNING_ORDER: readonly TransferWarningClass[] = TRANSFER_WARNING_CLASSES\n\n/** A variant line's identity in the product it targets. */\nfunction optionKey(values: Readonly<Record<string, unknown>>, names: readonly (string | null)[]): string | null {\n const parts: string[] = []\n OPTION_VALUE_FIELDS.forEach((fieldId, axis) => {\n const value = text(values[fieldId])\n if (value && names[axis]) parts.push(`${names[axis]}=${value.toLowerCase()}`)\n })\n return parts.length ? parts.join('|') : null\n}\n\n/** The value a field's diff leaves, or what the record held. */\nfunction after(diff: readonly TransferFieldChange[], before: Readonly<Record<string, unknown>>, fieldId: string): unknown {\n const change = diff.find((entry) => entry.fieldId === fieldId)\n return change ? change.after : before[fieldId]\n}\n\n/**\n * A product's document from its record values (see {@link productRecord}),\n * for checking what a plan would store with the model's own rules.\n */\nexport function productFromRecord(\n values: Readonly<Record<string, unknown>>,\n variants: ReadonlyArray<{ id: string; values: Readonly<Record<string, unknown>> }>,\n): HostProduct {\n const names = OPTION_NAME_FIELDS.map((fieldId) => text(values[fieldId]))\n const options: ProductOption[] = []\n names.forEach((name, axis) => {\n if (!name) return\n const seen: string[] = []\n for (const variant of variants) {\n const value = text(variant.values[OPTION_VALUE_FIELDS[axis] as string])\n if (value && !seen.includes(value)) seen.push(value)\n }\n options.push({ name, values: seen })\n })\n const checkIn = isBlankTransferValue(values[F.checkIn]) ? undefined : checkInFromCell(values[F.checkIn])\n return {\n name: text(values[F.title]),\n slug: text(values[F.handle]),\n type: (fixedListId(PRODUCT_KIND_PICKLIST, values[F.kind]) ?? 'physical') as ProductType,\n status: (fixedListId(PRODUCT_STATUS_PICKLIST, values[F.status]) ?? 'active') as ProductStatus,\n ...(options.length ? { options } : {}),\n ...(checkIn ? { checkIn } : {}),\n variants: variants.map((variant) => variantFromRecord(variant.id, variant.values, names)),\n }\n}\n\n/** One variant of a document from its record values. */\nexport function variantFromRecord(\n id: string,\n values: Readonly<Record<string, unknown>>,\n optionNames: readonly (string | null | undefined)[],\n): ProductVariant {\n const options: Record<string, string> = {}\n OPTION_VALUE_FIELDS.forEach((fieldId, axis) => {\n const name = text(optionNames[axis])\n const value = text(values[fieldId])\n if (name && value) options[name] = value\n })\n const number = (fieldId: string): number | undefined => {\n const raw = values[fieldId]\n return raw === null || raw === undefined || raw === '' || !Number.isFinite(Number(raw)) ? undefined : Number(raw)\n }\n const inventory = number(F.inventory)\n const checkIn = isBlankTransferValue(values[F.variantCheckIn]) ? undefined : checkInFromCell(values[F.variantCheckIn])\n return {\n id,\n ...(Object.keys(options).length ? { options } : {}),\n priceUsd: number(F.price) as number,\n ...(text(values[F.sku]) ? { sku: text(values[F.sku]) } : {}),\n ...(text(values[F.barcode]) ? { barcode: text(values[F.barcode]) } : {}),\n ...(number(F.compareAtPrice) !== undefined ? { compareAtPriceUsd: number(F.compareAtPrice) } : {}),\n ...(number(F.weightGrams) !== undefined ? { weightGrams: number(F.weightGrams) } : {}),\n ...(text(values[F.variantImage]) ? { imageUrl: text(values[F.variantImage]) } : {}),\n inventory: inventory === undefined ? null : Math.max(0, Math.round(inventory)),\n ...(checkIn ? { checkIn } : {}),\n }\n}\n\n/** The fields a new product is refused without. */\nconst PRODUCT_PLAN_FIELDS = (fields: readonly TransferField[]) =>\n fields\n .filter((field) => !VARIANT_LEVEL_FIELDS.includes(field.id))\n .map((field) => (field.id === F.title ? { ...field, required: true } : field))\nconst VARIANT_PLAN_FIELDS = (fields: readonly TransferField[]) =>\n fields\n .filter((field) => VARIANT_LEVEL_FIELDS.includes(field.id))\n .map((field) => (field.id === F.price ? { ...field, required: true } : field))\n\n/**\n * The products resource's plan: the core's plan per product and per variant,\n * folded back into one verdict per file row (see the block header).\n */\nexport function planProductTransfer(input: BuildTransferPlanInput, context: ProductPlanContext): TransferPlan {\n const rows = input.rows.map(normalizeRow)\n const tally = new Tally()\n\n // The groups, in the order their first rows appear.\n const groups = new Map<string, Group>()\n rows.forEach((row, position) => {\n const key = groupKey(row, position)\n const group = groups.get(key) ?? { key, positions: [] }\n group.positions.push(position)\n groups.set(key, group)\n })\n const ordered = [...groups.values()]\n\n // The product half: each group's first row, with the group's images and option names.\n const leaders = ordered.map((group): TransferPlanRow => {\n const first = rows[group.positions[0] as number] as TransferPlanRow\n const values = pick(first.values, [...PRODUCT_LEVEL_FIELDS, 'id'])\n const images: string[] = []\n for (const position of group.positions) {\n const url = text(rows[position]?.values[F.image])\n if (url && !images.includes(url)) images.push(url)\n }\n if (images.length) values[F.image] = images\n else delete values[F.image]\n OPTION_NAME_FIELDS.forEach((fieldId) => {\n if (!isBlankTransferValue(values[fieldId])) return\n for (const position of group.positions) {\n const name = text(rows[position]?.values[fieldId])\n if (name) {\n values[fieldId] = name\n break\n }\n }\n })\n for (const fieldId of REGISTER_PRODUCT_FIELDS) {\n for (const position of group.positions.slice(1)) {\n const row = rows[position] as TransferPlanRow\n const cell = row.values[fieldId]\n if (isBlankTransferValue(cell)) continue\n if (isBlankTransferValue(values[fieldId])) values[fieldId] = cell\n else if (cell !== values[fieldId]) {\n tally.add('droppedCell', {\n row: row.index,\n fieldId,\n value: text(cell),\n detail: 'A product holds one of these, and an earlier row of this product already gives it.',\n })\n }\n }\n }\n return { ...first, values }\n })\n const leaderMatches = ordered.map(\n (group) => input.matches[group.positions[0] as number] ?? ({ kind: 'new' } as RowMatchOutcome),\n )\n const productPlan = buildTransferPlan({\n fields: PRODUCT_PLAN_FIELDS(input.fields),\n rows: leaders,\n matches: leaderMatches,\n existing: input.existing,\n policy: input.policy,\n limits: context.maxCreates === undefined ? {} : { maxCreates: context.maxCreates },\n })\n tally.merge(productPlan.warnings)\n\n const variantFields = VARIANT_PLAN_FIELDS(input.fields)\n const out: ProductPlannedRow[] = new Array(rows.length)\n // Slugs this plan gives new products, so two new ones never share one.\n const handedOut = new Set<string>()\n\n ordered.forEach((group, at) => {\n const planned = productPlan.rows[at] as PlannedTransferRow\n const leaderPosition = group.positions[0] as number\n const leaderIndex = (rows[leaderPosition] as TransferPlanRow).index\n const original = (position: number): RowMatchOutcome =>\n input.matches[position] ?? ({ kind: 'new' } as RowMatchOutcome)\n\n // A product that writes nothing: every row of it follows its first.\n if (planned.verdict === 'skip' || planned.verdict === 'fail') {\n for (const position of group.positions) {\n const row = rows[position] as TransferPlanRow\n out[position] =\n position === leaderPosition\n ? planned\n : {\n index: row.index,\n verdict: planned.verdict,\n recordId: null,\n ...(planned.reason ? { reason: planned.reason } : {}),\n diff: [],\n heldBack: [],\n warnings: [],\n match: original(position),\n }\n }\n return\n }\n\n const creating = planned.verdict === 'create'\n const productId = creating ? context.newProductId() : (planned.recordId as string)\n const before = creating ? {} : (input.existing.get(productId) ?? {})\n const optionNames = OPTION_NAME_FIELDS.map((fieldId) => text(after(planned.diff, before, fieldId)) || null)\n\n // The variants the product has, and which one each line names.\n const existingVariants = creating\n ? []\n : ((before[PRODUCT_VARIANT_ORDER] as string[] | undefined) ?? []).map((id) => ({\n id,\n values: (before[productVariantKey(id)] ?? {}) as VariantRecord,\n }))\n const lines = group.positions.filter((position) => {\n const values = (rows[position] as TransferPlanRow).values\n return hasAny(values, VARIANT_LEVEL_FIELDS)\n })\n const claimed = new Map<string, number>()\n const lineTargets = new Map<number, { id: string; isNew: boolean; via?: { fieldId: string; value: string } }>()\n const lineMatches: RowMatchOutcome[] = []\n const lineRows: TransferPlanRow[] = []\n const linePositions: number[] = []\n const existingVariantValues = new Map<string, Readonly<Record<string, unknown>>>()\n const duplicates = new Map<number, number>()\n for (const position of lines) {\n const row = rows[position] as TransferPlanRow\n const sku = text(row.values[F.sku]).toLowerCase()\n const key = optionKey(row.values, optionNames)\n let target = sku ? existingVariants.find((variant) => text(variant.values[F.sku]).toLowerCase() === sku) : undefined\n let via: { fieldId: string; value: string } | undefined = sku ? { fieldId: F.sku, value: sku } : undefined\n if (!target && key) {\n target = existingVariants.find((variant) => optionKey(variant.values, optionNames) === key)\n via = { fieldId: F.option1Value, value: key }\n }\n if (!target && !key && !sku && existingVariants.length === 1 && lines.length === 1) {\n target = existingVariants[0]\n via = { fieldId: 'id', value: target?.id ?? '' }\n }\n // Two lines naming one variant, or one new variant twice: the first one counts.\n const identity = target ? `v:${target.id}` : sku ? `s:${sku}` : key ? `o:${key}` : null\n const earlier = identity ? claimed.get(identity) : undefined\n if (earlier !== undefined) {\n duplicates.set(position, earlier)\n continue\n }\n if (identity) claimed.set(identity, position)\n const id = target ? target.id : context.newVariantId()\n lineTargets.set(position, { id, isNew: !target, ...(via ? { via } : {}) })\n lineRows.push({ ...row, values: pick(row.values, VARIANT_LEVEL_FIELDS) })\n linePositions.push(position)\n if (target) {\n existingVariantValues.set(`${productId}::${target.id}`, target.values)\n lineMatches.push({ kind: 'matched', recordId: `${productId}::${target.id}`, via: via as { fieldId: string; value: string } })\n } else {\n lineMatches.push({ kind: 'new' })\n }\n }\n // A cell a row could not have read, on a row no variant plan reports it for.\n for (const position of group.positions) {\n if (position === leaderPosition || linePositions.includes(position)) continue\n const row = rows[position] as TransferPlanRow\n for (const problem of row.problems ?? []) {\n if (!REGISTER_PRODUCT_FIELDS.includes(problem.fieldId)) continue\n tally.add('droppedCell', { row: row.index, fieldId: problem.fieldId, value: problem.raw, detail: problem.message })\n }\n }\n const variantPlan = buildTransferPlan({\n fields: variantFields,\n rows: lineRows,\n matches: lineMatches,\n existing: existingVariantValues,\n policy: input.policy,\n })\n tally.merge(variantPlan.warnings)\n const lineVerdicts = new Map<number, PlannedTransferRow>()\n lineRows.forEach((row, at) => {\n const position = linePositions[at] as number\n const verdict = variantPlan.rows[at] as PlannedTransferRow\n const target = lineTargets.get(position)\n // Stock kept per location moves per location, never as one total.\n if (target && !target.isNew && verdict.verdict === 'update') {\n const values = existingVariantValues.get(`${productId}::${target.id}`) as VariantRecord | undefined\n if (values?.$byLocation && verdict.diff.some((change) => change.fieldId === F.inventory)) {\n verdict.diff = verdict.diff.filter((change) => change.fieldId !== F.inventory)\n verdict.heldBack = [...verdict.heldBack, F.inventory]\n verdict.warnings = [...new Set([...verdict.warnings, 'lockedRule' as const])]\n tally.add('lockedRule', {\n row: row.index,\n fieldId: F.inventory,\n value: text(row.values[F.inventory]),\n detail: 'This variant’s stock is kept by location; change it per location on the products page.',\n })\n if (!verdict.diff.length) verdict.verdict = 'unchanged'\n }\n }\n lineVerdicts.set(position, verdict)\n })\n\n // A new product needs a variant.\n const createdLines = [...lineVerdicts.entries()].filter(([, verdict]) => verdict.verdict === 'create')\n if (creating && !createdLines.length) {\n for (const position of group.positions) {\n const row = rows[position] as TransferPlanRow\n out[position] = {\n index: row.index,\n verdict: 'fail',\n recordId: null,\n reason: 'missingRequired',\n missing: [F.price],\n diff: position === leaderPosition ? planned.diff : [],\n heldBack: [],\n warnings: position === leaderPosition ? planned.warnings : [],\n match: original(position),\n }\n }\n return\n }\n\n // The handle a new product is stored under: the file's, or one made from its title.\n let slug = ''\n let problem: string | undefined\n if (creating) {\n const base = text(after(planned.diff, before, F.handle)) || commerceSlug(text(after(planned.diff, before, F.title))) || 'product'\n const taken = (candidate: string) => handedOut.has(candidate) || Boolean(context.slugTaken?.(candidate))\n slug = base\n for (let suffix = 2; taken(slug); suffix += 1) {\n const tail = `-${suffix}`\n slug = `${base.slice(0, COMMERCE_SLUG_MAX_LENGTH - tail.length)}${tail}`\n }\n handedOut.add(slug)\n if (slug !== base) {\n tally.add('lockedRule', {\n row: leaderIndex,\n fieldId: F.handle,\n value: base,\n detail: `Another product holds /products/${base}; this one is created at /products/${slug}.`,\n })\n planned.warnings = [...new Set([...planned.warnings, 'lockedRule' as const])]\n planned.heldBack = [...planned.heldBack, F.handle]\n }\n }\n\n // What the product would hold once every row of it is written, by the model's own rules.\n const productValues: Record<string, unknown> = { ...before }\n for (const change of planned.diff) productValues[change.fieldId] = change.after\n if (creating) productValues[F.handle] = slug\n const finalVariants = existingVariants.map((variant) => ({ id: variant.id, values: { ...variant.values } as Record<string, unknown> }))\n for (const [position, verdict] of lineVerdicts) {\n if (verdict.verdict !== 'create' && verdict.verdict !== 'update') continue\n const target = lineTargets.get(position) as { id: string; isNew: boolean }\n let entry = finalVariants.find((variant) => variant.id === target.id)\n if (!entry) {\n entry = { id: target.id, values: {} }\n finalVariants.push(entry)\n }\n for (const change of verdict.diff) entry.values[change.fieldId] = change.after\n }\n let addOnVariants: Record<string, string[]> | undefined\n if (finalVariants.length > COMMERCE_MAX_VARIANTS) {\n problem = `A product holds at most ${COMMERCE_MAX_VARIANTS} variants; this file gives it ${finalVariants.length}.`\n } else {\n const candidate = productFromRecord(productValues, finalVariants)\n let check = validateProductForSave(candidate)\n const addOns = planned.diff.find((change) => change.fieldId === F.modifierGroups)?.after\n if (!check && !isBlankTransferValue(addOns)) {\n const variantIds = addOnVariantIds(candidate.variants)\n const resolved = modifierGroupsFromAddOnCell(addOns, [], variantIds)\n check =\n resolved.problem ??\n validateProductForSave({ ...candidate, modifierGroups: resolved.groups ?? [] }) ??\n variantMatrixProblem(candidate.options)\n if (resolved.groups?.some((entry) => entry.options.some((option) => option.priceCentsByVariant))) {\n addOnVariants = variantIds\n }\n }\n if (check) problem = check\n }\n\n const create = creating\n ? {\n slug,\n values: Object.fromEntries(planned.diff.map((change) => [change.fieldId, change.after])),\n variants: createdLines.map(([position, verdict]) => ({\n id: (lineTargets.get(position) as { id: string }).id,\n values: Object.fromEntries(verdict.diff.map((change) => [change.fieldId, change.after])),\n })),\n }\n : undefined\n\n for (const position of group.positions) {\n const row = rows[position] as TransferPlanRow\n const isLeader = position === leaderPosition\n const line = lineVerdicts.get(position)\n const target = lineTargets.get(position)\n const duplicateOf = duplicates.get(position)\n const base: Pick<PlannedTransferRow, 'index' | 'match'> = { index: row.index, match: original(position) }\n if (duplicateOf !== undefined) {\n const firstRow = (rows[duplicateOf] as TransferPlanRow).index\n tally.add('duplicateInFile', {\n row: row.index,\n fieldId: F.sku,\n value: text(row.values[F.sku]) || text(row.values[F.option1Value]),\n detail: `The same variant as row ${firstRow + 1}`,\n })\n out[position] = {\n ...base,\n verdict: 'skip',\n recordId: creating ? null : productId,\n reason: 'duplicateInFile',\n diff: [],\n heldBack: [],\n warnings: ['duplicateInFile'],\n }\n continue\n }\n const productDiff = isLeader ? planned.diff : []\n const lineDiff = line && (line.verdict === 'create' || line.verdict === 'update') ? line.diff : []\n const writes = productDiff.length + lineDiff.length > 0\n const lineFailed = line && (line.verdict === 'fail' || line.verdict === 'skip')\n if (lineFailed && isLeader && (productDiff.length || creating)) {\n // The product's own changes still land; the variant on this row does not, and says so.\n tally.add('droppedCell', {\n row: row.index,\n ...(line.missing?.[0] ? { fieldId: line.missing[0] } : {}),\n detail: `The variant on this row is not written (${line.reason ?? line.verdict}).`,\n })\n }\n const warnings = [...new Set([...(isLeader ? planned.warnings : []), ...(line?.warnings ?? [])])]\n const heldBack = [...(isLeader ? planned.heldBack : []), ...(line?.heldBack ?? [])]\n const plan: ProductRowPlan = {\n productId,\n leader: leaderIndex,\n role: creating ? (isLeader ? 'create' : 'part') : 'update',\n ...(target && lineDiff.length ? { variant: { id: target.id, isNew: target.isNew } } : {}),\n ...(isLeader && create ? { create } : {}),\n ...(problem ? { problem } : {}),\n ...(isLeader && addOnVariants ? { addOnVariants } : {}),\n }\n if (lineFailed && (!isLeader || !(productDiff.length || creating))) {\n out[position] = {\n ...base,\n verdict: line.verdict,\n recordId: creating ? null : productId,\n ...(line.reason ? { reason: line.reason } : {}),\n ...(line.missing ? { missing: line.missing } : {}),\n diff: [],\n heldBack,\n warnings,\n }\n continue\n }\n const verdict: PlannedTransferRow['verdict'] = creating\n ? isLeader || writes\n ? 'create'\n : 'unchanged'\n : writes\n ? 'update'\n : 'unchanged'\n out[position] = {\n ...base,\n verdict,\n recordId: creating ? null : productId,\n diff: [...productDiff, ...lineDiff],\n heldBack,\n warnings,\n ...(verdict === 'create' || verdict === 'update' ? { commerce: plan } : problem ? { commerce: plan } : {}),\n } as ProductPlannedRow\n }\n })\n\n const summary = { create: 0, update: 0, unchanged: 0, skip: 0, fail: 0, total: out.length }\n for (const row of out) summary[row.verdict] += 1\n const warnings = tally.list(WARNING_ORDER)\n return {\n rows: out,\n summary,\n warnings,\n acknowledgementsRequired: warnings.filter((entry) => entry.requiresAcknowledgement).map((entry) => entry.class),\n }\n}\n\n/** The handles a plan may create products under, for the server to ask which are taken. */\nexport function productPlanHandles(rows: readonly TransferPlanRow[]): string[] {\n const out = new Set<string>()\n for (const row of rows) {\n const handle = commerceSlug(text(row.values[F.handle])) || commerceSlug(text(row.values[F.title]))\n if (handle) out.add(handle)\n }\n return [...out]\n}\n\n/*==========================================\n * WHAT A PLANNED ROW WRITES\n *=========================================*/\n\n/** Category names → ids, for the categories a row names. */\nexport type CategoryIdsOf = (names: readonly string[]) => string[]\n\n/** The product fields a row's changes set, as the document stores them. */\nfunction productFieldPatch(\n changes: Readonly<Record<string, unknown>>,\n categoryIdsOf: CategoryIdsOf,\n): Partial<HostProduct> & { seo?: HostProduct['seo'] } {\n const patch: Partial<HostProduct> = {}\n const has = (fieldId: string) => fieldId in changes\n const value = (fieldId: string) => changes[fieldId]\n if (has(F.title)) patch.name = text(value(F.title))\n if (has(F.description)) patch.description = text(value(F.description)) || undefined\n if (has(F.kind)) patch.type = (fixedListId(PRODUCT_KIND_PICKLIST, value(F.kind)) ?? 'physical') as ProductType\n if (has(F.status)) patch.status = (fixedListId(PRODUCT_STATUS_PICKLIST, value(F.status)) ?? 'active') as ProductStatus\n if (has(F.tags)) patch.tags = productTagList(value(F.tags))\n if (has(F.categories)) {\n const names = Array.isArray(value(F.categories)) ? (value(F.categories) as unknown[]).map(text).filter(Boolean) : []\n patch.categoryIds = categoryIdsOf(names)\n }\n if (has(F.image)) {\n const urls = Array.isArray(value(F.image)) ? (value(F.image) as unknown[]).map(text).filter(Boolean) : []\n patch.mediaUrls = urls\n }\n if (has(F.taxExempt)) patch.taxExempt = value(F.taxExempt) === true\n if (has(F.oversellPolicy)) {\n patch.oversellPolicy = (fixedListId(PRODUCT_OVERSELL_PICKLIST, value(F.oversellPolicy)) ?? 'deny') as 'deny' | 'backorder'\n }\n if (has(F.lowStockThreshold)) {\n const threshold = Number(value(F.lowStockThreshold))\n patch.lowStockThreshold = value(F.lowStockThreshold) === null || !Number.isFinite(threshold) ? undefined : Math.max(0, Math.round(threshold))\n }\n if (has(F.posQuickKey)) patch.posQuickKey = value(F.posQuickKey) === null ? undefined : value(F.posQuickKey) === true\n if (has(F.checkIn)) patch.checkIn = isBlankTransferValue(value(F.checkIn)) ? undefined : checkInFromCell(value(F.checkIn))\n return patch\n}\n\n/** A product with one planned row's changes written into it — the product's own on its first row, and the row's variant. */\nexport function applyProductRow(\n current: HostProduct,\n changes: {\n product?: Readonly<Record<string, unknown>>\n variant?: { id: string; isNew: boolean; values: Readonly<Record<string, unknown>> }\n /** The variants an add-ons cell's prices name, when the plan knows more than the product holds yet. */\n addOnVariants?: Readonly<Record<string, string[]>>\n },\n categoryIdsOf: CategoryIdsOf,\n): HostProduct {\n const next: HostProduct = {\n ...current,\n options: (current.options ?? []).map((option) => ({ ...option, values: [...option.values] })),\n variants: current.variants.map((variant) => ({ ...variant })),\n }\n const product = changes.product ?? {}\n Object.assign(next, productFieldPatch(product, categoryIdsOf))\n if (F.seoTitle in product || F.seoDescription in product) {\n const seo = { ...(current.seo ?? {}) }\n if (F.seoTitle in product) seo.title = text(product[F.seoTitle]) || undefined\n if (F.seoDescription in product) seo.description = text(product[F.seoDescription]) || undefined\n next.seo = Object.fromEntries(Object.entries(seo).filter(([, entry]) => entry !== undefined))\n }\n if (F.modifierGroups in product) {\n const { groups } = isBlankTransferValue(product[F.modifierGroups])\n ? { groups: [] }\n : modifierGroupsFromAddOnCell(\n product[F.modifierGroups],\n current.modifierGroups,\n changes.addOnVariants ?? addOnVariantIds(next.variants),\n )\n if (groups?.length) next.modifierGroups = groups\n else if (groups) delete next.modifierGroups\n }\n // An option the product does not have yet takes its name.\n const options = next.options as ProductOption[]\n OPTION_NAME_FIELDS.forEach((fieldId, axis) => {\n const name = text(product[fieldId])\n if (name && !options[axis]) options[axis] = { name, values: [] }\n })\n const variant = changes.variant\n if (variant) {\n const names = options.map((option) => option?.name ?? null)\n const at = next.variants.findIndex((entry) => entry.id === variant.id)\n const existing = at >= 0 ? (next.variants[at] as ProductVariant) : null\n const record = existing ? variantRecord(existing, options) : {}\n const merged = variantFromRecord(variant.id, { ...record, ...variant.values }, names)\n const written: ProductVariant = existing\n ? {\n ...existing,\n ...merged,\n // What a file never names is kept: stock by location, and anything the variant carries besides.\n ...(existing.inventoryByLocation ? { inventoryByLocation: existing.inventoryByLocation, inventory: existing.inventory } : {}),\n }\n : merged\n for (const key of ['sku', 'barcode', 'compareAtPriceUsd', 'weightGrams', 'imageUrl'] as const) {\n if (merged[key] === undefined) delete written[key]\n }\n // Its check-in moves only when the file names it, and stays exactly as stored when not.\n if (F.variantCheckIn in variant.values ? merged.checkIn === undefined : existing?.checkIn === undefined) delete written.checkIn\n else if (!(F.variantCheckIn in variant.values)) written.checkIn = existing?.checkIn\n if (at >= 0) next.variants[at] = written\n else next.variants.push(written)\n // Each option value the variant holds is one its option offers.\n options.forEach((option, axis) => {\n const value = text(variant.values[OPTION_VALUE_FIELDS[axis] as string])\n if (option && value && !option.values.includes(value)) option.values.push(value)\n })\n }\n next.options = options.filter(Boolean)\n if (!next.options.length) delete next.options\n return next\n}\n\n/** A new product's document from its leader's plan, before the platform's stamps. */\nexport function createProductDocument(\n create: NonNullable<ProductRowPlan['create']>,\n categoryIdsOf: CategoryIdsOf,\n): HostProduct {\n const base = productFromRecord({ ...create.values, [F.handle]: create.slug }, create.variants)\n return applyProductRow(\n { ...base, variants: base.variants },\n { product: Object.fromEntries(Object.entries(create.values).filter(([fieldId]) => !OPTION_NAME_FIELDS.includes(fieldId as never))) },\n categoryIdsOf,\n )\n}\n\n/** The values one planned row changes, split into the product's and its variant's. */\nexport function productRowChanges(row: ProductPlannedRow): {\n product: Record<string, unknown>\n variant?: { id: string; isNew: boolean; values: Record<string, unknown> }\n addOnVariants?: Record<string, string[]>\n} {\n const product: Record<string, unknown> = {}\n const variant: Record<string, unknown> = {}\n for (const change of row.diff) {\n if (VARIANT_LEVEL_FIELDS.includes(change.fieldId)) variant[change.fieldId] = change.after\n else if (PRODUCT_LEVEL_FIELDS.includes(change.fieldId)) product[change.fieldId] = change.after\n }\n const target = row.commerce?.variant\n const addOnVariants = row.commerce?.addOnVariants\n return { product, ...(target ? { variant: { ...target, values: variant } } : {}), ...(addOnVariants ? { addOnVariants } : {}) }\n}\n"],"names":["validateProductForSave","buildTransferPlan","isBlankTransferValue","TRANSFER_SYSTEM_GROUP","TRANSFER_WARNING_CLASSES","COMMERCE_MAX_VARIANTS","COMMERCE_SLUG_MAX_LENGTH","commerceSlug","productInventory","productPriceRange","variantMatrixProblem","addOnCellOf","addOnVariantIds","checkInCellOf","checkInFromCell","modifierGroupsFromAddOnCell","readAddOnCell","readCheckInCell","writeAddOnCell","writeCheckInCell","PRODUCT_FIELD","handle","title","description","kind","status","published","tags","categories","option1Name","option2Name","option3Name","image","seoTitle","seoDescription","taxExempt","oversellPolicy","lowStockThreshold","posQuickKey","checkIn","modifierGroups","option1Value","option2Value","option3Value","sku","barcode","price","compareAtPrice","inventory","weightGrams","variantImage","variantCheckIn","priceFrom","totalInventory","soldOut","variantCount","createdAt","updatedAt","F","PRODUCT_KIND_PICKLIST","PRODUCT_STATUS_PICKLIST","PRODUCT_OVERSELL_PICKLIST","PRODUCT_CATEGORY_PICKLIST","KIND_LABELS","physical","digital","service","STATUS_LABELS","active","draft","archived","OVERSELL_LABELS","deny","backorder","fixedList","labels","defaultValueId","restricted","standardValues","Object","entries","map","id","label","PRODUCT_FIXED_PICKLISTS","fixedListId","picklistId","value","spec","key","String","trim","toLowerCase","found","find","entry","fixedListLabel","PRODUCT_TRANSFER_GROUPS","PRODUCT_LEVEL_FIELDS","REGISTER_PRODUCT_FIELDS","VARIANT_LEVEL_FIELDS","OPTION_NAME_FIELDS","OPTION_VALUE_FIELDS","PRODUCT_STANDARD_FIELDS","group","type","maxLength","aliases","PRODUCT_DERIVED_FIELDS","PRODUCT_SYSTEM_FIELDS","PRODUCT_MATCH_KEYS","fieldId","normalizer","PRODUCT_LOCKED_RULES","reason","forced","mode","blank","SHOPIFY_PRODUCT_COLUMNS","PRODUCT_ALIAS_DICTIONARIES","source","fromEntries","column","SHOPIFY_PRODUCT_PRESET","fieldIds","headers","filter","PRODUCT_VARIANT_ORDER","productVariantKey","variantId","isoOf","ms","time","toMillis","Number","isFinite","Date","toISOString","variantRecord","variant","options","values","priceUsd","compareAtPriceUsd","imageUrl","forEach","axis","name","inventoryByLocation","keys","length","$byLocation","productRecord","stored","categoryNames","Map","product","variants","Array","isArray","low","total","record","slug","join","categoryIds","get","mediaUrls","seo","createdAtMs","updatedAtMs","productExportRows","variantIds","images","count","Math","max","variantFields","Set","rows","index","row","has","push","productExportRowCount","text","undefined","dollars","ok","amount","currency","toUpperCase","message","round","amountMinor","number","productTagList","list","split","seen","out","raw","tag","add","normalizeRow","problems","drop","code","read","pick","hasAny","some","groupKey","position","Tally","merge","warnings","warning","class","requiresAcknowledgement","sample","samples","rowSet","fieldSet","warningClass","acknowledge","byClass","set","order","sort","a","b","indexOf","size","WARNING_ORDER","optionKey","names","parts","after","diff","before","change","productFromRecord","includes","variantFromRecord","optionNames","PRODUCT_PLAN_FIELDS","fields","field","required","VARIANT_PLAN_FIELDS","planProductTransfer","input","context","tally","groups","positions","ordered","leaders","first","url","slice","cell","detail","leaderMatches","matches","productPlan","existing","policy","limits","maxCreates","handedOut","at","planned","leaderPosition","leaderIndex","original","verdict","recordId","heldBack","match","creating","productId","newProductId","existingVariants","lines","claimed","lineTargets","lineMatches","lineRows","linePositions","existingVariantValues","duplicates","target","via","identity","earlier","newVariantId","isNew","problem","variantPlan","lineVerdicts","createdLines","missing","base","taken","candidate","Boolean","slugTaken","suffix","tail","productValues","finalVariants","addOnVariants","check","addOns","resolved","option","priceCentsByVariant","create","isLeader","line","duplicateOf","firstRow","productDiff","lineDiff","writes","lineFailed","plan","leader","role","commerce","summary","update","unchanged","skip","fail","acknowledgementsRequired","productPlanHandles","productFieldPatch","changes","categoryIdsOf","patch","urls","threshold","applyProductRow","current","next","assign","findIndex","merged","written","createProductDocument","productRowChanges"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,iCAA6B;AACpE,SACEC,iBAAiB,EACjBC,oBAAoB,EACpBC,qBAAqB,EACrBC,wBAAwB,QAiBnB,6BAA4B;AAEnC,SACEC,qBAAqB,EACrBC,wBAAwB,EACxBC,YAAY,EACZC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QAMf,uBAAm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OA;IAPtB,MAAMzB,UAAmC,CAAC;IAC1C,MAAMjB,UAAmC,CAAC;IAC1C,KAAK,MAAMsG,UAAU5D,IAAI0D,IAAI,CAAE;QAC7B,IAAI3I,qBAAqB+I,QAAQ,CAACF,OAAOlI,OAAO,GAAG4B,OAAO,CAACsG,OAAOlI,OAAO,CAAC,GAAGkI,OAAOH,KAAK;aACpF,IAAI5I,qBAAqBiJ,QAAQ,CAACF,OAAOlI,OAAO,GAAG6C,OAAO,CAACqF,OAAOlI,OAAO,CAAC,GAAGkI,OAAOH,KAAK;IAChG;IACA,MAAMuD,UAAShH,gBAAAA,IAAIsJ,QAAQ,qBAAZtJ,cAAc1C,OAAO;IACpC,MAAM8K,iBAAgBpI,iBAAAA,IAAIsJ,QAAQ,qBAAZtJ,eAAcoI,aAAa;IACjD,OAAO;QAAE7J;OAAayI,SAAS;QAAE1J,SAAS,aAAK0J;YAAQxJ,QAAQF;;IAAU,IAAI,CAAC,GAAQ8K,gBAAgB;QAAEA;IAAc,IAAI,CAAC;AAC7H"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/transfer/product-transfer.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 { validateProductForSave } from '../model/product-card-rules'\nimport {\n buildTransferPlan,\n isBlankTransferValue,\n TRANSFER_SYSTEM_GROUP,\n TRANSFER_WARNING_CLASSES,\n type BuildTransferPlanInput,\n type DeriveProblemCode,\n type MatchKeySpec,\n type PlannedTransferRow,\n type RowMatchOutcome,\n type TransferAliasDictionary,\n type TransferField,\n type TransferFieldChange,\n type TransferFieldGroup,\n type TransferLockedRule,\n type TransferPlan,\n type TransferPlanRow,\n type TransferResourcePreset,\n type TransferWarning,\n type TransferWarningClass,\n type TransferWarningSample,\n} from '@aglyn/aglyn/data-transfer'\nimport type { PicklistSpec } from '@aglyn/aglyn/app-utils/picklists'\nimport {\n COMMERCE_MAX_VARIANTS,\n COMMERCE_SLUG_MAX_LENGTH,\n commerceSlug,\n productInventory,\n productPriceRange,\n variantMatrixProblem,\n type HostProduct,\n type ProductOption,\n type ProductStatus,\n type ProductType,\n type ProductVariant,\n} from '../model/commerce'\nimport {\n addOnCellOf,\n addOnVariantIds,\n checkInCellOf,\n checkInFromCell,\n modifierGroupsFromAddOnCell,\n readAddOnCell,\n readCheckInCell,\n writeAddOnCell,\n writeCheckInCell,\n} from './product-register-cells'\n\n/*\n * PRODUCTS ON THE TRANSFER FRAMEWORK (AGL-3531).\n *\n * ## One product, one row per variant\n *\n * A product's file is laid out the way storefront platforms lay theirs out:\n * a row per variant, the product's own fields (title, description, tags…)\n * on its first row, and every row carrying the product's handle. Images\n * follow the same convention — the first on the first row, the next on the\n * second, and rows of only a handle and an image when there are more images\n * than variants. So a store moving here from Shopify uploads its own export\n * as it is, and the Shopify preset writes one Shopify reads back.\n *\n * ## Rows fold into products\n *\n * The engine plans rows; a product is several. `planProductTransfer` (this\n * resource's `plan` hook) folds the rows of one handle into one product: the\n * first row decides whether the product is new or which one it is (by\n * handle, then SKU, then ID — the person's order), its product fields are\n * planned against the product, and every row's variant fields are planned\n * against the variant it names — by SKU, then by its option values, then the\n * single variant of a single-variant product. A match is UPDATED; the old\n * importer created a second product under a suffixed slug.\n *\n * Every row keeps its own verdict and diff, so the dry run shows what each\n * line of the file does, and the plan stashes what the apply needs on the\n * row (`commerce`): the product's id — minted here for a new one, so a retry\n * finds what it already wrote — the variant's, and for a new product the\n * whole document.\n *\n * ## Add-ons, check-in and quick keys\n *\n * The register's settings travel as plain cells (`product-register-cells.ts`).\n * A file without their columns never touches them, and an add-ons cell is\n * asked the questions the product editor's Save asks: `validateProductForSave` and\n * the 100-combination rule, `variantMatrixProblem`.\n *\n * ## What a file never sets\n *\n * Option names already on a product (renaming one moves every variant, which\n * the product editor does), stock kept by location (moved per location), and\n * the search, stock and collection keys every write derives.\n */\n\n/*==========================================\n * FIELDS\n *=========================================*/\n\n/** The field ids, as the catalog and every file name them. */\nexport const PRODUCT_FIELD = {\n handle: 'handle',\n title: 'title',\n description: 'description',\n kind: 'type',\n status: 'status',\n published: 'published',\n tags: 'tags',\n categories: 'categories',\n option1Name: 'option1Name',\n option2Name: 'option2Name',\n option3Name: 'option3Name',\n image: 'image',\n seoTitle: 'seoTitle',\n seoDescription: 'seoDescription',\n taxExempt: 'taxExempt',\n oversellPolicy: 'oversellPolicy',\n lowStockThreshold: 'lowStockThreshold',\n posQuickKey: 'posQuickKey',\n checkIn: 'checkIn',\n modifierGroups: 'modifierGroups',\n option1Value: 'option1Value',\n option2Value: 'option2Value',\n option3Value: 'option3Value',\n sku: 'sku',\n barcode: 'barcode',\n price: 'price',\n compareAtPrice: 'compareAtPrice',\n inventory: 'inventory',\n weightGrams: 'weightGrams',\n variantImage: 'variantImage',\n variantCheckIn: 'variantCheckIn',\n priceFrom: 'priceFrom',\n totalInventory: 'totalInventory',\n soldOut: 'soldOut',\n variantCount: 'variantCount',\n createdAt: 'createdAt',\n updatedAt: 'updatedAt',\n} as const\n\nconst F = PRODUCT_FIELD\n\n/** The picklists the product fields name. */\nexport const PRODUCT_KIND_PICKLIST = 'commerce.productKind'\nexport const PRODUCT_STATUS_PICKLIST = 'commerce.productStatus'\nexport const PRODUCT_OVERSELL_PICKLIST = 'commerce.oversellPolicy'\nexport const PRODUCT_CATEGORY_PICKLIST = 'commerce.categories'\n\nconst KIND_LABELS: Record<ProductType, string> = {\n physical: 'Physical',\n digital: 'Digital',\n service: 'Service',\n}\nconst STATUS_LABELS: Record<ProductStatus, string> = {\n active: 'Active',\n draft: 'Draft',\n archived: 'Archived',\n}\nconst OVERSELL_LABELS: Record<'deny' | 'backorder', string> = {\n deny: 'Stop selling',\n backorder: 'Keep selling',\n}\n\n/** A fixed list as the values step matches it: a file adds nothing to it. */\nfunction fixedList(labels: Record<string, string>, defaultValueId: string): PicklistSpec {\n return {\n restricted: true,\n standardValues: Object.entries(labels).map(([id, label]) => ({ id, label })),\n defaultValueId,\n }\n}\n\n/** The fixed lists products name, by picklist id. */\nexport const PRODUCT_FIXED_PICKLISTS: Readonly<Record<string, PicklistSpec>> = {\n [PRODUCT_KIND_PICKLIST]: fixedList(KIND_LABELS, 'physical'),\n [PRODUCT_STATUS_PICKLIST]: fixedList(STATUS_LABELS, 'active'),\n [PRODUCT_OVERSELL_PICKLIST]: fixedList(OVERSELL_LABELS, 'deny'),\n}\n\n/** The id a label of a fixed list names, by label or id in any case; `null` for none. */\nexport function fixedListId(picklistId: string, value: unknown): string | null {\n const spec = PRODUCT_FIXED_PICKLISTS[picklistId]\n const key = String(value ?? '').trim().toLowerCase()\n if (!spec || !key) return null\n const found = spec.standardValues.find(\n (entry) => entry.id.toLowerCase() === key || entry.label.toLowerCase() === key,\n )\n return found ? found.id : null\n}\n\n/** A fixed list's label for a stored id. */\nfunction fixedListLabel(picklistId: string, id: unknown): string | null {\n const spec = PRODUCT_FIXED_PICKLISTS[picklistId]\n return spec?.standardValues.find((entry) => entry.id === id)?.label ?? null\n}\n\nexport const PRODUCT_TRANSFER_GROUPS: readonly TransferFieldGroup[] = [\n { id: 'product', label: 'Product' },\n { id: 'variant', label: 'Variant' },\n { id: 'options', label: 'Options' },\n { id: 'media', label: 'Images' },\n { id: 'selling', label: 'Selling' },\n { id: 'seo', label: 'Search listing' },\n { id: 'computed', label: 'Computed' },\n]\n\n/** The fields a product's first row carries: the product's own. */\nexport const PRODUCT_LEVEL_FIELDS: readonly string[] = [\n F.handle,\n F.title,\n F.description,\n F.kind,\n F.status,\n F.published,\n F.tags,\n F.categories,\n F.option1Name,\n F.option2Name,\n F.option3Name,\n F.image,\n F.seoTitle,\n F.seoDescription,\n F.taxExempt,\n F.oversellPolicy,\n F.lowStockThreshold,\n F.posQuickKey,\n F.checkIn,\n F.modifierGroups,\n]\n\n/**\n * The product fields a file may give on any of a product's rows: one value\n * for the product, the first row's if it has one. A different value further\n * down is reported, never dropped without a word.\n */\nconst REGISTER_PRODUCT_FIELDS: readonly string[] = [F.posQuickKey, F.checkIn, F.modifierGroups]\n\n/** The fields every row carries for its own variant. */\nexport const VARIANT_LEVEL_FIELDS: readonly string[] = [\n F.option1Value,\n F.option2Value,\n F.option3Value,\n F.sku,\n F.barcode,\n F.price,\n F.compareAtPrice,\n F.inventory,\n F.weightGrams,\n F.variantImage,\n F.variantCheckIn,\n]\n\nconst OPTION_NAME_FIELDS = [F.option1Name, F.option2Name, F.option3Name] as const\nconst OPTION_VALUE_FIELDS = [F.option1Value, F.option2Value, F.option3Value] as const\n\n/** Every writable product field, in picker order. */\nexport const PRODUCT_STANDARD_FIELDS: readonly TransferField[] = [\n {\n id: F.handle,\n label: 'Handle',\n group: 'product',\n type: 'text',\n maxLength: 80,\n aliases: ['slug', 'url handle', 'product handle'],\n description: 'The product’s address, /products/<handle>. Rows with one handle are one product.',\n },\n {\n id: F.title,\n label: 'Title',\n group: 'product',\n type: 'text',\n aliases: ['name', 'product name', 'product title'],\n description: 'Needed for a new product.',\n },\n {\n id: F.description,\n label: 'Description',\n group: 'product',\n type: 'longText',\n aliases: ['body', 'body html', 'product description', 'description html'],\n },\n {\n id: F.kind,\n label: 'Kind',\n group: 'product',\n type: 'picklist',\n picklistId: PRODUCT_KIND_PICKLIST,\n aliases: ['product kind', 'type'],\n description: 'Physical, Digital or Service.',\n },\n {\n id: F.status,\n label: 'Status',\n group: 'product',\n type: 'picklist',\n picklistId: PRODUCT_STATUS_PICKLIST,\n aliases: ['product status'],\n description: 'Active, Draft or Archived.',\n },\n {\n id: F.published,\n label: 'Published',\n group: 'product',\n type: 'boolean',\n aliases: ['visible', 'online'],\n description: 'Read as the status when the file has no Status: yes is Active, no is Draft.',\n },\n {\n id: F.tags,\n label: 'Tags',\n group: 'product',\n type: 'text',\n aliases: ['tag', 'keywords'],\n description: 'Separated by commas; their case is kept, because collections match a tag exactly.',\n },\n {\n id: F.categories,\n label: 'Categories',\n group: 'product',\n type: 'multiPicklist',\n picklistId: PRODUCT_CATEGORY_PICKLIST,\n aliases: ['category', 'product categories'],\n description: 'By name. A name the site does not have can be added as a new category.',\n },\n { id: F.option1Name, label: 'Option 1 name', group: 'options', type: 'text', maxLength: 60 },\n { id: F.option1Value, label: 'Option 1 value', group: 'options', type: 'text', maxLength: 60 },\n { id: F.option2Name, label: 'Option 2 name', group: 'options', type: 'text', maxLength: 60 },\n { id: F.option2Value, label: 'Option 2 value', group: 'options', type: 'text', maxLength: 60 },\n { id: F.option3Name, label: 'Option 3 name', group: 'options', type: 'text', maxLength: 60 },\n { id: F.option3Value, label: 'Option 3 value', group: 'options', type: 'text', maxLength: 60 },\n {\n id: F.sku,\n label: 'SKU',\n group: 'variant',\n type: 'text',\n aliases: ['variant sku', 'stock keeping unit', 'item number'],\n },\n {\n id: F.barcode,\n label: 'Barcode',\n group: 'variant',\n type: 'text',\n aliases: ['variant barcode', 'gtin', 'upc', 'ean', 'isbn'],\n },\n {\n id: F.price,\n label: 'Price',\n group: 'variant',\n type: 'currency',\n aliases: ['variant price', 'price usd', 'unit price'],\n description: 'In US dollars. Needed for a new variant.',\n },\n {\n id: F.compareAtPrice,\n label: 'Compare-at price',\n group: 'variant',\n type: 'currency',\n aliases: ['variant compare at price', 'compare at price', 'was price', 'original price'],\n description: 'The strike-through price; above the price, or a product is refused.',\n },\n {\n id: F.inventory,\n label: 'Inventory',\n group: 'variant',\n type: 'integer',\n aliases: ['variant inventory qty', 'inventory quantity', 'quantity', 'stock', 'on hand'],\n description: 'Units in stock; blank is not counted. Stock kept by location is changed on the products page.',\n },\n {\n id: F.weightGrams,\n label: 'Weight (grams)',\n group: 'variant',\n type: 'number',\n aliases: ['variant grams', 'grams', 'weight'],\n },\n {\n id: F.variantImage,\n label: 'Variant image',\n group: 'variant',\n type: 'url',\n aliases: ['variant image url'],\n },\n {\n id: F.variantCheckIn,\n label: 'Variant check-in',\n group: 'variant',\n type: 'text',\n aliases: ['variant needs check-in', 'variant check in'],\n description: 'This variant’s own check-in, in the words of Check-in. Blank follows the product.',\n },\n {\n id: F.image,\n label: 'Image',\n group: 'media',\n type: 'url',\n aliases: ['image url', 'image src', 'photo', 'picture'],\n description: 'One image per row; the first row’s is the photo the storefront leads with.',\n },\n {\n id: F.seoTitle,\n label: 'SEO title',\n group: 'seo',\n type: 'text',\n aliases: ['meta title', 'page title', 'search title'],\n },\n {\n id: F.seoDescription,\n label: 'SEO description',\n group: 'seo',\n type: 'longText',\n aliases: ['meta description', 'search description'],\n },\n {\n id: F.taxExempt,\n label: 'Tax exempt',\n group: 'selling',\n type: 'boolean',\n aliases: ['tax free', 'no tax'],\n },\n {\n id: F.oversellPolicy,\n label: 'When sold out',\n group: 'selling',\n type: 'picklist',\n picklistId: PRODUCT_OVERSELL_PICKLIST,\n aliases: ['oversell policy', 'inventory policy', 'backorders'],\n description: 'Stop selling, or Keep selling as a backorder.',\n },\n {\n id: F.lowStockThreshold,\n label: 'Low stock alert at',\n group: 'selling',\n type: 'integer',\n aliases: ['low stock threshold', 'reorder point'],\n },\n {\n id: F.posQuickKey,\n label: 'Quick key',\n group: 'selling',\n type: 'boolean',\n aliases: ['quick key at the register', 'pos quick key', 'register quick key'],\n description: 'Yes shows the product under Quick keys on the register’s first screen.',\n },\n {\n id: F.checkIn,\n label: 'Check-in',\n group: 'selling',\n type: 'text',\n aliases: ['needs check-in', 'check in', 'checkin'],\n description: 'No or Yes. Yes can add how many people one item admits and asking the day: Yes, 4 people, ask which day.',\n },\n {\n id: F.modifierGroups,\n label: 'Add-ons',\n group: 'selling',\n type: 'longText',\n aliases: ['add ons', 'addons', 'modifiers', 'modifier groups'],\n description: 'Groups split by semicolons: Milk (at least 1): Whole, Oat +$0.75; Extras (at most 3, register only): Extra shot +$1.00.',\n },\n]\n\nexport const PRODUCT_DERIVED_FIELDS: readonly TransferField[] = [\n { id: F.priceFrom, label: 'Lowest price', group: 'computed', type: 'number' },\n { id: F.totalInventory, label: 'Total inventory', group: 'computed', type: 'integer' },\n { id: F.soldOut, label: 'Sold out', group: 'computed', type: 'boolean' },\n { id: F.variantCount, label: 'Variants', group: 'computed', type: 'integer' },\n]\n\nexport const PRODUCT_SYSTEM_FIELDS: readonly TransferField[] = [\n { id: F.createdAt, label: 'Created', group: TRANSFER_SYSTEM_GROUP.id, type: 'datetime' },\n { id: F.updatedAt, label: 'Updated', group: TRANSFER_SYSTEM_GROUP.id, type: 'datetime' },\n]\n\n/** Handle, then SKU, then the Aglyn ID. */\nexport const PRODUCT_MATCH_KEYS: readonly MatchKeySpec[] = [\n { fieldId: F.handle, normalizer: 'slug' },\n { fieldId: F.sku, normalizer: 'caseless' },\n { fieldId: 'id', normalizer: 'aglynId' },\n]\n\n/**\n * A product's handle and its option names are changed in the product editor,\n * never by a file: the handle is the product's address, and renaming an\n * option moves every variant. A file gives a new product both, and names an\n * option a product does not have yet.\n */\nexport const PRODUCT_LOCKED_RULES: readonly TransferLockedRule[] = [\n {\n fieldId: F.handle,\n reason:\n 'A product’s handle is its address; a file gives a new product one, and an existing product’s is changed in the product editor.',\n forced: { mode: 'fillBlanks', blank: 'leave' },\n },\n ...OPTION_NAME_FIELDS.map((fieldId) => ({\n fieldId,\n reason:\n 'An option a product already has is renamed in the product editor, where every variant moves with it; a file only names an option the product does not have yet.',\n forced: { mode: 'fillBlanks' as const, blank: 'leave' as const },\n })),\n]\n\n/*==========================================\n * THE SHOPIFY LAYOUT\n *=========================================*/\n\n/** Shopify's product CSV columns, by the field each one means. */\nexport const SHOPIFY_PRODUCT_COLUMNS: Readonly<Record<string, string>> = {\n [F.handle]: 'Handle',\n [F.title]: 'Title',\n [F.description]: 'Body (HTML)',\n [F.tags]: 'Tags',\n [F.published]: 'Published',\n [F.option1Name]: 'Option1 Name',\n [F.option1Value]: 'Option1 Value',\n [F.option2Name]: 'Option2 Name',\n [F.option2Value]: 'Option2 Value',\n [F.option3Name]: 'Option3 Name',\n [F.option3Value]: 'Option3 Value',\n [F.sku]: 'Variant SKU',\n [F.weightGrams]: 'Variant Grams',\n [F.inventory]: 'Variant Inventory Qty',\n [F.oversellPolicy]: 'Variant Inventory Policy',\n [F.price]: 'Variant Price',\n [F.compareAtPrice]: 'Variant Compare At Price',\n [F.barcode]: 'Variant Barcode',\n [F.image]: 'Image Src',\n [F.seoTitle]: 'SEO Title',\n [F.seoDescription]: 'SEO Description',\n [F.variantImage]: 'Variant Image',\n [F.status]: 'Status',\n}\n\n/** Shopify's export headers, so its file maps column for column. */\nexport const PRODUCT_ALIAS_DICTIONARIES: readonly TransferAliasDictionary[] = [\n {\n source: 'Shopify',\n aliases: Object.fromEntries(\n Object.entries(SHOPIFY_PRODUCT_COLUMNS).map(([fieldId, column]) => [fieldId, [column]]),\n ),\n },\n]\n\n/**\n * The Shopify preset: Shopify's product CSV columns, in Shopify's order and\n * under Shopify's names. Status is left out — Shopify reads it in lowercase\n * and Published says the same thing — and so is the kind, which Shopify's\n * \"Type\" does not mean.\n */\nexport const SHOPIFY_PRODUCT_PRESET: TransferResourcePreset = {\n id: 'shopify',\n label: 'Shopify',\n description: 'Shopify’s product CSV: its columns, its order and its names.',\n fieldIds: [\n F.handle,\n F.title,\n F.description,\n F.tags,\n F.published,\n F.option1Name,\n F.option1Value,\n F.option2Name,\n F.option2Value,\n F.option3Name,\n F.option3Value,\n F.sku,\n F.weightGrams,\n F.inventory,\n F.oversellPolicy,\n F.price,\n F.compareAtPrice,\n F.barcode,\n F.image,\n F.seoTitle,\n F.seoDescription,\n F.variantImage,\n ],\n headers: Object.fromEntries(\n Object.entries(SHOPIFY_PRODUCT_COLUMNS).filter(([fieldId]) => fieldId !== F.status),\n ),\n}\n\n/*==========================================\n * A PRODUCT AS RECORDS\n *=========================================*/\n\n/** Where a product's record keeps its variants, apart from its fields. */\nexport const PRODUCT_VARIANT_ORDER = '$variants'\n\n/** The record key one variant's values live under. */\nexport function productVariantKey(variantId: string): string {\n return `$variant:${variantId}`\n}\n\n/** A variant's values, as a file names them. */\nexport type VariantRecord = Record<string, unknown> & {\n /** Its stock is kept per location. */\n $byLocation?: boolean\n}\n\n/** A product as a stored document, the way every reader lifts one. */\ntype StoredProduct = Partial<HostProduct> & {\n createdAt?: unknown\n updatedAt?: unknown\n createdAtMs?: number\n updatedAtMs?: number\n}\n\nconst isoOf = (value: unknown, ms?: number): string | null => {\n const time =\n typeof ms === 'number'\n ? ms\n : value && typeof (value as { toMillis?: () => number }).toMillis === 'function'\n ? (value as { toMillis: () => number }).toMillis()\n : typeof value === 'number'\n ? value\n : null\n return time === null || !Number.isFinite(time) ? null : new Date(time).toISOString()\n}\n\n/** One variant as a file names it. */\nexport function variantRecord(variant: ProductVariant, options: readonly ProductOption[]): VariantRecord {\n const values: VariantRecord = {\n [F.sku]: variant.sku ?? null,\n [F.barcode]: variant.barcode ?? null,\n [F.price]: Number.isFinite(Number(variant.priceUsd)) ? Number(variant.priceUsd) : null,\n [F.compareAtPrice]: variant.compareAtPriceUsd ?? null,\n [F.inventory]: typeof variant.inventory === 'number' ? variant.inventory : null,\n [F.weightGrams]: variant.weightGrams ?? null,\n [F.variantImage]: variant.imageUrl ?? null,\n }\n OPTION_VALUE_FIELDS.forEach((fieldId, axis) => {\n const name = options[axis]?.name\n values[fieldId] = name ? (variant.options?.[name] ?? null) : null\n })\n if (variant.inventoryByLocation && Object.keys(variant.inventoryByLocation).length) values.$byLocation = true\n // Only when set: an undo snapshot written before this column compares equal.\n const checkIn = checkInCellOf(variant.checkIn)\n if (checkIn) values[F.variantCheckIn] = checkIn\n return values\n}\n\n/**\n * A product as one record: its fields by field id, and its variants under\n * {@link productVariantKey} in the order {@link PRODUCT_VARIANT_ORDER} lists\n * them. The lookup answers this shape, so the dry run's before → after and\n * undo's \"edited since\" both read a product the way a file names it.\n */\nexport function productRecord(\n stored: StoredProduct,\n categoryNames: ReadonlyMap<string, string> = new Map(),\n): Record<string, unknown> {\n const product = stored as HostProduct\n const options = product.options ?? []\n const variants = Array.isArray(product.variants) ? product.variants : []\n const [low] = variants.length ? productPriceRange(product) : [null]\n const total = variants.length ? productInventory(product) : null\n const record: Record<string, unknown> = {\n [F.handle]: product.slug ?? null,\n [F.title]: product.name ?? null,\n [F.description]: product.description ?? null,\n [F.kind]: fixedListLabel(PRODUCT_KIND_PICKLIST, product.type ?? 'physical'),\n [F.status]: fixedListLabel(PRODUCT_STATUS_PICKLIST, product.status ?? 'active'),\n [F.published]: (product.status ?? 'active') === 'active',\n [F.tags]: product.tags?.length ? product.tags.join(', ') : null,\n [F.categories]: (product.categoryIds ?? []).map((id) => categoryNames.get(id) ?? id),\n [F.image]: product.mediaUrls?.length ? [...product.mediaUrls] : product.imageUrl ? [product.imageUrl] : [],\n [F.seoTitle]: product.seo?.title ?? null,\n [F.seoDescription]: product.seo?.description ?? null,\n [F.taxExempt]: product.taxExempt ?? null,\n [F.oversellPolicy]: fixedListLabel(PRODUCT_OVERSELL_PICKLIST, product.oversellPolicy ?? 'deny'),\n [F.lowStockThreshold]: product.lowStockThreshold ?? null,\n [F.posQuickKey]: product.posQuickKey ?? null,\n [F.checkIn]: checkInCellOf(product.checkIn),\n [F.modifierGroups]: addOnCellOf(product.modifierGroups, variants),\n [F.priceFrom]: low,\n [F.totalInventory]: total,\n [F.soldOut]: total !== null && total <= 0 && product.oversellPolicy !== 'backorder',\n [F.variantCount]: variants.length,\n [F.createdAt]: isoOf(stored.createdAt, stored.createdAtMs),\n [F.updatedAt]: isoOf(stored.updatedAt, stored.updatedAtMs),\n [PRODUCT_VARIANT_ORDER]: variants.map((variant) => variant.id),\n }\n OPTION_NAME_FIELDS.forEach((fieldId, axis) => {\n record[fieldId] = options[axis]?.name ?? null\n })\n for (const variant of variants) record[productVariantKey(variant.id)] = variantRecord(variant, options)\n return record\n}\n\n/**\n * A product's rows in a file, holding only `fieldIds`: one per variant (and\n * per image past the variants), the product's own fields on the first, the\n * handle and the ID on every one.\n */\nexport function productExportRows(\n id: string,\n stored: StoredProduct,\n fieldIds: readonly string[],\n categoryNames: ReadonlyMap<string, string> = new Map(),\n): Array<Record<string, unknown>> {\n const record = productRecord(stored, categoryNames)\n const variantIds = record[PRODUCT_VARIANT_ORDER] as string[]\n const images = record[F.image] as string[]\n const count = Math.max(1, variantIds.length, images.length)\n const variantFields = new Set(VARIANT_LEVEL_FIELDS)\n const rows: Array<Record<string, unknown>> = []\n for (let index = 0; index < count; index += 1) {\n const variantId = variantIds[index]\n const variant = variantId ? (record[productVariantKey(variantId)] as VariantRecord) : null\n const row: Record<string, unknown> = {}\n for (const fieldId of fieldIds) {\n if (fieldId === 'id') row[fieldId] = id\n else if (fieldId === F.handle) row[fieldId] = record[F.handle]\n else if (fieldId === F.image) row[fieldId] = images[index] ?? null\n else if (variantFields.has(fieldId)) row[fieldId] = variant ? (variant[fieldId] ?? null) : null\n else row[fieldId] = index === 0 ? (record[fieldId] ?? null) : null\n }\n rows.push(row)\n }\n return rows\n}\n\n/** How many rows {@link productExportRows} writes for a product. */\nexport function productExportRowCount(stored: Pick<StoredProduct, 'variants' | 'mediaUrls' | 'imageUrl'>): number {\n const variants = Array.isArray(stored.variants) ? stored.variants.length : 0\n const images = stored.mediaUrls?.length ?? (stored.imageUrl ? 1 : 0)\n return Math.max(1, variants, images)\n}\n\n/*==========================================\n * THE PLAN\n *=========================================*/\n\n/** What a planned product row carries for the apply. */\nexport interface ProductRowPlan {\n /** The product the row writes: its id, or the id a new one is created under. */\n productId: string\n /** The file row carrying the product's own fields. */\n leader: number\n /**\n * `create` makes the product (its leader); `part` is a row folded into a\n * product the leader creates; `update` writes this row's changes into an\n * existing product.\n */\n role: 'create' | 'part' | 'update'\n /** The variant this row writes, when it writes one. */\n variant?: { id: string; isNew: boolean }\n /** On a new product's leader: the whole document's parts. */\n create?: {\n slug: string\n values: Record<string, unknown>\n variants: Array<{ id: string; values: Record<string, unknown> }>\n }\n /** Why the product this row belongs to cannot be stored, when it cannot. */\n problem?: string\n /**\n * On a first row whose add-ons are priced by variant: the variants by name\n * once every row is written, since a later row may be what adds one.\n */\n addOnVariants?: Record<string, string[]>\n}\n\n/** A planned row with what the apply needs. */\nexport type ProductPlannedRow = PlannedTransferRow & { commerce?: ProductRowPlan }\n\nexport interface ProductPlanContext {\n /** A new product's id. */\n newProductId(): string\n /** A new variant's id, unique within its product. */\n newVariantId(): string\n /** Whether a slug is held by a product already (deleted ones included). */\n slugTaken?(slug: string): boolean\n /** How many products the site may still create; unbounded when absent. */\n maxCreates?: number\n}\n\nconst text = (value: unknown): string => (value === null || value === undefined ? '' : String(value).trim())\n\n/** A money cell as US dollars: the derived amount, or the number as typed. */\nfunction dollars(value: unknown): { ok: true; value: number | null } | { ok: false; message: string } {\n if (value === null || value === undefined || value === '') return { ok: true, value: null }\n if (typeof value === 'number') return { ok: true, value }\n if (typeof value === 'object' && 'amountMinor' in (value as object)) {\n const amount = value as { amountMinor: number; currency: string }\n if (String(amount.currency).toUpperCase() !== 'USD') {\n return { ok: false, message: `Prices are in US dollars; ${amount.currency} is not converted.` }\n }\n return { ok: true, value: Math.round(Number(amount.amountMinor)) / 100 }\n }\n const number = Number(value)\n return Number.isFinite(number) ? { ok: true, value: number } : { ok: false, message: `\"${String(value)}\" is not a price.` }\n}\n\n/** The tags a cell names, in their own case. */\nexport function productTagList(value: unknown): string[] {\n const list = Array.isArray(value) ? value : String(value ?? '').split(',')\n const seen = new Set<string>()\n const out: string[] = []\n for (const raw of list) {\n const tag = String(raw).trim()\n if (!tag || seen.has(tag)) continue\n seen.add(tag)\n out.push(tag)\n }\n return out\n}\n\n/**\n * A row's values the way the plan compares them with a record: prices in\n * dollars, a fixed list's label checked, tags as one comma list, Published\n * read as the status. What cannot be read is dropped as a located problem.\n */\nfunction normalizeRow(row: TransferPlanRow): TransferPlanRow {\n const values: Record<string, unknown> = { ...row.values }\n const problems = [...(row.problems ?? [])]\n const drop = (fieldId: string, code: DeriveProblemCode, message: string) => {\n problems.push({ fieldId, raw: text(values[fieldId]), code, message })\n delete values[fieldId]\n }\n for (const fieldId of [F.price, F.compareAtPrice]) {\n if (!(fieldId in values)) continue\n const read = dollars(values[fieldId])\n if ('message' in read) drop(fieldId, 'invalidCurrency', read.message)\n else values[fieldId] = read.value\n }\n for (const [fieldId, picklistId] of [\n [F.kind, PRODUCT_KIND_PICKLIST],\n [F.status, PRODUCT_STATUS_PICKLIST],\n [F.oversellPolicy, PRODUCT_OVERSELL_PICKLIST],\n ] as const) {\n if (isBlankTransferValue(values[fieldId])) continue\n const id = fixedListId(picklistId, values[fieldId])\n if (id) values[fieldId] = fixedListLabel(picklistId, id)\n else drop(fieldId, 'invalidJson', `\"${text(values[fieldId])}\" is not one of ${PRODUCT_FIXED_PICKLISTS[picklistId]?.standardValues.map((entry) => entry.label).join(', ')}.`)\n }\n if (F.tags in values && !isBlankTransferValue(values[F.tags])) {\n values[F.tags] = productTagList(values[F.tags]).join(', ')\n }\n if (F.handle in values && !isBlankTransferValue(values[F.handle])) {\n const slug = commerceSlug(text(values[F.handle]))\n if (slug) values[F.handle] = slug\n else drop(F.handle, 'invalidUrl', `\"${text(values[F.handle])}\" has no letters or numbers to make a handle from.`)\n }\n for (const fieldId of [F.checkIn, F.variantCheckIn]) {\n if (isBlankTransferValue(values[fieldId])) continue\n const read = readCheckInCell(values[fieldId])\n if ('message' in read) drop(fieldId, 'invalidJson', read.message)\n else values[fieldId] = writeCheckInCell(read.value)\n }\n if (!isBlankTransferValue(values[F.modifierGroups])) {\n const read = readAddOnCell(values[F.modifierGroups])\n if ('message' in read) drop(F.modifierGroups, 'invalidJson', read.message)\n else values[F.modifierGroups] = writeAddOnCell(read.value)\n }\n if (F.published in values) {\n if (isBlankTransferValue(values[F.status]) && typeof values[F.published] === 'boolean') {\n values[F.status] = values[F.published] ? STATUS_LABELS.active : STATUS_LABELS.draft\n }\n delete values[F.published]\n }\n return { ...row, values, ...(problems.length ? { problems } : {}) }\n}\n\nconst pick = (values: Readonly<Record<string, unknown>>, fieldIds: readonly string[]): Record<string, unknown> => {\n const out: Record<string, unknown> = {}\n for (const fieldId of fieldIds) if (fieldId in values) out[fieldId] = values[fieldId]\n return out\n}\n\nconst hasAny = (values: Readonly<Record<string, unknown>>, fieldIds: readonly string[]): boolean =>\n fieldIds.some((fieldId) => !isBlankTransferValue(values[fieldId]))\n\n/** Which product a row belongs to in the file. */\nfunction groupKey(row: TransferPlanRow, position: number): string {\n const handle = text(row.values[F.handle])\n if (handle) return `h:${handle}`\n const id = text(row.values['id'])\n if (id) return `i:${id}`\n return `r:${position}`\n}\n\ninterface Group {\n key: string\n positions: number[]\n}\n\n/** Warnings, tallied the way the core tallies them, for what this plan adds and merges. */\nclass Tally {\n private readonly byClass = new Map<TransferWarningClass, TransferWarning & { rowSet: Set<number>; fieldSet: Set<string> }>()\n\n merge(warnings: readonly TransferWarning[]): void {\n for (const warning of warnings) {\n const entry = this.entry(warning.class, warning.requiresAcknowledgement)\n entry.count += warning.count\n for (const sample of warning.samples) {\n entry.rowSet.add(sample.row)\n if (entry.samples.length < 5) entry.samples.push(sample)\n }\n for (const fieldId of warning.fieldIds) entry.fieldSet.add(fieldId)\n entry.requiresAcknowledgement ||= warning.requiresAcknowledgement\n }\n }\n\n add(warningClass: TransferWarningClass, sample: TransferWarningSample): void {\n const entry = this.entry(warningClass, true)\n entry.count += 1\n entry.rowSet.add(sample.row)\n if (sample.fieldId) entry.fieldSet.add(sample.fieldId)\n if (entry.samples.length < 5) entry.samples.push(sample)\n }\n\n private entry(warningClass: TransferWarningClass, acknowledge: boolean) {\n let entry = this.byClass.get(warningClass)\n if (!entry) {\n entry = {\n class: warningClass,\n count: 0,\n rows: 0,\n fieldIds: [],\n samples: [],\n requiresAcknowledgement: acknowledge,\n rowSet: new Set(),\n fieldSet: new Set(),\n }\n this.byClass.set(warningClass, entry)\n }\n return entry\n }\n\n list(order: readonly TransferWarningClass[]): TransferWarning[] {\n return [...this.byClass.values()]\n .sort((a, b) => order.indexOf(a.class) - order.indexOf(b.class))\n .map(({ rowSet, fieldSet, ...warning }) => ({\n ...warning,\n // In file order: the product plan reports each product's first row\n // before the variant plans report the rest.\n samples: [...warning.samples].sort((a, b) => a.row - b.row),\n rows: Math.max(rowSet.size, warning.rows),\n fieldIds: [...fieldSet],\n }))\n }\n}\n\n/** The order the core lists warning classes in. */\nconst WARNING_ORDER: readonly TransferWarningClass[] = TRANSFER_WARNING_CLASSES\n\n/** A variant line's identity in the product it targets. */\nfunction optionKey(values: Readonly<Record<string, unknown>>, names: readonly (string | null)[]): string | null {\n const parts: string[] = []\n OPTION_VALUE_FIELDS.forEach((fieldId, axis) => {\n const value = text(values[fieldId])\n if (value && names[axis]) parts.push(`${names[axis]}=${value.toLowerCase()}`)\n })\n return parts.length ? parts.join('|') : null\n}\n\n/** The value a field's diff leaves, or what the record held. */\nfunction after(diff: readonly TransferFieldChange[], before: Readonly<Record<string, unknown>>, fieldId: string): unknown {\n const change = diff.find((entry) => entry.fieldId === fieldId)\n return change ? change.after : before[fieldId]\n}\n\n/**\n * A product's document from its record values (see {@link productRecord}),\n * for checking what a plan would store with the model's own rules.\n */\nexport function productFromRecord(\n values: Readonly<Record<string, unknown>>,\n variants: ReadonlyArray<{ id: string; values: Readonly<Record<string, unknown>> }>,\n): HostProduct {\n const names = OPTION_NAME_FIELDS.map((fieldId) => text(values[fieldId]))\n const options: ProductOption[] = []\n names.forEach((name, axis) => {\n if (!name) return\n const seen: string[] = []\n for (const variant of variants) {\n const value = text(variant.values[OPTION_VALUE_FIELDS[axis] as string])\n if (value && !seen.includes(value)) seen.push(value)\n }\n options.push({ name, values: seen })\n })\n const checkIn = isBlankTransferValue(values[F.checkIn]) ? undefined : checkInFromCell(values[F.checkIn])\n return {\n name: text(values[F.title]),\n slug: text(values[F.handle]),\n type: (fixedListId(PRODUCT_KIND_PICKLIST, values[F.kind]) ?? 'physical') as ProductType,\n status: (fixedListId(PRODUCT_STATUS_PICKLIST, values[F.status]) ?? 'active') as ProductStatus,\n ...(options.length ? { options } : {}),\n ...(checkIn ? { checkIn } : {}),\n variants: variants.map((variant) => variantFromRecord(variant.id, variant.values, names)),\n }\n}\n\n/** One variant of a document from its record values. */\nexport function variantFromRecord(\n id: string,\n values: Readonly<Record<string, unknown>>,\n optionNames: readonly (string | null | undefined)[],\n): ProductVariant {\n const options: Record<string, string> = {}\n OPTION_VALUE_FIELDS.forEach((fieldId, axis) => {\n const name = text(optionNames[axis])\n const value = text(values[fieldId])\n if (name && value) options[name] = value\n })\n const number = (fieldId: string): number | undefined => {\n const raw = values[fieldId]\n return raw === null || raw === undefined || raw === '' || !Number.isFinite(Number(raw)) ? undefined : Number(raw)\n }\n const inventory = number(F.inventory)\n const checkIn = isBlankTransferValue(values[F.variantCheckIn]) ? undefined : checkInFromCell(values[F.variantCheckIn])\n return {\n id,\n ...(Object.keys(options).length ? { options } : {}),\n priceUsd: number(F.price) as number,\n ...(text(values[F.sku]) ? { sku: text(values[F.sku]) } : {}),\n ...(text(values[F.barcode]) ? { barcode: text(values[F.barcode]) } : {}),\n ...(number(F.compareAtPrice) !== undefined ? { compareAtPriceUsd: number(F.compareAtPrice) } : {}),\n ...(number(F.weightGrams) !== undefined ? { weightGrams: number(F.weightGrams) } : {}),\n ...(text(values[F.variantImage]) ? { imageUrl: text(values[F.variantImage]) } : {}),\n inventory: inventory === undefined ? null : Math.max(0, Math.round(inventory)),\n ...(checkIn ? { checkIn } : {}),\n }\n}\n\n/** The fields a new product is refused without. */\nconst PRODUCT_PLAN_FIELDS = (fields: readonly TransferField[]) =>\n fields\n .filter((field) => !VARIANT_LEVEL_FIELDS.includes(field.id))\n .map((field) => (field.id === F.title ? { ...field, required: true } : field))\nconst VARIANT_PLAN_FIELDS = (fields: readonly TransferField[]) =>\n fields\n .filter((field) => VARIANT_LEVEL_FIELDS.includes(field.id))\n .map((field) => (field.id === F.price ? { ...field, required: true } : field))\n\n/**\n * The products resource's plan: the core's plan per product and per variant,\n * folded back into one verdict per file row (see the block header).\n */\nexport function planProductTransfer(input: BuildTransferPlanInput, context: ProductPlanContext): TransferPlan {\n const rows = input.rows.map(normalizeRow)\n const tally = new Tally()\n\n // The groups, in the order their first rows appear.\n const groups = new Map<string, Group>()\n rows.forEach((row, position) => {\n const key = groupKey(row, position)\n const group = groups.get(key) ?? { key, positions: [] }\n group.positions.push(position)\n groups.set(key, group)\n })\n const ordered = [...groups.values()]\n\n // The product half: each group's first row, with the group's images and option names.\n const leaders = ordered.map((group): TransferPlanRow => {\n const first = rows[group.positions[0] as number] as TransferPlanRow\n const values = pick(first.values, [...PRODUCT_LEVEL_FIELDS, 'id'])\n const images: string[] = []\n for (const position of group.positions) {\n const url = text(rows[position]?.values[F.image])\n if (url && !images.includes(url)) images.push(url)\n }\n if (images.length) values[F.image] = images\n else delete values[F.image]\n OPTION_NAME_FIELDS.forEach((fieldId) => {\n if (!isBlankTransferValue(values[fieldId])) return\n for (const position of group.positions) {\n const name = text(rows[position]?.values[fieldId])\n if (name) {\n values[fieldId] = name\n break\n }\n }\n })\n for (const fieldId of REGISTER_PRODUCT_FIELDS) {\n for (const position of group.positions.slice(1)) {\n const row = rows[position] as TransferPlanRow\n const cell = row.values[fieldId]\n if (isBlankTransferValue(cell)) continue\n if (isBlankTransferValue(values[fieldId])) values[fieldId] = cell\n else if (cell !== values[fieldId]) {\n tally.add('droppedCell', {\n row: row.index,\n fieldId,\n value: text(cell),\n detail: 'A product holds one of these, and an earlier row of this product already gives it.',\n })\n }\n }\n }\n return { ...first, values }\n })\n const leaderMatches = ordered.map(\n (group) => input.matches[group.positions[0] as number] ?? ({ kind: 'new' } as RowMatchOutcome),\n )\n const productPlan = buildTransferPlan({\n fields: PRODUCT_PLAN_FIELDS(input.fields),\n rows: leaders,\n matches: leaderMatches,\n existing: input.existing,\n policy: input.policy,\n limits: context.maxCreates === undefined ? {} : { maxCreates: context.maxCreates },\n })\n tally.merge(productPlan.warnings)\n\n const variantFields = VARIANT_PLAN_FIELDS(input.fields)\n const out: ProductPlannedRow[] = new Array(rows.length)\n // Slugs this plan gives new products, so two new ones never share one.\n const handedOut = new Set<string>()\n\n ordered.forEach((group, at) => {\n const planned = productPlan.rows[at] as PlannedTransferRow\n const leaderPosition = group.positions[0] as number\n const leaderIndex = (rows[leaderPosition] as TransferPlanRow).index\n const original = (position: number): RowMatchOutcome =>\n input.matches[position] ?? ({ kind: 'new' } as RowMatchOutcome)\n\n // A product that writes nothing: every row of it follows its first.\n if (planned.verdict === 'skip' || planned.verdict === 'fail') {\n for (const position of group.positions) {\n const row = rows[position] as TransferPlanRow\n out[position] =\n position === leaderPosition\n ? planned\n : {\n index: row.index,\n verdict: planned.verdict,\n recordId: null,\n ...(planned.reason ? { reason: planned.reason } : {}),\n diff: [],\n heldBack: [],\n warnings: [],\n match: original(position),\n }\n }\n return\n }\n\n const creating = planned.verdict === 'create'\n const productId = creating ? context.newProductId() : (planned.recordId as string)\n const before = creating ? {} : (input.existing.get(productId) ?? {})\n const optionNames = OPTION_NAME_FIELDS.map((fieldId) => text(after(planned.diff, before, fieldId)) || null)\n\n // The variants the product has, and which one each line names.\n const existingVariants = creating\n ? []\n : ((before[PRODUCT_VARIANT_ORDER] as string[] | undefined) ?? []).map((id) => ({\n id,\n values: (before[productVariantKey(id)] ?? {}) as VariantRecord,\n }))\n const lines = group.positions.filter((position) => {\n const values = (rows[position] as TransferPlanRow).values\n return hasAny(values, VARIANT_LEVEL_FIELDS)\n })\n const claimed = new Map<string, number>()\n const lineTargets = new Map<number, { id: string; isNew: boolean; via?: { fieldId: string; value: string } }>()\n const lineMatches: RowMatchOutcome[] = []\n const lineRows: TransferPlanRow[] = []\n const linePositions: number[] = []\n const existingVariantValues = new Map<string, Readonly<Record<string, unknown>>>()\n const duplicates = new Map<number, number>()\n for (const position of lines) {\n const row = rows[position] as TransferPlanRow\n const sku = text(row.values[F.sku]).toLowerCase()\n const key = optionKey(row.values, optionNames)\n let target = sku ? existingVariants.find((variant) => text(variant.values[F.sku]).toLowerCase() === sku) : undefined\n let via: { fieldId: string; value: string } | undefined = sku ? { fieldId: F.sku, value: sku } : undefined\n if (!target && key) {\n target = existingVariants.find((variant) => optionKey(variant.values, optionNames) === key)\n via = { fieldId: F.option1Value, value: key }\n }\n if (!target && !key && !sku && existingVariants.length === 1 && lines.length === 1) {\n target = existingVariants[0]\n via = { fieldId: 'id', value: target?.id ?? '' }\n }\n // Two lines naming one variant, or one new variant twice: the first one counts.\n const identity = target ? `v:${target.id}` : sku ? `s:${sku}` : key ? `o:${key}` : null\n const earlier = identity ? claimed.get(identity) : undefined\n if (earlier !== undefined) {\n duplicates.set(position, earlier)\n continue\n }\n if (identity) claimed.set(identity, position)\n const id = target ? target.id : context.newVariantId()\n lineTargets.set(position, { id, isNew: !target, ...(via ? { via } : {}) })\n // The product's first row went into the product plan whole, which\n // reports every read note it carries (a reformatted price, a cell it\n // could not read). Its line carries none, or the Review step lists each\n // of them twice, once from each plan (\"5 times in 3 rows\" for 3 price\n // cells, AGL-4047). The product plan always runs, so nothing is lost.\n const noted = position === leaderPosition ? { ...row, derivations: [], problems: [] } : row\n lineRows.push({ ...noted, values: pick(row.values, VARIANT_LEVEL_FIELDS) })\n linePositions.push(position)\n if (target) {\n existingVariantValues.set(`${productId}::${target.id}`, target.values)\n lineMatches.push({ kind: 'matched', recordId: `${productId}::${target.id}`, via: via as { fieldId: string; value: string } })\n } else {\n lineMatches.push({ kind: 'new' })\n }\n }\n // A cell a row could not have read, on a row no variant plan reports it for.\n for (const position of group.positions) {\n if (position === leaderPosition || linePositions.includes(position)) continue\n const row = rows[position] as TransferPlanRow\n for (const problem of row.problems ?? []) {\n if (!REGISTER_PRODUCT_FIELDS.includes(problem.fieldId)) continue\n tally.add('droppedCell', { row: row.index, fieldId: problem.fieldId, value: problem.raw, detail: problem.message })\n }\n }\n const variantPlan = buildTransferPlan({\n fields: variantFields,\n rows: lineRows,\n matches: lineMatches,\n existing: existingVariantValues,\n policy: input.policy,\n })\n tally.merge(variantPlan.warnings)\n const lineVerdicts = new Map<number, PlannedTransferRow>()\n lineRows.forEach((row, at) => {\n const position = linePositions[at] as number\n const verdict = variantPlan.rows[at] as PlannedTransferRow\n const target = lineTargets.get(position)\n // Stock kept per location moves per location, never as one total.\n if (target && !target.isNew && verdict.verdict === 'update') {\n const values = existingVariantValues.get(`${productId}::${target.id}`) as VariantRecord | undefined\n if (values?.$byLocation && verdict.diff.some((change) => change.fieldId === F.inventory)) {\n verdict.diff = verdict.diff.filter((change) => change.fieldId !== F.inventory)\n verdict.heldBack = [...verdict.heldBack, F.inventory]\n verdict.warnings = [...new Set([...verdict.warnings, 'lockedRule' as const])]\n tally.add('lockedRule', {\n row: row.index,\n fieldId: F.inventory,\n value: text(row.values[F.inventory]),\n detail: 'This variant’s stock is kept by location; change it per location on the products page.',\n })\n if (!verdict.diff.length) verdict.verdict = 'unchanged'\n }\n }\n lineVerdicts.set(position, verdict)\n })\n\n // A new product needs a variant.\n const createdLines = [...lineVerdicts.entries()].filter(([, verdict]) => verdict.verdict === 'create')\n if (creating && !createdLines.length) {\n for (const position of group.positions) {\n const row = rows[position] as TransferPlanRow\n out[position] = {\n index: row.index,\n verdict: 'fail',\n recordId: null,\n reason: 'missingRequired',\n missing: [F.price],\n diff: position === leaderPosition ? planned.diff : [],\n heldBack: [],\n warnings: position === leaderPosition ? planned.warnings : [],\n match: original(position),\n }\n }\n return\n }\n\n // The handle a new product is stored under: the file's, or one made from its title.\n let slug = ''\n let problem: string | undefined\n if (creating) {\n const base = text(after(planned.diff, before, F.handle)) || commerceSlug(text(after(planned.diff, before, F.title))) || 'product'\n const taken = (candidate: string) => handedOut.has(candidate) || Boolean(context.slugTaken?.(candidate))\n slug = base\n for (let suffix = 2; taken(slug); suffix += 1) {\n const tail = `-${suffix}`\n slug = `${base.slice(0, COMMERCE_SLUG_MAX_LENGTH - tail.length)}${tail}`\n }\n handedOut.add(slug)\n if (slug !== base) {\n tally.add('lockedRule', {\n row: leaderIndex,\n fieldId: F.handle,\n value: base,\n detail: `Another product holds /products/${base}; this one is created at /products/${slug}.`,\n })\n planned.warnings = [...new Set([...planned.warnings, 'lockedRule' as const])]\n planned.heldBack = [...planned.heldBack, F.handle]\n }\n }\n\n // What the product would hold once every row of it is written, by the model's own rules.\n const productValues: Record<string, unknown> = { ...before }\n for (const change of planned.diff) productValues[change.fieldId] = change.after\n if (creating) productValues[F.handle] = slug\n const finalVariants = existingVariants.map((variant) => ({ id: variant.id, values: { ...variant.values } as Record<string, unknown> }))\n for (const [position, verdict] of lineVerdicts) {\n if (verdict.verdict !== 'create' && verdict.verdict !== 'update') continue\n const target = lineTargets.get(position) as { id: string; isNew: boolean }\n let entry = finalVariants.find((variant) => variant.id === target.id)\n if (!entry) {\n entry = { id: target.id, values: {} }\n finalVariants.push(entry)\n }\n for (const change of verdict.diff) entry.values[change.fieldId] = change.after\n }\n let addOnVariants: Record<string, string[]> | undefined\n if (finalVariants.length > COMMERCE_MAX_VARIANTS) {\n problem = `A product holds at most ${COMMERCE_MAX_VARIANTS} variants; this file gives it ${finalVariants.length}.`\n } else {\n const candidate = productFromRecord(productValues, finalVariants)\n let check = validateProductForSave(candidate)\n const addOns = planned.diff.find((change) => change.fieldId === F.modifierGroups)?.after\n if (!check && !isBlankTransferValue(addOns)) {\n const variantIds = addOnVariantIds(candidate.variants)\n const resolved = modifierGroupsFromAddOnCell(addOns, [], variantIds)\n check =\n resolved.problem ??\n validateProductForSave({ ...candidate, modifierGroups: resolved.groups ?? [] }) ??\n variantMatrixProblem(candidate.options)\n if (resolved.groups?.some((entry) => entry.options.some((option) => option.priceCentsByVariant))) {\n addOnVariants = variantIds\n }\n }\n if (check) problem = check\n }\n\n const create = creating\n ? {\n slug,\n values: Object.fromEntries(planned.diff.map((change) => [change.fieldId, change.after])),\n variants: createdLines.map(([position, verdict]) => ({\n id: (lineTargets.get(position) as { id: string }).id,\n values: Object.fromEntries(verdict.diff.map((change) => [change.fieldId, change.after])),\n })),\n }\n : undefined\n\n for (const position of group.positions) {\n const row = rows[position] as TransferPlanRow\n const isLeader = position === leaderPosition\n const line = lineVerdicts.get(position)\n const target = lineTargets.get(position)\n const duplicateOf = duplicates.get(position)\n const base: Pick<PlannedTransferRow, 'index' | 'match'> = { index: row.index, match: original(position) }\n if (duplicateOf !== undefined) {\n const firstRow = (rows[duplicateOf] as TransferPlanRow).index\n tally.add('duplicateInFile', {\n row: row.index,\n fieldId: F.sku,\n value: text(row.values[F.sku]) || text(row.values[F.option1Value]),\n detail: `The same variant as row ${firstRow + 1}`,\n })\n out[position] = {\n ...base,\n verdict: 'skip',\n recordId: creating ? null : productId,\n reason: 'duplicateInFile',\n diff: [],\n heldBack: [],\n warnings: ['duplicateInFile'],\n }\n continue\n }\n const productDiff = isLeader ? planned.diff : []\n const lineDiff = line && (line.verdict === 'create' || line.verdict === 'update') ? line.diff : []\n const writes = productDiff.length + lineDiff.length > 0\n const lineFailed = line && (line.verdict === 'fail' || line.verdict === 'skip')\n if (lineFailed && isLeader && (productDiff.length || creating)) {\n // The product's own changes still land; the variant on this row does not, and says so.\n tally.add('droppedCell', {\n row: row.index,\n ...(line.missing?.[0] ? { fieldId: line.missing[0] } : {}),\n detail: `The variant on this row is not written (${line.reason ?? line.verdict}).`,\n })\n }\n const warnings = [...new Set([...(isLeader ? planned.warnings : []), ...(line?.warnings ?? [])])]\n const heldBack = [...(isLeader ? planned.heldBack : []), ...(line?.heldBack ?? [])]\n const plan: ProductRowPlan = {\n productId,\n leader: leaderIndex,\n role: creating ? (isLeader ? 'create' : 'part') : 'update',\n ...(target && lineDiff.length ? { variant: { id: target.id, isNew: target.isNew } } : {}),\n ...(isLeader && create ? { create } : {}),\n ...(problem ? { problem } : {}),\n ...(isLeader && addOnVariants ? { addOnVariants } : {}),\n }\n if (lineFailed && (!isLeader || !(productDiff.length || creating))) {\n out[position] = {\n ...base,\n verdict: line.verdict,\n recordId: creating ? null : productId,\n ...(line.reason ? { reason: line.reason } : {}),\n ...(line.missing ? { missing: line.missing } : {}),\n diff: [],\n heldBack,\n warnings,\n }\n continue\n }\n const verdict: PlannedTransferRow['verdict'] = creating\n ? isLeader || writes\n ? 'create'\n : 'unchanged'\n : writes\n ? 'update'\n : 'unchanged'\n out[position] = {\n ...base,\n verdict,\n recordId: creating ? null : productId,\n diff: [...productDiff, ...lineDiff],\n heldBack,\n warnings,\n ...(verdict === 'create' || verdict === 'update' ? { commerce: plan } : problem ? { commerce: plan } : {}),\n } as ProductPlannedRow\n }\n })\n\n const summary = { create: 0, update: 0, unchanged: 0, skip: 0, fail: 0, total: out.length }\n for (const row of out) summary[row.verdict] += 1\n const warnings = tally.list(WARNING_ORDER)\n return {\n rows: out,\n summary,\n warnings,\n acknowledgementsRequired: warnings.filter((entry) => entry.requiresAcknowledgement).map((entry) => entry.class),\n }\n}\n\n/** The handles a plan may create products under, for the server to ask which are taken. */\nexport function productPlanHandles(rows: readonly TransferPlanRow[]): string[] {\n const out = new Set<string>()\n for (const row of rows) {\n const handle = commerceSlug(text(row.values[F.handle])) || commerceSlug(text(row.values[F.title]))\n if (handle) out.add(handle)\n }\n return [...out]\n}\n\n/*==========================================\n * WHAT A PLANNED ROW WRITES\n *=========================================*/\n\n/** Category names → ids, for the categories a row names. */\nexport type CategoryIdsOf = (names: readonly string[]) => string[]\n\n/** The product fields a row's changes set, as the document stores them. */\nfunction productFieldPatch(\n changes: Readonly<Record<string, unknown>>,\n categoryIdsOf: CategoryIdsOf,\n): Partial<HostProduct> & { seo?: HostProduct['seo'] } {\n const patch: Partial<HostProduct> = {}\n const has = (fieldId: string) => fieldId in changes\n const value = (fieldId: string) => changes[fieldId]\n if (has(F.title)) patch.name = text(value(F.title))\n if (has(F.description)) patch.description = text(value(F.description)) || undefined\n if (has(F.kind)) patch.type = (fixedListId(PRODUCT_KIND_PICKLIST, value(F.kind)) ?? 'physical') as ProductType\n if (has(F.status)) patch.status = (fixedListId(PRODUCT_STATUS_PICKLIST, value(F.status)) ?? 'active') as ProductStatus\n if (has(F.tags)) patch.tags = productTagList(value(F.tags))\n if (has(F.categories)) {\n const names = Array.isArray(value(F.categories)) ? (value(F.categories) as unknown[]).map(text).filter(Boolean) : []\n patch.categoryIds = categoryIdsOf(names)\n }\n if (has(F.image)) {\n const urls = Array.isArray(value(F.image)) ? (value(F.image) as unknown[]).map(text).filter(Boolean) : []\n patch.mediaUrls = urls\n }\n if (has(F.taxExempt)) patch.taxExempt = value(F.taxExempt) === true\n if (has(F.oversellPolicy)) {\n patch.oversellPolicy = (fixedListId(PRODUCT_OVERSELL_PICKLIST, value(F.oversellPolicy)) ?? 'deny') as 'deny' | 'backorder'\n }\n if (has(F.lowStockThreshold)) {\n const threshold = Number(value(F.lowStockThreshold))\n patch.lowStockThreshold = value(F.lowStockThreshold) === null || !Number.isFinite(threshold) ? undefined : Math.max(0, Math.round(threshold))\n }\n if (has(F.posQuickKey)) patch.posQuickKey = value(F.posQuickKey) === null ? undefined : value(F.posQuickKey) === true\n if (has(F.checkIn)) patch.checkIn = isBlankTransferValue(value(F.checkIn)) ? undefined : checkInFromCell(value(F.checkIn))\n return patch\n}\n\n/** A product with one planned row's changes written into it — the product's own on its first row, and the row's variant. */\nexport function applyProductRow(\n current: HostProduct,\n changes: {\n product?: Readonly<Record<string, unknown>>\n variant?: { id: string; isNew: boolean; values: Readonly<Record<string, unknown>> }\n /** The variants an add-ons cell's prices name, when the plan knows more than the product holds yet. */\n addOnVariants?: Readonly<Record<string, string[]>>\n },\n categoryIdsOf: CategoryIdsOf,\n): HostProduct {\n const next: HostProduct = {\n ...current,\n options: (current.options ?? []).map((option) => ({ ...option, values: [...option.values] })),\n variants: current.variants.map((variant) => ({ ...variant })),\n }\n const product = changes.product ?? {}\n Object.assign(next, productFieldPatch(product, categoryIdsOf))\n if (F.seoTitle in product || F.seoDescription in product) {\n const seo = { ...(current.seo ?? {}) }\n if (F.seoTitle in product) seo.title = text(product[F.seoTitle]) || undefined\n if (F.seoDescription in product) seo.description = text(product[F.seoDescription]) || undefined\n next.seo = Object.fromEntries(Object.entries(seo).filter(([, entry]) => entry !== undefined))\n }\n if (F.modifierGroups in product) {\n const { groups } = isBlankTransferValue(product[F.modifierGroups])\n ? { groups: [] }\n : modifierGroupsFromAddOnCell(\n product[F.modifierGroups],\n current.modifierGroups,\n changes.addOnVariants ?? addOnVariantIds(next.variants),\n )\n if (groups?.length) next.modifierGroups = groups\n else if (groups) delete next.modifierGroups\n }\n // An option the product does not have yet takes its name.\n const options = next.options as ProductOption[]\n OPTION_NAME_FIELDS.forEach((fieldId, axis) => {\n const name = text(product[fieldId])\n if (name && !options[axis]) options[axis] = { name, values: [] }\n })\n const variant = changes.variant\n if (variant) {\n const names = options.map((option) => option?.name ?? null)\n const at = next.variants.findIndex((entry) => entry.id === variant.id)\n const existing = at >= 0 ? (next.variants[at] as ProductVariant) : null\n const record = existing ? variantRecord(existing, options) : {}\n const merged = variantFromRecord(variant.id, { ...record, ...variant.values }, names)\n const written: ProductVariant = existing\n ? {\n ...existing,\n ...merged,\n // What a file never names is kept: stock by location, and anything the variant carries besides.\n ...(existing.inventoryByLocation ? { inventoryByLocation: existing.inventoryByLocation, inventory: existing.inventory } : {}),\n }\n : merged\n for (const key of ['sku', 'barcode', 'compareAtPriceUsd', 'weightGrams', 'imageUrl'] as const) {\n if (merged[key] === undefined) delete written[key]\n }\n // Its check-in moves only when the file names it, and stays exactly as stored when not.\n if (F.variantCheckIn in variant.values ? merged.checkIn === undefined : existing?.checkIn === undefined) delete written.checkIn\n else if (!(F.variantCheckIn in variant.values)) written.checkIn = existing?.checkIn\n if (at >= 0) next.variants[at] = written\n else next.variants.push(written)\n // Each option value the variant holds is one its option offers.\n options.forEach((option, axis) => {\n const value = text(variant.values[OPTION_VALUE_FIELDS[axis] as string])\n if (option && value && !option.values.includes(value)) option.values.push(value)\n })\n }\n next.options = options.filter(Boolean)\n if (!next.options.length) delete next.options\n return next\n}\n\n/** A new product's document from its leader's plan, before the platform's stamps. */\nexport function createProductDocument(\n create: NonNullable<ProductRowPlan['create']>,\n categoryIdsOf: CategoryIdsOf,\n): HostProduct {\n const base = productFromRecord({ ...create.values, [F.handle]: create.slug }, create.variants)\n return applyProductRow(\n { ...base, variants: base.variants },\n { product: Object.fromEntries(Object.entries(create.values).filter(([fieldId]) => !OPTION_NAME_FIELDS.includes(fieldId as never))) },\n categoryIdsOf,\n )\n}\n\n/** The values one planned row changes, split into the product's and its variant's. */\nexport function productRowChanges(row: ProductPlannedRow): {\n product: Record<string, unknown>\n variant?: { id: string; isNew: boolean; values: Record<string, unknown> }\n addOnVariants?: Record<string, string[]>\n} {\n const product: Record<string, unknown> = {}\n const variant: Record<string, unknown> = {}\n for (const change of row.diff) {\n if (VARIANT_LEVEL_FIELDS.includes(change.fieldId)) variant[change.fieldId] = change.after\n else if (PRODUCT_LEVEL_FIELDS.includes(change.fieldId)) product[change.fieldId] = change.after\n }\n const target = row.commerce?.variant\n const addOnVariants = row.commerce?.addOnVariants\n return { product, ...(target ? { variant: { ...target, values: variant } } : {}), ...(addOnVariants ? { addOnVariants } : {}) }\n}\n"],"names":["validateProductForSave","buildTransferPlan","isBlankTransferValue","TRANSFER_SYSTEM_GROUP","TRANSFER_WARNING_CLASSES","COMMERCE_MAX_VARIANTS","COMMERCE_SLUG_MAX_LENGTH","commerceSlug","productInventory","productPriceRange","variantMatrixProblem","addOnCellOf","addOnVariantIds","checkInCellOf","checkInFromCell","modifierGroupsFromAddOnCell","readAddOnCell","readCheckInCell","writeAddOnCell","writeCheckInCell","PRODUCT_FIELD","handle","title","description","kind","status","published","tags","categories","option1Name","option2Name","option3Name","image","seoTitle","seoDescription","taxExempt","oversellPolicy","lowStockThreshold","posQuickKey","checkIn","modifierGroups","option1Value","option2Value","option3Value","sku","barcode","price","compareAtPrice","inventory","weightGrams","variantImage","variantCheckIn","priceFrom","totalInventory","soldOut","variantCount","createdAt","updatedAt","F","PRODUCT_KIND_PICKLIST","PRODUCT_STATUS_PICKLIST","PRODUCT_OVERSELL_PICKLIST","PRODUCT_CATEGORY_PICKLIST","KIND_LABELS","physical","digital","service","STATUS_LABELS","active","draft","archived","OVERSELL_LABELS","deny","backorder","fixedList","labels","defaultValueId","restricted","standardValues","Object","entries","map","id","label","PRODUCT_FIXED_PICKLISTS","fixedListId","picklistId","value","spec","key","String","trim","toLowerCase","found","find","entry","fixedListLabel","PRODUCT_TRANSFER_GROUPS","PRODUCT_LEVEL_FIELDS","REGISTER_PRODUCT_FIELDS","VARIANT_LEVEL_FIELDS","OPTION_NAME_FIELDS","OPTION_VALUE_FIELDS","PRODUCT_STANDARD_FIELDS","group","type","maxLength","aliases","PRODUCT_DERIVED_FIELDS","PRODUCT_SYSTEM_FIELDS","PRODUCT_MATCH_KEYS","fieldId","normalizer","PRODUCT_LOCKED_RULES","reason","forced","mode","blank","SHOPIFY_PRODUCT_COLUMNS","PRODUCT_ALIAS_DICTIONARIES","source","fromEntries","column","SHOPIFY_PRODUCT_PRESET","fieldIds","headers","filter","PRODUCT_VARIANT_ORDER","productVariantKey","variantId","isoOf","ms","time","toMillis","Number","isFinite","Date","toISOString","variantRecord","variant","options","values","priceUsd","compareAtPriceUsd","imageUrl","forEach","axis","name","inventoryByLocation","keys","length","$byLocation","productRecord","stored","categoryNames","Map","product","variants","Array","isArray","low","total","record","slug","join","categoryIds","get","mediaUrls","seo","createdAtMs","updatedAtMs","productExportRows","variantIds","images","count","Math","max","variantFields","Set","rows","index","row","has","push","productExportRowCount","text","undefined","dollars","ok","amount","currency","toUpperCase","message","round","amountMinor","number","productTagList","list","split","seen","out","raw","tag","add","normalizeRow","problems","drop","code","read","pick","hasAny","some","groupKey","position","Tally","merge","warnings","warning","class","requiresAcknowledgement","sample","samples","rowSet","fieldSet","warningClass","acknowledge","byClass","set","order","sort","a","b","indexOf","size","WARNING_ORDER","optionKey","names","parts","after","diff","before","change","productFromRecord","includes","variantFromRecord","optionNames","PRODUCT_PLAN_FIELDS","fields","field","required","VARIANT_PLAN_FIELDS","planProductTransfer","input","context","tally","groups","positions","ordered","leaders","first","url","slice","cell","detail","leaderMatches","matches","productPlan","existing","policy","limits","maxCreates","handedOut","at","planned","leaderPosition","leaderIndex","original","verdict","recordId","heldBack","match","creating","productId","newProductId","existingVariants","lines","claimed","lineTargets","lineMatches","lineRows","linePositions","existingVariantValues","duplicates","target","via","identity","earlier","newVariantId","isNew","noted","derivations","problem","variantPlan","lineVerdicts","createdLines","missing","base","taken","candidate","Boolean","slugTaken","suffix","tail","productValues","finalVariants","addOnVariants","check","addOns","resolved","option","priceCentsByVariant","create","isLeader","line","duplicateOf","firstRow","productDiff","lineDiff","writes","lineFailed","plan","leader","role","commerce","summary","update","unchanged","skip","fail","acknowledgementsRequired","productPlanHandles","productFieldPatch","changes","categoryIdsOf","patch","urls","threshold","applyProductRow","current","next","assign","findIndex","merged","written","createProductDocument","productRowChanges"],"mappings":";;AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,iCAA6B;AACpE,SACEC,iBAAiB,EACjBC,oBAAoB,EACpBC,qBAAqB,EACrBC,wBAAwB,QAiBnB,6BAA4B;AAEnC,SACEC,qBAAqB,EACrBC,wBAAwB,EACxBC,YAAY,EACZC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QAMf,uBAAmB;AAC1B,SACEC,WAAW,EACXC,eAAe,EACfC,aAAa,EACbC,eAAe,EACfC,2BAA2B,EAC3BC,aAAa,EACbC,eAAe,EACfC,cAAc,EACdC,gBAAgB,QACX,8BAA0B;AAEjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CC,GAED;;2CAE2C,GAE3C,4DAA4D,GAC5D,OAAO,MAAMC,gBAAgB;IAC3BC,QAAQ;IACRC,OAAO;IACPC,aAAa;IACbC,MAAM;IACNC,QAAQ;IACRC,WAAW;IACXC,MAAM;IACNC,YAAY;IACZC,aAAa;IACbC,aAAa;IACbC,aAAa;IACb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