@flowselections/floriday-klanten-module 1.0.98 → 1.0.100

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 (35) hide show
  1. package/dist-lib/components/klanten/BulkStickerUploadDialog.d.ts +10 -1
  2. package/dist-lib/components/klanten/BulkStickerUploadDialog.d.ts.map +1 -1
  3. package/dist-lib/components/klanten/BulkStickerUploadDialog.js +44 -22
  4. package/dist-lib/components/klanten/CustomerAssortmentTab.d.ts.map +1 -1
  5. package/dist-lib/components/klanten/CustomerAssortmentTab.js +19 -5
  6. package/dist-lib/components/klanten/CustomerStickerCell.d.ts +4 -1
  7. package/dist-lib/components/klanten/CustomerStickerCell.d.ts.map +1 -1
  8. package/dist-lib/components/klanten/CustomerStickerCell.js +6 -4
  9. package/dist-lib/components/klanten/CustomerStickerFormatDialog.d.ts +3 -1
  10. package/dist-lib/components/klanten/CustomerStickerFormatDialog.d.ts.map +1 -1
  11. package/dist-lib/components/klanten/CustomerStickerFormatDialog.js +5 -4
  12. package/dist-lib/components/klanten/StickerSizeLine.d.ts +3 -1
  13. package/dist-lib/components/klanten/StickerSizeLine.d.ts.map +1 -1
  14. package/dist-lib/components/klanten/StickerSizeLine.js +4 -4
  15. package/dist-lib/index.d.ts +1 -1
  16. package/dist-lib/index.d.ts.map +1 -1
  17. package/dist-lib/integrations/supabase/types.d.ts +379 -0
  18. package/dist-lib/integrations/supabase/types.d.ts.map +1 -1
  19. package/dist-lib/lib/customer-stickers.functions.d.ts +58 -0
  20. package/dist-lib/lib/customer-stickers.functions.d.ts.map +1 -1
  21. package/dist-lib/lib/customer-stickers.functions.js +285 -252
  22. package/dist-lib/lib/pdf-thumbnail.d.ts +4 -0
  23. package/dist-lib/lib/pdf-thumbnail.d.ts.map +1 -0
  24. package/dist-lib/lib/pdf-thumbnail.js +49 -0
  25. package/dist-lib/lib/sticker-match.d.ts +19 -0
  26. package/dist-lib/lib/sticker-match.d.ts.map +1 -0
  27. package/dist-lib/lib/sticker-match.js +46 -0
  28. package/dist-lib/lib/sticker-porties.d.ts +2 -0
  29. package/dist-lib/lib/sticker-porties.d.ts.map +1 -1
  30. package/dist-lib/lib/sticker-porties.js +2 -0
  31. package/dist-lib/lib/sticker-soort.d.ts +20 -0
  32. package/dist-lib/lib/sticker-soort.d.ts.map +1 -0
  33. package/dist-lib/lib/sticker-soort.js +20 -0
  34. package/package.json +2 -1
  35. package/schema/klanten.sql +27 -2
@@ -2,6 +2,18 @@ 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";
6
+ import { isTabelOntbreekt } from "./tabel-ontbreekt.js";
7
+ import { FUST_NIET_BESCHIKBAAR, formaatVoorSoort, stickerDoelpad, stickerTabel, } from "./sticker-soort.js";
8
+ const soortSchema = z.enum(["product", "fust"]).default("product");
9
+ /** Vertaalt een ontbrekende fusttabel naar een rustige melding; andere fouten ongewijzigd. */
10
+ function soortFout(soort, error) {
11
+ if (soort === "fust" && isTabelOntbreekt(error)) {
12
+ console.error("customer_fust_stickers ontbreekt in deze database", error);
13
+ return new Error(FUST_NIET_BESCHIKBAAR);
14
+ }
15
+ return new Error(error.message);
16
+ }
5
17
  const BUCKET = "customer-stickers";
6
18
  const SIGNED_TTL = 60 * 60; // 1 uur
