@tokenoftrust/storefront-runner 7.11.10 → 7.12.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.
@@ -2,7 +2,195 @@ import {
2
2
  isPublicCatalogProduct, normalizePurchaseOptions, priceForPurchaseOption, resolveMembershipRule,
3
3
  type CatalogProduct, type CatalogVariant, type TenantConfig,
4
4
  } from "@tot/public-runtime";
5
+ import type { Queryable, QueryStatement } from "@/lib/catalog/d1/catalog";
5
6
  import { resolveMemberContext } from "@/lib/membership/eligibility";
7
+ import type { ShopperScope } from "./scope";
8
+
9
+ export interface TierSkuPrice {
10
+ unitMinor: number;
11
+ currency: string;
12
+ }
13
+
14
+ export interface TierSkuPriceRow extends TierSkuPrice {
15
+ sku: string;
16
+ updatedAt: string;
17
+ }
18
+
19
+ export interface TierSkuPriceInput {
20
+ sku: string;
21
+ unitMinor: number;
22
+ currency?: string;
23
+ }
24
+
25
+ const MAX_SKU_LENGTH = 128;
26
+ const MAX_TIER_ID_LENGTH = 128;
27
+ const SKU_QUERY_CHUNK_SIZE = 90;
28
+ const UPSERT_BATCH_CHUNK_SIZE = 50;
29
+ const CURRENCY_RE = /^[A-Z]{3}$/;
30
+ const CONTROL_CHAR_RE = /\p{C}/u;
31
+
32
+ export function normalizePricingSku(raw: unknown): string | null {
33
+ if (typeof raw !== "string") return null;
34
+ const trimmed = raw.trim();
35
+ if (!trimmed || trimmed.length > MAX_SKU_LENGTH || CONTROL_CHAR_RE.test(trimmed)) return null;
36
+ return trimmed;
37
+ }
38
+
39
+ export function normalizePricingTierId(raw: unknown): string | null {
40
+ if (typeof raw !== "string") return null;
41
+ const trimmed = raw.trim();
42
+ if (!trimmed || trimmed.length > MAX_TIER_ID_LENGTH || CONTROL_CHAR_RE.test(trimmed)) return null;
43
+ return trimmed;
44
+ }
45
+
46
+ export function normalizePricingCurrency(raw: unknown): string | null {
47
+ if (raw === undefined) return "USD";
48
+ if (typeof raw !== "string" || !CURRENCY_RE.test(raw)) return null;
49
+ return raw;
50
+ }
51
+
52
+ export function normalizeTierSkuPriceInput(entry: unknown): { sku: string; unitMinor: number; currency: string } | null {
53
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) return null;
54
+ const record = entry as Record<string, unknown>;
55
+ for (const key of Object.keys(record)) {
56
+ if (key !== "sku" && key !== "unitMinor" && key !== "currency") return null;
57
+ }
58
+ const sku = normalizePricingSku(record.sku);
59
+ if (!sku) return null;
60
+ if (typeof record.unitMinor !== "number" || !Number.isSafeInteger(record.unitMinor) || record.unitMinor < 0) {
61
+ return null;
62
+ }
63
+ const currency = normalizePricingCurrency(record.currency);
64
+ if (!currency) return null;
65
+ return { sku, unitMinor: record.unitMinor, currency };
66
+ }
67
+
68
+ export async function readTierSkuPrices(
69
+ db: Queryable,
70
+ scope: ShopperScope,
71
+ tierId: string,
72
+ skus?: readonly string[],
73
+ ): Promise<Map<string, TierSkuPrice>> {
74
+ const normalizedTier = normalizePricingTierId(tierId);
75
+ const out = new Map<string, TierSkuPrice>();
76
+ if (!normalizedTier) return out;
77
+
78
+ if (skus === undefined) {
79
+ const rows = await db.all<{ sku: string; unit_minor: number; currency: string }>(
80
+ `SELECT sku, unit_minor, currency
81
+ FROM shopper_tier_sku_prices
82
+ WHERE tenant_id = ? AND stage = ? AND tier_id = ?
83
+ ORDER BY sku ASC`,
84
+ scope.tenantId, scope.stage, normalizedTier,
85
+ );
86
+ for (const row of rows) {
87
+ out.set(row.sku, { unitMinor: row.unit_minor, currency: row.currency });
88
+ }
89
+ return out;
90
+ }
91
+
92
+ const uniqueSkus: string[] = [];
93
+ const seen = new Set<string>();
94
+ for (const rawSku of skus) {
95
+ const sku = normalizePricingSku(rawSku);
96
+ if (sku && !seen.has(sku)) {
97
+ seen.add(sku);
98
+ uniqueSkus.push(sku);
99
+ }
100
+ }
101
+ if (uniqueSkus.length === 0) return out;
102
+
103
+ for (let offset = 0; offset < uniqueSkus.length; offset += SKU_QUERY_CHUNK_SIZE) {
104
+ const chunk = uniqueSkus.slice(offset, offset + SKU_QUERY_CHUNK_SIZE);
105
+ const placeholders = chunk.map(() => "?").join(", ");
106
+ const rows = await db.all<{ sku: string; unit_minor: number; currency: string }>(
107
+ `SELECT sku, unit_minor, currency
108
+ FROM shopper_tier_sku_prices
109
+ WHERE tenant_id = ? AND stage = ? AND tier_id = ? AND sku IN (${placeholders})`,
110
+ scope.tenantId, scope.stage, normalizedTier, ...chunk,
111
+ );
112
+ for (const row of rows) {
113
+ out.set(row.sku, { unitMinor: row.unit_minor, currency: row.currency });
114
+ }
115
+ }
116
+ return out;
117
+ }
118
+
119
+ export async function listTierSkuPrices(
120
+ db: Queryable,
121
+ scope: ShopperScope,
122
+ tierId: string,
123
+ ): Promise<TierSkuPriceRow[]> {
124
+ const normalizedTier = normalizePricingTierId(tierId);
125
+ if (!normalizedTier) return [];
126
+ return db.all<TierSkuPriceRow>(
127
+ `SELECT sku, unit_minor AS unitMinor, currency, updated_at AS updatedAt
128
+ FROM shopper_tier_sku_prices
129
+ WHERE tenant_id = ? AND stage = ? AND tier_id = ?
130
+ ORDER BY sku ASC`,
131
+ scope.tenantId, scope.stage, normalizedTier,
132
+ );
133
+ }
134
+
135
+ export async function upsertTierSkuPrices(
136
+ db: Queryable,
137
+ scope: ShopperScope,
138
+ tierId: string,
139
+ entries: readonly TierSkuPriceInput[],
140
+ nowIso = new Date().toISOString(),
141
+ ): Promise<number> {
142
+ const normalizedTier = normalizePricingTierId(tierId);
143
+ if (!normalizedTier) throw new Error("invalid_tier_id");
144
+
145
+ const normalized: { sku: string; unitMinor: number; currency: string }[] = [];
146
+ for (const entry of entries) {
147
+ const parsed = normalizeTierSkuPriceInput(entry);
148
+ if (!parsed) throw new Error("invalid_sku_price");
149
+ normalized.push(parsed);
150
+ }
151
+ if (normalized.length === 0) return 0;
152
+
153
+ const sql = `INSERT INTO shopper_tier_sku_prices (tenant_id, stage, tier_id, sku, unit_minor, currency, updated_at)
154
+ VALUES (?, ?, ?, ?, ?, ?, ?)
155
+ ON CONFLICT (tenant_id, stage, tier_id, sku) DO UPDATE SET
156
+ unit_minor = excluded.unit_minor,
157
+ currency = excluded.currency,
158
+ updated_at = excluded.updated_at`;
159
+
160
+ const statements: QueryStatement[] = normalized.map(entry => ({
161
+ sql,
162
+ params: [scope.tenantId, scope.stage, normalizedTier, entry.sku, entry.unitMinor, entry.currency, nowIso],
163
+ }));
164
+
165
+ if (db.batch) {
166
+ for (let offset = 0; offset < statements.length; offset += UPSERT_BATCH_CHUNK_SIZE) {
167
+ await db.batch(statements.slice(offset, offset + UPSERT_BATCH_CHUNK_SIZE));
168
+ }
169
+ } else {
170
+ for (const statement of statements) {
171
+ await db.run(statement.sql, ...(statement.params ?? []));
172
+ }
173
+ }
174
+ return normalized.length;
175
+ }
176
+
177
+ export async function deleteTierSkuPrice(
178
+ db: Queryable,
179
+ scope: ShopperScope,
180
+ tierId: string,
181
+ sku: string,
182
+ ): Promise<boolean> {
183
+ const normalizedTier = normalizePricingTierId(tierId);
184
+ const normalizedSku = normalizePricingSku(sku);
185
+ if (!normalizedTier || !normalizedSku) return false;
186
+ const deleted = await db.first<{ sku: string }>(
187
+ `DELETE FROM shopper_tier_sku_prices
188
+ WHERE tenant_id = ? AND stage = ? AND tier_id = ? AND sku = ?
189
+ RETURNING sku`,
190
+ scope.tenantId, scope.stage, normalizedTier, normalizedSku,
191
+ );
192
+ return deleted !== null;
193
+ }
6
194
 
