diff --git a/CLAUDE.md b/CLAUDE.md index 99403cf..41046c7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,12 +12,21 @@ independent of, `eib-processor/` — not a tool hosted inside that platform). Se `UI_DESIGN_THEME.md` for the Bettersight brand system and `UI_DESIGN_THEME_ENTERPRISE.md` for this app's own light-theme override of it. -This product deliberately does **not** categorize transactions (bank description → -accounting description) — it only structures the statement and proves the math. That's -a different, narrower scope than the in-app `bank_statement_categorizer` tools that live -inside `eib-processor`. The original full product spec this was scoped down from is -copied into this repo at `docs/bankstatement.md` — section 1.3 there is where the -categorization boundary is defined; section 15 is the full 7-phase table referenced below. +**Update 2026-10-31: this product now DOES optionally categorize transactions** - a +deliberate, explicit scope expansion past the line below, not an oversight (see +"Transaction categorization" under Key decisions & lessons for the full record). The +original framing, kept here for history: this product used to deliberately not +categorize transactions (bank description → accounting description) - it only +structured the statement and proved the math, a narrower scope than the in-app +`bank_statement_categorizer` tools that live inside `eib-processor`. Categorization here +is still architecturally separate from extraction/checks - it's a user-maintained, +project-scoped set of pattern→accounting-category rules applied entirely client-side to +the transactions this app has already extracted and verified, shown as a second +"Categorization" tab beside Transactions - not a second parsing pass, and the extraction +pipeline itself was never touched. The original full product spec this was scoped down +from is copied into this repo at `docs/bankstatement.md` — section 1.3 there is where +the categorization boundary is defined (now superseded); section 15 is the full 7-phase +table referenced below. ## Build scope & status @@ -155,7 +164,25 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co /api/process also catches LayoutMappingRequired ahead of the generic ValueError handler, returning HTTP 422 with {needs_mapping, fingerprint, fingerprintHash} — - see "Layout mapper" under Key decisions & lessons + see "Layout mapper" under Key decisions & lessons. As + of 2026-11-19, POST /api/export/qbo is a second export + format alongside /export — same recheck-then-build + shape, requires a `bank_account` field, returns a + .qbo attachment via qbo_service.py instead of + excel_service.py; see ".qbo export" under Key decisions + & lessons (renamed/corrected from an earlier route of + the same name ending in ".qfx" - see that entry for + why). POST /api/export/xero-csv, same day, is a + THIRD — reuses parse_export_request as-is (no extra + required field, unlike qbo), returns a .csv via + xero_csv_service.py; see "Xero export" under Key + decisions & lessons for why it needs no bank-account + field at all, unlike qbo. POST /api/export/csv, same + day, is a FOURTH — also reuses parse_export_request + as-is, returns a .csv via csv_service.py (a plain, + generic transactions dump, distinct from xero-csv's + own import-specific shape); see "Four export formats + consolidated" under Key decisions & lessons health.py — GET /health — pings Docling via docling_repository /services extraction_service.py — text-PDF-vs-OCR routing + the dual-engine cross-check @@ -187,6 +214,35 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co used to be file_repository.save_workbook, removed 2026-10-13 — /api/export now streams straight from an in-memory buffer, see below) + qbo_service.py — NEW 2026-11-19 (renamed/corrected same day from an + earlier qfx_service.py - see ".qbo export" under Key + decisions & lessons for why) — builds a QuickBooks + (Web Connect .qbo) export string entirely in memory, + OFX 1.x SGML (not XML), same no-disk discipline as + excel_service.py — reuses this pipeline's own existing + `transactions` data, no new extraction logic; see + ".qbo export" under Key decisions & lessons for the + FITID/escaping design, the INTU.BID finding, and the + real bugs this stage's own testing caught + xero_csv_service.py — NEW 2026-11-19, same day as qbo_service.py — builds + a Xero-compatible statement-import CSV (Date/Amount/ + Payee/Description), using Python's stdlib csv module + for safe quoting. Needs no bank-account input at all + (Xero's own CSV import has no + equivalent) and reuses this pipeline's own existing + "DD Mon YYYY" date text unchanged - see "Xero export" + under Key decisions & lessons for the research behind + both of those design choices + csv_service.py — NEW 2026-11-19, same day — a plain, generic + transactions CSV (Date/Description/Amount/Balance/ + Status/Check flags, matching excel_service.py's own + Transactions sheet exactly, reusing that module's own + _flagged_row_indexes() directly). Unlike + xero_csv_service.py, writes EVERY transaction row + regardless of a missing date/amount - a plain dump + has no structural requirement to violate; see "Four + export formats consolidated" under Key decisions & + lessons /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/L.6/L.7 stages (2026-10-14/15): @@ -206,7 +262,15 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co can't be mistaken for this ledger's own money - see "A real new-statement bug..." under Key decisions & lessons for the real phantom-transaction regression - this needed to guard against. extract_pdf()/ + this needed to guard against. As of 2026-11-16, + _parse_money() also recognizes a parenthesized + amount ("(25.00)") as negative, via a shared + _split_sign() helper also used by + _parse_money_with_patterns() - see "Parenthesized + negative amounts recognized" under Key decisions & + lessons for the real blank-extraction bug this + fixed on a single-Amount-column statement. + extract_pdf()/ extract_page() gained forced_zones/forced_sign_convention/ ignored_row_rules/date_format/start_page/ @@ -335,7 +399,19 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co possible), not just the cross-check role it plays for a normal text PDF. `_run_ocr_only()` additionally falls back to `raw_ocr_extract.py` on a PER-PAGE basis when Docling's own table-structure recognition fails for a given page (zero transaction rows) — see "OCR / - scanned statements" below. + scanned statements" below. As of the manual "Map" button (2026-11-14), `run()` also + computes `fingerprint`/`fingerprintHash` unconditionally on a SUCCESSFUL extraction + (not just the two failure paths, which already did) — so the frontend can open the + manual mapping screen against an already-successful extraction to CORRECT it, not just + an outright-failed one; see that entry under Key decisions & lessons. As of manual + layout mapping for OCR sources (also 2026-11-14), `_run_ocr_only(file_path, docling_url, + forced_mapping=None)` gained that same `forced_mapping` parameter — when it carries a + `columnMap`, Docling's own table-structure call is skipped entirely and the request + routes straight to `raw_ocr_extract.py`'s new forced-zone support, and the fingerprint + computed on every path (including now the OCR auto-detect failure path, via + `LayoutMappingRequired`) is no longer hardcoded `None`/`None` — it's a real fingerprint + from the new `_ocr_header_candidate_geometry`/`_ocr_fingerprint` helpers. See "Manual + layout mapping for OCR-sourced statements" under Key decisions & lessons. - `backend/services/pipeline_service.py` — orchestrates extract → reconcile → normalize → run checks. - `backend/services/checks_service.py` — the six checks (statement balance, running-balance @@ -354,7 +430,14 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co frontend is what persists an export long-term now (`documentsService.saveExportFile`, PocketBase/R2), not this backend at all. As of review screen R.5 (2026-10-14), also writes an optional "Edits" sheet (`_write_edits_sheet`) whenever the export request - carries a non-empty `edit_log` - see that entry under Key decisions & lessons. + carries a non-empty `edit_log` - see that entry under Key decisions & lessons. As of + transaction categorization (2026-10-31), also writes an optional "Categorized + Summary" sheet (`_write_categorized_summary_sheet`) whenever the export request + carries a `categorization` object - built entirely client-side + (`useCategorization.js`), this backend never computes or even understands a + categorization rule itself, just renders whatever plain `{matched, unmatched}` + structure it's handed - see "Transaction categorization" under Key decisions & + lessons. - `backend/services/extraction/raw_ocr_extract.py` — the per-page fallback for `extraction_service._run_ocr_only` when Docling's table-structure recognition fails on a scanned/photographed page. Runs OCR directly (`tesserocr`) for raw word text + pixel @@ -362,7 +445,21 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co reuses `table_extract.py`'s own column-geometry logic unchanged. See "OCR / scanned statements" below for the full reasoning, the two real adaptations this needed (pixel-to-point scaling, cross-page zone sharing), and the one known edge case that isn't - reliably fixed. + reliably fixed. As of manual layout mapping for OCR sources (2026-11-14), `extract_pdf`/ + `extract_image` also accept the same `forced_zones`/`forced_sign_convention`/ + `ignored_row_rules`/`date_format`/`header_bottom`/`value_patterns` parameters + `table_extract.extract_pdf` does (plus `start_page` on `extract_pdf` only - a bare image + has no multi-page concept), and a new `header_candidate_geometry(file_path, is_image)` - + the OCR-side equivalent of `table_extract.header_candidate_geometry()` - computes a real + fingerprint from OCR'd words. See "Manual layout mapping for OCR-sourced statements" + under Key decisions & lessons for the full record, including a real bug this stage's own + testing caught (`extract_image` was initially missing `header_bottom` entirely). As of + 2026-11-16, `_extract_words()` also upscales a low-resolution image to + `_MIN_OCR_WIDTH_PX=1600px` before running tesserocr (never downscales an already- + adequate one) - a real reported "Preview returns blank" statement turned out to be a + 480x800px phone photo tesserocr could barely read at all at its native size; see "Two + real bugs found investigating a specific real-world statement report" under Key + decisions & lessons. - `backend/measure.py` — the measurement harness. Auto-discovers its corpus from `fixtures/*.pdf` with a matching `*_ground_truth.xlsx` sibling (each ground-truth file is a `Transactions` sheet of date/status/description/amount/balance rows in the same @@ -459,6 +556,16 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co Key decisions & lessons; `editLog`/`acknowledgedFlags`/ `accepted`/`acceptedAt` all live directly on `doc.result`, no new PocketBase migration needed). + `addPendingMappingDocument`/`replacePendingMappingDocument`/ + `removePendingMappingDocument` (NEW 2026-11-15, per-document + mapping queue for batch uploads) - a document entry's own + `pendingMapping` field (`{file, fingerprint, fingerprintHash, + needsValueConfirmation, candidateRow, fieldOrder}` or `null`) + is now where "this statement still needs manual mapping" + lives, not layoutMapperStore's old single pending-file slot - + see that entry under Key decisions & lessons for the real bug + this fixes (a second needs-mapping file in the same batch used + to silently overwrite and lose the first's pending state). uiStore.js — `resultsOpen`/`toggleResultsOpen()`/`closeResultsOpen()` (renamed from `resultExpanded`/`toggleResultExpanded` - 2026-10-13, now drives TransactionsTable's own Results @@ -517,7 +624,36 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co never both at once) for the narrower needs_value_confirmation case - see CLAUDE.md's own "Value-pattern mapping" entries under Key decisions & - lessons. + lessons. As of the manual "Map" button (2026-11-14), also + holds `pendingDocumentId` - null for the normal auto- + triggered flow, set when the mapper was launched + manually (TransactionsTable.vue) to CORRECT an already- + loaded document instead of mapping a freshly-failed one - + see that entry under Key decisions & lessons for why + `ManualMappingView.vue`'s own Save needs to tell the two + apart. As of the per-document mapping queue (2026-11-15), + no longer holds "which statements still need mapping" at + all - that moved to extractionStore's own `pendingMapping` + field on each placeholder document (a real reported bug + fix: this store's old single-slot design silently lost + every needs-mapping file in a batch except whichever one + happened to be here last). This store is now purely the + short-lived bridge across ONE /map-layout navigation - + gained a `pendingDocKey` alongside `pendingDocumentId`, + set when the mapper was launched from a queued placeholder + rather than either of the other two cases, so Save knows + to replace that placeholder's own queue slot - see "Per- + document mapping queue for batch uploads" under Key + decisions & lessons. + usageStore.js (NEW 2026-11-16, billing/usage-tracking + foundation — `pagesThisPeriod`/`loadUsage()`/ + `recordExtraction()`, the live counter + `AppHeader.vue`'s own badge reads; "this period" is + currently just the calendar month, an explicit + placeholder until a real subscription/plan record + exists to anchor the user's own described pause/resume + billing cycle against instead — see "Usage tracking + foundation" under Key decisions & lessons). /repositories — raw HTTP/storage access only: extractionRepository.js (fetch calls to /api/process|recheck|export), localStorageRepository.js (kept for any future per-viewer @@ -548,7 +684,13 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co token). documentsService.js (`saveDocument`/ `updateDocument`/`listDocuments`/`deleteDocument`/ `saveExportFile`/`sourceFileUrl`/`moveToProject` — the real, - authoritative document persistence layer now). + authoritative document persistence layer now. + `savePendingMappingDocument` (NEW 2026-11-16) saves a + needs-mapping/needs-value-confirmation placeholder - same + multipart shape as `saveDocument`, just with no `result` + and the new `needsMapping`/`pendingFingerprint`/etc fields + instead - see "Persisted pending-mapping statements" under + Key decisions & lessons). projectsService.js (`getDefaultProject`/`listProjects`/ `createProject`/`renameProject`/`deleteProject` — see "PocketBase Stage B.2/B.3" under Key decisions & lessons for @@ -572,10 +714,56 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co mapping's own sourceDocument/file through pbAdmin, since a superuser session never shares the app user's `pb` client); uses pbAdmin throughout, never `pb`. + categorizationRulesService.js (NEW 2026-10-31, transaction + categorization — `listForProject`/`createRule`/ + `deleteRule`, project-scoped PocketBase CRUD; also exports + the pure, non-PocketBase `matchDescription(description, + rules)` in the same file, alongside the CRUD — same + precedent `layoutMappingsService.js` sets with + `scoreNearMatch`/`findBestMatch`. Case-insensitive + substring match, longest matching pattern wins when more + than one rule matches — see "Transaction categorization" + under Key decisions & lessons for the full design). + usageService.js (NEW 2026-11-16, billing/usage-tracking + foundation — `recordUsage`/`getPagesSince`, thin + PocketBase wrappers over the new `usageEvents` + collection; see "Usage tracking foundation" under Key + decisions & lessons for a real date-filter bug this + stage's own testing found and fixed in + `getPagesSince`). bankAccountProfilesService.js (NEW + 2026-11-19, QBO export foundation — `listForProject`/ + `createProfile`/`deleteProfile`, same thin-wrapper shape + as categorizationRulesService.js, over the new + bankAccountProfiles collection; see "QBO export" under + Key decisions & lessons). extractionService.js itself + gained `exportQbo(result, openingBalance, + closingBalance, bankAccount)` the same day — mirrors + `exportWorkbook` exactly, routes to a new + `/api/export/qbo` backend endpoint instead. Also gained + `exportXeroCsv(result, openingBalance, closingBalance)` + the same day, no bankAccount parameter — routes to + `/api/export/xero-csv`; see "Xero export" under Key + decisions & lessons for why this one needs no bank- + account input at all, unlike exportQbo. Also gained + `exportCsv(result, openingBalance, closingBalance)` the + same day — a plain, generic CSV (distinct from + exportXeroCsv's own import-specific shape), routes to + `/api/export/csv`; reused inside TransactionsTable.vue's + own new `DOWNLOAD_FORMATS` lookup alongside + `exportWorkbook`, see "Four export formats consolidated" + under Key decisions & lessons. /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 - out to useDocuments below), useDocuments + out to useDocuments below. As of 2026-11-16, also probes + each staged IMAGE's own real resolution + (`lowResolutionWarnings`, fired-not-awaited so staging + itself stays synchronous) and flags one below + `LOW_RESOLUTION_WIDTH_PX` - the same threshold + `raw_ocr_extract._MIN_OCR_WIDTH_PX` uses server-side to + decide whether to upscale before OCR, kept deliberately + in sync - see "Low-resolution image upload warning" + under Key decisions & lessons), useDocuments (`loadDocuments(filter)` — fetches via `documentsService.listDocuments`, used by both `ExtractorView`'s initial load and `ProjectSidebar`'s @@ -625,7 +813,28 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co click-and-drag-to-define-a-region interaction the manual mapping screen, L.6, will use; owned by SourceDocumentPanel.vue via a new `regionDrawMode` prop, - a no-op everywhere today) + a no-op everywhere today), + useCategorization (NEW 2026-10-31, transaction + categorization — groups the active document's own + already-extracted `transactions` against the active + DOCUMENT's own `project` field's categorizationRules + (deliberately NOT `projectsStore.activeProjectId` - the + sidebar's "All" filter can be active while a specific + document, which still belongs to exactly one project, is + open). Recomputed live from whatever rules exist right + now, never persisted on the document itself. Exposes + `rules`/`matched`/`unmatched`/`summaryForExport` (the + exact shape `excel_service.py`'s + `_write_categorized_summary_sheet` expects) plus + `addRule`/`removeRule`, both re-bucketing immediately with + no refetch - see "Transaction categorization" under Key + decisions & lessons), useBankAccountProfiles (NEW + 2026-11-19, QBO export foundation — same loading shape as + useCategorization's own rules-half, scoped to the active + document's own project; `profiles`/`addProfile`, no + transaction-matching equivalent since a bank account + profile isn't matched against anything - see "QBO export" + under Key decisions & lessons) /components — AppHeader (sticky top bar — brand mark, active-project breadcrumb, account menu with email + sign out; added 2026-10-13, see "Enterprise app-shell redesign" under Key @@ -662,8 +871,51 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co ResultCard.vue's old content, merged in and that file deleted outright, 2026-10-13 — see "Document delete/ rename..." under Key decisions & lessons — plus the "Move - to project" select + its own ConfirmModal), TransactionRow, - ResizablePanels. `RestoreBanner` was removed in Stage B.2 + to project" select + its own ConfirmModal; as of + transaction categorization (2026-10-31), its own + `.txn-col-head` is a two-item Transactions/Categorization + tab switch rather than a bare heading - see that entry + under Key decisions & lessons; as of the manual "Map" + button (2026-11-14), `.txn-actions-right` also has a + "Map" button - re-fetches the active document's own + sourceFile and launches `/map-layout` against it, to + CORRECT an already-successful extraction that still got + something wrong, not just the auto-triggered flow for a + failed one - see that entry under Key decisions & + lessons. QBO/Xero export support landed in + `.txn-top-bar-right` the same day (2026-11-19) as their + own separate buttons at first - see "QBO export"/"Xero + export" under Key decisions & lessons for each format's + own design - but a real reported UI problem (three + download buttons crowding the row) meant they were + consolidated, same day, into ONE "Download" trigger + + chevron dropdown (QuickBooks/Xero/CSV/Excel, in that + order) - see "Four export formats consolidated" under + Key decisions & lessons for the full restructure, + including the new generic CSV format and the + generalization of Excel's own single/all download logic + to also cover it), TransactionRow, + ResizablePanels, CategorizationPanel (NEW 2026-10-31 - + the Categorization tab's own body: a rules list + inline + "add rule" form, a "Categorized" table grouped by + accounting category, and an "Unmatched" section where + each group of identically-described unmatched + transactions gets its own inline "assign a category" + control; takes a `useCategorization()` instance, + instantiated once at TransactionsTable.vue's level, as a + prop), BankAccountProfileModal (NEW 2026-11-19 - shown + when a QBO download's own active document has no + remembered bank account profile yet; picks an existing + one or creates a new one inline - purely presentational, + same "parent owns every PocketBase call" convention + DocumentOptionsModal already established). TransactionRow + gained its own exclude-from-export checkbox (NEW + 2026-11-19, its own `.row-select` column, separate from + `.row-actions`) - see "Per-transaction 'include in + downloads' checkbox" under Key decisions & lessons; + TransactionsTable.vue's own `resultForExport()` reads it + at download time, plus a header "select/deselect all + visible" checkbox. `RestoreBanner` was removed in Stage B.2 (see Key decisions & lessons) — PocketBase being the real backend left no ambiguity for it to explain. Every button/ nav icon site-wide uses FontAwesome solid icons @@ -701,6 +953,23 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co second instance of the SAME bug already found and fixed on the backend the same day) and the `hasRequiredShape`→ `canPreview` gate-coverage fix caught during plan review. + As of the manual "Map" button (2026-11-14), reachable + WITHOUT a failed extraction at all - its own region- + drawing UI/Preview/startPage/headerBottom inference + needed zero changes; only `handleSaveMapping()` branches + on a new `layoutMapperStore.pendingDocumentId` to UPDATE + the existing document in place instead of creating a + second, duplicate one - see that entry under Key + decisions & lessons. As of 2026-11-16, a new + `imagePointScale` converts every drawn region's own + `columnMap`/`headerBottom` value from the image's natural + pixel space into PDF points (a no-op for a PDF) before + `forced_mapping` is sent - a real, systemic bug fix: every + image-sourced mapping before this sent zones in the WRONG + coordinate space entirely, since the backend's own OCR + path scales word positions to points first. See "Two real + bugs found investigating a specific real-world statement + report" under Key decisions & lessons. /views/LayoutsView.vue — NEW 2026-10-15, layout mapper L.7 — routed at /layouts (linked from AppHeader.vue's own new nav item). List/ Inspect/Test/Version-history/Rollback/Retire for every @@ -815,6 +1084,40 @@ statement files, why every document is required to belong to a project from day store; confirmed empirically (not assumed) that PocketBase's required:true rejects an empty JSON object the same way it rejects a missing one. + pb_migrations/11_add_categorization_rules.js + — NEW 2026-10-31 — creates categorizationRules + (transaction categorization - see that entry under + Key decisions & lessons). Project-scoped (owner + + project relation, mirroring documents.project's own + shape) with no sharing/promotion concept at all, + unlike layoutMappings - a client's own chart-of- + accounts mapping has no cross-user "two independent + confirmations" scenario, so no hook is involved. + pb_migrations/12_add_pending_mapping_fields.js + — NEW 2026-11-16 — relaxes documents.result to + optional and adds needsMapping/needsValueConfirmation/ + pendingFingerprint/pendingFingerprintHash/ + pendingCandidateRow/pendingFieldOrder - lets a + statement still waiting on manual mapping survive a + page reload instead of only ever living in memory; + see "Persisted pending-mapping statements" under Key + decisions & lessons. + pb_migrations/13_add_usage_events.js + — NEW 2026-11-16 — creates usageEvents (billing/usage- + tracking foundation - see "Usage tracking foundation" + under Key decisions & lessons). Append-only/immutable + (owner can create but never update/delete their own + record) - one event per successfully delivered + extraction, carrying its own page count. + pb_migrations/14_add_bank_account_profiles.js + — NEW 2026-11-19 — creates bankAccountProfiles (QBO + export foundation - see "QBO export" under Key + decisions & lessons) and adds + documents.bankAccountProfile. Project-scoped, same + no-sharing pattern categorizationRules already + established - a bank account profile has no cross- + user confirmation scenario. `accountId` deliberately + not required/labeled as the real account number. pb_hooks/promote_shared_layout_mapping.pb.js — NEW 2026-10-14 — onRecordAfterCreateSuccess on layoutMappings: promotes both records to "shared" @@ -3069,6 +3372,1723 @@ before their mapping, both correctly fail PocketBase's own required-relation che inputs, the inline errors appearing live, Preview/Save enabling - Claude-in-Chrome still did not connect this session. +**Transaction categorization, shipped 2026-10-31 - a deliberate scope expansion past +this product's own original "does not categorize transactions" boundary (see the +updated "What this is" note at the top of this file).** The user asked to review +`docs/bank_statement_categorizer/` - legacy categorization code ported from the +sibling `eib-processor` platform, placed in this repo purely as reference material, +never wired into this app's own `backend/app.py` - and propose how to bring real +categorization into this product, floating their own UI idea: Transactions as one tab, +Categorization as a second, switchable tab right beside it. + +**What the review found, and why none of the legacy code was reused as-is:** +- The legacy parser (`parse_rbc_statement`, hardcoded `DEBIT_ZONE`/`CREDIT_ZONE`/ + `BALANCE_ZONE` pixel ranges, RBC-only) duplicates what this app's own + `table_extract.py` already does far more robustly (bank-agnostic, dual-engine, + six checks, the whole layout-mapper/value-pattern stack). Categorization here + categorizes the `transactions` this app has **already extracted and verified** - no + second PDF pass, ever. +- The legacy matching logic (`common.match_description_rule`) is a black box - the + shared `common.py` module it imports doesn't exist anywhere in this repo at all + (confirmed via `find . -iname "common.py"`, empty). Its behavior was inferable from + the sample `description_rules.csv` (a dozen differently-suffixed "Misc Payment MC + FEE..." lines all collapsing to one rule keyed on a short pattern) and from the + user's own direct clarification during planning: matching is plain substring-in- + description text. Reimplemented transparently rather than guessing at the missing + module's exact internals. +- The legacy rule storage (a flat CSV, no per-client separation) is replaced by a new, + project-scoped PocketBase collection - `documents.project` was *explicitly* designed + back in the original PocketBase Stage B.1 work in anticipation of exactly this + feature (that migration's own comment: "a future per-project category-mapping + feature needs that scoping from day one"). +- The legacy "unmapped → pause → confirm → resume" flow uses an in-memory + `PENDING_RUNS` dict, explicitly commented in the legacy code as unsafe for + concurrent use. Not needed here: categorization recomputes live from whatever rules + exist right now, so resolving an unmatched description just means saving a new rule + and letting the UI recompute - no server-side session/token at all. + +**Design decisions, each made explicit rather than assumed:** +- **Categorization is computed live from current rules, never persisted on the + document.** Rules can change after a document was extracted; recomputing on every + view/export always reflects the latest rules, and needed zero new field on + `documents.result` and zero migration for document records - only the rules + themselves persist. +- **Matching stays entirely in the frontend** - same architectural split as the layout + mapper's own near-match comparator (`layoutMappingsService.scoreNearMatch`, pure JS, + never duplicated in Python). The frontend already holds both the extracted + `transactions` and (via PocketBase) the rules; Flask only gets involved at export + time, to write one additional Excel sheet, the same way `edit_log` already flows + through `/api/export` untouched. `categorizationRulesService.js`'s own + `matchDescription(description, rules)` is case-insensitive substring matching, with + the **longest matching pattern winning** when more than one rule matches - a + deterministic tie-break, no fuzzy scoring. +- **Rules are scoped by the active DOCUMENT's own `project` field** + (`extractionStore.activeDocument.project`), not `projectsStore.activeProjectId` - the + sidebar's "All" filter can be active while a specific document (which still belongs + to exactly one project) is open, and it's that document's own project whose rules + apply. Called out explicitly in the plan as the same category of binding bug this + file already records once, for "Move to project" (`result.project` vs. + `activeDocument.project`) - not repeated here. +- **No reconciliation check was added.** The legacy tool's own `reconciled` flag is + just `opening + net ≈ closing`; since categorizing only relabels transactions and + never drops or alters amounts, this identity is already guaranteed by the + extractor's own `statement_balance` check - re-deriving it here would be redundant, + not a safety net. +- **Unmatched transactions are never hidden** - grouped by raw description (count + + total) in both the UI and the exported Excel sheet's own "Unmatched" section, which + is always written even when empty, so an export with full coverage visibly shows + zero unmatched rather than silently omitting the section - the same governing rule + as everywhere else in this app (see below). +- **Rule management is inline in the Categorization tab**, not a separate routed page. + `LayoutsView.vue`'s own List/Inspect page is the obvious model for a *future* + dedicated rules-management screen if this ever needs one, but the inline version + (a compact rules list + an inline "add rule" form, plus a per-unmatched-group + "assign a category" control) covers the actual workflow with far less surface area. + +**What was built:** a new PocketBase collection, `categorizationRules` +(`pb_migrations/11_add_categorization_rules.js` - `owner`/`project` relations, +`pattern`/`accountingCategory` text fields, rules keyed off `owner` directly, same +choice `documents` makes despite also carrying a `project` relation). A new +`categorizationRulesService.js` (CRUD + the pure `matchDescription` export, same +precedent `layoutMappingsService.js` sets with `scoreNearMatch`/`findBestMatch`). A new +`useCategorization.js` composable - one pass over the active document's transactions, +bucketing each into a matched-by-category group or an unmatched-by-raw-description +group, exposing `rules`/`matched`/`unmatched`/`summaryForExport`/`addRule`/`removeRule`. +A new `CategorizationPanel.vue` (the tab's own body). `TransactionsTable.vue`'s own +`.txn-col-head` (previously a bare "Transactions" `

