210 lines
7.7 KiB
Python
210 lines
7.7 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")
|
|
|
|
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)
|