From a9f4b5a597cef5476e56f4504360fba8b1509de3 Mon Sep 17 00:00:00 2001 From: JasonFraser Date: Tue, 25 Aug 2026 12:36:11 -0400 Subject: [PATCH] Add Donor Revenue Report tool New Blueprint at app/tools/donor_report/ (registered on the platform home page), following the eib tool's conventions: - logic.py: parse_project() splits " - - " with the join-back fix for hyphenated donor names; donor merge map is a bind-mounted CSV (donor_merge_map.csv, same pattern as merchant_lookup.csv) covering the confirmed G Adventures/EasyJet/ TruTravels/IGF spelling variants. Per stakeholder direction, any row with no real donor segment (blank Project, or a 2-part Project with no donor at the end) and any row whose donor segment is literally "General" both collapse into one unified "General" report. - Aggregation groups to (donor, account, slob, category) and sums - since this is a trial balance, groups that net to exactly zero are real (reclassifications, offsetting entries) rather than bugs, so they're simply not displayed rather than needing special-case duplicate detection. Verified the grand total across all donors matches summing the raw filtered rows directly. - build_donor_workbook() copies report_summary_template.xlsx per donor, expanding the template's fixed 5-row detail area via insert_rows() to fit each donor's actual row count (1-30+), writing Category -> SLOB subtotal -> Account header -> Total Revenue, with the Expenses section shifted down accordingly and left unpopulated per the current scope (revenue only). - routes.py: /donor-report/api/process (single synchronous call, no progress polling needed - unlike the eib tool there's no slow external step) and /api/download/. - templates/donor_report/index.html: single-upload page in the same theme as the platform shell. Verified end to end against the real sample trial balance: 10 donor sheets generated, all merge-map variants resolved correctly, no empty sheets for accounts that fully net to zero, and the total revenue figure matches an independent manual calculation from the raw file (4,384,170.35). Co-Authored-By: Claude Sonnet 5 --- .gitignore | 2 + app/main.py | 12 + app/tools/donor_report/__init__.py | 3 + app/tools/donor_report/donor_merge_map.csv | 11 + app/tools/donor_report/logic.py | 209 +++++++++++ .../donor_report/report_summary_template.xlsx | Bin 0 -> 9260 bytes app/tools/donor_report/routes.py | 63 ++++ docker-compose.yml | 1 + templates/donor_report/index.html | 332 ++++++++++++++++++ 9 files changed, 633 insertions(+) create mode 100644 app/tools/donor_report/__init__.py create mode 100644 app/tools/donor_report/donor_merge_map.csv create mode 100644 app/tools/donor_report/logic.py create mode 100644 app/tools/donor_report/report_summary_template.xlsx create mode 100644 app/tools/donor_report/routes.py create mode 100644 templates/donor_report/index.html 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 0000000000000000000000000000000000000000..543230454f7db5a35adc4ee78a8c16b0a0441196 GIT binary patch literal 9260 zcmeHtg;yNg^7UZB-6d#9aMut#!7X?oID^9w26qMx1Sb$6IKc_-u7d>E;BG;J3?BF< zdH4P9y}9rE3*PHl>zvhVde`bcr*`e?s#a4(LM8${0H6T?06Ku_VVad80ss($3;+-U z&=B>dK@QG92WKNq4@V%_fWzJ1jy4+^ktq{^2*3V+$A9q(lq3wQbaCOmxRAS*-e6Z) zsFXnCKY&09SYC>?cgOb@ndzrnTi>U@y}^^pBDN8%AQ)Nj;yE6&s&ufgg@pAssbfV1 z^tEdlQVMeRK=&EjNXg@z^j;lh5>ZNUlN%XDTBHI#ys7I_=X<^?sZc^;MNA^*zn(S+ z)y7}$ZNMthD-iCR?^sdMUcwg|D4f7sA0wQ!v1ax%JY8p(M~*wtHErl z-r#hdq}U2(s^^_DHbY$E3W;gKSsY$|(9|kOt;|PJSr~p+q}Ll`%i8As+S{{@DJtSj z?YdEb*vg1qKV2e#4l+IqP_vDwCMo4{81d;AC(cnC{N72sc*D3#NY%YeY2KI~9b>LS zMsLry@(G&$Tvb?*1>&3E*IzHxu6kfb!(){^+KD;NfxNt{>0c0|4Ou9toiKH(J(caWS01eN73@I!rh%jhujXU`~#oR>+auZD`-c)M5;tl%kuYToaw9ufO~PZcSv)Bg)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;F@C@jF26*I}$kp-!r(pIO5at*}>9yy~5sZIzdt}y4PuaS_Y z285}|4L``eDtAF$!IH)%NN^KU^spQw230SrW)#IvQ_2yZ} zS&a9fUGd&F`nvBG^-9$=nfez&cstqD%IsZK)3nD1)KP2O8L|vamD7wueLyJRQ`b3< zK2g^jL{j5C!|0GRS}$oCmwFn)tb}qQ`(@4TtS@hoI}u6BZ*-L7aE8+;iP2wpYj3fSlsUK_5IzFxAUJr)m30{_2l?N?pK}tN z8h`00{|@}UtM(_f8Gf(7_1Jy~|Gm)vClmm%!1x9J|CIfIxAS}T_fJd7SpRnu|ELB3 zZsqs7)}K~T@P1kOy~_2wf#37xKMfp`{xa}q_WV2a_mtvK=mW}sL4Qv$ez)*<4gC`j t0O(Kw0RK?b-{F6cgnxyPQvU`1M_g1>M1k)v0DuAi`NKs!k?!Z&{{#ODJuUzM literal 0 HcmV?d00001 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)
+
+
+ + +
+ + +
+
+ + + + + +