bettersight-statement-extra.../docs/bank_statement_categorizer/routes.py

138 lines
5.0 KiB
Python

import os, uuid
from flask import Blueprint, request, jsonify, send_file, render_template, current_app
from werkzeug.utils import secure_filename
from .logic import (
parse_rbc_statement,
build_categorized_summary,
write_output_workbook,
list_rules,
upsert_rules,
delete_rule,
)
bank_statement_categorizer_bp = Blueprint(
"bank_statement_categorizer", __name__, url_prefix="/bank-statement-categorizer"
)
# Parsed transactions for a run paused awaiting unmapped-description
# review, keyed by a one-time token - same explicit single-job/single-
# user shortcut as every other tool's PENDING_RUNS in this app (see
# app/tools/financial_reports/routes.py), not safe for concurrent runs,
# not meant to be. Avoids re-parsing the PDF on every round of mapping.
PENDING_RUNS = {}
def _check_and_respond(parsed, title):
rules = list_rules()
summary = build_categorized_summary(parsed, rules)
if summary["unmapped"]:
token = str(uuid.uuid4())
PENDING_RUNS[token] = {"parsed": parsed, "title": title}
return jsonify({
"status": "needs_review",
"token": token,
"unmapped": summary["unmapped"],
}), 200
fname = f"Bank_Statement_Categorized_{uuid.uuid4().hex[:8]}.xlsx"
fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], fname)
write_output_workbook(summary, fpath, title=title)
calculated_closing_balance = round(summary["opening_balance"] + summary["credit_total"] + summary["debit_total"], 2)
return jsonify({
"status": "ok",
"filename": fname,
"reconciled": summary["reconciled"],
"opening_balance": summary["opening_balance"],
"closing_balance": summary["closing_balance"],
"calculated_closing_balance": calculated_closing_balance,
"credit_total": summary["credit_total"],
"debit_total": summary["debit_total"],
"rows": summary["rows"],
}), 200
@bank_statement_categorizer_bp.route("/")
def index():
return render_template("bank_statement_categorizer/index.html")
@bank_statement_categorizer_bp.route("/api/process", methods=["POST"])
def api_process():
f = request.files.get("statement_file")
if not f or not f.filename:
return jsonify({"error": "Upload a bank statement PDF"}), 400
path = os.path.join(current_app.config["UPLOAD_FOLDER"], f"{uuid.uuid4()}_{secure_filename(f.filename)}")
f.save(path)
try:
parsed = parse_rbc_statement(path)
except ValueError as e:
return jsonify({"error": str(e)}), 400
except Exception as e:
return jsonify({"error": f"Could not parse {f.filename}: {e}"}), 400
finally:
os.remove(path)
title = request.form.get("title") or "Bank Statement Categorizer"
return _check_and_respond(parsed, title)
@bank_statement_categorizer_bp.route("/api/confirm-mappings", methods=["POST"])
def api_confirm_mappings():
data = request.get_json(silent=True) or {}
token = data.get("token")
decisions = data.get("decisions", [])
pending = PENDING_RUNS.get(token)
if pending is None:
return jsonify({
"error": "This review session has expired or wasn't found - please re-upload and try again.",
}), 400
for d in decisions:
pattern = str(d.get("pattern", "")).strip()
target = str(d.get("accounting_description", "")).strip()
if not pattern or not target:
return jsonify({"error": "Every mapped description needs both a pattern and an accounting description."}), 400
del PENDING_RUNS[token]
entries = [(d["pattern"].strip(), d["accounting_description"].strip()) for d in decisions]
if entries:
upsert_rules(entries)
return _check_and_respond(pending["parsed"], pending["title"])
@bank_statement_categorizer_bp.route("/api/rules", methods=["GET", "POST"])
def api_rules():
if request.method == "GET":
return jsonify({"rules": list_rules()}), 200
data = request.get_json(silent=True) or {}
pattern = str(data.get("pattern", "")).strip()
target = str(data.get("accounting_description", "")).strip()
if not pattern or not target:
return jsonify({"error": "pattern and accounting_description are required"}), 400
upsert_rules([(pattern, target)])
return jsonify({"status": "ok", "rules": list_rules()}), 200
@bank_statement_categorizer_bp.route("/api/rules/delete", methods=["POST"])
def api_delete_rule():
data = request.get_json(silent=True) or {}
pattern = str(data.get("pattern", "")).strip()
if not pattern:
return jsonify({"error": "pattern is required"}), 400
delete_rule(pattern)
return jsonify({"status": "ok", "rules": list_rules()}), 200
@bank_statement_categorizer_bp.route("/api/download/<filename>")
def api_download(filename):
safe = secure_filename(filename)
fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], safe)
if not os.path.exists(fpath):
return jsonify({"error": "File not found"}), 404
return send_file(fpath, as_attachment=True)