@murumets-ee/imports 0.49.0 → 0.51.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 (50) hide show
  1. package/dist/carmaker-feed-C_MnDaOC.mjs +2 -0
  2. package/dist/{carmaker-feed-CxhZBrkO.mjs.map → carmaker-feed-C_MnDaOC.mjs.map} +1 -1
  3. package/dist/carmaker-feed-DlD2xPs0.d.mts +58 -0
  4. package/dist/carmaker-feed-DlD2xPs0.d.mts.map +1 -0
  5. package/dist/{cleanup-CHjDgvKT.mjs → cleanup-DdILFoAP.mjs} +2 -2
  6. package/dist/{cleanup-CHjDgvKT.mjs.map → cleanup-DdILFoAP.mjs.map} +1 -1
  7. package/dist/index.d.mts +7 -5
  8. package/dist/index.d.mts.map +1 -1
  9. package/dist/index.mjs +1 -1
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/mapping/index.d.mts +2 -359
  12. package/dist/mapping/index.d.mts.map +1 -1
  13. package/dist/mapping/index.mjs +1 -1
  14. package/dist/{mapping-transform-D76b-P-p.mjs → mapping-transform-AMFEg1rS.mjs} +2 -2
  15. package/dist/{mapping-transform-D76b-P-p.mjs.map → mapping-transform-AMFEg1rS.mjs.map} +1 -1
  16. package/dist/{parts-schema-D0gMhNWj.mjs → parts-schema-BBUINSdN.mjs} +2 -2
  17. package/dist/{parts-schema-D0gMhNWj.mjs.map → parts-schema-BBUINSdN.mjs.map} +1 -1
  18. package/dist/{parts-schema-x8_GRYWc.d.mts → parts-schema-u5kr5zFg.d.mts} +359 -3
  19. package/dist/parts-schema-u5kr5zFg.d.mts.map +1 -0
  20. package/dist/plugin.d.mts +1 -1
  21. package/dist/plugin.mjs +1 -1
  22. package/dist/plugin.mjs.map +1 -1
  23. package/dist/runner-wPnCZlB4.mjs +2 -0
  24. package/dist/runner-wPnCZlB4.mjs.map +1 -0
  25. package/dist/{schema-registry-C_lQje-K.mjs → schema-registry-B_7AweTa.mjs} +2 -2
  26. package/dist/{schema-registry-C_lQje-K.mjs.map → schema-registry-B_7AweTa.mjs.map} +1 -1
  27. package/dist/storage-resolver.d.mts +1 -1
  28. package/dist/transform-DwAQ4b-j.mjs +2 -0
  29. package/dist/transform-DwAQ4b-j.mjs.map +1 -0
  30. package/dist/{transform-CABBaYmF.d.mts → transform-WeiiLdYP.d.mts} +12 -1
  31. package/dist/transform-WeiiLdYP.d.mts.map +1 -0
  32. package/dist/transforms.d.mts +2 -46
  33. package/dist/transforms.mjs +1 -1
  34. package/dist/{worker-DRTgbtT7.d.mts → worker-DH3SN-91.d.mts} +189 -4
  35. package/dist/worker-DH3SN-91.d.mts.map +1 -0
  36. package/dist/worker.d.mts +1 -1
  37. package/dist/worker.mjs +1 -1
  38. package/dist/worker.mjs.map +1 -1
  39. package/dist/{xlsx-reader-Ccesszbc.mjs → xlsx-reader-Dsq_ERiB.mjs} +2 -2
  40. package/dist/{xlsx-reader-Ccesszbc.mjs.map → xlsx-reader-Dsq_ERiB.mjs.map} +1 -1
  41. package/package.json +8 -8
  42. package/dist/carmaker-feed-CxhZBrkO.mjs +0 -2
  43. package/dist/parts-schema-x8_GRYWc.d.mts.map +0 -1
  44. package/dist/runner-C-s6SD7t.mjs +0 -2
  45. package/dist/runner-C-s6SD7t.mjs.map +0 -1
  46. package/dist/transform-CABBaYmF.d.mts.map +0 -1
  47. package/dist/transform-DIzWppgJ.mjs +0 -2
  48. package/dist/transform-DIzWppgJ.mjs.map +0 -1
  49. package/dist/transforms.d.mts.map +0 -1
  50. package/dist/worker-DRTgbtT7.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"parts-schema-D0gMhNWj.mjs","names":[],"sources":["../src/mapping/number-format.ts","../src/mapping/column-transforms.ts","../src/mapping/engine.ts","../src/mapping/target-schema.ts","../src/mapping/parts-schema.ts"],"sourcesContent":["/**\n * Number parsing for the configurable mapping engine (commerce-demo phase 02).\n *\n * Real supplier feeds (R03) disagree on decimal AND thousands separators:\n * `55.02` (dot decimal), `326,88` (comma decimal), `1.234,56` (EU\n * thousands+decimal), `1,234.56` (US), `1 234,56` (space-grouped). The mapping\n * stores an explicit `{ decimal, thousands }` per profile so there is no guessing\n * — `parseNumber` trusts the configured format.\n *\n * Two parsers live here:\n * - `parseNumber(raw, format)` — the format-driven parser used by the generic\n * `number` per-column transform.\n * - `parseEuropeanNumber(raw)` — the carmaker-feed legacy parser (comma decimal,\n * dot thousands, **bare-dot rejected as ambiguous**). Carries the carmaker feed's\n * documented format with two intentional broadenings vs the old inline parser:\n * it trims surrounding whitespace, and returns `null` (not `NaN`) for an empty /\n * `'NA'` cell so both number ops share absent-vs-malformed semantics. The\n * carmaker doc-shape suite (27 tests) is the regression net.\n */\n\n/** Separator config for {@link parseNumber}. Stored per `import_mapping`. */\nexport interface NumberFormat {\n /** Decimal separator. */\n decimal: '.' | ','\n /** Thousands grouping separator. `''` = none. */\n thousands: '' | '.' | ',' | ' '\n}\n\n/** Post-cleanup numeric form: optional sign, digits, optional single decimal. */\nconst STRICT_NUMBER_RE = /^-?\\d+(\\.\\d+)?$/\n\n/**\n * Parse a feed cell into a number using an EXPLICIT `{ decimal, thousands }`\n * format. No ambiguity: thousands separators are stripped, the decimal separator\n * is normalised to `.`, and the result is strict-validated.\n *\n * Returns:\n * - `null` for an empty / `'NA'` cell (a legitimately-absent value — the caller\n * decides whether that's allowed for a given target field).\n * - `NaN` for a non-empty but unparseable cell (malformed — the caller surfaces\n * a row-level error rather than coercing to 0).\n * - the parsed number otherwise.\n *\n * A character that is neither a digit, the configured decimal, the configured\n * thousands separator, nor a leading `-` makes the cell unparseable (`NaN`) —\n * e.g. a literal `.` when the format's decimal is `,` and thousands is not `.`.\n */\nexport function parseNumber(raw: string, format: NumberFormat): number | null {\n const trimmed = raw.trim()\n if (trimmed === '' || trimmed.toUpperCase() === 'NA') return null\n\n const { decimal, thousands } = format\n let s = trimmed\n // 1. Remove every thousands separator (when one is configured).\n if (thousands !== '') s = s.split(thousands).join('')\n\n // 2. Normalise the decimal separator to `.`. After thousands removal, the\n // \"other\" separator must not appear — if it does, the cell doesn't match\n // the declared format and is unparseable.\n if (decimal === ',') {\n if (s.includes('.')) return Number.NaN\n s = s.split(',').join('.')\n } else {\n // decimal === '.'\n if (s.includes(',')) return Number.NaN\n }\n\n if (!STRICT_NUMBER_RE.test(s)) return Number.NaN\n return Number.parseFloat(s)\n}\n\n/**\n * Convert a major-unit money value (e.g. `55.02` EUR) to integer MINOR units\n * (`5502`). Rounds to the nearest cent to absorb float drift. The commerce-demo\n * PartsDocument money fields (`list_price_minor`, `purchase_price_minor`,\n * `core_charge_minor`) are integer minor units so derived prices (PR4) don't\n * accrue rounding error — see F003 in progress.md.\n */\nexport function toMinorUnits(value: number): number {\n return Math.round(value * 100)\n}\n\n/**\n * Parse a European-formatted decimal: `,` is the decimal separator, `.` is the\n * (optional) thousands separator. Returns `null` for an empty / `'NA'` cell and\n * `NaN` on unparseable (malformed) input.\n *\n * This is the carmaker-feed legacy parser, preserved from the hardcoded transform.\n * Crucially it **rejects bare-dot** input (`1.98`, `1.234`) as ambiguous rather\n * than guessing — the carmaker feeds are documented as comma-decimal, and a `.`\n * without a `,` could mean a US-format decimal OR a thousands marker. The\n * format-driven {@link parseNumber} doesn't need this guard (its separators are\n * explicit); the carmaker path keeps it.\n *\n * The `null` (absent) vs `NaN` (malformed) split mirrors {@link parseNumber} so\n * the mapping engine treats both number ops uniformly: a target field's `buildRow`\n * reads `null` as \"not provided\" and `NaN` as \"invalid\". This is what lets the\n * reimplemented carmaker transform keep its `GrossPrice 'NA' → null` behaviour\n * (optional field) while still erroring on a malformed `NetPrice` (required).\n *\n * Cases: `'1,98'`→`1.98`, `'1.234,56'`→`1234.56`, `'5'`→`5`, `'-5,00'`→`-5`,\n * empty / `'NA'` → `null`. Rejected (`NaN`): bare-dot (`'1.98'`, `'1.234'`),\n * trailing junk (`'1,98EUR'`), multiple commas (`'1,2,3'`), other non-numeric.\n */\nexport function parseEuropeanNumber(s: string): number | null {\n const trimmed = s.trim()\n if (trimmed === '' || trimmed.toUpperCase() === 'NA') return null\n const hasComma = trimmed.includes(',')\n const hasDot = trimmed.includes('.')\n let cleaned: string\n if (hasComma && hasDot) {\n // European thousands+decimal: strip every `.`, then swap the (sole) `,` for\n // `.`. The strict regex below catches multi-comma input.\n cleaned = trimmed.replace(/\\./g, '').replace(',', '.')\n } else if (hasComma) {\n cleaned = trimmed.replace(',', '.')\n } else if (hasDot) {\n return Number.NaN\n } else {\n cleaned = trimmed\n }\n if (!STRICT_NUMBER_RE.test(cleaned)) return Number.NaN\n return Number.parseFloat(cleaned)\n}\n","/**\n * Per-column transforms for the mapping engine (commerce-demo phase 02, D005).\n *\n * A **bounded, enum-keyed** library of cleaning operations applied to a source\n * cell before it lands on a target field. This is the security model from R02:\n * transforms are declarative operations with Zod-validated params, NEVER\n * user-supplied executable code. The carmaker feed's logic decomposes exactly\n * into `stripPrefix` + `europeanNumber` (+ the schema's code-normalize).\n *\n * Number-producing ops (`number`, `europeanNumber`) are TERMINAL by convention —\n * they convert the string cell into `number | null`; string ops after them are\n * no-ops. The engine reads the result as `string | number | null` and hands it to\n * the target schema's `buildRow`.\n */\n\nimport { z } from 'zod'\nimport { type NumberFormat, parseEuropeanNumber, parseNumber } from './number-format.js'\n\n/** Max length for a strip-affix value — bounds the param, no ReDoS surface. */\nconst MAX_AFFIX_LEN = 32\n\n/**\n * Discriminated union of bounded transform ops. The TS type is INFERRED from\n * this schema so there's a single source of truth + the snapshot is validated at\n * the engine boundary.\n */\nexport const columnTransformSchema = z.discriminatedUnion('op', [\n z.object({ op: z.literal('trim') }),\n z.object({ op: z.literal('uppercase') }),\n z.object({ op: z.literal('lowercase') }),\n z.object({ op: z.literal('stripPrefix'), value: z.string().min(1).max(MAX_AFFIX_LEN) }),\n z.object({ op: z.literal('stripSuffix'), value: z.string().min(1).max(MAX_AFFIX_LEN) }),\n z.object({ op: z.literal('defaultIfEmpty'), value: z.string().max(255) }),\n z.object({ op: z.literal('number') }),\n z.object({ op: z.literal('europeanNumber') }),\n])\n\n/** One declarative cleaning operation. */\nexport type ColumnTransform = z.infer<typeof columnTransformSchema>\n\n/** The discriminator literal of a {@link ColumnTransform}. */\nexport type ColumnTransformOp = ColumnTransform['op']\n\n/** UI descriptor for one transform op: its key, a label, and whether it takes a `value` param. */\nexport interface ColumnTransformOpDescriptor {\n op: ColumnTransformOp\n label: string\n /** `true` → the op carries a `value` string param (`stripPrefix`/`stripSuffix`/`defaultIfEmpty`). */\n hasValue: boolean\n}\n\n/**\n * Static catalogue of the available per-column transform ops, for the PR3 wizard's\n * transform picker. The ORDER is the suggested UI order; `number`/`europeanNumber`\n * are terminal (see {@link applyColumnTransforms}) and labelled accordingly.\n */\nexport const COLUMN_TRANSFORM_OPS: readonly ColumnTransformOpDescriptor[] = [\n { op: 'trim', label: 'Trim whitespace', hasValue: false },\n { op: 'uppercase', label: 'Uppercase', hasValue: false },\n { op: 'lowercase', label: 'Lowercase', hasValue: false },\n { op: 'stripPrefix', label: 'Strip prefix', hasValue: true },\n { op: 'stripSuffix', label: 'Strip suffix', hasValue: true },\n { op: 'defaultIfEmpty', label: 'Default if empty', hasValue: true },\n { op: 'number', label: 'Parse number (uses number format)', hasValue: false },\n { op: 'europeanNumber', label: 'Parse European number (1.234,56)', hasValue: false },\n] as const\n\n/** The value a column carries as it moves through the transform pipeline. */\nexport type CellValue = string | number | null\n\n/**\n * Apply a transform pipeline to a raw cell, left-to-right. String ops act on the\n * string value; the `number` / `europeanNumber` ops are terminal (convert to\n * `number | null`, with `NaN` for a malformed numeric — the schema's `buildRow`\n * surfaces that as a row error). Once the value is non-string, later string ops\n * pass through unchanged.\n */\nexport function applyColumnTransforms(\n raw: string,\n transforms: readonly ColumnTransform[],\n format: NumberFormat,\n): CellValue {\n let value: CellValue = raw\n for (const t of transforms) {\n if (typeof value !== 'string') {\n // A prior number op already produced number|null — string ops are no-ops\n // past this point (number ops are terminal by convention).\n continue\n }\n switch (t.op) {\n case 'trim':\n value = value.trim()\n break\n case 'uppercase':\n value = value.toUpperCase()\n break\n case 'lowercase':\n value = value.toLowerCase()\n break\n case 'stripPrefix':\n value = value.startsWith(t.value) ? value.slice(t.value.length) : value\n break\n case 'stripSuffix':\n value = value.endsWith(t.value) ? value.slice(0, value.length - t.value.length) : value\n break\n case 'defaultIfEmpty':\n value = value.trim() === '' ? t.value : value\n break\n case 'number':\n value = parseNumber(value, format)\n break\n case 'europeanNumber':\n value = parseEuropeanNumber(value)\n break\n }\n }\n return value\n}\n","/**\n * Mapping engine (commerce-demo phase 02, D005).\n *\n * Turns a declarative `MappingConfig` (which source column → which whitelisted\n * target field, plus per-column transforms + a number format) into a\n * `RowTransform` the existing runner drives. The pipeline per row is:\n *\n * raw cells → applyColumnTransforms(per column) → MappedRow → schema.buildRow\n *\n * Two whitelists guard the boundary (R02 injection model): the `target_schema`\n * name resolves to a registered `TargetSchema`, and every `column_map[].target`\n * must be one of that schema's fields — enforced here at build time (throws),\n * before any row is processed.\n *\n * `resolveMapping` implements the D002 most-specific ladder used at enqueue time\n * to pick the `(supplier, brand)` mapping over the `(supplier, NULL)` default.\n */\n\nimport { z } from 'zod'\nimport type { RowTransform } from '../transform.js'\nimport { applyColumnTransforms, columnTransformSchema } from './column-transforms.js'\nimport type { MappedRow, TargetSchema } from './target-schema.js'\n\n/** One column-map entry. `target` is checked against the schema whitelist separately. */\nexport const mappingColumnSchema = z.object({\n /** Source header name (or positional index string for headerless feeds). */\n source: z.string().min(1).max(256),\n /** Target field key — must be in the chosen schema's whitelist (enforced in `buildMappingTransform`). */\n target: z.string().min(1).max(64),\n /** Ordered per-column cleaning ops. Defaults to none. */\n transforms: z.array(columnTransformSchema).default([]),\n})\nexport type MappingColumn = z.infer<typeof mappingColumnSchema>\n\n/**\n * Decimal + thousands separators for the `number` transform.\n *\n * The two MUST differ: `parseNumber` strips every thousands separator FIRST, so a\n * config where `decimal === thousands` (e.g. both `,`) would strip the decimal\n * separator too — `326,88` → `32688`, a silent 100× error rather than a row error.\n * Rejected at save (`assertValidMapping`) AND at run (`mappingConfigSchema`).\n */\nexport const numberFormatSchema = z\n .object({\n decimal: z.enum(['.', ',']),\n thousands: z.enum(['', '.', ',', ' ']),\n })\n .refine((f) => f.decimal !== f.thousands, {\n message: 'decimal and thousands separators must differ',\n path: ['thousands'],\n })\n\n/**\n * The portable mapping config — the subset of an `import_mapping` row the engine\n * needs. The enqueuer SNAPSHOTS this into `import_run.params.mapping` so a run\n * records the exact mapping it used (reproducible) and the transform stays a pure\n * function of `(row, ctx)` with no per-row DB I/O.\n */\nexport const mappingConfigSchema = z.object({\n targetSchema: z.string().min(1).max(64),\n numberFormat: numberFormatSchema,\n columnMap: z.array(mappingColumnSchema),\n})\nexport type MappingConfig = z.infer<typeof mappingConfigSchema>\n\n/**\n * Build a `RowTransform` from a validated mapping config + its target schema.\n *\n * Throws at BUILD time if any `column_map` target is outside the schema's\n * whitelist (deny-by-default, R02) — so a misconfigured mapping fails loudly\n * before a single row is written, rather than silently dropping a column.\n *\n * Generic over the schema's output type, so passing the concrete `partsSchema`\n * yields a `RowTransform<PartsDocument>` (the carmaker path keeps its typing); the\n * registry-resolved `TargetSchema<unknown>` yields `RowTransform<unknown>` (the\n * `commerce:mapping` path, where the output type isn't known until runtime).\n */\nexport function buildMappingTransform<TOut>(\n config: MappingConfig,\n schema: TargetSchema<TOut>,\n): RowTransform<TOut> {\n const allowed = new Set(schema.fields.map((f) => f.key))\n for (const col of config.columnMap) {\n if (!allowed.has(col.target)) {\n throw new Error(\n `Mapping target \"${col.target}\" is not a field of schema \"${schema.name}\" ` +\n `(allowed: ${[...allowed].join(', ')})`,\n )\n }\n }\n\n const format = config.numberFormat\n const columnMap = config.columnMap\n\n return async (row, ctx) => {\n const mapped: MappedRow = {}\n for (const col of columnMap) {\n // `source` is read as data from the parsed row map — never used as a key\n // into framework objects (R02). A missing source column yields `''`.\n const raw = row[col.source] ?? ''\n mapped[col.target] = applyColumnTransforms(raw, col.transforms, format)\n }\n return schema.buildRow(mapped, {\n importRunId: ctx.importRunId,\n rowNumber: ctx.rowNumber,\n params: ctx.params,\n })\n }\n}\n\n/** The minimal shape `resolveMapping` needs — satisfied by an `import_mapping` row or a test fixture. */\nexport interface ResolvableMapping {\n /** `null` = supplier default (applies to all brands). */\n brandId: string | null\n active: boolean\n}\n\n/**\n * Most-specific resolution (D002 ladder): given the candidate mappings for one\n * `(supplier, target_schema)` and the requested brand, return the brand-specific\n * mapping if one exists, else the supplier-default (`brandId === null`). Inactive\n * mappings are skipped. Returns `undefined` when nothing matches.\n */\nexport function resolveMapping<M extends ResolvableMapping>(\n mappings: readonly M[],\n brandId: string | null,\n): M | undefined {\n const active = mappings.filter((m) => m.active)\n if (brandId !== null) {\n const specific = active.find((m) => m.brandId === brandId)\n if (specific) return specific\n }\n return active.find((m) => m.brandId === null)\n}\n","/**\n * TargetSchema — the contract a mapping writes INTO (commerce-demo phase 02, D005).\n *\n * A mapping's `column_map` points source columns at a schema's whitelisted target\n * fields; the engine applies the per-column transforms to build a `MappedRow`, then\n * hands it to `schema.buildRow` to produce the typed output document (an ES\n * `PartsDocument` for `parts`, a discount row for `discount_table`).\n *\n * The `fields` list is the SECOND injection-boundary whitelist (the first is the\n * registered schema name): a `column_map` entry whose `target` is not a field key\n * here is rejected at validation time (R02). Two schemas ship in PR2 — `parts` and\n * `discount_table`.\n */\n\nimport type { RowResult } from '../transform.js'\nimport type { CellValue } from './column-transforms.js'\n\n/** One whitelisted target field on a schema. */\nexport interface TargetField {\n /** Stable target key referenced by `column_map[].target`. */\n key: string\n /** Human label for the wizard dropdown (PR3). */\n label: string\n /** Whether a mapping for this schema MUST include this target. */\n required: boolean\n /** Coarse type — drives the wizard's transform suggestions; `buildRow` does the real coercion. */\n type: 'string' | 'number'\n /**\n * Header spellings this field should be SUGGESTED for when the wizard auto-assigns a freshly\n * previewed file. Purely advisory: the operator can always override, and nothing here widens\n * the injection-boundary whitelist — `key` remains the only accepted `column_map[].target`.\n *\n * Real feeds do not name their columns after our keys (a supplier ships `partno`, `VARUOSA\n * KOOD`, `ArticleName`, never `code`), so without aliases the wizard suggests nothing for the\n * columns that matter and the operator has to know the schema by heart. `describeTargetSchemas`\n * ships this to the wizard verbatim, so a field's synonyms live next to the field itself\n * rather than in a lookup table on the client.\n *\n * Only add a spelling whose meaning is UNAMBIGUOUS. An alias is a silent decision applied to\n * somebody's catalogue — see the supersession fields below, where two spellings that both read\n * as \"replacement\" denote opposite directions and are therefore deliberately absent.\n */\n aliases?: readonly string[]\n}\n\n/** The per-row product of the engine: target field key → cleaned value. */\nexport type MappedRow = Record<string, CellValue>\n\n/** Per-row context handed to `buildRow`. `params` is the opaque per-run params object. */\nexport interface BuildRowContext {\n importRunId: string\n rowNumber: number\n /**\n * Opaque per-run params (the parts schema reads brand/supplier identity from\n * it; `discount_table` ignores it). The schema validates the shape it needs.\n */\n params: Record<string, unknown>\n}\n\n/** A registered target schema: a whitelist + a row builder. */\nexport interface TargetSchema<TOut> {\n /** Registered name — also the `import_mapping.target_schema` value. */\n name: string\n /** The target-field whitelist (injection boundary). */\n fields: readonly TargetField[]\n /** Build a typed output (success) / skip / error from a mapped row. */\n buildRow(mapped: MappedRow, ctx: BuildRowContext): RowResult<TOut>\n}\n\n// ---------------------------------------------------------------------------\n// Shared `buildRow` helpers (used by every concrete schema).\n// ---------------------------------------------------------------------------\n\n/**\n * A nullable text cell → trimmed string, or `null` for empty / non-string. Accepts\n * `undefined` (an UNMAPPED target — indexed access under `noUncheckedIndexedAccess`)\n * and treats it as absent.\n */\nexport function textOrNull(v: CellValue | undefined): string | null {\n if (typeof v !== 'string') return null\n const t = v.trim()\n return t === '' ? null : t\n}\n\n/** The three outcomes a `number` / `europeanNumber` op produces for a cell. */\nexport type NumberOutcome =\n | { kind: 'value'; value: number }\n | { kind: 'absent' }\n | { kind: 'invalid' }\n\n/**\n * Classify a cell that should hold a number. `undefined` (unmapped) / `null` →\n * absent; a real number → value (`NaN` → invalid); a non-empty raw string (no\n * number op declared) → invalid; a blank raw string → absent.\n */\nexport function numberCell(v: CellValue | undefined): NumberOutcome {\n if (v === undefined || v === null) return { kind: 'absent' }\n if (typeof v === 'number') {\n return Number.isNaN(v) ? { kind: 'invalid' } : { kind: 'value', value: v }\n }\n return v.trim() === '' ? { kind: 'absent' } : { kind: 'invalid' }\n}\n\n/** Build a `RowResult` error variant (assignable to any `TargetSchema<TOut>`). */\nexport function rowError(errorType: string, message: string, field: string) {\n return { kind: 'error' as const, error: { errorType, message, field } }\n}\n","/**\n * `parts` target schema — maps a cleaned feed row into the ES `PartsDocument`\n * (commerce-demo phase 02, D005). This is the SHARED assembly + validation logic\n * the reimplemented carmaker transform and every operator-built `parts` mapping\n * run through, so the row taxonomy (code normalization, currency gate, price\n * validation) is uniform across all supplier feeds.\n *\n * **Field coverage.** This schema populates the direct passthroughs (the existing\n * `PartsDocument` columns plus `list_price_minor`, `discount_group`,\n * `superseding_code`) AND the DERIVED `purchase_price_minor` (PR4 — direct net, or\n * two-file `list × (1 − groupDiscount)` resolved from `params.discountGroups`). Core\n * charge (Korpusetasu, PR7, D004) has TWO encodings → one `core_charge_minor`:\n * Encoding A is a `surcharge`/`core_charge` COLUMN on the saleable row (written here);\n * Encoding B is a separate `<code>*S` core-fee row that skips the saleable index and\n * emits a doc-patch attaching its deposit to the PARENT part in the runner's phase-2\n * pass. Replacement-pair SIDE EFFECTS (separate entity) are PR6 — emitted from\n * `superseding_code` and/or `replaces_code`, which name the same relationship from\n * opposite ends and are pairs-only (`replaces_code` has no `PartsDocument` column).\n *\n * **Money.** Every money field is integer minor units via `toMinorUnits` (F003), and\n * the two-file derivation stays in minor units end-to-end (no major↔minor\n * round-trip). The legacy `net_price_eur` stays a major-unit float for back-compat:\n * it holds the direct net price, or — for a two-file LIST feed with no direct net —\n * the list price as a display placeholder (the true cost is `purchase_price_minor`).\n *\n * **Cost-pending warning.** A list-only row whose `discount_group` doesn't resolve\n * against `params.discountGroups` is still indexed (list set, `purchase_price_minor`\n * null) and carries a `no_purchase_price` WARNING — not a row error (phase 03 §5).\n */\n\nimport type { PartsDocument } from '@murumets-ee/search-elasticsearch'\nimport { z } from 'zod'\nimport type { DirectionalPair, DocPatch, RowWarning } from '../transform.js'\nimport type { CellValue } from './column-transforms.js'\nimport { toMinorUnits } from './number-format.js'\nimport {\n type BuildRowContext,\n type MappedRow,\n numberCell,\n rowError,\n type TargetField,\n type TargetSchema,\n textOrNull,\n} from './target-schema.js'\n\n/**\n * Params the `parts` schema reads from the run — the per-(supplier, brand)\n * identity resolved at enqueue time. Identical to the carmaker transform's params\n * (the carmaker path re-exports this), so brand/supplier injection + the optional\n * supplier code-prefix strip are validated the same way everywhere.\n */\nexport const partsParamsSchema = z.object({\n brandId: z.string().uuid(),\n brandSlug: z.string().min(1).max(64),\n supplierId: z.string().uuid(),\n supplierDisplayName: z.string().min(1).max(255),\n importBatchId: z.string().uuid(),\n /** Supplier code prefix to strip before normalization (e.g. `'ME-'`). Optional. */\n supplierCodePrefix: z\n .string()\n .max(8)\n .regex(/^[A-Z0-9-]+$/, 'must be uppercase alphanumeric or \"-\"')\n .optional(),\n /**\n * Purchase-discount map for this supplier (commerce-demo PR4, phase 03 §2):\n * `{ groupCode → discountPct }`, resolved from `supplier_discount_group` at\n * enqueue time and snapshotted onto the run so `buildRow` stays a pure function\n * (no per-row DB I/O; `@murumets-ee/imports` stays a leaf). Absent for direct-net\n * suppliers + the carmaker path. Percentages are 0–100 (the entity constrains them).\n */\n discountGroups: z.record(z.string(), z.number().min(0).max(100)).optional(),\n})\nexport type PartsParams = z.infer<typeof partsParamsSchema>\n\n/** Per-run memoization of the parsed params (keyed on the `ctx.params` reference). */\nconst paramsCache = new WeakMap<object, PartsParams>()\n\nfunction resolveParams(raw: Record<string, unknown>): PartsParams {\n const cached = paramsCache.get(raw)\n if (cached) return cached\n const parsed = partsParamsSchema.parse(raw)\n paramsCache.set(raw, parsed)\n return parsed\n}\n\n/** Per-locale display-name target fields (8 locales). */\nconst NAME_LOCALES = ['de', 'en', 'es', 'fr', 'it', 'nl', 'pt', 'ro'] as const\ntype NameLocale = (typeof NAME_LOCALES)[number]\nconst nameKey = (l: NameLocale): `name_${NameLocale}` => `name_${l}`\n\n/**\n * The `parts` target-field whitelist.\n *\n * **On the two supersession fields.** They exist as a PAIR because the direction of a\n * \"replacement\" column cannot be read off its name. TecDoc's data format defines `SupersNo` /\n * `ErsatzNr` as *\"Article ArtNo supersedes Article SupersNo\"* — the column holds the OLD code\n * and the row is current. German `ersetzt durch` and English `replaced by` mean the exact\n * opposite: the column holds the NEW code and the row is obsolete. Both are \"replacement\"\n * words; only the grammatical voice distinguishes them, and a bare noun like `Ersatznummer`\n * carries no voice at all. TecDoc's own SOAP API resolved this by shipping `replacesArticles`\n * and `replacedByArticles` as separate elements rather than one ambiguous field, and that is\n * what these two keys are.\n *\n * Getting it backwards is silent — an inverted feed builds well-formed chains with valid heads\n * and no warnings, and the union-find merge is append-only, so re-importing the right way round\n * does NOT repair it. Hence: no alias in this file is ambiguous about direction, and the\n * genuinely ambiguous spellings (`superseded no`, `Ersatznummer`, `Ersatz-Nr`) are deliberately\n * aliased to NEITHER field, so an operator meeting one has to state the direction rather than\n * inherit a guess.\n */\nconst PARTS_FIELDS: readonly TargetField[] = [\n {\n key: 'code',\n label: 'Code',\n required: true,\n type: 'string',\n // `part no` already covers a `partno` header: aliases are compared as bare alphanumerics,\n // and a header matches on a run of its own tokens, so both spellings reduce to `partno`.\n aliases: [\n 'part no',\n 'part number',\n 'article name',\n 'article no',\n 'article number',\n 'sku',\n 'varuosa kood',\n 'kood',\n 'artikelnummer',\n 'artikel nr',\n ],\n },\n {\n key: 'net_price',\n label: 'Net price',\n required: false,\n type: 'number',\n aliases: ['price', 'net price discount', 'nettopreis', 'netto'],\n },\n {\n key: 'gross_price',\n label: 'Gross price',\n required: false,\n type: 'number',\n aliases: ['bruttopreis', 'brutto'],\n },\n {\n key: 'list_price',\n label: 'List price',\n required: false,\n type: 'number',\n // `JAEHIND KM-TA` is Estonian for \"retail price, VAT-excluded\" (R03 sample A).\n aliases: ['retail price', 'rrp', 'jaehind', 'jaehind km ta', 'listenpreis'],\n },\n {\n key: 'currency',\n label: 'Currency',\n required: false,\n type: 'string',\n aliases: ['currency cd', 'currency code', 'valuuta'],\n },\n {\n key: 'barcode',\n label: 'Barcode',\n required: false,\n type: 'string',\n // `ean code` / `gtin code` are whole-header aliases on purpose: without them a header\n // spelled `EAN Code` matches the bare `code` token and claims the REQUIRED part-code\n // field, because `code` (4 chars) outscores the `ean` alias (3). A whole-header hit\n // outranks any partial run, so naming the compound form settles it.\n aliases: ['ean', 'ean code', 'gtin', 'gtin code', 'triipkood'],\n },\n {\n key: 'description1',\n label: 'Description 1',\n required: false,\n type: 'string',\n aliases: ['description', 'kirjeldus', 'beschreibung'],\n },\n { key: 'description2', label: 'Description 2', required: false, type: 'string' },\n {\n key: 'discount_group',\n label: 'Discount group',\n required: false,\n type: 'string',\n // `TOOTEGRUPP` is Estonian for \"product group\" (R03 sample A), which IS the discount key.\n // A bare `group` is deliberately NOT here: on a parts feed it is as likely an assortment\n // or category group, and a wrong-but-colliding value resolves against\n // `params.discountGroups` and derives a wrong `purchase_price_minor` with no warning at all\n // (only a NON-colliding code raises `no_purchase_price`). A silent money error is worth\n // more than a saved click.\n aliases: ['product group', 'tootegrupp', 'rabattgruppe'],\n },\n {\n /**\n * The NEWER code that supersedes THIS row — the row's own code is the obsolete one.\n * Emits `(this row → the value)`.\n */\n key: 'superseding_code',\n label: 'Replaced by (newer code)',\n required: false,\n type: 'string',\n // Every entry states direction by grammar: a passive (\"replaced by\", \"ersetzt durch\",\n // \"vervangen door\") or a word that means \"the one after\" (\"successor\", \"new code\",\n // \"Nachfolgenummer\"). A bare noun phrase like `replacement code` does NOT — it reads just\n // as easily as \"the code this replaces\" — so it is excluded for the same reason\n // `Ersatznummer` is.\n aliases: [\n 'replaced by',\n 'successor',\n 'successor code',\n 'new code',\n 'ersetzt durch',\n 'wird ersetzt durch',\n 'nachfolgenummer',\n 'vervangen door',\n ],\n },\n {\n /**\n * The OLDER code THIS row supersedes — the row's own code is the current one. Emits the\n * INVERSE pair `(the value → this row)`. This is TecDoc table 204's shape.\n */\n key: 'replaces_code',\n label: 'Replaces (older code)',\n required: false,\n type: 'string',\n // Same rule from the other side: active verbs (\"replaces\", \"supersedes\") or words meaning\n // \"the one before\" (\"predecessor\", \"old code\", \"Vorgängernummer\"). `superseded article` is\n // NOT here — TecDoc reads that phrasing as the old code, but it is the same bare\n // past-participle family as `superseded no`, which this file refuses to auto-assign;\n // excluding one and accepting the other would be incoherent.\n aliases: [\n 'replaces',\n 'supersedes',\n 'old code',\n 'previous code',\n 'predecessor',\n 'vorgaengernummer',\n ],\n },\n // Core charge (Korpusetasu, commerce-demo PR7, D004). Encoding A: a supplier's\n // `surcharge`/`core_charge` COLUMN maps here → this row's deposit. (Encoding B —\n // a separate `<code>*S` row — needs no whitelist field; it's detected on the code.)\n {\n key: 'core_charge',\n label: 'Core charge',\n required: false,\n type: 'number',\n aliases: ['surcharge', 'deposit', 'core deposit', 'korpusetasu', 'pfand'],\n },\n ...NAME_LOCALES.map(\n (l): TargetField => ({\n key: nameKey(l),\n label: `Name (${l})`,\n required: false,\n type: 'string',\n // The carmaker feed ships these as `Description_<LOCALE>` (R03 sample D).\n aliases: [`description ${l}`, `name ${l}`],\n }),\n ),\n] as const\n\nconst NORMALIZE_CODE_RE = /[\\s-]/g\n/**\n * Uppercase + dash/whitespace-stripped (D2). `*`/other chars are preserved (e.g. `*S`\n * markers). EXPORTED so downstream consumers that key off `code_normalized` — the\n * replacement editor (commerce-demo PR6), which normalizes admin-typed codes before\n * matching members — use the IDENTICAL rule (R05 Q7: normalization must match across\n * every code source or merge-on-collision silently fails to collide).\n */\nexport function normalizeCode(s: string): string {\n return s.toUpperCase().replace(NORMALIZE_CODE_RE, '')\n}\n\n/**\n * A supersession cell → one normalized code, or `null` when there is no usable edge end:\n * unmapped, blank, or punctuation-only (a `'---'` placeholder normalizes to the empty string).\n *\n * **The supplier prefix must be stripped here too.** `code_normalized` removes\n * `params.supplierCodePrefix` before normalizing, so a feed that writes `FO-1120698` in its own\n * code column also writes `FO-1091888` in its supersession column. Normalizing one with the\n * prefix and the other without produces an edge between a code that exists in the catalogue and\n * one that never will — the chain builds cleanly and matches nothing, which is indistinguishable\n * from having no supersession data at all.\n */\nfunction normalizeCodeCell(\n cell: CellValue | undefined,\n supplierCodePrefix: string | undefined,\n): string | null {\n const raw = textOrNull(cell)\n if (raw === null) return null\n const stripped =\n supplierCodePrefix && raw.startsWith(supplierCodePrefix)\n ? raw.slice(supplierCodePrefix.length)\n : raw\n const normalized = normalizeCode(stripped)\n return normalized === '' ? null : normalized\n}\n\n/**\n * Two-file purchase price (phase 03 §2): `list × (1 − discountPct/100)`, computed\n * ENTIRELY in integer minor units so no major↔minor round-trip can introduce drift\n * (F003). `listMinor` is already minor units; the result is rounded to the nearest\n * minor unit. Worked (R03 A+B): `5502 × 0.74 = 4071.48 → 4071` (€40.71).\n */\nfunction deriveTwoFilePurchaseMinor(listMinor: number, discountPct: number): number {\n return Math.round(listMinor * (1 - discountPct / 100))\n}\n\n/**\n * The core-charge marker suffix on a NORMALIZED code (D004, SD002). `normalizeCode`\n * uppercases + strips dashes/spaces but PRESERVES `*`, so a `<code>*S` core-fee row\n * arrives here intact — e.g. `1120698*S`. A code ending in `*S` is a core-fee line,\n * not a saleable part (Encoding B).\n */\nconst CORE_FEE_SUFFIX = '*S'\n\n/** The five core-charge doc fields the two encodings write. */\ntype CoreChargeFields = Pick<\n PartsDocument,\n | 'core_charge_minor'\n | 'core_charge_currency'\n | 'core_charge_refundable'\n | 'core_charge_tax_class'\n | 'core_charge_tax_inclusive'\n>\n\n/**\n * The tax-NEUTRAL core-charge block (D004 / D007) for a deposit amount in minor\n * units, or all-null when there's no core charge. EUR (D9) + refundable by default;\n * the imported EU feed amounts are net so `tax_inclusive = false`; `tax_class` stays\n * null — no rate is baked in here, the future pluggable EU/US tax engine maps it (D007).\n */\nfunction coreChargeFields(minor: number | null): CoreChargeFields {\n if (minor === null) {\n return {\n core_charge_minor: null,\n core_charge_currency: null,\n core_charge_refundable: null,\n core_charge_tax_class: null,\n core_charge_tax_inclusive: null,\n }\n }\n return {\n core_charge_minor: minor,\n core_charge_currency: 'EUR',\n core_charge_refundable: true,\n core_charge_tax_class: null,\n core_charge_tax_inclusive: false,\n }\n}\n\n/**\n * The `parts` schema. `buildRow` THROWS on invalid run params (so a misconfigured\n * run surfaces as a transform error, matching the carmaker contract) and returns a\n * typed `RowResult` per row otherwise.\n */\nexport const partsSchema: TargetSchema<PartsDocument> = {\n name: 'parts',\n fields: PARTS_FIELDS,\n buildRow(mapped: MappedRow, ctx: BuildRowContext) {\n const params = resolveParams(ctx.params)\n\n // 1. Code (required) → raw `code` + normalized `code_normalized` + doc id.\n const codeRaw = typeof mapped.code === 'string' ? mapped.code.trim() : ''\n if (!codeRaw) return rowError('missing_code', 'code is empty', 'code')\n const stripped =\n params.supplierCodePrefix && codeRaw.startsWith(params.supplierCodePrefix)\n ? codeRaw.slice(params.supplierCodePrefix.length)\n : codeRaw\n const codeNormalized = normalizeCode(stripped)\n if (!codeNormalized) {\n return rowError(\n 'empty_normalized_code',\n `Code \"${codeRaw}\" is empty after normalization`,\n 'code',\n )\n }\n\n // 2. Currency gate (D9 EUR-only). Unmapped/blank defaults to EUR. Runs BEFORE the\n // `*S` detection so a non-EUR core-fee row is rejected too — Encoding A and B keep\n // the SAME currency contract (a `*S` deposit is never silently coerced to EUR).\n const currencyText = textOrNull(mapped.currency)\n const currency = currencyText ?? 'EUR'\n if (currency !== 'EUR') {\n return rowError(\n 'unsupported_currency',\n `Currency \"${currency}\" not supported (EUR-only)`,\n 'currency',\n )\n }\n\n // 2b. Core-fee line — Encoding B (D004, SD002). A `<code>*S` normalized code is a\n // core-fee MARKER row, not a saleable part: strip the `*S`, take THIS row's net\n // price as the deposit, and emit a doc-patch that attaches it onto the PARENT\n // part's core-charge fields. The row itself SKIPS the saleable index (never a\n // `*S` SKU — D004). The runner applies the patch in a phase-2 pass; a parent\n // that isn't in the import becomes an `orphan_core_charge` warning (never a\n // phantom doc, never a silent drop). A `*S` with no parent code, or no/invalid\n // amount, is a row error.\n if (codeNormalized.endsWith(CORE_FEE_SUFFIX)) {\n const parentNormalized = codeNormalized.slice(0, -CORE_FEE_SUFFIX.length)\n if (!parentNormalized) {\n return rowError(\n 'core_charge_no_parent',\n `Core-fee row \"${codeRaw}\" has no part code before the \"*S\" marker`,\n 'code',\n )\n }\n const deposit = numberCell(mapped.net_price)\n if (deposit.kind === 'invalid') {\n return rowError(\n 'invalid_core_charge',\n 'core-fee (*S) row net_price is not a number',\n 'net_price',\n )\n }\n if (deposit.kind === 'absent') {\n return rowError(\n 'missing_core_charge',\n 'core-fee (*S) row has no net_price to use as the deposit',\n 'net_price',\n )\n }\n // Gate on the MINOR-unit result (a sub-cent value like 0.004 → round to 0):\n // 0 / sub-cent / negative deposit → nothing to attach; drop it without a patch\n // rather than zeroing a parent's core charge.\n const depositMinor = toMinorUnits(deposit.value)\n if (depositMinor <= 0) {\n return { kind: 'skip', reason: 'core_fee_zero' }\n }\n const patch: DocPatch<PartsDocument> = {\n id: `${parentNormalized}__${params.supplierId}`,\n doc: coreChargeFields(depositMinor),\n orphanWarning: {\n warningType: 'orphan_core_charge',\n message: 'core-fee (*S) row references a part not present in this import',\n field: 'code',\n },\n }\n return { kind: 'skip', reason: 'core_charge_marker', patches: [patch] }\n }\n\n // 3. Prices. net/gross/list each: absent → null, invalid → error, value → number.\n const net = numberCell(mapped.net_price)\n if (net.kind === 'invalid')\n return rowError('invalid_net_price', 'net_price is not a number', 'net_price')\n const gross = numberCell(mapped.gross_price)\n if (gross.kind === 'invalid') {\n return rowError('invalid_gross_price', 'gross_price is not a number', 'gross_price')\n }\n const list = numberCell(mapped.list_price)\n if (list.kind === 'invalid')\n return rowError('invalid_list_price', 'list_price is not a number', 'list_price')\n\n const netValue = net.kind === 'value' ? net.value : null\n const listValue = list.kind === 'value' ? list.value : null\n // At least one price must resolve. `net_price_eur` is non-nullable on the doc,\n // so it takes the direct net or — for a list-only two-file feed — the list\n // price as a display placeholder (the true cost is `purchase_price_minor`).\n const displayPrice = netValue ?? listValue\n if (displayPrice === null) {\n return rowError('missing_price', 'no net_price or list_price provided', 'price')\n }\n\n // 4. Purchase-price derivation (phase 03 §2, PR4). All money stays in integer\n // minor units (F003 — never round-trip back to major).\n // - direct net column (R03 C/D) → purchase = net\n // - two-file list × (1 − groupDiscount) → purchase = round(list × (1 − d/100))\n // - neither resolvable → cost pending: index list-only + WARN\n // (a `no_purchase_price` warning, NOT a row error — the part is still indexed).\n const discountGroup = textOrNull(mapped.discount_group)\n const listMinor = listValue === null ? null : toMinorUnits(listValue)\n let purchasePriceMinor: number | null = null\n const warnings: RowWarning[] = []\n if (netValue !== null) {\n purchasePriceMinor = toMinorUnits(netValue)\n } else if (listMinor !== null) {\n // List-only row: resolve the supplier's discount group → derive cost.\n const discountPct =\n discountGroup !== null ? params.discountGroups?.[discountGroup] : undefined\n if (discountPct !== undefined) {\n purchasePriceMinor = deriveTwoFilePurchaseMinor(listMinor, discountPct)\n } else {\n warnings.push({\n warningType: 'no_purchase_price',\n message:\n discountGroup === null\n ? 'list price present but no discount group on the row — cost pending'\n : `no discount group \"${discountGroup}\" configured for this supplier — cost pending`,\n field: 'discount_group',\n })\n }\n }\n\n // 5. Replacement-pair side-output (commerce-demo PR6, SD007). Both supersession columns\n // are SPARSE on a full manufacturer catalogue, and both produce the same\n // `(from = older → to = newer)` edge the chain engine consumes — they differ only in\n // which end of the edge the row itself is:\n // `superseding_code` → the value is NEWER, so the edge runs (this row → value);\n // `replaces_code` → the value is OLDER, so the edge runs (value → this row).\n // Every code is normalized the SAME way as `code_normalized` so the downstream merge\n // collides codes across feeds (R05 Q7). A value that is empty, normalizes to empty\n // (e.g. `'---'`), or self-pairs yields no edge. A row MAY carry both columns — that is\n // a legitimate three-code chain (older → this → newer), not a conflict.\n const pairs: DirectionalPair[] = []\n const supersedingNormalized = normalizeCodeCell(\n mapped.superseding_code,\n params.supplierCodePrefix,\n )\n if (supersedingNormalized !== null && supersedingNormalized !== codeNormalized) {\n pairs.push({ from: codeNormalized, to: supersedingNormalized })\n }\n const replacesNormalized = normalizeCodeCell(mapped.replaces_code, params.supplierCodePrefix)\n if (replacesNormalized !== null && replacesNormalized !== codeNormalized) {\n pairs.push({ from: replacesNormalized, to: codeNormalized })\n }\n\n // 6. Core charge — Encoding A (D004). A `surcharge`/`core_charge` COLUMN on this\n // saleable row is the deposit for THIS part. 0 / empty / absent / sub-cent → no\n // core charge. (Encoding B — a separate `<code>*S` row — is handled at step 1b\n // and attaches to the parent in phase-2, so it never reaches here. In the unusual\n // case a part has BOTH a `core_charge` column AND a sibling `*S` row — suppliers\n // use one encoding — the `*S` phase-2 patch runs after indexing and wins.)\n const coreChargeCell = numberCell(mapped.core_charge)\n if (coreChargeCell.kind === 'invalid') {\n return rowError('invalid_core_charge', 'core_charge is not a number', 'core_charge')\n }\n // Gate on the MINOR-unit result so a sub-cent value (rounds to 0) yields no charge.\n const coreChargeMinorRaw =\n coreChargeCell.kind === 'value' ? toMinorUnits(coreChargeCell.value) : null\n const coreChargeMinor =\n coreChargeMinorRaw !== null && coreChargeMinorRaw > 0 ? coreChargeMinorRaw : null\n\n const docId = `${codeNormalized}__${params.supplierId}`\n const doc: PartsDocument = {\n doc_id: docId,\n code: codeRaw,\n code_normalized: codeNormalized,\n brand_id: params.brandId,\n brand_slug: params.brandSlug,\n supplier_id: params.supplierId,\n supplier_display_name: params.supplierDisplayName,\n net_price_eur: displayPrice,\n gross_price_eur: gross.kind === 'value' ? gross.value : null,\n currency: 'EUR',\n barcode: textOrNull(mapped.barcode),\n name_de: textOrNull(mapped.name_de),\n name_en: textOrNull(mapped.name_en),\n name_es: textOrNull(mapped.name_es),\n name_fr: textOrNull(mapped.name_fr),\n name_it: textOrNull(mapped.name_it),\n name_nl: textOrNull(mapped.name_nl),\n name_pt: textOrNull(mapped.name_pt),\n name_ro: textOrNull(mapped.name_ro),\n description1: textOrNull(mapped.description1),\n description2: textOrNull(mapped.description2),\n // commerce-demo: list price → minor units; group + code passthroughs.\n list_price_minor: listMinor,\n discount_group: discountGroup,\n superseding_code: textOrNull(mapped.superseding_code),\n // Derived purchase cost (PR4 — direct net or two-file list × (1 − d)); null = cost pending.\n purchase_price_minor: purchasePriceMinor,\n // Core charge (PR7, Encoding A column) — or all-null when this row has none.\n ...coreChargeFields(coreChargeMinor),\n import_batch_id: params.importBatchId,\n imported_at: new Date().toISOString(),\n }\n\n return {\n kind: 'success',\n id: docId,\n doc,\n ...(warnings.length > 0 && { warnings }),\n ...(pairs.length > 0 && { pairs }),\n }\n },\n}\n"],"mappings":"wBA6BA,MAAM,EAAmB,kBAkBzB,SAAgB,EAAY,EAAa,EAAqC,CAC5E,IAAM,EAAU,EAAI,KAAK,EACzB,GAAI,IAAY,IAAM,EAAQ,YAAY,IAAM,KAAM,OAAO,KAE7D,GAAM,CAAE,UAAS,aAAc,EAC3B,EAAI,EAOR,GALI,IAAc,KAAI,EAAI,EAAE,MAAM,CAAS,CAAC,CAAC,KAAK,EAAE,GAKhD,IAAY,IAAK,CACnB,GAAI,EAAE,SAAS,GAAG,EAAG,MAAO,KAC5B,EAAI,EAAE,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,CAC3B,MAEE,GAAI,EAAE,SAAS,GAAG,EAAG,MAAO,KAI9B,OADK,EAAiB,KAAK,CAAC,EACrB,OAAO,WAAW,CAAC,EADY,GAExC,CASA,SAAgB,EAAa,EAAuB,CAClD,OAAO,KAAK,MAAM,EAAQ,GAAG,CAC/B,CAwBA,SAAgB,EAAoB,EAA0B,CAC5D,IAAM,EAAU,EAAE,KAAK,EACvB,GAAI,IAAY,IAAM,EAAQ,YAAY,IAAM,KAAM,OAAO,KAC7D,IAAM,EAAW,EAAQ,SAAS,GAAG,EAC/B,EAAS,EAAQ,SAAS,GAAG,EAC/B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,EAAW,EAAO,OAAO,EAClC,QAAS,EAAW,EAAO,OAAO,EAClC,QAAS,EAAW,EAAO,OAAO,EAClC,aAAc,EAAW,EAAO,YAAY,EAC5C,aAAc,EAAW,EAAO,YAAY,EAE5C,iBAAkB,EAClB,eAAgB,EAChB,iBAAkB,EAAW,EAAO,gBAAgB,EAEpD,qBAAsB,EAEtB,GAAG,EAAiB,CAAe,EACnC,gBAAiB,EAAO,cACxB,YAAa,IAAI,KAAK,CAAA,CAAE,YAAY,CAMlC,EACF,GAAI,EAAS,OAAS,GAAK,CAAE,UAAS,EACtC,GAAI,EAAM,OAAS,GAAK,CAAE,OAAM,CAClC,CACF,CACF"}
