Move Excel exports to R2; remove dead per-extraction workbook generation
The actual request was simple (store exports in R2 like source files, pending a retention-duration decision), but investigating where exports were written surfaced something worse: /api/process built and saved a full workbook to disk on EVERY extraction, and nothing in the frontend ever called /api/download/<filename> to retrieve it (confirmed by grep - no reference anywhere). Every extraction was silently orphaning an .xlsx file for no reason; 91 had already accumulated locally from this session's own testing alone. Removed the dead work entirely: /api/process no longer builds or saves a workbook at all. /api/download/<filename>, file_repository. save_workbook/resolve_output_path, and OUTPUT_FOLDER (env var, volume, directory) are all gone - confirmed nothing else referenced any of them before removing. outputs/ deleted, including its 91 accumulated files. /api/export (the only path actually used - Download Excel/All) now builds the workbook into an in-memory BytesIO and streams it straight from there - never touches disk, not even temporarily. The frontend persists it long-term instead: documentsService.saveExportFile uploads the same Blob the browser download already used to a new exportFile field (pb_migrations/3_add_export_file.js), stored in R2 same as sourceFile. Overwrites the previous export rather than keeping a history - no retention policy has been decided yet, and keeping every version would just relocate the same unbounded-growth problem from the VPS to R2 instead of fixing it. Best-effort from ResultCard.vue - a save failure is reported but never blocks the browser download itself. Verified for real: /api/process's response no longer has `filename` (title still does); /api/export still streams a valid, correctly-typed .xlsx; /app/outputs no longer exists in the rebuilt container; the old /api/download URL now falls through to the ordinary SPA catch-all, not a leftover route. documentsService.saveExportFile run against the REAL bytes /api/export produced, fetched back through the R2-backed URL, confirmed byte-for-byte - and confirmed a second export overwrites rather than creating a second record. measure.py unaffected; npm run build passes.
This commit is contained in:
parent
e59013cdcb
commit
63c790f52b
|
|
@ -5,7 +5,5 @@ __pycache__/
|
||||||
.claude/
|
.claude/
|
||||||
uploads/*
|
uploads/*
|
||||||
!uploads/.gitkeep
|
!uploads/.gitkeep
|
||||||
outputs/*
|
|
||||||
!outputs/.gitkeep
|
|
||||||
results/*.json
|
results/*.json
|
||||||
.env
|
.env
|
||||||
|
|
|
||||||
115
CLAUDE.md
115
CLAUDE.md
|
|
@ -134,14 +134,17 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co
|
||||||
app.py — Flask app factory: registers blueprints; "/" and any
|
app.py — Flask app factory: registers blueprints; "/" and any
|
||||||
other non-API path serve frontend/dist's index.html
|
other non-API path serve frontend/dist's index.html
|
||||||
(SPA fallback) or the matching static asset if one exists
|
(SPA fallback) or the matching static asset if one exists
|
||||||
dependencies.py — DOCLING_URL/UPLOAD_FOLDER/OUTPUT_FOLDER read from env
|
dependencies.py — DOCLING_URL/UPLOAD_FOLDER read from env once at import
|
||||||
once at import time; repositories import this directly
|
time; repositories import this directly rather than
|
||||||
rather than reaching into Flask's current_app
|
reaching into Flask's current_app (OUTPUT_FOLDER
|
||||||
|
removed 2026-10-13 — see below, nothing writes
|
||||||
|
generated Excel files to disk anymore)
|
||||||
measure.py — the measurement harness (see below), relocated
|
measure.py — the measurement harness (see below), relocated
|
||||||
/routes
|
/routes
|
||||||
extraction.py — Blueprint: POST /api/process, /recheck, /export,
|
extraction.py — Blueprint: POST /api/process, /recheck, /export —
|
||||||
GET /api/download/<filename> — request in, call a
|
request in, call a service, response out, no business
|
||||||
service, response out, no business logic
|
logic. GET /api/download/<filename> removed 2026-10-13
|
||||||
|
(was dead — nothing ever called it, see below)
|
||||||
health.py — GET /health — pings Docling via docling_repository
|
health.py — GET /health — pings Docling via docling_repository
|
||||||
/services
|
/services
|
||||||
extraction_service.py — text-PDF-vs-OCR routing + the dual-engine cross-check
|
extraction_service.py — text-PDF-vs-OCR routing + the dual-engine cross-check
|
||||||
|
|
@ -149,9 +152,12 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co
|
||||||
checks_service.py — the checks (was checks.py, near-direct relocate)
|
checks_service.py — the checks (was checks.py, near-direct relocate)
|
||||||
pipeline_service.py — composes extraction_service + checks_service (was
|
pipeline_service.py — composes extraction_service + checks_service (was
|
||||||
pipeline.py)
|
pipeline.py)
|
||||||
excel_service.py — builds the openpyxl Workbook object (the *building*
|
excel_service.py — builds the openpyxl Workbook object entirely in
|
||||||
half of the old excel_export.py — saving to disk moved
|
memory — never touches disk itself (the *building*
|
||||||
to file_repository)
|
half of the old excel_export.py; the *saving* half
|
||||||
|
used to be file_repository.save_workbook, removed
|
||||||
|
2026-10-13 — /api/export now streams straight from an
|
||||||
|
in-memory buffer, see below)
|
||||||
/extraction — pure parsing/domain logic, no I/O:
|
/extraction — pure parsing/domain logic, no I/O:
|
||||||
table_extract.py — the pdfplumber extractor (unchanged)
|
table_extract.py — the pdfplumber extractor (unchanged)
|
||||||
layout_rules.py — shared column/balance keyword vocabulary (unchanged)
|
layout_rules.py — shared column/balance keyword vocabulary (unchanged)
|
||||||
|
|
@ -168,9 +174,11 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co
|
||||||
NOT treated as repositories):
|
NOT treated as repositories):
|
||||||
docling_repository.py — the raw HTTP POST to Docling (was
|
docling_repository.py — the raw HTTP POST to Docling (was
|
||||||
docling_client.convert() alone)
|
docling_client.convert() alone)
|
||||||
file_repository.py — save/remove an upload, save a workbook, resolve an
|
file_repository.py — save/remove an upload (was main.py's ad hoc
|
||||||
output path (was main.py's ad hoc f.save/os.remove/
|
f.save/os.remove calls). Used to also save a workbook
|
||||||
workbook.save/send_file calls)
|
to disk and resolve an output path for /api/download
|
||||||
|
— both removed 2026-10-13, see below; this is now
|
||||||
|
upload-only.
|
||||||
/schemas
|
/schemas
|
||||||
extraction_schema.py — validates/shapes the process/recheck/export request
|
extraction_schema.py — validates/shapes the process/recheck/export request
|
||||||
bodies (was main.py's inline _opt_float helpers)
|
bodies (was main.py's inline _opt_float helpers)
|
||||||
|
|
@ -232,9 +240,13 @@ security only, not the full SaaS-shaped doc — and the judgment call on what co
|
||||||
UI can show it even when the check itself is "not available." Running-balance and
|
UI can show it even when the check itself is "not available." Running-balance and
|
||||||
date-ordering checks try both directions and pick whichever has fewer violations, rather
|
date-ordering checks try both directions and pick whichever has fewer violations, rather
|
||||||
than assuming one.
|
than assuming one.
|
||||||
- `backend/services/excel_service.py` + `backend/repositories/file_repository.py` —
|
- `backend/services/excel_service.py` — Transactions + Summary sheet export, built
|
||||||
Transactions + Summary sheet export, split across the build (service) and disk-write
|
entirely in memory. No disk-write repository boundary anymore (there used to be one,
|
||||||
(repository) boundary.
|
`file_repository.save_workbook` — removed 2026-10-13 along with /api/process's own
|
||||||
|
dead workbook generation and the never-called /api/download/<filename> route; see
|
||||||
|
"Excel exports moved to R2" under Key decisions & lessons for the full story). The
|
||||||
|
frontend is what persists an export long-term now (`documentsService.saveExportFile`,
|
||||||
|
PocketBase/R2), not this backend at all.
|
||||||
- `backend/services/extraction/raw_ocr_extract.py` — the per-page fallback for
|
- `backend/services/extraction/raw_ocr_extract.py` — the per-page fallback for
|
||||||
`extraction_service._run_ocr_only` when Docling's table-structure recognition fails on a
|
`extraction_service._run_ocr_only` when Docling's table-structure recognition fails on a
|
||||||
scanned/photographed page. Runs OCR directly (`tesserocr`) for raw word text + pixel
|
scanned/photographed page. Runs OCR directly (`tesserocr`) for raw word text + pixel
|
||||||
|
|
@ -361,6 +373,12 @@ statement files, why every document is required to belong to a project from day
|
||||||
assumed — a plain base collection doesn't get them
|
assumed — a plain base collection doesn't get them
|
||||||
automatically the way the users auth collection does).
|
automatically the way the users auth collection does).
|
||||||
Adds autodate created/updated to both.
|
Adds autodate created/updated to both.
|
||||||
|
pb_migrations/3_add_export_file.js
|
||||||
|
— adds exportFile (type:"file") to documents - the
|
||||||
|
generated Excel workbook, stored in R2 same as
|
||||||
|
sourceFile, overwritten on every re-export rather than
|
||||||
|
kept as a history (see "Excel exports moved to R2"
|
||||||
|
under Key decisions & lessons).
|
||||||
pb_hooks/ensure_default_project.pb.js
|
pb_hooks/ensure_default_project.pb.js
|
||||||
— fires on every new users record (password signup and
|
— fires on every new users record (password signup and
|
||||||
Google OAuth2 signup both create one the same way) and
|
Google OAuth2 signup both create one the same way) and
|
||||||
|
|
@ -734,6 +752,68 @@ PATCH response echoed it back. `npm run build` passes. `measure.py` + both servi
|
||||||
health checks unaffected (no backend Python or Docling code touched); R2/Google settings
|
health checks unaffected (no backend Python or Docling code touched); R2/Google settings
|
||||||
confirmed to survive the PocketBase container rebuild (named volume, not reset).
|
confirmed to survive the PocketBase container rebuild (named volume, not reset).
|
||||||
|
|
||||||
|
**Excel exports moved to R2; a real dead-code/storage bug found and removed along the
|
||||||
|
way, 2026-10-13.** The user's actual request was simple - store generated Excel exports
|
||||||
|
in R2 too, "until we determine a data retention duration" (same VPS-storage concern that
|
||||||
|
prompted moving source PDFs/images to R2 in Stage B.1/B.2). Investigating where exports
|
||||||
|
were being written surfaced something worse than expected: **`/api/process` built and
|
||||||
|
saved a full Excel workbook to disk on EVERY SINGLE extraction, and nothing in the
|
||||||
|
frontend ever called `/api/download/<filename>` to retrieve it** (confirmed by grepping
|
||||||
|
the entire frontend for any reference to that route - none existed). Every extraction
|
||||||
|
was silently leaving a permanently-orphaned `.xlsx` file in `outputs/` for no reason at
|
||||||
|
all. Checking the real local `outputs/` directory from this session's own testing found
|
||||||
|
**91 orphaned files already accumulated** - concrete, not hypothetical, proof of the
|
||||||
|
exact problem the user was worried about. This wasn't "move existing storage to R2," it
|
||||||
|
was "most of this was pure waste that should never have been written anywhere."
|
||||||
|
|
||||||
|
Fixed in two parts:
|
||||||
|
1. **Removed the dead work entirely**: `/api/process` no longer builds or saves a
|
||||||
|
workbook at all (just returns the pipeline result + title). `/api/download/<filename>`,
|
||||||
|
`file_repository.save_workbook`, `file_repository.resolve_output_path`, and the
|
||||||
|
`OUTPUT_FOLDER` env var/volume/directory are all gone - nothing else referenced any of
|
||||||
|
them (confirmed by grep before removing, not assumed). `outputs/` itself was deleted,
|
||||||
|
including its 91 accumulated files and its `.gitkeep`/`.gitignore` entries.
|
||||||
|
2. **`/api/export`** (the ONLY path that was ever actually used - triggered deliberately
|
||||||
|
by Download Excel/All) was rewritten to build the workbook into an in-memory `BytesIO`
|
||||||
|
and `send_file` straight from that buffer - it never touches disk at all now, not even
|
||||||
|
temporarily. The frontend is what persists the result long-term:
|
||||||
|
`documentsService.saveExportFile(pbId, blob, fileName)` uploads the SAME `Blob` the
|
||||||
|
browser download already used (Blobs are immutable/reusable - one fetch serves both,
|
||||||
|
no second request) to a new `exportFile` field on the `documents` collection
|
||||||
|
(`pb_migrations/3_add_export_file.js`), stored in R2 the same way `sourceFile` already
|
||||||
|
is. Deliberately overwrites the previous export rather than keeping a history - a real
|
||||||
|
retention policy (how long to keep exports, or anything else, at all) hasn't been
|
||||||
|
decided yet, and keeping every past version would just relocate the exact unbounded-
|
||||||
|
growth problem this was meant to solve from the VPS to R2 instead of fixing it.
|
||||||
|
Persisting to R2 is best-effort from `ResultCard.vue`'s side - a failure there is
|
||||||
|
reported but never blocks or undoes the browser download the user actually asked for.
|
||||||
|
|
||||||
|
Verified for real, not assumed from the diff: `curl`'d `/api/process` and confirmed
|
||||||
|
`filename` is gone from the response while `title` (still genuinely used) remains;
|
||||||
|
`curl`'d `/api/export` and confirmed it still streams a valid, correctly-typed `.xlsx`
|
||||||
|
with the right `Content-Disposition`; confirmed `/app/outputs` no longer exists inside
|
||||||
|
the rebuilt container; confirmed hitting the old `/api/download/...` URL now falls
|
||||||
|
through to the ordinary SPA catch-all (the same 200+index.html any other unmatched path
|
||||||
|
already gets, not a leftover route in disguise - checked against a second, unrelated
|
||||||
|
nonexistent path to be sure). Then ran the real `documentsService.saveExportFile` against
|
||||||
|
the REAL `.xlsx` bytes `/api/export` had just produced (not a fake test file): uploaded
|
||||||
|
it, fetched it back through the R2-backed URL, confirmed a byte-for-byte match: and
|
||||||
|
confirmed a second export on the same document overwrites (`exportFile`'s own name
|
||||||
|
changes) rather than creating a second document record. `measure.py` unaffected (the
|
||||||
|
extraction pipeline itself untouched); `npm run build` passes.
|
||||||
|
|
||||||
|
**Separately, a real explanation gap worth recording honestly:** earlier in this same
|
||||||
|
conversation, "every processed document now saves directly to PocketBase" was accurate
|
||||||
|
about the API/record-creation path but read as if the file BYTES land in PocketBase's own
|
||||||
|
storage, which isn't what happens once R2 is configured - the user caught this and asked
|
||||||
|
directly which statement was correct. Resolution: both were consistent with the same real
|
||||||
|
behavior, just one used "PocketBase" loosely (the system/API as a whole, replacing
|
||||||
|
localStorage) and the other precisely (the record/metadata lives in PocketBase's SQLite;
|
||||||
|
the file bytes themselves are transparently redirected to R2, never touching PocketBase's
|
||||||
|
own local disk). Worth remembering when describing this architecture again: say "the
|
||||||
|
PocketBase *record*" vs. "the file bytes in R2" explicitly, rather than "stored in
|
||||||
|
PocketBase" unqualified.
|
||||||
|
|
||||||
**Governing rule: never silently correct or exclude data.** This shows up in several
|
**Governing rule: never silently correct or exclude data.** This shows up in several
|
||||||
concrete places, not just as an abstract principle:
|
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
|
- A row with an unusual status (e.g. HSBC's "Cancelled" wires) stays in the output and is
|
||||||
|
|
@ -1007,7 +1087,10 @@ restructure; the behavior itself predates it and is unchanged:
|
||||||
document through the same per-document export, triggering N sequential browser
|
document through the same per-document export, triggering N sequential browser
|
||||||
downloads rather than a zip bundle (some browsers prompt to allow multiple downloads
|
downloads rather than a zip bundle (some browsers prompt to allow multiple downloads
|
||||||
from one click - a known, minor wrinkle, not worth a new backend endpoint + dependency
|
from one click - a known, minor wrinkle, not worth a new backend endpoint + dependency
|
||||||
for a v1).
|
for a v1). As of 2026-10-13, every download also persists that same file to PocketBase/
|
||||||
|
R2 (`documentsService.saveExportFile`, best-effort - a failure there is reported but
|
||||||
|
never blocks the browser download itself) - the latest export only, overwritten each
|
||||||
|
time, not a history (no retention policy has been decided yet).
|
||||||
- Opening/closing balance inputs always start blank (never auto-filled) — a separate
|
- 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,
|
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
|
turning green when the `statement_balance` check outcome is "pass". Deliberate, to reduce
|
||||||
|
|
|
||||||
|
|
@ -35,7 +35,7 @@ RUN pip install --no-cache-dir -r requirements.txt
|
||||||
COPY backend/ backend/
|
COPY backend/ backend/
|
||||||
COPY --from=frontend-build /frontend/dist frontend/dist
|
COPY --from=frontend-build /frontend/dist frontend/dist
|
||||||
|
|
||||||
RUN mkdir -p /app/uploads /app/outputs
|
RUN mkdir -p /app/uploads
|
||||||
|
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -57,6 +57,5 @@ app = create_app()
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
os.makedirs(dependencies.UPLOAD_FOLDER, exist_ok=True)
|
os.makedirs(dependencies.UPLOAD_FOLDER, exist_ok=True)
|
||||||
os.makedirs(dependencies.OUTPUT_FOLDER, exist_ok=True)
|
|
||||||
port = int(os.environ.get("PORT", 8080))
|
port = int(os.environ.get("PORT", 8080))
|
||||||
app.run(host="0.0.0.0", port=port, debug=False, threaded=True)
|
app.run(host="0.0.0.0", port=port, debug=False, threaded=True)
|
||||||
|
|
|
||||||
|
|
@ -7,5 +7,4 @@ import os
|
||||||
|
|
||||||
DOCLING_URL = os.environ.get("DOCLING_URL", "http://localhost:5001")
|
DOCLING_URL = os.environ.get("DOCLING_URL", "http://localhost:5001")
|
||||||
UPLOAD_FOLDER = os.environ.get("UPLOAD_FOLDER", "/app/uploads")
|
UPLOAD_FOLDER = os.environ.get("UPLOAD_FOLDER", "/app/uploads")
|
||||||
OUTPUT_FOLDER = os.environ.get("OUTPUT_FOLDER", "/app/outputs")
|
|
||||||
MAX_CONTENT_LENGTH = 50 * 1024 * 1024
|
MAX_CONTENT_LENGTH = 50 * 1024 * 1024
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
# All local filesystem data access: saving an upload, removing it after
|
# Local filesystem access for an uploaded statement - saving it for the
|
||||||
# processing, writing an Excel workbook, resolving an output file's path.
|
# duration of processing, removing it once done. Generated Excel exports
|
||||||
# No business logic - callers decide what to save and when; this just
|
# no longer touch disk at all (see routes/extraction.py's /api/export -
|
||||||
# does the I/O.
|
# served from an in-memory buffer) or this repository - the frontend
|
||||||
|
# persists them straight to PocketBase/R2 instead (documentsService.js's
|
||||||
|
# saveExportFile), so there's nothing on the VPS's own disk to clean up.
|
||||||
import os
|
import os
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
|
|
@ -31,29 +33,5 @@ def remove_upload(path):
|
||||||
|
|
||||||
|
|
||||||
def new_output_filename():
|
def new_output_filename():
|
||||||
"""A fresh, collision-safe filename for a generated Excel export."""
|
"""A fresh, collision-safe filename for a generated Excel export - just a name, no disk I/O."""
|
||||||
return f"Statement_Extraction_{uuid.uuid4().hex[:8]}.xlsx"
|
return f"Statement_Extraction_{uuid.uuid4().hex[:8]}.xlsx"
|
||||||
|
|
||||||
|
|
||||||
def save_workbook(workbook, output_folder, filename):
|
|
||||||
"""
|
|
||||||
Writes an openpyxl Workbook to disk.
|
|
||||||
|
|
||||||
Data flow:
|
|
||||||
workbook (openpyxl.Workbook) - the built workbook (see
|
|
||||||
excel_service.build_workbook)
|
|
||||||
output_folder (str)
|
|
||||||
filename (str)
|
|
||||||
returns (str) - the full saved path
|
|
||||||
"""
|
|
||||||
path = os.path.join(output_folder, filename)
|
|
||||||
workbook.save(path)
|
|
||||||
return path
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_output_path(output_folder, filename):
|
|
||||||
"""Full path for a previously-saved output file, sanitized against
|
|
||||||
path traversal - or None if it doesn't exist."""
|
|
||||||
safe = secure_filename(filename)
|
|
||||||
path = os.path.join(output_folder, safe)
|
|
||||||
return path if os.path.exists(path) else None
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,6 @@
|
||||||
# HTTP routes for statement extraction, recheck, and export - request in, call services, response out.
|
# HTTP routes for statement extraction, recheck, and export - request in, call services, response out.
|
||||||
|
import io
|
||||||
|
|
||||||
from flask import Blueprint, request, jsonify, send_file
|
from flask import Blueprint, request, jsonify, send_file
|
||||||
|
|
||||||
import dependencies
|
import dependencies
|
||||||
|
|
@ -21,8 +23,14 @@ def process():
|
||||||
-> extraction_schema.parse_process_request (validate)
|
-> extraction_schema.parse_process_request (validate)
|
||||||
-> file_repository.save_upload (write to disk)
|
-> file_repository.save_upload (write to disk)
|
||||||
-> pipeline_service.run (extract + check)
|
-> pipeline_service.run (extract + check)
|
||||||
-> excel_service.build_workbook + file_repository.save_workbook (export)
|
-> JSON response: the pipeline result plus title
|
||||||
-> JSON response: the pipeline result plus filename/title
|
|
||||||
|
No Excel workbook is built here - nothing ever downloaded the one this
|
||||||
|
route used to generate-and-save on every extraction (confirmed: no
|
||||||
|
frontend call ever hit the old /api/download/<filename> route), so it
|
||||||
|
was pure wasted work and wasted disk space. The actual Excel a user
|
||||||
|
gets comes from /api/export, triggered deliberately by Download
|
||||||
|
Excel/All - see that route below.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
file_storage, opening_balance, closing_balance = extraction_schema.parse_process_request(request)
|
file_storage, opening_balance, closing_balance = extraction_schema.parse_process_request(request)
|
||||||
|
|
@ -39,20 +47,7 @@ def process():
|
||||||
finally:
|
finally:
|
||||||
file_repository.remove_upload(path)
|
file_repository.remove_upload(path)
|
||||||
|
|
||||||
workbook = excel_service.build_workbook(result, title=file_storage.filename)
|
return jsonify({**result, "title": file_storage.filename}), 200
|
||||||
fname = file_repository.new_output_filename()
|
|
||||||
file_repository.save_workbook(workbook, dependencies.OUTPUT_FOLDER, fname)
|
|
||||||
|
|
||||||
return jsonify({**result, "filename": fname, "title": file_storage.filename}), 200
|
|
||||||
|
|
||||||
|
|
||||||
@extraction_bp.route("/download/<filename>")
|
|
||||||
def download(filename):
|
|
||||||
"""Downloads a previously-exported Excel file by name."""
|
|
||||||
path = file_repository.resolve_output_path(dependencies.OUTPUT_FOLDER, filename)
|
|
||||||
if path is None:
|
|
||||||
return jsonify({"error": "File not found"}), 404
|
|
||||||
return send_file(path, as_attachment=True)
|
|
||||||
|
|
||||||
|
|
||||||
@extraction_bp.route("/recheck", methods=["POST"])
|
@extraction_bp.route("/recheck", methods=["POST"])
|
||||||
|
|
@ -81,7 +76,7 @@ def recheck():
|
||||||
def export():
|
def export():
|
||||||
"""
|
"""
|
||||||
Re-runs the checks against the (possibly edited) transaction list,
|
Re-runs the checks against the (possibly edited) transaction list,
|
||||||
same as /api/recheck, then writes and returns the Excel workbook in
|
same as /api/recheck, then builds and returns the Excel workbook in
|
||||||
one round trip - so a downloaded file always reflects whatever is
|
one round trip - so a downloaded file always reflects whatever is
|
||||||
currently on screen, edits included, rather than the original
|
currently on screen, edits included, rather than the original
|
||||||
extraction from before any correction.
|
extraction from before any correction.
|
||||||
|
|
@ -91,8 +86,12 @@ def export():
|
||||||
narrative_direction?, brought_forward_balance?, title?)
|
narrative_direction?, brought_forward_balance?, title?)
|
||||||
-> extraction_schema.parse_export_request (validate)
|
-> extraction_schema.parse_export_request (validate)
|
||||||
-> pipeline_service.recheck (re-run checks on the edited data)
|
-> pipeline_service.recheck (re-run checks on the edited data)
|
||||||
-> excel_service.build_workbook + file_repository.save_workbook
|
-> excel_service.build_workbook (in memory, no disk write)
|
||||||
-> file response: the .xlsx attachment
|
-> file response: the .xlsx attachment, streamed straight from that
|
||||||
|
in-memory buffer. The frontend is the one that persists this
|
||||||
|
file long-term (documentsService.saveExportFile, PocketBase/R2 -
|
||||||
|
see CLAUDE.md), not this route - Flask never writes it to disk
|
||||||
|
at all, so there's nothing here to ever clean up.
|
||||||
"""
|
"""
|
||||||
data = extraction_schema.parse_export_request(request.get_json(silent=True))
|
data = extraction_schema.parse_export_request(request.get_json(silent=True))
|
||||||
check_results = pipeline_service.recheck(
|
check_results = pipeline_service.recheck(
|
||||||
|
|
@ -108,6 +107,11 @@ def export():
|
||||||
**check_results,
|
**check_results,
|
||||||
}
|
}
|
||||||
workbook = excel_service.build_workbook(result, title=data["title"])
|
workbook = excel_service.build_workbook(result, title=data["title"])
|
||||||
|
buffer = io.BytesIO()
|
||||||
|
workbook.save(buffer)
|
||||||
|
buffer.seek(0)
|
||||||
fname = file_repository.new_output_filename()
|
fname = file_repository.new_output_filename()
|
||||||
path = file_repository.save_workbook(workbook, dependencies.OUTPUT_FOLDER, fname)
|
return send_file(
|
||||||
return send_file(path, as_attachment=True, download_name=fname)
|
buffer, as_attachment=True, download_name=fname,
|
||||||
|
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
# Builds the Transactions + Summary Excel workbook - the actual disk write is file_repository's job.
|
# Builds the Transactions + Summary Excel workbook, entirely in memory - callers decide where it ends up (an in-memory buffer streamed straight to the client, see routes/extraction.py's /api/export).
|
||||||
import openpyxl
|
import openpyxl
|
||||||
from openpyxl.styles import Font
|
from openpyxl.styles import Font
|
||||||
|
|
||||||
|
|
@ -40,8 +40,7 @@ def _flagged_row_indexes(result):
|
||||||
|
|
||||||
def build_workbook(result, title="Statement Extraction"):
|
def build_workbook(result, title="Statement Extraction"):
|
||||||
"""
|
"""
|
||||||
Builds the Transactions + Summary workbook in memory - does not touch
|
Builds the Transactions + Summary workbook in memory - never touches disk itself.
|
||||||
disk (see file_repository.save_workbook for that).
|
|
||||||
|
|
||||||
Data flow:
|
Data flow:
|
||||||
result (dict) - a pipeline_service.run()/recheck() result:
|
result (dict) - a pipeline_service.run()/recheck() result:
|
||||||
|
|
|
||||||
|
|
@ -29,13 +29,11 @@ services:
|
||||||
environment:
|
environment:
|
||||||
- DOCLING_URL=http://docling:5001
|
- DOCLING_URL=http://docling:5001
|
||||||
- UPLOAD_FOLDER=/app/uploads
|
- UPLOAD_FOLDER=/app/uploads
|
||||||
- OUTPUT_FOLDER=/app/outputs
|
|
||||||
depends_on:
|
depends_on:
|
||||||
docling:
|
docling:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
volumes:
|
volumes:
|
||||||
- ./uploads:/app/uploads
|
- ./uploads:/app/uploads
|
||||||
- ./outputs:/app/outputs
|
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
pb_data:
|
pb_data:
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ import { ref, computed } from 'vue'
|
||||||
import { useExtractionStore } from '../stores/extractionStore'
|
import { useExtractionStore } from '../stores/extractionStore'
|
||||||
import { useUiStore } from '../stores/uiStore'
|
import { useUiStore } from '../stores/uiStore'
|
||||||
import * as extractionService from '../services/extractionService'
|
import * as extractionService from '../services/extractionService'
|
||||||
|
import * as documentsService from '../services/documentsService'
|
||||||
import * as formatService from '../services/formatService'
|
import * as formatService from '../services/formatService'
|
||||||
|
|
||||||
const extractionStore = useExtractionStore()
|
const extractionStore = useExtractionStore()
|
||||||
|
|
@ -27,17 +28,34 @@ const downloadingAll = ref(false)
|
||||||
// done, so this only lights up once there's nothing left running.
|
// done, so this only lights up once there's nothing left running.
|
||||||
const showDownloadAll = computed(() => !extractionStore.isBatchProcessing && extractionStore.documents.length > 1)
|
const showDownloadAll = computed(() => !extractionStore.isBatchProcessing && extractionStore.documents.length > 1)
|
||||||
|
|
||||||
/** Triggers one browser save for a given {result, openingBalance, closingBalance, title}. */
|
/**
|
||||||
async function downloadOne({ result: r, openingBalance, closingBalance }) {
|
* Triggers one browser save for a given {pbId, result, openingBalance,
|
||||||
|
* closingBalance}, then best-effort persists the SAME blob to R2 (via
|
||||||
|
* PocketBase's own file storage - documentsService.saveExportFile,
|
||||||
|
* overwriting whatever export was there before, see that function's own
|
||||||
|
* comment for why only the latest). The Blob is immutable and reusable,
|
||||||
|
* so the one fetch serves both the browser download and the R2 upload -
|
||||||
|
* no second request. A failure saving to R2 is reported but never
|
||||||
|
* blocks or undoes the download the user actually asked for.
|
||||||
|
*/
|
||||||
|
async function downloadOne({ pbId, result: r, openingBalance, closingBalance }) {
|
||||||
const blob = await extractionService.exportWorkbook(r, openingBalance, closingBalance)
|
const blob = await extractionService.exportWorkbook(r, openingBalance, closingBalance)
|
||||||
|
const fileName = (r.title || 'Statement_Extraction').replace(/\.pdf$/i, '') + '.xlsx'
|
||||||
|
|
||||||
const url = URL.createObjectURL(blob)
|
const url = URL.createObjectURL(blob)
|
||||||
const a = document.createElement('a')
|
const a = document.createElement('a')
|
||||||
a.href = url
|
a.href = url
|
||||||
a.download = (r.title || 'Statement_Extraction').replace(/\.pdf$/i, '') + '.xlsx'
|
a.download = fileName
|
||||||
document.body.appendChild(a)
|
document.body.appendChild(a)
|
||||||
a.click()
|
a.click()
|
||||||
a.remove()
|
a.remove()
|
||||||
URL.revokeObjectURL(url)
|
URL.revokeObjectURL(url)
|
||||||
|
|
||||||
|
try {
|
||||||
|
await documentsService.saveExportFile(pbId, blob, fileName)
|
||||||
|
} catch (e) {
|
||||||
|
extractionStore.setError('Downloaded, but could not save a copy for later: ' + e.message)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -54,6 +72,7 @@ async function handleDownload() {
|
||||||
extractionStore.clearError()
|
extractionStore.clearError()
|
||||||
try {
|
try {
|
||||||
await downloadOne({
|
await downloadOne({
|
||||||
|
pbId: extractionStore.activeDocument?.pbId,
|
||||||
result: result.value,
|
result: result.value,
|
||||||
openingBalance: extractionStore.effectiveOpeningBalance,
|
openingBalance: extractionStore.effectiveOpeningBalance,
|
||||||
closingBalance: extractionStore.effectiveClosingBalance,
|
closingBalance: extractionStore.effectiveClosingBalance,
|
||||||
|
|
@ -80,6 +99,7 @@ async function handleDownloadAll() {
|
||||||
for (const doc of extractionStore.documents) {
|
for (const doc of extractionStore.documents) {
|
||||||
try {
|
try {
|
||||||
await downloadOne({
|
await downloadOne({
|
||||||
|
pbId: doc.pbId,
|
||||||
result: doc.result,
|
result: doc.result,
|
||||||
openingBalance: extractionService.effectiveBalance(
|
openingBalance: extractionService.effectiveBalance(
|
||||||
formatService.parseNum(doc.openingBalanceInput), doc.result?.opening_balance,
|
formatService.parseNum(doc.openingBalanceInput), doc.result?.opening_balance,
|
||||||
|
|
|
||||||
|
|
@ -64,6 +64,22 @@ export async function deleteDocument(id) {
|
||||||
return pb.collection('documents').delete(id)
|
return pb.collection('documents').delete(id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persists a generated Excel export to R2 (via PocketBase's own file
|
||||||
|
* storage, same as sourceFile) - overwrites whatever export file was
|
||||||
|
* there before, deliberately keeping only the LATEST one, not a
|
||||||
|
* history. A real retention policy (how long to keep exports - or
|
||||||
|
* anything else - at all) hasn't been decided yet; this is the interim
|
||||||
|
* shape until it is. Best-effort from the caller's side (see
|
||||||
|
* ResultCard.vue) - a failure here shouldn't block the browser download
|
||||||
|
* the user actually asked for.
|
||||||
|
*/
|
||||||
|
export async function saveExportFile(id, blob, fileName) {
|
||||||
|
const formData = new FormData()
|
||||||
|
formData.append('exportFile', blob, fileName)
|
||||||
|
return pb.collection('documents').update(id, formData)
|
||||||
|
}
|
||||||
|
|
||||||
/** A servable URL for a document record's original source file, or null if none was uploaded. */
|
/** A servable URL for a document record's original source file, or null if none was uploaded. */
|
||||||
export function sourceFileUrl(record) {
|
export function sourceFileUrl(record) {
|
||||||
return record.sourceFile ? pb.files.getURL(record, record.sourceFile) : null
|
return record.sourceFile ? pb.files.getURL(record, record.sourceFile) : null
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,23 @@
|
||||||
|
/// <reference path="../pb_data/types.d.ts" />
|
||||||
|
|
||||||
|
/**
|
||||||
|
* exportFile holds the latest generated Excel workbook for a document -
|
||||||
|
* stored in R2 same as sourceFile, once configure-secrets.sh has run.
|
||||||
|
* Deliberately the LATEST one only, overwritten on every new export, not
|
||||||
|
* a historical list - re-exporting after an edit already produces an
|
||||||
|
* updated file (the frontend's own "a downloaded file always reflects
|
||||||
|
* whatever is on screen" behavior), so keeping every past version would
|
||||||
|
* just be the same unbounded-growth problem this was meant to solve,
|
||||||
|
* moved from the VPS to R2 instead of actually fixed. A real retention
|
||||||
|
* policy (how long an export - or anything else - should be kept) is a
|
||||||
|
* separate, not-yet-made decision; this is the interim shape until then.
|
||||||
|
*/
|
||||||
|
migrate((app) => {
|
||||||
|
let documents = app.findCollectionByNameOrId('documents')
|
||||||
|
documents.fields.add(new Field({ type: 'file', name: 'exportFile', maxSelect: 1 }))
|
||||||
|
app.save(documents)
|
||||||
|
}, (app) => {
|
||||||
|
let documents = app.findCollectionByNameOrId('documents')
|
||||||
|
documents.fields.removeByName('exportFile')
|
||||||
|
app.save(documents)
|
||||||
|
})
|
||||||
Loading…
Reference in New Issue