diff --git a/.gitignore b/.gitignore index 5d8f380..2313a66 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,6 @@ __pycache__/ !app/tools/eib/eib_pre_template.xlsx !app/tools/eib/planeterra_equals_cards_transactions_eib_v45.xlsx !app/tools/eib/merchant_lookup.csv +!app/tools/donor_report/report_summary_template.xlsx +!app/tools/donor_report/donor_merge_map.csv .claude/settings.local.json diff --git a/app/main.py b/app/main.py index cefd6ab..73ee788 100644 --- a/app/main.py +++ b/app/main.py @@ -2,6 +2,7 @@ import os from flask import Flask, render_template from tools.eib import eib_bp +from tools.donor_report import donor_report_bp # ── Tool registry ──────────────────────────────────────────────────────────── # Each entry drives one card on the landing page. Add a new tool by @@ -19,6 +20,16 @@ TOOLS = [ "url": "/eib/", "status": "online", }, + { + "name": "Donor Revenue Report", + "tagline": "Trial Balance → Per-Donor Financial Extract", + "description": ( + "Generates a formatted financial extract workbook from the " + "revenue trial balance, with one sheet per donor." + ), + "url": "/donor-report/", + "status": "online", + }, ] @@ -29,6 +40,7 @@ def create_app(): app.config["MAX_CONTENT_LENGTH"] = 50 * 1024 * 1024 # 50MB app.register_blueprint(eib_bp) + app.register_blueprint(donor_report_bp) @app.route("/") def home(): diff --git a/app/tools/donor_report/__init__.py b/app/tools/donor_report/__init__.py new file mode 100644 index 0000000..1328082 --- /dev/null +++ b/app/tools/donor_report/__init__.py @@ -0,0 +1,3 @@ +from .routes import donor_report_bp + +__all__ = ["donor_report_bp"] diff --git a/app/tools/donor_report/donor_merge_map.csv b/app/tools/donor_report/donor_merge_map.csv new file mode 100644 index 0000000..677ed08 --- /dev/null +++ b/app/tools/donor_report/donor_merge_map.csv @@ -0,0 +1,11 @@ +raw_donor,canonical_donor +G Adventures,G Adventures +G-Adventures,G Adventures +G - Adventures,G Adventures +Easy Jet,EasyJet +EasyJet,EasyJet +TruTravels,TruTravels +Tru Travel,TruTravels +IGF,IGF +IGF DERTOUR,IGF +DERTOUR,IGF diff --git a/app/tools/donor_report/logic.py b/app/tools/donor_report/logic.py new file mode 100644 index 0000000..7f55ad4 --- /dev/null +++ b/app/tools/donor_report/logic.py @@ -0,0 +1,209 @@ +import os, re, csv +from datetime import datetime +import pandas as pd +import openpyxl +from openpyxl.styles import Font + +TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), "report_summary_template.xlsx") +TEMPLATE_SHEET = "Sheet1" + +DONOR_MERGE_MAP_PATH = os.path.join(os.path.dirname(__file__), "donor_merge_map.csv") + +REVENUE_ACCOUNT_CODES = ("43000", "48000") + +FONT_NAME = "Aptos Narrow" +FONT_SIZE = 12 +REGULAR_FONT = Font(name=FONT_NAME, size=FONT_SIZE, bold=False) +BOLD_FONT = Font(name=FONT_NAME, size=FONT_SIZE, bold=True) +AMOUNT_FORMAT = "#,##0.00;(#,##0.00)" + +_INVALID_SHEET_CHARS = re.compile(r'[:\\/?*\[\]]') + + +def _load_donor_merge_map(path=DONOR_MERGE_MAP_PATH): + """ + Read the raw-donor -> canonical-donor mapping fresh from + donor_merge_map.csv on every call, same pattern (and same reasoning) + as the EIB tool's merchant_lookup.csv: bind-mounted, so edits take + effect on the next run with no rebuild. + """ + merge_map = {} + if not os.path.exists(path): + return merge_map + with open(path, newline="", encoding="utf-8") as f: + for row in csv.DictReader(f): + raw = row.get("raw_donor") + if raw: + merge_map[raw] = row.get("canonical_donor") or raw + return merge_map + + +def parse_project(project): + """ + Split a Project string (" - - ") into + (slob, raw_donor). Donor parts beyond the second are joined back with + " - " so hyphenated donor names (e.g. "G - Adventures") survive intact. + + Fewer than 3 parts means there's no real donor segment at all (e.g. + "Planeterra - General", "Planeterra - General Fund", or a blank + Project cell) - slob is whatever's left (may be empty), raw_donor is + None, which routes to the unified "General" bucket in resolve_donor(). + """ + if not project or not str(project).strip(): + return "", None + parts = str(project).split(" - ") + if len(parts) < 3: + slob = parts[1] if len(parts) == 2 else "" + return slob, None + return parts[1], " - ".join(parts[2:]) + + +def resolve_donor(raw_donor, merge_map): + """ + No real donor segment (raw_donor is None), or a donor segment that's + literally "General", both collapse into one canonical "General" + report - per stakeholder direction, "no donor name at the end" and + "donor literally named General" are the same bucket, not two. + """ + if not raw_donor: + return "General" + canonical = merge_map.get(raw_donor, raw_donor) + return "General" if canonical == "General" else canonical + + +def process_trial_balance(tb_df, merge_map=None): + """ + Filter the raw trial balance to revenue rows (43000/48000), parse each + row's Project into (slob, donor), apply the donor merge map, flip the + sign (revenue is stored as a negative/credit balance), and aggregate + down to one row per (donor, account, slob, category). + + Summing is the whole strategy for the "duplicate-looking" rows in the + source data (offsetting entries, fund reclassifications, etc.) - a + group that nets to zero just doesn't produce a line in the output; + there's no need to detect or special-case why it nets to zero. + """ + if merge_map is None: + merge_map = _load_donor_merge_map() + + df = tb_df.copy() + df = df[df["Ledger Account"].astype(str).str.strip().str.startswith(REVENUE_ACCOUNT_CODES)] + + codes = df["Ledger Account"].astype(str).str.split(":", n=1) + df["account_code"] = codes.str[0].str.strip() + df["account_name"] = codes.str[1].str.strip() + + parsed = df["Project"].apply(parse_project) + df["slob"] = parsed.apply(lambda t: t[0]) + df["donor"] = parsed.apply(lambda t: resolve_donor(t[1], merge_map)) + + df["category"] = df["Revenue Category"].fillna("(Uncategorized)") + df["amount"] = -df["Planeterra Foundation"].fillna(0) + + grouped = ( + df.groupby(["donor", "account_code", "account_name", "slob", "category"], as_index=False)["amount"] + .sum() + ) + # Drop groups that net to exactly zero - nothing to show, and the + # remaining rows already sum to the correct total without them. + grouped = grouped[grouped["amount"].abs() >= 0.005].reset_index(drop=True) + return grouped + + +def sanitize_sheet_name(name): + cleaned = _INVALID_SHEET_CHARS.sub("", str(name)) + return cleaned[:31] or "Sheet" + + +def _write_cell(ws, row, col, value, bold=False, number_format=None): + c = ws.cell(row=row, column=col, value=value) + c.font = BOLD_FONT if bold else REGULAR_FONT + if number_format: + c.number_format = number_format + return c + + +def _write_donor_sheet(wb, template_ws, donor, donor_df): + ws = wb.copy_worksheet(template_ws) + ws.title = sanitize_sheet_name(donor) + + ws["A1"] = donor + ws["B3"] = datetime.today().strftime("%Y-%m-%d") + + # How many rows this donor's detail block needs: per account, one + # header row, then per SLOB one header row + one row per category + + # one subtotal row. + needed = 0 + accounts = donor_df.sort_values("account_code")["account_code"].unique() + for code in accounts: + needed += 1 + acct_df = donor_df[donor_df["account_code"] == code] + for slob in sorted(acct_df["slob"].unique()): + slob_df = acct_df[acct_df["slob"] == slob] + needed += 1 + len(slob_df) + 1 + + # Template reserves rows 7-12 (6 rows) for the detail block before + # "Total Revenue" at row 13. Expand if this donor needs more. + available = 6 + if needed > available: + ws.insert_rows(13, needed - available) + + row = 7 + total_revenue = 0.0 + for code in accounts: + acct_df = donor_df[donor_df["account_code"] == code] + account_name = acct_df["account_name"].iloc[0] + _write_cell(ws, row, 1, account_name, bold=False) + row += 1 + + for slob in sorted(acct_df["slob"].unique()): + slob_df = acct_df[acct_df["slob"] == slob] + slob_label = slob or "(No project code)" + _write_cell(ws, row, 1, f" {slob_label}", bold=False) + row += 1 + + slob_total = 0.0 + for _, r in slob_df.sort_values("category").iterrows(): + amount = round(r["amount"], 2) + _write_cell(ws, row, 1, f" {r['category']}", bold=False) + _write_cell(ws, row, 2, amount, bold=False, number_format=AMOUNT_FORMAT) + _write_cell(ws, row, 3, slob_label, bold=False) + _write_cell(ws, row, 4, r["category"], bold=False) + slob_total += amount + row += 1 + + slob_total = round(slob_total, 2) + _write_cell(ws, row, 1, f" {slob_label} Subtotal", bold=True) + _write_cell(ws, row, 2, slob_total, bold=True, number_format=AMOUNT_FORMAT) + row += 1 + total_revenue += slob_total + + total_revenue = round(total_revenue, 2) + total_row = 7 + needed + _write_cell(ws, total_row, 1, "Total Revenue", bold=True) + _write_cell(ws, total_row, 2, total_revenue, bold=True, number_format=AMOUNT_FORMAT) + + return total_revenue + + +def build_donor_workbook(grouped_df, output_path, template_path=TEMPLATE_PATH): + """ + Write one sheet per donor into a copy of report_summary_template.xlsx, + sorted alphabetically by donor name. Returns (donor_count, grand_total). + """ + wb = openpyxl.load_workbook(template_path) + template_ws = wb[TEMPLATE_SHEET] + + donors = sorted(grouped_df["donor"].unique()) + grand_total = 0.0 + written = 0 + for donor in donors: + donor_df = grouped_df[grouped_df["donor"] == donor] + if donor_df.empty: + continue + grand_total += _write_donor_sheet(wb, template_ws, donor, donor_df) + written += 1 + + del wb[TEMPLATE_SHEET] + wb.save(output_path) + return written, round(grand_total, 2) diff --git a/app/tools/donor_report/report_summary_template.xlsx b/app/tools/donor_report/report_summary_template.xlsx new file mode 100644 index 0000000..5432304 Binary files /dev/null and b/app/tools/donor_report/report_summary_template.xlsx differ diff --git a/app/tools/donor_report/routes.py b/app/tools/donor_report/routes.py new file mode 100644 index 0000000..ebc0927 --- /dev/null +++ b/app/tools/donor_report/routes.py @@ -0,0 +1,63 @@ +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) diff --git a/docker-compose.yml b/docker-compose.yml index 02c7234..bad525b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -25,6 +25,7 @@ services: - ./uploads:/app/uploads - ./outputs:/app/outputs - ./app/tools/eib/merchant_lookup.csv:/app/app/tools/eib/merchant_lookup.csv + - ./app/tools/donor_report/donor_merge_map.csv:/app/app/tools/donor_report/donor_merge_map.csv environment: - FLASK_ENV=production - DOCLING_URL=http://docling:5001 diff --git a/templates/donor_report/index.html b/templates/donor_report/index.html new file mode 100644 index 0000000..12cfae1 --- /dev/null +++ b/templates/donor_report/index.html @@ -0,0 +1,332 @@ + + + + + +Donor Revenue Report — Undo Designs + + + + + +
+ +
+ +
+
+
Planeterra International Foundation
+

Donor Revenue Report

+

Upload the revenue trial balance to generate one formatted financial extract sheet per donor.

+
+ +
+
+ +
+ + + + +
+
Click to browse or drag & drop
+
Revenue trial balance (.xlsx)
+
+
+ + + +
+
+ Processing… +
+
+
+ +
+
+
+ + + +
+
+
Report generated
+
+
+
+ +
+
+
—
+
Donor Sheets
+
+
+
—
+
Total Revenue (CAD)
+
+
+ + +
+ + +
+
+ + + + + +