import os, re, csv from datetime import datetime import pandas as pd import openpyxl from openpyxl.styles import Font from common import load_gl_dump # noqa: F401 - re-exported for routes.py TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), "report_summary_template.xlsx") TEMPLATE_SHEET = "Sheet1" DONOR_MERGE_MAP_PATH = os.path.join(os.path.dirname(__file__), "donor_merge_map.csv") REVENUE_ACCOUNT_CODES = ("43000", "48000") # All P&L expense accounts (everything below "Total" in the chart of # accounts that isn't Balance Sheet or Revenue). Project/donor # attribution turned out to be present across nearly all of these, not # just the "Disbursements to Projects" ones - confirm this scope is # right before relying on the Expenses section for real reporting. EXPENSE_ACCOUNT_CODES = ( "68010", "68020", "68030", "70000", "70010", "70020", "70030", "71060", "72000", "72100", "72300", "72400", "72600", "72800", "72900", "78000", "79000", "81000", "82000", ) FONT_NAME = "Aptos Narrow" FONT_SIZE = 12 REGULAR_FONT = Font(name=FONT_NAME, size=FONT_SIZE, bold=False) BOLD_FONT = Font(name=FONT_NAME, size=FONT_SIZE, bold=True) AMOUNT_FORMAT = "#,##0.00;(#,##0.00)" DATE_FORMAT = "yyyy-mm-dd" RECONCILE_TOLERANCE = 0.01 # GL Dump column names differ slightly from the trial balance's (e.g. # "Spend Category as Worktag" vs the TB's "Spend Category") - kept # separate from REVENUE_ACCOUNT_CODES/EXPENSE_ACCOUNT_CODES's category # column args used against the TB. GL_AMOUNT_COL = "Net Ledger Debit minus Credit" GL_REVENUE_CATEGORY_COL = "Revenue Category" GL_EXPENSE_CATEGORY_COL = "Spend Category as Worktag" US_AGGREGATE_NOTE = ( "(Aggregated — Planeterra International Foundation Ltd; " "no transaction-level detail in this export)" ) _INVALID_SHEET_CHARS = re.compile(r'[:\\/?*\[\]]') def _load_donor_merge_map(path=DONOR_MERGE_MAP_PATH): """ Read the raw-donor -> canonical-donor mapping fresh from donor_merge_map.csv on every call, same pattern (and same reasoning) as the EIB tool's merchant_lookup.csv: bind-mounted, so edits take effect on the next run with no rebuild. """ merge_map = {} if not os.path.exists(path): return merge_map with open(path, newline="", encoding="utf-8") as f: for row in csv.DictReader(f): raw = row.get("raw_donor") if raw: merge_map[raw] = row.get("canonical_donor") or raw return merge_map def parse_project(project): """ Split a Project string (" - - ") into (slob, raw_donor). Donor parts beyond the second are joined back with " - " so hyphenated donor names (e.g. "G - Adventures") survive intact. Fewer than 3 parts means there's no real donor segment at all (e.g. "Planeterra - General", "Planeterra - General Fund", or a blank Project cell) - slob is whatever's left (may be empty), raw_donor is None, which routes to the unified "General" bucket in resolve_donor(). """ if not project or not str(project).strip(): return "", None parts = str(project).split(" - ") if len(parts) < 3: slob = parts[1] if len(parts) == 2 else "" return slob, None return parts[1], " - ".join(parts[2:]) def resolve_donor(raw_donor, merge_map): """ No real donor segment (raw_donor is None), or a donor segment that's literally "General", both collapse into one canonical "General" report - per stakeholder direction, "no donor name at the end" and "donor literally named General" are the same bucket, not two. """ if not raw_donor: return "General" canonical = merge_map.get(raw_donor, raw_donor) return "General" if canonical == "General" else canonical def _entity_total(df): """Combined amount across both entities - Planeterra Foundation and Planeterra International Foundation Ltd. Eliminations is excluded: it's zero on every row in the sample data, and D+E already matches the trial balance's own precomputed "Total" (D+E+F) column as a result, so there's nothing it would currently change.""" return df["Planeterra Foundation"].fillna(0) + df["Planeterra International Foundation Ltd"].fillna(0) def _entity_total_us_only(df): """Planeterra International Foundation Ltd only - used for the detailed-mode US-entity supplementary rows. The GL Dump only covers the Canada entity (Planeterra Foundation), so when transaction-level detail is available, Canada's contribution comes from the GL Dump (process_revenue_detail/process_expense_detail) and the US entity's still comes from the trial balance, same as today - just kept separate instead of pre-combined into one blended figure.""" return df["Planeterra International Foundation Ltd"].fillna(0) def full_file_balance(tb_df): """ Sum every row's combined entity total across the WHOLE file (not just revenue/expense rows) - a complete, correctly-exported trial balance nets to zero across all accounts. Used as an upload integrity check, independent of the revenue/expense filtering below. """ return round(_entity_total(tb_df).sum(), 2) # GL Dump loading (find_gl_header_row/load_gl_dump) lives in app/common.py - # financial_reports needs the exact same logic, which is what crossed the # "lift it out" threshold from CLAUDE.md's module-boundary guidance. def _process_side(tb_df, account_codes, category_col, flip_sign, merge_map, entity_total_fn=_entity_total): df = tb_df.copy() df = df[df["Ledger Account"].astype(str).str.strip().str.startswith(account_codes)] parsed = df["Project"].apply(parse_project) df["slob"] = parsed.apply(lambda t: t[0]) df["donor"] = parsed.apply(lambda t: resolve_donor(t[1], merge_map)) df["category"] = df[category_col].fillna("(Uncategorized)") raw_amount = entity_total_fn(df) df["amount"] = -raw_amount if flip_sign else raw_amount # Grouped by donor -> project code -> category only, deliberately not # by Ledger Account: the same project code/category can appear under # more than one GL account (e.g. the same spend category posted to # two different expense accounts), and showing that as two rows with # an identical-looking label is exactly the clutter a non-finance # reader doesn't need - one combined row per (project code, category) # is the whole point of grouping "by project code". grouped = ( df.groupby(["donor", "slob", "category"], as_index=False)["amount"] .sum() ) # Drop groups that net to exactly zero - since this is a trial # balance, a group netting to zero is a real reclassification/ # offsetting entry, not a bug, and the remaining rows already sum to # the correct total without it. grouped = grouped[grouped["amount"].abs() >= 0.005].reset_index(drop=True) return grouped def process_revenue(tb_df, merge_map=None): """ Revenue (43000/48000) is stored as a negative/credit balance in the trial balance - flipped here so it displays positive. """ if merge_map is None: merge_map = _load_donor_merge_map() return _process_side(tb_df, REVENUE_ACCOUNT_CODES, "Revenue Category", True, merge_map) def process_expense(tb_df, merge_map=None): """ Expense accounts are debit-normal (already positive in the trial balance) - no sign flip. """ if merge_map is None: merge_map = _load_donor_merge_map() return _process_side(tb_df, EXPENSE_ACCOUNT_CODES, "Spend Category", False, merge_map) def process_revenue_us_only(tb_df, merge_map=None): """US-entity-only counterpart to process_revenue, for the detailed- mode supplementary rows (see _entity_total_us_only).""" if merge_map is None: merge_map = _load_donor_merge_map() return _process_side(tb_df, REVENUE_ACCOUNT_CODES, "Revenue Category", True, merge_map, entity_total_fn=_entity_total_us_only) def process_expense_us_only(tb_df, merge_map=None): """US-entity-only counterpart to process_expense, for the detailed- mode supplementary rows (see _entity_total_us_only).""" if merge_map is None: merge_map = _load_donor_merge_map() return _process_side(tb_df, EXPENSE_ACCOUNT_CODES, "Spend Category", False, merge_map, entity_total_fn=_entity_total_us_only) def _process_side_detail(gl_df, account_codes, category_col, flip_sign, merge_map, include_date): """ Canada-only, line-item-level counterpart to _process_side: same account-code filter, Project parsing, and donor resolution, but keeps one row per GL line (no groupby/sum) and carries the descriptive columns through instead of collapsing them away. Source is the GL Dump's own "Net Ledger Debit minus Credit" (local/CAD currency) - confirmed to reconcile exactly to the trial balance's Planeterra Foundation column at the account level, given a matching period range and Status == "Posted" (already filtered by load_gl_dump). """ df = gl_df.copy() df = df[df["Ledger Account"].astype(str).str.strip().str.startswith(account_codes)] parsed = df["Project"].apply(parse_project) df["slob"] = parsed.apply(lambda t: t[0]) df["donor"] = parsed.apply(lambda t: resolve_donor(t[1], merge_map)) df["category"] = df[category_col].fillna("(Uncategorized)") raw_amount = df[GL_AMOUNT_COL].fillna(0) df["amount"] = -raw_amount if flip_sign else raw_amount df["journal_memo"] = df["Journal Memo"] df["line_memo"] = df["Line Memo"] df["line_description"] = df["Line Description"] df["contingent_worker"] = df["Contingent Worker"] df["supplier_name"] = df["Supplier Name"] if include_date: df["accounting_date"] = df["Accounting Date"] cols = ["donor", "slob", "category", "amount", "journal_memo", "line_memo", "line_description", "contingent_worker", "supplier_name"] if include_date: cols.append("accounting_date") result = df[cols].copy() result = result[result["amount"].abs() >= 0.005] return result.reset_index(drop=True) def process_revenue_detail(gl_df, merge_map=None): """Line-item revenue detail (Canada only) from a loaded GL Dump - see _process_side_detail. Includes Accounting Date.""" if merge_map is None: merge_map = _load_donor_merge_map() return _process_side_detail(gl_df, REVENUE_ACCOUNT_CODES, GL_REVENUE_CATEGORY_COL, True, merge_map, include_date=True) def process_expense_detail(gl_df, merge_map=None): """Line-item expense detail (Canada only) from a loaded GL Dump - see _process_side_detail. No Accounting Date (revenue-only request).""" if merge_map is None: merge_map = _load_donor_merge_map() return _process_side_detail(gl_df, EXPENSE_ACCOUNT_CODES, GL_EXPENSE_CATEGORY_COL, False, merge_map, include_date=False) def reconcile_detail_to_trial_balance(revenue_detail, revenue_us, revenue_tb_df, expense_detail, expense_us, expense_tb_df): """ Cross-check the detailed (GL Canada + TB US aggregate) totals against each trial balance's own combined-entity total for the same account scope - the two should match exactly if the GL Dump's period/status/ currency scope actually lines up with the trial balance (confirmed by hand for one matching Aug 2025-Jul 2026 export set). A material mismatch here means the two inputs are out of sync (different period range, unposted entries included, wrong currency) and the report would otherwise silently show a wrong number for the Canada side. """ def check(detail_df, us_df, tb_df, account_codes, flip_sign): detail_total = round(detail_df["amount"].sum() + us_df["amount"].sum(), 2) sub = tb_df[tb_df["Ledger Account"].astype(str).str.strip().str.startswith(account_codes)] raw = sub[["Planeterra Foundation", "Planeterra International Foundation Ltd"]].fillna(0).sum().sum() expected_total = round(-raw if flip_sign else raw, 2) diff = round(expected_total - detail_total, 2) return { "matches": bool(abs(diff) < RECONCILE_TOLERANCE), "expected": expected_total, "actual": detail_total, "diff": diff, } return { "revenue": check(revenue_detail, revenue_us, revenue_tb_df, REVENUE_ACCOUNT_CODES, True), "expense": check(expense_detail, expense_us, expense_tb_df, EXPENSE_ACCOUNT_CODES, False), } def reconcile_gl_by_account(gl_df, revenue_tb_df, expense_tb_df): """ Per-account reconciliation between the GL Dump (Canada, already filtered to Status == "Posted" by load_gl_dump) and the two trial balances - the same check done by hand while first investigating this GL Dump: for every individual revenue/expense Ledger Account code, the GL's own local-currency (CAD) net debit-minus-credit should sum to that account's trial balance total (Planeterra Foundation column only, since the GL Dump only covers Canada) - compared directly, with no sign flip, since both sources already use the same debit/credit convention (a whole-side check like reconcile_detail_to_trial_balance can pass even when two individual accounts are each wrong in offsetting directions; this catches that). Returns a list of per-account dicts (account, side, trial_balance, gl_dump, diff, matches), one per account code with activity in either source, sorted with any mismatches first (then by account code). """ results = [] for account_codes, tb_df, side in [ (REVENUE_ACCOUNT_CODES, revenue_tb_df, "revenue"), (EXPENSE_ACCOUNT_CODES, expense_tb_df, "expense"), ]: for code in account_codes: gl_sub = gl_df[gl_df["Ledger Account"].astype(str).str.startswith(code)] gl_total = round(gl_sub[GL_AMOUNT_COL].fillna(0).sum(), 2) tb_sub = tb_df[tb_df["Ledger Account"].astype(str).str.strip().str.startswith(code)] tb_total = round(tb_sub["Planeterra Foundation"].fillna(0).sum(), 2) if abs(gl_total) < 0.005 and abs(tb_total) < 0.005: continue # no activity on this account in either source label_source = gl_sub["Ledger Account"] if not gl_sub.empty else tb_sub["Ledger Account"] account_label = str(label_source.iloc[0]).strip() if len(label_source) else code diff = round(tb_total - gl_total, 2) results.append({ "account": account_label, "side": side, "trial_balance": tb_total, "gl_dump": gl_total, "diff": diff, "matches": bool(abs(diff) < RECONCILE_TOLERANCE), }) results.sort(key=lambda r: (r["matches"], r["account"])) return results def sanitize_sheet_name(name): cleaned = _INVALID_SHEET_CHARS.sub("", str(name)) return cleaned[:31] or "Sheet" def _write_cell(ws, row, col, value, bold=False, number_format=None): c = ws.cell(row=row, column=col, value=value) c.font = BOLD_FONT if bold else REGULAR_FONT if number_format: c.number_format = number_format return c def _rows_needed(df): """One row per (project code, category) - no header or subtotal rows.""" return len(df) def _adjust_block(ws, block_start, available, needed): """ Grow or shrink the reserved block of rows starting at block_start so it's exactly `needed` rows, by inserting or deleting rows right at the boundary. Whatever originally followed the reserved block (e.g. the template's "Total Revenue" label) rides along with the insert/delete and ends up at exactly block_start + needed - avoiding a stale duplicate label when needed < available. """ if needed > available: ws.insert_rows(block_start + available, needed - available) elif needed < available: ws.delete_rows(block_start + needed, available - needed) def _write_section(ws, start_row, df): """ Write one row per (project code, category), sorted by project code then category, starting at start_row - a flat, clean list with no account/subtotal rows breaking it up, so the whole section is one contiguous range for the section total's SUM formula. Returns (first_row, last_row) of the written range (None if empty) and this section's raw total. """ if df.empty: return None, 0.0 row = start_row section_total = 0.0 for _, r in df.sort_values(["slob", "category"]).iterrows(): amount = round(r["amount"], 2) slob_label = r["slob"] or "(No project code)" # Explicitly blank column A - the template's own placeholder text # ("Donations & Fundraising Revenue", "Disbursement to Projects") # sits on this first row otherwise, since ws.cell(value=None) is a # no-op in openpyxl rather than a clear - direct assignment is needed. ws.cell(row=row, column=1).value = None _write_cell(ws, row, 2, amount, bold=False, number_format=AMOUNT_FORMAT) _write_cell(ws, row, 3, slob_label, bold=False) _write_cell(ws, row, 4, r["category"], bold=False) section_total += amount row += 1 return (start_row, row - 1), round(section_total, 2) def _clean_text(v): """NaN (float, from pandas) -> None, so a blank GL field writes as an actually-empty cell instead of the literal text "nan".""" return None if pd.isna(v) else v def _rows_needed_detail(detail_df, us_df): """One row per Canada GL line, one row per US-entity aggregate (donor, slob, category) row, plus one subtotal row per distinct category across both.""" categories = set(detail_df["category"]).union(us_df["category"]) return len(detail_df) + len(us_df) + len(categories) def _write_section_detail(ws, start_row, detail_df, us_df, include_date): """ Write one section (Revenue or Expenses) in detailed mode: one bold subtotal row per category (a live SUM formula over that category's own rows) followed by that category's individual rows - Canada's full GL transaction detail (Journal Memo/Line Memo/Description/ Contingent Worker/Supplier Name, and for revenue, Accounting Date), then any US-entity activity as one aggregated row per project code (the GL Dump only covers the Canada entity - see load_gl_dump/process_*_detail). Categories are sorted alphabetically; within a category, Canada rows are sorted by project code (then accounting date, for revenue) and US rows by project code. Returns (list of category-subtotal row numbers, next free row, section's raw total) - the row-number list (not a single contiguous range) is what the caller sums for the section's Total Revenue/Total Expenses formula, since the subtotal rows themselves aren't contiguous with each other. """ if detail_df.empty and us_df.empty: return [], start_row, 0.0 row = start_row subtotal_rows = [] section_total = 0.0 categories = sorted(set(detail_df["category"]).union(us_df["category"])) for category in categories: cat_detail = detail_df[detail_df["category"] == category] cat_us = us_df[us_df["category"] == category] if cat_detail.empty and cat_us.empty: continue subtotal_row = row row += 1 first_detail_row = row sort_cols = ["slob", "accounting_date"] if include_date else ["slob"] for _, r in cat_detail.sort_values(sort_cols, kind="stable").iterrows(): amount = round(r["amount"], 2) ws.cell(row=row, column=1).value = None _write_cell(ws, row, 2, amount, bold=False, number_format=AMOUNT_FORMAT) _write_cell(ws, row, 3, r["slob"] or "(No project code)", bold=False) _write_cell(ws, row, 5, _clean_text(r["journal_memo"]), bold=False) _write_cell(ws, row, 6, _clean_text(r["line_memo"]), bold=False) _write_cell(ws, row, 7, _clean_text(r["line_description"]), bold=False) _write_cell(ws, row, 8, _clean_text(r["contingent_worker"]), bold=False) _write_cell(ws, row, 9, _clean_text(r["supplier_name"]), bold=False) if include_date: date_val = r["accounting_date"] c = ws.cell(row=row, column=10, value=date_val.to_pydatetime() if pd.notna(date_val) else None) c.font = REGULAR_FONT c.number_format = DATE_FORMAT section_total += amount row += 1 for _, r in cat_us.sort_values("slob", kind="stable").iterrows(): amount = round(r["amount"], 2) ws.cell(row=row, column=1).value = None _write_cell(ws, row, 2, amount, bold=False, number_format=AMOUNT_FORMAT) _write_cell(ws, row, 3, r["slob"] or "(No project code)", bold=False) _write_cell(ws, row, 6, US_AGGREGATE_NOTE, bold=False) section_total += amount row += 1 last_detail_row = row - 1 # Same reasoning as _write_section's column-A clear: the # template's own placeholder text ("Donations & Fundraising # Revenue", "Disbursement to Projects") sits on this row when # it's the section's first row, and ws.cell(value=None) is a # no-op in openpyxl rather than a clear - direct assignment needed. ws.cell(row=subtotal_row, column=1).value = None _write_cell(ws, subtotal_row, 4, category, bold=True) c = ws.cell(row=subtotal_row, column=2, value=f"=SUM(B{first_detail_row}:B{last_detail_row})") c.font = BOLD_FONT c.number_format = AMOUNT_FORMAT subtotal_rows.append(subtotal_row) return subtotal_rows, row, round(section_total, 2) DETAIL_HEADERS = {5: "Journal Memo", 6: "Line Memo", 7: "Line Description", 8: "Contingent Worker", 9: "Supplier Name", 10: "Accounting Date"} def _write_donor_sheet(wb, template_ws, donor, revenue_df=None, expense_df=None, revenue_detail_df=None, revenue_us_df=None, expense_detail_df=None, expense_us_df=None): detail_mode = revenue_detail_df is not None ws = wb.copy_worksheet(template_ws) ws.title = sanitize_sheet_name(donor) ws["A1"] = donor ws["B3"] = datetime.today().strftime("%Y-%m-%d") if detail_mode: for col, label in DETAIL_HEADERS.items(): _write_cell(ws, 5, col, label, bold=False) revenue_needed = _rows_needed_detail(revenue_detail_df, revenue_us_df) expense_needed = _rows_needed_detail(expense_detail_df, expense_us_df) else: revenue_needed = _rows_needed(revenue_df) expense_needed = _rows_needed(expense_df) # Template reserves rows 7-12 (6 rows) for Revenue detail before # "Total Revenue", and (after that) 3 rows for Expenses detail before # "Total Expenses". Adjust each block to fit this donor exactly. _adjust_block(ws, 7, 6, revenue_needed) total_revenue_row = 7 + revenue_needed expense_block_start = total_revenue_row + 3 # +2 blank/header rows, +1 to detail start _adjust_block(ws, expense_block_start, 3, expense_needed) total_expenses_row = expense_block_start + expense_needed surplus_row = total_expenses_row + 2 if detail_mode: rev_subtotal_rows, _, revenue_total = _write_section_detail( ws, 7, revenue_detail_df, revenue_us_df, include_date=True) exp_subtotal_rows, _, expense_total = _write_section_detail( ws, expense_block_start, expense_detail_df, expense_us_df, include_date=False) rev_formula = "=" + "+".join(f"B{r}" for r in rev_subtotal_rows) if rev_subtotal_rows else 0 exp_formula = "=" + "+".join(f"B{r}" for r in exp_subtotal_rows) if exp_subtotal_rows else 0 else: rev_range, revenue_total = _write_section(ws, 7, revenue_df) exp_range, expense_total = _write_section(ws, expense_block_start, expense_df) rev_formula = f"=SUM(B{rev_range[0]}:B{rev_range[1]})" if rev_range else 0 exp_formula = f"=SUM(B{exp_range[0]}:B{exp_range[1]})" if exp_range else 0 _write_cell(ws, total_revenue_row, 1, "Total Revenue", bold=True) c = ws.cell(row=total_revenue_row, column=2, value=rev_formula) c.font = BOLD_FONT c.number_format = AMOUNT_FORMAT _write_cell(ws, total_expenses_row, 1, "Total Expenses", bold=True) c = ws.cell(row=total_expenses_row, column=2, value=exp_formula) c.font = BOLD_FONT c.number_format = AMOUNT_FORMAT _write_cell(ws, surplus_row, 1, "Surplus/(Deficit)", bold=False) c = ws.cell(row=surplus_row, column=2, value=f"=B{total_revenue_row}-B{total_expenses_row}") c.font = REGULAR_FONT c.number_format = AMOUNT_FORMAT return { "sheet_title": ws.title, "total_revenue_row": total_revenue_row, "total_expenses_row": total_expenses_row, "revenue_total": revenue_total, "expense_total": expense_total, } def _write_summary_sheet(wb, donor_infos): """ Insert a "Summary" sheet at the front of the workbook: one row per donor with Revenue/Expenses/Surplus, each a live formula referencing that donor's own Total Revenue/Total Expenses cell (so it can never drift out of sync with the per-donor sheets), plus a grand-total row that's the same figure shown in the web UI's result screen. """ ws = wb.create_sheet("Summary", 0) ws.column_dimensions["A"].width = 28.5 for col in "BCD": ws.column_dimensions[col].width = 22 _write_cell(ws, 1, 1, "Donor Revenue Report — Summary", bold=True) _write_cell(ws, 2, 1, datetime.today().strftime("%Y-%m-%d"), bold=False) header_row = 4 for col, label in enumerate(["Donor", "Revenue", "Expenses", "Surplus/(Deficit)"], start=1): _write_cell(ws, header_row, col, label, bold=True) row = header_row + 1 first_data_row = row for info in donor_infos: ref = f"'{info['sheet_title']}'!B{{}}" _write_cell(ws, row, 1, info["sheet_title"], bold=False) c = ws.cell(row=row, column=2, value=f"={ref.format(info['total_revenue_row'])}") c.font = REGULAR_FONT c.number_format = AMOUNT_FORMAT c = ws.cell(row=row, column=3, value=f"={ref.format(info['total_expenses_row'])}") c.font = REGULAR_FONT c.number_format = AMOUNT_FORMAT c = ws.cell(row=row, column=4, value=f"=B{row}-C{row}") c.font = REGULAR_FONT c.number_format = AMOUNT_FORMAT row += 1 last_data_row = row - 1 total_row = row + 1 _write_cell(ws, total_row, 1, "Total", bold=True) for col in (2, 3, 4): letter = "BCD"[col - 2] c = ws.cell(row=total_row, column=col, value=f"=SUM({letter}{first_data_row}:{letter}{last_data_row})") c.font = BOLD_FONT c.number_format = AMOUNT_FORMAT def build_donor_workbook(revenue_grouped, expense_grouped, output_path, template_path=TEMPLATE_PATH, revenue_detail=None, revenue_us=None, expense_detail=None, expense_us=None): """ Write one sheet per donor into a copy of report_summary_template.xlsx, sorted alphabetically, plus a "Summary" sheet at the front totaling each donor's Revenue/Expenses/Surplus. Returns (donor_count, total_revenue, total_expense). revenue_grouped/expense_grouped (the simple per-(project code, category) aggregates from process_revenue/process_expense) are always required. Passing revenue_detail (and the other three detail DataFrames alongside it) switches every donor sheet to the detailed, GL-line-level layout instead (see _write_donor_sheet) - the donor list is then drawn from the detail DataFrames, since a donor could in principle appear in GL activity that groups to a zero-net (and so absent) row in the trial balance aggregate. """ detail_mode = revenue_detail is not None wb = openpyxl.load_workbook(template_path) template_ws = wb[TEMPLATE_SHEET] if detail_mode: # New columns only matter in detailed mode - width them on the # template sheet once, before copying, so every donor sheet # inherits them automatically. for col, width in zip("EFGHIJ", (22, 28, 34, 20, 24, 14)): template_ws.column_dimensions[col].width = width donors = sorted( set(revenue_detail["donor"]) | set(revenue_us["donor"]) | set(expense_detail["donor"]) | set(expense_us["donor"]) ) else: donors = sorted(set(revenue_grouped["donor"]).union(expense_grouped["donor"])) total_revenue = 0.0 total_expense = 0.0 donor_infos = [] for donor in donors: if detail_mode: rd = revenue_detail[revenue_detail["donor"] == donor] ru = revenue_us[revenue_us["donor"] == donor] ed = expense_detail[expense_detail["donor"] == donor] eu = expense_us[expense_us["donor"] == donor] if rd.empty and ru.empty and ed.empty and eu.empty: continue info = _write_donor_sheet(wb, template_ws, donor, revenue_detail_df=rd, revenue_us_df=ru, expense_detail_df=ed, expense_us_df=eu) else: rev_df = revenue_grouped[revenue_grouped["donor"] == donor] exp_df = expense_grouped[expense_grouped["donor"] == donor] if rev_df.empty and exp_df.empty: continue info = _write_donor_sheet(wb, template_ws, donor, revenue_df=rev_df, expense_df=exp_df) total_revenue += info["revenue_total"] total_expense += info["expense_total"] donor_infos.append(info) _write_summary_sheet(wb, donor_infos) del wb[TEMPLATE_SHEET] wb.save(output_path) return len(donor_infos), round(total_revenue, 2), round(total_expense, 2)