equals-wd-card-expense-proc.../app/tools/financial_reports/logic.py

3016 lines
149 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os, csv, re, shutil, copy
from datetime import datetime
from collections import defaultdict
import pandas as pd
import openpyxl
from openpyxl.styles import Font, Border, Side
from openpyxl.utils import get_column_letter
from openpyxl.comments import Comment
from openpyxl.formatting.rule import CellIsRule
from common import load_gl_dump, GL_AMOUNT_COL, net_gl_lines, build_gl_schedule # noqa: F401 - load_gl_dump re-exported for routes.py
ACCOUNT_MAP_PATH = os.path.join(os.path.dirname(__file__), "balance_sheet_account_map.csv")
BUDGET_KEY_MAP_PATH = os.path.join(os.path.dirname(__file__), "budget_line_key_map.csv")
STORED_BUDGET_PATH = os.path.join(os.path.dirname(__file__), "stored_budget_file.xlsx")
CATEGORY_REASSIGNMENT_MAP_PATH = os.path.join(os.path.dirname(__file__), "category_reassignment_map.csv")
PROJECT_REASSIGNMENT_MAP_PATH = os.path.join(os.path.dirname(__file__), "project_reassignment_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",
)
# 79000/81000 are mechanical FX-revaluation accounts - confirmed for real
# their "category" text is really just whatever unrelated GL entry
# happened to generate the revaluation line (Accrued Vacation, Corporate
# Credit Card Clearing, Wages Salaries Payable, etc), not a real
# categorization. Every row under these two accounts always collapses to
# one category matching the account's own name - a fixed business rule,
# unconditional and not user-editable (see process_category_summary /
# _budget_detail_rows), unlike the reassignment maps below.
FORCED_CATEGORY_BY_ACCOUNT = {
"79000": "Realized Currency Loss/(Gain)",
"81000": "Unrealized Currency Loss/(Gain)",
}
FORCED_CATEGORY_ACCOUNT_CODES = set(FORCED_CATEGORY_BY_ACCOUNT)
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
# Balance Sheet supporting schedules: one per account whose code starts
# with 1 (Assets), 2 (Liabilities) or 3 (Equity) - 4 and up is Revenue/
# Expense, already covered by the Category Summary. GL Dump upload is
# optional; schedules are skipped entirely when it's not provided.
SCHEDULE_ACCOUNT_PREFIXES = ("1", "2", "3")
# These two are employee/contractor expense-report clearing accounts -
# confirmed for real their lines never carry a Spend Category (0%), but
# Contingent Worker is populated on the large majority of lines (76% on
# 13170, 87% on 20130) and is a far more useful categorization than the
# generic memo-text fallback for an account that's fundamentally "who
# submitted this expense report", not "what was it for".
CONTINGENT_WORKER_ACCOUNT_CODES = {"13170", "20130"}
_TRAILING_MONTH_RE = re.compile(
r"\s*-?\s*(January|February|March|April|May|June|July|August|September|October|November|December|"
r"Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept|Sep|Oct|Nov|Dec)\.?\s*\d{2,4}\s*$",
re.IGNORECASE,
)
_FISCAL_YEAR_RE = re.compile(r"\s*-?\s*FY\s*\d{2,4}\s*$", re.IGNORECASE)
_CATEGORY_STOPWORDS = {"project", "expense", "expenses", "accrual", "final", "the", "of", "for", "and"}
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 _apply_reassignment(text_series, account_code_series, mapping):
"""
Rename each value in text_series to mapping[(account_code,
_norm_key(value))]'s target, wherever a real (non-None/"leave as
is") target is on record - the shared mechanism behind both category
and project reassignment (see find_unmapped_tb_categories/_projects,
category_mapping_lookup/project_mapping_lookup, and the Manage
Mappings panel). A value with no entry in mapping, or one recorded
as an explicit "leave as is" (target None), passes through
unchanged. mapping: {(account_code, norm_source): target_or_None}.
"""
if not mapping:
return text_series
return pd.Series(
[mapping.get((code, _norm_key(val))) or val for code, val in zip(account_code_series, text_series)],
index=text_series.index,
)
def _compute_applied_category_project(df, cat_col, category_map, project_map):
"""
Given a raw revenue/expense TB DataFrame: the "as-grouped" category
and project_code Series - placeholder-filled, canonicalized, then
reassigned (category_map/project_map, see _apply_reassignment), then
79000/81000 forced (see FORCED_CATEGORY_BY_ACCOUNT) - in that order,
the exact same per-row logic process_category_summary applies before
grouping. Also used to write "Category (Applied)"/"Project
(Applied)" columns onto the raw Revenue TB/Expense TB sheet copies
(see build_report_workbook), so the live SUMIFS formulas built
against those columns (see _sumifs_expr) always match exactly what
was actually grouped - without this, a reassigned or forced-
collapsed category would carry Category Summary criteria text that
no longer matches anything in an otherwise-verbatim raw sheet, and
every such formula would silently evaluate to zero once opened in
Excel.
"""
category = _canonicalize_text(df[cat_col].fillna("(Uncategorized)"))
project_code = _canonicalize_text(df["Project"].fillna("(No project)"))
account_code = df["Ledger Account"].astype(str).str.split(":", n=1).str[0].str.strip()
return _apply_reassignment_and_forced_collapse(category, project_code, account_code, category_map, project_map)
def _apply_reassignment_and_forced_collapse(category, project_code, account_code, category_map, project_map):
"""
Shared tail of _compute_applied_category_project (TB rows, one
fixed category column) and build_gl_detail_sheet (GL Dump rows,
whose raw category text comes from a DIFFERENT column depending on
whether the row is revenue or expense - see that function) - once
category/project_code are already canonicalized placeholder-filled
Series, apply the reassignment maps (see _apply_reassignment) then
the 79000/81000 forced collapse (see FORCED_CATEGORY_BY_ACCOUNT), in
that order.
"""
category = _apply_reassignment(category, account_code, category_map)
project_code = _apply_reassignment(project_code, account_code, project_map)
for code, forced_category in FORCED_CATEGORY_BY_ACCOUNT.items():
category = category.mask(account_code == code, forced_category)
return category, project_code
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, budget_df=None, category_map=None, project_map=None):
"""
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.
category_map / project_map: optional {(account_code, norm_source):
target_or_None} lookups (see category_mapping_lookup/
project_mapping_lookup and _apply_reassignment) - when a TB row's
category or project text has a real target on record, it's renamed
to that target BEFORE grouping, so its actuals fold straight into
the target's row (project code renamed independently of category,
and vice versa - reassigning "G Adventures Donation" to "Corporate
Supporters" keeps whatever project code that row already had).
Applied before the 79000/81000 forced collapse below, so that rule
always wins regardless of what's on record in either map.
budget_df: optional, a loaded Budget file (see load_budget_file).
When it's the detailed format (see budget_is_detailed), any
(account, category, project) combination present in the Budget file
with NO actual trial-balance activity this period gets its own row
too, canada=us=0 - confirmed for real this matters: without it, a
not-yet-spent budgeted project has no row to hang its Budget/
Variance/Budget (Full Year) figures on at all, silently dropping its
whole budget from every total built on these rows - large enough,
across many such projects, to flip an apparent YTD surplus into a
deficit purely from omission, not from any real overspend. A
combination is only added this way if it has a real full-year
budget figure (its own YTD slice can still be $0, e.g. a project not
budgeted to start until later in the year) - one with no actual
activity AND no budget for the year either is a genuinely empty
line with nothing to show or investigate, so it's left out rather
than added as a row of three zeros. These synthetic rows never
affect canada/us sums (they're exactly 0) or the reconciliation
check (computed from source_totals, before this union), but callers
that care whether a row reflects REAL activity (e.g.
find_unmatched_budget_projects) must filter on canada/us being
nonzero themselves - this function doesn't distinguish the two kinds
of row any other way.
"""
results = {}
source_totals = {}
budget_detail = None
if budget_df is not None and budget_is_detailed(budget_df):
budget_detail = _budget_detail_rows(budget_df)
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"], d["project_code"] = _compute_applied_category_project(d, cat_col, category_map, project_map)
d["slob"] = d["project_code"].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)
if budget_detail is not None:
existing_keys = set(zip(
grouped["account"].str.split(":").str[0],
grouped["category"].map(_norm_key),
grouped["project_code"].map(_norm_key),
))
role_budget = budget_detail[budget_detail["account_code"].isin(codes)]
new_rows = []
seen_new = {} # norm_key -> row dict (accumulates Total - CAD across every source row sharing the key)
for _, r in role_budget.iterrows():
norm_key = (r["account_code"], _norm_key(r["category"]), _norm_key(r["project"]))
if norm_key in existing_keys:
continue
total_cad = r["Total - CAD"]
total_cad = 0.0 if pd.isna(total_cad) else float(total_cad)
if norm_key in seen_new:
seen_new[norm_key]["_full_year_budget"] += total_cad
continue
seen_new[norm_key] = {
"account": r["Account"], "category": r["category"],
"slob": extract_slob(r["project"]), "project_code": r["project"],
"canada": 0.0, "us": 0.0, "_full_year_budget": total_cad,
}
# A combination with no actual activity yet AND no budgeted
# amount for the year either is a genuinely empty line -
# nothing to show, nothing to investigate - so it's dropped
# here rather than added as a row with three zeros across
# the board. Only a real full-year budget figure (even if
# this period's own YTD slice of it happens to be $0, e.g.
# a project not budgeted to start until later in the year)
# earns the row.
new_rows = [
{k: v for k, v in row.items() if not k.startswith("_")}
for row in seen_new.values() if abs(row["_full_year_budget"]) >= 0.005
]
if new_rows:
grouped = pd.concat([grouped, pd.DataFrame(new_rows)], ignore_index=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 find_unmapped_bs_accounts(revenue_tb_df, account_map=None):
"""
Every Balance Sheet account (code prefix 1/2/3 - see
SCHEDULE_ACCOUNT_PREFIXES) with a nonzero combined (Canada+US) trial
balance that ISN'T covered by balance_sheet_account_map.csv - these
silently drop out of compute_balance_sheet's totals with no error, so
the Balance Sheet's own balance_check can be off by exactly a missing
account's balance with no indication why. Confirmed for real twice
(accounts 12500 and 12501, each caught only because their omission
happened to throw the report visibly out of balance) - a mapped
account the file simply doesn't use would never surface this way, so
this check is the only thing standing between a new account code and
a silent, unexplained mismatch.
Returns a list of {"account_code", "account_label", "tb_total",
"suggested_section", "suggested_sign"} dicts, sorted by account code.
The suggestions are a first-digit-based guess (1->Assets/+1,
2->Liabilities/-1, 3->NetAssets/-1, matching every existing row in
the map) for the caller to present for approval - never applied
automatically, and deliberately no suggested_line_item, since there's
no reasonable default label to guess.
"""
if account_map is None:
account_map = _load_account_map()
mapped_codes = {code for entry in account_map.values() for code, _ in entry["codes"]}
full = revenue_tb_df.copy()
full["_code"] = full["Ledger Account"].astype(str).str.split(":", n=1).str[0].str.strip()
full = full[full["_code"].str.startswith(SCHEDULE_ACCOUNT_PREFIXES)]
full["_combined"] = full["Planeterra Foundation"].fillna(0) + full["Planeterra International Foundation Ltd"].fillna(0)
by_code = full.groupby("_code").agg(_combined=("_combined", "sum"), _label=("Ledger Account", "first"))
unmapped = []
for code, row in by_code.iterrows():
if code in mapped_codes:
continue
total = round(row["_combined"], 2)
if abs(total) < 0.005:
continue # no real activity - not worth flagging
prefix = code[0]
section = {"1": "Assets", "2": "Liabilities", "3": "NetAssets"}.get(prefix, "Assets")
sign = 1 if prefix == "1" else -1
unmapped.append({
"account_code": code,
"account_label": str(row["_label"]).strip(),
"tb_total": total,
"suggested_section": section,
"suggested_sign": sign,
})
unmapped.sort(key=lambda r: r["account_code"])
return unmapped
def append_to_account_map(mappings, path=ACCOUNT_MAP_PATH):
"""
Append user-approved account-code -> line-item mappings to
balance_sheet_account_map.csv (see find_unmapped_bs_accounts) -
called only after explicit approval in the UI, never automatically.
mappings: list of {"account_code", "line_item", "section", "sign"}.
"""
if not mappings:
return
file_exists = os.path.exists(path)
with open(path, "a", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
if not file_exists:
writer.writerow(["line_item", "section", "account_code", "sign"])
for m in mappings:
writer.writerow([m["line_item"], m["section"], m["account_code"], m["sign"]])
_BUDGET_HEADER_REQUIRED_COLS = {"GL Name", "Project"}
# The FY27+ format is self-describing - it carries its own Account/
# Category/Project Code columns directly (see budget_is_detailed),
# unlike the older FY26-style format (GL Name + Project only), which
# needed the indirect budget_line_key_map.csv lookup below because the
# file itself never said which account/project a line belonged to.
_BUDGET_HEADER_REQUIRED_COLS_DETAILED = {"GL Name", "Account", "Category", "Project Code"}
def find_budget_header_row(path, max_scan_rows=30):
"""
Budget exports carry a small title block above the real header row
("Planeterra - FY26/FY27 Budget", "All figures in CAD", etc) - scan
for the row satisfying either the older format's required columns
(GL Name, Project) or the newer, self-describing format's (GL Name,
Account, Category, Project Code) rather than hardcoding a row
number, same reasoning as common.py's find_gl_header_row.
"""
raw = pd.read_excel(path, sheet_name=0, header=None, nrows=max_scan_rows)
for i, row in raw.iterrows():
vals = {str(v) for v in row.tolist() if pd.notna(v)}
if _BUDGET_HEADER_REQUIRED_COLS <= vals or _BUDGET_HEADER_REQUIRED_COLS_DETAILED <= vals:
return i
return None
def budget_is_detailed(budget_df):
"""True when the uploaded Budget file carries its own Account/
Category/Project Code columns directly (the FY27+ format), so a
budget line's (account, category, project) key can be read straight
off the file - no manual budget_line_key_map.csv entry needed."""
return {"Account", "Category", "Project Code"} <= set(budget_df.columns)
# The handful of project-name spellings that differ between the FY27
# budget file and the trial balance by more than case/whitespace (a
# straight lower+strip match, used everywhere else here, doesn't
# collapse these) - confirmed for real against the July 2026 TB:
# "G-Adventures" (budget, no space around the hyphen) vs "G Adventures"/
# "G - Adventures" (TB, inconsistent between projects) is the recurring
# pattern, plus one GCTN casing difference. Keyed by the budget file's
# exact raw text; the fixed value is the TB's actual spelling.
BUDGET_PROJECT_NAME_FIXES = {
"Planeterra - C&B - G-Adventures": "Planeterra - C&B - G Adventures",
"Planeterra - CTI - G-Adventures": "Planeterra - CTI - G Adventures",
"Planeterra - GCTN - EasyJet": "Planeterra - GCTN - Easyjet",
"Planeterra - GCTN - G-Adventures": "Planeterra - GCTN - G - Adventures",
}
# The inverse of the map above: given a TB-spelled project (what
# Category Summary's own rows display), what the raw Budget sheet
# itself actually calls it - needed because a live SUMIFS formula
# against the Budget sheet has to search for whatever text is really
# sitting in that sheet's own Project Code column, not the TB's spelling.
_REVERSE_BUDGET_PROJECT_FIXES = {v: k for k, v in BUDGET_PROJECT_NAME_FIXES.items()}
def _norm_key(s):
"""Plain lower+strip - the join key used to match budget rows
against Category Summary's own (account, category, project) groups.
Not _canonicalize_text: that function dedupes casing variants WITHIN
one already-loaded file, whereas this join is ACROSS two
independently-cased files, so both sides need normalizing to the
same key regardless of which casing either file happens to use."""
return str(s or "").strip().lower()
def _budget_detail_rows(budget_df):
"""
For a detailed-format Budget file (see budget_is_detailed): just
the real line-item rows - Account, Category and Project Code all
populated - as a plain (account_code, category, project) key ready
to join against actuals. Excludes the sheet's own subtotal/rollup
rows (Account blank, e.g. "G Adventures Total", "Program Costs",
"Net" - confirmed for real: 52 of them in the FY27 file, each
already redundant with the sum of the detail rows it's totaling, so
including them would double the budget for every category they
roll up). BUDGET_PROJECT_NAME_FIXES is applied to the raw Project
Code text before it's used as a join key. The same 79000/81000
forced-category collapse process_category_summary applies to the
actuals side (see FORCED_CATEGORY_BY_ACCOUNT) is applied here too,
defensively - confirmed for real the FY27 budget file already only
carries one already-matching category per account for these two, so
this is a no-op in practice, kept in case a future budget file ever
splits either one into more than one category.
"""
df = budget_df[budget_df["Account"].notna()].copy()
df["account_code"] = df["Account"].astype(str).str.split(":", n=1).str[0].str.strip()
df["category"] = df["Category"].astype(str).str.strip()
df["project"] = df["Project Code"].astype(str).str.strip().apply(
lambda p: BUDGET_PROJECT_NAME_FIXES.get(p, p)
)
for code, forced_category in FORCED_CATEGORY_BY_ACCOUNT.items():
df.loc[df["account_code"] == code, "category"] = forced_category
return df
def load_budget_file(path):
"""
Read a Budget export: locate its header row (see
find_budget_header_row) and load the data below it. Returns None if
this doesn't look like a Budget file (no matching header row found)
- the caller falls back to treating the upload as unrecognized.
"""
header_row = find_budget_header_row(path)
if header_row is None:
return None
df = pd.read_excel(path, sheet_name=0, header=header_row)
return df.reset_index(drop=True)
def load_stored_budget_file():
"""
The persisted Budget file (see STORED_BUDGET_PATH) - a single-file
bind mount, same pattern as balance_sheet_account_map.csv, so a
Budget file uploaded once via /api/upload-budget survives container
rebuilds and every future report run can just check the "Budget vs
Actual" box without re-uploading it. Returns None if nothing has
been stored yet, or the stored file no longer parses as a Budget
file (shouldn't happen - only save_stored_budget_file writes here,
and it validates first).
"""
if not os.path.exists(STORED_BUDGET_PATH):
return None
return load_budget_file(STORED_BUDGET_PATH)
def save_stored_budget_file(upload_path):
"""
Validate upload_path as a real Budget file (see load_budget_file),
then persist it to STORED_BUDGET_PATH, replacing whatever was
stored before. Returns the loaded DataFrame on success; raises
ValueError (with a message safe to show the user) if upload_path
doesn't look like a Budget file - the stored copy is left untouched
in that case, never overwritten with something unparseable.
"""
df = load_budget_file(upload_path)
if df is None:
raise ValueError(
"This doesn't look like a Budget file (no header row with \"GL Name\" and "
"\"Project\", or \"GL Name\", \"Account\", \"Category\", \"Project Code\" found)."
)
shutil.copyfile(upload_path, STORED_BUDGET_PATH)
return df
def stored_budget_file_status():
"""{"exists": bool, "uploaded_at": ISO 8601 string or None} - for
the UI to show what's currently stored (see /api/budget-status)."""
if not os.path.exists(STORED_BUDGET_PATH):
return {"exists": False, "uploaded_at": None}
mtime = datetime.fromtimestamp(os.path.getmtime(STORED_BUDGET_PATH))
return {"exists": True, "uploaded_at": mtime.isoformat()}
def budget_options_by_account(budget_df):
"""
{account_code: {"account_name", "categories": [...], "projects":
[...]}} for a detailed-format Budget file - every real category and
project text that account has in the budget, for the standalone
Manage Mappings panel to build inline reassignment dropdowns from
(see /api/budget-options). Unlike the review gates' own
budget_categories/budget_projects (computed per flagged row during
an actual run - see find_unmapped_tb_categories/_projects), this
needs to work with just the stored Budget file, no TB upload in
hand, so it's every account's options up front rather than one
account's options for one specific flagged combo. Empty dict if
budget_df is None or isn't the detailed format.
"""
if budget_df is None or not budget_is_detailed(budget_df):
return {}
result = {}
for _, r in _budget_detail_rows(budget_df).iterrows():
entry = result.setdefault(r["account_code"], {"account_name": r["Account"], "categories": set(), "projects": set()})
entry["categories"].add(r["category"])
entry["projects"].add(r["project"])
return {
code: {"account_name": v["account_name"], "categories": sorted(v["categories"]), "projects": sorted(v["projects"])}
for code, v in result.items()
}
def _budget_month_columns(budget_df):
"""
The budget file's monthly figures live under columns whose own
header is an actual date (one calendar month each, e.g. 2025-08-01)
rather than a fixed, named set of columns - collecting them this way
(instead of hardcoding column letters like the source workbook's own
"=SUM(L:V)" does) is what lets YTD be computed for any report_date
without anyone having to hand-extend a formula every month. Returns
[(date, column_name), ...] sorted chronologically.
"""
months = []
for col in budget_df.columns:
if isinstance(col, datetime):
months.append((col, col))
elif hasattr(col, "to_pydatetime"): # pandas.Timestamp
months.append((col.to_pydatetime(), col))
months.sort(key=lambda t: t[0])
return months
def compute_budget_ytd(budget_df, report_date):
"""
Add two columns: "ytd_budget" - for each row, the sum of every
monthly budget column whose own month is on or before report_date
(the dynamic replacement for the source workbook's hardcoded
"=SUM(L:V)"-through-June formula, which needs hand-extending by one
column every month as the fiscal year progresses) - and
"month_budget" - just the single monthly column whose own month is
the SAME calendar month as report_date (0 if report_date's month
isn't one of the budget's own month columns at all, e.g. a report
date outside the budgeted fiscal year). report_date is a
"YYYY-MM-DD" string (as used throughout this tool).
"""
cutoff = datetime.strptime(report_date, "%Y-%m-%d")
months = _budget_month_columns(budget_df)
cols_in_scope = [name for month, name in months if month <= cutoff]
month_col = next((name for month, name in months
if month.year == cutoff.year and month.month == cutoff.month), None)
df = budget_df.copy()
if cols_in_scope:
# Coerce first: a monthly column can come back as object dtype
# when even one row in it holds a stray non-numeric value (a
# leftover text note, a blank formula cell) - summing that
# directly raises (str + float), so any such value becomes NaN
# (then 0) instead of crashing the whole report.
numeric = df[cols_in_scope].apply(pd.to_numeric, errors="coerce")
df["ytd_budget"] = numeric.fillna(0).sum(axis=1)
else:
df["ytd_budget"] = 0.0
df["month_budget"] = pd.to_numeric(df[month_col], errors="coerce").fillna(0) if month_col is not None else 0.0
return df
def _normalize_budget_no(value):
"""
The budget file's "No." column is the GL account code for expense
rows (a real float like 68000.0 when read via pandas) - normalize to
a plain integer-looking string ("68000") so the same row produces
the same key whether it's read fresh from an upload or typed into
the CSV by hand. Blank/NaN becomes "" (revenue rows often lack a
real code here - see build_budget_vs_actual's key design).
"""
if value is None or (isinstance(value, float) and pd.isna(value)):
return ""
try:
f = float(value)
return str(int(f)) if f.is_integer() else str(f)
except (TypeError, ValueError):
return str(value).strip()
def _load_budget_key_map(path=BUDGET_KEY_MAP_PATH):
"""
Read the Budget line -> (account, project) mapping fresh from
budget_line_key_map.csv on every call - same bind-mounted-CSV pattern
as the other lookup tables. This is the explicit, auditable
replacement for the source workbook's hardcoded
='FY26 Budget'!AB7-style cell references: instead of a budget row's
identity being "whatever row number happens to be there," it's
(account code, GL Name text), which survives the budget file being
regenerated each period even if row order shifts.
The key is a (budget_no, gl_name) tuple, NOT gl_name alone - GL Name
text is NOT reliably unique on its own (confirmed for real: "C&B -
Evaneos" is reused as the label for six distinct budget lines under
six different GL account codes - a GL-Name-only key summed all six
together under whichever one entry referenced that text, materially
inflating that line's budget figure). budget_no is "" for the rare
row that genuinely has no code of its own.
Returns {(budget_no, gl_name): (summary_account, summary_project)}.
summary_project is "" for an account-level budget line with no
specific project, not a wildcard - see build_budget_vs_actual for
why that distinction matters.
"""
mapping = {}
if not os.path.exists(path):
return mapping
with open(path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
gl_name = (row.get("budget_gl_name") or "").strip()
if not gl_name:
continue
budget_no = _normalize_budget_no(row.get("budget_no"))
mapping[(budget_no, gl_name)] = (
(row.get("summary_account") or "").strip(),
(row.get("summary_project") or "").strip(),
)
return mapping
def append_to_budget_key_map(mappings, path=BUDGET_KEY_MAP_PATH):
"""
Append user-approved (budget_no, GL Name) -> (account, project)
mappings to budget_line_key_map.csv (see find_unmapped_budget_lines)
- called only after explicit approval in the UI, never automatically.
mappings: list of {"budget_gl_name", "budget_no", "summary_account", "summary_project"}.
"""
if not mappings:
return
file_exists = os.path.exists(path)
with open(path, "a", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
if not file_exists:
writer.writerow(["budget_gl_name", "budget_no", "summary_account", "summary_project"])
for m in mappings:
writer.writerow([m["budget_gl_name"], m.get("budget_no", ""), m["summary_account"], m.get("summary_project", "")])
def _load_reassignment_rows(path):
"""
Every row of a category/project reassignment CSV, verbatim - list of
{"account_code", "source", "target"} dicts, "target" "" meaning an
explicit "leave as is, don't ask again" decision (the row's mere
presence is what suppresses future review-gate prompts for that
(account, source) - see find_unmapped_tb_categories/_projects),
not "no decision yet". Same bind-mounted-CSV-read-fresh-every-call
pattern as the other lookup tables.
"""
if not os.path.exists(path):
return []
rows = []
with open(path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
account_code = (row.get("account_code") or "").strip()
source = (row.get("source") or "").strip()
if not account_code or not source:
continue
rows.append({"account_code": account_code, "source": source, "target": (row.get("target") or "").strip()})
return rows
def _save_reassignment_rows(rows, path):
"""Full rewrite, not append - same pattern as merchant_lookup.csv's
add_merchant_mappings, needed here because entries must be editable
and removable from the UI at any time (see the Manage Mappings
panel), not just ever-growing."""
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["account_code", "source", "target"])
for r in rows:
writer.writerow([r["account_code"], r["source"], r["target"]])
def _upsert_reassignment_rows_batch(path, entries):
"""
Apply many (account_code, source, target) reassignment decisions in
ONE read-modify-write pass. Always use this (or a single-entry call
to it, see _upsert_reassignment_row) rather than looping a
read-modify-write per decision - confirmed for real that looping
lost writes when resolving a ~24-item review gate: each iteration's
write to the bind-mounted CSV can race the next iteration's read on
Docker's bind-mount layer, silently dropping earlier entries.
"""
rows = _load_reassignment_rows(path)
by_key = {(r["account_code"], _norm_key(r["source"])): r for r in rows}
for account_code, source, target in entries:
account_code = str(account_code).strip()
source = str(source).strip()
by_key[(account_code, _norm_key(source))] = {
"account_code": account_code, "source": source, "target": str(target or "").strip(),
}
rows = sorted(by_key.values(), key=lambda r: (r["account_code"], r["source"]))
_save_reassignment_rows(rows, path)
def _upsert_reassignment_row(path, account_code, source, target):
_upsert_reassignment_rows_batch(path, [(account_code, source, target)])
def _delete_reassignment_row(path, account_code, source):
account_code = str(account_code).strip()
key = (account_code, _norm_key(source))
rows = [r for r in _load_reassignment_rows(path) if (r["account_code"], _norm_key(r["source"])) != key]
_save_reassignment_rows(rows, path)
def _reassignment_lookup(rows):
"""Raw rows (see _load_reassignment_rows) -> {(account_code,
norm_source): target_or_None} - the fast-lookup form
process_category_summary/_apply_reassignment actually use, with a
blank target normalized to None ("leave as is")."""
return {(r["account_code"], _norm_key(r["source"])): (r["target"] or None) for r in rows}
def list_category_mappings():
"""Every category reassignment on file, for the Manage Mappings
panel and for category_mapping_lookup() - see _load_reassignment_rows."""
return _load_reassignment_rows(CATEGORY_REASSIGNMENT_MAP_PATH)
def category_mapping_lookup():
"""{(account_code, norm_source): target_or_None} - what
process_category_summary/find_unmapped_tb_projects actually pass
around (see _apply_reassignment)."""
return _reassignment_lookup(list_category_mappings())
def upsert_category_mapping(account_code, source, target):
"""
Add or update one (account_code, source) -> target category
reassignment (target "" = an explicit "leave as is" decision, not
"no mapping") and persist the whole table. Called both by
/api/confirm-category-mapping (see find_unmapped_tb_categories) and
directly by the standalone Manage Mappings panel.
"""
_upsert_reassignment_row(CATEGORY_REASSIGNMENT_MAP_PATH, account_code, source, target)
def upsert_category_mappings(entries):
"""
Batch equivalent of upsert_category_mapping - entries: list of
(account_code, source, target) tuples, applied in one
read-modify-write pass (see _upsert_reassignment_rows_batch). Use
this instead of calling upsert_category_mapping in a loop whenever
resolving more than one decision at once (e.g. an entire review
gate's worth) - looping individual upserts can lose writes on a
bind-mounted filesystem.
"""
_upsert_reassignment_rows_batch(CATEGORY_REASSIGNMENT_MAP_PATH, entries)
def delete_category_mapping(account_code, source):
"""Remove a category reassignment entirely - unlike an explicit
"leave as is" (target ""), this makes the (account, source) eligible
to be flagged by find_unmapped_tb_categories again."""
_delete_reassignment_row(CATEGORY_REASSIGNMENT_MAP_PATH, account_code, source)
def list_project_mappings():
"""Project-code equivalent of list_category_mappings()."""
return _load_reassignment_rows(PROJECT_REASSIGNMENT_MAP_PATH)
def project_mapping_lookup():
"""Project-code equivalent of category_mapping_lookup()."""
return _reassignment_lookup(list_project_mappings())
def upsert_project_mapping(account_code, source, target):
"""Project-code equivalent of upsert_category_mapping()."""
_upsert_reassignment_row(PROJECT_REASSIGNMENT_MAP_PATH, account_code, source, target)
def upsert_project_mappings(entries):
"""Batch equivalent of upsert_project_mapping() - see
upsert_category_mappings()."""
_upsert_reassignment_rows_batch(PROJECT_REASSIGNMENT_MAP_PATH, entries)
def delete_project_mapping(account_code, source):
"""Project-code equivalent of delete_category_mapping()."""
_delete_reassignment_row(PROJECT_REASSIGNMENT_MAP_PATH, account_code, source)
def find_unmatched_budget_projects(budget_df, grouped, report_date):
"""
Detailed-format Budget file (see budget_is_detailed) equivalent of
find_unmapped_budget_lines below: every (account, category, project)
combo with a real nonzero YTD budget whose project text doesn't
match ANY actual trial-balance row under that same account, at all -
confirmed for real against the FY27 budget vs. the July 2026 TB: 3
such combos, each a plausible brand-new/not-yet-spent project rather
than an error, but exactly the kind of silent gap this tool always
surfaces for review rather than guessing about (same principle as
find_unmapped_bs_accounts/find_unmapped_budget_lines).
grouped is process_category_summary's own {"revenue": df, "expense":
df} result, so "does this project exist in the TB" is checked
against the exact same data the actual-side comparison itself uses
- not a separate re-derivation that could disagree with it.
Returns a list of {"account", "category", "project", "ytd_budget"}
dicts for caller-side review, never auto-mapped.
"""
tb_projects_by_account = defaultdict(set)
for role_df in (grouped["revenue"], grouped["expense"]):
for _, r in role_df.iterrows():
if abs(r["canada"]) < 0.005 and abs(r["us"]) < 0.005:
continue # a real actual-$0 row (or a budget-only row process_category_summary
# added with no actual yet) isn't "real TB activity"
code = r["account"].split(":")[0].strip()
tb_projects_by_account[code].add(_norm_key(r["project_code"]))
df = compute_budget_ytd(_budget_detail_rows(budget_df), report_date)
unmatched = []
seen = set()
for _, row in df.iterrows():
account_code, category, project = row["account_code"], row["category"], row["project"]
key = (account_code, _norm_key(category), _norm_key(project))
if key in seen:
continue
ytd = row.get("ytd_budget", 0) or 0
if abs(ytd) < 0.005:
continue # no real budget activity on this line - not worth flagging
if _norm_key(project) in tb_projects_by_account.get(account_code, set()):
continue # this exact project has real TB activity somewhere under this account
seen.add(key)
unmatched.append({
"account": row["Account"], "category": category, "project": project,
"ytd_budget": round(float(ytd), 2),
})
unmatched.sort(key=lambda r: (r["account"], r["category"], r["project"]))
return unmatched
def find_budget_rows_missing_account(budget_df, report_date):
"""
Detailed-format Budget file rows that look like real detail lines -
a real Category, a real Project Code, a nonzero dollar amount - but
have a blank Account, so _budget_detail_rows (which filters on
Account being present) silently excludes them from everything: no
Category Summary row to attach to, no live SUMIFS formula anywhere
can reference them, and no review gate short of this one would ever
surface the gap. Confirmed for real: one such row in the FY27
budget ("Staff FAMS", $25,296.64) is exactly why this tool's own
computed Full Year budget surplus didn't match the source file's own
"Net" row - the file's own rollup formula sums the whole section
regardless of whether Account is filled in, so it silently includes
a line this tool has nowhere to put.
Returns a list of {"no", "gl_name", "category", "project", "amount"}
dicts for caller-side review - the fix has to happen in the source
Budget workbook itself (add the missing Account), so this is
acknowledge-only, same as find_unmatched_budget_projects.
"""
d = budget_df[
budget_df["Account"].isna()
& budget_df["Category"].notna()
& budget_df["Project Code"].notna()
].copy()
if d.empty:
return []
d = compute_budget_ytd(d, report_date)
missing = []
for _, row in d.iterrows():
total_cad = row.get("Total - CAD", 0) or 0
if pd.isna(total_cad):
total_cad = 0
if abs(total_cad) < 0.005:
continue
missing.append({
"no": row.get("No."), "gl_name": row.get("GL Name"),
"category": row["Category"], "project": row["Project Code"],
"amount": round(float(total_cad), 2),
})
missing.sort(key=lambda r: (r["category"], r["project"]))
return missing
def find_unmapped_tb_categories(revenue_df, expense_df, budget_df, category_map=None, project_map=None):
"""
Every (account, category, project) combo with real nonzero YTD
actual activity whose category text has no home anywhere in the
Budget file for that account, and isn't already decided one way or
the other in category_reassignment_map.csv (see
category_mapping_lookup/upsert_category_mapping) - the forward-
looking counterpart to find_unmatched_budget_projects (which checks
the other direction: budgeted lines with no matching actual).
Accounts 79000/81000 are always excluded - their category is a
fixed business rule, never user-editable (see
FORCED_CATEGORY_BY_ACCOUNT). "Already decided"/"already matches"
stay at the (account, category) level, ignoring project - a
category decision applies uniformly regardless of which project a
row happens to be filed under (see process_category_summary's
docstring) - but project is broken out (not collapsed away) here,
and each row carries its own budget_projects options too, mirroring
find_unmapped_tb_projects's own category options, so a category can
be reassigned with the context of which project it's on, and that
project optionally reassigned in the very same decision (see
api_confirm_category_mapping, symmetric with
api_confirm_project_mapping's category_action).
Runs process_category_summary with NO maps applied (the raw TB
picture) so a combo already folded into a target category by a
prior decision naturally disappears from this list on its own;
category_map is only used to skip combos that were explicitly left
as-is (which don't get folded into anything, so they'd otherwise
keep reappearing here forever).
Returns [{"account_code", "account_name", "category", "project",
"amount", "budget_categories": [...], "budget_projects": [...]}]
sorted by account then category then project, for caller-side
review (see the category_mapping review gate) - never auto-applied.
"""
if category_map is None:
category_map = category_mapping_lookup()
if project_map is None:
project_map = project_mapping_lookup()
grouped, _ = process_category_summary(revenue_df, expense_df)
budget_categories_by_account = defaultdict(dict) # account_code -> {norm_key: display_text}
budget_projects_by_account = defaultdict(dict)
if budget_df is not None and budget_is_detailed(budget_df):
for _, r in _budget_detail_rows(budget_df).iterrows():
budget_categories_by_account[r["account_code"]][_norm_key(r["category"])] = r["category"]
budget_projects_by_account[r["account_code"]][_norm_key(r["project"])] = r["project"]
unmapped = []
for role_df in (grouped["revenue"], grouped["expense"]):
agg = role_df.groupby(["account", "category", "project_code"], as_index=False)[["canada", "us"]].sum()
for _, r in agg.iterrows():
amount = round(r["canada"] + r["us"], 2)
if abs(amount) < 0.005:
continue
account_code = r["account"].split(":")[0].strip()
if account_code in FORCED_CATEGORY_ACCOUNT_CODES:
continue
if (account_code, _norm_key(r["category"])) in category_map:
continue # already decided (mapped or explicitly left as-is)
available_categories = budget_categories_by_account.get(account_code, {})
if _norm_key(r["category"]) in available_categories:
continue # already matches a real budget category for this account
unmapped.append({
"account_code": account_code, "account_name": r["account"],
"category": r["category"], "project": r["project_code"], "amount": amount,
"budget_categories": sorted(available_categories.values()),
"budget_projects": sorted(budget_projects_by_account.get(account_code, {}).values()),
})
unmapped.sort(key=lambda r: (r["account_code"], r["category"], r["project"]))
return unmapped
def find_unmapped_tb_projects(revenue_df, expense_df, budget_df, category_map=None, project_map=None):
"""
Same idea as find_unmapped_tb_categories, but for project codes:
every (account, category, project) combo with real nonzero YTD
actual activity whose project text has no home anywhere in the
Budget file for that account, and isn't already decided in
project_reassignment_map.csv. The "already decided" and "already
matches" checks are both at the (account, project) level, ignoring
category - a project reassignment applies wherever that project
code shows up, project codes being a cross-cutting real-world
initiative rather than something scoped to one category - but
category is broken out (not collapsed away) here, and each row
carries its own budget_categories options too, so a project can be
reassigned with the context of which category it's currently filed
under, and optionally re-categorized in the very same decision
("keep it in the same category, or move it to another category" -
see api_confirm_project_mapping, which applies that half via
upsert_category_mapping, same mechanism as the category_mapping
gate itself). Runs on the ALREADY category-mapped picture
(category_map is applied when computing grouped, matching the
review-gate order in _check_gates_and_respond - category resolves
first, then project). BUDGET_PROJECT_NAME_FIXES is applied on the
budget side (via _budget_detail_rows, same as
find_unmatched_budget_projects) so a known spelling difference
isn't flagged as a real gap.
Returns [{"account_code", "account_name", "category", "project",
"amount", "budget_projects": [...], "budget_categories": [...]}],
never auto-applied.
"""
if category_map is None:
category_map = category_mapping_lookup()
if project_map is None:
project_map = project_mapping_lookup()
grouped, _ = process_category_summary(revenue_df, expense_df, category_map=category_map)
budget_projects_by_account = defaultdict(dict)
budget_categories_by_account = defaultdict(dict)
if budget_df is not None and budget_is_detailed(budget_df):
for _, r in _budget_detail_rows(budget_df).iterrows():
budget_projects_by_account[r["account_code"]][_norm_key(r["project"])] = r["project"]
budget_categories_by_account[r["account_code"]][_norm_key(r["category"])] = r["category"]
unmapped = []
for role_df in (grouped["revenue"], grouped["expense"]):
agg = role_df.groupby(["account", "category", "project_code"], as_index=False)[["canada", "us"]].sum()
for _, r in agg.iterrows():
amount = round(r["canada"] + r["us"], 2)
if abs(amount) < 0.005:
continue
account_code = r["account"].split(":")[0].strip()
if (account_code, _norm_key(r["project_code"])) in project_map:
continue # already decided (mapped or explicitly left as-is)
available_projects = budget_projects_by_account.get(account_code, {})
if _norm_key(r["project_code"]) in available_projects:
continue # already matches a real budget project for this account
unmapped.append({
"account_code": account_code, "account_name": r["account"],
"category": r["category"], "project": r["project_code"], "amount": amount,
"budget_projects": sorted(available_projects.values()),
"budget_categories": sorted(budget_categories_by_account.get(account_code, {}).values()),
})
unmapped.sort(key=lambda r: (r["account_code"], r["category"], r["project"]))
return unmapped
def find_unmapped_budget_lines(budget_df, report_date, key_map=None):
"""
Older-format Budget file (no Account/Category/Project Code columns
of its own - see budget_is_detailed) review gate: every budget row
with a real (nonzero) YTD figure whose (account code, GL Name) key
isn't in budget_line_key_map.csv - these would otherwise be silently
dropped from the Budget vs. Actual report with no indication, the
exact failure mode already confirmed for real in the source
workbook (two budget-linked accounts worth of real dollars - Agent
Costs and General Office - present in "1. Summary (Manual)" but
never pulled into "Budget & Actuals Worksheet (FS)" because nobody
added their key to that sheet's own column K).
Returns a list of {"budget_gl_name", "budget_no", "ytd_budget"}
dicts for caller-side review, never auto-mapped.
"""
if key_map is None:
key_map = _load_budget_key_map()
df = compute_budget_ytd(budget_df, report_date)
unmapped = []
seen = set()
for _, row in df.iterrows():
gl_name = row.get("GL Name")
if not gl_name or pd.isna(gl_name):
continue
gl_name = str(gl_name).strip()
budget_no = _normalize_budget_no(row.get("No."))
key = (budget_no, gl_name)
if key in key_map or key in seen:
continue
ytd = row.get("ytd_budget", 0) or 0
if abs(ytd) < 0.005:
continue # no real budget activity on this line - not worth flagging
seen.add(key)
unmapped.append({"budget_gl_name": gl_name, "budget_no": budget_no, "ytd_budget": round(float(ytd), 2)})
unmapped.sort(key=lambda r: (r["budget_no"], r["budget_gl_name"]))
return unmapped
def _actual_totals_from_grouped(grouped):
"""
Two lookups straight from process_category_summary's own {"revenue":
df, "expense": df} output, canada+us combined (already sign-flipped
for revenue there) - so Budget vs Actual's actual-side figures
always agree with what Category Summary itself shows, never a
separately re-derived number that could drift from it:
by_account_category_project: {(code, category_norm, project_norm):
amount} - the detailed-format budget path's exact match grain.
by_account_project: {(code, project_norm): amount} - the coarser
grain the older budget format's key map targets (account + project
only; that format never carried a category of its own).
Keys are _norm_key'd (lower+strip) rather than exact text on either
side - Category Summary's own project_code is already
_canonicalize_text-deduped internally, but a hand-typed
budget_line_key_map.csv entry (older format) or the budget file's
own raw text (newer format) isn't guaranteed to match that exact
chosen casing, and Excel/Sheets' own SUMIFS this whole tool mirrors
already treats text case-insensitively - so should this join.
"""
by_acp = defaultdict(float)
by_ap = defaultdict(float)
for role_df in (grouped["revenue"], grouped["expense"]):
for _, r in role_df.iterrows():
code = r["account"].split(":")[0].strip()
cat_key, proj_key = _norm_key(r["category"]), _norm_key(r["project_code"])
amount = r["canada"] + r["us"]
by_acp[(code, cat_key, proj_key)] += amount
by_ap[(code, proj_key)] += amount
return by_acp, by_ap
def _build_budget_vs_actual_detailed(budget_df, grouped, report_date):
"""
build_budget_vs_actual's path for a detailed-format Budget file (see
budget_is_detailed): the (account, category, project) key comes
straight from the file's own columns (via _budget_detail_rows, with
BUDGET_PROJECT_NAME_FIXES applied) - no manual key-map needed at all,
since the file already says exactly what it's for.
"""
by_acp, _ = _actual_totals_from_grouped(grouped)
detail = compute_budget_ytd(_budget_detail_rows(budget_df), report_date)
budget_by_key = defaultdict(lambda: [0.0, 0.0]) # [ytd, month]
display = {}
for _, row in detail.iterrows():
account_code, category, project = row["account_code"], row["category"], row["project"]
key = (account_code, _norm_key(category), _norm_key(project))
budget_by_key[key][0] += row.get("ytd_budget", 0) or 0
budget_by_key[key][1] += row.get("month_budget", 0) or 0
display.setdefault(key, (row["Account"], category, project))
matched_keys = set()
rows = []
for key, (ytd, month) in budget_by_key.items():
account, category, project = display[key]
account_code = key[0]
budget_ytd, month_budget = round(ytd, 2), round(month, 2)
actual_ytd = round(by_acp.get(key, 0.0), 2)
matched_keys.add(key)
variance = round(actual_ytd - budget_ytd, 2)
pct_of_budget = round(actual_ytd / budget_ytd, 4) if abs(budget_ytd) >= 0.005 else None
rows.append({
"budget_gl_name": "", "budget_no": "", "account": account,
"category": category, "project": project,
"budget_ytd": budget_ytd, "actual_ytd": actual_ytd,
"month_budget": month_budget, "variance": variance, "pct_of_budget": pct_of_budget,
})
unbudgeted_actuals = []
for (code, cat_key, proj_key), amount in by_acp.items():
if (code, cat_key, proj_key) in matched_keys or abs(amount) < 0.005:
continue
unbudgeted_actuals.append({
"account_code": code, "category": cat_key, "project": proj_key, "actual_ytd": round(amount, 2),
})
unbudgeted_actuals.sort(key=lambda r: (r["account_code"], r["category"], r["project"]))
rows.sort(key=lambda r: (r["account"], r["category"], r["project"]))
return {"rows": rows, "unbudgeted_actuals": unbudgeted_actuals}
def _build_budget_vs_actual_legacy(budget_df, grouped, report_date, key_map):
"""
build_budget_vs_actual's path for the older Budget format (no
Account/Category/Project Code columns of its own - see
budget_is_detailed): join via budget_line_key_map.csv, one output
row per mapped budget line (see _load_budget_key_map). Actuals are
matched by (account code, Project) only - that format never carried
a category dimension - EXACT text match (case-insensitive, see
_actual_totals_from_grouped) only, never fuzzy/guessed, per explicit
direction. A key-map entry with a blank summary_project matches only
TB rows whose own Project is ALSO blank for that account - not
"every row for that account regardless of project" - since several
accounts have both an account-level budget line (e.g. "Individual
Donors", no project) and separate project-specific lines (e.g.
"-G Touring") under the same account code; treating blank as a
wildcard would double-count the project-specific rows into the
account-level line too. The tradeoff: a blank-project budget line
shows $0 actual if its real TB counterpart always does carry a
project tag - in which case those dollars surface instead in
unbudgeted_actuals below, which is the correct outcome (a real gap
to review, not a silent miscount).
"""
_, by_ap = _actual_totals_from_grouped(grouped)
budget_df = compute_budget_ytd(budget_df, report_date)
budget_by_key = defaultdict(lambda: [0.0, 0.0]) # [ytd, month]
for _, row in budget_df.iterrows():
gl_name = row.get("GL Name")
if not gl_name or pd.isna(gl_name):
continue
budget_no = _normalize_budget_no(row.get("No."))
key = (budget_no, str(gl_name).strip())
budget_by_key[key][0] += row.get("ytd_budget", 0) or 0
budget_by_key[key][1] += row.get("month_budget", 0) or 0
matched_keys = set()
rows = []
for (budget_no, gl_name), (account, project) in key_map.items():
account_code = account.split(":")[0].strip()
proj_key = _norm_key(project)
ytd, month = budget_by_key.get((budget_no, gl_name), (0.0, 0.0))
budget_ytd, month_budget = round(ytd, 2), round(month, 2)
actual_ytd = round(by_ap.get((account_code, proj_key), 0.0), 2)
matched_keys.add((account_code, proj_key))
variance = round(actual_ytd - budget_ytd, 2)
pct_of_budget = round(actual_ytd / budget_ytd, 4) if abs(budget_ytd) >= 0.005 else None
rows.append({
"budget_gl_name": gl_name, "budget_no": budget_no, "account": account,
"category": "", "project": project,
"budget_ytd": budget_ytd, "actual_ytd": actual_ytd,
"month_budget": month_budget, "variance": variance, "pct_of_budget": pct_of_budget,
})
unbudgeted_actuals = []
for (code, proj_key), amount in by_ap.items():
if (code, proj_key) in matched_keys or abs(amount) < 0.005:
continue
unbudgeted_actuals.append({"account_code": code, "category": "", "project": proj_key, "actual_ytd": round(amount, 2)})
unbudgeted_actuals.sort(key=lambda r: (r["account_code"], r["project"]))
rows.sort(key=lambda r: (r["account"], r["project"]))
return {"rows": rows, "unbudgeted_actuals": unbudgeted_actuals}
def build_budget_vs_actual(grouped, budget_df, report_date, key_map=None):
"""
Dispatches to the detailed-format or legacy-format path (see
budget_is_detailed) - the two Budget file shapes this tool
supports need genuinely different join logic (own columns vs. a
manual key-map), not one blended code path. grouped is
process_category_summary's own output, reused so the actual-side
figures here are always identical to Category Summary's (see
_actual_totals_from_grouped) rather than a second, separately
re-derived pass over the trial balance.
Returns {"rows": [...], "unbudgeted_actuals": [...]} - rows is one
dict per matched budget line (account, category, project,
budget_gl_name, budget_ytd, month_budget, actual_ytd, variance,
pct_of_budget - actual_ytd is the only actual-side figure available:
a single trial-balance upload is inherently YTD-cumulative, so an
actual figure for just the current month would need a prior-period
upload to diff against, which this tool doesn't yet take);
unbudgeted_actuals lists (account, category, project) combinations
with real actual $ that no budget line's key targets at all -
surfaced instead of silently omitted.
"""
if budget_is_detailed(budget_df):
return _build_budget_vs_actual_detailed(budget_df, grouped, report_date)
if key_map is None:
key_map = _load_budget_key_map()
return _build_budget_vs_actual_legacy(budget_df, grouped, report_date, key_map)
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
# Top+bottom rule under/over a major total row (Total Revenue, Project
# Costs, Net Revenues, each non-project-level account's own subtotal,
# Total Expenses, Surplus/(Deficit)) - see _apply_total_row_border.
_TOTAL_ROW_BORDER = Border(top=Side(style="thin"), bottom=Side(style="thin"))
def _apply_total_row_border(ws, row, first_col=1, last_col=10):
"""Apply _TOTAL_ROW_BORDER across every column from first_col to
last_col (A:J by default) on one row - including columns that have
no value in them, so the rule reads as a single unbroken line
across the whole row, not just under the cells that happen to hold
text or a formula."""
for col in range(first_col, last_col + 1):
ws.cell(row=row, column=col).border = _TOTAL_ROW_BORDER
def write_source_sheet(wb, df, sheet_name, hidden=False):
"""
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.
hidden: when True, the sheet is created but marked hidden (still
fully readable by any formula referencing it - Excel doesn't care
whether a sheet is hidden when evaluating formulas, only when
displaying its own tab bar) - used for the Budget sheet once a
nicer-looking, styled copy of the actual uploaded file is also
present (see _copy_original_budget_sheet/build_report_workbook):
this plain data dump keeps powering every live SUMIFS formula, it's
just not the one a person is meant to look at directly anymore.
"""
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
if hidden:
ws.sheet_state = "hidden"
return ws
def _copy_original_budget_sheet(wb, file_path, sheet_name):
"""
A VISIBLE, faithfully-styled copy of the uploaded Budget file's own
first sheet - fonts, fills, borders, number formats, column widths,
row heights, merged cell ranges, and the file's own formulas (not
flattened to values) - straight from file_path (the actual uploaded
.xlsx, untouched - see STORED_BUDGET_PATH/save_stored_budget_file).
Unlike write_source_sheet's "Budget" data sheet (still built and
still what every live SUMIFS formula in Category Summary actually
reads - see build_report_workbook - but now hidden), this sheet
exists purely so a person opening the file sees something that
looks like what they actually uploaded, not a plain computer-
generated table. Editing THIS sheet has no effect on any calculated
figure - a comment on its own A1 says so, since nothing else about
its appearance would otherwise suggest that.
Best-effort: openpyxl can't carry over everything a workbook can
contain (conditional formatting, data validation, images/charts,
cell comments of the ORIGINAL file aren't copied), but covers
everything a typical budget spreadsheet actually uses. Only the
file's first sheet is copied - same assumption load_budget_file
already makes (sheet_name=0) - so a formula referencing a different
sheet in the original file won't resolve here.
"""
src_wb = openpyxl.load_workbook(file_path, data_only=False)
src_ws = src_wb.worksheets[0]
dst_ws = wb.create_sheet(sheet_name)
for row in src_ws.iter_rows():
for cell in row:
if cell.value is None and not cell.has_style:
continue
new_cell = dst_ws.cell(row=cell.row, column=cell.column, value=cell.value)
if cell.has_style:
new_cell.font = copy.copy(cell.font)
new_cell.fill = copy.copy(cell.fill)
new_cell.border = copy.copy(cell.border)
new_cell.alignment = copy.copy(cell.alignment)
new_cell.protection = copy.copy(cell.protection)
new_cell.number_format = cell.number_format
for col_letter, dim in src_ws.column_dimensions.items():
if dim.width:
dst_ws.column_dimensions[col_letter].width = dim.width
for row_idx, dim in src_ws.row_dimensions.items():
if dim.height:
dst_ws.row_dimensions[row_idx].height = dim.height
for merged_range in src_ws.merged_cells.ranges:
dst_ws.merge_cells(str(merged_range))
if src_ws.freeze_panes:
dst_ws.freeze_panes = src_ws.freeze_panes
note_cell = dst_ws.cell(row=1, column=1)
note_cell.comment = Comment(
"Reference copy of the uploaded Budget file, for readability only. "
"Editing this sheet has no effect on any figure in this report - "
"the live calculations read from a separate, hidden copy of this "
"same data (see the hidden \"Budget\" sheet).",
"Financial Reports",
)
return dst_ws
def _tb_source_cols(df):
"""
Maps a TB sheet's "Ledger Account" and (appended) "Category
(Applied)"/"Project (Applied)" columns to their exact column letters
as written by write_source_sheet (same column order as df.columns,
header row 1) - same pattern as _budget_sheet_columns, for the
Revenue TB/Expense TB sheets instead of the Budget sheet. df must
already carry the two appended "(Applied)" columns (see
_compute_applied_category_project / build_report_workbook) - "Ledger
Account" itself is always column A, unaffected by anything appended
after it.
"""
columns = list(df.columns)
def letter_of(name):
return get_column_letter(columns.index(name) + 1)
return {"account": letter_of("Ledger Account"), "category": letter_of("Category (Applied)"), "project": letter_of("Project (Applied)")}
def _sumifs_expr(sheet_name, amount_col_letter, cols, 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.
cols = {"account", "category", "project"} -> column letter on
sheet_name. Criteria are matched against the "Category (Applied)"/
"Project (Applied)" columns (see _compute_applied_category_project),
not the sheet's own original Revenue/Spend Category or Project
columns - those stay an untouched, verbatim copy of what was
uploaded, so any reassignment or 79000/81000 forced-collapse
wouldn't otherwise be reflected there for a criteria match to find.
Unlike those original columns, "(Applied)" cells are never truly
blank - a missing category/project is always written out as the
literal "(Uncategorized)"/"(No project)" placeholder text - so,
unlike this function's pre-"(Applied)"-column predecessor, the
criteria is always the literal category/project text, never an
empty-string/ISBLANK-style substitute.
"""
cat_crit = f'"{_excel_str(category)}"'
proj_crit = 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}'!{cols['account']}:{cols['account']},{acct_crit},"
f"'{sheet_name}'!{cols['category']}:{cols['category']},{cat_crit},"
f"'{sheet_name}'!{cols['project']}:{cols['project']},{proj_crit})"
)
def _sumifs_expr_no_project(sheet_name, amount_col_letter, cols, 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 = f'"{_excel_str(category)}"'
acct_crit = f'"{_excel_str(account)}"'
return (
f"SUMIFS('{sheet_name}'!{amount_col_letter}:{amount_col_letter},"
f"'{sheet_name}'!{cols['account']}:{cols['account']},{acct_crit},"
f"'{sheet_name}'!{cols['category']}:{cols['category']},{cat_crit})"
)
def _budget_sumifs_expr(sheet_name, sum_col_letter, cols, account, category, project_code):
"""
Same shape as _sumifs_expr, but against the raw "Budget" sheet (a
verbatim copy of the uploaded Budget file - see write_source_sheet)
instead of the trial balance. cols = {"account", "category",
"project"} column letters on that sheet (see _budget_sheet_columns -
these vary run to run, since they're wherever the uploaded file's
own columns land, not a fixed layout). project_code is first mapped
back to whatever spelling the Budget file itself actually uses (see
_REVERSE_BUDGET_PROJECT_FIXES) - the criteria has to match the real
text sitting in that sheet, not the TB's own spelling of the same
project.
"""
cat_crit = '""' if category == "(Uncategorized)" else f'"{_excel_str(category)}"'
budget_project = _REVERSE_BUDGET_PROJECT_FIXES.get(project_code, project_code)
proj_crit = '""' if project_code == "(No project)" else f'"{_excel_str(budget_project)}"'
acct_crit = f'"{_excel_str(account)}"'
return (
f"SUMIFS('{sheet_name}'!{sum_col_letter}:{sum_col_letter},"
f"'{sheet_name}'!{cols['account']}:{cols['account']},{acct_crit},"
f"'{sheet_name}'!{cols['category']}:{cols['category']},{cat_crit},"
f"'{sheet_name}'!{cols['project']}:{cols['project']},{proj_crit})"
)
def _budget_sumifs_expr_no_project(sheet_name, sum_col_letter, cols, account, category):
"""Same as _budget_sumifs_expr but without the Project criterion -
used for accounts that aren't broken out by project (70000 and up),
matching _sumifs_expr_no_project's own reasoning."""
cat_crit = '""' if category == "(Uncategorized)" else f'"{_excel_str(category)}"'
acct_crit = f'"{_excel_str(account)}"'
return (
f"SUMIFS('{sheet_name}'!{sum_col_letter}:{sum_col_letter},"
f"'{sheet_name}'!{cols['account']}:{cols['account']},{acct_crit},"
f"'{sheet_name}'!{cols['category']}:{cols['category']},{cat_crit})"
)
def _budget_sheet_columns(budget_df, report_date):
"""
Maps the raw Budget file's own Account/Category/Project Code/Total -
CAD columns, plus which month columns (Aug through report_date's own
month) are in scope for YTD, to their exact column letters on the
"Budget" sheet as written by write_source_sheet (same column order
as budget_df.columns, header row 1, data from row 2 - a plain,
unmodified copy of the uploaded file below its own header row, so
whatever column a field lands in there is exactly where it started
relative to the file's own header row).
Returns (cols, ytd_month_letters, full_year_letter): cols is
{"account", "category", "project"} -> column letter; ytd_month_letters
is the ordered list of month column letters on or before report_date;
full_year_letter is the "Total - CAD" column.
"""
columns = list(budget_df.columns)
def letter_of(name):
return get_column_letter(columns.index(name) + 1)
cols = {"account": letter_of("Account"), "category": letter_of("Category"), "project": letter_of("Project Code")}
full_year_letter = letter_of("Total - CAD")
months = _budget_month_columns(budget_df)
cutoff = datetime.strptime(report_date, "%Y-%m-%d")
ytd_month_letters = [letter_of(name) for month, name in months if month <= cutoff]
return cols, ytd_month_letters, full_year_letter
def _write_variance_cell(ws, row, budget_ctx, total_col, bold):
total_letter = ws.cell(row=row, column=total_col).column_letter
budget_letter = ws.cell(row=row, column=budget_ctx["budget_col"]).column_letter
c = ws.cell(row=row, column=budget_ctx["variance_col"], value=f"={total_letter}{row}-{budget_letter}{row}")
c.font = BOLD_FONT if bold else REGULAR_FONT
c.number_format = budget_ctx["number_format"]
def _write_budget_detail_cells(ws, row, budget_ctx, total_col, account, category, project=None):
"""
Budget (YTD)/Budget (Full Year) as live SUMIFS formulas against the
raw "Budget" sheet (a verbatim copy of the uploaded file, written by
build_report_workbook via write_source_sheet before Category Summary
is built), plus a live Variance
(=Total YTD - Budget YTD) formula. Matches by (account, category,
project) when project is given (the PROJECT_LEVEL_ACCOUNT_CODES
rows), or by (account, category) alone - matching every project at
once - for the "70000 and up" rows that never show a project split
of their own. YTD sums one SUMIFS term per month column from Aug
through report_date's own month (joined with "+"); Full Year is a
single SUMIFS against the file's own "Total - CAD" column. No-op
(leaves the cells blank) if budget_ctx is None - no budget file was
uploaded, or it wasn't the detailed format.
"""
if budget_ctx is None:
return
sheet_name, cols = budget_ctx["sheet_name"], budget_ctx["cols"]
if project is not None:
ytd_terms = [_budget_sumifs_expr(sheet_name, mc, cols, account, category, project)
for mc in budget_ctx["ytd_month_letters"]]
full_year_formula = "=" + _budget_sumifs_expr(sheet_name, budget_ctx["full_year_letter"], cols, account, category, project)
else:
ytd_terms = [_budget_sumifs_expr_no_project(sheet_name, mc, cols, account, category)
for mc in budget_ctx["ytd_month_letters"]]
full_year_formula = "=" + _budget_sumifs_expr_no_project(sheet_name, budget_ctx["full_year_letter"], cols, account, category)
ytd_formula = "=" + "+".join(ytd_terms) if ytd_terms else "=0"
c = ws.cell(row=row, column=budget_ctx["budget_col"], value=ytd_formula)
c.font, c.number_format = REGULAR_FONT, budget_ctx["number_format"]
c = ws.cell(row=row, column=budget_ctx["full_year_col"], value=full_year_formula)
c.font, c.number_format = REGULAR_FONT, budget_ctx["number_format"]
_write_variance_cell(ws, row, budget_ctx, total_col, bold=False)
def _write_budget_range_cells(ws, row, budget_ctx, total_col, first_r, last_r):
"""Budget (YTD)/Budget (Full Year) as a live SUM(first_r:last_r)
formula for a subtotal row over its own CONTIGUOUS detail rows
(a category's detail rows, an account's category-subtotal rows),
plus Variance. No-op if budget_ctx is None."""
if budget_ctx is None:
return
for col in (budget_ctx["budget_col"], budget_ctx["full_year_col"]):
letter = ws.cell(row=first_r, column=col).column_letter
c = ws.cell(row=row, column=col, value=f"=SUM({letter}{first_r}:{letter}{last_r})")
c.font, c.number_format = BOLD_FONT, budget_ctx["number_format"]
_write_variance_cell(ws, row, budget_ctx, total_col, bold=True)
def _write_budget_sum_of_rows_cells(ws, row, budget_ctx, total_col, source_rows):
"""Budget (YTD)/Budget (Full Year) as a live sum of specific,
non-contiguous row numbers (e.g. "Project Costs" summing just
68010's and 68030's own account-subtotal rows), plus Variance.
No-op if budget_ctx is None."""
if budget_ctx is None:
return
for col in (budget_ctx["budget_col"], budget_ctx["full_year_col"]):
letter = ws.cell(row=row, column=col).column_letter
formula = "=" + "+".join(f"{letter}{r}" for r in source_rows) if source_rows else 0
c = ws.cell(row=row, column=col, value=formula)
c.font, c.number_format = BOLD_FONT, budget_ctx["number_format"]
_write_variance_cell(ws, row, budget_ctx, total_col, bold=True)
def _write_budget_diff_cells(ws, row, budget_ctx, total_col, minuend_row, subtrahend_row):
"""Budget (YTD)/Budget (Full Year) as (another row's value) minus
(a third row's value), not a sum - "Net Revenues" (Total Revenue -
Project Costs) and "Surplus/(Deficit)" (Total Revenue - Total
Expenses) both need this shape, not SUM. No-op if budget_ctx is
None."""
if budget_ctx is None:
return
for col in (budget_ctx["budget_col"], budget_ctx["full_year_col"]):
letter = ws.cell(row=row, column=col).column_letter
c = ws.cell(row=row, column=col, value=f"={letter}{minuend_row}-{letter}{subtrahend_row}")
c.font, c.number_format = BOLD_FONT, budget_ctx["number_format"]
_write_variance_cell(ws, row, budget_ctx, total_col, bold=True)
def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, number_format,
source_sheet_name, source_cols, flip_sign, total_revenue_row=None, budget_ctx=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', source_cols, account, category, r['project_code'])}"
us_formula = f"={sign}{_sumifs_expr(source_sheet_name, 'E', source_cols, 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
_write_budget_detail_cells(ws, row, budget_ctx, total_col, account, category, r["project_code"])
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
_write_budget_range_cells(ws, cat_subtotal_row, budget_ctx, total_col, cat_first_row, cat_last_row)
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
_write_budget_sum_of_rows_cells(ws, account_subtotal_row, budget_ctx, total_col, category_subtotal_rows)
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', source_cols, account, category)}"
us_formula = f"={sign}{_sumifs_expr_no_project(source_sheet_name, 'E', source_cols, 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
_write_budget_detail_cells(ws, row, budget_ctx, total_col, account, category)
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)
_write_cell(ws, account_subtotal_row, 2, f"Total {account.split(':', 1)[1].strip()}", 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
_write_budget_range_cells(ws, account_subtotal_row, budget_ctx, total_col, first_r, last_r)
_apply_total_row_border(ws, account_subtotal_row)
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, 2, "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
_write_budget_sum_of_rows_cells(ws, row, budget_ctx, total_col, project_cost_rows)
_apply_total_row_border(ws, row)
row += 1
_write_cell(ws, row, 2, "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
_write_budget_diff_cells(ws, row, budget_ctx, total_col, total_revenue_row, project_costs_row)
_apply_total_row_border(ws, row)
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, budget_df=None,
revenue_source_cols=None, expense_source_cols=None):
"""
revenue_source_cols / expense_source_cols: column-letter maps (see
_tb_source_cols) for the Revenue TB/Expense TB sheets' "Ledger
Account" and appended "Category (Applied)"/"Project (Applied)"
columns - required whenever any live SUMIFS formula will be written
(i.e. whenever revenue_df/expense_df are non-empty), since the
criteria have to hit those columns, not the sheet's own untouched
Revenue/Spend Category or Project columns (see _sumifs_expr).
budget_df: optional, a loaded Budget file (see load_budget_file).
When it's the detailed format (see budget_is_detailed), three extra
columns get populated onto these same (account, category, project)
rows as live SUMIFS formulas against the raw "Budget" sheet (see
_write_budget_detail_cells) - Budget (YTD) (Aug through report_date's
own month), Variance (Total YTD - Budget YTD), and Budget (Full Year)
(the budget file's own full fiscal-year total, unconditional on
report_date). Omitted (left blank, as always) when budget_df is None
or is the older, non-detailed format, which doesn't carry a category
of its own to key this on.
"""
ws = wb.create_sheet("1. Summary (Manual)")
for col, width in zip("ABCDEFGHIJ", (32, 20, 34, 15, 15, 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 Entity YTD", "US Entity YTD",
"Consolidation Adjustments", "Actual Total YTD", "Budget YTD", "Variance", "Budget FY-27"]
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, VARIANCE_COL, FULL_YEAR_COL = 4, 5, 6, 7, 8, 9, 10
budget_ctx = None
if budget_df is not None and budget_is_detailed(budget_df):
cols, ytd_month_letters, full_year_letter = _budget_sheet_columns(budget_df, report_date)
budget_ctx = {
"sheet_name": "Budget", "cols": cols,
"ytd_month_letters": ytd_month_letters, "full_year_letter": full_year_letter,
"budget_col": BUDGET_COL, "variance_col": VARIANCE_COL, "full_year_col": FULL_YEAR_COL,
"number_format": number_format,
}
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, revenue_source_cols, flip_sign=True, budget_ctx=budget_ctx,
)
total_revenue_row = row
_write_cell(ws, row, 2, "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
_write_budget_sum_of_rows_cells(ws, row, budget_ctx, TOTAL_COL, rev_subtotals)
_apply_total_row_border(ws, row)
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, expense_source_cols, flip_sign=False, total_revenue_row=total_revenue_row, budget_ctx=budget_ctx,
)
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
_write_budget_sum_of_rows_cells(ws, row, budget_ctx, TOTAL_COL, exp_subtotals)
_apply_total_row_border(ws, row)
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
_write_budget_diff_cells(ws, row, budget_ctx, TOTAL_COL, total_revenue_row, total_expenses_row)
_apply_total_row_border(ws, row)
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)
# Variance (column I - see VARIANCE_COL) below -$0.0001 (a real
# overspend against budget, not just floating-point noise around
# exactly $0) shows in red - covers every detail/subtotal/total row
# that has a Variance figure at all, from the first data row through
# Surplus/(Deficit) (the last one).
variance_col_letter = get_column_letter(VARIANCE_COL)
ws.conditional_formatting.add(
f"{variance_col_letter}{header_row + 1}:{variance_col_letter}{surplus_row}",
CellIsRule(operator="lessThan", formula=["-0.0001"], font=Font(color="FFFF0000")),
)
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,
}
def _gl_uncategorized_detail_rows(gl_df):
"""
Every posted GL Dump line (see common.load_gl_dump) under a tracked
revenue or expense account whose own category field - Revenue
Category for a revenue account, Spend Category as Worktag for an
expense account, since the GL Dump carries both revenue AND expense
lines together in one file, unlike the TB exports' separate RC/SC
sheets - or Project is blank: the GL-level version of the same
"(Uncategorized)"/"(No project)" gap Category Summary flags on its
own aggregated rows (see process_category_summary, same blank
check), but at full transaction detail - every individual journal
line, every one of the GL Dump's own ~54 columns - rather than one
row per already-aggregated TB combination. That's what's actually
needed to trace a gap back to its source and correct the tagging at
the transaction level, not just confirm a gap exists.
Returns a copy of the flagged rows (all original GL Dump columns
intact) plus "_signed_amount" (Net Ledger Debit minus Credit,
sign-flipped for revenue accounts to match Category Summary's own
convention) and "_reason"; empty (with those columns) if nothing is
flagged or gl_df is None.
"""
if gl_df is None:
return None
codes = REVENUE_ACCOUNT_CODES + EXPENSE_ACCOUNT_CODES
d = gl_df[gl_df["Ledger Account"].astype(str).str.strip().str.startswith(codes)].copy()
if d.empty:
return d
account_code = d["Ledger Account"].astype(str).str.split(":", n=1).str[0].str.strip()
is_revenue = account_code.isin(REVENUE_ACCOUNT_CODES)
category_value = d["Revenue Category"].where(is_revenue, d["Spend Category as Worktag"])
cat_blank = category_value.isna() | (category_value.astype(str).str.strip() == "")
proj_blank = d["Project"].isna() | (d["Project"].astype(str).str.strip() == "")
flagged = d[cat_blank | proj_blank].copy()
if flagged.empty:
return flagged
signed = flagged["Net Ledger Debit minus Credit"].fillna(0)
is_revenue_f = is_revenue[flagged.index]
flagged["_signed_amount"] = signed.where(~is_revenue_f, -signed)
cat_blank_f, proj_blank_f = cat_blank[flagged.index], proj_blank[flagged.index]
flagged["_reason"] = [
"No Category & No Project" if c and p else ("No Category" if c else "No Project")
for c, p in zip(cat_blank_f, proj_blank_f)
]
return flagged.sort_values(["Ledger Account"])
def build_uncategorized_detail_sheet(wb, gl_df, report_date, title, number_format):
"""
"Uncategorized Detail" sheet: every posted GL Dump line behind a
"(Uncategorized)" or "(No project)" row on Category Summary, at full
transaction detail - every one of the GL Dump's own ~54 columns
(Journal Memo, Line Memo, Supplier Name, Cost Center, everything),
not just the handful Category Summary itself shows - since actually
fixing a tagging gap means tracing it back to the real journal line,
not just knowing a gap exists (see _gl_uncategorized_detail_rows).
"Amount (Summary sign)" is Net Ledger Debit minus Credit (one of the
verbatim columns already on this same row) with revenue's sign
flipped to match Category Summary's own convention - a plain value,
not a formula pointing elsewhere: unlike the Budget/TB-linked
figures elsewhere in this workbook, there's no aggregation here to
trace back through - the full, unaggregated source row is already
sitting right next to it. Requires a GL Dump upload - the caller
(build_report_workbook) only calls this when gl_df is not None, same
optional-input pattern as the Balance Sheet supporting schedules.
Returns {"row_count", "total"}.
"""
flagged = _gl_uncategorized_detail_rows(gl_df)
gl_columns = list(gl_df.columns)
ws = wb.create_sheet("Uncategorized Detail")
ws.column_dimensions["A"].width = 22
ws.column_dimensions["B"].width = 15
for col_idx in range(3, len(gl_columns) + 3):
ws.column_dimensions[get_column_letter(col_idx)].width = 20
_write_cell(ws, 1, 1, title, bold=True)
_write_cell(ws, 2, 1, f"Uncategorized / No-Project Detail (from the GL Dump) — {report_date}", bold=True)
_write_cell(ws, 3, 1,
'Every posted GL Dump line behind a "(Uncategorized)" or "(No project)" row on '
'1. Summary (Manual) - full transaction detail, every GL Dump column, to trace and correct at the source.',
italic=True)
header_row = 5
headers = ["Why flagged", "Amount (Summary sign)"] + gl_columns
for col, label in enumerate(headers, start=1):
_write_cell(ws, header_row, col, label, bold=True)
row = header_row + 1
if flagged.empty:
_write_cell(ws, row, 1, "None found", italic=True)
return {"row_count": 0, "total": 0.0}
first_row = row
for _, r in flagged.iterrows():
_write_cell(ws, row, 1, r["_reason"])
c = ws.cell(row=row, column=2, value=round(r["_signed_amount"], 2))
c.font, c.number_format = REGULAR_FONT, number_format
for col_idx, col_name in enumerate(gl_columns, start=3):
val = r[col_name]
ws.cell(row=row, column=col_idx, value=None if pd.isna(val) else val)
row += 1
last_row = row - 1
total_row = row + 1
_write_cell(ws, total_row, 1, "Total", bold=True)
c = ws.cell(row=total_row, column=2, value=f"=SUM(B{first_row}:B{last_row})")
c.font, c.number_format = BOLD_FONT, number_format
return {"row_count": last_row - first_row + 1, "total": round(flagged["_signed_amount"].sum(), 2)}
return {"revenue_count": counts["revenue"], "expense_count": counts["expense"], "total": round(total, 2)}
def build_reassignment_reference_sheet(wb, title):
"""
"Reassignment Reference" sheet: for every category or project that's
actually been reassigned (a real, non-blank target on record - see
list_category_mappings/list_project_mappings) or forced-collapsed
(79000/81000 - see FORCED_CATEGORY_BY_ACCOUNT), what the ORIGINAL
text looked like in the uploaded TB/GL before Category Summary
folded it into the value shown there.
Everywhere else on Category Summary, the Account/Category/Project
Code columns already ARE the right filter criteria for an external
GL export - nothing was renamed, so there's nothing to bridge. This
sheet exists only to cover the handful of cases where that's no
longer true, without duplicating any GL/TB data itself. "Leave as
is" decisions (blank target) are skipped - nothing was actually
renamed for those, so there's no original-vs-shown-as gap to list.
Returns the number of rows written, or None if there's nothing to
show (the sheet isn't created at all in that case).
"""
rows = []
for m in list_category_mappings():
if m["target"]:
rows.append({"account_code": m["account_code"], "type": "Category", "original": m["source"], "shows_as": m["target"]})
for m in list_project_mappings():
if m["target"]:
rows.append({"account_code": m["account_code"], "type": "Project", "original": m["source"], "shows_as": m["target"]})
for code, forced in FORCED_CATEGORY_BY_ACCOUNT.items():
rows.append({"account_code": code, "type": "Category", "original": "(any - every category under this account)", "shows_as": forced})
if not rows:
return None
rows.sort(key=lambda r: (r["account_code"], r["type"], r["original"]))
ws = wb.create_sheet("Reassignment Reference")
for col, width in zip("ABCD", (14, 12, 46, 46)):
ws.column_dimensions[col].width = width
_write_cell(ws, 1, 1, title, bold=True)
_write_cell(ws, 2, 1, "What Category Summary's reassigned/collapsed rows originally looked like in your GL/TB", bold=True)
_write_cell(ws, 3, 1,
"Everywhere else, Category Summary's own Account/Category/Project Code columns are already "
"the right filter criteria for an external GL export - this is only the exceptions.",
italic=True)
header_row = 5
for col, label in enumerate(["Account Code", "Type", "Original Value (in your GL/TB)", "Shows As (in Category Summary)"], start=1):
_write_cell(ws, header_row, col, label, bold=True)
row = header_row + 1
for r in rows:
_write_cell(ws, row, 1, r["account_code"])
_write_cell(ws, row, 2, r["type"])
_write_cell(ws, row, 3, r["original"])
_write_cell(ws, row, 4, r["shows_as"])
row += 1
return len(rows)
def build_gl_detail_sheet(wb, gl_df, category_map, project_map, report_date, title, number_format):
"""
"GL Detail" sheet: every revenue/expense GL Dump line (see
common.load_gl_dump), tagged with "Account (Applied)"/"Category
(Applied)"/"Project (Applied)" columns computed the exact same way
Category Summary itself groups rows - reassignment and 79000/81000
forced collapse both applied (see
_apply_reassignment_and_forced_collapse) - then sorted by that same
(account, category, project) hierarchy. Scrolling down this sheet
lines up with scrolling down "1. Summary (Manual)": the block of GL
lines behind any given account/category sits together, in the same
relative order, nothing to filter or cross-reference by hand.
(Account sorts in plain ascending order here, not Category
Summary's own project-level-accounts-first bucketing used purely
for the Project Costs/Net Revenues subtotal placement - the
grouping hierarchy is the same, the physical row sequence for
project-cost accounts isn't.)
A genuinely separate, static reference - nothing on Category
Summary points at this sheet, so it can't affect any calculated
figure, and building it can't break anything already working (same
reasoning as build_uncategorized_detail_sheet, just not limited to
"(Uncategorized)"/"(No project)" rows).
Unlike the GL Dump's raw "Revenue Category"/"Spend Category as
Worktag" columns (one or the other populated depending on the row,
never both), "Category (Applied)" is always one single column,
since that's the whole point - the same shape Category Summary
itself groups by.
Returns {"row_count", "total"}, or None if gl_df is None.
"""
if gl_df is None:
return None
codes = REVENUE_ACCOUNT_CODES + EXPENSE_ACCOUNT_CODES
d = gl_df[gl_df["Ledger Account"].astype(str).str.strip().str.startswith(codes)].copy()
gl_columns = list(gl_df.columns)
ws = wb.create_sheet("GL Detail")
ws.column_dimensions["A"].width = 32
ws.column_dimensions["B"].width = 28
ws.column_dimensions["C"].width = 34
ws.column_dimensions["D"].width = 15
for col_idx in range(5, len(gl_columns) + 5):
ws.column_dimensions[get_column_letter(col_idx)].width = 20
_write_cell(ws, 1, 1, title, bold=True)
_write_cell(ws, 2, 1, f"GL Detail — {report_date}", bold=True)
_write_cell(ws, 3, 1,
"Every revenue/expense GL Dump line, tagged and sorted the same way Category Summary "
"groups its own rows (Account, Category, Project Code) - scroll both sheets together.",
italic=True)
header_row = 5
headers = ["Account (Applied)", "Category (Applied)", "Project (Applied)", "Amount (Summary sign)"] + gl_columns
for col, label in enumerate(headers, start=1):
_write_cell(ws, header_row, col, label, bold=True)
row = header_row + 1
if d.empty:
_write_cell(ws, row, 1, "None found", italic=True)
return {"row_count": 0, "total": 0.0}
account_code = d["Ledger Account"].astype(str).str.split(":", n=1).str[0].str.strip()
is_revenue = account_code.isin(REVENUE_ACCOUNT_CODES)
raw_category = d["Revenue Category"].where(is_revenue, d["Spend Category as Worktag"])
d["Account (Applied)"] = _canonicalize_text(d["Ledger Account"])
category = _canonicalize_text(raw_category.fillna("(Uncategorized)"))
project_code = _canonicalize_text(d["Project"].fillna("(No project)"))
d["Category (Applied)"], d["Project (Applied)"] = _apply_reassignment_and_forced_collapse(
category, project_code, account_code, category_map, project_map,
)
signed = pd.to_numeric(d[GL_AMOUNT_COL], errors="coerce").fillna(0)
d["_signed_amount"] = signed.where(~is_revenue, -signed)
d = d.sort_values(["Account (Applied)", "Category (Applied)", "Project (Applied)"])
first_row = row
for _, r in d.iterrows():
_write_cell(ws, row, 1, r["Account (Applied)"])
_write_cell(ws, row, 2, r["Category (Applied)"])
_write_cell(ws, row, 3, r["Project (Applied)"])
c = ws.cell(row=row, column=4, value=round(r["_signed_amount"], 2))
c.font, c.number_format = REGULAR_FONT, number_format
for col_idx, col_name in enumerate(gl_columns, start=5):
val = r[col_name]
ws.cell(row=row, column=col_idx, value=None if pd.isna(val) else val)
row += 1
last_row = row - 1
total_row = row + 1
_write_cell(ws, total_row, 1, "Total", bold=True)
c = ws.cell(row=total_row, column=4, value=f"=SUM(D{first_row}:D{last_row})")
c.font, c.number_format = BOLD_FONT, number_format
return {"row_count": last_row - first_row + 1, "total": round(d["_signed_amount"].sum(), 2)}
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 get_schedule_accounts(tb_df):
"""
Distinct Ledger Account values (code:name) with a code prefix of 1, 2
or 3 (Balance Sheet - Assets/Liabilities/Equity; 4 and up is Revenue/
Expense, out of scope here) and a nonzero Canada balance, each mapped
to that balance. Reads from ONE trial balance file only - both
uploads are full trial balance exports containing the same Balance
Sheet rows, so summing both would double it (same reasoning as
compute_balance_sheet's own single-file read). Returns an ordered
dict-like {account: tb_balance}, sorted by account code.
"""
df = tb_df.copy()
df["_code"] = df["Ledger Account"].astype(str).str.strip().str.extract(r"^(\d+)")[0]
df = df[df["_code"].notna() & df["_code"].str[0].isin(SCHEDULE_ACCOUNT_PREFIXES)]
grouped = df.groupby("Ledger Account")["Planeterra Foundation"].sum().round(2)
grouped = grouped[grouped.abs() >= 0.005]
return grouped.sort_index().to_dict()
def _normalize_memo(memo):
"""
Strip a trailing month/year or bare fiscal-year reference (full or
abbreviated month, any case) so recurring monthly/annual entries like
"Vacation accrual - July 2026", "- June 2026" and "Trees Accrual -
FY25" group under one label. Then drop a small set of generic
accounting filler words ("Project", "Expense(s)", "Accrual", "Final")
that otherwise keep the SAME recurring item split across several
near-identical phrasings - confirmed for real: "Trees Expense
Accrual", "Project Trees Expenses Accrual", "Trees Expense Final
Accrual" and "Trees Accrual - FY25" are the same underlying accrual,
and left unmerged, they also broke the revaluation-folding logic by
creating extra ambiguous Project-match candidates (see
_attribute_revaluation_lines). If stripping filler words would leave
nothing, the original (date-stripped) text is kept instead - an
unmerged category is a cosmetic imperfection; an empty one isn't.
"""
text = _TRAILING_MONTH_RE.sub("", str(memo))
text = _FISCAL_YEAR_RE.sub("", text).strip()
words = [w for w in re.split(r"\s+", text) if w]
significant = [w for w in words if w.lower().strip("-,.") not in _CATEGORY_STOPWORDS]
return " ".join(significant).strip(" -") or text
def _categorize_schedule_line(row, account_code):
"""Returns (label, is_reliable) - the shape common.build_gl_schedule's
categorize_fn expects. is_reliable=True means "trust this and never
re-fold it as a revaluation line" (see common._attribute_revaluation_lines).
Contingent Worker first, but ONLY for the expense-report clearing
accounts in CONTINGENT_WORKER_ACCOUNT_CODES - those accounts are
fundamentally "who submitted this expense report", not "what was it
for", and confirmed for real to never carry a Spend Category (0% on
both 13170 and 20130) while Contingent Worker is populated on the
large majority of their lines. For every other account: Spend
Category as Worktag - a real, structured GL field, so trusted as-is
with no text normalization - when the line carries one (confirmed for
real: coverage varies hugely by account, from ~88% on accrual-type
accounts like 20300/13100 down to 0% on AP/AR-type accounts, so this
is never assumed present). Otherwise falls back to the prior
heuristic - Supplier Name, then Line Memo, then Journal Memo, with
any trailing month/year stripped so recurring entries merge
automatically (not reliable - this is exactly what
_attribute_revaluation_lines exists to patch up for a reval-shaped
line) - unchanged for accounts that don't tag a Spend Category at
all, and also the fallback within a Contingent Worker account for
whichever lines don't have one."""
if account_code in CONTINGENT_WORKER_ACCOUNT_CODES:
worker = row.get("Contingent Worker")
if pd.notna(worker) and str(worker).strip():
return str(worker).strip(), True
spend_category = row.get("Spend Category as Worktag")
if pd.notna(spend_category) and str(spend_category).strip():
return str(spend_category).strip(), True
supplier = row.get("Supplier Name")
if pd.notna(supplier):
return supplier, False
memo = row.get("Line Memo")
if pd.isna(memo):
memo = row.get("Journal Memo")
if pd.isna(memo):
return "(no memo)", False
return _normalize_memo(memo), False
def build_account_schedule(gl_df, account):
"""
Full supporting-schedule pipeline for one Balance Sheet account:
filter to this account's posted GL lines, net out reversals/wash
entries (see common.net_gl_lines - pass order matters, see its own
docstring), then categorize and group what's left by (category,
currency) with an effective FX rate per group (see
common.build_gl_schedule). Returns the grouped schedule DataFrame
(empty if there's no GL activity at all for this account - the
caller's reconciliation check will flag that against a nonzero trial
balance rather than silently showing nothing).
"""
account_code = account.split(":")[0]
sub = gl_df[gl_df["Ledger Account"].astype(str).str.strip().str.startswith(account_code)].copy()
sub = sub[sub[GL_AMOUNT_COL].abs() >= 0.005]
empty_columns = ["category", "orig_currency", "orig_total", "cad_total", "rate", "amt_cad", "memo", "line_memo"]
if sub.empty:
return pd.DataFrame(columns=empty_columns)
sub = net_gl_lines(sub)
if sub.empty:
return pd.DataFrame(columns=empty_columns)
schedule = build_gl_schedule(
sub, lambda row: _categorize_schedule_line(row, account_code),
extra_columns=["Journal Memo", "Line Memo"],
)
return schedule.rename(columns={"Journal Memo": "memo", "Line Memo": "line_memo"})
_SCHEDULE_SHEET_INVALID_CHARS = re.compile(r'[:\\/?*\[\]]')
def _sanitize_schedule_sheet_name(account):
code, _, name = account.partition(":")
label = f"{code} {name}".strip() if name else code
cleaned = _SCHEDULE_SHEET_INVALID_CHARS.sub("", label)
return cleaned[:31] or "Schedule"
def write_schedule_sheet(wb, account, schedule_df, tb_total, report_date, title, number_format):
"""
Write one supporting schedule sheet for a single Balance Sheet
account: Description | Memo | Line Memo | Original Curr | Curr | Rate
| Amt (CAD), one row per (category, currency) - the same category
appears more than once if it carries balances in more than one
currency (e.g. an accrual with both a CAD and a USD portion). Memo/
Line Memo show the raw Journal Memo/Line Memo off whichever single GL
line contributed the largest absolute amount to that row (see
_build_schedule_rows) - a representative sample, not every line's
memo, since the row itself is a sum across possibly many GL lines. A
Total row sums Amt (CAD) via a live formula, checked alongside the
account's own trial balance figure with a MATCH/MISMATCH indicator -
the same "arithmetic check back to the uploaded files" pattern used
throughout this tool.
"""
ws = wb.create_sheet(_sanitize_schedule_sheet_name(account))
ws.column_dimensions["A"].width = 46
for col, width in zip("BC", (28, 28)):
ws.column_dimensions[col].width = width
for col, width in zip("DEF", (15, 7, 9)):
ws.column_dimensions[col].width = width
ws.column_dimensions["G"].width = 16
_write_cell(ws, 1, 1, title, bold=True)
_write_cell(ws, 2, 1, f"Supporting Schedule — {account}", bold=True)
_write_cell(ws, 3, 1, f"As of {report_date}", bold=True)
header_row = 5
for col, label in enumerate(
["Description", "Memo", "Line Memo", "Original Curr", "Curr", "Rate", "Amt (CAD)"], start=1
):
_write_cell(ws, header_row, col, label, bold=True)
row = header_row + 1
first_data_row = row
if schedule_df.empty:
_write_cell(ws, row, 1, "No matching GL activity found for this account", bold=False)
_write_cell(ws, row, 7, 0, bold=False, number_format=number_format)
row += 1
for _, r in schedule_df.iterrows():
_write_cell(ws, row, 1, r["category"], bold=False)
_write_cell(ws, row, 2, r["memo"] if r["memo"] else "", bold=False)
_write_cell(ws, row, 3, r["line_memo"] if r["line_memo"] else "", bold=False)
if r["rate"] is not None:
_write_cell(ws, row, 4, round(r["orig_total"], 2), bold=False, number_format=number_format)
_write_cell(ws, row, 5, r["orig_currency"], bold=False)
_write_cell(ws, row, 6, round(r["rate"], 4), bold=False, number_format="0.0000")
_write_cell(ws, row, 7, round(r["amt_cad"], 2), bold=False, number_format=number_format)
row += 1
last_data_row = row - 1
total_row = row + 1
_write_cell(ws, total_row, 1, "Total", bold=True)
c = ws.cell(row=total_row, column=7, value=f"=SUM(G{first_data_row}:G{last_data_row})")
c.font, c.number_format = BOLD_FONT, number_format
schedule_total = round(schedule_df["amt_cad"].sum(), 2) if not schedule_df.empty else 0.0
diff = round(tb_total - schedule_total, 2)
matches = bool(abs(diff) < RECONCILE_TOLERANCE)
_write_cell(ws, total_row, 9, "Trial Balance:", bold=False)
_write_cell(ws, total_row, 10, tb_total, bold=False, number_format=number_format)
_write_cell(ws, total_row, 11, "MATCH" if matches else "MISMATCH", bold=True)
return {"account": account, "tb_total": tb_total, "schedule_total": schedule_total,
"diff": diff, "matches": matches}
def _gl_period_tokens(period_value):
"""
The GL Dump's "Period" metadata cell holds one newline-separated
token per period the export covers - a single "P01 Aug" for a
one-month export, or one line per period for a multi-period/full-
fiscal-year export. Used to tell a narrow, single-period export
(where a missing beginning balance is almost certainly the cause of
a mismatch) apart from a broad, multi-period one (where it usually
isn't - confirmed for real: a full FY25-FY26, 12-period export that
also has "Include Beginning Balance: No" still reconciles exactly for
every account, because a multi-period export starting at the fiscal
year's own open already carries the real "Beginning Balance" journal
entries in its own data, regardless of what this header flag says).
"""
if not period_value:
return []
return [t.strip() for t in str(period_value).splitlines() if t.strip()]
def diagnose_schedule_mismatches(gl_df, schedule_results):
"""
When one or more Balance Sheet supporting schedules don't tie to
their trial balance, check the GL Dump's own declared export scope
(see common.load_gl_dump's gl_metadata) for the most common,
deterministic explanation before assuming a data error: unlike
Revenue/Expense accounts (which reset to zero each fiscal year),
Balance Sheet accounts carry a cumulative balance from all prior
history - a GL export scoped to a single period AND explicitly
excluding the beginning balance can only ever capture that one
period's activity, never the account's real running balance.
Confirmed for real against a period-scoped export where every
schedule but one mismatched - the one exception was an account that
happened to start that period at $0, so the missing beginning
balance didn't matter for it. A multi-period export with the same
flag set is NOT treated as the same situation - see
_gl_period_tokens for why that combination isn't reliable evidence
on its own (confirmed against a real, correctly-reconciling export).
Returns a list of {"title", "detail"} dicts (empty if there are no
mismatches at all) - meant to sit alongside the raw MISMATCH table as
context, not replace it.
"""
mismatches = [r for r in schedule_results if not r["matches"]]
if not mismatches:
return []
meta = gl_df.attrs.get("gl_metadata", {}) if hasattr(gl_df, "attrs") else {}
beginning_balance = str(meta.get("Include Beginning Balance", "")).strip().lower()
period_tokens = _gl_period_tokens(meta.get("Period"))
company = meta.get("Company")
if beginning_balance == "no" and len(period_tokens) <= 1:
scope = f" (scoped to {period_tokens[0]})" if period_tokens else ""
return [{
"title": "GL Dump excludes the beginning balance",
"detail": (
f"This GL Dump's own export settings say “Include Beginning Balance: No”{scope}. "
f"Balance Sheet accounts (unlike Revenue/Expense) carry a cumulative balance from "
f"all prior periods, so without the beginning balance a schedule can only reflect "
f"this export's own activity - never the account's real running balance. This "
f"explains {len(mismatches)} of {len(schedule_results)} mismatched schedule(s); "
f"any that do match are accounts that happened to start this period at $0. "
f"Re-export the GL Dump with “Include Beginning Balance” set to Yes (or "
f"covering the account's full history back to inception) and re-upload."
),
}]
diagnoses = []
if beginning_balance == "no" and len(period_tokens) > 1:
diagnoses.append({
"title": "GL Dump has no beginning balance line, but spans multiple periods",
"detail": (
f"This export's own settings say “Include Beginning Balance: No”, but it covers "
f"{len(period_tokens)} periods ({period_tokens[0]} to {period_tokens[-1]}), not "
f"just one - a multi-period export like this usually still reconciles even with "
f"this flag off, since a “Beginning Balance” journal entry is typically posted at "
f"the start of a fiscal year and would already be included. If a mismatched "
f"account's true history goes back further than this export's earliest period, "
f"that's the more likely cause here - try an export starting further back, or one "
f"with a genuine opening-balance entry for that account."
),
})
diagnoses.append({
"title": "Other things worth checking",
"detail": (
"The GL Dump's period range actually matches the trial balance's period"
+ (f" (this export covers {period_tokens[0]} to {period_tokens[-1]})"
if len(period_tokens) > 1 else
f" (this export covers {period_tokens[0]})" if period_tokens else "")
+ ", the trial balance and GL Dump were exported for the same company/entity"
+ (f" (this export is for {company})" if company else "")
+ ", and that no posted entries were excluded (unposted/draft entries are already "
"filtered out by this tool)."
),
})
return diagnoses
def build_all_schedules(wb, revenue_df, gl_df, report_date, title, number_format):
"""
Build one supporting schedule sheet per Balance Sheet account (see
get_schedule_accounts), in account-code order, right after the
Balance Sheet sheet (caller controls insertion order by calling this
right after build_balance_sheet_sheet). Returns the list of per-
account reconciliation results for the API response/UI.
"""
results = []
for account, tb_total in get_schedule_accounts(revenue_df).items():
schedule_df = build_account_schedule(gl_df, account)
results.append(write_schedule_sheet(wb, account, schedule_df, tb_total, report_date, title, number_format))
return results
def build_report_workbook(revenue_df, expense_df, output_path, sections, report_date, title,
use_cents=False, gl_df=None, budget_df=None, budget_file_path=None):
"""
sections: {"category_summary": bool, "balance_sheet": bool}
gl_df: optional, a loaded GL Dump (see common.load_gl_dump) - when
provided (and the Balance Sheet section is included), one supporting
schedule sheet gets built per Balance Sheet account (see
build_all_schedules), right after the Balance Sheet sheet. Omitted
entirely - not even empty placeholders - when gl_df is None.
budget_df: optional, a loaded Budget file (see load_budget_file) -
when it's the detailed format (see budget_is_detailed), a plain data
copy of it is written as a HIDDEN "Budget" sheet, and Category
Summary's own Budget/Variance/Budget (Full Year) columns pull from
it via live formula (see build_category_summary_sheet). Either
format also feeds a Budget vs Actual JSON summary (see
build_budget_vs_actual) for the API response, whether or not it's
the detailed format. Omitted entirely when budget_df is None.
budget_file_path: optional, the actual uploaded Budget .xlsx's path
on disk (see STORED_BUDGET_PATH, or the one-off upload's own saved
path for this run) - when given (and budget_df is the detailed
format), a faithfully-styled copy of that real file becomes the
workbook's own first sheet ("Budget (Original)" - see
_copy_original_budget_sheet), the one a person actually looks at;
the hidden "Budget" data sheet still does 100% of the calculation
work behind it. Without a path (e.g. it went missing on disk), the
"Budget" data sheet is left visible instead, so there's always at
least one budget reference in the workbook.
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
# grouped/source_totals are needed for Net Income (Balance Sheet)
# and for the Budget vs Actual JSON summary regardless of which
# sections are included, so compute them unconditionally, up front.
# budget_df is passed in here (not just to build_category_summary_sheet
# below) so a budgeted-but-not-yet-spent (account, category, project)
# gets its own row - canada=us=0 - everywhere grouped is used, not
# just on the sheet: without this, that combination has nowhere to
# attach its Budget/Variance/Budget (Full Year) figures at all,
# silently dropping its whole budget from every total (confirmed for
# real: this alone was large enough to flip an apparent YTD surplus
# into a deficit, purely from omission). category_map/project_map
# (see category_mapping_lookup/project_mapping_lookup) apply every
# standing reassignment decision on record, same as everywhere else
# process_category_summary is called.
category_map = category_mapping_lookup()
project_map = project_mapping_lookup()
grouped, source_totals = process_category_summary(
revenue_df, expense_df, budget_df=budget_df,
category_map=category_map, project_map=project_map,
)
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)
# Augmented copies of the raw TB files - the exact same uploaded
# columns, plus two appended ("Category (Applied)"/"Project
# (Applied)") reflecting any reassignment/79000-81000 collapse (see
# _compute_applied_category_project) - written as the "Revenue TB"/
# "Expense TB" sheets below instead of the untouched originals, so
# the live SUMIFS formulas built against them (see _sumifs_expr)
# have real cells to match: criteria text built from an already-
# reassigned category has nothing to match in the sheet's own
# original Revenue/Spend Category column, which never changes.
revenue_df_aug = revenue_df.copy()
revenue_df_aug["Category (Applied)"], revenue_df_aug["Project (Applied)"] = _compute_applied_category_project(
revenue_df, "Revenue Category", category_map, project_map,
)
expense_df_aug = expense_df.copy()
expense_df_aug["Category (Applied)"], expense_df_aug["Project (Applied)"] = _compute_applied_category_project(
expense_df, "Spend Category", category_map, project_map,
)
revenue_source_cols = _tb_source_cols(revenue_df_aug)
expense_source_cols = _tb_source_cols(expense_df_aug)
# The Budget file lands as the workbook's first sheet(s), so it's a
# standing, independently-checkable support anyone can open and see
# for themselves - a faithfully-styled copy of the actual uploaded
# file when budget_file_path is available (see
# _copy_original_budget_sheet - what a person actually looks at),
# plus the plain-data "Budget" sheet (see write_source_sheet) that
# Category Summary's own Budget/Variance/Budget (Full Year) columns
# pull from via live SUMIFS formulas (see build_category_summary_sheet)
# - hidden once the nicer copy exists, since nobody needs to look at
# it directly anymore, but still doing all the actual calculation
# work either way.
if budget_df is not None and budget_is_detailed(budget_df):
visible_budget_copy_built = False
if budget_file_path and os.path.exists(budget_file_path):
try:
_copy_original_budget_sheet(wb, budget_file_path, "Budget (Original)")
visible_budget_copy_built = True
except Exception as e:
print(f"Could not build a styled Budget (Original) copy from {budget_file_path}: {e}")
write_source_sheet(wb, budget_df, "Budget", hidden=visible_budget_copy_built)
if budget_df is not None:
budget_result = build_budget_vs_actual(grouped, budget_df, report_date)
summary["budget_vs_actual"] = {
"lines": len(budget_result["rows"]),
"total_budget": round(sum(r["budget_ytd"] for r in budget_result["rows"]), 2),
"total_actual": round(sum(r["actual_ytd"] for r in budget_result["rows"]), 2),
"unbudgeted_actuals": budget_result["unbudgeted_actuals"],
}
if sections.get("category_summary", True):
cat_summary = build_category_summary_sheet(
wb, grouped["revenue"], grouped["expense"], source_totals, report_date, title,
number_format=number_format, budget_df=budget_df,
revenue_source_cols=revenue_source_cols, expense_source_cols=expense_source_cols,
)
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"],
}
if gl_df is not None:
summary["uncategorized_detail"] = build_uncategorized_detail_sheet(
wb, gl_df, report_date, title, number_format,
)
summary["gl_detail"] = build_gl_detail_sheet(
wb, gl_df, category_map, project_map, report_date, title, number_format,
)
reassignment_rows = build_reassignment_reference_sheet(wb, title)
if reassignment_rows is not None:
summary["reassignment_reference_rows"] = reassignment_rows
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"]
if gl_df is not None:
schedule_results = build_all_schedules(wb, revenue_df, gl_df, report_date, title, number_format)
summary["schedules"] = schedule_results
summary["reconciled"] = summary["reconciled"] and all(r["matches"] for r in schedule_results)
diagnostics = diagnose_schedule_mismatches(gl_df, schedule_results)
if diagnostics:
summary["schedule_diagnostics"] = diagnostics
# Bring the two uploaded files in as their own sheets (plus the two
# appended "(Applied)" columns - see above) - everything above ties
# back to these via formula rather than a baked-in number.
write_source_sheet(wb, revenue_df_aug, REVENUE_SHEET_NAME)
write_source_sheet(wb, expense_df_aug, EXPENSE_SHEET_NAME)
wb.save(output_path)
return summary