From 6e4da3f385e137ac3c1c5ce226519c4bc03f2864 Mon Sep 17 00:00:00 2001 From: JasonFraser Date: Mon, 12 Oct 2026 06:32:49 -0400 Subject: [PATCH] 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 / 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 --- CLAUDE.md | 239 ++- Dockerfile | 17 +- backend/app.py | 36 +- frontend/.gitignore | 24 + frontend/.vscode/extensions.json | 3 + frontend/README.md | 5 + frontend/index.html | 14 + frontend/package-lock.json | 1578 +++++++++++++++++ frontend/package.json | 20 + frontend/public/favicon.svg | 1 + frontend/src/App.vue | 11 + frontend/src/assets/main.css | 279 +++ frontend/src/components/FileUploadZone.vue | 57 + .../src/components/ProcessingIndicator.vue | 19 + frontend/src/components/ResizablePanels.vue | 80 + frontend/src/components/RestoreBanner.vue | 27 + frontend/src/components/ResultCard.vue | 84 + .../src/components/SourceDocumentPanel.vue | 43 + frontend/src/components/TransactionRow.vue | 100 ++ frontend/src/components/TransactionsTable.vue | 93 + frontend/src/composables/useAutoGrow.js | 20 + frontend/src/composables/useExtraction.js | 51 + frontend/src/composables/useFileUpload.js | 90 + frontend/src/composables/useImageZoom.js | 51 + .../src/composables/useProcessingPhases.js | 60 + frontend/src/composables/useRowEditing.js | 78 + frontend/src/main.js | 9 + .../src/repositories/extractionRepository.js | 53 + .../repositories/localStorageRepository.js | 31 + frontend/src/router/index.js | 9 + frontend/src/services/extractionService.js | 89 + frontend/src/services/formatService.js | 30 + frontend/src/stores/extractionStore.js | 88 + frontend/src/stores/uiStore.js | 43 + frontend/src/views/ExtractorView.vue | 74 + frontend/vite.config.js | 14 + templates/index.html | 895 ---------- 37 files changed, 3455 insertions(+), 960 deletions(-) create mode 100644 frontend/.gitignore create mode 100644 frontend/.vscode/extensions.json create mode 100644 frontend/README.md create mode 100644 frontend/index.html create mode 100644 frontend/package-lock.json create mode 100644 frontend/package.json create mode 100644 frontend/public/favicon.svg create mode 100644 frontend/src/App.vue create mode 100644 frontend/src/assets/main.css create mode 100644 frontend/src/components/FileUploadZone.vue create mode 100644 frontend/src/components/ProcessingIndicator.vue create mode 100644 frontend/src/components/ResizablePanels.vue create mode 100644 frontend/src/components/RestoreBanner.vue create mode 100644 frontend/src/components/ResultCard.vue create mode 100644 frontend/src/components/SourceDocumentPanel.vue create mode 100644 frontend/src/components/TransactionRow.vue create mode 100644 frontend/src/components/TransactionsTable.vue create mode 100644 frontend/src/composables/useAutoGrow.js create mode 100644 frontend/src/composables/useExtraction.js create mode 100644 frontend/src/composables/useFileUpload.js create mode 100644 frontend/src/composables/useImageZoom.js create mode 100644 frontend/src/composables/useProcessingPhases.js create mode 100644 frontend/src/composables/useRowEditing.js create mode 100644 frontend/src/main.js create mode 100644 frontend/src/repositories/extractionRepository.js create mode 100644 frontend/src/repositories/localStorageRepository.js create mode 100644 frontend/src/router/index.js create mode 100644 frontend/src/services/extractionService.js create mode 100644 frontend/src/services/formatService.js create mode 100644 frontend/src/stores/extractionStore.js create mode 100644 frontend/src/stores/uiStore.js create mode 100644 frontend/src/views/ExtractorView.vue create mode 100644 frontend/vite.config.js delete mode 100644 templates/index.html diff --git a/CLAUDE.md b/CLAUDE.md index 0eb92ef..013d705 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 (
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("/")`) 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 `/` 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 ` +
+ Statement image preview +
+ diff --git a/frontend/src/components/TransactionRow.vue b/frontend/src/components/TransactionRow.vue new file mode 100644 index 0000000..9249bcc --- /dev/null +++ b/frontend/src/components/TransactionRow.vue @@ -0,0 +1,100 @@ + + + diff --git a/frontend/src/components/TransactionsTable.vue b/frontend/src/components/TransactionsTable.vue new file mode 100644 index 0000000..218f114 --- /dev/null +++ b/frontend/src/components/TransactionsTable.vue @@ -0,0 +1,93 @@ + + + diff --git a/frontend/src/composables/useAutoGrow.js b/frontend/src/composables/useAutoGrow.js new file mode 100644 index 0000000..16635f7 --- /dev/null +++ b/frontend/src/composables/useAutoGrow.js @@ -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 } +} diff --git a/frontend/src/composables/useExtraction.js b/frontend/src/composables/useExtraction.js new file mode 100644 index 0000000..e0ee801 --- /dev/null +++ b/frontend/src/composables/useExtraction.js @@ -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 } +} diff --git a/frontend/src/composables/useFileUpload.js b/frontend/src/composables/useFileUpload.js new file mode 100644 index 0000000..954c184 --- /dev/null +++ b/frontend/src/composables/useFileUpload.js @@ -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, + } +} diff --git a/frontend/src/composables/useImageZoom.js b/frontend/src/composables/useImageZoom.js new file mode 100644 index 0000000..c2a2713 --- /dev/null +++ b/frontend/src/composables/useImageZoom.js @@ -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 } +} diff --git a/frontend/src/composables/useProcessingPhases.js b/frontend/src/composables/useProcessingPhases.js new file mode 100644 index 0000000..2e8deb3 --- /dev/null +++ b/frontend/src/composables/useProcessingPhases.js @@ -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 } +} diff --git a/frontend/src/composables/useRowEditing.js b/frontend/src/composables/useRowEditing.js new file mode 100644 index 0000000..e93022d --- /dev/null +++ b/frontend/src/composables/useRowEditing.js @@ -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 } +} diff --git a/frontend/src/main.js b/frontend/src/main.js new file mode 100644 index 0000000..227198e --- /dev/null +++ b/frontend/src/main.js @@ -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') diff --git a/frontend/src/repositories/extractionRepository.js b/frontend/src/repositories/extractionRepository.js new file mode 100644 index 0000000..85dab64 --- /dev/null +++ b/frontend/src/repositories/extractionRepository.js @@ -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() +} diff --git a/frontend/src/repositories/localStorageRepository.js b/frontend/src/repositories/localStorageRepository.js new file mode 100644 index 0000000..57720dc --- /dev/null +++ b/frontend/src/repositories/localStorageRepository.js @@ -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 */ + } +} diff --git a/frontend/src/router/index.js b/frontend/src/router/index.js new file mode 100644 index 0000000..355cfaf --- /dev/null +++ b/frontend/src/router/index.js @@ -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 }], +}) diff --git a/frontend/src/services/extractionService.js b/frontend/src/services/extractionService.js new file mode 100644 index 0000000..20bf117 --- /dev/null +++ b/frontend/src/services/extractionService.js @@ -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) +} diff --git a/frontend/src/services/formatService.js b/frontend/src/services/formatService.js new file mode 100644 index 0000000..fe7517e --- /dev/null +++ b/frontend/src/services/formatService.js @@ -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) +} diff --git a/frontend/src/stores/extractionStore.js b/frontend/src/stores/extractionStore.js new file mode 100644 index 0000000..75f0c97 --- /dev/null +++ b/frontend/src/stores/extractionStore.js @@ -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 = '' + }, + }, +}) diff --git a/frontend/src/stores/uiStore.js b/frontend/src/stores/uiStore.js new file mode 100644 index 0000000..a082322 --- /dev/null +++ b/frontend/src/stores/uiStore.js @@ -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 + }, + }, +}) diff --git a/frontend/src/views/ExtractorView.vue b/frontend/src/views/ExtractorView.vue new file mode 100644 index 0000000..b7446fb --- /dev/null +++ b/frontend/src/views/ExtractorView.vue @@ -0,0 +1,74 @@ + + + diff --git a/frontend/vite.config.js b/frontend/vite.config.js new file mode 100644 index 0000000..009116a --- /dev/null +++ b/frontend/vite.config.js @@ -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', + }, + }, +}) diff --git a/templates/index.html b/templates/index.html deleted file mode 100644 index 75ad2c5..0000000 --- a/templates/index.html +++ /dev/null @@ -1,895 +0,0 @@ - - - - - -Bank Statement Extractor - - - - -
-
Extraction & verification
-

Bank Statement Extractor

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

Statement

-
- -
Drop a statement PDF or photo here or browse
-
.pdf, .jpg, or .png files
-
- - - -
-
- -
-
- - -
- -
-
-
- -

Result

-
- -
-
-
-
-
    -
    -
    - -
    -
    -
    -

    Source Document

    - -
    - - -
    - -
    - -
    -
    -

    Transactions

    - -
    -
    -
    - - -
    -
    -
    - - -
    -
    -
    -
    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.
    -
    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.
    -
    - - - - - - - - - - - -
    DateDescriptionAmountBalanceStatus
    -
    -
    -
    -
    -
    - - - -