302 lines
11 KiB
Python
302 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)]
|
|
|
|
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[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 - 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):
|
|
"""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
|
|
for code in df["account_code"].unique():
|
|
needed += 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
|
|
|
|
|
|
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 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
|
|
|
|
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
|
|
|
|
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)
|
|
section_total += amount
|
|
row += 1
|
|
cat_last_row = row - 1
|
|
|
|
_write_cell(ws, row, 1, f" {slob_label} Subtotal", bold=True)
|
|
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
|
|
|
|
return subtotal_cells, 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_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 (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)
|