""" Reproduces, exactly, the per-account balance check the user already builds by hand in "1. Summary (Manual)" columns AE-AJ of the real consolidated workbook: an independent trial-balance total (from "TB SC & Pr (Manual)" - both TB (Manual) sheets carry the full chart of accounts, just tagged with a different category column, and the user's own AE-AJ formulas query only the SC one, revenue included) compared against whatever the Summary sheet's own row-level formulas currently produce (its cached column H, summed by account). A nonzero difference means the manual E/F formula mapping for that account doesn't fully cover the trial balance - Flask-free per this repo's tool convention. Deliberately does NOT try to reverse-engineer the row-level E/F SUMIFS formulas themselves (confirmed impractical: they carry bespoke per-row adjustments - category-text criteria, hardcoded manual offsets, cross- references to other rows), and deliberately does NOT try to infer whether a (category, project) combination is "covered" by reading Summary's own C/D columns either - tried that, confirmed unreliable for real (a bespoke formula can pull in a category that never appears in its own row's C column at all, so a "not referenced anywhere in Summary" finding isn't trustworthy evidence of a real gap). What IS reliable, and is now the only diagnostic this tool offers: a plain structural diff between this period's trial balance and the prior period's - literally, does account X have more (or different) rows this period than last period, and if so, which ones exactly (down to the Excel row number). No guessing about what Summary's formulas do or don't capture - just "here's what's actually new in the source data, go look at it yourself." """ import re import openpyxl from tools.financial_reports.logic import REVENUE_ACCOUNT_CODES, EXPENSE_ACCOUNT_CODES RC_SHEET_NAME = "TB RC & Pr (Manual)" SC_SHEET_NAME = "TB SC & Pr (Manual)" SUMMARY_SHEET_NAME = "1. Summary (Manual)" ALL_ACCOUNT_CODES = REVENUE_ACCOUNT_CODES + EXPENSE_ACCOUNT_CODES RECONCILE_TOLERANCE = 0.01 _TB_REQUIRED_COLS = {"Ledger Account", "Project", "Planeterra Foundation"} def _find_tb_header_row(ws, max_scan_rows=30): """ The TB (Manual) sheets carry a metadata block (Organization, As of Period, Ledger, etc) above the real header row - scan for the row whose values include "Ledger Account", "Project" and "Planeterra Foundation" (present in every export of this format), same reasoning as common.py's find_gl_header_row. """ for r in range(1, max_scan_rows + 1): vals = {str(ws.cell(row=r, column=c).value) for c in range(1, ws.max_column + 1) if ws.cell(row=r, column=c).value is not None} if _TB_REQUIRED_COLS <= vals: return r return None def load_summary_check_sheets(path): """ Open the uploaded consolidated workbook and pull out the three sheets this check needs. Returns (rc_ws, sc_ws, summary_ws, error) - error is a human-readable string (and all sheets None) if any is missing, naming the sheets that actually exist so the user can see what went wrong instead of a bare KeyError. """ wb = openpyxl.load_workbook(path, data_only=True) missing = [n for n in (RC_SHEET_NAME, SC_SHEET_NAME, SUMMARY_SHEET_NAME) if n not in wb.sheetnames] if missing: return None, None, None, ( f"This workbook is missing the sheet(s) {', '.join(missing)} - " f"found: {', '.join(wb.sheetnames)}." ) return wb[RC_SHEET_NAME], wb[SC_SHEET_NAME], wb[SUMMARY_SHEET_NAME], None def read_tb_rows(tb_ws): """ Returns (rows, by_account): rows is a list of {"account", "category", "project", "canada", "us", "row"} dicts (one per TB line, header block skipped; "row" is the sheet's own 1-indexed Excel row number, so a diagnostic hint can point the user straight at it); by_account is {account_code: (canada_total, us_total)} summed across every row for that code - the independent TB-side total this check compares the Summary sheet against (see AH in the source workbook). "category" reads whichever of "Revenue Category" (RC sheet) or "Spend Category" (SC sheet) is present. """ header_row = _find_tb_header_row(tb_ws) if header_row is None: return [], {} headers = {tb_ws.cell(row=header_row, column=c).value: c for c in range(1, tb_ws.max_column + 1)} acct_col = headers.get("Ledger Account") proj_col = headers.get("Project") cat_col = headers.get("Revenue Category") or headers.get("Spend Category") canada_col = headers.get("Planeterra Foundation") us_col = headers.get("Planeterra International Foundation Ltd") rows = [] by_account = {} for r in range(header_row + 1, tb_ws.max_row + 1): account = tb_ws.cell(row=r, column=acct_col).value if not account: continue account = str(account).strip() code = account.split(":")[0].strip() project = tb_ws.cell(row=r, column=proj_col).value project = str(project).strip() if project else "" category = (tb_ws.cell(row=r, column=cat_col).value if cat_col else None) category = str(category).strip() if category else "" canada = tb_ws.cell(row=r, column=canada_col).value or 0 us = (tb_ws.cell(row=r, column=us_col).value or 0) if us_col else 0 rows.append({"account": account, "category": category, "project": project, "canada": canada, "us": us, "row": r}) if code in ALL_ACCOUNT_CODES: prev_c, prev_u = by_account.get(code, (0, 0)) by_account[code] = (prev_c + canada, prev_u + us) return rows, by_account def read_summary_actuals(summary_ws): """ {account_code: total} - the Summary sheet's own cached column H (Actual), grouped by account (column B), for every row on a tracked account code, regardless of how that row's own E/F formula happens to be built - this reproduces the source workbook's own AI column without needing to parse any formula. """ totals = {} for r in range(1, summary_ws.max_row + 1): account = summary_ws.cell(row=r, column=2).value # B if not account: continue code = str(account).strip().split(":")[0].strip() if code not in ALL_ACCOUNT_CODES: continue h = summary_ws.cell(row=r, column=8).value # H if h is None: continue totals[code] = totals.get(code, 0) + h return totals def read_summary_rows_detailed(summary_ws_values, summary_ws_formulas): """ One dict per Summary row (any tracked account): {"row", "account" (code), "category", "project", "canada" (cached E), "us" (cached F), "e_formula", "f_formula"} - "project" is "" for a blanket/catch-all row (no D value), which is how every real per-row formula in this workbook distinguishes "sum this one project" from "sum whatever isn't claimed elsewhere". Formula text is only used for the subtraction-list cross-check in _account_key_breakdown below; cached values are what everything else compares against. """ rows = [] for r in range(1, summary_ws_values.max_row + 1): account = summary_ws_values.cell(row=r, column=2).value # B if not account: continue code = str(account).strip().split(":")[0].strip() if code not in ALL_ACCOUNT_CODES: continue category = summary_ws_values.cell(row=r, column=3).value or "" # C project_raw = summary_ws_values.cell(row=r, column=4).value # D project = str(project_raw).strip() if project_raw else "" canada = summary_ws_values.cell(row=r, column=5).value or 0 # E us = summary_ws_values.cell(row=r, column=6).value or 0 # F e_formula = summary_ws_formulas.cell(row=r, column=5).value f_formula = summary_ws_formulas.cell(row=r, column=6).value rows.append({ "row": r, "account": code, "category": str(category).strip(), "project": project, "canada": canada, "us": us, "e_formula": e_formula if isinstance(e_formula, str) else None, "f_formula": f_formula if isinstance(f_formula, str) else None, }) return rows def _account_key_breakdown(code, tb_rows, summary_rows, flip): """ The line-by-line reconciliation this tool couldn't do generically before: group both the TB and the Summary sheet's own rows for this one account by (category, project), then work through them by elimination - the same process a human would use by hand: 1. Any TB (category, project) combo that has its own dedicated Summary row: compare the two directly. A nonzero diff here means that row's own formula is wrong (references the wrong criteria, a stale hardcoded value, etc) - flagged as "keyed". 2. Any TB combo with NO dedicated row falls to whichever "blanket" Summary row exists for that (account, category) - a row with a blank project, which by convention sums everything in the category not already claimed by a dedicated row (usually via an explicit "-E-E..." subtraction list in its own formula). Compare the blanket row's cached value against the sum of the actually-uncovered TB rows; if they disagree, diff the formula's own subtraction list against the real set of dedicated rows for that category to name exactly which row is missing (a genuine double-count) or extraneous (an over-subtraction). 3. Any TB combo with no dedicated row AND no blanket row at all: flagged as fully uncovered - these TB dollars aren't captured anywhere in the Summary sheet. Confirmed against a real discrepancy: this exact process (by hand) found a $3,559.78 double-count (a blanket row's subtraction list missing one sibling), plus two fully-uncovered TB lines ($215.64 and $30,728.81) - the three summed to the user's reported $34,504.23 diff exactly. Matching is case-insensitive (Excel's own SUMIFS text criteria are case-insensitive) - confirmed for real this matters: TB's "CTI - EasyJet" and the Summary's own "CTI - Easyjet" differ only in case, which Excel treats as the same project (and the row's cached value proves it - the formula genuinely captures those TB rows), but a naive exact-string match would wrongly call that TB group "uncovered" and misattribute $4,234.37 in real discrepancy elsewhere. Display text keeps the TB sheet's own original casing. Revenue accounts carry the same sign flip as the aggregate AE-AJ-style check (see run_summary_check): the TB stores revenue on its natural credit (negative) side while the Summary sheet's own row formulas report it positive, so `flip=True` negates each TB row's canada/us before grouping - applied per-row so the case-insensitive key matching above still lines up against Summary's row-level cache. """ def norm(s): return (s or "").strip().lower() sign = -1 if flip else 1 tb_by_key = {} # (norm_cat, norm_proj) -> {canada, us, rows, cat_display, proj_display} for row in tb_rows: if row["account"].split(":")[0].strip() != code: continue key = (norm(row["category"]), norm(row["project"])) slot = tb_by_key.setdefault(key, { "canada": 0.0, "us": 0.0, "rows": [], "cat_display": row["category"], "proj_display": row["project"], }) slot["canada"] += sign * row["canada"] slot["us"] += sign * row["us"] slot["rows"].append(row["row"]) keyed = {} # (norm_cat, norm_proj) -> summary row dict blanket = {} # norm_cat -> summary row dict cat_display = {} # norm_cat -> a display label (prefer Summary's own text) for sr in summary_rows: if sr["account"] != code: continue nc = norm(sr["category"]) cat_display.setdefault(nc, sr["category"]) if sr["project"]: keyed[(nc, norm(sr["project"]))] = sr else: blanket[nc] = sr problems = [] checked_keys = 0 uncovered_by_cat = {} # norm_cat -> {canada, us, rows} for (nc, nproj), tb in tb_by_key.items(): checked_keys += 1 cat_display.setdefault(nc, tb["cat_display"]) if nproj and (nc, nproj) in keyed: sr = keyed[(nc, nproj)] diff_c = round(sr["canada"] - tb["canada"], 2) diff_u = round(sr["us"] - tb["us"], 2) if abs(diff_c) >= RECONCILE_TOLERANCE or abs(diff_u) >= RECONCILE_TOLERANCE: problems.append({ "kind": "keyed", "category": tb["cat_display"] or "(no category)", "project": tb["proj_display"] or "(no project)", "summary_row": sr["row"], "tb_canada": round(tb["canada"], 2), "tb_us": round(tb["us"], 2), "summary_canada": round(sr["canada"], 2), "summary_us": round(sr["us"], 2), "diff_canada": diff_c, "diff_us": diff_u, "tb_rows": tb["rows"], }) else: slot = uncovered_by_cat.setdefault(nc, {"canada": 0.0, "us": 0.0, "rows": []}) slot["canada"] += tb["canada"] slot["us"] += tb["us"] slot["rows"].extend(tb["rows"]) # A dedicated Summary row can cache a nonzero value with NO matching # TB key on this account at all - confirmed for real: row 87 (labeled # 68030) is a pure cross-account reference whose entire $25,715.67 # comes from a 68010 TB row, so 68030 has no TB row of its own for # that (category, project) key. The loop above only ever visits # TB-side keys, so a phantom capture like this would otherwise be # silently dropped - visit any keyed Summary row whose key never # appeared in tb_by_key at all, treating its TB side as zero. for (nc, nproj), sr in keyed.items(): if (nc, nproj) in tb_by_key: continue if abs(sr["canada"]) < RECONCILE_TOLERANCE and abs(sr["us"]) < RECONCILE_TOLERANCE: continue problems.append({ "kind": "keyed", "category": sr["category"] or "(no category)", "project": sr["project"] or "(no project)", "summary_row": sr["row"], "tb_canada": 0.0, "tb_us": 0.0, "summary_canada": round(sr["canada"], 2), "summary_us": round(sr["us"], 2), "diff_canada": round(sr["canada"], 2), "diff_us": round(sr["us"], 2), "tb_rows": [], }) checked_categories = len(set(uncovered_by_cat) | set(blanket)) for nc in sorted(set(uncovered_by_cat) | set(blanket)): unc = uncovered_by_cat.get(nc, {"canada": 0.0, "us": 0.0, "rows": []}) br = blanket.get(nc) label = cat_display.get(nc, nc) dedicated_rows = sorted(sr["row"] for (c2, p2), sr in keyed.items() if c2 == nc) if br is None: if abs(unc["canada"]) >= RECONCILE_TOLERANCE or abs(unc["us"]) >= RECONCILE_TOLERANCE: problems.append({ "kind": "uncovered", "category": label or "(no category)", "summary_row": None, "canada": round(unc["canada"], 2), "us": round(unc["us"], 2), "tb_rows": unc["rows"], "dedicated_rows": dedicated_rows, }) continue diff_c = round(br["canada"] - unc["canada"], 2) diff_u = round(br["us"] - unc["us"], 2) if abs(diff_c) < RECONCILE_TOLERANCE and abs(diff_u) < RECONCILE_TOLERANCE: continue e_terms = set(int(n) for n in re.findall(r'-E(\d+)', br.get("e_formula") or "")) f_terms = set(int(n) for n in re.findall(r'-F(\d+)', br.get("f_formula") or "")) problems.append({ "kind": "blanket", "category": label or "(no category)", "summary_row": br["row"], "uncovered_canada": round(unc["canada"], 2), "uncovered_us": round(unc["us"], 2), "blanket_canada": round(br["canada"], 2), "blanket_us": round(br["us"], 2), "diff_canada": diff_c, "diff_us": diff_u, "tb_rows": unc["rows"], "dedicated_rows": dedicated_rows, "missing_from_subtraction_canada": [r for r in dedicated_rows if r not in e_terms], "missing_from_subtraction_us": [r for r in dedicated_rows if r not in f_terms], "extra_subtraction_canada": sorted(e_terms - set(dedicated_rows)), "extra_subtraction_us": sorted(f_terms - set(dedicated_rows)), }) problems.sort(key=lambda p: -(abs(p.get("diff_canada", p.get("canada", 0))) + abs(p.get("diff_us", p.get("us", 0))))) # Self-check: this breakdown should fully account for the account's # real tb_total - summary_total diff. It's reported honestly rather # than assumed - confirmed for real that it doesn't always: 43000 # (Donation and Fundraising Revenue) carries a formula pattern this # by-elimination process doesn't decompose (many small same-account # reclassification pairs between category/project combos, not a # simple keyed/blanket/cross-account-reference shape), so its # breakdown explains none of its real diff - surfacing that plainly # beats silently implying a complete answer. explained = 0.0 for p in problems: if p["kind"] in ("keyed", "blanket"): explained += p["diff_canada"] + p["diff_us"] else: explained -= (p["canada"] + p["us"]) explained_diff = round(-explained, 2) # tb_total - summary_total sign, matching entry["diff"] return {"checked_keys": checked_keys, "checked_categories": checked_categories, "problems": problems, "explained_diff": explained_diff} def _rows_for_diagnostics(rc, sc): """ Revenue accounts' row detail comes from RC, expense accounts' from SC - "TB SC & Pr (Manual)" is pivoted around Spend Category, which doesn't meaningfully apply to revenue accounts, so its row-level breakout for revenue is coarser than "TB RC & Pr (Manual)"'s (confirmed for real: a genuine new revenue-side line was invisible reading SC alone). """ combined = [] for row in rc: code = row["account"].split(":")[0].strip() if code in REVENUE_ACCOUNT_CODES: combined.append(row) for row in sc: code = row["account"].split(":")[0].strip() if code in EXPENSE_ACCOUNT_CODES: combined.append(row) return combined def run_summary_check(current_path, prior_path=None): """ The main entry point: reproduces the AE-AJ balance check per account (see module docstring), plus - only when a prior-period workbook is supplied - a plain structural diff for any account that doesn't balance: how many rows does this account have this period vs last period, and which specific (category, project, row number) entries are actually new. No inference about Summary's own formulas at all; just "here's what changed in the source data." Returns (results, totals, error) - error is a string if either required sheet is missing from current_path (results/totals are then None). totals is {"revenue": {...}, "expenses": {...}}, each an aggregate tb_total/summary_total/diff/matches across every account in that group - this is the check that actually determines "balanced" the way the source workbook's own row 15/row 39 totals do: individual accounts can carry offsetting diffs (a misclassification between two accounts, not a coverage gap) that net to ~zero in aggregate, and that's a real, common, non-error pattern - confirmed against the real June workbook, which nets to ~$0 on both totals despite two individual account pairs each showing large, exactly-offsetting diffs (43000/48000 and 68010/68030). """ rc_ws, sc_ws, summary_ws, error = load_summary_check_sheets(current_path) if error: return None, None, error # A second, formulas-mode open of the same workbook - only the Summary # sheet's raw E/F formula text is needed (for the blanket-row # subtraction-list cross-check in _account_key_breakdown), so the # cached-values workbook above is used for everything else. summary_ws_formulas = openpyxl.load_workbook(current_path, data_only=False)[SUMMARY_SHEET_NAME] summary_rows_detailed = read_summary_rows_detailed(summary_ws, summary_ws_formulas) # The aggregate per-account total (tb_by_account) stays SC-only, # matching the source workbook's own AE-AJ formulas exactly (verified # against real cached values). rc_rows/sc_rows below are only for the # row-count/diff diagnostic, which needs the correctly-pivoted side # per account type (see _rows_for_diagnostics). rc_rows, _ = read_tb_rows(rc_ws) sc_rows, tb_by_account = read_tb_rows(sc_ws) summary_by_account = read_summary_actuals(summary_ws) tb_rows = _rows_for_diagnostics(rc_rows, sc_rows) tb_row_count = {} for row in tb_rows: code = row["account"].split(":")[0].strip() tb_row_count[code] = tb_row_count.get(code, 0) + 1 prior_row_count = {} prior_by_account_key = {} # {account_code: {(category, project): occurrence_count}} if prior_path is not None: prior_rc_ws, prior_sc_ws, _, prior_error = load_summary_check_sheets(prior_path) if prior_error is None: prior_rc_rows, _ = read_tb_rows(prior_rc_ws) prior_sc_rows, _ = read_tb_rows(prior_sc_ws) for row in _rows_for_diagnostics(prior_rc_rows, prior_sc_rows): code = row["account"].split(":")[0].strip() prior_row_count[code] = prior_row_count.get(code, 0) + 1 bucket = prior_by_account_key.setdefault(code, {}) key = (row["category"], row["project"]) bucket[key] = bucket.get(key, 0) + 1 current_by_account_key = {} for row in tb_rows: code = row["account"].split(":")[0].strip() if code not in ALL_ACCOUNT_CODES: continue bucket = current_by_account_key.setdefault(code, {}) key = (row["category"], row["project"]) if key in bucket: c0, u0, rows0 = bucket[key] bucket[key] = (c0 + row["canada"], u0 + row["us"], rows0 + [row["row"]]) else: bucket[key] = (row["canada"], row["us"], [row["row"]]) results = [] for code in ALL_ACCOUNT_CODES: canada, us = tb_by_account.get(code, (0, 0)) flip = code in REVENUE_ACCOUNT_CODES tb_total = round((-(canada + us)) if flip else (canada + us), 2) summary_total = round(summary_by_account.get(code, 0.0), 2) diff = round(tb_total - summary_total, 2) matches = abs(diff) < RECONCILE_TOLERANCE if abs(tb_total) < 0.005 and abs(summary_total) < 0.005: continue # no activity on this account at all this period # Account's own display label, straight from the TB (falls back # to just the code if this account had zero TB rows this period). label = next((row["account"] for row in tb_rows if row["account"].split(":")[0].strip() == code), code) entry = {"account": label, "tb_total": tb_total, "summary_total": summary_total, "diff": diff, "matches": matches, "tb_row_count": tb_row_count.get(code, 0)} if not matches: kb = _account_key_breakdown(code, tb_rows, summary_rows_detailed, flip) kb["unexplained_diff"] = round(diff - kb["explained_diff"], 2) entry["key_breakdown"] = kb if not matches and prior_by_account_key: entry["prior_tb_row_count"] = prior_row_count.get(code, 0) keys_here = current_by_account_key.get(code, {}) prior_key_counts = prior_by_account_key.get(code, {}) # Brand-new (category, project) combos - never seen last period. new_lines = [ {"category": cat or "(no category)", "project": proj or "(no project)", "canada": round(c, 2), "us": round(u, 2), "tb_rows": tb_rows_list} for (cat, proj), (c, u, tb_rows_list) in keys_here.items() if prior_key_counts.get((cat, proj), 0) == 0 and (abs(c) >= 0.005 or abs(u) >= 0.005) ] entry["new_since_prior"] = sorted(new_lines, key=lambda x: (x["category"], x["project"])) # A combo that ALREADY existed last period can still have picked # up an extra row this period - a raw row-count check (which # this tool's whole point is to trust) would flag the account, # but a pure "is this key new" check would silently merge the # extra row into the existing bucket and never mention it. # Confirmed for real: 68010 gained exactly 8 rows between two # periods, but only 7 were genuinely new keys - the 8th was a # real, distinct $281,073.79 line that happened to share its # (category, project) with an existing row, so it never showed # up as "new" under key-set logic alone. Surface the whole # current-period group so a human can see all of it rather than # silently trusting an inflated bucket. grown = [ {"category": cat or "(no category)", "project": proj or "(no project)", "canada": round(c, 2), "us": round(u, 2), "tb_rows": tb_rows_list, "prior_count": prior_key_counts.get((cat, proj), 0), "current_count": len(tb_rows_list)} for (cat, proj), (c, u, tb_rows_list) in keys_here.items() if 0 < prior_key_counts.get((cat, proj), 0) < len(tb_rows_list) ] entry["grown_since_prior"] = sorted(grown, key=lambda x: (x["category"], x["project"])) results.append(entry) results.sort(key=lambda r: (r["matches"], r["account"])) totals = {} for group_name, codes in [("revenue", REVENUE_ACCOUNT_CODES), ("expenses", EXPENSE_ACCOUNT_CODES)]: group_results = [r for r in results if r["account"].split(":")[0].strip() in codes] tb_sum = round(sum(r["tb_total"] for r in group_results), 2) summary_sum = round(sum(r["summary_total"] for r in group_results), 2) diff_sum = round(tb_sum - summary_sum, 2) totals[group_name] = { "tb_total": tb_sum, "summary_total": summary_sum, "diff": diff_sum, "matches": abs(diff_sum) < RECONCILE_TOLERANCE, } return results, totals, None