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 "<Company> - <SLOB> - <Donor...>"
  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/<filename>.
- 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 <noreply@anthropic.com>
This commit is contained in:
JasonFraser 2026-08-25 12:36:11 -04:00
parent e339b7147a
commit a9f4b5a597
9 changed files with 633 additions and 0 deletions

2
.gitignore vendored
View File

@ -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

View File

@ -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():

View File

@ -0,0 +1,3 @@
from .routes import donor_report_bp
__all__ = ["donor_report_bp"]

View File

@ -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
1 raw_donor canonical_donor
2 G Adventures G Adventures
3 G-Adventures G Adventures
4 G - Adventures G Adventures
5 Easy Jet EasyJet
6 EasyJet EasyJet
7 TruTravels TruTravels
8 Tru Travel TruTravels
9 IGF IGF
10 IGF DERTOUR IGF
11 DERTOUR IGF

View File

@ -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 ("<Company> - <SLOB> - <Donor...>") 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)

Binary file not shown.

View File

@ -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/<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)

View File

@ -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

View File

@ -0,0 +1,332 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Donor Revenue Report — Undo Designs</title>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
--navy: #0C1A3A;
--navy-2: #12244C;
--navy-3: #1a2f5e;
--navy-4: #0a1428;
--cyan: #00D4FF;
--cyan-dim: rgba(0,212,255,.12);
--cyan-glow: rgba(0,212,255,.06);
--blue: #1B8EF8;
--green: #10D98A;
--green-dim: rgba(16,217,138,.12);
--red: #F04438;
--red-dim: rgba(240,68,56,.12);
--amber: #F79009;
--w1: rgba(255,255,255,.95);
--w2: rgba(255,255,255,.65);
--w3: rgba(255,255,255,.35);
--w4: rgba(255,255,255,.10);
--w5: rgba(255,255,255,.05);
--border: rgba(255,255,255,.07);
--border-c: rgba(0,212,255,.18);
--mono: 'JetBrains Mono', monospace;
--disp: 'Space Grotesk', sans-serif;
--body: 'Inter', sans-serif;
--radius: 10px;
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: var(--body);
background: var(--navy-4);
color: var(--w1);
min-height: 100vh;
-webkit-font-smoothing: antialiased;
display: flex;
flex-direction: column;
}
body::before {
content: '';
position: fixed; inset: 0; pointer-events: none; z-index: 0;
background-image: radial-gradient(circle, rgba(0,212,255,.07) 1px, transparent 1px);
background-size: 28px 28px;
}
header {
position: sticky; top: 0; z-index: 100;
background: rgba(12,26,58,.85);
backdrop-filter: blur(12px);
border-bottom: 1px solid var(--border);
padding: 0 32px;
height: 60px;
display: flex; align-items: center; justify-content: space-between;
}
.logo {
display: flex; align-items: center; gap: 10px;
font-family: var(--disp); font-size: 15px; font-weight: 600;
color: var(--w1); text-decoration: none;
}
.logo-icon {
width: 30px; height: 30px;
background: linear-gradient(135deg, var(--navy-3), var(--navy-2));
border: 1px solid var(--border-c);
border-radius: 7px;
display: flex; align-items: center; justify-content: center;
}
.logo-icon svg { width: 16px; height: 16px; }
.logo span { color: var(--cyan); }
main {
position: relative; z-index: 1;
flex: 1;
max-width: 720px;
width: 100%;
margin: 0 auto;
padding: 48px 24px 80px;
}
.page-title { margin-bottom: 40px; }
.eyebrow {
font-family: var(--mono); font-size: 10px;
letter-spacing: .16em; text-transform: uppercase;
color: var(--cyan); margin-bottom: 10px;
}
.page-title h1 {
font-family: var(--disp); font-size: 28px; font-weight: 700;
color: var(--w1); line-height: 1.2; margin-bottom: 8px;
}
.page-title p { font-size: 14px; color: var(--w2); line-height: 1.6; max-width: 520px; }
.card {
background: var(--navy-2);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 24px;
margin-bottom: 16px;
}
.file-zone {
border: 1.5px dashed var(--border);
border-radius: 8px;
padding: 28px 20px;
text-align: center;
cursor: pointer;
transition: all .2s;
position: relative;
}
.file-zone:hover, .file-zone.drag-over { border-color: var(--cyan); background: var(--cyan-glow); }
.file-zone input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%; }
.file-zone-icon {
width: 36px; height: 36px; margin: 0 auto 10px;
background: var(--w5); border-radius: 8px;
display: flex; align-items: center; justify-content: center;
}
.file-zone-icon svg { width: 18px; height: 18px; color: var(--w3); }
.file-zone-label { font-size: 13px; color: var(--w2); }
.file-zone-label strong { color: var(--cyan); }
.file-zone-sub { font-size: 11px; color: var(--w3); margin-top: 4px; }
.file-chosen { font-family: var(--mono); font-size: 11px; color: var(--green); margin-top: 8px; }
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
padding: 11px 22px; border-radius: 8px; border: none;
font-family: var(--disp); font-size: 13px; font-weight: 600;
cursor: pointer; transition: all .2s; text-decoration: none;
width: 100%; margin-top: 16px;
}
.btn-primary { background: linear-gradient(135deg, var(--cyan), var(--blue)); color: var(--navy); }
.btn-primary:hover { filter: brightness(1.08); }
.btn-primary:disabled { opacity: .4; cursor: not-allowed; filter: none; }
.spinner {
display: none;
align-items: center; gap: 8px;
font-family: var(--mono); font-size: 11px; color: var(--w3);
margin-top: 12px;
}
.spinner.visible { display: flex; }
.spinner-dot {
width: 6px; height: 6px; border-radius: 50%; background: var(--cyan);
animation: pulse 1s infinite ease-in-out;
}
@keyframes pulse { 0%,100% { opacity: .3; } 50% { opacity: 1; } }
.error-note {
display: none;
font-size: 12px; color: var(--red); background: var(--red-dim);
border: 1px solid rgba(240,68,56,.2); border-radius: 8px;
padding: 12px 14px; margin-top: 12px;
}
.error-note.visible { display: block; }
.result-card { display: none; }
.result-card.visible { display: block; }
.result-header { display: flex; align-items: center; gap: 10px; margin-bottom: 18px; }
.result-icon {
width: 32px; height: 32px; border-radius: 8px;
background: var(--green-dim); display: flex; align-items: center; justify-content: center;
}
.result-icon svg { width: 16px; height: 16px; }
.result-title { font-family: var(--disp); font-size: 15px; font-weight: 600; color: var(--w1); }
.result-sub { font-size: 12px; color: var(--w3); margin-top: 2px; }
.stats-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 16px; }
.stat-box { background: var(--w5); border: 1px solid var(--border); border-radius: 8px; padding: 12px; }
.stat-value { font-family: var(--mono); font-size: 18px; font-weight: 500; color: var(--cyan); line-height: 1; }
.stat-label { font-size: 10px; color: var(--w3); margin-top: 4px; text-transform: uppercase; letter-spacing: .08em; }
.section-label { font-family: var(--mono); font-size: 9.5px; letter-spacing: .14em; text-transform: uppercase; color: var(--w3); margin-bottom: 10px; }
.donor-list { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 4px; }
.donor-chip {
font-family: var(--mono); font-size: 10.5px; color: var(--w2);
background: var(--w5); border: 1px solid var(--border); border-radius: 20px;
padding: 4px 10px;
}
footer { position: relative; z-index: 1; text-align: center; padding: 20px; font-size: 11px; color: var(--w3); border-top: 1px solid var(--border); }
footer a { color: var(--cyan); text-decoration: none; }
</style>
</head>
<body>
<header>
<a class="logo" href="/">
<div class="logo-icon">
<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2 4h12M2 8h8M2 12h5" stroke="#00D4FF" stroke-width="1.5" stroke-linecap="round"/>
</svg>
</div>
Donor <span>Revenue Report</span>
</a>
</header>
<main>
<div class="page-title">
<div class="eyebrow">Planeterra International Foundation</div>
<h1>Donor Revenue Report</h1>
<p>Upload the revenue trial balance to generate one formatted financial extract sheet per donor.</p>
</div>
<div class="card">
<div class="file-zone" id="tbZone">
<input type="file" id="tbFile" accept=".xlsx,.xls">
<div class="file-zone-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14,2 14,8 20,8"/>
</svg>
</div>
<div class="file-zone-label"><strong>Click to browse</strong> or drag & drop</div>
<div class="file-zone-sub">Revenue trial balance (.xlsx)</div>
<div class="file-chosen" id="tbChosen"></div>
</div>
<button class="btn btn-primary" id="processBtn" disabled>Generate Report</button>
<div class="spinner" id="spinner">
<div class="spinner-dot"></div>
Processing…
</div>
<div class="error-note" id="errorNote"></div>
</div>
<div class="card result-card" id="resultCard">
<div class="result-header">
<div class="result-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="#10D98A" stroke-width="2.5">
<polyline points="20,6 9,17 4,12"/>
</svg>
</div>
<div>
<div class="result-title">Report generated</div>
<div class="result-sub" id="resultSub"></div>
</div>
</div>
<div class="stats-grid">
<div class="stat-box">
<div class="stat-value" id="statDonors">—</div>
<div class="stat-label">Donor Sheets</div>
</div>
<div class="stat-box">
<div class="stat-value" id="statTotal">—</div>
<div class="stat-label">Total Revenue (CAD)</div>
</div>
</div>
<div class="section-label">Donors Included</div>
<div class="donor-list" id="donorList"></div>
<button class="btn btn-primary" id="downloadBtn">Download Report</button>
</div>
</main>
<footer>
Built by <a href="https://undodesigns.com" target="_blank">Undo Designs</a> · Donor Revenue Report v1
</footer>
<script>
const $ = id => document.getElementById(id);
const zone = $('tbZone'), input = $('tbFile'), chosen = $('tbChosen');
zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
zone.addEventListener('drop', e => {
e.preventDefault(); zone.classList.remove('drag-over');
if (e.dataTransfer.files[0]) {
input.files = e.dataTransfer.files;
chosen.textContent = e.dataTransfer.files[0].name;
$('processBtn').disabled = false;
}
});
input.addEventListener('change', () => {
if (input.files[0]) {
chosen.textContent = input.files[0].name;
$('processBtn').disabled = false;
}
});
let lastFilename = '';
$('processBtn').addEventListener('click', async () => {
const file = input.files[0];
if (!file) return;
$('processBtn').disabled = true;
$('spinner').classList.add('visible');
$('errorNote').classList.remove('visible');
$('resultCard').classList.remove('visible');
const fd = new FormData();
fd.append('trial_balance_file', file);
try {
const r = await fetch('/donor-report/api/process', { method: 'POST', body: fd });
const d = await r.json();
if (d.status === 'ok') {
lastFilename = d.filename;
$('resultSub').textContent = d.filename;
$('statDonors').textContent = d.donors;
$('statTotal').textContent = '$' + d.total_revenue.toLocaleString('en-US', {minimumFractionDigits: 2});
$('donorList').innerHTML = d.donor_names.map(n => `<div class="donor-chip">${n}</div>`).join('');
$('resultCard').classList.add('visible');
} else {
$('errorNote').textContent = d.error || 'Unexpected error';
$('errorNote').classList.add('visible');
}
} catch (e) {
$('errorNote').textContent = 'Network error: ' + e.message;
$('errorNote').classList.add('visible');
}
$('spinner').classList.remove('visible');
$('processBtn').disabled = false;
});
$('downloadBtn').addEventListener('click', () => {
if (lastFilename) window.location.href = '/donor-report/api/download/' + encodeURIComponent(lastFilename);
});
</script>
</body>
</html>