7
19
  export const ALLOWED_STICKER_MIME = [
@@ -10,6 +22,20 @@ export const ALLOWED_STICKER_MIME = [
10
22
  "image/jpeg",
11
23
  "image/svg+xml",
12
24
  ];
25
+ /** Leest stickerinstellingen; fustkolommen alleen erbij voor soort 'fust'. */
26
+ async function leesInstellingen(sb, customerKey, soort) {
27
+ const cols = soort === "fust" ? "width_mm, height_mm, fust_width_mm, fust_height_mm" : "width_mm, height_mm";
28
+ const { data, error } = await sb
29
+ .from("customer_sticker_settings")
30
+ .select(cols)
31
+ .eq("customer_key", customerKey)
32
+ .maybeSingle();
33
+ if (error) {
34
+ console.error("Stickerinstellingen lezen mislukt", error);
35
+ return null;
36
+ }
37
+ return data ?? null;
38
+ }
13
39
  /** Geladen etiketten uit Layouts (printers + routes). Ontbreekt iets: lege lijst, geen fout. */
14
40
  async function loadLabels(sb) {
15
41
  const out = [];
@@ -60,17 +86,22 @@ async function signed(sb, path) {
60
86
  const { data } = await sb.storage.from(BUCKET).createSignedUrl(path, SIGNED_TTL);
61
87
  return data?.signedUrl ?? null;
62
88
  }
63
- export const listCustomerStickers = createServerFn({ method: "POST" })
64
- .middleware([requireSupabaseAuth])
65
- .inputValidator((input) => z.object({ customerKey: z.string().min(1) }).parse(input))
66
- .handler(async ({ data, context }) => {
89
+ /** Kern van listCustomerStickers (los aanroepbaar voor tests). */
90
+ export async function listCustomerStickersKern(data, context) {
91
+ data = { ...data, soort: data?.soort === "fust" ? "fust" : "product" };
67
92
  const sb = context.supabase;
68
93
  const { data: rows, error } = await sb
69
- .from("customer_product_stickers")
94
+ .from(stickerTabel(data.soort))
70
95
  .select("trade_item_key, file_path, file_name, mime_type, file_size, updated_at, source, width_mm, height_mm")
71
96
  .eq("customer_key", data.customerKey);
72
- if (error)
97
+ if (error) {
98
+ // Fusttabel nog niet geïnstalleerd: lege fustlijst, productstickers werken door.
99
+ if (data.soort === "fust" && isTabelOntbreekt(error)) {
100
+ console.error("customer_fust_stickers ontbreekt in deze database", error);
101
+ return { stickers: [], format: null, soort: "fust" };
102
+ }
73
103
  throw new Error(error.message);
104
+ }
74
105
  const stickers = [];
75
106
  for (const r of rows ?? []) {
76
107
  stickers.push({
@@ -84,18 +115,16 @@ export const listCustomerStickers = createServerFn({ method: "POST" })
84
115
  source: r.source === "floriday" ? "floriday" : "manual",
85
116
  width_mm: r.width_mm != null ? Number(r.width_mm) : null,
86
117
  height_mm: r.height_mm != null ? Number(r.height_mm) : null,
118
+ soort: data.soort,
87
119
  });
88
120
  }
89
- const { data: fmt } = await sb
90
- .from("customer_sticker_settings")
91
- .select("width_mm, height_mm")
92
- .eq("customer_key", data.customerKey)
93
- .maybeSingle();
94
- return {
95
- stickers,
96
- format: fmt ? { width_mm: Number(fmt.width_mm), height_mm: Number(fmt.height_mm) } : null,
97
- };
98
- });
121
+ const fmt = await leesInstellingen(sb, data.customerKey, data.soort);
122
+ return { stickers, format: formaatVoorSoort(fmt, data.soort), soort: data.soort };
123
+ }
124
+ export const listCustomerStickers = createServerFn({ method: "POST" })
125
+ .middleware([requireSupabaseAuth])
126
+ .inputValidator((input) => z.object({ customerKey: z.string().min(1), soort: soortSchema }).parse(input))
127
+ .handler(async ({ data, context }) => listCustomerStickersKern(data, context));
99
128
  export const confirmStickerUpload = createServerFn({ method: "POST" })
100
129
  .middleware([requireSupabaseAuth])
101
130
  .inputValidator((input) => z
@@ -106,10 +135,12 @@ export const confirmStickerUpload = createServerFn({ method: "POST" })
106
135
  fileName: z.string().min(1),
107
136
  mimeType: z.string().min(1),
108
137
  fileSize: z.number().nullable().optional(),
138
+ soort: soortSchema,
109
139
  })
110
140
  .parse(input))
