bettersight-statement-extra.../backend/routes/extraction.py

295 lines
13 KiB
Python

# HTTP routes for statement extraction, recheck, and export - request in, call services, response out.
import io
from flask import Blueprint, request, jsonify, send_file
import dependencies
from schemas import extraction_schema
from schemas.extraction_schema import ValidationError
from services import pipeline_service
from services import excel_service
from services import qbo_service
from services import xero_csv_service
from services import csv_service
from services.extraction_service import LayoutMappingRequired, ValueRecognitionRequired
from repositories import file_repository
extraction_bp = Blueprint("extraction", __name__, url_prefix="/api")
@extraction_bp.route("/process", methods=["POST"])
def process():
"""
Extracts and verifies a freshly-uploaded statement.
Data flow:
request (multipart form: statement_file, opening_balance?, closing_balance?,
forced_mapping? - layout mapper work, see extraction_schema)
-> extraction_schema.parse_process_request (validate)
-> file_repository.save_upload (write to disk)
-> pipeline_service.run (extract + check)
-> JSON response: the pipeline result plus 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:
file_storage, opening_balance, closing_balance, forced_mapping = extraction_schema.parse_process_request(request)
except ValidationError as e:
return jsonify({"error": str(e)}), 400
path = file_repository.save_upload(file_storage, dependencies.UPLOAD_FOLDER)
try:
result = pipeline_service.run(path, dependencies.DOCLING_URL, opening_balance, closing_balance, forced_mapping)
except LayoutMappingRequired as e:
# Caught ahead of the generic ValueError handler below (this IS
# a ValueError subclass) - the layout mapper's own entry point:
# tier 1 (keyword detector) and tier 2 (layout_quirks) both
# failed on every page, so the frontend needs the fingerprint to
# look up a stored mapping or open the manual mapping screen,
# not just a dead-end error message.
return jsonify({
"error": str(e), "needs_mapping": True,
"fingerprint": e.fingerprint, "fingerprintHash": e.fingerprint_hash,
}), 422
except ValueRecognitionRequired as e:
# Also caught ahead of the generic ValueError handler (also a
# ValueError subclass) - a narrower, later-stage sibling of
# LayoutMappingRequired above: the column POSITIONS were found
# fine, only the raw VALUES in them didn't parse. Carries one
# representative example row so the frontend can ask for a
# single correction per field instead of full region-drawing.
return jsonify({
"error": str(e), "needs_value_confirmation": True,
"fingerprint": e.fingerprint, "fingerprintHash": e.fingerprint_hash,
"candidateRow": e.candidate_row, "fieldOrder": e.field_order,
}), 422
except ValueError as e:
return jsonify({"error": str(e)}), 400
except Exception as e:
return jsonify({"error": f"Could not parse {file_storage.filename}: {e}"}), 400
finally:
file_repository.remove_upload(path)
return jsonify({**result, "title": file_storage.filename}), 200
@extraction_bp.route("/recheck", methods=["POST"])
def recheck():
"""
Re-runs the checks against a (possibly user-edited) transaction list
without re-extracting anything - used for live status/flag updates in
the UI right after an edit. See pipeline_service.recheck().
Data flow:
request (JSON: transactions, page_reports, period?, balances?, narrative_direction?)
-> extraction_schema.parse_recheck_request (validate)
-> pipeline_service.recheck (re-run checks only)
-> JSON response: {status, checks}
"""
data = extraction_schema.parse_recheck_request(request.get_json(silent=True))
check_results = pipeline_service.recheck(
data["transactions"], data["page_reports"], data["period"],
data["opening_balance"], data["closing_balance"],
narrative_direction=data["narrative_direction"],
)
return jsonify(check_results), 200
@extraction_bp.route("/export", methods=["POST"])
def export():
"""
Re-runs the checks against the (possibly edited) transaction list,
same as /api/recheck, then builds and returns the Excel workbook in
one round trip - so a downloaded file always reflects whatever is
currently on screen, edits included, rather than the original
extraction from before any correction.
Data flow:
request (JSON: transactions, page_reports, period?, balances?,
narrative_direction?, brought_forward_balance?, title?)
-> extraction_schema.parse_export_request (validate)
-> pipeline_service.recheck (re-run checks on the edited data)
-> excel_service.build_workbook (in memory, no disk write)
-> 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))
check_results = pipeline_service.recheck(
data["transactions"], data["page_reports"], data["period"],
data["opening_balance"], data["closing_balance"],
narrative_direction=data["narrative_direction"],
)
result = {
"transactions": data["transactions"],
"page_reports": data["page_reports"],
"period": data["period"],
"brought_forward_balance": data["brought_forward_balance"],
"edit_log": data["edit_log"],
"categorization": data["categorization"],
**check_results,
}
workbook = excel_service.build_workbook(result, title=data["title"])
buffer = io.BytesIO()
workbook.save(buffer)
buffer.seek(0)
fname = file_repository.new_output_filename()
return send_file(
buffer, as_attachment=True, download_name=fname,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
@extraction_bp.route("/export/qbo", methods=["POST"])
def export_qbo():
"""
QuickBooks (Web Connect .qbo)-compatible export - the accounting-
software integration half of this app's own exports, alongside the
existing Excel one above (see CLAUDE.md's ".qbo export" entry for
the full design record, including why this was renamed/corrected
from an earlier "QFX" route that never actually wrote the one field,
<INTU.BID>, that distinguishes an Intuit-variant OFX file from plain
generic OFX). Same recheck-then-build shape as /api/export - a
downloaded QBO always reflects whatever's currently on screen, edits
included - differing only in which builder runs at the end and in
requiring one extra field (`bank_account`) that export doesn't need.
Data flow:
request (JSON: parse_export_request's own fields, plus a required
bank_account: {bankId, accountId, accountType})
-> extraction_schema.parse_qbo_export_request (validate)
-> pipeline_service.recheck (re-run checks on the edited data)
-> qbo_service.build_qbo (in memory, no disk write)
-> file response: the .qbo attachment, streamed from an in-memory
text buffer - the frontend persists a copy to PocketBase/R2
the same way it already does for the Excel export
(documentsService.saveExportFile), not this route.
Unlike every other schema function in this file,
parse_qbo_export_request can genuinely raise ValidationError (a
missing/malformed bank_account) - confirmed directly, not assumed,
that /api/process is the only other route here that actually needs
this try/except today (parse_export_request/parse_recheck_request
have no required-field checks of their own, so ValidationError is
never actually raised on those paths) - caught here the same way
/api/process already does, rather than falling through to a bare
500 with no useful message for the frontend to show.
"""
try:
data = extraction_schema.parse_qbo_export_request(request.get_json(silent=True))
except ValidationError as e:
return jsonify({"error": str(e)}), 400
check_results = pipeline_service.recheck(
data["transactions"], data["page_reports"], data["period"],
data["opening_balance"], data["closing_balance"],
narrative_direction=data["narrative_direction"],
)
result = {
"transactions": data["transactions"],
"page_reports": data["page_reports"],
"period": data["period"],
"brought_forward_balance": data["brought_forward_balance"],
**check_results,
}
qbo_text = qbo_service.build_qbo(result, data["bank_account"], title=data["title"])
buffer = io.BytesIO(qbo_text.encode("utf-8"))
fname = file_repository.new_qbo_output_filename()
return send_file(
buffer, as_attachment=True, download_name=fname,
mimetype="application/vnd.intu.qbo",
)
@extraction_bp.route("/export/xero-csv", methods=["POST"])
def export_xero_csv():
"""
Xero-compatible statement-import CSV export - the second accounting-
software integration this app supports, alongside QBO's own QFX
above (see CLAUDE.md's "Xero export" entry for the full design
record). Same recheck-then-build shape as /api/export/qfx, but
genuinely simpler: Xero's own CSV import has no embedded bank-
account block at all (that's chosen inside Xero's own UI at import
time), so this needs no `bank_account` field and therefore no
bankAccountProfiles lookup on the frontend side either - confirmed
directly from Xero's own documented import requirements before
building this, not assumed to mirror QFX's own shape.
Data flow:
request (JSON: parse_export_request's own fields - no extra
required field, unlike /api/export/qfx)
-> extraction_schema.parse_export_request (validate - same
schema /api/export already uses)
-> pipeline_service.recheck (re-run checks on the edited data)
-> xero_csv_service.build_csv (in memory, no disk write)
-> file response: the .csv attachment, streamed from an in-memory
text buffer.
"""
data = extraction_schema.parse_export_request(request.get_json(silent=True))
check_results = pipeline_service.recheck(
data["transactions"], data["page_reports"], data["period"],
data["opening_balance"], data["closing_balance"],
narrative_direction=data["narrative_direction"],
)
result = {
"transactions": data["transactions"],
"page_reports": data["page_reports"],
"period": data["period"],
"brought_forward_balance": data["brought_forward_balance"],
**check_results,
}
csv_text = xero_csv_service.build_csv(result, title=data["title"])
buffer = io.BytesIO(csv_text.encode("utf-8"))
fname = file_repository.new_xero_csv_output_filename()
return send_file(
buffer, as_attachment=True, download_name=fname,
mimetype="text/csv",
)
@extraction_bp.route("/export/csv", methods=["POST"])
def export_csv():
"""
A plain, generic transactions CSV export - the same Date/Description/
Amount/Balance/Status/Check-flags data excel_service.py's own
Transactions sheet writes, as one flat CSV file (see csv_service.py's
own docstring for how this differs from xero-csv's own import-
specific shape). Same recheck-then-build shape as every other export
route here, no extra required field (reuses parse_export_request
as-is, same as /api/export/xero-csv).
Data flow:
request (JSON: parse_export_request's own fields)
-> extraction_schema.parse_export_request (validate)
-> pipeline_service.recheck (re-run checks on the edited data)
-> csv_service.build_csv (in memory, no disk write)
-> file response: the .csv attachment, streamed from an in-memory
text buffer.
"""
data = extraction_schema.parse_export_request(request.get_json(silent=True))
check_results = pipeline_service.recheck(
data["transactions"], data["page_reports"], data["period"],
data["opening_balance"], data["closing_balance"],
narrative_direction=data["narrative_direction"],
)
result = {
"transactions": data["transactions"],
"page_reports": data["page_reports"],
"period": data["period"],
"brought_forward_balance": data["brought_forward_balance"],
**check_results,
}
csv_text = csv_service.build_csv(result)
buffer = io.BytesIO(csv_text.encode("utf-8"))
fname = file_repository.new_plain_csv_output_filename()
return send_file(
buffer, as_attachment=True, download_name=fname,
mimetype="text/csv",
)