@flowselections/facturen-installatie-techniek 1.0.3 → 1.4.1

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 (65) 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 +155 -52
  6. package/dist-lib/components/FactuurDetailPage.d.ts.map +1 -1
  7. package/dist-lib/components/FactuurDetailPage.js +240 -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 +159 -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/ModuleErrorView.d.ts +6 -0
  15. package/dist-lib/components/ModuleErrorView.d.ts.map +1 -0
  16. package/dist-lib/components/ModuleErrorView.js +11 -0
  17. package/dist-lib/components/WerkbonPreviewPanel.d.ts +4 -0
  18. package/dist-lib/components/WerkbonPreviewPanel.d.ts.map +1 -0
  19. package/dist-lib/components/WerkbonPreviewPanel.js +40 -0
  20. package/dist-lib/components/settings/InstellingenPage.d.ts +5 -0
  21. package/dist-lib/components/settings/InstellingenPage.d.ts.map +1 -0
  22. package/dist-lib/components/settings/InstellingenPage.js +119 -0
  23. package/dist-lib/components/settings/InvoiceBrandingSettingsCard.d.ts +2 -0
  24. package/dist-lib/components/settings/InvoiceBrandingSettingsCard.d.ts.map +1 -0
  25. package/dist-lib/components/settings/InvoiceBrandingSettingsCard.js +64 -0
  26. package/dist-lib/components/settings/InvoiceEmailSettingsCard.d.ts +2 -0
  27. package/dist-lib/components/settings/InvoiceEmailSettingsCard.d.ts.map +1 -0
  28. package/dist-lib/components/settings/InvoiceEmailSettingsCard.js +41 -0
  29. package/dist-lib/components/settings/ModuleHealthSettingsCard.d.ts +3 -0
  30. package/dist-lib/components/settings/ModuleHealthSettingsCard.d.ts.map +1 -0
  31. package/dist-lib/components/settings/ModuleHealthSettingsCard.js +47 -0
  32. package/dist-lib/index.d.ts +11 -0
  33. package/dist-lib/index.d.ts.map +1 -1
  34. package/dist-lib/index.js +18 -2
  35. package/dist-lib/integrations/supabase/auth-middleware.d.ts +11 -22550
  36. package/dist-lib/integrations/supabase/auth-middleware.d.ts.map +1 -1
  37. package/dist-lib/integrations/supabase/auth-middleware.js +3 -1
  38. package/dist-lib/integrations/supabase/client.d.ts +3 -22548
  39. package/dist-lib/integrations/supabase/client.d.ts.map +1 -1
  40. package/dist-lib/integrations/supabase/client.js +3 -11
  41. package/dist-lib/integrations/supabase/client.server.d.ts +2 -22547
  42. package/dist-lib/integrations/supabase/client.server.d.ts.map +1 -1
  43. package/dist-lib/integrations/supabase/client.server.js +1 -0
  44. package/dist-lib/integrations/supabase/previewAuthStorage.d.ts +6 -0
  45. package/dist-lib/integrations/supabase/previewAuthStorage.d.ts.map +1 -0
  46. package/dist-lib/integrations/supabase/previewAuthStorage.js +99 -0
  47. package/dist-lib/integrations/supabase/types.d.ts +24886 -11380
  48. package/dist-lib/integrations/supabase/types.d.ts.map +1 -1
  49. package/dist-lib/integrations/supabase/types.js +2 -0
  50. package/dist-lib/lib/articles.functions.d.ts +24 -0
  51. package/dist-lib/lib/articles.functions.d.ts.map +1 -0
  52. package/dist-lib/lib/articles.functions.js +112 -0
  53. package/dist-lib/lib/auth-attach.d.ts +6 -0
  54. package/dist-lib/lib/auth-attach.d.ts.map +1 -0
  55. package/dist-lib/lib/auth-attach.js +17 -0
  56. package/dist-lib/lib/config.d.ts +21 -0
  57. package/dist-lib/lib/config.d.ts.map +1 -0
  58. package/dist-lib/lib/config.js +22 -0
  59. package/dist-lib/lib/dependencies.d.ts +9 -0
  60. package/dist-lib/lib/dependencies.d.ts.map +1 -0
  61. package/dist-lib/lib/dependencies.js +43 -0
  62. package/dist-lib/lib/facturen.d.ts +200 -0
  63. package/dist-lib/lib/facturen.d.ts.map +1 -1
  64. package/dist-lib/lib/facturen.js +465 -16
  65. package/package.json +60 -8