111
141
  .handler(async ({ data, context }) => {
112
142
  const sb = context.supabase;
143
+ const tabel = stickerTabel(data.soort);
113
144
  if (!ALLOWED_STICKER_MIME.includes(data.mimeType)) {
114
145
  throw new Error("Dit bestandstype wordt niet ondersteund. Gebruik PDF, PNG, JPG of SVG.");
115
146
  }
@@ -118,14 +149,16 @@ export const confirmStickerUpload = createServerFn({ method: "POST" })
118
149
  !data.filePath.startsWith(`${safe(data.customerKey)}/`)) {
119
150
  throw new Error("Ongeldig bestandspad.");
120
151
  }
121
- const { data: existing } = await sb
122
- .from("customer_product_stickers")
152
+ const { data: existing, error: exErr } = await sb
153
+ .from(tabel)
123
154
  .select("file_path")
124
155
  .eq("customer_key", data.customerKey)
125
156
  .eq("trade_item_key", data.tradeItemKey)
126
157
  .maybeSingle();
158
+ if (exErr)
159
+ throw soortFout(data.soort, exErr);
127
160
  const det = await detectForPath(sb, data.filePath, data.mimeType, await loadLabels(sb));
128
- const { error } = await sb.from("customer_product_stickers").upsert({
161
+ const rij = {
129
162
  customer_key: data.customerKey,
130
163
  trade_item_key: data.tradeItemKey,
131
164
  width_mm: det.size?.width_mm ?? null,
@@ -136,12 +169,14 @@ export const confirmStickerUpload = createServerFn({ method: "POST" })
136
169
  file_size: data.fileSize ?? null,
137
170
  uploaded_by: context.userId ?? null,
138
171
  source: "manual",
139
- floriday_sticker_id: null,
140
172
  content_hash: null,
141
173
  updated_at: new Date().toISOString(),
142
- }, { onConflict: "customer_key,trade_item_key" });
174
+ };
175
+ if (data.soort === "product")
176
+ rij.floriday_sticker_id = null;
177
+ const { error } = await sb.from(tabel).upsert(rij, { onConflict: "customer_key,trade_item_key" });
143
178
  if (error)
144
- throw new Error(error.message);
179
+ throw soortFout(data.soort, error);
145
180
  if (existing?.file_path && existing.file_path !== data.filePath) {
146
181
  await sb.storage.from(BUCKET).remove([existing.file_path]);
147
182
  }
@@ -151,40 +186,44 @@ export const confirmStickerUpload = createServerFn({ method: "POST" })
151
186
  export const deleteCustomerSticker = createServerFn({ method: "POST" })
152
187
  .middleware([requireSupabaseAuth])
153
188
  .inputValidator((input) => z
154
- .object({ customerKey: z.string().min(1), tradeItemKey: z.string().min(1) })
189
+ .object({ customerKey: z.string().min(1), tradeItemKey: z.string().min(1), soort: soortSchema })
155
190
  .parse(input))
156
191
  .handler(async ({ data, context }) => {
157
192
  const sb = context.supabase;
158
- const { data: row } = await sb
159
- .from("customer_product_stickers")
193
+ const tabel = stickerTabel(data.soort);
194
+ const { data: row, error: rowErr } = await sb
195
+ .from(tabel)
160
196
  .select("file_path")
161
197
  .eq("customer_key", data.customerKey)
162
198
  .eq("trade_item_key", data.tradeItemKey)
163
199
  .maybeSingle();
200
+ if (rowErr)
201
+ throw soortFout(data.soort, rowErr);
164
202
  const { error } = await sb
165
- .from("customer_product_stickers")
203
+ .from(tabel)
166
204
  .delete()
167
205
  .eq("customer_key", data.customerKey)
168
206
  .eq("trade_item_key", data.tradeItemKey);
169
207
  if (error)
170
- throw new Error(error.message);
208
+ throw soortFout(data.soort, error);
171
209
  if (row?.file_path)
172
210
  await sb.storage.from(BUCKET).remove([row.file_path]);
173
211
  return { ok: true };
174
212
  });
175
213
  export const getCustomerStickerSettings = createServerFn({ method: "POST" })
176
214
  .middleware([requireSupabaseAuth])
177
- .inputValidator((input) => z.object({ customerKey: z.string().min(1) }).parse(input))
215
+ .inputValidator((input) => z.object({ customerKey: z.string().min(1), soort: soortSchema }).parse(input))
178
216
  .handler(async ({ data, context }) => {
179
217
  const sb = context.supabase;
218
+ const cols = data.soort === "fust" ? "width_mm, height_mm, fust_width_mm, fust_height_mm" : "width_mm, height_mm";
180
219
  const { data: fmt, error } = await sb
181
220
  .from("customer_sticker_settings")
182
- .select("width_mm, height_mm")
221
+ .select(cols)
183
222
  .eq("customer_key", data.customerKey)
184
223
  .maybeSingle();
185
224
  if (error)
186
225
  throw new Error(error.message);
187
- return fmt ? { width_mm: Number(fmt.width_mm), height_mm: Number(fmt.height_mm) } : null;
226
+ return formaatVoorSoort(fmt, data.soort);
188
227
  });
189
228
  export const setCustomerStickerSettings = createServerFn({ method: "POST" })
190
229
  .middleware([requireSupabaseAuth])
@@ -193,16 +232,15 @@ export const setCustomerStickerSettings = createServerFn({ method: "POST" })
193
232
  customerKey: z.string().min(1),
194
233
  widthMm: z.number().positive(),
195
234
  heightMm: z.number().positive(),
235
+ soort: soortSchema,
196
236
  })
