Restructure frontend to Vue 3 + Vite (Stage 2 of 2)

Rebuilds templates/index.html (896 lines of vanilla JS, no framework, no
build step) as frontend/, a Vue 3 app per ENTERPRISE_STANDARDS.md's
frontend layering (views -> components -> composables -> services ->
repositories, Pinia for stores) - same agreed scope as Stage 1 (backend):
structure + commenting, not the full SaaS-shaped doc.

The full original file was read in full before starting (every function
enumerated against the plan, not re-derived from memory) to make sure
nothing documented in CLAUDE.md's "Frontend / UI state" section got
simplified away: sticky side-by-side layout with a draggable resizer,
Hide/Show Source Doc, collapsible Result card, per-row pencil-to-edit,
comma-formatted numbers, localStorage persistence with a restore banner,
image zoom controls, the pencil-icon-color and description-autogrow
fixes from earlier this session.

The original ask that started this whole detour - processing-phase text
with an animated ellipsis during /api/process - lands here as the one
genuinely new feature (useProcessingPhases.js + ProcessingIndicator.vue),
honestly simulated rather than claiming real progress (the backend is
one synchronous request with no streaming signal).

backend/app.py now serves frontend/dist (built via a new Dockerfile
multi-stage build: a node stage runs npm ci && npm run build, the Python
stage copies backend/ + that dist/ output) instead of rendering a Jinja
template - a manual SPA-fallback route serves a real static asset if one
exists at the requested path, else index.html. One real bug caught and
fixed before this ever ran: the first version also left Flask's own
automatic static route enabled, registering a duplicate/conflicting rule
against the same /<path:...> pattern as the manual catch-all - fixed by
disabling Flask's own static handling (static_folder=None) entirely.

