diff --git a/CLAUDE.md b/CLAUDE.md index 72de550..29a3070 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -30,7 +30,7 @@ to rough effort: | Phase | Contains | Status here | |---|---|---| | **1** | Extraction + 6 checks + Excel export, dual-engine, measurement harness | **In progress — see gaps below** | -| 2 | Review screen, suggested-fix patterns, OCR, 2nd+ bank support | OCR routing + working Docling-fallback (`raw_ocr_extract.py`) built and verified against a real multi-page scan 2026-10-11 — one known single-page edge case remains unreliable, see "OCR / scanned statements" below — review screen **in progress, staged R.1-R.5** (see "Review screen"/"R.2"/"R.3"/"R.4" under Key decisions & lessons) — R.1 (source-position capture + the pdf.js highlighting viewer), R.2 (plain-language flags + jump-to-flagged navigation), R.3 (the suggested-fix engine - debit/credit swap, transposed digits, OCR digit misread), and R.4 (structural row edits - flip sign, insert, split, merge, delete, behind a "more actions" menu) all shipped 2026-10-13; "date format swapped" and a separate "bulk column fix" both investigated and found not to apply to this pipeline's own data shape (see R.3/R.4's own entries); only R.5 (accept/acknowledge + edit log) remains, not started yet | +| 2 | Review screen, suggested-fix patterns, OCR, 2nd+ bank support | OCR routing + working Docling-fallback (`raw_ocr_extract.py`) built and verified against a real multi-page scan 2026-10-11 — one known single-page edge case remains unreliable, see "OCR / scanned statements" below — **review screen (R.1-R.5) complete as of 2026-10-13** (see "Review screen"/"R.2"/"R.3"/"R.4"/"R.5" under Key decisions & lessons) — R.1 (source-position capture + the pdf.js highlighting viewer), R.2 (plain-language flags + jump-to-flagged navigation), R.3 (the suggested-fix engine - debit/credit swap, transposed digits, OCR digit misread), R.4 (structural row edits - flip sign, insert, split, merge, delete, behind a "more actions" menu), and R.5 (edit log + acknowledge/accept workflow + an optional Excel "Edits" sheet) all shipped; "date format swapped" and a separate "bulk column fix" both investigated and found not to apply to this pipeline's own data shape (see R.3/R.4's own entries) | | 3 | Layout mapper (fingerprinting, versioning, drift detection) | Not started | | 4 | Multi-tenant practice/client accounts, Frappe data model | Not started | | 5 | Free front door, public accuracy page | Not started | @@ -266,7 +266,9 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co dead workbook generation and the never-called /api/download/ route; see "Excel exports moved to R2" under Key decisions & lessons for the full story). The frontend is what persists an export long-term now (`documentsService.saveExportFile`, - PocketBase/R2), not this backend at all. + PocketBase/R2), not this backend at all. As of review screen R.5 (2026-10-14), also + writes an optional "Edits" sheet (`_write_edits_sheet`) whenever the export request + carries a non-empty `edit_log` - see that entry under Key decisions & lessons. - `backend/services/extraction/raw_ocr_extract.py` — the per-page fallback for `extraction_service._run_ocr_only` when Docling's table-structure recognition fails on a scanned/photographed page. Runs OCR directly (`tesserocr`) for raw word text + pixel @@ -353,6 +355,12 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co (NEW 2026-10-13, review screen R.4 - see that entry under Key decisions & lessons for the full record, including why there's no separate `splitTransaction` action). + `appendEditLogEntry`/`acknowledgeFlag`/`unacknowledgeFlag`/ + `flagAcknowledged`/`allFlagsAcknowledged`/`acceptDocument` + (NEW 2026-10-14, review screen R.5 - see that entry under + Key decisions & lessons; `editLog`/`acknowledgedFlags`/ + `accepted`/`acceptedAt` all live directly on + `doc.result`, no new PocketBase migration needed). uiStore.js — `resultsOpen`/`toggleResultsOpen()`/`closeResultsOpen()` (renamed from `resultExpanded`/`toggleResultExpanded` - 2026-10-13, now drives TransactionsTable's own Results @@ -1779,6 +1787,91 @@ touched). Not machine-verified: the actual "more actions" menu, the two confirm modals, and the resulting table row changes - Claude-in-Chrome still did not connect this session. +**R.5 — edit log + acknowledge/accept workflow, shipped 2026-10-14. This closes out +the full review screen plan (R.1-R.5).** No new PocketBase migration needed - a +document's `result` field is already an arbitrary JSON blob the backend never +inspects the shape of (confirmed: `documentsService.updateDocument` PATCHes +`{result}` wholesale), so `editLog`/`acknowledgedFlags`/`accepted`/`acceptedAt` are +just new keys on that same object, written by the frontend and read back by it. + +`extractionStore.js` gained: `appendEditLogEntry(entry)` (pushes `{...entry, at: +ISOString}` onto `doc.result.editLog`, lazily initialized); `acknowledgeFlag(checkName, +index, note?)`/`unacknowledgeFlag(checkName, index)` (write/delete +`doc.result.acknowledgedFlags[checkName][index]`); `flagAcknowledged` (parameterized +getter, `(checkName, index) => boolean`); `allFlagsAcknowledged` (getter - walks every +check in `ROW_FLAG_CHECK_NAMES`, imported from `flagCatalogService.js` rather than +re-listed, so this can't silently drift from that file's own four row-flagging checks - +and every one of that check's `mismatches`/`issues` entries, confirming each has a +matching `acknowledgedFlags` entry; vacuously `true` when nothing is flagged at all, so +a clean "Verified" document was never blocked on acknowledging zero flags); +`acceptDocument()` (sets `accepted: true`/`acceptedAt: ISOString`, trusting its caller +the same way every other store action here does - the actual accept GATE lives in the +UI, not the store). + +Every mutation site that changes a transaction field now logs it, one entry per +CHANGED field (not one undifferentiated "row changed" blob) so a single "merge with +next" that touches description+amount+balance produces three log entries, not one: +- `useRowEditing.js`'s `saveEdit()` - diffs the draft against the transaction's actual + prior values field-by-field (date/description/amount/balance/status) before + committing, logging only the fields that actually changed, `source: 'manual'`. +- `TransactionRow.vue`'s `applySuggestedFix()` - logs the one field the suggestion + named, oldValue captured BEFORE the fix is applied, `source: 'suggested_fix'` + (distinguishing an engine-proposed fix from a hand-typed edit in the log/Excel sheet). +- The four R.4 structural actions, each with a descriptive, non-field label since + there's no single before/after VALUE to log for "a row was inserted": `handleFlipSign` + (logs the real `amount` old/new, since that's a genuine field change), `handleInsertAfter` + (`_row_inserted`), `handleSplit` (`_row_split`), `confirmMerge` (`_rows_merged`, + `oldValue` is the now-removed row's own index for traceability), `confirmDeleteRow` + (`_row_deleted`, `oldValue` is the deleted row's own description) - all `source: 'manual'`. + +**Acknowledge UI**: each flag in `TransactionRow.vue`'s existing R.2 flag-detail panel +gets its own "Mark as checked"/"Acknowledged" toggle button, keyed by that flag's own +`checkName` (already present on every `flagsForIndex()` result) - acknowledging doesn't +change any transaction data, it only records that a human reviewed it (the exact case +this exists for: HSBC-Aug's real Cancelled-wire `running_balance` mismatch, which is +correct-and-expected, not a data error to fix). Persisted best-effort via +`documentsService.updateDocument`, same discipline as every other row mutation, but the +toggle itself never blocks on that persist succeeding. + +**Accept UI**: a new "Accept"/"Accepted" button in `TransactionsTable.vue`'s top bar, +beside Download - enabled when `status === 'Verified'` (nothing to review) OR +`allFlagsAcknowledged` is true (everything flagged has been looked at); disabled +otherwise, with a title tooltip explaining why. Calls `extractionStore.acceptDocument()` +then persists via `documentsService.updateDocument`. + +**`backend/services/excel_service.py`** - `extraction_schema.parse_export_request()` +now passes `edit_log` through unchanged (`data.get("edit_log") or []`), and +`routes/extraction.py`'s `/api/export` includes it in the `result` dict it hands to +`excel_service.build_workbook()`. A new `_write_edits_sheet(wb, edit_log)` writes a +Row/Field/Old value/New value/When/Source table (1-based row numbers, matching the +Transactions sheet's own numbering - `entry["index"]` stays 0-based everywhere +internally), called conditionally - `if result.get("edit_log"):` - right before +`build_workbook()` returns, so an export with no edits made gains no empty "Edits" +sheet nobody asked for (`docs/bankstatement.md` §8's own spec: "Excel: ... optional +Edits sheet"). + +Verified, not assumed: `backend/measure.py` re-run, byte-identical to the pre-R.5 +baseline (1.0 field accuracy on all three fixtures, same statuses) - this stage adds +only new, always-optional data, nothing existing changed. A real `/api/process` call +against the HSBC-Sep fixture, then a real `/api/export` call against that actual +result with a synthetic `edit_log` attached, confirmed the real, rebuilt container +("Edits" sheet appears with the right headers/values/1-based row numbers only when +`edit_log` is non-empty; omitted it entirely when the payload carried none) - this +caught a real gap in the test setup itself (the first attempt 500'd with a `KeyError: +'pdfplumber_count'` from hand-rolled `page_reports` that didn't match the real shape; +switching to an actual `/api/process` response fixed it, not a product bug). +`extractionStore.js`'s new getters/actions were executed directly against real Pinia +(not reimplemented) across acknowledging one of two flags vs. both, unacknowledging, +`allFlagsAcknowledged`'s vacuous-true case for an unflagged document, and +`acceptDocument()`. `useRowEditing.js`'s edited `saveEdit()` was run for real against +a document actually created on the live PocketBase container: edited one field, +confirmed exactly one editLog entry with the correct old/new values and `source: +'manual'`, confirmed the OTHER, unchanged field produced no entry, and re-fetched the +PocketBase record directly (not trusting the in-memory store) to confirm the edit log +was genuinely persisted, not just held in memory. `npm run build` passes; the `app` +container rebuilt and confirmed serving the new bundle (`appendEditLogEntry` present +in the built JS). + **Governing rule: never silently correct or exclude data.** This shows up in several concrete places, not just as an abstract principle: - A row with an unusual status (e.g. HSBC's "Cancelled" wires) stays in the output and is @@ -2166,6 +2259,15 @@ restructure; the behavior itself predates it and is unchanged: a new one right after - the user divides them manually, nothing is auto-split), merge with the next row, delete this row. Delete and merge each confirm via the same `ConfirmModal` pattern every other destructive action in this app uses. +- Every mutation above (manual cell edit, suggested-fix apply, every structural + action) also appends an entry to the document's own edit log (added 2026-10-14, + review screen R.5 - `extractionStore.appendEditLogEntry`), included as an optional + "Edits" sheet in the downloaded Excel workbook. Each flag in a row's flag-detail + panel (R.2) also gets its own "Mark as checked"/"Acknowledged" toggle - reviewing a + flag doesn't change any data, it just records that a human looked at it (e.g. a + genuine Cancelled-wire balance break that's correct as-is, nothing to fix). A new + "Accept"/"Accepted" button in `TransactionsTable.vue`'s top bar, beside Download, is + enabled once the statement is "Verified" or every flagged row has been acknowledged. - All numeric displays are comma-formatted (`formatService.js`'s `fmtMoney`/`fmtNum`). - Edits persist to PocketBase (`documentsService.js`'s `saveDocument`/`updateDocument` - as of 2026-10-13, replacing the earlier localStorage-only version entirely, not diff --git a/backend/routes/extraction.py b/backend/routes/extraction.py index 621edd3..a09ad82 100644 --- a/backend/routes/extraction.py +++ b/backend/routes/extraction.py @@ -104,6 +104,7 @@ def export(): "page_reports": data["page_reports"], "period": data["period"], "brought_forward_balance": data["brought_forward_balance"], + "edit_log": data["edit_log"], **check_results, } workbook = excel_service.build_workbook(result, title=data["title"]) diff --git a/backend/schemas/extraction_schema.py b/backend/schemas/extraction_schema.py index 46741ea..646490c 100644 --- a/backend/schemas/extraction_schema.py +++ b/backend/schemas/extraction_schema.py @@ -61,15 +61,24 @@ def parse_export_request(json_body): """ Validates and extracts the /api/export JSON body - same shape as parse_recheck_request plus the fields the exported workbook itself - needs (brought_forward_balance, title). + needs (brought_forward_balance, title, edit_log). Data flow: json_body (dict) - the request's parsed JSON (or {} if absent/invalid) returns (dict) - parse_recheck_request's fields plus - brought_forward_balance and title + brought_forward_balance, title, and edit_log + + edit_log is passed through unchanged (a plain list of {index, field, + oldValue, newValue, at, source} entries, already fully formed on the + frontend - see extractionStore.js's appendEditLogEntry) - this schema + doesn't inspect its own shape, same as it already doesn't for + transactions/page_reports; excel_service.py only writes an "Edits" + sheet at all when this is non-empty, so an export with no edits + doesn't gain an empty sheet nobody asked for. """ data = json_body or {} parsed = parse_recheck_request(data) parsed["brought_forward_balance"] = data.get("brought_forward_balance") parsed["title"] = data.get("title") or "Statement Extraction" + parsed["edit_log"] = data.get("edit_log") or [] return parsed diff --git a/backend/services/excel_service.py b/backend/services/excel_service.py index e5cc1f6..8e28e13 100644 --- a/backend/services/excel_service.py +++ b/backend/services/excel_service.py @@ -93,4 +93,34 @@ def build_workbook(result, title="Statement Extraction"): _write_cell(ws2, r, 2, f"{c['outcome']}: {c['detail']}") r += 1 + # Optional - only written when the frontend actually sent a non-empty + # edit_log (extractionStore.js's own appendEditLogEntry, see + # CLAUDE.md's "R.5" entry) - an export with no edits made doesn't + # gain an empty sheet nobody asked for. docs/bankstatement.md + # section 8's own spec: "Excel: ... optional Edits sheet." + if result.get("edit_log"): + _write_edits_sheet(wb, result["edit_log"]) + return wb + + +def _write_edits_sheet(wb, edit_log): + ws = wb.create_sheet("Edits") + for col, width in zip("ABCDEF", (8, 18, 30, 30, 20, 14)): + ws.column_dimensions[col].width = width + headers = ["Row", "Field", "Old value", "New value", "When", "Source"] + for col, label in enumerate(headers, start=1): + _write_cell(ws, 1, col, label, bold=True) + row = 2 + for entry in edit_log: + # 1-based row number for a human reader, matching the + # Transactions sheet's own row numbering - entry["index"] is the + # same 0-based transaction index used everywhere else internally. + row_no = (entry.get("index") or 0) + 1 + _write_cell(ws, row, 1, row_no) + _write_cell(ws, row, 2, entry.get("field")) + _write_cell(ws, row, 3, str(entry.get("oldValue")) if entry.get("oldValue") is not None else "") + _write_cell(ws, row, 4, str(entry.get("newValue")) if entry.get("newValue") is not None else "") + _write_cell(ws, row, 5, entry.get("at")) + _write_cell(ws, row, 6, entry.get("source")) + row += 1 diff --git a/frontend/src/assets/main.css b/frontend/src/assets/main.css index 6e83d96..24ba225 100644 --- a/frontend/src/assets/main.css +++ b/frontend/src/assets/main.css @@ -294,6 +294,15 @@ tr.editing td{ background:rgba(37,99,235,.03); } .flag-show-source{ font-size:11.5px; padding:0 12px; height:30px; } .flag-show-source:disabled{ opacity:.4; cursor:not-allowed; } +/* "Mark as checked" (review screen R.5) - sits under each flag's own + four-part explanation, right-aligned via margin-left:auto since + .flag-detail isn't itself a flex container (its parts stack as plain + block divs); .active mirrors .btn-toggle-active's own filled style so + an acknowledged flag reads as visually "done", not just text-changed. */ +.flag-acknowledge{ display:flex; margin-left:auto; margin-top:6px; font-size:11.5px; padding:0 12px; height:28px; } +.flag-acknowledge.active{ background:var(--green); border-color:var(--green); color:#fff; } +.flag-acknowledge.active:hover{ background:var(--green); } + /* suggested_fixes_service.py's own one-click fixes (review screen R.3) - never applied automatically, always a deliberate "Apply fix" click against the evidence text shown right above it. */ @@ -319,7 +328,13 @@ tr.editing td{ background:rgba(37,99,235,.03); } padding-bottom:12px; margin-bottom:14px; border-bottom:1px solid var(--border-2); flex-shrink:0; } +.txn-top-bar-right{ display:flex; align-items:center; gap:8px; justify-self:end; } .txn-download-btn{ justify-self:end; } +/* Accept (review screen R.5) - .active mirrors .btn-toggle-active's own + filled style once accepted, same pattern .flag-acknowledge uses. */ +.txn-accept-btn.btn-toggle-active{ background:var(--green); box-shadow:none; } +.txn-accept-btn.btn-toggle-active:hover{ background:var(--green); } +.txn-accept-btn:disabled{ opacity:.45; cursor:not-allowed; } .results-trigger-wrap{ position:relative; justify-self:start; } .results-toggle{ @@ -578,7 +593,8 @@ tr.editing td{ background:rgba(37,99,235,.03); } @container txncol (max-width: 620px){ .txn-top-bar{ grid-template-columns:1fr; justify-items:stretch; gap:10px; } .results-trigger-wrap, .doc-nav{ justify-self:center; } - .txn-download-btn{ justify-self:stretch; } + .txn-top-bar-right{ justify-self:stretch; } + .txn-top-bar-right .btn-toggle{ flex:1 1 0; } } .login-page{ min-height:100vh; display:flex; align-items:center; justify-content:center; padding:24px; } diff --git a/frontend/src/components/TransactionRow.vue b/frontend/src/components/TransactionRow.vue index cbda3ac..e800399 100644 --- a/frontend/src/components/TransactionRow.vue +++ b/frontend/src/components/TransactionRow.vue @@ -23,6 +23,15 @@ * already uses (useRowEditing.js), so there's one path for "a value on * this row changed," not two that could quietly diverge. * + * Each flag in the expanded panel also has its own "Mark as checked" + * toggle (review screen R.5) - acknowledging doesn't change any data, + * just records that a human reviewed it (e.g. a genuine Cancelled wire + * breaking the balance chain on purpose, nothing to fix), which is what + * TransactionsTable.vue's Accept button gates on when the document's + * own status isn't already "Verified". Every mutation here (manual + * edit, suggested-fix apply, every structural action) also appends to + * the document's edit log via extractionStore.appendEditLogEntry. + * * Also hosts the structural row edits (review screen R.4) behind a * "more actions" menu - flip debit/credit, insert a row (for one the * extractor genuinely missed), split this row (duplicate + divide @@ -134,7 +143,12 @@ async function persistAndRecheck() { async function applySuggestedFix() { if (!suggestion.value || applyingFix.value) return applyingFix.value = true - extractionStore.saveRowEdit(suggestion.value.index, { [suggestion.value.fix.field]: suggestion.value.fix.value }) + const { index: fixIndex, fix } = suggestion.value + const oldValue = extractionStore.currentResult.transactions[fixIndex]?.[fix.field] + extractionStore.saveRowEdit(fixIndex, { [fix.field]: fix.value }) + extractionStore.appendEditLogEntry({ + index: fixIndex, field: fix.field, oldValue, newValue: fix.value, source: 'suggested_fix', + }) await persistAndRecheck() applyingFix.value = false } @@ -152,7 +166,11 @@ function closeRowMenu() { async function handleFlipSign() { closeRowMenu() busy.value = true + const oldValue = props.transaction.amount extractionStore.flipTransactionSign(props.index) + extractionStore.appendEditLogEntry({ + index: props.index, field: 'amount', oldValue, newValue: extractionStore.currentResult.transactions[props.index]?.amount, source: 'manual', + }) await persistAndRecheck() busy.value = false } @@ -162,6 +180,9 @@ async function handleInsertAfter() { closeRowMenu() busy.value = true extractionStore.insertTransactionAfter(props.index) + extractionStore.appendEditLogEntry({ + index: props.index + 1, field: '_row_inserted', oldValue: null, newValue: null, source: 'manual', + }) await persistAndRecheck() busy.value = false } @@ -171,6 +192,9 @@ async function handleSplit() { closeRowMenu() busy.value = true extractionStore.insertTransactionAfter(props.index, { ...props.transaction }) + extractionStore.appendEditLogEntry({ + index: props.index + 1, field: '_row_split', oldValue: null, newValue: null, source: 'manual', + }) await persistAndRecheck() busy.value = false } @@ -183,11 +207,34 @@ function requestMerge() { async function confirmMerge() { busy.value = true extractionStore.mergeWithNext(props.index) + extractionStore.appendEditLogEntry({ + index: props.index, field: '_rows_merged', oldValue: props.index + 1, newValue: null, source: 'manual', + }) await persistAndRecheck() showMergeConfirm.value = false busy.value = false } +// ── Acknowledge workflow (review screen R.5) ──────────────────────── +// A flag can be reviewed and left as-is (e.g. a genuine Cancelled wire +// breaking the balance chain on purpose - nothing to "fix") without +// blocking the document from ever being accepted. Acknowledging doesn't +// change any data, only records that a human looked at it - persisted +// best-effort, same discipline as every other row mutation here, but +// never blocks the toggle itself on that persist succeeding. +function isAcknowledged(checkName) { + return extractionStore.flagAcknowledged(checkName, props.index) +} +async function toggleAcknowledge(checkName) { + if (isAcknowledged(checkName)) extractionStore.unacknowledgeFlag(checkName, props.index) + else extractionStore.acknowledgeFlag(checkName, props.index) + try { + await documentsService.updateDocument(extractionStore.activeDocument.pbId, { result: extractionStore.currentResult }) + } catch (e) { + extractionStore.setError('Could not save the acknowledgement: ' + e.message) + } +} + const showDeleteRowConfirm = ref(false) function requestDeleteRow() { closeRowMenu() @@ -195,6 +242,9 @@ function requestDeleteRow() { } async function confirmDeleteRow() { busy.value = true + extractionStore.appendEditLogEntry({ + index: props.index, field: '_row_deleted', oldValue: props.transaction.description, newValue: null, source: 'manual', + }) extractionStore.deleteTransaction(props.index) await persistAndRecheck() showDeleteRowConfirm.value = false @@ -281,6 +331,15 @@ async function confirmDeleteRow() {
Where: {{ flag.where }}
Why: {{ flag.why }}
What to do: {{ flag.whatToDo }}
+
diff --git a/frontend/src/components/TransactionsTable.vue b/frontend/src/components/TransactionsTable.vue index 63f7f05..099018a 100644 --- a/frontend/src/components/TransactionsTable.vue +++ b/frontend/src/components/TransactionsTable.vue @@ -349,6 +349,30 @@ async function handleRecheck() { } rechecking.value = false } + +// ── Accept workflow (review screen R.5) ────────────────────────────── +// A "Verified" statement needs no review at all - every check already +// passed. Anything else (Needs review/Failed) can still be accepted, +// but only once every row the checks actually flagged has been looked +// at and explicitly acknowledged (TransactionRow.vue's own "Mark as +// checked" toggle) - accepting isn't a way to skip review, it's the +// record that review happened. +const isAccepted = computed(() => Boolean(result.value?.accepted)) +const canAccept = computed(() => result.value && (result.value.status === 'Verified' || extractionStore.allFlagsAcknowledged)) +const accepting = ref(false) + +async function handleAccept() { + if (!canAccept.value || accepting.value) return + accepting.value = true + extractionStore.clearError() + extractionStore.acceptDocument() + try { + await documentsService.updateDocument(extractionStore.activeDocument.pbId, { result: extractionStore.currentResult }) + } catch (e) { + extractionStore.setError('Could not save acceptance: ' + e.message) + } + accepting.value = false +}