@flowselections/floriday-klanten-module 1.0.98 → 1.0.99

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.
@@ -106,6 +106,27 @@ export type StickerMatchSuggestion = {
106
106
  confidence: number;
107
107
  reason: string | null;
108
108
  };
109
+ type StickerSuggestInput = {
110
+ files: {
111
+ fileId: string;
112
+ fileName: string;
113
+ thumbnail?: string | null;
114
+ }[];
115
+ products: {
116
+ key: string;
117
+ name: string;
118
+ code?: string | null;
119
+ vbn?: string | null;
120
+ botanical?: string | null;
121
+ }[];
122
+ };
123
+ /** Kern van suggestStickerMatches; los geëxporteerd zodat de AI-foutafhandeling testbaar is. */
124
+ export declare function koppelStickerSuggesties(data: StickerSuggestInput, context: {
125
+ userId?: string | null;
126
+ }): Promise<{
127
+ suggestions: StickerMatchSuggestion[];
128
+ aiError?: string | null;
129
+ }>;
109
130
  export declare const suggestStickerMatches: import("@tanstack/start-client-core").OptionalFetcher<readonly [import("@tanstack/start-client-core").FunctionMiddlewareAfterServer<{}, unknown, undefined, {
110
131
  supabase: import("../integrations/supabase/auth-middleware.js").AuthedSupabaseClient;
111
132
  userId: string;
@@ -203,4 +224,5 @@ export declare const previewStickerSizes: import("@tanstack/start-client-core").
203
224
  userId: string;
204
225
  claims: import("@supabase/auth-js").JwtPayload;
205
226
  }, undefined, undefined, undefined>], undefined, Promise<StickerSizePreviewRow[]>>;
227
+ export {};
206
228
  //# sourceMappingURL=customer-stickers.functions.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"customer-stickers.functions.d.ts","sourceRoot":"","sources":["../../src/lib/customer-stickers.functions.ts"],"names":[],"mappings":"AAGA,OAAO,EAIL,KAAK,iBAAiB,EACvB,MAAM,gBAAgB,CAAC;AAKxB,eAAO,MAAM,oBAAoB,0EAKvB,CAAC;AAEX,MAAM,MAAM,eAAe,GAAG;IAC5B,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAA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;;;;GAoB7B,CAAC;AAEL,6EAA6E;AAC7E,eAAO,MAAM,kBAAkB;;;;8CAEL,OAAO;;;8BAc7B,CAAC;AAEL,MAAM,MAAM,qBAAqB,GAAG;IAClC,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,iBAAiB,CAAC,QAAQ,CAAC,CAAC;IACpC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB,CAAC;AAEF,yGAAyG;AACzG,eAAO,MAAM,mBAAmB;;;;kFA8B5B,CAAC"}
@@ -2,6 +2,7 @@ import { createServerFn } from "@tanstack/react-start";
2
2
  import { z } from "zod";
3
3
  import { requireSupabaseAuth } from "../integrations/supabase/auth-middleware.js";
4
4
  import { detectStickerSize, parseLoadedLabel, } from "./sticker-size.js";
5
+ import { geminiGenerateUrl, matchByFileName } from "./sticker-match.js";
5
6
  const BUCKET = "customer-stickers";
6
7
  const SIGNED_TTL = 60 * 60; // 1 uur
