import os, uuid from datetime import datetime from flask import Blueprint, request, jsonify, send_file, render_template, current_app from werkzeug.utils import secure_filename import pandas as pd from .logic import ( classify_trial_balance_file, full_file_balance, build_report_workbook, ) financial_reports_bp = Blueprint("financial_reports", __name__, url_prefix="/financial-reports") BALANCE_TOLERANCE = 0.01 @financial_reports_bp.route("/") def index(): return render_template("financial_reports/index.html") @financial_reports_bp.route("/api/process", methods=["POST"]) def api_process(): files = [ f for key, f in request.files.items() if key.startswith("trial_balance_file") and f.filename ] if not files: return jsonify({"error": "No files uploaded"}), 400 by_role = {} unrecognized = [] for f in files: path = os.path.join( current_app.config["UPLOAD_FOLDER"], f"{uuid.uuid4()}_{secure_filename(f.filename)}", ) f.save(path) try: df = pd.read_excel(path) except Exception as e: return jsonify({"error": f"Could not read {f.filename}: {e}"}), 400 role = classify_trial_balance_file(df) if role is None: unrecognized.append(f.filename) continue if role in by_role: return jsonify({ "error": f"Got two {role} trial balance files " f"({by_role[role]['name']}, {f.filename}) — upload exactly one of each.", }), 400 by_role[role] = {"df": df, "name": f.filename} missing = [r for r in ("revenue", "expense") if r not in by_role] if missing: parts = [] if "revenue" in missing: parts.append("a revenue trial balance (needs a 'Revenue Category' column)") if "expense" in missing: parts.append("an expense trial balance (needs a 'Spend Category' column)") msg = "Upload " + " and ".join(parts) + " to generate a report." if unrecognized: msg += f" Could not recognize: {', '.join(unrecognized)}." return jsonify({"error": msg}), 400 for role in ("revenue", "expense"): bal = full_file_balance(by_role[role]["df"]) if abs(bal) > BALANCE_TOLERANCE: return jsonify({ "error": f"The {role} trial balance ({by_role[role]['name']}) doesn't sum to " f"zero (off by {bal:,.2f}) — this doesn't look like a complete trial " f"balance export. Re-export and try again.", }), 400 sections = { "category_summary": request.form.get("include_category_summary", "true") == "true", "balance_sheet": request.form.get("include_balance_sheet", "true") == "true", } if not sections["category_summary"] and not sections["balance_sheet"]: return jsonify({"error": "Include at least one report section"}), 400 report_date = request.form.get("report_date") or datetime.today().strftime("%Y-%m-%d") title = request.form.get("title") or "Planeterra International Foundation (Group Consolidated)" use_cents = request.form.get("use_cents", "false") == "true" fname = f"Financial_Report_{report_date}.xlsx" fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], fname) try: summary = build_report_workbook( by_role["revenue"]["df"], by_role["expense"]["df"], fpath, sections, report_date, title, use_cents=use_cents, ) except ValueError as e: return jsonify({"error": str(e)}), 400 return jsonify({"status": "ok", "filename": fname, **summary}), 200 @financial_reports_bp.route("/api/download/") 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)