Add expense trial balance support to Donor Revenue Report
Multi-file upload (auto-classifies each uploaded file as revenue or expense by column headers - "Revenue Category" vs "Spend Category" - so the order doesn't matter), with a clear prompt if only one file is uploaded or a role is duplicated/unrecognized. - logic.py: process_revenue()/process_expense() share one _process_side() implementation (revenue flips sign, expense doesn't - expense accounts are already debit-normal). EXPENSE_ACCOUNT_CODES covers all 19 P&L expense accounts (68010-82000), not just the "Disbursements to Projects" ones - real per-donor Project attribution turned out to be present across nearly all of them (salaries, travel, currency gain/loss, etc.), confirmed against the actual sample data. full_file_balance() checks each uploaded file's raw, unfiltered total nets to ~zero - a basic trial-balance integrity check independent of the revenue/expense filtering - and blocks processing if not. - Donor sheets now write both Revenue and Expenses sections (same Account -> SLOB -> Category -> Subtotal hierarchy for both), and every subtotal/total/surplus cell is a real Excel SUM/subtraction formula rather than a precomputed value, so the numbers are auditable directly in the workbook. - Fixed a latent bug found while adding the Expenses section: the previous row-insert logic could leave a stale duplicate "Total Revenue" label when a donor had fewer lines than the template reserves. _adjust_block() now inserts OR deletes rows symmetrically so the template's own total labels always land exactly where expected - no more relying on need >= the template's reserved slack. - routes.py: /api/process now accepts trial_balance_file_0.. (multiple), classifies each by its columns, and returns total_revenue, total_expense, and surplus_deficit alongside the existing donor count. - templates/donor_report/index.html: multi-file drop zone (mirroring the EIB tool's PDF upload pattern) and two more stat boxes (Total Expense, Surplus/(Deficit), red/green colored). - Added "Easyjet" (lowercase) to the donor merge map - a variant not present in the revenue file, found only once the expense file was processed. Verified end to end: every SLOB subtotal, Total Revenue, Total Expenses, and Surplus/(Deficit) formula in the generated workbook was independently re-evaluated (recursively resolving formula-to-formula references) and cross-checked against the API's reported totals - exact match on all 12 donor sheets and the grand total (revenue 4,384,170.35 / expense 3,611,064.64 / surplus 773,105.71). Also verified the zero-revenue and zero-expense edge cases produce no duplicate total labels. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
a9f4b5a597
commit
8d2da18bfb
|
|
@ -4,6 +4,7 @@ G-Adventures,G Adventures
|
|||
G - Adventures,G Adventures
|
||||
Easy Jet,EasyJet
|
||||
EasyJet,EasyJet
|
||||
Easyjet,EasyJet
|
||||
TruTravels,TruTravels
|
||||
Tru Travel,TruTravels
|
||||
IGF,IGF
|
||||
|
|
|
|||
|
|
|
@ -10,6 +10,17 @@ TEMPLATE_SHEET = "Sheet1"
|
|||
DONOR_MERGE_MAP_PATH = os.path.join(os.path.dirname(__file__), "donor_merge_map.csv")
|
||||
|
||||
REVENUE_ACCOUNT_CODES = ("43000", "48000")
|
||||
# All P&L expense accounts (everything below "Total" in the chart of
|
||||
# accounts that isn't Balance Sheet or Revenue). Project/donor
|
||||
# attribution turned out to be present across nearly all of these, not
|
||||
# just the "Disbursements to Projects" ones - confirm this scope is
|
||||
# right before relying on the Expenses section for real reporting.
|
||||
EXPENSE_ACCOUNT_CODES = (
|
||||
"68010", "68020", "68030",
|
||||
"70000", "70010", "70020", "70030", "71060",
|
||||
"72000", "72100", "72300", "72400", "72600", "72800", "72900",
|
||||
"78000", "79000", "81000", "82000",
|
||||
)
|
||||
|
||||
FONT_NAME = "Aptos Narrow"
|
||||
FONT_SIZE = 12
|
||||
|
|
@ -71,23 +82,19 @@ def resolve_donor(raw_donor, merge_map):
|
|||
return "General" if canonical == "General" else canonical
|
||||
|
||||
|
||||
def process_trial_balance(tb_df, merge_map=None):
|
||||
def full_file_balance(tb_df):
|
||||
"""
|
||||
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.
|
||||
Sum every row's Planeterra Foundation value across the WHOLE file
|
||||
(not just revenue/expense rows) - a complete, correctly-exported
|
||||
trial balance nets to zero across all accounts. Used as an upload
|
||||
integrity check, independent of the revenue/expense filtering below.
|
||||
"""
|
||||
if merge_map is None:
|
||||
merge_map = _load_donor_merge_map()
|
||||
return round(tb_df["Planeterra Foundation"].fillna(0).sum(), 2)
|
||||
|
||||
|
||||
def _process_side(tb_df, account_codes, category_col, flip_sign, merge_map):
|
||||
df = tb_df.copy()
|
||||
df = df[df["Ledger Account"].astype(str).str.strip().str.startswith(REVENUE_ACCOUNT_CODES)]
|
||||
df = df[df["Ledger Account"].astype(str).str.strip().str.startswith(account_codes)]
|
||||
|
||||
codes = df["Ledger Account"].astype(str).str.split(":", n=1)
|
||||
df["account_code"] = codes.str[0].str.strip()
|
||||
|
|
@ -97,19 +104,42 @@ def process_trial_balance(tb_df, merge_map=None):
|
|||
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)
|
||||
df["category"] = df[category_col].fillna("(Uncategorized)")
|
||||
raw_amount = df["Planeterra Foundation"].fillna(0)
|
||||
df["amount"] = -raw_amount if flip_sign else raw_amount
|
||||
|
||||
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.
|
||||
# Drop groups that net to exactly zero - since this is a trial
|
||||
# balance, a group netting to zero is a real reclassification/
|
||||
# offsetting entry, not a bug, and the remaining rows already sum to
|
||||
# the correct total without it.
|
||||
grouped = grouped[grouped["amount"].abs() >= 0.005].reset_index(drop=True)
|
||||
return grouped
|
||||
|
||||
|
||||
def process_revenue(tb_df, merge_map=None):
|
||||
"""
|
||||
Revenue (43000/48000) is stored as a negative/credit balance in the
|
||||
trial balance - flipped here so it displays positive.
|
||||
"""
|
||||
if merge_map is None:
|
||||
merge_map = _load_donor_merge_map()
|
||||
return _process_side(tb_df, REVENUE_ACCOUNT_CODES, "Revenue Category", True, merge_map)
|
||||
|
||||
|
||||
def process_expense(tb_df, merge_map=None):
|
||||
"""
|
||||
Expense accounts are debit-normal (already positive in the trial
|
||||
balance) - no sign flip.
|
||||
"""
|
||||
if merge_map is None:
|
||||
merge_map = _load_donor_merge_map()
|
||||
return _process_side(tb_df, EXPENSE_ACCOUNT_CODES, "Spend Category", False, merge_map)
|
||||
|
||||
|
||||
def sanitize_sheet_name(name):
|
||||
cleaned = _INVALID_SHEET_CHARS.sub("", str(name))
|
||||
return cleaned[:31] or "Sheet"
|
||||
|
|
@ -123,35 +153,51 @@ def _write_cell(ws, row, col, value, bold=False, number_format=None):
|
|||
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.
|
||||
def _rows_needed(df):
|
||||
"""How many rows a section (Revenue or Expenses) needs: one header
|
||||
row per account, then per SLOB one header row + one row per category
|
||||
+ one subtotal row."""
|
||||
if df.empty:
|
||||
return 0
|
||||
needed = 0
|
||||
accounts = donor_df.sort_values("account_code")["account_code"].unique()
|
||||
for code in accounts:
|
||||
for code in df["account_code"].unique():
|
||||
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
|
||||
acct_df = df[df["account_code"] == code]
|
||||
for slob in acct_df["slob"].unique():
|
||||
needed += 1 + len(acct_df[acct_df["slob"] == slob]) + 1
|
||||
return needed
|
||||
|
||||
# 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
|
||||
|
||||
def _adjust_block(ws, block_start, available, needed):
|
||||
"""
|
||||
Grow or shrink the reserved block of rows starting at block_start so
|
||||
it's exactly `needed` rows, by inserting or deleting rows right at
|
||||
the boundary. Whatever originally followed the reserved block (e.g.
|
||||
the template's "Total Revenue" label) rides along with the
|
||||
insert/delete and ends up at exactly block_start + needed - avoiding
|
||||
a stale duplicate label when needed < available.
|
||||
"""
|
||||
if needed > available:
|
||||
ws.insert_rows(13, needed - available)
|
||||
ws.insert_rows(block_start + available, needed - available)
|
||||
elif needed < available:
|
||||
ws.delete_rows(block_start + needed, available - needed)
|
||||
|
||||
row = 7
|
||||
total_revenue = 0.0
|
||||
for code in accounts:
|
||||
acct_df = donor_df[donor_df["account_code"] == code]
|
||||
|
||||
def _write_section(ws, start_row, df):
|
||||
"""
|
||||
Write Account -> SLOB -> Category rows starting at start_row, with a
|
||||
SUM formula (over its own category rows) on each SLOB subtotal row.
|
||||
Returns the list of subtotal cell coordinates (for the section
|
||||
total's own SUM formula) and this section's raw total.
|
||||
"""
|
||||
row = start_row
|
||||
subtotal_cells = []
|
||||
section_total = 0.0
|
||||
if df.empty:
|
||||
return subtotal_cells, section_total
|
||||
|
||||
for code in sorted(df["account_code"].unique()):
|
||||
acct_df = df[df["account_code"] == code]
|
||||
account_name = acct_df["account_name"].iloc[0]
|
||||
_write_cell(ws, row, 1, account_name, bold=False)
|
||||
row += 1
|
||||
|
|
@ -162,48 +208,94 @@ def _write_donor_sheet(wb, template_ws, donor, donor_df):
|
|||
_write_cell(ws, row, 1, f" {slob_label}", bold=False)
|
||||
row += 1
|
||||
|
||||
slob_total = 0.0
|
||||
cat_first_row = row
|
||||
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
|
||||
section_total += amount
|
||||
row += 1
|
||||
cat_last_row = 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)
|
||||
c = ws.cell(row=row, column=2, value=f"=SUM(B{cat_first_row}:B{cat_last_row})")
|
||||
c.font = BOLD_FONT
|
||||
c.number_format = AMOUNT_FORMAT
|
||||
subtotal_cells.append(f"B{row}")
|
||||
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
|
||||
return subtotal_cells, round(section_total, 2)
|
||||
|
||||
|
||||
def build_donor_workbook(grouped_df, output_path, template_path=TEMPLATE_PATH):
|
||||
def _write_donor_sheet(wb, template_ws, donor, revenue_df, expense_df):
|
||||
ws = wb.copy_worksheet(template_ws)
|
||||
ws.title = sanitize_sheet_name(donor)
|
||||
|
||||
ws["A1"] = donor
|
||||
ws["B3"] = datetime.today().strftime("%Y-%m-%d")
|
||||
|
||||
revenue_needed = _rows_needed(revenue_df)
|
||||
expense_needed = _rows_needed(expense_df)
|
||||
|
||||
# Template reserves rows 7-12 (6 rows) for Revenue detail before
|
||||
# "Total Revenue", and (after that) 3 rows for Expenses detail before
|
||||
# "Total Expenses". Adjust each block to fit this donor exactly.
|
||||
_adjust_block(ws, 7, 6, revenue_needed)
|
||||
total_revenue_row = 7 + revenue_needed
|
||||
expense_block_start = total_revenue_row + 3 # +2 blank/header rows, +1 to detail start
|
||||
|
||||
_adjust_block(ws, expense_block_start, 3, expense_needed)
|
||||
total_expenses_row = expense_block_start + expense_needed
|
||||
surplus_row = total_expenses_row + 2
|
||||
|
||||
rev_subtotals, revenue_total = _write_section(ws, 7, revenue_df)
|
||||
exp_subtotals, expense_total = _write_section(ws, expense_block_start, expense_df)
|
||||
|
||||
_write_cell(ws, total_revenue_row, 1, "Total Revenue", bold=True)
|
||||
c = ws.cell(row=total_revenue_row, column=2,
|
||||
value=("=SUM(" + ",".join(rev_subtotals) + ")") if rev_subtotals else 0)
|
||||
c.font = BOLD_FONT
|
||||
c.number_format = AMOUNT_FORMAT
|
||||
|
||||
_write_cell(ws, total_expenses_row, 1, "Total Expenses", bold=True)
|
||||
c = ws.cell(row=total_expenses_row, column=2,
|
||||
value=("=SUM(" + ",".join(exp_subtotals) + ")") if exp_subtotals else 0)
|
||||
c.font = BOLD_FONT
|
||||
c.number_format = AMOUNT_FORMAT
|
||||
|
||||
_write_cell(ws, surplus_row, 1, "Surplus/(Deficit)", bold=False)
|
||||
c = ws.cell(row=surplus_row, column=2, value=f"=B{total_revenue_row}-B{total_expenses_row}")
|
||||
c.font = REGULAR_FONT
|
||||
c.number_format = AMOUNT_FORMAT
|
||||
|
||||
return revenue_total, expense_total
|
||||
|
||||
|
||||
def build_donor_workbook(revenue_grouped, expense_grouped, 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).
|
||||
Write one sheet per donor (the union of donors appearing in either
|
||||
grouped DataFrame) into a copy of report_summary_template.xlsx,
|
||||
sorted alphabetically. Returns (donor_count, total_revenue, total_expense).
|
||||
"""
|
||||
wb = openpyxl.load_workbook(template_path)
|
||||
template_ws = wb[TEMPLATE_SHEET]
|
||||
|
||||
donors = sorted(grouped_df["donor"].unique())
|
||||
grand_total = 0.0
|
||||
donors = sorted(set(revenue_grouped["donor"]).union(expense_grouped["donor"]))
|
||||
total_revenue = 0.0
|
||||
total_expense = 0.0
|
||||
written = 0
|
||||
for donor in donors:
|
||||
donor_df = grouped_df[grouped_df["donor"] == donor]
|
||||
if donor_df.empty:
|
||||
rev_df = revenue_grouped[revenue_grouped["donor"] == donor]
|
||||
exp_df = expense_grouped[expense_grouped["donor"] == donor]
|
||||
if rev_df.empty and exp_df.empty:
|
||||
continue
|
||||
grand_total += _write_donor_sheet(wb, template_ws, donor, donor_df)
|
||||
r_total, e_total = _write_donor_sheet(wb, template_ws, donor, rev_df, exp_df)
|
||||
total_revenue += r_total
|
||||
total_expense += e_total
|
||||
written += 1
|
||||
|
||||
del wb[TEMPLATE_SHEET]
|
||||
wb.save(output_path)
|
||||
return written, round(grand_total, 2)
|
||||
return written, round(total_revenue, 2), round(total_expense, 2)
|
||||
|
|
|
|||
|
|
@ -4,10 +4,27 @@ from flask import Blueprint, request, jsonify, send_file, render_template, curre
|
|||
from werkzeug.utils import secure_filename
|
||||
import pandas as pd
|
||||
|
||||
from .logic import process_trial_balance, build_donor_workbook
|
||||
from .logic import (
|
||||
process_revenue,
|
||||
process_expense,
|
||||
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():
|
||||
|
|
@ -16,41 +33,81 @@ def index():
|
|||
|
||||
@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
|
||||
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
|
||||
|
||||
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)
|
||||
by_role = {}
|
||||
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
|
||||
|
||||
try:
|
||||
tb_df = pd.read_excel(tb_path)
|
||||
except Exception as e:
|
||||
return jsonify({"error": f"Could not read trial balance file: {e}"}), 400
|
||||
role = _classify_file(df)
|
||||
if role is None:
|
||||
unrecognized.append(f.filename)
|
||||
continue
|
||||
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}
|
||||
|
||||
required_cols = {"Ledger Account", "Project", "Revenue Category", "Planeterra Foundation"}
|
||||
missing = required_cols - set(tb_df.columns)
|
||||
missing = [r for r in ("revenue", "expense") if r not in by_role]
|
||||
if missing:
|
||||
return jsonify({"error": f"Missing expected column(s): {', '.join(sorted(missing))}"}), 400
|
||||
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
|
||||
|
||||
grouped = process_trial_balance(tb_df)
|
||||
if grouped.empty:
|
||||
return jsonify({"error": "No revenue (43000/48000) rows found in this file"}), 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
|
||||
|
||||
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)
|
||||
donor_count, total_revenue, total_expense = build_donor_workbook(revenue_grouped, expense_grouped, fpath)
|
||||
surplus_deficit = round(total_revenue - total_expense, 2)
|
||||
|
||||
donor_names = sorted(set(revenue_grouped["donor"]).union(expense_grouped["donor"]))
|
||||
|
||||
return jsonify({
|
||||
"status": "ok",
|
||||
"filename": fname,
|
||||
"donors": donor_count,
|
||||
"total_revenue": grand_total,
|
||||
"donor_names": sorted(grouped["donor"].unique().tolist()),
|
||||
"total_revenue": total_revenue,
|
||||
"total_expense": total_expense,
|
||||
"surplus_deficit": surplus_deficit,
|
||||
"donor_names": donor_names,
|
||||
}), 200
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -127,6 +127,18 @@ main {
|
|||
.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; }
|
||||
|
||||
.tb-file-list { list-style: none; margin-top: 12px; }
|
||||
.tb-file-list li {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 8px 12px; border: 1px solid var(--border);
|
||||
border-radius: 6px; margin-bottom: 6px;
|
||||
font-family: var(--mono); font-size: 11px; color: var(--w2);
|
||||
background: var(--w5);
|
||||
}
|
||||
.tb-file-list li span { color: var(--cyan); margin-right: 8px; }
|
||||
.tb-remove { background: none; border: none; cursor: pointer; color: var(--w3); font-size: 14px; padding: 0 4px; transition: color .15s; }
|
||||
.tb-remove:hover { color: var(--red); }
|
||||
|
||||
.btn {
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
|
||||
padding: 11px 22px; border-radius: 8px; border: none;
|
||||
|
|
@ -173,6 +185,8 @@ main {
|
|||
.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-value.positive { color: var(--green); }
|
||||
.stat-value.negative { color: var(--red); }
|
||||
.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; }
|
||||
|
|
@ -204,22 +218,22 @@ footer a { color: var(--cyan); text-decoration: none; }
|
|||
<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>
|
||||
<p>Upload the revenue trial balance and the expense 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" id="tbZone" style="cursor:default">
|
||||
<input type="file" id="tbFileInput" accept=".xlsx,.xls" multiple style="display:none">
|
||||
<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 class="file-zone-label" id="tbDropLabel"><strong>Drop trial balance files here</strong> or <span style="color:var(--cyan);cursor:pointer" id="tbBrowseBtn">browse</span></div>
|
||||
<div class="file-zone-sub">Revenue trial balance + expense trial balance (.xlsx)</div>
|
||||
</div>
|
||||
<ul class="tb-file-list" id="tbFileList"></ul>
|
||||
|
||||
<button class="btn btn-primary" id="processBtn" disabled>Generate Report</button>
|
||||
|
||||
|
|
@ -249,9 +263,17 @@ footer a { color: var(--cyan); text-decoration: none; }
|
|||
<div class="stat-label">Donor Sheets</div>
|
||||
</div>
|
||||
<div class="stat-box">
|
||||
<div class="stat-value" id="statTotal">—</div>
|
||||
<div class="stat-value" id="statRevenue">—</div>
|
||||
<div class="stat-label">Total Revenue (CAD)</div>
|
||||
</div>
|
||||
<div class="stat-box">
|
||||
<div class="stat-value" id="statExpense">—</div>
|
||||
<div class="stat-label">Total Expense (CAD)</div>
|
||||
</div>
|
||||
<div class="stat-box">
|
||||
<div class="stat-value" id="statSurplus">—</div>
|
||||
<div class="stat-label">Surplus / (Deficit)</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-label">Donors Included</div>
|
||||
|
|
@ -268,29 +290,63 @@ footer a { color: var(--cyan); text-decoration: none; }
|
|||
<script>
|
||||
const $ = id => document.getElementById(id);
|
||||
|
||||
const zone = $('tbZone'), input = $('tbFile'), chosen = $('tbChosen');
|
||||
// ── Multi-file upload ──────────────────────────────────────────────────────
|
||||
const tbFiles = [];
|
||||
|
||||
function renderFileList() {
|
||||
const list = $('tbFileList');
|
||||
list.innerHTML = '';
|
||||
tbFiles.forEach((file, idx) => {
|
||||
const li = document.createElement('li');
|
||||
li.innerHTML = `<span>${idx + 1}</span>${file.name}
|
||||
<button class="tb-remove" data-idx="${idx}" title="Remove">✕</button>`;
|
||||
list.appendChild(li);
|
||||
});
|
||||
list.querySelectorAll('.tb-remove').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
tbFiles.splice(+btn.dataset.idx, 1);
|
||||
renderFileList();
|
||||
$('processBtn').disabled = tbFiles.length === 0;
|
||||
});
|
||||
});
|
||||
$('tbDropLabel').innerHTML = tbFiles.length
|
||||
? `<strong>${tbFiles.length} file${tbFiles.length > 1 ? 's' : ''} selected</strong> — <span style="color:var(--cyan);cursor:pointer" id="tbBrowseBtn">add more</span>`
|
||||
: `<strong>Drop trial balance files here</strong> or <span style="color:var(--cyan);cursor:pointer" id="tbBrowseBtn">browse</span>`;
|
||||
document.getElementById('tbBrowseBtn')?.addEventListener('click', () => $('tbFileInput').click());
|
||||
}
|
||||
|
||||
$('tbBrowseBtn').addEventListener('click', () => $('tbFileInput').click());
|
||||
$('tbFileInput').addEventListener('change', () => {
|
||||
Array.from($('tbFileInput').files).forEach(f => {
|
||||
if (!tbFiles.find(x => x.name === f.name)) tbFiles.push(f);
|
||||
});
|
||||
$('tbFileInput').value = '';
|
||||
$('processBtn').disabled = tbFiles.length === 0;
|
||||
renderFileList();
|
||||
});
|
||||
|
||||
const zone = $('tbZone');
|
||||
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;
|
||||
}
|
||||
Array.from(e.dataTransfer.files)
|
||||
.filter(f => f.name.endsWith('.xlsx') || f.name.endsWith('.xls'))
|
||||
.forEach(f => { if (!tbFiles.find(x => x.name === f.name)) tbFiles.push(f); });
|
||||
$('processBtn').disabled = tbFiles.length === 0;
|
||||
renderFileList();
|
||||
});
|
||||
|
||||
// ── Process ───────────────────────────────────────────────────────────────
|
||||
let lastFilename = '';
|
||||
|
||||
function fmtMoney(n) {
|
||||
const sign = n < 0 ? '-' : '';
|
||||
return sign + '$' + Math.abs(n).toLocaleString('en-US', {minimumFractionDigits: 2});
|
||||
}
|
||||
|
||||
$('processBtn').addEventListener('click', async () => {
|
||||
const file = input.files[0];
|
||||
if (!file) return;
|
||||
if (tbFiles.length === 0) return;
|
||||
|
||||
$('processBtn').disabled = true;
|
||||
$('spinner').classList.add('visible');
|
||||
|
|
@ -298,7 +354,7 @@ $('processBtn').addEventListener('click', async () => {
|
|||
$('resultCard').classList.remove('visible');
|
||||
|
||||
const fd = new FormData();
|
||||
fd.append('trial_balance_file', file);
|
||||
tbFiles.forEach((f, i) => fd.append(`trial_balance_file_${i}`, f));
|
||||
|
||||
try {
|
||||
const r = await fetch('/donor-report/api/process', { method: 'POST', body: fd });
|
||||
|
|
@ -308,7 +364,11 @@ $('processBtn').addEventListener('click', async () => {
|
|||
lastFilename = d.filename;
|
||||
$('resultSub').textContent = d.filename;
|
||||
$('statDonors').textContent = d.donors;
|
||||
$('statTotal').textContent = '$' + d.total_revenue.toLocaleString('en-US', {minimumFractionDigits: 2});
|
||||
$('statRevenue').textContent = fmtMoney(d.total_revenue);
|
||||
$('statExpense').textContent = fmtMoney(d.total_expense);
|
||||
const surplusEl = $('statSurplus');
|
||||
surplusEl.textContent = fmtMoney(d.surplus_deficit);
|
||||
surplusEl.className = 'stat-value ' + (d.surplus_deficit >= 0 ? 'positive' : 'negative');
|
||||
$('donorList').innerHTML = d.donor_names.map(n => `<div class="donor-chip">${n}</div>`).join('');
|
||||
$('resultCard').classList.add('visible');
|
||||
} else {
|
||||
|
|
|
|||
Loading…
Reference in New Issue