@@ -1,33 +1,114 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useCallback, useEffect, useState } from "react";
3
- import { Link, useParams } from "@tanstack/react-router";
4
- import { Badge, Button, Card, CardContent, CardHeader, CardTitle, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Table, TableBody, TableCell, TableHead, TableHeader, TableRow, toast, } from "@flowselections/core";
5
- import { ArrowLeft } from "lucide-react";
6
- import { fetchInvoice, fetchInvoiceItems, formatCents, KIND_LABELS, SOURCE_LABELS, STATUS_LABELS, updateInvoiceStatus, } from "../lib/facturen";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useCallback, useEffect, useRef, useState } from "react";
3
+ import { DEFAULT_VAT_RATE } from "../lib/config";
4
+ import { Link, useNavigate, useParams, useSearch } from "@tanstack/react-router";
5
+ import { Badge, Button, Dialog, DialogContent, DialogHeader, DialogTitle, Input, Label, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Textarea, toast, } from "@flowselections/core";
6
+ import { ArrowLeft, ChevronLeft, ChevronRight, Download, FileCheck2, Mail, Pencil, Save, X } from "lucide-react";
7
+ import { detailsFromRecord, downloadPdfBase64, elementToPdfBase64, emptyInvoiceBranding, emptyInvoiceDetails, fetchCustomerEmail, fetchInvoice, fetchInvoiceEmailPurpose, fetchSenderForPurpose, fetchInvoiceItems, fetchInvoices, getInvoiceLogoUrl, itemToEditLine, registerInvoiceSend, sendInvoiceEmail, SOURCE_LABELS, STATUS_LABELS, updateInvoiceFull, updateInvoiceStatus, } from "../lib/facturen";
8
+ import { InvoiceA4Preview } from "./InvoiceA4Preview";
9
+ const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
10
+ const isValidEmail = (value) => EMAIL_PATTERN.test(value.trim());
7
11
  export function FactuurDetailPage() {
8
12
  const { id } = useParams({ from: "/_authenticated/facturen-installatietechniek/detail/$id" });
13
+ const search = useSearch({ from: "/_authenticated/facturen-installatietechniek/detail/$id" });
14
+ const navigate = useNavigate();
9
15
  const [invoice, setInvoice] = useState(null);
10
- const [items, setItems] = useState([]);
16
+ const [lines, setLines] = useState([]);
17
+ const [details, setDetails] = useState(emptyInvoiceDetails);
11
18
  const [loading, setLoading] = useState(true);
12
19
  const [saving, setSaving] = useState(false);
20
+ const [editing, setEditing] = useState(false);
21
+ const [logoUrl, setLogoUrl] = useState(null);
22
+ const [sendOpen, setSendOpen] = useState(false);
23
+ const [mail, setMail] = useState({ to: "", subject: "", message: "" });
24
+ const [mailToTouched, setMailToTouched] = useState(false);
25
+ const [knownEmail, setKnownEmail] = useState("");
26
+ const [confirmOpen, setConfirmOpen] = useState(false);
27
+ const [sender, setSender] = useState(null);
28
+ const [attachPdf, setAttachPdf] = useState(true);
29
+ const [preparedPdf, setPreparedPdf] = useState("");
30
+ const [preparingPdf, setPreparingPdf] = useState(false);
31
+ const [siblingInvoices, setSiblingInvoices] = useState(null);
32
+ const [siblingsLoading, setSiblingsLoading] = useState(true);
33
+ const siblingRetryRef = useRef(false);
34
+ const sheetRef = useRef(null);
35
+ const autoOpenedRef = useRef(false);
36
+ const sendingRef = useRef(false);
37
+ const statusRef = useRef(false);
38
+ const [senderChecked, setSenderChecked] = useState(false);
39
+ const loadSeqRef = useRef(0);
13
40
  const load = useCallback(async () => {
41
+ const seq = ++loadSeqRef.current;
14
42
  setLoading(true);
15
43
  try {
16
44
  const [inv, rows] = await Promise.all([fetchInvoice(id), fetchInvoiceItems(id)]);
45
+ if (seq !== loadSeqRef.current)
46
+ return;
47
+ const logo = await getInvoiceLogoUrl(inv?.branding_snapshot?.logo_path);
48
+ if (seq !== loadSeqRef.current)
49
+ return;
17
50
  setInvoice(inv);
18
- setItems(rows);
51
+ setDetails(detailsFromRecord(inv));
52
+ const safeRows = Array.isArray(rows) ? rows : [];
53
+ setLines(safeRows.map((r) => itemToEditLine(r, Number(inv?.vat_rate ?? DEFAULT_VAT_RATE))));
54
+ setLogoUrl(logo);
19
55
  }
20
56
  catch {
21
- toast.error("Factuur kon niet worden geladen");
57
+ if (seq === loadSeqRef.current)
58
+ toast.error("Factuur kon niet worden geladen");
22
59
  }
23
60
  finally {
24
- setLoading(false);
61
+ if (seq === loadSeqRef.current)
62
+ setLoading(false);
25
63
  }
26
64
  }, [id]);
27
65
  useEffect(() => {
28
66
  void load();
29
67
  }, [load]);
68
+ const loadSiblings = useCallback(async () => {
69
+ setSiblingsLoading(true);
70
+ try {
71
+ const rows = await fetchInvoices();
72
+ setSiblingInvoices(Array.isArray(rows) ? rows : []);
73
+ }
74
+ catch {
75
+ setSiblingInvoices(null);
76
+ }
77
+ finally {
78
+ setSiblingsLoading(false);
79
+ }
80
+ }, []);
81
+ useEffect(() => {
82
+ void loadSiblings();
83
+ }, [loadSiblings]);
84
+ // Als de huidige factuur nog niet in de lijst staat (net aangemaakt), één keer opnieuw ophalen.
85
+ useEffect(() => {
86
+ if (siblingsLoading || !siblingInvoices || siblingRetryRef.current)
87
+ return;
88
+ if (siblingInvoices.some((i) => i.id === id))
89
+ return;
90
+ siblingRetryRef.current = true;
91
+ void loadSiblings();
92
+ }, [siblingInvoices, siblingsLoading, id, loadSiblings]);
93
+ const listIndex = siblingInvoices ? siblingInvoices.findIndex((i) => i.id === id) : -1;
94
+ // Lijst is nieuwste eerst: vorige op de lijst = rij erboven, volgende = rij eronder.
95
+ const prevInvoice = listIndex > 0 ? siblingInvoices[listIndex - 1] : undefined;
96
+ const nextInvoice = listIndex >= 0 && siblingInvoices && listIndex < siblingInvoices.length - 1
97
+ ? siblingInvoices[listIndex + 1]
98
+ : undefined;
99
+ const goToSibling = (targetId) => {
100
+ if (!targetId)
101
+ return;
102
+ navigate({
103
+ to: "/facturen-installatietechniek/detail/$id",
104
+ params: { id: targetId },
105
+ search: { send: false },
106
+ });
107
+ };
30
108
  const changeStatus = async (status) => {
109
+ if (statusRef.current)
110
+ return;
111
+ statusRef.current = true;
31
112
  setSaving(true);
32
113
  try {
33
114
  await updateInvoiceStatus(id, status);
@@ -37,15 +118,161 @@ export function FactuurDetailPage() {
37
118
  catch {
38
119
  toast.error("Status bijwerken mislukt");
39
120
  }
121
+ finally {
122
+ statusRef.current = false;
123
+ setSaving(false);
124
+ }
125
+ };
126
+ const save = async () => {
127
+ setSaving(true);
128
+ try {
129
+ await updateInvoiceFull(id, details, lines, invoice?.note ?? null);
130
+ toast.success("Factuur opgeslagen");
131
+ setEditing(false);
132
+ await load();
133
+ }
134
+ catch (e) {
135
+ toast.error(e instanceof Error ? e.message : "Opslaan mislukt");
136
+ }
40
137
  finally {
41
138
  setSaving(false);
42
139
  }
43
140
  };
44
- if (loading) {
141
+ const pdfFilename = `Factuur-${invoice?.invoice_number ?? "concept"}.pdf`;
142
+ const openSend = async () => {
143
+ const num = invoice?.invoice_number ?? "";
144
+ const company = invoice?.branding_snapshot?.company_name ?? "";
145
+ let storedEmail = "";
146
+ try {
147
+ storedEmail = (await fetchCustomerEmail(invoice?.customer_id)) ?? "";
148
+ }
149
+ catch {
150
+ storedEmail = "";
151
+ }
152
+ setKnownEmail(storedEmail.trim());
153
+ const customerEmail = invoice?.sent_to || storedEmail;
154
+ setMail({
155
+ to: customerEmail,
156
+ subject: `Factuur ${num}${company ? ` van ${company}` : ""}`,
157
+ message: `Beste ${details.customer_attention || details.customer_name || "klant"},\n\nIn de bijlage vindt u factuur ${num}.\n\nMet vriendelijke groet,\n${company}`,
158
+ });
159
+ setSender(null);
160
+ setSenderChecked(false);
161
+ setAttachPdf(true);
162
+ setPreparedPdf("");
163
+ setMailToTouched(false);
164
+ fetchInvoiceEmailPurpose().then(fetchSenderForPurpose).then(setSender).catch(() => setSender(null)).finally(() => setSenderChecked(true));
165
+ setSendOpen(true);
166
+ if (!sheetRef.current)
167
+ return;
168
+ setPreparingPdf(true);
169
+ try {
170
+ const pdf = await elementToPdfBase64(sheetRef.current);
171
+ setPreparedPdf(pdf);
172
+ downloadPdfBase64(pdf, pdfFilename);
173
+ }
174
+ catch (error) {
175
+ toast.error(error instanceof Error ? error.message : "De factuur-PDF kon niet worden aangemaakt");
176
+ }
177
+ finally {
178
+ setPreparingPdf(false);
179
+ }
180
+ };
181
+ useEffect(() => {
182
+ autoOpenedRef.current = false;
183
+ }, [id]);
184
+ useEffect(() => {
185
+ if (loading || !invoice || !search.send || autoOpenedRef.current)
186
+ return;
187
+ autoOpenedRef.current = true;
188
+ void openSend();
189
+ void navigate({
190
+ to: "/facturen-installatietechniek/detail/$id",
191
+ params: { id },
192
+ search: { send: false },
193
+ replace: true,
194
+ });
195
+ }, [id, invoice, loading, navigate, search.send]);
196
+ const send = () => {
197
+ if (!isValidEmail(mail.to)) {
198
+ toast.error("Vul een geldig e-mailadres in");
199
+ return;
200
+ }
201
+ if (!invoice)
202
+ return;
203
+ if (senderChecked && !sender) {
204
+ toast.error("Er is geen afzender ingesteld. Stel die in bij Instellingen → Factuur e-mail.");
205
+ return;
206
+ }
207
+ if (!attachPdf || !preparedPdf) {
208
+ toast.error("Vink de PDF-bijlage aan voordat u de factuur verzendt");
209
+ return;
210
+ }
211
+ if (mail.to.trim().toLowerCase() !== knownEmail.toLowerCase()) {
212
+ setConfirmOpen(true);
213
+ return;
214
+ }
215
+ void doSend();
216
+ };
217
+ const doSend = async () => {
218
+ setConfirmOpen(false);
219
+ if (sendingRef.current)
220
+ return;
221
+ if (!invoice || !isValidEmail(mail.to) || !attachPdf || !preparedPdf)
222
+ return;
223
+ sendingRef.current = true;
224
+ const targetInvoice = nextInvoice ?? prevInvoice;
225
+ setSaving(true);
226
+ try {
227
+ const queued = await sendInvoiceEmail({
228
+ invoiceId: id,
229
+ to: mail.to.trim(),
230
+ subject: mail.subject,
231
+ message: mail.message,
232
+ pdfBase64: preparedPdf,
233
+ filename: pdfFilename,
234
+ });
235
+ try {
236
+ await registerInvoiceSend(id, queued.outboxId);
237
+ }
238
+ catch (e) {
239
+ toast.warning(e instanceof Error ? e.message : "De e-mail staat in de wachtrij, maar de factuur kon niet als verzonden worden geregistreerd");
240
+ }
241
+ toast.success(`Factuur verzonden naar ${mail.to.trim()}`, {
242
+ description: "De factuur staat nu op Verzonden. De e-mailmodule verwerkt de verzending met de PDF als bijlage.",
243
+ });
244
+ setSendOpen(false);
245
+ if (targetInvoice) {
246
+ navigate({
247
+ to: "/facturen-installatietechniek/detail/$id",
248
+ params: { id: targetInvoice.id },
249
+ search: { send: false },
250
+ });
251
+ }
252
+ else {
253
+ navigate({ to: "/facturen-installatietechniek" });
254
+ }
255
+ }
256
+ catch (e) {
257
+ toast.error(e instanceof Error ? e.message : "Verzenden mislukt");
258
+ }
259
+ finally {
260
+ sendingRef.current = false;
261
+ setSaving(false);
262
+ }
263
+ };
264
+ const changeSendOpen = (nextOpen) => {
265
+ setSendOpen(nextOpen);
266
+ if (!nextOpen) {
267
+ setPreparedPdf("");
268
+ }
269
+ };
270
+ if (loading && !invoice)
45
271
  return _jsx("main", { className: "p-6 text-sm text-muted-foreground", children: "Laden\u2026" });
46
- }
47
272
  if (!invoice) {
48
273
  return (_jsxs("main", { className: "space-y-4 p-6", children: [_jsx("p", { className: "text-sm text-muted-foreground", children: "Factuur niet gevonden." }), _jsx(Button, { asChild: true, variant: "outline", children: _jsx(Link, { to: "/facturen-installatietechniek", children: "Terug naar overzicht" }) })] }));
49
274
  }
50
- return (_jsxs("main", { className: "space-y-6 p-6", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [_jsx(Button, { asChild: true, variant: "ghost", size: "sm", children: _jsxs(Link, { to: "/facturen-installatietechniek", className: "gap-1", children: [_jsx(ArrowLeft, { className: "h-4 w-4" }), "Overzicht"] }) }), _jsx("h1", { className: "text-xl font-semibold", children: invoice.invoice_number ?? "Concept" }), _jsxs(Badge, { variant: "outline", children: [SOURCE_LABELS[invoice.source_type] ?? invoice.source_type, invoice.source_number ? ` ${invoice.source_number}` : ""] }), _jsx("div", { className: "ml-auto w-48", children: _jsxs(Select, { value: invoice.status, onValueChange: (v) => changeStatus(v), disabled: saving, children: [_jsx(SelectTrigger, { children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: Object.entries(STATUS_LABELS).map(([value, label]) => (_jsx(SelectItem, { value: value, children: label }, value))) })] }) })] }), _jsxs("div", { className: "grid gap-4 sm:grid-cols-3", children: [_jsxs(Card, { children: [_jsx(CardHeader, { className: "pb-2", children: _jsx(CardTitle, { className: "text-sm font-medium text-muted-foreground", children: "Klant" }) }), _jsx(CardContent, { className: "text-base", children: invoice.customer_name ?? "—" })] }), _jsxs(Card, { children: [_jsx(CardHeader, { className: "pb-2", children: _jsx(CardTitle, { className: "text-sm font-medium text-muted-foreground", children: "Factuurdatum" }) }), _jsx(CardContent, { className: "text-base", children: new Date(invoice.invoice_date).toLocaleDateString("nl-NL") })] }), _jsxs(Card, { children: [_jsx(CardHeader, { className: "pb-2", children: _jsx(CardTitle, { className: "text-sm font-medium text-muted-foreground", children: "Totaal incl. btw" }) }), _jsx(CardContent, { className: "text-base font-semibold", children: formatCents(invoice.total_cents) })] })] }), _jsxs(Card, { children: [_jsx(CardHeader, { children: _jsx(CardTitle, { children: "Regels" }) }), _jsxs(CardContent, { className: "space-y-4", children: [items.length === 0 ? (_jsx("p", { className: "text-sm text-muted-foreground", children: "Deze factuur heeft geen regels." })) : (_jsxs(Table, { children: [_jsx(TableHeader, { children: _jsxs(TableRow, { children: [_jsx(TableHead, { children: "Omschrijving" }), _jsx(TableHead, { children: "Soort" }), _jsx(TableHead, { className: "text-right", children: "Aantal" }), _jsx(TableHead, { children: "Eenheid" }), _jsx(TableHead, { className: "text-right", children: "Stukprijs" }), _jsx(TableHead, { className: "text-right", children: "Totaal" })] }) }), _jsx(TableBody, { children: items.map((item) => (_jsxs(TableRow, { children: [_jsx(TableCell, { children: item.description }), _jsx(TableCell, { children: KIND_LABELS[item.kind] ?? item.kind }), _jsx(TableCell, { className: "text-right", children: Number(item.quantity) }), _jsx(TableCell, { children: item.unit }), _jsx(TableCell, { className: "text-right", children: formatCents(item.unit_price_cents) }), _jsx(TableCell, { className: "text-right", children: formatCents(item.total_cents) })] }, item.id))) })] })), _jsxs("div", { className: "ml-auto w-64 space-y-1 text-sm", children: [_jsxs("div", { className: "flex justify-between", children: [_jsx("span", { className: "text-muted-foreground", children: "Subtotaal" }), _jsx("span", { children: formatCents(invoice.subtotal_cents) })] }), _jsxs("div", { className: "flex justify-between", children: [_jsxs("span", { className: "text-muted-foreground", children: ["Btw ", Number(invoice.vat_rate), "%"] }), _jsx("span", { children: formatCents(invoice.vat_cents) })] }), _jsxs("div", { className: "flex justify-between font-semibold", children: [_jsx("span", { children: "Totaal" }), _jsx("span", { children: formatCents(invoice.total_cents) })] })] })] })] }), invoice.note ? (_jsxs(Card, { children: [_jsx(CardHeader, { children: _jsx(CardTitle, { children: "Notitie" }) }), _jsx(CardContent, { className: "text-sm", children: invoice.note })] })) : null] }));
275
+ const isConcept = invoice.status === "concept";
276
+ const wasSent = Boolean(invoice.sent_at);
277
+ return (_jsxs("main", { className: "space-y-6 p-6", children: [_jsxs("div", { className: "sticky top-16 z-20 -mx-6 flex flex-wrap items-center gap-3 border-b border-border/60 bg-background px-6 py-3", children: [_jsx(Button, { asChild: true, variant: "ghost", size: "sm", children: _jsxs(Link, { to: "/facturen-installatietechniek", className: "gap-1", children: [_jsx(ArrowLeft, { className: "h-4 w-4" }), "Overzicht"] }) }), _jsx("h1", { className: "text-xl font-semibold", children: invoice.invoice_number ?? "Concept" }), _jsxs(Badge, { variant: "outline", children: [SOURCE_LABELS[invoice.source_type] ?? invoice.source_type, invoice.source_number ? ` ${invoice.source_number}` : ""] }), invoice.sent_at ? (_jsxs("span", { className: "text-xs text-muted-foreground", children: ["Verzonden ", new Date(invoice.sent_at).toLocaleString("nl-NL"), " aan ", invoice.sent_to] })) : null, _jsxs("div", { className: "ml-auto flex flex-wrap items-center gap-2", children: [_jsxs("div", { className: "flex items-center gap-1 rounded-full border border-border bg-card p-1", children: [_jsx(Button, { variant: "ghost", size: "icon", className: "h-8 w-8 rounded-full", "aria-label": "Vorige factuur op de lijst", title: "Vorige factuur op de lijst", disabled: editing || loading || siblingsLoading || !prevInvoice, onClick: () => goToSibling(prevInvoice?.id), children: _jsx(ChevronLeft, { className: "h-5 w-5" }) }), _jsx(Button, { variant: "ghost", size: "icon", className: "h-8 w-8 rounded-full", "aria-label": "Volgende factuur op de lijst", title: "Volgende factuur op de lijst", disabled: editing || loading || siblingsLoading || !nextInvoice, onClick: () => goToSibling(nextInvoice?.id), children: _jsx(ChevronRight, { className: "h-5 w-5" }) })] }), editing ? (_jsxs(_Fragment, { children: [_jsxs(Button, { variant: "outline", onClick: () => { setEditing(false); void load(); }, disabled: saving, children: [_jsx(X, { className: "mr-2 h-4 w-4" }), "Annuleren"] }), _jsxs(Button, { onClick: save, disabled: saving, children: [_jsx(Save, { className: "mr-2 h-4 w-4" }), saving ? "Opslaan…" : "Opslaan"] })] })) : (_jsxs(_Fragment, { children: [!wasSent ? (_jsxs(Button, { variant: "outline", onClick: () => (isConcept ? setEditing(true) : toast.error("Alleen conceptfacturen kunnen worden bewerkt. Zet de status terug op Concept.")), children: [_jsx(Pencil, { className: "mr-2 h-4 w-4" }), "Bewerken"] })) : null, _jsxs(Button, { onClick: () => void openSend(), children: [_jsx(Mail, { className: "mr-2 h-4 w-4" }), wasSent ? "Opnieuw verzenden" : "Verzenden"] })] })), _jsx("div", { className: "w-44", children: _jsxs(Select, { value: invoice.status, onValueChange: (v) => changeStatus(v), disabled: saving || editing, children: [_jsx(SelectTrigger, { children: _jsx(SelectValue, {}) }), _jsx(SelectContent, { children: Object.entries(STATUS_LABELS).map(([value, label]) => (_jsx(SelectItem, { value: value, children: label }, value))) })] }) })] })] }), _jsx("div", { children: _jsx("div", { className: "min-w-0", children: _jsx(InvoiceA4Preview, { ref: sheetRef, branding: invoice.branding_snapshot ?? emptyInvoiceBranding(), details: details, lines: lines, invoiceNumber: invoice.invoice_number, logoUrl: logoUrl, printable: !editing, editable: editing, defaultVat: String(Number(invoice.vat_rate) || DEFAULT_VAT_RATE), onDetailsChange: setDetails, onLinesChange: setLines }) }) }), _jsx(Dialog, { open: sendOpen, onOpenChange: changeSendOpen, children: _jsxs(DialogContent, { className: "flex max-h-[92vh] max-w-[calc(100vw-2rem)] flex-col sm:max-w-lg", children: [_jsx(DialogHeader, { children: _jsx(DialogTitle, { children: "Factuur verzenden" }) }), _jsxs("div", { className: "min-h-0 flex-1 space-y-3 overflow-y-auto pr-1", children: [_jsxs("div", { className: "space-y-1", children: [_jsx(Label, { htmlFor: "mail-to", children: "E-mailadres klant" }), _jsx(Input, { id: "mail-to", type: "email", value: mail.to, onChange: (e) => setMail({ ...mail, to: e.target.value }), onBlur: () => setMailToTouched(true), placeholder: "naam@bedrijf.nl", "aria-invalid": mailToTouched && !isValidEmail(mail.to) }), mailToTouched && !isValidEmail(mail.to) ? (_jsx("p", { className: "text-xs text-destructive", children: "Vul een geldig e-mailadres in, bijvoorbeeld naam@bedrijf.nl" })) : null] }), _jsxs("div", { className: "space-y-1", children: [_jsx(Label, { htmlFor: "mail-subject", children: "Onderwerp" }), _jsx(Input, { id: "mail-subject", value: mail.subject, onChange: (e) => setMail({ ...mail, subject: e.target.value }) })] }), _jsxs("div", { className: "space-y-1", children: [_jsx(Label, { htmlFor: "mail-msg", children: "Bericht" }), _jsx(Textarea, { id: "mail-msg", rows: 6, value: mail.message, onChange: (e) => setMail({ ...mail, message: e.target.value }) })] }), _jsxs("label", { className: "flex cursor-pointer items-start gap-3 rounded-md border border-border p-3", children: [_jsx("input", { type: "checkbox", checked: attachPdf, onChange: (event) => setAttachPdf(event.target.checked), className: "mt-1 h-4 w-4 accent-primary" }), _jsxs("span", { className: "min-w-0 flex-1", children: [_jsxs("span", { className: "flex items-center gap-2 text-sm font-medium", children: [preparedPdf ? _jsx(FileCheck2, { className: "h-4 w-4 text-primary" }) : _jsx(Download, { className: "h-4 w-4" }), "Factuur als PDF meesturen"] }), _jsx("span", { className: "mt-1 block truncate text-xs text-muted-foreground", children: preparingPdf ? "PDF wordt aangemaakt en gedownload…" : preparedPdf ? `${pdfFilename} is gedownload en klaar als bijlage.` : "PDF kon niet worden voorbereid." })] })] }), !attachPdf ? _jsx("p", { className: "text-xs text-destructive", children: "Vink de PDF aan om deze e-mail te kunnen versturen." }) : null, _jsxs("p", { className: "text-xs text-muted-foreground", children: [!senderChecked ? _jsx(_Fragment, { children: "Afzender controleren\u2026 " }) : sender ? _jsxs(_Fragment, { children: ["Verzonden vanaf ", _jsx("span", { className: "font-medium text-foreground", children: sender.account_email }), ". "] }) : _jsx("span", { className: "text-destructive", children: "Geen afzender ingesteld (Instellingen \u2192 Factuur e-mail). " }), "De factuur wordt als PDF-bijlage aangeboden aan de e-mailmodule."] }), _jsxs(Button, { className: "w-full", onClick: send, disabled: saving || preparingPdf || (senderChecked && !sender) || !attachPdf || !preparedPdf || !isValidEmail(mail.to), children: [_jsx(Mail, { className: "mr-2 h-4 w-4" }), saving ? "Bezig…" : preparingPdf ? "PDF voorbereiden…" : "Verzenden met PDF"] })] })] }) }), _jsx(Dialog, { open: confirmOpen, onOpenChange: setConfirmOpen, children: _jsxs(DialogContent, { className: "max-w-md", children: [_jsx(DialogHeader, { children: _jsx(DialogTitle, { children: "Ander e-mailadres dan bekend" }) }), _jsxs("p", { className: "text-sm text-muted-foreground", children: [knownEmail ? (_jsxs(_Fragment, { children: ["Dit adres wijkt af van het bekende adres van de klant (", _jsx("span", { className: "font-medium text-foreground", children: knownEmail }), ")."] })) : (_jsx(_Fragment, { children: "Er is geen e-mailadres van deze klant bekend." })), " ", "Weet je zeker dat je naar ", _jsx("span", { className: "font-medium text-foreground", children: mail.to.trim() }), " wilt verzenden?"] }), _jsxs("div", { className: "flex justify-end gap-2", children: [_jsx(Button, { variant: "outline", onClick: () => setConfirmOpen(false), children: "Annuleren" }), _jsx(Button, { onClick: () => void doSend(), disabled: saving, children: "Toch verzenden" })] })] }) })] }));
51
278
  }