7
195
  export function shopperTierAvailable(tenant: TenantConfig, tierId: string): boolean {
8
196
  return resolveMembershipRule(resolveMemberContext({ memberTierId: tierId }), tenant.commerce?.membership) !== undefined;
@@ -12,10 +200,38 @@ export function shopperCatalogProduct(tenant: TenantConfig, product: CatalogProd
12
200
  return !!product && !!tenant.tot_data_scope && product.tenant_id === tenant.tot_data_scope && isPublicCatalogProduct(product);
13
201
  }
14
202
 
15
- export function shopperVariantPrice(tenant: TenantConfig, product: CatalogProduct, variant: CatalogVariant, tierId: string | null) {
203
+ export function shopperVariantPrice(
204
+ tenant: TenantConfig,
205
+ product: CatalogProduct,
206
+ variant: CatalogVariant,
207
+ tierId: string | null,
208
+ skuOverrides?: ReadonlyMap<string, TierSkuPrice>,
209
+ ) {
16
210
  if (tierId && !shopperTierAvailable(tenant, tierId)) return null;
17
211
  const option = normalizePurchaseOptions(product).find(candidate => candidate.kind === "one_time");
18
212
  if (!option || variant.product_id !== product.id || variant.tenant_id !== product.tenant_id) return null;
213
+
214
+ if (tierId && variant.sku && skuOverrides) {
215
+ const override = skuOverrides.get(variant.sku);
216
+ if (
217
+ override &&
218
+ override.currency.toUpperCase() === variant.currency.toUpperCase() &&
219
+ Number.isSafeInteger(override.unitMinor) &&
220
+ override.unitMinor >= 0
221
+ ) {
222
+ const price = override.unitMinor / 100;
223
+ const compareAtPrice = variant.price > price ? variant.price : (variant.compare_at_price ?? null);
224
+ return {
225
+ id: variant.id,
226
+ title: variant.title,
227
+ available: variant.inventory.available,
228
+ price,
229
+ compareAtPrice,
230
+ currency: variant.currency,
231
+ };
232
+ }
233
+ }
234
+
19
235
  const priced = priceForPurchaseOption(variant.price, option, {
20
236
  member: resolveMemberContext({ memberTierId: tierId }),
21
237
  program: tenant.commerce?.membership,
@@ -15,7 +15,7 @@ type PortalMutation = Extract<ShopperPortalAdmission, `${string}-mutation`>;
15
15
  export type ShopperRouteAdmission = {
16
16
  GET?: Exclude<ShopperAdmissionClass, "shopper-origin" | "shopper-owner-mutation" | PortalMutation>;
17
17
  POST?: Extract<ShopperAdmissionClass, "shopper-origin" | "shopper-owner-mutation" | PortalMutation>;
18
- DELETE?: PortalMutation;
18
+ DELETE?: Extract<ShopperAdmissionClass, "shopper-owner-mutation" | PortalMutation>;
19
19
  };
20
20
 
21
21
  export interface ShopperScope {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "7.11.10",
3
+ "version": "7.12.0",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
6
6
  "packageManager": "pnpm@11.9.0",
@@ -40,6 +40,7 @@
40
40
  "./pool-asset-headers": "./src/pool-asset-headers.ts",
41
41
  "./catalog-files": "./src/catalog-files.ts",
42
42
  "./sku": "./src/sku.ts",
43
+ "./paste-order-list": "./src/catalog/paste-order-list.ts",
43
44
  "./embed-catalog": "./src/embed-catalog.mjs",
44
45
  "./retention-holds": "./src/retention-holds.ts",
45
46
  "./publication-content-redirects": "./src/publication-content-redirects.ts",
@@ -0,0 +1,551 @@
1
+ /**
2
+ * Deterministic-first Paste-a-List wholesale ordering parser & catalog matcher.
3
+ *
4
+ * Pure, edge-safe module (no Node APIs) that parses free-text wholesale order
5
+ * lists into structured quantity + query lines, matches them deterministically
6
+ * against active catalog products & variants, surfaces matched / ambiguous /
7
+ * unmatched outcomes, and aggregates matched lines into a cart batch.
8
+ */
9
+ import type { CatalogProduct, CatalogVariant } from "../product.js";
10
+ import { isPublicCatalogProduct } from "../product.js";
11
+ import { cartLineKey, MAX_CART_QUANTITY } from "../checkout.js";
12
+
13
+ /** Maximum accepted raw text payload (16 KiB). */
14
+ export const PASTE_ORDER_MAX_INPUT_BYTES = 16_384;
15
+
16
+ /** Maximum number of candidates surfaced for an ambiguous line. */
17
+ export const PASTE_ORDER_MAX_CANDIDATES = 5;
18
+
19
+ const MIN_FUZZY_SCORE = 0.55;
20
+ const MIN_QUERY_COVERAGE = 0.5;
21
+ const AMBIGUITY_MARGIN = 0.08;
22
+
23
+ const UNIT_ONLY_RE = /^(?:mg|ml|oz|g|kg|lb|lbs|ct|pk|pack|packs|box|boxes|case|cases)$/i;
24
+ const MEASURE_JOIN_RE = /(\d+)\s+(mg|ml|oz|g|kg|ct|pk)\b/gi;
25
+ const DEFAULT_VARIANT_TITLE = "default title";
26
+
27
+ export interface ParsedOrderLine {
28
+ /** 1-based index among non-empty parsed lines. */
29
+ lineNumber: number;
30
+ /** Trimmed raw segment before quantity extraction. */
31
+ rawLine: string;
32
+ /** Positive integer quantity clamped to 1..MAX_CART_QUANTITY. */
33
+ quantity: number;
34
+ /** True when the input explicitly stated a quantity; false when defaulted to 1. */
35
+ quantityExplicit: boolean;
36
+ /** Cleaned product/variant/SKU search query. */
37
+ query: string;
38
+ }
39
+
40
+ export type PasteOrderMatchKind = "sku" | "fuzzy";
41
+
42
+ export interface PasteOrderCandidate {
43
+ productId: string;
44
+ productHandle: string;
45
+ productTitle: string;
46
+ vendor?: string;
47
+ variantId: string;
48
+ variantTitle: string;
49
+ sku?: string;
50
+ lineKey: string;
51
+ optionValues: Record<string, string>;
52
+ /** Omitted when hidePrices is enabled. */
53
+ price?: number;
54
+ currency: string;
55
+ available: boolean;
56
+ /** Deterministic confidence score in [0, 1]. */
57
+ confidence: number;
58
+ matchKind: PasteOrderMatchKind;
59
+ }
60
+
61
+ export type PasteOrderLineStatus = "matched" | "ambiguous" | "unmatched";
62
+
63
+ export interface PasteOrderMatchedLine {
64
+ lineNumber: number;
65
+ rawLine: string;
66
+ query: string;
67
+ quantity: number;
68
+ quantityExplicit: boolean;
69
+ status: PasteOrderLineStatus;
70
+ /** Set when status === "matched". */
71
+ match?: PasteOrderCandidate;
72
+ /** Top candidate when matched, up to maxCandidates when ambiguous, empty when unmatched. */
73
+ candidates: PasteOrderCandidate[];
74
+ }
75
+
76
+ export interface PasteOrderCartItem {
77
+ productId: string;
78
+ productHandle: string;
79
+ productTitle: string;
80
+ variantId: string;
81
+ variantTitle: string;
82
+ sku?: string;
83
+ lineKey: string;
84
+ quantity: number;
85
+ /** Omitted when hidePrices is enabled. */
86
+ price?: number;
87
+ currency: string;
88
+ available: boolean;
89
+ }
90
+
91
+ export interface PasteOrderMatchResult {
92
+ lines: PasteOrderMatchedLine[];
93
+ matchedCount: number;
94
+ ambiguousCount: number;
95
+ unmatchedCount: number;
96
+ cartItems: PasteOrderCartItem[];
97
+ }
98
+
99
+ export interface MatchPasteOrderOptions {
100
+ /** Omit prices from candidates and cart items (e.g. hidePricesForGuests). */
101
+ hidePrices?: boolean;
102
+ /** Maximum candidates returned for ambiguous lines (default 5). */
103
+ maxCandidates?: number;
104
+ }
105
+
106
+ function clampQuantity(raw: number): number {
107
+ if (!Number.isFinite(raw) || raw < 1) return 1;
108
+ return Math.min(Math.floor(raw), MAX_CART_QUANTITY);
109
+ }
110
+
111
+ /**
112
+ * Split raw free-text input into individual candidate segments.
113
+ * Preserves inline ratios like "50/50" or "VG/PG" by only splitting on `/`
114
+ * when surrounded by whitespace (` / `).
115
+ */
116
+ function splitRawSegments(rawText: string): string[] {
117
+ const normalized = rawText.replace(/\r\n?/g, "\n");
118
+ const segments: string[] = [];
119
+ for (const line of normalized.split("\n")) {
120
+ for (const semiPart of line.split(";")) {
121
+ for (const slashPart of semiPart.split(/\s+\/\s+/)) {
122
+ const cleaned = slashPart
123
+ .trim()
124
+ .replace(/^(?:[-*•▪–—]\s+)+/, "")
125
+ .replace(/^\d+[.)]\s+/, "")
126
+ .trim();
127
+ if (cleaned.length > 0) {
128
+ segments.push(cleaned);
129
+ }
130
+ }
131
+ }
132
+ }
133
+ return segments;
134
+ }
135
+
136
+ function extractQuantityAndQuery(segment: string): {
137
+ quantity: number;
138
+ quantityExplicit: boolean;
139
+ query: string;
140
+ } {
141
+ // 1. Leading "10 x Product", "10x Product", "10 * Product"
142
+ const leadingCross = /^(\d+)\s*[x×*]\s+(.+)$/i.exec(segment);
143
+ if (leadingCross?.[1] && leadingCross[2]) {
144
+ const query = leadingCross[2].trim();
145
+ if (query.length > 0) {
146
+ return { quantity: clampQuantity(Number(leadingCross[1])), quantityExplicit: true, query };
147
+ }
148
+ }
149
+
150
+ // 2. Leading "x 10 Product" / "x10 Product"
151
+ const leadingXFirst = /^[x×]\s*(\d+)\s+(.+)$/i.exec(segment);
152
+ if (leadingXFirst?.[1] && leadingXFirst[2]) {
153
+ const query = leadingXFirst[2].trim();
154
+ if (query.length > 0) {
155
+ return { quantity: clampQuantity(Number(leadingXFirst[1])), quantityExplicit: true, query };
156
+ }
157
+ }
158
+
159
+ // 3. Trailing "SKU-123 x 5" / "SKU-123 x5" / "SKU-123 * 5"
160
+ const trailingCross = /^(.+?)\s+[x×*]\s*(\d+)$/i.exec(segment);
161
+ if (trailingCross?.[1] && trailingCross[2]) {
162
+ const query = trailingCross[1].trim();
163
+ if (query.length > 0) {
164
+ return { quantity: clampQuantity(Number(trailingCross[2])), quantityExplicit: true, query };
165
+ }
166
+ }
167
+
168
+ // 4. Trailing "SKU-123 qty 5" / "SKU-123 qty: 5"
169
+ const trailingQtyWord = /^(.+?)\s+(?:qty|quantity)[:=\s]+(\d+)$/i.exec(segment);
170
+ if (trailingQtyWord?.[1] && trailingQtyWord[2]) {
171
+ const query = trailingQtyWord[1].trim();
172
+ if (query.length > 0) {
173
+ return { quantity: clampQuantity(Number(trailingQtyWord[2])), quantityExplicit: true, query };
174
+ }
175
+ }
176
+
177
+ // 5. Trailing "SKU-123, 5"
178
+ const trailingComma = /^(.+?)\s*,\s*(\d+)$/.exec(segment);
179
+ if (trailingComma?.[1] && trailingComma[2]) {
180
+ const query = trailingComma[1].trim();
181
+ if (query.length > 0) {
182
+ return { quantity: clampQuantity(Number(trailingComma[2])), quantityExplicit: true, query };
183
+ }
184
+ }
185
+
186
+ // 6. Trailing "SKU-123 - 5" (requires spaces around dash so hyphenated SKUs stay intact)
187
+ const trailingDash = /^(.+?)\s+[-–—]\s+(\d+)$/.exec(segment);
188
+ if (trailingDash?.[1] && trailingDash[2]) {
189
+ const query = trailingDash[1].trim();
190
+ if (query.length > 0) {
191
+ return { quantity: clampQuantity(Number(trailingDash[2])), quantityExplicit: true, query };
192
+ }
193
+ }
194
+
195
+ // 7. Trailing parenthetical "HorizonTech Pink Lemonade (10)"
196
+ const trailingParens = /^(.+?)\s*\(\s*(\d+)\s*\)$/.exec(segment);
197
+ if (trailingParens?.[1] && trailingParens[2]) {
198
+ const query = trailingParens[1].trim();
199
+ if (query.length > 0) {
200
+ return { quantity: clampQuantity(Number(trailingParens[2])), quantityExplicit: true, query };
201
+ }
202
+ }
203
+
204
+ // 8. Leading bare integer "12 Blue Razz 35mg"
205
+ const leadingNumber = /^(\d+)\s+(.+)$/.exec(segment);
206
+ if (leadingNumber?.[1] && leadingNumber[2]) {
207
+ const query = leadingNumber[2].trim();
208
+ if (query.length > 0 && !UNIT_ONLY_RE.test(query)) {
209
+ return { quantity: clampQuantity(Number(leadingNumber[1])), quantityExplicit: true, query };
210
+ }
211
+ }
212
+
213
+ return { quantity: 1, quantityExplicit: false, query: segment };
214
+ }
215
+
216
+ /**
217
+ * Deterministically parse a free-text wholesale order list into structured lines.
218
+ */
219
+ export function parsePasteOrderList(rawText: string): ParsedOrderLine[] {
220
+ if (!rawText || typeof rawText !== "string") return [];
221
+ const segments = splitRawSegments(rawText);
222
+ return segments.map((rawLine, index) => {
223
+ const { quantity, quantityExplicit, query } = extractQuantityAndQuery(rawLine);
224
+ return {
225
+ lineNumber: index + 1,
226
+ rawLine,
227
+ quantity,
228
+ quantityExplicit,
229
+ query,
230
+ };
231
+ });
232
+ }
233
+
234
+ function tokenize(text: string): string[] {
235
+ const normalized = text
236
+ .toLowerCase()
237
+ .replace(MEASURE_JOIN_RE, "$1$2");
238
+ const raw = normalized.split(/[^a-z0-9]+/);
239
+ const seen = new Set<string>();
240
+ const out: string[] = [];
241
+ for (const token of raw) {
242
+ if (token.length > 0 && !seen.has(token)) {
243
+ seen.add(token);
244
+ out.push(token);
245
+ }
246
+ }
247
+ return out;
248
+ }
249
+
250
+ interface IndexedVariant {
251
+ product: CatalogProduct;
252
+ variant: CatalogVariant;
253
+ skuLower: string | null;
254
+ coreTokens: Set<string>;
255
+ coreTokenList: string[];
256
+ variantTokens: Set<string>;
257
+ variantTokenList: string[];
258
+ }
259
+
260
+ function indexCatalog(products: readonly CatalogProduct[]): IndexedVariant[] {
261
+ const indexed: IndexedVariant[] = [];
262
+ for (const product of products) {
263
+ if (!isPublicCatalogProduct(product)) continue;
264
+ const productTokens = tokenize([product.title, product.vendor ?? ""].join(" "));
265
+ for (const variant of product.variants) {
266
+ const optionTexts = Object.values(variant.option_values ?? {});
267
+ const variantTitleClean =
268
+ variant.title && variant.title.trim().toLowerCase() !== DEFAULT_VARIANT_TITLE
269
+ ? variant.title
270
+ : "";
271
+ const variantTokenList = tokenize([variantTitleClean, ...optionTexts].join(" "));
272
+ const variantTokens = new Set(variantTokenList);
273
+ const skuTokens = variant.sku ? tokenize(variant.sku) : [];
274
+
275
+ const coreTokens = new Set<string>([...productTokens, ...variantTokenList, ...skuTokens]);
276
+ const skuLower = variant.sku?.trim() ? variant.sku.trim().toLowerCase() : null;
277
+
278
+ indexed.push({
279
+ product,
280
+ variant,
281
+ skuLower,
282
+ coreTokens,
283
+ coreTokenList: [...coreTokens],
284
+ variantTokens,
285
+ variantTokenList,
286
+ });
287
+ }
288
+ }
289
+ return indexed;
290
+ }
291
+
292
+ function tokenMatchWeight(queryToken: string, targetSet: Set<string>, targetList: string[]): number {
293
+ if (targetSet.has(queryToken)) return 1.0;
294
+ if (queryToken.length >= 3) {
295
+ for (const target of targetList) {
296
+ if (target.startsWith(queryToken) || (target.length >= 4 && queryToken.startsWith(target))) {
297
+ return 0.7;
298
+ }
299
+ }
300
+ }
301
+ return 0;
302
+ }
303
+
304
+ function toCandidate(
305
+ entry: IndexedVariant,
306
+ confidence: number,
307
+ matchKind: PasteOrderMatchKind,
308
+ hidePrices: boolean,
309
+ ): PasteOrderCandidate {
310
+ const { product, variant } = entry;
311
+ const candidate: PasteOrderCandidate = {
312
+ productId: product.id,
313
+ productHandle: product.handle,
314
+ productTitle: product.title,
315
+ variantId: variant.id,
316
+ variantTitle: variant.title,
317
+ lineKey: cartLineKey(variant),
318
+ optionValues: { ...(variant.option_values ?? {}) },
319
+ currency: variant.currency,
320
+ available: Boolean(variant.inventory?.available),
321
+ confidence: Math.round(confidence * 1000) / 1000,
322
+ matchKind,
323
+ };
324
+ if (product.vendor) candidate.vendor = product.vendor;
325
+ if (variant.sku) candidate.sku = variant.sku;
326
+ if (!hidePrices) candidate.price = variant.price;
327
+ return candidate;
328
+ }
329
+
330
+ function scoreLine(
331
+ parsed: ParsedOrderLine,
332
+ catalog: readonly IndexedVariant[],
333
+ hidePrices: boolean,
334
+ maxCandidates: number,
335
+ ): PasteOrderMatchedLine {
336
+ const qSku = parsed.query.trim().toLowerCase();
337
+
338
+ // 1. Exact SKU match (case-insensitive)
339
+ if (qSku.length > 0) {
340
+ const exactSkuMatches = catalog.filter((entry) => entry.skuLower !== null && entry.skuLower === qSku);
341
+ const firstExact = exactSkuMatches[0];
342
+ if (exactSkuMatches.length === 1 && firstExact) {
343
+ const match = toCandidate(firstExact, 1.0, "sku", hidePrices);
344
+ return {
345
+ lineNumber: parsed.lineNumber,
346
+ rawLine: parsed.rawLine,
347
+ query: parsed.query,
348
+ quantity: parsed.quantity,
349
+ quantityExplicit: parsed.quantityExplicit,
350
+ status: "matched",
351
+ match,
352
+ candidates: [match],
353
+ };
354
+ }
355
+ if (exactSkuMatches.length > 1) {
356
+ const candidates = exactSkuMatches
357
+ .slice(0, maxCandidates)
358
+ .map((entry) => toCandidate(entry, 1.0, "sku", hidePrices));
359
+ return {
360
+ lineNumber: parsed.lineNumber,
361
+ rawLine: parsed.rawLine,
362
+ query: parsed.query,
363
+ quantity: parsed.quantity,
364
+ quantityExplicit: parsed.quantityExplicit,
365
+ status: "ambiguous",
366
+ candidates,
367
+ };
368
+ }
369
+ }
370
+
371
+ // 2. Deterministic fuzzy token-overlap scoring
372
+ const queryTokens = tokenize(parsed.query);
373
+ if (queryTokens.length === 0) {
374
+ return {
375
+ lineNumber: parsed.lineNumber,
376
+ rawLine: parsed.rawLine,
377
+ query: parsed.query,
378
+ quantity: parsed.quantity,
379
+ quantityExplicit: parsed.quantityExplicit,
380
+ status: "unmatched",
381
+ candidates: [],
382
+ };
383
+ }
384
+
385
+ const queryTokenSet = new Set(queryTokens);
386
+ const scored: { entry: IndexedVariant; score: number }[] = [];
387
+
388
+ for (const entry of catalog) {
389
+ if (entry.coreTokens.size === 0) continue;
390
+
391
+ let queryHitWeight = 0;
392
+ for (const qt of queryTokens) {
393
+ queryHitWeight += tokenMatchWeight(qt, entry.coreTokens, entry.coreTokenList);
394
+ }
395
+ const queryCoverage = queryHitWeight / queryTokens.length;
396
+ if (queryCoverage < MIN_QUERY_COVERAGE) continue;
397
+
398
+ let variantCoverage = 1.0;
399
+ if (entry.variantTokenList.length > 0) {
400
+ let variantHitWeight = 0;
401
+ for (const vt of entry.variantTokenList) {
402
+ variantHitWeight += tokenMatchWeight(vt, queryTokenSet, queryTokens);
403
+ }
404
+ variantCoverage = variantHitWeight / entry.variantTokenList.length;
405
+ }
406
+
407
+ let coreHitCount = 0;
408
+ for (const ct of entry.coreTokenList) {
409
+ if (tokenMatchWeight(ct, queryTokenSet, queryTokens) > 0) {
410
+ coreHitCount += 1;
411
+ }
412
+ }
413
+ const corePrecision = coreHitCount / entry.coreTokenList.length;
414
+
415
+ const rawScore = 0.72 * queryCoverage + 0.18 * variantCoverage + 0.10 * corePrecision;
416
+ const score = Math.min(0.99, rawScore);
417
+
418
+ if (score >= MIN_FUZZY_SCORE) {
419
+ scored.push({ entry, score });
420
+ }
421
+ }
422
+
423
+ if (scored.length === 0) {
424
+ return {
425
+ lineNumber: parsed.lineNumber,
426
+ rawLine: parsed.rawLine,
427
+ query: parsed.query,
428
+ quantity: parsed.quantity,
429
+ quantityExplicit: parsed.quantityExplicit,
430
+ status: "unmatched",
431
+ candidates: [],
432
+ };
433
+ }
434
+
435
+ scored.sort((a, b) => {
436
+ if (b.score !== a.score) return b.score - a.score;
437
+ const availDiff = Number(Boolean(b.entry.variant.inventory?.available)) - Number(Boolean(a.entry.variant.inventory?.available));
438
+ if (availDiff !== 0) return availDiff;
439
+ if (a.entry.product.handle !== b.entry.product.handle) {
440
+ return a.entry.product.handle < b.entry.product.handle ? -1 : 1;
441
+ }
442
+ return a.entry.variant.id < b.entry.variant.id ? -1 : a.entry.variant.id > b.entry.variant.id ? 1 : 0;
443
+ });
444
+
445
+ const top = scored[0];
446
+ if (!top) {
447
+ return {
448
+ lineNumber: parsed.lineNumber,
449
+ rawLine: parsed.rawLine,
450
+ query: parsed.query,
451
+ quantity: parsed.quantity,
452
+ quantityExplicit: parsed.quantityExplicit,
453
+ status: "unmatched",
454
+ candidates: [],
455
+ };
456
+ }
457
+ const second = scored[1];
458
+ const unambiguous = !second || top.score - second.score >= AMBIGUITY_MARGIN;
459
+
460
+ if (unambiguous) {
461
+ const match = toCandidate(top.entry, top.score, "fuzzy", hidePrices);
462
+ return {
463
+ lineNumber: parsed.lineNumber,
464
+ rawLine: parsed.rawLine,
465
+ query: parsed.query,
466
+ quantity: parsed.quantity,
467
+ quantityExplicit: parsed.quantityExplicit,
468
+ status: "matched",
469
+ match,
470
+ candidates: [match],
471
+ };
472
+ }
473
+
474
+ const candidates = scored
475
+ .slice(0, maxCandidates)
476
+ .map((item) => toCandidate(item.entry, item.score, "fuzzy", hidePrices));
477
+
478
+ return {
479
+ lineNumber: parsed.lineNumber,
480
+ rawLine: parsed.rawLine,
481
+ query: parsed.query,
482
+ quantity: parsed.quantity,
483
+ quantityExplicit: parsed.quantityExplicit,
484
+ status: "ambiguous",
485
+ candidates,
486
+ };
487
+ }
488
+
489
+ /**
490
+ * Parse a free-text wholesale order list and deterministically match each line
491
+ * against active catalog products & variants, returning matched/ambiguous/unmatched
492
+ * lines plus an aggregated cart batch for matched variants.
493
+ */
494
+ export function matchPasteOrderList(
495
+ rawText: string,
496
+ products: readonly CatalogProduct[],
497
+ options: MatchPasteOrderOptions = {},
498
+ ): PasteOrderMatchResult {
499
+ const hidePrices = options.hidePrices === true;
500
+ const maxCandidates = Math.max(1, Math.min(options.maxCandidates ?? PASTE_ORDER_MAX_CANDIDATES, 10));
501
+
502
+ const parsedLines = parsePasteOrderList(rawText);
503
+ const catalog = indexCatalog(products);
504
+
505
+ const lines: PasteOrderMatchedLine[] = [];
506
+ let matchedCount = 0;
507
+ let ambiguousCount = 0;
508
+ let unmatchedCount = 0;
509
+
510
+ const cartByVariantId = new Map<string, PasteOrderCartItem>();
511
+
512
+ for (const parsed of parsedLines) {
513
+ const result = scoreLine(parsed, catalog, hidePrices, maxCandidates);
514
+ lines.push(result);
515
+
516
+ if (result.status === "matched" && result.match) {
517
+ matchedCount += 1;
518
+ const existing = cartByVariantId.get(result.match.variantId);
519
+ if (existing) {
520
+ existing.quantity = clampQuantity(existing.quantity + result.quantity);
521
+ } else {
522
+ const item: PasteOrderCartItem = {
523
+ productId: result.match.productId,
524
+ productHandle: result.match.productHandle,
525
+ productTitle: result.match.productTitle,
526
+ variantId: result.match.variantId,
527
+ variantTitle: result.match.variantTitle,
528
+ lineKey: result.match.lineKey,
529
+ quantity: result.quantity,
530
+ currency: result.match.currency,
531
+ available: result.match.available,
532
+ };
533
+ if (result.match.sku) item.sku = result.match.sku;
534
+ if (!hidePrices && result.match.price !== undefined) item.price = result.match.price;
535
+ cartByVariantId.set(result.match.variantId, item);
536
+ }
537
+ } else if (result.status === "ambiguous") {
538
+ ambiguousCount += 1;
539
+ } else {
540
+ unmatchedCount += 1;
541
+ }
542
+ }
543
+
544
+ return {
545
+ lines,
546
+ matchedCount,
547
+ ambiguousCount,
548
+ unmatchedCount,
549
+ cartItems: [...cartByVariantId.values()],
550
+ };
551
+ }