1
+ {"version":3,"file":"parts-schema-BBUINSdN.mjs","names":[],"sources":["../src/mapping/number-format.ts","../src/mapping/column-transforms.ts","../src/mapping/engine.ts","../src/mapping/target-schema.ts","../src/mapping/parts-schema.ts"],"sourcesContent":["/**\n * Number parsing for the configurable mapping engine (commerce-demo phase 02).\n *\n * Real supplier feeds (R03) disagree on decimal AND thousands separators:\n * `55.02` (dot decimal), `326,88` (comma decimal), `1.234,56` (EU\n * thousands+decimal), `1,234.56` (US), `1 234,56` (space-grouped). The mapping\n * stores an explicit `{ decimal, thousands }` per profile so there is no guessing\n * — `parseNumber` trusts the configured format.\n *\n * Two parsers live here:\n * - `parseNumber(raw, format)` — the format-driven parser used by the generic\n * `number` per-column transform.\n * - `parseEuropeanNumber(raw)` — the carmaker-feed legacy parser (comma decimal,\n * dot thousands, **bare-dot rejected as ambiguous**). Carries the carmaker feed's\n * documented format with two intentional broadenings vs the old inline parser:\n * it trims surrounding whitespace, and returns `null` (not `NaN`) for an empty /\n * `'NA'` cell so both number ops share absent-vs-malformed semantics. The\n * carmaker doc-shape suite (27 tests) is the regression net.\n */\n\n/** Separator config for {@link parseNumber}. Stored per `import_mapping`. */\nexport interface NumberFormat {\n /** Decimal separator. */\n decimal: '.' | ','\n /** Thousands grouping separator. `''` = none. */\n thousands: '' | '.' | ',' | ' '\n}\n\n/** Post-cleanup numeric form: optional sign, digits, optional single decimal. */\nconst STRICT_NUMBER_RE = /^-?\\d+(\\.\\d+)?$/\n\n/**\n * Parse a feed cell into a number using an EXPLICIT `{ decimal, thousands }`\n * format. No ambiguity: thousands separators are stripped, the decimal separator\n * is normalised to `.`, and the result is strict-validated.\n *\n * Returns:\n * - `null` for an empty / `'NA'` cell (a legitimately-absent value — the caller\n * decides whether that's allowed for a given target field).\n * - `NaN` for a non-empty but unparseable cell (malformed — the caller surfaces\n * a row-level error rather than coercing to 0).\n * - the parsed number otherwise.\n *\n * A character that is neither a digit, the configured decimal, the configured\n * thousands separator, nor a leading `-` makes the cell unparseable (`NaN`) —\n * e.g. a literal `.` when the format's decimal is `,` and thousands is not `.`.\n */\nexport function parseNumber(raw: string, format: NumberFormat): number | null {\n const trimmed = raw.trim()\n if (trimmed === '' || trimmed.toUpperCase() === 'NA') return null\n\n const { decimal, thousands } = format\n let s = trimmed\n // 1. Remove every thousands separator (when one is configured).\n if (thousands !== '') s = s.split(thousands).join('')\n\n // 2. Normalise the decimal separator to `.`. After thousands removal, the\n // \"other\" separator must not appear — if it does, the cell doesn't match\n // the declared format and is unparseable.\n if (decimal === ',') {\n if (s.includes('.')) return Number.NaN\n s = s.split(',').join('.')\n } else {\n // decimal === '.'\n if (s.includes(',')) return Number.NaN\n }\n\n if (!STRICT_NUMBER_RE.test(s)) return Number.NaN\n return Number.parseFloat(s)\n}\n\n/**\n * Convert a major-unit money value (e.g. `55.02` EUR) to integer MINOR units\n * (`5502`). Rounds to the nearest cent to absorb float drift. The commerce-demo\n * PartsDocument money fields (`list_price_minor`, `purchase_price_minor`,\n * `core_charge_minor`) are integer minor units so derived prices (PR4) don't\n * accrue rounding error — see F003 in progress.md.\n */\nexport function toMinorUnits(value: number): number {\n return Math.round(value * 100)\n}\n\n/**\n * Parse a European-formatted decimal: `,` is the decimal separator, `.` is the\n * (optional) thousands separator. Returns `null` for an empty / `'NA'` cell and\n * `NaN` on unparseable (malformed) input.\n *\n * This is the carmaker-feed legacy parser, preserved from the hardcoded transform.\n * Crucially it **rejects bare-dot** input (`1.98`, `1.234`) as ambiguous rather\n * than guessing — the carmaker feeds are documented as comma-decimal, and a `.`\n * without a `,` could mean a US-format decimal OR a thousands marker. The\n * format-driven {@link parseNumber} doesn't need this guard (its separators are\n * explicit); the carmaker path keeps it.\n *\n * The `null` (absent) vs `NaN` (malformed) split mirrors {@link parseNumber} so\n * the mapping engine treats both number ops uniformly: a target field's `buildRow`\n * reads `null` as \"not provided\" and `NaN` as \"invalid\". This is what lets the\n * reimplemented carmaker transform keep its `GrossPrice 'NA' → null` behaviour\n * (optional field) while still erroring on a malformed `NetPrice` (required).\n *\n * Cases: `'1,98'`→`1.98`, `'1.234,56'`→`1234.56`, `'5'`→`5`, `'-5,00'`→`-5`,\n * empty / `'NA'` → `null`. Rejected (`NaN`): bare-dot (`'1.98'`, `'1.234'`),\n * trailing junk (`'1,98EUR'`), multiple commas (`'1,2,3'`), other non-numeric.\n */\nexport function parseEuropeanNumber(s: string): number | null {\n const trimmed = s.trim()\n if (trimmed === '' || trimmed.toUpperCase() === 'NA') return null\n const hasComma = trimmed.includes(',')\n const hasDot = trimmed.includes('.')\n let cleaned: string\n if (hasComma && hasDot) {\n // European thousands+decimal: strip every `.`, then swap the (sole) `,` for\n // `.`. The strict regex below catches multi-comma input.\n cleaned = trimmed.replace(/\\./g, '').replace(',', '.')\n } else if (hasComma) {\n cleaned = trimmed.replace(',', '.')\n } else if (hasDot) {\n return Number.NaN\n } else {\n cleaned = trimmed\n }\n if (!STRICT_NUMBER_RE.test(cleaned)) return Number.NaN\n return Number.parseFloat(cleaned)\n}\n","/**\n * Per-column transforms for the mapping engine (commerce-demo phase 02, D005).\n *\n * A **bounded, enum-keyed** library of cleaning operations applied to a source\n * cell before it lands on a target field. This is the security model from R02:\n * transforms are declarative operations with Zod-validated params, NEVER\n * user-supplied executable code. The carmaker feed's logic decomposes exactly\n * into `stripPrefix` + `europeanNumber` (+ the schema's code-normalize).\n *\n * Number-producing ops (`number`, `europeanNumber`) are TERMINAL by convention —\n * they convert the string cell into `number | null`; string ops after them are\n * no-ops. The engine reads the result as `string | number | null` and hands it to\n * the target schema's `buildRow`.\n */\n\nimport { z } from 'zod'\nimport { type NumberFormat, parseEuropeanNumber, parseNumber } from './number-format.js'\n\n/** Max length for a strip-affix value — bounds the param, no ReDoS surface. */\nconst MAX_AFFIX_LEN = 32\n\n/**\n * Discriminated union of bounded transform ops. The TS type is INFERRED from\n * this schema so there's a single source of truth + the snapshot is validated at\n * the engine boundary.\n */\nexport const columnTransformSchema = z.discriminatedUnion('op', [\n z.object({ op: z.literal('trim') }),\n z.object({ op: z.literal('uppercase') }),\n z.object({ op: z.literal('lowercase') }),\n z.object({ op: z.literal('stripPrefix'), value: z.string().min(1).max(MAX_AFFIX_LEN) }),\n z.object({ op: z.literal('stripSuffix'), value: z.string().min(1).max(MAX_AFFIX_LEN) }),\n z.object({ op: z.literal('defaultIfEmpty'), value: z.string().max(255) }),\n z.object({ op: z.literal('number') }),\n z.object({ op: z.literal('europeanNumber') }),\n])\n\n/** One declarative cleaning operation. */\nexport type ColumnTransform = z.infer<typeof columnTransformSchema>\n\n/** The discriminator literal of a {@link ColumnTransform}. */\nexport type ColumnTransformOp = ColumnTransform['op']\n\n/** UI descriptor for one transform op: its key, a label, and whether it takes a `value` param. */\nexport interface ColumnTransformOpDescriptor {\n op: ColumnTransformOp\n label: string\n /** `true` → the op carries a `value` string param (`stripPrefix`/`stripSuffix`/`defaultIfEmpty`). */\n hasValue: boolean\n}\n\n/**\n * Static catalogue of the available per-column transform ops, for the PR3 wizard's\n * transform picker. The ORDER is the suggested UI order; `number`/`europeanNumber`\n * are terminal (see {@link applyColumnTransforms}) and labelled accordingly.\n */\nexport const COLUMN_TRANSFORM_OPS: readonly ColumnTransformOpDescriptor[] = [\n { op: 'trim', label: 'Trim whitespace', hasValue: false },\n { op: 'uppercase', label: 'Uppercase', hasValue: false },\n { op: 'lowercase', label: 'Lowercase', hasValue: false },\n { op: 'stripPrefix', label: 'Strip prefix', hasValue: true },\n { op: 'stripSuffix', label: 'Strip suffix', hasValue: true },\n { op: 'defaultIfEmpty', label: 'Default if empty', hasValue: true },\n { op: 'number', label: 'Parse number (uses number format)', hasValue: false },\n { op: 'europeanNumber', label: 'Parse European number (1.234,56)', hasValue: false },\n] as const\n\n/** The value a column carries as it moves through the transform pipeline. */\nexport type CellValue = string | number | null\n\n/**\n * Apply a transform pipeline to a raw cell, left-to-right. String ops act on the\n * string value; the `number` / `europeanNumber` ops are terminal (convert to\n * `number | null`, with `NaN` for a malformed numeric — the schema's `buildRow`\n * surfaces that as a row error). Once the value is non-string, later string ops\n * pass through unchanged.\n */\nexport function applyColumnTransforms(\n raw: string,\n transforms: readonly ColumnTransform[],\n format: NumberFormat,\n): CellValue {\n let value: CellValue = raw\n for (const t of transforms) {\n if (typeof value !== 'string') {\n // A prior number op already produced number|null — string ops are no-ops\n // past this point (number ops are terminal by convention).\n continue\n }\n switch (t.op) {\n case 'trim':\n value = value.trim()\n break\n case 'uppercase':\n value = value.toUpperCase()\n break\n case 'lowercase':\n value = value.toLowerCase()\n break\n case 'stripPrefix':\n value = value.startsWith(t.value) ? value.slice(t.value.length) : value\n break\n case 'stripSuffix':\n value = value.endsWith(t.value) ? value.slice(0, value.length - t.value.length) : value\n break\n case 'defaultIfEmpty':\n value = value.trim() === '' ? t.value : value\n break\n case 'number':\n value = parseNumber(value, format)\n break\n case 'europeanNumber':\n value = parseEuropeanNumber(value)\n break\n }\n }\n return value\n}\n","/**\n * Mapping engine (commerce-demo phase 02, D005).\n *\n * Turns a declarative `MappingConfig` (which source column → which whitelisted\n * target field, plus per-column transforms + a number format) into a\n * `RowTransform` the existing runner drives. The pipeline per row is:\n *\n * raw cells → applyColumnTransforms(per column) → MappedRow → schema.buildRow\n *\n * Two whitelists guard the boundary (R02 injection model): the `target_schema`\n * name resolves to a registered `TargetSchema`, and every `column_map[].target`\n * must be one of that schema's fields — enforced here at build time (throws),\n * before any row is processed.\n *\n * `resolveMapping` implements the D002 most-specific ladder used at enqueue time\n * to pick the `(supplier, brand)` mapping over the `(supplier, NULL)` default.\n */\n\nimport { z } from 'zod'\nimport type { RowTransform } from '../transform.js'\nimport { applyColumnTransforms, columnTransformSchema } from './column-transforms.js'\nimport type { MappedRow, TargetSchema } from './target-schema.js'\n\n/** One column-map entry. `target` is checked against the schema whitelist separately. */\nexport const mappingColumnSchema = z.object({\n /** Source header name (or positional index string for headerless feeds). */\n source: z.string().min(1).max(256),\n /** Target field key — must be in the chosen schema's whitelist (enforced in `buildMappingTransform`). */\n target: z.string().min(1).max(64),\n /** Ordered per-column cleaning ops. Defaults to none. */\n transforms: z.array(columnTransformSchema).default([]),\n})\nexport type MappingColumn = z.infer<typeof mappingColumnSchema>\n\n/**\n * Decimal + thousands separators for the `number` transform.\n *\n * The two MUST differ: `parseNumber` strips every thousands separator FIRST, so a\n * config where `decimal === thousands` (e.g. both `,`) would strip the decimal\n * separator too — `326,88` → `32688`, a silent 100× error rather than a row error.\n * Rejected at save (`assertValidMapping`) AND at run (`mappingConfigSchema`).\n */\nexport const numberFormatSchema = z\n .object({\n decimal: z.enum(['.', ',']),\n thousands: z.enum(['', '.', ',', ' ']),\n })\n .refine((f) => f.decimal !== f.thousands, {\n message: 'decimal and thousands separators must differ',\n path: ['thousands'],\n })\n\n/**\n * The portable mapping config — the subset of an `import_mapping` row the engine\n * needs. The enqueuer SNAPSHOTS this into `import_run.params.mapping` so a run\n * records the exact mapping it used (reproducible) and the transform stays a pure\n * function of `(row, ctx)` with no per-row DB I/O.\n */\nexport const mappingConfigSchema = z.object({\n targetSchema: z.string().min(1).max(64),\n numberFormat: numberFormatSchema,\n columnMap: z.array(mappingColumnSchema),\n})\nexport type MappingConfig = z.infer<typeof mappingConfigSchema>\n\n/**\n * Build a `RowTransform` from a validated mapping config + its target schema.\n *\n * Throws at BUILD time if any `column_map` target is outside the schema's\n * whitelist (deny-by-default, R02) — so a misconfigured mapping fails loudly\n * before a single row is written, rather than silently dropping a column.\n *\n * Generic over the schema's output type, so passing the concrete `partsSchema`\n * yields a `RowTransform<PartsDocument>` (the carmaker path keeps its typing); the\n * registry-resolved `TargetSchema<unknown>` yields `RowTransform<unknown>` (the\n * `commerce:mapping` path, where the output type isn't known until runtime).\n */\nexport function buildMappingTransform<TOut>(\n config: MappingConfig,\n schema: TargetSchema<TOut>,\n): RowTransform<TOut> {\n const allowed = new Set(schema.fields.map((f) => f.key))\n for (const col of config.columnMap) {\n if (!allowed.has(col.target)) {\n throw new Error(\n `Mapping target \"${col.target}\" is not a field of schema \"${schema.name}\" ` +\n `(allowed: ${[...allowed].join(', ')})`,\n )\n }\n }\n\n const format = config.numberFormat\n const columnMap = config.columnMap\n\n return async (row, ctx) => {\n const mapped: MappedRow = {}\n for (const col of columnMap) {\n // `source` is read as data from the parsed row map — never used as a key\n // into framework objects (R02). A missing source column yields `''`.\n const raw = row[col.source] ?? ''\n mapped[col.target] = applyColumnTransforms(raw, col.transforms, format)\n }\n return schema.buildRow(mapped, {\n importRunId: ctx.importRunId,\n rowNumber: ctx.rowNumber,\n params: ctx.params,\n })\n }\n}\n\n/** The minimal shape `resolveMapping` needs — satisfied by an `import_mapping` row or a test fixture. */\nexport interface ResolvableMapping {\n /** `null` = supplier default (applies to all brands). */\n brandId: string | null\n active: boolean\n}\n\n/**\n * Most-specific resolution (D002 ladder): given the candidate mappings for one\n * `(supplier, target_schema)` and the requested brand, return the brand-specific\n * mapping if one exists, else the supplier-default (`brandId === null`). Inactive\n * mappings are skipped. Returns `undefined` when nothing matches.\n */\nexport function resolveMapping<M extends ResolvableMapping>(\n mappings: readonly M[],\n brandId: string | null,\n): M | undefined {\n const active = mappings.filter((m) => m.active)\n if (brandId !== null) {\n const specific = active.find((m) => m.brandId === brandId)\n if (specific) return specific\n }\n return active.find((m) => m.brandId === null)\n}\n","/**\n * TargetSchema — the contract a mapping writes INTO (commerce-demo phase 02, D005).\n *\n * A mapping's `column_map` points source columns at a schema's whitelisted target\n * fields; the engine applies the per-column transforms to build a `MappedRow`, then\n * hands it to `schema.buildRow` to produce the typed output document (an ES\n * `PartsDocument` for `parts`, a discount row for `discount_table`).\n *\n * The `fields` list is the SECOND injection-boundary whitelist (the first is the\n * registered schema name): a `column_map` entry whose `target` is not a field key\n * here is rejected at validation time (R02). Two schemas ship in PR2 — `parts` and\n * `discount_table`.\n */\n\nimport type { RowResult } from '../transform.js'\nimport type { CellValue } from './column-transforms.js'\n\n/** One whitelisted target field on a schema. */\nexport interface TargetField {\n /** Stable target key referenced by `column_map[].target`. */\n key: string\n /** Human label for the wizard dropdown (PR3). */\n label: string\n /** Whether a mapping for this schema MUST include this target. */\n required: boolean\n /** Coarse type — drives the wizard's transform suggestions; `buildRow` does the real coercion. */\n type: 'string' | 'number'\n /**\n * Header spellings this field should be SUGGESTED for when the wizard auto-assigns a freshly\n * previewed file. Purely advisory: the operator can always override, and nothing here widens\n * the injection-boundary whitelist — `key` remains the only accepted `column_map[].target`.\n *\n * Real feeds do not name their columns after our keys (a supplier ships `partno`, `VARUOSA\n * KOOD`, `ArticleName`, never `code`), so without aliases the wizard suggests nothing for the\n * columns that matter and the operator has to know the schema by heart. `describeTargetSchemas`\n * ships this to the wizard verbatim, so a field's synonyms live next to the field itself\n * rather than in a lookup table on the client.\n *\n * Only add a spelling whose meaning is UNAMBIGUOUS. An alias is a silent decision applied to\n * somebody's catalogue — see the supersession fields below, where two spellings that both read\n * as \"replacement\" denote opposite directions and are therefore deliberately absent.\n */\n aliases?: readonly string[]\n}\n\n/** The per-row product of the engine: target field key → cleaned value. */\nexport type MappedRow = Record<string, CellValue>\n\n/** Per-row context handed to `buildRow`. `params` is the opaque per-run params object. */\nexport interface BuildRowContext {\n importRunId: string\n rowNumber: number\n /**\n * Opaque per-run params (the parts schema reads brand/supplier identity from\n * it; `discount_table` ignores it). The schema validates the shape it needs.\n */\n params: Record<string, unknown>\n}\n\n/** A registered target schema: a whitelist + a row builder. */\nexport interface TargetSchema<TOut> {\n /** Registered name — also the `import_mapping.target_schema` value. */\n name: string\n /** The target-field whitelist (injection boundary). */\n fields: readonly TargetField[]\n /** Build a typed output (success) / skip / error from a mapped row. */\n buildRow(mapped: MappedRow, ctx: BuildRowContext): RowResult<TOut>\n}\n\n// ---------------------------------------------------------------------------\n// Shared `buildRow` helpers (used by every concrete schema).\n// ---------------------------------------------------------------------------\n\n/**\n * A nullable text cell → trimmed string, or `null` for empty / non-string. Accepts\n * `undefined` (an UNMAPPED target — indexed access under `noUncheckedIndexedAccess`)\n * and treats it as absent.\n */\nexport function textOrNull(v: CellValue | undefined): string | null {\n if (typeof v !== 'string') return null\n const t = v.trim()\n return t === '' ? null : t\n}\n\n/** The three outcomes a `number` / `europeanNumber` op produces for a cell. */\nexport type NumberOutcome =\n | { kind: 'value'; value: number }\n | { kind: 'absent' }\n | { kind: 'invalid' }\n\n/**\n * Classify a cell that should hold a number. `undefined` (unmapped) / `null` →\n * absent; a real number → value (`NaN` → invalid); a non-empty raw string (no\n * number op declared) → invalid; a blank raw string → absent.\n */\nexport function numberCell(v: CellValue | undefined): NumberOutcome {\n if (v === undefined || v === null) return { kind: 'absent' }\n if (typeof v === 'number') {\n return Number.isNaN(v) ? { kind: 'invalid' } : { kind: 'value', value: v }\n }\n return v.trim() === '' ? { kind: 'absent' } : { kind: 'invalid' }\n}\n\n/** Build a `RowResult` error variant (assignable to any `TargetSchema<TOut>`). */\nexport function rowError(errorType: string, message: string, field: string) {\n return { kind: 'error' as const, error: { errorType, message, field } }\n}\n","/**\n * `parts` target schema — maps a cleaned feed row into the ES `PartsDocument`\n * (commerce-demo phase 02, D005). This is the SHARED assembly + validation logic\n * the reimplemented carmaker transform and every operator-built `parts` mapping\n * run through, so the row taxonomy (code normalization, currency gate, price\n * validation) is uniform across all supplier feeds.\n *\n * **Field coverage.** This schema populates the direct passthroughs (the existing\n * `PartsDocument` columns plus `list_price_minor`, `discount_group`,\n * `superseding_code`) AND the DERIVED `purchase_price_minor` (PR4 — direct net, or\n * two-file `list × (1 − groupDiscount)` resolved from `params.discountGroups`). Core\n * charge (Korpusetasu, PR7, D004) has TWO encodings → one `core_charge_minor`:\n * Encoding A is a `surcharge`/`core_charge` COLUMN on the saleable row (written here);\n * Encoding B is a separate `<code>*S` core-fee row that skips the saleable index and\n * emits a doc-patch attaching its deposit to the PARENT part in the runner's phase-2\n * pass. Replacement-pair SIDE EFFECTS (separate entity) are PR6 — emitted from\n * `superseding_code` and/or `replaces_code`, which name the same relationship from\n * opposite ends and are pairs-only (`replaces_code` has no `PartsDocument` column).\n *\n * **Money.** Every money field is integer minor units via `toMinorUnits` (F003), and\n * the two-file derivation stays in minor units end-to-end (no major↔minor\n * round-trip). The legacy `net_price_eur` stays a major-unit float for back-compat:\n * it holds the direct net price, or — for a two-file LIST feed with no direct net —\n * the list price as a display placeholder (the true cost is `purchase_price_minor`).\n *\n * **Cost-pending warning.** A list-only row whose `discount_group` doesn't resolve\n * against `params.discountGroups` is still indexed (list set, `purchase_price_minor`\n * null) and carries a `no_purchase_price` WARNING — not a row error (phase 03 §5).\n */\n\nimport type { PartsDocument } from '@murumets-ee/search-elasticsearch'\nimport { z } from 'zod'\nimport type { DirectionalPair, DocPatch, RowWarning } from '../transform.js'\nimport type { CellValue } from './column-transforms.js'\nimport { toMinorUnits } from './number-format.js'\nimport {\n type BuildRowContext,\n type MappedRow,\n numberCell,\n rowError,\n type TargetField,\n type TargetSchema,\n textOrNull,\n} from './target-schema.js'\n\n/**\n * Params the `parts` schema reads from the run — the per-(supplier, brand)\n * identity resolved at enqueue time. Identical to the carmaker transform's params\n * (the carmaker path re-exports this), so brand/supplier injection + the optional\n * supplier code-prefix strip are validated the same way everywhere.\n */\nexport const partsParamsSchema = z.object({\n brandId: z.string().uuid(),\n brandSlug: z.string().min(1).max(64),\n supplierId: z.string().uuid(),\n supplierDisplayName: z.string().min(1).max(255),\n importBatchId: z.string().uuid(),\n /** Supplier code prefix to strip before normalization (e.g. `'ME-'`). Optional. */\n supplierCodePrefix: z\n .string()\n .max(8)\n .regex(/^[A-Z0-9-]+$/, 'must be uppercase alphanumeric or \"-\"')\n .optional(),\n /**\n * Purchase-discount map for this supplier (commerce-demo PR4, phase 03 §2):\n * `{ groupCode → discountPct }`, resolved from `supplier_discount_group` at\n * enqueue time and snapshotted onto the run so `buildRow` stays a pure function\n * (no per-row DB I/O; `@murumets-ee/imports` stays a leaf). Absent for direct-net\n * suppliers + the carmaker path. Percentages are 0–100 (the entity constrains them).\n */\n discountGroups: z.record(z.string(), z.number().min(0).max(100)).optional(),\n})\nexport type PartsParams = z.infer<typeof partsParamsSchema>\n\n/** Per-run memoization of the parsed params (keyed on the `ctx.params` reference). */\nconst paramsCache = new WeakMap<object, PartsParams>()\n\nfunction resolveParams(raw: Record<string, unknown>): PartsParams {\n const cached = paramsCache.get(raw)\n if (cached) return cached\n const parsed = partsParamsSchema.parse(raw)\n paramsCache.set(raw, parsed)\n return parsed\n}\n\n/** Per-locale display-name target fields (8 locales). */\nconst NAME_LOCALES = ['de', 'en', 'es', 'fr', 'it', 'nl', 'pt', 'ro'] as const\ntype NameLocale = (typeof NAME_LOCALES)[number]\nconst nameKey = (l: NameLocale): `name_${NameLocale}` => `name_${l}`\n\n/**\n * The `parts` target-field whitelist.\n *\n * **On the two supersession fields.** They exist as a PAIR because the direction of a\n * \"replacement\" column cannot be read off its name. TecDoc's data format defines `SupersNo` /\n * `ErsatzNr` as *\"Article ArtNo supersedes Article SupersNo\"* — the column holds the OLD code\n * and the row is current. German `ersetzt durch` and English `replaced by` mean the exact\n * opposite: the column holds the NEW code and the row is obsolete. Both are \"replacement\"\n * words; only the grammatical voice distinguishes them, and a bare noun like `Ersatznummer`\n * carries no voice at all. TecDoc's own SOAP API resolved this by shipping `replacesArticles`\n * and `replacedByArticles` as separate elements rather than one ambiguous field, and that is\n * what these two keys are.\n *\n * Getting it backwards is silent — an inverted feed builds well-formed chains with valid heads\n * and no warnings, and the union-find merge is append-only, so re-importing the right way round\n * does NOT repair it. Hence: no alias in this file is ambiguous about direction, and the\n * genuinely ambiguous spellings (`superseded no`, `Ersatznummer`, `Ersatz-Nr`) are deliberately\n * aliased to NEITHER field, so an operator meeting one has to state the direction rather than\n * inherit a guess.\n */\nconst PARTS_FIELDS: readonly TargetField[] = [\n {\n key: 'code',\n label: 'Code',\n required: true,\n type: 'string',\n // `part no` already covers a `partno` header: aliases are compared as bare alphanumerics,\n // and a header matches on a run of its own tokens, so both spellings reduce to `partno`.\n aliases: [\n 'part no',\n 'part number',\n 'article name',\n 'article no',\n 'article number',\n 'sku',\n 'varuosa kood',\n 'kood',\n 'artikelnummer',\n 'artikel nr',\n ],\n },\n {\n key: 'net_price',\n label: 'Net price',\n required: false,\n type: 'number',\n aliases: ['price', 'net price discount', 'nettopreis', 'netto'],\n },\n {\n key: 'gross_price',\n label: 'Gross price',\n required: false,\n type: 'number',\n aliases: ['bruttopreis', 'brutto'],\n },\n {\n key: 'list_price',\n label: 'List price',\n required: false,\n type: 'number',\n // `JAEHIND KM-TA` is Estonian for \"retail price, VAT-excluded\" (R03 sample A).\n aliases: ['retail price', 'rrp', 'jaehind', 'jaehind km ta', 'listenpreis'],\n },\n {\n key: 'currency',\n label: 'Currency',\n required: false,\n type: 'string',\n aliases: ['currency cd', 'currency code', 'valuuta'],\n },\n {\n key: 'barcode',\n label: 'Barcode',\n required: false,\n type: 'string',\n // `ean code` / `gtin code` are whole-header aliases on purpose: without them a header\n // spelled `EAN Code` matches the bare `code` token and claims the REQUIRED part-code\n // field, because `code` (4 chars) outscores the `ean` alias (3). A whole-header hit\n // outranks any partial run, so naming the compound form settles it.\n aliases: ['ean', 'ean code', 'gtin', 'gtin code', 'triipkood'],\n },\n {\n key: 'description1',\n label: 'Description 1',\n required: false,\n type: 'string',\n aliases: ['description', 'kirjeldus', 'beschreibung'],\n },\n { key: 'description2', label: 'Description 2', required: false, type: 'string' },\n {\n key: 'discount_group',\n label: 'Discount group',\n required: false,\n type: 'string',\n // `TOOTEGRUPP` is Estonian for \"product group\" (R03 sample A), which IS the discount key.\n // A bare `group` is deliberately NOT here: on a parts feed it is as likely an assortment\n // or category group, and a wrong-but-colliding value resolves against\n // `params.discountGroups` and derives a wrong `purchase_price_minor` with no warning at all\n // (only a NON-colliding code raises `no_purchase_price`). A silent money error is worth\n // more than a saved click.\n aliases: ['product group', 'tootegrupp', 'rabattgruppe'],\n },\n {\n /**\n * The NEWER code that supersedes THIS row — the row's own code is the obsolete one.\n * Emits `(this row → the value)`.\n */\n key: 'superseding_code',\n label: 'Replaced by (newer code)',\n required: false,\n type: 'string',\n // Every entry states direction by grammar: a passive (\"replaced by\", \"ersetzt durch\",\n // \"vervangen door\") or a word that means \"the one after\" (\"successor\", \"new code\",\n // \"Nachfolgenummer\"). A bare noun phrase like `replacement code` does NOT — it reads just\n // as easily as \"the code this replaces\" — so it is excluded for the same reason\n // `Ersatznummer` is.\n aliases: [\n 'replaced by',\n 'successor',\n 'successor code',\n 'new code',\n 'ersetzt durch',\n 'wird ersetzt durch',\n 'nachfolgenummer',\n 'vervangen door',\n ],\n },\n {\n /**\n * The OLDER code THIS row supersedes — the row's own code is the current one. Emits the\n * INVERSE pair `(the value → this row)`. This is TecDoc table 204's shape.\n */\n key: 'replaces_code',\n label: 'Replaces (older code)',\n required: false,\n type: 'string',\n // Same rule from the other side: active verbs (\"replaces\", \"supersedes\") or words meaning\n // \"the one before\" (\"predecessor\", \"old code\", \"Vorgängernummer\"). `superseded article` is\n // NOT here — TecDoc reads that phrasing as the old code, but it is the same bare\n // past-participle family as `superseded no`, which this file refuses to auto-assign;\n // excluding one and accepting the other would be incoherent.\n aliases: [\n 'replaces',\n 'supersedes',\n 'old code',\n 'previous code',\n 'predecessor',\n 'vorgaengernummer',\n ],\n },\n // Core charge (Korpusetasu, commerce-demo PR7, D004). Encoding A: a supplier's\n // `surcharge`/`core_charge` COLUMN maps here → this row's deposit. (Encoding B —\n // a separate `<code>*S` row — needs no whitelist field; it's detected on the code.)\n {\n key: 'core_charge',\n label: 'Core charge',\n required: false,\n type: 'number',\n aliases: ['surcharge', 'deposit', 'core deposit', 'korpusetasu', 'pfand'],\n },\n ...NAME_LOCALES.map(\n (l): TargetField => ({\n key: nameKey(l),\n label: `Name (${l})`,\n required: false,\n type: 'string',\n // The carmaker feed ships these as `Description_<LOCALE>` (R03 sample D).\n aliases: [`description ${l}`, `name ${l}`],\n }),\n ),\n] as const\n\nconst NORMALIZE_CODE_RE = /[\\s-]/g\n/**\n * Uppercase + dash/whitespace-stripped (D2). `*`/other chars are preserved (e.g. `*S`\n * markers). EXPORTED so downstream consumers that key off `code_normalized` — the\n * replacement editor (commerce-demo PR6), which normalizes admin-typed codes before\n * matching members — use the IDENTICAL rule (R05 Q7: normalization must match across\n * every code source or merge-on-collision silently fails to collide).\n */\nexport function normalizeCode(s: string): string {\n return s.toUpperCase().replace(NORMALIZE_CODE_RE, '')\n}\n\n/**\n * A supersession cell → one normalized code, or `null` when there is no usable edge end:\n * unmapped, blank, or punctuation-only (a `'---'` placeholder normalizes to the empty string).\n *\n * **The supplier prefix must be stripped here too.** `code_normalized` removes\n * `params.supplierCodePrefix` before normalizing, so a feed that writes `FO-1120698` in its own\n * code column also writes `FO-1091888` in its supersession column. Normalizing one with the\n * prefix and the other without produces an edge between a code that exists in the catalogue and\n * one that never will — the chain builds cleanly and matches nothing, which is indistinguishable\n * from having no supersession data at all.\n */\nfunction normalizeCodeCell(\n cell: CellValue | undefined,\n supplierCodePrefix: string | undefined,\n): string | null {\n const raw = textOrNull(cell)\n if (raw === null) return null\n const stripped =\n supplierCodePrefix && raw.startsWith(supplierCodePrefix)\n ? raw.slice(supplierCodePrefix.length)\n : raw\n const normalized = normalizeCode(stripped)\n return normalized === '' ? null : normalized\n}\n\n/**\n * Two-file purchase price (phase 03 §2): `list × (1 − discountPct/100)`, computed\n * ENTIRELY in integer minor units so no major↔minor round-trip can introduce drift\n * (F003). `listMinor` is already minor units; the result is rounded to the nearest\n * minor unit. Worked (R03 A+B): `5502 × 0.74 = 4071.48 → 4071` (€40.71).\n */\nfunction deriveTwoFilePurchaseMinor(listMinor: number, discountPct: number): number {\n return Math.round(listMinor * (1 - discountPct / 100))\n}\n\n/**\n * The core-charge marker suffix on a NORMALIZED code (D004, SD002). `normalizeCode`\n * uppercases + strips dashes/spaces but PRESERVES `*`, so a `<code>*S` core-fee row\n * arrives here intact — e.g. `1120698*S`. A code ending in `*S` is a core-fee line,\n * not a saleable part (Encoding B).\n */\nconst CORE_FEE_SUFFIX = '*S'\n\n/** The five core-charge doc fields the two encodings write. */\ntype CoreChargeFields = Pick<\n PartsDocument,\n | 'core_charge_minor'\n | 'core_charge_currency'\n | 'core_charge_refundable'\n | 'core_charge_tax_class'\n | 'core_charge_tax_inclusive'\n>\n\n/**\n * The tax-NEUTRAL core-charge block (D004 / D007) for a deposit amount in minor\n * units, or all-null when there's no core charge. EUR (D9) + refundable by default;\n * the imported EU feed amounts are net so `tax_inclusive = false`; `tax_class` stays\n * null — no rate is baked in here, the future pluggable EU/US tax engine maps it (D007).\n */\nfunction coreChargeFields(minor: number | null): CoreChargeFields {\n if (minor === null) {\n return {\n core_charge_minor: null,\n core_charge_currency: null,\n core_charge_refundable: null,\n core_charge_tax_class: null,\n core_charge_tax_inclusive: null,\n }\n }\n return {\n core_charge_minor: minor,\n core_charge_currency: 'EUR',\n core_charge_refundable: true,\n core_charge_tax_class: null,\n core_charge_tax_inclusive: false,\n }\n}\n\n/**\n * The `parts` schema. `buildRow` THROWS on invalid run params (so a misconfigured\n * run surfaces as a transform error, matching the carmaker contract) and returns a\n * typed `RowResult` per row otherwise.\n */\nexport const partsSchema: TargetSchema<PartsDocument> = {\n name: 'parts',\n fields: PARTS_FIELDS,\n buildRow(mapped: MappedRow, ctx: BuildRowContext) {\n const params = resolveParams(ctx.params)\n\n // 1. Code (required) → raw `code` + normalized `code_normalized` + doc id.\n const codeRaw = typeof mapped.code === 'string' ? mapped.code.trim() : ''\n if (!codeRaw) return rowError('missing_code', 'code is empty', 'code')\n const stripped =\n params.supplierCodePrefix && codeRaw.startsWith(params.supplierCodePrefix)\n ? codeRaw.slice(params.supplierCodePrefix.length)\n : codeRaw\n const codeNormalized = normalizeCode(stripped)\n if (!codeNormalized) {\n return rowError(\n 'empty_normalized_code',\n `Code \"${codeRaw}\" is empty after normalization`,\n 'code',\n )\n }\n\n // 2. Currency gate (D9 EUR-only). Unmapped/blank defaults to EUR. Runs BEFORE the\n // `*S` detection so a non-EUR core-fee row is rejected too — Encoding A and B keep\n // the SAME currency contract (a `*S` deposit is never silently coerced to EUR).\n const currencyText = textOrNull(mapped.currency)\n const currency = currencyText ?? 'EUR'\n if (currency !== 'EUR') {\n return rowError(\n 'unsupported_currency',\n `Currency \"${currency}\" not supported (EUR-only)`,\n 'currency',\n )\n }\n\n // 2b. Core-fee line — Encoding B (D004, SD002). A `<code>*S` normalized code is a\n // core-fee MARKER row, not a saleable part: strip the `*S`, take THIS row's net\n // price as the deposit, and emit a doc-patch that attaches it onto the PARENT\n // part's core-charge fields. The row itself SKIPS the saleable index (never a\n // `*S` SKU — D004). The runner applies the patch in a phase-2 pass; a parent\n // that isn't in the import becomes an `orphan_core_charge` warning (never a\n // phantom doc, never a silent drop). A `*S` with no parent code, or no/invalid\n // amount, is a row error.\n if (codeNormalized.endsWith(CORE_FEE_SUFFIX)) {\n const parentNormalized = codeNormalized.slice(0, -CORE_FEE_SUFFIX.length)\n if (!parentNormalized) {\n return rowError(\n 'core_charge_no_parent',\n `Core-fee row \"${codeRaw}\" has no part code before the \"*S\" marker`,\n 'code',\n )\n }\n const deposit = numberCell(mapped.net_price)\n if (deposit.kind === 'invalid') {\n return rowError(\n 'invalid_core_charge',\n 'core-fee (*S) row net_price is not a number',\n 'net_price',\n )\n }\n if (deposit.kind === 'absent') {\n return rowError(\n 'missing_core_charge',\n 'core-fee (*S) row has no net_price to use as the deposit',\n 'net_price',\n )\n }\n // Gate on the MINOR-unit result (a sub-cent value like 0.004 → round to 0):\n // 0 / sub-cent / negative deposit → nothing to attach; drop it without a patch\n // rather than zeroing a parent's core charge.\n const depositMinor = toMinorUnits(deposit.value)\n if (depositMinor <= 0) {\n return { kind: 'skip', reason: 'core_fee_zero' }\n }\n const patch: DocPatch<PartsDocument> = {\n id: `${parentNormalized}__${params.supplierId}`,\n doc: coreChargeFields(depositMinor),\n orphanWarning: {\n warningType: 'orphan_core_charge',\n message: 'core-fee (*S) row references a part not present in this import',\n field: 'code',\n },\n }\n return { kind: 'skip', reason: 'core_charge_marker', patches: [patch] }\n }\n\n // 3. Prices. net/gross/list each: absent → null, invalid → error, value → number.\n const net = numberCell(mapped.net_price)\n if (net.kind === 'invalid')\n return rowError('invalid_net_price', 'net_price is not a number', 'net_price')\n const gross = numberCell(mapped.gross_price)\n if (gross.kind === 'invalid') {\n return rowError('invalid_gross_price', 'gross_price is not a number', 'gross_price')\n }\n const list = numberCell(mapped.list_price)\n if (list.kind === 'invalid')\n return rowError('invalid_list_price', 'list_price is not a number', 'list_price')\n\n const netValue = net.kind === 'value' ? net.value : null\n const listValue = list.kind === 'value' ? list.value : null\n // At least one price must resolve. `net_price_eur` is non-nullable on the doc,\n // so it takes the direct net or — for a list-only two-file feed — the list\n // price as a display placeholder (the true cost is `purchase_price_minor`).\n const displayPrice = netValue ?? listValue\n if (displayPrice === null) {\n return rowError('missing_price', 'no net_price or list_price provided', 'price')\n }\n\n // 4. Purchase-price derivation (phase 03 §2, PR4). All money stays in integer\n // minor units (F003 — never round-trip back to major).\n // - direct net column (R03 C/D) → purchase = net\n // - two-file list × (1 − groupDiscount) → purchase = round(list × (1 − d/100))\n // - neither resolvable → cost pending: index list-only + WARN\n // (a `no_purchase_price` warning, NOT a row error — the part is still indexed).\n const discountGroup = textOrNull(mapped.discount_group)\n const listMinor = listValue === null ? null : toMinorUnits(listValue)\n let purchasePriceMinor: number | null = null\n const warnings: RowWarning[] = []\n if (netValue !== null) {\n purchasePriceMinor = toMinorUnits(netValue)\n } else if (listMinor !== null) {\n // List-only row: resolve the supplier's discount group → derive cost.\n const discountPct =\n discountGroup !== null ? params.discountGroups?.[discountGroup] : undefined\n if (discountPct !== undefined) {\n purchasePriceMinor = deriveTwoFilePurchaseMinor(listMinor, discountPct)\n } else {\n warnings.push({\n warningType: 'no_purchase_price',\n message:\n discountGroup === null\n ? 'list price present but no discount group on the row — cost pending'\n : `no discount group \"${discountGroup}\" configured for this supplier — cost pending`,\n field: 'discount_group',\n })\n }\n }\n\n // 5. Replacement-pair side-output (commerce-demo PR6, SD007). Both supersession columns\n // are SPARSE on a full manufacturer catalogue, and both produce the same\n // `(from = older → to = newer)` edge the chain engine consumes — they differ only in\n // which end of the edge the row itself is:\n // `superseding_code` → the value is NEWER, so the edge runs (this row → value);\n // `replaces_code` → the value is OLDER, so the edge runs (value → this row).\n // Every code is normalized the SAME way as `code_normalized` so the downstream merge\n // collides codes across feeds (R05 Q7). A value that is empty, normalizes to empty\n // (e.g. `'---'`), or self-pairs yields no edge. A row MAY carry both columns — that is\n // a legitimate three-code chain (older → this → newer), not a conflict.\n const pairs: DirectionalPair[] = []\n const supersedingNormalized = normalizeCodeCell(\n mapped.superseding_code,\n params.supplierCodePrefix,\n )\n if (supersedingNormalized !== null && supersedingNormalized !== codeNormalized) {\n pairs.push({ from: codeNormalized, to: supersedingNormalized })\n }\n const replacesNormalized = normalizeCodeCell(mapped.replaces_code, params.supplierCodePrefix)\n if (replacesNormalized !== null && replacesNormalized !== codeNormalized) {\n pairs.push({ from: replacesNormalized, to: codeNormalized })\n }\n\n // 6. Core charge — Encoding A (D004). A `surcharge`/`core_charge` COLUMN on this\n // saleable row is the deposit for THIS part. 0 / empty / absent / sub-cent → no\n // core charge. (Encoding B — a separate `<code>*S` row — is handled at step 1b\n // and attaches to the parent in phase-2, so it never reaches here. In the unusual\n // case a part has BOTH a `core_charge` column AND a sibling `*S` row — suppliers\n // use one encoding — the `*S` phase-2 patch runs after indexing and wins.)\n const coreChargeCell = numberCell(mapped.core_charge)\n if (coreChargeCell.kind === 'invalid') {\n return rowError('invalid_core_charge', 'core_charge is not a number', 'core_charge')\n }\n // Gate on the MINOR-unit result so a sub-cent value (rounds to 0) yields no charge.\n const coreChargeMinorRaw =\n coreChargeCell.kind === 'value' ? toMinorUnits(coreChargeCell.value) : null\n const coreChargeMinor =\n coreChargeMinorRaw !== null && coreChargeMinorRaw > 0 ? coreChargeMinorRaw : null\n\n const docId = `${codeNormalized}__${params.supplierId}`\n const doc: PartsDocument = {\n doc_id: docId,\n code: codeRaw,\n code_normalized: codeNormalized,\n brand_id: params.brandId,\n brand_slug: params.brandSlug,\n supplier_id: params.supplierId,\n supplier_display_name: params.supplierDisplayName,\n net_price_eur: displayPrice,\n gross_price_eur: gross.kind === 'value' ? gross.value : null,\n currency: 'EUR',\n barcode: textOrNull(mapped.barcode),\n name_de: textOrNull(mapped.name_de),\n name_en: textOrNull(mapped.name_en),\n name_es: textOrNull(mapped.name_es),\n name_fr: textOrNull(mapped.name_fr),\n name_it: textOrNull(mapped.name_it),\n name_nl: textOrNull(mapped.name_nl),\n name_pt: textOrNull(mapped.name_pt),\n name_ro: textOrNull(mapped.name_ro),\n description1: textOrNull(mapped.description1),\n description2: textOrNull(mapped.description2),\n // commerce-demo: list price → minor units; group + code passthroughs.\n list_price_minor: listMinor,\n discount_group: discountGroup,\n superseding_code: textOrNull(mapped.superseding_code),\n // Derived purchase cost (PR4 — direct net or two-file list × (1 − d)); null = cost pending.\n purchase_price_minor: purchasePriceMinor,\n // Core charge (PR7, Encoding A column) — or all-null when this row has none.\n ...coreChargeFields(coreChargeMinor),\n import_batch_id: params.importBatchId,\n imported_at: new Date().toISOString(),\n }\n\n return {\n kind: 'success',\n id: docId,\n doc,\n ...(warnings.length > 0 && { warnings }),\n ...(pairs.length > 0 && { pairs }),\n // Value-drift sampling (F010 / #602) — the DERIVED cost, not the raw\n // net/list price, so a decimal-format flip on either the direct-net\n // or two-file source column shows up here regardless of which pricing\n // path this supplier's feed uses. `null` (cost-pending) is omitted,\n // same as `no_purchase_price` warnings already do — the collector\n // counts it toward `nullRate` instead.\n ...(purchasePriceMinor !== null && { priceSample: purchasePriceMinor }),\n }\n },\n}\n"],"mappings":"wBA6BA,MAAM,EAAmB,kBAkBzB,SAAgB,EAAY,EAAa,EAAqC,CAC5E,IAAM,EAAU,EAAI,KAAK,EACzB,GAAI,IAAY,IAAM,EAAQ,YAAY,IAAM,KAAM,OAAO,KAE7D,GAAM,CAAE,UAAS,aAAc,EAC3B,EAAI,EAOR,GALI,IAAc,KAAI,EAAI,EAAE,MAAM,CAAS,CAAC,CAAC,KAAK,EAAE,GAKhD,IAAY,IAAK,CACnB,GAAI,EAAE,SAAS,GAAG,EAAG,MAAO,KAC5B,EAAI,EAAE,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,CAC3B,MAEE,GAAI,EAAE,SAAS,GAAG,EAAG,MAAO,KAI9B,OADK,EAAiB,KAAK,CAAC,EACrB,OAAO,WAAW,CAAC,EADY,GAExC,CASA,SAAgB,EAAa,EAAuB,CAClD,OAAO,KAAK,MAAM,EAAQ,GAAG,CAC/B,CAwBA,SAAgB,EAAoB,EAA0B,CAC5D,IAAM,EAAU,EAAE,KAAK,EACvB,GAAI,IAAY,IAAM,EAAQ,YAAY,IAAM,KAAM,OAAO,KAC7D,IAAM,EAAW,EAAQ,SAAS,GAAG,EAC/B,EAAS,EAAQ,SAAS,GAAG,EAC/B,EACJ,GAAI,GAAY,EAGd,EAAU,EAAQ,QAAQ,MAAO,EAAE,CAAC,CAAC,QAAQ,IAAK,GAAG,OAChD,GAAI,EACT,EAAU,EAAQ,QAAQ,IAAK,GAAG,OAC7B,GAAI,EACT,MAAO,SAEP,GAAU,EAGZ,OADK,EAAiB,KAAK,CAAO,EAC3B,OAAO,WAAW,CAAO,EADY,GAE9C,CCxGA,MAOa,EAAwB,EAAE,mBAAmB,KAAM,CAC9D,EAAE,OAAO,CAAE,GAAI,EAAE,QAAQ,MAAM,CAAE,CAAC,EAClC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