@flowselections/facturen-installatie-techniek 1.0.2 → 1.3.4

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 (53) hide show
  1. package/dist-lib/components/ArticlePhoto.d.ts +8 -0
  2. package/dist-lib/components/ArticlePhoto.d.ts.map +1 -0
  3. package/dist-lib/components/ArticlePhoto.js +7 -0
  4. package/dist-lib/components/FacturenForInstallatieTechniek.d.ts.map +1 -1
  5. package/dist-lib/components/FacturenForInstallatieTechniek.js +143 -50
  6. package/dist-lib/components/FactuurDetailPage.d.ts.map +1 -1
  7. package/dist-lib/components/FactuurDetailPage.js +224 -13
  8. package/dist-lib/components/InvoiceA4Preview.d.ts +19 -0
  9. package/dist-lib/components/InvoiceA4Preview.d.ts.map +1 -0
  10. package/dist-lib/components/InvoiceA4Preview.js +118 -0
  11. package/dist-lib/components/InvoiceDetailsFields.d.ts +7 -0
  12. package/dist-lib/components/InvoiceDetailsFields.d.ts.map +1 -0
  13. package/dist-lib/components/InvoiceDetailsFields.js +21 -0
  14. package/dist-lib/components/WerkbonPreviewPanel.d.ts +4 -0
  15. package/dist-lib/components/WerkbonPreviewPanel.d.ts.map +1 -0
  16. package/dist-lib/components/WerkbonPreviewPanel.js +40 -0
  17. package/dist-lib/components/settings/InstellingenPage.d.ts +5 -0
  18. package/dist-lib/components/settings/InstellingenPage.d.ts.map +1 -0
  19. package/dist-lib/components/settings/InstellingenPage.js +119 -0
  20. package/dist-lib/components/settings/InvoiceBrandingSettingsCard.d.ts +2 -0
  21. package/dist-lib/components/settings/InvoiceBrandingSettingsCard.d.ts.map +1 -0
  22. package/dist-lib/components/settings/InvoiceBrandingSettingsCard.js +64 -0
  23. package/dist-lib/components/settings/InvoiceEmailSettingsCard.d.ts +2 -0
  24. package/dist-lib/components/settings/InvoiceEmailSettingsCard.d.ts.map +1 -0
  25. package/dist-lib/components/settings/InvoiceEmailSettingsCard.js +41 -0
  26. package/dist-lib/index.d.ts +8 -0
  27. package/dist-lib/index.d.ts.map +1 -1
  28. package/dist-lib/index.js +14 -2
  29. package/dist-lib/integrations/supabase/auth-middleware.d.ts +11 -22550
  30. package/dist-lib/integrations/supabase/auth-middleware.d.ts.map +1 -1
  31. package/dist-lib/integrations/supabase/auth-middleware.js +3 -1
  32. package/dist-lib/integrations/supabase/client.d.ts +2 -22547
  33. package/dist-lib/integrations/supabase/client.d.ts.map +1 -1
  34. package/dist-lib/integrations/supabase/client.js +4 -1
  35. package/dist-lib/integrations/supabase/client.server.d.ts +2 -22547
  36. package/dist-lib/integrations/supabase/client.server.d.ts.map +1 -1
  37. package/dist-lib/integrations/supabase/client.server.js +1 -0
  38. package/dist-lib/integrations/supabase/previewAuthStorage.d.ts +6 -0
  39. package/dist-lib/integrations/supabase/previewAuthStorage.d.ts.map +1 -0
  40. package/dist-lib/integrations/supabase/previewAuthStorage.js +99 -0
  41. package/dist-lib/integrations/supabase/types.d.ts +24631 -11349
  42. package/dist-lib/integrations/supabase/types.d.ts.map +1 -1
  43. package/dist-lib/integrations/supabase/types.js +2 -0
  44. package/dist-lib/lib/articles.functions.d.ts +19 -0
  45. package/dist-lib/lib/articles.functions.d.ts.map +1 -0
  46. package/dist-lib/lib/articles.functions.js +91 -0
  47. package/dist-lib/lib/config.d.ts +16 -0
  48. package/dist-lib/lib/config.d.ts.map +1 -0
  49. package/dist-lib/lib/config.js +17 -0
  50. package/dist-lib/lib/facturen.d.ts +196 -0
  51. package/dist-lib/lib/facturen.d.ts.map +1 -1
  52. package/dist-lib/lib/facturen.js +441 -16
  53. package/package.json +57 -5
