diff --git a/.gitignore b/.gitignore index c68cb9e..91c9345 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ outputs/ __pycache__/ *.pyc .env +.DS_Store *.xlsx *.csv *.pdf diff --git a/app/common.py b/app/common.py new file mode 100644 index 0000000..630e501 --- /dev/null +++ b/app/common.py @@ -0,0 +1,353 @@ +""" +Shared, Flask-free helpers used by more than one tool. Per the "simple but +modular" convention (see CLAUDE.md), this stays empty until a second tool +actually duplicates something an existing tool already has - GL Dump +loading was the first thing to hit that bar (donor_report, then +financial_reports); the GL netting/grouping pipeline below is the second +(financial_reports' Balance Sheet supporting schedules, then gl_analyzer). +""" +import re +from collections import defaultdict, deque + +import pandas as pd + +GL_AMOUNT_COL = "Net Ledger Debit minus Credit" +_JE_RE = re.compile(r"JE-\d{4}-\d+") + + +def find_gl_header_row(path, max_scan_rows=60): + """ + GL Dump exports carry a variable-length metadata block (Company, + Year, Period, Status filter, etc - one label per row) before the + real column-header row. That row's position isn't stable enough to + hardcode - seen at row index 22 in one export and 23 in another (a + difference in how many metadata rows the export included) - so scan + for the row whose values include both "Journal" and "Ledger Account" + (the real header, present in every export of this format seen so + far). Returns the 0-indexed row number, or None if no such row is + found in the first max_scan_rows rows (not a GL Dump). + """ + 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 "Journal" in vals and "Ledger Account" in vals: + return i + return None + + +def _extract_gl_metadata(path, header_row): + """ + The metadata block above the real header row (see find_gl_header_row) + is one label/value pair per row - Company, Year, Period, Include + Beginning Balance, etc. Read into a dict keyed by label, for + diagnostics (e.g. explaining why a schedule doesn't tie to the trial + balance) rather than the report data itself - callers that don't need + it can ignore df.attrs entirely. + """ + if header_row == 0: + return {} + raw = pd.read_excel(path, sheet_name=0, header=None, nrows=header_row) + meta = {} + for _, row in raw.iterrows(): + vals = [v for v in row.tolist() if pd.notna(v)] + if len(vals) >= 2 and isinstance(vals[0], str): + meta[str(vals[0]).strip()] = vals[1] + return meta + + +def load_gl_dump(path): + """ + Read a GL Dump export: locate its header row (see + find_gl_header_row), load the data below it, and filter to + Status == "Posted" - draft/in-progress entries wouldn't be reflected + in a trial balance and would throw off any reconciliation built on + this data. Returns None if this doesn't look like a GL Dump (no + matching header row found in the first 60 rows) - the caller falls + back to treating the file as an unrecognized upload. + + The returned DataFrame carries the export's own metadata block (see + _extract_gl_metadata) in df.attrs["gl_metadata"] - pandas preserves + .attrs through the filtering/reset_index below, so callers that want + it (e.g. financial_reports' schedule-mismatch diagnostics) can read + it straight off the DataFrame instead of re-parsing the file. + """ + header_row = find_gl_header_row(path) + if header_row is None: + return None + metadata = _extract_gl_metadata(path, header_row) + df = pd.read_excel(path, sheet_name=0, header=header_row) + if "Status" in df.columns: + df = df[df["Status"] == "Posted"] + df = df.reset_index(drop=True) + df.attrs["gl_metadata"] = metadata + return df + + +def _extract_je(text): + if pd.isna(text): + return None + m = _JE_RE.match(str(text).strip()) + return m.group(0) if m else None + + +def reversed_by_pass(df): + """ + Pass 1 of the GL netting pipeline: drop any journal explicitly linked + to another via Reversed By/Reverses, where BOTH journals are present + in this data - meaning the reversal already happened within the + period this GL export covers, so neither side should show as still + outstanding. + """ + journals_present = set(df["Journal Number"].dropna().unique()) + cleared = set() + for _, row in df.iterrows(): + for field in ("Reversed By", "Reverses"): + target = _extract_je(row.get(field)) + if target is not None and target in journals_present: + cleared.add(row["Journal Number"]) + cleared.add(target) + return df[~df["Journal Number"].isin(cleared)] + + +def fifo_netting_pass(df): + """ + Pass 2: FIFO exact-amount netting on whatever's left after pass 1 - + catches informal reversals (a separate manual journal entry for the + exact opposite amount, with no explicit Reversed By/Reverses link and + not a same-journal wash). Each line cancels the oldest still-open + line with the exact opposite amount; what's left is what still makes + up the balance. + """ + df = df.sort_values("Accounting Date", kind="stable") + pending = defaultdict(deque) + for idx, row in df.iterrows(): + cents = round(row[GL_AMOUNT_COL] * 100) + opp = -cents + if pending[opp]: + pending[opp].popleft() + else: + pending[cents].append(idx) + keep_idx = [i for dq in pending.values() for i in dq] + return df.loc[sorted(keep_idx)] + + +def journal_wash_pass(df): + """ + Pass 3: drop every line belonging to a journal whose own lines net to + ~$0 - a pure reclassification/relabeling with no effect on the + balance (e.g. one line's amount split across two others within the + same journal), which pairwise exact-amount matching (pass 2) can't + catch since it only cancels 2-line pairs. Lines with no Journal + Number are left alone - nothing to group them by. + """ + has_journal = df["Journal Number"].notna() + with_journal, without_journal = df[has_journal], df[~has_journal] + if with_journal.empty: + return df + totals = with_journal.groupby("Journal Number")[GL_AMOUNT_COL].sum() + wash_journals = set(totals[totals.abs() < 0.005].index) + kept = with_journal[~with_journal["Journal Number"].isin(wash_journals)] + return pd.concat([kept, without_journal]) + + +def net_gl_lines(df): + """ + Runs the three netting passes in the required order: Reversed + By/Reverses, THEN FIFO exact-amount netting, THEN the same-journal + wash - not wash-before-FIFO. A journal can look like a "control total + + itemized detail" breakdown (e.g. a "Beginning Balance" journal: one + +176,983.94 line plus dozens of negative lines listing what makes it + up) rather than a genuine reclassification wash, even though its own + lines also net to ~$0. Dropping the whole journal before FIFO runs + would remove those itemized lines before they get a chance to find + their real, later-dated FIFO counterpart elsewhere - orphaning that + counterpart as a false "still outstanding" line (confirmed: this + happened for real, reproducibly, on account 20300's Beginning Balance + journal). Running FIFO first lets genuine cross-journal matches + happen normally; the wash pass then only cleans up whatever + same-journal zero-sum residue FIFO can't catch on its own (pairwise + only) - which is exactly account 13100's 3-line reclassification + case. + """ + df = reversed_by_pass(df) + df = fifo_netting_pass(df) + df = journal_wash_pass(df) + return df + + +def _attribute_revaluation_lines(df): + """ + A line whose original-currency amount is exactly zero but whose CAD + amount isn't is a pure revaluation/FX-timing adjustment - there's no + "original currency movement" of its own, it's purely restating an + EXISTING foreign-currency balance to a new rate. It should never + survive as its own schedule row; it belongs folded into whichever + category actually holds that foreign-currency balance, via the same + Project + currency it's tagged with (confirmed against account + 20300's and 13100's real supporting schedules - every revaluation + line traced to its owning category this way). + + Matching is (Project, currency) against every OTHER category's own + lines. A unique match reassigns the line's category outright and gets + folded in immediately (phase 1) - before a genuine collision (more + than one category shares that Project+currency, e.g. a small balance + and a large one booked under the same Project) gets resolved (phase + 2) by picking whichever candidate's resulting blended rate lands + closest to that currency's reference rate. + + Two things the reference rate and the per-candidate blend must get + right, both confirmed against real collisions (Trees vs. Tribes under + "Planeterra - C&B - G Adventures"/USD; Vacation vs. Elizabeth's line + under "Planeterra - General Fund"/USD): + + - The reference rate must be built ONLY from categories that were + never a candidate in any collision, not a median over every + category's raw rate. A colliding category's own pre-fold rate is + not yet trustworthy (it's exactly what's being resolved), so + including it drags the reference away from the true period rate - + confirmed for real: with Vacation and Elizabeth's raw, unfolded + rates both included in the median, the reference landed near their + shared (wrong) raw value instead of the true 1.4017 established by + the account's genuinely unambiguous categories, and every + collision resolved onto the wrong candidate as a result. + - A candidate's blended rate must be computed from ONLY that + category's rows in the SAME currency as the line being resolved - + a category spanning multiple currencies (e.g. Vacation has CAD, + GBP, and USD lines) has its currencies confused if all of that + category's rows are summed together regardless of currency. + + A line with no match at all (no other category shares its Project+ + currency) is left as its own row rather than silently dropped, since + dropping it would break the schedule's tie-out to the trial balance. + + A reval-shaped line whose "category_reliable" column is already True + is skipped entirely - the caller (see build_gl_schedule) decides what + counts as reliable; confirmed for real that this matters for + financial_reports' Spend Category-based categorization: on account + 20300, 204 of 254 reval-shaped lines already carry their own Spend + Category, and re-folding them via the Project+currency heuristic + would risk reassigning an already-correct category onto the wrong + candidate. + """ + is_reval = (df["orig_amount"].abs() < 0.005) & ~df["category_reliable"] + if not is_reval.any(): + return df + + labeled = df[~is_reval] + if labeled.empty: + return df + + df = df.copy() + candidates_by_key = labeled.groupby(["Project", "orig_currency"])["category"].unique() + + ambiguous_categories = { + cat for cands in candidates_by_key if len(cands) > 1 for cat in cands + } + + def _rate_by_currency(current_df, exclude_categories=()): + cur_labeled = current_df[~is_reval] + if exclude_categories: + cur_labeled = cur_labeled[~cur_labeled["category"].isin(exclude_categories)] + tmp = cur_labeled.groupby(["category", "orig_currency"]).agg( + orig_total=("orig_amount", "sum"), cad_total=(GL_AMOUNT_COL, "sum"), + ) + tmp = tmp[tmp["orig_total"].abs() >= 0.005] + if tmp.empty: + return {} + tmp["rate"] = tmp["cad_total"] / tmp["orig_total"] + return tmp.groupby(level="orig_currency")["rate"].median().to_dict() + + # Phase 1: fold every unambiguous (single-candidate) line immediately. + unresolved = [] + for idx in df[is_reval].index: + row = df.loc[idx] + candidates = candidates_by_key.get((row.get("Project"), row["orig_currency"]), []) + if len(candidates) == 1: + df.at[idx, "category"] = candidates[0] + else: + unresolved.append(idx) + + if not unresolved: + return df + + # Phase 2: resolve genuine collisions against a reference built only + # from categories that were never ambiguous in the first place, with + # an all-categories fallback for a currency where every category + # happens to be caught up in some collision. + ref_rate = _rate_by_currency(df, exclude_categories=ambiguous_categories) + fallback_rate = _rate_by_currency(df) + for idx in unresolved: + row = df.loc[idx] + currency = row["orig_currency"] + candidates = candidates_by_key.get((row.get("Project"), currency), []) + if len(candidates) == 0: + continue # no owning category found - stays its own row + target = ref_rate.get(currency, fallback_rate.get(currency)) + best, best_dist = None, None + for cand in candidates: + cand_rows = df[(df["category"] == cand) & (df["orig_currency"] == currency)] + cand_orig = cand_rows["orig_amount"].sum() + if abs(cand_orig) < 0.005: + continue + implied_rate = (cand_rows[GL_AMOUNT_COL].sum() + row[GL_AMOUNT_COL]) / cand_orig + dist = abs(implied_rate - target) if target is not None else 0 + if best_dist is None or dist < best_dist: + best, best_dist = cand, dist + if best is not None: + df.at[idx, "category"] = best + return df + + +def build_gl_schedule(df, categorize_fn, extra_columns=None): + """ + Categorize every line via categorize_fn(row) -> (label, is_reliable), + fold revaluation/FX-timing lines into their owning label (see + _attribute_revaluation_lines), then group by (label, original + currency) with an effective FX rate computed as CAD total / + original-currency total per group - a blended, period-appropriate + rate rather than one assumed flat rate, since a label can span many + different accrual/transaction dates. + + extra_columns (a list of raw column names, default none) each get a + representative value per group - the raw value off whichever single + GL line in that group has the largest absolute CAD amount. These are + per-transaction fields, so a grouped row (which can combine many GL + lines) can't show all of them - the biggest line's value is the most + representative single one to surface, not a synthesized or averaged + one. Output columns are named after extra_columns verbatim. + + df must already be netted (see net_gl_lines) and filtered to + whatever scope the caller wants one schedule for (e.g. one account). + """ + extra_columns = extra_columns or [] + df = df.copy() + labels_reliable = df.apply(categorize_fn, axis=1, result_type="expand") + df["category"], df["category_reliable"] = labels_reliable[0], labels_reliable[1] + df["orig_currency"] = df.get("Transaction Currency.1") + df["orig_amount"] = df["Transaction Debit Amount"].fillna(0) - df["Transaction Credit Amount"].fillna(0) + is_cad_native = df["orig_currency"].isna() | (df["orig_currency"] == "CAD") + df.loc[is_cad_native, "orig_currency"] = "CAD" + df.loc[is_cad_native, "orig_amount"] = df.loc[is_cad_native, GL_AMOUNT_COL] + + df = _attribute_revaluation_lines(df) + + grouped = df.groupby(["category", "orig_currency"], as_index=False).agg( + orig_total=("orig_amount", "sum"), cad_total=(GL_AMOUNT_COL, "sum"), + ) + has_rate = grouped["orig_total"].abs() >= 0.005 + grouped["rate"] = None + grouped.loc[has_rate, "rate"] = grouped.loc[has_rate, "cad_total"] / grouped.loc[has_rate, "orig_total"] + + if extra_columns: + biggest_line_idx = df.groupby(["category", "orig_currency"])[GL_AMOUNT_COL].apply( + lambda s: s.abs().idxmax() + ) + representative = df.loc[biggest_line_idx.values, ["category", "orig_currency", *extra_columns]] + grouped = grouped.merge(representative, on=["category", "orig_currency"], how="left") + for col in extra_columns: + grouped[col] = grouped[col].where(grouped[col].notna(), None) + + grouped["amt_cad"] = grouped["cad_total"] # always the true ledger amount, whether or not a rate applies + grouped.loc[~has_rate, "orig_total"] = None + grouped.loc[~has_rate, "orig_currency"] = None + return grouped.sort_values("amt_cad", key=lambda s: s.abs(), ascending=False).reset_index(drop=True) diff --git a/app/main.py b/app/main.py index 93eab8e..71180a3 100644 --- a/app/main.py +++ b/app/main.py @@ -3,9 +3,13 @@ from flask import Flask, render_template from tools.eib import eib_bp from tools.donor_report import donor_report_bp +from tools.donor_report_gl import donor_report_gl_bp from tools.financial_reports import financial_reports_bp from tools.payslip import payslip_bp from tools.receipt import receipt_bp +from tools.pdf_unlock import pdf_unlock_bp +from tools.summary_check import summary_check_bp +from tools.gl_analyzer import gl_analyzer_bp # ── Tool registry ──────────────────────────────────────────────────────────── # Each entry drives one card on the landing page. Add a new tool by @@ -33,6 +37,17 @@ TOOLS = [ "url": "/donor-report/", "status": "online", }, + { + "name": "Donor Revenue Report (GL Only)", + "tagline": "GL Dump alone → Per-Donor Financial Extract", + "description": ( + "Same per-donor financial extract as Donor Revenue Report, but " + "needs only a GL Dump - no trial balance required. Canada entity " + "only, since a GL Dump has no US-entity activity to draw on." + ), + "url": "/donor-report-gl/", + "status": "online", + }, { "name": "Financial Reports", "tagline": "Trial Balance → Category Summary & Balance Sheet", @@ -66,6 +81,43 @@ TOOLS = [ "url": "/receipt/", "status": "online", }, + { + "name": "PDF Unlock", + "tagline": "Remove PDF password protection", + "description": ( + "Strips owner-set restrictions (no printing, no copying, etc) from " + "a PDF, and removes its open password too when you supply it - " + "leaves you with a plain, unrestricted PDF." + ), + "url": "/pdf-unlock/", + "status": "online", + }, + { + "name": "Summary Reconciliation Check", + "tagline": "Find which TB lines the Summary formulas are missing", + "description": ( + "Reproduces the per-account balance check from '1. Summary " + "(Manual)' columns AE-AJ - flags any account where the manual " + "E/F formula mapping doesn't fully cover the trial balance, and " + "(with an optional prior-period workbook) points at new TB " + "lines that likely need a mapping added." + ), + "url": "/summary-check/", + "status": "online", + }, + { + "name": "GL Analyzer", + "tagline": "Any account, any field - what's driving the balance", + "description": ( + "Upload a GL extract, pick any account(s) - revenue, expense, " + "balance sheet, any - and pick which field to group by and which " + "extra fields to show. Nets out reversing/wash entries the same " + "way the Financial Reports tool's Balance Sheet schedules do, " + "then shows exactly what's making up the balance." + ), + "url": "/gl-analyzer/", + "status": "online", + }, ] @@ -77,9 +129,13 @@ def create_app(): app.register_blueprint(eib_bp) app.register_blueprint(donor_report_bp) + app.register_blueprint(donor_report_gl_bp) app.register_blueprint(financial_reports_bp) app.register_blueprint(payslip_bp) app.register_blueprint(receipt_bp) + app.register_blueprint(pdf_unlock_bp) + app.register_blueprint(summary_check_bp) + app.register_blueprint(gl_analyzer_bp) @app.route("/") def home(): diff --git a/app/tools/donor_report/logic.py b/app/tools/donor_report/logic.py index 115e6ba..b2f6056 100644 --- a/app/tools/donor_report/logic.py +++ b/app/tools/donor_report/logic.py @@ -4,6 +4,8 @@ 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" @@ -27,6 +29,20 @@ 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'[:\\/?*\[\]]') @@ -91,6 +107,17 @@ def _entity_total(df): 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 @@ -101,7 +128,12 @@ def full_file_balance(tb_df): return round(_entity_total(tb_df).sum(), 2) -def _process_side(tb_df, account_codes, category_col, flip_sign, merge_map): +# 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)] @@ -110,7 +142,7 @@ def _process_side(tb_df, account_codes, category_col, flip_sign, merge_map): df["donor"] = parsed.apply(lambda t: resolve_donor(t[1], merge_map)) df["category"] = df[category_col].fillna("(Uncategorized)") - raw_amount = _entity_total(df) + 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 @@ -152,6 +184,158 @@ def process_expense(tb_df, merge_map=None): 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" @@ -216,15 +400,123 @@ def _write_section(ws, start_row, df): return (start_row, row - 1), round(section_total, 2) -def _write_donor_sheet(wb, template_ws, donor, revenue_df, expense_df): +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") - revenue_needed = _rows_needed(revenue_df) - expense_needed = _rows_needed(expense_df) + 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 @@ -237,18 +529,26 @@ def _write_donor_sheet(wb, template_ws, donor, revenue_df, expense_df): total_expenses_row = expense_block_start + expense_needed surplus_row = total_expenses_row + 2 - rev_range, revenue_total = _write_section(ws, 7, revenue_df) - exp_range, expense_total = _write_section(ws, expense_block_start, expense_df) + 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=f"=SUM(B{rev_range[0]}:B{rev_range[1]})" if rev_range else 0) + 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=f"=SUM(B{exp_range[0]}:B{exp_range[1]})" if exp_range else 0) + c = ws.cell(row=total_expenses_row, column=2, value=exp_formula) c.font = BOLD_FONT c.number_format = AMOUNT_FORMAT @@ -313,27 +613,62 @@ def _write_summary_sheet(wb, donor_infos): c.number_format = AMOUNT_FORMAT -def build_donor_workbook(revenue_grouped, expense_grouped, output_path, template_path=TEMPLATE_PATH): +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 (the union of donors appearing in either - grouped DataFrame) into a copy of report_summary_template.xlsx, + 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] - donors = sorted(set(revenue_grouped["donor"]).union(expense_grouped["donor"])) + 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: - 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, rev_df, exp_df) + 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) diff --git a/app/tools/donor_report/routes.py b/app/tools/donor_report/routes.py index abf36b2..5474d8b 100644 --- a/app/tools/donor_report/routes.py +++ b/app/tools/donor_report/routes.py @@ -7,6 +7,13 @@ import pandas as pd from .logic import ( process_revenue, process_expense, + process_revenue_us_only, + process_expense_us_only, + process_revenue_detail, + process_expense_detail, + load_gl_dump, + reconcile_detail_to_trial_balance, + reconcile_gl_by_account, build_donor_workbook, full_file_balance, _load_donor_merge_map, @@ -41,6 +48,7 @@ def api_process(): return jsonify({"error": "No files uploaded"}), 400 by_role = {} + gl_dump = None # {"df": ..., "name": ...} - optional, enables transaction detail unrecognized = [] for f in files: path = os.path.join( @@ -54,15 +62,28 @@ def api_process(): return jsonify({"error": f"Could not read {f.filename}: {e}"}), 400 role = _classify_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 (transaction detail, + # optional) before giving up on it. + 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 + + unrecognized.append(f.filename) missing = [r for r in ("revenue", "expense") if r not in by_role] if missing: @@ -92,15 +113,47 @@ def api_process(): if revenue_grouped.empty and expense_grouped.empty: return jsonify({"error": "No revenue or expense rows found in the uploaded files"}), 400 + reconciliation = None + account_reconciliation = None + build_kwargs = {} + if gl_dump is not None: + revenue_detail = process_revenue_detail(gl_dump["df"], merge_map) + revenue_us = process_revenue_us_only(by_role["revenue"]["df"], merge_map) + expense_detail = process_expense_detail(gl_dump["df"], merge_map) + expense_us = process_expense_us_only(by_role["expense"]["df"], merge_map) + + reconciliation = reconcile_detail_to_trial_balance( + revenue_detail, revenue_us, by_role["revenue"]["df"], + expense_detail, expense_us, by_role["expense"]["df"], + ) + # Per-account breakdown (Canada GL vs. Canada TB column) - the + # side-level check above can pass even when two individual + # accounts are each wrong in offsetting directions; this catches + # that by checking every revenue/expense Ledger Account on its own. + account_reconciliation = reconcile_gl_by_account( + gl_dump["df"], by_role["revenue"]["df"], by_role["expense"]["df"], + ) + build_kwargs = { + "revenue_detail": revenue_detail, "revenue_us": revenue_us, + "expense_detail": expense_detail, "expense_us": expense_us, + } + today = datetime.today().strftime("%Y-%m-%d") fname = f"Donor_Revenue_Report_{today}.xlsx" fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], fname) - donor_count, total_revenue, total_expense = build_donor_workbook(revenue_grouped, expense_grouped, fpath) + donor_count, total_revenue, total_expense = build_donor_workbook( + revenue_grouped, expense_grouped, fpath, **build_kwargs) surplus_deficit = round(total_revenue - total_expense, 2) - donor_names = sorted(set(revenue_grouped["donor"]).union(expense_grouped["donor"])) + if gl_dump is not None: + donor_names = sorted( + set(build_kwargs["revenue_detail"]["donor"]) | set(build_kwargs["revenue_us"]["donor"]) | + set(build_kwargs["expense_detail"]["donor"]) | set(build_kwargs["expense_us"]["donor"]) + ) + else: + donor_names = sorted(set(revenue_grouped["donor"]).union(expense_grouped["donor"])) - return jsonify({ + response = { "status": "ok", "filename": fname, "donors": donor_count, @@ -108,7 +161,13 @@ def api_process(): "total_expense": total_expense, "surplus_deficit": surplus_deficit, "donor_names": donor_names, - }), 200 + "detail_mode": gl_dump is not None, + } + if reconciliation is not None: + response["reconciliation"] = reconciliation + if account_reconciliation is not None: + response["account_reconciliation"] = account_reconciliation + return jsonify(response), 200 @donor_report_bp.route("/api/download/") diff --git a/app/tools/donor_report_gl/__init__.py b/app/tools/donor_report_gl/__init__.py new file mode 100644 index 0000000..f0fd5c3 --- /dev/null +++ b/app/tools/donor_report_gl/__init__.py @@ -0,0 +1,3 @@ +from .routes import donor_report_gl_bp + +__all__ = ["donor_report_gl_bp"] diff --git a/app/tools/donor_report_gl/logic.py b/app/tools/donor_report_gl/logic.py new file mode 100644 index 0000000..185a94e --- /dev/null +++ b/app/tools/donor_report_gl/logic.py @@ -0,0 +1,48 @@ +""" +Donor Revenue Report built from a GL Dump alone - for when a trial +balance isn't available. Deliberately reuses donor_report's own project- +parsing, donor-resolution, categorization, and workbook-writing logic +(same donor_merge_map.csv and report_summary_template.xlsx it already +has) rather than re-implementing any of it, so a donor's numbers here can +never drift out of sync with what donor_report itself would show for the +same GL Dump - only the input requirement differs. + +Necessarily Canada-only (Planeterra Foundation): a GL Dump has no +visibility into the US entity's activity, which donor_report's trial- +balance-based US-aggregate rows normally supply. That's surfaced to the +caller as us_entity_included=False rather than silently omitted. +""" +import pandas as pd + +from tools.donor_report.logic import ( + process_revenue_detail, + process_expense_detail, + build_donor_workbook, +) + +# Same columns process_revenue_detail/process_expense_detail produce (see +# donor_report/logic.py's _process_side_detail) - build_donor_workbook's +# detailed-mode writer expects revenue_us/expense_us to have this shape +# even when there's no US-entity data to put in them. +_EMPTY_US_COLUMNS = [ + "donor", "slob", "category", "amount", + "journal_memo", "line_memo", "line_description", "contingent_worker", "supplier_name", +] + + +def build_gl_only_report(gl_df, output_path): + """ + Build the donor workbook straight from a GL Dump's revenue/expense + line-item detail, with no US-entity supplementary rows (there's no + trial balance to source them from). Returns (donor_count, + total_revenue, total_expense), same shape as build_donor_workbook. + """ + revenue_detail = process_revenue_detail(gl_df) + expense_detail = process_expense_detail(gl_df) + empty_us = pd.DataFrame(columns=_EMPTY_US_COLUMNS) + + return build_donor_workbook( + None, None, output_path, + revenue_detail=revenue_detail, revenue_us=empty_us, + expense_detail=expense_detail, expense_us=empty_us, + ) diff --git a/app/tools/donor_report_gl/routes.py b/app/tools/donor_report_gl/routes.py new file mode 100644 index 0000000..9c7c904 --- /dev/null +++ b/app/tools/donor_report_gl/routes.py @@ -0,0 +1,65 @@ +import os, uuid +from datetime import datetime +from flask import Blueprint, request, jsonify, send_file, render_template, current_app +from werkzeug.utils import secure_filename + +from common import load_gl_dump +from .logic import build_gl_only_report + +donor_report_gl_bp = Blueprint("donor_report_gl", __name__, url_prefix="/donor-report-gl") + + +@donor_report_gl_bp.route("/") +def index(): + return render_template("donor_report_gl/index.html") + + +@donor_report_gl_bp.route("/api/process", methods=["POST"]) +def api_process(): + f = request.files.get("gl_file") + if not f or not f.filename: + return jsonify({"error": "No GL Dump uploaded"}), 400 + + path = os.path.join( + current_app.config["UPLOAD_FOLDER"], + f"{uuid.uuid4()}_{secure_filename(f.filename)}", + ) + f.save(path) + try: + gl_df = load_gl_dump(path) + finally: + os.remove(path) + + if gl_df is None: + return jsonify({ + "error": f"Could not recognize {f.filename} as a GL Dump export " + f"(no row with both \"Journal\" and \"Ledger Account\" found).", + }), 400 + + fname = f"Donor_Revenue_Report_GL_{datetime.today().strftime('%Y-%m-%d')}.xlsx" + fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], fname) + donor_count, total_revenue, total_expense = build_gl_only_report(gl_df, fpath) + + if donor_count == 0: + return jsonify({ + "error": "No revenue or expense activity found in this GL Dump for the " + "donor report's account ranges.", + }), 400 + + return jsonify({ + "status": "ok", + "filename": fname, + "donors": donor_count, + "total_revenue": total_revenue, + "total_expense": total_expense, + "surplus_deficit": round(total_revenue - total_expense, 2), + }), 200 + + +@donor_report_gl_bp.route("/api/download/") +def api_download(filename): + safe = secure_filename(filename) + fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], safe) + if not os.path.exists(fpath): + return jsonify({"error": "File not found"}), 404 + return send_file(fpath, as_attachment=True) diff --git a/app/tools/gl_analyzer/__init__.py b/app/tools/gl_analyzer/__init__.py new file mode 100644 index 0000000..f457dc5 --- /dev/null +++ b/app/tools/gl_analyzer/__init__.py @@ -0,0 +1 @@ +from .routes import gl_analyzer_bp diff --git a/app/tools/gl_analyzer/logic.py b/app/tools/gl_analyzer/logic.py new file mode 100644 index 0000000..30bde52 --- /dev/null +++ b/app/tools/gl_analyzer/logic.py @@ -0,0 +1,180 @@ +""" +GL Analyzer: a general-purpose version of financial_reports' Balance +Sheet supporting-schedule feature. That feature nets out reversing/wash +GL entries and groups what's left by a fixed categorization chain (Spend +Category, Contingent Worker, Supplier/memo fallback), for Balance Sheet +accounts only. This tool exposes the same underlying pipeline (see +common.net_gl_lines / common.build_gl_schedule) for ANY account and ANY +GL Dump column the user picks as the grouping field - "what's actually +making up this balance" for a revenue or expense account works exactly +the same way as it does for a Balance Sheet account. Flask-free per this +repo's tool convention. +""" +import re + +import pandas as pd +import openpyxl +from openpyxl.styles import Font +from openpyxl.utils import get_column_letter + +from common import GL_AMOUNT_COL, net_gl_lines, build_gl_schedule + +FONT_NAME = "Arial" +FONT_SIZE = 11 +BOLD_FONT = Font(name=FONT_NAME, size=FONT_SIZE, bold=True) +ACCOUNTING_FORMAT_CENTS = '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)' + +_SHEET_INVALID_CHARS = re.compile(r'[:\\/?*\[\]]') + + +def list_accounts(gl_df): + """ + Distinct Ledger Account values in this GL Dump, each with a line + count, sorted by account code - the account picker's data source. + Deliberately no prefix restriction (unlike financial_reports' Balance + Sheet schedules, scoped to codes 1/2/3) - this tool works on any + account, revenue and expense included. + """ + codes = gl_df["Ledger Account"].astype(str).str.strip() + counts = codes.value_counts() + accounts = [ + {"code": account.split(":")[0].strip(), "label": account, "line_count": int(count)} + for account, count in counts.items() + ] + accounts.sort(key=lambda a: a["code"]) + return accounts + + +def header_fill_rates(gl_df, account_codes): + """ + For the GL lines belonging to any of account_codes, every column's + non-null fill rate (0-100), sorted highest first - lets the UI steer + the user toward a header that will actually produce a useful + schedule for THIS account rather than a generic column list that + might be mostly blank (confirmed for real: Spend Category coverage + alone ranges from 0% on AP/AR-type accounts to ~88% on accrual-type + ones - see financial_reports' CONTINGENT_WORKER_ACCOUNT_CODES). + """ + codes = set(account_codes) + account_col = gl_df["Ledger Account"].astype(str).str.strip().str.split(":").str[0] + sub = gl_df[account_col.isin(codes)] + line_count = len(sub) + if line_count == 0: + return {"columns": [], "line_count": 0} + columns = [ + {"name": col, "fill_pct": round(100 * sub[col].notna().mean(), 1)} + for col in gl_df.columns + ] + columns.sort(key=lambda c: (-c["fill_pct"], c["name"])) + return {"columns": columns, "line_count": line_count} + + +def _make_categorize_fn(main_header): + def categorize(row): + value = row.get(main_header) + if pd.notna(value) and str(value).strip(): + return str(value).strip(), True + return "(blank)", False + return categorize + + +def build_account_report(gl_df, account, main_header, extra_headers): + """ + Full pipeline for one account: filter to its posted GL lines, net + out reversals/wash entries (common.net_gl_lines - same three-pass + pipeline financial_reports' Balance Sheet schedules use), then group + what's left by main_header's raw value ("(blank)" for a missing + value - still subject to revaluation-line folding, see + common._attribute_revaluation_lines, so a blank FX-timing line still + gets attributed to whichever real group shares its Project+currency) + with an effective FX rate per group (common.build_gl_schedule). + Returns the grouped schedule DataFrame (empty if no GL activity for + this account). + """ + account_code = account.split(":")[0].strip() + 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", *extra_headers] + if sub.empty: + return pd.DataFrame(columns=empty_columns) + + sub = net_gl_lines(sub) + if sub.empty: + return pd.DataFrame(columns=empty_columns) + + return build_gl_schedule(sub, _make_categorize_fn(main_header), extra_columns=extra_headers) + + +def _sanitize_sheet_name(account): + code, _, name = account.partition(":") + label = f"{code} {name}".strip() if name else code + cleaned = _SHEET_INVALID_CHARS.sub("", label) + return cleaned[:31] or "Schedule" + + +def _write_cell(ws, row, col, value, bold=False, number_format=None): + c = ws.cell(row=row, column=col, value=value) + c.font = Font(name=FONT_NAME, size=FONT_SIZE, bold=bold) + if number_format: + c.number_format = number_format + return c + + +def write_account_sheet(wb, account, schedule_df, main_header, extra_headers, report_date, + number_format=ACCOUNTING_FORMAT_CENTS): + """ + One sheet per account: Description (main_header's value) | one column + per extra_headers | Original Curr | Curr | Rate | Amt (CAD), one row + per (category, currency) - same row shape as financial_reports' + write_schedule_sheet, but with a dynamic extra-column set and no + Trial Balance check block (there's no separate TB upload in this + tool - just a Total row via a live SUM formula). + """ + ws = wb.create_sheet(_sanitize_sheet_name(account)) + ws.column_dimensions["A"].width = 46 + for i in range(len(extra_headers)): + ws.column_dimensions[get_column_letter(2 + i)].width = 28 + + curr_col = 2 + len(extra_headers) # Original Curr + rate_col = curr_col + 2 # Rate + amt_col = curr_col + 3 # Amt (CAD) + for offset, width in enumerate((15, 7, 9)): + ws.column_dimensions[get_column_letter(curr_col + offset)].width = width + ws.column_dimensions[get_column_letter(amt_col)].width = 16 + + _write_cell(ws, 1, 1, f"GL Analysis — {account}", bold=True) + _write_cell(ws, 2, 1, f"Grouped by: {main_header}", bold=True) + _write_cell(ws, 3, 1, f"As of {report_date}", bold=True) + + header_row = 5 + headers = ["Description", *extra_headers, "Original Curr", "Curr", "Rate", "Amt (CAD)"] + for col, label in enumerate(headers, 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, amt_col, 0, number_format=number_format) + row += 1 + for _, r in schedule_df.iterrows(): + _write_cell(ws, row, 1, r["category"], bold=False) + for i, col_name in enumerate(extra_headers): + value = r[col_name] + _write_cell(ws, row, 2 + i, value if pd.notna(value) else "", bold=False) + if r["rate"] is not None: + _write_cell(ws, row, curr_col, round(r["orig_total"], 2), bold=False, number_format=number_format) + _write_cell(ws, row, curr_col + 1, r["orig_currency"], bold=False) + _write_cell(ws, row, rate_col, round(r["rate"], 4), bold=False, number_format="0.0000") + _write_cell(ws, row, amt_col, 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) + amt_letter = get_column_letter(amt_col) + c = ws.cell(row=total_row, column=amt_col, value=f"=SUM({amt_letter}{first_data_row}:{amt_letter}{last_data_row})") + c.font, c.number_format = BOLD_FONT, number_format + + total = round(schedule_df["amt_cad"].sum(), 2) if not schedule_df.empty else 0.0 + return {"account": account, "total": total, "row_count": len(schedule_df)} diff --git a/app/tools/gl_analyzer/routes.py b/app/tools/gl_analyzer/routes.py new file mode 100644 index 0000000..22b991f --- /dev/null +++ b/app/tools/gl_analyzer/routes.py @@ -0,0 +1,129 @@ +import os, uuid +from datetime import datetime +from flask import Blueprint, request, jsonify, render_template, current_app, send_file +from werkzeug.utils import secure_filename +import openpyxl + +from common import load_gl_dump +from .logic import list_accounts, header_fill_rates, build_account_report, write_account_sheet + +gl_analyzer_bp = Blueprint("gl_analyzer", __name__, url_prefix="/gl-analyzer") + +# Single-user/single-session shortcut, same documented pattern as eib's +# LAST_RESULT/PROCESS_STATUS: keeps the uploaded GL Dump's saved path +# (not the parsed DataFrame) so the later /api/headers and /api/generate +# steps of the wizard don't need a re-upload. Not safe for concurrent +# multi-user use - not a concern for this internal, single-operator tool. +UPLOADED_FILES = {} + + +def _load(upload_id): + path = UPLOADED_FILES.get(upload_id) + if path is None or not os.path.exists(path): + return None + return load_gl_dump(path) + + +@gl_analyzer_bp.route("/") +def index(): + return render_template("gl_analyzer/index.html") + + +@gl_analyzer_bp.route("/api/upload", methods=["POST"]) +def api_upload(): + f = request.files.get("gl_file") + if not f or not f.filename: + return jsonify({"error": "Upload a GL extract"}), 400 + + path = os.path.join(current_app.config["UPLOAD_FOLDER"], f"{uuid.uuid4()}_{secure_filename(f.filename)}") + f.save(path) + + gl_df = load_gl_dump(path) + if gl_df is None: + os.remove(path) + return jsonify({"error": "This doesn't look like a GL Dump export (no header row with " + "\"Journal\" and \"Ledger Account\" found)."}), 400 + + upload_id = str(uuid.uuid4()) + UPLOADED_FILES[upload_id] = path + + return jsonify({ + "status": "ok", + "upload_id": upload_id, + "accounts": list_accounts(gl_df), + "line_count": len(gl_df), + }), 200 + + +@gl_analyzer_bp.route("/api/headers", methods=["POST"]) +def api_headers(): + data = request.get_json(silent=True) or {} + upload_id = data.get("upload_id") + account_codes = data.get("account_codes") or [] + if not account_codes: + return jsonify({"error": "Select at least one account"}), 400 + + gl_df = _load(upload_id) + if gl_df is None: + return jsonify({"error": "Upload expired or not found - upload the GL extract again"}), 400 + + result = header_fill_rates(gl_df, account_codes) + return jsonify({"status": "ok", **result}), 200 + + +@gl_analyzer_bp.route("/api/generate", methods=["POST"]) +def api_generate(): + data = request.get_json(silent=True) or {} + upload_id = data.get("upload_id") + account_labels = data.get("accounts") or [] + main_header = data.get("main_header") + extra_headers = data.get("extra_headers") or [] + if not account_labels or not main_header: + return jsonify({"error": "Select at least one account and a main header"}), 400 + + gl_df = _load(upload_id) + if gl_df is None: + return jsonify({"error": "Upload expired or not found - upload the GL extract again"}), 400 + + report_date = datetime.now().strftime("%Y-%m-%d") + wb = openpyxl.Workbook() + wb.remove(wb.active) + + accounts_out = [] + for account in account_labels: + schedule_df = build_account_report(gl_df, account, main_header, extra_headers) + summary = write_account_sheet(wb, account, schedule_df, main_header, extra_headers, report_date) + rows = [] + for _, r in schedule_df.iterrows(): + row = { + "category": r["category"], + "orig_total": r["orig_total"] if r["rate"] is not None else None, + "orig_currency": r["orig_currency"], + "rate": r["rate"], + "amt_cad": r["amt_cad"], + } + for col in extra_headers: + value = r[col] + row[col] = value if value == value else None # NaN-safe (NaN != NaN) + rows.append(row) + accounts_out.append({ + "account": account, "total": summary["total"], "row_count": summary["row_count"], "rows": rows, + }) + + filename = f"GL_Analysis_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx" + out_path = os.path.join(current_app.config["OUTPUT_FOLDER"], filename) + wb.save(out_path) + + return jsonify({ + "status": "ok", "accounts": accounts_out, "main_header": main_header, + "extra_headers": extra_headers, "download_filename": filename, + }), 200 + + +@gl_analyzer_bp.route("/api/download/") +def api_download(filename): + safe = secure_filename(filename) + fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], safe) + if not os.path.exists(fpath): + return jsonify({"error": "File not found"}), 404 + return send_file(fpath, as_attachment=True) diff --git a/app/tools/pdf_unlock/__init__.py b/app/tools/pdf_unlock/__init__.py new file mode 100644 index 0000000..6f836bf --- /dev/null +++ b/app/tools/pdf_unlock/__init__.py @@ -0,0 +1,3 @@ +from .routes import pdf_unlock_bp + +__all__ = ["pdf_unlock_bp"] diff --git a/app/tools/pdf_unlock/logic.py b/app/tools/pdf_unlock/logic.py new file mode 100644 index 0000000..db87338 --- /dev/null +++ b/app/tools/pdf_unlock/logic.py @@ -0,0 +1,35 @@ +""" +Removes PDF password protection: both an open/user password (if supplied +and correct) and any owner-only permission restrictions (no printing, no +copying, etc), which QPDF can always strip without needing the owner +password - only the user/open password, when one is set, actually gates +access and must be supplied by the caller. Flask-free per this repo's +tool convention (see CLAUDE.md). +""" +import pikepdf + + +class WrongPasswordError(Exception): + """Raised when the PDF has an open password and none/the wrong one was supplied.""" + + +def unlock_pdf(input_path, output_path, password=None): + """ + Decrypt the PDF at input_path and write an unprotected copy to + output_path. Returns True if the source PDF was actually protected + (open password and/or owner restrictions), False if it was already + a plain, unprotected PDF - so the caller can give an accurate status + message either way. + """ + try: + pdf = pikepdf.open(input_path, password=password or "") + except pikepdf.PasswordError: + raise WrongPasswordError( + "Incorrect password for this PDF." if password + else "This PDF requires a password to open - enter it and try again." + ) + + was_protected = pdf.is_encrypted + pdf.save(output_path, encryption=False) + pdf.close() + return was_protected diff --git a/app/tools/pdf_unlock/routes.py b/app/tools/pdf_unlock/routes.py new file mode 100644 index 0000000..3535d51 --- /dev/null +++ b/app/tools/pdf_unlock/routes.py @@ -0,0 +1,59 @@ +import os, uuid +from flask import Blueprint, request, jsonify, send_file, render_template, current_app +from werkzeug.utils import secure_filename + +from .logic import unlock_pdf, WrongPasswordError + +pdf_unlock_bp = Blueprint("pdf_unlock", __name__, url_prefix="/pdf-unlock") + + +@pdf_unlock_bp.route("/") +def index(): + return render_template("pdf_unlock/index.html") + + +@pdf_unlock_bp.route("/api/unlock", methods=["POST"]) +def api_unlock(): + f = request.files.get("pdf_file") + if not f or not f.filename: + return jsonify({"error": "No PDF uploaded"}), 400 + if not f.filename.lower().endswith(".pdf"): + return jsonify({"error": "Please upload a .pdf file"}), 400 + + password = request.form.get("password") or None + + in_path = os.path.join( + current_app.config["UPLOAD_FOLDER"], + f"{uuid.uuid4()}_{secure_filename(f.filename)}", + ) + f.save(in_path) + + base_name = secure_filename(f.filename) + out_name = f"{uuid.uuid4()}_unlocked_{base_name}" + out_path = os.path.join(current_app.config["OUTPUT_FOLDER"], out_name) + + try: + was_protected = unlock_pdf(in_path, out_path, password=password) + except WrongPasswordError as e: + return jsonify({"error": str(e)}), 400 + except Exception as e: + return jsonify({"error": f"Could not process this PDF: {e}"}), 400 + finally: + os.remove(in_path) + + return jsonify({ + "status": "ok", + "filename": out_name, + "download_name": f"unlocked_{base_name}", + "was_protected": was_protected, + }), 200 + + +@pdf_unlock_bp.route("/api/download/") +def api_download(filename): + safe = secure_filename(filename) + fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], safe) + if not os.path.exists(fpath): + return jsonify({"error": "File not found"}), 404 + download_name = request.args.get("as") or safe + return send_file(fpath, as_attachment=True, download_name=secure_filename(download_name)) diff --git a/app/tools/summary_check/__init__.py b/app/tools/summary_check/__init__.py new file mode 100644 index 0000000..d9ce0d3 --- /dev/null +++ b/app/tools/summary_check/__init__.py @@ -0,0 +1,3 @@ +from .routes import summary_check_bp + +__all__ = ["summary_check_bp"] diff --git a/app/tools/summary_check/logic.py b/app/tools/summary_check/logic.py new file mode 100644 index 0000000..422d1be --- /dev/null +++ b/app/tools/summary_check/logic.py @@ -0,0 +1,545 @@ +""" +Reproduces, exactly, the per-account balance check the user already +builds by hand in "1. Summary (Manual)" columns AE-AJ of the real +consolidated workbook: an independent trial-balance total (from +"TB SC & Pr (Manual)" - both TB (Manual) sheets carry the full chart of +accounts, just tagged with a different category column, and the user's +own AE-AJ formulas query only the SC one, revenue included) compared +against whatever the Summary sheet's own row-level formulas currently +produce (its cached column H, summed by account). A nonzero difference +means the manual E/F formula mapping for that account doesn't fully +cover the trial balance - Flask-free per this repo's tool convention. + +Deliberately does NOT try to reverse-engineer the row-level E/F SUMIFS +formulas themselves (confirmed impractical: they carry bespoke per-row +adjustments - category-text criteria, hardcoded manual offsets, cross- +references to other rows), and deliberately does NOT try to infer +whether a (category, project) combination is "covered" by reading +Summary's own C/D columns either - tried that, confirmed unreliable for +real (a bespoke formula can pull in a category that never appears in its +own row's C column at all, so a "not referenced anywhere in Summary" +finding isn't trustworthy evidence of a real gap). + +What IS reliable, and is now the only diagnostic this tool offers: a +plain structural diff between this period's trial balance and the prior +period's - literally, does account X have more (or different) rows this +period than last period, and if so, which ones exactly (down to the +Excel row number). No guessing about what Summary's formulas do or +don't capture - just "here's what's actually new in the source data, +go look at it yourself." +""" +import re + +import openpyxl + +from tools.financial_reports.logic import REVENUE_ACCOUNT_CODES, EXPENSE_ACCOUNT_CODES + +RC_SHEET_NAME = "TB RC & Pr (Manual)" +SC_SHEET_NAME = "TB SC & Pr (Manual)" +SUMMARY_SHEET_NAME = "1. Summary (Manual)" +ALL_ACCOUNT_CODES = REVENUE_ACCOUNT_CODES + EXPENSE_ACCOUNT_CODES +RECONCILE_TOLERANCE = 0.01 + +_TB_REQUIRED_COLS = {"Ledger Account", "Project", "Planeterra Foundation"} + + +def _find_tb_header_row(ws, max_scan_rows=30): + """ + The TB (Manual) sheets carry a metadata block (Organization, As of + Period, Ledger, etc) above the real header row - scan for the row + whose values include "Ledger Account", "Project" and "Planeterra + Foundation" (present in every export of this format), same reasoning + as common.py's find_gl_header_row. + """ + for r in range(1, max_scan_rows + 1): + vals = {str(ws.cell(row=r, column=c).value) for c in range(1, ws.max_column + 1) + if ws.cell(row=r, column=c).value is not None} + if _TB_REQUIRED_COLS <= vals: + return r + return None + + +def load_summary_check_sheets(path): + """ + Open the uploaded consolidated workbook and pull out the three sheets + this check needs. Returns (rc_ws, sc_ws, summary_ws, error) - error is + a human-readable string (and all sheets None) if any is missing, + naming the sheets that actually exist so the user can see what went + wrong instead of a bare KeyError. + """ + wb = openpyxl.load_workbook(path, data_only=True) + missing = [n for n in (RC_SHEET_NAME, SC_SHEET_NAME, SUMMARY_SHEET_NAME) if n not in wb.sheetnames] + if missing: + return None, None, None, ( + f"This workbook is missing the sheet(s) {', '.join(missing)} - " + f"found: {', '.join(wb.sheetnames)}." + ) + return wb[RC_SHEET_NAME], wb[SC_SHEET_NAME], wb[SUMMARY_SHEET_NAME], None + + +def read_tb_rows(tb_ws): + """ + Returns (rows, by_account): rows is a list of {"account", "category", + "project", "canada", "us", "row"} dicts (one per TB line, header + block skipped; "row" is the sheet's own 1-indexed Excel row number, + so a diagnostic hint can point the user straight at it); by_account + is {account_code: (canada_total, us_total)} summed across every row + for that code - the independent TB-side total this check compares + the Summary sheet against (see AH in the source workbook). + + "category" reads whichever of "Revenue Category" (RC sheet) or + "Spend Category" (SC sheet) is present. + """ + header_row = _find_tb_header_row(tb_ws) + if header_row is None: + return [], {} + headers = {tb_ws.cell(row=header_row, column=c).value: c for c in range(1, tb_ws.max_column + 1)} + acct_col = headers.get("Ledger Account") + proj_col = headers.get("Project") + cat_col = headers.get("Revenue Category") or headers.get("Spend Category") + canada_col = headers.get("Planeterra Foundation") + us_col = headers.get("Planeterra International Foundation Ltd") + + rows = [] + by_account = {} + for r in range(header_row + 1, tb_ws.max_row + 1): + account = tb_ws.cell(row=r, column=acct_col).value + if not account: + continue + account = str(account).strip() + code = account.split(":")[0].strip() + project = tb_ws.cell(row=r, column=proj_col).value + project = str(project).strip() if project else "" + category = (tb_ws.cell(row=r, column=cat_col).value if cat_col else None) + category = str(category).strip() if category else "" + canada = tb_ws.cell(row=r, column=canada_col).value or 0 + us = (tb_ws.cell(row=r, column=us_col).value or 0) if us_col else 0 + + rows.append({"account": account, "category": category, "project": project, + "canada": canada, "us": us, "row": r}) + if code in ALL_ACCOUNT_CODES: + prev_c, prev_u = by_account.get(code, (0, 0)) + by_account[code] = (prev_c + canada, prev_u + us) + + return rows, by_account + + +def read_summary_actuals(summary_ws): + """ + {account_code: total} - the Summary sheet's own cached column H + (Actual), grouped by account (column B), for every row on a tracked + account code, regardless of how that row's own E/F formula happens + to be built - this reproduces the source workbook's own AI column + without needing to parse any formula. + """ + totals = {} + for r in range(1, summary_ws.max_row + 1): + account = summary_ws.cell(row=r, column=2).value # B + if not account: + continue + code = str(account).strip().split(":")[0].strip() + if code not in ALL_ACCOUNT_CODES: + continue + h = summary_ws.cell(row=r, column=8).value # H + if h is None: + continue + totals[code] = totals.get(code, 0) + h + return totals + + +def read_summary_rows_detailed(summary_ws_values, summary_ws_formulas): + """ + One dict per Summary row (any tracked account): {"row", "account" + (code), "category", "project", "canada" (cached E), "us" (cached F), + "e_formula", "f_formula"} - "project" is "" for a blanket/catch-all + row (no D value), which is how every real per-row formula in this + workbook distinguishes "sum this one project" from "sum whatever + isn't claimed elsewhere". Formula text is only used for the + subtraction-list cross-check in _account_key_breakdown below; cached + values are what everything else compares against. + """ + rows = [] + for r in range(1, summary_ws_values.max_row + 1): + account = summary_ws_values.cell(row=r, column=2).value # B + if not account: + continue + code = str(account).strip().split(":")[0].strip() + if code not in ALL_ACCOUNT_CODES: + continue + category = summary_ws_values.cell(row=r, column=3).value or "" # C + project_raw = summary_ws_values.cell(row=r, column=4).value # D + project = str(project_raw).strip() if project_raw else "" + canada = summary_ws_values.cell(row=r, column=5).value or 0 # E + us = summary_ws_values.cell(row=r, column=6).value or 0 # F + e_formula = summary_ws_formulas.cell(row=r, column=5).value + f_formula = summary_ws_formulas.cell(row=r, column=6).value + rows.append({ + "row": r, "account": code, "category": str(category).strip(), "project": project, + "canada": canada, "us": us, + "e_formula": e_formula if isinstance(e_formula, str) else None, + "f_formula": f_formula if isinstance(f_formula, str) else None, + }) + return rows + + +def _account_key_breakdown(code, tb_rows, summary_rows, flip): + """ + The line-by-line reconciliation this tool couldn't do generically + before: group both the TB and the Summary sheet's own rows for this + one account by (category, project), then work through them by + elimination - the same process a human would use by hand: + + 1. Any TB (category, project) combo that has its own dedicated + Summary row: compare the two directly. A nonzero diff here means + that row's own formula is wrong (references the wrong criteria, + a stale hardcoded value, etc) - flagged as "keyed". + 2. Any TB combo with NO dedicated row falls to whichever "blanket" + Summary row exists for that (account, category) - a row with a + blank project, which by convention sums everything in the + category not already claimed by a dedicated row (usually via an + explicit "-E-E..." subtraction list in its own + formula). Compare the blanket row's cached value against the sum + of the actually-uncovered TB rows; if they disagree, diff the + formula's own subtraction list against the real set of dedicated + rows for that category to name exactly which row is missing (a + genuine double-count) or extraneous (an over-subtraction). + 3. Any TB combo with no dedicated row AND no blanket row at all: + flagged as fully uncovered - these TB dollars aren't captured + anywhere in the Summary sheet. + + Confirmed against a real discrepancy: this exact process (by hand) + found a $3,559.78 double-count (a blanket row's subtraction list + missing one sibling), plus two fully-uncovered TB lines + ($215.64 and $30,728.81) - the three summed to the user's reported + $34,504.23 diff exactly. + + Matching is case-insensitive (Excel's own SUMIFS text criteria are + case-insensitive) - confirmed for real this matters: TB's "CTI - + EasyJet" and the Summary's own "CTI - Easyjet" differ only in case, + which Excel treats as the same project (and the row's cached value + proves it - the formula genuinely captures those TB rows), but a + naive exact-string match would wrongly call that TB group + "uncovered" and misattribute $4,234.37 in real discrepancy elsewhere. + Display text keeps the TB sheet's own original casing. + + Revenue accounts carry the same sign flip as the aggregate AE-AJ-style + check (see run_summary_check): the TB stores revenue on its natural + credit (negative) side while the Summary sheet's own row formulas + report it positive, so `flip=True` negates each TB row's canada/us + before grouping - applied per-row so the case-insensitive key + matching above still lines up against Summary's row-level cache. + """ + def norm(s): + return (s or "").strip().lower() + + sign = -1 if flip else 1 + tb_by_key = {} # (norm_cat, norm_proj) -> {canada, us, rows, cat_display, proj_display} + for row in tb_rows: + if row["account"].split(":")[0].strip() != code: + continue + key = (norm(row["category"]), norm(row["project"])) + slot = tb_by_key.setdefault(key, { + "canada": 0.0, "us": 0.0, "rows": [], + "cat_display": row["category"], "proj_display": row["project"], + }) + slot["canada"] += sign * row["canada"] + slot["us"] += sign * row["us"] + slot["rows"].append(row["row"]) + + keyed = {} # (norm_cat, norm_proj) -> summary row dict + blanket = {} # norm_cat -> summary row dict + cat_display = {} # norm_cat -> a display label (prefer Summary's own text) + for sr in summary_rows: + if sr["account"] != code: + continue + nc = norm(sr["category"]) + cat_display.setdefault(nc, sr["category"]) + if sr["project"]: + keyed[(nc, norm(sr["project"]))] = sr + else: + blanket[nc] = sr + + problems = [] + checked_keys = 0 + uncovered_by_cat = {} # norm_cat -> {canada, us, rows} + + for (nc, nproj), tb in tb_by_key.items(): + checked_keys += 1 + cat_display.setdefault(nc, tb["cat_display"]) + if nproj and (nc, nproj) in keyed: + sr = keyed[(nc, nproj)] + diff_c = round(sr["canada"] - tb["canada"], 2) + diff_u = round(sr["us"] - tb["us"], 2) + if abs(diff_c) >= RECONCILE_TOLERANCE or abs(diff_u) >= RECONCILE_TOLERANCE: + problems.append({ + "kind": "keyed", + "category": tb["cat_display"] or "(no category)", + "project": tb["proj_display"] or "(no project)", + "summary_row": sr["row"], + "tb_canada": round(tb["canada"], 2), "tb_us": round(tb["us"], 2), + "summary_canada": round(sr["canada"], 2), "summary_us": round(sr["us"], 2), + "diff_canada": diff_c, "diff_us": diff_u, "tb_rows": tb["rows"], + }) + else: + slot = uncovered_by_cat.setdefault(nc, {"canada": 0.0, "us": 0.0, "rows": []}) + slot["canada"] += tb["canada"] + slot["us"] += tb["us"] + slot["rows"].extend(tb["rows"]) + + # A dedicated Summary row can cache a nonzero value with NO matching + # TB key on this account at all - confirmed for real: row 87 (labeled + # 68030) is a pure cross-account reference whose entire $25,715.67 + # comes from a 68010 TB row, so 68030 has no TB row of its own for + # that (category, project) key. The loop above only ever visits + # TB-side keys, so a phantom capture like this would otherwise be + # silently dropped - visit any keyed Summary row whose key never + # appeared in tb_by_key at all, treating its TB side as zero. + for (nc, nproj), sr in keyed.items(): + if (nc, nproj) in tb_by_key: + continue + if abs(sr["canada"]) < RECONCILE_TOLERANCE and abs(sr["us"]) < RECONCILE_TOLERANCE: + continue + problems.append({ + "kind": "keyed", + "category": sr["category"] or "(no category)", + "project": sr["project"] or "(no project)", + "summary_row": sr["row"], + "tb_canada": 0.0, "tb_us": 0.0, + "summary_canada": round(sr["canada"], 2), "summary_us": round(sr["us"], 2), + "diff_canada": round(sr["canada"], 2), "diff_us": round(sr["us"], 2), "tb_rows": [], + }) + + checked_categories = len(set(uncovered_by_cat) | set(blanket)) + + for nc in sorted(set(uncovered_by_cat) | set(blanket)): + unc = uncovered_by_cat.get(nc, {"canada": 0.0, "us": 0.0, "rows": []}) + br = blanket.get(nc) + label = cat_display.get(nc, nc) + dedicated_rows = sorted(sr["row"] for (c2, p2), sr in keyed.items() if c2 == nc) + + if br is None: + if abs(unc["canada"]) >= RECONCILE_TOLERANCE or abs(unc["us"]) >= RECONCILE_TOLERANCE: + problems.append({ + "kind": "uncovered", + "category": label or "(no category)", "summary_row": None, + "canada": round(unc["canada"], 2), "us": round(unc["us"], 2), + "tb_rows": unc["rows"], "dedicated_rows": dedicated_rows, + }) + continue + + diff_c = round(br["canada"] - unc["canada"], 2) + diff_u = round(br["us"] - unc["us"], 2) + if abs(diff_c) < RECONCILE_TOLERANCE and abs(diff_u) < RECONCILE_TOLERANCE: + continue + + e_terms = set(int(n) for n in re.findall(r'-E(\d+)', br.get("e_formula") or "")) + f_terms = set(int(n) for n in re.findall(r'-F(\d+)', br.get("f_formula") or "")) + problems.append({ + "kind": "blanket", + "category": label or "(no category)", "summary_row": br["row"], + "uncovered_canada": round(unc["canada"], 2), "uncovered_us": round(unc["us"], 2), + "blanket_canada": round(br["canada"], 2), "blanket_us": round(br["us"], 2), + "diff_canada": diff_c, "diff_us": diff_u, "tb_rows": unc["rows"], + "dedicated_rows": dedicated_rows, + "missing_from_subtraction_canada": [r for r in dedicated_rows if r not in e_terms], + "missing_from_subtraction_us": [r for r in dedicated_rows if r not in f_terms], + "extra_subtraction_canada": sorted(e_terms - set(dedicated_rows)), + "extra_subtraction_us": sorted(f_terms - set(dedicated_rows)), + }) + + problems.sort(key=lambda p: -(abs(p.get("diff_canada", p.get("canada", 0))) + + abs(p.get("diff_us", p.get("us", 0))))) + + # Self-check: this breakdown should fully account for the account's + # real tb_total - summary_total diff. It's reported honestly rather + # than assumed - confirmed for real that it doesn't always: 43000 + # (Donation and Fundraising Revenue) carries a formula pattern this + # by-elimination process doesn't decompose (many small same-account + # reclassification pairs between category/project combos, not a + # simple keyed/blanket/cross-account-reference shape), so its + # breakdown explains none of its real diff - surfacing that plainly + # beats silently implying a complete answer. + explained = 0.0 + for p in problems: + if p["kind"] in ("keyed", "blanket"): + explained += p["diff_canada"] + p["diff_us"] + else: + explained -= (p["canada"] + p["us"]) + explained_diff = round(-explained, 2) # tb_total - summary_total sign, matching entry["diff"] + + return {"checked_keys": checked_keys, "checked_categories": checked_categories, + "problems": problems, "explained_diff": explained_diff} + + +def _rows_for_diagnostics(rc, sc): + """ + Revenue accounts' row detail comes from RC, expense accounts' from SC + - "TB SC & Pr (Manual)" is pivoted around Spend Category, which + doesn't meaningfully apply to revenue accounts, so its row-level + breakout for revenue is coarser than "TB RC & Pr (Manual)"'s + (confirmed for real: a genuine new revenue-side line was invisible + reading SC alone). + """ + combined = [] + for row in rc: + code = row["account"].split(":")[0].strip() + if code in REVENUE_ACCOUNT_CODES: + combined.append(row) + for row in sc: + code = row["account"].split(":")[0].strip() + if code in EXPENSE_ACCOUNT_CODES: + combined.append(row) + return combined + + +def run_summary_check(current_path, prior_path=None): + """ + The main entry point: reproduces the AE-AJ balance check per account + (see module docstring), plus - only when a prior-period workbook is + supplied - a plain structural diff for any account that doesn't + balance: how many rows does this account have this period vs last + period, and which specific (category, project, row number) entries + are actually new. No inference about Summary's own formulas at all; + just "here's what changed in the source data." + + Returns (results, totals, error) - error is a string if either + required sheet is missing from current_path (results/totals are then + None). totals is {"revenue": {...}, "expenses": {...}}, each an + aggregate tb_total/summary_total/diff/matches across every account in + that group - this is the check that actually determines "balanced" + the way the source workbook's own row 15/row 39 totals do: individual + accounts can carry offsetting diffs (a misclassification between two + accounts, not a coverage gap) that net to ~zero in aggregate, and + that's a real, common, non-error pattern - confirmed against the + real June workbook, which nets to ~$0 on both totals despite two + individual account pairs each showing large, exactly-offsetting + diffs (43000/48000 and 68010/68030). + """ + rc_ws, sc_ws, summary_ws, error = load_summary_check_sheets(current_path) + if error: + return None, None, error + + # A second, formulas-mode open of the same workbook - only the Summary + # sheet's raw E/F formula text is needed (for the blanket-row + # subtraction-list cross-check in _account_key_breakdown), so the + # cached-values workbook above is used for everything else. + summary_ws_formulas = openpyxl.load_workbook(current_path, data_only=False)[SUMMARY_SHEET_NAME] + summary_rows_detailed = read_summary_rows_detailed(summary_ws, summary_ws_formulas) + + # The aggregate per-account total (tb_by_account) stays SC-only, + # matching the source workbook's own AE-AJ formulas exactly (verified + # against real cached values). rc_rows/sc_rows below are only for the + # row-count/diff diagnostic, which needs the correctly-pivoted side + # per account type (see _rows_for_diagnostics). + rc_rows, _ = read_tb_rows(rc_ws) + sc_rows, tb_by_account = read_tb_rows(sc_ws) + summary_by_account = read_summary_actuals(summary_ws) + + tb_rows = _rows_for_diagnostics(rc_rows, sc_rows) + + tb_row_count = {} + for row in tb_rows: + code = row["account"].split(":")[0].strip() + tb_row_count[code] = tb_row_count.get(code, 0) + 1 + + prior_row_count = {} + prior_by_account_key = {} # {account_code: {(category, project): occurrence_count}} + if prior_path is not None: + prior_rc_ws, prior_sc_ws, _, prior_error = load_summary_check_sheets(prior_path) + if prior_error is None: + prior_rc_rows, _ = read_tb_rows(prior_rc_ws) + prior_sc_rows, _ = read_tb_rows(prior_sc_ws) + for row in _rows_for_diagnostics(prior_rc_rows, prior_sc_rows): + code = row["account"].split(":")[0].strip() + prior_row_count[code] = prior_row_count.get(code, 0) + 1 + bucket = prior_by_account_key.setdefault(code, {}) + key = (row["category"], row["project"]) + bucket[key] = bucket.get(key, 0) + 1 + + current_by_account_key = {} + for row in tb_rows: + code = row["account"].split(":")[0].strip() + if code not in ALL_ACCOUNT_CODES: + continue + bucket = current_by_account_key.setdefault(code, {}) + key = (row["category"], row["project"]) + if key in bucket: + c0, u0, rows0 = bucket[key] + bucket[key] = (c0 + row["canada"], u0 + row["us"], rows0 + [row["row"]]) + else: + bucket[key] = (row["canada"], row["us"], [row["row"]]) + + results = [] + for code in ALL_ACCOUNT_CODES: + canada, us = tb_by_account.get(code, (0, 0)) + flip = code in REVENUE_ACCOUNT_CODES + tb_total = round((-(canada + us)) if flip else (canada + us), 2) + summary_total = round(summary_by_account.get(code, 0.0), 2) + diff = round(tb_total - summary_total, 2) + matches = abs(diff) < RECONCILE_TOLERANCE + if abs(tb_total) < 0.005 and abs(summary_total) < 0.005: + continue # no activity on this account at all this period + + # Account's own display label, straight from the TB (falls back + # to just the code if this account had zero TB rows this period). + label = next((row["account"] for row in tb_rows if row["account"].split(":")[0].strip() == code), code) + + entry = {"account": label, "tb_total": tb_total, "summary_total": summary_total, + "diff": diff, "matches": matches, "tb_row_count": tb_row_count.get(code, 0)} + + if not matches: + kb = _account_key_breakdown(code, tb_rows, summary_rows_detailed, flip) + kb["unexplained_diff"] = round(diff - kb["explained_diff"], 2) + entry["key_breakdown"] = kb + + if not matches and prior_by_account_key: + entry["prior_tb_row_count"] = prior_row_count.get(code, 0) + keys_here = current_by_account_key.get(code, {}) + prior_key_counts = prior_by_account_key.get(code, {}) + + # Brand-new (category, project) combos - never seen last period. + new_lines = [ + {"category": cat or "(no category)", "project": proj or "(no project)", + "canada": round(c, 2), "us": round(u, 2), "tb_rows": tb_rows_list} + for (cat, proj), (c, u, tb_rows_list) in keys_here.items() + if prior_key_counts.get((cat, proj), 0) == 0 and (abs(c) >= 0.005 or abs(u) >= 0.005) + ] + entry["new_since_prior"] = sorted(new_lines, key=lambda x: (x["category"], x["project"])) + + # A combo that ALREADY existed last period can still have picked + # up an extra row this period - a raw row-count check (which + # this tool's whole point is to trust) would flag the account, + # but a pure "is this key new" check would silently merge the + # extra row into the existing bucket and never mention it. + # Confirmed for real: 68010 gained exactly 8 rows between two + # periods, but only 7 were genuinely new keys - the 8th was a + # real, distinct $281,073.79 line that happened to share its + # (category, project) with an existing row, so it never showed + # up as "new" under key-set logic alone. Surface the whole + # current-period group so a human can see all of it rather than + # silently trusting an inflated bucket. + grown = [ + {"category": cat or "(no category)", "project": proj or "(no project)", + "canada": round(c, 2), "us": round(u, 2), "tb_rows": tb_rows_list, + "prior_count": prior_key_counts.get((cat, proj), 0), "current_count": len(tb_rows_list)} + for (cat, proj), (c, u, tb_rows_list) in keys_here.items() + if 0 < prior_key_counts.get((cat, proj), 0) < len(tb_rows_list) + ] + entry["grown_since_prior"] = sorted(grown, key=lambda x: (x["category"], x["project"])) + + results.append(entry) + + results.sort(key=lambda r: (r["matches"], r["account"])) + + totals = {} + for group_name, codes in [("revenue", REVENUE_ACCOUNT_CODES), ("expenses", EXPENSE_ACCOUNT_CODES)]: + group_results = [r for r in results if r["account"].split(":")[0].strip() in codes] + tb_sum = round(sum(r["tb_total"] for r in group_results), 2) + summary_sum = round(sum(r["summary_total"] for r in group_results), 2) + diff_sum = round(tb_sum - summary_sum, 2) + totals[group_name] = { + "tb_total": tb_sum, "summary_total": summary_sum, + "diff": diff_sum, "matches": abs(diff_sum) < RECONCILE_TOLERANCE, + } + + return results, totals, None diff --git a/app/tools/summary_check/routes.py b/app/tools/summary_check/routes.py new file mode 100644 index 0000000..15f20fb --- /dev/null +++ b/app/tools/summary_check/routes.py @@ -0,0 +1,53 @@ +import os, uuid +from flask import Blueprint, request, jsonify, render_template, current_app +from werkzeug.utils import secure_filename + +from .logic import run_summary_check + +summary_check_bp = Blueprint("summary_check", __name__, url_prefix="/summary-check") + + +@summary_check_bp.route("/") +def index(): + return render_template("summary_check/index.html") + + +@summary_check_bp.route("/api/check", methods=["POST"]) +def api_check(): + current_file = request.files.get("current_file") + if not current_file or not current_file.filename: + return jsonify({"error": "Upload this period's consolidated workbook"}), 400 + + def _save(f): + path = os.path.join( + current_app.config["UPLOAD_FOLDER"], + f"{uuid.uuid4()}_{secure_filename(f.filename)}", + ) + f.save(path) + return path + + current_path = _save(current_file) + prior_path = None + prior_file = request.files.get("prior_file") + if prior_file and prior_file.filename: + prior_path = _save(prior_file) + + try: + results, totals, error = run_summary_check(current_path, prior_path) + finally: + os.remove(current_path) + if prior_path: + os.remove(prior_path) + + if error: + return jsonify({"error": error}), 400 + + mismatches = [r for r in results if not r["matches"]] + return jsonify({ + "status": "ok", + "accounts": results, + "totals": totals, + "mismatch_count": len(mismatches), + "total_count": len(results), + "prior_file_used": prior_path is not None, + }), 200 diff --git a/requirements.txt b/requirements.txt index a6b3127..e5c79f9 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,3 +3,4 @@ pandas==2.2.2 openpyxl==3.1.2 requests==2.32.3 werkzeug==3.0.3 +pikepdf==9.5.2 diff --git a/templates/donor_report/index.html b/templates/donor_report/index.html index 1ea84cc..5731f94 100644 --- a/templates/donor_report/index.html +++ b/templates/donor_report/index.html @@ -197,6 +197,40 @@ main { padding: 4px 10px; } +.detail-badge { + display: inline-flex; align-items: center; gap: 5px; + font-family: var(--mono); font-size: 10px; color: var(--cyan); + background: var(--cyan-dim); border: 1px solid var(--border-c); + border-radius: 20px; padding: 3px 10px; margin-top: 6px; +} +.recon-row { + display: flex; align-items: center; justify-content: space-between; + padding: 8px 0; border-bottom: 1px solid var(--w5); + font-family: var(--mono); font-size: 11px; color: var(--w2); +} +.recon-row:last-child { border-bottom: none; } +.recon-badge { padding: 3px 9px; border-radius: 20px; font-size: 10px; font-weight: 500; } +.recon-badge.ok { background: var(--green-dim); color: var(--green); } +.recon-badge.warn { background: var(--red-dim); color: var(--red); } + +.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); } + 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; } @@ -218,7 +252,7 @@ footer a { color: var(--cyan); text-decoration: none; }
Planeterra International Foundation

