@flowselections/floriday-afhandeling-module 1.0.45 → 1.0.47

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 (46) hide show
  1. package/dist-lib/components/afhandeling/ControlePage.js +1 -1
  2. package/dist-lib/components/afhandeling/DagDetailDialog.d.ts.map +1 -1
  3. package/dist-lib/components/afhandeling/DagDetailDialog.js +32 -9
  4. package/dist-lib/components/afhandeling/ScanControleView.js +1 -1
  5. package/dist-lib/components/afhandeling/VervoerdersPage.js +1 -1
  6. package/dist-lib/components/afhandeling/VerzetOrderDialog.js +1 -1
  7. package/dist-lib/components/afhandeling/WerkplekWaarschuwing.d.ts +9 -9
  8. package/dist-lib/components/afhandeling/WerkplekWaarschuwing.js +28 -28
  9. package/dist-lib/components/ui/responsive-dialog.js +1 -1
  10. package/dist-lib/hooks/usePickMode.d.ts +1 -1
  11. package/dist-lib/integrations/supabase/auth-middleware.d.ts +2422 -45
  12. package/dist-lib/integrations/supabase/auth-middleware.d.ts.map +1 -1
  13. package/dist-lib/integrations/supabase/client.server.d.ts +2422 -45
  14. package/dist-lib/integrations/supabase/client.server.d.ts.map +1 -1
  15. package/dist-lib/integrations/supabase/client.server.js +1 -1
  16. package/dist-lib/integrations/supabase/moduleClient.d.ts +2422 -45
  17. package/dist-lib/integrations/supabase/moduleClient.d.ts.map +1 -1
  18. package/dist-lib/integrations/supabase/previewAuthStorage.d.ts +1 -1
  19. package/dist-lib/integrations/supabase/previewAuthStorage.d.ts.map +1 -1
  20. package/dist-lib/integrations/supabase/previewAuthStorage.js +8 -1
  21. package/dist-lib/integrations/supabase/types.d.ts +2461 -42
  22. package/dist-lib/integrations/supabase/types.d.ts.map +1 -1
  23. package/dist-lib/lib/afhandelingSettings.functions.d.ts +4760 -6
  24. package/dist-lib/lib/afhandelingSettings.functions.d.ts.map +1 -1
  25. package/dist-lib/lib/carriers.functions.d.ts +11900 -15
  26. package/dist-lib/lib/carriers.functions.d.ts.map +1 -1
  27. package/dist-lib/lib/cartAssignments.functions.d.ts +43261 -42
  28. package/dist-lib/lib/cartAssignments.functions.d.ts.map +1 -1
  29. package/dist-lib/lib/cartAssignments.functions.js +69 -0
  30. package/dist-lib/lib/cartControl.functions.d.ts +26180 -33
  31. package/dist-lib/lib/cartControl.functions.d.ts.map +1 -1
  32. package/dist-lib/lib/deliveryNote.functions.d.ts +2422 -45
  33. package/dist-lib/lib/deliveryNote.functions.d.ts.map +1 -1
  34. package/dist-lib/lib/deliveryNotePrint.d.ts +33 -33
  35. package/dist-lib/lib/deliveryNotePrint.js +219 -219
  36. package/dist-lib/lib/engineLayouts.functions.d.ts +2422 -45
  37. package/dist-lib/lib/engineLayouts.functions.d.ts.map +1 -1
  38. package/dist-lib/lib/floriday.functions.d.ts +4760 -6
  39. package/dist-lib/lib/floriday.functions.d.ts.map +1 -1
  40. package/dist-lib/lib/logisticsEngine/capacity.js +1 -1
  41. package/dist-lib/lib/logisticsEngine/staffPlanning.js +1 -1
  42. package/dist-lib/lib/orderFulfilment.functions.d.ts +2422 -45
  43. package/dist-lib/lib/orderFulfilment.functions.d.ts.map +1 -1
  44. package/dist-lib/lib/pickDates.functions.d.ts +2422 -45
  45. package/dist-lib/lib/pickDates.functions.d.ts.map +1 -1
  46. package/package.json +3 -3
