From 05c305d6ff213bb2fbc5969c7b473ac61dd780ac Mon Sep 17 00:00:00 2001 From: JasonFraser Date: Thu, 1 Oct 2026 20:02:13 -0400 Subject: [PATCH] Add category/project reassignment mapping, visible Budget copy, and Category Summary formatting to Financial Reports - New category/project reassignment system: when a TB category or project has no home in the uploaded Budget file, two sequential review gates (category_mapping, then project_mapping) let the user fold it into an existing budget category/project (merging actuals into the target row, project code preserved) or explicitly leave it as-is - persisted to category_reassignment_map.csv/ project_reassignment_map.csv, editable any time via a standalone Manage Mappings panel with inline dropdowns sourced from the stored Budget file's own real categories/projects per account. - Accounts 79000/81000 (FX revaluation) always collapse every category under them into one fixed name, unconditionally. - Fixed a live-formula bug the reassignment work exposed: Category Summary's SUMIFS criteria were built from reassigned/collapsed category text but pointed at the untouched raw TB sheets, so a merged row's formula would silently evaluate to zero in real Excel. Fixed by writing "Category (Applied)"/"Project (Applied)" columns onto the Revenue TB/Expense TB sheet copies and pointing formulas at those instead. - A faithfully-styled, visible copy of the actual uploaded Budget file ("Budget (Original)") now replaces the old plain-data dump as what a person sees first; the plain-data "Budget" sheet still powers every live formula but is now hidden. - Category Summary formatting: "Total Revenue"/"Project Costs"/"Net Revenues" moved to the Category column; each 68020-82000 account subtotal gets a "Total " label; every major total/subtotal row gets a top+bottom border; the Variance column conditionally formats values below -$0.0001 in red. - Two new reference sheets: "Reassignment Reference" (original-vs- shown-as text for every actual reassignment/forced collapse) and "GL Detail" (every GL Dump line tagged and sorted the same way Category Summary groups its own rows) - both purely additive, neither feeds any calculated figure. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01HToTtpxzoxeugsa1Ve61gn --- .../balance_sheet_account_map.csv | 2 + app/tools/financial_reports/logic.py | 2296 ++++++++++++++++- app/tools/financial_reports/routes.py | 537 +++- docker-compose.yml | 5 + templates/financial_reports/index.html | 981 ++++++- 5 files changed, 3728 insertions(+), 93 deletions(-) diff --git a/app/tools/financial_reports/balance_sheet_account_map.csv b/app/tools/financial_reports/balance_sheet_account_map.csv index 77de357..96964ee 100644 --- a/app/tools/financial_reports/balance_sheet_account_map.csv +++ b/app/tools/financial_reports/balance_sheet_account_map.csv @@ -9,6 +9,8 @@ Accounts receivable,Assets,12002,1 Accounts receivable,Assets,12010,1 Accounts receivable,Assets,12020,1 Accounts receivable,Assets,12800,1 +Accounts receivable,Assets,12500,1 +Accounts receivable,Assets,12501,1 Prepaids,Assets,13100,1 Due from related companies,Assets,13160,1 Due from related companies,Assets,13170,1 diff --git a/app/tools/financial_reports/logic.py b/app/tools/financial_reports/logic.py index 428ba06..3688a9a 100644 --- a/app/tools/financial_reports/logic.py +++ b/app/tools/financial_reports/logic.py @@ -1,10 +1,20 @@ -import os, csv +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 +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 @@ -16,6 +26,20 @@ EXPENSE_ACCOUNT_CODES = ( "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" @@ -42,6 +66,26 @@ 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): """ @@ -138,6 +182,68 @@ def _canonicalize_text(series): 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 @@ -170,7 +276,7 @@ def _assert_no_case_collisions(df, cols, context): ) -def process_category_summary(revenue_df, expense_df): +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 @@ -180,9 +286,48 @@ def process_category_summary(revenue_df, expense_df): 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), @@ -191,9 +336,8 @@ def process_category_summary(revenue_df, expense_df): d = d[d["Ledger Account"].astype(str).str.strip().str.startswith(codes)] d["account"] = _canonicalize_text(d["Ledger Account"]) - d["category"] = _canonicalize_text(d[cat_col].fillna("(Uncategorized)")) - d["project_code"] = _canonicalize_text(d["Project"].fillna("(No project)")) - d["slob"] = d["Project"].apply(extract_slob) + 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) @@ -214,6 +358,44 @@ def process_category_summary(revenue_df, expense_df): 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 @@ -285,6 +467,990 @@ def compute_balance_sheet(revenue_tb_df, expense_tb_df, net_income, account_map= } +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) @@ -293,13 +1459,38 @@ def _write_cell(ws, row, col, value, bold=False, number_format=None, italic=Fals return c -def write_source_sheet(wb, df, sheet_name): +# 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): @@ -310,46 +1501,298 @@ def write_source_sheet(wb, df, sheet_name): 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 _sumifs_expr(sheet_name, amount_col_letter, account, category, project_code): +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. Blank category/ - project in the source (our "(Uncategorized)"/"(No project)" - placeholders) match against an empty-string criteria, same as the - template's ISBLANK(...) branches did. + 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 = '""' if category == "(Uncategorized)" else f'"{_excel_str(category)}"' - proj_crit = '""' if project_code == "(No project)" else f'"{_excel_str(project_code)}"' + 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}'!A:A,{acct_crit}," - f"'{sheet_name}'!C:C,{cat_crit}," - f"'{sheet_name}'!B:B,{proj_crit})" + 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, account, category): +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 = '""' if category == "(Uncategorized)" else f'"{_excel_str(category)}"' + 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}'!A:A,{acct_crit}," - f"'{sheet_name}'!C:C,{cat_crit})" + 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, flip_sign, total_revenue_row=None): + 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 @@ -403,8 +1846,8 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu canada = round(r["canada"], 2) us = round(r["us"], 2) sign = "-" if flip_sign else "" - canada_formula = f"={sign}{_sumifs_expr(source_sheet_name, 'D', account, category, r['project_code'])}" - us_formula = f"={sign}{_sumifs_expr(source_sheet_name, 'E', account, category, r['project_code'])}" + 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) @@ -416,6 +1859,7 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu 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 @@ -427,6 +1871,7 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu 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) @@ -436,6 +1881,7 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu 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 - @@ -444,8 +1890,8 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu category_rows = [] for category in sorted(acct_df["category"].unique()): sign = "-" if flip_sign else "" - canada_formula = f"={sign}{_sumifs_expr_no_project(source_sheet_name, 'D', account, category)}" - us_formula = f"={sign}{_sumifs_expr_no_project(source_sheet_name, 'E', account, category)}" + 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) @@ -455,18 +1901,22 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu 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: @@ -479,66 +1929,103 @@ def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, nu # 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) + _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, 1, "Net Revenues", bold=True) + _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): + 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("ABCDEFGH", (32, 20, 34, 15, 15, 15, 15, 15)): + 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 YTD", "US YTD", - "Consolidation Adjustments", "Total YTD", "Budget"] + 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 = 4, 5, 6, 7, 8 + 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, flip_sign=True, + REVENUE_SHEET_NAME, revenue_source_cols, flip_sign=True, budget_ctx=budget_ctx, ) total_revenue_row = row - _write_cell(ws, row, 1, "Total Revenue", bold=True) + _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, flip_sign=False, total_revenue_row=total_revenue_row, + EXPENSE_SHEET_NAME, expense_source_cols, flip_sign=False, total_revenue_row=total_revenue_row, budget_ctx=budget_ctx, ) total_expenses_row = row @@ -549,6 +2036,8 @@ def build_category_summary_sheet(wb, revenue_df, expense_df, source_totals, repo 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 @@ -559,6 +2048,8 @@ def build_category_summary_sheet(wb, revenue_df, expense_df, source_totals, repo 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 ────────────────────────── @@ -594,6 +2085,17 @@ def build_category_summary_sheet(wb, revenue_df, expense_df, source_totals, repo 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, @@ -612,6 +2114,284 @@ def build_category_summary_sheet(wb, revenue_df, expense_df, source_totals, repo } +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"), @@ -730,10 +2510,339 @@ def build_balance_sheet_sheet(wb, bs, net_income, report_date, title, account_ma 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): + 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 @@ -752,11 +2861,85 @@ def build_report_workbook(revenue_df, expense_df, output_path, sections, report_ 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): - grouped, source_totals = process_category_summary(revenue_df, expense_df) cat_summary = build_category_summary_sheet( wb, grouped["revenue"], grouped["expense"], source_totals, report_date, title, - number_format=number_format, + 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"] @@ -791,13 +2974,17 @@ def build_report_workbook(revenue_df, expense_df, output_path, sections, report_ "total_revenue_row": cat_summary["total_revenue_row"], "total_expenses_row": cat_summary["total_expenses_row"], } - else: - # Balance Sheet still needs Net Income even if Category Summary - # isn't being included in this run's output. - grouped, _ = process_category_summary(revenue_df, expense_df) - rev_total = round(grouped["revenue"]["canada"].sum() + grouped["revenue"]["us"].sum(), 2) - exp_total = round(grouped["expense"]["canada"].sum() + grouped["expense"]["us"].sum(), 2) - net_income = round(rev_total - exp_total, 2) + if 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() @@ -810,10 +2997,19 @@ def build_report_workbook(revenue_df, expense_df, output_path, sections, report_ summary["balance_sheet_balanced"] = bool(abs(bs["balance_check"]) < RECONCILE_TOLERANCE) summary["reconciled"] = summary["reconciled"] and summary["balance_sheet_balanced"] - # Bring the two uploaded files in as their own sheets - everything - # above ties back to these via formula rather than a baked-in number. - write_source_sheet(wb, revenue_df, REVENUE_SHEET_NAME) - write_source_sheet(wb, expense_df, EXPENSE_SHEET_NAME) + 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 diff --git a/app/tools/financial_reports/routes.py b/app/tools/financial_reports/routes.py index a035ee5..8810a3d 100644 --- a/app/tools/financial_reports/routes.py +++ b/app/tools/financial_reports/routes.py @@ -8,11 +8,155 @@ from .logic import ( classify_trial_balance_file, full_file_balance, build_report_workbook, + load_gl_dump, + load_budget_file, + find_unmapped_bs_accounts, + append_to_account_map, + find_unmapped_budget_lines, + append_to_budget_key_map, + process_category_summary, + budget_is_detailed, + find_unmatched_budget_projects, + find_budget_rows_missing_account, + load_stored_budget_file, + save_stored_budget_file, + stored_budget_file_status, + STORED_BUDGET_PATH, + budget_options_by_account, + find_unmapped_tb_categories, + find_unmapped_tb_projects, + category_mapping_lookup, + project_mapping_lookup, + list_category_mappings, + upsert_category_mapping, + upsert_category_mappings, + delete_category_mapping, + list_project_mappings, + upsert_project_mapping, + upsert_project_mappings, + delete_project_mapping, ) financial_reports_bp = Blueprint("financial_reports", __name__, url_prefix="/financial-reports") BALANCE_TOLERANCE = 0.01 +VALID_SECTIONS = {"Assets", "Liabilities", "NetAssets"} + +# Holds the parsed inputs for a run that's paused awaiting account-map or +# budget-key-map review (see find_unmapped_bs_accounts/ +# find_unmapped_budget_lines), keyed by a one-time token, so the confirm +# endpoints can finish the run without a re-upload. Same explicit single- +# job/single-user shortcut as the EIB tool's LAST_RESULT - not safe for +# concurrent runs, not meant to be. +PENDING_RUNS = {} + + +def _generate_report(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents): + fname = f"Financial_Report_{report_date}.xlsx" + fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], fname) + try: + summary = build_report_workbook( + revenue_df, expense_df, fpath, + sections, report_date, title, use_cents=use_cents, + gl_df=schedules_gl_df, budget_df=budget_df, budget_file_path=budget_file_path, + ) + except ValueError as e: + return jsonify({"error": str(e)}), 400 + + summary["schedules_included"] = schedules_gl_df is not None + summary["budget_included"] = budget_df is not None + return jsonify({"status": "ok", "filename": fname, **summary}), 200 + + +def _stash_pending_run(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents): + token = str(uuid.uuid4()) + PENDING_RUNS[token] = { + "revenue_df": revenue_df, "expense_df": expense_df, + "schedules_gl_df": schedules_gl_df, "budget_df": budget_df, "budget_file_path": budget_file_path, + "sections": sections, "report_date": report_date, "title": title, "use_cents": use_cents, + } + return token + + +def _check_gates_and_respond(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents, + skip_accounts_gate=False, skip_budget_gate=False, skip_budget_projects_gate=False, + skip_category_mapping_gate=False, skip_project_mapping_gate=False): + """ + Independent review gates, checked in order, each pausing the run + (see _stash_pending_run) rather than silently dropping data: unmapped + Balance Sheet accounts (find_unmapped_bs_accounts), then - only for a + detailed-format Budget file (see budget_is_detailed) - TB categories + with no home in the budget (find_unmapped_tb_categories), then TB + project codes with no home in the budget on the now-recategorized + picture (find_unmapped_tb_projects), then unmatched budget projects + (find_unmatched_budget_projects) - or, for the older Budget format, + unmapped budget lines (find_unmapped_budget_lines). All confirm + endpoints call back into this same function after applying their own + mapping (or, for budget_projects, just acknowledging), so a run + needing more than one review naturally proceeds from one to the next + instead of skipping the rest. + + skip_*_gate: set by a confirm endpoint for the gate it just handled, + so that submitting fewer mappings than there were unmapped items + (deliberately leaving some unmapped for now) proceeds with the run + instead of re-showing the identical review - confirmed as a real bug + for the accounts/budget_lines gates: without this, an empty or + partial mappings list looped forever, since the same items are still + genuinely unmapped in the CSV and would otherwise be found again. + The OTHER gates are still checked normally either way. + """ + if sections["balance_sheet"] and not skip_accounts_gate: + unmapped_accounts = find_unmapped_bs_accounts(revenue_df) + if unmapped_accounts: + token = _stash_pending_run(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents) + return jsonify({ + "status": "needs_review", "review_type": "accounts", + "token": token, "unmapped_accounts": unmapped_accounts, + }), 200 + + if budget_df is not None and budget_is_detailed(budget_df) and not skip_category_mapping_gate: + unmapped_categories = find_unmapped_tb_categories(revenue_df, expense_df, budget_df) + if unmapped_categories: + token = _stash_pending_run(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents) + return jsonify({ + "status": "needs_review", "review_type": "category_mapping", + "token": token, "unmapped_categories": unmapped_categories, + }), 200 + + if budget_df is not None and budget_is_detailed(budget_df) and not skip_project_mapping_gate: + unmapped_projects = find_unmapped_tb_projects(revenue_df, expense_df, budget_df) + if unmapped_projects: + token = _stash_pending_run(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents) + return jsonify({ + "status": "needs_review", "review_type": "project_mapping", + "token": token, "unmapped_projects": unmapped_projects, + }), 200 + + if budget_df is not None and budget_is_detailed(budget_df) and not skip_budget_projects_gate: + grouped, _ = process_category_summary( + revenue_df, expense_df, + category_map=category_mapping_lookup(), project_map=project_mapping_lookup(), + ) + unmatched_budget_projects = find_unmatched_budget_projects(budget_df, grouped, report_date) + missing_account_rows = find_budget_rows_missing_account(budget_df, report_date) + if unmatched_budget_projects or missing_account_rows: + token = _stash_pending_run(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents) + return jsonify({ + "status": "needs_review", "review_type": "budget_projects", + "token": token, "unmatched_budget_projects": unmatched_budget_projects, + "missing_account_rows": missing_account_rows, + }), 200 + + if budget_df is not None and not budget_is_detailed(budget_df) and not skip_budget_gate: + unmapped_budget_lines = find_unmapped_budget_lines(budget_df, report_date) + if unmapped_budget_lines: + token = _stash_pending_run(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents) + return jsonify({ + "status": "needs_review", "review_type": "budget_lines", + "token": token, "unmapped_budget_lines": unmapped_budget_lines, + }), 200 + + return _generate_report(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents) @financial_reports_bp.route("/") @@ -20,6 +164,38 @@ def index(): return render_template("financial_reports/index.html") +@financial_reports_bp.route("/api/budget-status") +def api_budget_status(): + return jsonify(stored_budget_file_status()), 200 + + +@financial_reports_bp.route("/api/budget-options") +def api_budget_options(): + """Every account's real budget categories/projects, from the + stored Budget file (see budget_options_by_account) - powers the + Manage Mappings panel's inline reassignment dropdowns, which (unlike + the review gates) aren't tied to any particular TB upload.""" + return jsonify({"by_account": budget_options_by_account(load_stored_budget_file())}), 200 + + +@financial_reports_bp.route("/api/upload-budget", methods=["POST"]) +def api_upload_budget(): + f = request.files.get("budget_file") + if not f or not f.filename: + return jsonify({"error": "Upload a Budget file"}), 400 + + path = os.path.join(current_app.config["UPLOAD_FOLDER"], f"{uuid.uuid4()}_{secure_filename(f.filename)}") + f.save(path) + try: + save_stored_budget_file(path) + except ValueError as e: + return jsonify({"error": str(e)}), 400 + finally: + os.remove(path) + + return jsonify({"status": "ok", **stored_budget_file_status()}), 200 + + @financial_reports_bp.route("/api/process", methods=["POST"]) def api_process(): files = [ @@ -30,6 +206,8 @@ def api_process(): return jsonify({"error": "No files uploaded"}), 400 by_role = {} + gl_dump = None # {"df": ..., "name": ...} - optional, enables per-account supporting schedules + budget_dump = None # {"df": ..., "name": ...} - optional, enables Budget vs Actual unrecognized = [] for f in files: path = os.path.join( @@ -43,15 +221,40 @@ def api_process(): return jsonify({"error": f"Could not read {f.filename}: {e}"}), 400 role = classify_trial_balance_file(df) - if role is None: - unrecognized.append(f.filename) + if role is not None: + if role in by_role: + return jsonify({ + "error": f"Got two {role} trial balance files " + f"({by_role[role]['name']}, {f.filename}) — upload exactly one of each.", + }), 400 + by_role[role] = {"df": df, "name": f.filename} continue - if role in by_role: - return jsonify({ - "error": f"Got two {role} trial balance files " - f"({by_role[role]['name']}, {f.filename}) — upload exactly one of each.", - }), 400 - by_role[role] = {"df": df, "name": f.filename} + + # Not a trial balance - see if it's a GL Dump (enables per-account + # Balance Sheet supporting schedules, optional) before giving up. + gl_df = load_gl_dump(path) + if gl_df is not None: + if gl_dump is not None: + return jsonify({ + "error": f"Got two GL Dump files ({gl_dump['name']}, {f.filename}) — " + f"upload at most one.", + }), 400 + gl_dump = {"df": gl_df, "name": f.filename} + continue + + # Not a GL Dump either - see if it's a Budget file (enables + # Budget vs Actual, optional) before giving up. + budget_df = load_budget_file(path) + if budget_df is not None: + if budget_dump is not None: + return jsonify({ + "error": f"Got two Budget files ({budget_dump['name']}, {f.filename}) — " + f"upload at most one.", + }), 400 + budget_dump = {"df": budget_df, "name": f.filename, "path": path} + continue + + unrecognized.append(f.filename) missing = [r for r in ("revenue", "expense") if r not in by_role] if missing: @@ -81,21 +284,319 @@ def api_process(): if not sections["category_summary"] and not sections["balance_sheet"]: return jsonify({"error": "Include at least one report section"}), 400 + include_schedules = request.form.get("include_schedules", "true") == "true" + include_budget = request.form.get("include_budget", "true") == "true" + report_date = request.form.get("report_date") or datetime.today().strftime("%Y-%m-%d") title = request.form.get("title") or "Planeterra International Foundation (Group Consolidated)" use_cents = request.form.get("use_cents", "false") == "true" - fname = f"Financial_Report_{report_date}.xlsx" - fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], fname) - 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 + schedules_gl_df = gl_dump["df"] if (gl_dump is not None and include_schedules) else None + # A budget file uploaded THIS run takes precedence (a deliberate + # one-off override); otherwise, if the box is checked, fall back to + # whatever's persisted via /api/upload-budget - the whole point being + # nobody has to re-upload the same Budget file on every single run. + # budget_file_path tracks the real .xlsx behind budget_df either way + # (this run's own temp upload, or the stored file) - see + # build_report_workbook's budget_file_path for what it's used for. + budget_df = None + budget_file_path = None + if include_budget: + if budget_dump is not None: + budget_df = budget_dump["df"] + budget_file_path = budget_dump["path"] + else: + budget_df = load_stored_budget_file() + budget_file_path = STORED_BUDGET_PATH if os.path.exists(STORED_BUDGET_PATH) else None - return jsonify({"status": "ok", "filename": fname, **summary}), 200 + return _check_gates_and_respond( + by_role["revenue"]["df"], by_role["expense"]["df"], schedules_gl_df, budget_df, budget_file_path, + sections, report_date, title, use_cents, + ) + + +@financial_reports_bp.route("/api/confirm-accounts", methods=["POST"]) +def api_confirm_accounts(): + data = request.get_json(silent=True) or {} + token = data.get("token") + mappings = data.get("mappings", []) + + # Look up without popping yet: a validation failure below must leave + # the pending run intact so the user can correct the payload and + # resubmit the same token, rather than burning their one confirm + # attempt on a rejected request (confirmed as a real bug: an invalid + # first submission silently invalidated the token, making a + # corrected retry fail with "session expired" even though the run + # was still sitting right there). + pending = PENDING_RUNS.get(token) + if pending is None: + return jsonify({ + "error": "This review session has expired or wasn't found - please re-upload and try again.", + }), 400 + + for m in mappings: + code = str(m.get("account_code", "")).strip() + line_item = str(m.get("line_item", "")).strip() + section = m.get("section") + sign = m.get("sign") + if not code or not line_item: + return jsonify({"error": f"Every included account needs a line item name (account {code or '?'})."}), 400 + if section not in VALID_SECTIONS: + return jsonify({"error": f"Invalid section '{section}' for account {code}."}), 400 + if sign not in (1, -1): + return jsonify({"error": f"Invalid sign '{sign}' for account {code} - must be 1 or -1."}), 400 + + del PENDING_RUNS[token] + if mappings: + append_to_account_map(mappings) + + return _check_gates_and_respond( + pending["revenue_df"], pending["expense_df"], pending["schedules_gl_df"], pending["budget_df"], pending["budget_file_path"], + pending["sections"], pending["report_date"], pending["title"], pending["use_cents"], + skip_accounts_gate=True, + ) + + +@financial_reports_bp.route("/api/confirm-budget-lines", methods=["POST"]) +def api_confirm_budget_lines(): + data = request.get_json(silent=True) or {} + token = data.get("token") + mappings = data.get("mappings", []) + + pending = PENDING_RUNS.get(token) + if pending is None: + return jsonify({ + "error": "This review session has expired or wasn't found - please re-upload and try again.", + }), 400 + + for m in mappings: + gl_name = str(m.get("budget_gl_name", "")).strip() + account = str(m.get("summary_account", "")).strip() + if not gl_name or not account: + return jsonify({"error": f"Every included budget line needs a target account (line {gl_name or '?'})."}), 400 + + del PENDING_RUNS[token] + if mappings: + append_to_budget_key_map(mappings) + + return _check_gates_and_respond( + pending["revenue_df"], pending["expense_df"], pending["schedules_gl_df"], pending["budget_df"], pending["budget_file_path"], + pending["sections"], pending["report_date"], pending["title"], pending["use_cents"], + skip_budget_gate=True, + ) + + +@financial_reports_bp.route("/api/confirm-budget-projects", methods=["POST"]) +def api_confirm_budget_projects(): + """ + Acknowledge-only gate (see find_unmatched_budget_projects) - unlike + the other two gates, there's no mapping to add: a detailed-format + Budget file already self-describes its (account, category, project) + key, so a flagged line is either a genuinely new/not-yet-spent + project (nothing to fix - proceed as-is) or a real typo that needs + correcting in the source Budget workbook itself, not patched around + here. This endpoint just needs the token to resume the run. + """ + data = request.get_json(silent=True) or {} + token = data.get("token") + + pending = PENDING_RUNS.get(token) + if pending is None: + return jsonify({ + "error": "This review session has expired or wasn't found - please re-upload and try again.", + }), 400 + + del PENDING_RUNS[token] + + return _check_gates_and_respond( + pending["revenue_df"], pending["expense_df"], pending["schedules_gl_df"], pending["budget_df"], pending["budget_file_path"], + pending["sections"], pending["report_date"], pending["title"], pending["use_cents"], + skip_budget_projects_gate=True, + ) + + +@financial_reports_bp.route("/api/confirm-category-mapping", methods=["POST"]) +def api_confirm_category_mapping(): + """ + Resolve the category_mapping gate (see find_unmapped_tb_categories): + each decision either maps a TB category to an existing budget + category (persisted to category_reassignment_map.csv, applied on + every future run - see upsert_category_mapping) or explicitly leaves + it as-is (also persisted, as a blank target, so it's never + re-flagged). A category simply left off the decisions list entirely + is NOT recorded either way, so it WILL be re-flagged next time - + the difference between "reviewed, leave as is" and "didn't get to + it yet". Each decision can ALSO carry a project reassignment + alongside the category one - symmetric with + api_confirm_project_mapping's category_action - since the row's + project is shown right there for context (see + find_unmapped_tb_categories). project_action defaults to "keep" (no + project change); "map" applies target_project via + upsert_project_mapping, the exact same mechanism the + project_mapping gate itself uses. + """ + data = request.get_json(silent=True) or {} + token = data.get("token") + decisions = data.get("decisions", []) + + pending = PENDING_RUNS.get(token) + if pending is None: + return jsonify({ + "error": "This review session has expired or wasn't found - please re-upload and try again.", + }), 400 + + for d in decisions: + account_code = str(d.get("account_code", "")).strip() + source = str(d.get("source", "")).strip() + action = d.get("action") + if not account_code or not source: + return jsonify({"error": "Every decision needs an account and a category."}), 400 + if action not in ("map", "leave_as_is"): + return jsonify({"error": f"Invalid action '{action}' for '{source}'."}), 400 + if action == "map" and not str(d.get("target_category", "")).strip(): + return jsonify({"error": f"Pick a target category for '{source}'."}), 400 + project_action = d.get("project_action", "keep") + if project_action not in ("keep", "map"): + return jsonify({"error": f"Invalid project_action '{project_action}' for '{source}'."}), 400 + if project_action == "map" and not str(d.get("target_project", "")).strip(): + return jsonify({"error": f"Pick a target project for '{source}'."}), 400 + + del PENDING_RUNS[token] + category_entries = [ + (d["account_code"], d["source"], str(d.get("target_category", "")).strip() if d["action"] == "map" else "") + for d in decisions + ] + upsert_category_mappings(category_entries) + project_entries = [ + (d["account_code"], d.get("project", ""), str(d.get("target_project", "")).strip()) + for d in decisions if d.get("project_action") == "map" + ] + if project_entries: + upsert_project_mappings(project_entries) + + return _check_gates_and_respond( + pending["revenue_df"], pending["expense_df"], pending["schedules_gl_df"], pending["budget_df"], pending["budget_file_path"], + pending["sections"], pending["report_date"], pending["title"], pending["use_cents"], + skip_category_mapping_gate=True, + ) + + +@financial_reports_bp.route("/api/confirm-project-mapping", methods=["POST"]) +def api_confirm_project_mapping(): + """ + Project-code equivalent of api_confirm_category_mapping - see + find_unmapped_tb_projects/upsert_project_mapping. Each decision can + ALSO carry a category reassignment alongside the project one - + "keep it in the same category, or move it to another category" - + since the row's category is shown right there for context (see + find_unmapped_tb_projects). category_action defaults to "keep" (no + category change, just the project); "map" applies target_category + via upsert_category_mapping, the exact same mechanism the + category_mapping gate itself uses, just triggered from this screen + since the two decisions are naturally made together here. + """ + data = request.get_json(silent=True) or {} + token = data.get("token") + decisions = data.get("decisions", []) + + pending = PENDING_RUNS.get(token) + if pending is None: + return jsonify({ + "error": "This review session has expired or wasn't found - please re-upload and try again.", + }), 400 + + for d in decisions: + account_code = str(d.get("account_code", "")).strip() + source = str(d.get("source", "")).strip() + action = d.get("action") + if not account_code or not source: + return jsonify({"error": "Every decision needs an account and a project."}), 400 + if action not in ("map", "leave_as_is"): + return jsonify({"error": f"Invalid action '{action}' for '{source}'."}), 400 + if action == "map" and not str(d.get("target_project", "")).strip(): + return jsonify({"error": f"Pick a target project for '{source}'."}), 400 + category_action = d.get("category_action", "keep") + if category_action not in ("keep", "map"): + return jsonify({"error": f"Invalid category_action '{category_action}' for '{source}'."}), 400 + if category_action == "map" and not str(d.get("target_category", "")).strip(): + return jsonify({"error": f"Pick a target category for '{source}'."}), 400 + + del PENDING_RUNS[token] + project_entries = [ + (d["account_code"], d["source"], str(d.get("target_project", "")).strip() if d["action"] == "map" else "") + for d in decisions + ] + upsert_project_mappings(project_entries) + category_entries = [ + (d["account_code"], d.get("category", ""), str(d.get("target_category", "")).strip()) + for d in decisions if d.get("category_action") == "map" + ] + if category_entries: + upsert_category_mappings(category_entries) + + return _check_gates_and_respond( + pending["revenue_df"], pending["expense_df"], pending["schedules_gl_df"], pending["budget_df"], pending["budget_file_path"], + pending["sections"], pending["report_date"], pending["title"], pending["use_cents"], + skip_project_mapping_gate=True, + ) + + +@financial_reports_bp.route("/api/category-mappings", methods=["GET", "POST"]) +def api_category_mappings(): + """ + GET: list every category reassignment on file (see + list_category_mappings). POST: add or update one directly - the + Manage Mappings panel's own affordance for editing decisions at any + time, independent of a run (unlike /api/confirm-category-mapping, + which only ever resolves items a review gate just surfaced). + """ + if request.method == "GET": + return jsonify({"mappings": list_category_mappings()}), 200 + + data = request.get_json(silent=True) or {} + account_code = str(data.get("account_code", "")).strip() + source = str(data.get("source", "")).strip() + if not account_code or not source: + return jsonify({"error": "account_code and source are required"}), 400 + upsert_category_mapping(account_code, source, str(data.get("target", "")).strip()) + return jsonify({"status": "ok", "mappings": list_category_mappings()}), 200 + + +@financial_reports_bp.route("/api/category-mappings/delete", methods=["POST"]) +def api_delete_category_mapping(): + data = request.get_json(silent=True) or {} + account_code = str(data.get("account_code", "")).strip() + source = str(data.get("source", "")).strip() + if not account_code or not source: + return jsonify({"error": "account_code and source are required"}), 400 + delete_category_mapping(account_code, source) + return jsonify({"status": "ok", "mappings": list_category_mappings()}), 200 + + +@financial_reports_bp.route("/api/project-mappings", methods=["GET", "POST"]) +def api_project_mappings(): + """Project-code equivalent of api_category_mappings.""" + if request.method == "GET": + return jsonify({"mappings": list_project_mappings()}), 200 + + data = request.get_json(silent=True) or {} + account_code = str(data.get("account_code", "")).strip() + source = str(data.get("source", "")).strip() + if not account_code or not source: + return jsonify({"error": "account_code and source are required"}), 400 + upsert_project_mapping(account_code, source, str(data.get("target", "")).strip()) + return jsonify({"status": "ok", "mappings": list_project_mappings()}), 200 + + +@financial_reports_bp.route("/api/project-mappings/delete", methods=["POST"]) +def api_delete_project_mapping(): + data = request.get_json(silent=True) or {} + account_code = str(data.get("account_code", "")).strip() + source = str(data.get("source", "")).strip() + if not account_code or not source: + return jsonify({"error": "account_code and source are required"}), 400 + delete_project_mapping(account_code, source) + return jsonify({"status": "ok", "mappings": list_project_mappings()}), 200 @financial_reports_bp.route("/api/download/") diff --git a/docker-compose.yml b/docker-compose.yml index 21ed9ef..9a3ee45 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -24,9 +24,14 @@ services: volumes: - ./uploads:/app/uploads - ./outputs:/app/outputs + - ./templates:/app/templates - ./app/tools/eib/merchant_lookup.csv:/app/app/tools/eib/merchant_lookup.csv - ./app/tools/donor_report/donor_merge_map.csv:/app/app/tools/donor_report/donor_merge_map.csv - ./app/tools/financial_reports/balance_sheet_account_map.csv:/app/app/tools/financial_reports/balance_sheet_account_map.csv + - ./app/tools/financial_reports/budget_line_key_map.csv:/app/app/tools/financial_reports/budget_line_key_map.csv + - ./app/tools/financial_reports/stored_budget_file.xlsx:/app/app/tools/financial_reports/stored_budget_file.xlsx + - ./app/tools/financial_reports/category_reassignment_map.csv:/app/app/tools/financial_reports/category_reassignment_map.csv + - ./app/tools/financial_reports/project_reassignment_map.csv:/app/app/tools/financial_reports/project_reassignment_map.csv environment: - FLASK_ENV=production - DOCLING_URL=http://docling:5001 diff --git a/templates/financial_reports/index.html b/templates/financial_reports/index.html index 7a6df19..5c86fc7 100644 --- a/templates/financial_reports/index.html +++ b/templates/financial_reports/index.html @@ -79,7 +79,7 @@ header { main { position: relative; z-index: 1; flex: 1; - max-width: 760px; + max-width: 1140px; width: 100%; margin: 0 auto; padding: 48px 24px 80px; @@ -163,6 +163,25 @@ main { .check-label { font-size: 13px; color: var(--w2); } .check-label strong { color: var(--w1); } +.budget-file-panel { + margin: 0 0 14px 30px; + padding: 10px 12px; + background: var(--w5); + border: 1px solid var(--border); + border-radius: 8px; + display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px; +} +.budget-file-status { font-size: 12px; color: var(--w2); } +.budget-file-status .filename { color: var(--w1); font-weight: 500; } +.budget-file-status.none { color: var(--w3); font-style: italic; } +.btn-link { + background: none; border: 1px solid var(--border-c); color: var(--cyan); + font-size: 11.5px; font-family: var(--disp); font-weight: 600; + padding: 6px 12px; border-radius: 6px; cursor: pointer; transition: all .15s; +} +.btn-link:hover { background: var(--cyan-glow); } +.btn-link:disabled { opacity: .4; cursor: not-allowed; } + .btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; padding: 11px 22px; border-radius: 8px; border: none; @@ -240,6 +259,109 @@ main { .compare-value { font-family: var(--mono); font-size: 12px; color: var(--w1); text-align: right; } .compare-header .compare-value { text-align: right; } +.acct-recon-table { + border: 1px solid var(--border); border-radius: 8px; overflow: hidden; + max-height: 280px; overflow-y: auto; +} +.acct-recon-row { + display: grid; grid-template-columns: 1fr 92px 92px 72px 62px; gap: 8px; + padding: 7px 10px; font-family: var(--mono); font-size: 10.5px; color: var(--w2); + border-bottom: 1px solid var(--w5); align-items: center; +} +.acct-recon-row:last-child { border-bottom: none; } +.acct-recon-row.head { + background: var(--w5); color: var(--w3); text-transform: uppercase; + letter-spacing: .06em; font-size: 9px; position: sticky; top: 0; +} +.acct-recon-row .num { text-align: right; } +.acct-recon-row.mismatch { background: var(--red-dim); } +.acct-recon-row.mismatch .num, .acct-recon-row.mismatch span:first-child { color: var(--w1); } + +.diagnostic-note { + display: flex; gap: 10px; align-items: flex-start; + font-size: 12px; color: var(--w2); background: var(--amber-dim, rgba(247,144,9,.12)); + border: 1px solid rgba(247,144,9,.25); border-radius: 8px; + padding: 12px 14px; margin-bottom: 10px; line-height: 1.55; +} +.diagnostic-note svg { width: 15px; height: 15px; color: var(--amber, #F79009); flex-shrink: 0; margin-top: 1px; } +.diagnostic-note strong { color: var(--w1); display: block; margin-bottom: 3px; } + +.review-intro { font-size: 12.5px; color: var(--w2); line-height: 1.55; margin-bottom: 16px; } +.review-step-badge { + display: inline-block; margin-left: 10px; padding: 2px 9px; border-radius: 20px; + background: var(--cyan-dim); border: 1px solid var(--border-c); color: var(--cyan); + font-family: var(--mono); font-size: 9.5px; font-weight: 500; letter-spacing: .04em; + text-transform: none; vertical-align: middle; +} +.review-next-note { + display: flex; gap: 8px; align-items: flex-start; + font-size: 11.5px; color: var(--w3); line-height: 1.5; + background: var(--w5); border: 1px solid var(--border); border-radius: 8px; + padding: 10px 12px; margin: -6px 0 16px; +} +.review-next-note::before { content: '→'; color: var(--cyan); flex-shrink: 0; } +.review-row { + display: grid; grid-template-columns: 20px 1fr 1.4fr 100px 150px; gap: 10px; align-items: center; + padding: 10px 0; border-bottom: 1px solid var(--w5); +} +.review-row:last-child { border-bottom: none; } +.review-row input[type="checkbox"] { width: 16px; height: 16px; accent-color: var(--cyan); cursor: pointer; } +.review-account-code { font-family: var(--mono); font-size: 11px; color: var(--w1); } +.review-account-sub { font-size: 10.5px; color: var(--w3); margin-top: 2px; } +.review-row input[type="text"], .review-row select { + width: 100%; background: var(--navy-4); border: 1px solid var(--border); border-radius: 6px; + padding: 7px 9px; font-family: var(--body); font-size: 12.5px; color: var(--w1); + outline: none; transition: border-color .2s; +} +.review-row input:focus, .review-row select:focus { border-color: var(--cyan); } +.review-row.excluded input[type="text"], .review-row.excluded select { opacity: .35; pointer-events: none; } +.review-row.excluded .review-account-code, .review-row.excluded .review-account-sub { opacity: .35; } +.review-row-budget { grid-template-columns: 20px 1.2fr 1fr 1fr; } +.review-row-mapping { grid-template-columns: 1fr 240px; } +.review-row-project-first { grid-template-columns: 1fr 320px 200px; } +.review-row-category-first { grid-template-columns: 1fr 200px 320px; } + +.mapping-list { list-style: none; margin-bottom: 4px; } +.mapping-list li { + display: flex; flex-direction: column; align-items: stretch; gap: 6px; + padding: 8px 12px; border: 1px solid var(--border); + border-radius: 6px; margin-bottom: 6px; + font-family: var(--mono); font-size: 11px; color: var(--w2); + background: var(--w5); +} +.mapping-primary-row { display: flex; align-items: center; gap: 10px; } +.mapping-row-info { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.mapping-list li .mapping-account { color: var(--cyan); margin-right: 8px; } +.mapping-list li .mapping-arrow { color: var(--w3); margin: 0 6px; } +.mapping-list li .mapping-leave { color: var(--w3); font-style: italic; } +.mapping-target-select { + flex-shrink: 0; max-width: 240px; + background: var(--navy-4); border: 1px solid var(--border); border-radius: 6px; + padding: 5px 8px; font-family: var(--body); font-size: 11.5px; color: var(--w1); + outline: none; transition: border-color .2s; +} +.mapping-target-select:focus { border-color: var(--cyan); } +.mapping-target-select:disabled { opacity: .5; } +.mapping-paired-row { + display: flex; align-items: center; gap: 8px; + padding-top: 6px; border-top: 1px dashed var(--border); +} +.mapping-paired-label { color: var(--w3); font-size: 10px; white-space: nowrap; flex-shrink: 0; } +.mapping-paired-source { + flex: 1; min-width: 0; + background: var(--navy-4); border: 1px solid var(--border); border-radius: 6px; + padding: 5px 8px; font-family: var(--body); font-size: 11.5px; color: var(--w1); + outline: none; transition: border-color .2s; +} +.mapping-paired-source:focus { border-color: var(--cyan); } +.mapping-paired-row .mapping-target-select { max-width: 200px; } +.mapping-empty { font-size: 12px; color: var(--w3); font-style: italic; padding: 4px 0 10px; } +.mapping-subhead { + font-family: var(--mono); font-size: 10px; letter-spacing: .1em; text-transform: uppercase; + color: var(--w3); margin: 18px 0 8px; +} +.mapping-subhead:first-child { margin-top: 0; } + 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; } @@ -275,7 +397,7 @@ footer a { color: var(--cyan); text-decoration: none; }
Drop trial balance files here or browse
-
Revenue trial balance + expense trial balance (.xlsx)
+
Revenue trial balance + expense trial balance (.xlsx) — plus an optional GL Dump for Balance Sheet supporting schedules, and/or a Budget file to use for just this one run (see Report Options below to store one permanently)
    @@ -295,6 +417,28 @@ footer a { color: var(--cyan); text-decoration: none; }
    Balance Sheet — Assets / Liabilities / Net Assets snapshot
    +
    +
    + +
    +
    Supporting Schedules — one per Balance Sheet account, requires a GL Dump upload
    +
    +
    +
    + +
    +
    Budget vs Actual — uses the stored Budget file below (or one dropped into Trial Balance Files above, just for this run)
    +
    +
    +
    Checking stored Budget file…
    + + +
    +
    +
    + Uploading… +
    +
    @@ -321,6 +465,92 @@ footer a { color: var(--cyan); text-decoration: none; }
    + + + + + + + + + + +
    +
    Category & Project Mappings
    +

    Every reassignment decision on record — made just now above, or added directly here — applied automatically on every future run. A blank target means "leave as is, don't ask again".

    + +
    Category Mappings
    +
    +
    +
    +
    +
    +
    + + +
    Project Mappings
    +
    +
    +
    +
    +
    +
    + +
    +
    @@ -385,6 +615,17 @@ footer a { color: var(--cyan); text-decoration: none; }
    + + + +
    @@ -398,12 +639,74 @@ const $ = id => document.getElementById(id); $('reportDate').valueAsDate = new Date(); +// ── Stored Budget file (see /api/upload-budget, /api/budget-status) ──────── +function fmtStoredDate(iso) { + const d = new Date(iso); + return d.toLocaleDateString('en-US', {year: 'numeric', month: 'short', day: 'numeric'}) + + ' ' + d.toLocaleTimeString('en-US', {hour: 'numeric', minute: '2-digit'}); +} + +async function refreshBudgetStatus() { + try { + const r = await fetch('/financial-reports/api/budget-status'); + const d = await r.json(); + const el = $('budgetFileStatus'); + if (d.exists) { + el.classList.remove('none'); + el.innerHTML = `Budget file stored — uploaded ${fmtStoredDate(d.uploaded_at)}`; + } else { + el.classList.add('none'); + el.textContent = 'No Budget file stored yet — upload one to enable Budget vs Actual'; + } + } catch (e) { + $('budgetFileStatus').textContent = 'Could not check stored Budget file status'; + } +} +refreshBudgetStatus(); + +$('budgetFileReplaceBtn').addEventListener('click', () => $('budgetFileInput').click()); +$('budgetFileInput').addEventListener('change', async () => { + const file = $('budgetFileInput').files[0]; + if (!file) return; + + $('budgetUploadError').classList.remove('visible'); + $('budgetFileReplaceBtn').disabled = true; + $('budgetUploadSpinner').classList.add('visible'); + + const fd = new FormData(); + fd.append('budget_file', file); + try { + const r = await fetch('/financial-reports/api/upload-budget', { method: 'POST', body: fd }); + const d = await r.json(); + if (r.ok && d.status === 'ok') { + await refreshBudgetStatus(); + // A new Budget file means new category/project options for the + // Manage Mappings panel's inline dropdowns (see refreshBudgetOptions). + await refreshBudgetOptions(); + refreshCategoryMappings(); + refreshProjectMappings(); + } else { + $('budgetUploadError').textContent = d.error || 'Unexpected error'; + $('budgetUploadError').classList.add('visible'); + } + } catch (e) { + $('budgetUploadError').textContent = 'Network error: ' + e.message; + $('budgetUploadError').classList.add('visible'); + } + + $('budgetUploadSpinner').classList.remove('visible'); + $('budgetFileReplaceBtn').disabled = false; + $('budgetFileInput').value = ''; +}); + // ── Checkboxes ────────────────────────────────────────────────────────────── function toggleCheck(rowId) { $(rowId).querySelector('.checkbox').classList.toggle('checked'); } $('checkCategorySummary').addEventListener('click', () => toggleCheck('checkCategorySummary')); $('checkBalanceSheet').addEventListener('click', () => toggleCheck('checkBalanceSheet')); +$('checkSchedules').addEventListener('click', () => toggleCheck('checkSchedules')); +$('checkBudget').addEventListener('click', () => toggleCheck('checkBudget')); $('checkCents').addEventListener('click', () => toggleCheck('checkCents')); function isChecked(rowId) { return $(rowId).querySelector('.checkbox').classList.contains('checked'); } @@ -457,32 +760,16 @@ zone.addEventListener('drop', e => { // ── Process ─────────────────────────────────────────────────────────────── let lastFilename = ''; +function escapeHtml(s) { + return String(s).replace(/&/g,'&').replace(//g,'>'); +} + function fmtMoney(n) { const sign = n < 0 ? '-' : ''; return sign + '$' + Math.abs(n).toLocaleString('en-US', {minimumFractionDigits: 2}); } -$('processBtn').addEventListener('click', async () => { - if (tbFiles.length === 0) return; - - $('processBtn').disabled = true; - $('spinner').classList.add('visible'); - $('errorNote').classList.remove('visible'); - $('resultCard').classList.remove('visible'); - - const fd = new FormData(); - tbFiles.forEach((f, i) => fd.append(`trial_balance_file_${i}`, f)); - fd.append('include_category_summary', isChecked('checkCategorySummary')); - fd.append('include_balance_sheet', isChecked('checkBalanceSheet')); - fd.append('use_cents', isChecked('checkCents')); - fd.append('report_date', $('reportDate').value); - fd.append('title', $('reportTitle').value); - - try { - const r = await fetch('/financial-reports/api/process', { method: 'POST', body: fd }); - const d = await r.json(); - - if (d.status === 'ok') { +function renderReportResult(d) { lastFilename = d.filename; $('resultSub').textContent = d.filename; @@ -530,6 +817,63 @@ $('processBtn').addEventListener('click', async () => { $('reconSection').style.display = 'none'; } + if (d.schedules && d.schedules.length) { + $('scheduleReconSection').style.display = ''; + + const diagnostics = d.schedule_diagnostics || []; + $('scheduleDiagnostics').innerHTML = diagnostics.map(diag => ` +
    + +
    ${escapeHtml(diag.title)}${escapeHtml(diag.detail)}
    +
    + `).join(''); + + const sch = d.schedules; + const mismatches = sch.filter(s => !s.matches).length; + $('scheduleReconLabel').textContent = mismatches + ? `Supporting Schedules vs. Trial Balance — ${mismatches} of ${sch.length} account${sch.length === 1 ? '' : 's'} MISMATCH` + : `Supporting Schedules vs. Trial Balance — all ${sch.length} accounts match`; + const rows = ['
    AccountTrial BalanceScheduleDiffStatus
    ']; + sch.forEach(s => { + rows.push(`
    + ${s.account} + ${fmtMoney(s.tb_total)} + ${fmtMoney(s.schedule_total)} + ${fmtMoney(s.diff)} + ${s.matches ? 'OK' : 'MISMATCH'} +
    `); + }); + $('scheduleReconTable').innerHTML = rows.join(''); + } else { + $('scheduleReconSection').style.display = 'none'; + $('scheduleDiagnostics').innerHTML = ''; + } + + if (d.budget_vs_actual) { + $('budgetSection').style.display = ''; + const bva = d.budget_vs_actual; + $('budgetLabel').textContent = `Budget vs Actual — ${bva.lines} line${bva.lines === 1 ? '' : 's'} · ` + + `Budget ${fmtMoney(bva.total_budget)} · Actual ${fmtMoney(bva.total_actual)}`; + + const unbudgeted = bva.unbudgeted_actuals || []; + if (unbudgeted.length) { + const total = unbudgeted.reduce((s, u) => s + u.actual_ytd, 0); + const rows = unbudgeted.map(u => + `
    ${escapeHtml(u.account_code)}${u.category ? ' — ' + escapeHtml(u.category) : ''}${u.project ? ' — ' + escapeHtml(u.project) : ''} + ${fmtMoney(u.actual_ytd)}
    `).join(''); + $('budgetUnbudgetedNote').innerHTML = ` +
    + +
    ${unbudgeted.length} account/project combination${unbudgeted.length === 1 ? '' : 's'} with actual activity but no budget line (${fmtMoney(total)} total)${rows}
    +
    `; + } else { + $('budgetUnbudgetedNote').innerHTML = ''; + } + } else { + $('budgetSection').style.display = 'none'; + $('budgetUnbudgetedNote').innerHTML = ''; + } + const icon = $('resultIcon'); if (d.reconciled) { icon.className = 'result-icon ok'; @@ -540,10 +884,597 @@ $('processBtn').addEventListener('click', async () => { } $('resultCard').classList.add('visible'); +} + +// ── Shared dispatcher: a response can be a finished report, either review +// gate (see routes.py's _check_gates_and_respond - confirming one gate can +// chain straight into needing the other), or an error. ──────────────────── +function hideAllReviewCards() { + $('reviewCard').style.display = 'none'; + $('reviewBudgetCard').style.display = 'none'; + $('reviewBudgetProjectsCard').style.display = 'none'; + $('reviewCategoryMappingCard').style.display = 'none'; + $('reviewProjectMappingCard').style.display = 'none'; +} + +function handleProcessResponse(d, errorNoteId) { + if (d.status === 'ok') { + hideAllReviewCards(); + renderReportResult(d); + refreshCategoryMappings(); + refreshProjectMappings(); + } else if (d.status === 'needs_review' && d.review_type === 'accounts') { + hideAllReviewCards(); + pendingToken = d.token; + pendingUnmapped = d.unmapped_accounts; + renderReviewRows(); + $('reviewCard').style.display = ''; + } else if (d.status === 'needs_review' && d.review_type === 'budget_lines') { + hideAllReviewCards(); + pendingBudgetToken = d.token; + pendingUnmappedBudgetLines = d.unmapped_budget_lines; + renderReviewBudgetRows(); + $('reviewBudgetCard').style.display = ''; + } else if (d.status === 'needs_review' && d.review_type === 'category_mapping') { + hideAllReviewCards(); + pendingCategoryMappingToken = d.token; + pendingUnmappedCategories = d.unmapped_categories; + renderReviewCategoryMappingRows(); + $('reviewCategoryMappingCard').style.display = ''; + } else if (d.status === 'needs_review' && d.review_type === 'project_mapping') { + hideAllReviewCards(); + pendingProjectMappingToken = d.token; + pendingUnmappedProjects = d.unmapped_projects; + renderReviewProjectMappingRows(); + $('reviewProjectMappingCard').style.display = ''; + } else if (d.status === 'needs_review' && d.review_type === 'budget_projects') { + hideAllReviewCards(); + pendingBudgetProjectsToken = d.token; + pendingUnmatchedBudgetProjects = d.unmatched_budget_projects; + pendingMissingAccountRows = d.missing_account_rows || []; + renderReviewBudgetProjectsRows(); + $('reviewBudgetProjectsCard').style.display = ''; + } else { + $(errorNoteId).textContent = d.error || 'Unexpected error'; + $(errorNoteId).classList.add('visible'); + } +} + +// ── Unmapped-account review (see /api/process's "needs_review" status) ───── +let pendingToken = null; +let pendingUnmapped = []; + +const SECTION_LABELS = { Assets: 'Assets', Liabilities: 'Liabilities', NetAssets: 'Net Assets' }; + +function renderReviewRows() { + $('reviewRows').innerHTML = pendingUnmapped.map((a, i) => ` +
    + +
    + + +
    + + + +
    + `).join(''); + + $('reviewRows').querySelectorAll('.review-include').forEach(cb => { + cb.addEventListener('change', () => { + cb.closest('.review-row').classList.toggle('excluded', !cb.checked); + }); + }); +} + +$('confirmAccountsBtn').addEventListener('click', async () => { + $('reviewErrorNote').classList.remove('visible'); + + const mappings = []; + let missingLabel = false; + $('reviewRows').querySelectorAll('.review-row').forEach(row => { + const idx = +row.dataset.idx; + if (!row.querySelector('.review-include').checked) return; + const lineItem = row.querySelector('.review-line-item').value.trim(); + if (!lineItem) { missingLabel = true; return; } + mappings.push({ + account_code: pendingUnmapped[idx].account_code, + line_item: lineItem, + section: row.querySelector('.review-section').value, + sign: parseInt(row.querySelector('.review-sign').value, 10), + }); + }); + + if (missingLabel) { + $('reviewErrorNote').textContent = 'Give every checked account a line item name, or uncheck it to leave it unmapped for now.'; + $('reviewErrorNote').classList.add('visible'); + return; + } + + $('confirmAccountsBtn').disabled = true; + $('reviewSpinner').classList.add('visible'); + + try { + const r = await fetch('/financial-reports/api/confirm-accounts', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token: pendingToken, mappings }), + }); + const d = await r.json(); + handleProcessResponse(d, 'reviewErrorNote'); + } catch (e) { + $('reviewErrorNote').textContent = 'Network error: ' + e.message; + $('reviewErrorNote').classList.add('visible'); + } + + $('reviewSpinner').classList.remove('visible'); + $('confirmAccountsBtn').disabled = false; +}); + +// ── Unmapped-budget-line review (see /api/process's "needs_review" status, +// review_type "budget_lines") ─────────────────────────────────────────────── +let pendingBudgetToken = null; +let pendingUnmappedBudgetLines = []; + +function renderReviewBudgetRows() { + $('reviewBudgetRows').innerHTML = pendingUnmappedBudgetLines.map((b, i) => ` +
    + +
    + + +
    + + +
    + `).join(''); + + $('reviewBudgetRows').querySelectorAll('.review-include').forEach(cb => { + cb.addEventListener('change', () => { + cb.closest('.review-row').classList.toggle('excluded', !cb.checked); + }); + }); +} + +$('confirmBudgetLinesBtn').addEventListener('click', async () => { + $('reviewBudgetErrorNote').classList.remove('visible'); + + const mappings = []; + let missingAccount = false; + $('reviewBudgetRows').querySelectorAll('.review-row').forEach(row => { + const idx = +row.dataset.idx; + if (!row.querySelector('.review-include').checked) return; + const account = row.querySelector('.review-target-account').value.trim(); + if (!account) { missingAccount = true; return; } + mappings.push({ + budget_gl_name: pendingUnmappedBudgetLines[idx].budget_gl_name, + budget_no: pendingUnmappedBudgetLines[idx].budget_no, + summary_account: account, + summary_project: row.querySelector('.review-target-project').value.trim(), + }); + }); + + if (missingAccount) { + $('reviewBudgetErrorNote').textContent = 'Give every checked budget line a target account, or uncheck it to leave it unmapped for now.'; + $('reviewBudgetErrorNote').classList.add('visible'); + return; + } + + $('confirmBudgetLinesBtn').disabled = true; + $('reviewBudgetSpinner').classList.add('visible'); + + try { + const r = await fetch('/financial-reports/api/confirm-budget-lines', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token: pendingBudgetToken, mappings }), + }); + const d = await r.json(); + handleProcessResponse(d, 'reviewBudgetErrorNote'); + } catch (e) { + $('reviewBudgetErrorNote').textContent = 'Network error: ' + e.message; + $('reviewBudgetErrorNote').classList.add('visible'); + } + + $('reviewBudgetSpinner').classList.remove('visible'); + $('confirmBudgetLinesBtn').disabled = false; +}); + +// ── Unmatched-budget-project review (see /api/process's "needs_review" +// status, review_type "budget_projects") - acknowledge-only, nothing to +// type in: a detailed-format budget file already carries its own +// account/category/project mapping (see routes.py's api_confirm_budget_projects). +let pendingBudgetProjectsToken = null; +let pendingUnmatchedBudgetProjects = []; +let pendingMissingAccountRows = []; + +function renderReviewBudgetProjectsRows() { + const unmatchedHtml = pendingUnmatchedBudgetProjects.map(p => ` +
    +
    + + +
    +
    + `).join(''); + + const missingAccountHtml = pendingMissingAccountRows.map(m => ` +
    +
    + + +
    +
    + `).join(''); + + let html = ''; + if (pendingMissingAccountRows.length) { + html += `
    Missing Account entirely (${pendingMissingAccountRows.length}) — fix in the source Budget workbook and re-upload
    ${missingAccountHtml}`; + } + if (pendingUnmatchedBudgetProjects.length) { + html += `
    No matching TB activity (${pendingUnmatchedBudgetProjects.length})
    ${unmatchedHtml}`; + } + $('reviewBudgetProjectsRows').innerHTML = html; + + const total = pendingMissingAccountRows.length + pendingUnmatchedBudgetProjects.length; + const parts = []; + if (pendingMissingAccountRows.length) parts.push(`${pendingMissingAccountRows.length} missing an Account entirely (worth fixing in the source workbook)`); + if (pendingUnmatchedBudgetProjects.length) parts.push(`${pendingUnmatchedBudgetProjects.length} with no matching TB activity (usually fine to continue past)`); + $('reviewBudgetProjectsSummary').textContent = `${total} budget file issue${total === 1 ? '' : 's'} found — ${parts.join(', ')}. Nothing needs to be filled in either way.`; + + $('reviewBudgetProjectsRows').style.display = 'none'; + $('toggleBudgetProjectsDetailsBtn').textContent = 'Show details'; +} + +$('toggleBudgetProjectsDetailsBtn').addEventListener('click', () => { + const rows = $('reviewBudgetProjectsRows'); + const hidden = rows.style.display === 'none'; + rows.style.display = hidden ? '' : 'none'; + $('toggleBudgetProjectsDetailsBtn').textContent = hidden ? 'Hide details' : 'Show details'; +}); + +$('confirmBudgetProjectsBtn').addEventListener('click', async () => { + $('reviewBudgetProjectsErrorNote').classList.remove('visible'); + $('confirmBudgetProjectsBtn').disabled = true; + $('reviewBudgetProjectsSpinner').classList.add('visible'); + + try { + const r = await fetch('/financial-reports/api/confirm-budget-projects', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token: pendingBudgetProjectsToken }), + }); + const d = await r.json(); + handleProcessResponse(d, 'reviewBudgetProjectsErrorNote'); + } catch (e) { + $('reviewBudgetProjectsErrorNote').textContent = 'Network error: ' + e.message; + $('reviewBudgetProjectsErrorNote').classList.add('visible'); + } + + $('reviewBudgetProjectsSpinner').classList.remove('visible'); + $('confirmBudgetProjectsBtn').disabled = false; +}); + +// ── Unmapped-TB-category review (see /api/process's "needs_review" status, +// review_type "category_mapping") - each row either folds into an existing +// budget category (a real merge - see logic.py's _apply_reassignment) or is +// left as-is, either way remembered via category_reassignment_map.csv. ──── +let pendingCategoryMappingToken = null; +let pendingUnmappedCategories = []; + +function renderReviewCategoryMappingRows() { + $('reviewCategoryMappingRows').innerHTML = pendingUnmappedCategories.map((c, i) => ` +
    +
    + + +
    + + +
    + `).join(''); +} + +$('confirmCategoryMappingBtn').addEventListener('click', async () => { + $('reviewCategoryMappingErrorNote').classList.remove('visible'); + + const decisions = pendingUnmappedCategories.map((c, i) => { + const targetCategory = $('reviewCategoryMappingRows').querySelector(`.review-target-category[data-idx="${i}"]`).value; + const targetProject = $('reviewCategoryMappingRows').querySelector(`.review-target-project[data-idx="${i}"]`).value; + const decision = targetCategory + ? { account_code: c.account_code, source: c.category, action: 'map', target_category: targetCategory } + : { account_code: c.account_code, source: c.category, action: 'leave_as_is' }; + decision.project = c.project; + if (targetProject) { + decision.project_action = 'map'; + decision.target_project = targetProject; } else { - $('errorNote').textContent = d.error || 'Unexpected error'; - $('errorNote').classList.add('visible'); + decision.project_action = 'keep'; } + return decision; + }); + + $('confirmCategoryMappingBtn').disabled = true; + $('reviewCategoryMappingSpinner').classList.add('visible'); + + try { + const r = await fetch('/financial-reports/api/confirm-category-mapping', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token: pendingCategoryMappingToken, decisions }), + }); + const d = await r.json(); + handleProcessResponse(d, 'reviewCategoryMappingErrorNote'); + } catch (e) { + $('reviewCategoryMappingErrorNote').textContent = 'Network error: ' + e.message; + $('reviewCategoryMappingErrorNote').classList.add('visible'); + } + + $('reviewCategoryMappingSpinner').classList.remove('visible'); + $('confirmCategoryMappingBtn').disabled = false; +}); + +// ── Unmapped-TB-project review (see /api/process's "needs_review" status, +// review_type "project_mapping") - same mechanics as category mapping. ───── +let pendingProjectMappingToken = null; +let pendingUnmappedProjects = []; + +function renderReviewProjectMappingRows() { + $('reviewProjectMappingRows').innerHTML = pendingUnmappedProjects.map((p, i) => ` +
    +
    + + +
    + + +
    + `).join(''); +} + +$('confirmProjectMappingBtn').addEventListener('click', async () => { + $('reviewProjectMappingErrorNote').classList.remove('visible'); + + const decisions = pendingUnmappedProjects.map((p, i) => { + const targetProject = $('reviewProjectMappingRows').querySelector(`.review-target-project[data-idx="${i}"]`).value; + const targetCategory = $('reviewProjectMappingRows').querySelector(`.review-target-category[data-idx="${i}"]`).value; + const decision = targetProject + ? { account_code: p.account_code, source: p.project, action: 'map', target_project: targetProject } + : { account_code: p.account_code, source: p.project, action: 'leave_as_is' }; + decision.category = p.category; + if (targetCategory) { + decision.category_action = 'map'; + decision.target_category = targetCategory; + } else { + decision.category_action = 'keep'; + } + return decision; + }); + + $('confirmProjectMappingBtn').disabled = true; + $('reviewProjectMappingSpinner').classList.add('visible'); + + try { + const r = await fetch('/financial-reports/api/confirm-project-mapping', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token: pendingProjectMappingToken, decisions }), + }); + const d = await r.json(); + handleProcessResponse(d, 'reviewProjectMappingErrorNote'); + } catch (e) { + $('reviewProjectMappingErrorNote').textContent = 'Network error: ' + e.message; + $('reviewProjectMappingErrorNote').classList.add('visible'); + } + + $('reviewProjectMappingSpinner').classList.remove('visible'); + $('confirmProjectMappingBtn').disabled = false; +}); + +// ── Manage Mappings panel (independent of any run - see +// /api/category-mappings, /api/project-mappings) - each existing mapping's +// target is a live dropdown (options from /api/budget-options, the stored +// Budget file's own categories/projects for that account), reassigned by +// picking a new option rather than deleting and waiting for a fresh run to +// re-flag it. ──────────────────────────────────────────────────────────── +let budgetOptionsByAccount = {}; + +async function refreshBudgetOptions() { + try { + const r = await fetch('/financial-reports/api/budget-options'); + const d = await r.json(); + budgetOptionsByAccount = d.by_account || {}; + } catch (e) { /* dropdowns just fall back to "Leave as is" + the current value */ } +} + +function buildMappingTargetOptions(accountCode, currentTarget, kind, placeholderLabel) { + const opts = budgetOptionsByAccount[accountCode]; + const list = opts ? (kind === 'category' ? opts.categories : opts.projects) : []; + const html = [``]; + if (currentTarget && !list.includes(currentTarget)) { + html.push(``); + } + list.forEach(v => { + html.push(``); + }); + return html.join(''); +} + +// kind's mapping list also gets a secondary "also reassign " +// row per entry, mirroring the review gates' combined category+project +// decision - unlike a flagged review-gate row, a saved mapping doesn't +// carry a specific project (or category) of its own, so this writes an +// independent companion entry to the OTHER file, keyed by whatever source +// text is typed in here (see api_confirm_category_mapping/_project_mapping +// for the review-gate equivalent, which already knows the source). +function renderMappingsList(containerId, mappings, kind, upsertUrl, onDelete) { + const el = $(containerId); + if (!mappings.length) { + el.innerHTML = '
    None yet
    '; + return; + } + const pairedKind = kind === 'category' ? 'project' : 'category'; + const pairedUpsertUrl = kind === 'category' ? '/financial-reports/api/project-mappings' : '/financial-reports/api/category-mappings'; + const pairedLabel = kind === 'category' ? '+ project:' : '+ category:'; + const pairedPlaceholder = kind === 'category' ? 'Project code to also reassign' : 'Category to also reassign'; + + el.innerHTML = '
      ' + mappings.map(m => ` +
    • +
      + ${escapeHtml(m.source)} + → + + +
      +
      + ${pairedLabel} + + + +
      +
    • `).join('') + '
    '; + + el.querySelectorAll('.mapping-target-select:not(.mapping-paired-target)').forEach(sel => { + sel.addEventListener('change', async () => { + sel.disabled = true; + try { + await fetch(upsertUrl, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ account_code: sel.dataset.account, source: sel.dataset.source, target: sel.value }), + }); + } finally { + if (kind === 'category') refreshCategoryMappings(); else refreshProjectMappings(); + } + }); + }); + el.querySelectorAll('.tb-remove').forEach(btn => { + btn.addEventListener('click', () => onDelete(btn.dataset.account, btn.dataset.source)); + }); + el.querySelectorAll('.mapping-paired-apply').forEach(btn => { + btn.addEventListener('click', async () => { + const row = btn.closest('.mapping-paired-row'); + const sourceInput = row.querySelector('.mapping-paired-source'); + const targetSelect = row.querySelector('.mapping-paired-target'); + const source = sourceInput.value.trim(); + if (!source) { sourceInput.focus(); return; } + btn.disabled = true; + try { + await fetch(pairedUpsertUrl, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ account_code: btn.dataset.account, source, target: targetSelect.value }), + }); + } finally { + if (pairedKind === 'category') refreshCategoryMappings(); else refreshProjectMappings(); + } + }); + }); +} + +async function refreshCategoryMappings() { + try { + const r = await fetch('/financial-reports/api/category-mappings'); + const d = await r.json(); + renderMappingsList('categoryMappingsList', d.mappings || [], 'category', '/financial-reports/api/category-mappings', deleteCategoryMappingRow); + } catch (e) { /* Manage Mappings panel is a convenience, fail quietly */ } +} +async function deleteCategoryMappingRow(account_code, source) { + await fetch('/financial-reports/api/category-mappings/delete', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ account_code, source }), + }); + refreshCategoryMappings(); +} +$('addCategoryMappingBtn').addEventListener('click', async () => { + const account_code = $('newCategoryAccountCode').value.trim(); + const source = $('newCategorySource').value.trim(); + const target = $('newCategoryTarget').value.trim(); + if (!account_code || !source) return; + await fetch('/financial-reports/api/category-mappings', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ account_code, source, target }), + }); + $('newCategoryAccountCode').value = ''; $('newCategorySource').value = ''; $('newCategoryTarget').value = ''; + refreshCategoryMappings(); +}); + +async function refreshProjectMappings() { + try { + const r = await fetch('/financial-reports/api/project-mappings'); + const d = await r.json(); + renderMappingsList('projectMappingsList', d.mappings || [], 'project', '/financial-reports/api/project-mappings', deleteProjectMappingRow); + } catch (e) { /* Manage Mappings panel is a convenience, fail quietly */ } +} +async function deleteProjectMappingRow(account_code, source) { + await fetch('/financial-reports/api/project-mappings/delete', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ account_code, source }), + }); + refreshProjectMappings(); +} +$('addProjectMappingBtn').addEventListener('click', async () => { + const account_code = $('newProjectAccountCode').value.trim(); + const source = $('newProjectSource').value.trim(); + const target = $('newProjectTarget').value.trim(); + if (!account_code || !source) return; + await fetch('/financial-reports/api/project-mappings', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ account_code, source, target }), + }); + $('newProjectAccountCode').value = ''; $('newProjectSource').value = ''; $('newProjectTarget').value = ''; + refreshProjectMappings(); +}); + +refreshBudgetOptions().then(() => { + refreshCategoryMappings(); + refreshProjectMappings(); +}); + +// ── Process ─────────────────────────────────────────────────────────────── +$('processBtn').addEventListener('click', async () => { + if (tbFiles.length === 0) return; + + $('processBtn').disabled = true; + $('spinner').classList.add('visible'); + $('errorNote').classList.remove('visible'); + $('resultCard').classList.remove('visible'); + hideAllReviewCards(); + + const fd = new FormData(); + tbFiles.forEach((f, i) => fd.append(`trial_balance_file_${i}`, f)); + fd.append('include_category_summary', isChecked('checkCategorySummary')); + fd.append('include_balance_sheet', isChecked('checkBalanceSheet')); + fd.append('include_schedules', isChecked('checkSchedules')); + fd.append('include_budget', isChecked('checkBudget')); + fd.append('use_cents', isChecked('checkCents')); + fd.append('report_date', $('reportDate').value); + fd.append('title', $('reportTitle').value); + + try { + const r = await fetch('/financial-reports/api/process', { method: 'POST', body: fd }); + const d = await r.json(); + handleProcessResponse(d, 'errorNote'); } catch (e) { $('errorNote').textContent = 'Network error: ' + e.message; $('errorNote').classList.add('visible');