Lift GL Dump helpers into app/common.py; add GL Analyzer, PDF Unlock, Summary Reconciliation Check, and Donor Report (GL Only) tools

Shared GL Dump loading/netting logic (find_gl_header_row, load_gl_dump,
reversed-by/FIFO/wash netting passes) now lives in app/common.py, used
by Donor Report's new GL-detail mode plus three new tools: Donor
Report (GL Only), GL Analyzer, and Summary Reconciliation Check.
PDF Unlock (via pikepdf) is unrelated but added alongside.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HToTtpxzoxeugsa1Ve61gn
This commit is contained in:
JasonFraser 2026-10-01 20:00:00 -04:00
parent a3196200de
commit 6d0e07ae78
23 changed files with 3839 additions and 34 deletions

1
.gitignore vendored
View File

@ -3,6 +3,7 @@ outputs/
__pycache__/
*.pyc
.env
.DS_Store
*.xlsx
*.csv
*.pdf

353
app/common.py Normal file
View File

@ -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)

View File

@ -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():

View File

@ -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)

View File

@ -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/<filename>")

View File

@ -0,0 +1,3 @@
from .routes import donor_report_gl_bp
__all__ = ["donor_report_gl_bp"]

View File

@ -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,
)

View File

@ -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/<filename>")
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)

View File

@ -0,0 +1 @@
from .routes import gl_analyzer_bp

View File

@ -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)}

View File

@ -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/<filename>")
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)

View File

@ -0,0 +1,3 @@
from .routes import pdf_unlock_bp
__all__ = ["pdf_unlock_bp"]

View File

@ -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

View File

@ -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/<filename>")
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))

View File

@ -0,0 +1,3 @@
from .routes import summary_check_bp
__all__ = ["summary_check_bp"]

View File

@ -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<row>-E<row>..." 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

View File

@ -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

View File

@ -3,3 +3,4 @@ pandas==2.2.2
openpyxl==3.1.2
requests==2.32.3
werkzeug==3.0.3
pikepdf==9.5.2

View File