@@ -1,34 +1,34 @@
1
- export interface DeliveryNoteItem {
2
- id: string;
3
- salesOrderId?: string | null;
4
- deliveryOrderId?: string | null;
5
- fulfillmentOrderId?: string | null;
6
- }
7
- /** Haalt de signed URL van een enkele afleverbrief op. */
8
- export declare function fetchDeliveryNoteUrl(salesOrderId: string): Promise<string>;
9
- /** Print een PDF vanaf een (signed) URL via de printwachtrij. */
10
- export declare function printPdfFromUrl(url: string, opties: {
11
- documentnaam: string;
12
- isHerprint?: boolean;
13
- }): Promise<void>;
14
- /** Haal en print één afleverbrief. */
15
- export declare function printDeliveryNote(salesOrderId: string, opties?: {
16
- documentnaam?: string;
17
- isHerprint?: boolean;
18
- }): Promise<void>;
19
- export interface BulkPrintResult {
20
- total: number;
21
- success: number;
22
- failed: Array<{
23
- id: string;
24
- error: string;
25
- }>;
26
- }
27
- /**
28
- * Print meerdere afleverbrieven als samengevoegde PDF's van maximaal 25 stuks.
29
- * Te grote opdrachten worden automatisch verder opgeknipt.
30
- */
31
- export declare function printDeliveryNotesMerged(items: DeliveryNoteItem[], opties?: {
32
- isHerprint?: boolean;
33
- }): Promise<BulkPrintResult>;
1
+ export interface DeliveryNoteItem {
2
+ id: string;
3
+ salesOrderId?: string | null;
4
+ deliveryOrderId?: string | null;
5
+ fulfillmentOrderId?: string | null;
6
+ }
7
+ /** Haalt de signed URL van een enkele afleverbrief op. */
8
+ export declare function fetchDeliveryNoteUrl(salesOrderId: string): Promise<string>;
9
+ /** Print een PDF vanaf een (signed) URL via de printwachtrij. */
10
+ export declare function printPdfFromUrl(url: string, opties: {
11
+ documentnaam: string;
12
+ isHerprint?: boolean;
13
+ }): Promise<void>;
14
+ /** Haal en print één afleverbrief. */
15
+ export declare function printDeliveryNote(salesOrderId: string, opties?: {
16
+ documentnaam?: string;
17
+ isHerprint?: boolean;
18
+ }): Promise<void>;
19
+ export interface BulkPrintResult {
20
+ total: number;
21
+ success: number;
22
+ failed: Array<{
23
+ id: string;
24
+ error: string;
25
+ }>;
26
+ }
27
+ /**
28
+ * Print meerdere afleverbrieven als samengevoegde PDF's van maximaal 25 stuks.
29
+ * Te grote opdrachten worden automatisch verder opgeknipt.
30
+ */
31
+ export declare function printDeliveryNotesMerged(items: DeliveryNoteItem[], opties?: {
32
+ isHerprint?: boolean;
33
+ }): Promise<BulkPrintResult>;
34
34
  //# sourceMappingURL=deliveryNotePrint.d.ts.map
