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 <noreply@anthropic.com>
This commit is contained in:
JasonFraser 2026-10-14 21:48:20 -04:00
parent 6e0d33510d
commit 4764023d87
8 changed files with 681 additions and 11 deletions

107
CLAUDE.md
View File

@ -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

View File

@ -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:

View File

@ -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 <input> - a <select> (ManualMappingView's own
date-format picker) needs the identical box so the two don't look
inconsistent sitting in the same row. */
.fields select{
width:100%; height:36px; padding:0 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; cursor:pointer;
}
.fields select:focus{ border-color:var(--blue); }
/* ManualMappingView.vue (layout mapper L.6) - source document beside a
stack of toolbar cards (roles, format, preview, save), the same
side-by-side spirit as the main extractor's own ResizablePanels but
without a drag-resizer - this page has no reason to let the user
resize it, so a plain flex split is simpler. */
.mapper-grid{ display:flex; gap:20px; align-items:flex-start; }
.mapper-source-card{ flex:0 0 52%; min-width:320px; display:flex; flex-direction:column; height:88vh; position:sticky; top:24px; }
.mapper-toolbar{ flex:1 1 auto; min-width:0; display:flex; flex-direction:column; }
.mapper-toolbar .card:last-child{ margin-bottom:0; }
.mapper-role-grid{ display:flex; flex-wrap:wrap; gap:8px; margin-bottom:10px; }
.mapper-role-btn{
display:inline-flex; align-items:center; gap:7px; background:var(--navy); border:1px solid var(--border-2);
color:var(--t2); font-family:var(--fb); font-size:12.5px; padding:8px 13px; border-radius:8px;
cursor:pointer; transition:all .15s;
}
.mapper-role-btn:hover{ border-color:var(--role-color); color:var(--role-color); }
.mapper-role-btn.active{ background:var(--role-color); border-color:var(--role-color); color:#fff; }
.mapper-role-btn.assigned:not(.active){ border-color:var(--role-color); color:var(--role-color); }
.mapper-role-btn.assigned:not(.active) i{ color:var(--role-color); }
.mapper-assigned-list{ list-style:none; margin:10px 0 0; padding:0; display:flex; flex-direction:column; gap:6px; }
.mapper-assigned-list li{
display:flex; align-items:center; gap:8px; background:var(--navy); border:1px solid var(--border-2);
border-radius:7px; padding:7px 8px 7px 11px; font-size:12.5px; color:var(--t1);
}
.mapper-assigned-dot{ width:9px; height:9px; border-radius:50%; flex-shrink:0; }
.mapper-checkbox-row{
display:flex; align-items:center; gap:8px; font-size:12.5px; color:var(--t2);
margin:14px 0 18px; cursor:pointer;
}
.mapper-checkbox-row input{ width:auto; height:auto; }
.mapper-ignore-add{ display:flex; gap:8px; margin-top:6px; }
.mapper-ignore-add input{
flex:1 1 auto; height:36px; padding:0 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;
}
.mapper-ignore-add input:focus{ border-color:var(--blue); }
.mapper-ignore-add .btn{ padding:0 14px; }
.mapper-save-actions{ display:flex; gap:10px; justify-content:flex-end; }
@media (max-width:980px){
.mapper-grid{ flex-direction:column; }
.mapper-source-card{ flex:1 1 auto; width:100%; height:70vh; position:static; }
}
@media (max-width:860px){
.app-body{ flex-direction:column; }
.app-sidebar{ position:static; width:100%; height:auto; border-right:none; border-bottom:1px solid var(--border); }

View File

@ -10,6 +10,7 @@
import { useExtractionStore } from '../stores/extractionStore'
import { useUiStore } from '../stores/uiStore'
import { useProjectsStore } from '../stores/projectsStore'
import { useLayoutMapperStore } from '../stores/layoutMapperStore'
import * as extractionService from '../services/extractionService'
import * as documentsService from '../services/documentsService'
import * as layoutMappingsService from '../services/layoutMappingsService'
@ -35,6 +36,7 @@ export function useBatchExtraction(confirmMappingFn) {
const extractionStore = useExtractionStore()
const uiStore = useUiStore()
const projectsStore = useProjectsStore()
const layoutMapperStore = useLayoutMapperStore()
const { isProcessing, phaseText, start, stop } = useProcessingPhases()
const { resolveNeedsMapping } = useLayoutMapping(confirmMappingFn)
@ -62,6 +64,16 @@ export function useBatchExtraction(confirmMappingFn) {
try {
let result = await extractionService.process(file, openingBalance, closingBalance)
let usedMapping = null
// Captured from the FIRST (needs_mapping) response, before
// `result` is overwritten below - a successful forced-mapping
// retry's own response is a normal pipeline result, which never
// carries fingerprintHash at all (that field only exists on the
// 422 needs_mapping response). Found this by re-reading the
// code, not by it failing a test: the line below used to read
// `result.fingerprintHash` AFTER the reassignment, which would
// always have been undefined - documents.layoutFingerprintHash
// would have silently never been set for an applied mapping.
let usedFingerprintHash = null
// Layout mapper work: neither the keyword detector nor the
// layout_quirks fallback could resolve this statement's columns
@ -71,10 +83,16 @@ export function useBatchExtraction(confirmMappingFn) {
if (result.needs_mapping) {
const resolved = await resolveNeedsMapping({ fingerprint: result.fingerprint, fingerprintHash: result.fingerprintHash })
if (resolved.applied) {
usedFingerprintHash = result.fingerprintHash
result = await extractionService.process(file, openingBalance, closingBalance, resolved.forcedMapping)
usedMapping = resolved.mapping
} else if (resolved.reason === 'no_match') {
result = { error: "This statement's layout isn't recognized yet and needs manual mapping (not available yet)." }
// The manual mapping screen's own entry point (layout mapper
// L.6) - held in layoutMapperStore since a real File can't
// survive a router navigation on its own; ExtractorView.vue
// shows a banner linking to /map-layout while this is set.
layoutMapperStore.setPending(file, resolved.fingerprint, resolved.fingerprintHash)
result = { error: `This statement's layout isn't recognized yet - map it from the banner above to continue.` }
} else {
result = { error: 'Mapping declined - extraction skipped for this file.' }
}
@ -100,7 +118,7 @@ export function useBatchExtraction(confirmMappingFn) {
layoutMappingUsed: usedMapping?.id,
layoutMappingVersionUsed: usedMapping?.version,
layoutApplied: usedMapping ? 'mapping' : 'auto',
layoutFingerprintHash: usedMapping ? result.fingerprintHash : undefined,
layoutFingerprintHash: usedMapping ? usedFingerprintHash : undefined,
})
// A mapping that was actually applied gets its usage recorded
// for drift detection regardless of whether the save above

View File

@ -1,9 +1,17 @@
// A single route today - kept as a real router (not inlined) per the
// standards doc's structure, so a second view doesn't need a rewrite.
// Kept as a real router (not inlined) per the standards doc's structure.
import { createRouter, createWebHistory } from 'vue-router'
import ExtractorView from '../views/ExtractorView.vue'
import ManualMappingView from '../views/ManualMappingView.vue'
export default createRouter({
history: createWebHistory(),
routes: [{ path: '/', name: 'extractor', component: ExtractorView }],
routes: [
{ path: '/', name: 'extractor', component: ExtractorView },
// Layout mapper work (L.6) - the manual mapping screen, reached via
// the banner ExtractorView.vue shows while layoutMapperStore has a
// pending file (set by useBatchExtraction.js when neither the
// keyword detector, layout_quirks, nor any stored mapping could
// resolve a statement's columns).
{ path: '/map-layout', name: 'map-layout', component: ManualMappingView },
],
})

View File

@ -0,0 +1,48 @@
/**
* Holds the ONE statement currently waiting on manual layout mapping -
* set by useBatchExtraction.js when useLayoutMapping.js's own
* resolveNeedsMapping() comes back with reason: "no_match" (neither the
* keyword detector, layout_quirks, nor any stored mapping could resolve
* this statement's columns). A real `File` object can't survive a
* router navigation on its own (there's no way to serialize one into a
* route param/query string), so it's held here in memory instead -
* ExtractorView.vue shows a small banner linking to /map-layout while
* this is set; ManualMappingView.vue reads it on mount and clears it
* once the mapping is saved (or the user navigates away).
*
* Deliberately holds only ONE pending file at a time, not a queue - a
* batch upload can still produce more than one "needs mapping" file,
* but mapping them one at a time (the second only reachable after the
* first is saved or dismissed) is the simpler, honest v1 behavior
* rather than building a queue UI nobody asked for yet. A second
* needs-mapping file in the same batch simply overwrites this (the
* earlier one's own extraction attempt already failed and was reported
* in the batch's own failure list - it isn't lost, just not
* auto-queued here).
*/
import { defineStore } from 'pinia'
export const useLayoutMapperStore = defineStore('layoutMapper', {
state: () => ({
pendingFile: null,
pendingFingerprint: null,
pendingFingerprintHash: null,
}),
getters: {
hasPending(state) {
return !!state.pendingFile
},
},
actions: {
setPending(file, fingerprint, fingerprintHash) {
this.pendingFile = file
this.pendingFingerprint = fingerprint
this.pendingFingerprintHash = fingerprintHash
},
clearPending() {
this.pendingFile = null
this.pendingFingerprint = null
this.pendingFingerprintHash = null
},
},
})

View File

@ -12,6 +12,7 @@ import { computed, onMounted, ref, watch } from 'vue'
import { useExtractionStore } from '../stores/extractionStore'
import { useProjectsStore } from '../stores/projectsStore'
import { useUiStore } from '../stores/uiStore'
import { useLayoutMapperStore } from '../stores/layoutMapperStore'
import { useFileUpload } from '../composables/useFileUpload'
import { useBatchExtraction } from '../composables/useBatchExtraction'
import { useDocuments } from '../composables/useDocuments'
@ -24,6 +25,7 @@ import ConfirmModal from '../components/ConfirmModal.vue'
const extractionStore = useExtractionStore()
const projectsStore = useProjectsStore()
const uiStore = useUiStore()
const layoutMapperStore = useLayoutMapperStore()
// Bridges TransactionRow.vue's "Show on source" request (uiStore.
// highlightRequest - see that store's own comment on why a store, not a
@ -120,6 +122,20 @@ onMounted(async () => {
@extract="handleExtract"
/>
<!--
Layout mapper work (L.6) - shown whenever useBatchExtraction.js
couldn't resolve a statement's columns at all (not even a stored
mapping matched) - layoutMapperStore holds that one file + its
fingerprint in memory until the user either maps it or picks a
different file, since a real File object can't survive a router
navigation on its own.
-->
<div v-if="layoutMapperStore.hasPending" class="banner banner-info">
<i class="fa-solid fa-table-cells-large"></i>
<span>"{{ layoutMapperStore.pendingFile.name }}" has a layout this app doesn't recognize yet.</span>
<RouterLink to="/map-layout" class="btn btn-primary">Map it now</RouterLink>
</div>
<ConfirmModal
:visible="!!pendingMappingConfirm"
title="Layout changed?"

View File

@ -0,0 +1,386 @@
<script setup>
/**
* ManualMappingView.vue
*
* The layout mapper's last resort (L.6) - reached only when NONE of the
* earlier tiers could resolve a statement's columns: not the keyword/
* geometry auto-detector, not the layout_quirks fallback, and not any
* stored mapping (exact or near match - see useLayoutMapping.js). The
* user assigns each column region by hand, once; the result is saved
* as a new, initially-private layoutMappings record that tier 3 (the
* fingerprint lookup) picks up automatically from then on - for this
* user immediately, for others once it's promoted to shared (see
* CLAUDE.md's "Layout mapper" entry for the full four-tier pipeline).
*
* Reads the pending file + its computed fingerprint from
* layoutMapperStore (a real File can't survive a router navigation on
* its own - see that store's own docstring) - if nothing is pending
* (a direct visit, or a page refresh), shows a plain "nothing to map"
* state rather than erroring.
*
* Flow: arm a field role, drag a box on the source document (only the
* box's own LEFT/RIGHT edges matter - table_extract.py's forced_zones
* are plain x-ranges applied to every row, not per-page bboxes), repeat
* for every needed column. Preview (required before Save is enabled)
* calls /api/process with the assembled forced_mapping and shows the
* first ten rows plus the statement-balance check outcome (shown, not
* gating - matches the underlying spec's own "preview before saving").
* Save Mapping creates the layoutMappings + an initial
* layoutMappingVersions record, saves the document via the existing
* documentsService.saveDocument, and returns to the extractor.
*/
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useExtractionStore } from '../stores/extractionStore'
import { useProjectsStore } from '../stores/projectsStore'
import { useLayoutMapperStore } from '../stores/layoutMapperStore'
import * as extractionService from '../services/extractionService'
import * as documentsService from '../services/documentsService'
import * as layoutMappingsService from '../services/layoutMappingsService'
import SourceDocumentPanel from '../components/SourceDocumentPanel.vue'
const IMAGE_FILE_RE = /\.(jpe?g|png)$/i
const router = useRouter()
const extractionStore = useExtractionStore()
const projectsStore = useProjectsStore()
const layoutMapperStore = useLayoutMapperStore()
const pendingFile = layoutMapperStore.pendingFile
const previewUrl = pendingFile ? URL.createObjectURL(pendingFile) : null
const isImage = pendingFile ? IMAGE_FILE_RE.test(pendingFile.name) : false
onBeforeUnmount(() => {
if (previewUrl) URL.revokeObjectURL(previewUrl)
})
const sourcePanelRef = ref(null)
// ── Field-role toolbar: arm a role, drag a box, it claims that role ──
const ROLES = [
{ key: 'date', label: 'Date', color: '#2563EB' },
{ key: 'description', label: 'Description', color: '#7C3AED' },
{ key: 'debit', label: 'Debit', color: '#DC2626' },
{ key: 'credit', label: 'Credit', color: '#16A34A' },
{ key: 'amount', label: 'Amount (single column)', color: '#D97706' },
{ key: 'balance', label: 'Balance', color: '#0891B2' },
]
const armedRole = ref(null)
const regions = ref([]) // [{role, page, bbox}]
function armRole(key) {
armedRole.value = armedRole.value === key ? null : key
}
function handleRegionDrawn({ page, bbox }) {
if (!armedRole.value) return
// One box per role, matching columnMap's own one-zone-per-field shape -
// drawing a new box for an already-assigned role replaces it rather
// than adding a second, conflicting zone.
regions.value = regions.value.filter((r) => r.role !== armedRole.value)
regions.value.push({ role: armedRole.value, page, bbox })
armedRole.value = null
markPreviewStale()
}
function removeRegion(role) {
regions.value = regions.value.filter((r) => r.role !== role)
markPreviewStale()
}
function roleMeta(key) {
return ROLES.find((r) => r.key === key)
}
const highlightBoxes = computed(() => regions.value.map((r) => ({
page: r.page, bbox: r.bbox, label: roleMeta(r.role)?.label, color: roleMeta(r.role)?.color,
})))
watch(highlightBoxes, (boxes) => sourcePanelRef.value?.showHighlights(boxes), { deep: true })
// ── Date format / sign convention / ignored rows ─────────────────────
const dateFormat = ref('textual')
const debitSelfSigned = ref(false)
const ignoredRowRules = ref([])
const newIgnoredRule = ref('')
function addIgnoredRule() {
const v = newIgnoredRule.value.trim()
if (!v) return
ignoredRowRules.value.push(v)
newIgnoredRule.value = ''
markPreviewStale()
}
function removeIgnoredRule(i) {
ignoredRowRules.value.splice(i, 1)
markPreviewStale()
}
const openingBalanceInput = ref('')
const closingBalanceInput = ref('')
// ── Assembling the forced_mapping the backend actually understands ──
const columnMap = computed(() => {
const map = {}
for (const r of regions.value) map[r.role] = [r.bbox.x0, r.bbox.x1]
return map
})
/** Same shape layout_rules.has_required_shape checks server-side - mirrored here only for an early, round-trip-free "Preview" disable, not duplicated validation logic. */
const hasRequiredShape = computed(() => {
const map = columnMap.value
if (!('date' in map) || !('balance' in map)) return false
return 'amount' in map || ('debit' in map && 'credit' in map)
})
const forcedMapping = computed(() => ({
columnMap: columnMap.value,
signConvention: { debitSelfSigned: debitSelfSigned.value },
ignoredRowRules: ignoredRowRules.value,
dateFormat: dateFormat.value,
// The table_extract.py gap this closes: a forced mapping has no
// per-page header_top of its own to anchor the usual "skip anything
// above the header" preamble filter against (see CLAUDE.md's "Layout
// mapper" L.2 entry - a real cover-page bug this fixed). Inferred as
// the earliest page the user actually drew a region on, since that's
// presumably where the real table starts; defaults to 1 for an image
// upload (no page concept at all).
startPage: regions.value.length ? Math.min(...regions.value.map((r) => r.page || 1)) : 1,
}))
// ── Preview ──────────────────────────────────────────────────────────
const previewResult = ref(null)
const previewError = ref('')
const previewing = ref(false)
const previewStale = ref(true)
function markPreviewStale() {
previewStale.value = true
}
async function handlePreview() {
if (!pendingFile || !hasRequiredShape.value || previewing.value) return
previewing.value = true
previewError.value = ''
try {
const result = await extractionService.process(pendingFile, openingBalanceInput.value, closingBalanceInput.value, forcedMapping.value)
if (result.error) {
previewError.value = result.error
previewResult.value = null
} else {
previewResult.value = result
previewStale.value = false
}
} catch (e) {
previewError.value = 'Network error: ' + e.message
previewResult.value = null
}
previewing.value = false
}
const previewRows = computed(() => previewResult.value?.transactions?.slice(0, 10) || [])
const previewBalanceCheck = computed(() => previewResult.value?.checks?.find((c) => c.name === 'statement_balance'))
// ── Save Mapping ───────────────────────────────────────────────────
const mappingName = ref('')
const saving = ref(false)
const saveError = ref('')
async function handleSaveMapping() {
if (!pendingFile || !previewResult.value || previewStale.value || saving.value) return
saving.value = true
saveError.value = ''
try {
const mapping = await layoutMappingsService.createMapping({
name: mappingName.value.trim() || pendingFile.name,
fingerprint: layoutMapperStore.pendingFingerprint,
fingerprintHash: layoutMapperStore.pendingFingerprintHash,
columnMap: columnMap.value,
dateFormat: dateFormat.value,
signConvention: { debitSelfSigned: debitSelfSigned.value },
ignoredRowRules: ignoredRowRules.value,
})
await layoutMappingsService.createVersion(mapping.id, {
versionNumber: mapping.version,
columnMap: mapping.columnMap,
dateFormat: mapping.dateFormat,
signConvention: mapping.signConvention,
ignoredRowRules: mapping.ignoredRowRules,
source: 'user',
})
const docKey = extractionService.docKeyFor(pendingFile)
const record = await documentsService.saveDocument({
docKey, fileName: pendingFile.name, sourceFile: pendingFile, result: previewResult.value,
project: projectsStore.activeProjectId,
openingBalanceInput: openingBalanceInput.value, closingBalanceInput: closingBalanceInput.value,
layoutMappingUsed: mapping.id,
layoutMappingVersionUsed: mapping.version,
layoutApplied: 'mapping',
layoutFingerprintHash: layoutMapperStore.pendingFingerprintHash,
})
projectsStore.addDocumentToCache(record.project, record)
extractionStore.addDocument({
pbId: record.id, docKey, fileName: pendingFile.name, project: record.project,
previewUrl: URL.createObjectURL(pendingFile), isImage,
result: previewResult.value,
openingBalanceInput: openingBalanceInput.value, closingBalanceInput: closingBalanceInput.value,
})
layoutMapperStore.clearPending()
router.push('/')
} catch (e) {
saveError.value = 'Could not save this mapping: ' + e.message
}
saving.value = false
}
function cancelMapping() {
layoutMapperStore.clearPending()
router.push('/')
}
</script>
<template>
<div class="eyebrow">Layout mapper</div>
<h1>Map this statement's columns</h1>
<div class="sub">
This statement's layout isn't recognized yet. Draw a box over each column on the source
document and assign it a role - only the box's left/right edges matter, its height doesn't.
Once saved, this mapping applies automatically to this statement's layout from now on.
</div>
<div v-if="!pendingFile" class="card">
<p class="note">Nothing is waiting to be mapped right now.</p>
<RouterLink to="/" class="btn btn-ghost">Back to the extractor</RouterLink>
</div>
<div v-else class="mapper-grid">
<div class="card mapper-source-card">
<SourceDocumentPanel
ref="sourcePanelRef"
:preview-url="previewUrl"
:is-image="isImage"
:region-draw-mode="true"
@region-drawn="handleRegionDrawn"
/>
</div>
<div class="mapper-toolbar">
<div class="card">
<h2>Assign columns</h2>
<div class="mapper-role-grid">
<button
v-for="role in ROLES" :key="role.key" type="button"
class="mapper-role-btn" :class="{ active: armedRole === role.key, assigned: regions.some((r) => r.role === role.key) }"
:style="{ '--role-color': role.color }"
@click="armRole(role.key)"
>
<i class="fa-solid" :class="armedRole === role.key ? 'fa-crosshairs' : 'fa-draw-polygon'"></i>
{{ role.label }}
</button>
</div>
<p class="note">{{ armedRole ? `Drag a box over the "${roleMeta(armedRole)?.label}" column now.` : 'Click a role above, then drag a box over its column.' }}</p>
<ul v-if="regions.length" class="mapper-assigned-list">
<li v-for="r in regions" :key="r.role">
<span class="mapper-assigned-dot" :style="{ background: roleMeta(r.role)?.color }"></span>
{{ roleMeta(r.role)?.label }}
<span v-if="r.page" class="note" style="margin:0 6px 0 auto;">page {{ r.page }}</span>
<button type="button" class="staged-file-remove" title="Remove this region" @click="removeRegion(r.role)">
<i class="fa-solid fa-xmark"></i>
</button>
</li>
</ul>
</div>
<div class="card">
<h2>Format</h2>
<div class="fields">
<div>
<label>Date format</label>
<select v-model="dateFormat" @change="markPreviewStale">
<option value="textual">Already text (e.g. "01 Sep 2026")</option>
<option value="dmy">Numeric, day first (DD/MM/YYYY)</option>
<option value="mdy">Numeric, month first (MM/DD/YYYY)</option>
<option value="ymd">Numeric, year first (YYYY/MM/DD)</option>
</select>
</div>
<div>
<label>Opening balance (optional)</label>
<input v-model="openingBalanceInput" type="text" inputmode="decimal" placeholder="e.g. 90,569.13" @change="markPreviewStale">
</div>
<div>
<label>Closing balance (optional)</label>
<input v-model="closingBalanceInput" type="text" inputmode="decimal" placeholder="e.g. 88,479.50" @change="markPreviewStale">
</div>
</div>
<label class="mapper-checkbox-row">
<input type="checkbox" v-model="debitSelfSigned" @change="markPreviewStale">
This statement's own debit column already prints a minus sign
</label>
<label>Ignore rows containing (e.g. a footer line with no column data)</label>
<div class="mapper-ignore-add">
<input v-model="newIgnoredRule" type="text" placeholder="e.g. Account Fees" @keyup.enter="addIgnoredRule">
<button type="button" class="btn btn-ghost" @click="addIgnoredRule"><i class="fa-solid fa-plus"></i></button>
</div>
<ul v-if="ignoredRowRules.length" class="mapper-assigned-list">
<li v-for="(rule, i) in ignoredRowRules" :key="i">
{{ rule }}
<button type="button" class="staged-file-remove" style="margin-left:auto;" @click="removeIgnoredRule(i)">
<i class="fa-solid fa-xmark"></i>
</button>
</li>
</ul>
</div>
<div class="card">
<h2>Preview</h2>
<button type="button" class="btn btn-primary" :disabled="!hasRequiredShape || previewing" @click="handlePreview">
<i class="fa-solid" :class="previewing ? 'fa-spinner fa-spin' : 'fa-eye'"></i>
{{ previewing ? 'Checking…' : 'Preview' }}
</button>
<p v-if="!hasRequiredShape" class="note">Assign at least Date, Balance, and either Amount or both Debit and Credit before previewing.</p>
<div v-if="previewError" class="error-note visible">{{ previewError }}</div>
<template v-if="previewResult">
<div class="banner banner-info" style="margin-top:14px;">
<i class="fa-solid fa-circle-info"></i>
<span v-if="previewBalanceCheck">
Statement balance check: <strong>{{ previewBalanceCheck.outcome.replace('_', ' ') }}</strong> — {{ previewBalanceCheck.detail }}
</span>
<span v-else>{{ previewResult.transactions.length }} transaction(s) found.</span>
</div>
<div class="table-wrap">
<table>
<thead>
<tr><th>Date</th><th>Description</th><th class="amt">Amount</th><th class="amt">Balance</th></tr>
</thead>
<tbody>
<tr v-for="(t, i) in previewRows" :key="i">
<td>{{ t.date }}</td>
<td>{{ t.description }}</td>
<td class="amt">{{ t.amount }}</td>
<td class="amt">{{ t.balance }}</td>
</tr>
</tbody>
</table>
</div>
<p class="note">Showing the first {{ previewRows.length }} of {{ previewResult.transactions.length }} transactions.</p>
</template>
</div>
<div class="card">
<h2>Save</h2>
<div class="fields" style="margin-bottom:14px;">
<div>
<label>Mapping name (optional)</label>
<input v-model="mappingName" type="text" :placeholder="pendingFile.name">
</div>
</div>
<div v-if="saveError" class="error-note visible">{{ saveError }}</div>
<div class="mapper-save-actions">
<button type="button" class="btn btn-ghost" :disabled="saving" @click="cancelMapping">Cancel</button>
<button type="button" class="btn btn-primary" :disabled="!previewResult || previewStale || saving" @click="handleSaveMapping">
<i class="fa-solid" :class="saving ? 'fa-spinner fa-spin' : 'fa-floppy-disk'"></i>
{{ saving ? 'Saving…' : 'Save Mapping' }}
</button>
</div>
<p v-if="previewResult && previewStale" class="note">The mapping changed since the last preview - preview again before saving.</p>
</div>
</div>
</div>
</template>