197
237
  .parse(input))
198
238
  .handler(async ({ data, context }) => {
199
239
  const sb = context.supabase;
200
- const { error } = await sb.from("customer_sticker_settings").upsert({
201
- customer_key: data.customerKey,
202
- width_mm: data.widthMm,
203
- height_mm: data.heightMm,
204
- updated_at: new Date().toISOString(),
205
- }, { onConflict: "customer_key" });
240
+ const maat = data.soort === "fust"
241
+ ? { fust_width_mm: data.widthMm, fust_height_mm: data.heightMm }
242
+ : { width_mm: data.widthMm, height_mm: data.heightMm };
243
+ const { error } = await sb.from("customer_sticker_settings").upsert({ customer_key: data.customerKey, ...maat, updated_at: new Date().toISOString() }, { onConflict: "customer_key" });
206
244
  if (error)
207
245
  throw new Error(error.message);
208
246
  return { ok: true };
@@ -211,87 +249,46 @@ export const setCustomerStickerSettings = createServerFn({ method: "POST" })
211
249
  * Aanknopingspunt voor de pick-/printmodule: geeft het stickerbestand en het
212
250
  * ingestelde formaat terug, of null als er geen klantsticker gekoppeld is.
213
251
  */
214
- export const getStickerForPrint = createServerFn({ method: "POST" })
215
- .middleware([requireSupabaseAuth])
216
- .inputValidator((input) => z
217
- .object({ customerKey: z.string().min(1), tradeItemKey: z.string().min(1) })
218
- .parse(input))
219
- .handler(async ({ data, context }) => {
252
+ /** Kern van getStickerForPrint (los aanroepbaar voor tests). */
253
+ export async function getStickerForPrintKern(data, context) {
254
+ data = { ...data, soort: data?.soort === "fust" ? "fust" : "product" };
220
255
  const sb = context.supabase;
221
- const { data: row } = await sb
222
- .from("customer_product_stickers")
256
+ const { data: row, error: rowErr } = await sb
257
+ .from(stickerTabel(data.soort))
223
258
  .select("file_path, file_name, mime_type, width_mm, height_mm")
224
259
  .eq("customer_key", data.customerKey)
225
260
  .eq("trade_item_key", data.tradeItemKey)
226
261
  .maybeSingle();
262
+ if (rowErr && data.soort === "fust" && isTabelOntbreekt(rowErr)) {
263
+ console.error("customer_fust_stickers ontbreekt in deze database", rowErr);
264
+ return null;
265
+ }
227
266
  if (!row?.file_path)
228
267
  return null;
229
268
  const own = row.width_mm != null && row.height_mm != null;
230
- const { data: fmt } = await sb
231
- .from("customer_sticker_settings")
232
- .select("width_mm, height_mm")
233
- .eq("customer_key", data.customerKey)
234
- .maybeSingle();
269
+ const fmt = formaatVoorSoort(await leesInstellingen(sb, data.customerKey, data.soort), data.soort);
235
270
  return {
236
271
  url: await signed(sb, row.file_path),
237
272
  file_name: row.file_name,
238
273
  mime_type: (row.mime_type ?? null),
239
- width_mm: own ? Number(row.width_mm) : fmt ? Number(fmt.width_mm) : null,
240
- height_mm: own ? Number(row.height_mm) : fmt ? Number(fmt.height_mm) : null,
274
+ width_mm: own ? Number(row.width_mm) : fmt ? fmt.width_mm : null,
275
+ height_mm: own ? Number(row.height_mm) : fmt ? fmt.height_mm : null,
241
276
  };
242
- });
277
+ }
278
+ export const getStickerForPrint = createServerFn({ method: "POST" })
279
+ .middleware([requireSupabaseAuth])
280
+ .inputValidator((input) => z
281
+ .object({ customerKey: z.string().min(1), tradeItemKey: z.string().min(1), soort: soortSchema })
282
+ .parse(input))
283
+ .handler(async ({ data, context }) => getStickerForPrintKern(data, context));
243
284
  // ---------------------------------------------------------------------------
244
285
  // Bulk-upload met AI-herkenning
245
286
  // ---------------------------------------------------------------------------
246
287
  const MAX_STICKER_SIZE = 10 * 1024 * 1024;
247
288
  const AI_MODULE_KEY = "klanten-stickers";
248
289
  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 }) => {
290
+ /** Kern van suggestStickerMatches; los geëxporteerd zodat de AI-foutafhandeling testbaar is. */
291
+ export async function koppelStickerSuggesties(data, context) {
295
292
  const products = data.products.map((p) => ({
296
293
  key: p.key,
297
294
  name: p.name,
@@ -317,178 +314,189 @@ export const suggestStickerMatches = createServerFn({ method: "POST" })
317
314
  }
318
315
  if (remaining.length === 0)
319
316
  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
317
  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
- });
318
+ try {
319
+ const { resolveModuleModel, logAiCall } = await import("./ai-module.server.js");
320
+ const model = await resolveModuleModel(AI_MODULE_KEY);
321
+ const productList = products
322
+ .map((p) => `- key: ${p.key} | naam: ${p.name}` +
323
+ (p.code ? ` | artikelcode: ${p.code}` : "") +
324
+ (p.vbn ? ` | VBN: ${p.vbn}` : "") +
325
+ (p.botanical ? ` | botanisch: ${p.botanical}` : ""))
326
+ .join("\n");
327
+ for (let i = 0; i < remaining.length; i += 4) {
328
+ const batch = remaining.slice(i, i + 4);
329
+ const parts = [
330
+ {
331
+ text: "Je koppelt stickerbestanden aan producten uit het assortiment van een bloemenhandel.\n" +
332
+ "Producten:\n" +
333
+ productList +
334
+ "\n\nHieronder volgen stickers. Voor elke sticker krijg je eerst de bestandsnaam en daarna (indien beschikbaar) een afbeelding van de sticker.\n" +
335
+ "Geef per sticker het best passende product terug. Kies alleen een product als je het redelijk zeker weet; anders tradeItemKey = null.\n" +
336
+ 'Antwoord uitsluitend als JSON-array: [{"fileId":"...","tradeItemKey":"..."|null,"confidence":0.0-1.0,"reason":"korte uitleg in het Nederlands"}]',
337
+ },
338
+ ];
339
+ for (const f of batch) {
340
+ parts.push({ text: `Sticker fileId=${f.fileId} bestandsnaam="${f.fileName}"` });
341
+ const t = f.thumbnail ?? "";
342
+ const m = /^data:([^;,]+);base64,(.+)$/.exec(t);
343
+ if (m)
344
+ parts.push({ inline_data: { mime_type: m[1], data: m[2] } });
376
345
  }
377
- catch (e) {
378
- lastMessage = "De AI-dienst is niet bereikbaar. Probeer het zo nog eens.";
346
+ const url = model.providerSlug === "gemini"
347
+ ? geminiGenerateUrl(model.baseUrl, model.modelSlug)
348
+ : null;
349
+ if (!url) {
350
+ throw new Error(`AI-aanbieder "${model.providerSlug}" wordt hier nog niet ondersteund. Kies een Gemini-model bij AI-authenticatie.`);
351
+ }
352
+ let json = null;
353
+ let lastMessage = "AI-herkenning mislukt.";
354
+ for (let attempt = 0; attempt < 4; attempt++) {
355
+ const started = Date.now();
356
+ let res;
357
+ try {
358
+ res = await fetch(url, {
359
+ method: "POST",
360
+ headers: { "Content-Type": "application/json", "x-goog-api-key": model.apiKey },
361
+ body: JSON.stringify({
362
+ contents: [{ role: "user", parts }],
363
+ generationConfig: { responseMimeType: "application/json", temperature: 0 },
364
+ }),
365
+ });
366
+ }
367
+ catch (e) {
368
+ lastMessage = "De AI-dienst is niet bereikbaar. Probeer het zo nog eens.";
369
+ await logAiCall({
370
+ moduleKey: AI_MODULE_KEY,
371
+ providerSlug: model.providerSlug,
372
+ modelSlug: model.modelSlug,
373
+ status: "error",
374
+ durationMs: Date.now() - started,
375
+ errorCode: "network",
376
+ errorMessage: e instanceof Error ? e.message.slice(0, 500) : null,
377
+ createdBy: context.userId ?? null,
378
+ });
379
+ await new Promise((r) => setTimeout(r, 1500 * 2 ** attempt));
380
+ continue;
381
+ }
382
+ if (res.ok) {
383
+ json = await res.json();
384
+ await logAiCall({
385
+ moduleKey: AI_MODULE_KEY,
386
+ providerSlug: model.providerSlug,
387
+ modelSlug: model.modelSlug,
388
+ status: "success",
389
+ durationMs: Date.now() - started,
390
+ createdBy: context.userId ?? null,
391
+ });
392
+ break;
393
+ }
394
+ const body = await res.text();
379
395
  await logAiCall({
380
396
  moduleKey: AI_MODULE_KEY,
381
397
  providerSlug: model.providerSlug,
382
398
  modelSlug: model.modelSlug,
383
399
  status: "error",
384
400
  durationMs: Date.now() - started,
385
- errorCode: "network",
386
- errorMessage: e instanceof Error ? e.message.slice(0, 500) : null,
401
+ errorCode: String(res.status),
402
+ errorMessage: body.slice(0, 500),
387
403
  createdBy: context.userId ?? null,
388
404
  });
389
- await new Promise((r) => setTimeout(r, 1500 * 2 ** attempt));
390
- continue;
405
+ if (res.status === 401 || res.status === 403) {
406
+ throw new Error("De AI-sleutel wordt geweigerd. Controleer de sleutel bij AI-authenticatie.");
407
+ }
408
+ if (res.status === 400 || res.status === 404) {
409
+ throw new Error(`Het ingestelde AI-model werd geweigerd (${res.status}). Controleer het model bij AI-authenticatie.`);
410
+ }
411
+ if (res.status === 429 || res.status >= 500) {
412
+ lastMessage =
413
+ "De AI-dienst is tijdelijk overbelast. De stickers zijn geüpload; koppel ze handmatig of probeer de herkenning zo nog eens.";
414
+ const retryAfter = Number(res.headers.get("retry-after"));
415
+ const waitMs = Number.isFinite(retryAfter) && retryAfter > 0
416
+ ? retryAfter * 1000
417
+ : 1500 * 2 ** attempt;
418
+ if (attempt < 3)
419
+ await new Promise((r) => setTimeout(r, waitMs));
420
+ continue;
421
+ }
422
+ throw new Error(`De AI-dienst gaf een fout (${res.status}).`);
391
423
  }
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;
424
+ if (!json) {
425
+ aiError = lastMessage;
426
+ for (const b of batch) {
427
+ suggestions.push({ fileId: b.fileId, tradeItemKey: null, confidence: 0, reason: null });
428
+ }
429
+ continue;
403
430
  }
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.");
431
+ const text = json?.candidates?.[0]?.content?.parts?.map((p) => p?.text ?? "").join("") ?? "";
432
+ const cleaned = text.trim().replace(/^```(?:json)?/i, "").replace(/```$/, "");
433
+ let parsed = [];
434
+ try {
435
+ parsed = JSON.parse(cleaned);
417
436
  }
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.`);
437
+ catch {
438
+ parsed = [];
420
439
  }
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;
440
+ const validKeys = new Set(products.map((p) => p.key));
441
+ for (const row of Array.isArray(parsed) ? parsed : []) {
442
+ const fileId = String(row?.fileId ?? "");
443
+ if (!batch.some((b) => b.fileId === fileId))
444
+ continue;
445
+ const key = row?.tradeItemKey ? String(row.tradeItemKey) : null;
446
+ suggestions.push({
447
+ fileId,
448
+ tradeItemKey: key && validKeys.has(key) ? key : null,
449
+ confidence: Number.isFinite(Number(row?.confidence)) ? Number(row.confidence) : 0,
450
+ reason: row?.reason ? String(row.reason).slice(0, 200) : null,
451
+ });
431
452
  }
432
- throw new Error(`De AI-dienst gaf een fout (${res.status}).`);
433
- }
434
- if (!json) {
435
- aiError = lastMessage;
436
453
  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 });
454
+ if (!suggestions.some((s) => s.fileId === b.fileId)) {
455
+ suggestions.push({ fileId: b.fileId, tradeItemKey: null, confidence: 0, reason: null });
456
+ }
466
457
  }
467
458
  }
468
459
  }
460
+ catch (e) {
461
+ // AI-fout: koppelingen op bestandsnaam blijven staan, reden gaat mee.
462
+ console.error("AI-herkenning van stickers mislukt", e);
463
+ aiError =
464
+ e instanceof Error && e.message
465
+ ? e.message
466
+ : "Automatisch herkennen lukte niet. Koppel de overige stickers handmatig.";
467
+ }
469
468
  return { suggestions, aiError };
470
- return { suggestions };
471
- });
472
- export const commitStickerBatch = createServerFn({ method: "POST" })
469
+ }
470
+ export const suggestStickerMatches = createServerFn({ method: "POST" })
473
471
  .middleware([requireSupabaseAuth])
474
472
  .inputValidator((input) => z
475
473
  .object({
476
- customerKey: z.string().min(1),
477
- batchId: z.string().min(1),
478
- items: z
474
+ files: z
479
475
  .array(z.object({
480
- inboxPath: z.string().min(1),
476
+ fileId: z.string().min(1),
481
477
  fileName: z.string().min(1),
482
- mimeType: z.string().min(1),
483
- fileSize: z.number().nullable().optional(),
484
- tradeItemKey: z.string().min(1),
485
- replaceExisting: z.boolean().default(false),
478
+ thumbnail: z.string().nullable().optional(),
486
479
  }))
487
- .min(1),
480
+ .min(1)
481
+ .max(200),
482
+ products: z
483
+ .array(z.object({
484
+ key: z.string().min(1),
485
+ name: z.string(),
486
+ code: z.string().nullable().optional(),
487
+ vbn: z.string().nullable().optional(),
488
+ botanical: z.string().nullable().optional(),
489
+ }))
490
+ .min(1)
491
+ .max(2000),
488
492
  })
489
493
  .parse(input))
490
- .handler(async ({ data, context }) => {
494
+ .handler(async ({ data, context }) => koppelStickerSuggesties(data, context));
495
+ /** Kern van commitStickerBatch (los aanroepbaar voor tests). */
496
+ export async function commitStickerBatchKern(data, context) {
497
+ data = { ...data, soort: data?.soort === "fust" ? "fust" : "product" };
491
498
  const sb = context.supabase;
499
+ const tabel = stickerTabel(data.soort);
492
500
  const prefix = `${safeStorageKey(data.customerKey)}/_inbox/${safeStorageKey(data.batchId)}/`;
493
501
  let linked = 0;
494
502
  let replaced = 0;
@@ -505,24 +513,26 @@ export const commitStickerBatch = createServerFn({ method: "POST" })
505
513
  }
506
514
  if ((it.fileSize ?? 0) > MAX_STICKER_SIZE)
507
515
  throw new Error("Bestand is groter dan 10 MB.");
508
- const { data: existing } = await sb
509
- .from("customer_product_stickers")
516
+ const { data: existing, error: exErr } = await sb
517
+ .from(tabel)
510
518
  .select("file_path")
511
519
  .eq("customer_key", data.customerKey)
512
520
  .eq("trade_item_key", it.tradeItemKey)
513
521
  .maybeSingle();
522
+ if (exErr)
523
+ throw soortFout(data.soort, exErr);
514
524
  if (existing?.file_path && !it.replaceExisting) {
515
525
  skipped++;
516
526
  continue;
517
527
  }
518
528
  const ext = (/\.([a-z0-9]+)$/i.exec(it.fileName)?.[1] ?? "bin").toLowerCase();
519
- const target = `${safeStorageKey(data.customerKey)}/${safeStorageKey(it.tradeItemKey)}/${crypto.randomUUID()}.${ext}`;
529
+ const target = stickerDoelpad(safeStorageKey(data.customerKey), safeStorageKey(it.tradeItemKey), data.soort, `${crypto.randomUUID()}.${ext}`);
520
530
  const { error: moveErr } = await sb.storage.from(BUCKET).move(it.inboxPath, target);
521
531
  if (moveErr)
522
532
  throw new Error(moveErr.message);
523
533
  const det = await detectForPath(sb, target, it.mimeType, labels);
524
534
  sizes.push({ fileName: it.fileName, tradeItemKey: it.tradeItemKey, method: det.method, size: det.size, suggestion: det.suggestion });
525
- const { error: upErr } = await sb.from("customer_product_stickers").upsert({
535
+ const rij = {
526
536
  customer_key: data.customerKey,
527
537
  trade_item_key: it.tradeItemKey,
528
538
  file_path: target,
@@ -533,12 +543,14 @@ export const commitStickerBatch = createServerFn({ method: "POST" })
533
543
  file_size: it.fileSize ?? null,
534
544
  uploaded_by: context.userId ?? null,
535
545
  source: "manual",
536
- floriday_sticker_id: null,
537
546
  content_hash: null,
538
547
  updated_at: new Date().toISOString(),
539
- }, { onConflict: "customer_key,trade_item_key" });
548
+ };
549
+ if (data.soort === "product")
550
+ rij.floriday_sticker_id = null;
551
+ const { error: upErr } = await sb.from(tabel).upsert(rij, { onConflict: "customer_key,trade_item_key" });
540
552
  if (upErr)
541
- throw new Error(upErr.message);
553
+ throw soortFout(data.soort, upErr);
542
554
  if (existing?.file_path) {
543
555
  await sb.storage.from(BUCKET).remove([existing.file_path]);
544
556
  replaced++;
@@ -557,7 +569,27 @@ export const commitStickerBatch = createServerFn({ method: "POST" })
557
569
  if (paths.length)
558
570
  await sb.storage.from(BUCKET).remove(paths);
559
571
  return { linked, replaced, skipped, failed, sizes };
560
- });
572
+ }
573
+ export const commitStickerBatch = createServerFn({ method: "POST" })
574
+ .middleware([requireSupabaseAuth])
575
+ .inputValidator((input) => z
576
+ .object({
577
+ customerKey: z.string().min(1),
578
+ batchId: z.string().min(1),
579
+ items: z
580
+ .array(z.object({
581
+ inboxPath: z.string().min(1),
582
+ fileName: z.string().min(1),
583
+ mimeType: z.string().min(1),
584
+ fileSize: z.number().nullable().optional(),
585
+ tradeItemKey: z.string().min(1),
586
+ replaceExisting: z.boolean().default(false),
587
+ }))
588
+ .min(1),
589
+ soort: soortSchema,
590
+ })
591
+ .parse(input))
592
+ .handler(async ({ data, context }) => commitStickerBatchKern(data, context));
561
593
  export const discardStickerBatch = createServerFn({ method: "POST" })
562
594
  .middleware([requireSupabaseAuth])
563
595
  .inputValidator((input) => z.object({ customerKey: z.string().min(1), batchId: z.string().min(1) }).parse(input))
@@ -579,13 +611,14 @@ export const setStickerSize = createServerFn({ method: "POST" })
579
611
  tradeItemKey: z.string().min(1),
580
612
  widthMm: z.number().positive().max(1000),
581
613
  heightMm: z.number().positive().max(1000),
614
+ soort: soortSchema,
582
615
  })
583
616
  .parse(input))
584
617
  .handler(async ({ data, context }) => {
585
618
  const sb = context.supabase;
586
619
  const r = (v) => Math.round(v * 10) / 10;
587
620
  const { error } = await sb
588
- .from("customer_product_stickers")
621
+ .from(stickerTabel(data.soort))
589
622
  .update({ width_mm: r(data.widthMm), height_mm: r(data.heightMm), updated_at: new Date().toISOString() })
590
623
  .eq("customer_key", data.customerKey)
591
624
  .eq("trade_item_key", data.tradeItemKey);
@@ -596,11 +629,11 @@ export const setStickerSize = createServerFn({ method: "POST" })
596
629
  /** Voorstel voor één sticker zonder maat (voor de knop in de stickercel). */
597
630
  export const suggestStickerSize = createServerFn({ method: "POST" })
598
631
  .middleware([requireSupabaseAuth])
599
- .inputValidator((input) => z.object({ customerKey: z.string().min(1), tradeItemKey: z.string().min(1) }).parse(input))
632
+ .inputValidator((input) => z.object({ customerKey: z.string().min(1), tradeItemKey: z.string().min(1), soort: soortSchema }).parse(input))
600
633
  .handler(async ({ data, context }) => {
601
634
  const sb = context.supabase;
602
635
  const { data: row } = await sb
603
- .from("customer_product_stickers")
636
+ .from(stickerTabel(data.soort))
604
637
  .select("file_path, mime_type")
605
638
  .eq("customer_key", data.customerKey)
606
639
  .eq("trade_item_key", data.tradeItemKey)