@@ -1,5 +1,80 @@
1
1
  import { supabase } from "@flowselections/core";
2
+ export const emptyInvoiceBranding = () => ({
3
+ company_name: "", address: "", postal_code: "", city: "",
4
+ chamber_of_commerce_number: "", vat_identification_number: "",
5
+ email: "", phone: "", iban: "", website: "",
6
+ primary_color: "#17365D", secondary_color: "#6B7280", logo_path: null,
7
+ payment_term_days: 30,
8
+ show_company_name: true,
9
+ });
10
+ export async function fetchInvoiceBranding() {
11
+ const { data, error } = await db.from("invoice_branding_settings").select("*").eq("singleton_key", true).maybeSingle();
12
+ if (error)
13
+ throw error;
14
+ return data ? { ...emptyInvoiceBranding(), ...data } : emptyInvoiceBranding();
15
+ }
16
+ export async function saveInvoiceBranding(value) {
17
+ const { data, error } = await db.rpc("invoice_save_branding_settings", { _payload: value });
18
+ if (error)
19
+ throw error;
20
+ return { ...emptyInvoiceBranding(), ...data };
21
+ }
22
+ export async function getInvoiceLogoUrl(path) {
23
+ if (!path)
24
+ return null;
25
+ const { data, error } = await supabase.storage.from(STORAGE_BUCKETS.logos).createSignedUrl(path, 3600);
26
+ if (error)
27
+ return null;
28
+ return data?.signedUrl ?? null;
29
+ }
2
30
  const db = supabase;
