Wire frontend fingerprint-lookup orchestration for the layout mapper (L.4)

useBatchExtraction.js now reacts to a needs_mapping:true response: looks up an
exact or near-match layout mapping (layoutMappingsService.js), applies it silently
on an exact match, asks for confirmation on a stale exact match or a near match via
a real ConfirmModal wired through ExtractorView.vue (not a placeholder), and falls
through to reason:'no_match' when nothing matches (the manual mapping screen's own
entry point, not built yet). A used mapping's usage is recorded for drift detection
and persisted onto the saved document record.

Found and fixed two real bugs in the near-match comparator by testing it against
the spec's own documented example (Debit/Credit renamed to Withdrawals/Deposits):
compute_fingerprint was building header_labels from whole header LINES instead of
per-field label text, making a two-word rename indistinguishable from a totally
different layout; added a field_labels map so the comparison is per-field. Even
after that, the first 70% overlap threshold still failed the documented example
itself (a 4-field rename of 2 fields is exactly 50%) - corrected to 50%, derived
from the example's own real numbers.

Verified: 18 assertions against the real layoutMappingsService/useLayoutMapping
(hard gates, the corrected per-field overlap, real PocketBase ownership/sharing
rules, stale-mapping decline/accept, no-match reporting); the real rebuilt
container's /api/process response now carries the fixed field_labels shape;
measure.py byte-identical throughout; npm run build passes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
JasonFraser 2026-10-14 19:51:42 -04:00
parent d76d335d9b
commit 92ba5f4386
10 changed files with 500 additions and 18 deletions

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-L.8 (the frontend fingerprint lookup, the manual mapping screen, the Layouts page, drift detection, 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-L.8 (the multi-highlight source panel, the manual mapping screen, the Layouts page, 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 |
@ -470,7 +470,11 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co
persistence moved to PocketBase, see below),
pocketbaseRepository.js (the one place the PocketBase JS
SDK client is instantiated — `VITE_POCKETBASE_URL`, default
`http://localhost:8090`)
`http://localhost:8090`), pocketbaseAdminRepository.js (NEW
2026-10-14, layout mapper L.4 — a SECOND, separate
PocketBase client instance used only for a real PocketBase
superuser session; never shares `pb.authStore` with the
logged-in app user's own client)
/services — extractionService.js (docKeyFor, effectiveBalance,
process/recheck/export orchestration — its old
localStorage-backed persist/restore/batch-key functions
@ -495,6 +499,16 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co
"PocketBase Stage B.2/B.3" under Key decisions & lessons for
the delete-guard rules and the deliberate circular import
with documentsService.js, confirmed safe at runtime).
layoutMappingsService.js (NEW 2026-10-14, layout mapper L.4
— `listMine`/`listSharedAndMine`/`findByFingerprintHash`/
`createMapping`/`createVersion`/`recordUsage`/`markStale`/
`retire`, plus the near-match comparator
`scoreNearMatch`/`findBestMatch` — see "Layout mapper"
under Key decisions & lessons for the two real bugs found
testing it against the spec's own documented example).
adminLayoutsService.js (NEW 2026-10-14 — the superuser's own
`listPending`/`approve`, ahead of L.8's actual review
screen; uses pbAdmin, never the app user's own `pb`).
/composables — useFileUpload (pure staging concern only as of Stage
B.3 — `chosenFiles` accumulate-not-replace with dedup,
drag/drop handlers; no longer owns `loadDocuments`, moved
@ -506,7 +520,14 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co
list SEQUENTIALLY, one `/api/process` call at a time, each
awaited before the next starts, then
`documentsService.saveDocument`s the result into
`projectsStore.activeProjectId`), useProcessingPhases
`projectsStore.activeProjectId`; as of layout mapper L.4
takes an optional `confirmMappingFn` param, passed straight
through to useLayoutMapping below, and reacts to a
`needs_mapping: true` response by resolving a mapping and
retrying before giving up), useLayoutMapping (NEW
2026-10-14 — `resolveNeedsMapping()`, the layout mapper's
own client-side exact/near-match orchestration; see
"Layout mapper" under Key decisions & lessons), useProcessingPhases
(per-file, untouched by the batch work - the batch
composable just prefixes its text with "Extracting N/M:
filename —"), useRowEditing (saveEdit() now calls
@ -2159,6 +2180,60 @@ rename and a self-retire by the owner both still succeed; the hook itself
re-confirmed working unchanged after the rule tightening (it writes via `e.app`,
bypassing rules entirely either way).
**L.4 shipped same day: the frontend fingerprint-lookup orchestration - including a
real, clickable confirm dialog, not a placeholder deferred to L.6.** New
`frontend/src/repositories/pocketbaseAdminRepository.js` (a SECOND PocketBase client
instance - a superuser session on the same `pb` instance the logged-in app user
already uses would clobber their session, since `pb.authStore` is one global slot
per client), `frontend/src/services/layoutMappingsService.js` (the CRUD/lookup
wrappers plus the near-match comparator - entirely client-side, never duplicated in
Python), `frontend/src/services/adminLayoutsService.js` (the superuser's own
`listPending()`/`approve()`, ahead of L.8's actual review screen), and new
`frontend/src/composables/useLayoutMapping.js` (`resolveNeedsMapping()` - exact
match applies silently; a stale exact match or a near match needs confirmation via
an injected `confirmFn`; no match reports `reason: 'no_match'` honestly rather than
pretending to handle it). `useBatchExtraction.js` now accepts a `confirmMappingFn`
parameter wired straight through to `useLayoutMapping`, and `ExtractorView.vue`
supplies a REAL one backed by the existing `<ConfirmModal>` (a Promise that resolves
when the user clicks Confirm/Cancel) - the near-match confirmation step genuinely
works today, not just in a Node test.
**Two real bugs found by testing the near-match comparator against the spec's own
documented example, not by reading the code and trusting it:**
- `layout_fingerprint.py::compute_fingerprint`'s first draft built `header_labels`
from each matched LINE's own full text (e.g. "date payment type and details
credits debits" as one entry), not per-FIELD label text - meaning "only Debit/
Credit got renamed" could never be distinguished from "this is a totally
different layout," since a whole line differs completely the moment any single
word in it changes. Fixed by adding a new `field_labels` key (`{field: literal
matched text}`) that the near-match comparator reads instead; `header_labels` (the
flat set) stays as the EXACT-match hash's own input, where full-text precision is
actually wanted.
- Even after that fix, a real test of the documented example ITSELF ("Debit"/
"Credit" renamed to "Withdrawals"/"Deposits") still failed - the first-drafted 70%
label-overlap threshold was simply too strict for the exact case it was written to
cover: renaming 2 of a 4-field layout (date/debit/credit/balance, no description
resolved on this candidate page) is precisely 50% overlap. Fixed by lowering the
threshold to 50%, derived by actually working through the documented example's
real numbers rather than picking a round number a second time.
**Verified, all real:** a hand-written Node script ran the REAL
`layoutMappingsService.js`/`useLayoutMapping.js` (not reimplementations) - 18
assertions: `scoreNearMatch`'s three hard gates (shape, order, position) plus the
corrected per-field overlap check (the renamed-labels case now passes; a genuinely
different shape or far-shifted positions still correctly reject), then against the
real running PocketBase - `findByFingerprintHash` respects ownership/sharing
correctly, `recordUsage` flips a mapping to `stale` on its first recorded failure,
and `resolveNeedsMapping` correctly declines a stale exact match when its injected
confirm callback returns false, applies it (with the real `columnMap` carried
through) when it returns true, and reports `reason: 'no_match'` for a genuinely
unmatched fingerprint. Through the real rebuilt container: a synthetic
unrecognizable PDF's `/api/process` response now carries a real `field_labels` key
inside `fingerprint`, confirming the fix reaches the actual HTTP contract, not just
the Python function in isolation. `backend/measure.py` byte-identical throughout
(fingerprinting only ever runs on the already-isolated failure path). `npm run
build` passes.
**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

@ -28,16 +28,33 @@ _MONEY_FIELDS_ORDERED = ("date", "description", "debit", "credit", "amount", "ba
def compute_fingerprint(words, lines_by_top, page_width, page_height):
"""
{header_labels, field_order, field_positions, page_width_bucket,
page_height_bucket, header_line_count, has_status_column,
has_single_amount_column} - see this module's own docstring for how
it's used. Built by resolving EVERY line on the candidate page
against the shared keyword vocabulary and unioning the matches,
since on a failing statement no single line resolves the full
required shape (that's the whole reason a fingerprint is being
computed at all).
{header_labels, field_labels, field_order, field_positions,
page_width_bucket, page_height_bucket, header_line_count,
has_status_column, has_single_amount_column} - see this module's own
docstring for how it's used. Built by resolving EVERY line on the
candidate page against the shared keyword vocabulary and unioning
the matches, since on a failing statement no single line resolves
the full required shape (that's the whole reason a fingerprint is
being computed at all).
`field_labels` ({field: literal matched text}, e.g. {"debit":
"debits", "credit": "credits"}) is what the frontend's own near-match
comparison (layoutMappingsService.js's scoreNearMatch) actually
reads - deliberately keyed by field, not just a flat text list, so
"only the Debit/Credit labels changed to Withdrawals/Deposits" can be
scored as "3 of 4 fields still match" rather than collapsing into an
undifferentiated set comparison that scores two still-identically-
shaped layouts as barely related just because a couple of words
changed (confirmed necessary for real - a flat-set Jaccard overlap
scored exactly that real case as only 33% similar, well under any
reasonable near-match threshold, when structurally it's the same
layout with 2 of 4 labels renamed). `header_labels` (the same text,
flattened to a sorted set) stays only as the literal-text component
of the EXACT-match hash (fingerprint_hash) - full text equality is
the right bar there, so no field-level leniency is wanted for it.
"""
resolved_by_x0 = {}
field_labels = {}
header_labels = []
header_line_count = 0
for top in sorted(lines_by_top.keys()):
@ -52,7 +69,10 @@ def compute_fingerprint(words, lines_by_top, page_width, page_height):
# fingerprint stable rather than picking whichever happened
# to be last in dict-iteration order.
resolved_by_x0.setdefault(field, (x0, x1))
header_labels.append(" ".join(w["text"] for w in line_sorted))
label_words = [w for w in line_sorted if x0 <= w["x0"] and w["x1"] <= x1]
label_text = " ".join(w["text"] for w in label_words).strip().lower()
field_labels.setdefault(field, label_text)
header_labels.append(label_text)
field_order = [f for f in _MONEY_FIELDS_ORDERED if f in resolved_by_x0]
field_positions = {}
@ -62,7 +82,8 @@ def compute_fingerprint(words, lines_by_top, page_width, page_height):
field_positions[field] = round(bucket, 4)
return {
"header_labels": sorted(set(label.strip().lower() for label in header_labels if label.strip())),
"header_labels": sorted(set(label for label in header_labels if label)),
"field_labels": field_labels,
"field_order": field_order,
"field_positions": field_positions,
"page_width_bucket": round(page_width / _PAGE_SIZE_BUCKET) * _PAGE_SIZE_BUCKET,

View File

@ -12,16 +12,31 @@ import { useUiStore } from '../stores/uiStore'
import { useProjectsStore } from '../stores/projectsStore'
import * as extractionService from '../services/extractionService'
import * as documentsService from '../services/documentsService'
import * as layoutMappingsService from '../services/layoutMappingsService'
import * as formatService from '../services/formatService'
import { useProcessingPhases } from './useProcessingPhases'
import { useLayoutMapping } from './useLayoutMapping'
const IMAGE_FILE_RE = /\.(jpe?g|png)$/i
export function useBatchExtraction() {
/** Whether a (possibly mapping-forced) extraction's own checks actually passed - the drift-detection signal a used mapping's usageCount/failureCount tracks (see layoutMappingsService.recordUsage). */
function checksPassed(result) {
const balanceCheck = result.checks?.find((c) => c.name === 'statement_balance')
const runningCheck = result.checks?.find((c) => c.name === 'running_balance')
return balanceCheck?.outcome !== 'fail' && !(runningCheck?.mismatches?.length)
}
/**
* `confirmMappingFn` - layout mapper work, passed straight through to
* useLayoutMapping.js's own `confirmFn` (see that file) - omit for the
* default "always decline a stale/near match" behavior.
*/
export function useBatchExtraction(confirmMappingFn) {
const extractionStore = useExtractionStore()
const uiStore = useUiStore()
const projectsStore = useProjectsStore()
const { isProcessing, phaseText, start, stop } = useProcessingPhases()
const { resolveNeedsMapping } = useLayoutMapping(confirmMappingFn)
/**
* Submits every chosen file for extraction, one at a time.
@ -45,7 +60,26 @@ export function useBatchExtraction() {
extractionStore.advanceBatch(i + 1, file.name)
start()
try {
const result = await extractionService.process(file, openingBalance, closingBalance)
let result = await extractionService.process(file, openingBalance, closingBalance)
let usedMapping = null
// Layout mapper work: neither the keyword detector nor the
// layout_quirks fallback could resolve this statement's columns
// - look for a stored mapping (exact match applies silently; a
// stale exact match or a near match needs confirmation) before
// giving up. See useLayoutMapping.js's own docstring.
if (result.needs_mapping) {
const resolved = await resolveNeedsMapping({ fingerprint: result.fingerprint, fingerprintHash: result.fingerprintHash })
if (resolved.applied) {
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)." }
} else {
result = { error: 'Mapping declined - extraction skipped for this file.' }
}
}
if (result.error) {
failures.push(`${file.name}: ${result.error}`)
} else {
@ -63,7 +97,17 @@ export function useBatchExtraction() {
// "All" view).
project: projectsStore.activeProjectId,
openingBalanceInput, closingBalanceInput,
layoutMappingUsed: usedMapping?.id,
layoutMappingVersionUsed: usedMapping?.version,
layoutApplied: usedMapping ? 'mapping' : 'auto',
layoutFingerprintHash: usedMapping ? result.fingerprintHash : undefined,
})
// A mapping that was actually applied gets its usage recorded
// for drift detection regardless of whether the save above
// succeeded - best-effort, never blocks showing the result.
if (usedMapping) {
layoutMappingsService.recordUsage(usedMapping.id, { success: checksPassed(result) }).catch(() => {})
}
// Keeps the sidebar's own per-project document list live if
// that project is currently expanded there - a no-op otherwise
// (see projectsStore.js's own comment on why this cache exists).

View File

@ -0,0 +1,67 @@
/**
* Orchestrates what happens after /api/process responds with
* needs_mapping: true - tier 1 (the keyword/geometry detector) AND
* tier 2 (layout_quirks) have both failed on every page (see
* backend/services/extraction_service.py's own LayoutMappingRequired).
* Entirely client-side: the exact/near-match lookup and comparison both
* run here, never duplicated server-side - see layoutMappingsService
* .js's own scoreNearMatch/findBestMatch for why.
*
* `confirmFn` - an injected `(mapping, {kind, changedLabels}) =>
* Promise<boolean>` callback for the "layout changed, please confirm"
* step (`kind` is "stale" or "near") - the real caller
* (useBatchExtraction.js, via ExtractorView.vue) wires this to a real
* ConfirmModal; a test can inject a scripted callback instead. Omitting
* it treats every stale/near case as declined, never silently applying
* a mapping without confirmation.
*/
import * as layoutMappingsService from '../services/layoutMappingsService'
function forcedMappingFor(mapping) {
return {
columnMap: mapping.columnMap,
signConvention: mapping.signConvention,
ignoredRowRules: mapping.ignoredRowRules,
dateFormat: mapping.dateFormat,
startPage: mapping.startPage,
}
}
export function useLayoutMapping(confirmFn) {
/**
* Returns {applied: true, mapping, forcedMapping} once a mapping is
* ready to retry extraction with, or {applied: false, reason:
* "declined" | "no_match", fingerprint, fingerprintHash} otherwise -
* "no_match" is the manual mapping screen's own entry point (layout
* mapper L.6, not built yet); the caller surfaces that honestly
* rather than pretending it was handled.
*/
async function resolveNeedsMapping({ fingerprint, fingerprintHash }) {
const exact = await layoutMappingsService.findByFingerprintHash(fingerprintHash)
if (exact) {
if (exact.status !== 'stale') {
return { applied: true, mapping: exact, forcedMapping: forcedMappingFor(exact) }
}
// An exact fingerprint match that's already flagged stale (a
// prior use failed its own checks) is never silently reapplied -
// treated the same as a near match, confirmation required.
const confirmed = confirmFn ? await confirmFn(exact, { kind: 'stale', changedLabels: [] }) : false
if (confirmed) return { applied: true, mapping: exact, forcedMapping: forcedMappingFor(exact) }
return { applied: false, reason: 'declined', fingerprint, fingerprintHash }
}
const candidates = await layoutMappingsService.listSharedAndMine()
const best = layoutMappingsService.findBestMatch(fingerprint, candidates)
if (best) {
const confirmed = confirmFn
? await confirmFn(best.mapping, { kind: 'near', changedLabels: best.changedLabels })
: false
if (confirmed) return { applied: true, mapping: best.mapping, forcedMapping: forcedMappingFor(best.mapping) }
return { applied: false, reason: 'declined', fingerprint, fingerprintHash }
}
return { applied: false, reason: 'no_match', fingerprint, fingerprintHash }
}
return { resolveNeedsMapping }
}

View File

@ -0,0 +1,16 @@
/**
* A SECOND, separate PocketBase client instance, used only to
* authenticate as a real PocketBase superuser (the layout mapper's own
* review screen, L.8 - not built yet; adminLayoutsService.js is the
* first consumer). Deliberately NOT the same `pb` instance
* pocketbaseRepository.js exports for the logged-in app user -
* `pb.authStore` is one global slot per client, so authenticating a
* superuser on that same instance would clobber the app user's own
* session. Not authenticated here - callers log in explicitly via
* `pbAdmin.collection('_superusers').authWithPassword(...)`.
*/
import PocketBase from 'pocketbase'
const POCKETBASE_URL = import.meta.env?.VITE_POCKETBASE_URL || 'http://localhost:8090'
export const pbAdmin = new PocketBase(POCKETBASE_URL)

View File

@ -0,0 +1,40 @@
/**
* The PocketBase superuser's own entry points for reviewing a new,
* still-private layout mapping and approving it straight to "shared" -
* the layout mapper's own review screen (L.8, not built yet) is the
* only planned consumer. Uses pbAdmin (pocketbaseAdminRepository.js),
* never the app user's own `pb` client - a superuser session lives in
* its own PocketBase auth collection (`_superusers`), entirely separate
* from the app's `users` collection.
*/
import { pbAdmin } from '../repositories/pocketbaseAdminRepository'
export async function login(email, password) {
await pbAdmin.collection('_superusers').authWithPassword(email, password)
}
export function logout() {
pbAdmin.authStore.clear()
}
export function isLoggedIn() {
return pbAdmin.authStore.isValid
}
/** Every mapping awaiting review - a real superuser session bypasses every collection rule, so this sees every owner's own private mappings, not just one user's. */
export async function listPending() {
return pbAdmin.collection('layoutMappings').getFullList({
filter: 'status = "private"',
sort: '-created',
})
}
/** Promotes one mapping straight to shared, bypassing the second-user-confirmation path entirely. */
export async function approve(id) {
return pbAdmin.collection('layoutMappings').update(id, {
status: 'shared',
promotedReason: 'superuser_approved',
approvedBySuperuser: pbAdmin.authStore.record?.email || '',
promotedAt: new Date().toISOString(),
})
}

View File

@ -24,6 +24,12 @@ import * as projectsService from './projectsService'
export async function saveDocument({
docKey, fileName, sourceFile, result, project,
openingBalanceInput, closingBalanceInput,
// Layout mapper work (see useLayoutMapping.js) - set only when this
// extraction used a saved mapping instead of auto-detection; every
// other call site (every HSBC/RBC-shaped statement, and any statement
// layout_quirks fixed on its own) leaves these unset, matching
// documents.layoutApplied's own "auto" default.
layoutMappingUsed, layoutMappingVersionUsed, layoutApplied, layoutFingerprintHash,
}) {
const projectId = project || (await projectsService.getDefaultProject()).id
@ -39,6 +45,10 @@ export async function saveDocument({
formData.append('result', JSON.stringify(result))
if (openingBalanceInput) formData.append('openingBalanceInput', openingBalanceInput)
if (closingBalanceInput) formData.append('closingBalanceInput', closingBalanceInput)
if (layoutMappingUsed) formData.append('layoutMappingUsed', layoutMappingUsed)
if (layoutMappingVersionUsed) formData.append('layoutMappingVersionUsed', layoutMappingVersionUsed)
if (layoutApplied) formData.append('layoutApplied', layoutApplied)
if (layoutFingerprintHash) formData.append('layoutFingerprintHash', layoutFingerprintHash)
formData.append('sourceFile', sourceFile)
return pb.collection('documents').create(formData)

View File

@ -27,12 +27,24 @@ export function effectiveBalance(typedValue, fallbackValue) {
return typedValue !== null && typedValue !== undefined ? typedValue : (fallbackValue ?? null)
}
/** Submits a chosen file (+ optional typed balances) for extraction. */
export async function process(file, openingBalanceInput, closingBalanceInput) {
/**
* Submits a chosen file (+ optional typed balances) for extraction.
*
* `forcedMapping` (layout mapper work - see useLayoutMapping.js) - when
* given, extracts directly from that mapping's own column positions
* instead of auto-detection; omitted on every normal upload. A response
* carrying `needs_mapping: true` (both the keyword detector and the
* layout_quirks fallback failed) is what useLayoutMapping.js's own
* resolveNeedsMapping() reacts to - this function itself doesn't
* special-case that response shape at all, it's just whatever JSON
* /api/process returned.
*/
export async function process(file, openingBalanceInput, closingBalanceInput, forcedMapping = null) {
const fd = new FormData()
fd.append('statement_file', file)
if (openingBalanceInput !== null) fd.append('opening_balance', openingBalanceInput)
if (closingBalanceInput !== null) fd.append('closing_balance', closingBalanceInput)
if (forcedMapping) fd.append('forced_mapping', JSON.stringify(forcedMapping))
return extractionRepository.processStatement(fd)
}

View File

@ -0,0 +1,159 @@
/**
* Business logic for saved layout mappings (the layout mapper's tier
* 3/4 - see CLAUDE.md's "Layout mapper" entry) - thin wrapper over the
* PocketBase SDK, same convention as documentsService.js/
* projectsService.js. The near-match comparator lives entirely here,
* client-side - never duplicated in Python - since it only ever needs
* to compare against the small set of mappings one logged-in user can
* already see (their own + shared).
*/
import { pb } from '../repositories/pocketbaseRepository'
/** The logged-in user's own mappings, newest first. */
export async function listMine() {
return pb.collection('layoutMappings').getFullList({
filter: `owner = "${pb.authStore.record.id}"`,
sort: '-created',
})
}
/** Every mapping the logged-in user can apply - their own plus every shared one. */
export async function listSharedAndMine() {
return pb.collection('layoutMappings').getFullList({
filter: `status = "shared" || owner = "${pb.authStore.record.id}"`,
sort: '-created',
})
}
/**
* The exact-fingerprint-hash match this user can see (their own or
* shared), or null if none exists - `null`, not a thrown error, so
* callers (useLayoutMapping.js) can treat "no match" as a plain value
* rather than a special case. Excludes "retired" - a retired mapping
* was deliberately withdrawn, never auto-applied again.
*/
export async function findByFingerprintHash(hash) {
try {
return await pb.collection('layoutMappings').getFirstListItem(
`fingerprintHash = "${hash}" && status != "retired" && (status = "shared" || owner = "${pb.authStore.record.id}")`,
)
} catch (e) {
return null
}
}
/** Creates a new, PRIVATE mapping (the manual mapping screen's own Save - layout mapper L.6, not built yet). */
export async function createMapping(data) {
return pb.collection('layoutMappings').create({
owner: pb.authStore.record.id,
status: 'private',
version: 1,
...data,
})
}
/** Appends an immutable version snapshot for a mapping - see layoutMappingVersions' own rules (append-only history). */
export async function createVersion(mappingId, snapshot) {
return pb.collection('layoutMappingVersions').create({
layoutMapping: mappingId,
createdBy: pb.authStore.record.id,
...snapshot,
})
}
/**
* Records one real use of a mapping - called after every extraction a
* mapping was applied to, success reflecting whether the resulting
* statement_balance/running_balance checks actually passed (see
* CLAUDE.md's own drift-detection reasoning). The FIRST failure flips
* the mapping to "stale" - no fuzzy threshold - so the next lookup
* demotes it to a confirm-prompt instead of silently reapplying
* something already known to be drifting.
*/
export async function recordUsage(id, { success }) {
const record = await pb.collection('layoutMappings').getOne(id)
const now = new Date().toISOString()
const patch = { lastUsedAt: now, usageCount: (record.usageCount || 0) + 1 }
if (!success) {
patch.failureCount = (record.failureCount || 0) + 1
patch.lastFailureAt = now
patch.status = 'stale'
}
return pb.collection('layoutMappings').update(id, patch)
}
export async function markStale(id) {
return pb.collection('layoutMappings').update(id, { status: 'stale' })
}
/** An owner retiring their own mapping - still allowed on a shared one via updateRule (only self-promotion TO "shared" is blocked, see pb_migrations/6). */
export async function retire(id) {
return pb.collection('layoutMappings').update(id, { status: 'retired' })
}
// Position buckets are 2% of page width (table_extract's own
// layout_fingerprint.py) - two buckets of tolerance absorbs ordinary
// jitter without conflating a genuinely different column position.
const POSITION_TOLERANCE = 0.04
// At least HALF the fields' own label text must still match exactly.
// Confirmed by working through the documented example itself, not
// picked arbitrarily: a bank renaming "Debit"/"Credit" to "Withdrawals"/
// "Deposits" changes 2 of a 4-field layout (date/debit/credit/balance,
// no description resolved) - exactly 50% overlap. A threshold above 0.5
// would reject the very example this comparison exists to cover; the
// column-shape/order/position hard gates above already rule out two
// genuinely different layouts ever reaching this check in the first
// place, so a straight majority of matching labels is a reasonable bar
// for "still recognizably the same layout" without being so strict it
// defeats its own documented purpose.
const LABEL_OVERLAP_THRESHOLD = 0.5
/**
* Whether `stored` (an existing layoutMappings record) is a near match
* for `candidate` (a freshly computed fingerprint) - returns
* {mapping, labelOverlap, changedLabels} or null. Three hard gates
* first (column SHAPE/order must be identical - a different shape is
* never a near match, it's a different layout), then a softer, PER-FIELD
* label-text comparison for the "layout changed, please confirm" case -
* deliberately per-field (candidate.field_labels[field] vs
* stored.field_labels[field]), not a flat Jaccard overlap of the whole
* header_labels list: confirmed necessary for real - a flat-set
* comparison scored a layout with only 2 of 4 labels renamed (e.g.
* "Debit"/"Credit" → "Withdrawals"/"Deposits", the documented example
* this exists for) as just 33% similar, since each renamed label counts
* as a pure miss on both sides - well under any reasonable threshold,
* even though the two layouts are structurally identical.
*/
export function scoreNearMatch(candidate, stored) {
const storedFp = stored.fingerprint
if (!storedFp) return null
if (candidate.has_status_column !== storedFp.has_status_column) return null
if (candidate.has_single_amount_column !== storedFp.has_single_amount_column) return null
if (JSON.stringify(candidate.field_order) !== JSON.stringify(storedFp.field_order)) return null
if (!candidate.field_order?.length) return null
for (const field of candidate.field_order) {
const a = candidate.field_positions?.[field]
const b = storedFp.field_positions?.[field]
if (a === undefined || b === undefined) return null
if (Math.abs(a - b) > POSITION_TOLERANCE) return null
}
const changedLabels = candidate.field_order.filter(
(field) => candidate.field_labels?.[field] !== storedFp.field_labels?.[field],
)
const overlap = (candidate.field_order.length - changedLabels.length) / candidate.field_order.length
if (overlap < LABEL_OVERLAP_THRESHOLD) return null
return { mapping: stored, labelOverlap: overlap, changedLabels }
}
/** The single best near match for `candidate` among `mappings`, or null. */
export function findBestMatch(candidate, mappings) {
let best = null
for (const stored of mappings) {
const scored = scoreNearMatch(candidate, stored)
if (scored && (!best || scored.labelOverlap > best.labelOverlap)) best = scored
}
return best
}

View File

@ -19,6 +19,7 @@ import FileUploadZone from '../components/FileUploadZone.vue'
import ResizablePanels from '../components/ResizablePanels.vue'
import SourceDocumentPanel from '../components/SourceDocumentPanel.vue'
import TransactionsTable from '../components/TransactionsTable.vue'
import ConfirmModal from '../components/ConfirmModal.vue'
const extractionStore = useExtractionStore()
const projectsStore = useProjectsStore()
@ -40,7 +41,34 @@ const {
chosenFiles, isDragOver,
removeChosenFile, clearChosenFiles, onFileInputChange, onDragOver, onDragLeave, onDrop,
} = useFileUpload()
const { isProcessing, phaseText, runBatch } = useBatchExtraction()
// Layout mapper work (see useLayoutMapping.js) - the "layout changed,
// please confirm" step for a stale-exact or near-match mapping.
// pendingMappingConfirm.resolve is the Promise resolver
// resolveNeedsMapping() is awaiting - set once a confirm is needed,
// cleared once the user answers via the modal below.
const pendingMappingConfirm = ref(null)
function confirmMapping(mapping, { kind, changedLabels }) {
return new Promise((resolve) => {
pendingMappingConfirm.value = { mapping, kind, changedLabels, resolve }
})
}
const mappingConfirmMessage = computed(() => {
const pending = pendingMappingConfirm.value
if (!pending) return ''
const name = pending.mapping.name || 'a saved layout mapping'
if (pending.kind === 'stale') {
return `"${name}" previously failed its own balance checks and was flagged as changed. Apply it anyway?`
}
const changed = pending.changedLabels.length ? ` (differs: ${pending.changedLabels.join(', ')})` : ''
return `This statement's layout looks similar to the saved mapping "${name}"${changed}. Apply it?`
})
function answerMappingConfirm(ok) {
pendingMappingConfirm.value?.resolve(ok)
pendingMappingConfirm.value = null
}
const { isProcessing, phaseText, runBatch } = useBatchExtraction(confirmMapping)
const { loadDocuments } = useDocuments()
// "Extracting 2/4: statement.pdf - Reading document..." while a batch of
@ -92,6 +120,16 @@ onMounted(async () => {
@extract="handleExtract"
/>
<ConfirmModal
:visible="!!pendingMappingConfirm"
title="Layout changed?"
:message="mappingConfirmMessage"
confirm-label="Apply mapping"
confirm-icon="fa-check"
@confirm="answerMappingConfirm(true)"
@cancel="answerMappingConfirm(false)"
/>
<!--
Source Document and Transactions (and the opening/closing balance
fields that live in the latter) are always visible, even before a