Category subtotal headings + live formulas against embedded source sheets

Two changes, confirmed with the user via concrete preview mockups
before building (avoiding a third wrong guess on the subtotal
structure after the account-grouping change):

- Reverted subtotal/heading grouping from Account back to Category
  (bold subtotal row per category, sorted alphabetically; within a
  category, detail rows sorted by account number then strategic area
  then full project code). Account still shows as the full unsplit
  "code:name" string on every detail row - that part of the account
  change stays, only the grouping key reverted.

- The two uploaded trial balance files are now embedded as their own
  sheets ("Revenue TB", "Expense TB") in the generated workbook, and
  every Category Summary/Balance Sheet cell is a live formula against
  them rather than a precomputed number - directly modeled on
  "1. Summary (Manual)"/"Balance Sheet (FS)"'s own SUMIFS/SUMIF
  formulas:
  - Category Summary detail rows: SUMIFS matching Account+Category+
    Project against the embedded sheet (blank category/project use ""
    criteria, mirroring the template's ISBLANK(...) branches).
  - Balance Sheet lines: SUMIF per mapped account code, wildcard-
    matched ("<code>:*") since the sheet stores code+name together.
    Totals (Total Current Assets, Total Assets, etc.) are formulas
    summing the line-item cells above them, not baked-in numbers.
  - Unrestricted (Net Assets) adds a live cross-sheet reference to
    Category Summary's own Total Revenue/Total Expenses cells for the
    period's Net Income, instead of a Python-computed literal.
  All formulas use only SUM/SUMIF/SUMIFS - no Excel-only functions -
  so the workbook is Google Sheets compatible, not just Excel.

Verified far more rigorously than a cross-check against my own Python
computation this time: wrote a SUMIFS/SUMIF simulator that evaluates
every formula against the actual embedded sheet data (not a
side-channel recomputation), recursively resolving subtotals, grand
totals, and the Balance Sheet's cross-sheet reference. Every result
matches exactly: 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:23:22 -04:00
parent 8f1ffe57c6
commit d0ebc3f995
1 changed files with 184 additions and 43 deletions

View File

@ -16,11 +16,13 @@ EXPENSE_ACCOUNT_CODES = (
"78000", "79000", "81000", "82000",
)
REVENUE_SHEET_NAME = "Revenue TB"
EXPENSE_SHEET_NAME = "Expense TB"
FONT_NAME = "Arial"
FONT_SIZE = 11
REGULAR_FONT = Font(name=FONT_NAME, size=FONT_SIZE, bold=False)
BOLD_FONT = Font(name=FONT_NAME, size=FONT_SIZE, bold=True)
TITLE_FONT = Font(name=FONT_NAME, size=FONT_SIZE, bold=True)
# Matches the accounting number format used in fs.xlsx's Balance Sheet (FS)
# sheet - parens for negative, dash for zero, whole dollars by default.
ACCOUNTING_FORMAT_WHOLE = '_(* #,##0_);_(* (#,##0);_(* "-"??_);_(@_)'
@ -80,17 +82,40 @@ def extract_slob(project):
return parts[1] if len(parts) >= 2 else ""
def _excel_str(s):
"""Escape a string for safe embedding as an exact-match SUMIFS/SUMIF
criteria: double embedded quotes, and tilde-escape wildcard characters
so a literal '*' or '?' in an account/category/project name is never
mistaken for a SUMIFS wildcard."""
s = str(s)
s = s.replace("~", "~~").replace("*", "~*").replace("?", "~?")
return s.replace('"', '""')
def _join_signed_terms(terms_with_sign):
"""terms_with_sign: [(expr, sign), ...]. Joins into 'A + B - C' style
(never 'A+-B') so the formula string is unambiguous."""
if not terms_with_sign:
return "0"
parts = []
for i, (expr, sign) in enumerate(terms_with_sign):
if i == 0:
parts.append(expr if sign > 0 else f"-{expr}")
else:
parts.append((" + " if sign > 0 else " - ") + expr)
return "".join(parts)
def process_category_summary(revenue_df, expense_df):
"""
Build the Category Summary rows: one per (account, category, project
code), Canada/US kept as separate columns (not combined, unlike the
donor report). "account" is the full raw "Ledger Account" string
(code:name together, unsplit) - same treatment as Project Code - and
is the primary grouping/subtotal key, sorted by account number
(string-sorting the full value works here since every code in this
chart of accounts is the same 5-digit width). Returns a dict with
'revenue' and 'expense' DataFrames plus the independently-computed
source totals used for the reconciliation check.
is shown per row but is no longer the grouping/subtotal key (Category
is - see _write_category_section). Returns a dict with 'revenue' and
'expense' DataFrames plus the independently-computed source totals
used for the reconciliation check.
"""
results = {}
source_totals = {}
@ -131,14 +156,18 @@ def process_category_summary(revenue_df, expense_df):
def compute_balance_sheet(revenue_tb_df, expense_tb_df, net_income, account_map=None):
"""
Compute each Balance Sheet line item as the combined (Canada + US)
total of its mapped account codes. Balance Sheet accounts live
outside the revenue/expense ranges entirely, but both uploaded files
are full trial balance exports - the same Balance Sheet rows appear
in both (just tagged with a different category column), so this
reads from ONE of them, not both concatenated, or every account
would be double-counted. net_income (Total Revenue - Total Expense,
combined entities) is added into "Unrestricted" alongside Retained
Earnings/CTA, matching how the source file derives Net Assets.
total of its mapped account codes - the Python-side numbers used for
the balance_check/summary reported to the UI (the workbook's own
cells are live SUMIF formulas instead - see build_balance_sheet_sheet
- so this is an independent cross-check, not what the file displays).
Balance Sheet accounts live outside the revenue/expense ranges
entirely, but both uploaded files are full trial balance exports -
the same Balance Sheet rows appear in both (just tagged with a
different category column), so this reads from ONE of them, not both
concatenated, or every account would be double-counted. net_income
(Total Revenue - Total Expense, combined entities) is added into
"Unrestricted" alongside Retained Earnings/CTA, matching how the
source file derives Net Assets.
"""
if account_map is None:
account_map = _load_account_map()
@ -191,15 +220,58 @@ def _write_cell(ws, row, col, value, bold=False, number_format=None, italic=Fals
return c
def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, number_format):
def write_source_sheet(wb, df, sheet_name):
"""
Dump an uploaded trial balance file into its own sheet, verbatim
(same columns, same order, plain values) - this is what the Category
Summary and Balance Sheet formulas point back at, so the generated
workbook is self-contained and auditable without the original
upload in hand.
"""
ws = wb.create_sheet(sheet_name)
for col_idx, col_name in enumerate(df.columns, start=1):
_write_cell(ws, 1, col_idx, col_name, bold=True)
clean = df.where(pd.notnull(df), None)
for row_idx, row in enumerate(clean.itertuples(index=False), start=2):
for col_idx, val in enumerate(row, start=1):
ws.cell(row=row_idx, column=col_idx, value=val)
for col_idx in range(1, len(df.columns) + 1):
ws.column_dimensions[ws.cell(row=1, column=col_idx).column_letter].width = 22
return ws
def _sumifs_expr(sheet_name, amount_col_letter, account, category, project_code):
"""
A SUMIFS pulling one row-group's amount straight from the raw source
sheet - directly modeled on "1. Summary (Manual)"'s own
sumifs('TB RC & Pr (Manual)'!D:D, ...) formulas. Blank category/
project in the source (our "(Uncategorized)"/"(No project)"
placeholders) match against an empty-string criteria, same as the
template's ISBLANK(...) branches did.
"""
cat_crit = '""' if category == "(Uncategorized)" else f'"{_excel_str(category)}"'
proj_crit = '""' if project_code == "(No project)" else f'"{_excel_str(project_code)}"'
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},"
f"'{sheet_name}'!B:B,{proj_crit})"
)
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
account (SUM formula over that account's own detail rows), sorted by
account number - string-sorting the full "code:name" value works
since every code in this chart of accounts is the same width - then
its detail rows sorted by strategic area then full project code.
Returns (list of account-subtotal row numbers, next free row,
section Canada/US raw totals).
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).
"""
row = start_row
subtotal_rows = []
@ -208,20 +280,26 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu
if df.empty:
return subtotal_rows, row, 0.0, 0.0
for account in sorted(df["account"].unique()):
acct_df = df[df["account"] == account].sort_values(["slob", "project_code"])
first_row = row + 1 # detail rows start after this account's own subtotal row
for category in sorted(df["category"].unique()):
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
row += 1
for _, r in acct_df.iterrows():
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, r["category"])
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'])}"
_write_cell(ws, row, 1, r["account"])
_write_cell(ws, row, 2, category)
_write_cell(ws, row, 3, r["project_code"])
_write_cell(ws, row, canada_col, canada, number_format=number_format)
_write_cell(ws, row, us_col, us, number_format=number_format)
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
@ -230,7 +308,7 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu
row += 1
last_row = row - 1
_write_cell(ws, subtotal_row, 1, account, bold=True)
_write_cell(ws, subtotal_row, 2, category, 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})")
@ -262,7 +340,8 @@ def build_category_summary_sheet(wb, revenue_df, expense_df, source_totals, repo
_write_cell(ws, row, 1, "Revenue", bold=True)
row += 1
rev_subtotals, row, rev_canada, rev_us = _write_category_section(
ws, row, revenue_df, CANADA_COL, US_COL, TOTAL_COL, number_format
ws, row, revenue_df, CANADA_COL, US_COL, TOTAL_COL, number_format,
REVENUE_SHEET_NAME, flip_sign=True,
)
total_revenue_row = row
@ -278,7 +357,8 @@ def build_category_summary_sheet(wb, revenue_df, expense_df, source_totals, repo
_write_cell(ws, row, 1, "Expenses", bold=True)
row += 1
exp_subtotals, row, exp_canada, exp_us = _write_category_section(
ws, row, expense_df, CANADA_COL, US_COL, TOTAL_COL, number_format
ws, row, expense_df, CANADA_COL, US_COL, TOTAL_COL, number_format,
EXPENSE_SHEET_NAME, flip_sign=False,
)
total_expenses_row = row
@ -327,6 +407,8 @@ def build_category_summary_sheet(wb, revenue_df, expense_df, source_totals, repo
"reconciled": canada_ok and us_ok,
"report_canada": report_canada, "source_canada": source_canada,
"report_us": report_us, "source_us": source_us,
"total_revenue_row": total_revenue_row,
"total_expenses_row": total_expenses_row,
}
@ -357,14 +439,19 @@ BALANCE_SHEET_LAYOUT = [
]
def build_balance_sheet_sheet(wb, bs, report_date, title, number_format=ACCOUNTING_FORMAT_WHOLE):
def build_balance_sheet_sheet(wb, bs, net_income, report_date, title, account_map, source_sheet_name,
category_summary_refs=None, number_format=ACCOUNTING_FORMAT_WHOLE):
"""
Fresh sheet matching fs.xlsx's "Balance Sheet (FS)" structure/labels/
fonts (Arial 11, bold section headers), but a single consolidated
(Canada+US combined) column for this period only - the source
file's month-over-month/prior-year comparison columns are static
historical snapshots that can't be regenerated from a single trial
balance upload.
balance upload. Every line and total is a live formula (SUMIF against
source_sheet_name, inspired directly by "Balance Sheet (FS)"'s own
sumif('TB RC & Pr (Manual)'!$A:$A, ...) formulas), not a precomputed
value - `bs` (from compute_balance_sheet) is only used as a fallback
for lines with no account-map entry (e.g. Deferred Revenue).
"""
ws = wb.create_sheet("Balance Sheet")
ws.column_dimensions["A"].width = 32
@ -374,30 +461,70 @@ def build_balance_sheet_sheet(wb, bs, report_date, title, number_format=ACCOUNTI
_write_cell(ws, 2, 1, "Balance Sheet (Consolidated)", bold=True)
_write_cell(ws, 3, 1, f"As of {report_date}", bold=True)
if category_summary_refs:
net_income_formula = (
f"'Category Summary'!D{category_summary_refs['total_revenue_row']}"
f"+'Category Summary'!E{category_summary_refs['total_revenue_row']}"
f"-'Category Summary'!D{category_summary_refs['total_expenses_row']}"
f"-'Category Summary'!E{category_summary_refs['total_expenses_row']}"
)
else:
net_income_formula = None
row_by_key = {}
row = 5
for label, is_section, key in BALANCE_SHEET_LAYOUT:
if label is None and key is None:
row += 1
continue
if key == "__total_current_assets__":
_write_cell(ws, row, 2, bs["total_current_assets"], bold=True, number_format=number_format)
f = "=" + "+".join(f"B{row_by_key[k]}" for k in ("Cash", "Accounts receivable", "Prepaids"))
c = ws.cell(row=row, column=2, value=f); c.font = BOLD_FONT; c.number_format = number_format
elif key == "__total_assets__":
_write_cell(ws, row, 1, "Total Assets", bold=True)
_write_cell(ws, row, 2, bs["total_assets"], bold=True, number_format=number_format)
tca_row = row_by_key["__total_current_assets__"]
f = "=" + "+".join([f"B{tca_row}"] + [f"B{row_by_key[k]}" for k in ("Due from related companies", "Capital Assets")])
c = ws.cell(row=row, column=2, value=f); c.font = BOLD_FONT; c.number_format = number_format
elif key == "__total_current_liabilities__":
_write_cell(ws, row, 2, bs["total_current_liabilities"], bold=True, number_format=number_format)
f = "=" + "+".join(f"B{row_by_key[k]}" for k in
("Due to related companies", "Accrued Liabilities", "Accounts Payable", "Deferred Revenue"))
c = ws.cell(row=row, column=2, value=f); c.font = BOLD_FONT; c.number_format = number_format
elif key == "__total_net_assets__":
_write_cell(ws, row, 2, bs["total_net_assets"], bold=True, number_format=number_format)
f = f"=B{row_by_key['Unrestricted']}"
c = ws.cell(row=row, column=2, value=f); c.font = BOLD_FONT; c.number_format = number_format
elif key == "__total_liab_and_net_assets__":
_write_cell(ws, row, 1, "Total Liabilities & Net Assets", bold=True)
_write_cell(ws, row, 2, bs["total_liab_and_net_assets"], bold=True, number_format=number_format)
f = f"=B{row_by_key['__total_current_liabilities__']}+B{row_by_key['__total_net_assets__']}"
c = ws.cell(row=row, column=2, value=f); c.font = BOLD_FONT; c.number_format = number_format
elif key == "__balance_check__":
_write_cell(ws, row, 1, "Balance check (Assets − Liabilities & Net Assets, should be 0)", italic=True)
_write_cell(ws, row, 2, bs["balance_check"], italic=True, number_format=number_format)
f = f"=B{row_by_key['__total_liab_and_net_assets__']}-B{row_by_key['__total_assets__']}"
c = ws.cell(row=row, column=2, value=f); c.font = Font(name=FONT_NAME, size=FONT_SIZE, italic=True); c.number_format = number_format
else:
_write_cell(ws, row, 1, label, bold=is_section)
if key is not None:
_write_cell(ws, row, 2, bs["values"].get(key, 0.0), number_format=number_format)
entry = account_map.get(key)
if entry and entry["codes"]:
base = _join_signed_terms(
[(f"SUMIF('{source_sheet_name}'!A:A,\"{code}:*\",'{source_sheet_name}'!{col}:{col})", sign)
for code, sign in entry["codes"] for col in ("D", "E")]
)
if key == "Unrestricted":
# Prefer a live cross-sheet reference to Category
# Summary's own totals; if that section isn't part of
# this run, fall back to the precomputed net_income
# figure passed in.
income_term = f"({net_income_formula})" if net_income_formula else str(net_income)
f = f"={base} + {income_term}"
else:
f = f"={base}"
else:
f = bs["values"].get(key, 0.0)
c = ws.cell(row=row, column=2, value=f)
c.font, c.number_format = REGULAR_FONT, number_format
row_by_key[key] = row
row += 1
return ws
@ -414,6 +541,7 @@ def build_report_workbook(revenue_df, expense_df, output_path, sections, report_
wb.remove(wb.active)
summary = {"reconciled": True}
category_summary_refs = None
if sections.get("category_summary", True):
grouped, source_totals = process_category_summary(revenue_df, expense_df)
@ -430,6 +558,10 @@ def build_report_workbook(revenue_df, expense_df, output_path, sections, report_
"us": {"report": cat_summary["report_us"], "source": cat_summary["source_us"]},
}
net_income = summary["surplus_deficit"]
category_summary_refs = {
"total_revenue_row": cat_summary["total_revenue_row"],
"total_expenses_row": cat_summary["total_expenses_row"],
}
else:
# Balance Sheet still needs Net Income even if Category Summary
# isn't being included in this run's output.
@ -439,11 +571,20 @@ def build_report_workbook(revenue_df, expense_df, output_path, sections, report_
net_income = round(rev_total - exp_total, 2)
if sections.get("balance_sheet", True):
bs = compute_balance_sheet(revenue_df, expense_df, net_income)
build_balance_sheet_sheet(wb, bs, report_date, title, number_format=number_format)
account_map = _load_account_map()
bs = compute_balance_sheet(revenue_df, expense_df, net_income, account_map=account_map)
build_balance_sheet_sheet(
wb, bs, net_income, report_date, title, account_map, REVENUE_SHEET_NAME,
category_summary_refs=category_summary_refs, number_format=number_format,
)
summary["balance_check"] = bs["balance_check"]
summary["balance_sheet_balanced"] = bool(abs(bs["balance_check"]) < RECONCILE_TOLERANCE)
summary["reconciled"] = summary["reconciled"] and summary["balance_sheet_balanced"]
# Bring the two uploaded files in as their own sheets - everything
# above ties back to these via formula rather than a baked-in number.
write_source_sheet(wb, revenue_df, REVENUE_SHEET_NAME)
write_source_sheet(wb, expense_df, EXPENSE_SHEET_NAME)
wb.save(output_path)
return summary