equals-wd-card-expense-proc.../app/tools/donor_report/logic.py

280 lines
11 KiB
Python

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")
# 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
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 full_file_balance(tb_df):
"""
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.
"""
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(account_codes)]
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[category_col].fillna("(Uncategorized)")
raw_amount = df["Planeterra Foundation"].fillna(0)
df["amount"] = -raw_amount if flip_sign else raw_amount
# Grouped by donor -> project code -> category only, deliberately not
# by Ledger Account: the same project code/category can appear under
# more than one GL account (e.g. the same spend category posted to
# two different expense accounts), and showing that as two rows with
# an identical-looking label is exactly the clutter a non-finance
# reader doesn't need - one combined row per (project code, category)
# is the whole point of grouping "by project code".
grouped = (
df.groupby(["donor", "slob", "category"], as_index=False)["amount"]
.sum()
)
# 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"
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 _rows_needed(df):
"""One row per (project code, category) - no header or subtotal rows."""
return len(df)
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(block_start + available, needed - available)
elif needed < available:
ws.delete_rows(block_start + needed, available - needed)
def _write_section(ws, start_row, df):
"""
Write one row per (project code, category), sorted by project code
then category, starting at start_row - a flat, clean list with no
account/subtotal rows breaking it up, so the whole section is one
contiguous range for the section total's SUM formula. Returns
(first_row, last_row) of the written range (None if empty) and this
section's raw total.
"""
if df.empty:
return None, 0.0
row = start_row
section_total = 0.0
for _, r in df.sort_values(["slob", "category"]).iterrows():
amount = round(r["amount"], 2)
slob_label = r["slob"] or "(No project code)"
# Explicitly blank column A - the template's own placeholder text
# ("Donations & Fundraising Revenue", "Disbursement to Projects")
# sits on this first row otherwise, since ws.cell(value=None) is a
# no-op in openpyxl rather than a clear - direct assignment is needed.
ws.cell(row=row, column=1).value = None
_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)
section_total += amount
row += 1
return (start_row, row - 1), round(section_total, 2)
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_range, revenue_total = _write_section(ws, 7, revenue_df)
exp_range, 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=f"=SUM(B{rev_range[0]}:B{rev_range[1]})" if rev_range 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=f"=SUM(B{exp_range[0]}:B{exp_range[1]})" if exp_range 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 (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(set(revenue_grouped["donor"]).union(expense_grouped["donor"]))
total_revenue = 0.0
total_expense = 0.0
written = 0
for donor in donors:
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
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(total_revenue, 2), round(total_expense, 2)