Collapse 70000+ accounts to Account>Category, add Project Costs/Net Revenues

Two changes drawn from a closer re-read of the reference template's
expense section:

- Accounts 70000 and up (Wages, Benefits, Occupancy, Travel, etc.) no
  longer break out by Project Code - one row per category, combining
  every project it was posted against (2-criteria SUMIFS: Account +
  Category, no Project). The three "Project Costs" accounts
  (68010/68020/68030) keep the full Account -> Category -> Project
  Code breakdown, since those are the accounts genuinely tied to
  specific donor projects.
- "Project Costs" (68010+68020+68030's account subtotals) and "Net
  Revenues" (Total Revenue - Project Costs) are now inserted
  immediately after the 68030 block, matching the reference template.
  Neither feeds into the account-subtotal list Total Expenses sums
  from, so the three accounts aren't double-counted.

Verified: every pre-existing total is byte-for-byte unchanged (this is
a pure display/grouping change, not a data change) - revenue
5,338,866.02 / expense 3,743,572.26 / surplus 1,595,293.76 /
balance_check 0.00 - and the new Project Costs (2,990,695.99) / Net
Revenues (2,348,170.03) figures were independently resolved via the
SUMIFS/SUM simulator and check out arithmetically
(5,338,866.02 - 2,990,695.99 = 2,348,170.03).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
JasonFraser 2026-08-25 16:49:59 -04:00
parent 462e67af41
commit e2a798600b
1 changed files with 115 additions and 29 deletions

View File

@ -260,8 +260,33 @@ def _sumifs_expr(sheet_name, amount_col_letter, account, category, project_code)
)
def _sumifs_expr_no_project(sheet_name, amount_col_letter, account, category):
"""
Same as _sumifs_expr but without the Project criterion - used for
accounts that aren't broken out by project (70000 and up), where one
row per category already covers every project it was posted against.
"""
cat_crit = '""' if category == "(Uncategorized)" else f'"{_excel_str(category)}"'
acct_crit = f'"{_excel_str(account)}"'
return (
f"SUMIFS('{sheet_name}'!{amount_col_letter}:{amount_col_letter},"
f"'{sheet_name}'!A:A,{acct_crit},"
f"'{sheet_name}'!C:C,{cat_crit})"
)
# Accounts that get the full Account -> Category -> Project Code
# breakdown. Everything else (70000 and up) is Account -> Category only -
# no per-project detail rows, matching the reference template.
PROJECT_LEVEL_ACCOUNT_CODES = {"43000", "48000", "68010", "68020", "68030"}
# The three "Project Costs" accounts specifically - summed into a
# "Project Costs" subtotal, then "Net Revenues" (Total Revenue - Project
# Costs), right after the 68030 block, matching the reference template.
PROJECT_COST_ACCOUNT_CODES = ("68010", "68020", "68030")
def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, number_format,
source_sheet_name, flip_sign):
source_sheet_name, flip_sign, total_revenue_row=None):
"""
Write one section (Revenue or Expenses), nested three levels deep:
Account (bold subtotal row, sorted ascending by account number) ->
@ -278,6 +303,7 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu
"""
row = start_row
account_subtotal_rows = []
project_cost_rows = []
canada_total = us_total = 0.0
if df.empty:
@ -285,27 +311,68 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu
for account in sorted(df["account"].unique()):
acct_df = df[df["account"] == account]
account_code = account.split(":")[0]
account_subtotal_row = row
row += 1
category_subtotal_rows = []
if account_code in PROJECT_LEVEL_ACCOUNT_CODES:
# Full Account -> Category -> Project Code breakdown.
category_subtotal_rows = []
for category in sorted(acct_df["category"].unique()):
cat_df = acct_df[acct_df["category"] == category].sort_values(["slob", "project_code"])
cat_first_row = row + 1 # detail rows start after this category's own subtotal row
cat_subtotal_row = row
row += 1
for category in sorted(acct_df["category"].unique()):
cat_df = acct_df[acct_df["category"] == category].sort_values(["slob", "project_code"])
cat_first_row = row + 1 # detail rows start after this category's own subtotal row
cat_subtotal_row = row
row += 1
for _, r in cat_df.iterrows():
canada = round(r["canada"], 2)
us = round(r["us"], 2)
sign = "-" if flip_sign else ""
canada_formula = f"={sign}{_sumifs_expr(source_sheet_name, 'D', account, category, r['project_code'])}"
us_formula = f"={sign}{_sumifs_expr(source_sheet_name, 'E', account, category, r['project_code'])}"
for _, r in cat_df.iterrows():
canada = round(r["canada"], 2)
us = round(r["us"], 2)
_write_cell(ws, row, 1, account)
_write_cell(ws, row, 2, category)
_write_cell(ws, row, 3, r["project_code"])
c = ws.cell(row=row, column=canada_col, value=canada_formula)
c.font, c.number_format = REGULAR_FONT, number_format
c = ws.cell(row=row, column=us_col, value=us_formula)
c.font, c.number_format = REGULAR_FONT, number_format
c = ws.cell(row=row, column=total_col, value=f"={ws.cell(row=row, column=canada_col).coordinate}+{ws.cell(row=row, column=us_col).coordinate}+{ws.cell(row=row, column=total_col - 1).coordinate}")
c.font = REGULAR_FONT
c.number_format = number_format
canada_total += canada
us_total += us
row += 1
cat_last_row = row - 1
_write_cell(ws, cat_subtotal_row, 2, category, bold=True)
for col in (canada_col, us_col, total_col):
letter = ws.cell(row=cat_first_row, column=col).column_letter
c = ws.cell(row=cat_subtotal_row, column=col, value=f"=SUM({letter}{cat_first_row}:{letter}{cat_last_row})")
c.font = BOLD_FONT
c.number_format = number_format
category_subtotal_rows.append(cat_subtotal_row)
_write_cell(ws, account_subtotal_row, 1, account, bold=True)
for col in (canada_col, us_col, total_col):
letter = ws.cell(row=account_subtotal_row, column=col).column_letter
formula = "=" + "+".join(f"{letter}{r}" for r in category_subtotal_rows)
c = ws.cell(row=account_subtotal_row, column=col, value=formula)
c.font = BOLD_FONT
c.number_format = number_format
else:
# 70000 and up: Account -> Category only, no per-project detail -
# one row per category, combining every project it was posted to.
cat_totals = acct_df.groupby("category")[["canada", "us"]].sum()
category_rows = []
for category in sorted(acct_df["category"].unique()):
sign = "-" if flip_sign else ""
canada_formula = f"={sign}{_sumifs_expr(source_sheet_name, 'D', account, category, r['project_code'])}"
us_formula = f"={sign}{_sumifs_expr(source_sheet_name, 'E', account, category, r['project_code'])}"
canada_formula = f"={sign}{_sumifs_expr_no_project(source_sheet_name, 'D', account, category)}"
us_formula = f"={sign}{_sumifs_expr_no_project(source_sheet_name, 'E', account, category)}"
_write_cell(ws, row, 1, account)
_write_cell(ws, row, 2, category)
_write_cell(ws, row, 3, r["project_code"])
c = ws.cell(row=row, column=canada_col, value=canada_formula)
c.font, c.number_format = REGULAR_FONT, number_format
c = ws.cell(row=row, column=us_col, value=us_formula)
@ -313,27 +380,46 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu
c = ws.cell(row=row, column=total_col, value=f"={ws.cell(row=row, column=canada_col).coordinate}+{ws.cell(row=row, column=us_col).coordinate}+{ws.cell(row=row, column=total_col - 1).coordinate}")
c.font = REGULAR_FONT
c.number_format = number_format
canada_total += canada
us_total += us
canada_total += round(cat_totals.loc[category, "canada"], 2)
us_total += round(cat_totals.loc[category, "us"], 2)
category_rows.append(row)
row += 1
cat_last_row = row - 1
_write_cell(ws, cat_subtotal_row, 2, category, bold=True)
_write_cell(ws, account_subtotal_row, 1, account, bold=True)
first_r, last_r = category_rows[0], category_rows[-1]
for col in (canada_col, us_col, total_col):
letter = ws.cell(row=cat_first_row, column=col).column_letter
c = ws.cell(row=cat_subtotal_row, column=col, value=f"=SUM({letter}{cat_first_row}:{letter}{cat_last_row})")
letter = ws.cell(row=account_subtotal_row, column=col).column_letter
c = ws.cell(row=account_subtotal_row, column=col, value=f"=SUM({letter}{first_r}:{letter}{last_r})")
c.font = BOLD_FONT
c.number_format = number_format
category_subtotal_rows.append(cat_subtotal_row)
_write_cell(ws, account_subtotal_row, 1, account, bold=True)
for col in (canada_col, us_col, total_col):
letter = ws.cell(row=account_subtotal_row, column=col).column_letter
formula = "=" + "+".join(f"{letter}{r}" for r in category_subtotal_rows)
c = ws.cell(row=account_subtotal_row, column=col, value=formula)
c.font = BOLD_FONT
c.number_format = number_format
account_subtotal_rows.append(account_subtotal_row)
if account_code in PROJECT_COST_ACCOUNT_CODES:
project_cost_rows.append(account_subtotal_row)
# Right after the 68030 block: a "Project Costs" subtotal (68010 +
# 68020 + 68030) and "Net Revenues" (Total Revenue - Project
# Costs), matching the reference template. Neither feeds into
# account_subtotal_rows, so Total Expenses (summed from that list)
# isn't double-counting the three accounts they roll up.
if account_code == "68030" and total_revenue_row is not None:
project_costs_row = row
_write_cell(ws, row, 1, "Project Costs", bold=True)
for col in (canada_col, us_col, total_col):
letter = ws.cell(row=row, column=col).column_letter
formula = "=" + "+".join(f"{letter}{r}" for r in project_cost_rows)
c = ws.cell(row=row, column=col, value=formula)
c.font = BOLD_FONT
c.number_format = number_format
row += 1
_write_cell(ws, row, 1, "Net Revenues", bold=True)
for col in (canada_col, us_col, total_col):
letter = ws.cell(row=row, column=col).column_letter
c = ws.cell(row=row, column=col, value=f"={letter}{total_revenue_row}-{letter}{project_costs_row}")
c.font = BOLD_FONT
c.number_format = number_format
row += 2
return account_subtotal_rows, row, round(canada_total, 2), round(us_total, 2)
@ -377,7 +463,7 @@ def build_category_summary_sheet(wb, revenue_df, expense_df, source_totals, repo
row += 1
exp_subtotals, row, exp_canada, exp_us = _write_category_section(
ws, row, expense_df, CANADA_COL, US_COL, TOTAL_COL, number_format,
EXPENSE_SHEET_NAME, flip_sign=False,
EXPENSE_SHEET_NAME, flip_sign=False, total_revenue_row=total_revenue_row,
)
total_expenses_row = row