Nest Category Summary three levels: Account > Category > Project Code

Final structure, after two prior attempts (Account-only, then
Category-only) didn't match what was actually wanted: Account is now
the outer grouping (bold subtotal row, sorted ascending by account
number - resolving the "account sequence jumps around" issue directly,
since account is the primary sort key rather than something to
reorder categories by), Category is a second bold subtotal level
nested within each account (sorted alphabetically, SUMs its own detail
rows), and Project Code remains the leaf-level sort/display column. A
category spanning more than one account (e.g. "Planeterra Program
Costs - Administration" under both 68010 and 68030) now correctly gets
its own separate subtotal block under each account, rather than being
merged into one flat block.

Verified with the same SUMIFS/SUMIF simulator built for the previous
formula rewrite - resolved every formula against the actual embedded
source-sheet data, including account and category subtotals nesting
correctly. All totals unchanged (this is purely a row layout/grouping
change): revenue 5,338,866.02 / expense 3,743,572.26 /
surplus 1,595,293.76 / balance_check 0.00.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
JasonFraser 2026-08-25 16:38:33 -04:00
parent 091928eea0
commit 462e67af41
1 changed files with 58 additions and 46 deletions

View File

@ -263,67 +263,79 @@ def _sumifs_expr(sheet_name, amount_col_letter, account, category, project_code)
def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, number_format,
source_sheet_name, flip_sign):
"""
Write one section (Revenue or Expenses): a bold subtotal row per
category (SUM formula over that category's own detail rows), sorted
alphabetically, then its detail rows sorted by account number,
strategic area, and full project code. Canada/US cells are live
SUMIFS formulas against source_sheet_name rather than precomputed
values. Returns (list of category-subtotal row numbers, next free
row, section Canada/US raw totals - the raw totals are still
computed in Python from df, for the reconciliation check and API
response, independent of what the formulas themselves resolve to).
Write one section (Revenue or Expenses), nested three levels deep:
Account (bold subtotal row, sorted ascending by account number) ->
Category (bold subtotal row within that account, sorted
alphabetically) -> detail rows (sorted by strategic area then full
project code). Canada/US detail cells are live SUMIFS formulas
against source_sheet_name rather than precomputed values; category
subtotals SUM their own detail rows, and each account subtotal SUMs
its own category subtotals. Returns (list of account-subtotal row
numbers, next free row, section Canada/US raw totals - the raw
totals are still computed in Python from df, for the reconciliation
check and API response, independent of what the formulas themselves
resolve to).
"""
row = start_row
subtotal_rows = []
account_subtotal_rows = []
canada_total = us_total = 0.0
if df.empty:
return subtotal_rows, row, 0.0, 0.0
return account_subtotal_rows, row, 0.0, 0.0
# Categories are ordered by their lowest account number (ascending),
# not alphabetically - so the account-number sequence a reader sees
# scrolling down the section is monotonic, not just ascending within
# each category block. Ties (categories sharing the same lowest
# account) fall back to alphabetical category order.
category_order = df.groupby("category")["account"].min().sort_values(kind="stable").index.tolist()
for category in category_order:
cat_df = df[df["category"] == category].sort_values(["account", "slob", "project_code"])
first_row = row + 1 # detail rows start after this category's own subtotal row
subtotal_row = row
for account in sorted(df["account"].unique()):
acct_df = df[df["account"] == account]
account_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', r['account'], category, r['project_code'])}"
us_formula = f"={sign}{_sumifs_expr(source_sheet_name, 'E', r['account'], category, r['project_code'])}"
category_subtotal_rows = []
_write_cell(ws, row, 1, r["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
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
last_row = row - 1
_write_cell(ws, subtotal_row, 2, category, bold=True)
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'])}"
_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=first_row, column=col).column_letter
c = ws.cell(row=subtotal_row, column=col, value=f"=SUM({letter}{first_row}:{letter}{last_row})")
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
subtotal_rows.append(subtotal_row)
account_subtotal_rows.append(account_subtotal_row)
return subtotal_rows, row, round(canada_total, 2), round(us_total, 2)
return account_subtotal_rows, row, round(canada_total, 2), round(us_total, 2)
def build_category_summary_sheet(wb, revenue_df, expense_df, source_totals, report_date, title,