bettersight-statement-extra.../templates/index.html

814 lines
34 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bank Statement Extractor</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;600&display=swap" rel="stylesheet">
<style>
:root{
/* Accent — single brand color, per UI_DESIGN_THEME.md (enterprise variant: standard blue) */
--blue:#2563EB;
--blue-b:#1D4ED8;
--cyan:#2563EB;
/* Status colors — never reused as brand accent */
--green:#16A34A; --green-l:#DCFCE7; --green-d:#15803D;
--amber:#D97706; --amber-l:#FEF3C7;
--red:#DC2626; --red-l:#FEE2E2;
/* Background stack — light surfaces, per UI_DESIGN_THEME.md's own
light-surface tokens (--surface/--surface-2/--page) */
--navy:#EEF1F6;
--navy-2:#FFFFFF;
--navy-3:#F8FAFD;
/* Text on light surfaces, per UI_DESIGN_THEME.md */
--t1:#0D1526; --t2:#2D3A52; --t3:#6B7A99; --t4:#9BA8C0;
/* Borders, per UI_DESIGN_THEME.md's light-surface tokens */
--border:rgba(28,56,121,.11);
--border-2:rgba(28,56,121,.18);
--border-b:rgba(37,99,235,.28);
--shadow:0 2px 8px rgba(12,26,60,.06),0 8px 28px rgba(12,26,60,.09),0 0 0 1px rgba(28,56,121,.06);
--shadow-h:0 4px 16px rgba(12,26,60,.10),0 16px 48px rgba(12,26,60,.13),0 0 0 1px rgba(37,99,235,.18);
--fd:'Inter',sans-serif;
--fb:'Inter',sans-serif;
--fm:'JetBrains Mono',monospace;
--r:8px;
}
*{ box-sizing:border-box; margin:0; padding:0; }
body{ font-family:var(--fb); background:var(--navy); color:var(--t1); min-height:100vh; -webkit-font-smoothing:antialiased; }
main{ position:relative; z-index:1; max-width:1360px; margin:0 auto; padding:56px 24px 90px; }
.eyebrow{
display:inline-flex; align-items:center; gap:7px;
font-family:var(--fm); font-size:11px; font-weight:600; letter-spacing:.12em; text-transform:uppercase;
color:var(--blue); background:rgba(37,99,235,.08); border:1px solid var(--border-b);
padding:5px 12px; border-radius:20px; margin-bottom:16px;
}
.eyebrow::before{ content:''; width:6px; height:6px; border-radius:50%; background:var(--blue); }
h1{ font-family:var(--fd); font-weight:800; font-size:30px; letter-spacing:-.01em; margin-bottom:10px; }
.sub{ color:var(--t3); font-size:14.5px; line-height:1.6; max-width:620px; margin-bottom:34px; }
.card{
background:var(--navy-2); border:1px solid var(--border); border-radius:var(--r);
padding:28px 26px; margin-bottom:22px; box-shadow:var(--shadow);
}
.card h2{
font-family:var(--fm); font-size:11px; font-weight:600; letter-spacing:.1em; text-transform:uppercase;
color:var(--blue); margin-bottom:18px;
}
.file-zone{
border:1.5px dashed var(--border-2); border-radius:10px; padding:26px 20px; text-align:center;
cursor:pointer; transition:all .2s; position:relative; margin-bottom:16px;
}
.file-zone:hover, .file-zone.drag-over{ border-color:var(--blue); background:rgba(37,99,235,.04); }
.file-zone input[type="file"]{ position:absolute; inset:0; opacity:0; cursor:pointer; width:100%; height:100%; }
.file-zone-label{ font-size:13.5px; color:var(--t2); }
.file-zone-label strong{ color:var(--blue); font-weight:600; }
.file-zone-sub{ font-size:11.5px; color:var(--t4); margin-top:5px; }
.file-zone-sub.file-chosen-name{ font-family:var(--fm); font-size:12px; color:var(--blue); margin-top:5px; }
.fields{ display:flex; flex-wrap:wrap; gap:16px; margin-bottom:16px; }
.fields > div{ flex:1 1 180px; min-width:160px; }
.fields label{ font-size:11.5px; color:var(--t3); display:block; margin-bottom:6px; white-space:normal; }
.fields input{
width:100%; padding:9px 11px; background:var(--navy); border:1px solid var(--border-2);
border-radius:8px; font-size:13px; color:var(--t1); font-family:var(--fb); outline:none; transition:border-color .2s;
}
.fields input:focus{ border-color:var(--blue); }
.calc-readout{ font-family:var(--fm); font-size:11.5px; color:var(--t3); margin-top:6px; min-height:14px; }
.calc-readout.match{ color:var(--green); }
.note{ font-size:12px; color:var(--t4); line-height:1.6; margin-bottom:18px; }
.btn{
display:inline-flex; align-items:center; justify-content:center; gap:8px;
font-family:var(--fd); font-weight:700; font-size:13.5px; border-radius:10px; border:none;
padding:11px 22px; cursor:pointer; transition:all .2s;
}
.btn-primary{ background:var(--blue); color:var(--navy-2); box-shadow:0 4px 18px rgba(37,99,235,.18); }
.btn-primary:hover{ background:var(--blue-b); }
.btn-primary:disabled{ opacity:.35; cursor:not-allowed; box-shadow:none; }
.btn-ghost{
background:transparent; color:var(--t1); border:1px solid var(--border-2);
}
.btn-ghost:hover{ border-color:var(--border-b); color:var(--blue); }
.spinner{ font-family:var(--fm); font-size:12px; color:var(--t4); margin-left:12px; }
.error-note{
display:none; font-size:12.5px; color:var(--red); background:var(--red-l);
border:1px solid rgba(220,38,38,.3); border-radius:9px; padding:11px 14px; margin-top:12px;
}
.error-note.visible{ display:block; }
.status-banner{
display:inline-flex; align-items:center; gap:9px; padding:7px 15px; border-radius:20px;
font-family:var(--fm); font-weight:600; font-size:12.5px; letter-spacing:.03em; text-transform:uppercase;
margin-bottom:18px;
}
.status-banner.Verified{ background:var(--green-l); color:var(--green-d); }
.status-banner.Needs-review{ background:var(--amber-l); color:var(--amber); }
.status-banner.Failed{ background:var(--red-l); color:var(--red); }
.period-note{ font-size:12.5px; color:var(--t3); margin-bottom:18px; }
.result-head{ display:flex; align-items:center; justify-content:space-between; gap:12px; }
.result-head-left{ display:flex; align-items:center; gap:10px; cursor:pointer; }
.result-head-left h2{ margin-bottom:0; }
.collapse-arrow{
display:inline-flex; align-items:center; justify-content:center;
width:20px; height:20px; background:transparent; border:none; cursor:pointer;
color:var(--blue); font-size:12px; line-height:1; transition:transform .2s; transform:rotate(0deg);
}
.collapse-arrow.expanded{ transform:rotate(90deg); }
.result-details{ display:none; margin-top:18px; }
.result-details.expanded{ display:block; }
.checks-list{ list-style:none; }
.checks-list li{
display:flex; gap:12px; align-items:flex-start; padding:11px 0; border-bottom:1px solid var(--border);
font-size:13px; color:var(--t2);
}
.checks-list li:last-child{ border-bottom:none; }
.checks-list strong{ font-family:var(--fd); font-weight:700; color:var(--t1); text-transform:capitalize; }
.tag{
font-family:var(--fm); font-size:9.5px; font-weight:600; text-transform:uppercase; letter-spacing:.06em;
padding:3px 9px; border-radius:20px; white-space:nowrap; flex-shrink:0; margin-top:1px;
}
.tag.pass{ background:var(--green-l); color:var(--green-d); }
.tag.fail{ background:var(--red-l); color:var(--red); }
.tag.needs_review{ background:var(--amber-l); color:var(--amber); }
.tag.not_available{ background:rgba(16,24,40,.06); color:var(--t4); }
.table-wrap{ overflow-x:auto; margin-top:4px; }
table{ width:100%; border-collapse:collapse; font-size:12.5px; table-layout:fixed; }
th{
text-align:left; padding:9px 10px; font-family:var(--fm); font-size:10px; font-weight:600;
letter-spacing:.06em; text-transform:uppercase; color:var(--t4); border-bottom:1px solid var(--border-2);
white-space:nowrap; overflow:hidden;
}
td{ text-align:left; padding:3px 4px; border-bottom:1px solid var(--border); color:var(--t2); white-space:nowrap; overflow:hidden; }
td.desc{ white-space:normal; color:var(--t1); overflow:visible; }
td.amt, th.amt{ text-align:right; font-family:var(--fm); }
tr.flagged td{ background:rgba(217,119,6,.08); }
tr.flagged td:first-child{ border-left:2px solid var(--amber); }
.cell-input{
width:100%; background:transparent; border:1px solid transparent; border-radius:5px;
padding:6px 6px; font:inherit; color:inherit; text-align:inherit; font-family:inherit;
}
.cell-input:read-only{ color:var(--t2); cursor:default; }
tr.editing .cell-input:not(:read-only):hover{ border-color:var(--border-2); }
tr.editing .cell-input:not(:read-only):focus{ outline:none; border-color:var(--blue); background:rgba(37,99,235,.05); }
.cell-input.edited{ background:rgba(37,99,235,.08); border-color:var(--border-b); }
.desc-input{
display:block; white-space:pre-wrap; word-break:break-word; resize:none;
overflow:hidden; min-height:28px; line-height:1.5;
}
td.amt .cell-input{ text-align:right; font-family:var(--fm); }
.row-actions{ width:34px; padding:3px 0 3px 4px !important; }
.row-btn{
background:transparent; border:none; cursor:pointer; padding:4px; border-radius:5px;
font-size:13px; line-height:1; color:var(--t4); transition:color .15s, background .15s;
}
.row-btn:hover{ color:var(--t1); background:rgba(16,24,40,.06); }
.row-btn.save{ color:var(--blue); }
.row-btn.cancel{ color:var(--t4); }
tr.editing td{ background:rgba(37,99,235,.03); }
.restore-banner{
display:none; align-items:center; justify-content:space-between; gap:12px;
font-size:12.5px; color:var(--t2); background:rgba(37,99,235,.07); border:1px solid var(--border-b);
border-radius:9px; padding:10px 14px; margin-bottom:16px;
}
.restore-banner.visible{ display:flex; }
.restore-banner button{
background:transparent; border:1px solid var(--border-2); color:var(--t3); font-family:var(--fb);
font-size:11.5px; padding:5px 10px; border-radius:7px; cursor:pointer; flex-shrink:0;
}
.restore-banner button:hover{ color:var(--t1); border-color:var(--border-b); }
#resultSection{ display:none; }
/* Sticky on the GROUP, not on pdf-col alone - keeps the source PDF and
transactions cards moving together as one unit while the main page
scrolls, instead of the PDF pinning in place while transactions
scrolls past it underneath (they'd drift out of alignment). */
.review-grid{ display:flex; align-items:start; position:sticky; top:24px; }
.pdf-col{ flex:0 0 40%; min-width:260px; }
.pdf-col iframe{
width:100%; height:82vh; border:1px solid var(--border-2); border-radius:10px;
background:var(--navy-3); display:block;
}
.resizer{
flex:0 0 28px; align-self:stretch; cursor:col-resize;
display:flex; align-items:center; justify-content:center;
touch-action:none; position:relative;
}
/* A fader-knob look, not just a thin line - a rounded, raised pill with
grip dashes through its middle, so it visibly reads as a two-finger
drag handle rather than a stray divider. */
.resizer::before{
content:''; width:14px; height:58px; border-radius:9px;
background:linear-gradient(180deg, var(--navy-3), var(--navy-2));
border:1px solid var(--border-2);
box-shadow: inset 0 1px 0 rgba(255,255,255,.6), 0 2px 8px rgba(16,24,40,.10);
transition: border-color .15s, box-shadow .15s;
}
.resizer::after{
content:''; position:absolute; top:50%; left:50%;
width:2px; height:18px; border-radius:1px; background:var(--t3);
box-shadow: -4px 0 0 var(--t3), 4px 0 0 var(--t3);
transform:translate(-50%,-50%);
transition: background .15s;
}
.resizer:hover::before, .resizer.dragging::before{
border-color:var(--border-b);
box-shadow: inset 0 1px 0 rgba(255,255,255,.7), 0 0 0 1px rgba(37,99,235,.25), 0 2px 10px rgba(16,24,40,.12);
}
.resizer:hover::after, .resizer.dragging::after{
background:var(--blue); box-shadow: -4px 0 0 var(--blue), 4px 0 0 var(--blue);
}
.txn-col{ flex:1 1 auto; min-width:260px; }
.txn-col-head{ display:flex; align-items:center; justify-content:space-between; margin-bottom:18px; }
.txn-col-head h2{ margin-bottom:0; }
.btn-toggle{
background:var(--blue); border:none; color:var(--navy-2); font-family:var(--fd); font-weight:700;
font-size:12px; padding:7px 15px; border-radius:8px; cursor:pointer; transition:all .15s; flex-shrink:0;
box-shadow:0 2px 10px rgba(37,99,235,.18);
}
.btn-toggle:hover{ background:var(--blue-b); }
.btn-toggle:disabled{ opacity:.5; cursor:not-allowed; box-shadow:none; }
.pdf-col.hidden-panel, .resizer.hidden-panel{ display:none; }
.txn-col .table-wrap{ max-height:82vh; overflow-y:auto; margin-top:4px; }
.txn-col table thead th{
position:sticky; top:0; background:var(--navy-2); z-index:1;
}
@media (max-width: 860px){
.review-grid{ flex-direction:column; position:static; }
.pdf-col{ position:static; flex-basis:auto !important; width:100%; }
.resizer{ display:none; }
.txn-col{ width:100%; }
}
</style>
</head>
<body>
<main>
<div class="eyebrow">Extraction &amp; verification</div>
<h1>Bank Statement Extractor</h1>
<div class="sub">Upload a bank statement PDF or photo. A text PDF structures the transactions and proves the arithmetic against two independent extraction passes; a scanned or photographed statement is read via OCR instead, with no second pass to cross-check it against.</div>
<div class="card upload-card">
<h2>Statement</h2>
<div class="file-zone" id="fileZone">
<input type="file" id="fileInput" accept=".pdf,application/pdf,.jpg,.jpeg,.png,image/jpeg,image/png">
<div class="file-zone-label"><strong>Drop a statement PDF or photo here</strong> or browse</div>
<div class="file-zone-sub" id="fileZoneSub">.pdf, .jpg, or .png files</div>
</div>
<button class="btn btn-primary" id="processBtn" disabled>Extract</button>
<span class="spinner" id="spinner" style="display:none">Processing…</span>
<div class="error-note" id="errorNote"></div>
</div>
<div id="resultSection">
<div class="restore-banner" id="restoreBanner">
<span id="restoreBannerText"></span>
<button id="discardRestoreBtn">Discard saved edits</button>
</div>
<div class="card">
<div class="result-head">
<div class="result-head-left" id="resultHeadLeft">
<button class="collapse-arrow" id="resultToggleBtn" type="button" aria-expanded="false" title="Show details">&#9656;</button>
<h2>Result</h2>
</div>
<button class="btn-toggle" id="downloadBtn" type="button">Download Excel</button>
</div>
<div class="result-details" id="resultDetails">
<div id="statusBanner" class="status-banner"></div>
<div id="periodNote" class="period-note"></div>
<ul class="checks-list" id="checksList"></ul>
</div>
</div>
<div class="review-grid">
<div class="card pdf-col" id="pdfCol">
<h2>Source Document</h2>
<iframe id="pdfPreview" title="Statement PDF preview"></iframe>
</div>
<div class="resizer" id="resizer"></div>
<div class="card txn-col">
<div class="txn-col-head">
<h2>Transactions</h2>
<button class="btn-toggle" id="togglePdfBtn" type="button">Hide Source Doc</button>
</div>
<div class="fields">
<div>
<label>Opening balance (optional)</label>
<input type="text" inputmode="decimal" id="openingBalance" placeholder="e.g. 90,569.13">
<div class="calc-readout" id="openingCalc"></div>
</div>
<div>
<label>Closing balance (optional)</label>
<input type="text" inputmode="decimal" id="closingBalance" placeholder="e.g. 88,479.50">
<div class="calc-readout" id="closingCalc"></div>
</div>
</div>
<div class="note">This statement format may not print a clean opening/closing balance — enter them here to run the full statement balance check; otherwise it's marked "not available" rather than guessed.</div>
<div class="note" id="editNote">Click the pencil on a row to edit it, then Save to commit - edits are saved to this browser as you confirm them, row by row.</div>
<div class="table-wrap">
<table>
<colgroup>
<col style="width:34px">
<col style="width:120px">
<col>
<col style="width:120px">
<col style="width:135px">
<col style="width:95px">
</colgroup>
<thead><tr><th></th><th>Date</th><th>Description</th><th class="amt">Amount</th><th class="amt">Balance</th><th>Status</th></tr></thead>
<tbody id="txnRows"></tbody>
</table>
</div>
</div>
</div>
</div>
</main>
<script>
const $ = id => document.getElementById(id);
function escapeHtml(s) {
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
function fmtMoney(n) {
if (n === null || n === undefined) return '—';
const sign = n < 0 ? '-' : '';
return sign + '$' + Math.abs(n).toLocaleString('en-US', {minimumFractionDigits: 2});
}
// Same comma grouping as fmtMoney but no $ sign - used inside the
// editable Amount/Balance cells, where a leading $ would just get
// parsed back out on save anyway.
function fmtNum(n) {
if (n === null || n === undefined) return '';
const sign = n < 0 ? '-' : '';
return sign + Math.abs(n).toLocaleString('en-US', {minimumFractionDigits: 2});
}
function parseNum(s) {
s = s.replace(/[^0-9.\-]/g, '');
return s === '' || s === '-' ? null : parseFloat(s);
}
// Whatever the user typed always wins; an intentionally blank field (no
// auto-fill, per the UI's own calculated-balance readouts) falls back
// to the statement's own auto-detected figure from the initial extract -
// otherwise a row edit's recheck/export would lose that figure entirely
// the moment the visible field is empty.
function effectiveOpeningBalance() {
const typed = parseNum($('openingBalance').value);
return typed !== null ? typed : (currentResult ? currentResult.opening_balance : null);
}
function effectiveClosingBalance() {
const typed = parseNum($('closingBalance').value);
return typed !== null ? typed : (currentResult ? currentResult.closing_balance : null);
}
function autoGrow(el) {
el.style.height = 'auto';
el.style.height = el.scrollHeight + 'px';
}
function autoGrowAll() {
document.querySelectorAll('#txnRows .desc-input').forEach(autoGrow);
}
// ── Collapse/expand the Result card's details ───────────────────────────
// Starts collapsed on every fresh result (just the status/download row
// shows) - the arrow on the left toggles the status banner/checks list,
// the Download Excel button on the right stays independently clickable.
function setResultExpanded(expanded) {
$('resultDetails').classList.toggle('expanded', expanded);
$('resultToggleBtn').classList.toggle('expanded', expanded);
$('resultToggleBtn').setAttribute('aria-expanded', String(expanded));
$('resultToggleBtn').title = expanded ? 'Hide details' : 'Show details';
}
$('resultHeadLeft').addEventListener('click', () => {
setResultExpanded(!$('resultDetails').classList.contains('expanded'));
});
let chosenFile = null;
let currentPdfUrl = null;
let currentResult = null;
let currentDocKey = null;
let lastFilename = '';
let flaggedIndexes = new Set();
// ── Persistence (edits survive a crash/reload) ──────────────────────────
// Keyed by the SOURCE file's own name+size (stable across re-selecting the
// same file after a crash), not the server's randomly-generated output
// filename - that changes every run even for the same source document.
function docKeyFor(file) {
return 'bse:doc:' + file.name + ':' + file.size;
}
function persist() {
if (!currentDocKey || !currentResult) return;
try {
localStorage.setItem(currentDocKey, JSON.stringify(currentResult));
localStorage.setItem('bse:last_doc_key', currentDocKey);
} catch (e) { /* storage full/unavailable - edits still work in-memory */ }
}
function tryRestore(key) {
let saved;
try { saved = localStorage.getItem(key); } catch (e) { return false; }
if (!saved) return false;
try {
const parsed = JSON.parse(saved);
currentResult = parsed;
currentDocKey = key;
renderResult(parsed, { restored: true });
return true;
} catch (e) { return false; }
}
function setFile(file) {
if (!file) return;
if (!/\.(pdf|jpe?g|png)$/i.test(file.name)) {
$('errorNote').textContent = 'Please choose a .pdf, .jpg, or .png file.';
$('errorNote').classList.add('visible');
return;
}
chosenFile = file;
$('errorNote').classList.remove('visible');
$('fileZoneSub').textContent = file.name;
$('fileZoneSub').classList.add('file-chosen-name');
$('processBtn').disabled = false;
if (currentPdfUrl) URL.revokeObjectURL(currentPdfUrl);
currentPdfUrl = URL.createObjectURL(file);
// #toolbar=1 forces the browser's native PDF viewer toolbar (page
// nav + zoom controls) on; navpanes=0 skips the thumbnails/bookmarks
// sidebar so the toolbar isn't competing for space in a narrow column.
// Harmless no-op for an image file in this same iframe - the browser's
// native image view ignores an unrecognized hash fragment and just
// displays the image, so a scanned/photographed upload still previews
// correctly without a separate <img> element or any branching here.
$('pdfPreview').src = currentPdfUrl + '#toolbar=1&navpanes=0&view=FitH';
const key = docKeyFor(file);
if (key === currentDocKey) {
// Same file re-selected (e.g. just to restore the preview after a
// crash) - leave the already-shown results/edits alone.
return;
}
$('resultSection').style.display = 'none';
currentResult = null;
currentDocKey = null;
tryRestore(key); // shows it immediately if this exact file has a saved session
}
const zone = $('fileZone');
$('fileInput').addEventListener('change', () => setFile($('fileInput').files[0]));
zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
zone.addEventListener('drop', e => {
e.preventDefault(); zone.classList.remove('drag-over');
setFile(e.dataTransfer.files[0]);
});
$('processBtn').addEventListener('click', async () => {
if (!chosenFile) return;
$('processBtn').disabled = true;
$('spinner').style.display = 'inline';
$('errorNote').classList.remove('visible');
$('resultSection').style.display = 'none';
const fd = new FormData();
fd.append('statement_file', chosenFile);
const obField = parseNum($('openingBalance').value);
if (obField !== null) fd.append('opening_balance', obField);
const cbField = parseNum($('closingBalance').value);
if (cbField !== null) fd.append('closing_balance', cbField);
try {
const r = await fetch('/api/process', { method: 'POST', body: fd });
const d = await r.json();
if (d.error) {
$('errorNote').textContent = d.error;
$('errorNote').classList.add('visible');
} else {
currentDocKey = docKeyFor(chosenFile);
currentResult = d;
persist();
renderResult(d);
}
} catch (e) {
$('errorNote').textContent = 'Network error: ' + e.message;
$('errorNote').classList.add('visible');
}
$('spinner').style.display = 'none';
$('processBtn').disabled = false;
});
function applyCheckResults(checkResult) {
currentResult.status = checkResult.status;
currentResult.checks = checkResult.checks;
const banner = $('statusBanner');
banner.className = 'status-banner ' + checkResult.status.replace(' ', '-');
banner.textContent = checkResult.status;
$('checksList').innerHTML = checkResult.checks.map(c => `
<li><span class="tag ${c.outcome}">${c.outcome.replace('_',' ')}</span>
<span><strong>${c.name.replace(/_/g,' ')}</strong> — ${escapeHtml(c.detail)}</span></li>
`).join('');
// The statement-balance check's own computed closing (opening +
// credits + debits) - shown under the Closing balance field as a
// read-only readout, separate from whatever the user may have typed
// there, turning green exactly when it matches (check outcome "pass").
const balanceCheck = checkResult.checks.find(c => c.name === 'statement_balance');
const matched = balanceCheck && balanceCheck.outcome === 'pass';
$('openingCalc').classList.toggle('match', matched);
$('closingCalc').classList.toggle('match', matched);
if (balanceCheck && balanceCheck.calculated_closing !== undefined && balanceCheck.calculated_closing !== null) {
$('closingCalc').textContent = 'Calculated: ' + fmtMoney(balanceCheck.calculated_closing);
} else {
$('closingCalc').textContent = '';
}
flaggedIndexes = new Set();
checkResult.checks.forEach(c => {
(c.mismatches || c.issues || []).forEach(item => {
if (item.index !== undefined) flaggedIndexes.add(item.index);
});
});
document.querySelectorAll('#txnRows tr').forEach((tr, i) => {
tr.classList.toggle('flagged', flaggedIndexes.has(i));
});
}
function renderResult(d, opts) {
opts = opts || {};
lastFilename = d.filename;
$('periodNote').textContent = d.period ? `Statement period: ${d.period}` : '';
// The input fields themselves stay exactly what the user typed (or
// blank, if they typed nothing) - never auto-filled, to avoid the
// confusion of a value appearing there that isn't the user's own.
// Whatever the statement printed inside its own table (see pipeline.py's
// own fallback) - or whatever the user already typed, which the server
// echoes back unchanged - shows instead as a separate read-only readout.
$('openingCalc').textContent = (d.opening_balance !== null && d.opening_balance !== undefined)
? 'Calculated: ' + fmtMoney(d.opening_balance) : '';
flaggedIndexes = new Set();
d.checks.forEach(c => {
(c.mismatches || c.issues || []).forEach(item => {
if (item.index !== undefined) flaggedIndexes.add(item.index);
});
});
renderTxnRows(d.transactions);
applyCheckResults({ status: d.status, checks: d.checks });
setResultExpanded(false);
const rb = $('restoreBanner');
if (opts.restored) {
$('restoreBannerText').textContent = 'Restored previously edited values for this file from this browser - re-select the source PDF above to view it alongside the data again.';
rb.classList.add('visible');
} else {
rb.classList.remove('visible');
}
$('resultSection').style.display = 'block';
// scrollHeight (what autoGrow measures) is always 0 on a hidden
// ancestor, so re-measure now that the section is actually visible -
// the earlier call inside renderTxnRows ran while it was still
// display:none and would have collapsed every description box.
autoGrowAll();
}
function rowHtml(t, i) {
return `
<tr class="${flaggedIndexes.has(i) ? 'flagged' : ''}" data-idx="${i}">
<td class="row-actions"><button class="row-btn edit" data-action="edit" title="Edit this row">&#9998;</button></td>
<td><input class="cell-input" data-field="date" value="${escapeHtml(t.date)}" readonly></td>
<td class="desc"><textarea class="cell-input desc-input" data-field="description" rows="1" readonly>${escapeHtml(t.description)}</textarea></td>
<td class="amt"><input class="cell-input" data-field="amount" type="text" value="${escapeHtml(fmtNum(t.amount))}" readonly></td>
<td class="amt"><input class="cell-input" data-field="balance" type="text" value="${escapeHtml(fmtNum(t.balance))}" readonly></td>
<td><input class="cell-input" data-field="status" value="${escapeHtml(t.status)}" readonly></td>
</tr>`;
}
function renderTxnRows(transactions) {
$('txnRows').innerHTML = transactions.map((t, i) => rowHtml(t, i)).join('');
autoGrowAll();
}
// ── Re-check after a saved edit ─────────────────────────────────────────
// Re-runs the six checks against the edited transactions (pipeline.recheck
// - no re-extraction) and updates the status banner/flags in place, so a
// correction can clear a flag (or a typo can raise one) right after it's
// saved. See also the Download button, which uses the same recheck logic
// server-side to keep the export consistent with saved edits.
async function recheck() {
if (!currentResult) return;
try {
const r = await fetch('/api/recheck', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
transactions: currentResult.transactions,
page_reports: currentResult.page_reports,
narrative_direction: currentResult.narrative_direction,
period: currentResult.period,
opening_balance: effectiveOpeningBalance(),
closing_balance: effectiveClosingBalance(),
}),
});
const d = await r.json();
if (!d.error) applyCheckResults(d);
} catch (e) { /* recheck is best-effort; the saved edit itself isn't lost either way */ }
}
// ── Pencil-to-edit, per-row Save/Cancel ─────────────────────────────────
// Cells are read-only by default - a row only becomes editable after its
// own pencil is clicked (so edits are always deliberate, never an
// accidental keystroke in a cell you were just scrolling past), and a
// commit only happens on that row's own Save, which is when the edit is
// applied to currentResult, persisted, and re-checked.
function setRowEditing(tr, editing) {
tr.classList.toggle('editing', editing);
tr.querySelectorAll('.cell-input').forEach(inp => { inp.readOnly = !editing; });
const actionCell = tr.querySelector('.row-actions');
actionCell.innerHTML = editing
? `<button class="row-btn save" data-action="save" title="Save this row">&#10003;</button>
<button class="row-btn cancel" data-action="cancel" title="Discard changes">&#10005;</button>`
: `<button class="row-btn edit" data-action="edit" title="Edit this row">&#9998;</button>`;
}
$('txnRows').addEventListener('input', e => {
if (e.target.classList.contains('desc-input')) autoGrow(e.target);
});
$('txnRows').addEventListener('click', e => {
const btn = e.target.closest('.row-btn');
if (!btn) return;
const tr = btn.closest('tr');
const idx = +tr.dataset.idx;
if (btn.dataset.action === 'edit') {
setRowEditing(tr, true);
const first = tr.querySelector('.cell-input');
first.focus();
autoGrow(tr.querySelector('.desc-input'));
} else if (btn.dataset.action === 'cancel') {
tr.outerHTML = rowHtml(currentResult.transactions[idx], idx);
autoGrow(document.querySelector(`#txnRows tr[data-idx="${idx}"] .desc-input`));
} else if (btn.dataset.action === 'save') {
tr.querySelectorAll('.cell-input').forEach(inp => {
const field = inp.dataset.field;
let value = inp.value;
if (field === 'amount' || field === 'balance') {
value = parseNum(value);
}
currentResult.transactions[idx][field] = value;
});
// Re-render from the saved data so Amount/Balance pick up comma
// formatting and the description re-wraps, whatever was typed.
tr.outerHTML = rowHtml(currentResult.transactions[idx], idx);
const newTr = document.querySelector(`#txnRows tr[data-idx="${idx}"]`);
newTr.querySelectorAll('.cell-input').forEach(inp => inp.classList.add('edited'));
autoGrow(newTr.querySelector('.desc-input'));
persist();
recheck();
}
});
$('discardRestoreBtn').addEventListener('click', () => {
if (currentDocKey) {
try { localStorage.removeItem(currentDocKey); } catch (e) {}
}
$('restoreBanner').classList.remove('visible');
});
$('downloadBtn').addEventListener('click', async () => {
if (!currentResult) return;
const btn = $('downloadBtn');
btn.disabled = true;
const prevText = btn.textContent;
btn.textContent = 'Preparing…';
try {
const r = await fetch('/api/export', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
transactions: currentResult.transactions,
page_reports: currentResult.page_reports,
narrative_direction: currentResult.narrative_direction,
period: currentResult.period,
brought_forward_balance: currentResult.brought_forward_balance,
title: currentResult.title,
opening_balance: effectiveOpeningBalance(),
closing_balance: effectiveClosingBalance(),
}),
});
if (!r.ok) throw new Error('Export failed');
const blob = await r.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = (currentResult.title || 'Statement_Extraction').replace(/\.pdf$/i, '') + '.xlsx';
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
} catch (e) {
$('errorNote').textContent = 'Could not generate the export: ' + e.message;
$('errorNote').classList.add('visible');
}
btn.disabled = false;
btn.textContent = prevText;
});
// On page load, restore any previous session right away - before any file
// is even chosen - so a crash mid-edit never loses work. The source PDF
// itself isn't persisted (not practical to store in localStorage), so the
// preview stays empty until the same file is re-picked.
(function restoreOnLoad() {
let lastKey;
try { lastKey = localStorage.getItem('bse:last_doc_key'); } catch (e) { return; }
if (lastKey) tryRestore(lastKey);
})();
// ── Hide/show the PDF column ────────────────────────────────────────────
// Collapses the PDF column (and its resizer handle) out of the flex row
// entirely - txn-col's own flex:1 1 auto then fills the freed width on
// its own, no extra sizing needed. The toggle lives in the Transactions
// header rather than the PDF card's own header, since that card
// disappears when hidden and would take its own "Show" button with it.
$('togglePdfBtn').addEventListener('click', () => {
const pdfCol = $('pdfCol');
const resizer = $('resizer');
const hidden = pdfCol.classList.toggle('hidden-panel');
resizer.classList.toggle('hidden-panel', hidden);
$('togglePdfBtn').textContent = hidden ? 'Show Source Doc' : 'Hide Source Doc';
});
// ── Draggable divider between the PDF and the transactions list ────────
(function() {
const grid = document.querySelector('.review-grid');
const resizer = $('resizer');
const pdfCol = $('pdfCol');
let dragging = false;
function setWidthFromX(clientX) {
const rect = grid.getBoundingClientRect();
let pct = ((clientX - rect.left) / rect.width) * 100;
pct = Math.max(25, Math.min(75, pct));
pdfCol.style.flexBasis = pct + '%';
}
function start(e) {
dragging = true;
resizer.classList.add('dragging');
document.body.style.userSelect = 'none';
e.preventDefault();
}
function move(e) {
if (!dragging) return;
const x = e.touches ? e.touches[0].clientX : e.clientX;
setWidthFromX(x);
}
function end() {
if (!dragging) return;
dragging = false;
resizer.classList.remove('dragging');
document.body.style.userSelect = '';
autoGrowAll(); // column width changed - descriptions may rewrap at a different height
}
resizer.addEventListener('mousedown', start);
window.addEventListener('mousemove', move);
window.addEventListener('mouseup', end);
resizer.addEventListener('touchstart', start, { passive: false });
window.addEventListener('touchmove', move, { passive: false });
window.addEventListener('touchend', end);
})();
</script>
</body>
</html>