-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
756 lines (681 loc) · 38 KB
/
worker.js
File metadata and controls
756 lines (681 loc) · 38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
// Cloudflare Worker — Invoice Generator
const PALETTE = Object.freeze({
brandTeal: "#00727D",
brandTealHover: "#005F69",
brandTealDark: "#0F4C52",
brandTealSurface: "#F0FAFB",
brandInk: "#0F172A",
textSecondary: "#334155",
textSubtle: "#64748B",
textTertiary: "#94A3B8",
surface1: "#FFFFFF",
surface2: "#F8FAFC",
surface3: "#F1F5F9",
borderDefault: "#E2E8F0",
surfaceButtonSecondary: "#E2E8F0",
warningBg: "#FFFBEB",
warningBorder: "#FDE68A",
warningText: "#B45309",
});
const TOKEN_CSS_BLOCK = `
:root {
--brand-teal: ${PALETTE.brandTeal};
--brand-teal-hover: ${PALETTE.brandTealHover};
--brand-teal-dark: ${PALETTE.brandTealDark};
--brand-teal-surface: ${PALETTE.brandTealSurface};
--brand-ink: ${PALETTE.brandInk};
--text-primary: var(--brand-ink);
--text-secondary: ${PALETTE.textSecondary};
--text-subtle: ${PALETTE.textSubtle};
--text-tertiary: ${PALETTE.textTertiary};
--surface-1: ${PALETTE.surface1};
--surface-2: ${PALETTE.surface2};
--surface-3: ${PALETTE.surface3};
--surface-button-secondary: ${PALETTE.surfaceButtonSecondary};
--border-default: ${PALETTE.borderDefault};
--color-warning-bg: ${PALETTE.warningBg};
--color-warning-border: ${PALETTE.warningBorder};
--color-warning-text: ${PALETTE.warningText};
}
`;
const TOKEN_CSS_MIN = `:root{--brand-teal:${PALETTE.brandTeal};--brand-teal-hover:${PALETTE.brandTealHover};--brand-teal-dark:${PALETTE.brandTealDark};--brand-teal-surface:${PALETTE.brandTealSurface};--brand-ink:${PALETTE.brandInk};--text-primary:var(--brand-ink);--text-secondary:${PALETTE.textSecondary};--text-subtle:${PALETTE.textSubtle};--text-tertiary:${PALETTE.textTertiary};--surface-1:${PALETTE.surface1};--surface-2:${PALETTE.surface2};--surface-3:${PALETTE.surface3};--surface-button-secondary:${PALETTE.surfaceButtonSecondary};--border-default:${PALETTE.borderDefault};--color-warning-bg:${PALETTE.warningBg};--color-warning-border:${PALETTE.warningBorder};--color-warning-text:${PALETTE.warningText}}`;
const FAVICON = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="256" height="256">
<rect width="100" height="100" rx="25" fill="${PALETTE.brandTeal}" />
<g transform="translate(15, 15) scale(2.9, 2.9)">
<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="${PALETTE.surface1}" stroke-width="1.2">
<path stroke-linecap="round" stroke-linejoin="round" d="M2.25 18.75a60.07 60.07 0 0 1 15.797 2.101c.727.198 1.453-.342 1.453-1.096V18.75M3.75 4.5v.75A.75.75 0 0 1 3 6h-.75m0 0v-.375c0-.621.504-1.125 1.125-1.125H20.25M2.25 6v9m18-10.5v.75c0 .414.336.75.75.75h.75m-1.5-1.5h.375c.621 0 1.125.504 1.125 1.125v9.75c0 .621-.504 1.125-1.125 1.125h-.375m1.5-1.5H21a.75.75 0 0 0-.75.75v.75m0 0H3.75m0 0h-.375a1.125 1.125 0 0 1-1.125-1.125V15m1.5 1.5v-.75A.75.75 0 0 0 3 15h-.75M15 10.5a3 3 0 1 1-6 0 3 3 0 0 1 6 0Zm3 0h.008v.008H18V10.5Zm-12 0h.008v.008H6V10.5Z" />
</svg>
</g>
</svg>`;
export default {
async fetch(request) {
const method = request.method.toUpperCase();
if (method !== "GET" && method !== "HEAD") {
return new Response("Method Not Allowed", {
status: 405,
headers: {
"Allow": "GET, HEAD",
"Content-Type": "text/plain;charset=utf-8",
},
});
}
const url = new URL(request.url);
const isHead = method === "HEAD";
if (url.pathname === "/favicon.svg" || url.pathname === "/favicon.ico") {
return new Response(isHead ? null : FAVICON, {
headers: {
"Content-Type": "image/svg+xml",
"Cache-Control": "public, max-age=604800",
},
});
}
if (url.pathname === "/" || url.pathname === "/index.html") {
return new Response(isHead ? null : HTML, {
headers: { "Content-Type": "text/html;charset=utf-8" },
});
}
return new Response("Not Found", {
status: 404,
headers: { "Content-Type": "text/plain;charset=utf-8" },
});
},
};
const HTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Invoice Generator</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
${TOKEN_CSS_BLOCK}
body { font-family: 'Inter', sans-serif; background: var(--surface-3); color: var(--text-primary); }
@media print {
body { background: var(--surface-1); }
.no-print { display: none !important; }
.print-page {
break-after: page;
page-break-after: always;
break-inside: avoid;
page-break-inside: avoid;
}
.print-page:last-child {
break-after: auto;
page-break-after: auto;
}
.print-page table,
.print-page thead,
.print-page tbody,
.print-page tr {
break-inside: avoid;
page-break-inside: avoid;
}
}
/* ── MOBILE OVERRIDES ──────────────────────────────────── */
@media (max-width: 640px) {
[data-page-wrap] {
padding: 20px 16px !important;
}
[data-section] {
padding: 20px !important;
}
[data-grid3] {
grid-template-columns: 1fr !important;
}
[data-grid2] {
grid-template-columns: 1fr !important;
}
[data-li-header] {
display: none !important;
}
[data-li-row] {
grid-template-columns: 1fr 1fr !important;
gap: 8px !important;
padding: 12px 0 !important;
border-bottom: 1px solid var(--border-default) !important;
margin-bottom: 0 !important;
}
[data-li-row] > [data-li-desc] {
grid-column: 1 / -1 !important;
}
[data-li-row] > [data-li-amount] {
text-align: left !important;
padding: 4px 0 !important;
}
[data-li-row] > [data-li-remove] {
justify-self: end !important;
align-self: center !important;
}
[data-preview-scale] {
overflow: hidden !important;
}
[data-topbar] {
gap: 12px !important;
}
button, input, textarea {
min-height: 44px;
}
/* Fix date inputs overflowing on mobile */
input[type="date"] {
max-width: 100% !important;
min-width: 0 !important;
overflow: hidden !important;
}
}
.btn-ui {
border: none;
font-family: 'Inter', sans-serif;
transition: background-color 120ms ease, box-shadow 120ms ease;
}
.btn-ui:focus-visible {
outline: 2px solid var(--brand-teal);
outline-offset: 2px;
box-shadow: 0 0 0 3px var(--brand-teal-surface);
}
.btn-primary {
background: var(--brand-teal);
color: var(--surface-1);
}
.btn-primary:hover { background: var(--brand-teal-hover); }
.btn-primary:active { background: var(--brand-teal-dark); }
.btn-secondary {
background: var(--surface-button-secondary);
color: var(--text-secondary);
}
.btn-secondary:hover { background: var(--surface-2); }
.btn-secondary:active { background: var(--border-default); }
.btn-add {
background: var(--brand-teal-surface);
color: var(--brand-teal);
border: 1px dashed var(--brand-teal);
}
.btn-add:hover { background: var(--surface-1); }
.btn-add:active { background: var(--surface-2); }
</style>
</head>
<body>
<div id="root"></div>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.9/babel.min.js"></script>
<script type="text/babel" data-type="module">
const { useState, useRef, useEffect } = React;
/* ── brand tokens ──────────────────────────────────────── */
const TOKENS = Object.freeze({
brandTeal: "var(--brand-teal)",
brandTealHover: "var(--brand-teal-hover)",
brandTealDark: "var(--brand-teal-dark)",
brandTealSurface: "var(--brand-teal-surface)",
textPrimary: "var(--text-primary)",
textSecondary: "var(--text-secondary)",
textSubtle: "var(--text-subtle)",
textTertiary: "var(--text-tertiary)",
surface1: "var(--surface-1)",
surface2: "var(--surface-2)",
surface3: "var(--surface-3)",
surfaceButtonSecondary: "var(--surface-button-secondary)",
borderDefault: "var(--border-default)",
});
const TOKEN_DECLARATIONS_MIN = ${JSON.stringify(TOKEN_CSS_MIN)};
const TEAL = TOKENS.brandTeal;
const DARK = TOKENS.textPrimary;
/* ── helpers ────────────────────────────────────────────── */
const fmt = (n) => {
const str = n.toLocaleString("en-ZA", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
return "R\\u00A0" + str;
};
const parseDateInput = (value) => {
if (typeof value !== "string") return null;
const match = value.trim().match(/^(\\d{4})-(\\d{2})-(\\d{2})$/);
if (!match) return null;
const y = Number(match[1]);
const m = Number(match[2]);
const d = Number(match[3]);
const dt = new Date(y, m - 1, d);
const isValid =
dt.getFullYear() === y &&
dt.getMonth() === m - 1 &&
dt.getDate() === d;
return isValid ? dt : null;
};
const fmtDate = (d) => {
if (!d) return "";
const dt = typeof d === "string" ? (parseDateInput(d) || new Date(d)) : d;
if (isNaN(dt.getTime())) return "";
return dt.toLocaleDateString("en-ZA", { day: "2-digit", month: "short", year: "numeric" });
};
const genId = () => Math.random().toString(36).slice(2, 10);
const seedRef = (billTo) => {
if (!billTo) return "";
const name = billTo.split("\\n")[0].trim();
return name.toUpperCase().replace(/\\s+/g, "-");
};
/* ── Pagination helper ─────────────────────────────────── */
// Page 1 has header + meta + table header = less room for rows.
// Continuation pages have a smaller header + table header = more room.
// Final page with notes/bank content needs additional reserved space.
const ROWS_FIRST_PAGE = 12;
const ROWS_CONT_PAGE = 22;
const ROWS_FINAL_WITH_EXTRAS = 16;
const MIN_ROWS_FINAL_WITH_EXTRAS = 8;
const CHARS_PER_EXTRA_LINE = 90;
const estimateLines = (text) => {
const cleaned = (text || "").trim();
if (!cleaned) return 0;
return cleaned
.split("\\n")
.filter(Boolean)
.reduce((sum, line) => sum + Math.max(1, Math.ceil(line.length / CHARS_PER_EXTRA_LINE)), 0);
};
function computeFinalPageCapacity(notes, bankDetails) {
const noteLines = estimateLines(notes);
const bankLines = estimateLines(bankDetails);
const noteReserve = noteLines > 0 ? noteLines + 2 : 0;
const bankReserve = bankLines > 0 ? bankLines + 2 : 0;
const reservedRows = noteReserve + bankReserve;
const dynamicCapacity = ROWS_CONT_PAGE - reservedRows;
return Math.max(
MIN_ROWS_FINAL_WITH_EXTRAS,
Math.min(ROWS_FINAL_WITH_EXTRAS, dynamicCapacity),
);
}
function paginateItems(items, options = {}) {
const list = Array.isArray(items) ? items : [];
if (list.length === 0) return [[]];
if (list.length <= ROWS_FIRST_PAGE) return [list];
const notes = (options.notes || "").trim();
const bankDetails = (options.bankDetails || "").trim();
const hasExtras = Boolean(notes || bankDetails);
const finalPageCapacity = hasExtras
? computeFinalPageCapacity(notes, bankDetails)
: ROWS_CONT_PAGE;
const pages = [];
let cursor = 0;
const firstTake = Math.min(ROWS_FIRST_PAGE, list.length);
pages.push(list.slice(cursor, cursor + firstTake));
cursor += firstTake;
let remaining = list.length - cursor;
while (remaining > finalPageCapacity) {
const take = Math.min(ROWS_CONT_PAGE, remaining - finalPageCapacity);
pages.push(list.slice(cursor, cursor + take));
cursor += take;
remaining -= take;
}
if (remaining > 0) {
pages.push(list.slice(cursor, cursor + remaining));
}
return pages;
}
/* ── PDF ────────────────────────────────────────────────── */
const savePDF = (ref) => {
const el = ref.current;
if (!el) {
console.error("Unable to export invoice: preview content is missing.");
alert("Unable to export right now. Switch to preview and try again.");
return;
}
const html = '<!DOCTYPE html><html><head><meta charset="utf-8">' +
'<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">' +
'<style>*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}' +
TOKEN_DECLARATIONS_MIN +
'@page{size:A4;margin:0}' +
"body{margin:0;padding:0;background:" + TOKENS.surface1 + ";font-family:'Inter',sans-serif;color:" + DARK + ";-webkit-print-color-adjust:exact;print-color-adjust:exact}" +
'.print-page{min-height:297mm;break-after:page;page-break-after:always;break-inside:avoid;page-break-inside:avoid}' +
'.print-page:last-child{break-after:auto;page-break-after:auto}' +
'.print-page table,.print-page thead,.print-page tbody,.print-page tr{break-inside:avoid;page-break-inside:avoid}' +
'</style>' +
'<script>window.onafterprint=function(){window.close();};<\\/script>' +
'</head><body>' + el.innerHTML + '</body></html>';
const blob = new Blob([html], { type: "text/html" });
const url = URL.createObjectURL(blob);
const downloadHtml = () => {
const link = document.createElement("a");
link.href = url;
link.download = "invoice.html";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
const win = window.open(url, "_blank");
if (!win) {
alert("Pop-up was blocked. Downloading invoice as HTML instead.");
downloadHtml();
} else {
setTimeout(() => {
try {
win.focus();
win.print();
} catch (err) {
console.error("Failed to open the print dialog.", err);
alert("Could not open the print dialog. Downloading invoice as HTML instead.");
downloadHtml();
}
}, 800);
}
setTimeout(() => URL.revokeObjectURL(url), 5000);
};
/* ── shared styles ─────────────────────────────────────── */
const inputStyle = { width: "100%", padding: "10px 14px", border: "1px solid " + TOKENS.borderDefault, borderRadius: 8, fontSize: 16, fontFamily: "'Inter', sans-serif", color: DARK, background: TOKENS.surface1, outline: "none", minWidth: 0 };
const labelStyle = { display: "block", fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: 1.2, color: TOKENS.textTertiary, marginBottom: 6 };
const sectionStyle = { background: TOKENS.surface1, borderRadius: 12, padding: 28, marginBottom: 20, boxShadow: "0 1px 3px rgba(0,0,0,0.06)" };
const thBase = { fontSize: 10, textTransform: "uppercase", letterSpacing: 1.5, color: TOKENS.textTertiary, fontWeight: 700, padding: "12px 16px", textAlign: "left", borderBottom: "2px solid " + TOKENS.borderDefault };
const thR = { ...thBase, textAlign: "right" };
/* ── Preview scaler hook ───────────────────────────────── */
const DESIGN_WIDTH = 820;
function usePreviewScale(wrapRef, innerRef, active) {
const [scale, setScale] = useState(1);
const [contentHeight, setContentHeight] = useState(1122);
useEffect(() => {
if (!active) return;
const compute = () => {
if (!wrapRef.current) return;
const w = wrapRef.current.offsetWidth;
const s = w < DESIGN_WIDTH ? w / DESIGN_WIDTH : 1;
setScale(s);
if (innerRef.current) {
setContentHeight(innerRef.current.offsetHeight);
}
};
const timer = setTimeout(compute, 50);
window.addEventListener("resize", compute);
return () => { clearTimeout(timer); window.removeEventListener("resize", compute); };
}, [active]);
return { scale, contentHeight };
}
/* ── Reusable page components ──────────────────────────── */
const PageFooter = ({ label, date, page, total }) => (
<div style={{ position: "absolute", bottom: 40, left: 48, right: 48, display: "flex", justifyContent: "space-between", alignItems: "flex-end", paddingTop: 20, borderTop: "1px solid " + TOKENS.borderDefault }}>
<p style={{ fontSize: 11, color: TOKENS.textTertiary }}>{label} · {date}</p>
<p style={{ fontSize: 11, color: TOKENS.textTertiary }}>Page {page} of {total}</p>
</div>
);
const ContHeader = ({ fromName, pageNum }) => (
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 32, paddingBottom: 20, borderBottom: "2px solid " + TEAL }}>
<div>
<h2 style={{ fontSize: 22, fontWeight: 700, color: DARK, margin: 0 }}>{fromName}</h2>
<p style={{ fontSize: 12, color: TOKENS.textTertiary, marginTop: 4 }}>Continued — page {pageNum}</p>
</div>
<div style={{ background: TEAL, color: TOKENS.surface1, padding: "8px 20px", fontSize: 14, fontWeight: 700, letterSpacing: 2 }}>INVOICE</div>
</div>
);
const ItemTable = ({ items, isLast }) => (
<table style={{ width: "100%", borderCollapse: "collapse", marginBottom: 32 }}>
<thead>
<tr>
<th style={thBase}>Description</th>
<th style={thR}>Qty</th>
<th style={thR}>Unit Price</th>
<th style={thR}>Amount</th>
</tr>
</thead>
<tbody>
{items.map((item, i) => {
const bb = (isLast && i === items.length - 1) ? "2px solid " + TOKENS.borderDefault : "1px solid " + TOKENS.borderDefault;
const td = { padding: "14px 16px", fontSize: 13, color: TOKENS.textSecondary, borderBottom: bb };
const tdR = { ...td, textAlign: "right", whiteSpace: "nowrap" };
return (
<tr key={item.id}>
<td style={td}>{item.description || "—"}</td>
<td style={tdR}>{item.qty}</td>
<td style={tdR}>{fmt(item.rate)}</td>
<td style={{ ...tdR, fontWeight: 500 }}>{fmt(item.qty * item.rate)}</td>
</tr>
);
})}
</tbody>
</table>
);
const InfoBlock = ({ variant, label, children, marginBottom }) => {
const isTeal = variant === "teal";
const barColor = isTeal ? TOKENS.brandTeal : TOKENS.borderDefault;
const labelColor = isTeal ? TOKENS.brandTeal : TOKENS.textTertiary;
const bodyBackground = isTeal ? TOKENS.brandTealSurface : TOKENS.surface2;
return (
<div style={{ marginBottom, borderRadius: 12, border: "1px solid " + TOKENS.borderDefault, background: TOKENS.surface1, overflow: "hidden", boxShadow: "0 1px 3px rgba(15, 23, 42, 0.06), 0 4px 12px rgba(15, 23, 42, 0.06)" }}>
<div style={{ height: 4, width: "100%", background: barColor }} />
<div style={{ padding: "14px 16px 16px", background: bodyBackground }}>
<h3 style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: 1.5, color: labelColor, marginBottom: 10, fontWeight: 700 }}>{label}</h3>
<p style={{ fontSize: 13, color: TOKENS.textSecondary, whiteSpace: "pre-line", lineHeight: 1.7 }}>{children}</p>
</div>
</div>
);
};
/* ════════════════════════════════════════════════════════ */
function InvoiceGenerator() {
const [view, setView] = useState("edit");
const sheetRef = useRef(null);
const previewWrapRef = useRef(null);
const { scale, contentHeight } = usePreviewScale(previewWrapRef, sheetRef, view === "preview");
/* ── form state ──────────────────────────────────────── */
const [invoiceNumber, setInvoiceNumber] = useState("");
const [invoiceDate, setInvoiceDate] = useState(new Date().toISOString().slice(0, 10));
const [dueDate, setDueDate] = useState("");
const [billTo, setBillTo] = useState("");
const [billFrom, setBillFrom] = useState("");
const [notes, setNotes] = useState("");
const [bankDetails, setBankDetails] = useState("");
const [paymentRef, setPaymentRef] = useState("");
const [refEdited, setRefEdited] = useState(false);
const handleBillToChange = (val) => {
setBillTo(val);
if (!refEdited) setPaymentRef(seedRef(val));
};
const handleRefChange = (val) => {
setPaymentRef(val);
setRefEdited(true);
};
/* ── line items ──────────────────────────────────────── */
const [items, setItems] = useState([
{ id: genId(), description: "", qty: 1, rate: 0 },
]);
const addItem = () => setItems([...items, { id: genId(), description: "", qty: 1, rate: 0 }]);
const removeItem = (id) => items.length > 1 && setItems(items.filter((i) => i.id !== id));
const updateItem = (id, field, value) => setItems(items.map((i) => i.id === id ? { ...i, [field]: value } : i));
const subtotal = items.reduce((s, i) => s + i.qty * i.rate, 0);
/* ── EDIT VIEW ───────────────────────────────────────── */
if (view === "edit") {
return (
<div data-page-wrap style={{ minHeight: "100vh", fontFamily: "'Inter', sans-serif", background: TOKENS.surface3, padding: "32px 24px" }}>
<div style={{ maxWidth: 640, margin: "0 auto" }}>
<div data-topbar style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 28, flexWrap: "wrap", gap: 12 }}>
<div>
<h1 style={{ fontSize: 26, fontWeight: 700, color: DARK }}>Invoice Generator</h1>
<p style={{ color: TOKENS.textSubtle, fontSize: 14, marginTop: 4 }}>{items.length} line item{items.length !== 1 ? "s" : ""} · {fmt(subtotal)}</p>
</div>
<button className="btn-ui btn-primary" onClick={() => setView("preview")} style={{ padding: "10px 24px", borderRadius: 8, fontSize: 14, fontWeight: 600, cursor: "pointer" }}>
Preview →
</button>
</div>
{/* Invoice Details */}
<div data-section style={sectionStyle}>
<h2 style={{ fontSize: 16, fontWeight: 700, color: DARK, marginBottom: 20 }}>Invoice Details</h2>
<div data-grid3 style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
<div><label style={labelStyle}>Invoice Number</label><input style={inputStyle} value={invoiceNumber} onChange={(e) => setInvoiceNumber(e.target.value)} placeholder="INV-001" /></div>
<div><label style={labelStyle}>Invoice Date</label><input type="date" style={inputStyle} value={invoiceDate} onChange={(e) => setInvoiceDate(e.target.value)} /></div>
<div><label style={labelStyle}>Due Date</label><input type="date" style={inputStyle} value={dueDate} onChange={(e) => setDueDate(e.target.value)} /></div>
</div>
</div>
{/* Billing */}
<div data-section style={sectionStyle}>
<h2 style={{ fontSize: 16, fontWeight: 700, color: DARK, marginBottom: 20 }}>Billing</h2>
<div data-grid2 style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
<div><label style={labelStyle}>Bill From</label><textarea style={{ ...inputStyle, minHeight: 88, resize: "vertical" }} value={billFrom} onChange={(e) => setBillFrom(e.target.value)} placeholder={"Your Name / Company\\n123 Street\\nCity, Code"} /></div>
<div><label style={labelStyle}>Bill To</label><textarea style={{ ...inputStyle, minHeight: 88, resize: "vertical" }} value={billTo} onChange={(e) => handleBillToChange(e.target.value)} placeholder={"Client Name / Company\\n456 Avenue\\nCity, Code"} /></div>
</div>
<div style={{ marginTop: 16 }}><label style={labelStyle}>Payment Reference</label><input style={inputStyle} value={paymentRef} onChange={(e) => handleRefChange(e.target.value)} placeholder="e.g. JOHN-CSC or SARAH-NOTES" /></div>
</div>
{/* Line Items */}
<div data-section style={sectionStyle}>
<h2 style={{ fontSize: 16, fontWeight: 700, color: DARK, marginBottom: 20 }}>Line Items</h2>
<div style={{ marginBottom: 16 }}>
<div data-li-header style={{ display: "grid", gridTemplateColumns: "1fr 80px 120px 100px 36px", gap: 10, marginBottom: 8 }}>
<span style={labelStyle}>Description</span>
<span style={labelStyle}>Qty</span>
<span style={labelStyle}>Unit Price</span>
<span style={{ ...labelStyle, textAlign: "right" }}>Amount</span>
<span />
</div>
{items.map((item) => (
<div data-li-row key={item.id} style={{ display: "grid", gridTemplateColumns: "1fr 80px 120px 100px 36px", gap: 10, marginBottom: 10, alignItems: "center" }}>
<div data-li-desc><input style={inputStyle} value={item.description} onChange={(e) => updateItem(item.id, "description", e.target.value)} placeholder="Description" /></div>
<div><input type="number" min="0" step="1" style={{ ...inputStyle, textAlign: "right" }} value={item.qty || ""} onChange={(e) => updateItem(item.id, "qty", parseFloat(e.target.value) || 0)} placeholder="Qty" /></div>
<div><input type="number" min="0" step="0.01" style={{ ...inputStyle, textAlign: "right" }} value={item.rate || ""} onChange={(e) => updateItem(item.id, "rate", parseFloat(e.target.value) || 0)} placeholder="Price" /></div>
<div data-li-amount style={{ textAlign: "right", fontSize: 14, fontWeight: 500, color: DARK, padding: "10px 0", whiteSpace: "nowrap" }}>{fmt(item.qty * item.rate)}</div>
<div data-li-remove><button onClick={() => removeItem(item.id)} style={{ background: "none", border: "none", cursor: items.length > 1 ? "pointer" : "default", opacity: items.length > 1 ? 0.4 : 0.15, fontSize: 18, color: TOKENS.textSubtle, padding: 0, lineHeight: 1, minHeight: 44, minWidth: 36 }} title="Remove">×</button></div>
</div>
))}
</div>
<button className="btn-ui btn-add" onClick={addItem} style={{ padding: "10px 20px", borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: "pointer", width: "100%" }}>
+ Add Line Item
</button>
<div style={{ display: "flex", justifyContent: "flex-end", marginTop: 16, paddingTop: 12, borderTop: "2px solid " + TEAL }}>
<span style={{ fontSize: 20, fontWeight: 700, color: DARK, whiteSpace: "nowrap" }}>{fmt(subtotal)}</span>
</div>
</div>
{/* Notes & Bank Details */}
<div data-section style={sectionStyle}>
<h2 style={{ fontSize: 16, fontWeight: 700, color: DARK, marginBottom: 20 }}>Additional Info</h2>
<div data-grid2 style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
<div><label style={labelStyle}>Notes</label><textarea style={{ ...inputStyle, minHeight: 88, resize: "vertical" }} value={notes} onChange={(e) => setNotes(e.target.value)} placeholder="Payment terms, thank you note, etc." /></div>
<div><label style={labelStyle}>Banking Details</label><textarea style={{ ...inputStyle, minHeight: 88, resize: "vertical" }} value={bankDetails} onChange={(e) => setBankDetails(e.target.value)} placeholder={"Bank: FNB\\nAccount: 12345678\\nBranch: 250655"} /></div>
</div>
</div>
</div>
</div>
);
}
/* ── PREVIEW / PRINT VIEW ────────────────────────────── */
const fromLines = billFrom.split("\\n");
const fromName = fromLines[0] || "Your Name";
const fromRest = fromLines.slice(1).join("\\n");
const pages = paginateItems(items, { notes, bankDetails });
const totalPages = pages.length;
const footerLabel = invoiceNumber || "Invoice";
const footerDate = fmtDate(invoiceDate);
const isLastPage = (idx) => idx === totalPages - 1;
return (
<div data-page-wrap style={{ minHeight: "100vh", fontFamily: "'Inter', sans-serif", background: TOKENS.surface3, padding: "32px 24px" }}>
<div style={{ maxWidth: 820, margin: "0 auto" }}>
<div className="no-print" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24 }}>
<button className="btn-ui btn-secondary" onClick={() => setView("edit")} style={{ padding: "10px 24px", borderRadius: 8, fontSize: 14, fontWeight: 500, cursor: "pointer" }}>
← Edit
</button>
<button className="btn-ui btn-primary" onClick={() => savePDF(sheetRef)} style={{ padding: "10px 28px", borderRadius: 8, fontSize: 14, fontWeight: 600, cursor: "pointer" }}>
Save as PDF ↓
</button>
</div>
<div ref={previewWrapRef} data-preview-scale style={{ overflow: "hidden", borderRadius: 4, boxShadow: "0 20px 60px rgba(0,0,0,0.15)", height: scale < 1 ? contentHeight * scale : "auto" }}>
<div style={{ transform: "scale(" + scale + ")", transformOrigin: "top left", width: DESIGN_WIDTH }}>
<div ref={sheetRef} style={{ background: TOKENS.surface1, width: DESIGN_WIDTH }}>
{/* ── PAGE 1 ─────────────────────────────────── */}
<div className="print-page" style={{ width: "100%", minHeight: 1122, padding: "40px 48px", position: "relative", fontFamily: "'Inter', sans-serif", color: DARK }}>
{/* Header */}
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 40, paddingBottom: 24, borderBottom: "3px solid " + TEAL }}>
<div>
<h1 style={{ fontSize: 30, fontWeight: 700, letterSpacing: -0.5, color: DARK, margin: 0 }}>{fromName}</h1>
{fromRest && <p style={{ fontSize: 13, color: TOKENS.textSubtle, marginTop: 4, whiteSpace: "pre-line" }}>{fromRest}</p>}
</div>
<div style={{ background: TEAL, color: TOKENS.surface1, padding: "12px 28px", fontSize: 20, fontWeight: 700, letterSpacing: 2 }}>INVOICE</div>
</div>
{/* Meta */}
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32, marginBottom: 36 }}>
<div>
<h3 style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: 1.5, color: TOKENS.textTertiary, marginBottom: 8, fontWeight: 700 }}>Bill To</h3>
<p style={{ fontSize: 13, lineHeight: 1.7, color: TOKENS.textSecondary, whiteSpace: "pre-line" }}>
{billTo || "Client Name"}
</p>
</div>
<div>
<h3 style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: 1.5, color: TOKENS.textTertiary, marginBottom: 8, fontWeight: 700 }}>Details</h3>
{[
invoiceNumber ? ["Invoice #", invoiceNumber] : null,
["Issue Date", fmtDate(invoiceDate) || "—"],
dueDate ? ["Due Date", fmtDate(dueDate)] : null,
(paymentRef || billTo) ? ["Payment Ref", paymentRef || seedRef(billTo)] : null,
].filter(Boolean).map(([k, v]) => (
<div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "2px 0", fontSize: 13, color: TOKENS.textSecondary }}>
<span>{k}</span><strong style={{ color: DARK, whiteSpace: "nowrap" }}>{v}</strong>
</div>
))}
</div>
</div>
{/* Table — page 1 items */}
<ItemTable items={pages[0]} isLast={isLastPage(0)} />
{/* Totals + notes + bank only on last page if single page */}
{totalPages === 1 && (
<React.Fragment>
<div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 48 }}>
<div style={{ width: 280 }}>
<div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", fontSize: 13, color: TOKENS.textSubtle }}>
<span>Subtotal</span><span style={{ color: TOKENS.textSecondary, whiteSpace: "nowrap" }}>{fmt(subtotal)}</span>
</div>
<div style={{ display: "flex", justifyContent: "space-between", padding: "16px 0 8px", fontSize: 20, fontWeight: 700, color: DARK, borderTop: "3px solid " + TEAL, marginTop: 8 }}>
<span>Total Due</span><span style={{ whiteSpace: "nowrap" }}>{fmt(subtotal)}</span>
</div>
</div>
</div>
{notes && (
<InfoBlock variant="slate" label="Notes" marginBottom={20}>
{notes}
</InfoBlock>
)}
{bankDetails && (
<InfoBlock variant="teal" label="Banking Details" marginBottom={32}>
{bankDetails}
</InfoBlock>
)}
</React.Fragment>
)}
<PageFooter label={footerLabel} date={footerDate} page={1} total={totalPages} />
</div>
{/* ── CONTINUATION PAGES ─────────────────────── */}
{pages.slice(1).map((pageItems, idx) => {
const pageNum = idx + 2;
const isLast = pageNum === totalPages;
return (
<div key={pageNum} className="print-page" style={{ width: "100%", minHeight: 1122, padding: "40px 48px", position: "relative", fontFamily: "'Inter', sans-serif", color: DARK, borderTop: "1px solid " + TOKENS.borderDefault }}>
<ContHeader fromName={fromName} pageNum={pageNum} />
<ItemTable items={pageItems} isLast={isLast} />
{/* Totals + notes + bank on the final page */}
{isLast && (
<React.Fragment>
<div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 48 }}>
<div style={{ width: 280 }}>
<div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", fontSize: 13, color: TOKENS.textSubtle }}>
<span>Subtotal</span><span style={{ color: TOKENS.textSecondary, whiteSpace: "nowrap" }}>{fmt(subtotal)}</span>
</div>
<div style={{ display: "flex", justifyContent: "space-between", padding: "16px 0 8px", fontSize: 20, fontWeight: 700, color: DARK, borderTop: "3px solid " + TEAL, marginTop: 8 }}>
<span>Total Due</span><span style={{ whiteSpace: "nowrap" }}>{fmt(subtotal)}</span>
</div>
</div>
</div>
{notes && (
<InfoBlock variant="slate" label="Notes" marginBottom={20}>
{notes}
</InfoBlock>
)}
{bankDetails && (
<InfoBlock variant="teal" label="Banking Details" marginBottom={32}>
{bankDetails}
</InfoBlock>
)}
</React.Fragment>
)}
<PageFooter label={footerLabel} date={footerDate} page={pageNum} total={totalPages} />
</div>
);
})}
</div>
</div>
</div>
</div>
</div>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(InvoiceGenerator));
</script>
</body>
</html>`;