equals-wd-card-expense-proc.../app/tools/donor_report/routes.py

180 lines
6.8 KiB
Python

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 (
process_revenue,
process_expense,
process_revenue_us_only,
process_expense_us_only,
process_revenue_detail,
process_expense_detail,
load_gl_dump,
reconcile_detail_to_trial_balance,
reconcile_gl_by_account,
build_donor_workbook,
full_file_balance,
_load_donor_merge_map,
)
donor_report_bp = Blueprint("donor_report", __name__, url_prefix="/donor-report")
BALANCE_TOLERANCE = 0.01
def _classify_file(df):
cols = set(df.columns)
if {"Ledger Account", "Project", "Planeterra Foundation", "Revenue Category"} <= cols:
return "revenue"
if {"Ledger Account", "Project", "Planeterra Foundation", "Spend Category"} <= cols:
return "expense"
return None
@donor_report_bp.route("/")
def index():
return render_template("donor_report/index.html")
@donor_report_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 = {}
gl_dump = None # {"df": ..., "name": ...} - optional, enables transaction detail
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_file(df)
if role is not None:
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}
continue
# Not a trial balance - see if it's a GL Dump (transaction detail,
# optional) before giving up on it.
gl_df = load_gl_dump(path)
if gl_df is not None:
if gl_dump is not None:
return jsonify({
"error": f"Got two GL Dump files ({gl_dump['name']}, {f.filename}) — "
f"upload at most one.",
}), 400
gl_dump = {"df": gl_df, "name": f.filename}
continue
unrecognized.append(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
merge_map = _load_donor_merge_map()
revenue_grouped = process_revenue(by_role["revenue"]["df"], merge_map)
expense_grouped = process_expense(by_role["expense"]["df"], merge_map)
if revenue_grouped.empty and expense_grouped.empty:
return jsonify({"error": "No revenue or expense rows found in the uploaded files"}), 400
reconciliation = None
account_reconciliation = None
build_kwargs = {}
if gl_dump is not None:
revenue_detail = process_revenue_detail(gl_dump["df"], merge_map)
revenue_us = process_revenue_us_only(by_role["revenue"]["df"], merge_map)
expense_detail = process_expense_detail(gl_dump["df"], merge_map)
expense_us = process_expense_us_only(by_role["expense"]["df"], merge_map)
reconciliation = reconcile_detail_to_trial_balance(
revenue_detail, revenue_us, by_role["revenue"]["df"],
expense_detail, expense_us, by_role["expense"]["df"],
)
# Per-account breakdown (Canada GL vs. Canada TB column) - the
# side-level check above can pass even when two individual
# accounts are each wrong in offsetting directions; this catches
# that by checking every revenue/expense Ledger Account on its own.
account_reconciliation = reconcile_gl_by_account(
gl_dump["df"], by_role["revenue"]["df"], by_role["expense"]["df"],
)
build_kwargs = {
"revenue_detail": revenue_detail, "revenue_us": revenue_us,
"expense_detail": expense_detail, "expense_us": expense_us,
}
today = datetime.today().strftime("%Y-%m-%d")
fname = f"Donor_Revenue_Report_{today}.xlsx"
fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], fname)
donor_count, total_revenue, total_expense = build_donor_workbook(
revenue_grouped, expense_grouped, fpath, **build_kwargs)
surplus_deficit = round(total_revenue - total_expense, 2)
if gl_dump is not None:
donor_names = sorted(
set(build_kwargs["revenue_detail"]["donor"]) | set(build_kwargs["revenue_us"]["donor"]) |
set(build_kwargs["expense_detail"]["donor"]) | set(build_kwargs["expense_us"]["donor"])
)
else:
donor_names = sorted(set(revenue_grouped["donor"]).union(expense_grouped["donor"]))
response = {
"status": "ok",
"filename": fname,
"donors": donor_count,
"total_revenue": total_revenue,
"total_expense": total_expense,
"surplus_deficit": surplus_deficit,
"donor_names": donor_names,
"detail_mode": gl_dump is not None,
}
if reconciliation is not None:
response["reconciliation"] = reconciliation
if account_reconciliation is not None:
response["account_reconciliation"] = account_reconciliation
return jsonify(response), 200
@donor_report_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)