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_trial_balance, build_donor_workbook donor_report_bp = Blueprint("donor_report", __name__, url_prefix="/donor-report") @donor_report_bp.route("/") def index(): return render_template("donor_report/index.html") @donor_report_bp.route("/api/process", methods=["POST"]) def api_process(): if "trial_balance_file" not in request.files: return jsonify({"error": "No trial balance file uploaded"}), 400 tb_file = request.files["trial_balance_file"] tb_path = os.path.join( current_app.config["UPLOAD_FOLDER"], f"{uuid.uuid4()}_{secure_filename(tb_file.filename)}", ) tb_file.save(tb_path) try: tb_df = pd.read_excel(tb_path) except Exception as e: return jsonify({"error": f"Could not read trial balance file: {e}"}), 400 required_cols = {"Ledger Account", "Project", "Revenue Category", "Planeterra Foundation"} missing = required_cols - set(tb_df.columns) if missing: return jsonify({"error": f"Missing expected column(s): {', '.join(sorted(missing))}"}), 400 grouped = process_trial_balance(tb_df) if grouped.empty: return jsonify({"error": "No revenue (43000/48000) rows found in this file"}), 400 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, grand_total = build_donor_workbook(grouped, fpath) return jsonify({ "status": "ok", "filename": fname, "donors": donor_count, "total_revenue": grand_total, "donor_names": sorted(grouped["donor"].unique().tolist()), }), 200 @donor_report_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)