7
8
  export const ALLOWED_STICKER_MIME = [
@@ -246,52 +247,8 @@ export const getStickerForPrint = createServerFn({ method: "POST" })
246
247
  const MAX_STICKER_SIZE = 10 * 1024 * 1024;
247
248
  const AI_MODULE_KEY = "klanten-stickers";
248
249
  export const safeStorageKey = (v) => v.replace(/[^a-zA-Z0-9._-]/g, "_");
249
- function normalizeToken(v) {
250
- return v.toLowerCase().replace(/[^a-z0-9]/g, "");
251
- }
252
- /** Goedkope voorbewerking: exacte code in de bestandsnaam. */
253
- function matchByFileName(fileName, products) {
254
- const hay = normalizeToken(fileName);
255
- if (!hay)
256
- return null;
257
- for (const p of products) {
258
- for (const [label, code] of [
259
- ["artikelcode", p.code],
260
- ["VBN-code", p.vbn],
261
- ]) {
262
- const t = code ? normalizeToken(code) : "";
263
- if (t.length >= 4 && hay.includes(t)) {
264
- return { tradeItemKey: p.key, reason: `Bestandsnaam bevat ${label} ${code}` };
265
- }
266
- }
267
- }
268
- return null;
269
- }
270
- export const suggestStickerMatches = createServerFn({ method: "POST" })
271
- .middleware([requireSupabaseAuth])
272
- .inputValidator((input) => z
273
- .object({
274
- files: z
275
- .array(z.object({
276
- fileId: z.string().min(1),
277
- fileName: z.string().min(1),
278
- thumbnail: z.string().nullable().optional(),
279
- }))
280
- .min(1)
281
- .max(200),
282
- products: z
283
- .array(z.object({
284
- key: z.string().min(1),
285
- name: z.string(),
286
- code: z.string().nullable().optional(),
287
- vbn: z.string().nullable().optional(),
288
- botanical: z.string().nullable().optional(),
289
- }))
290
- .min(1)
291
- .max(2000),
292
- })
293
- .parse(input))
294
- .handler(async ({ data, context }) => {
250
+ /** Kern van suggestStickerMatches; los geëxporteerd zodat de AI-foutafhandeling testbaar is. */
251
+ export async function koppelStickerSuggesties(data, context) {
295
252
  const products = data.products.map((p) => ({
296
253
  key: p.key,
297
254
  name: p.name,
@@ -317,158 +274,184 @@ export const suggestStickerMatches = createServerFn({ method: "POST" })
317
274
  }
318
275
  if (remaining.length === 0)
319
276
  return { suggestions };
320
- const { resolveModuleModel, logAiCall, AiModuleError } = await import("./ai-module.server.js");
321
- let model;
322
- try {
323
- model = await resolveModuleModel(AI_MODULE_KEY);
324
- }
325
- catch (e) {
326
- if (e instanceof AiModuleError)
327
- throw new Error(e.message);
328
- throw e;
329
- }
330
- const productList = products
331
- .map((p) => `- key: ${p.key} | naam: ${p.name}` +
332
- (p.code ? ` | artikelcode: ${p.code}` : "") +
333
- (p.vbn ? ` | VBN: ${p.vbn}` : "") +
334
- (p.botanical ? ` | botanisch: ${p.botanical}` : ""))
335
- .join("\n");
336
277
  let aiError = null;
337
- for (let i = 0; i < remaining.length; i += 4) {
338
- const batch = remaining.slice(i, i + 4);
339
- const parts = [
340
- {
341
- text: "Je koppelt stickerbestanden aan producten uit het assortiment van een bloemenhandel.\n" +
342
- "Producten:\n" +
343
- productList +
344
- "\n\nHieronder volgen stickers. Voor elke sticker krijg je eerst de bestandsnaam en daarna (indien beschikbaar) een afbeelding van de sticker.\n" +
345
- "Geef per sticker het best passende product terug. Kies alleen een product als je het redelijk zeker weet; anders tradeItemKey = null.\n" +
346
- 'Antwoord uitsluitend als JSON-array: [{"fileId":"...","tradeItemKey":"..."|null,"confidence":0.0-1.0,"reason":"korte uitleg in het Nederlands"}]',
347
- },
348
- ];
349
- for (const f of batch) {
350
- parts.push({ text: `Sticker fileId=${f.fileId} bestandsnaam="${f.fileName}"` });
351
- const t = f.thumbnail ?? "";
352
- const m = /^data:([^;,]+);base64,(.+)$/.exec(t);
353
- if (m)
354
- parts.push({ inline_data: { mime_type: m[1], data: m[2] } });
355
- }
356
- const url = model.providerSlug === "gemini"
357
- ? `${model.baseUrl}/v1beta/models/${model.modelSlug}:generateContent`
358
- : null;
359
- if (!url) {
360
- throw new Error(`AI-aanbieder "${model.providerSlug}" wordt hier nog niet ondersteund. Kies een Gemini-model bij AI-authenticatie.`);
361
- }
362
- let json = null;
363
- let lastMessage = "AI-herkenning mislukt.";
364
- for (let attempt = 0; attempt < 4; attempt++) {
365
- const started = Date.now();
366
- let res;
367
- try {
368
- res = await fetch(url, {
369
- method: "POST",
370
- headers: { "Content-Type": "application/json", "x-goog-api-key": model.apiKey },
371
- body: JSON.stringify({
372
- contents: [{ role: "user", parts }],
373
- generationConfig: { responseMimeType: "application/json", temperature: 0 },
374
- }),
375
- });
278
+ try {
279
+ const { resolveModuleModel, logAiCall } = await import("./ai-module.server.js");
280
+ const model = await resolveModuleModel(AI_MODULE_KEY);
281
+ const productList = products
282
+ .map((p) => `- key: ${p.key} | naam: ${p.name}` +
283
+ (p.code ? ` | artikelcode: ${p.code}` : "") +
284
+ (p.vbn ? ` | VBN: ${p.vbn}` : "") +
285
+ (p.botanical ? ` | botanisch: ${p.botanical}` : ""))
286
+ .join("\n");
287
+ for (let i = 0; i < remaining.length; i += 4) {
288
+ const batch = remaining.slice(i, i + 4);
289
+ const parts = [
290
+ {
291
+ text: "Je koppelt stickerbestanden aan producten uit het assortiment van een bloemenhandel.\n" +
292
+ "Producten:\n" +
293
+ productList +
294
+ "\n\nHieronder volgen stickers. Voor elke sticker krijg je eerst de bestandsnaam en daarna (indien beschikbaar) een afbeelding van de sticker.\n" +
295
+ "Geef per sticker het best passende product terug. Kies alleen een product als je het redelijk zeker weet; anders tradeItemKey = null.\n" +
296
+ 'Antwoord uitsluitend als JSON-array: [{"fileId":"...","tradeItemKey":"..."|null,"confidence":0.0-1.0,"reason":"korte uitleg in het Nederlands"}]',
297
+ },
298
+ ];
299
+ for (const f of batch) {
300
+ parts.push({ text: `Sticker fileId=${f.fileId} bestandsnaam="${f.fileName}"` });
301
+ const t = f.thumbnail ?? "";
302
+ const m = /^data:([^;,]+);base64,(.+)$/.exec(t);
303
+ if (m)
304
+ parts.push({ inline_data: { mime_type: m[1], data: m[2] } });
305
+ }
306
+ const url = model.providerSlug === "gemini"
307
+ ? geminiGenerateUrl(model.baseUrl, model.modelSlug)
308
+ : null;
309
+ if (!url) {
310
+ throw new Error(`AI-aanbieder "${model.providerSlug}" wordt hier nog niet ondersteund. Kies een Gemini-model bij AI-authenticatie.`);
376
311
  }
377
- catch (e) {
378
- lastMessage = "De AI-dienst is niet bereikbaar. Probeer het zo nog eens.";
312
+ let json = null;
313
+ let lastMessage = "AI-herkenning mislukt.";
314
+ for (let attempt = 0; attempt < 4; attempt++) {
315
+ const started = Date.now();
316
+ let res;
317
+ try {
318
+ res = await fetch(url, {
319
+ method: "POST",
320
+ headers: { "Content-Type": "application/json", "x-goog-api-key": model.apiKey },
321
+ body: JSON.stringify({
322
+ contents: [{ role: "user", parts }],
323
+ generationConfig: { responseMimeType: "application/json", temperature: 0 },
324
+ }),
325
+ });
326
+ }
327
+ catch (e) {
328
+ lastMessage = "De AI-dienst is niet bereikbaar. Probeer het zo nog eens.";
329
+ await logAiCall({
330
+ moduleKey: AI_MODULE_KEY,
331
+ providerSlug: model.providerSlug,
332
+ modelSlug: model.modelSlug,
333
+ status: "error",
334
+ durationMs: Date.now() - started,
335
+ errorCode: "network",
336
+ errorMessage: e instanceof Error ? e.message.slice(0, 500) : null,
337
+ createdBy: context.userId ?? null,
338
+ });
339
+ await new Promise((r) => setTimeout(r, 1500 * 2 ** attempt));
340
+ continue;
341
+ }
342
+ if (res.ok) {
343
+ json = await res.json();
344
+ await logAiCall({
345
+ moduleKey: AI_MODULE_KEY,
346
+ providerSlug: model.providerSlug,
347
+ modelSlug: model.modelSlug,
348
+ status: "success",
349
+ durationMs: Date.now() - started,
350
+ createdBy: context.userId ?? null,
351
+ });
352
+ break;
353
+ }
354
+ const body = await res.text();
379
355
  await logAiCall({
380
356
  moduleKey: AI_MODULE_KEY,
381
357
  providerSlug: model.providerSlug,
382
358
  modelSlug: model.modelSlug,
383
359
  status: "error",
384
360
  durationMs: Date.now() - started,
385
- errorCode: "network",
386
- errorMessage: e instanceof Error ? e.message.slice(0, 500) : null,
361
+ errorCode: String(res.status),
362
+ errorMessage: body.slice(0, 500),
387
363
  createdBy: context.userId ?? null,
388
364
  });
389
- await new Promise((r) => setTimeout(r, 1500 * 2 ** attempt));
390
- continue;
365
+ if (res.status === 401 || res.status === 403) {
366
+ throw new Error("De AI-sleutel wordt geweigerd. Controleer de sleutel bij AI-authenticatie.");
367
+ }
368
+ if (res.status === 400 || res.status === 404) {
369
+ throw new Error(`Het ingestelde AI-model werd geweigerd (${res.status}). Controleer het model bij AI-authenticatie.`);
370
+ }
371
+ if (res.status === 429 || res.status >= 500) {
372
+ lastMessage =
373
+ "De AI-dienst is tijdelijk overbelast. De stickers zijn geüpload; koppel ze handmatig of probeer de herkenning zo nog eens.";
374
+ const retryAfter = Number(res.headers.get("retry-after"));
375
+ const waitMs = Number.isFinite(retryAfter) && retryAfter > 0
376
+ ? retryAfter * 1000
377
+ : 1500 * 2 ** attempt;
378
+ if (attempt < 3)
379
+ await new Promise((r) => setTimeout(r, waitMs));
380
+ continue;
381
+ }
382
+ throw new Error(`De AI-dienst gaf een fout (${res.status}).`);
391
383
  }
392
- if (res.ok) {
393
- json = await res.json();
394
- await logAiCall({
395
- moduleKey: AI_MODULE_KEY,
396
- providerSlug: model.providerSlug,
397
- modelSlug: model.modelSlug,
398
- status: "success",
399
- durationMs: Date.now() - started,
400
- createdBy: context.userId ?? null,
401
- });
402
- break;
384
+ if (!json) {
385
+ aiError = lastMessage;
386
+ for (const b of batch) {
387
+ suggestions.push({ fileId: b.fileId, tradeItemKey: null, confidence: 0, reason: null });
388
+ }
389
+ continue;
403
390
  }
404
- const body = await res.text();
405
- await logAiCall({
406
- moduleKey: AI_MODULE_KEY,
407
- providerSlug: model.providerSlug,
408
- modelSlug: model.modelSlug,
409
- status: "error",
410
- durationMs: Date.now() - started,
411
- errorCode: String(res.status),
412
- errorMessage: body.slice(0, 500),
413
- createdBy: context.userId ?? null,
414
- });
415
- if (res.status === 401 || res.status === 403) {
416
- throw new Error("De AI-sleutel wordt geweigerd. Controleer de sleutel bij AI-authenticatie.");
391
+ const text = json?.candidates?.[0]?.content?.parts?.map((p) => p?.text ?? "").join("") ?? "";
392
+ const cleaned = text.trim().replace(/^```(?:json)?/i, "").replace(/```$/, "");
393
+ let parsed = [];
394
+ try {
395
+ parsed = JSON.parse(cleaned);
417
396
  }
418
- if (res.status === 400 || res.status === 404) {
419
- throw new Error(`Het ingestelde AI-model werd geweigerd (${res.status}). Controleer het model bij AI-authenticatie.`);
397
+ catch {
398
+ parsed = [];
420
399
  }
421
- if (res.status === 429 || res.status >= 500) {
422
- lastMessage =
423
- "De AI-dienst is tijdelijk overbelast. De stickers zijn geüpload; koppel ze handmatig of probeer de herkenning zo nog eens.";
424
- const retryAfter = Number(res.headers.get("retry-after"));
425
- const waitMs = Number.isFinite(retryAfter) && retryAfter > 0
426
- ? retryAfter * 1000
427
- : 1500 * 2 ** attempt;
428
- if (attempt < 3)
429
- await new Promise((r) => setTimeout(r, waitMs));
430
- continue;
400
+ const validKeys = new Set(products.map((p) => p.key));
401
+ for (const row of Array.isArray(parsed) ? parsed : []) {
402
+ const fileId = String(row?.fileId ?? "");
403
+ if (!batch.some((b) => b.fileId === fileId))
404
+ continue;
405
+ const key = row?.tradeItemKey ? String(row.tradeItemKey) : null;
406
+ suggestions.push({
407
+ fileId,
408
+ tradeItemKey: key && validKeys.has(key) ? key : null,
409
+ confidence: Number.isFinite(Number(row?.confidence)) ? Number(row.confidence) : 0,
410
+ reason: row?.reason ? String(row.reason).slice(0, 200) : null,
411
+ });
431
412
  }
432
- throw new Error(`De AI-dienst gaf een fout (${res.status}).`);
433
- }
434
- if (!json) {
435
- aiError = lastMessage;
436
413
  for (const b of batch) {
437
- suggestions.push({ fileId: b.fileId, tradeItemKey: null, confidence: 0, reason: null });
438
- }
439
- continue;
440
- }
441
- const text = json?.candidates?.[0]?.content?.parts?.map((p) => p?.text ?? "").join("") ?? "";
442
- const cleaned = text.trim().replace(/^```(?:json)?/i, "").replace(/```$/, "");
443
- let parsed = [];
444
- try {
445
- parsed = JSON.parse(cleaned);
446
- }
447
- catch {
448
- parsed = [];
449
- }
450
- const validKeys = new Set(products.map((p) => p.key));
451
- for (const row of Array.isArray(parsed) ? parsed : []) {
452
- const fileId = String(row?.fileId ?? "");
453
- if (!batch.some((b) => b.fileId === fileId))
454
- continue;
455
- const key = row?.tradeItemKey ? String(row.tradeItemKey) : null;
456
- suggestions.push({
457
- fileId,
458
- tradeItemKey: key && validKeys.has(key) ? key : null,
459
- confidence: Number.isFinite(Number(row?.confidence)) ? Number(row.confidence) : 0,
460
- reason: row?.reason ? String(row.reason).slice(0, 200) : null,
461
- });
462
- }
463
- for (const b of batch) {
464
- if (!suggestions.some((s) => s.fileId === b.fileId)) {
465
- suggestions.push({ fileId: b.fileId, tradeItemKey: null, confidence: 0, reason: null });
414
+ if (!suggestions.some((s) => s.fileId === b.fileId)) {
415
+ suggestions.push({ fileId: b.fileId, tradeItemKey: null, confidence: 0, reason: null });
416
+ }
466
417
  }
467
418
  }
468
419
  }
420
+ catch (e) {
421
+ // AI-fout: koppelingen op bestandsnaam blijven staan, reden gaat mee.
422
+ console.error("AI-herkenning van stickers mislukt", e);
423
+ aiError =
424
+ e instanceof Error && e.message
425
+ ? e.message
426
+ : "Automatisch herkennen lukte niet. Koppel de overige stickers handmatig.";
427
+ }
469
428
  return { suggestions, aiError };
470
- return { suggestions };
471
- });
429
+ }
430
+ export const suggestStickerMatches = createServerFn({ method: "POST" })
431
+ .middleware([requireSupabaseAuth])
432
+ .inputValidator((input) => z
433
+ .object({
434
+ files: z
435
+ .array(z.object({
436
+ fileId: z.string().min(1),
437
+ fileName: z.string().min(1),
438
+ thumbnail: z.string().nullable().optional(),
439
+ }))
440
+ .min(1)
441
+ .max(200),
442
+ products: z
443
+ .array(z.object({
444
+ key: z.string().min(1),
445
+ name: z.string(),
446
+ code: z.string().nullable().optional(),
447
+ vbn: z.string().nullable().optional(),
448
+ botanical: z.string().nullable().optional(),
449
+ }))
450
+ .min(1)
451
+ .max(2000),
452
+ })
453
+ .parse(input))
454
+ .handler(async ({ data, context }) => koppelStickerSuggesties(data, context));
472
455
  export const commitStickerBatch = createServerFn({ method: "POST" })
473
456
  .middleware([requireSupabaseAuth])
474
457
  .inputValidator((input) => z
@@ -0,0 +1,19 @@
1
+ export type StickerMatchProduct = {
2
+ key: string;
3
+ name: string;
4
+ code: string | null;
5
+ vbn: string | null;
6
+ };
7
+ export declare function normalizeToken(v: string): string;
8
+ /** Haalt een afsluitend /v1beta of /v1 van het basisadres en bouwt het Gemini-adres. */
9
+ export declare function geminiGenerateUrl(baseUrl: string, modelSlug: string): string;
10
+ /**
11
+ * Koppelen op bestandsnaam: artikelcode, VBN-code of productnaam (zonder
12
+ * streepjes/punten). De langste passende waarde wint; staan er twee
13
+ * verschillende artikelen gelijk bovenaan, dan wordt er niet gekoppeld.
14
+ */
15
+ export declare function matchByFileName(fileName: string, products: StickerMatchProduct[]): {
16
+ tradeItemKey: string;
17
+ reason: string;
18
+ } | null;
19
+ //# sourceMappingURL=sticker-match.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sticker-match.d.ts","sourceRoot":"","sources":["../../src/lib/sticker-match.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,mBAAmB,GAAG;IAChC,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;CACpB,CAAC;AAEF,wBAAgB,cAAc,CAAC,CAAC,EAAE,MAAM,UAEvC;AAED,wFAAwF;AACxF,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAG5E;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,mBAAmB,EAAE,GAC9B;IAAE,YAAY,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CA4BjD"}
@@ -0,0 +1,46 @@
1
+ export function normalizeToken(v) {
2
+ return v.toLowerCase().replace(/[^a-z0-9]/g, "");
3
+ }
4
+ /** Haalt een afsluitend /v1beta of /v1 van het basisadres en bouwt het Gemini-adres. */
5
+ export function geminiGenerateUrl(baseUrl, modelSlug) {
6
+ const base = baseUrl.replace(/\/+$/, "").replace(/\/v1(beta)?$/i, "");
7
+ return `${base}/v1beta/models/${modelSlug}:generateContent`;
8
+ }
9
+ /**
10
+ * Koppelen op bestandsnaam: artikelcode, VBN-code of productnaam (zonder
11
+ * streepjes/punten). De langste passende waarde wint; staan er twee
12
+ * verschillende artikelen gelijk bovenaan, dan wordt er niet gekoppeld.
13
+ */
14
+ export function matchByFileName(fileName, products) {
15
+ const hay = normalizeToken(fileName.replace(/\.[a-z0-9]{2,5}$/i, ""));
16
+ if (!hay)
17
+ return null;
18
+ let best = null;
19
+ let tie = false;
20
+ for (const p of products) {
21
+ const kandidaten = [
22
+ ["artikelcode", p.code, 4],
23
+ ["VBN-code", p.vbn, 4],
24
+ ["productnaam", p.name, 5],
25
+ ];
26
+ let pBest = null;
27
+ for (const [label, raw, min] of kandidaten) {
28
+ const t = raw ? normalizeToken(raw) : "";
29
+ if (t.length >= min && hay.includes(t) && (!pBest || t.length > pBest.len)) {
30
+ pBest = { len: t.length, reason: `Bestandsnaam bevat ${label} ${raw}` };
31
+ }
32
+ }
33
+ if (!pBest)
34
+ continue;
35
+ if (!best || pBest.len > best.len) {
36
+ best = { key: p.key, ...pBest };
37
+ tie = false;
38
+ }
39
+ else if (pBest.len === best.len && p.key !== best.key) {
40
+ tie = true;
41
+ }
42
+ }
43
+ if (!best || tie)
44
+ return null;
45
+ return { tradeItemKey: best.key, reason: best.reason };
46
+ }
@@ -1,5 +1,7 @@
1
1
  export declare const MAX_STICKER_BESTANDEN = 1000;
2
2
  export declare const STICKER_PORTIE = 200;
3
+ /** Aantal stickers per aanvraag aan de server bij automatisch koppelen. */
4
+ export declare const STICKER_AANVRAAG = 8;
3
5
  export declare function teVeelStickerBestanden(aantal: number): string | null;
4
6
  export declare function inPorties<T>(items: T[], grootte?: number): T[][];
5
7
  //# sourceMappingURL=sticker-porties.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sticker-porties.d.ts","sourceRoot":"","sources":["../../src/lib/sticker-porties.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,qBAAqB,OAAO,CAAC;AAC1C,eAAO,MAAM,cAAc,MAAM,CAAC;AAElC,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAGpE;AAED,wBAAgB,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE,OAAO,SAAiB,GAAG,CAAC,EAAE,EAAE,CAIxE"}
1
+ {"version":3,"file":"sticker-porties.d.ts","sourceRoot":"","sources":["../../src/lib/sticker-porties.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,qBAAqB,OAAO,CAAC;AAC1C,eAAO,MAAM,cAAc,MAAM,CAAC;AAClC,2EAA2E;AAC3E,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAElC,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAGpE;AAED,wBAAgB,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,EAAE,OAAO,SAAiB,GAAG,CAAC,EAAE,EAAE,CAIxE"}
@@ -1,5 +1,7 @@
1
1
  export const MAX_STICKER_BESTANDEN = 1000;
2
2
  export const STICKER_PORTIE = 200;
3
+ /** Aantal stickers per aanvraag aan de server bij automatisch koppelen. */
4
+ export const STICKER_AANVRAAG = 8;
3
5
  export function teVeelStickerBestanden(aantal) {
4
6
  if (aantal <= MAX_STICKER_BESTANDEN)
5
7
  return null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flowselections/floriday-klanten-module",
3
- "version": "1.0.98",
3
+ "version": "1.0.99",
4
4
  "private": false,
5
5
  "sideEffects": false,
6
6
  "type": "module",