-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
547 lines (461 loc) · 16.3 KB
/
Copy pathapp.js
File metadata and controls
547 lines (461 loc) · 16.3 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
import hdfcCreditCard from "./parsers/hdfc-credit-card.js";
import hdfcBank from "./parsers/hdfc-bank.js";
import rblBank from "./parsers/rbl-bank.js";
/* ── Tool registry ── */
const tools = [hdfcCreditCard, hdfcBank, rblBank];
let activeTool = null;
/* ── DOM refs ── */
const homeView = document.getElementById("home-view");
const toolView = document.getElementById("tool-view");
const toolGrid = document.getElementById("tool-grid");
const toolCardTemplate = document.getElementById("tool-card-template");
const backBtn = document.getElementById("back-btn");
const toolTitle = document.getElementById("tool-title");
const toolDescription = document.getElementById("tool-description");
const dropzone = document.getElementById("dropzone");
const dropzoneIcon = dropzone.querySelector(".dropzone-icon");
const dropzoneTitle = dropzone.querySelector(".dropzone-title");
const dropzoneSubtitle = dropzone.querySelector(".dropzone-subtitle");
const fileInput = document.getElementById("file-input");
const fileList = document.getElementById("file-list");
const tileTemplate = document.getElementById("file-tile-template");
const sharedStatus = document.getElementById("shared-status");
const PAGE_SIZE = 20;
/* ── Navigation ── */
function showHome() {
activeTool = null;
toolView.hidden = true;
homeView.hidden = false;
fileList.innerHTML = "";
document.title = "Statement Tools";
const base = window.location.pathname + window.location.search;
window.history.pushState(null, "", base);
}
function showTool(tool) {
activeTool = tool;
homeView.hidden = true;
toolView.hidden = false;
fileList.innerHTML = "";
toolTitle.textContent = tool.name;
toolDescription.textContent = tool.description;
fileInput.setAttribute("accept", tool.accept);
// Update dropzone text based on tool
const isExcel = tool.accept.includes(".xls");
dropzoneIcon.textContent = isExcel ? "XLS" : "PDF";
dropzoneTitle.textContent = `Drop your ${tool.fileLabel} here`;
dropzoneSubtitle.textContent = "or click to choose files";
document.title = `${tool.name} — Statement Tools`;
const base = window.location.pathname + window.location.search;
window.history.pushState(null, "", `${base}#${tool.id}`);
}
backBtn.addEventListener("click", showHome);
window.addEventListener("popstate", () => {
const hash = window.location.hash.slice(1);
if (hash) {
const tool = tools.find((t) => t.id === hash);
if (tool) {
showTool(tool);
return;
}
}
showHome();
});
/* ── Build tool cards ── */
function renderToolGrid() {
toolGrid.innerHTML = "";
for (const tool of tools) {
const node = toolCardTemplate.content.firstElementChild.cloneNode(true);
node.querySelector(".tool-card-icon").textContent = tool.icon;
node.querySelector(".tool-card-name").textContent = tool.name;
node.querySelector(".tool-card-description").textContent = tool.description;
node.addEventListener("click", () => showTool(tool));
toolGrid.appendChild(node);
}
}
renderToolGrid();
/* ── Shared helpers ── */
function rowsToCsv(rows, columns) {
const escapeCell = (value) => {
const cell = value === null || value === undefined ? "" : String(value);
return `"${cell.replace(/"/g, '""')}"`;
};
const lines = [columns.map(escapeCell).join(",")];
for (const row of rows) {
lines.push(columns.map((col) => escapeCell(row[col] ?? "")).join(","));
}
return lines.join("\n");
}
function renderCsvTable(container, rows, columns) {
container.innerHTML = "";
const tableScroll = document.createElement("div");
tableScroll.className = "csv-table-scroll";
const table = document.createElement("table");
table.className = "csv-table";
const thead = document.createElement("thead");
const headRow = document.createElement("tr");
columns.forEach((col) => {
const th = document.createElement("th");
th.textContent = col;
headRow.appendChild(th);
});
thead.appendChild(headRow);
table.appendChild(thead);
const tbody = document.createElement("tbody");
rows.forEach((row) => {
const tr = document.createElement("tr");
columns.forEach((col) => {
const td = document.createElement("td");
td.textContent = row[col] ?? "";
tr.appendChild(td);
});
tbody.appendChild(tr);
});
table.appendChild(tbody);
tableScroll.appendChild(table);
container.appendChild(tableScroll);
}
/* ── File tile ── */
function createTile(file) {
const tool = activeTool;
if (!tool) return;
const node = tileTemplate.content.firstElementChild.cloneNode(true);
const nameEl = node.querySelector(".file-name");
const statusEl = node.querySelector(".file-status");
const removeBtn = node.querySelector(".file-remove");
const downloadLink = node.querySelector(".download-link");
const passwordBox = node.querySelector(".password-inline");
const passwordInput = passwordBox.querySelector("input");
const passwordSubmit = node.querySelector(".password-submit");
const previewPanel = node.querySelector(".preview-panel");
const previewClose = node.querySelector(".preview-close");
const previewPdfBtn = node.querySelector(".preview-pdf-btn");
const previewCsvBtn = node.querySelector(".preview-csv-btn");
const previewPdf = node.querySelector(".preview-pdf-view");
const previewCsv = node.querySelector(".preview-csv-view");
// Rename preview button for non-PDF tools
const isPdf = tool.accept.includes("pdf");
previewPdfBtn.textContent = isPdf ? "Preview PDF" : "Preview File";
let csvUrl = null;
let fileUrl = null;
let parsedRows = null;
let parsedColumns = null;
let currentPage = 1;
const setStatus = (message) => {
statusEl.textContent = message;
};
const cleanup = () => {
if (csvUrl) {
URL.revokeObjectURL(csvUrl);
csvUrl = null;
}
if (fileUrl) {
URL.revokeObjectURL(fileUrl);
fileUrl = null;
}
node.remove();
};
const showPreviewPanel = () => {
previewPanel.hidden = false;
};
const hidePreviewPanel = () => {
previewPanel.hidden = true;
previewPdf.hidden = true;
previewCsv.hidden = true;
};
const renderFilePreview = () => {
previewPdf.innerHTML = "";
if (isPdf) {
const iframe = document.createElement("iframe");
iframe.src = fileUrl;
previewPdf.appendChild(iframe);
} else {
const msg = document.createElement("p");
msg.className = "csv-note";
msg.textContent = "File preview is not available for this format. Use CSV preview instead.";
previewPdf.appendChild(msg);
}
};
const renderCsvPreviewIfReady = () => {
previewCsv.innerHTML = "";
if (!parsedRows || !parsedColumns) {
const msg = document.createElement("p");
msg.className = "csv-note";
msg.textContent = "Parse the statement to preview CSV.";
previewCsv.appendChild(msg);
return;
}
const totalPages = Math.max(1, Math.ceil(parsedRows.length / PAGE_SIZE));
currentPage = Math.min(Math.max(1, currentPage), totalPages);
const start = (currentPage - 1) * PAGE_SIZE;
const end = Math.min(start + PAGE_SIZE, parsedRows.length);
const previewRows = parsedRows.slice(start, end);
renderCsvTable(previewCsv, previewRows, parsedColumns);
const pagination = document.createElement("div");
pagination.className = "csv-pagination";
const info = document.createElement("span");
info.className = "page-info";
info.textContent = `Page ${currentPage} of ${totalPages} \u2014 rows ${start + 1}-${end} of ${parsedRows.length}`;
const controls = document.createElement("div");
controls.className = "page-controls";
const prevBtn = document.createElement("button");
prevBtn.type = "button";
prevBtn.className = "ghost";
prevBtn.textContent = "Previous";
prevBtn.disabled = currentPage === 1;
prevBtn.addEventListener("click", () => {
currentPage = Math.max(1, currentPage - 1);
renderCsvPreviewIfReady();
});
const nextBtn = document.createElement("button");
nextBtn.type = "button";
nextBtn.className = "ghost";
nextBtn.textContent = "Next";
nextBtn.disabled = currentPage === totalPages;
nextBtn.addEventListener("click", () => {
currentPage = Math.min(totalPages, currentPage + 1);
renderCsvPreviewIfReady();
});
controls.appendChild(prevBtn);
controls.appendChild(nextBtn);
pagination.appendChild(info);
pagination.appendChild(controls);
previewCsv.appendChild(pagination);
};
const runParse = async () => {
downloadLink.hidden = true;
passwordBox.hidden = true;
previewPdfBtn.hidden = true;
previewCsvBtn.hidden = true;
setStatus("Parsing...");
try {
const password = tool.needsPassword ? passwordInput.value.trim() : undefined;
const { rows, format } = await tool.parseFile(file, password);
if (!rows.length) {
setStatus("No transactions detected. The file may use a different layout.");
return;
}
const columns = tool.getColumns(format);
const csv = rowsToCsv(rows, columns);
const blob = new Blob([csv], { type: "text/csv" });
if (csvUrl) {
URL.revokeObjectURL(csvUrl);
}
csvUrl = URL.createObjectURL(blob);
downloadLink.href = csvUrl;
downloadLink.download = file.name.replace(/\.[^.]+$/, "") + ".csv";
downloadLink.hidden = false;
parsedRows = rows;
parsedColumns = columns;
currentPage = 1;
previewPdfBtn.hidden = !isPdf;
previewCsvBtn.hidden = false;
setStatus(`Parsed ${rows.length} transactions.`);
} catch (err) {
if (err?.name === "PasswordException") {
passwordBox.hidden = false;
previewPdfBtn.hidden = true;
previewCsvBtn.hidden = true;
setStatus("Password required to open this PDF.");
} else {
setStatus(`Failed to parse: ${err.message || err}`);
}
}
};
nameEl.textContent = file.name;
setStatus("Parsing...");
fileUrl = URL.createObjectURL(file);
removeBtn.addEventListener("click", cleanup);
passwordSubmit.addEventListener("click", runParse);
previewClose.addEventListener("click", hidePreviewPanel);
previewPdfBtn.addEventListener("click", () => {
showPreviewPanel();
previewCsv.hidden = true;
previewPdf.hidden = false;
renderFilePreview();
});
previewCsvBtn.addEventListener("click", () => {
showPreviewPanel();
previewPdf.hidden = true;
previewCsv.hidden = false;
renderCsvPreviewIfReady();
});
fileList.appendChild(node);
runParse();
}
function acceptFiles(fileListLike) {
const tool = activeTool;
if (!tool) return;
const files = Array.from(fileListLike);
files.forEach((file) => {
if (!tool.isValidFile(file)) return;
createTile(file);
});
}
/* ── Shared status helpers ── */
function setSharedStatus(message, isError = false) {
if (!sharedStatus) return;
if (!message) {
sharedStatus.textContent = "";
sharedStatus.hidden = true;
sharedStatus.classList.remove("is-error");
return;
}
sharedStatus.textContent = message;
sharedStatus.hidden = false;
sharedStatus.classList.toggle("is-error", isError);
}
function clearSharedUrlParams() {
const url = new URL(window.location.href);
url.searchParams.delete("shared");
window.history.replaceState({}, "", url);
}
/* ── PWA / Service worker ── */
async function registerServiceWorker() {
if (!("serviceWorker" in navigator)) return;
try {
await navigator.serviceWorker.register("/service-worker.js");
} catch (err) {
console.error("Service worker registration failed:", err);
}
}
function registerFileLaunchConsumer() {
if (!("launchQueue" in window) || typeof window.launchQueue.setConsumer !== "function") return;
window.launchQueue.setConsumer(async (launchParams) => {
if (!launchParams?.files?.length) return;
try {
const openedFiles = [];
for (const fileHandle of launchParams.files) {
if (!fileHandle || typeof fileHandle.getFile !== "function") continue;
const file = await fileHandle.getFile();
openedFiles.push(file);
}
if (openedFiles.length) {
if (!activeTool) showTool(tools[0]);
acceptFiles(openedFiles);
setSharedStatus(
`Imported ${openedFiles.length} file${openedFiles.length === 1 ? "" : "s"} from file open.`,
);
} else {
setSharedStatus("No file was provided from file open.", true);
}
} catch (err) {
setSharedStatus("Could not open file from the system handler.", true);
console.error("File handler import failed:", err);
}
});
}
async function waitForServiceWorkerControl(timeoutMs = 5000) {
if (navigator.serviceWorker.controller) return;
await Promise.race([
navigator.serviceWorker.ready,
new Promise((_, reject) => {
setTimeout(() => reject(new Error("Timed out waiting for service worker")), timeoutMs);
}),
]);
if (!navigator.serviceWorker.controller) {
throw new Error("Current page is not controlled by service worker");
}
}
async function importSharedFilesIfAny() {
const url = new URL(window.location.href);
const sharedState = url.searchParams.get("shared");
let importedCount = 0;
if (!sharedState) return;
if (!activeTool) showTool(tools[0]);
if (sharedState === "empty") {
setSharedStatus("Share target did not include a file.", true);
clearSharedUrlParams();
return;
}
if (!("serviceWorker" in navigator)) {
setSharedStatus("Shared import needs service worker support.", true);
clearSharedUrlParams();
return;
}
try {
await waitForServiceWorkerControl();
const pendingResponse = await fetch("/shared-files/pending", { cache: "no-store" });
if (pendingResponse.status === 204) {
setSharedStatus("No shared file is pending. Upload a file manually.");
clearSharedUrlParams();
return;
}
if (!pendingResponse.ok) {
throw new Error(`Pending request failed with status ${pendingResponse.status}`);
}
const pending = await pendingResponse.json();
const sharedFiles = [];
for (const meta of pending.files || []) {
if (!meta?.url) continue;
const fileResponse = await fetch(meta.url, { cache: "no-store" });
if (!fileResponse.ok) continue;
const blob = await fileResponse.blob();
sharedFiles.push(
new File([blob], meta.name || "statement.pdf", {
type: meta.type || blob.type || "application/pdf",
lastModified: Date.now(),
}),
);
}
if (sharedFiles.length) {
acceptFiles(sharedFiles);
importedCount = sharedFiles.length;
setSharedStatus(
`Imported ${sharedFiles.length} file${sharedFiles.length === 1 ? "" : "s"} from share target.`,
);
} else {
setSharedStatus("No valid file was found in shared data.", true);
}
try {
if (pending.id) {
await fetch(`/shared-files/consume?id=${encodeURIComponent(pending.id)}`, {
cache: "no-store",
});
} else {
await fetch("/shared-files/consume", { cache: "no-store" });
}
} catch (consumeErr) {
console.warn("Shared cleanup failed:", consumeErr);
}
} catch (err) {
if (!importedCount) {
setSharedStatus("Could not import shared file. You can still upload manually.", true);
}
console.error("Shared import failed:", err);
} finally {
clearSharedUrlParams();
}
}
/* ── Init ── */
registerServiceWorker();
registerFileLaunchConsumer();
importSharedFilesIfAny();
// Deep-link: if URL has a tool hash, open it directly
const initialHash = window.location.hash.slice(1);
if (initialHash) {
const tool = tools.find((t) => t.id === initialHash);
if (tool) showTool(tool);
}
/* ── Dropzone events ── */
fileInput.addEventListener("change", (event) => {
acceptFiles(event.target.files);
fileInput.value = "";
});
dropzone.addEventListener("dragover", (event) => {
event.preventDefault();
dropzone.classList.add("is-dragging");
});
dropzone.addEventListener("dragleave", () => {
dropzone.classList.remove("is-dragging");
});
dropzone.addEventListener("drop", (event) => {
event.preventDefault();
dropzone.classList.remove("is-dragging");
acceptFiles(event.dataTransfer.files);
});
dropzone.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
fileInput.click();
}
});