Verified without a browser (the extension could not connect, tried
repeatedly): npm run build succeeds, formatService.js's pure functions
tested directly in Node, every prop/emit/store reference cross-checked
by hand across all ~20 new files, and full regression through the real
Docker container (SPA serving, static assets, /health, /api/* routing,
dual-engine extraction, measure.py - all unaffected or identical to
baseline). Actual interactive behavior - upload, drag/drop, the
processing-phase animation, editing, zoom, the resizer, persistence/
restore, download - was verified by the user in their own browser, not
by Claude. templates/index.html was kept in place as a fallback until
that confirmation came back, then deleted.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
JasonFraser 2026-10-12 06:32:49 -04:00
parent 081ab6ac50
commit 6e4da3f385
37 changed files with 3455 additions and 960 deletions

239
CLAUDE.md
View File

@ -100,7 +100,14 @@ docker compose down # stop and remove both containers
```
- App: http://localhost:8091
- No hot reload — template/code edits require a rebuild to show up.
- Backend edits require a Docker rebuild (`docker compose up --build -d app`) to show up —
no hot reload inside the container. Frontend development has its own faster loop: `cd
frontend && npm run dev` runs Vite's dev server (default `localhost:5173`) with real hot
module reload, proxying `/api/*` to `localhost:8091` (see `frontend/vite.config.js`) so it
talks to the same running backend/Docling containers without any CORS setup. The Docker
image itself always serves the *built* `frontend/dist` (`npm run build`, done
automatically as the Dockerfile's first stage) — rebuild the image to see frontend changes
at `:8091`, same as a backend change.
- There is still no test suite, but the measurement harness now exists:
`python3 backend/measure.py` (from the repo root; needs `openpyxl`, `pdfplumber` on
PATH/venv — the same `requirements.txt` the app itself uses) runs every
@ -112,20 +119,21 @@ docker compose down # stop and remove both containers
## Architecture
**Restructured 2026-10-11 into `backend/`, layered per `ENTERPRISE_STANDARDS.md`** (routes
→ services → repositories → schemas) — the old flat `app/` directory no longer exists. See
"Enterprise-standards restructure" under Key decisions & lessons for the scope decision
(structure + commenting + applicable security only, not the full SaaS-shaped doc) and the
judgment call on what counts as a "repository" here (no DB exists — see that section
before assuming a pattern from the standards doc maps 1:1 onto this app). `templates/`
still holds the live frontend (see "Frontend / UI state" below) — the Vue 3 rewrite the
standards doc's frontend layering implies is its own later stage, not done yet; `backend/`
still serves `templates/index.html` at `/` unchanged in the meantime.
**Restructured 2026-10-11/12 into `backend/` + `frontend/`, layered per
`ENTERPRISE_STANDARDS.md`** — backend: routes → services → repositories → schemas; frontend:
views → components → composables → services → repositories, Pinia for global state. The old
flat `app/` directory and `templates/index.html` no longer exist — both restructures are
done (see "Enterprise-standards restructure" and "Frontend restructure to Vue 3" under Key
decisions & lessons for the scope decision on each: structure + commenting + applicable
security only, not the full SaaS-shaped doc — and the judgment call on what counts as a
"repository" here, since there's no DB). `backend/app.py` now serves the built Vue app
(`frontend/dist`, produced by `npm run build`) as static files at `/`, not a Jinja template.
```
/backend
app.py — Flask app factory: registers blueprints, keeps "/"
serving today's templates/index.html
app.py — Flask app factory: registers blueprints; "/" and any
other non-API path serve frontend/dist's index.html
(SPA fallback) or the matching static asset if one exists
dependencies.py — DOCLING_URL/UPLOAD_FOLDER/OUTPUT_FOLDER read from env
once at import time; repositories import this directly
rather than reaching into Flask's current_app
@ -243,13 +251,65 @@ still serves `templates/index.html` at `/` unchanged in the meantime.
reports/logs both of the spec's section-11 measures. Position-matched field comparison
(not matched by value), so a swapped-order bug shows up as a mismatch rather than being
silently absorbed. Run from the repo root: `python3 backend/measure.py`.
- `templates/index.html` — the entire frontend: a single vanilla-JS page, no framework,
no build step. See "Frontend / UI state" below — it has been through many rounds of
layout and theme iteration and the current state is not obvious from a first read.
- `frontend/` — Vue 3 + Vite, replacing the old single-file `templates/index.html`
(896 lines of vanilla JS, no framework, no build step). See "Frontend restructure to Vue
3" under Key decisions & lessons for the full migration record, and "Frontend / UI state"
below for every behavior this had to faithfully reproduce (sticky layout, resizer,
per-row editing, localStorage persistence, image zoom, etc.) — it went through many
rounds of layout/theme iteration before this restructure and none of that was simplified
away in the rewrite.
```
/frontend/src
main.js — createApp(App).use(pinia).use(router).mount('#app')
App.vue — page chrome (<main> wrapper) around the routed view
/assets/main.css — the full original CSS, moved verbatim - same tokens, same rules
/router/index.js — one route today ('/' -> ExtractorView), kept as a real
router per the standards doc's structure
/stores (Pinia)
extractionStore.js — currentResult (kept as one cohesive object matching the
server's own shape), currentDocKey, flaggedIndexes,
errorMessage (the SAME shared error area the original used
for upload/process/download errors alike - not split per
component), openingBalanceInput/closingBalanceInput (read
live by any recheck/export call, not just the inputs
themselves) + effectiveOpeningBalance/effectiveClosingBalance
getters
uiStore.js — resultExpanded, pdfColHidden, pdfColWidthPct,
restoreBannerVisible, layoutVersion (an incrementing counter
every TransactionRow's own description textarea watches to
re-measure its height - replaces the original's global
autoGrowAll() call, bumped on a resize-drag ending or the
Hide/Show toggle, the same two trigger points the original had)
/repositories — raw HTTP/storage access only: extractionRepository.js
(fetch calls to /api/process|recheck|export),
localStorageRepository.js
/services — extractionService.js (docKeyFor, persist/restore,
effectiveBalance, process/recheck/export orchestration),
formatService.js (fmtMoney/fmtNum/parseNum - escapeHtml
dropped, redundant once Vue's own {{ }} auto-escapes)
/composables — useFileUpload, useExtraction, useProcessingPhases (NEW -
the original ask that started this detour, see below),
useRowEditing, useImageZoom, useAutoGrow
/components — FileUploadZone, ProcessingIndicator (NEW), RestoreBanner,
ResultCard, SourceDocumentPanel, TransactionsTable,
TransactionRow, ResizablePanels
/views/ExtractorView.vue — composes everything above - this IS the whole page
```
**One real bug caught and fixed during this restructure, server-side:** the production
`Dockerfile` serves `frontend/dist` from Flask via a catch-all route
(`@app.route("/<path:path>")`) that serves a real static file if one exists at that path,
else falls back to `index.html` (SPA routing). The first version of this also left
Flask's OWN automatic static route enabled (`static_folder=FRONTEND_DIST,
static_url_path=""`) — registering TWO rules against the identical `/<path:...>` pattern.
Fixed by setting `static_folder=None` and handling serving entirely in the manual
catch-all. Confirmed working end-to-end against the real container: `/` serves the SPA,
a real asset path (`/assets/*.js`) serves with the correct content-type, `/health` and
`/api/*` aren't shadowed by the catch-all.
## Key decisions & lessons
**Enterprise-standards restructure, Stage 1 of 2, done 2026-10-11.** User asked to split
**Enterprise-standards restructure, Stage 1 of 2 (backend), done 2026-10-11 — see "Frontend
restructure to Vue 3" below for Stage 2.** User asked to split
this repo into `frontend/`/`backend/` and rebuild both per `ENTERPRISE_STANDARDS.md` — a
generic template written for a multi-tenant SaaS (JWT auth, PocketBase, Sentry, circuit
breakers, CI/CD with staging/production, 80%-enforced test coverage, daily backups), none
@ -270,11 +330,11 @@ not repositories, since they aren't access to an external system; `table_extract
already calling pdfplumber directly before this restructure, and that didn't change.
This was **Stage 1 (backend) only, by explicit agreement** — the user asked to checkpoint
before the much larger, riskier Stage 2 (frontend → Vue 3 + Vite, Pinia, composables,
~10 components replacing ~830 lines of vanilla JS, where every documented behavior in
"Frontend / UI state" below has to be faithfully reproduced). `backend/app.py` deliberately
still serves `templates/index.html` at `/` unchanged — stripping that out now, before Vue
exists to replace it, would have broken the UI the user tests in their own browser.
before the much larger, riskier Stage 2 (frontend → Vue 3 + Vite, Pinia, composables, ~10
components replacing ~830 lines of vanilla JS) — done the next day, see below.
`backend/app.py` deliberately still served `templates/index.html` at `/` unchanged
throughout Stage 1 — stripping that out before Vue existed to replace it would have broken
the UI the user was testing in their own browser; that only changed once Stage 2 shipped.
Verified identical behavior before deleting the old `app/` directory: `measure.py` against
the fixture corpus (same field accuracy as the pre-restructure baseline), plus real
end-to-end `curl` tests through the rebuilt Docker container on both the dual-engine path
@ -297,6 +357,50 @@ correctly surfaces the `ocr_source` check and stays below "Verified", a mixed
unaffected — confirmed both as a direct function call and through `/api/recheck` on the
real running app.
**Frontend restructure to Vue 3, Stage 2 of 2, done 2026-10-12.** Rebuilt
`templates/index.html` (896 lines of vanilla JS, read in full before starting — every
function enumerated against the plan, not re-derived from memory) as `frontend/`, a Vue 3 +
Vite app per `ENTERPRISE_STANDARDS.md`'s frontend layering (views → components →
composables → services → repositories, Pinia for stores) — same scope agreement as Stage 1.
Full structure is in the Architecture section above; this entry is about what the migration
itself required getting right.
The original ask that triggered this whole detour — processing-phase text with an animated
ellipsis during `/api/process` — landed here as the one genuinely new feature
(`useProcessingPhases.js` + `ProcessingIndicator.vue`), built once in Vue rather than once
in vanilla JS and then rewritten. It's honestly simulated, not real progress: `/api/process`
is one synchronous request with no streaming signal, so the phase labels
("Reading document…" → "Extracting transactions…" → "Cross-checking with a second
engine…" → "Running verification checks…" → "Preparing results…") cycle on a timer that
holds on the last phase if the real request runs long, rather than looping back in a way
that would misleadingly suggest the work restarted.
**One real bug caught mid-build, before it ever shipped:** `ResultCard.vue`'s first draft
gave the Download button's own errors a separate local `error-note`, instead of routing
them through the shared `extractionStore.errorMessage` the original vanilla-JS version used
for upload/process/download errors alike (one `#errorNote` element, several different
call sites). Caught by checking the draft against the plan's own explicit callout of this
shared-error-area behavior, fixed before the build was ever run.
**Honest account of what got verified and how, since the browser extension couldn't connect
for interactive testing (tried repeatedly):**
- `npm run build` succeeds; `formatService.js`'s pure functions tested directly in Node
- Every prop/emit name and every Pinia store field/action reference cross-checked by hand
across all ~20 new files (`grep` every usage site, confirm each matches its
definition) — this is how the Flask static-route duplication bug (see the Architecture
section's own callout) was the only other real bug found, everything else checked out
- Full regression through the real Docker container: `/` serves the SPA, static assets
serve with correct content-types, `/health` and `/api/*` untouched, dual-engine
extraction returns identical results to the pre-restructure baseline, `measure.py`
unaffected (this stage touches no backend code)
- **Actual interactive behavior — file upload, drag/drop, the processing-phase animation,
pencil-to-edit/Save/Cancel, image zoom, the resizer, Hide/Show Source Doc, the
collapsible Result card, localStorage persistence/restore, Download Excel — was verified
by the user in their own browser, not by Claude.** `templates/index.html` was
deliberately kept in place as a fallback until the user confirmed this worked, then
deleted once they had. If this is ever revisited and something in that list turns out
subtly broken, this is the honest paper trail of what was and wasn't machine-verified.
**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
@ -452,45 +556,72 @@ be set explicitly (`/usr/share/tesseract-ocr/5/tessdata`); tesserocr does not re
auto-discover Debian's tessdata location on its own (confirmed for real: failed with
"invalid tessdata path: ./" without it).
## Frontend / UI state (as of 2026-10-11)
## Frontend / UI state (as of 2026-10-12)
**Theme is enterprise-light, not the Bettersight brand default.** `UI_DESIGN_THEME.md`
specifies a dark-first brand system (deep navy base, single lime-green accent) — that's
the default for Bettersight-family products. This app's `templates/index.html` was
explicitly converted away from that default, on direct user request, to match a specific
enterprise-SaaS reference screenshot (light background, standard blue `#2563EB` accent,
white cards, 8px radii). The conversion kept the **same set of CSS custom properties**
defined in `UI_DESIGN_THEME.md` (same names, same count) and only changed their *values*
— including reusing that doc's own already-specified "light surface" and "text on light
surfaces" token values where they existed, rather than inventing new ones. If asked to
touch the theme again, preserve this token-value-only discipline rather than restructuring
the `:root` block or hardcoding colors inline.
the default for Bettersight-family products. This app was explicitly converted away from
that default, on direct user request, to match a specific enterprise-SaaS reference
screenshot (light background, standard blue `#2563EB` accent, white cards, 8px radii). The
conversion kept the **same set of CSS custom properties** defined in `UI_DESIGN_THEME.md`
(same names, same count) and only changed their *values* — including reusing that doc's own
already-specified "light surface" and "text on light surfaces" token values where they
existed, rather than inventing new ones. This lives in `frontend/src/assets/main.css` now
(moved verbatim in the Vue restructure — see Key decisions & lessons — not rewritten). If
asked to touch the theme again, preserve this token-value-only discipline rather than
restructuring the `:root` block or hardcoding colors inline.
Key current UI behaviors, each the result of an explicit, specific user request (don't
"simplify" these away without asking first):
- The upload zone (`#fileInput`) accepts `.pdf`, `.jpg`/`.jpeg`, and `.png` (added
2026-10-11 for OCR support — see "OCR / scanned statements" above) — the client-side
extension check and the preview `<iframe>` both widened accordingly; an image file in
that same iframe just renders as an image (the PDF-viewer hash params are harmlessly
ignored), so no separate `<img>` element or branching was needed for this.
- PDF ("Source Document") and Transactions sit side-by-side with a draggable resizer
(`.resizer`, styled as a vertical grip-knob), both wrapped in `.review-grid` which is
what's `position:sticky` (not the PDF column alone) so they scroll as one unit.
- A Hide/Show toggle in the Transactions header (`#togglePdfBtn`, labeled "Hide Source
Doc"/"Show Source Doc") collapses the PDF column so Transactions fills the row.
- The Result card is collapsible: a chevron + "Result" heading on the left toggle the
status banner/checks list; Download Excel stays on the right, always visible; every
fresh extraction starts collapsed (`setResultExpanded(false)` runs in `renderResult`).
"simplify" these away without asking first) — implementation pointers reflect the Vue
restructure; the behavior itself predates it and is unchanged:
- The upload zone accepts `.pdf`, `.jpg`/`.jpeg`, and `.png` (added 2026-10-11 for OCR
support — see "OCR / scanned statements" above). A PDF gets the browser's native viewer
(its own zoom toolbar) in an iframe; an image gets its own dedicated zoomable/scrollable
panel instead (added 2026-10-11, after the OCR support landed — an image in the same
iframe has no viewer chrome at all, confirmed by testing it) — see
`SourceDocumentPanel.vue`/`useImageZoom.js`: −/+/Fit controls, width-based zoom (not CSS
`transform:scale`, so the panel's `overflow:auto` actually produces real scrollbars when
zoomed in), opens at fit-width by default (the same first impression the PDF viewer's own
`view=FitH` gives).
- PDF/image ("Source Document") and Transactions sit side-by-side with a draggable resizer
(`ResizablePanels.vue`, the handle styled as a vertical grip-knob), both wrapped in one
sticky flex row so they scroll as one unit (not the source-doc column alone).
- A Hide/Show toggle in the Transactions header (`TransactionsTable.vue`, driven by
`uiStore.pdfColHidden`, labeled "Hide Source Doc"/"Show Source Doc") collapses the
source-doc column so Transactions fills the row.
- The Result card (`ResultCard.vue`) is collapsible: a chevron + "Result" heading on the
left toggle the status banner/checks list (`uiStore.resultExpanded`); Download Excel
stays on the right, always visible; every fresh extraction starts collapsed.
- Opening/closing balance inputs always start blank (never auto-filled) — a separate
read-only "Calculated: $X" readout below each one shows the auto-detected or typed
value, turning green when `statement_balance` check outcome is "pass". This was a
deliberate choice to reduce confusion about what's user-entered vs. auto-detected.
- Per-row edit lock: cells are read-only until that row's pencil icon is clicked; a
per-row Save commits to `currentResult` and triggers `/api/recheck`; Cancel discards.
- All numeric displays are comma-formatted (`fmtMoney`/`fmtNum`).
- Edits persist to `localStorage`, keyed by the source file's name+size (`docKeyFor`),
so a crash/reload can restore in-progress edits; the PDF preview itself can't be
persisted this way and needs the same file re-selected to reappear.
read-only "Calculated: $X" readout below each one shows the auto-detected or typed value,
turning green when the `statement_balance` check outcome is "pass". Deliberate, to reduce
confusion about what's user-entered vs. auto-detected. One real asymmetry worth knowing
if this is ever touched: the opening readout is a snapshot of the ORIGINAL extraction's
own `opening_balance` (the backend never returns a new one on recheck, only status/checks
change) while the closing readout recomputes live on every recheck — confirmed by reading
the original vanilla-JS implementation closely before the Vue rewrite, and reproduced
deliberately rather than "fixed" as an inconsistency (see `TransactionsTable.vue`'s own
comment).
- Per-row edit lock (`TransactionRow.vue`/`useRowEditing.js`): cells are read-only until
that row's pencil icon is clicked (pencil rendered in the blue accent color, fixed
2026-10-11 — it was the default muted gray, inconsistent with the Save button's own blue);
a per-row Save commits the edit and triggers a recheck; Cancel discards. The description
textarea's auto-height had a real bug, also fixed 2026-10-11: hiding the Source Document
panel widens the transactions column, which can change how description text wraps, but
nothing re-measured the textarea height when that happened (only an actual edit/save
did) — now `uiStore.layoutVersion` bumps on that toggle (and on a resize-drag ending) and
every row's own textarea watches it to re-measure.
- All numeric displays are comma-formatted (`formatService.js`'s `fmtMoney`/`fmtNum`).
- Edits persist to `localStorage`, keyed by the source file's name+size
(`extractionService.docKeyFor`), so a crash/reload can restore in-progress edits; the
source-document preview itself can't be persisted this way and needs the same file
re-selected to reappear.
- The Extract button shows simulated processing-phase text with an animated ellipsis while
`/api/process` is in flight (`useProcessingPhases.js`/`ProcessingIndicator.vue`, added
2026-10-12) — honestly simulated, not real progress (the backend is one synchronous
request with no streaming signal): cycles through an ordered, honestly-labeled phase
sequence on a timer, holding on the last phase rather than looping if the real request
runs long.
## Outstanding before Phase 1 can be called done

View File

@ -1,3 +1,13 @@
# Stage 1: build the Vue frontend (frontend/dist is the only output
# carried into the final image).
FROM node:20-slim AS frontend-build
WORKDIR /frontend
COPY frontend/package.json frontend/package-lock.json* ./
RUN npm install
COPY frontend/ .
RUN npm run build
# Stage 2: the Python backend, serving the built frontend as static files.
FROM python:3.11-slim
WORKDIR /app
@ -18,7 +28,12 @@ ENV TESSDATA_PREFIX=/usr/share/tesseract-ocr/5/tessdata
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# Only backend/ and the built frontend are copied in - fixtures/docs/
# results/measure.py's own corpus aren't needed at runtime (measure.py
# is a dev-time verification tool, run from the repo root, not part of
# the deployed image's own behavior).
COPY backend/ backend/
COPY --from=frontend-build /frontend/dist frontend/dist
RUN mkdir -p /app/uploads /app/outputs

View File

@ -1,11 +1,13 @@
# Flask app factory - registers blueprints, wires config from dependencies.py.
import os
from flask import Flask, render_template
from flask import Flask, send_from_directory
import dependencies
from routes.extraction import extraction_bp
from routes.health import health_bp
FRONTEND_DIST = os.path.join(os.path.dirname(__file__), "..", "frontend", "dist")
def create_app():
"""
@ -16,23 +18,37 @@ def create_app():
returns (Flask) - the configured app, routes registered, ready to run
Steps:
1. Create the Flask instance (template_folder still points at the
existing templates/ directory - the frontend restructure into
its own Vue app is a later stage; this app keeps serving the
current UI unchanged in the meantime)
1. Create the Flask instance, static files served from the built
Vue app (frontend/dist, produced by `npm run build`) rather than
Jinja-rendered templates - Stage 2 of the enterprise-standards
migration moved the frontend to its own Vue 3 app; templates/
is no longer used
2. Apply config from dependencies.py (upload size cap)
3. Register the extraction and health blueprints
4. Keep the "/" route serving today's UI, unchanged
4. "/" and any other non-API path serve the SPA's own index.html
(Vite's own client-side router has just the one route today,
but this keeps a future deep link or page refresh working) -
Flask's static route only matches an EXISTING file under
frontend/dist (e.g. /assets/index-XXXX.js), so this catch-all
is what serves index.html for everything else
"""
app = Flask(__name__, template_folder="../templates")
# static_folder=None - Flask's own automatic static route would
# register at the same "/<path:filename>" pattern as the manual
# catch-all below, a duplicate/conflicting route registration.
# Serving is handled entirely by that catch-all instead.
app = Flask(__name__, static_folder=None)
app.config["MAX_CONTENT_LENGTH"] = dependencies.MAX_CONTENT_LENGTH
app.register_blueprint(extraction_bp)
app.register_blueprint(health_bp)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def spa(path):
full_path = os.path.join(FRONTEND_DIST, path)
if path and os.path.isfile(full_path):
return send_from_directory(FRONTEND_DIST, path)
return send_from_directory(FRONTEND_DIST, "index.html")
return app

24
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

3
frontend/.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"recommendations": ["Vue.volar"]
}

5
frontend/README.md Normal file
View File

@ -0,0 +1,5 @@
# Vue 3 + Vite
This template should help get you started developing with Vue 3 in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
Learn more about IDE Support for Vue in the [Vue Docs Scaling up Guide](https://vuejs.org/guide/scaling-up/tooling.html#ide-support).

14
frontend/index.html Normal file
View File

@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;600&display=swap" rel="stylesheet">
<title>Bank Statement Extractor</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

1578
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
frontend/package.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"pinia": "^4.0.3",
"vue": "^3.5.42",
"vue-router": "^5.4.0"
},
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.8",
"vite": "^8.3.0"
}
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

11
frontend/src/App.vue Normal file
View File

@ -0,0 +1,11 @@
<script setup>
/**
* App.vue - page chrome (the <main> wrapper) around the routed view.
*/
</script>
<template>
<main>
<RouterView />
</main>
</template>

View File

@ -0,0 +1,279 @@
:root{
/* Accent — single brand color, per UI_DESIGN_THEME.md (enterprise variant: standard blue) */
--blue:#2563EB;
--blue-b:#1D4ED8;
--cyan:#2563EB;
/* Status colors — never reused as brand accent */
--green:#16A34A; --green-l:#DCFCE7; --green-d:#15803D;
--amber:#D97706; --amber-l:#FEF3C7;
--red:#DC2626; --red-l:#FEE2E2;
/* Background stack — light surfaces, per UI_DESIGN_THEME.md's own
light-surface tokens (--surface/--surface-2/--page) */
--navy:#EEF1F6;
--navy-2:#FFFFFF;
--navy-3:#F8FAFD;
/* Text on light surfaces, per UI_DESIGN_THEME.md */
--t1:#0D1526; --t2:#2D3A52; --t3:#6B7A99; --t4:#9BA8C0;
/* Borders, per UI_DESIGN_THEME.md's light-surface tokens */
--border:rgba(28,56,121,.11);
--border-2:rgba(28,56,121,.18);
--border-b:rgba(37,99,235,.28);
--shadow:0 2px 8px rgba(12,26,60,.06),0 8px 28px rgba(12,26,60,.09),0 0 0 1px rgba(28,56,121,.06);
--shadow-h:0 4px 16px rgba(12,26,60,.10),0 16px 48px rgba(12,26,60,.13),0 0 0 1px rgba(37,99,235,.18);
--fd:'Inter',sans-serif;
--fb:'Inter',sans-serif;
--fm:'JetBrains Mono',monospace;
--r:8px;
}
*{ box-sizing:border-box; margin:0; padding:0; }
body{ font-family:var(--fb); background:var(--navy); color:var(--t1); min-height:100vh; -webkit-font-smoothing:antialiased; }
main{ position:relative; z-index:1; max-width:1360px; margin:0 auto; padding:56px 24px 90px; }
.eyebrow{
display:inline-flex; align-items:center; gap:7px;
font-family:var(--fm); font-size:11px; font-weight:600; letter-spacing:.12em; text-transform:uppercase;
color:var(--blue); background:rgba(37,99,235,.08); border:1px solid var(--border-b);
padding:5px 12px; border-radius:20px; margin-bottom:16px;
}
.eyebrow::before{ content:''; width:6px; height:6px; border-radius:50%; background:var(--blue); }
h1{ font-family:var(--fd); font-weight:800; font-size:30px; letter-spacing:-.01em; margin-bottom:10px; }
.sub{ color:var(--t3); font-size:14.5px; line-height:1.6; max-width:620px; margin-bottom:34px; }
.card{
background:var(--navy-2); border:1px solid var(--border); border-radius:var(--r);
padding:28px 26px; margin-bottom:22px; box-shadow:var(--shadow);
}
.card h2{
font-family:var(--fm); font-size:11px; font-weight:600; letter-spacing:.1em; text-transform:uppercase;
color:var(--blue); margin-bottom:18px;
}
.file-zone{
border:1.5px dashed var(--border-2); border-radius:10px; padding:26px 20px; text-align:center;
cursor:pointer; transition:all .2s; position:relative; margin-bottom:16px;
}
.file-zone:hover, .file-zone.drag-over{ border-color:var(--blue); background:rgba(37,99,235,.04); }
.file-zone input[type="file"]{ position:absolute; inset:0; opacity:0; cursor:pointer; width:100%; height:100%; }
.file-zone-label{ font-size:13.5px; color:var(--t2); }
.file-zone-label strong{ color:var(--blue); font-weight:600; }
.file-zone-sub{ font-size:11.5px; color:var(--t4); margin-top:5px; }
.file-zone-sub.file-chosen-name{ font-family:var(--fm); font-size:12px; color:var(--blue); margin-top:5px; }
.fields{ display:flex; flex-wrap:wrap; gap:16px; margin-bottom:16px; }
.fields > div{ flex:1 1 180px; min-width:160px; }
.fields label{ font-size:11.5px; color:var(--t3); display:block; margin-bottom:6px; white-space:normal; }
.fields input{
width:100%; padding:9px 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;
}
.fields input:focus{ border-color:var(--blue); }
.calc-readout{ font-family:var(--fm); font-size:11.5px; color:var(--t3); margin-top:6px; min-height:14px; }
.calc-readout.match{ color:var(--green); }
.note{ font-size:12px; color:var(--t4); line-height:1.6; margin-bottom:18px; }
.btn{
display:inline-flex; align-items:center; justify-content:center; gap:8px;
font-family:var(--fd); font-weight:700; font-size:13.5px; border-radius:10px; border:none;
padding:11px 22px; cursor:pointer; transition:all .2s;
}
.btn-primary{ background:var(--blue); color:var(--navy-2); box-shadow:0 4px 18px rgba(37,99,235,.18); }
.btn-primary:hover{ background:var(--blue-b); }
.btn-primary:disabled{ opacity:.35; cursor:not-allowed; box-shadow:none; }
.btn-ghost{
background:transparent; color:var(--t1); border:1px solid var(--border-2);
}
.btn-ghost:hover{ border-color:var(--border-b); color:var(--blue); }
.spinner{ font-family:var(--fm); font-size:12px; color:var(--t4); margin-left:12px; }
.error-note{
display:none; font-size:12.5px; color:var(--red); background:var(--red-l);
border:1px solid rgba(220,38,38,.3); border-radius:9px; padding:11px 14px; margin-top:12px;
}
.error-note.visible{ display:block; }
.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;
margin-bottom:18px;
}
.status-banner.Verified{ background:var(--green-l); color:var(--green-d); }
.status-banner.Needs-review{ background:var(--amber-l); color:var(--amber); }
.status-banner.Failed{ background:var(--red-l); color:var(--red); }
.period-note{ font-size:12.5px; color:var(--t3); margin-bottom:18px; }
.result-head{ display:flex; align-items:center; justify-content:space-between; gap:12px; }
.result-head-left{ display:flex; align-items:center; gap:10px; cursor:pointer; }
.result-head-left h2{ margin-bottom:0; }
.collapse-arrow{
display:inline-flex; align-items:center; justify-content:center;
width:20px; height:20px; background:transparent; border:none; cursor:pointer;
color:var(--blue); font-size:12px; line-height:1; transition:transform .2s; transform:rotate(0deg);
}
.collapse-arrow.expanded{ transform:rotate(90deg); }
.result-details{ display:none; margin-top:18px; }
.result-details.expanded{ display:block; }
.checks-list{ list-style:none; }
.checks-list li{
display:flex; gap:12px; align-items:flex-start; padding:11px 0; border-bottom:1px solid var(--border);
font-size:13px; color:var(--t2);
}
.checks-list li:last-child{ border-bottom:none; }
.checks-list strong{ font-family:var(--fd); font-weight:700; color:var(--t1); text-transform:capitalize; }
.tag{
font-family:var(--fm); font-size:9.5px; font-weight:600; text-transform:uppercase; letter-spacing:.06em;
padding:3px 9px; border-radius:20px; white-space:nowrap; flex-shrink:0; margin-top:1px;
}
.tag.pass{ background:var(--green-l); color:var(--green-d); }
.tag.fail{ background:var(--red-l); color:var(--red); }
.tag.needs_review{ background:var(--amber-l); color:var(--amber); }
.tag.not_available{ background:rgba(16,24,40,.06); color:var(--t4); }
.table-wrap{ overflow-x:auto; margin-top:4px; }
table{ width:100%; border-collapse:collapse; font-size:12.5px; table-layout:fixed; }
th{
text-align:left; padding:9px 10px; font-family:var(--fm); font-size:10px; font-weight:600;
letter-spacing:.06em; text-transform:uppercase; color:var(--t4); border-bottom:1px solid var(--border-2);
white-space:nowrap; overflow:hidden;
}
td{ text-align:left; padding:3px 4px; border-bottom:1px solid var(--border); color:var(--t2); white-space:nowrap; overflow:hidden; }
td.desc{ white-space:normal; color:var(--t1); overflow:visible; }
td.amt, th.amt{ text-align:right; font-family:var(--fm); }
tr.flagged td{ background:rgba(217,119,6,.08); }
tr.flagged td:first-child{ border-left:2px solid var(--amber); }
.cell-input{
width:100%; background:transparent; border:1px solid transparent; border-radius:5px;
padding:6px 6px; font:inherit; color:inherit; text-align:inherit; font-family:inherit;
}
.cell-input:read-only{ color:var(--t2); cursor:default; }
tr.editing .cell-input:not(:read-only):hover{ border-color:var(--border-2); }
tr.editing .cell-input:not(:read-only):focus{ outline:none; border-color:var(--blue); background:rgba(37,99,235,.05); }
.cell-input.edited{ background:rgba(37,99,235,.08); border-color:var(--border-b); }
.desc-input{
display:block; white-space:pre-wrap; word-break:break-word; resize:none;
overflow:hidden; min-height:28px; line-height:1.5;
}
td.amt .cell-input{ text-align:right; font-family:var(--fm); }
.row-actions{ width:34px; padding:3px 0 3px 4px !important; }
.row-btn{
background:transparent; border:none; cursor:pointer; padding:4px; border-radius:5px;
font-size:13px; line-height:1; color:var(--t4); transition:color .15s, background .15s;
}
.row-btn:hover{ color:var(--t1); background:rgba(16,24,40,.06); }
.row-btn.edit{ color:var(--blue); }
.row-btn.save{ color:var(--blue); }
.row-btn.cancel{ color:var(--t4); }
tr.editing td{ background:rgba(37,99,235,.03); }
.restore-banner{
display:none; align-items:center; justify-content:space-between; gap:12px;
font-size:12.5px; color:var(--t2); background:rgba(37,99,235,.07); border:1px solid var(--border-b);
border-radius:9px; padding:10px 14px; margin-bottom:16px;
}
.restore-banner.visible{ display:flex; }
.restore-banner button{
background:transparent; border:1px solid var(--border-2); color:var(--t3); font-family:var(--fb);
font-size:11.5px; padding:5px 10px; border-radius:7px; cursor:pointer; flex-shrink:0;
}
.restore-banner button:hover{ color:var(--t1); border-color:var(--border-b); }
#resultSection{ display:none; }
/* Sticky on the GROUP, not on pdf-col alone - keeps the source PDF and
transactions cards moving together as one unit while the main page
scrolls, instead of the PDF pinning in place while transactions
scrolls past it underneath (they'd drift out of alignment). */
.review-grid{ display:flex; align-items:start; position:sticky; top:24px; }
.pdf-col{ flex:0 0 40%; min-width:260px; }
.pdf-col-head{ display:flex; align-items:center; justify-content:space-between; margin-bottom:10px; }
.pdf-col-head h2{ margin-bottom:0; }
.pdf-col iframe{
width:100%; height:82vh; border:1px solid var(--border-2); border-radius:10px;
background:var(--navy-3); display:block;
}
/* Images get their own zoomable/scrollable panel instead of the PDF
iframe - a browser-native PDF viewer has its own zoom controls built
in, an <img> in the same iframe would have none at all, which is the
gap this fills. Width-based zoom (not CSS transform:scale), so the
wrap's overflow:auto actually produces scrollbars for the zoomed-in
content - transform alone doesn't change an element's layout size, so
a scaled-up image would just overflow uncontrollably instead. */
.img-zoom-controls{ display:flex; align-items:center; gap:4px; }
.img-zoom-controls button{
background:var(--navy-3); border:1px solid var(--border-2); color:var(--t2);
width:26px; height:26px; border-radius:6px; cursor:pointer; font-size:14px; line-height:1;
display:flex; align-items:center; justify-content:center; padding:0; transition:all .15s;
}
.img-zoom-controls button#imgZoomReset{ width:auto; padding:0 9px; font-size:11px; font-weight:700; }
.img-zoom-controls button:hover{ background:rgba(37,99,235,.08); border-color:var(--blue); color:var(--blue); }
.img-zoom-controls span{ font-size:11.5px; color:var(--t3); min-width:38px; text-align:center; font-family:var(--fm); }
.img-preview-wrap{
width:100%; height:82vh; border:1px solid var(--border-2); border-radius:10px;
background:var(--navy-3); overflow:auto; display:block;
}
.img-preview-wrap img{ display:block; }
.resizer{
flex:0 0 28px; align-self:stretch; cursor:col-resize;
display:flex; align-items:center; justify-content:center;
touch-action:none; position:relative;
}
/* A fader-knob look, not just a thin line - a rounded, raised pill with
grip dashes through its middle, so it visibly reads as a two-finger
drag handle rather than a stray divider. */
.resizer::before{
content:''; width:14px; height:58px; border-radius:9px;
background:linear-gradient(180deg, var(--navy-3), var(--navy-2));
border:1px solid var(--border-2);
box-shadow: inset 0 1px 0 rgba(255,255,255,.6), 0 2px 8px rgba(16,24,40,.10);
transition: border-color .15s, box-shadow .15s;
}
.resizer::after{
content:''; position:absolute; top:50%; left:50%;
width:2px; height:18px; border-radius:1px; background:var(--t3);
box-shadow: -4px 0 0 var(--t3), 4px 0 0 var(--t3);
transform:translate(-50%,-50%);
transition: background .15s;
}
.resizer:hover::before, .resizer.dragging::before{
border-color:var(--border-b);
box-shadow: inset 0 1px 0 rgba(255,255,255,.7), 0 0 0 1px rgba(37,99,235,.25), 0 2px 10px rgba(16,24,40,.12);
}
.resizer:hover::after, .resizer.dragging::after{
background:var(--blue); box-shadow: -4px 0 0 var(--blue), 4px 0 0 var(--blue);
}
.txn-col{ flex:1 1 auto; min-width:260px; }
.txn-col-head{ display:flex; align-items:center; justify-content:space-between; margin-bottom:18px; }
.txn-col-head h2{ margin-bottom:0; }
.btn-toggle{
background:var(--blue); border:none; color:var(--navy-2); font-family:var(--fd); font-weight:700;
font-size:12px; padding:7px 15px; border-radius:8px; cursor:pointer; transition:all .15s; flex-shrink:0;
box-shadow:0 2px 10px rgba(37,99,235,.18);
}
.btn-toggle:hover{ background:var(--blue-b); }
.btn-toggle:disabled{ opacity:.5; cursor:not-allowed; box-shadow:none; }
.pdf-col.hidden-panel, .resizer.hidden-panel{ display:none; }
.txn-col .table-wrap{ max-height:82vh; overflow-y:auto; margin-top:4px; }
.txn-col table thead th{
position:sticky; top:0; background:var(--navy-2); z-index:1;
}
@media (max-width: 860px){
.review-grid{ flex-direction:column; position:static; }
.pdf-col{ position:static; flex-basis:auto !important; width:100%; }
.resizer{ display:none; }
.txn-col{ width:100%; }
}