@ -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; }
</style>
@ -218,7 +252,7 @@ footer a { color: var(--cyan); text-decoration: none; }
<div class="page-title">
<div class="eyebrow">Planeterra International Foundation</div>
<h1>Donor Revenue Report</h1>
<p>Upload the revenue trial balance and the expense trial balance to generate one formatted financial extract sheet per donor.</p>
<p>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.</p>
</div>
<div class="card">
@ -231,7 +265,7 @@ footer a { color: var(--cyan); text-decoration: none; }
</svg>
</div>
<div class="file-zone-label" id="tbDropLabel"><strong>Drop trial balance files here</strong> or <span style="color:var(--cyan);cursor:pointer" id="tbBrowseBtn">browse</span></div>
<div class="file-zone-sub">Revenue trial balance + expense trial balance (.xlsx)</div>
<div class="file-zone-sub">Revenue trial balance + expense trial balance (.xlsx) — plus an optional GL Dump for transaction-level detail</div>
</div>
<ul class="tb-file-list" id="tbFileList"></ul>
@ -254,9 +288,20 @@ footer a { color: var(--cyan); text-decoration: none; }
<div>
<div class="result-title">Report generated</div>
<div class="result-sub" id="resultSub"></div>
<div class="detail-badge" id="detailBadge" style="display:none">Transaction-level detail included</div>
</div>
</div>
<div id="reconSection" style="display:none; margin-bottom:16px">
<div class="section-label">Reconciliation — GL Dump vs. Trial Balance</div>
<div id="reconRows"></div>
</div>
<div id="acctReconSection" style="display:none; margin-bottom:16px">
<div class="section-label" id="acctReconLabel">Per-Account Reconciliation</div>
<div class="acct-recon-table" id="acctReconTable"></div>
</div>
<div class="stats-grid">
<div class="stat-box">
<div class="stat-value" id="statDonors">—</div>
@ -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 => `<div class="donor-chip">${n}</div>`).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(`<div class="recon-row"><span>${label}: expected ${fmtMoney(side.expected)} vs GL+US total ${fmtMoney(side.actual)}</span>
<span class="recon-badge ${side.matches ? 'ok' : 'warn'}">${side.matches ? 'MATCH' : 'MISMATCH'}</span></div>`);
}
$('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 = ['<div class="acct-recon-row head"><span>Account</span><span class="num">Trial Balance</span><span class="num">GL Dump</span><span class="num">Diff</span><span>Status</span></div>'];
acct.forEach(a => {
rows.push(`<div class="acct-recon-row${a.matches ? '' : ' mismatch'}">
<span>${a.account}</span>
<span class="num">${fmtMoney(a.trial_balance)}</span>
<span class="num">${fmtMoney(a.gl_dump)}</span>
<span class="num">${fmtMoney(a.diff)}</span>
<span class="recon-badge ${a.matches ? 'ok' : 'warn'}">${a.matches ? 'OK' : 'MISMATCH'}</span>
</div>`);
});
$('acctReconTable').innerHTML = rows.join('');
} else {
$('acctReconSection').style.display = 'none';
}
$('resultCard').classList.add('visible');
} else {
$('errorNote').textContent = d.error || 'Unexpected error';

View File

@ -0,0 +1,365 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Donor Revenue Report (GL Only) — Undo Designs</title>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
--navy: #0C1A3A;
--navy-2: #12244C;
--navy-3: #1a2f5e;
--navy-4: #0a1428;
--cyan: #00D4FF;
--cyan-dim: rgba(0,212,255,.12);
--cyan-glow: rgba(0,212,255,.06);
--blue: #1B8EF8;
--green: #10D98A;
--green-dim: rgba(16,217,138,.12);
--red: #F04438;
--red-dim: rgba(240,68,56,.12);
--amber: #F79009;
--amber-dim: rgba(247,144,9,.12);
--w1: rgba(255,255,255,.95);
--w2: rgba(255,255,255,.65);
--w3: rgba(255,255,255,.35);
--w4: rgba(255,255,255,.10);
--w5: rgba(255,255,255,.05);
--border: rgba(255,255,255,.07);
--border-c: rgba(0,212,255,.18);
--mono: 'JetBrains Mono', monospace;
--disp: 'Space Grotesk', sans-serif;
--body: 'Inter', sans-serif;
--radius: 10px;
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: var(--body);
background: var(--navy-4);
color: var(--w1);
min-height: 100vh;
-webkit-font-smoothing: antialiased;
display: flex;
flex-direction: column;
}
body::before {
content: '';
position: fixed; inset: 0; pointer-events: none; z-index: 0;
background-image: radial-gradient(circle, rgba(0,212,255,.07) 1px, transparent 1px);
background-size: 28px 28px;
}
header {
position: sticky; top: 0; z-index: 100;
background: rgba(12,26,58,.85);
backdrop-filter: blur(12px);
border-bottom: 1px solid var(--border);
padding: 0 32px;
height: 60px;
display: flex; align-items: center; justify-content: space-between;
}
.logo {
display: flex; align-items: center; gap: 10px;
font-family: var(--disp); font-size: 15px; font-weight: 600;
color: var(--w1); text-decoration: none;
}
.logo-icon {
width: 30px; height: 30px;
background: linear-gradient(135deg, var(--navy-3), var(--navy-2));
border: 1px solid var(--border-c);
border-radius: 7px;
display: flex; align-items: center; justify-content: center;
}
.logo-icon svg { width: 16px; height: 16px; }
.logo span { color: var(--cyan); }
main {
position: relative; z-index: 1;
flex: 1;
max-width: 640px;
width: 100%;
margin: 0 auto;
padding: 48px 24px 80px;
}
.page-title { margin-bottom: 24px; }
.eyebrow {
font-family: var(--mono); font-size: 10px;
letter-spacing: .16em; text-transform: uppercase;
color: var(--cyan); margin-bottom: 10px;
}
.page-title h1 {
font-family: var(--disp); font-size: 28px; font-weight: 700;
color: var(--w1); line-height: 1.2; margin-bottom: 8px;
}
.page-title p { font-size: 14px; color: var(--w2); line-height: 1.6; }
.scope-note {
display: flex; gap: 10px; align-items: flex-start;
font-size: 12.5px; color: var(--w2); background: var(--amber-dim);
border: 1px solid rgba(247,144,9,.25); border-radius: 8px;
padding: 12px 14px; margin-bottom: 24px; line-height: 1.55;
}
.scope-note svg { width: 15px; height: 15px; color: var(--amber); flex-shrink: 0; margin-top: 1px; }
.scope-note strong { color: var(--w1); }
.card {
background: var(--navy-2);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 24px;
margin-bottom: 16px;
}
.card-label {
font-family: var(--mono); font-size: 9.5px; letter-spacing: .14em;
text-transform: uppercase; color: var(--w3); margin-bottom: 14px;
}
.file-zone {
border: 1.5px dashed var(--border);
border-radius: 8px;
padding: 28px 20px;
text-align: center;
cursor: pointer;
transition: all .2s;
position: relative;
}
.file-zone:hover, .file-zone.drag-over { border-color: var(--cyan); background: var(--cyan-glow); }
.file-zone input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%; }
.file-zone-icon {
width: 36px; height: 36px; margin: 0 auto 10px;
background: var(--w5); border-radius: 8px;
display: flex; align-items: center; justify-content: center;
}
.file-zone-icon svg { width: 18px; height: 18px; color: var(--w3); }
.file-zone-label { font-size: 13px; color: var(--w2); }
.file-zone-label strong { color: var(--cyan); }
.file-zone-sub { font-size: 11px; color: var(--w3); margin-top: 4px; }
.file-chosen { font-family: var(--mono); font-size: 11.5px; color: var(--green); margin-top: 10px; }
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
padding: 11px 22px; border-radius: 8px; border: none;
font-family: var(--disp); font-size: 13px; font-weight: 600;
cursor: pointer; transition: all .2s; text-decoration: none;
width: 100%; margin-top: 16px;
}
.btn-primary { background: linear-gradient(135deg, var(--cyan), var(--blue)); color: var(--navy); }
.btn-primary:hover { filter: brightness(1.08); }
.btn-primary:disabled { opacity: .4; cursor: not-allowed; filter: none; }
.spinner {
display: none;
align-items: center; gap: 8px;
font-family: var(--mono); font-size: 11px; color: var(--w3);
margin-top: 12px;
}
.spinner.visible { display: flex; }
.spinner-dot {
width: 6px; height: 6px; border-radius: 50%; background: var(--cyan);
animation: pulse 1s infinite ease-in-out;
}
@keyframes pulse { 0%,100% { opacity: .3; } 50% { opacity: 1; } }
.error-note {
display: none;
font-size: 12px; color: var(--red); background: var(--red-dim);
border: 1px solid rgba(240,68,56,.2); border-radius: 8px;
padding: 12px 14px; margin-top: 12px;
}
.error-note.visible { display: block; }
.result-card { display: none; }
.result-card.visible { display: block; }
.result-header { display: flex; align-items: center; gap: 10px; margin-bottom: 18px; }
.result-icon {
width: 32px; height: 32px; border-radius: 8px;
background: var(--green-dim); display: flex; align-items: center; justify-content: center;
}
.result-icon svg { width: 16px; height: 16px; }
.result-title { font-family: var(--disp); font-size: 15px; font-weight: 600; color: var(--w1); }
.result-sub { font-size: 12px; color: var(--w3); margin-top: 2px; }
.stats-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 8px; }
.stat-box { background: var(--w5); border: 1px solid var(--border); border-radius: 8px; padding: 12px; }
.stat-value { font-family: var(--mono); font-size: 18px; font-weight: 500; color: var(--cyan); line-height: 1; }
.stat-value.positive { color: var(--green); }
.stat-value.negative { color: var(--red); }
.stat-label { font-size: 10px; color: var(--w3); margin-top: 4px; text-transform: uppercase; letter-spacing: .08em; }
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; }
</style>
</head>
<body>
<header>
<a class="logo" href="/">
<div class="logo-icon">
<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2 4h12M2 8h8M2 12h5" stroke="#00D4FF" stroke-width="1.5" stroke-linecap="round"/>
</svg>
</div>
Donor Report <span>(GL Only)</span>
</a>
</header>
<main>
<div class="page-title">
<div class="eyebrow">Planeterra International Foundation</div>
<h1>Donor Revenue Report — GL Only</h1>
<p>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).</p>
</div>
<div class="scope-note">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 9v4m0 4h.01M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/></svg>
<div><strong>Canada entity only.</strong> 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 <a href="/donor-report/" style="color:var(--cyan)">Donor Revenue Report</a> tool instead for the complete picture.</div>
</div>
<div class="card">
<div class="card-label">GL Dump File</div>
<div class="file-zone" id="fileZone">
<input type="file" id="fileInput" accept=".xlsx,.xls">
<div class="file-zone-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14,2 14,8 20,8"/>
</svg>
</div>
<div class="file-zone-label" id="dropLabel"><strong>Drop a GL Dump export here</strong> or browse</div>
<div class="file-zone-sub">.xlsx / .xls — must have a "Journal" + "Ledger Account" header row</div>
</div>
<div class="file-chosen" id="fileChosen" style="display:none"></div>
<button class="btn btn-primary" id="processBtn" disabled>Generate Report</button>
<div class="spinner" id="spinner">
<div class="spinner-dot"></div>
Processing…
</div>
<div class="error-note" id="errorNote"></div>
</div>
<div class="card result-card" id="resultCard">
<div class="result-header">
<div class="result-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="#10D98A" stroke-width="2.5">
<polyline points="20,6 9,17 4,12"/>
</svg>
</div>
<div>
<div class="result-title">Report generated</div>
<div class="result-sub" id="resultSub"></div>
</div>
</div>
<div class="stats-grid">
<div class="stat-box">
<div class="stat-value" id="statDonors">—</div>
<div class="stat-label">Donor Sheets</div>
</div>
<div class="stat-box">
<div class="stat-value" id="statRevenue">—</div>
<div class="stat-label">Total Revenue (CAD)</div>
</div>
<div class="stat-box">
<div class="stat-value" id="statExpense">—</div>
<div class="stat-label">Total Expense (CAD)</div>
</div>
<div class="stat-box">
<div class="stat-value" id="statSurplus">—</div>
<div class="stat-label">Surplus / (Deficit)</div>
</div>
</div>
<button class="btn btn-primary" id="downloadBtn">Download Report</button>
</div>
</main>
<footer>
Built by <a href="https://undodesigns.com" target="_blank">Undo Designs</a> · Donor Revenue Report (GL Only) v1
</footer>
<script>
const $ = id => document.getElementById(id);
let chosenFile = null;
function setFile(file) {
if (!file) return;
if (!/\.(xlsx|xls)$/i.test(file.name)) {
$('errorNote').textContent = 'Please choose a .xlsx or .xls file.';
$('errorNote').classList.add('visible');
return;
}
chosenFile = file;
$('errorNote').classList.remove('visible');
$('fileChosen').textContent = file.name;
$('fileChosen').style.display = 'block';
$('processBtn').disabled = false;
$('resultCard').classList.remove('visible');
}
const zone = $('fileZone');
$('fileInput').addEventListener('change', () => setFile($('fileInput').files[0]));
zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
zone.addEventListener('drop', e => {
e.preventDefault(); zone.classList.remove('drag-over');
setFile(e.dataTransfer.files[0]);
});
let lastFilename = '';
function fmtMoney(n) {
const sign = n < 0 ? '-' : '';
return sign + '$' + Math.abs(n).toLocaleString('en-US', {minimumFractionDigits: 2});
}
$('processBtn').addEventListener('click', async () => {
if (!chosenFile) return;
$('processBtn').disabled = true;
$('spinner').classList.add('visible');
$('errorNote').classList.remove('visible');
$('resultCard').classList.remove('visible');
const fd = new FormData();
fd.append('gl_file', chosenFile);
try {
const r = await fetch('/donor-report-gl/api/process', { method: 'POST', body: fd });
const d = await r.json();
if (d.status === 'ok') {
lastFilename = d.filename;
$('resultSub').textContent = d.filename;
$('statDonors').textContent = d.donors;
$('statRevenue').textContent = fmtMoney(d.total_revenue);
$('statExpense').textContent = fmtMoney(d.total_expense);
const surplusEl = $('statSurplus');
surplusEl.textContent = fmtMoney(d.surplus_deficit);
surplusEl.className = 'stat-value ' + (d.surplus_deficit >= 0 ? 'positive' : 'negative');
$('resultCard').classList.add('visible');
} else {
$('errorNote').textContent = d.error || 'Unexpected error';
$('errorNote').classList.add('visible');
}
} catch (e) {
$('errorNote').textContent = 'Network error: ' + e.message;
$('errorNote').classList.add('visible');
}
$('spinner').classList.remove('visible');
$('processBtn').disabled = false;
});
$('downloadBtn').addEventListener('click', () => {
if (lastFilename) window.location.href = '/donor-report-gl/api/download/' + encodeURIComponent(lastFilename);
});
</script>
</body>
</html>

View File