`) is now a two-item +Transactions/Categorization tab switch (`activeTab`, a local ref, not a route) - +everything Transactions-specific (the actions row, balance fields, mismatch note, the +table itself) is wrapped in `v-show="activeTab === 'transactions'"` rather than `v-if`, +so switching tabs never loses filter/sort state or an in-progress balance-field edit; +`.txn-top-bar` (Results/DocumentNavBar/Accept/Download) stays visible regardless of +tab, since it's document-level chrome, not Transactions-specific. The tab buttons +themselves needed `font-size:24px` to match the plain, unstyled browser-default `

` +size/weight the heading they replaced (and "Source Document"'s own heading) both +render at with no explicit font-size rule of their own - confirmed by checking that no +global `h2` rule exists in `main.css` before picking a size, not guessed. Backend: +`extraction_schema.parse_export_request` passes a new `categorization` field through +unchanged (same discipline as `edit_log`); `routes/extraction.py`'s `/api/export` +merges it into the `result` dict; `excel_service._write_categorized_summary_sheet` +writes it as a new "Categorized Summary" sheet, called conditionally exactly like +`_write_edits_sheet`. `handleDownloadCurrent` (the single-document download path) +passes `categorization.summaryForExport.value` through; `handleDownloadAll` (looping +every loaded document) deliberately does NOT, since the `categorization` composable +instance only ever exists for the ACTIVE document - a documented, accepted scope limit +rather than a silent gap, same honesty standard as every other known limitation in +this file. + +**Verified, all real, at every layer, following the plan's own suggested build +order (schema → pure logic → backend passthrough → UI, each verified before the +next was built on top of it):** +- The migration applied against the real, rebuilt PocketBase container (migrations + are baked into the image at build time via `COPY pb_migrations`, not volume-mounted + - confirmed a plain container *restart* does NOT pick up a new migration file, + only `docker compose up --build -d pocketbase` does); the real collection's schema + fetched via the REST API and confirmed to match exactly. +- `categorizationRulesService.js` (the actual file, not reimplemented) executed from a + plain Node script against the live container: `matchDescription`'s longest-pattern- + wins/no-match/case-insensitive behavior (pure, no PocketBase); `createRule`/ + `listForProject`/`deleteRule` round-tripped for real; a second, independent user's + own project confirmed to see zero of a first user's rules, and a query against the + FIRST user's own project (from the second user's session) correctly returns an empty + list rather than an error - PocketBase's `listRule` filters rather than denies, the + same behavior already documented for `documents`, reconfirmed here rather than + assumed to generalize. +- `useCategorization.js` (the actual composable, not reimplemented) executed directly + against REAL Vue reactivity (`ref`/`computed`/`watch` from the real `vue` package, + not a mock) with real PocketBase-backed rules and synthetic transactions: longest- + pattern-wins correctly distinguished "Oyster Payroll" from "Oyster Payroll - + Additional"; several transactions sharing identical raw description text correctly + grouped into one unmatched entry with the right count/sum; `summaryForExport` + confirmed plain-JSON-serializable (no stray `Map`/`Set` leaking through); `addRule` + immediately re-bucketed previously-unmatched rows into `matched` with no refetch, + and `removeRule` correctly put them back. +- `backend/measure.py` re-run against the full HSBC/RBC/Equals-Money-adjacent fixture + corpus after the backend changes - byte-identical to the documented baseline (field + accuracy 1.0 on all three, same statuses) - this stage touches zero extraction/check + code, confirmed rather than assumed. +- A real `/api/process` call against the HSBC-Sep fixture, then two real `/api/export` + calls against that actual result through the rebuilt container: one with a hand- + built `categorization` payload (confirmed the "Categorized Summary" sheet appears + with the correct matched-group row, the correct "Unmatched" header + row, and + accounting-formatted amounts) and one with the field omitted entirely (confirmed no + such sheet is written at all) - not assumed from the code, opened with `openpyxl` + inside the container and read back row by row. +- `npm run build` passes; the built bundle hash-matched against what the rebuilt `app` + container actually serves at `/` (same file hash both places, not just "the build + succeeded"); grepped for `CategorizationPanel`/`txn-tab`/`categorizationRules` in the + built JS and confirmed present. +- Test data (rules, projects, users) from every verification pass deleted from the + real running PocketBase afterward via direct superuser REST calls, in dependency + order (categorizationRules → project → user - confirmed by testing: deleting a + project while a categorizationRules record still referenced it correctly failed with + PocketBase's own required-relation error, same category of ordering this file + already documents for layoutMappings/documents/users). + +**Not machine-verified:** the actual click-through - switching tabs, typing into the +inline "add rule" form, watching an unmatched group recategorize live after saving a +rule - Claude-in-Chrome did not connect this session, same standing limitation as +every other UI-only verification in this file. + +**Manual "Map" button - correcting an already-successful (but wrong) extraction, +shipped 2026-11-14.** A real statement extracted without throwing any error, but got +something wrong - the wrong start page/header boundary silently pulled preamble text +into the first transaction's own description, the same category of mistake L.6/L.7's +own `startPage`/`headerBottom` work exists to prevent, just not caught by the +auto-detector this time. Until now, the ENTIRE layout-mapper/`/map-layout` screen was +only ever reachable automatically, when extraction failed outright +(`LayoutMappingRequired`/`ValueRecognitionRequired`) - there was no way for a user to +proactively open it against a statement that technically "succeeded." + +**The real gap this exposed**: a successful extraction never computed or returned a +fingerprint at all - only the two failure paths in `extraction_service.run()` did. +Fixed by computing it UNCONDITIONALLY now, right after extraction succeeds (the same +`table_extract.header_candidate_geometry()` + `layout_fingerprint.compute_fingerprint()` +call the failure paths already make, not threaded through from elsewhere) - included +in every `/api/process` response as `fingerprint`/`fingerprintHash`, `None`/`None` for +an OCR-sourced document (no text layer to derive one from). `pipeline_service.run()` +passes both straight through unchanged. This is pure addition - no existing +extraction/check behavior touched, confirmed via `backend/measure.py` (byte-identical +to the documented baseline before and after). + +**The frontend side - reusing 100% of the existing L.1-L.8 machinery, not a second +screen.** `TransactionsTable.vue` gained a "Map" button in `.txn-actions-right` +(first, before "Flagged only"/"Next flagged" - `btn-toggle`, no new CSS needed), +enabled only when the active document's own result carries a fingerprint. Clicking it: +re-fetches the document's own `sourceFile` from PocketBase/R2 (the raw `File` object +isn't kept around once a document is loaded - see `extractionStore.js`'s own doc +shape), wraps the fetched bytes back into a `File` with the original filename, and +calls `layoutMapperStore.setPending(file, fingerprint, fingerprintHash, documentId)` - +the EXACT same action the auto-triggered failure flow already calls, just with a new +4th argument. `ManualMappingView.vue` needed ZERO changes to its own region-drawing +UI, Preview, or `startPage`/`headerBottom` inference - all of that already works +identically regardless of how the screen was reached. + +**The one real design decision this needed**: Save had to behave differently +depending on how the screen was reached. The ORIGINAL flow (a failed extraction) has +no existing document to speak of, so Save correctly creates a brand new one. Reusing +that path unchanged for a document being CORRECTED would have left the user with TWO +documents - the old, wrong one still sitting there, plus a new, duplicate, correct +one - not what "correct the mapping" means from their own perspective. Fixed with a +new `layoutMapperStore.pendingDocumentId` (null for the normal flow, set for this +one) - `ManualMappingView.vue`'s `handleSaveMapping()` branches on it: set → +`documentsService.updateDocument(pendingDocumentId, {result, layoutMappingUsed, ...})` ++ a new `extractionStore.replaceDocumentResult(pbId, result, {...})` (finds the +document by id and replaces its result/layout fields/flaggedIndexes in place, rather +than `addDocument`'s own append); unset → the original create-a-new-document path, +byte-for-byte unchanged. + +**Verified, all real, against the real rebuilt container - 15 assertions, executing +the actual store/service files (never reimplementations):** a real `/api/process` +call against the RBC fixture confirmed a successful extraction now carries a genuine +fingerprint; the document was saved normally (simulating the original, already- +"successful" upload); the exact re-fetch sequence `handleMapClick()` itself performs +(`documentsService.getDocument` → `sourceFileUrl` → `fetch` → wrap as `File`) was +confirmed to reproduce the ORIGINAL upload's bytes exactly, byte-for-byte; the real +`layoutMapperStore.setPending(...,documentId)` and `extractionStore +.replaceDocumentResult(...)` were exercised directly, confirming exactly ONE document +record exists in PocketBase after Save (not two), exactly ONE in-memory document in +`extractionStore.documents` (not two), and both correctly reflect the new mapping's +id - the "update in place, don't duplicate" behavior this whole design decision +exists for. `backend/measure.py` re-run clean after the backend half. `npm run build` +passes; the `app` container rebuilt and confirmed serving the new bundle. Test data +(mapping, version, document, project, user) deleted from the real PocketBase +afterward in dependency order (version → mapping → document → project → user). + +**Not machine-verified:** the actual click-through - clicking Map, drawing the +correcting regions, Preview, Save, and watching the SAME document update in the +Transactions tab afterward rather than a new one appearing - Claude-in-Chrome did not +connect this session, same standing limitation as every other UI-only feature in this +file. + +**Two follow-up fixes to the Map button, same day: it was disabled for every real +statement, and it moved into the "Move to" row.** + +**The real bug, found by checking the live PocketBase data directly rather than +guessing:** every document the user had actually loaded predates this feature's own +backend change - their stored `result` JSON genuinely has no `fingerprint` key at +all, since it was saved by a Flask process from before that change shipped. A fresh +`/api/process` call, confirmed directly, already returns one correctly; the button +gating on `result.fingerprint` being present was therefore correct in spirit but +left every pre-existing document (which is to say, everything the user had to test +with) permanently disabled with no way out short of a full re-upload. + +Fixed by making the button SELF-HEAL instead of just checking for a fingerprint: +`canMap` now gates only on `extraction_method !== 'ocr'` (the one case that's +genuinely, structurally impossible - no text layer to derive a fingerprint from, +re-extracting can't fix that). `handleMapClick()` re-fetches the source file as +before, but if the CURRENT result has no fingerprint, it now re-runs +`extractionService.process()` against that same re-fetched file first - which, on +the NOW-current backend, always returns one - before proceeding into the mapper. +Verified directly: built a document whose stored result had its fingerprint +stripped out (reproducing the exact real documents found above), confirmed it +genuinely had none after a real re-fetch from PocketBase, then confirmed the same +self-heal branch `handleMapClick()` runs correctly recovers a real fingerprint via +re-extraction - a document extracted before this backend change is never stuck. + +**Moved into the same line as "Move to project," per explicit request** - the +button's own `.txn-actions-right` slot was the wrong spot; it now lives inside +`.move-to-project` itself, directly after the project `