@@ -0,0 +1,19 @@
1
+ import { type CustomerOption, type EditLine, type InvoiceBranding, type InvoiceDetails } from "../lib/facturen";
2
+ type Props = {
3
+ branding: InvoiceBranding;
4
+ details: InvoiceDetails;
5
+ lines: EditLine[];
6
+ invoiceNumber?: string | null;
7
+ numberIsProvisional?: boolean;
8
+ logoUrl?: string | null;
9
+ printable?: boolean;
10
+ editable?: boolean;
11
+ defaultVat?: string;
12
+ onDetailsChange?: (d: InvoiceDetails) => void;
13
+ onLinesChange?: (l: EditLine[]) => void;
14
+ /** Toon klantkeuzelijst bij Klantnaam (alleen nieuwe handmatige factuur). */
15
+ onCustomerPick?: (c: CustomerOption) => void;
16
+ };
17
+ export declare const InvoiceA4Preview: import("react").ForwardRefExoticComponent<Props & import("react").RefAttributes<HTMLElement>>;
18
+ export {};
19
+ //# sourceMappingURL=InvoiceA4Preview.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InvoiceA4Preview.d.ts","sourceRoot":"","sources":["../../src/components/InvoiceA4Preview.tsx"],"names":[],"mappings":"AAMA,OAAO,EAML,KAAK,cAAc,EACnB,KAAK,QAAQ,EACb,KAAK,eAAe,EACpB,KAAK,cAAc,EAEpB,MAAM,iBAAiB,CAAC;AAIzB,KAAK,KAAK,GAAG;IACX,QAAQ,EAAE,eAAe,CAAC;IAC1B,OAAO,EAAE,cAAc,CAAC;IACxB,KAAK,EAAE,QAAQ,EAAE,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,CAAC,CAAC,EAAE,cAAc,KAAK,IAAI,CAAC;IAC9C,aAAa,CAAC,EAAE,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,IAAI,CAAC;IACxC,6EAA6E;IAC7E,cAAc,CAAC,EAAE,CAAC,CAAC,EAAE,cAAc,KAAK,IAAI,CAAC;CAC9C,CAAC;AAqDF,eAAO,MAAM,gBAAgB,+FA4K3B,CAAC"}
@@ -0,0 +1,159 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { forwardRef, useEffect, useMemo, useState } from "react";
3
+ import { DEFAULT_VAT_RATE, SEARCH_DEBOUNCE_MS, VAT_OPTIONS as CONFIG_VAT_OPTIONS } from "../lib/config";
4
+ import { dependencyMessage } from "../lib/dependencies";
5
+ import { useServerFn } from "@tanstack/react-start";
6
+ import { Button, Input, Popover, PopoverContent, PopoverTrigger } from "@flowselections/core";
7
+ import { ChevronDown, Package, Plus, Printer, Search, Trash2 } from "lucide-react";
8
+ import { editLineToBillable, emptyEditLine, searchCustomers, fetchPackages, formatCents, } from "../lib/facturen";
9
+ import { listInvoiceArticles } from "../lib/articles.functions";
10
+ import { ArticlePhoto } from "./ArticlePhoto";
11
+ const VAT_OPTIONS = CONFIG_VAT_OPTIONS;
12
+ function CustomerPicker({ details, onDetailsChange, onPick }) {
13
+ const [open, setOpen] = useState(false);
14
+ const [q, setQ] = useState("");
15
+ const [items, setItems] = useState([]);
16
+ const [loading, setLoading] = useState(false);
17
+ const [error, setError] = useState("");
18
+ useEffect(() => {
19
+ if (!open)
20
+ return;
21
+ let active = true;
22
+ setLoading(true);
23
+ const t = setTimeout(() => {
24
+ searchCustomers(q)
25
+ .then((r) => { if (active) {
26
+ setItems(Array.isArray(r) ? r : []);
27
+ setError("");
28
+ } })
29
+ .catch((e) => { if (active) {
30
+ setItems([]);
31
+ setError(dependencyMessage(e, "klanten", "Klanten"));
32
+ } })
33
+ .finally(() => { if (active)
34
+ setLoading(false); });
35
+ }, SEARCH_DEBOUNCE_MS);
36
+ return () => { active = false; clearTimeout(t); };
37
+ }, [open, q]);
38
+ const filtered = Array.isArray(items) ? items : [];
39
+ return (_jsxs("div", { className: "flex items-center gap-1", children: [_jsx("input", { value: details.customer_name, placeholder: "Klantnaam", onChange: (e) => onDetailsChange?.({ ...details, customer_name: e.target.value }), className: "w-full rounded-sm border border-dashed border-border bg-transparent px-1 py-0.5 font-semibold outline-none focus:border-primary" }), _jsxs(Popover, { open: open, onOpenChange: setOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx(Button, { type: "button", variant: "outline", size: "sm", className: "h-6 shrink-0 px-1.5 print:hidden", "aria-label": "Kies klant", children: _jsx(ChevronDown, { className: "h-3.5 w-3.5" }) }) }), _jsxs(PopoverContent, { align: "start", className: "w-80 p-2", children: [_jsx(Input, { autoFocus: true, placeholder: "Zoek klant\u2026", value: q, onChange: (e) => setQ(e.target.value) }), _jsx("div", { className: "mt-2 max-h-64 overflow-y-auto", children: error ? _jsx("p", { className: "p-2 text-xs text-destructive", children: error }) : loading ? _jsx("p", { className: "p-2 text-xs text-muted-foreground", children: "Laden\u2026" }) : filtered.length === 0 ? _jsx("p", { className: "p-2 text-xs text-muted-foreground", children: "Geen klanten gevonden." }) : filtered.map((c) => (_jsxs("button", { type: "button", onClick: () => { onPick(c); setOpen(false); setQ(""); }, className: "block w-full rounded-sm px-2 py-1.5 text-left text-sm hover:bg-accent", children: [_jsx("div", { className: "font-medium", children: c.name ?? "—" }), _jsx("div", { className: "text-xs text-muted-foreground", children: [c.customer_number, c.billing_city].filter(Boolean).join(" · ") })] }, c.id))) })] })] })] }));
40
+ }
41
+ export const InvoiceA4Preview = forwardRef(function InvoiceA4Preview({ branding, details, lines, invoiceNumber, numberIsProvisional, logoUrl, printable = true, editable = false, defaultVat = String(DEFAULT_VAT_RATE), onDetailsChange, onLinesChange, onCustomerPick }, ref) {
42
+ const safeLines = Array.isArray(lines) ? lines : [];
43
+ const listArticles = useServerFn(listInvoiceArticles);
44
+ const [articles, setArticles] = useState([]);
45
+ const articleIds = safeLines.map((line) => line.articleId).filter((id) => Boolean(id));
46
+ const idsKey = [...new Set(articleIds)].sort().join(",");
47
+ useEffect(() => {
48
+ if (!idsKey)
49
+ return;
50
+ let active = true;
51
+ listArticles({ data: { ids: idsKey.split(",") } })
52
+ .then((result) => { if (active)
53
+ setArticles(Array.isArray(result) ? result : []); })
54
+ .catch(() => { if (active)
55
+ setArticles([]); });
56
+ return () => { active = false; };
57
+ }, [listArticles, idsKey]);
58
+ const articleById = useMemo(() => new Map(articles.map((article) => [article.id, article])), [articles]);
59
+ const computed = safeLines.map(editLineToBillable);
60
+ const subtotal = computed.reduce((s, l) => s + (l.line_total_cents ?? 0), 0);
61
+ const vatGroups = useMemo(() => {
62
+ const m = new Map();
63
+ computed.forEach((l) => m.set(l.vat_rate, (m.get(l.vat_rate) ?? 0) + (l.line_total_cents ?? 0)));
64
+ return [...m.entries()].sort((a, b) => b[0] - a[0]).map(([rate, base]) => ({ rate, vat: Math.round((base * rate) / 100) }));
65
+ }, [computed]);
66
+ const vatTotal = vatGroups.reduce((s, g) => s + g.vat, 0);
67
+ const number = invoiceNumber || "Wordt toegekend";
68
+ const contact = [branding.address, [branding.postal_code, branding.city].filter(Boolean).join(" "), branding.email, branding.phone, branding.website].filter(Boolean);
69
+ const setD = (k) => (v) => onDetailsChange?.({ ...details, [k]: v });
70
+ const setL = (i, patch) => onLinesChange?.(safeLines.map((l, idx) => (idx === i ? { ...l, ...patch } : l)));
71
+ const F = ({ k, placeholder, type, className }) => editable ? (_jsx("input", { type: type ?? "text", value: details[k], placeholder: placeholder, onChange: (e) => setD(k)(e.target.value), className: `w-full rounded-sm border border-dashed border-border bg-transparent px-1 py-0.5 outline-none focus:border-primary ${className ?? ""}` })) : (_jsx("span", { className: className, children: details[k] || (type === "date" ? "—" : placeholder) }));
72
+ const fmtDate = (v) => (v ? new Date(`${v}T12:00:00`).toLocaleDateString("nl-NL") : "—");
73
+ return (_jsxs("div", { className: "space-y-2", children: [printable ? (_jsx("div", { className: "flex justify-end print:hidden", children: _jsxs(Button, { type: "button", variant: "outline", size: "sm", onClick: () => window.print(), children: [_jsx(Printer, { className: "mr-2 h-4 w-4" }), "Afdrukken"] }) })) : null, _jsxs("article", { ref: ref, className: "invoice-print-target mx-auto flex min-h-[1123px] w-full max-w-[794px] flex-col bg-card text-card-foreground shadow-sm ring-1 ring-border", style: { "--invoice-primary": branding.primary_color, "--invoice-secondary": branding.secondary_color }, children: [_jsxs("header", { className: "flex h-36 items-stretch bg-[var(--invoice-primary)] px-8 py-4 text-primary-foreground", children: [_jsxs("div", { className: "flex flex-1 items-center gap-3", children: [_jsx("div", { className: "flex h-full items-center", children: logoUrl ? _jsx("img", { src: logoUrl, alt: `${branding.company_name} logo`, crossOrigin: "anonymous", className: "max-h-full max-w-56 object-contain" }) : _jsx("span", { className: "text-xs opacity-75", children: "BEDRIJFSLOGO" }) }), branding.show_company_name !== false ? _jsx("div", { className: "text-2xl font-semibold", children: branding.company_name || "Bedrijfsnaam" }) : null] }), _jsx("div", { className: "flex flex-col items-start justify-center text-left text-[11px] leading-4", children: contact.map((v) => _jsx("div", { children: v }, v)) })] }), _jsxs("div", { className: "flex flex-1 flex-col px-10 py-8 text-xs", children: [_jsxs("div", { className: "mb-8 flex items-start justify-between gap-8", children: [_jsxs("div", { className: "w-64 space-y-0.5 leading-5", children: [editable && onCustomerPick ? (_jsx(CustomerPicker, { details: details, onDetailsChange: onDetailsChange, onPick: onCustomerPick })) : (F({ k: "customer_name", placeholder: "Klantnaam", className: "font-semibold" })), editable || details.customer_attention ? _jsx("div", { children: F({ k: "customer_attention", placeholder: "T.a.v." }) }) : null, _jsx("div", { children: F({ k: "customer_address", placeholder: "Adres" }) }), _jsxs("div", { className: "flex gap-1", children: [F({ k: "customer_postal_code", placeholder: "Postcode", className: "w-24" }), F({ k: "customer_city", placeholder: "Plaats" })] }), editable || details.customer_vat_number ? _jsxs("div", { className: "flex items-center gap-1", children: [_jsx("span", { className: "shrink-0", children: "Btw-nr:" }), F({ k: "customer_vat_number", placeholder: "—" })] }) : null] }), _jsxs("div", { className: "min-w-72", children: [_jsx("h2", { className: "mb-3 text-2xl font-semibold", children: "FACTUUR" }), _jsxs("dl", { className: "grid grid-cols-[auto_1fr] items-center gap-x-5 gap-y-1", children: [_jsx("dt", { children: "Factuurnummer" }), _jsxs("dd", { className: "font-medium", children: [number, numberIsProvisional && invoiceNumber ? _jsx("span", { className: "ml-1 text-[10px] font-normal text-muted-foreground print:hidden", children: "(voorlopig)" }) : null] }), _jsx("dt", { children: "Factuurdatum" }), _jsx("dd", { children: editable ? F({ k: "invoice_date", placeholder: "", type: "date" }) : fmtDate(details.invoice_date) }), _jsx("dt", { children: "Betaaltermijn" }), _jsx("dd", { children: editable ? _jsxs("span", { className: "flex items-center gap-1", children: [F({ k: "payment_term_days", placeholder: "30", className: "w-14" }), "dagen"] }) : `${details.payment_term_days || branding.payment_term_days} dagen` }), _jsx("dt", { children: "Vervaldatum" }), _jsx("dd", { children: formatDueDate(details.invoice_date, details.payment_term_days) }), _jsx("dt", { children: "Debiteurnummer" }), _jsx("dd", { children: F({ k: "debtor_number", placeholder: "—" }) }), _jsx("dt", { children: "Referentie" }), _jsx("dd", { children: F({ k: "reference", placeholder: "—" }) }), _jsx("dt", { children: "Werkbonnummer" }), _jsx("dd", { children: F({ k: "source_number", placeholder: "—" }) }), _jsx("dt", { children: "Werkadres" }), _jsx("dd", { children: F({ k: "work_address", placeholder: "—" }) }), _jsx("dt", { children: "Uitvoerdatum" }), _jsx("dd", { children: editable ? F({ k: "execution_date", placeholder: "", type: "date" }) : fmtDate(details.execution_date) })] })] })] }), _jsxs("table", { className: "w-full table-fixed border-collapse text-left", children: [_jsx("thead", { className: "border-y border-foreground/30", children: _jsxs("tr", { children: [_jsx("th", { className: "w-[44%] py-2", children: "Omschrijving" }), _jsx("th", { className: "w-[12%] py-2 text-right", children: "Aantal" }), _jsx("th", { className: "w-[15%] py-2 text-right", children: "Prijs" }), _jsx("th", { className: "w-[11%] py-2 text-right", children: "Btw" }), _jsx("th", { className: "w-[15%] py-2 text-right", children: "Totaal" }), editable ? _jsx("th", { className: "w-[3%]" }) : null] }) }), _jsx("tbody", { children: safeLines.length ? safeLines.map((line, i) => {
74
+ const c = computed[i];
75
+ return (_jsx("tr", { className: "border-b border-border/60 align-top", children: editable ? (_jsxs(_Fragment, { children: [_jsx("td", { className: "py-1 pr-2", children: _jsxs("div", { className: "flex items-start gap-2", children: [_jsx("textarea", { rows: 1, value: line.description, placeholder: "Omschrijving", readOnly: Boolean(line.articleId), onChange: (e) => setL(i, { description: e.target.value }), className: "min-w-0 flex-1 resize-y rounded-sm border border-dashed border-border bg-transparent px-1 py-0.5 outline-none focus:border-primary read-only:border-transparent read-only:bg-muted/40" }), line.articleId ? _jsx(ArticlePhoto, { src: articleById.get(line.articleId)?.photo_url ?? line.photoUrl, alt: line.description, className: "h-9 w-9" }) : null] }) }), _jsx("td", { className: "py-1", children: _jsx("input", { value: line.quantity, onChange: (e) => setL(i, { quantity: e.target.value }), className: "w-full rounded-sm border border-dashed border-border bg-transparent px-1 py-0.5 text-right outline-none focus:border-primary" }) }), _jsx("td", { className: "py-1 pl-1", children: _jsx("input", { value: line.price, placeholder: "0,00", readOnly: Boolean(line.articleId), onChange: (e) => setL(i, { price: e.target.value }), className: "w-full rounded-sm border border-dashed border-border bg-transparent px-1 py-0.5 text-right outline-none focus:border-primary read-only:border-transparent read-only:bg-muted/40" }) }), _jsx("td", { className: "py-1 pl-1", children: _jsx("select", { value: line.vat, disabled: Boolean(line.articleId), onChange: (e) => setL(i, { vat: e.target.value }), className: "w-full rounded-sm border border-dashed border-border bg-transparent px-0.5 py-0.5 text-right outline-none disabled:border-transparent disabled:bg-muted/40 disabled:opacity-100", children: [...new Set([...VAT_OPTIONS, line.vat])].map((v) => _jsxs("option", { value: v, children: [v, "%"] }, v)) }) }), _jsx("td", { className: "py-1.5 text-right", children: formatCents(c.line_total_cents) }), _jsx("td", { className: "py-1 text-right print:hidden", children: _jsx("button", { type: "button", "aria-label": "Regel verwijderen", onClick: () => onLinesChange?.(safeLines.filter((_, idx) => idx !== i)), className: "text-muted-foreground hover:text-destructive", children: _jsx(Trash2, { className: "h-3.5 w-3.5" }) }) })] })) : (_jsxs(_Fragment, { children: [_jsx("td", { className: "whitespace-pre-wrap break-words py-2 pr-3", children: _jsxs("div", { className: "flex items-start gap-2", children: [_jsx("span", { className: "min-w-0 flex-1", children: line.description || "—" }), line.articleId ? _jsx(ArticlePhoto, { src: articleById.get(line.articleId)?.photo_url ?? line.photoUrl, alt: line.description, className: "h-9 w-9" }) : null] }) }), _jsxs("td", { className: "py-2 text-right", children: [c.quantity, " ", line.unit] }), _jsx("td", { className: "py-2 text-right", children: formatCents(c.unit_price_cents) }), _jsxs("td", { className: "py-2 text-right", children: [c.vat_rate, "%"] }), _jsx("td", { className: "py-2 text-right", children: formatCents(c.line_total_cents) })] })) }, i));
76
+ }) : _jsx("tr", { children: _jsx("td", { colSpan: editable ? 6 : 5, className: "py-8 text-center text-muted-foreground", children: "Nog geen factuurregels" }) }) })] }), editable ? _jsx(AddLineBar, { defaultVat: defaultVat, onAdd: (l) => onLinesChange?.([...safeLines, l]) }) : null, _jsxs("div", { className: "mt-6 ml-auto w-64 space-y-1.5", children: [_jsxs("div", { className: "flex justify-between", children: [_jsx("span", { children: "Totaal excl. btw" }), _jsx("span", { children: formatCents(subtotal) })] }), (vatGroups.length ? vatGroups : [{ rate: Number(defaultVat) || 0, vat: 0 }]).map((g) => (_jsxs("div", { className: "flex justify-between", children: [_jsxs("span", { children: ["Btw ", g.rate, "%"] }), _jsx("span", { children: formatCents(g.vat) })] }, g.rate))), _jsxs("div", { className: "flex justify-between border-t border-foreground pt-2 text-sm font-semibold", children: [_jsx("span", { children: "Door u te betalen" }), _jsx("span", { children: formatCents(subtotal + vatTotal) })] })] }), _jsxs("p", { className: "mt-auto pb-5 pt-8 text-center font-medium", children: ["Graag betaling binnen ", details.payment_term_days || branding.payment_term_days, " dagen o.v.v. ", number] })] }), _jsxs("footer", { className: "grid min-h-16 grid-cols-3 items-center gap-4 bg-[var(--invoice-secondary)] px-8 py-4 text-[10px] text-primary-foreground", children: [_jsxs("span", { children: ["KvK ", branding.chamber_of_commerce_number || "—"] }), _jsxs("span", { className: "text-center", children: ["Btw-id ", branding.vat_identification_number || "—"] }), _jsxs("span", { className: "text-right", children: ["IBAN ", branding.iban || "—"] })] })] }), _jsx("style", { children: `@page{size:A4;margin:0}@media print{body *{visibility:hidden!important}.invoice-print-target,.invoice-print-target *{visibility:visible!important}.invoice-print-target{position:absolute!important;inset:0!important;width:210mm!important;min-height:297mm!important;height:auto!important;max-width:none!important;box-shadow:none!important;print-color-adjust:exact!important;-webkit-print-color-adjust:exact!important}.invoice-print-target tr{break-inside:avoid}}` })] }));
77
+ });
78
+ function AddLineBar({ defaultVat, onAdd }) {
79
+ const searchArticles = useServerFn(listInvoiceArticles);
80
+ const [articles, setArticles] = useState([]);
81
+ const [articlesLoading, setArticlesLoading] = useState(false);
82
+ const [articlesError, setArticlesError] = useState("");
83
+ const [packagesError, setPackagesError] = useState("");
84
+ const [packages, setPackages] = useState([]);
85
+ const [packageOpen, setPackageOpen] = useState(false);
86
+ const [packageQuery, setPackageQuery] = useState("");
87
+ const [articleOpen, setArticleOpen] = useState(false);
88
+ const [articleQuery, setArticleQuery] = useState("");
89
+ useEffect(() => {
90
+ fetchPackages()
91
+ .then((r) => { setPackages(Array.isArray(r) ? r : []); setPackagesError(""); })
92
+ .catch((e) => { setPackages([]); setPackagesError(dependencyMessage(e, "werkbonnen", "Pakketten")); });
93
+ }, []);
94
+ useEffect(() => {
95
+ if (!articleOpen)
96
+ return;
97
+ let active = true;
98
+ setArticlesLoading(true);
99
+ const t = setTimeout(() => {
100
+ searchArticles({ data: { query: articleQuery } })
101
+ .then((r) => { if (active) {
102
+ setArticles(Array.isArray(r) ? r : []);
103
+ setArticlesError("");
104
+ } })
105
+ .catch((e) => {
106
+ if (!active)
107
+ return;
108
+ setArticles([]);
109
+ const msg = e instanceof Error ? e.message : "";
110
+ setArticlesError(msg.startsWith("MISSING_DEPENDENCY:") ? `Materialen niet beschikbaar: ${msg.slice(19).trim()}` : "Artikelen konden niet worden geladen. Probeer het opnieuw.");
111
+ })
112
+ .finally(() => { if (active)
113
+ setArticlesLoading(false); });
114
+ }, SEARCH_DEBOUNCE_MS);
115
+ return () => { active = false; clearTimeout(t); };
116
+ }, [articleOpen, articleQuery, searchArticles]);
117
+ const safePackages = Array.isArray(packages) ? packages : [];
118
+ const safeArticles = Array.isArray(articles) ? articles : [];
119
+ const filteredPackages = safePackages.filter((p) => !packageQuery.trim() || [p.name, p.code, p.description].some((v) => (v ?? "").toLowerCase().includes(packageQuery.trim().toLowerCase())));
120
+ const filteredArticles = safeArticles;
121
+ return (_jsxs("div", { className: "mt-3 flex flex-wrap items-center gap-2 print:hidden", children: [_jsxs(Button, { type: "button", size: "sm", variant: "outline", onClick: () => onAdd(emptyEditLine(defaultVat)), children: [_jsx(Plus, { className: "mr-1 h-4 w-4" }), "Vrije regel"] }), _jsxs(Popover, { open: articleOpen, onOpenChange: setArticleOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { type: "button", size: "sm", variant: "outline", children: [_jsx(Search, { className: "mr-1 h-4 w-4" }), "Materiaal zoeken"] }) }), _jsxs(PopoverContent, { className: "w-[min(42rem,calc(100vw-2rem))] p-2", align: "start", children: [_jsx(Input, { autoFocus: true, placeholder: "Zoek op titel, artikelcode, EAN of omschrijving\u2026", value: articleQuery, onChange: (e) => setArticleQuery(e.target.value) }), _jsx("div", { className: "mt-2 flex max-h-[18rem] flex-wrap content-start touch-pan-y gap-1 overflow-y-auto overscroll-contain", onWheel: (event) => {
122
+ event.preventDefault();
123
+ event.stopPropagation();
124
+ event.currentTarget.scrollTop += event.deltaY;
125
+ }, children: articlesError ? _jsx("p", { className: "w-full p-3 text-sm text-destructive", children: articlesError }) : articlesLoading ? _jsx("p", { className: "w-full p-3 text-sm text-muted-foreground", children: "Artikelen laden\u2026" }) : filteredArticles.length === 0 ? _jsx("p", { className: "w-full p-3 text-sm text-muted-foreground", children: "Geen artikelen gevonden." }) : filteredArticles.map((article) => (_jsxs(Button, { type: "button", variant: "ghost", className: "flex h-auto w-fit flex-col items-start gap-2 overflow-hidden p-2 text-left", onClick: () => {
126
+ onAdd({
127
+ description: article.description?.trim() ? `${article.name} — ${article.description.trim()}` : article.name,
128
+ quantity: "1",
129
+ unit: article.unit,
130
+ price: (article.sales_price_cents / 100).toFixed(2).replace(".", ","),
131
+ vat: defaultVat,
132
+ kind: "material",
133
+ articleId: article.id,
134
+ photoUrl: article.photo_url,
135
+ });
136
+ setArticleOpen(false);
137
+ setArticleQuery("");
138
+ }, children: [_jsx(ArticlePhoto, { src: article.photo_url, alt: article.name, className: "h-24 w-24" }), _jsxs("span", { className: "w-24", children: [_jsx("span", { className: "line-clamp-2 block whitespace-normal font-medium leading-snug", children: article.name }), _jsxs("span", { className: "mt-1 block truncate text-xs text-muted-foreground", children: ["EAN ", article.gtin || "—"] }), _jsx("span", { className: "mt-1 block font-semibold", children: formatCents(article.sales_price_cents) })] })] }, article.id))) })] })] }), _jsxs(Popover, { open: packageOpen, onOpenChange: setPackageOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { type: "button", size: "sm", variant: "outline", children: [_jsx(Package, { className: "mr-1 h-4 w-4" }), "Pakket"] }) }), _jsxs(PopoverContent, { className: "w-96 p-2", align: "start", children: [_jsx(Input, { autoFocus: true, placeholder: "Zoek pakket\u2026", value: packageQuery, onChange: (e) => setPackageQuery(e.target.value) }), _jsx("div", { className: "mt-2 max-h-72 overflow-y-auto", children: packagesError ? _jsx("p", { className: "p-2 text-sm text-destructive", children: packagesError }) : filteredPackages.length === 0 ? _jsx("p", { className: "p-2 text-sm text-muted-foreground", children: "Geen pakketten gevonden." }) : filteredPackages.map((p) => (_jsxs(Button, { type: "button", variant: "ghost", className: "flex h-auto w-full items-start justify-between gap-2 px-2 py-1.5 text-left text-sm", onClick: () => {
139
+ const cents = Math.round(Number(p.unit_price_cents) || 0);
140
+ onAdd({
141
+ description: p.description?.trim() ? `${p.name} — ${p.description.trim()}` : p.name,
142
+ quantity: String(Number(p.default_quantity) > 0 ? Number(p.default_quantity) : 1),
143
+ unit: "pakket",
144
+ price: (cents / 100).toFixed(2).replace(".", ","),
145
+ vat: defaultVat,
146
+ kind: "package",
147
+ packageId: p.id,
148
+ });
149
+ setPackageOpen(false);
150
+ setPackageQuery("");
151
+ }, children: [_jsxs("span", { className: "min-w-0", children: [_jsx("span", { className: "block truncate font-medium", children: p.name }), p.code ? _jsx("span", { className: "block text-xs text-muted-foreground", children: p.code }) : null] }), _jsx("span", { className: "shrink-0", children: formatCents(p.unit_price_cents) })] }, p.id))) })] })] })] }));
152
+ }
153
+ function formatDueDate(invoiceDate, paymentTerm) {
154
+ if (!invoiceDate)
155
+ return "—";
156
+ const date = new Date(`${invoiceDate}T12:00:00`);
157
+ date.setDate(date.getDate() + (parseInt(paymentTerm, 10) || 0));
158
+ return date.toLocaleDateString("nl-NL");
159
+ }
@@ -0,0 +1,7 @@
1
+ import type { InvoiceDetails } from "../lib/facturen";
2
+ export declare function InvoiceDetailsFields({ value, onChange, disabled, }: {
3
+ value: InvoiceDetails;
4
+ onChange: (next: InvoiceDetails) => void;
5
+ disabled?: boolean;
6
+ }): import("react").JSX.Element;
7
+ //# sourceMappingURL=InvoiceDetailsFields.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InvoiceDetailsFields.d.ts","sourceRoot":"","sources":["../../src/components/InvoiceDetailsFields.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAkBtD,wBAAgB,oBAAoB,CAAC,EACnC,KAAK,EACL,QAAQ,EACR,QAAQ,GACT,EAAE;IACD,KAAK,EAAE,cAAc,CAAC;IACtB,QAAQ,EAAE,CAAC,IAAI,EAAE,cAAc,KAAK,IAAI,CAAC;IACzC,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,+BAgCA"}
@@ -0,0 +1,21 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Input, Label } from "@flowselections/core";
3
+ const FIELDS = [
4
+ { key: "customer_name", label: "Klantnaam", group: "klant" },
5
+ { key: "customer_attention", label: "t.a.v. / p/a", group: "klant" },
6
+ { key: "customer_address", label: "Adres", group: "klant" },
7
+ { key: "customer_postal_code", label: "Postcode", group: "klant" },
8
+ { key: "customer_city", label: "Plaats", group: "klant" },
9
+ { key: "debtor_number", label: "Debiteurnummer", group: "klant" },
10
+ { key: "customer_vat_number", label: "Btw-nummer", group: "klant" },
11
+ { key: "invoice_date", label: "Factuurdatum", type: "date", group: "factuur" },
12
+ { key: "payment_term_days", label: "Betaaltermijn (dagen)", type: "number", group: "factuur" },
13
+ { key: "reference", label: "Referentie", group: "factuur" },
14
+ { key: "source_number", label: "Werkbonnummer", group: "factuur" },
15
+ { key: "work_address", label: "Werkadres", group: "factuur" },
16
+ { key: "execution_date", label: "Uitvoerdatum", type: "date", group: "factuur" },
17
+ ];
18
+ export function InvoiceDetailsFields({ value, onChange, disabled, }) {
19
+ const render = (group) => FIELDS.filter((f) => f.group === group).map((f) => (_jsxs("div", { className: "space-y-1", children: [_jsx(Label, { htmlFor: `inv-${f.key}`, className: "text-xs", children: f.label }), _jsx(Input, { id: `inv-${f.key}`, type: f.type ?? "text", value: String(value[f.key] ?? ""), disabled: disabled, onChange: (e) => onChange({ ...value, [f.key]: e.target.value }) })] }, f.key)));
20
+ return (_jsxs("div", { className: "space-y-3 rounded-md border p-3", children: [_jsx("p", { className: "text-sm font-medium", children: "Factuurgegevens" }), _jsxs("div", { className: "grid gap-4 sm:grid-cols-2", children: [_jsxs("div", { className: "space-y-2", children: [_jsx("p", { className: "text-xs font-medium uppercase text-muted-foreground", children: "Klant / debiteur" }), render("klant")] }), _jsxs("div", { className: "space-y-2", children: [_jsx("p", { className: "text-xs font-medium uppercase text-muted-foreground", children: "Factuur" }), render("factuur")] })] })] }));
21
+ }
@@ -0,0 +1,6 @@
1
+ /** Nette foutweergave voor de pagina's van de Facturen-module (geen wit scherm). */
2
+ export declare function ModuleErrorView({ reset }: {
3
+ error?: unknown;
4
+ reset?: () => void;
5
+ }): import("react").JSX.Element;
6
+ //# sourceMappingURL=ModuleErrorView.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ModuleErrorView.d.ts","sourceRoot":"","sources":["../../src/components/ModuleErrorView.tsx"],"names":[],"mappings":"AAGA,oFAAoF;AACpF,wBAAgB,eAAe,CAAC,EAAE,KAAK,EAAE,EAAE;IAAE,KAAK,CAAC,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,IAAI,CAAA;CAAE,+BAgBjF"}
@@ -0,0 +1,11 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Button } from "@flowselections/core";
3
+ import { useRouter } from "@tanstack/react-router";
4
+ /** Nette foutweergave voor de pagina's van de Facturen-module (geen wit scherm). */
5
+ export function ModuleErrorView({ reset }) {
6
+ const router = useRouter();
7
+ return (_jsxs("main", { className: "space-y-4 p-6", children: [_jsx("p", { className: "text-sm text-muted-foreground", children: "Er ging iets mis bij het laden van deze pagina." }), _jsx(Button, { variant: "outline", onClick: () => {
8
+ reset?.();
9
+ void router.invalidate();
10
+ }, children: "Opnieuw proberen" })] }));
11
+ }
@@ -0,0 +1,4 @@
1
+ export declare function WerkbonPreviewPanel({ workOrderId }: {
2
+ workOrderId: string;
3
+ }): import("react").JSX.Element;
4
+ //# sourceMappingURL=WerkbonPreviewPanel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WerkbonPreviewPanel.d.ts","sourceRoot":"","sources":["../../src/components/WerkbonPreviewPanel.tsx"],"names":[],"mappings":"AAwBA,wBAAgB,mBAAmB,CAAC,EAAE,WAAW,EAAE,EAAE;IAAE,WAAW,EAAE,MAAM,CAAA;CAAE,+BA0F3E"}