Add review screen R.5: edit log, acknowledge/accept workflow, Excel Edits sheet

Completes the R.1-R.5 review screen plan. editLog/acknowledgedFlags/accepted all
live on the existing result JSON blob, no new PocketBase migration needed. Every
row mutation (manual edit, suggested-fix apply, structural edits) now logs a
field-level edit log entry; flags can be individually acknowledged; a document
can be Accepted once Verified or fully acknowledged; exports gain an optional
Edits sheet when edit_log is non-empty.

Verified: measure.py byte-identical to the pre-R.5 baseline, real curl round trip
through the rebuilt container confirming the Edits sheet appears/omits correctly,
extractionStore's new getters/actions run directly against real Pinia, and
useRowEditing's edit-log capture confirmed against a document actually persisted
on the live PocketBase container.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
JasonFraser 2026-10-13 20:41:13 -04:00
parent 9adf3d8fca
commit 6913d45d20
11 changed files with 357 additions and 12 deletions

106
CLAUDE.md
View File

@ -30,7 +30,7 @@ to rough effort:
| Phase | Contains | Status here | | Phase | Contains | Status here |
|---|---|---| |---|---|---|
| **1** | Extraction + 6 checks + Excel export, dual-engine, measurement harness | **In progress — see gaps below** | | **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 | | 3 | Layout mapper (fingerprinting, versioning, drift detection) | Not started |
| 4 | Multi-tenant practice/client accounts, Frappe data model | Not started | | 4 | Multi-tenant practice/client accounts, Frappe data model | Not started |
| 5 | Free front door, public accuracy page | 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/<filename> route; see dead workbook generation and the never-called /api/download/<filename> route; see
"Excel exports moved to R2" under Key decisions & lessons for the full story). The "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`, 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 - `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 `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 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 (NEW 2026-10-13, review screen R.4 - see that entry under
Key decisions & lessons for the full record, including why Key decisions & lessons for the full record, including why
there's no separate `splitTransaction` action). 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()` uiStore.js — `resultsOpen`/`toggleResultsOpen()`/`closeResultsOpen()`
(renamed from `resultExpanded`/`toggleResultExpanded` - (renamed from `resultExpanded`/`toggleResultExpanded` -
2026-10-13, now drives TransactionsTable's own Results 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 modals, and the resulting table row changes - Claude-in-Chrome still did not connect
this session. 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 **Governing rule: never silently correct or exclude data.** This shows up in several
concrete places, not just as an abstract principle: 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 - 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), 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 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. `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`). - All numeric displays are comma-formatted (`formatService.js`'s `fmtMoney`/`fmtNum`).
- Edits persist to PocketBase (`documentsService.js`'s `saveDocument`/`updateDocument` - - Edits persist to PocketBase (`documentsService.js`'s `saveDocument`/`updateDocument` -
as of 2026-10-13, replacing the earlier localStorage-only version entirely, not as of 2026-10-13, replacing the earlier localStorage-only version entirely, not

View File

@ -104,6 +104,7 @@ def export():
"page_reports": data["page_reports"], "page_reports": data["page_reports"],
"period": data["period"], "period": data["period"],
"brought_forward_balance": data["brought_forward_balance"], "brought_forward_balance": data["brought_forward_balance"],
"edit_log": data["edit_log"],
**check_results, **check_results,
} }
workbook = excel_service.build_workbook(result, title=data["title"]) workbook = excel_service.build_workbook(result, title=data["title"])

View File