@@ -1,219 +1,219 @@
1
- // Client-side helpers voor het ophalen en printen van Floriday-afleverbrieven
2
- // via de gateway-endpoints van de Authenticatie-module.
3
- // De Authenticatie-module accepteert een Supabase Bearer-token en stuurt
4
- // CORS-headers, dus we bellen direct cross-origin — geen eigen proxy nodig.
5
- import { printPdfBase64 } from "../components/pickstation/printDocuments";
6
- import { supabase } from "../integrations/supabase/moduleClient";
7
- import { resolveGatewayBaseClient } from "./gatewayBase";
8
- let floridayEnvironmentPromise = null;
9
- async function getFloridayEnvironment() {
10
- floridayEnvironmentPromise ?? (floridayEnvironmentPromise = Promise.resolve(supabase.from("floriday_settings").select("active_environment").eq("id", 1).maybeSingle()).then(({ data, error }) => {
11
- if (error) {
12
- console.warn("[delivery-note-print] active Floriday environment ophalen mislukt", error);
13
- }
14
- return data?.active_environment ?? "live";
15
- }));
16
- return floridayEnvironmentPromise;
17
- }
18
- async function getAccessToken() {
19
- const { data } = await supabase.auth.getSession();
20
- const token = data.session?.access_token;
21
- if (!token) {
22
- throw new Error("Niet ingelogd — kan afleverbrief niet ophalen.");
23
- }
24
- return token;
25
- }
26
- async function postJson(path, body) {
27
- const token = await getAccessToken();
28
- const base = resolveGatewayBaseClient();
29
- const res = await fetch(`${base}${path}`, {
30
- method: "POST",
31
- headers: {
32
- "Content-Type": "application/json",
33
- Authorization: `Bearer ${token}`,
34
- },
35
- body: JSON.stringify(body),
36
- });
37
- const ct = res.headers.get("content-type") ?? "";
38
- if (!ct.includes("application/json")) {
39
- throw new Error(`Gateway onbereikbaar (HTTP ${res.status}) — ontving ${ct || "onbekend content-type"}.`);
40
- }
41
- const text = await res.text();
42
- let data = null;
43
- try {
44
- data = text ? JSON.parse(text) : null;
45
- }
46
- catch {
47
- data = { ok: false, error: text };
48
- }
49
- return { status: res.status, data: data };
50
- }
51
- /**
52
- * Zoekt delivery-order IDs in de lokale cache voor een gegeven sales-order.
53
- * De gateway kan een delivery-note alleen genereren als er een delivery-order bestaat;
54
- * door hier eerst zelf te resolven omzeilen we de "Geen delivery-order beschikbaar" fout
55
- * wanneer de gateway de koppeling nog niet ziet.
56
- */
57
- async function resolveDeliveryOrderIds(salesOrderId) {
58
- const { data, error } = await supabase
59
- .from("floriday_delivery_orders_cache")
60
- .select("floriday_id, data")
61
- .contains("data", { fulfillmentRequests: [{ salesOrderId }] });
62
- if (error) {
63
- console.warn("[delivery-note-print] delivery-order lookup mislukt", error);
64
- return [];
65
- }
66
- const ids = new Set();
67
- for (const row of (data ?? [])) {
68
- const d = row.data;
69
- if (d?.isDeleted)
70
- continue;
71
- if (d?.fulfillmentRequests?.some((f) => f.salesOrderId === salesOrderId)) {
72
- ids.add(row.floriday_id);
73
- }
74
- }
75
- return [...ids];
76
- }
77
- /** Haalt de signed URL van een enkele afleverbrief op. */
78
- export async function fetchDeliveryNoteUrl(salesOrderId) {
79
- const environment = await getFloridayEnvironment();
80
- const deliveryOrderIds = await resolveDeliveryOrderIds(salesOrderId);
81
- if (deliveryOrderIds.length > 1) {
82
- throw new Error("Deze verkooporder heeft meerdere afleverbrieven — gebruik de dag-print om ze samen af te drukken.");
83
- }
84
- const payload = {
85
- environment,
86
- kind: "delivery-note",
87
- salesOrderId,
88
- };
89
- if (deliveryOrderIds[0])
90
- payload.deliveryOrderId = deliveryOrderIds[0];
91
- const { status, data } = await postJson("/api/public/gateway/pdf", payload);
92
- if (status === 409) {
93
- throw new Error("Deze verkooporder heeft meerdere afleverbrieven — gebruik de dag-print om ze samen af te drukken.");
94
- }
95
- if (!data?.ok || !data.url) {
96
- throw new Error(data?.error ?? `Afleverbrief ophalen mislukt (HTTP ${status})`);
97
- }
98
- return data.url;
99
- }
100
- /** Print een PDF vanaf een (signed) URL via de printwachtrij. */
101
- export async function printPdfFromUrl(url, opties) {
102
- const res = await fetch(url);
103
- if (!res.ok)
104
- throw new Error(`PDF download mislukt (HTTP ${res.status})`);
105
- const buf = new Uint8Array(await res.arrayBuffer());
106
- let binary = "";
107
- const chunk = 0x8000;
108
- for (let i = 0; i < buf.length; i += chunk) {
109
- binary += String.fromCharCode(...buf.subarray(i, i + chunk));
110
- }
111
- const base64 = btoa(binary);
112
- await printPdfBase64(base64, {
113
- documenttype: "afleverbrief",
114
- documentnaam: opties.documentnaam,
115
- isHerprint: opties.isHerprint,
116
- papierformaat: "A4",
117
- });
118
- }
119
- /** Haal en print één afleverbrief. */
120
- export async function printDeliveryNote(salesOrderId, opties) {
121
- const url = await fetchDeliveryNoteUrl(salesOrderId);
122
- await printPdfFromUrl(url, {
123
- documentnaam: opties?.documentnaam ?? `AFL-${salesOrderId}`,
124
- isHerprint: opties?.isHerprint,
125
- });
126
- }
127
- /** Maximaal aantal afleverbrieven in één samengevoegde printopdracht. */
128
- const CHUNK_SIZE = 25;
129
- /** Boven deze payloadgrootte (bytes) wordt de chunk gehalveerd. */
130
- const MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
131
- function base64Bytes(b64) {
132
- return Math.floor((b64.length * 3) / 4);
133
- }
134
- function vandaagIso() {
135
- return new Date().toISOString().slice(0, 10);
136
- }
137
- /**
138
- * Print meerdere afleverbrieven als samengevoegde PDF's van maximaal 25 stuks.
139
- * Te grote opdrachten worden automatisch verder opgeknipt.
140
- */
141
- export async function printDeliveryNotesMerged(items, opties) {
142
- const valid = items.filter((i) => i.salesOrderId || i.deliveryOrderId || i.fulfillmentOrderId);
143
- const summary = { total: valid.length, success: 0, failed: [] };
144
- if (valid.length === 0)
145
- return summary;
146
- const environment = await getFloridayEnvironment();
147
- // Verrijk items met deliveryOrderId uit de lokale cache waar mogelijk,
148
- // zodat de gateway niet meer op salesOrderId hoeft te zoeken.
149
- const enriched = [];
150
- for (const it of valid) {
151
- if (it.deliveryOrderId || it.fulfillmentOrderId || !it.salesOrderId) {
152
- enriched.push(it);
153
- continue;
154
- }
155
- const ids = await resolveDeliveryOrderIds(it.salesOrderId);
156
- if (ids.length === 0) {
157
- enriched.push(it);
158
- }
159
- else {
160
- for (const doId of ids)
161
- enriched.push({ ...it, deliveryOrderId: doId });
162
- }
163
- }
164
- const dag = vandaagIso();
165
- let deel = 0;
166
- const printChunk = async (chunk) => {
167
- if (chunk.length === 0)
168
- return;
169
- const { status, data } = await postJson("/api/public/gateway/pdf/bulk-merged", {
170
- environment,
171
- items: chunk.map((it) => ({
172
- id: it.id,
173
- ...(it.salesOrderId ? { salesOrderId: it.salesOrderId } : {}),
174
- ...(it.deliveryOrderId ? { deliveryOrderId: it.deliveryOrderId } : {}),
175
- ...(it.fulfillmentOrderId ? { fulfillmentOrderId: it.fulfillmentOrderId } : {}),
176
- })),
177
- });
178
- if (!data?.ok || !data.pdfBase64) {
179
- const err = data?.error ?? `HTTP ${status}`;
180
- for (const it of chunk)
181
- summary.failed.push({ id: it.id, error: err });
182
- return;
183
- }
184
- // Te grote samengevoegde PDF: halveren en opnieuw opvragen.
185
- if (chunk.length > 1 && base64Bytes(data.pdfBase64) > MAX_PAYLOAD_BYTES) {
186
- const half = Math.ceil(chunk.length / 2);
187
- await printChunk(chunk.slice(0, half));
188
- await printChunk(chunk.slice(half));
189
- return;
190
- }
191
- deel += 1;
192
- const documentnaam = chunk.length === 1
193
- ? `AFL-${chunk[0].salesOrderId ?? chunk[0].deliveryOrderId ?? chunk[0].id}`
194
- : `AFL-${dag}-deel-${deel}`;
195
- try {
196
- await printPdfBase64(data.pdfBase64, {
197
- documenttype: "afleverbrief",
198
- documentnaam,
199
- isHerprint: opties?.isHerprint,
200
- papierformaat: "A4",
201
- });
202
- }
203
- catch (e) {
204
- const msg = e instanceof Error ? e.message : "Printen mislukt";
205
- for (const it of chunk)
206
- summary.failed.push({ id: it.id, error: msg });
207
- return;
208
- }
209
- summary.success += data.success ?? chunk.length;
210
- for (const r of data.results ?? []) {
211
- if (!r.ok)
212
- summary.failed.push({ id: r.id, error: r.error ?? "onbekende fout" });
213
- }
214
- };
215
- for (let i = 0; i < enriched.length; i += CHUNK_SIZE) {
216
- await printChunk(enriched.slice(i, i + CHUNK_SIZE));
217
- }
218
- return summary;
219
- }
1
+ // Client-side helpers voor het ophalen en printen van Floriday-afleverbrieven
2
+ // via de gateway-endpoints van de Authenticatie-module.
3
+ // De Authenticatie-module accepteert een Supabase Bearer-token en stuurt
4
+ // CORS-headers, dus we bellen direct cross-origin — geen eigen proxy nodig.
5
+ import { printPdfBase64 } from "../components/pickstation/printDocuments";
6
+ import { supabase } from "../integrations/supabase/moduleClient";
7
+ import { resolveGatewayBaseClient } from "./gatewayBase";
8
+ let floridayEnvironmentPromise = null;
9
+ async function getFloridayEnvironment() {
10
+ floridayEnvironmentPromise ?? (floridayEnvironmentPromise = Promise.resolve(supabase.from("floriday_settings").select("active_environment").eq("id", 1).maybeSingle()).then(({ data, error }) => {
11
+ if (error) {
12
+ console.warn("[delivery-note-print] active Floriday environment ophalen mislukt", error);
13
+ }
14
+ return data?.active_environment ?? "live";
15
+ }));
16
+ return floridayEnvironmentPromise;
17
+ }
18
+ async function getAccessToken() {
19
+ const { data } = await supabase.auth.getSession();
20
+ const token = data.session?.access_token;
21
+ if (!token) {
22
+ throw new Error("Niet ingelogd — kan afleverbrief niet ophalen.");
23
+ }
24
+ return token;
25
+ }
26
+ async function postJson(path, body) {
27
+ const token = await getAccessToken();
28
+ const base = resolveGatewayBaseClient();
29
+ const res = await fetch(`${base}${path}`, {
30
+ method: "POST",
31
+ headers: {
32
+ "Content-Type": "application/json",
33
+ Authorization: `Bearer ${token}`,
34
+ },
35
+ body: JSON.stringify(body),
36
+ });
37
+ const ct = res.headers.get("content-type") ?? "";
38
+ if (!ct.includes("application/json")) {
39
+ throw new Error(`Gateway onbereikbaar (HTTP ${res.status}) — ontving ${ct || "onbekend content-type"}.`);
40
+ }
41
+ const text = await res.text();
42
+ let data = null;
43
+ try {
44
+ data = text ? JSON.parse(text) : null;
45
+ }
46
+ catch {
47
+ data = { ok: false, error: text };
48
+ }
49
+ return { status: res.status, data: data };
50
+ }
51
+ /**
52
+ * Zoekt delivery-order IDs in de lokale cache voor een gegeven sales-order.
53
+ * De gateway kan een delivery-note alleen genereren als er een delivery-order bestaat;
54
+ * door hier eerst zelf te resolven omzeilen we de "Geen delivery-order beschikbaar" fout
55
+ * wanneer de gateway de koppeling nog niet ziet.
56
+ */
57
+ async function resolveDeliveryOrderIds(salesOrderId) {
58
+ const { data, error } = await supabase
59
+ .from("floriday_delivery_orders_cache")
60
+ .select("floriday_id, data")
61
+ .contains("data", { fulfillmentRequests: [{ salesOrderId }] });
62
+ if (error) {
63
+ console.warn("[delivery-note-print] delivery-order lookup mislukt", error);
64
+ return [];
65
+ }
66
+ const ids = new Set();
67
+ for (const row of (data ?? [])) {
68
+ const d = row.data;
69
+ if (d?.isDeleted)
70
+ continue;
71
+ if (d?.fulfillmentRequests?.some((f) => f.salesOrderId === salesOrderId)) {
72
+ ids.add(row.floriday_id);
73
+ }
74
+ }
75
+ return [...ids];
76
+ }
77
+ /** Haalt de signed URL van een enkele afleverbrief op. */
78
+ export async function fetchDeliveryNoteUrl(salesOrderId) {
79
+ const environment = await getFloridayEnvironment();
80
+ const deliveryOrderIds = await resolveDeliveryOrderIds(salesOrderId);
81
+ if (deliveryOrderIds.length > 1) {
82
+ throw new Error("Deze verkooporder heeft meerdere afleverbrieven — gebruik de dag-print om ze samen af te drukken.");
83
+ }
84
+ const payload = {
85
+ environment,
86
+ kind: "delivery-note",
87
+ salesOrderId,
88
+ };
89
+ if (deliveryOrderIds[0])
90
+ payload.deliveryOrderId = deliveryOrderIds[0];
91
+ const { status, data } = await postJson("/api/public/gateway/pdf", payload);
92
+ if (status === 409) {
93
+ throw new Error("Deze verkooporder heeft meerdere afleverbrieven — gebruik de dag-print om ze samen af te drukken.");
94
+ }
95
+ if (!data?.ok || !data.url) {
96
+ throw new Error(data?.error ?? `Afleverbrief ophalen mislukt (HTTP ${status})`);
97
+ }
98
+ return data.url;
99
+ }
100
+ /** Print een PDF vanaf een (signed) URL via de printwachtrij. */
101
+ export async function printPdfFromUrl(url, opties) {
102
+ const res = await fetch(url);
103
+ if (!res.ok)
104
+ throw new Error(`PDF download mislukt (HTTP ${res.status})`);
105
+ const buf = new Uint8Array(await res.arrayBuffer());
106
+ let binary = "";
107
+ const chunk = 0x8000;
108
+ for (let i = 0; i < buf.length; i += chunk) {
109
+ binary += String.fromCharCode(...buf.subarray(i, i + chunk));
110
+ }
111
+ const base64 = btoa(binary);
112
+ await printPdfBase64(base64, {
113
+ documenttype: "afleverbrief",
114
+ documentnaam: opties.documentnaam,
115
+ isHerprint: opties.isHerprint,
116
+ papierformaat: "A4",
117
+ });
118
+ }
119
+ /** Haal en print één afleverbrief. */
120
+ export async function printDeliveryNote(salesOrderId, opties) {
121
+ const url = await fetchDeliveryNoteUrl(salesOrderId);
122
+ await printPdfFromUrl(url, {
123
+ documentnaam: opties?.documentnaam ?? `AFL-${salesOrderId}`,
124
+ isHerprint: opties?.isHerprint,
125
+ });
126
+ }
127
+ /** Maximaal aantal afleverbrieven in één samengevoegde printopdracht. */
128
+ const CHUNK_SIZE = 25;
129
+ /** Boven deze payloadgrootte (bytes) wordt de chunk gehalveerd. */
130
+ const MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
131
+ function base64Bytes(b64) {
132
+ return Math.floor((b64.length * 3) / 4);
133
+ }
134
+ function vandaagIso() {
135
+ return new Date().toISOString().slice(0, 10);
136
+ }
137
+ /**
138
+ * Print meerdere afleverbrieven als samengevoegde PDF's van maximaal 25 stuks.
139
+ * Te grote opdrachten worden automatisch verder opgeknipt.
140
+ */
141
+ export async function printDeliveryNotesMerged(items, opties) {
142
+ const valid = items.filter((i) => i.salesOrderId || i.deliveryOrderId || i.fulfillmentOrderId);
143
+ const summary = { total: valid.length, success: 0, failed: [] };
144
+ if (valid.length === 0)
145
+ return summary;
146
+ const environment = await getFloridayEnvironment();
147
+ // Verrijk items met deliveryOrderId uit de lokale cache waar mogelijk,
148
+ // zodat de gateway niet meer op salesOrderId hoeft te zoeken.
149
+ const enriched = [];
150
+ for (const it of valid) {
151
+ if (it.deliveryOrderId || it.fulfillmentOrderId || !it.salesOrderId) {
152
+ enriched.push(it);
153
+ continue;
154
+ }
155
+ const ids = await resolveDeliveryOrderIds(it.salesOrderId);
156
+ if (ids.length === 0) {
157
+ enriched.push(it);
158
+ }
159
+ else {
160
+ for (const doId of ids)
161
+ enriched.push({ ...it, deliveryOrderId: doId });
162
+ }
163
+ }
164
+ const dag = vandaagIso();
165
+ let deel = 0;
166
+ const printChunk = async (chunk) => {
167
+ if (chunk.length === 0)
168
+ return;
169
+ const { status, data } = await postJson("/api/public/gateway/pdf/bulk-merged", {
170
+ environment,
171
+ items: chunk.map((it) => ({
172
+ id: it.id,
173
+ ...(it.salesOrderId ? { salesOrderId: it.salesOrderId } : {}),
174
+ ...(it.deliveryOrderId ? { deliveryOrderId: it.deliveryOrderId } : {}),
175
+ ...(it.fulfillmentOrderId ? { fulfillmentOrderId: it.fulfillmentOrderId } : {}),
176
+ })),
177
+ });
178
+ if (!data?.ok || !data.pdfBase64) {
179
+ const err = data?.error ?? `HTTP ${status}`;
180
+ for (const it of chunk)
181
+ summary.failed.push({ id: it.id, error: err });
182
+ return;
183
+ }
184
+ // Te grote samengevoegde PDF: halveren en opnieuw opvragen.
185
+ if (chunk.length > 1 && base64Bytes(data.pdfBase64) > MAX_PAYLOAD_BYTES) {
186
+ const half = Math.ceil(chunk.length / 2);
187
+ await printChunk(chunk.slice(0, half));
188
+ await printChunk(chunk.slice(half));
189
+ return;
190
+ }
191
+ deel += 1;
192
+ const documentnaam = chunk.length === 1
193
+ ? `AFL-${chunk[0].salesOrderId ?? chunk[0].deliveryOrderId ?? chunk[0].id}`
194
+ : `AFL-${dag}-deel-${deel}`;
195
+ try {
196
+ await printPdfBase64(data.pdfBase64, {
197
+ documenttype: "afleverbrief",
198
+ documentnaam,
199
+ isHerprint: opties?.isHerprint,
200
+ papierformaat: "A4",
201
+ });
202
+ }
203
+ catch (e) {
204
+ const msg = e instanceof Error ? e.message : "Printen mislukt";
205
+ for (const it of chunk)
206
+ summary.failed.push({ id: it.id, error: msg });
207
+ return;
208
+ }
209
+ summary.success += data.success ?? chunk.length;
210
+ for (const r of data.results ?? []) {
211
+ if (!r.ok)
212
+ summary.failed.push({ id: r.id, error: r.error ?? "onbekende fout" });
213
+ }
214
+ };
215
+ for (let i = 0; i < enriched.length; i += CHUNK_SIZE) {
216
+ await printChunk(enriched.slice(i, i + CHUNK_SIZE));
217
+ }
218
+ return summary;
219
+ }