# 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 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?) -> 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/ 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 = 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) 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"], **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", )