@ -61,15 +61,24 @@ def parse_export_request(json_body):
""" """
Validates and extracts the /api/export JSON body - same shape as Validates and extracts the /api/export JSON body - same shape as
parse_recheck_request plus the fields the exported workbook itself parse_recheck_request plus the fields the exported workbook itself
needs (brought_forward_balance, title). needs (brought_forward_balance, title, edit_log).
Data flow: Data flow:
json_body (dict) - the request's parsed JSON (or {} if absent/invalid) json_body (dict) - the request's parsed JSON (or {} if absent/invalid)
returns (dict) - parse_recheck_request's fields plus 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 {} data = json_body or {}
parsed = parse_recheck_request(data) parsed = parse_recheck_request(data)
parsed["brought_forward_balance"] = data.get("brought_forward_balance") parsed["brought_forward_balance"] = data.get("brought_forward_balance")
parsed["title"] = data.get("title") or "Statement Extraction" parsed["title"] = data.get("title") or "Statement Extraction"
parsed["edit_log"] = data.get("edit_log") or []
return parsed return parsed

View File

@ -93,4 +93,34 @@ def build_workbook(result, title="Statement Extraction"):
_write_cell(ws2, r, 2, f"{c['outcome']}: {c['detail']}") _write_cell(ws2, r, 2, f"{c['outcome']}: {c['detail']}")
r += 1 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 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

View File