View File

@ -0,0 +1,57 @@
<script setup>
/**
* FileUploadZone.vue
*
* Drop zone, file picker, and the Extract button. Also hosts the SINGLE
* shared error-note area - in the original vanilla-JS version this one
* element shows upload-validation errors, process errors, AND download
* errors (even though downloading happens from ResultCard, visually
* elsewhere on the page) - a pre-existing UX quirk, preserved exactly
* rather than "fixed" unprompted.
*
* Presentational - file-selection/extraction state and handlers come
* from ExtractorView (which owns useFileUpload/useExtraction once, since
* SourceDocumentPanel also needs the same chosenFile/currentPdfUrl).
*/
import { computed } from 'vue'
import { useExtractionStore } from '../stores/extractionStore'
import ProcessingIndicator from './ProcessingIndicator.vue'
const props = defineProps({
chosenFile: { type: File, default: null },
isDragOver: { type: Boolean, default: false },
isProcessing: { type: Boolean, required: true },
phaseText: { type: String, required: true },
})
const emit = defineEmits(['file-input-change', 'drag-over', 'drag-leave', 'drop', 'extract'])
const extractionStore = useExtractionStore()
const fileZoneSubText = computed(() => props.chosenFile?.name || '.pdf, .jpg, or .png files')
</script>
<template>
<div class="card upload-card">
<h2>Statement</h2>
<div
class="file-zone"
:class="{ 'drag-over': isDragOver }"
@dragover="emit('drag-over', $event)"
@dragleave="emit('drag-leave')"
@drop="emit('drop', $event)"
>
<input
type="file"
accept=".pdf,application/pdf,.jpg,.jpeg,.png,image/jpeg,image/png"
@change="emit('file-input-change', $event)"
>
<div class="file-zone-label"><strong>Drop a statement PDF or photo here</strong> or browse</div>
<div class="file-zone-sub" :class="{ 'file-chosen-name': !!chosenFile }">{{ fileZoneSubText }}</div>
</div>
<button class="btn btn-primary" type="button" :disabled="!chosenFile || isProcessing" @click="emit('extract')">
Extract
</button>
<ProcessingIndicator :is-processing="isProcessing" :phase-text="phaseText" />
<div class="error-note" :class="{ visible: !!extractionStore.errorMessage }">{{ extractionStore.errorMessage }}</div>
</div>
</template>

View File

@ -0,0 +1,19 @@
<script setup>
/**
* ProcessingIndicator.vue
*
* Shows the simulated processing-phase text (with its animated ellipsis,
* see useProcessingPhases.js) next to the Extract button while a request
* is in flight. Purely presentational - takes isProcessing/phaseText as
* props rather than owning the timer itself, so it stays reusable
* wherever processing feedback is needed.
*/
defineProps({
isProcessing: { type: Boolean, required: true },
phaseText: { type: String, required: true },
})
</script>
<template>
<span v-if="isProcessing" class="spinner">{{ phaseText }}</span>
</template>

View File

@ -0,0 +1,80 @@
<script setup>
/**
* ResizablePanels.vue
*
* The sticky side-by-side layout: Source Document | drag handle |
* Transactions. Owns the resize-drag math and the panel's hidden/shown
* state (driven by uiStore.pdfColHidden, toggled from TransactionsTable's
* own header button since that's where it visually lives). Sticky on
* the GROUP, not the source-doc column alone - keeps both panels moving
* together as one unit while the page scrolls, instead of the source
* doc pinning in place while transactions scrolls past it underneath
* (they'd drift out of alignment).
*/
import { ref, onMounted, onUnmounted } from 'vue'
import { useUiStore } from '../stores/uiStore'
const uiStore = useUiStore()
const gridRef = ref(null)
const dragging = ref(false)
function setWidthFromX(clientX) {
const rect = gridRef.value.getBoundingClientRect()
let pct = ((clientX - rect.left) / rect.width) * 100
pct = Math.max(25, Math.min(75, pct))
uiStore.pdfColWidthPct = pct
}
function start(e) {
dragging.value = true
document.body.style.userSelect = 'none'
e.preventDefault()
}
function move(e) {
if (!dragging.value) return
const x = e.touches ? e.touches[0].clientX : e.clientX
setWidthFromX(x)
}
function end() {
if (!dragging.value) return
dragging.value = false
document.body.style.userSelect = ''
// Column width just changed - descriptions may rewrap at a different height.
uiStore.bumpLayout()
}
// Dragging continues even if the cursor leaves the resizer itself, so
// move/end listen on the window, not the handle - matching the original.
onMounted(() => {
window.addEventListener('mousemove', move)
window.addEventListener('mouseup', end)
window.addEventListener('touchmove', move, { passive: false })
window.addEventListener('touchend', end)
})
onUnmounted(() => {
window.removeEventListener('mousemove', move)
window.removeEventListener('mouseup', end)
window.removeEventListener('touchmove', move)
window.removeEventListener('touchend', end)
})
</script>
<template>
<div ref="gridRef" class="review-grid">
<div v-show="!uiStore.pdfColHidden" class="card pdf-col" :style="{ flexBasis: uiStore.pdfColWidthPct + '%' }">
<slot name="source" />
</div>
<div
v-show="!uiStore.pdfColHidden"
class="resizer"
:class="{ dragging }"
@mousedown="start"
@touchstart="start"
></div>
<div class="card txn-col">
<slot name="transactions" />
</div>
</div>
</template>