@ -0,0 +1,528 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GL Analyzer — Undo Designs</title>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
--navy: #0C1A3A;
--navy-2: #12244C;
--navy-3: #1a2f5e;
--navy-4: #0a1428;
--cyan: #00D4FF;
--cyan-dim: rgba(0,212,255,.12);
--cyan-glow: rgba(0,212,255,.06);
--blue: #1B8EF8;
--green: #10D98A;
--green-dim: rgba(16,217,138,.12);
--red: #F04438;
--red-dim: rgba(240,68,56,.12);
--amber: #F79009;
--amber-dim: rgba(247,144,9,.12);
--w1: rgba(255,255,255,.95);
--w2: rgba(255,255,255,.65);
--w3: rgba(255,255,255,.35);
--w4: rgba(255,255,255,.10);
--w5: rgba(255,255,255,.05);
--border: rgba(255,255,255,.07);
--border-c: rgba(0,212,255,.18);
--mono: 'JetBrains Mono', monospace;
--disp: 'Space Grotesk', sans-serif;
--body: 'Inter', sans-serif;
--radius: 10px;
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: var(--body);
background: var(--navy-4);
color: var(--w1);
min-height: 100vh;
-webkit-font-smoothing: antialiased;
display: flex;
flex-direction: column;
}
body::before {
content: '';
position: fixed; inset: 0; pointer-events: none; z-index: 0;
background-image: radial-gradient(circle, rgba(0,212,255,.07) 1px, transparent 1px);
background-size: 28px 28px;
}
header {
position: sticky; top: 0; z-index: 100;
background: rgba(12,26,58,.85);
backdrop-filter: blur(12px);
border-bottom: 1px solid var(--border);
padding: 0 32px;
height: 60px;
display: flex; align-items: center; justify-content: space-between;
}
.logo {
display: flex; align-items: center; gap: 10px;
font-family: var(--disp); font-size: 15px; font-weight: 600;
color: var(--w1); text-decoration: none;
}
.logo-icon {
width: 30px; height: 30px;
background: linear-gradient(135deg, var(--navy-3), var(--navy-2));
border: 1px solid var(--border-c);
border-radius: 7px;
display: flex; align-items: center; justify-content: center;
}
.logo-icon svg { width: 16px; height: 16px; }
.logo span { color: var(--cyan); }
main {
position: relative; z-index: 1;
flex: 1;
max-width: 820px;
width: 100%;
margin: 0 auto;
padding: 48px 24px 80px;
}
.page-title { margin-bottom: 24px; }
.eyebrow {
font-family: var(--mono); font-size: 10px;
letter-spacing: .16em; text-transform: uppercase;
color: var(--cyan); margin-bottom: 10px;
}
.page-title h1 {
font-family: var(--disp); font-size: 26px; font-weight: 700;
color: var(--w1); line-height: 1.2; margin-bottom: 8px;
}
.page-title p { font-size: 14px; color: var(--w2); line-height: 1.6; }
.card {
background: var(--navy-2);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 24px;
margin-bottom: 16px;
transition: opacity .2s;
}
.card.disabled { opacity: .4; pointer-events: none; }
.card-label {
display: flex; align-items: center; gap: 8px;
font-family: var(--mono); font-size: 9.5px; letter-spacing: .14em;
text-transform: uppercase; color: var(--w3); margin-bottom: 14px;
}
.card-label .step-num {
width: 18px; height: 18px; border-radius: 50%;
background: var(--cyan-dim); color: var(--cyan);
display: flex; align-items: center; justify-content: center;
font-size: 10px; font-weight: 600;
}
.file-zone {
border: 1.5px dashed var(--border);
border-radius: 8px;
padding: 22px 16px;
text-align: center;
cursor: pointer;
transition: all .2s;
position: relative;
}
.file-zone:hover, .file-zone.drag-over { border-color: var(--cyan); background: var(--cyan-glow); }
.file-zone input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%; }
.file-zone-label { font-size: 13px; color: var(--w2); }
.file-zone-label strong { color: var(--cyan); }
.file-zone-sub { font-size: 11px; color: var(--w3); margin-top: 4px; }
.file-chosen { font-family: var(--mono); font-size: 11.5px; color: var(--green); margin-top: 8px; }
.field-note { font-size: 11.5px; color: var(--w3); margin-top: 6px; line-height: 1.5; }
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
padding: 11px 22px; border-radius: 8px; border: none;
font-family: var(--disp); font-size: 13px; font-weight: 600;
cursor: pointer; transition: all .2s; text-decoration: none;
width: 100%; margin-top: 18px;
}
.btn-primary { background: linear-gradient(135deg, var(--cyan), var(--blue)); color: var(--navy); }
.btn-primary:hover { filter: brightness(1.08); }
.btn-primary:disabled { opacity: .4; cursor: not-allowed; filter: none; }
.spinner {
display: none;
align-items: center; gap: 8px;
font-family: var(--mono); font-size: 11px; color: var(--w3);
margin-top: 12px;
}
.spinner.visible { display: flex; }
.spinner-dot {
width: 6px; height: 6px; border-radius: 50%; background: var(--cyan);
animation: pulse 1s infinite ease-in-out;
}
@keyframes pulse { 0%,100% { opacity: .3; } 50% { opacity: 1; } }
.error-note {
display: none;
font-size: 12px; color: var(--red); background: var(--red-dim);
border: 1px solid rgba(240,68,56,.2); border-radius: 8px;
padding: 12px 14px; margin-top: 12px;
}
.error-note.visible { display: block; }
.checklist { max-height: 320px; overflow-y: auto; border: 1px solid var(--w5); border-radius: 8px; }
.check-row {
display: flex; align-items: center; gap: 10px;
padding: 9px 12px; border-bottom: 1px solid var(--w5); cursor: pointer;
}
.check-row:last-child { border-bottom: none; }
.check-row:hover { background: var(--cyan-glow); }
.check-row input { accent-color: var(--cyan); width: 15px; height: 15px; flex-shrink: 0; }
.check-row .name { font-size: 12.5px; color: var(--w1); flex: 1; }
.check-row .meta { font-family: var(--mono); font-size: 10.5px; color: var(--w3); }
.check-row .fill { font-family: var(--mono); font-size: 10.5px; padding: 2px 7px; border-radius: 20px; }
.fill-high { background: var(--green-dim); color: var(--green); }
.fill-mid { background: var(--amber-dim); color: var(--amber); }
.fill-low { background: var(--red-dim); color: var(--red); }
.filter-input {
width: 100%; padding: 9px 12px; margin-bottom: 8px;
background: var(--navy-4); border: 1px solid var(--w5); border-radius: 8px;
color: var(--w1); font-size: 12.5px; font-family: var(--body);
}
.filter-input:focus { outline: none; border-color: var(--cyan); }
.filter-input::placeholder { color: var(--w3); }
.field-group-label {
font-size: 11.5px; color: var(--w2); margin: 16px 0 8px; font-weight: 500;
}
.field-group-label:first-child { margin-top: 0; }
.result-section { margin-bottom: 24px; }
.result-header {
display: flex; align-items: center; justify-content: space-between;
margin-bottom: 10px;
}
.result-title { font-family: var(--disp); font-size: 14px; font-weight: 600; color: var(--w1); }
.result-total { font-family: var(--mono); font-size: 13px; color: var(--cyan); }
.result-table-wrap { overflow-x: auto; border: 1px solid var(--w5); border-radius: 8px; }
table.result-table { width: 100%; border-collapse: collapse; font-size: 11.5px; }
table.result-table th {
text-align: left; padding: 8px 10px; background: var(--navy-3);
font-family: var(--mono); font-size: 9px; letter-spacing: .05em; text-transform: uppercase;
color: var(--w3); white-space: nowrap; border-bottom: 1px solid var(--w5);
}
table.result-table td {
padding: 7px 10px; border-bottom: 1px solid var(--w5); color: var(--w2);
white-space: nowrap; max-width: 260px; overflow: hidden; text-overflow: ellipsis;
}
table.result-table td.num { text-align: right; font-family: var(--mono); color: var(--w1); }
table.result-table tr.total-row td { font-weight: 600; color: var(--w1); border-bottom: none; }
table.result-table tr:last-child td { border-bottom: none; }
.download-link {
display: inline-flex; align-items: center; gap: 6px;
font-family: var(--mono); font-size: 12px; color: var(--cyan);
text-decoration: none; margin-top: 16px;
}
.download-link:hover { text-decoration: underline; }
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; }
</style>
</head>
<body>
<header>
<a class="logo" href="/">
<div class="logo-icon">
<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2 4h12M2 8h8M2 12h5" stroke="#00D4FF" stroke-width="1.5" stroke-linecap="round"/>
</svg>
</div>
GL <span>Analyzer</span>
</a>
</header>
<main>
<div class="page-title">
<div class="eyebrow">Planeterra International Foundation</div>
<h1>GL Analyzer</h1>
<p>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.</p>
</div>
<div class="card" id="step1Card">
<div class="card-label"><span class="step-num">1</span> Upload GL Extract</div>
<div class="file-zone" id="fileZone">
<input type="file" id="fileInput" accept=".xlsx,.xls">
<div class="file-zone-label"><strong>Drop your GL extract here</strong> or browse</div>
<div class="file-zone-sub">A GL Dump export (any header row position, scanned automatically)</div>
</div>
<div class="file-chosen" id="fileChosen" style="display:none"></div>
<button class="btn btn-primary" id="uploadBtn" disabled>Upload</button>
<div class="spinner" id="uploadSpinner"><div class="spinner-dot"></div>Uploading…</div>
<div class="error-note" id="uploadError"></div>
</div>
<div class="card disabled" id="step2Card">
<div class="card-label"><span class="step-num">2</span> Select Account(s)</div>
<input type="text" class="filter-input" id="acctFilter" placeholder="Filter by code or name…">
<div class="checklist" id="acctList"></div>
<button class="btn btn-primary" id="headersBtn" disabled>Show Available Fields</button>
<div class="spinner" id="headersSpinner"><div class="spinner-dot"></div>Checking fields…</div>
<div class="error-note" id="headersError"></div>
</div>
<div class="card disabled" id="step3Card">
<div class="card-label"><span class="step-num">3</span> Choose Fields</div>
<p class="field-note" style="margin-bottom:4px">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)".</p>
<div class="field-group-label">Main field (what to group the balance by)</div>
<input type="text" class="filter-input" id="mainFilter" placeholder="Filter fields…">
<div class="checklist" id="mainHeaderList"></div>
<div class="field-group-label">Extra fields to show alongside each row (optional)</div>
<input type="text" class="filter-input" id="extraFilter" placeholder="Filter fields…">
<div class="checklist" id="extraHeaderList"></div>
<button class="btn btn-primary" id="generateBtn" disabled>Generate</button>
<div class="spinner" id="generateSpinner"><div class="spinner-dot"></div>Generating…</div>
<div class="error-note" id="generateError"></div>
</div>
<div class="card" id="resultCard" style="display:none">
<div class="card-label">Results</div>
<div id="resultSections"></div>
<a class="download-link" id="downloadLink" href="#">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M12 3v14m0 0l-5-5m5 5l5-5M4 21h16"/></svg>
Download Excel workbook
</a>
</div>
</main>
<footer>
Built by <a href="https://undodesigns.com" target="_blank">Undo Designs</a> · GL Analyzer v1
</footer>
<script>
const $ = id => document.getElementById(id);
function escapeHtml(s) {
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
function fmtMoney(n) {
if (n === null || n === undefined) return '';
const sign = n < 0 ? '-' : '';
return sign + '$' + Math.abs(n).toLocaleString('en-US', {minimumFractionDigits: 2});
}
function fillClass(pct) {
if (pct >= 60) return 'fill-high';
if (pct >= 15) return 'fill-mid';
return 'fill-low';
}
let chosenFile = null;
let uploadId = null;
let allAccounts = [];
let allHeaders = [];
let selectedAccountLabels = [];
// ── Step 1: upload ──────────────────────────────────────────────────────
const fileZone = $('fileZone'), fileInput = $('fileInput');
function handleFile(file) {
if (!file || !/\.(xlsx|xls)$/i.test(file.name)) return;
chosenFile = file;
$('fileChosen').textContent = file.name;
$('fileChosen').style.display = 'block';
$('uploadBtn').disabled = false;
}
fileInput.addEventListener('change', () => handleFile(fileInput.files[0]));
fileZone.addEventListener('dragover', e => { e.preventDefault(); fileZone.classList.add('drag-over'); });
fileZone.addEventListener('dragleave', () => fileZone.classList.remove('drag-over'));
fileZone.addEventListener('drop', e => {
e.preventDefault(); fileZone.classList.remove('drag-over');
handleFile(e.dataTransfer.files[0]);
});
$('uploadBtn').addEventListener('click', async () => {
if (!chosenFile) return;
$('uploadBtn').disabled = true;
$('uploadSpinner').classList.add('visible');
$('uploadError').classList.remove('visible');
const fd = new FormData();
fd.append('gl_file', chosenFile);
try {
const r = await fetch('/gl-analyzer/api/upload', { method: 'POST', body: fd });
const d = await r.json();
if (d.status === 'ok') {
uploadId = d.upload_id;
allAccounts = d.accounts;
renderAccountList();
$('step2Card').classList.remove('disabled');
$('step3Card').classList.add('disabled');
$('resultCard').style.display = 'none';
} else {
$('uploadError').textContent = d.error || 'Unexpected error';
$('uploadError').classList.add('visible');
}
} catch (e) {
$('uploadError').textContent = 'Network error: ' + e.message;
$('uploadError').classList.add('visible');
}
$('uploadSpinner').classList.remove('visible');
$('uploadBtn').disabled = false;
});
// ── Step 2: account selection ───────────────────────────────────────────
function renderAccountList(filterText) {
const f = (filterText || '').toLowerCase();
const rows = allAccounts.filter(a => !f || a.label.toLowerCase().includes(f) || a.code.includes(f));
$('acctList').innerHTML = rows.map(a => `
<label class="check-row">
<input type="checkbox" class="acct-check" value="${escapeHtml(a.label)}">
<span class="name">${escapeHtml(a.label)}</span>
<span class="meta">${a.line_count.toLocaleString()} lines</span>
</label>`).join('') || '<div style="padding:14px;color:var(--w3);font-size:12px">No matching accounts</div>';
$('acctList').querySelectorAll('.acct-check').forEach(cb => {
cb.addEventListener('change', updateHeadersBtnState);
});
}
$('acctFilter').addEventListener('input', e => renderAccountList(e.target.value));
function updateHeadersBtnState() {
const checked = $('acctList').querySelectorAll('.acct-check:checked');
$('headersBtn').disabled = checked.length === 0;
}
$('headersBtn').addEventListener('click', async () => {
const checked = [...$('acctList').querySelectorAll('.acct-check:checked')];
selectedAccountLabels = checked.map(cb => cb.value);
const codes = [...new Set(selectedAccountLabels.map(l => l.split(':')[0]))];
$('headersBtn').disabled = true;
$('headersSpinner').classList.add('visible');
$('headersError').classList.remove('visible');
try {
const r = await fetch('/gl-analyzer/api/headers', {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({upload_id: uploadId, account_codes: codes}),
});
const d = await r.json();
if (d.status === 'ok') {
allHeaders = d.columns;
renderHeaderLists();
$('step3Card').classList.remove('disabled');
$('resultCard').style.display = 'none';
} else {
$('headersError').textContent = d.error || 'Unexpected error';
$('headersError').classList.add('visible');
}
} catch (e) {
$('headersError').textContent = 'Network error: ' + e.message;
$('headersError').classList.add('visible');
}
$('headersSpinner').classList.remove('visible');
$('headersBtn').disabled = false;
});
// ── Step 3: field selection ─────────────────────────────────────────────
function renderHeaderLists(mainFilterText, extraFilterText) {
const mf = (mainFilterText || '').toLowerCase();
const ef = (extraFilterText || '').toLowerCase();
const currentMain = $('mainHeaderList').querySelector('input:checked')?.value;
const currentExtras = new Set([...$('extraHeaderList').querySelectorAll('input:checked')].map(i => i.value));
const mainRows = allHeaders.filter(h => !mf || h.name.toLowerCase().includes(mf));
$('mainHeaderList').innerHTML = mainRows.map(h => `
<label class="check-row">
<input type="radio" name="mainHeader" value="${escapeHtml(h.name)}" ${h.name === currentMain ? 'checked' : ''}>
<span class="name">${escapeHtml(h.name)}</span>
<span class="fill ${fillClass(h.fill_pct)}">${h.fill_pct}%</span>
</label>`).join('');
const extraRows = allHeaders.filter(h => !ef || h.name.toLowerCase().includes(ef));
$('extraHeaderList').innerHTML = extraRows.map(h => `
<label class="check-row">
<input type="checkbox" class="extra-check" value="${escapeHtml(h.name)}" ${currentExtras.has(h.name) ? 'checked' : ''}>
<span class="name">${escapeHtml(h.name)}</span>
<span class="fill ${fillClass(h.fill_pct)}">${h.fill_pct}%</span>
</label>`).join('');
$('mainHeaderList').querySelectorAll('input').forEach(i => i.addEventListener('change', updateGenerateBtnState));
updateGenerateBtnState();
}
$('mainFilter').addEventListener('input', e => renderHeaderLists(e.target.value, $('extraFilter').value));
$('extraFilter').addEventListener('input', e => renderHeaderLists($('mainFilter').value, e.target.value));
function updateGenerateBtnState() {
$('generateBtn').disabled = !$('mainHeaderList').querySelector('input:checked');
}
$('generateBtn').addEventListener('click', async () => {
const mainHeader = $('mainHeaderList').querySelector('input:checked')?.value;
if (!mainHeader) return;
const extraHeaders = [...$('extraHeaderList').querySelectorAll('input:checked')].map(i => i.value).filter(h => h !== mainHeader);
$('generateBtn').disabled = true;
$('generateSpinner').classList.add('visible');
$('generateError').classList.remove('visible');
try {
const r = await fetch('/gl-analyzer/api/generate', {
method: 'POST', headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
upload_id: uploadId, accounts: selectedAccountLabels,
main_header: mainHeader, extra_headers: extraHeaders,
}),
});
const d = await r.json();
if (d.status === 'ok') {
renderResults(d);
$('resultCard').style.display = 'block';
$('resultCard').scrollIntoView({behavior: 'smooth', block: 'start'});
} else {
$('generateError').textContent = d.error || 'Unexpected error';
$('generateError').classList.add('visible');
}
} catch (e) {
$('generateError').textContent = 'Network error: ' + e.message;
$('generateError').classList.add('visible');
}
$('generateSpinner').classList.remove('visible');
$('generateBtn').disabled = false;
});
// ── Results ──────────────────────────────────────────────────────────────
function renderResults(d) {
$('resultSections').innerHTML = d.accounts.map(a => {
const extraCols = d.extra_headers;
const head = `<tr>
<th>Description</th>
${extraCols.map(c => `<th>${escapeHtml(c)}</th>`).join('')}
<th>Orig Curr</th><th>Curr</th><th>Rate</th><th>Amt (CAD)</th>
</tr>`;
const body = a.rows.map(r => `<tr>
<td>${escapeHtml(r.category)}</td>
${extraCols.map(c => `<td title="${escapeHtml(r[c] ?? '')}">${escapeHtml(r[c] ?? '')}</td>`).join('')}
<td class="num">${r.orig_total !== null ? fmtMoney(r.orig_total) : ''}</td>
<td>${r.orig_currency ?? ''}</td>
<td class="num">${r.rate !== null ? r.rate.toFixed(4) : ''}</td>
<td class="num">${fmtMoney(r.amt_cad)}</td>
</tr>`).join('');
const totalRow = `<tr class="total-row">
<td>Total</td>${extraCols.map(() => '<td></td>').join('')}<td></td><td></td><td></td>
<td class="num">${fmtMoney(a.total)}</td>
</tr>`;
return `<div class="result-section">
<div class="result-header">
<div class="result-title">${escapeHtml(a.account)}</div>
<div class="result-total">${fmtMoney(a.total)} · ${a.row_count} row${a.row_count === 1 ? '' : 's'}</div>
</div>
<div class="result-table-wrap">
<table class="result-table">${head}${body || '<tr><td colspan="99" style="color:var(--w3)">No matching GL activity</td></tr>'}${totalRow}</table>
</div>
</div>`;
}).join('');
$('downloadLink').href = `/gl-analyzer/api/download/${encodeURIComponent(d.download_filename)}`;
}
</script>
</body>
</html>

