diff --git a/app/tools/financial_reports/logic.py b/app/tools/financial_reports/logic.py index 007f146..428ba06 100644 --- a/app/tools/financial_reports/logic.py +++ b/app/tools/financial_reports/logic.py @@ -19,6 +19,18 @@ EXPENSE_ACCOUNT_CODES = ( 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) @@ -106,6 +118,58 @@ def _join_signed_terms(terms_with_sign): return "".join(parts) +def _canonicalize_text(series): + """ + Collapse case/whitespace-only variants of the same text (e.g. + "OffSite Meetings" vs "Offsite Meetings") to a single canonical label, + chosen as the most frequent original casing for that text (ties go to + whichever sorts first, for determinism). + + This matters because SUMIFS/SUMIF text criteria in Excel/Google Sheets + match case-insensitively: if two distinct-case variants were left as + separate groupby rows, each would get its own SUMIFS formula, and each + formula would sum BOTH variants' source rows - silently double-counting + the overlap. Canonicalizing before grouping keeps one row per + case-insensitive value, so the live formula matches only that value. + """ + stripped = series.astype(str).str.strip() + norm = stripped.str.lower() + canonical = stripped.groupby(norm).agg(lambda s: sorted(s.value_counts().items(), key=lambda kv: (-kv[1], kv[0]))[0][0]) + return norm.map(canonical) + + +def _assert_no_case_collisions(df, cols, context): + """ + Defensive regression check for the case-insensitive SUMIFS bug that + _canonicalize_text fixes: verify no two distinct combinations of + `cols` normalize (strip + lowercase) to the same key. A violation + means canonicalization missed something and the live SUMIFS/SUMIF + formulas for these rows would silently double-count each other once + opened in Excel/Sheets - exactly what happened with "OffSite + Meetings" vs "Offsite Meetings" under account 72300, which the old + Python-only reconciliation check (grouped total vs. source total - + mathematically equal no matter how the rows are labeled) could never + have caught. Raises rather than shipping a workbook that won't + reconcile once its formulas are actually evaluated. + """ + tmp = df[cols].copy() + norm_cols = [] + for c in cols: + nc = f"{c}__norm" + tmp[nc] = tmp[c].astype(str).str.strip().str.lower() + norm_cols.append(nc) + for _, g in tmp.groupby(norm_cols): + distinct = g[cols].drop_duplicates() + if len(distinct) > 1: + raise ValueError( + f"{context}: found values that differ only by case/whitespace " + f"and would collide under Excel/Sheets' case-insensitive " + f"SUMIFS matching: {distinct.to_dict('records')}. Fix the " + f"source data (or extend _canonicalize_text if this is a " + f"legitimate new case) before generating the report." + ) + + def process_category_summary(revenue_df, expense_df): """ Build the Category Summary rows: one per (account, category, project @@ -126,9 +190,9 @@ def process_category_summary(revenue_df, expense_df): d = df.copy() d = d[d["Ledger Account"].astype(str).str.strip().str.startswith(codes)] - d["account"] = d["Ledger Account"].astype(str).str.strip() - d["category"] = d[cat_col].fillna("(Uncategorized)") - d["project_code"] = d["Project"].fillna("(No project)") + d["account"] = _canonicalize_text(d["Ledger Account"]) + d["category"] = _canonicalize_text(d[cat_col].fillna("(Uncategorized)")) + d["project_code"] = _canonicalize_text(d["Project"].fillna("(No project)")) d["slob"] = d["Project"].apply(extract_slob) canada = d["Planeterra Foundation"].fillna(0) @@ -148,7 +212,16 @@ def process_category_summary(revenue_df, expense_df): [["canada", "us"]].sum() ) grouped = grouped[(grouped["canada"].abs() >= 0.005) | (grouped["us"].abs() >= 0.005)] - results[key] = grouped.reset_index(drop=True) + grouped = grouped.reset_index(drop=True) + + # Two granularities, because the two account groups use different + # SUMIFS criteria: project-level accounts key on all three columns, + # collapsed accounts (68020, 70000 and up) key on account+category + # only (see PROJECT_LEVEL_ACCOUNT_CODES / _write_category_section). + _assert_no_case_collisions(grouped, ["account", "category", "project_code"], f"{key} category summary") + _assert_no_case_collisions(grouped, ["account", "category"], f"{key} category summary (account+category)") + + results[key] = grouped return results, source_totals @@ -275,24 +348,16 @@ def _sumifs_expr_no_project(sheet_name, amount_col_letter, account, category): ) -# Accounts that get the full Account -> Category -> Project Code -# breakdown. Everything else (70000 and up) is Account -> Category only - -# no per-project detail rows, matching the reference template. -PROJECT_LEVEL_ACCOUNT_CODES = {"43000", "48000", "68010", "68020", "68030"} -# The three "Project Costs" accounts specifically - summed into a -# "Project Costs" subtotal, then "Net Revenues" (Total Revenue - Project -# Costs), right after the 68030 block, matching the reference template. -PROJECT_COST_ACCOUNT_CODES = ("68010", "68020", "68030") - - def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, number_format, source_sheet_name, flip_sign, total_revenue_row=None): """ Write one section (Revenue or Expenses), nested three levels deep: - Account (bold subtotal row, sorted ascending by account number) -> - Category (bold subtotal row within that account, sorted - alphabetically) -> detail rows (sorted by strategic area then full - project code). Canada/US detail cells are live SUMIFS formulas + 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 @@ -309,7 +374,17 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu if df.empty: return account_subtotal_rows, row, 0.0, 0.0 - for account in sorted(df["account"].unique()): + # 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 @@ -397,12 +472,12 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu if account_code in PROJECT_COST_ACCOUNT_CODES: project_cost_rows.append(account_subtotal_row) - # Right after the 68030 block: a "Project Costs" subtotal (68010 + - # 68020 + 68030) and "Net Revenues" (Total Revenue - Project - # Costs), matching the reference template. Neither feeds into - # account_subtotal_rows, so Total Expenses (summed from that list) - # isn't double-counting the three accounts they roll up. - if account_code == "68030" and total_revenue_row is not None: + # Right after the last project-level account (68010, 68030): a + # "Project Costs" subtotal and "Net Revenues" (Total Revenue - + # Project Costs), matching the reference template. Neither feeds + # into account_subtotal_rows, so Total Expenses (summed from that + # list) isn't double-counting the accounts they roll up. + if account == last_project_account and total_revenue_row is not None: project_costs_row = row _write_cell(ws, row, 1, "Project Costs", bold=True) for col in (canada_col, us_col, total_col): @@ -426,7 +501,7 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu def build_category_summary_sheet(wb, revenue_df, expense_df, source_totals, report_date, title, number_format=ACCOUNTING_FORMAT_WHOLE): - ws = wb.create_sheet("Category Summary") + ws = wb.create_sheet("1. Summary (Manual)") for col, width in zip("ABCDEFGH", (32, 20, 34, 15, 15, 15, 15, 15)): ws.column_dimensions[col].width = width @@ -506,9 +581,29 @@ def build_category_summary_sheet(wb, revenue_df, expense_df, source_totals, repo _write_cell(ws, row, 3, "US — source file total"); _write_cell(ws, row, 4, source_us, number_format=number_format) _write_cell(ws, row, 5, "MATCH" if us_ok else "MISMATCH", bold=True) + # Report vs. source figures for the three headline metrics (Total + # Income, Total Expenses, Surplus/Deficit) - the "report" side is what + # the 1. Summary (Manual)/Balance Sheet (FS) sheets show (and what the + # Balance Sheet's Net Income term is built from); the "source" side is + # summed directly from the uploaded files, independent of any + # grouping/labeling, so the UI can show the two side by side. + revenue_total = round(rev_canada + rev_us, 2) + expense_total = round(exp_canada + exp_us, 2) + source_revenue_total = round(source_totals["revenue_canada"] + source_totals["revenue_us"], 2) + source_expense_total = round(source_totals["expense_canada"] + source_totals["expense_us"], 2) + surplus_deficit = round(revenue_total - expense_total, 2) + source_surplus_deficit = round(source_revenue_total - source_expense_total, 2) + return { - "revenue_total": round(rev_canada + rev_us, 2), - "expense_total": round(exp_canada + exp_us, 2), + "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, @@ -558,7 +653,7 @@ def build_balance_sheet_sheet(wb, bs, net_income, report_date, title, account_ma value - `bs` (from compute_balance_sheet) is only used as a fallback for lines with no account-map entry (e.g. Deferred Revenue). """ - ws = wb.create_sheet("Balance Sheet") + ws = wb.create_sheet("Balance Sheet (FS)") ws.column_dimensions["A"].width = 32 ws.column_dimensions["B"].width = 18 @@ -568,10 +663,10 @@ def build_balance_sheet_sheet(wb, bs, net_income, report_date, title, account_ma if category_summary_refs: net_income_formula = ( - f"'Category Summary'!D{category_summary_refs['total_revenue_row']}" - f"+'Category Summary'!E{category_summary_refs['total_revenue_row']}" - f"-'Category Summary'!D{category_summary_refs['total_expenses_row']}" - f"-'Category Summary'!E{category_summary_refs['total_expenses_row']}" + 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 @@ -644,6 +739,15 @@ def build_report_workbook(revenue_df, expense_df, output_path, sections, report_ 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 @@ -656,12 +760,32 @@ def build_report_workbook(revenue_df, expense_df, output_path, sections, report_ ) summary["revenue_total"] = cat_summary["revenue_total"] summary["expense_total"] = cat_summary["expense_total"] - summary["surplus_deficit"] = round(cat_summary["revenue_total"] - cat_summary["expense_total"], 2) - summary["reconciled"] = summary["reconciled"] and cat_summary["reconciled"] + 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"], diff --git a/app/tools/financial_reports/routes.py b/app/tools/financial_reports/routes.py index dafe3f1..a035ee5 100644 --- a/app/tools/financial_reports/routes.py +++ b/app/tools/financial_reports/routes.py @@ -87,10 +87,13 @@ def api_process(): fname = f"Financial_Report_{report_date}.xlsx" fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], fname) - summary = build_report_workbook( - by_role["revenue"]["df"], by_role["expense"]["df"], fpath, - sections, report_date, title, use_cents=use_cents, - ) + try: + summary = build_report_workbook( + by_role["revenue"]["df"], by_role["expense"]["df"], fpath, + sections, report_date, title, use_cents=use_cents, + ) + except ValueError as e: + return jsonify({"error": str(e)}), 400 return jsonify({"status": "ok", "filename": fname, **summary}), 200 diff --git a/templates/financial_reports/index.html b/templates/financial_reports/index.html index 5b55730..7a6df19 100644 --- a/templates/financial_reports/index.html +++ b/templates/financial_reports/index.html @@ -225,6 +225,21 @@ main { .recon-badge.ok { background: var(--green-dim); color: var(--green); } .recon-badge.warn { background: var(--red-dim); color: var(--red); } +.compare-table { margin-bottom: 16px; } +.compare-row { + display: grid; grid-template-columns: 1.15fr 1fr 1fr 76px; gap: 10px; align-items: center; + padding: 9px 0; border-bottom: 1px solid var(--w5); +} +.compare-row:last-child { border-bottom: none; } +.compare-row.compare-header { + border-bottom: 1px solid var(--border); padding-bottom: 8px; + font-family: var(--mono); font-size: 9.5px; letter-spacing: .08em; + text-transform: uppercase; color: var(--w3); +} +.compare-label { font-size: 12px; color: var(--w2); } +.compare-value { font-family: var(--mono); font-size: 12px; color: var(--w1); text-align: right; } +.compare-header .compare-value { text-align: right; } + footer { position: relative; z-index: 1; text-align: center; padding: 20px; font-size: 11px; color: var(--w3); border-top: 1px solid var(--border); } footer a { color: var(--cyan); text-decoration: none; } @@ -338,6 +353,33 @@ footer a { color: var(--cyan); text-decoration: none; } + +