View File

@ -0,0 +1,27 @@
<script setup>
/**
* RestoreBanner.vue
*
* Shown after a session is restored from localStorage for a re-selected
* file. "Discard" clears the saved edits for this doc key and hides the
* banner - the in-memory result stays as-is either way.
*/
import { useExtractionStore } from '../stores/extractionStore'
import { useUiStore } from '../stores/uiStore'
import * as extractionService from '../services/extractionService'
const extractionStore = useExtractionStore()
const uiStore = useUiStore()
function discard() {
extractionService.discardPersisted(extractionStore.currentDocKey)
uiStore.hideRestoreBanner()
}
</script>
<template>
<div class="restore-banner" :class="{ visible: uiStore.restoreBannerVisible }">
<span>{{ uiStore.restoreBannerText }}</span>
<button @click="discard">Discard saved edits</button>
</div>
</template>

View File

@ -0,0 +1,84 @@
<script setup>
/**
* ResultCard.vue
*
* The collapsible Result card: a chevron + "Result" heading on the left
* toggle the status banner/checks list; Download Excel stays on the
* right, always visible and independently clickable.
*/
import { ref, computed } from 'vue'
import { useExtractionStore } from '../stores/extractionStore'
import { useUiStore } from '../stores/uiStore'
import * as extractionService from '../services/extractionService'
const extractionStore = useExtractionStore()
const uiStore = useUiStore()
const result = computed(() => extractionStore.currentResult)
const statusClass = computed(() => 'status-banner ' + (result.value?.status || '').replace(' ', '-'))
const periodText = computed(() => (result.value?.period ? `Statement period: ${result.value.period}` : ''))
const downloading = ref(false)
/**
* Requests the current (possibly edited) workbook and triggers a browser
* save - the same recheck-then-export round trip the backend's own
* /api/export route performs, so a downloaded file always reflects
* whatever is currently on screen. Errors go through the shared
* extractionStore.errorMessage, same single error-note area the upload
* and process flows use - not a separate one per component.
*/
async function handleDownload() {
if (!result.value) return
downloading.value = true
extractionStore.clearError()
try {
const blob = await extractionService.exportWorkbook(
result.value,
extractionStore.effectiveOpeningBalance,
extractionStore.effectiveClosingBalance,
)
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = (result.value.title || 'Statement_Extraction').replace(/\.pdf$/i, '') + '.xlsx'
document.body.appendChild(a)
a.click()
a.remove()
URL.revokeObjectURL(url)
} catch (e) {
extractionStore.setError('Could not generate the export: ' + e.message)
}
downloading.value = false
}
</script>
<template>
<div class="card">
<div class="result-head">
<div class="result-head-left" @click="uiStore.toggleResultExpanded">
<button
class="collapse-arrow"
:class="{ expanded: uiStore.resultExpanded }"
type="button"
:aria-expanded="String(uiStore.resultExpanded)"
:title="uiStore.resultExpanded ? 'Hide details' : 'Show details'"
>&#9656;</button>
<h2>Result</h2>
</div>
<button class="btn-toggle" type="button" :disabled="downloading" @click="handleDownload">
{{ downloading ? 'Preparing…' : 'Download Excel' }}
</button>
</div>
<div class="result-details" :class="{ expanded: uiStore.resultExpanded }">
<div :class="statusClass">{{ result.status }}</div>
<div class="period-note">{{ periodText }}</div>
<ul class="checks-list">
<li v-for="check in result.checks" :key="check.name">
<span class="tag" :class="check.outcome">{{ check.outcome.replace('_', ' ') }}</span>
<span><strong>{{ check.name.replace(/_/g, ' ') }}</strong> — {{ check.detail }}</span>
</li>
</ul>
</div>
</div>
</template>

View File

@ -0,0 +1,43 @@
<script setup>
/**
* SourceDocumentPanel.vue
*
* The Source Document card: a PDF gets the browser's native viewer (with
* its own zoom toolbar) in an iframe; an image has no such chrome, so it
* gets its own zoomable/scrollable panel instead - see useImageZoom.js.
*
* Data flow:
* previewUrl (string|null) - blob URL for the chosen file
* isImage (boolean) - whether to render the image panel instead of the iframe
*/
import { computed } from 'vue'
import { useImageZoom } from '../composables/useImageZoom'
const props = defineProps({
previewUrl: { type: String, default: null },
isImage: { type: Boolean, default: false },
})
const { imgRef, wrapRef, zoomLevelText, onImageLoad, zoomIn, zoomOut, resetZoom } = useImageZoom()
// #toolbar=1 forces the browser's native PDF viewer toolbar (page nav +
// zoom controls) on; navpanes=0 skips the thumbnails/bookmarks sidebar
// so the toolbar isn't competing for space in a narrow column.
const pdfSrc = computed(() => (props.previewUrl ? props.previewUrl + '#toolbar=1&navpanes=0&view=FitH' : ''))
</script>
<template>
<div class="pdf-col-head">
<h2>Source Document</h2>
<div v-if="isImage" class="img-zoom-controls">
<button type="button" title="Zoom out" @click="zoomOut">&#8722;</button>
<span>{{ zoomLevelText }}</span>
<button type="button" title="Zoom in" @click="zoomIn">+</button>
<button type="button" title="Reset zoom to fit" @click="resetZoom">Fit</button>
</div>
</div>
<iframe v-if="!isImage" :src="pdfSrc" title="Statement PDF preview"></iframe>
<div v-else ref="wrapRef" class="img-preview-wrap">
<img ref="imgRef" :src="previewUrl" alt="Statement image preview" @load="onImageLoad">
</div>
</template>

View File

@ -0,0 +1,100 @@
<script setup>
/**
* TransactionRow.vue
*
* One transaction row: read-only by default, editable after its own
* pencil is clicked, with Save (commit + recheck) / Cancel (discard).
*
* Data flow:
* index (number) - this row's position in currentResult.transactions
* transaction (object) - {date, description, amount, balance, status}
* isFlagged (boolean) - whether any check flagged this row
*/
import { ref, watch, nextTick, onMounted } from 'vue'
import { useUiStore } from '../stores/uiStore'
import { useRowEditing } from '../composables/useRowEditing'
import { useAutoGrow } from '../composables/useAutoGrow'
const props = defineProps({
index: { type: Number, required: true },
transaction: { type: Object, required: true },
isFlagged: { type: Boolean, default: false },
})
const uiStore = useUiStore()
const { isEditing, wasEdited, draft, startEdit, cancelEdit, saveEdit } = useRowEditing(props.index)
const { textareaRef, measure } = useAutoGrow()
const firstInputRef = ref(null)
// Step 1: re-measure the description box whenever its own text changes
// (typing while editing), the transactions column's width changes (the
// Hide/Show toggle or a resize-drag ending - see uiStore.layoutVersion),
// or on first mount.
watch([() => draft.description, () => uiStore.layoutVersion], () => nextTick(measure))
onMounted(() => nextTick(measure))
// Step 2: entering edit mode focuses the first field and re-measures the
// description box, same as the original's own edit-start behavior.
function handleEdit() {
startEdit()
nextTick(() => {
firstInputRef.value?.focus()
measure()
})
}
</script>
<template>
<tr :class="{ flagged: isFlagged, editing: isEditing }">
<td class="row-actions">
<button v-if="!isEditing" class="row-btn edit" title="Edit this row" @click="handleEdit">&#9998;</button>
<template v-else>
<button class="row-btn save" title="Save this row" @click="saveEdit">&#10003;</button>
<button class="row-btn cancel" title="Discard changes" @click="cancelEdit">&#10005;</button>
</template>
</td>
<td>
<input
ref="firstInputRef"
v-model="draft.date"
class="cell-input"
:class="{ edited: wasEdited }"
:readonly="!isEditing"
>
</td>
<td class="desc">
<textarea
ref="textareaRef"
v-model="draft.description"
class="cell-input desc-input"
:class="{ edited: wasEdited }"
rows="1"
:readonly="!isEditing"
></textarea>
</td>
<td class="amt">
<input
v-model="draft.amount"
class="cell-input"
:class="{ edited: wasEdited }"
:readonly="!isEditing"
>
</td>
<td class="amt">
<input
v-model="draft.balance"
class="cell-input"
:class="{ edited: wasEdited }"
:readonly="!isEditing"
>
</td>
<td>
<input
v-model="draft.status"
class="cell-input"
:class="{ edited: wasEdited }"
:readonly="!isEditing"
>
</td>
</tr>
</template>

View File

@ -0,0 +1,93 @@
<script setup>
/**
* TransactionsTable.vue
*
* Opening/closing balance inputs + their calculated readouts, the
* Hide/Show Source Doc toggle, and the transactions table itself.
*
* The opening-balance readout is deliberately a snapshot of the
* ORIGINAL extraction's own opening_balance - the backend never returns
* a new one on recheck (only status/checks change), so this stays
* correct without needing special-casing; only its green/not-green
* "match" state follows the live statement_balance check outcome, same
* asymmetry the original vanilla-JS version had (confirmed by reading
* it: openingCalc's text is set once in renderResult and never touched
* again by applyCheckResults, while closingCalc's text IS recomputed on
* every recheck).
*/
import { computed } from 'vue'
import { useExtractionStore } from '../stores/extractionStore'
import { useUiStore } from '../stores/uiStore'
import { fmtMoney } from '../services/formatService'
import TransactionRow from './TransactionRow.vue'
const extractionStore = useExtractionStore()
const uiStore = useUiStore()
const result = computed(() => extractionStore.currentResult)
const balanceCheck = computed(() => result.value?.checks?.find((c) => c.name === 'statement_balance'))
const balanceMatches = computed(() => balanceCheck.value?.outcome === 'pass')
const openingCalcText = computed(() => {
const v = result.value?.opening_balance
return v !== null && v !== undefined ? 'Calculated: ' + fmtMoney(v) : ''
})
const closingCalcText = computed(() => {
const v = balanceCheck.value?.calculated_closing
return v !== undefined && v !== null ? 'Calculated: ' + fmtMoney(v) : ''
})
const toggleLabel = computed(() => (uiStore.pdfColHidden ? 'Show Source Doc' : 'Hide Source Doc'))
</script>
<template>
<div class="txn-col-head">
<h2>Transactions</h2>
<button class="btn-toggle" type="button" @click="uiStore.togglePdfCol">{{ toggleLabel }}</button>
</div>
<div class="fields">
<div>
<label>Opening balance (optional)</label>
<input v-model="extractionStore.openingBalanceInput" type="text" inputmode="decimal" placeholder="e.g. 90,569.13">
<div class="calc-readout" :class="{ match: balanceMatches }">{{ openingCalcText }}</div>
</div>
<div>
<label>Closing balance (optional)</label>
<input v-model="extractionStore.closingBalanceInput" type="text" inputmode="decimal" placeholder="e.g. 88,479.50">
<div class="calc-readout" :class="{ match: balanceMatches }">{{ closingCalcText }}</div>
</div>
</div>
<div class="note">This statement format may not print a clean opening/closing balance — enter them here to run the full statement balance check; otherwise it's marked "not available" rather than guessed.</div>
<div class="note">Click the pencil on a row to edit it, then Save to commit - edits are saved to this browser as you confirm them, row by row.</div>
<div class="table-wrap">
<table>
<colgroup>
<col style="width:34px">
<col style="width:120px">
<col>
<col style="width:120px">
<col style="width:135px">
<col style="width:95px">
</colgroup>
<thead>
<tr>
<th></th>
<th>Date</th>
<th>Description</th>
<th class="amt">Amount</th>
<th class="amt">Balance</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<TransactionRow
v-for="(t, i) in result.transactions"
:key="i"
:index="i"
:transaction="t"
:is-flagged="extractionStore.flaggedIndexes.has(i)"
/>
</tbody>
</table>
</div>
</template>

View File

@ -0,0 +1,20 @@
/**
* Grows a textarea's height to fit its content - the mechanic only;
* callers decide when to re-measure (on mount, on their own content
* change, on edit-start, or on uiStore.layoutVersion changing - see
* TransactionRow.vue).
*/
import { ref } from 'vue'
export function useAutoGrow() {
const textareaRef = ref(null)
function measure() {
const el = textareaRef.value
if (!el) return
el.style.height = 'auto'
el.style.height = el.scrollHeight + 'px'
}
return { textareaRef, measure }
}

View File

@ -0,0 +1,51 @@
/**
* Orchestrates the Extract button: runs the processing-phase indicator
* while the request is in flight, submits the file, and writes the
* result into the extraction store on success.
*/
import { useExtractionStore } from '../stores/extractionStore'
import { useUiStore } from '../stores/uiStore'
import * as extractionService from '../services/extractionService'
import * as formatService from '../services/formatService'
import { useProcessingPhases } from './useProcessingPhases'
export function useExtraction() {
const extractionStore = useExtractionStore()
const uiStore = useUiStore()
const { isProcessing, phaseText, start, stop } = useProcessingPhases()
/**
* Submits the chosen file for extraction.
*
* Data flow:
* file (File)
* openingBalanceInput (string) - raw text from the opening balance field
* closingBalanceInput (string) - raw text from the closing balance field
*/
async function runExtraction(file, openingBalanceInput, closingBalanceInput) {
if (!file) return
extractionStore.clearError()
start()
try {
const openingBalance = formatService.parseNum(openingBalanceInput)
const closingBalance = formatService.parseNum(closingBalanceInput)
const result = await extractionService.process(file, openingBalance, closingBalance)
if (result.error) {
extractionStore.setError(result.error)
} else {
const key = extractionService.docKeyFor(file)
extractionStore.setResult(result, key)
extractionService.persistResult(key, result)
uiStore.hideRestoreBanner()
uiStore.resultExpanded = false
}
} catch (e) {
extractionStore.setError('Network error: ' + e.message)
}
stop()
}
return { isProcessing, phaseText, runExtraction }
}

View File