View File

@ -0,0 +1,356 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PDF Unlock — Undo Designs</title>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
--navy: #0C1A3A;
--navy-2: #12244C;
--navy-3: #1a2f5e;
--navy-4: #0a1428;
--cyan: #00D4FF;
--cyan-dim: rgba(0,212,255,.12);
--cyan-glow: rgba(0,212,255,.06);
--blue: #1B8EF8;
--green: #10D98A;
--green-dim: rgba(16,217,138,.12);
--red: #F04438;
--red-dim: rgba(240,68,56,.12);
--amber: #F79009;
--w1: rgba(255,255,255,.95);
--w2: rgba(255,255,255,.65);
--w3: rgba(255,255,255,.35);
--w4: rgba(255,255,255,.10);
--w5: rgba(255,255,255,.05);
--border: rgba(255,255,255,.07);
--border-c: rgba(0,212,255,.18);
--mono: 'JetBrains Mono', monospace;
--disp: 'Space Grotesk', sans-serif;
--body: 'Inter', sans-serif;
--radius: 10px;
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: var(--body);
background: var(--navy-4);
color: var(--w1);
min-height: 100vh;
-webkit-font-smoothing: antialiased;
display: flex;
flex-direction: column;
}
body::before {
content: '';
position: fixed; inset: 0; pointer-events: none; z-index: 0;
background-image: radial-gradient(circle, rgba(0,212,255,.07) 1px, transparent 1px);
background-size: 28px 28px;
}
header {
position: sticky; top: 0; z-index: 100;
background: rgba(12,26,58,.85);
backdrop-filter: blur(12px);
border-bottom: 1px solid var(--border);
padding: 0 32px;
height: 60px;
display: flex; align-items: center; justify-content: space-between;
}
.logo {
display: flex; align-items: center; gap: 10px;
font-family: var(--disp); font-size: 15px; font-weight: 600;
color: var(--w1); text-decoration: none;
}
.logo-icon {
width: 30px; height: 30px;
background: linear-gradient(135deg, var(--navy-3), var(--navy-2));
border: 1px solid var(--border-c);
border-radius: 7px;
display: flex; align-items: center; justify-content: center;
}
.logo-icon svg { width: 16px; height: 16px; }
.logo span { color: var(--cyan); }
.privacy-badge {
display: flex; align-items: center; gap: 6px;
font-family: var(--mono); font-size: 10.5px; color: var(--green);
background: var(--green-dim); border: 1px solid rgba(16,217,138,.25);
padding: 5px 12px; border-radius: 20px;
}
.privacy-badge svg { width: 12px; height: 12px; }
main {
position: relative; z-index: 1;
flex: 1;
max-width: 640px;
width: 100%;
margin: 0 auto;
padding: 48px 24px 80px;
}
.page-title { margin-bottom: 40px; }
.eyebrow {
font-family: var(--mono); font-size: 10px;
letter-spacing: .16em; text-transform: uppercase;
color: var(--cyan); margin-bottom: 10px;
}
.page-title h1 {
font-family: var(--disp); font-size: 28px; font-weight: 700;
color: var(--w1); line-height: 1.2; margin-bottom: 8px;
}
.page-title p { font-size: 14px; color: var(--w2); line-height: 1.6; }
.card {
background: var(--navy-2);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 24px;
margin-bottom: 16px;
}
.card-label {
font-family: var(--mono); font-size: 9.5px; letter-spacing: .14em;
text-transform: uppercase; color: var(--w3); margin-bottom: 14px;
}
.file-zone {
border: 1.5px dashed var(--border);
border-radius: 8px;
padding: 28px 20px;
text-align: center;
cursor: pointer;
transition: all .2s;
position: relative;
}
.file-zone:hover, .file-zone.drag-over { border-color: var(--cyan); background: var(--cyan-glow); }
.file-zone input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%; }
.file-zone-icon {
width: 36px; height: 36px; margin: 0 auto 10px;
background: var(--w5); border-radius: 8px;
display: flex; align-items: center; justify-content: center;
}
.file-zone-icon svg { width: 18px; height: 18px; color: var(--w3); }
.file-zone-label { font-size: 13px; color: var(--w2); }
.file-zone-label strong { color: var(--cyan); }
.file-zone-sub { font-size: 11px; color: var(--w3); margin-top: 4px; }
.file-chosen { font-family: var(--mono); font-size: 11.5px; color: var(--green); margin-top: 10px; }
.field { margin-top: 16px; }
.field label { display: block; font-size: 11px; color: var(--w3); margin-bottom: 6px; }
.field-hint { font-size: 11px; color: var(--w3); margin-top: 6px; line-height: 1.5; }
.field input[type="password"], .field input[type="text"] {
width: 100%; background: var(--navy-4); border: 1px solid var(--border); border-radius: 6px;
padding: 9px 12px; font-family: var(--body); font-size: 13px; color: var(--w1);
outline: none; transition: border-color .2s;
}
.field input:focus { border-color: var(--cyan); }
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
padding: 11px 22px; border-radius: 8px; border: none;
font-family: var(--disp); font-size: 13px; font-weight: 600;
cursor: pointer; transition: all .2s; text-decoration: none;
width: 100%; margin-top: 16px;
}
.btn-primary { background: linear-gradient(135deg, var(--cyan), var(--blue)); color: var(--navy); }
.btn-primary:hover { filter: brightness(1.08); }
.btn-primary:disabled { opacity: .4; cursor: not-allowed; filter: none; }
.spinner {
display: none;
align-items: center; gap: 8px;
font-family: var(--mono); font-size: 11px; color: var(--w3);
margin-top: 12px;
}
.spinner.visible { display: flex; }
.spinner-dot {
width: 6px; height: 6px; border-radius: 50%; background: var(--cyan);
animation: pulse 1s infinite ease-in-out;
}
@keyframes pulse { 0%,100% { opacity: .3; } 50% { opacity: 1; } }
.error-note {
display: none;
font-size: 12px; color: var(--red); background: var(--red-dim);
border: 1px solid rgba(240,68,56,.2); border-radius: 8px;
padding: 12px 14px; margin-top: 12px;
}
.error-note.visible { display: block; }
.result-card { display: none; }
.result-card.visible { display: block; }
.result-header { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; }
.result-icon {
width: 32px; height: 32px; border-radius: 8px;
background: var(--green-dim); display: flex; align-items: center; justify-content: center;
}
.result-icon svg { width: 16px; height: 16px; }
.result-title { font-family: var(--disp); font-size: 15px; font-weight: 600; color: var(--w1); }
.result-sub { font-size: 12px; color: var(--w3); margin-top: 2px; }
.notice-note {
font-size: 12px; color: var(--w2); background: var(--w5);
border: 1px solid var(--border); border-radius: 8px;
padding: 12px 14px; margin-top: 14px; line-height: 1.5;
}
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; }
</style>
</head>
<body>
<header>
<a class="logo" href="/">
<div class="logo-icon">
<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2 4h12M2 8h8M2 12h5" stroke="#00D4FF" stroke-width="1.5" stroke-linecap="round"/>
</svg>
</div>
PDF <span>Unlock</span>
</a>
<div class="privacy-badge">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
</svg>
Deleted from the server right after processing
</div>
</header>
<main>
<div class="page-title">
<div class="eyebrow">PDF Utilities</div>
<h1>PDF Unlock</h1>
<p>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.</p>
</div>
<div class="card">
<div class="card-label">PDF File</div>
<div class="file-zone" id="fileZone">
<input type="file" id="fileInput" accept=".pdf,application/pdf">
<div class="file-zone-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14,2 14,8 20,8"/>
</svg>
</div>
<div class="file-zone-label" id="dropLabel"><strong>Drop a PDF here</strong> or browse</div>
<div class="file-zone-sub">.pdf files only</div>
</div>
<div class="file-chosen" id="fileChosen" style="display:none"></div>
<div class="field">
<label for="pwInput">Open password (only if this PDF requires one to view)</label>
<input type="password" id="pwInput" placeholder="Leave blank if the PDF isn't password-protected to open">
<div class="field-hint">Owner-set restrictions (printing, copying, editing) are removed automatically, no password needed. An open password can only be removed if you know it.</div>
</div>
<button class="btn btn-primary" id="unlockBtn" disabled>Unlock PDF</button>
<div class="spinner" id="spinner">
<div class="spinner-dot"></div>
Processing…
</div>
<div class="error-note" id="errorNote"></div>
</div>
<div class="card result-card" id="resultCard">
<div class="result-header">
<div class="result-icon">
<svg viewBox="0 0 24 24" fill="none" stroke="#10D98A" stroke-width="2.5">
<polyline points="20,6 9,17 4,12"/>
</svg>
</div>
<div>
<div class="result-title" id="resultTitle">PDF unlocked</div>
<div class="result-sub" id="resultSub"></div>
</div>
</div>
<button class="btn btn-primary" id="downloadBtn">Download Unlocked PDF</button>
</div>
</main>
<footer>
Built by <a href="https://undodesigns.com" target="_blank">Undo Designs</a> · PDF Unlock v1
</footer>
<script>
const $ = id => document.getElementById(id);
let chosenFile = null;
function setFile(file) {
if (!file) return;
if (!/\.pdf$/i.test(file.name)) {
$('errorNote').textContent = 'Please choose a .pdf file.';
$('errorNote').classList.add('visible');
return;
}
chosenFile = file;
$('errorNote').classList.remove('visible');
$('fileChosen').textContent = file.name;
$('fileChosen').style.display = 'block';
$('unlockBtn').disabled = false;
$('resultCard').classList.remove('visible');
}
const zone = $('fileZone');
$('fileInput').addEventListener('change', () => setFile($('fileInput').files[0]));
zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
zone.addEventListener('drop', e => {
e.preventDefault(); zone.classList.remove('drag-over');
setFile(e.dataTransfer.files[0]);
});
let lastFilename = '';
let lastDownloadName = '';
$('unlockBtn').addEventListener('click', async () => {
if (!chosenFile) return;
$('unlockBtn').disabled = true;
$('spinner').classList.add('visible');
$('errorNote').classList.remove('visible');
$('resultCard').classList.remove('visible');
const fd = new FormData();
fd.append('pdf_file', chosenFile);
const pw = $('pwInput').value;
if (pw) fd.append('password', pw);
try {
const r = await fetch('/pdf-unlock/api/unlock', { method: 'POST', body: fd });
const d = await r.json();
if (d.status === 'ok') {
lastFilename = d.filename;
lastDownloadName = d.download_name;
$('resultSub').textContent = d.was_protected
? 'Password protection removed successfully.'
: 'This PDF wasn\'t protected — here\'s a clean copy.';
$('resultCard').classList.add('visible');
} else {
$('errorNote').textContent = d.error || 'Unexpected error';
$('errorNote').classList.add('visible');
}
} catch (e) {
$('errorNote').textContent = 'Network error: ' + e.message;
$('errorNote').classList.add('visible');
}
$('spinner').classList.remove('visible');
$('unlockBtn').disabled = false;
});
$('downloadBtn').addEventListener('click', () => {
if (!lastFilename) return;
window.location.href = '/pdf-unlock/api/download/' + encodeURIComponent(lastFilename)
+ '?as=' + encodeURIComponent(lastDownloadName);
});
</script>
</body>
</html>