31
+ import { DEFAULT_VAT_RATE, STORAGE_BUCKETS, INVOICE_PAGE_SIZE, MAX_TOTAL_ROWS, QUERY_BATCH_SIZE } from "./config";
32
+ /** Klanten uit Klanten (Planner) — alleen lezen. */
33
+ export async function fetchCustomers() {
34
+ return fetchAllPages((from, to) => db
35
+ .from("itk_customers")
36
+ .select("id, name, customer_number, general_email, billing_street, billing_postcode, billing_city, vat_number")
37
+ .order("name", { ascending: true })
38
+ .order("id", { ascending: true })
39
+ .range(from, to));
40
+ }
41
+ /** Haalt alle rijen op in blokken, zodat er nooit stil rijen wegvallen door de 1000-rijenlimiet. */
42
+ export async function fetchAllPages(page, batch = QUERY_BATCH_SIZE) {
43
+ const out = [];
44
+ for (let from = 0; from < MAX_TOTAL_ROWS; from += batch) {
45
+ const { data, error } = await page(from, from + batch - 1);
46
+ if (error)
47
+ throw error;
48
+ const rows = Array.isArray(data) ? data : [];
49
+ out.push(...rows);
50
+ if (rows.length < batch)
51
+ break;
52
+ }
53
+ return out;
54
+ }
55
+ export async function fetchCustomerEmail(customerId) {
56
+ if (!customerId)
57
+ return "";
58
+ const { data, error } = await db
59
+ .from("itk_customers")
60
+ .select("general_email")
61
+ .eq("id", customerId)
62
+ .maybeSingle();
63
+ if (error)
64
+ throw error;
65
+ return typeof data?.general_email === "string" ? data.general_email : "";
66
+ }
67
+ export async function fetchPackages() {
68
+ const { data, error } = await db
69
+ .from("werkbon_packages")
70
+ .select("id, code, name, description, unit_price_cents, default_quantity")
71
+ .eq("active", true)
72
+ .order("sort_order", { ascending: true })
73
+ .order("name", { ascending: true });
74
+ if (error)
75
+ throw error;
76
+ return Array.isArray(data) ? data : [];
77
+ }
3
78
  export const STATUS_LABELS = {
4
79
  concept: "Concept",
5
80
  verzonden: "Verzonden",
@@ -29,23 +104,100 @@ export function euroToCents(input) {
29
104
  const parsed = parseFloat(String(input).replace(/\./g, "").replace(",", "."));
30
105
  return Number.isFinite(parsed) ? Math.round(parsed * 100) : 0;
31
106
  }
107
+ async function ensureSession() {
108
+ try {
109
+ const { data: sessionData } = await supabase.auth.getSession();
110
+ const session = sessionData?.session;
111
+ if (session?.access_token && session.refresh_token) {
112
+ await supabase.auth.setSession({ access_token: session.access_token, refresh_token: session.refresh_token });
113
+ }
114
+ return Boolean(session?.access_token);
115
+ }
116
+ catch {
117
+ return false;
118
+ }
119
+ }
120
+ // Haalt alle conceptfacturen op (die moeten altijd zichtbaar zijn) plus één pagina
121
+ // van de overige facturen. Zet eerst de opgeslagen sessie opnieuw op de client:
122
+ // er kunnen twee clients dezelfde sessie delen, waardoor een aanvraag ongemerkt
123
+ // als gast vertrekt en leeg terugkomt. Bij een lege lijst volgt één herkansing.
124
+ export async function fetchInvoicesDetailed(opts = {}) {
125
+ const authenticated = await ensureSession();
126
+ const offset = Math.max(0, opts.offset ?? 0);
127
+ const status = opts.status && opts.status !== "alle" ? opts.status : null;
128
+ const source = opts.source && opts.source !== "alle" ? opts.source : null;
129
+ const loadConcepts = () => status && status !== "concept"
130
+ ? Promise.resolve([])
131
+ : fetchAllPages((from, to) => {
132
+ let q = db.from("invoices").select("*").eq("status", "concept");
133
+ if (source)
134
+ q = q.eq("source_type", source);
135
+ return q.order("created_at", { ascending: false }).order("id").range(from, to);
136
+ });
137
+ const loadPage = async () => {
138
+ if (status === "concept")
139
+ return { rows: [], hasMore: false };
140
+ let q = db.from("invoices").select("*").neq("status", "concept");
141
+ if (status)
142
+ q = q.eq("status", status);
143
+ if (source)
144
+ q = q.eq("source_type", source);
145
+ const { data, error } = await q
146
+ .order("created_at", { ascending: false })
147
+ .order("id")
148
+ .range(offset, offset + INVOICE_PAGE_SIZE);
149
+ if (error)
150
+ throw error;
151
+ const rows = Array.isArray(data) ? data : [];
152
+ return { rows: rows.slice(0, INVOICE_PAGE_SIZE), hasMore: rows.length > INVOICE_PAGE_SIZE };
153
+ };
154
+ const run = async () => {
155
+ const [concepts, page] = await Promise.all([offset === 0 ? loadConcepts() : Promise.resolve([]), loadPage()]);
156
+ return { invoices: [...concepts, ...page.rows], hasMore: page.hasMore };
157
+ };
158
+ try {
159
+ let result = await run();
160
+ if (result.invoices.length === 0 && authenticated && offset === 0)
161
+ result = await run();
162
+ return { ...result, authenticated, failed: false };
163
+ }
164
+ catch {
165
+ return { invoices: [], authenticated, failed: true, hasMore: false };
166
+ }
167
+ }
168
+ export async function fetchInvoiceKpis() {
169
+ const yearStart = `${new Date().getFullYear()}-01-01`;
170
+ const [paid, open] = await Promise.all([
171
+ fetchAllPages((from, to) => db.from("invoices").select("id, total_cents, invoice_date").eq("status", "betaald").gte("invoice_date", yearStart).order("id").range(from, to)),
172
+ db.from("invoices").select("id", { count: "exact", head: true }).in("status", ["verzonden", "vervallen"]),
173
+ ]);
174
+ if (open.error)
175
+ throw open.error;
176
+ return { paidThisYear: paid, openCount: Number(open.count) || 0 };
177
+ }
178
+ /** Alle facturen (nieuwste eerst), in blokken opgehaald — o.a. voor vorige/volgende. */
32
179
  export async function fetchInvoices() {
33
- const { data, error } = await db
34
- .from("invoices")
35
- .select("*")
36
- .order("created_at", { ascending: false })
37
- .limit(500);
38
- if (error)
39
- throw error;
40
- return Array.isArray(data) ? data : [];
180
+ await ensureSession();
181
+ return fetchAllPages((from, to) => db.from("invoices").select("*").order("created_at", { ascending: false }).order("id").range(from, to));
41
182
  }
42
183
  export async function fetchInvoice(id) {
43
- const { data, error } = await db.from("invoices").select("*").eq("id", id).maybeSingle();
44
- if (error)
45
- throw error;
46
- return data ?? null;
184
+ const once = async () => {
185
+ const { data, error } = await db.from("invoices").select("*").eq("id", id).maybeSingle();
186
+ if (error)
187
+ throw error;
188
+ return data ?? null;
189
+ };
190
+ await ensureSession();
191
+ const first = await once();
192
+ if (first)
193
+ return first;
194
+ // Sessie hing mogelijk nog niet aan de verbinding: één keer opnieuw proberen.
195
+ await new Promise((r) => setTimeout(r, 300));
196
+ await ensureSession();
197
+ return once();
47
198
  }
48
199
  export async function fetchInvoiceItems(id) {
200
+ await ensureSession();
49
201
  const { data, error } = await db
50
202
  .from("invoice_items")
51
203
  .select("*")
@@ -65,9 +217,10 @@ export async function listSources(sourceType) {
65
217
  return Array.isArray(data) ? data : [];
66
218
  }
67
219
  export async function fetchSourceLines(sourceType, sourceId) {
68
- const fn = sourceType === "work_order" ? "wo_get_billable_lines" : "quote_get_billable_lines";
69
- const arg = sourceType === "work_order" ? { _work_order_id: sourceId } : { _quotation_id: sourceId };
70
- const { data, error } = await db.rpc(fn, arg);
220
+ const { data, error } = await db.rpc("invoice_source_lines", {
221
+ _source_type: sourceType,
222
+ _source_id: sourceId,
223
+ });
71
224
  if (error)
72
225
  throw error;
73
226
  return Array.isArray(data) ? data : [];
@@ -80,9 +233,10 @@ export async function createInvoiceFromSource(payload) {
80
233
  source_number: payload.sourceNumber ?? null,
81
234
  customer_id: payload.customerId ?? null,
82
235
  customer_name: payload.customerName ?? null,
83
- vat_rate: payload.vatRate ?? 21,
236
+ vat_rate: payload.vatRate ?? DEFAULT_VAT_RATE,
84
237
  invoice_date: payload.invoiceDate ?? new Date().toISOString().slice(0, 10),
85
238
  note: payload.note ?? null,
239
+ ...(payload.details ? detailsToPayload(payload.details) : {}),
86
240
  lines: payload.lines,
87
241
  },
88
242
  });
@@ -92,11 +246,282 @@ export async function createInvoiceFromSource(payload) {
92
246
  }
93
247
  export async function updateInvoiceStatus(id, status) {
94
248
  const { error } = await db.from("invoices").update({ status }).eq("id", id);
249
+ if (error)
250
+ throw new Error(error.message || "Status kon niet worden gewijzigd");
251
+ }
252
+ // Marqueert een factuur als verzonden, maar alleen als er bewijs van de e-mail is:
253
+ // de outbox-rij moet bestaan en de PDF van díe factuur als bijlage hebben.
254
+ export async function registerInvoiceSend(invoiceId, outboxId) {
255
+ const { data, error } = await db.rpc("invoice_register_send", { _invoice_id: invoiceId, _outbox_id: outboxId });
256
+ if (error)
257
+ throw new Error(error.message || "De factuur kon niet als verzonden worden geregistreerd");
258
+ return (data ?? {});
259
+ }
260
+ export const emptyInvoiceDetails = (paymentTermDays = 30) => ({
261
+ customer_name: "",
262
+ customer_attention: "",
263
+ customer_address: "",
264
+ customer_postal_code: "",
265
+ customer_city: "",
266
+ debtor_number: "",
267
+ customer_vat_number: "",
268
+ invoice_date: new Date().toISOString().slice(0, 10),
269
+ payment_term_days: String(paymentTermDays),
270
+ reference: "",
271
+ source_number: "",
272
+ work_address: "",
273
+ execution_date: "",
274
+ });
275
+ export function detailsFromRecord(r) {
276
+ const base = emptyInvoiceDetails();
277
+ if (!r)
278
+ return base;
279
+ const out = { ...base };
280
+ Object.keys(base).forEach((k) => {
281
+ const v = r[k];
282
+ if (v !== null && v !== undefined && v !== "")
283
+ out[k] = String(v);
284
+ });
285
+ return out;
286
+ }
287
+ export function detailsToPayload(d) {
288
+ const term = parseInt(d.payment_term_days, 10);
289
+ const due = new Date(d.invoice_date || new Date().toISOString().slice(0, 10));
290
+ due.setDate(due.getDate() + (Number.isFinite(term) ? term : 30));
291
+ return {
292
+ customer_name: d.customer_name.trim() || null,
293
+ customer_attention: d.customer_attention.trim() || null,
294
+ customer_address: d.customer_address.trim() || null,
295
+ customer_postal_code: d.customer_postal_code.trim() || null,
296
+ customer_city: d.customer_city.trim() || null,
297
+ debtor_number: d.debtor_number.trim() || null,
298
+ customer_vat_number: d.customer_vat_number.trim() || null,
299
+ invoice_date: d.invoice_date || null,
300
+ payment_term_days: Number.isFinite(term) ? term : 30,
301
+ due_date: due.toISOString().slice(0, 10),
302
+ reference: d.reference.trim() || null,
303
+ source_number: d.source_number.trim() || null,
304
+ work_address: d.work_address.trim() || null,
305
+ execution_date: d.execution_date || null,
306
+ };
307
+ }
308
+ export async function updateInvoiceDetails(id, d) {
309
+ const { error } = await db.from("invoices").update(detailsToPayload(d)).eq("id", id);
95
310
  if (error)
96
311
  throw error;
97
312
  }
313
+ export async function fetchReadyWorkOrders() {
314
+ const { data, error } = await db.rpc("invoice_ready_work_orders", { _limit: 200 });
315
+ if (error)
316
+ throw error;
317
+ return Array.isArray(data) ? data : [];
318
+ }
319
+ /** Werkbon-id's waarvoor in Offertes al een offerte bestaat (alleen lezen, informatief). */
320
+ export async function fetchWorkOrderIdsWithQuote(ids) {
321
+ const result = new Set();
322
+ if (ids.length === 0)
323
+ return result;
324
+ const list = ids.join(",");
325
+ const { data, error } = await db
326
+ .from("itk_offertes")
327
+ .select("source_ref, werkbon_id")
328
+ .or(`source_ref.in.(${list}),werkbon_id.in.(${list})`);
329
+ if (error)
330
+ return result;
331
+ const rows = Array.isArray(data) ? data : [];
332
+ for (const r of rows) {
333
+ if (r.source_ref)
334
+ result.add(r.source_ref);
335
+ if (r.werkbon_id)
336
+ result.add(r.werkbon_id);
337
+ }
338
+ return result;
339
+ }
98
340
  export async function deleteInvoice(id) {
99
341
  const { error } = await db.from("invoices").delete().eq("id", id);
342
+ if (error)
343
+ throw new Error(error.message || "Factuur kon niet worden verwijderd");
344
+ }
345
+ export async function fetchWorkOrderPreview(id) {
346
+ const { data, error } = await db
347
+ .from("werkbonnen")
348
+ .select("id, project_number, status, work_address, room_number, scheduled_start_time, scheduled_end_time, complaint_description, technician_task_description, technician_notes, externe_referentie, signature_name, signature_accepted_at, customer_id")
349
+ .eq("id", id)
350
+ .maybeSingle();
100
351
  if (error)
101
352
  throw error;
353
+ if (!data)
354
+ return null;
355
+ const row = data;
356
+ let customer_name = null;
357
+ if (row.customer_id) {
358
+ const { data: c } = await db.from("itk_customers").select("name").eq("id", row.customer_id).maybeSingle();
359
+ customer_name = c?.name ?? null;
360
+ }
361
+ return { ...row, customer_name };
362
+ }
363
+ export const emptyEditLine = (vat = String(DEFAULT_VAT_RATE)) => ({ description: "", quantity: "1", unit: "stuk", price: "", vat, kind: "other" });
364
+ const num = (v) => { const n = parseFloat(String(v).replace(",", ".")); return Number.isFinite(n) ? n : 0; };
365
+ export function editLineToBillable(l, index) {
366
+ const quantity = num(l.quantity);
367
+ const unit_price_cents = euroToCents(l.price);
368
+ return {
369
+ description: l.description.trim(),
370
+ kind: l.packageId ? "package" : l.kind || "other",
371
+ quantity,
372
+ unit: l.unit || "stuk",
373
+ unit_price_cents,
374
+ line_total_cents: Math.round(quantity * unit_price_cents),
375
+ sort_order: index + 1,
376
+ vat_rate: num(l.vat),
377
+ source_line_ref: l.articleId ?? undefined,
378
+ };
379
+ }
380
+ export function itemToEditLine(i, fallbackVat) {
381
+ return {
382
+ description: i.description ?? "",
383
+ quantity: String(Number(i.quantity) || 0),
384
+ unit: i.unit || "stuk",
385
+ price: ((Number(i.unit_price_cents) || 0) / 100).toFixed(2).replace(".", ","),
386
+ vat: String(i.vat_rate ?? fallbackVat),
387
+ kind: i.kind || "other",
388
+ articleId: i.kind === "material" ? i.source_line_ref ?? undefined : undefined,
389
+ };
390
+ }
391
+ export async function peekNextInvoiceNumber() {
392
+ const { data, error } = await db.rpc("invoice_peek_next_number");
393
+ if (error)
394
+ return null;
395
+ return typeof data === "string" ? data : null;
396
+ }
397
+ export async function updateInvoiceFull(id, d, lines, note) {
398
+ const payloadLines = lines.filter((l) => l.description.trim()).map(editLineToBillable);
399
+ const { error } = await db.rpc("invoice_update_full", {
400
+ _invoice_id: id,
401
+ _payload: { ...detailsToPayload(d), note, lines: payloadLines },
402
+ });
403
+ if (error)
404
+ throw error;
405
+ const { data: savedItems, error: itemsError } = await db
406
+ .from("invoice_items")
407
+ .select("id, sort_order")
408
+ .eq("invoice_id", id)
409
+ .order("sort_order", { ascending: true });
410
+ if (itemsError)
411
+ throw itemsError;
412
+ const safeItems = Array.isArray(savedItems) ? savedItems : [];
413
+ await Promise.all(safeItems.map((item, index) => {
414
+ const articleId = payloadLines[index]?.source_line_ref ?? null;
415
+ return db.from("invoice_items").update({ source_line_ref: articleId }).eq("id", item.id).then(({ error: updateError }) => {
416
+ if (updateError)
417
+ throw updateError;
418
+ });
419
+ }));
420
+ }
421
+ /** Standaard e-maildoeleinden van de e-mailmodule. */
422
+ export const EMAIL_PURPOSE_OPTIONS = [
423
+ { key: "orders", label: "Orders" }, { key: "support", label: "Support" },
424
+ { key: "internal", label: "Intern" }, { key: "system", label: "Systeem" },
425
+ { key: "marketing", label: "Marketing" }, { key: "inkoop", label: "Inkoop" },
426
+ { key: "transport", label: "Transport" },
427
+ ];
428
+ export async function fetchInvoiceEmailPurpose() {
429
+ const { data, error } = await db.from("invoice_branding_settings").select("email_purpose").eq("singleton_key", true).maybeSingle();
430
+ if (error)
431
+ throw error;
432
+ const v = data?.email_purpose;
433
+ return typeof v === "string" && v ? v : null;
434
+ }
435
+ export async function saveInvoiceEmailPurpose(purpose) {
436
+ const { error } = await db.rpc("invoice_set_email_purpose", { _purpose: purpose });
437
+ if (error)
438
+ throw error;
439
+ }
440
+ const PDF_SIGNATURE_BASE64 = "JVBERi0";
441
+ function assertValidPdfBase64(value) {
442
+ const normalized = value.replace(/\s/g, "");
443
+ if (!normalized || !normalized.startsWith(PDF_SIGNATURE_BASE64)) {
444
+ throw new Error("De factuur-PDF kon niet geldig worden aangemaakt. Probeer het opnieuw.");
445
+ }
446
+ if (normalized.length < 1000) {
447
+ throw new Error("De aangemaakte factuur-PDF is leeg of onvolledig.");
448
+ }
449
+ }
450
+ export async function fetchSenderForPurpose(purpose) {
451
+ if (!purpose)
452
+ return null;
453
+ const { data, error } = await db.rpc("email_auth_for_purpose", { _purpose: purpose, _direction: "send" });
454
+ if (error)
455
+ throw error;
456
+ const list = Array.isArray(data) ? data : [];
457
+ return list[0] ?? null;
458
+ }
459
+ export async function sendInvoiceEmail(p) {
460
+ assertValidPdfBase64(p.pdfBase64);
461
+ const purpose = await fetchInvoiceEmailPurpose();
462
+ if (!purpose)
463
+ throw new Error("Kies eerst een e-maildoeleinde bij Instellingen → Factuur e-mail.");
464
+ const conn = await fetchSenderForPurpose(purpose);
465
+ if (!conn?.id)
466
+ throw new Error(`Er is geen mailbox gekoppeld aan het doeleinde '${purpose}'. Koppel er een in de e-mailmodule.`);
467
+ const INVOICE_MAIL_PURPOSE = purpose;
468
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
469
+ const { data: u } = await supabase.auth.getUser();
470
+ const attachment = {
471
+ filename: p.filename,
472
+ content_type: "application/pdf",
473
+ encoding: "base64",
474
+ content_base64: p.pdfBase64,
475
+ };
476
+ const { data: queued, error } = await db.from("email_auth_outbox").insert({
477
+ purpose: INVOICE_MAIL_PURPOSE,
478
+ connection_id: conn.id,
479
+ to_addresses: [p.to],
480
+ subject: p.subject,
481
+ text_body: p.message,
482
+ html_body: `<p>${esc(p.message).replace(/\n/g, "<br>")}</p>`,
483
+ attachments: [attachment],
484
+ created_by: u?.user?.id ?? null,
485
+ }).select("id, status, attachments").single();
486
+ if (error)
487
+ throw error;
488
+ const storedAttachments = Array.isArray(queued?.attachments) ? queued.attachments : [];
489
+ if (storedAttachments.length !== 1) {
490
+ throw new Error("De PDF-bijlage is niet opgeslagen. De e-mail is niet als verzonden gemarkeerd.");
491
+ }
492
+ return { outboxId: queued.id, status: queued.status };
493
+ }
494
+ export async function elementToPdfBase64(el) {
495
+ const [{ default: html2canvas }, { jsPDF }] = await Promise.all([import("html2canvas-pro"), import("jspdf")]);
496
+ const canvas = await html2canvas(el, { scale: 2, useCORS: true, backgroundColor: "#ffffff" });
497
+ const pdf = new jsPDF({ unit: "mm", format: "a4" });
498
+ const w = 210;
499
+ const h = (canvas.height * w) / canvas.width;
500
+ pdf.addImage(canvas.toDataURL("image/jpeg", 0.92), "JPEG", 0, 0, w, Math.min(h, 297));
501
+ const pdfBase64 = pdf.output("datauristring").split(",")[1] ?? "";
502
+ assertValidPdfBase64(pdfBase64);
503
+ return pdfBase64;
504
+ }
505
+ export function downloadPdfBase64(pdfBase64, filename) {
506
+ assertValidPdfBase64(pdfBase64);
507
+ const binary = window.atob(pdfBase64.replace(/\s/g, ""));
508
+ const bytes = new Uint8Array(binary.length);
509
+ for (let index = 0; index < binary.length; index += 1)
510
+ bytes[index] = binary.charCodeAt(index);
511
+ const url = URL.createObjectURL(new Blob([bytes], { type: "application/pdf" }));
512
+ const link = document.createElement("a");
513
+ link.href = url;
514
+ link.download = filename;
515
+ document.body.appendChild(link);
516
+ link.click();
517
+ link.remove();
518
+ window.setTimeout(() => URL.revokeObjectURL(url), 1000);
519
+ }
520
+ export function pdfBase64ToObjectUrl(pdfBase64) {
521
+ assertValidPdfBase64(pdfBase64);
522
+ const binary = window.atob(pdfBase64.replace(/\s/g, ""));
523
+ const bytes = new Uint8Array(binary.length);
524
+ for (let index = 0; index < binary.length; index += 1)
525
+ bytes[index] = binary.charCodeAt(index);
526
+ return URL.createObjectURL(new Blob([bytes], { type: "application/pdf" }));
102
527
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flowselections/facturen-installatie-techniek",
3
- "version": "1.0.2",
3
+ "version": "1.3.4",
4
4
  "flowselections": {
5
5
  "moduleId": "facturen-installatietechniek",
6
6
  "pages": [
@@ -14,7 +14,57 @@
14
14
  "route": "facturen-installatietechniek/detail/$id",
15
15
  "title": "Factuur"
16
16
  }
17
- ]
17
+ ],
18
+ "handover": {
19
+ "titel": "Facturen Installatietechniek",
20
+ "samenvatting": "Centrale facturatie voor installatietechniek met A4-weergave, afdrukfunctie, vastgezette bedrijfsgegevens en unieke factuurnummers. Werkbonnen en offertes kunnen via een RPC worden omgezet in facturen; handmatige facturen, pakketten en materialen uit Artikelen zijn ook mogelijk. De materiaalzoeker toont tijdelijk ondertekende foto's uit de private opslag, berekent verkoopprijzen met de eigen of algemene marge en bewaart geen tijdelijke fotolinks. Eigenaar van itk_customers is Klanten planner installatietechniek (installatietechniek-klanten-planner); deze module leest itk_customers alleen en schrijft er nooit in. Facturen zijn direct op de A4-weergave te bewerken (regels met eigen btw), opgeslagen concepten opnieuw te bewerken en met een vooraf gedownloade, verplicht aangevinkte en gevalideerde PDF-bijlage via het gekozen e-maildoeleinde in de e-mailwachtrij te plaatsen. Aflevering en bijlageverwerking zijn eigendom van E-mail - Authenticatie. De huisstijl heeft een vinkje om de bedrijfsnaam wel of niet naast het logo in de bovenbalk te tonen (show_company_name). Of een factuur al verzonden is, wordt bijgehouden op basis van echt bewijs: invoice_register_send legt verzondenmoment en -adres alleen vast als de e-mail in email_auth_outbox de PDF van dat factuurnummer als bijlage heeft, het moment wordt nooit overschreven en een bewezen verzonden factuur is niet meer te bewerken (knop 'Opnieuw verzenden').",
21
+ "eigenTabellen": [
22
+ "invoices",
23
+ "invoice_items",
24
+ "invoice_branding_settings"
25
+ ],
26
+ "leestTabellen": [
27
+ "werkbonnen",
28
+ "werkbon_package_lines",
29
+ "werkbon_packages",
30
+ "werkbon_materials",
31
+ "itk_offertes",
32
+ "itk_offerte_regels",
33
+ "itk_customers",
34
+ "artikelen_cache",
35
+ "artikelen_instellingen",
36
+ "invoice_branding_settings",
37
+ "email_auth_connections"
38
+ ],
39
+ "schrijftTabellen": [
40
+ "invoices",
41
+ "invoice_items",
42
+ "invoice_branding_settings",
43
+ "email_auth_outbox"
44
+ ],
45
+ "biedtFuncties": [
46
+ "invoice_create_from_source(_source_type text, _source_id uuid, _payload jsonb)",
47
+ "invoice_list_sources(_source_type text, _limit integer)",
48
+ "invoice_get_summary(_invoice_id uuid)",
49
+ "invoice_get_billable_lines(_source_type text, _source_id uuid)",
50
+ "invoice_get_for_source(_source_type text, _source_id uuid)",
51
+ "invoice_source_lines(_source_type text, _source_id uuid)",
52
+ "invoice_ready_work_orders(_limit integer)",
53
+ "invoice_save_branding_settings(_payload jsonb)",
54
+ "invoice_branding_snapshot()",
55
+ "invoice_peek_next_number",
56
+ "invoice_update_full",
57
+ "invoice_mark_sent",
58
+ "invoice_register_send(_invoice_id uuid, _outbox_id uuid) -> {status, sent_at, sent_to, first_send}: registreert een verzending alleen op bewijs van een echte e-mail in email_auth_outbox met de factuur-PDF als bijlage",
59
+ "invoice_set_email_purpose",
60
+ "invoice_work_order_locked(_werkbon_id uuid) -> {locked, invoice_id, invoice_number, status}: Offertes moet dit controleren; bij locked alleen als vervolgwerkbon toestaan"
61
+ ],
62
+ "gebruiktFuncties": [
63
+ "email_auth_for_purpose"
64
+ ],
65
+ "herzieningstermijnDagen": 90,
66
+ "laatstBevestigdOp": "2026-10-06"
67
+ }
18
68
  },
19
69
  "private": false,
20
70
  "sideEffects": false,
@@ -55,13 +105,15 @@
55
105
  "sonner": "^2.0.0"
56
106
  },
57
107
  "dependencies": {
58
- "@supabase/supabase-js": "^2.110.0"
108
+ "@supabase/supabase-js": "^2.110.0",
109
+ "html2canvas-pro": "^2.4.5",
110
+ "jspdf": "^4.2.1"
59
111
  },
60
112
  "devDependencies": {
61
113
  "@cloudflare/vite-plugin": "^1.25.5",
62
114
  "@eslint/js": "^9.32.0",
63
- "@flowselections/core": "1.0.12",
64
- "@lovable.dev/vite-tanstack-config": "2.13.1",
115
+ "@flowselections/core": "1.0.29",
116
+ "@lovable.dev/vite-tanstack-config": "2.26.5",
65
117
  "@rsbuild/core": "^1.0.0",
66
118
  "@tailwindcss/vite": "^4.2.1",
67
119
  "@tanstack/react-query": "^5.83.0",