import os, csv from datetime import datetime import pandas as pd import openpyxl from openpyxl.styles import Font ACCOUNT_MAP_PATH = os.path.join(os.path.dirname(__file__), "balance_sheet_account_map.csv") REVENUE_ACCOUNT_CODES = ("43000", "48000") # Same expense scope as the donor report - see that tool's logic.py for why # this covers all P&L expense accounts rather than just "project cost" ones. EXPENSE_ACCOUNT_CODES = ( "68010", "68020", "68030", "70000", "70010", "70020", "70030", "71060", "72000", "72100", "72300", "72400", "72600", "72800", "72900", "78000", "79000", "81000", "82000", ) REVENUE_SHEET_NAME = "Revenue TB" EXPENSE_SHEET_NAME = "Expense TB" # Accounts that get the full Account -> Category -> Project Code # breakdown, positioned ahead of the "Project Costs" subtotal. Everything # else (68020 included) is Account -> Category only, no per-project detail # rows, and is positioned after "Net Revenues" alongside 70000 and up - # matching the reference template. PROJECT_LEVEL_ACCOUNT_CODES = {"43000", "48000", "68010", "68030"} # The two "Project Costs" accounts specifically - summed into a # "Project Costs" subtotal, then "Net Revenues" (Total Revenue - Project # Costs), right after the last project-level account, matching the # reference template. PROJECT_COST_ACCOUNT_CODES = ("68010", "68030") 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) # 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);_(* "-"??_);_(@_)' ACCOUNTING_FORMAT_CENTS = '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)' RECONCILE_TOLERANCE = 0.01 def _load_account_map(path=ACCOUNT_MAP_PATH): """ Read the Balance Sheet account-code -> line-item mapping fresh from balance_sheet_account_map.csv on every call, same bind-mounted-CSV pattern as the other tools' lookup tables. Returns {line_item: {"section": ..., "codes": [(code, sign), ...]}}, with line items in first-seen CSV order. """ mapping = {} if not os.path.exists(path): return mapping with open(path, newline="", encoding="utf-8") as f: for row in csv.DictReader(f): line_item = row.get("line_item") if not line_item: continue entry = mapping.setdefault(line_item, {"section": row.get("section"), "codes": []}) entry["codes"].append((row.get("account_code", "").strip(), int(row.get("sign", 1)))) return mapping def classify_trial_balance_file(df): """Revenue and expense trial balance exports share every column except the category one - detect which is which by that column.""" cols = set(df.columns) if {"Ledger Account", "Project", "Planeterra Foundation", "Revenue Category"} <= cols: return "revenue" if {"Ledger Account", "Project", "Planeterra Foundation", "Spend Category"} <= cols: return "expense" return None def full_file_balance(tb_df): """Sum every row's combined-entity value across the WHOLE file - a complete, correctly-exported trial balance nets to zero. Same integrity check as the donor report, duplicated here since this tool is deliberately self-contained.""" combined = tb_df["Planeterra Foundation"].fillna(0) + tb_df["Planeterra International Foundation Ltd"].fillna(0) return round(combined.sum(), 2) def extract_slob(project): """Pull just the strategic-area segment (e.g. 'C&B') out of a Project string, for sort order only - the full string is always what's displayed in the Project Code column.""" if not project or not str(project).strip(): return "" parts = str(project).split(" - ") 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 _canonicalize_text(series): """ Collapse case/whitespace-only variants of the same text (e.g. "OffSite Meetings" vs "Offsite Meetings") to a single canonical label, chosen as the most frequent original casing for that text (ties go to whichever sorts first, for determinism). This matters because SUMIFS/SUMIF text criteria in Excel/Google Sheets match case-insensitively: if two distinct-case variants were left as separate groupby rows, each would get its own SUMIFS formula, and each formula would sum BOTH variants' source rows - silently double-counting the overlap. Canonicalizing before grouping keeps one row per case-insensitive value, so the live formula matches only that value. """ stripped = series.astype(str).str.strip() norm = stripped.str.lower() canonical = stripped.groupby(norm).agg(lambda s: sorted(s.value_counts().items(), key=lambda kv: (-kv[1], kv[0]))[0][0]) return norm.map(canonical) def _assert_no_case_collisions(df, cols, context): """ Defensive regression check for the case-insensitive SUMIFS bug that _canonicalize_text fixes: verify no two distinct combinations of `cols` normalize (strip + lowercase) to the same key. A violation means canonicalization missed something and the live SUMIFS/SUMIF formulas for these rows would silently double-count each other once opened in Excel/Sheets - exactly what happened with "OffSite Meetings" vs "Offsite Meetings" under account 72300, which the old Python-only reconciliation check (grouped total vs. source total - mathematically equal no matter how the rows are labeled) could never have caught. Raises rather than shipping a workbook that won't reconcile once its formulas are actually evaluated. """ tmp = df[cols].copy() norm_cols = [] for c in cols: nc = f"{c}__norm" tmp[nc] = tmp[c].astype(str).str.strip().str.lower() norm_cols.append(nc) for _, g in tmp.groupby(norm_cols): distinct = g[cols].drop_duplicates() if len(distinct) > 1: raise ValueError( f"{context}: found values that differ only by case/whitespace " f"and would collide under Excel/Sheets' case-insensitive " f"SUMIFS matching: {distinct.to_dict('records')}. Fix the " f"source data (or extend _canonicalize_text if this is a " f"legitimate new case) before generating the report." ) 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 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 = {} for key, df, codes, cat_col, flip in [ ("revenue", revenue_df, REVENUE_ACCOUNT_CODES, "Revenue Category", True), ("expense", expense_df, EXPENSE_ACCOUNT_CODES, "Spend Category", False), ]: d = df.copy() d = d[d["Ledger Account"].astype(str).str.strip().str.startswith(codes)] d["account"] = _canonicalize_text(d["Ledger Account"]) d["category"] = _canonicalize_text(d[cat_col].fillna("(Uncategorized)")) d["project_code"] = _canonicalize_text(d["Project"].fillna("(No project)")) d["slob"] = d["Project"].apply(extract_slob) canada = d["Planeterra Foundation"].fillna(0) us = d["Planeterra International Foundation Ltd"].fillna(0) if flip: canada, us = -canada, -us d["canada"] = canada d["us"] = us # Source totals, independent of the groupby below, for the # reconciliation check. source_totals[f"{key}_canada"] = round(canada.sum(), 2) source_totals[f"{key}_us"] = round(us.sum(), 2) grouped = ( d.groupby(["account", "category", "slob", "project_code"], as_index=False) [["canada", "us"]].sum() ) grouped = grouped[(grouped["canada"].abs() >= 0.005) | (grouped["us"].abs() >= 0.005)] grouped = grouped.reset_index(drop=True) # Two granularities, because the two account groups use different # SUMIFS criteria: project-level accounts key on all three columns, # collapsed accounts (68020, 70000 and up) key on account+category # only (see PROJECT_LEVEL_ACCOUNT_CODES / _write_category_section). _assert_no_case_collisions(grouped, ["account", "category", "project_code"], f"{key} category summary") _assert_no_case_collisions(grouped, ["account", "category"], f"{key} category summary (account+category)") results[key] = grouped return results, source_totals 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 - 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() full = revenue_tb_df.copy() full["_code"] = full["Ledger Account"].astype(str).str.split(":", n=1).str[0].str.strip() full["_combined"] = full["Planeterra Foundation"].fillna(0) + full["Planeterra International Foundation Ltd"].fillna(0) by_code = full.groupby("_code")["_combined"].sum() values = {} for line_item, entry in account_map.items(): total = 0.0 for code, sign in entry["codes"]: total += sign * by_code.get(code, 0) values[line_item] = round(total, 2) values.setdefault("Deferred Revenue", 0.0) values["Unrestricted"] = round(values.get("Unrestricted", 0.0) + net_income, 2) total_current_assets = round( values.get("Cash", 0) + values.get("Accounts receivable", 0) + values.get("Prepaids", 0), 2 ) total_assets = round( total_current_assets + values.get("Due from related companies", 0) + values.get("Capital Assets", 0), 2 ) total_current_liabilities = round( values.get("Due to related companies", 0) + values.get("Accrued Liabilities", 0) + values.get("Accounts Payable", 0) + values.get("Deferred Revenue", 0), 2 ) total_net_assets = round(values.get("Unrestricted", 0), 2) total_liab_and_net_assets = round(total_current_liabilities + total_net_assets, 2) balance_check = round(total_liab_and_net_assets - total_assets, 2) return { "values": values, "total_current_assets": total_current_assets, "total_assets": total_assets, "total_current_liabilities": total_current_liabilities, "total_net_assets": total_net_assets, "total_liab_and_net_assets": total_liab_and_net_assets, "balance_check": balance_check, } def _write_cell(ws, row, col, value, bold=False, number_format=None, italic=False): c = ws.cell(row=row, column=col, value=value) c.font = Font(name=FONT_NAME, size=FONT_SIZE, bold=bold, italic=italic) if number_format: c.number_format = number_format return c 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 _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})" ) def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, number_format, source_sheet_name, flip_sign, total_revenue_row=None): """ Write one section (Revenue or Expenses), nested three levels deep: Account (bold subtotal row, ascending by account number within two groups - PROJECT_LEVEL_ACCOUNT_CODES first, everything else after - see the Project Costs/Net Revenues insertion below) -> 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 account_subtotal_rows = [] project_cost_rows = [] canada_total = us_total = 0.0 if df.empty: return account_subtotal_rows, row, 0.0, 0.0 # Project-level accounts (full Account -> Category -> Project Code # breakdown) are always written first, ascending among themselves, so # the "Project Costs"/"Net Revenues" subtotal can sit right after them. # Everything else (68020 included) follows, ascending among itself - # physically after Net Revenues, not in its raw numeric position. all_accounts = sorted(df["account"].unique()) project_accounts = [a for a in all_accounts if a.split(":")[0] in PROJECT_LEVEL_ACCOUNT_CODES] other_accounts = [a for a in all_accounts if a.split(":")[0] not in PROJECT_LEVEL_ACCOUNT_CODES] last_project_account = project_accounts[-1] if project_accounts else None for account in project_accounts + other_accounts: acct_df = df[df["account"] == account] account_code = account.split(":")[0] account_subtotal_row = row row += 1 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 _, 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=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_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, 2, category) 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 += round(cat_totals.loc[category, "canada"], 2) us_total += round(cat_totals.loc[category, "us"], 2) category_rows.append(row) row += 1 _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=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 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 last project-level account (68010, 68030): a # "Project Costs" subtotal 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 accounts they roll up. if account == last_project_account 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) def build_category_summary_sheet(wb, revenue_df, expense_df, source_totals, report_date, title, number_format=ACCOUNTING_FORMAT_WHOLE): ws = wb.create_sheet("1. Summary (Manual)") for col, width in zip("ABCDEFGH", (32, 20, 34, 15, 15, 15, 15, 15)): ws.column_dimensions[col].width = width _write_cell(ws, 1, 1, title, bold=True) _write_cell(ws, 2, 1, f"Category Summary — {report_date}", bold=True) header_row = 4 headers = ["Account", "Category", "Project Code", "Canada YTD", "US YTD", "Consolidation Adjustments", "Total YTD", "Budget"] for col, label in enumerate(headers, start=1): _write_cell(ws, header_row, col, label, bold=True) CANADA_COL, US_COL, ADJ_COL, TOTAL_COL, BUDGET_COL = 4, 5, 6, 7, 8 row = header_row + 1 _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, REVENUE_SHEET_NAME, flip_sign=True, ) total_revenue_row = row _write_cell(ws, row, 1, "Total Revenue", 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 rev_subtotals) if rev_subtotals else 0 c = ws.cell(row=row, column=col, value=formula) c.font = BOLD_FONT c.number_format = number_format row += 2 _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, EXPENSE_SHEET_NAME, flip_sign=False, total_revenue_row=total_revenue_row, ) total_expenses_row = row _write_cell(ws, row, 1, "Total Expenses", 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 exp_subtotals) if exp_subtotals else 0 c = ws.cell(row=row, column=col, value=formula) c.font = BOLD_FONT c.number_format = number_format row += 2 surplus_row = row _write_cell(ws, row, 1, "Surplus/(Deficit)", 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}{total_expenses_row}") c.font = BOLD_FONT c.number_format = number_format row += 3 # ── Reconciliation back to the uploaded files ────────────────────────── report_canada = round(rev_canada + exp_canada, 2) report_us = round(rev_us + exp_us, 2) source_canada = round(source_totals["revenue_canada"] + source_totals["expense_canada"], 2) source_us = round(source_totals["revenue_us"] + source_totals["expense_us"], 2) # bool(...) here matters: comparisons on pandas-derived floats produce # numpy.bool_, which isn't JSON-serializable (unlike native Python bool). canada_ok = bool(abs(report_canada - source_canada) < RECONCILE_TOLERANCE) us_ok = bool(abs(report_us - source_us) < RECONCILE_TOLERANCE) _write_cell(ws, row, 1, "Reconciliation to uploaded files", bold=True) row += 1 _write_cell(ws, row, 1, "Canada — report total"); _write_cell(ws, row, 2, report_canada, number_format=number_format) _write_cell(ws, row, 3, "Canada — source file total"); _write_cell(ws, row, 4, source_canada, number_format=number_format) _write_cell(ws, row, 5, "MATCH" if canada_ok else "MISMATCH", bold=True) row += 1 _write_cell(ws, row, 1, "US — report total"); _write_cell(ws, row, 2, report_us, number_format=number_format) _write_cell(ws, row, 3, "US — source file total"); _write_cell(ws, row, 4, source_us, number_format=number_format) _write_cell(ws, row, 5, "MATCH" if us_ok else "MISMATCH", bold=True) # Report vs. source figures for the three headline metrics (Total # Income, Total Expenses, Surplus/Deficit) - the "report" side is what # the 1. Summary (Manual)/Balance Sheet (FS) sheets show (and what the # Balance Sheet's Net Income term is built from); the "source" side is # summed directly from the uploaded files, independent of any # grouping/labeling, so the UI can show the two side by side. revenue_total = round(rev_canada + rev_us, 2) expense_total = round(exp_canada + exp_us, 2) source_revenue_total = round(source_totals["revenue_canada"] + source_totals["revenue_us"], 2) source_expense_total = round(source_totals["expense_canada"] + source_totals["expense_us"], 2) surplus_deficit = round(revenue_total - expense_total, 2) source_surplus_deficit = round(source_revenue_total - source_expense_total, 2) return { "revenue_total": revenue_total, "expense_total": expense_total, "surplus_deficit": surplus_deficit, "source_revenue_total": source_revenue_total, "source_expense_total": source_expense_total, "source_surplus_deficit": source_surplus_deficit, "revenue_match": bool(abs(revenue_total - source_revenue_total) < RECONCILE_TOLERANCE), "expense_match": bool(abs(expense_total - source_expense_total) < RECONCILE_TOLERANCE), "surplus_match": bool(abs(surplus_deficit - source_surplus_deficit) < RECONCILE_TOLERANCE), "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, } BALANCE_SHEET_LAYOUT = [ ("Assets", True, None), ("Cash", False, "Cash"), ("Accounts receivable", False, "Accounts receivable"), ("Prepaids", False, "Prepaids"), (None, False, "__total_current_assets__"), (None, False, None), # blank spacer row ("Due from related companies", False, "Due from related companies"), ("Capital Assets", False, "Capital Assets"), (None, False, "__total_assets__"), (None, False, None), ("Liabilities", True, None), ("Current Liabilities", False, None), ("Due to related companies", False, "Due to related companies"), ("Accrued Liabilities", False, "Accrued Liabilities"), ("Accounts Payable", False, "Accounts Payable"), ("Deferred Revenue", False, "Deferred Revenue"), (None, False, "__total_current_liabilities__"), (None, False, None), ("Net Assets", True, None), ("Unrestricted", False, "Unrestricted"), (None, False, "__total_net_assets__"), (None, False, "__total_liab_and_net_assets__"), (None, False, "__balance_check__"), ] 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. 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 (FS)") ws.column_dimensions["A"].width = 32 ws.column_dimensions["B"].width = 18 _write_cell(ws, 1, 1, title, bold=True) _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"'1. Summary (Manual)'!D{category_summary_refs['total_revenue_row']}" f"+'1. Summary (Manual)'!E{category_summary_refs['total_revenue_row']}" f"-'1. Summary (Manual)'!D{category_summary_refs['total_expenses_row']}" f"-'1. Summary (Manual)'!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__": 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) 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__": 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__": 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) 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) 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: 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 def build_report_workbook(revenue_df, expense_df, output_path, sections, report_date, title, use_cents=False): """ sections: {"category_summary": bool, "balance_sheet": bool} Returns a summary dict for the API response / results screen. """ number_format = ACCOUNTING_FORMAT_CENTS if use_cents else ACCOUNTING_FORMAT_WHOLE wb = openpyxl.Workbook() wb.remove(wb.active) # openpyxl writes formula cells with no cached result and leaves # calcMode unset - fullCalcOnLoad="1" (openpyxl's default) forces a # full recalc the first time the file is opened, which is why values # show correctly on first view, but an unset calcMode is ambiguous to # some apps rather than reliably read as automatic. Set both # explicitly so edits to the TB sheets keep recalculating the Summary/ # Balance Sheet formulas afterwards too, not just on that first open. wb.calculation.calcMode = "auto" wb.calculation.fullCalcOnLoad = True summary = {"reconciled": True} category_summary_refs = None if sections.get("category_summary", True): grouped, source_totals = process_category_summary(revenue_df, expense_df) cat_summary = build_category_summary_sheet( wb, grouped["revenue"], grouped["expense"], source_totals, report_date, title, number_format=number_format, ) summary["revenue_total"] = cat_summary["revenue_total"] summary["expense_total"] = cat_summary["expense_total"] summary["surplus_deficit"] = cat_summary["surplus_deficit"] summary["reconciled"] = ( summary["reconciled"] and cat_summary["reconciled"] and cat_summary["revenue_match"] and cat_summary["expense_match"] and cat_summary["surplus_match"] ) summary["reconciliation"] = { "canada": {"report": cat_summary["report_canada"], "source": cat_summary["source_canada"]}, "us": {"report": cat_summary["report_us"], "source": cat_summary["source_us"]}, } # Report (1. Summary (Manual)/Balance Sheet (FS)) vs. source-file # figures for the three headline metrics, so the UI can show them # side by side rather than only the combined Canada/US check above. summary["headline_comparison"] = { "income": { "report": cat_summary["revenue_total"], "source": cat_summary["source_revenue_total"], "match": cat_summary["revenue_match"], }, "expenses": { "report": cat_summary["expense_total"], "source": cat_summary["source_expense_total"], "match": cat_summary["expense_match"], }, "surplus": { "report": cat_summary["surplus_deficit"], "source": cat_summary["source_surplus_deficit"], "match": cat_summary["surplus_match"], }, } 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. grouped, _ = process_category_summary(revenue_df, expense_df) rev_total = round(grouped["revenue"]["canada"].sum() + grouped["revenue"]["us"].sum(), 2) exp_total = round(grouped["expense"]["canada"].sum() + grouped["expense"]["us"].sum(), 2) net_income = round(rev_total - exp_total, 2) if sections.get("balance_sheet", True): 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