@ -0,0 +1,90 @@
/**
* File selection (browse/drag-drop), preview URL management, and
* restoring a previously-edited session for the same source file.
*/
import { ref, computed } from 'vue'
import { useExtractionStore } from '../stores/extractionStore'
import { useUiStore } from '../stores/uiStore'
import * as extractionService from '../services/extractionService'
const ACCEPTED_FILE_RE = /\.(pdf|jpe?g|png)$/i
const IMAGE_FILE_RE = /\.(jpe?g|png)$/i
export function useFileUpload() {
const extractionStore = useExtractionStore()
const uiStore = useUiStore()
const chosenFile = ref(null)
const currentPdfUrl = ref(null)
const isDragOver = ref(false)
const isImage = computed(() => (chosenFile.value ? IMAGE_FILE_RE.test(chosenFile.value.name) : false))
/** Shows a previously-saved session for this doc key, if one exists. */
function tryRestore(key) {
const restored = extractionService.restoreResult(key)
if (!restored) return false
extractionStore.setResult(restored, key)
uiStore.showRestoreBanner(
'Restored previously edited values for this file from this browser - re-select the source PDF above to view it alongside the data again.'
)
uiStore.resultExpanded = false
return true
}
/**
* Validates and adopts a newly-chosen file, swapping the preview URL
* and either keeping the current result (same file re-selected after a
* crash, just to restore the preview) or clearing it and checking for a
* saved session under the new file's own doc key.
*/
function setFile(file) {
if (!file) return
extractionStore.clearError()
if (!ACCEPTED_FILE_RE.test(file.name)) {
extractionStore.setError('Please choose a .pdf, .jpg, or .png file.')
return
}
chosenFile.value = file
if (currentPdfUrl.value) URL.revokeObjectURL(currentPdfUrl.value)
currentPdfUrl.value = URL.createObjectURL(file)
const key = extractionService.docKeyFor(file)
if (key === extractionStore.currentDocKey) {
return
}
extractionStore.clearResult()
uiStore.hideRestoreBanner()
tryRestore(key)
}
function onFileInputChange(e) {
setFile(e.target.files[0])
}
function onDragOver(e) {
e.preventDefault()
isDragOver.value = true
}
function onDragLeave() {
isDragOver.value = false
}
function onDrop(e) {
e.preventDefault()
isDragOver.value = false
setFile(e.dataTransfer.files[0])
}
/** Restores the most recent session, if any, before any file is chosen. */
function restoreOnLoad() {
const key = extractionService.lastDocKey()
if (key) tryRestore(key)
}
return {
chosenFile, currentPdfUrl, isDragOver, isImage,
setFile, onFileInputChange, onDragOver, onDragLeave, onDrop, restoreOnLoad,
}
}

View File

@ -0,0 +1,51 @@
/**
* Zoom/fit math for the image source-document panel - width-based (not
* CSS transform:scale), so the wrap's overflow:auto actually produces
* scrollbars for the zoomed-in content.
*/
import { ref, computed } from 'vue'
const ZOOM_STEP = 0.25
const ZOOM_MIN = 0.25
const ZOOM_MAX = 4
export function useImageZoom() {
const imgRef = ref(null)
const wrapRef = ref(null)
const zoom = ref(1)
const fitZoom = ref(1)
const zoomLevelText = computed(() => Math.round(zoom.value * 100) + '%')
function applyZoom(z) {
zoom.value = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, z))
const img = imgRef.value
if (img && img.naturalWidth) img.style.width = Math.round(img.naturalWidth * zoom.value) + 'px'
}
/**
* Fit-to-width on load, the same starting impression the PDF viewer's
* own view=FitH gives - a native-resolution phone photo is usually
* much wider than this panel and would otherwise open mostly
* off-screen, needing an immediate manual zoom-out just to get
* oriented.
*/
function onImageLoad() {
const img = imgRef.value
const wrap = wrapRef.value
fitZoom.value = img && img.naturalWidth ? Math.min(1, wrap.clientWidth / img.naturalWidth) : 1
applyZoom(fitZoom.value)
}
function zoomIn() {
applyZoom(zoom.value + ZOOM_STEP)
}
function zoomOut() {
applyZoom(zoom.value - ZOOM_STEP)
}
function resetZoom() {
applyZoom(fitZoom.value)
}
return { imgRef, wrapRef, zoomLevelText, onImageLoad, zoomIn, zoomOut, resetZoom }
}

View File

@ -0,0 +1,60 @@
/**
* Simulated processing-phase text with an animated ellipsis, shown while
* /api/process is in flight. There is no real progress signal from the
* backend - it's one synchronous request - so this is a client-side
* timer cycling through an honestly-ordered sequence of what the
* pipeline is actually doing (see backend/services/pipeline_service.py's
* own run() order), not a measurement of real completion.
*/
import { ref, computed } from 'vue'
const PHASES = [
'Reading document',
'Extracting transactions',
'Cross-checking with a second engine',
'Running verification checks',
'Preparing results',
]
const PHASE_INTERVAL_MS = 1800
const DOT_INTERVAL_MS = 400
export function useProcessingPhases() {
const isProcessing = ref(false)
const phaseIndex = ref(0)
const dotCount = ref(1)
let phaseTimer = null
let dotTimer = null
const phaseText = computed(() => {
const dots = '.'.repeat(dotCount.value)
return `${PHASES[phaseIndex.value]}${dots}`
})
function start() {
isProcessing.value = true
phaseIndex.value = 0
dotCount.value = 1
// Advances through PHASES on a timer; holds on the last one if the
// real request takes longer than the simulated sequence rather than
// looping back to "Reading document" - looping would misleadingly
// suggest the work restarted.
phaseTimer = setInterval(() => {
if (phaseIndex.value < PHASES.length - 1) phaseIndex.value++
}, PHASE_INTERVAL_MS)
dotTimer = setInterval(() => {
dotCount.value = (dotCount.value % 3) + 1
}, DOT_INTERVAL_MS)
}
function stop() {
isProcessing.value = false
clearInterval(phaseTimer)
clearInterval(dotTimer)
phaseTimer = null
dotTimer = null
}
return { isProcessing, phaseText, start, stop }
}

View File

@ -0,0 +1,78 @@
/**
* Per-row pencil-to-edit, Save/Cancel state machine. Cells are read-only
* by default - a row only becomes editable after its own pencil is
* clicked (so edits are always deliberate, never an accidental keystroke
* in a cell you were just scrolling past), and a commit only happens on
* that row's own Save, which is when the edit is applied to the store,
* persisted, and re-checked.
*/
import { ref, reactive } from 'vue'
import { useExtractionStore } from '../stores/extractionStore'
import * as extractionService from '../services/extractionService'
import { fmtNum, parseNum } from '../services/formatService'
export function useRowEditing(index) {
const extractionStore = useExtractionStore()
const isEditing = ref(false)
const wasEdited = ref(false)
const draft = reactive({ date: '', description: '', amount: '', balance: '', status: '' })
function loadDraft() {
const t = extractionStore.currentResult.transactions[index]
draft.date = t.date
draft.description = t.description
draft.amount = fmtNum(t.amount)
draft.balance = fmtNum(t.balance)
draft.status = t.status
}
// draft is the single display source whether editing or not (kept in
// sync with the saved transaction on mount, on cancel, and after a
// save) - simpler than branching the template between two value
// sources depending on edit state.
loadDraft()
function startEdit() {
loadDraft()
isEditing.value = true
}
function cancelEdit() {
loadDraft() // discard any unsaved changes, revert to last saved values
isEditing.value = false
}
/**
* Commits the draft to the store, re-renders from the saved data
* (picking up comma formatting), persists to localStorage, and
* re-checks - clearing a flag (or raising one) right after a fix, the
* same as the Download button, which uses the same recheck logic
* server-side to keep the export consistent with saved edits.
*/
async function saveEdit() {
extractionStore.saveRowEdit(index, {
date: draft.date,
description: draft.description,
amount: parseNum(draft.amount),
balance: parseNum(draft.balance),
status: draft.status,
})
wasEdited.value = true
isEditing.value = false
extractionService.persistResult(extractionStore.currentDocKey, extractionStore.currentResult)
try {
const checkResult = await extractionService.recheck(
extractionStore.currentResult,
extractionStore.effectiveOpeningBalance,
extractionStore.effectiveClosingBalance,
)
if (!checkResult.error) extractionStore.applyCheckResults(checkResult)
} catch (e) {
/* recheck is best-effort; the saved edit itself isn't lost either way */
}
}
return { isEditing, wasEdited, draft, startEdit, cancelEdit, saveEdit }
}

9
frontend/src/main.js Normal file
View File

@ -0,0 +1,9 @@
// App bootstrap: Pinia for stores, vue-router for the (single) route,
// global CSS imported once here rather than per-component.
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import './assets/main.css'
createApp(App).use(createPinia()).use(router).mount('#app')

View File

@ -0,0 +1,53 @@
/**
* All HTTP calls to the backend's extraction API - no business logic here,
* only building requests and parsing responses.
*/
/**
* Submits a freshly-chosen file for extraction.
*
* Data flow:
* formData (FormData) - statement_file + optional opening_balance/closing_balance
* returns (object) - the parsed JSON response (may contain {error})
*/
export async function processStatement(formData) {
const res = await fetch('/api/process', { method: 'POST', body: formData })
return res.json()
}
/**
* Re-runs the checks against a (possibly edited) transaction list.
*
* Data flow:
* payload (object) - transactions, page_reports, period, balances, narrative_direction
* returns (object) - {status, checks} or {error}
*/
export async function recheckTransactions(payload) {
const res = await fetch('/api/recheck', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
return res.json()
}
/**
* Re-runs the checks and returns the generated Excel workbook.
*
* Data flow:
* payload (object) - same shape as recheckTransactions, plus
* brought_forward_balance/title
* returns (Blob) - the .xlsx file
*
* Throws if the server responds with a non-2xx status - the caller decides
* how to surface that.
*/
export async function exportStatement(payload) {
const res = await fetch('/api/export', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
if (!res.ok) throw new Error('Export failed')
return res.blob()
}

View File

@ -0,0 +1,31 @@
/**
* Thin wrapper around browser localStorage - no business logic, just
* get/set/remove, each guarded against storage being full/unavailable
* (private browsing, quota exceeded) so a caller never has to catch
* these itself.
*/
export function getItem(key) {
try {
return localStorage.getItem(key)
} catch (e) {
return null
}
}
export function setItem(key, value) {
try {
localStorage.setItem(key, value)
return true
} catch (e) {
return false
}
}
export function removeItem(key) {
try {
localStorage.removeItem(key)
} catch (e) {
/* nothing to clean up if storage was never usable */
}
}

View File

@ -0,0 +1,9 @@
// 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.
import { createRouter, createWebHistory } from 'vue-router'
import ExtractorView from '../views/ExtractorView.vue'
export default createRouter({
history: createWebHistory(),
routes: [{ path: '/', name: 'extractor', component: ExtractorView }],
})

View File

@ -0,0 +1,89 @@
/**
* Business logic for extracting, persisting, and re-checking a statement -
* calls repositories only, never touches fetch()/localStorage directly.
*/
import * as extractionRepository from '../repositories/extractionRepository'
import * as localStorageRepository from '../repositories/localStorageRepository'
const LAST_DOC_KEY = 'bse:last_doc_key'
/**
* The localStorage key for one source file's result - keyed by the
* SOURCE file's own name+size (stable across re-selecting the same file
* after a crash), not the server's randomly-generated output filename,
* which changes every run even for the same source document.
*/
export function docKeyFor(file) {
return 'bse:doc:' + file.name + ':' + file.size
}
/** Saves a result under its doc key and remembers it as the most recent session. */
export function persistResult(docKey, result) {
if (!docKey || !result) return
const ok = localStorageRepository.setItem(docKey, JSON.stringify(result))
if (ok) localStorageRepository.setItem(LAST_DOC_KEY, docKey)
}
/** A previously-persisted result for a doc key, or null if none/corrupt. */
export function restoreResult(docKey) {
const saved = localStorageRepository.getItem(docKey)
if (!saved) return null
try {
return JSON.parse(saved)
} catch (e) {
return null
}
}
/** The doc key of the most recently viewed session, for restore-on-load. */
export function lastDocKey() {
return localStorageRepository.getItem(LAST_DOC_KEY)
}
export function discardPersisted(docKey) {
if (docKey) localStorageRepository.removeItem(docKey)
}
/**
* Whatever the user typed always wins; an intentionally blank field (no
* auto-fill, per the UI's own calculated-balance readouts) falls back to
* the statement's own auto-detected figure from the initial extract -
* otherwise a row edit's recheck/export would lose that figure entirely
* the moment the visible field is empty.
*/
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) {
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)
return extractionRepository.processStatement(fd)
}
function recheckPayload(result, openingBalance, closingBalance) {
return {
transactions: result.transactions,
page_reports: result.page_reports,
narrative_direction: result.narrative_direction,
period: result.period,
opening_balance: openingBalance,
closing_balance: closingBalance,
}
}
export async function recheck(result, openingBalance, closingBalance) {
return extractionRepository.recheckTransactions(recheckPayload(result, openingBalance, closingBalance))
}
export async function exportWorkbook(result, openingBalance, closingBalance) {
const payload = {
...recheckPayload(result, openingBalance, closingBalance),
brought_forward_balance: result.brought_forward_balance,
title: result.title,
}
return extractionRepository.exportStatement(payload)
}

View File

@ -0,0 +1,30 @@
/**
* Number formatting/parsing shared across the transactions table and
* balance fields. escapeHtml from the original vanilla-JS version is
* deliberately not reproduced here - Vue's own template interpolation
* ({{ }}) already HTML-escapes, making a manual version redundant.
*/
/** A signed amount as "$1,234.56" / "-$1,234.56", or an em dash for null/undefined. */
export function fmtMoney(n) {
if (n === null || n === undefined) return '—'
const sign = n < 0 ? '-' : ''
return sign + '$' + Math.abs(n).toLocaleString('en-US', { minimumFractionDigits: 2 })
}
/**
* Same comma grouping as fmtMoney but no $ sign - used inside the
* editable Amount/Balance cells, where a leading $ would just get parsed
* back out on save anyway.
*/
export function fmtNum(n) {
if (n === null || n === undefined) return ''
const sign = n < 0 ? '-' : ''
return sign + Math.abs(n).toLocaleString('en-US', { minimumFractionDigits: 2 })
}
/** A typed string back to a number, or null if it doesn't contain one. */
export function parseNum(s) {
const cleaned = String(s).replace(/[^0-9.\-]/g, '')
return cleaned === '' || cleaned === '-' ? null : parseFloat(cleaned)
}

View File

