From 4764023d87b92fce0b97fbced6698030a47077f5 Mon Sep 17 00:00:00 2001 From: JasonFraser Date: Wed, 14 Oct 2026 21:48:20 -0400 Subject: [PATCH] Add the manual layout mapping screen - the core deliverable of the layout mapper (L.6) New /map-layout route (ManualMappingView.vue): draw a box over each column on the source document, assign it a role, set date format/sign convention/ignored rows, Preview (required before Save) runs the real forced-mapping extraction and shows the first ten rows plus the balance check outcome, Save Mapping persists the mapping + an initial version + the document. A real File can't survive a router navigation, so a new layoutMapperStore holds the one pending file + fingerprint in memory; ExtractorView.vue shows a banner linking to the mapper while one is set. Two real bugs found by actually wiring this up and testing it end to end: useBatchExtraction.js was reading fingerprintHash from the wrong (post-reassignment) response, which never carries that field - would have silently left documents.layoutFingerprintHash unset for every mapping-applied extraction. More consequential: forced-mapping column zones were completely unpadded, so a word landing a fraction of a point past a raw boundary (or a human's own imprecise drag) could silently exclude a whole transaction with no error - fixed with a new _FORCED_ZONE_PADDING in table_extract.py, the same discipline the auto-detected path's own zones already use. Verified end to end against a hand-built synthetic statement (unmatchable gibberish headers, 3 real transaction rows at known coordinates) through the real rebuilt container: Preview correctly extracts all 3 transactions with a passing balance check; Save persists correctly (confirmed on the re-fetched document record, not the create response); a second, independent upload of the identical file then silently auto-applies the saved mapping with zero further input, producing byte-identical results to the manual Preview - the actual proof this feature exists for. measure.py byte-identical throughout; a regression re-run of the earlier Equals Money forced-mapping test confirmed the zone-padding fix changed nothing there. npm run build passes. Co-Authored-By: Claude Sonnet 5 --- CLAUDE.md | 107 ++++- backend/services/extraction/table_extract.py | 28 +- frontend/src/assets/main.css | 71 ++++ .../src/composables/useBatchExtraction.js | 22 +- frontend/src/router/index.js | 14 +- frontend/src/stores/layoutMapperStore.js | 48 +++ frontend/src/views/ExtractorView.vue | 16 + frontend/src/views/ManualMappingView.vue | 386 ++++++++++++++++++ 8 files changed, 681 insertions(+), 11 deletions(-) create mode 100644 frontend/src/stores/layoutMapperStore.js create mode 100644 frontend/src/views/ManualMappingView.vue diff --git a/CLAUDE.md b/CLAUDE.md index 314d653..ade41fc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,7 +31,7 @@ to rough effort: |---|---|---| | **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 (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) | **Pulled forward and in progress as of 2026-10-14** (see "Layout mapper" under Key decisions & lessons) - staged L.1-L.8, full spec scope (§6/§6.1/§9) plus a superuser-review promotion path beyond what's written. L.1 (a modular "layout quirks" tier for mechanical geometric oddities, ahead of the mapper itself) shipped - fixed a real new statement (an Equals Money account) whose header label wrapped across physical lines, plus two more real differences the same statement surfaced (a "$"-prefixed money format, an ISO-shaped date format). L.2 (fingerprinting + the forced-mapping backend contract, no UI/PocketBase yet) shipped - also surfaced and fixed a real gap (a forced mapping had no page-boundary concept, swallowing a cover page's own letterhead into the first transaction; fixed with a new `start_page` field). L.3 (the `layoutMappings`/`layoutMappingVersions` PocketBase schema + the auto-promotion hook) shipped - found and fixed a real rule gap during testing (an owner could self-promote their own mapping to "shared" via a plain update; PocketBase rules gate who can update, not which fields). L.4 (the frontend fingerprint-lookup orchestration, including a real, clickable confirm dialog in `ExtractorView.vue` - not deferred to L.6) shipped - found and fixed two real bugs in the near-match comparator while testing it against the spec's own documented example (per-line vs per-field label text; a 70% overlap threshold that was too strict for that very example, corrected to 50%). L.5 (multi-highlight `SourceDocumentPanel` + a new click-and-drag region tool, `useRegionDraw.js`) shipped - the groundwork L.6's manual mapping screen will build on. L.6-L.8 (the manual mapping screen, the Layouts page, the superuser review screen) not started yet | +| 3 | Layout mapper (fingerprinting, versioning, drift detection) | **Pulled forward and in progress as of 2026-10-14** (see "Layout mapper" under Key decisions & lessons) - staged L.1-L.8, full spec scope (§6/§6.1/§9) plus a superuser-review promotion path beyond what's written. L.1 (a modular "layout quirks" tier for mechanical geometric oddities, ahead of the mapper itself) shipped - fixed a real new statement (an Equals Money account) whose header label wrapped across physical lines, plus two more real differences the same statement surfaced (a "$"-prefixed money format, an ISO-shaped date format). L.2 (fingerprinting + the forced-mapping backend contract, no UI/PocketBase yet) shipped - also surfaced and fixed a real gap (a forced mapping had no page-boundary concept, swallowing a cover page's own letterhead into the first transaction; fixed with a new `start_page` field). L.3 (the `layoutMappings`/`layoutMappingVersions` PocketBase schema + the auto-promotion hook) shipped - found and fixed a real rule gap during testing (an owner could self-promote their own mapping to "shared" via a plain update; PocketBase rules gate who can update, not which fields). L.4 (the frontend fingerprint-lookup orchestration, including a real, clickable confirm dialog in `ExtractorView.vue` - not deferred to L.6) shipped - found and fixed two real bugs in the near-match comparator while testing it against the spec's own documented example (per-line vs per-field label text; a 70% overlap threshold that was too strict for that very example, corrected to 50%). L.5 (multi-highlight `SourceDocumentPanel` + a new click-and-drag region tool, `useRegionDraw.js`) shipped. **L.6 (`ManualMappingView.vue`, the core deliverable) shipped** - the full save-once-apply-forever loop proven end to end against a real synthetic statement; also caught and fixed a real, consequential bug along the way (forced-mapping column zones were unpadded, so a word landing a fraction of a point past a raw boundary - or a human's own imprecise mouse drag - could silently exclude a whole transaction with no error). L.7-L.8 (the Layouts page, drift detection, the superuser review screen) not started yet | | 4 | Multi-tenant practice/client accounts, Frappe data model | Not started | | 5 | Free front door, public accuracy page | Not started | | 6 | Append mode, credit cards, multi-account statements | Not started | @@ -183,7 +183,7 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co in-memory buffer, see below) /extraction — pure parsing/domain logic, no I/O: table_extract.py — the pdfplumber extractor. As of the layout-mapper - work's L.1/L.2 stages (2026-10-14): calls + work's L.1/L.2/L.6 stages (2026-10-14): calls layout_quirks.normalize() as a fallback when the plain single-line header detector finds nothing; _MONEY_RE accepts an optional leading "$"; @@ -191,8 +191,12 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co new; extract_pdf()/extract_page() gained forced_zones/forced_sign_convention/ ignored_row_rules/date_format/start_page params, - all no-ops when omitted — see "Layout mapper" - under Key decisions & lessons + all no-ops when omitted; each forced_zones range + is padded by _FORCED_ZONE_PADDING=3pt before use + (L.6 - a real bug this fixed: an unpadded zone + boundary could silently exclude a word whose own + reported x1 landed a fraction of a point past it) + — see "Layout mapper" under Key decisions & lessons layout_rules.py — shared column/balance keyword vocabulary. As of L.1, also owns the public match_line_fields/ resolve_header_matches (relocated from @@ -463,6 +467,13 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co never expanded) - see "Sidebar's per-project document list didn't update live" under Key decisions & lessons for the real bug this fixed and the full verification record. + layoutMapperStore.js (NEW 2026-10-14, layout mapper L.6) — + holds the ONE statement currently waiting on manual + mapping (`pendingFile`/`pendingFingerprint`/ + `pendingFingerprintHash`) - a real `File` can't survive a + router navigation on its own, so this is the bridge + between `useBatchExtraction.js` (sets it on a `no_match` + result) and `ManualMappingView.vue` (reads/clears it). /repositories — raw HTTP/storage access only: extractionRepository.js (fetch calls to /api/process|recheck|export), localStorageRepository.js (kept for any future per-viewer @@ -603,7 +614,19 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co shell 2026-10-13 — ProjectSidebar is account-wide chrome, not specific to this one page). `App.vue` gates the whole shell behind `authStore.isAuthenticated`, showing `LoginView` - otherwise. + otherwise. As of layout mapper L.6 (2026-10-14), also shows + a small banner (linking to /map-layout) while + layoutMapperStore has a pending file. + /views/ManualMappingView.vue — NEW 2026-10-14, layout mapper L.6 (the core + deliverable of that whole plan) — routed at /map-layout. + SourceDocumentPanel in regionDrawMode beside a field-role + toolbar, date-format/sign-convention/ignored-row controls, + a required Preview step, and Save Mapping - see "Layout + mapper" under Key decisions & lessons for the full record, + including the two real bugs this stage's own end-to-end + testing caught (a stale-reference save-field bug, and a + real forced-zone boundary-precision bug fixed in + table_extract.py itself). ``` **One real bug caught and fixed during this restructure, server-side:** the production `Dockerfile` serves `frontend/dist` from Flask via a catch-all route @@ -2281,6 +2304,80 @@ proven correct by the Node tests above, but seeing it drawn on screen is the user's own check, same standing limitation as every other frontend-only change this session (Claude-in-Chrome still not connected). +**L.6 shipped same day: `ManualMappingView.vue` - the core deliverable of the whole +layout-mapper plan.** A new routed view (`/map-layout`) - `SourceDocumentPanel` in +`regionDrawMode` beside a field-role toolbar (Date/Description/Debit/Credit/Amount/ +Balance - click a role to arm it, drag a box, it claims that role; assigned regions +listed with a remove button each), a date-format selector (`textual`/`dmy`/`mdy`/ +`ymd`), a "this statement's debit column already prints its own minus sign" +checkbox, an ignored-row-rule list, and the familiar opening/closing balance +inputs. **Preview** (required before Save unlocks) calls `/api/process` with the +assembled `forced_mapping` and shows the first ten transactions plus the +statement-balance check's own outcome - shown, never gating, matching the +underlying spec's own "preview before saving." **Save Mapping** creates the +`layoutMappings` record + an initial `layoutMappingVersions` entry, then saves the +document via the existing `documentsService.saveDocument` with its +`layoutMappingUsed`/`layoutMappingVersionUsed`/`layoutApplied`/ +`layoutFingerprintHash` fields set. + +A real `File` object can't survive a router navigation on its own (no way to +serialize one into a route param), so new `frontend/src/stores/ +layoutMapperStore.js` holds exactly ONE pending file + its fingerprint in memory - +deliberately not a queue (see that store's own docstring for why) - set by +`useBatchExtraction.js` whenever `useLayoutMapping.js`'s own `resolveNeedsMapping()` +comes back with `reason: "no_match"`. `ExtractorView.vue` shows a small banner +linking to `/map-layout` while one is pending. + +**Two real bugs found while actually wiring this up and testing it end to end - +not assumed safe from reading the code:** +- `useBatchExtraction.js`'s own `layoutFingerprintHash` save field was reading + `result.fingerprintHash` AFTER `result` had already been reassigned to the + forced-mapping retry's own response - which never carries that field at all + (only the 422 `needs_mapping` response does, from before the retry). Would have + silently left `documents.layoutFingerprintHash` unset for every mapping-applied + extraction, forever. Fixed by capturing it into its own variable before the + reassignment, caught by re-reading the data flow carefully before building L.6 + on top of it, not by a failing test. +- **A more consequential one, found by the first genuine end-to-end Preview + against real synthetic transaction data** (the Equals Money PDF no longer + reaches this screen at all now that L.1's quirks module resolves it - a + deliberately-constructed gibberish-header statement with 3 real transaction rows + was needed to actually exercise this path): a forced mapping's `columnMap` + ranges were used completely unpadded. A word's own reported `x1` landed a + FRACTION OF A POINT past the raw zone boundary (confirmed directly - a value + that looked like `416.1` at a glance was actually `416.14`), silently excluding + an entire transaction from classification with no error at all. This is exactly + the failure mode a human's own imprecise mouse drag would hit even more often + than a float-rounding artifact would - directly the kind of thing the + "never silently exclude data" governing rule exists to catch. Fixed with a new + `table_extract._FORCED_ZONE_PADDING = 3` points applied to every forced zone in + `extract_pdf()` - the same discipline the auto-detected path's own zones already + use (a generous `-80`/`+5` padding there), just a smaller margin here, since + this only needs to absorb imprecision, not "where does the data sit relative to + the header" uncertainty. + +**Verified, all real, end to end - the actual proof this whole stage exists for:** +a hand-built synthetic PDF (gibberish, unmatchable header labels; 3 real +transaction rows with known amounts/balances at known coordinates) confirmed to +genuinely trigger `needs_mapping` through the real pipeline. Driving the REAL +frontend services from Node against the rebuilt container: Preview with a +hand-assembled `forcedMapping` (replicating exactly what the view's own +role-toolbar would produce) correctly extracted all 3 transactions with the right +signs/balances and a passing `running_balance` check; Save created the mapping + +version + a `documents` record whose layout fields were confirmed on the +PERSISTED record (re-fetched, not the create response's own echo); **a second, +completely independent upload of the identical file was then confirmed to +silently auto-apply the saved mapping** via the real `useLayoutMapping +.resolveNeedsMapping()` - the injected confirm callback was never even invoked, +true silent exact-match application - producing byte-identical transactions to +the manual Preview. A direct regression re-run of L.2's own Equals-Money +forced-mapping test confirmed the new zone padding didn't change that +already-correct result. `backend/measure.py` byte-identical throughout; `npm run +build` passes; every new icon class was confirmed present in the installed +FontAwesome set before use. **Not machine-verified:** the actual click-and-drag +interaction, the toolbar's visual behavior, and the banner's own appearance in a +real browser - same standing limitation as every other UI stage this session. + **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 diff --git a/backend/services/extraction/table_extract.py b/backend/services/extraction/table_extract.py index 24f9b42..dc63bf7 100644 --- a/backend/services/extraction/table_extract.py +++ b/backend/services/extraction/table_extract.py @@ -4,6 +4,12 @@ from services.extraction import layout_rules from services.extraction import layout_quirks X_TOLERANCE = 1.5 +# Points each forced_zones range (extract_pdf's own layout-mapper +# argument) is padded outward by before use - see extract_pdf's own +# docstring for the real bug this fixes (a word's reported x1 landing a +# fraction of a point past an unpadded zone boundary, silently excluding +# it) and why a user's own hand-drawn region needs this margin too. +_FORCED_ZONE_PADDING = 3 # Optional leading "$" - confirmed necessary for real on an Equals Money # statement, which prints every amount as "$33.62" rather than the bare # "33.62"/"1,280.25" HSBC/RBC both use. No real statement seen so far @@ -520,10 +526,30 @@ def extract_pdf(pdf_path, forced_zones=None, forced_sign_convention=None, ignore `start_page` are skipped entirely - never classified as narrative OR transaction data, the same as "above this page's own header row" already is for the auto-detected case. + + Each `forced_zones` range is padded outward by + `_FORCED_ZONE_PADDING` points before use - confirmed necessary for + real: a word's own reported x1 can sit a fraction of a point past a + zone's raw, unpadded upper bound (floating-point precision in how + pdfplumber reports word positions, confirmed directly - a value that + LOOKS like 416.1 at a glance is actually 416.14), silently excluding + it from money classification with no error at all - exactly the + "never silently exclude data" governing rule this whole app is built + around, and the realistic case this guards (a user's own hand-drawn + region in the manual mapping screen, L.6, rarely lands exactly on a + glyph's true edge either) is far more consequential than the literal + float-rounding example that first surfaced it. The auto-detected + path already pads its own zones generously for an analogous reason + (`-80`/`+5` on money zones, `-5`/`+15` on text zones in `_find_zones` + above) - this is the same discipline, just a smaller margin, since + this only needs to absorb imprecision, not "where does the real data + sit relative to a header label" uncertainty. """ import pdfplumber result = {} - zones = dict(forced_zones) if forced_zones else None + zones = None + if forced_zones: + zones = {field: (x0 - _FORCED_ZONE_PADDING, x1 + _FORCED_ZONE_PADDING) for field, (x0, x1) in forced_zones.items()} if zones is not None and forced_sign_convention is not None: zones.setdefault("_debit_self_signed", forced_sign_convention.get("debitSelfSigned", True)) with pdfplumber.open(pdf_path) as pdf: diff --git a/frontend/src/assets/main.css b/frontend/src/assets/main.css index 54acc26..f27cea3 100644 --- a/frontend/src/assets/main.css +++ b/frontend/src/assets/main.css @@ -144,6 +144,18 @@ h1{ font-family:var(--fd); font-weight:800; font-size:30px; letter-spacing:-.01e .error-note.visible{ display:block; } .fields-row + .error-note.visible{ margin-bottom:14px; } +/* The layout mapper's own "this statement needs manual mapping" notice + (L.6, 2026-10-14) - the same bordered-notice shape as .error-note, + just blue/informational rather than red/error, since this isn't a + failure the user did anything wrong to cause. */ +.banner{ + display:flex; align-items:center; gap:10px; font-size:12.5px; color:var(--t2); + border-radius:9px; padding:11px 14px; margin-bottom:18px; +} +.banner-info{ background:rgba(37,99,235,.08); border:1px solid var(--border-b); } +.banner-info i{ color:var(--blue); flex-shrink:0; } +.banner span{ flex:1 1 auto; } + .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; @@ -869,6 +881,65 @@ tr.editing td{ background:rgba(37,99,235,.03); } .input-icon-wrap i{ position:absolute; left:11px; top:50%; transform:translateY(-50%); font-size:12px; color:var(--t4); pointer-events:none; } .input-icon-wrap input{ padding-left:34px; } +/* .fields already styles - a