-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvoice.js
More file actions
278 lines (238 loc) · 8.81 KB
/
Copy pathinvoice.js
File metadata and controls
278 lines (238 loc) · 8.81 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
const STORAGE_KEY = "invoiceData";
const THEME_KEY = "invoiceTheme";
// ── Theme ────────────────────────────────────────────────────
function applyTheme(theme) {
document.documentElement.setAttribute("data-theme", theme);
document.querySelectorAll(".theme-swatch").forEach((btn) => {
btn.classList.toggle("active", btn.dataset.theme === theme);
});
localStorage.setItem(THEME_KEY, theme);
}
// Apply saved theme immediately (before DOM fully paints)
applyTheme(localStorage.getItem(THEME_KEY) || "navy");
document.getElementById("theme-picker").addEventListener("click", (e) => {
const swatch = e.target.closest(".theme-swatch");
if (swatch) applyTheme(swatch.dataset.theme);
});
// DOM references (declared early to avoid forward-reference issues)
const datePicker = document.getElementById("datePicker");
const dateDisplay = document.querySelector('[data-field="invoiceDateDisplay"]');
const lineItemsBody = document.getElementById("lineItems");
const addRowBtn = document.getElementById("addRowBtn");
const resetBtn = document.getElementById("resetBtn");
// Default placeholder values
const defaults = {
invoiceNumber: "0000",
fromName: "Your Name",
fromAddress: "Your Address",
invoiceDate: "",
billToName: "Client Name",
billToAddress: "Client Address",
footerContact: "Your Address · Your Phone · Your Email",
lineItems: [{ description: "Description of services", amount: "$0.00" }],
};
// Header / footer editable fields (not line items)
const headerFields = [
"invoiceNumber",
"fromName",
"fromAddress",
"invoiceDate",
"billToName",
"billToAddress",
"footerContact",
];
// ── Helpers ──────────────────────────────────────────────────
function isInput(el) {
return el.tagName === "INPUT";
}
const currencyFmt = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
});
function formatCurrency(n) {
return currencyFmt.format(n);
}
function parseCurrency(str) {
return parseFloat(String(str).replace(/[^0-9.\-]/g, "")) || 0;
}
function formatDate(dateStr) {
if (!dateStr) return "Select Date";
const [y, m, d] = dateStr.split("-").map(Number);
if (!y || !m || !d) return "Select Date";
const date = new Date(y, m - 1, d);
if (isNaN(date.getTime())) return "Select Date";
return date.toLocaleDateString("en-US", {
year: "numeric",
month: "long",
day: "numeric",
});
}
// ── Debounce ─────────────────────────────────────────────────
function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
// ── Totals ───────────────────────────────────────────────────
function syncTotals() {
const rows = lineItemsBody.querySelectorAll(".line-item");
let total = 0;
rows.forEach((row) => {
const amountCell = row.querySelector('[data-field="amount"]');
if (amountCell) total += parseCurrency(amountCell.textContent);
});
const formatted = formatCurrency(total);
document.querySelector('[data-field="subtotal"]').textContent = formatted;
document.querySelector('[data-field="totalDue"]').textContent =
formatted + " USD";
}
// ── Persistence ──────────────────────────────────────────────
function gatherData() {
const data = {};
for (const key of headerFields) {
const el = document.querySelector(`[data-field="${key}"]`);
if (el) data[key] = isInput(el) ? el.value : el.textContent.trim();
}
// Gather line items
data.lineItems = [];
lineItemsBody.querySelectorAll(".line-item").forEach((row) => {
const desc = row.querySelector('[data-field="description"]');
const amt = row.querySelector('[data-field="amount"]');
if (desc && amt) {
data.lineItems.push({
description: desc.textContent.trim(),
amount: amt.textContent.trim(),
});
}
});
return data;
}
function save() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(gatherData()));
}
const debouncedSave = debounce(save, 300);
// ── Line-item row creation ───────────────────────────────────
function createRow(description, amount) {
const tr = document.createElement("tr");
tr.className = "line-item";
tr.innerHTML = `
<td contenteditable="true" data-field="description">${escapeHTML(description)}</td>
<td contenteditable="true" data-field="amount">${escapeHTML(amount)}</td>
<td class="no-print">
<button class="remove-row" title="Remove line item" aria-label="Remove line item">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</td>`;
bindRowEvents(tr);
return tr;
}
function escapeHTML(str) {
const div = document.createElement("div");
div.textContent = str;
return div.innerHTML;
}
function bindRowEvents(row) {
row.querySelectorAll("[contenteditable]").forEach((el) => {
el.addEventListener("input", () => {
if (el.dataset.field === "amount") syncTotals();
debouncedSave();
});
el.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
el.blur();
}
});
});
const removeBtn = row.querySelector(".remove-row");
if (removeBtn) {
removeBtn.addEventListener("click", () => {
// Keep at least one row
if (lineItemsBody.querySelectorAll(".line-item").length <= 1) return;
row.remove();
syncTotals();
debouncedSave();
});
}
}
// ── Load ─────────────────────────────────────────────────────
function load() {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}");
const hasData = Object.keys(saved).length > 0;
// Restore header/footer fields
for (const key of headerFields) {
const el = document.querySelector(`[data-field="${key}"]`);
if (!el) continue;
const value = hasData ? saved[key] : defaults[key];
if (value !== undefined) {
if (isInput(el)) el.value = value;
else el.textContent = value;
}
}
// Sync date display
if (datePicker.value) {
dateDisplay.textContent = formatDate(datePicker.value);
} else {
dateDisplay.textContent = formatDate(defaults.invoiceDate);
}
// Restore line items
const items =
hasData && saved.lineItems ? saved.lineItems : defaults.lineItems;
lineItemsBody.innerHTML = "";
items.forEach((item) => {
lineItemsBody.appendChild(
createRow(item.description || "", item.amount || "$0.00"),
);
});
syncTotals();
}
// ── Event listeners ──────────────────────────────────────────
// Header/footer contenteditable fields
document
.querySelectorAll("header [contenteditable], footer [contenteditable]")
.forEach((el) => {
el.addEventListener("input", () => debouncedSave());
el.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
el.blur();
}
});
});
// Invoice number (inside header <p>)
const invoiceNumberEl = document.querySelector('[data-field="invoiceNumber"]');
if (invoiceNumberEl) {
invoiceNumberEl.addEventListener("input", () => debouncedSave());
invoiceNumberEl.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
invoiceNumberEl.blur();
}
});
}
// Date picker
datePicker.addEventListener("change", () => {
dateDisplay.textContent = formatDate(datePicker.value);
debouncedSave();
});
// Add row
addRowBtn.addEventListener("click", () => {
const newRow = createRow("Description of services", "$0.00");
lineItemsBody.appendChild(newRow);
newRow.querySelector('[data-field="description"]').focus();
debouncedSave();
});
// Reset
resetBtn.addEventListener("click", () => {
if (!confirm("Reset all invoice data to defaults?")) return;
localStorage.removeItem(STORAGE_KEY);
load();
});
// Bind events on the initial HTML row (will be replaced by load, but guard)
lineItemsBody.querySelectorAll(".line-item").forEach(bindRowEvents);
// ── Init ─────────────────────────────────────────────────────
load();