View File

@ -0,0 +1,545 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Summary Reconciliation Check — Undo Designs</title>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
--navy: #0C1A3A;
--navy-2: #12244C;
--navy-3: #1a2f5e;
--navy-4: #0a1428;
--cyan: #00D4FF;
--cyan-dim: rgba(0,212,255,.12);
--cyan-glow: rgba(0,212,255,.06);
--blue: #1B8EF8;
--green: #10D98A;
--green-dim: rgba(16,217,138,.12);
--red: #F04438;
--red-dim: rgba(240,68,56,.12);
--amber: #F79009;
--amber-dim: rgba(247,144,9,.12);
--w1: rgba(255,255,255,.95);
--w2: rgba(255,255,255,.65);
--w3: rgba(255,255,255,.35);
--w4: rgba(255,255,255,.10);
--w5: rgba(255,255,255,.05);
--border: rgba(255,255,255,.07);
--border-c: rgba(0,212,255,.18);
--mono: 'JetBrains Mono', monospace;
--disp: 'Space Grotesk', sans-serif;
--body: 'Inter', sans-serif;
--radius: 10px;
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: var(--body);
background: var(--navy-4);
color: var(--w1);
min-height: 100vh;
-webkit-font-smoothing: antialiased;
display: flex;
flex-direction: column;
}
body::before {
content: '';
position: fixed; inset: 0; pointer-events: none; z-index: 0;
background-image: radial-gradient(circle, rgba(0,212,255,.07) 1px, transparent 1px);
background-size: 28px 28px;
}
header {
position: sticky; top: 0; z-index: 100;
background: rgba(12,26,58,.85);
backdrop-filter: blur(12px);
border-bottom: 1px solid var(--border);
padding: 0 32px;
height: 60px;
display: flex; align-items: center; justify-content: space-between;
}
.logo {
display: flex; align-items: center; gap: 10px;
font-family: var(--disp); font-size: 15px; font-weight: 600;
color: var(--w1); text-decoration: none;
}
.logo-icon {
width: 30px; height: 30px;
background: linear-gradient(135deg, var(--navy-3), var(--navy-2));
border: 1px solid var(--border-c);
border-radius: 7px;
display: flex; align-items: center; justify-content: center;
}
.logo-icon svg { width: 16px; height: 16px; }
.logo span { color: var(--cyan); }
main {
position: relative; z-index: 1;
flex: 1;
max-width: 760px;
width: 100%;
margin: 0 auto;
padding: 48px 24px 80px;
}
.page-title { margin-bottom: 24px; }
.eyebrow {
font-family: var(--mono); font-size: 10px;
letter-spacing: .16em; text-transform: uppercase;
color: var(--cyan); margin-bottom: 10px;
}
.page-title h1 {
font-family: var(--disp); font-size: 26px; font-weight: 700;
color: var(--w1); line-height: 1.2; margin-bottom: 8px;
}
.page-title p { font-size: 14px; color: var(--w2); line-height: 1.6; }
.card {
background: var(--navy-2);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 24px;
margin-bottom: 16px;
}
.card-label {
font-family: var(--mono); font-size: 9.5px; letter-spacing: .14em;
text-transform: uppercase; color: var(--w3); margin-bottom: 14px;
}
.file-zone {
border: 1.5px dashed var(--border);
border-radius: 8px;
padding: 22px 16px;
text-align: center;
cursor: pointer;
transition: all .2s;
position: relative;
}
.file-zone:hover, .file-zone.drag-over { border-color: var(--cyan); background: var(--cyan-glow); }
.file-zone input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%; }
.file-zone-label { font-size: 13px; color: var(--w2); }
.file-zone-label strong { color: var(--cyan); }
.file-zone-sub { font-size: 11px; color: var(--w3); margin-top: 4px; }
.file-chosen { font-family: var(--mono); font-size: 11.5px; color: var(--green); margin-top: 8px; }
.field-note { font-size: 11.5px; color: var(--w3); margin-top: 6px; line-height: 1.5; }
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
padding: 11px 22px; border-radius: 8px; border: none;
font-family: var(--disp); font-size: 13px; font-weight: 600;
cursor: pointer; transition: all .2s; text-decoration: none;
width: 100%; margin-top: 18px;
}
.btn-primary { background: linear-gradient(135deg, var(--cyan), var(--blue)); color: var(--navy); }
.btn-primary:hover { filter: brightness(1.08); }
.btn-primary:disabled { opacity: .4; cursor: not-allowed; filter: none; }
.spinner {
display: none;
align-items: center; gap: 8px;
font-family: var(--mono); font-size: 11px; color: var(--w3);
margin-top: 12px;
}
.spinner.visible { display: flex; }
.spinner-dot {
width: 6px; height: 6px; border-radius: 50%; background: var(--cyan);
animation: pulse 1s infinite ease-in-out;
}
@keyframes pulse { 0%,100% { opacity: .3; } 50% { opacity: 1; } }
.error-note {
display: none;
font-size: 12px; color: var(--red); background: var(--red-dim);
border: 1px solid rgba(240,68,56,.2); border-radius: 8px;
padding: 12px 14px; margin-top: 12px;
}
.error-note.visible { display: block; }
.result-card { display: none; }
.result-card.visible { display: block; }
.result-header { display: flex; align-items: center; gap: 10px; margin-bottom: 16px; }
.result-icon {
width: 32px; height: 32px; border-radius: 8px;
display: flex; align-items: center; justify-content: center;
}
.result-icon.ok { background: var(--green-dim); }
.result-icon.warn { background: var(--red-dim); }
.result-icon svg { width: 16px; height: 16px; }
.result-title { font-family: var(--disp); font-size: 15px; font-weight: 600; color: var(--w1); }
.result-sub { font-size: 12px; color: var(--w3); margin-top: 2px; }
.acct-row {
border: 1px solid var(--border); border-radius: 8px; padding: 12px 14px;
margin-bottom: 8px;
}
.acct-row.mismatch { border-color: rgba(240,68,56,.3); background: var(--red-dim); }
.acct-row-head { display: grid; grid-template-columns: 1fr 110px 110px 90px 70px; gap: 10px; align-items: center; }
.acct-row-head span:not(:first-child) { text-align: right; font-family: var(--mono); font-size: 11.5px; }
.acct-label { font-size: 12.5px; color: var(--w1); }
.recon-badge { padding: 3px 9px; border-radius: 20px; font-size: 10px; font-weight: 500; text-align: center; }
.recon-badge.ok { background: var(--green-dim); color: var(--green); }
.recon-badge.warn { background: var(--red-dim); color: var(--red); }
.acct-hint { margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--w5); }
.acct-hint-label {
font-family: var(--mono); font-size: 9.5px; letter-spacing: .08em; text-transform: uppercase;
color: var(--amber); margin-bottom: 6px;
}
.acct-hint-row {
display: flex; justify-content: space-between; font-size: 11.5px; color: var(--w2);
padding: 3px 0; font-family: var(--mono);
}
.acct-hint-empty { font-size: 11.5px; color: var(--w3); font-style: italic; }
.kb-toggle {
margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--w5);
display: flex; align-items: center; justify-content: space-between; cursor: pointer;
user-select: none;
}
.kb-toggle-label {
font-family: var(--mono); font-size: 9.5px; letter-spacing: .08em; text-transform: uppercase;
color: var(--cyan);
}
.kb-toggle-arrow { color: var(--w3); font-size: 10px; transition: transform .15s; }
.kb-toggle.open .kb-toggle-arrow { transform: rotate(90deg); }
.kb-body { display: none; margin-top: 10px; }
.kb-body.open { display: block; }
.kb-explain-line { font-size: 11px; color: var(--w2); margin-bottom: 10px; line-height: 1.5; }
.kb-explain-line.partial { color: var(--amber); }
.kb-problem {
border: 1px solid var(--w5); border-radius: 6px; padding: 8px 10px; margin-bottom: 6px;
font-size: 11px;
}
.kb-problem-head { display: flex; justify-content: space-between; gap: 10px; margin-bottom: 4px; }
.kb-problem-title { color: var(--w1); }
.kb-problem-kind {
font-family: var(--mono); font-size: 8.5px; letter-spacing: .06em; text-transform: uppercase;
padding: 1px 6px; border-radius: 10px; white-space: nowrap; height: fit-content;
}
.kb-problem-kind.keyed { background: var(--amber-dim); color: var(--amber); }
.kb-problem-kind.blanket { background: rgba(27,142,248,.15); color: var(--blue); }
.kb-problem-kind.uncovered { background: var(--red-dim); color: var(--red); }
.kb-problem-row { display: flex; justify-content: space-between; font-family: var(--mono); font-size: 10.5px; color: var(--w2); padding: 1px 0; }
.kb-problem-row .lbl { color: var(--w3); }
.kb-problem-note { font-size: 10.5px; color: var(--w3); margin-top: 4px; line-height: 1.5; }
.kb-problem-note strong { color: var(--w2); }
.col-head {
display: grid; grid-template-columns: 1fr 110px 110px 90px 70px; gap: 10px;
font-family: var(--mono); font-size: 9px; letter-spacing: .06em; text-transform: uppercase;
color: var(--w3); padding: 0 14px 8px;
}
.col-head span:not(:first-child) { text-align: right; }
footer { position: relative; z-index: 1; text-align: center; padding: 20px; font-size: 11px; color: var(--w3); border-top: 1px solid var(--border); }
footer a { color: var(--cyan); text-decoration: none; }
</style>
</head>
<body>
<header>
<a class="logo" href="/">
<div class="logo-icon">
<svg viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2 4h12M2 8h8M2 12h5" stroke="#00D4FF" stroke-width="1.5" stroke-linecap="round"/>
</svg>
</div>
Summary <span>Check</span>
</a>
</header>
<main>
<div class="page-title">
<div class="eyebrow">Planeterra International Foundation</div>
<h1>Summary Reconciliation Check</h1>
<p>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.</p>
</div>
<div class="card">
<div class="card-label">This Period's Workbook</div>
<div class="file-zone" id="currentZone">
<input type="file" id="currentFileInput" accept=".xlsx,.xls">
<div class="file-zone-label"><strong>Drop this period's consolidated workbook here</strong> or browse</div>
<div class="file-zone-sub">Must contain "TB SC & Pr (Manual)" and "1. Summary (Manual)" sheets</div>
</div>
<div class="file-chosen" id="currentFileChosen" style="display:none"></div>
<div class="card-label" style="margin-top:20px">Prior Period's Workbook (optional)</div>
<div class="file-zone" id="priorZone">
<input type="file" id="priorFileInput" accept=".xlsx,.xls">
<div class="file-zone-label"><strong>Drop last period's workbook here</strong> or browse</div>
<div class="file-zone-sub">Enables the "new lines since last period" hint for any mismatched account</div>
</div>
<div class="file-chosen" id="priorFileChosen" style="display:none"></div>
<button class="btn btn-primary" id="checkBtn" disabled>Run Check</button>
<div class="spinner" id="spinner">
<div class="spinner-dot"></div>
Checking…
</div>
<div class="error-note" id="errorNote"></div>
</div>
<div class="card result-card" id="resultCard">
<div class="result-header">
<div class="result-icon" id="resultIcon">
<svg viewBox="0 0 24 24" fill="none" stroke="#10D98A" stroke-width="2.5">
<polyline points="20,6 9,17 4,12"/>
</svg>
</div>
<div>
<div class="result-title" id="resultTitle"></div>
<div class="result-sub" id="resultSub"></div>
</div>
</div>
<div class="card-label" style="margin-top:4px">Aggregate Balance (the "is this workbook actually balanced" answer)</div>
<div id="totalsRows" style="margin-bottom:18px"></div>
<div class="card-label">Per-Account Detail</div>
<p class="field-note" style="margin-bottom:12px">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.</p>
<div class="col-head">
<span>Account</span><span>TB Total</span><span>Summary Total</span><span>Diff</span><span>Status</span>
</div>
<div id="acctRows"></div>
</div>
</main>
<footer>
Built by <a href="https://undodesigns.com" target="_blank">Undo Designs</a> · Summary Reconciliation Check v1
</footer>
<script>
const $ = id => document.getElementById(id);
function escapeHtml(s) {
return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
function fmtMoney(n) {
const sign = n < 0 ? '-' : '';
return sign + '$' + Math.abs(n).toLocaleString('en-US', {minimumFractionDigits: 2});
}
let currentFile = null;
let priorFile = null;
function setupZone(zoneId, inputId, chosenId, onSet) {
const zone = $(zoneId);
const input = $(inputId);
function handle(file) {
if (!file) return;
if (!/\.(xlsx|xls)$/i.test(file.name)) return;
onSet(file);
$(chosenId).textContent = file.name;
$(chosenId).style.display = 'block';
$('checkBtn').disabled = !currentFile;
$('resultCard').classList.remove('visible');
}
input.addEventListener('change', () => handle(input.files[0]));
zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
zone.addEventListener('drop', e => {
e.preventDefault(); zone.classList.remove('drag-over');
handle(e.dataTransfer.files[0]);
});
}
setupZone('currentZone', 'currentFileInput', 'currentFileChosen', f => currentFile = f);
setupZone('priorZone', 'priorFileInput', 'priorFileChosen', f => priorFile = f);
$('checkBtn').addEventListener('click', async () => {
if (!currentFile) return;
$('checkBtn').disabled = true;
$('spinner').classList.add('visible');
$('errorNote').classList.remove('visible');
$('resultCard').classList.remove('visible');
const fd = new FormData();
fd.append('current_file', currentFile);
if (priorFile) fd.append('prior_file', priorFile);
try {
const r = await fetch('/summary-check/api/check', { method: 'POST', body: fd });
const d = await r.json();
if (d.status === 'ok') {
const icon = $('resultIcon');
const aggregateBalanced = d.totals.revenue.matches && d.totals.expenses.matches;
if (aggregateBalanced) {
icon.className = 'result-icon ok';
$('resultTitle').textContent = 'Workbook balances';
} else {
icon.className = 'result-icon warn';
$('resultTitle').textContent = 'Workbook does not balance';
}
$('resultSub').textContent = (d.mismatch_count === 0 ? 'All accounts match individually. ' : `${d.mismatch_count} of ${d.total_count} individual accounts show a diff (see detail below). `)
+ (d.prior_file_used
? 'Prior-period workbook supplied — new-line hints included for mismatched accounts.'
: 'No prior-period workbook supplied — add one for new-line hints on mismatched accounts.');
$('totalsRows').innerHTML = ['revenue', 'expenses'].map(key => {
const t = d.totals[key];
const label = key === 'revenue' ? 'Total Revenue' : 'Total Expenses';
return `<div class="acct-row${t.matches ? '' : ' mismatch'}">
<div class="acct-row-head">
<span class="acct-label">${label}</span>
<span>${fmtMoney(t.tb_total)}</span>
<span>${fmtMoney(t.summary_total)}</span>
<span>${fmtMoney(t.diff)}</span>
<span class="recon-badge ${t.matches ? 'ok' : 'warn'}">${t.matches ? 'OK' : 'MISMATCH'}</span>
</div>
</div>`;
}).join('');
function fmtTbRows(rowsArr) {
if (!rowsArr || !rowsArr.length) return '';
return 'TB row' + (rowsArr.length > 1 ? 's ' : ' ') + rowsArr.join(', ');
}
function fmtCatProj(n) {
return escapeHtml(n.category) + ' / ' + escapeHtml(n.project);
}
function fmtSubtractionHint(p) {
const bits = [];
if (p.missing_from_subtraction_canada && p.missing_from_subtraction_canada.length) {
bits.push(`Summary row${p.missing_from_subtraction_canada.length>1?'s':''} <strong>${p.missing_from_subtraction_canada.join(', ')}</strong> ${p.missing_from_subtraction_canada.length>1?'are':'is'} not excluded from this row's Canada (E) formula — likely double-counted`);
}
if (p.missing_from_subtraction_us && p.missing_from_subtraction_us.length && p.blanket_us) {
bits.push(`Summary row${p.missing_from_subtraction_us.length>1?'s':''} <strong>${p.missing_from_subtraction_us.join(', ')}</strong> ${p.missing_from_subtraction_us.length>1?'are':'is'} not excluded from this row's US (F) formula`);
}
if (p.extra_subtraction_canada && p.extra_subtraction_canada.length) {
bits.push(`Row${p.extra_subtraction_canada.length>1?'s':''} <strong>${p.extra_subtraction_canada.join(', ')}</strong> ${p.extra_subtraction_canada.length>1?'are':'is'} subtracted in Canada (E) but ${p.extra_subtraction_canada.length>1?"aren't":"isn't"} a dedicated row for this category — likely an over-subtraction`);
}
return bits.join('. ');
}
function fmtKbProblem(p) {
if (p.kind === 'keyed') {
return `<div class="kb-problem">
<div class="kb-problem-head">
<span class="kb-problem-title">${escapeHtml(p.category)} / ${escapeHtml(p.project)} ${p.summary_row ? '<span style="color:var(--w3)">→ Summary row ' + p.summary_row + '</span>' : '<span style="color:var(--red)">→ no TB data under this account (likely a cross-account reference)</span>'}</span>
<span class="kb-problem-kind keyed">Keyed row</span>
</div>
<div class="kb-problem-row"><span class="lbl">TB (${fmtTbRows(p.tb_rows) || 'none'})</span><span>${fmtMoney(p.tb_canada)} CAN / ${fmtMoney(p.tb_us)} US</span></div>
<div class="kb-problem-row"><span class="lbl">Summary row ${p.summary_row ?? '—'}</span><span>${fmtMoney(p.summary_canada)} CAN / ${fmtMoney(p.summary_us)} US</span></div>
<div class="kb-problem-row"><span class="lbl">Diff (Summary − TB)</span><span style="color:var(--red)">${fmtMoney(p.diff_canada)} CAN / ${fmtMoney(p.diff_us)} US</span></div>
</div>`;
}
if (p.kind === 'blanket') {
const hint = fmtSubtractionHint(p);
return `<div class="kb-problem">
<div class="kb-problem-head">
<span class="kb-problem-title">${escapeHtml(p.category)} <span style="color:var(--w3)">→ blanket Summary row ${p.summary_row}</span></span>
<span class="kb-problem-kind blanket">Blanket collector</span>
</div>
<div class="kb-problem-row"><span class="lbl">Uncovered TB residual (${fmtTbRows(p.tb_rows) || 'none'})</span><span>${fmtMoney(p.uncovered_canada)} CAN / ${fmtMoney(p.uncovered_us)} US</span></div>
<div class="kb-problem-row"><span class="lbl">Blanket row cached value</span><span>${fmtMoney(p.blanket_canada)} CAN / ${fmtMoney(p.blanket_us)} US</span></div>
<div class="kb-problem-row"><span class="lbl">Diff (blanket − uncovered)</span><span style="color:var(--red)">${fmtMoney(p.diff_canada)} CAN / ${fmtMoney(p.diff_us)} US</span></div>
${hint ? `<div class="kb-problem-note">${hint}</div>` : ''}
</div>`;
}
// uncovered
return `<div class="kb-problem">
<div class="kb-problem-head">
<span class="kb-problem-title">${escapeHtml(p.category)} <span style="color:var(--red)">→ no Summary row captures this at all (no dedicated project row, no blanket collector)</span></span>
<span class="kb-problem-kind uncovered">Fully uncovered</span>
</div>
<div class="kb-problem-row"><span class="lbl">TB (${fmtTbRows(p.tb_rows) || 'none'})</span><span>${fmtMoney(p.canada)} CAN / ${fmtMoney(p.us)} US</span></div>
</div>`;
}
let kbCounter = 0;
window.toggleKb = function(id) {
const body = document.getElementById('kbBody' + id);
const toggle = document.getElementById('kbToggle' + id);
body.classList.toggle('open');
toggle.classList.toggle('open');
};
$('acctRows').innerHTML = d.accounts.map(a => {
let hints = '';
if (!a.matches) {
const rowCountLine = ('prior_tb_row_count' in a)
? `<div class="acct-hint-row"><span>TB row count</span><span>${a.prior_tb_row_count} prior → ${a.tb_row_count} current</span></div>`
: `<div class="acct-hint-row"><span>TB row count</span><span>${a.tb_row_count} current (no prior period uploaded)</span></div>`;
hints += `<div class="acct-hint">
<div class="acct-hint-label">Row count comparison</div>
${rowCountLine}
</div>`;
if (a.new_since_prior) {
hints += `<div class="acct-hint">
<div class="acct-hint-label">New category/project lines since prior period (present in current TB, absent from prior TB — plain diff, no guessing)</div>
${a.new_since_prior.length
? a.new_since_prior.map(n => `<div class="acct-hint-row"><span>${fmtCatProj(n)} <span style="color:var(--w3)">(${fmtTbRows(n.tb_rows)})</span></span><span>${fmtMoney(n.canada)} CAN / ${fmtMoney(n.us)} US</span></div>`).join('')
: '<div class="acct-hint-empty">None found among brand-new combos.</div>'}
</div>`;
}
if (a.grown_since_prior && a.grown_since_prior.length) {
hints += `<div class="acct-hint">
<div class="acct-hint-label" style="color:var(--amber)">Existing combos with MORE rows than last period — one or more of these rows is new, but shares its category/project with an old row so it can't be singled out automatically. Review all rows listed.</div>
${a.grown_since_prior.map(n => `<div class="acct-hint-row"><span>${fmtCatProj(n)} <span style="color:var(--w3)">(${n.prior_count} row${n.prior_count===1?'':'s'} prior → ${n.current_count} now — ${fmtTbRows(n.tb_rows)})</span></span><span>${fmtMoney(n.canada)} CAN / ${fmtMoney(n.us)} US</span></div>`).join('')}
</div>`;
}
if (!a.new_since_prior) {
hints += `<div class="acct-hint-empty" style="margin-top:6px">Upload a prior-period workbook to see exactly which lines are new for this account.</div>`;
}
}
let kbSection = '';
if (!a.matches && a.key_breakdown) {
const kb = a.key_breakdown;
kbCounter++;
const kid = kbCounter;
const fullyExplained = Math.abs(kb.unexplained_diff) < 0.02;
const explainLine = fullyExplained
? `This breakdown fully accounts for the ${fmtMoney(a.diff)} diff above — every dollar is traced to a specific row or gap below.`
: `This breakdown traces ${fmtMoney(kb.explained_diff)} of the ${fmtMoney(a.diff)} diff (${fmtMoney(kb.unexplained_diff)} unaccounted for). The remainder likely reflects a difference between the TB RC and TB SC sheets themselves for this account (revenue accounts' Spend-Category sheet is coarser than the Revenue-Category one), rather than a row-level formula bug.`;
const problemsHtml = kb.problems.length
? kb.problems.map(fmtKbProblem).join('')
: `<div class="acct-hint-empty">No individual row-level or blanket-collector mismatches found — checked ${kb.checked_keys} TB line(s) across ${kb.checked_categories} categor${kb.checked_categories===1?'y':'ies'}.</div>`;
kbSection = `
<div class="kb-toggle" id="kbToggle${kid}" onclick="toggleKb(${kid})">
<span class="kb-toggle-label">Detailed line-by-line breakdown (${kb.problems.length} flagged)</span>
<span class="kb-toggle-arrow">▶</span>
</div>
<div class="kb-body" id="kbBody${kid}">
<div class="kb-explain-line${fullyExplained ? '' : ' partial'}">${explainLine}</div>
${problemsHtml}
</div>`;
}
return `<div class="acct-row${a.matches ? '' : ' mismatch'}">
<div class="acct-row-head">
<span class="acct-label">${escapeHtml(a.account)}</span>
<span>${fmtMoney(a.tb_total)}</span>
<span>${fmtMoney(a.summary_total)}</span>
<span>${fmtMoney(a.diff)}</span>
<span class="recon-badge ${a.matches ? 'ok' : 'warn'}">${a.matches ? 'OK' : 'MISMATCH'}</span>
</div>
${hints}
${kbSection}
</div>`;
}).join('');
$('resultCard').classList.add('visible');
} else {
$('errorNote').textContent = d.error || 'Unexpected error';
$('errorNote').classList.add('visible');
}
} catch (e) {
$('errorNote').textContent = 'Network error: ' + e.message;
$('errorNote').classList.add('visible');
}
$('spinner').classList.remove('visible');
$('checkBtn').disabled = false;
});
</script>
</body>
</html>