Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
565 lines (504 loc) · 33 KB
/
Copy pathindex.html
File metadata and controls
565 lines (504 loc) · 33 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Dashboard - AIIT.support</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.8.2/jspdf.plugin.autotable.min.js"></script>
<style>
:root { --font-inter: 'Inter', sans-serif; }
body { font-family: var(--font-inter); }
.break-words { word-break: break-word; }
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
input[type=number] { -moz-appearance: textfield; }
.safe-bottom { padding-bottom: max(0.5rem, env(safe-area-inset-bottom)); }
.safe-top { padding-top: max(0.5rem, env(safe-area-inset-top)); }
textarea { resize: vertical; }
input[type="date"]::-webkit-calendar-picker-indicator {
display: none;
-webkit-appearance: none;
}
.invisible-input, .invisible-input:focus {
border: none !important;
outline: none !important;
box-shadow: none !important;
-webkit-appearance: none !important;
-moz-appearance: none !important;
appearance: none !important;
background-color: transparent !important;
resize: none !important;
padding-left: 0 !important;
padding-right: 0 !important;
}
#invoiceNumber.invisible-input { padding-left: 1.25rem !important; }
#dateIssued.invisible-input { padding-left: 2.5rem !important; padding-right: 0.75rem !important; }
.preview-active .main-container { max-width: 98% !important; }
.preview-active .editor-column { width: 55%; }
.preview-active .preview-column { display: flex !important; width: 45%; }
@media (max-width: 768px) {
.invoice-table-container { display: none; }
.invoice-cards-container { display: block; }
.preview-active .editor-column { width: 100%; }
.preview-active .preview-column { display: none !important; }
}
@media (min-width: 769px) {
.invoice-table-container { display: block; }
.invoice-cards-container { display: none; }
}
</style>
</head>
<body class="bg-stone-100 p-2 sm:p-6 safe-top safe-bottom">
<div class="main-container max-w-5xl mx-auto flex flex-row gap-4 transition-all duration-300 h-[calc(100vh-3rem)]">
<div class="editor-column w-full bg-white rounded-xl shadow-2xl overflow-hidden flex flex-col h-full">
<div class="border-b border-stone-200 shrink-0">
<div class="flex justify-end p-4 gap-2 items-center">
<div id="saveStatus" class="text-[10px] text-teal-600 font-bold mr-auto ml-2">✓ Saved</div>
<button id="aiSmartFillBtn" class="bg-gradient-to-r from-teal-600 to-indigo-600 hover:from-teal-700 hover:to-indigo-700 text-white px-3 py-1 text-xs font-bold rounded-full transition-all shadow flex items-center gap-1" title="Smart Fill with AI & PII Filter">
⚡ AI Smart Fill
</button>
<select id="currencySelect" class="bg-white border border-stone-200 rounded-full px-3 py-1 text-sm font-bold text-stone-700 shadow-sm focus:ring-teal-500 focus:border-teal-500">
<option value="USD">$ USD</option>
<option value="EUR">€ EUR</option>
<option value="GBP">£ GBP</option>
<option value="JPY">¥ JPY</option>
</select>
<button id="newInvoiceBtn" class="bg-white hover:bg-stone-100 text-stone-700 w-9 h-9 rounded-full transition-colors flex items-center justify-center shadow-lg border border-stone-200" title="New Invoice">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-5 h-5"><path fill-rule="evenodd" d="M10 3a1 1 0 011 1v4h4a1 1 0 110 2h-4v4a1 1 0 11-2 0v-4H5a1 1 0 110-2h4V4a1 1 0 011-1z" clip-rule="evenodd"/></svg>
</button>
<button id="livePreviewToggleBtn" class="bg-white hover:bg-stone-100 text-stone-700 w-9 h-9 rounded-full transition-colors flex items-center justify-center shadow-lg border border-stone-200" title="Toggle Live PDF Preview">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6">
<path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8l-6-6zM13 9V3.5L18.5 9H13z" />
<circle cx="12" cy="15" r="3" fill="white" />
<circle cx="12" cy="15" r="1.5" fill="currentColor" />
</svg>
</button>
<button id="exportPdfBtn" class="bg-teal-600 hover:bg-teal-700 text-white w-9 h-9 rounded-full transition-colors flex items-center justify-center shadow-lg border border-stone-200" title="Export as PDF">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-5 h-5"><path fill-rule="evenodd" d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z" clip-rule="evenodd"/></svg>
</button>
</div>
<div class="flex items-start justify-between px-6 pb-4">
<div class="pt-2">
<a href="https://www.aiit.support" target="_blank">
<span class="text-xl font-bold text-stone-800"><span class="text-teal-600">AI</span>IT.</span>
</a>
</div>
<div class="flex flex-col items-end gap-y-1">
<div class="flex items-center gap-x-2">
<label class="text-[10px] font-bold uppercase text-stone-500">INVOICE:</label>
<div class="relative">
<span class="absolute inset-y-0 left-0 flex items-center pl-3 text-stone-400">#</span>
<input id="invoiceNumber" type="text" maxlength="8" class="invisible-input font-bold w-24 text-right py-1 px-3 border-stone-200 border rounded" />
</div>
</div>
<div class="flex items-center gap-x-2">
<label class="text-[10px] font-bold uppercase text-stone-500">DATE:</label>
<div class="relative">
<button class="absolute inset-y-0 left-0 flex items-center pl-3 text-stone-400" onclick="document.getElementById('dateIssued').showPicker()">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4"><path fill-rule="evenodd" d="M5.75 3a.75.75 0 01.75.75v.25h7V3.75a.75.75 0 011.5 0V4h.25A2.75 2.75 0 0118 6.75v8.5A2.75 2.75 0 0115.25 18H4.75A2.75 2.75 0 012 15.25v-8.5A2.75 2.75 0 014.75 4H5v-.25A.75.75 0 015.75 3zM4.5 6.75A1.25 1.25 0 003.25 8v7.25c0 .69.56 1.25 1.25 1.25h10.5c.69 0 1.25-.56 1.25-1.25V8c0-.69-.56-1.25-1.25-1.25H4.5z" clip-rule="evenodd"/></svg>
</button>
<input id="dateIssued" type="date" class="invisible-input font-bold uppercase w-full text-right py-1 px-3 border-stone-200 border rounded" />
</div>
</div>
</div>
</div>
<div class="px-6 py-4 border-t border-stone-100 bg-stone-50/50">
<div class="grid grid-cols-2 gap-4">
<div class="grid grid-cols-[auto,1fr] gap-x-2">
<label class="text-[10px] font-bold text-teal-600 uppercase pt-1 text-right">FROM:</label>
<input id="from-line1" type="text" class="invisible-input font-bold block w-full rounded py-0.5 px-2" />
<label> </label>
<textarea id="from-rest" rows="2" class="invisible-input text-xs block w-full rounded py-0.5 px-2"></textarea>
</div>
<div class="grid grid-cols-[auto,1fr] gap-x-2">
<label class="text-[10px] font-bold text-teal-600 uppercase pt-1 text-right">BILL TO:</label>
<input id="client-line1" type="text" list="clientSuggestions" class="invisible-input font-bold block w-full rounded py-0.5 px-2" />
<datalist id="clientSuggestions"></datalist>
<label> </label>
<textarea id="client-rest" rows="2" class="invisible-input text-xs block w-full rounded py-0.5 px-2"></textarea>
</div>
</div>
</div>
</div>
<main class="p-4 flex-grow overflow-y-auto">
<div class="invoice-table-container">
<table id="invoiceTable" class="min-w-full table-fixed divide-y divide-stone-200 border border-stone-200 rounded-lg overflow-hidden">
<colgroup><col><col class="w-[10ch]"><col class="w-[12ch]"><col class="w-[14ch]"><col class="w-[100px]"></colgroup>
<thead class="bg-teal-600">
<tr>
<th class="px-4 py-2 text-left text-[10px] font-bold text-white uppercase tracking-wider">Description</th>
<th class="px-4 py-2 text-right text-[10px] font-bold text-white uppercase tracking-wider">Qty/Hrs</th>
<th class="px-4 py-2 text-right text-[10px] font-bold text-white uppercase tracking-wider">Rate</th>
<th class="px-4 py-2 text-right text-[10px] font-bold text-white uppercase tracking-wider">Total</th>
<th class="px-4 py-2 text-center text-[10px] font-bold text-white uppercase tracking-wider">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-stone-200"></tbody>
</table>
</div>
<div id="invoiceCards" class="invoice-cards-container space-y-3"></div>
</main>
<footer class="bg-stone-50 p-4 border-t border-stone-200 shrink-0">
<div class="flex justify-between items-center mb-4">
<span class="text-sm font-bold text-stone-600 uppercase tracking-wider">Total Amount Due:</span>
<span id="grandTotalCell" class="text-xl font-black text-stone-900"></span>
</div>
<div class="grid grid-cols-[auto,1fr] gap-x-2">
<label class="text-[10px] font-bold text-stone-500 uppercase pt-2 text-right">Notes:</label>
<textarea id="notes" rows="1" class="invisible-input block w-full text-xs rounded border-stone-200 border py-1 px-2"></textarea>
</div>
</footer>
</div>
<div class="preview-column hidden bg-stone-800 rounded-xl shadow-2xl overflow-hidden flex-col h-full">
<div class="bg-stone-900 text-white p-2 px-4 flex justify-between items-center shrink-0">
<span class="text-[10px] font-bold uppercase tracking-widest text-stone-400">Live PDF Preview</span>
<button onclick="document.body.classList.toggle('preview-active')" class="text-stone-500 hover:text-white transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-4 h-4"><path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"/></svg>
</button>
</div>
<iframe id="pdfPreviewIframe" class="w-full h-full bg-stone-700 border-none"></iframe>
</div>
</div>
<datalist id="descriptionSuggestions"></datalist>
<script>
document.addEventListener('DOMContentLoaded', () => {
const clientLine1 = document.getElementById('client-line1');
const clientRest = document.getElementById('client-rest');
const fromLine1 = document.getElementById('from-line1');
const fromRest = document.getElementById('from-rest');
const invoiceTableBody = document.querySelector('#invoiceTable tbody');
const invoiceCards = document.getElementById('invoiceCards');
const grandTotalCell = document.getElementById('grandTotalCell');
const invoiceNumberInput = document.getElementById('invoiceNumber');
const dateIssuedInput = document.getElementById('dateIssued');
const notesInput = document.getElementById('notes');
const exportPdfBtn = document.getElementById('exportPdfBtn');
const newInvoiceBtn = document.getElementById('newInvoiceBtn');
const livePreviewToggleBtn = document.getElementById('livePreviewToggleBtn');
const currencySelect = document.getElementById('currencySelect');
const pdfPreviewIframe = document.getElementById('pdfPreviewIframe');
const saveStatus = document.getElementById('saveStatus');
let invoiceData = [];
let activeEditIndex = 0;
let selectedCurrency = localStorage.getItem('selectedCurrency') || 'USD';
let clientAddressMap = {};
const currencyMap = {
'USD': { symbol: '$', code: 'USD' }, 'EUR': { symbol: '€', code: 'EUR' },
'GBP': { symbol: '£', code: 'GBP' }, 'JPY': { symbol: '¥', code: 'JPY' }
};
currencySelect.value = selectedCurrency;
currencySelect.addEventListener('change', (e) => {
selectedCurrency = e.target.value;
localStorage.setItem('selectedCurrency', selectedCurrency);
renderInvoice();
updatePreview();
});
livePreviewToggleBtn.addEventListener('click', () => {
document.body.classList.toggle('preview-active');
updatePreview();
});
function formatCurrency(amount) {
const num = Number.isFinite(Number(amount)) ? Number(amount) : 0;
const cur = currencyMap[selectedCurrency];
return num.toLocaleString('en-US', { style: 'currency', currency: cur.code, minimumFractionDigits: 2 });
}
function getTodayDateString() {
const today = new Date();
return `${today.getFullYear()}-${String(today.getMonth()+1).padStart(2,'0')}-${String(today.getDate()).padStart(2,'0')}`;
}
function autoResizeTextarea(el) {
if (!el) return; el.style.height = 'auto'; el.style.height = el.scrollHeight + 'px';
}
function splitAddress(fullAddress) {
const lines = (fullAddress || '').split('\n');
return [lines.shift() || '', lines.join('\n')];
}
function syncTextareaHeights() {
if (!fromRest || !clientRest) return;
fromRest.style.height = clientRest.style.height = 'auto';
const h = Math.max(fromRest.scrollHeight, clientRest.scrollHeight, 28);
fromRest.style.height = clientRest.style.height = h + 'px';
}
function defaultFirstRow() { return { description: 'Products & Services', quantity: 6.0, unit: 'Hrs', rate: 75.00, total: 450.00, isPayment: false }; }
function showSaveStatus(status) {
if (!saveStatus) return;
saveStatus.textContent = status === 'saving' ? '● Saving...' : '✓ Saved';
saveStatus.className = status === 'saving' ? 'text-[10px] text-amber-500 font-bold mr-auto ml-2' : 'text-[10px] text-teal-600 font-bold mr-auto ml-2';
}
async function initializeDashboard() {
try {
const saved = await fetchJson('/api/invoices');
if (saved && saved.length > 0) {
invoiceNumberInput.value = saved[0].invoice_number || '001';
const [f1, fR] = splitAddress(saved[0].contractor_name);
fromLine1.value = f1; fromRest.value = fR;
const [c1, cR] = splitAddress(saved[0].client);
clientLine1.value = c1; clientRest.value = cR;
notesInput.value = saved[0].notes || '';
invoiceData = saved.map(r => ({ description: r.description, quantity: r.hours, unit: 'Hrs', rate: r.hourly_rate, total: r.total, isPayment: r.total < 0 }));
} else {
setGlobalDefaults();
invoiceData = [defaultFirstRow()];
}
} catch (e) { setGlobalDefaults(); invoiceData = [defaultFirstRow()]; }
finally { renderInvoice(); fetchSuggestions(); syncTextareaHeights(); }
}
function setGlobalDefaults() {
invoiceNumberInput.value = localStorage.getItem('lastInvoiceNumber') || '001';
dateIssuedInput.value = getTodayDateString();
const [f1, fR] = splitAddress(localStorage.getItem('lastFrom') || 'Your Company, Inc.');
fromLine1.value = f1; fromRest.value = fR;
const [c1, cR] = splitAddress(localStorage.getItem('lastClient') || 'Client Name');
clientLine1.value = c1; clientRest.value = cR;
}
async function saveInvoiceData() {
showSaveStatus('saving');
const payload = {
invoiceNumber: invoiceNumberInput.value,
contractorName: `${fromLine1.value}\n${fromRest.value}`,
client: `${clientLine1.value}\n${clientRest.value}`,
notes: notesInput.value,
items: invoiceData.map(it => ({ client: clientLine1.value, date: dateIssuedInput.value, description: it.description, hours: it.quantity, hourlyRate: it.rate, total: it.total }))
};
await postJson('/api/invoices', payload);
showSaveStatus('saved');
updatePreview();
}
function renderInvoice() {
invoiceTableBody.innerHTML = ''; invoiceCards.innerHTML = '';
invoiceData.forEach((entry, index) => {
const isEditing = (index === activeEditIndex);
invoiceTableBody.appendChild(isEditing ? renderEditableRow(entry, index) : renderStaticRow(entry, index));
invoiceCards.appendChild(isEditing ? renderEditableCard(entry, index) : renderStaticCard(entry, index));
});
const grandTotal = invoiceData.reduce((s, it) => s + (it.total || 0), 0);
grandTotalCell.textContent = formatCurrency(grandTotal);
}
function renderStaticRow(entry, index) {
const tr = document.createElement('tr'); tr.className = index % 2 ? 'bg-stone-50' : 'bg-white'; tr.onclick = () => { activeEditIndex = index; renderInvoice(); };
tr.innerHTML = `
<td class="px-4 py-2 text-xs text-stone-900">${entry.description}</td>
<td class="px-4 py-2 text-xs text-right text-stone-500">${entry.isPayment ? '—' : entry.quantity.toFixed(2)}</td>
<td class="px-4 py-2 text-xs text-right text-stone-500">${entry.isPayment ? '—' : formatCurrency(entry.rate)}</td>
<td class="px-4 py-2 text-xs text-right font-bold text-stone-700">${formatCurrency(entry.total)}</td>
<td class="px-4 py-2 text-center">${index > 0 ? `<button onclick="event.stopPropagation(); moveRow(${index}, -1)" class="p-1">↑</button><button onclick="event.stopPropagation(); moveRow(${index}, 1)" class="p-1">↓</button>` : ''}</td>
`;
return tr;
}
function renderEditableRow(entry, index) {
const tr = document.createElement('tr'); tr.className = 'bg-teal-50 shadow-inner';
const tdDesc = document.createElement('td'); tdDesc.className = 'p-2';
const desc = document.createElement('textarea'); desc.className = 'w-full text-xs p-1 border rounded'; desc.value = entry.description;
const applyShortcuts = (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); activeEditIndex = (index + 1 < invoiceData.length) ? index + 1 : null; renderInvoice(); }
else if (e.key === 'Enter' && e.shiftKey) { e.preventDefault(); invoiceData.splice(index + 1, 0, defaultFirstRow()); activeEditIndex = index + 1; renderInvoice(); saveInvoiceData(); }
else if (e.key === 'Escape') { e.preventDefault(); activeEditIndex = null; renderInvoice(); }
};
desc.onkeydown = applyShortcuts;
desc.oninput = (e) => { entry.description = e.target.value; saveInvoiceData(); };
tdDesc.appendChild(desc);
const tdQty = document.createElement('td'); tdQty.className = 'p-2';
if (!entry.isPayment) {
const qty = document.createElement('input'); qty.type = 'number'; qty.className = 'w-full text-right text-xs p-1 border rounded'; qty.value = entry.quantity;
qty.onkeydown = applyShortcuts;
qty.oninput = (e) => { entry.quantity = parseFloat(e.target.value) || 0; entry.total = entry.quantity * entry.rate; renderInvoice(); saveInvoiceData(); };
tdQty.appendChild(qty);
} else { tdQty.innerHTML = '<span class="text-stone-400 block text-center">—</span>'; }
const tdRate = document.createElement('td'); tdRate.className = 'p-2';
if (!entry.isPayment) {
const rate = document.createElement('input'); rate.type = 'number'; rate.className = 'w-full text-right text-xs p-1 border rounded'; rate.value = entry.rate;
rate.onkeydown = applyShortcuts;
rate.oninput = (e) => { entry.rate = parseFloat(e.target.value) || 0; entry.total = entry.quantity * entry.rate; renderInvoice(); saveInvoiceData(); };
tdRate.appendChild(rate);
} else { tdRate.innerHTML = '<span class="text-stone-400 block text-center">—</span>'; }
const tdTotal = document.createElement('td'); tdTotal.className = 'p-2 text-right font-bold text-xs';
if (entry.isPayment) {
const tot = document.createElement('input'); tot.type = 'number'; tot.className = 'w-full text-right text-xs p-1 border rounded'; tot.value = Math.abs(entry.total);
tot.onkeydown = applyShortcuts;
tot.oninput = (e) => { entry.total = -Math.abs(parseFloat(e.target.value) || 0); renderInvoice(); saveInvoiceData(); };
tdTotal.appendChild(tot);
} else { tdTotal.textContent = formatCurrency(entry.total); }
const tdActions = document.createElement('td'); tdActions.className = 'p-2 text-center flex gap-1 justify-center';
const save = document.createElement('button'); save.innerHTML = '✓'; save.onclick = () => { activeEditIndex = null; renderInvoice(); };
const del = document.createElement('button'); del.innerHTML = '×'; del.onclick = () => { invoiceData.splice(index, 1); activeEditIndex = 0; renderInvoice(); saveInvoiceData(); };
const pay = document.createElement('button'); pay.innerHTML = '$'; pay.onclick = () => { entry.isPayment = !entry.isPayment; entry.quantity = 0; entry.rate = 0; renderInvoice(); };
tdActions.append(pay, save, del);
tr.append(tdDesc, tdQty, tdRate, tdTotal, tdActions);
if (index === 0) { const add = document.createElement('button'); add.innerHTML = '+'; add.onclick = () => { invoiceData.splice(1, 0, {...entry}); activeEditIndex = 0; renderInvoice(); saveInvoiceData(); }; tdActions.prepend(add); }
return tr;
}
function renderStaticCard(entry, index) {
const div = document.createElement('div'); div.className = 'bg-white p-3 rounded-lg shadow-sm border border-stone-200';
div.onclick = () => { activeEditIndex = index; renderInvoice(); };
div.innerHTML = `
<div class="font-bold text-stone-800 text-sm">${entry.description}</div>
<div class="flex justify-between items-end mt-2">
<div class="text-[10px] text-stone-500">${entry.isPayment ? 'Payment' : `${entry.quantity} @ ${formatCurrency(entry.rate)}`}</div>
<div class="font-bold text-teal-700 text-xs">${formatCurrency(entry.total)}</div>
</div>
`;
return div;
}
function renderEditableCard(entry, index) {
const div = document.createElement('div'); div.className = 'bg-teal-50 p-3 rounded-lg shadow-md border-2 border-teal-500 space-y-2';
const d = document.createElement('textarea'); d.className = 'w-full text-sm p-2 rounded border'; d.value = entry.description;
d.oninput = (e) => { entry.description = e.target.value; saveInvoiceData(); };
div.appendChild(d);
const grid = document.createElement('div'); grid.className = 'grid grid-cols-2 gap-2';
if (!entry.isPayment) {
const q = document.createElement('input'); q.type = 'number'; q.className = 'p-2 rounded border text-sm'; q.value = entry.quantity;
q.oninput = (e) => { entry.quantity = parseFloat(e.target.value) || 0; entry.total = entry.quantity * entry.rate; saveInvoiceData(); };
const r = document.createElement('input'); r.type = 'number'; r.className = 'p-2 rounded border text-sm'; r.value = entry.rate;
r.oninput = (e) => { entry.rate = parseFloat(e.target.value) || 0; entry.total = entry.quantity * entry.rate; saveInvoiceData(); };
grid.append(q, r);
} else {
const t = document.createElement('input'); t.type = 'number'; t.className = 'col-span-2 p-2 rounded border text-sm'; t.value = Math.abs(entry.total);
t.oninput = (e) => { entry.total = -Math.abs(parseFloat(e.target.value) || 0); saveInvoiceData(); };
grid.append(t);
}
div.append(grid);
const acts = document.createElement('div'); acts.className = 'flex justify-end gap-2 pt-2';
const s = document.createElement('button'); s.className = 'bg-teal-600 text-white px-4 py-1 rounded text-xs'; s.textContent = 'Save'; s.onclick = () => { activeEditIndex = null; renderInvoice(); };
acts.append(s); div.appendChild(acts);
return div;
}
function moveRow(i, d) {
const ni = i + d; if (ni < 1 || ni >= invoiceData.length) return;
const t = invoiceData[i]; invoiceData[i] = invoiceData[ni]; invoiceData[ni] = t;
renderInvoice(); saveInvoiceData();
}
async function fetchSuggestions() {
const clients = await fetchJson('/api/suggestions/clients');
if (clients) {
clientAddressMap = {};
const list = document.getElementById('clientSuggestions');
list.innerHTML = '';
clients.forEach(fullStr => {
const [name, rest] = splitAddress(fullStr);
clientAddressMap[name] = rest;
const opt = document.createElement('option');
opt.value = name;
list.appendChild(opt);
});
}
const descs = await fetchJson('/api/suggestions/descriptions');
if (descs) descriptionSuggestions.innerHTML = descs.map(d => `<option value="${d}">`).join('');
}
clientLine1.addEventListener('input', (e) => {
const name = e.target.value;
if (clientAddressMap[name]) {
clientRest.value = clientAddressMap[name];
saveInvoiceData();
}
});
function updatePreview() {
if (!document.body.classList.contains('preview-active')) return;
const { jsPDF } = window.jspdf; const doc = new jsPDF();
const teal = [13, 148, 136]; const stone = [68, 64, 60];
doc.setFont('helvetica','bold'); doc.setFontSize(20); doc.setTextColor(...teal); doc.text('AI', 14, 20);
doc.setTextColor(...stone); doc.text('IT.', 14 + doc.getTextWidth('AI'), 20);
doc.setFontSize(10); doc.text(`INVOICE: #${invoiceNumberInput.value}`, 196, 15, {align:'right'});
doc.text(`DATE: ${dateIssuedInput.value}`, 196, 22, {align:'right'});
doc.autoTable({
startY: 40, head: [['Description','Qty','Rate','Total']],
body: invoiceData.slice(1).map(it => [it.description, it.quantity.toFixed(2), formatCurrency(it.rate), formatCurrency(it.total)]),
headStyles: { fillColor: teal },
foot: [[{content:'Total Amount Due:', colSpan:3, styles:{halign:'right'}}, formatCurrency(invoiceData.reduce((s,it)=>s+it.total,0))]]
});
pdfPreviewIframe.src = doc.output('bloburl');
}
async function fetchJson(u) { try { const r = await fetch(u); return r.json(); } catch(e) { return null; } }
async function postJson(u, b) { try { await fetch(u, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(b) }); } catch(e) {} }
newInvoiceBtn.onclick = () => { if(confirm('Clear invoice?')) { setGlobalDefaults(); invoiceData = [defaultFirstRow()]; renderInvoice(); saveInvoiceData(); } };
exportPdfBtn.onclick = () => { updatePreview(); renderInvoice(); };
initializeDashboard();
});
</script>
<!-- AI Smart Fill Modal -->
<div id="aiModal" class="fixed inset-0 bg-stone-900/60 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4">
<div class="bg-white rounded-2xl shadow-2xl max-w-lg w-full p-6 space-y-4 border border-stone-200">
<div class="flex items-center justify-between border-b border-stone-100 pb-3">
<h3 class="text-lg font-bold text-stone-800 flex items-center gap-2">
<span class="text-teal-600">⚡</span> AI Invoice Smart Fill
</h3>
<button id="closeAiModalBtn" class="text-stone-400 hover:text-stone-600 font-bold text-xl">×</button>
</div>
<p class="text-xs text-stone-500">
Enter work notes or natural language prompt (e.g. <em>"Worked 4.5 hrs for Acme Corp at $120/hr on server configuration"</em>). All PII (SSNs, phone numbers, emails, cards) is automatically redacted locally.
</p>
<textarea id="aiPromptInput" rows="4" class="w-full text-xs p-3 border border-stone-200 rounded-lg focus:ring-2 focus:ring-teal-500 focus:outline-none" placeholder="Paste work notes or prompt here..."></textarea>
<div id="piiBadges" class="hidden text-xs bg-amber-50 border border-amber-200 text-amber-800 p-2.5 rounded-lg font-mono text-[11px]">
<!-- PII Redaction Badges injected here -->
</div>
<div class="flex justify-end gap-2 pt-2">
<button id="cancelAiModalBtn" class="px-4 py-2 text-xs font-bold text-stone-600 bg-stone-100 hover:bg-stone-200 rounded-lg">Cancel</button>
<button id="processAiPromptBtn" class="px-4 py-2 text-xs font-bold text-white bg-teal-600 hover:bg-teal-700 rounded-lg shadow">Generate Invoice Line Item</button>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const aiSmartFillBtn = document.getElementById('aiSmartFillBtn');
const aiModal = document.getElementById('aiModal');
const closeAiModalBtn = document.getElementById('closeAiModalBtn');
const cancelAiModalBtn = document.getElementById('cancelAiModalBtn');
const processAiPromptBtn = document.getElementById('processAiPromptBtn');
const aiPromptInput = document.getElementById('aiPromptInput');
const piiBadges = document.getElementById('piiBadges');
if (aiSmartFillBtn) {
aiSmartFillBtn.onclick = () => {
aiPromptInput.value = '';
piiBadges.classList.add('hidden');
aiModal.classList.remove('hidden');
};
}
const closeModal = () => aiModal.classList.add('hidden');
if (closeAiModalBtn) closeAiModalBtn.onclick = closeModal;
if (cancelAiModalBtn) cancelAiModalBtn.onclick = closeModal;
if (processAiPromptBtn) {
processAiPromptBtn.onclick = async () => {
const prompt = aiPromptInput.value.trim();
if (!prompt) return alert('Please enter a work note or prompt.');
try {
const res = await fetch('/api/ai/parse-prompt', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt })
});
if (!res.ok) throw new Error('Failed to parse prompt.');
const data = await res.json();
if (data.piiSummary && data.piiSummary.redactedCount > 0) {
piiBadges.innerHTML = `🛡️ <strong>PII Sanitized:</strong> Redacted ${data.piiSummary.redactedCount} item(s) [${data.piiSummary.detectedTypes.join(', ')}]`;
piiBadges.classList.remove('hidden');
}
// Populate invoice line item
const today = new Date().toISOString().split('T')[0];
const newItem = {
client: data.client || 'Client Name',
date: today,
description: data.description || prompt,
quantity: data.hours || 1,
rate: data.hourlyRate || 100,
total: data.total || 100
};
// Set client if field exists
const clientInput = document.getElementById('clientLine1');
if (clientInput && data.client) clientInput.value = data.client;
// Append item to invoiceData
if (typeof invoiceData !== 'undefined') {
invoiceData.push(newItem);
if (typeof renderInvoice === 'function') renderInvoice();
if (typeof saveInvoiceData === 'function') saveInvoiceData();
}
setTimeout(closeModal, 1200);
} catch (err) {
alert('Error parsing AI prompt: ' + err.message);
}
};
}
});
</script>
</body>
</html>