@ -0,0 +1,88 @@
/**
* Global state for the currently-loaded statement result - the full
* server response (transactions, checks, status, page_reports, etc.)
* kept as one cohesive object matching the server's own shape, not
* over-normalized into separate pieces of state. Also holds the opening/
* closing balance input fields' raw typed text - these need to be read
* live by any recheck/export call (a row save, the download button),
* not just the component that renders the input boxes, so they live
* here rather than as local component state.
*/
import { defineStore } from 'pinia'
import { parseNum } from '../services/formatService'
import { effectiveBalance } from '../services/extractionService'
export const useExtractionStore = defineStore('extraction', {
state: () => ({
currentResult: null,
currentDocKey: null,
flaggedIndexes: new Set(),
errorMessage: '',
openingBalanceInput: '',
closingBalanceInput: '',
}),
getters: {
/** The typed opening balance, or the statement's own auto-detected figure if blank. */
effectiveOpeningBalance(state) {
return effectiveBalance(parseNum(state.openingBalanceInput), state.currentResult?.opening_balance)
},
/** The typed closing balance, or the statement's own auto-detected figure if blank. */
effectiveClosingBalance(state) {
return effectiveBalance(parseNum(state.closingBalanceInput), state.currentResult?.closing_balance)
},
},
actions: {
/** Replaces the current result wholesale (a fresh extract or a restored session). */
setResult(result, docKey) {
this.currentResult = result
this.currentDocKey = docKey
this.recomputeFlags()
},
/**
* Updates just the status/checks portion after a recheck - mirrors
* the server's own recheck response shape {status, checks}.
*/
applyCheckResults(checkResult) {
if (!this.currentResult) return
this.currentResult.status = checkResult.status
this.currentResult.checks = checkResult.checks
this.recomputeFlags()
},
/**
* Rebuilds flaggedIndexes from the current checks - every check's
* own mismatches/issues list carries {index, ...} entries for the
* specific transaction rows it flagged.
*/
recomputeFlags() {
const flagged = new Set()
for (const check of this.currentResult?.checks || []) {
for (const item of check.mismatches || check.issues || []) {
if (item.index !== undefined) flagged.add(item.index)
}
}
this.flaggedIndexes = flagged
},
/** Applies a saved row edit's fields to the transaction at idx. */
saveRowEdit(idx, fields) {
if (!this.currentResult) return
Object.assign(this.currentResult.transactions[idx], fields)
},
clearResult() {
this.currentResult = null
this.currentDocKey = null
this.flaggedIndexes = new Set()
},
setError(message) {
this.errorMessage = message
},
clearError() {
this.errorMessage = ''
},
},
})

View File

@ -0,0 +1,43 @@
/**
* Pure view-chrome state, unrelated to the extraction data itself:
* collapse/expand, panel visibility/width, and a layout-change counter
* description boxes watch to know when to re-measure their own height.
*/
import { defineStore } from 'pinia'
export const useUiStore = defineStore('ui', {
state: () => ({
resultExpanded: false,
pdfColHidden: false,
pdfColWidthPct: 40, // matches .pdf-col's own CSS default (flex: 0 0 40%)
restoreBannerVisible: false,
restoreBannerText: '',
/**
* Bumped whenever the transactions column's available width changes
* (the Hide/Show toggle, or a resize-drag ending) - every
* TransactionRow's own description textarea watches this to
* re-measure its height, replacing the old global autoGrowAll()
* call pattern with something each row can react to independently.
*/
layoutVersion: 0,
}),
actions: {
toggleResultExpanded() {
this.resultExpanded = !this.resultExpanded
},
togglePdfCol() {
this.pdfColHidden = !this.pdfColHidden
this.bumpLayout()
},
bumpLayout() {
this.layoutVersion++
},
showRestoreBanner(text) {
this.restoreBannerText = text
this.restoreBannerVisible = true
},
hideRestoreBanner() {
this.restoreBannerVisible = false
},
},
})

View File

@ -0,0 +1,74 @@
<script setup>
/**
* ExtractorView.vue
*
* The whole current page: upload, result, and side-by-side review.
* Owns useFileUpload/useExtraction once (rather than each consuming
* component owning its own copy) since both FileUploadZone and
* SourceDocumentPanel need the same chosenFile/currentPdfUrl state.
*/
import { onMounted } from 'vue'
import { useExtractionStore } from '../stores/extractionStore'
import { useFileUpload } from '../composables/useFileUpload'
import { useExtraction } from '../composables/useExtraction'
import FileUploadZone from '../components/FileUploadZone.vue'
import RestoreBanner from '../components/RestoreBanner.vue'
import ResultCard from '../components/ResultCard.vue'
import ResizablePanels from '../components/ResizablePanels.vue'
import SourceDocumentPanel from '../components/SourceDocumentPanel.vue'
import TransactionsTable from '../components/TransactionsTable.vue'
const extractionStore = useExtractionStore()
const {
chosenFile, currentPdfUrl, isDragOver, isImage,
onFileInputChange, onDragOver, onDragLeave, onDrop, restoreOnLoad,
} = useFileUpload()
const { isProcessing, phaseText, runExtraction } = useExtraction()
function handleExtract() {
if (!chosenFile.value) return
runExtraction(chosenFile.value, extractionStore.openingBalanceInput, extractionStore.closingBalanceInput)
}
// On page load, restore any previous session right away - before any
// file is even chosen - so a crash mid-edit never loses work. The
// source file itself isn't persisted (not practical to store in
// localStorage), so the preview stays empty until the same file is
// re-picked.
onMounted(restoreOnLoad)
</script>
<template>
<div class="eyebrow">Extraction &amp; verification</div>
<h1>Bank Statement Extractor</h1>
<div class="sub">
Upload a bank statement PDF or photo. A text PDF structures the transactions and proves the
arithmetic against two independent extraction passes; a scanned or photographed statement is
read via OCR instead, with no second pass to cross-check it against.
</div>
<FileUploadZone
:chosen-file="chosenFile"
:is-drag-over="isDragOver"
:is-processing="isProcessing"
:phase-text="phaseText"
@file-input-change="onFileInputChange"
@drag-over="onDragOver"
@drag-leave="onDragLeave"
@drop="onDrop"
@extract="handleExtract"
/>
<div v-if="extractionStore.currentResult">
<RestoreBanner />
<ResultCard />
<ResizablePanels>
<template #source>
<SourceDocumentPanel :preview-url="currentPdfUrl" :is-image="isImage" />
</template>
<template #transactions>
<TransactionsTable />
</template>
</ResizablePanels>
</div>
</template>

14
frontend/vite.config.js Normal file
View File

@ -0,0 +1,14 @@
// Vite config - the /api proxy lets fetch('/api/...') work unchanged in
// dev against the Flask backend, same as it does in production where
// both are served from the same origin.
import vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [vue()],
server: {
proxy: {
'/api': 'http://localhost:8091',
},
},
})

View File