@ -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{ font-size:11.5px; padding:0 12px; height:30px; }
.flag-show-source:disabled{ opacity:.4; cursor:not-allowed; } .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) - /* suggested_fixes_service.py's own one-click fixes (review screen R.3) -
never applied automatically, always a deliberate "Apply fix" click never applied automatically, always a deliberate "Apply fix" click
against the evidence text shown right above it. */ 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); padding-bottom:12px; margin-bottom:14px; border-bottom:1px solid var(--border-2);
flex-shrink:0; flex-shrink:0;
} }
.txn-top-bar-right{ display:flex; align-items:center; gap:8px; justify-self:end; }
.txn-download-btn{ 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-trigger-wrap{ position:relative; justify-self:start; }
.results-toggle{ .results-toggle{
@ -578,7 +593,8 @@ tr.editing td{ background:rgba(37,99,235,.03); }
@container txncol (max-width: 620px){ @container txncol (max-width: 620px){
.txn-top-bar{ grid-template-columns:1fr; justify-items:stretch; gap:10px; } .txn-top-bar{ grid-template-columns:1fr; justify-items:stretch; gap:10px; }
.results-trigger-wrap, .doc-nav{ justify-self:center; } .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; } .login-page{ min-height:100vh; display:flex; align-items:center; justify-content:center; padding:24px; }

View File

@ -23,6 +23,15 @@
* already uses (useRowEditing.js), so there's one path for "a value on * already uses (useRowEditing.js), so there's one path for "a value on
* this row changed," not two that could quietly diverge. * 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 * Also hosts the structural row edits (review screen R.4) behind a
* "more actions" menu - flip debit/credit, insert a row (for one the * "more actions" menu - flip debit/credit, insert a row (for one the
* extractor genuinely missed), split this row (duplicate + divide * extractor genuinely missed), split this row (duplicate + divide
@ -134,7 +143,12 @@ async function persistAndRecheck() {
async function applySuggestedFix() { async function applySuggestedFix() {
if (!suggestion.value || applyingFix.value) return if (!suggestion.value || applyingFix.value) return
applyingFix.value = true 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() await persistAndRecheck()
applyingFix.value = false applyingFix.value = false
} }
@ -152,7 +166,11 @@ function closeRowMenu() {
async function handleFlipSign() { async function handleFlipSign() {
closeRowMenu() closeRowMenu()
busy.value = true busy.value = true
const oldValue = props.transaction.amount
extractionStore.flipTransactionSign(props.index) extractionStore.flipTransactionSign(props.index)
extractionStore.appendEditLogEntry({
index: props.index, field: 'amount', oldValue, newValue: extractionStore.currentResult.transactions[props.index]?.amount, source: 'manual',
})
await persistAndRecheck() await persistAndRecheck()
busy.value = false busy.value = false
} }
@ -162,6 +180,9 @@ async function handleInsertAfter() {
closeRowMenu() closeRowMenu()
busy.value = true busy.value = true
extractionStore.insertTransactionAfter(props.index) extractionStore.insertTransactionAfter(props.index)
extractionStore.appendEditLogEntry({
index: props.index + 1, field: '_row_inserted', oldValue: null, newValue: null, source: 'manual',
})
await persistAndRecheck() await persistAndRecheck()
busy.value = false busy.value = false
} }
@ -171,6 +192,9 @@ async function handleSplit() {
closeRowMenu() closeRowMenu()
busy.value = true busy.value = true
extractionStore.insertTransactionAfter(props.index, { ...props.transaction }) extractionStore.insertTransactionAfter(props.index, { ...props.transaction })
extractionStore.appendEditLogEntry({
index: props.index + 1, field: '_row_split', oldValue: null, newValue: null, source: 'manual',
})
await persistAndRecheck() await persistAndRecheck()
busy.value = false busy.value = false
} }
@ -183,11 +207,34 @@ function requestMerge() {
async function confirmMerge() { async function confirmMerge() {
busy.value = true busy.value = true
extractionStore.mergeWithNext(props.index) extractionStore.mergeWithNext(props.index)
extractionStore.appendEditLogEntry({
index: props.index, field: '_rows_merged', oldValue: props.index + 1, newValue: null, source: 'manual',
})
await persistAndRecheck() await persistAndRecheck()
showMergeConfirm.value = false showMergeConfirm.value = false
busy.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) const showDeleteRowConfirm = ref(false)
function requestDeleteRow() { function requestDeleteRow() {
closeRowMenu() closeRowMenu()
@ -195,6 +242,9 @@ function requestDeleteRow() {
} }
async function confirmDeleteRow() { async function confirmDeleteRow() {
busy.value = true busy.value = true
extractionStore.appendEditLogEntry({
index: props.index, field: '_row_deleted', oldValue: props.transaction.description, newValue: null, source: 'manual',
})
extractionStore.deleteTransaction(props.index) extractionStore.deleteTransaction(props.index)
await persistAndRecheck() await persistAndRecheck()
showDeleteRowConfirm.value = false showDeleteRowConfirm.value = false
@ -281,6 +331,15 @@ async function confirmDeleteRow() {
<div class="flag-detail-part"><strong>Where:</strong> {{ flag.where }}</div> <div class="flag-detail-part"><strong>Where:</strong> {{ flag.where }}</div>
<div class="flag-detail-part"><strong>Why:</strong> {{ flag.why }}</div> <div class="flag-detail-part"><strong>Why:</strong> {{ flag.why }}</div>
<div class="flag-detail-part"><strong>What to do:</strong> {{ flag.whatToDo }}</div> <div class="flag-detail-part"><strong>What to do:</strong> {{ flag.whatToDo }}</div>
<button
type="button"
class="btn-toggle flag-acknowledge"
:class="{ active: isAcknowledged(flag.checkName) }"
@click="toggleAcknowledge(flag.checkName)"
>
<i class="fa-solid" :class="isAcknowledged(flag.checkName) ? 'fa-check-double' : 'fa-check'"></i>
{{ isAcknowledged(flag.checkName) ? 'Acknowledged' : 'Mark as checked' }}
</button>
</div> </div>
<div v-if="suggestion" class="suggested-fix"> <div v-if="suggestion" class="suggested-fix">

View File

@ -349,6 +349,30 @@ async function handleRecheck() {
} }
rechecking.value = false 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
}
</script> </script>
<template> <template>
@ -384,10 +408,23 @@ async function handleRecheck() {
<DocumentNavBar /> <DocumentNavBar />
<button type="button" class="btn-toggle txn-download-btn" :disabled="!result || downloading" @click="handleDownloadClick"> <div class="txn-top-bar-right">
<i class="fa-solid" :class="downloading ? 'fa-spinner fa-spin' : 'fa-file-excel'"></i> <button
{{ downloading ? 'Preparing…' : 'Download' }} type="button"
</button> class="btn-toggle txn-accept-btn"
:class="{ 'btn-toggle-active': isAccepted }"
:disabled="!result || accepting || (!canAccept && !isAccepted)"
:title="canAccept || isAccepted ? '' : 'Acknowledge every flagged row before accepting'"
@click="handleAccept"
>
<i class="fa-solid" :class="accepting ? 'fa-spinner fa-spin' : 'fa-circle-check'"></i>
{{ isAccepted ? 'Accepted' : 'Accept' }}
</button>
<button type="button" class="btn-toggle txn-download-btn" :disabled="!result || downloading" @click="handleDownloadClick">
<i class="fa-solid" :class="downloading ? 'fa-spinner fa-spin' : 'fa-file-excel'"></i>
{{ downloading ? 'Preparing…' : 'Download' }}
</button>
</div>
</div> </div>
<DownloadChoiceModal <DownloadChoiceModal
:visible="showDownloadChoice" :visible="showDownloadChoice"

View File

@ -52,13 +52,22 @@ export function useRowEditing(index) {
* server-side to keep the export consistent with saved edits. * server-side to keep the export consistent with saved edits.
*/ */
async function saveEdit() { async function saveEdit() {
extractionStore.saveRowEdit(index, { const before = extractionStore.currentResult.transactions[index]
const after = {
date: draft.date, date: draft.date,
description: draft.description, description: draft.description,
amount: parseNum(draft.amount), amount: parseNum(draft.amount),
balance: parseNum(draft.balance), balance: parseNum(draft.balance),
status: draft.status, status: draft.status,
}) }
for (const field of Object.keys(after)) {
if (before[field] !== after[field]) {
extractionStore.appendEditLogEntry({
index, field, oldValue: before[field], newValue: after[field], source: 'manual',
})
}
}
extractionStore.saveRowEdit(index, after)
wasEdited.value = true wasEdited.value = true
isEditing.value = false isEditing.value = false
try { try {

View File

@ -56,6 +56,10 @@ export async function exportWorkbook(result, openingBalance, closingBalance) {
...recheckPayload(result, openingBalance, closingBalance), ...recheckPayload(result, openingBalance, closingBalance),
brought_forward_balance: result.brought_forward_balance, brought_forward_balance: result.brought_forward_balance,
title: result.title, title: result.title,
// Optional - excel_service.py only writes an "Edits" sheet when
// this is non-empty (see CLAUDE.md's "R.5" entry), so a statement
// with no edits doesn't gain an empty sheet nobody asked for.
edit_log: result.editLog || [],
} }
return extractionRepository.exportStatement(payload) return extractionRepository.exportStatement(payload)
} }

View File

@ -109,6 +109,9 @@ const BUILDERS = {
narrative_direction: narrativeDirectionFlag, narrative_direction: narrativeDirectionFlag,
} }
/** The only checks that ever flag an individual row - exported so extractionStore.js's own "has everything been acknowledged" logic (R.5) doesn't keep a second, driftable copy of this same list. */
export const ROW_FLAG_CHECK_NAMES = Object.keys(BUILDERS)
/** /**
* Every flag for a given transaction index, across all four row-flagging * Every flag for a given transaction index, across all four row-flagging
* checks - a row can carry more than one (e.g. a bad date AND a broken * checks - a row can carry more than one (e.g. a bad date AND a broken

View File

@ -15,6 +15,7 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { parseNum } from '../services/formatService' import { parseNum } from '../services/formatService'
import { effectiveBalance } from '../services/extractionService' import { effectiveBalance } from '../services/extractionService'
import { ROW_FLAG_CHECK_NAMES } from '../services/flagCatalogService'
/** /**
* Flagged transaction indexes for a given result - every check's own * Flagged transaction indexes for a given result - every check's own
@ -100,6 +101,36 @@ export const useExtractionStore = defineStore('extraction', {
const doc = state.documents[state.activeIndex] const doc = state.documents[state.activeIndex]
return doc ? doc.closingBalanceInput : state.pendingClosingBalance return doc ? doc.closingBalanceInput : state.pendingClosingBalance
}, },
/** Whether the active document's flag at (checkName, index) has been acknowledged. */
flagAcknowledged(state) {
return (checkName, index) => {
const doc = state.documents[state.activeIndex]
return Boolean(doc?.result?.acknowledgedFlags?.[checkName]?.[index])
}
},
/**
* Whether every currently-flagged row has an acknowledgedFlags entry
* for EVERY row-flagging check it's actually flagged under - not just
* "has at least one acknowledgement." Walks the same four row-level
* checks flagCatalogService.js's own ROW_FLAG_CHECK_NAMES names
* (imported rather than re-listed, so this can't silently drift from
* that file if a check is ever added/removed there), so a row flagged
* by two different checks needs both acknowledged, not just one.
* True (vacuously) when there's nothing flagged at all.
*/
allFlagsAcknowledged(state) {
const doc = state.documents[state.activeIndex]
if (!doc?.result) return true
const acked = doc.result.acknowledgedFlags || {}
for (const check of doc.result.checks || []) {
if (!ROW_FLAG_CHECK_NAMES.includes(check.name)) continue
for (const item of check.mismatches || check.issues || []) {
if (item.index === undefined) continue
if (!acked[check.name]?.[item.index]) return false
}
}
return true
},
}, },
actions: { actions: {
/** /**
@ -195,6 +226,50 @@ export const useExtractionStore = defineStore('extraction', {
Object.assign(doc.result.transactions[idx], fields) Object.assign(doc.result.transactions[idx], fields)
}, },
// ── Edit log + acknowledge/accept workflow (review screen R.5) ────
// `editLog`/`acknowledgedFlags`/`accepted`/`acceptedAt` all live
// directly on doc.result - the same arbitrary JSON blob
// documentsService.updateDocument already PATCHes wholesale, so none
// of this needed a new PocketBase migration.
/**
* Appends one entry to the active document's edit log - every
* mutation site (manual cell edit, suggested-fix apply, and every
* R.4 structural action) calls this once per changed field, so a
* single "merge with next" that changes description+amount+balance
* logs three entries, not one undifferentiated "row changed" blob.
*/
appendEditLogEntry(entry) {
const doc = this.activeDocument
if (!doc) return
if (!doc.result.editLog) doc.result.editLog = []
doc.result.editLog.push({ ...entry, at: new Date().toISOString() })
},
/** Marks a flag at (checkName, index) as reviewed - doesn't change the underlying data, just records that a human looked at it. */
acknowledgeFlag(checkName, index, note = '') {
const doc = this.activeDocument
if (!doc) return
if (!doc.result.acknowledgedFlags) doc.result.acknowledgedFlags = {}
if (!doc.result.acknowledgedFlags[checkName]) doc.result.acknowledgedFlags[checkName] = {}
doc.result.acknowledgedFlags[checkName][index] = { note, checkedAt: new Date().toISOString() }
},
/** Reverses acknowledgeFlag - e.g. the user realizes they need to look again. */
unacknowledgeFlag(checkName, index) {
const doc = this.activeDocument
if (!doc?.result?.acknowledgedFlags?.[checkName]) return
delete doc.result.acknowledgedFlags[checkName][index]
},
/** Marks the active document as accepted - gated in the UI (TransactionsTable.vue) on status==="Verified" or allFlagsAcknowledged, not enforced here (the store trusts its caller, same as every other action). */
acceptDocument() {
const doc = this.activeDocument
if (!doc) return
doc.result.accepted = true
doc.result.acceptedAt = new Date().toISOString()
},
// ── Structural row edits (review screen R.4) ────────────────────── // ── Structural row edits (review screen R.4) ──────────────────────
// Each one mutates currentResult.transactions only - TransactionRow.vue // Each one mutates currentResult.transactions only - TransactionRow.vue
// is the one place that calls these, always followed by the same // is the one place that calls these, always followed by the same