Donor Revenue Report

-

Upload the revenue trial balance and the expense trial balance to generate one formatted financial extract sheet per donor.

+

Upload the revenue trial balance and the expense trial balance to generate one formatted financial extract sheet per donor. Optionally add a GL Dump export too, to break each donor's revenue/expense down to individual transactions (line memo, description, contingent worker, supplier, and — for revenue — the exact accounting date) instead of one summarized row per project code/category.

@@ -231,7 +265,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 transaction-level detail
    @@ -254,9 +288,20 @@ footer a { color: var(--cyan); text-decoration: none; }
    Report generated
    +
    + + + +
    —
    @@ -370,6 +415,43 @@ $('processBtn').addEventListener('click', async () => { surplusEl.textContent = fmtMoney(d.surplus_deficit); surplusEl.className = 'stat-value ' + (d.surplus_deficit >= 0 ? 'positive' : 'negative'); $('donorList').innerHTML = d.donor_names.map(n => `
    ${n}
    `).join(''); + + $('detailBadge').style.display = d.detail_mode ? 'inline-flex' : 'none'; + + if (d.reconciliation) { + $('reconSection').style.display = ''; + const rows = []; + for (const [label, side] of [['Revenue', d.reconciliation.revenue], ['Expenses', d.reconciliation.expense]]) { + rows.push(`
    ${label}: expected ${fmtMoney(side.expected)} vs GL+US total ${fmtMoney(side.actual)} + ${side.matches ? 'MATCH' : 'MISMATCH'}
    `); + } + $('reconRows').innerHTML = rows.join(''); + } else { + $('reconSection').style.display = 'none'; + } + + if (d.account_reconciliation && d.account_reconciliation.length) { + $('acctReconSection').style.display = ''; + const acct = d.account_reconciliation; + const mismatches = acct.filter(a => !a.matches).length; + $('acctReconLabel').textContent = mismatches + ? `Per-Account Reconciliation — ${mismatches} of ${acct.length} account${acct.length === 1 ? '' : 's'} MISMATCH` + : `Per-Account Reconciliation — all ${acct.length} accounts match`; + const rows = ['
    AccountTrial BalanceGL DumpDiffStatus
    ']; + acct.forEach(a => { + rows.push(`
    + ${a.account} + ${fmtMoney(a.trial_balance)} + ${fmtMoney(a.gl_dump)} + ${fmtMoney(a.diff)} + ${a.matches ? 'OK' : 'MISMATCH'} +
    `); + }); + $('acctReconTable').innerHTML = rows.join(''); + } else { + $('acctReconSection').style.display = 'none'; + } + $('resultCard').classList.add('visible'); } else { $('errorNote').textContent = d.error || 'Unexpected error'; diff --git a/templates/donor_report_gl/index.html b/templates/donor_report_gl/index.html new file mode 100644 index 0000000..332071c --- /dev/null +++ b/templates/donor_report_gl/index.html @@ -0,0 +1,365 @@ + + + + + +Donor Revenue Report (GL Only) — Undo Designs + + + + + +
    + +
    + +
    +
    +
    Planeterra International Foundation
    +

    Donor Revenue Report — GL Only

    +

    Upload just a GL Dump export — no trial balance needed — to generate one formatted financial extract sheet per donor, broken down to individual transactions (line memo, description, contingent worker, supplier, and accounting date for revenue).

    +
    + +
    + +
    Canada entity only. A GL Dump alone has no visibility into Planeterra International Foundation Ltd's (US) activity — that supplementary detail only comes from a trial balance. If you have both a GL Dump and the trial balances, use the regular Donor Revenue Report tool instead for the complete picture.
    +
    + +
    +
    GL Dump File
    +
    + +
    + + + + +
    +
    Drop a GL Dump export here or browse
    +
    .xlsx / .xls — must have a "Journal" + "Ledger Account" header row
    +
    + + + +
    +
    + Processing… +
    +
    +
    + +
    +
    +
    + + + +
    +
    +
    Report generated
    +
    +
    +
    + +
    +
    +
    —
    +
    Donor Sheets
    +
    +
    +
    —
    +
    Total Revenue (CAD)
    +
    +
    +
    —
    +
    Total Expense (CAD)
    +
    +
    +
    —
    +
    Surplus / (Deficit)
    +
    +
    + + +
    +
    + +
    + Built by Undo Designs · Donor Revenue Report (GL Only) v1 +
    + + + + diff --git a/templates/gl_analyzer/index.html b/templates/gl_analyzer/index.html new file mode 100644 index 0000000..ef38d0c --- /dev/null +++ b/templates/gl_analyzer/index.html @@ -0,0 +1,528 @@ + + + + + +GL Analyzer — Undo Designs + + + + + +
    + +
    + +
    +
    +
    Planeterra International Foundation
    +

    GL Analyzer

    +

    Upload a GL extract, pick any account(s), then pick which field to group by and which extra fields to show. Nets out reversing/wash entries the same way the Financial Reports tool's Balance Sheet schedules do, then shows exactly what's making up the balance.

    +
    + +
    +
    1 Upload GL Extract
    +
    + +
    Drop your GL extract here or browse
    +
    A GL Dump export (any header row position, scanned automatically)
    +
    + + +
    Uploading…
    +
    +
    + +
    +
    2 Select Account(s)
    + +
    + +
    Checking fields…
    +
    +
    + +
    +
    3 Choose Fields
    +

    Percentages show how often each field is actually populated across the GL lines for your selected account(s) — pick a main field with good coverage, or the schedule will mostly show "(blank)".

    + +
    Main field (what to group the balance by)
    + +
    + +
    Extra fields to show alongside each row (optional)
    + +
    + + +
    Generating…
    +
    +
    + + +
    + + + + + + diff --git a/templates/pdf_unlock/index.html b/templates/pdf_unlock/index.html new file mode 100644 index 0000000..4c62e23 --- /dev/null +++ b/templates/pdf_unlock/index.html @@ -0,0 +1,356 @@ + + + + + +PDF Unlock — Undo Designs + + + + + +
    + +
    + + + + Deleted from the server right after processing +
    +
    + +
    +
    +
    PDF Utilities
    +

    PDF Unlock

    +

    Removes PDF password security so you're free to use your PDFs as you want. Strips owner-set restrictions (no printing, no copying, no editing) automatically, and removes the open password too if you supply it below.

    +
    + +
    +
    PDF File
    +
    + +
    + + + + +
    +
    Drop a PDF here or browse
    +
    .pdf files only
    +
    + + +
    + + +
    Owner-set restrictions (printing, copying, editing) are removed automatically, no password needed. An open password can only be removed if you know it.
    +
    + + +
    +
    + Processing… +
    +
    +
    + +
    +
    +
    + + + +
    +
    +
    PDF unlocked
    +
    +
    +
    + +
    +
    + + + + + + diff --git a/templates/summary_check/index.html b/templates/summary_check/index.html new file mode 100644 index 0000000..b4723dc --- /dev/null +++ b/templates/summary_check/index.html @@ -0,0 +1,545 @@ + + + + + +Summary Reconciliation Check — Undo Designs + + + + + +
    + +
    + +
    +
    +
    Planeterra International Foundation
    +

    Summary Reconciliation Check

    +

    Reproduces the per-account balance check from "1. Summary (Manual)" columns AE-AJ: an independent trial balance total per account, compared against what the Summary sheet's own formulas currently produce. Flags any account whose manual E/F mapping doesn't fully cover the trial balance.

    +
    + +
    +
    This Period's Workbook
    +
    + +
    Drop this period's consolidated workbook here or browse
    +
    Must contain "TB SC & Pr (Manual)" and "1. Summary (Manual)" sheets
    +
    + + +
    Prior Period's Workbook (optional)
    +
    + +
    Drop last period's workbook here or browse
    +
    Enables the "new lines since last period" hint for any mismatched account
    +
    + + + +
    +
    + Checking… +
    +
    +
    + +
    +
    +
    + + + +
    +
    +
    +
    +
    +
    + +
    Aggregate Balance (the "is this workbook actually balanced" answer)
    +
    + +
    Per-Account Detail
    +

    Individual accounts can show a nonzero diff even when the aggregate above balances — that's usually a misclassification between two related accounts (their diffs cancel out), not a real coverage gap. Focus on accounts whose diff isn't offset by a matching pair. TB row numbers below refer to "TB RC & Pr (Manual)" for revenue accounts and "TB SC & Pr (Manual)" for expense accounts.

    +
    + AccountTB TotalSummary TotalDiffStatus +
    +
    +
    +
    + +
    + Built by Undo Designs · Summary Reconciliation Check v1 +
    + + + +