@ -1,895 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bank Statement Extractor</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;600&display=swap" rel="stylesheet">
<style>
:root{
/* Accent — single brand color, per UI_DESIGN_THEME.md (enterprise variant: standard blue) */
--blue:#2563EB;
--blue-b:#1D4ED8;
--cyan:#2563EB;
/* Status colors — never reused as brand accent */
--green:#16A34A; --green-l:#DCFCE7; --green-d:#15803D;
--amber:#D97706; --amber-l:#FEF3C7;
--red:#DC2626; --red-l:#FEE2E2;
/* Background stack — light surfaces, per UI_DESIGN_THEME.md's own
light-surface tokens (--surface/--surface-2/--page) */
--navy:#EEF1F6;
--navy-2:#FFFFFF;
--navy-3:#F8FAFD;
/* Text on light surfaces, per UI_DESIGN_THEME.md */
--t1:#0D1526; --t2:#2D3A52; --t3:#6B7A99; --t4:#9BA8C0;
/* Borders, per UI_DESIGN_THEME.md's light-surface tokens */
--border:rgba(28,56,121,.11);
--border-2:rgba(28,56,121,.18);
--border-b:rgba(37,99,235,.28);
--shadow:0 2px 8px rgba(12,26,60,.06),0 8px 28px rgba(12,26,60,.09),0 0 0 1px rgba(28,56,121,.06);
--shadow-h:0 4px 16px rgba(12,26,60,.10),0 16px 48px rgba(12,26,60,.13),0 0 0 1px rgba(37,99,235,.18);
--fd:'Inter',sans-serif;
--fb:'Inter',sans-serif;
--fm:'JetBrains Mono',monospace;
--r:8px;
}
*{ box-sizing:border-box; margin:0; padding:0; }
body{ font-family:var(--fb); background:var(--navy); color:var(--t1); min-height:100vh; -webkit-font-smoothing:antialiased; }
main{ position:relative; z-index:1; max-width:1360px; margin:0 auto; padding:56px 24px 90px; }
.eyebrow{
display:inline-flex; align-items:center; gap:7px;
font-family:var(--fm); font-size:11px; font-weight:600; letter-spacing:.12em; text-transform:uppercase;
color:var(--blue); background:rgba(37,99,235,.08); border:1px solid var(--border-b);
padding:5px 12px; border-radius:20px; margin-bottom:16px;
}
.eyebrow::before{ content:''; width:6px; height:6px; border-radius:50%; background:var(--blue); }
h1{ font-family:var(--fd); font-weight:800; font-size:30px; letter-spacing:-.01em; margin-bottom:10px; }
.sub{ color:var(--t3); font-size:14.5px; line-height:1.6; max-width:620px; margin-bottom:34px; }
.card{
background:var(--navy-2); border:1px solid var(--border); border-radius:var(--r);
padding:28px 26px; margin-bottom:22px; box-shadow:var(--shadow);
}
.card h2{
font-family:var(--fm); font-size:11px; font-weight:600; letter-spacing:.1em; text-transform:uppercase;
color:var(--blue); margin-bottom:18px;
}
.file-zone{
border:1.5px dashed var(--border-2); border-radius:10px; padding:26px 20px; text-align:center;
cursor:pointer; transition:all .2s; position:relative; margin-bottom:16px;
}
.file-zone:hover, .file-zone.drag-over{ border-color:var(--blue); background:rgba(37,99,235,.04); }
.file-zone input[type="file"]{ position:absolute; inset:0; opacity:0; cursor:pointer; width:100%; height:100%; }
.file-zone-label{ font-size:13.5px; color:var(--t2); }
.file-zone-label strong{ color:var(--blue); font-weight:600; }
.file-zone-sub{ font-size:11.5px; color:var(--t4); margin-top:5px; }
.file-zone-sub.file-chosen-name{ font-family:var(--fm); font-size:12px; color:var(--blue); margin-top:5px; }
.fields{ display:flex; flex-wrap:wrap; gap:16px; margin-bottom:16px; }
.fields > div{ flex:1 1 180px; min-width:160px; }
.fields label{ font-size:11.5px; color:var(--t3); display:block; margin-bottom:6px; white-space:normal; }
.fields input{
width:100%; padding:9px 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;
}
.fields input:focus{ border-color:var(--blue); }
.calc-readout{ font-family:var(--fm); font-size:11.5px; color:var(--t3); margin-top:6px; min-height:14px; }
.calc-readout.match{ color:var(--green); }
.note{ font-size:12px; color:var(--t4); line-height:1.6; margin-bottom:18px; }
.btn{
display:inline-flex; align-items:center; justify-content:center; gap:8px;
font-family:var(--fd); font-weight:700; font-size:13.5px; border-radius:10px; border:none;
padding:11px 22px; cursor:pointer; transition:all .2s;
}
.btn-primary{ background:var(--blue); color:var(--navy-2); box-shadow:0 4px 18px rgba(37,99,235,.18); }
.btn-primary:hover{ background:var(--blue-b); }
.btn-primary:disabled{ opacity:.35; cursor:not-allowed; box-shadow:none; }
.btn-ghost{
background:transparent; color:var(--t1); border:1px solid var(--border-2);
}
.btn-ghost:hover{ border-color:var(--border-b); color:var(--blue); }
.spinner{ font-family:var(--fm); font-size:12px; color:var(--t4); margin-left:12px; }
.error-note{
display:none; font-size:12.5px; color:var(--red); background:var(--red-l);
border:1px solid rgba(220,38,38,.3); border-radius:9px; padding:11px 14px; margin-top:12px;
}
.error-note.visible{ display:block; }
.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;
margin-bottom:18px;
}
.status-banner.Verified{ background:var(--green-l); color:var(--green-d); }
.status-banner.Needs-review{ background:var(--amber-l); color:var(--amber); }
.status-banner.Failed{ background:var(--red-l); color:var(--red); }
.period-note{ font-size:12.5px; color:var(--t3); margin-bottom:18px; }
.result-head{ display:flex; align-items:center; justify-content:space-between; gap:12px; }
.result-head-left{ display:flex; align-items:center; gap:10px; cursor:pointer; }
.result-head-left h2{ margin-bottom:0; }
.collapse-arrow{
display:inline-flex; align-items:center; justify-content:center;
width:20px; height:20px; background:transparent; border:none; cursor:pointer;
color:var(--blue); font-size:12px; line-height:1; transition:transform .2s; transform:rotate(0deg);
}
.collapse-arrow.expanded{ transform:rotate(90deg); }
.result-details{ display:none; margin-top:18px; }
.result-details.expanded{ display:block; }
.checks-list{ list-style:none; }
.checks-list li{
display:flex; gap:12px; align-items:flex-start; padding:11px 0; border-bottom:1px solid var(--border);
font-size:13px; color:var(--t2);
}
.checks-list li:last-child{ border-bottom:none; }
.checks-list strong{ font-family:var(--fd); font-weight:700; color:var(--t1); text-transform:capitalize; }
.tag{
font-family:var(--fm); font-size:9.5px; font-weight:600; text-transform:uppercase; letter-spacing:.06em;
padding:3px 9px; border-radius:20px; white-space:nowrap; flex-shrink:0; margin-top:1px;
}
.tag.pass{ background:var(--green-l); color:var(--green-d); }
.tag.fail{ background:var(--red-l); color:var(--red); }
.tag.needs_review{ background:var(--amber-l); color:var(--amber); }
.tag.not_available{ background:rgba(16,24,40,.06); color:var(--t4); }
.table-wrap{ overflow-x:auto; margin-top:4px; }
table{ width:100%; border-collapse:collapse; font-size:12.5px; table-layout:fixed; }
th{
text-align:left; padding:9px 10px; font-family:var(--fm); font-size:10px; font-weight:600;
letter-spacing:.06em; text-transform:uppercase; color:var(--t4); border-bottom:1px solid var(--border-2);
white-space:nowrap; overflow:hidden;
}
td{ text-align:left; padding:3px 4px; border-bottom:1px solid var(--border); color:var(--t2); white-space:nowrap; overflow:hidden; }
td.desc{ white-space:normal; color:var(--t1); overflow:visible; }
td.amt, th.amt{ text-align:right; font-family:var(--fm); }
tr.flagged td{ background:rgba(217,119,6,.08); }
tr.flagged td:first-child{ border-left:2px solid var(--amber); }
.cell-input{
width:100%; background:transparent; border:1px solid transparent; border-radius:5px;
padding:6px 6px; font:inherit; color:inherit; text-align:inherit; font-family:inherit;
}
.cell-input:read-only{ color:var(--t2); cursor:default; }
tr.editing .cell-input:not(:read-only):hover{ border-color:var(--border-2); }
tr.editing .cell-input:not(:read-only):focus{ outline:none; border-color:var(--blue); background:rgba(37,99,235,.05); }
.cell-input.edited{ background:rgba(37,99,235,.08); border-color:var(--border-b); }
.desc-input{
display:block; white-space:pre-wrap; word-break:break-word; resize:none;
overflow:hidden; min-height:28px; line-height:1.5;
}
td.amt .cell-input{ text-align:right; font-family:var(--fm); }
.row-actions{ width:34px; padding:3px 0 3px 4px !important; }
.row-btn{
background:transparent; border:none; cursor:pointer; padding:4px; border-radius:5px;
font-size:13px; line-height:1; color:var(--t4); transition:color .15s, background .15s;
}
.row-btn:hover{ color:var(--t1); background:rgba(16,24,40,.06); }
.row-btn.edit{ color:var(--blue); }
.row-btn.save{ color:var(--blue); }
.row-btn.cancel{ color:var(--t4); }
tr.editing td{ background:rgba(37,99,235,.03); }
.restore-banner{
display:none; align-items:center; justify-content:space-between; gap:12px;
font-size:12.5px; color:var(--t2); background:rgba(37,99,235,.07); border:1px solid var(--border-b);
border-radius:9px; padding:10px 14px; margin-bottom:16px;
}
.restore-banner.visible{ display:flex; }
.restore-banner button{
background:transparent; border:1px solid var(--border-2); color:var(--t3); font-family:var(--fb);
font-size:11.5px; padding:5px 10px; border-radius:7px; cursor:pointer; flex-shrink:0;
}
.restore-banner button:hover{ color:var(--t1); border-color:var(--border-b); }
#resultSection{ display:none; }
/* Sticky on the GROUP, not on pdf-col alone - keeps the source PDF and
transactions cards moving together as one unit while the main page
scrolls, instead of the PDF pinning in place while transactions
scrolls past it underneath (they'd drift out of alignment). */
.review-grid{ display:flex; align-items:start; position:sticky; top:24px; }
.pdf-col{ flex:0 0 40%; min-width:260px; }
.pdf-col-head{ display:flex; align-items:center; justify-content:space-between; margin-bottom:10px; }
.pdf-col-head h2{ margin-bottom:0; }
.pdf-col iframe{
width:100%; height:82vh; border:1px solid var(--border-2); border-radius:10px;
background:var(--navy-3); display:block;
}
/* Images get their own zoomable/scrollable panel instead of the PDF
iframe - a browser-native PDF viewer has its own zoom controls built
in, an <img> in the same iframe would have none at all, which is the
gap this fills. Width-based zoom (not CSS transform:scale), so the
wrap's overflow:auto actually produces scrollbars for the zoomed-in
content - transform alone doesn't change an element's layout size, so
a scaled-up image would just overflow uncontrollably instead. */
.img-zoom-controls{ display:flex; align-items:center; gap:4px; }
.img-zoom-controls button{
background:var(--navy-3); border:1px solid var(--border-2); color:var(--t2);
width:26px; height:26px; border-radius:6px; cursor:pointer; font-size:14px; line-height:1;
display:flex; align-items:center; justify-content:center; padding:0; transition:all .15s;
}
.img-zoom-controls button#imgZoomReset{ width:auto; padding:0 9px; font-size:11px; font-weight:700; }
.img-zoom-controls button:hover{ background:rgba(37,99,235,.08); border-color:var(--blue); color:var(--blue); }
.img-zoom-controls span{ font-size:11.5px; color:var(--t3); min-width:38px; text-align:center; font-family:var(--fm); }
.img-preview-wrap{
width:100%; height:82vh; border:1px solid var(--border-2); border-radius:10px;
background:var(--navy-3); overflow:auto; display:block;
}
.img-preview-wrap img{ display:block; }
.resizer{
flex:0 0 28px; align-self:stretch; cursor:col-resize;
display:flex; align-items:center; justify-content:center;
touch-action:none; position:relative;
}
/* A fader-knob look, not just a thin line - a rounded, raised pill with
grip dashes through its middle, so it visibly reads as a two-finger
drag handle rather than a stray divider. */
.resizer::before{
content:''; width:14px; height:58px; border-radius:9px;
background:linear-gradient(180deg, var(--navy-3), var(--navy-2));
border:1px solid var(--border-2);
box-shadow: inset 0 1px 0 rgba(255,255,255,.6), 0 2px 8px rgba(16,24,40,.10);
transition: border-color .15s, box-shadow .15s;
}
.resizer::after{
content:''; position:absolute; top:50%; left:50%;
width:2px; height:18px; border-radius:1px; background:var(--t3);
box-shadow: -4px 0 0 var(--t3), 4px 0 0 var(--t3);
transform:translate(-50%,-50%);
transition: background .15s;
}
.resizer:hover::before, .resizer.dragging::before{
border-color:var(--border-b);
box-shadow: inset 0 1px 0 rgba(255,255,255,.7), 0 0 0 1px rgba(37,99,235,.25), 0 2px 10px rgba(16,24,40,.12);
}
.resizer:hover::after, .resizer.dragging::after{
background:var(--blue); box-shadow: -4px 0 0 var(--blue), 4px 0 0 var(--blue);
}
.txn-col{ flex:1 1 auto; min-width:260px; }
.txn-col-head{ display:flex; align-items:center; justify-content:space-between; margin-bottom:18px; }
.txn-col-head h2{ margin-bottom:0; }
.btn-toggle{
background:var(--blue); border:none; color:var(--navy-2); font-family:var(--fd); font-weight:700;
font-size:12px; padding:7px 15px; border-radius:8px; cursor:pointer; transition:all .15s; flex-shrink:0;
box-shadow:0 2px 10px rgba(37,99,235,.18);
}
.btn-toggle:hover{ background:var(--blue-b); }
.btn-toggle:disabled{ opacity:.5; cursor:not-allowed; box-shadow:none; }
.pdf-col.hidden-panel, .resizer.hidden-panel{ display:none; }
.txn-col .table-wrap{ max-height:82vh; overflow-y:auto; margin-top:4px; }
.txn-col table thead th{
position:sticky; top:0; background:var(--navy-2); z-index:1;
}
@media (max-width: 860px){
.review-grid{ flex-direction:column; position:static; }
.pdf-col{ position:static; flex-basis:auto !important; width:100%; }
.resizer{ display:none; }
.txn-col{ width:100%; }
}
</style>
</head>
<body>
<main>
<div class="eyebrow">Extraction &amp; verification</div>
<h1>Bank Statement Extractor</h1>
<div class="sub">Upload a bank statement PDF or photo. A text PDF structures the transactions and proves the arithmetic against two independent extraction passes; a scanned or photographed statement is read via OCR instead, with no second pass to cross-check it against.</div>
<div class="card upload-card">
<h2>Statement</h2>
<div class="file-zone" id="fileZone">
<input type="file" id="fileInput" accept=".pdf,application/pdf,.jpg,.jpeg,.png,image/jpeg,image/png">
<div class="file-zone-label"><strong>Drop a statement PDF or photo here</strong> or browse</div>
<div class="file-zone-sub" id="fileZoneSub">.pdf, .jpg, or .png files</div>
</div>
<button class="btn btn-primary" id="processBtn" disabled>Extract</button>
<span class="spinner" id="spinner" style="display:none">Processing…</span>
<div class="error-note" id="errorNote"></div>
</div>
<div id="resultSection">
<div class="restore-banner" id="restoreBanner">
<span id="restoreBannerText"></span>
<button id="discardRestoreBtn">Discard saved edits</button>
</div>
<div class="card">
<div class="result-head">
<div class="result-head-left" id="resultHeadLeft">
<button class="collapse-arrow" id="resultToggleBtn" type="button" aria-expanded="false" title="Show details">&#9656;</button>
<h2>Result</h2>
</div>
<button class="btn-toggle" id="downloadBtn" type="button">Download Excel</button>
</div>
<div class="result-details" id="resultDetails">
<div id="statusBanner" class="status-banner"></div>
<div id="periodNote" class="period-note"></div>
<ul class="checks-list" id="checksList"></ul>
</div>
</div>
<div class="review-grid">
<div class="card pdf-col" id="pdfCol">
<div class="pdf-col-head">
<h2>Source Document</h2>
<div class="img-zoom-controls" id="imgZoomControls" hidden>
<button type="button" id="imgZoomOut" title="Zoom out">&#8722;</button>
<span id="imgZoomLevel">100%</span>
<button type="button" id="imgZoomIn" title="Zoom in">+</button>
<button type="button" id="imgZoomReset" title="Reset zoom to fit">Fit</button>
</div>
</div>
<iframe id="pdfPreview" title="Statement PDF preview"></iframe>
<div class="img-preview-wrap" id="imgPreviewWrap" hidden>
<img id="imgPreview" alt="Statement image preview">
</div>
</div>
<div class="resizer" id="resizer"></div>
<div class="card txn-col">
<div class="txn-col-head">
<h2>Transactions</h2>
<button class="btn-toggle" id="togglePdfBtn" type="button">Hide Source Doc</button>
</div>
<div class="fields">
<div>
<label>Opening balance (optional)</label>
<input type="text" inputmode="decimal" id="openingBalance" placeholder="e.g. 90,569.13">
<div class="calc-readout" id="openingCalc"></div>
</div>
<div>
<label>Closing balance (optional)</label>
<input type="text" inputmode="decimal" id="closingBalance" placeholder="e.g. 88,479.50">
<div class="calc-readout" id="closingCalc"></div>
</div>
</div>
<div class="note">This statement format may not print a clean opening/closing balance — enter them here to run the full statement balance check; otherwise it's marked "not available" rather than guessed.</div>
<div class="note" id="editNote">Click the pencil on a row to edit it, then Save to commit - edits are saved to this browser as you confirm them, row by row.</div>
<div class="table-wrap">
<table>
<colgroup>
<col style="width:34px">
<col style="width:120px">
<col>
<col style="width:120px">
<col style="width:135px">
<col style="width:95px">
</colgroup>
<thead><tr><th></th><th>Date</th><th>Description</th><th class="amt">Amount</th><th class="amt">Balance</th><th>Status</th></tr></thead>
<tbody id="txnRows"></tbody>
</table>
</div>
</div>
</div>
</div>
</main>
<script>
const $ = id => document.getElementById(id);
function escapeHtml(s) {
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
function fmtMoney(n) {
if (n === null || n === undefined) return '—';
const sign = n < 0 ? '-' : '';
return sign + '$' + Math.abs(n).toLocaleString('en-US', {minimumFractionDigits: 2});
}
// Same comma grouping as fmtMoney but no $ sign - used inside the
// editable Amount/Balance cells, where a leading $ would just get
// parsed back out on save anyway.
function fmtNum(n) {
if (n === null || n === undefined) return '';
const sign = n < 0 ? '-' : '';
return sign + Math.abs(n).toLocaleString('en-US', {minimumFractionDigits: 2});
}
function parseNum(s) {
s = s.replace(/[^0-9.\-]/g, '');
return s === '' || s === '-' ? null : parseFloat(s);
}
// Whatever the user typed always wins; an intentionally blank field (no
// auto-fill, per the UI's own calculated-balance readouts) falls back
// to the statement's own auto-detected figure from the initial extract -
// otherwise a row edit's recheck/export would lose that figure entirely
// the moment the visible field is empty.
function effectiveOpeningBalance() {
const typed = parseNum($('openingBalance').value);
return typed !== null ? typed : (currentResult ? currentResult.opening_balance : null);
}
function effectiveClosingBalance() {
const typed = parseNum($('closingBalance').value);
return typed !== null ? typed : (currentResult ? currentResult.closing_balance : null);
}
function autoGrow(el) {
el.style.height = 'auto';
el.style.height = el.scrollHeight + 'px';
}
function autoGrowAll() {
document.querySelectorAll('#txnRows .desc-input').forEach(autoGrow);
}
// ── Collapse/expand the Result card's details ───────────────────────────
// Starts collapsed on every fresh result (just the status/download row
// shows) - the arrow on the left toggles the status banner/checks list,
// the Download Excel button on the right stays independently clickable.
function setResultExpanded(expanded) {
$('resultDetails').classList.toggle('expanded', expanded);
$('resultToggleBtn').classList.toggle('expanded', expanded);
$('resultToggleBtn').setAttribute('aria-expanded', String(expanded));
$('resultToggleBtn').title = expanded ? 'Hide details' : 'Show details';
}
$('resultHeadLeft').addEventListener('click', () => {
setResultExpanded(!$('resultDetails').classList.contains('expanded'));
});
let chosenFile = null;
let currentPdfUrl = null;
let currentResult = null;
let currentDocKey = null;
let lastFilename = '';
let flaggedIndexes = new Set();
// ── Persistence (edits survive a crash/reload) ──────────────────────────
// Keyed by the SOURCE file's own name+size (stable across re-selecting the
// same file after a crash), not the server's randomly-generated output
// filename - that changes every run even for the same source document.
function docKeyFor(file) {
return 'bse:doc:' + file.name + ':' + file.size;
}
function persist() {
if (!currentDocKey || !currentResult) return;
try {
localStorage.setItem(currentDocKey, JSON.stringify(currentResult));
localStorage.setItem('bse:last_doc_key', currentDocKey);
} catch (e) { /* storage full/unavailable - edits still work in-memory */ }
}
function tryRestore(key) {
let saved;
try { saved = localStorage.getItem(key); } catch (e) { return false; }
if (!saved) return false;
try {
const parsed = JSON.parse(saved);
currentResult = parsed;
currentDocKey = key;
renderResult(parsed, { restored: true });
return true;
} catch (e) { return false; }
}
function setFile(file) {
if (!file) return;
if (!/\.(pdf|jpe?g|png)$/i.test(file.name)) {
$('errorNote').textContent = 'Please choose a .pdf, .jpg, or .png file.';
$('errorNote').classList.add('visible');
return;
}
chosenFile = file;
$('errorNote').classList.remove('visible');
$('fileZoneSub').textContent = file.name;
$('fileZoneSub').classList.add('file-chosen-name');
$('processBtn').disabled = false;
if (currentPdfUrl) URL.revokeObjectURL(currentPdfUrl);
currentPdfUrl = URL.createObjectURL(file);
const isImage = /\.(jpe?g|png)$/i.test(file.name);
if (isImage) {
// An image has no native viewer chrome the way a browser's built-in
// PDF viewer does - #toolbar=1 etc only means something for a PDF -
// so it gets its own zoomable/scrollable panel instead of the iframe.
$('pdfPreview').style.display = 'none';
$('imgPreviewWrap').hidden = false;
$('imgZoomControls').hidden = false;
$('imgPreview').src = currentPdfUrl;
} else {
$('pdfPreview').style.display = '';
$('imgPreviewWrap').hidden = true;
$('imgZoomControls').hidden = true;
// #toolbar=1 forces the browser's native PDF viewer toolbar (page
// nav + zoom controls) on; navpanes=0 skips the thumbnails/bookmarks
// sidebar so the toolbar isn't competing for space in a narrow column.
$('pdfPreview').src = currentPdfUrl + '#toolbar=1&navpanes=0&view=FitH';
}
const key = docKeyFor(file);
if (key === currentDocKey) {
// Same file re-selected (e.g. just to restore the preview after a
// crash) - leave the already-shown results/edits alone.
return;
}
$('resultSection').style.display = 'none';
currentResult = null;
currentDocKey = null;
tryRestore(key); // shows it immediately if this exact file has a saved session
}
const zone = $('fileZone');
$('fileInput').addEventListener('change', () => setFile($('fileInput').files[0]));
zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
zone.addEventListener('drop', e => {
e.preventDefault(); zone.classList.remove('drag-over');
setFile(e.dataTransfer.files[0]);
});
$('processBtn').addEventListener('click', async () => {
if (!chosenFile) return;
$('processBtn').disabled = true;
$('spinner').style.display = 'inline';
$('errorNote').classList.remove('visible');
$('resultSection').style.display = 'none';
const fd = new FormData();
fd.append('statement_file', chosenFile);
const obField = parseNum($('openingBalance').value);
if (obField !== null) fd.append('opening_balance', obField);
const cbField = parseNum($('closingBalance').value);
if (cbField !== null) fd.append('closing_balance', cbField);
try {
const r = await fetch('/api/process', { method: 'POST', body: fd });
const d = await r.json();
if (d.error) {
$('errorNote').textContent = d.error;
$('errorNote').classList.add('visible');
} else {
currentDocKey = docKeyFor(chosenFile);
currentResult = d;
persist();
renderResult(d);
}
} catch (e) {
$('errorNote').textContent = 'Network error: ' + e.message;
$('errorNote').classList.add('visible');
}
$('spinner').style.display = 'none';
$('processBtn').disabled = false;
});
function applyCheckResults(checkResult) {
currentResult.status = checkResult.status;
currentResult.checks = checkResult.checks;
const banner = $('statusBanner');
banner.className = 'status-banner ' + checkResult.status.replace(' ', '-');
banner.textContent = checkResult.status;
$('checksList').innerHTML = checkResult.checks.map(c => `
<li><span class="tag ${c.outcome}">${c.outcome.replace('_',' ')}</span>
<span><strong>${c.name.replace(/_/g,' ')}</strong> — ${escapeHtml(c.detail)}</span></li>
`).join('');
// The statement-balance check's own computed closing (opening +
// credits + debits) - shown under the Closing balance field as a
// read-only readout, separate from whatever the user may have typed
// there, turning green exactly when it matches (check outcome "pass").
const balanceCheck = checkResult.checks.find(c => c.name === 'statement_balance');
const matched = balanceCheck && balanceCheck.outcome === 'pass';
$('openingCalc').classList.toggle('match', matched);
$('closingCalc').classList.toggle('match', matched);
if (balanceCheck && balanceCheck.calculated_closing !== undefined && balanceCheck.calculated_closing !== null) {
$('closingCalc').textContent = 'Calculated: ' + fmtMoney(balanceCheck.calculated_closing);
} else {
$('closingCalc').textContent = '';
}
flaggedIndexes = new Set();
checkResult.checks.forEach(c => {
(c.mismatches || c.issues || []).forEach(item => {
if (item.index !== undefined) flaggedIndexes.add(item.index);
});
});
document.querySelectorAll('#txnRows tr').forEach((tr, i) => {
tr.classList.toggle('flagged', flaggedIndexes.has(i));
});
}
function renderResult(d, opts) {
opts = opts || {};
lastFilename = d.filename;
$('periodNote').textContent = d.period ? `Statement period: ${d.period}` : '';
// The input fields themselves stay exactly what the user typed (or
// blank, if they typed nothing) - never auto-filled, to avoid the
// confusion of a value appearing there that isn't the user's own.
// Whatever the statement printed inside its own table (see pipeline.py's
// own fallback) - or whatever the user already typed, which the server
// echoes back unchanged - shows instead as a separate read-only readout.
$('openingCalc').textContent = (d.opening_balance !== null && d.opening_balance !== undefined)
? 'Calculated: ' + fmtMoney(d.opening_balance) : '';
flaggedIndexes = new Set();
d.checks.forEach(c => {
(c.mismatches || c.issues || []).forEach(item => {
if (item.index !== undefined) flaggedIndexes.add(item.index);
});
});
renderTxnRows(d.transactions);
applyCheckResults({ status: d.status, checks: d.checks });
setResultExpanded(false);
const rb = $('restoreBanner');
if (opts.restored) {
$('restoreBannerText').textContent = 'Restored previously edited values for this file from this browser - re-select the source PDF above to view it alongside the data again.';
rb.classList.add('visible');
} else {
rb.classList.remove('visible');
}
$('resultSection').style.display = 'block';
// scrollHeight (what autoGrow measures) is always 0 on a hidden
// ancestor, so re-measure now that the section is actually visible -
// the earlier call inside renderTxnRows ran while it was still
// display:none and would have collapsed every description box.
autoGrowAll();
}
function rowHtml(t, i) {
return `
<tr class="${flaggedIndexes.has(i) ? 'flagged' : ''}" data-idx="${i}">
<td class="row-actions"><button class="row-btn edit" data-action="edit" title="Edit this row">&#9998;</button></td>
<td><input class="cell-input" data-field="date" value="${escapeHtml(t.date)}" readonly></td>
<td class="desc"><textarea class="cell-input desc-input" data-field="description" rows="1" readonly>${escapeHtml(t.description)}</textarea></td>
<td class="amt"><input class="cell-input" data-field="amount" type="text" value="${escapeHtml(fmtNum(t.amount))}" readonly></td>
<td class="amt"><input class="cell-input" data-field="balance" type="text" value="${escapeHtml(fmtNum(t.balance))}" readonly></td>
<td><input class="cell-input" data-field="status" value="${escapeHtml(t.status)}" readonly></td>
</tr>`;
}
function renderTxnRows(transactions) {
$('txnRows').innerHTML = transactions.map((t, i) => rowHtml(t, i)).join('');
autoGrowAll();
}
// ── Re-check after a saved edit ─────────────────────────────────────────
// Re-runs the six checks against the edited transactions (pipeline.recheck
// - no re-extraction) and updates the status banner/flags in place, so a
// correction can clear a flag (or a typo can raise one) right after it's
// saved. See also the Download button, which uses the same recheck logic
// server-side to keep the export consistent with saved edits.
async function recheck() {
if (!currentResult) return;
try {
const r = await fetch('/api/recheck', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
transactions: currentResult.transactions,
page_reports: currentResult.page_reports,
narrative_direction: currentResult.narrative_direction,
period: currentResult.period,
opening_balance: effectiveOpeningBalance(),
closing_balance: effectiveClosingBalance(),
}),
});
const d = await r.json();
if (!d.error) applyCheckResults(d);
} catch (e) { /* recheck is best-effort; the saved edit itself isn't lost either way */ }
}
// ── Pencil-to-edit, per-row Save/Cancel ─────────────────────────────────
// Cells are read-only by default - a row only becomes editable after its
// own pencil is clicked (so edits are always deliberate, never an
// accidental keystroke in a cell you were just scrolling past), and a
// commit only happens on that row's own Save, which is when the edit is
// applied to currentResult, persisted, and re-checked.
function setRowEditing(tr, editing) {
tr.classList.toggle('editing', editing);
tr.querySelectorAll('.cell-input').forEach(inp => { inp.readOnly = !editing; });
const actionCell = tr.querySelector('.row-actions');
actionCell.innerHTML = editing
? `<button class="row-btn save" data-action="save" title="Save this row">&#10003;</button>
<button class="row-btn cancel" data-action="cancel" title="Discard changes">&#10005;</button>`
: `<button class="row-btn edit" data-action="edit" title="Edit this row">&#9998;</button>`;
}
$('txnRows').addEventListener('input', e => {
if (e.target.classList.contains('desc-input')) autoGrow(e.target);
});
$('txnRows').addEventListener('click', e => {
const btn = e.target.closest('.row-btn');
if (!btn) return;
const tr = btn.closest('tr');
const idx = +tr.dataset.idx;
if (btn.dataset.action === 'edit') {
setRowEditing(tr, true);
const first = tr.querySelector('.cell-input');
first.focus();
autoGrow(tr.querySelector('.desc-input'));
} else if (btn.dataset.action === 'cancel') {
tr.outerHTML = rowHtml(currentResult.transactions[idx], idx);
autoGrow(document.querySelector(`#txnRows tr[data-idx="${idx}"] .desc-input`));
} else if (btn.dataset.action === 'save') {
tr.querySelectorAll('.cell-input').forEach(inp => {
const field = inp.dataset.field;
let value = inp.value;
if (field === 'amount' || field === 'balance') {
value = parseNum(value);
}
currentResult.transactions[idx][field] = value;
});
// Re-render from the saved data so Amount/Balance pick up comma
// formatting and the description re-wraps, whatever was typed.
tr.outerHTML = rowHtml(currentResult.transactions[idx], idx);
const newTr = document.querySelector(`#txnRows tr[data-idx="${idx}"]`);
newTr.querySelectorAll('.cell-input').forEach(inp => inp.classList.add('edited'));
autoGrow(newTr.querySelector('.desc-input'));
persist();
recheck();
}
});
$('discardRestoreBtn').addEventListener('click', () => {
if (currentDocKey) {
try { localStorage.removeItem(currentDocKey); } catch (e) {}
}
$('restoreBanner').classList.remove('visible');
});
$('downloadBtn').addEventListener('click', async () => {
if (!currentResult) return;
const btn = $('downloadBtn');
btn.disabled = true;
const prevText = btn.textContent;
btn.textContent = 'Preparing…';
try {
const r = await fetch('/api/export', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
transactions: currentResult.transactions,
page_reports: currentResult.page_reports,
narrative_direction: currentResult.narrative_direction,
period: currentResult.period,
brought_forward_balance: currentResult.brought_forward_balance,
title: currentResult.title,
opening_balance: effectiveOpeningBalance(),
closing_balance: effectiveClosingBalance(),
}),
});
if (!r.ok) throw new Error('Export failed');
const blob = await r.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = (currentResult.title || 'Statement_Extraction').replace(/\.pdf$/i, '') + '.xlsx';
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
} catch (e) {
$('errorNote').textContent = 'Could not generate the export: ' + e.message;
$('errorNote').classList.add('visible');
}
btn.disabled = false;
btn.textContent = prevText;
});
// On page load, restore any previous session right away - before any file
// is even chosen - so a crash mid-edit never loses work. The source PDF
// itself isn't persisted (not practical to store in localStorage), so the
// preview stays empty until the same file is re-picked.
(function restoreOnLoad() {
let lastKey;
try { lastKey = localStorage.getItem('bse:last_doc_key'); } catch (e) { return; }
if (lastKey) tryRestore(lastKey);
})();
// ── Image zoom controls (the PDF path gets this for free from the
// browser's own native viewer - #toolbar=1 in setFile - an <img> has no
// such chrome, so this fills that gap) ──────────────────────────────────
// Width-based, not CSS transform:scale - see the .img-preview-wrap CSS
// comment for why a scaled-up image needs its actual layout size changed
// for the wrap's overflow:auto to produce real scrollbars.
const IMG_ZOOM_STEP = 0.25, IMG_ZOOM_MIN = 0.25, IMG_ZOOM_MAX = 4;
let imgZoom = 1, imgFitZoom = 1;
function setImgZoom(z) {
const img = $('imgPreview');
imgZoom = Math.max(IMG_ZOOM_MIN, Math.min(IMG_ZOOM_MAX, z));
if (img.naturalWidth) img.style.width = Math.round(img.naturalWidth * imgZoom) + 'px';
$('imgZoomLevel').textContent = Math.round(imgZoom * 100) + '%';
}
$('imgPreview').addEventListener('load', () => {
const img = $('imgPreview');
const wrap = $('imgPreviewWrap');
// Fit-to-width on load, the same starting impression the PDF viewer's
// own view=FitH gives - a native-resolution phone photo is usually
// much wider than this panel and would otherwise open mostly
// off-screen, needing an immediate manual zoom-out just to get
// oriented.
imgFitZoom = img.naturalWidth ? Math.min(1, wrap.clientWidth / img.naturalWidth) : 1;
setImgZoom(imgFitZoom);
});
$('imgZoomIn').addEventListener('click', () => setImgZoom(imgZoom + IMG_ZOOM_STEP));
$('imgZoomOut').addEventListener('click', () => setImgZoom(imgZoom - IMG_ZOOM_STEP));
$('imgZoomReset').addEventListener('click', () => setImgZoom(imgFitZoom));
// ── Hide/show the PDF column ────────────────────────────────────────────
// Collapses the PDF column (and its resizer handle) out of the flex row
// entirely - txn-col's own flex:1 1 auto then fills the freed width on
// its own, no extra sizing needed. The toggle lives in the Transactions
// header rather than the PDF card's own header, since that card
// disappears when hidden and would take its own "Show" button with it.
$('togglePdfBtn').addEventListener('click', () => {
const pdfCol = $('pdfCol');
const resizer = $('resizer');
const hidden = pdfCol.classList.toggle('hidden-panel');
resizer.classList.toggle('hidden-panel', hidden);
$('togglePdfBtn').textContent = hidden ? 'Show Source Doc' : 'Hide Source Doc';
// Transactions column just changed width - every description box may
// rewrap at a different height, same reason the drag-resizer's own
// move handler re-measures (see its own comment below).
autoGrowAll();
});
// ── Draggable divider between the PDF and the transactions list ────────
(function() {
const grid = document.querySelector('.review-grid');
const resizer = $('resizer');
const pdfCol = $('pdfCol');
let dragging = false;
function setWidthFromX(clientX) {
const rect = grid.getBoundingClientRect();
let pct = ((clientX - rect.left) / rect.width) * 100;
pct = Math.max(25, Math.min(75, pct));
pdfCol.style.flexBasis = pct + '%';
}
function start(e) {
dragging = true;
resizer.classList.add('dragging');
document.body.style.userSelect = 'none';
e.preventDefault();
}
function move(e) {
if (!dragging) return;
const x = e.touches ? e.touches[0].clientX : e.clientX;
setWidthFromX(x);
}
function end() {
if (!dragging) return;
dragging = false;
resizer.classList.remove('dragging');
document.body.style.userSelect = '';
autoGrowAll(); // column width changed - descriptions may rewrap at a different height
}
resizer.addEventListener('mousedown', start);
window.addEventListener('mousemove', move);
window.addEventListener('mouseup', end);
resizer.addEventListener('touchstart', start, { passive: false });
window.addEventListener('touchmove', move, { passive: false });
window.addEventListener('touchend', end);
})();
</script>
</body>
</html>