Compare commits

...

7 Commits

Author SHA1 Message Date
JasonFraser dfd3a710e0 Fix Category Summary/Balance Sheet reconciliation and account grouping
- Canonicalize category/project/account text before grouping so
  case-only variants (e.g. "OffSite Meetings" vs "Offsite Meetings")
  collapse to one row instead of producing two SUMIFS formulas that
  double-count each other under Excel/Sheets' case-insensitive text
  matching - this was the source of the reported mismatch.
- Add _assert_no_case_collisions as a build-time safety net; the old
  Python-only reconciliation check couldn't catch this class of bug
  since grouped-vs-source totals are mathematically equal regardless
  of labeling. routes.py now returns a clean 400 if it ever fires.
- Reposition 68020 out of the project-level (Account>Category>Project)
  section into the collapsed section with 70000+, so only 68010/68030
  remain above the Project Costs subtotal, matching the reference
  template.
- Rename the two output sheets to "1. Summary (Manual)" and
  "Balance Sheet (FS)", updating the cross-sheet Net Income formula
  reference to match.
- Explicitly set calcMode="auto" (in addition to openpyxl's default
  fullCalcOnLoad) so edits to the TB sheets keep recalculating
  dependent formulas after the first open, not just on it.
- Add a "Report vs. Source Files" comparison table to the results UI
  showing Total Income/Expenses/Surplus side by side against figures
  computed independently from the uploaded files.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 21:54:07 -04:00
JasonFraser e2a798600b Collapse 70000+ accounts to Account>Category, add Project Costs/Net Revenues
Two changes drawn from a closer re-read of the reference template's
expense section:

- Accounts 70000 and up (Wages, Benefits, Occupancy, Travel, etc.) no
  longer break out by Project Code - one row per category, combining
  every project it was posted against (2-criteria SUMIFS: Account +
  Category, no Project). The three "Project Costs" accounts
  (68010/68020/68030) keep the full Account -> Category -> Project
  Code breakdown, since those are the accounts genuinely tied to
  specific donor projects.
- "Project Costs" (68010+68020+68030's account subtotals) and "Net
  Revenues" (Total Revenue - Project Costs) are now inserted
  immediately after the 68030 block, matching the reference template.
  Neither feeds into the account-subtotal list Total Expenses sums
  from, so the three accounts aren't double-counted.

Verified: every pre-existing total is byte-for-byte unchanged (this is
a pure display/grouping change, not a data change) - revenue
5,338,866.02 / expense 3,743,572.26 / surplus 1,595,293.76 /
balance_check 0.00 - and the new Project Costs (2,990,695.99) / Net
Revenues (2,348,170.03) figures were independently resolved via the
SUMIFS/SUM simulator and check out arithmetically
(5,338,866.02 - 2,990,695.99 = 2,348,170.03).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 16:49:59 -04:00
JasonFraser 462e67af41 Nest Category Summary three levels: Account > Category > Project Code
Final structure, after two prior attempts (Account-only, then
Category-only) didn't match what was actually wanted: Account is now
the outer grouping (bold subtotal row, sorted ascending by account
number - resolving the "account sequence jumps around" issue directly,
since account is the primary sort key rather than something to
reorder categories by), Category is a second bold subtotal level
nested within each account (sorted alphabetically, SUMs its own detail
rows), and Project Code remains the leaf-level sort/display column. A
category spanning more than one account (e.g. "Planeterra Program
Costs - Administration" under both 68010 and 68030) now correctly gets
its own separate subtotal block under each account, rather than being
merged into one flat block.

Verified with the same SUMIFS/SUMIF simulator built for the previous
formula rewrite - resolved every formula against the actual embedded
source-sheet data, including account and category subtotals nesting
correctly. All totals unchanged (this is purely a row layout/grouping
change): revenue 5,338,866.02 / expense 3,743,572.26 /
surplus 1,595,293.76 / balance_check 0.00.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 16:38:33 -04:00
JasonFraser 091928eea0 Order categories by account number, not alphabetically
Within a category, rows were already ascending by account number, but
categories themselves were visited alphabetically - so the overall
account-number sequence down a section jumped around (e.g. 78000,
81000, 72400, 70000, 71060, 72600, 78000 again...) even though each
individual category block was internally ordered. Categories are now
visited in ascending order of their lowest account number (ties break
alphabetically), so the account-number sequence is monotonic across
the whole Revenue/Expenses section, not just within each category.

Verified: extracted the lead account code of every category block in
the Expenses section and confirmed the sequence is non-decreasing
end to end. Same totals as before (this only changes row order, not
values): revenue 5,338,866.02 / expense 3,743,572.26 /
balance_check 0.00.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 16:32:11 -04:00
JasonFraser d0ebc3f995 Category subtotal headings + live formulas against embedded source sheets
Two changes, confirmed with the user via concrete preview mockups
before building (avoiding a third wrong guess on the subtotal
structure after the account-grouping change):

- Reverted subtotal/heading grouping from Account back to Category
  (bold subtotal row per category, sorted alphabetically; within a
  category, detail rows sorted by account number then strategic area
  then full project code). Account still shows as the full unsplit
  "code:name" string on every detail row - that part of the account
  change stays, only the grouping key reverted.

- The two uploaded trial balance files are now embedded as their own
  sheets ("Revenue TB", "Expense TB") in the generated workbook, and
  every Category Summary/Balance Sheet cell is a live formula against
  them rather than a precomputed number - directly modeled on
  "1. Summary (Manual)"/"Balance Sheet (FS)"'s own SUMIFS/SUMIF
  formulas:
  - Category Summary detail rows: SUMIFS matching Account+Category+
    Project against the embedded sheet (blank category/project use ""
    criteria, mirroring the template's ISBLANK(...) branches).
  - Balance Sheet lines: SUMIF per mapped account code, wildcard-
    matched ("<code>:*") since the sheet stores code+name together.
    Totals (Total Current Assets, Total Assets, etc.) are formulas
    summing the line-item cells above them, not baked-in numbers.
  - Unrestricted (Net Assets) adds a live cross-sheet reference to
    Category Summary's own Total Revenue/Total Expenses cells for the
    period's Net Income, instead of a Python-computed literal.
  All formulas use only SUM/SUMIF/SUMIFS - no Excel-only functions -
  so the workbook is Google Sheets compatible, not just Excel.

Verified far more rigorously than a cross-check against my own Python
computation this time: wrote a SUMIFS/SUMIF simulator that evaluates
every formula against the actual embedded sheet data (not a
side-channel recomputation), recursively resolving subtotals, grand
totals, and the Balance Sheet's cross-sheet reference. Every result
matches exactly: revenue 5,338,866.02 / expense 3,743,572.26 /
surplus 1,595,293.76 / balance_check 0.00.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 16:23:22 -04:00
JasonFraser 8f1ffe57c6 Category Summary: group/sort by account number, show full account string
Two changes per closer re-reading of the reference template:

- "Account" column now shows the full raw Ledger Account string
  (e.g. "43000:Donation and Fundraising Revenue"), unsplit - same
  treatment as Project Code already gets, rather than parsing out just
  the name.
- Subtotal grouping switches from Category to Account, sorted by
  account number ascending (43000, 48000, then 68010..82000 in the
  Expenses section). String-sorting the full account value works here
  since every code in this chart of accounts is the same 5-digit
  width, so no separate numeric-sort key was needed. Within each
  account, detail rows are still sorted by strategic area (C&B, CTI,
  GCTN, General) then full project code. Category is now a plain
  column rather than a grouping level.

Purely a grouping/display change - re-verified end to end that every
total is unaffected: Category Summary reconciliation still MATCHES
exactly, Balance Sheet balance_check is still 0.00, and every Total
Revenue/Total Expenses/Surplus formula resolves to the same figures
as before (revenue 5,338,866.02 / expense 3,743,572.26 /
surplus 1,595,293.76).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 16:09:25 -04:00
JasonFraser c9fd95572a Add Financial Reports tool: Category Summary + Balance Sheet snapshot
New tool at /financial-reports/, same two-file trial balance upload as
the donor report, generating a workbook built fresh with openpyxl
(no bundled Excel template - the sheets are constructed to match
fs.xlsx's own structure/formatting rather than adjusting a copy of it):

- Category Summary: mirrors "1. Summary (Manual)" from the reference
  workbook - Account | Category | Project Code (full raw string,
  unsplit) | Canada YTD | US YTD | Consolidation Adjustments (blank) |
  Total YTD (formula) | Budget (header only, left blank for manual
  formulas). Category-level subtotal rows (SUM formulas), sorted within
  a category by strategic area then full project code. Total Revenue/
  Total Expenses/Surplus as formulas summing the category subtotals.
- Balance Sheet: single-period snapshot matching "Balance Sheet (FS)"'s
  labels/section order/Arial-11 formatting - the source file's
  month-over-month and prior-year columns are static historical
  snapshots that can't be regenerated from one trial balance upload, so
  this is one consolidated (Canada+US) column for the current period.
  Account-code-to-line-item mapping lives in
  balance_sheet_account_map.csv (bind-mounted, same pattern as the
  other tools' lookup tables), seeded from fs.xlsx's own N-S helper
  columns. Net Assets/Unrestricted = Retained Earnings (36000) + CTA
  (36300) + this period's computed Net Income - avoids needing prior-
  period data since 36000 already carries the cumulative prior position.
- Arithmetic check back to the uploaded files: every run independently
  re-sums Planeterra Foundation/Planeterra International Foundation Ltd
  across the filtered revenue+expense rows and compares against the
  Category Summary's own Canada/US totals, surfaced on both the results
  screen and embedded in the workbook. The Balance Sheet's own
  Assets-vs-Liabilities+NetAssets check is exposed the same way.
- UI: multi-file upload (auto-classifies revenue vs. expense by column
  headers), checkboxes for which sections to include, report date,
  report title, and a whole-dollars-vs-cents number format toggle.

Two real bugs found and fixed during testing, not just simplified logic:
- numpy.bool_ (from pandas comparisons) isn't JSON-serializable, unlike
  native Python bool - silently 500'd the endpoint until wrapped.
- compute_balance_sheet() was concatenating both uploaded files before
  summing Balance Sheet accounts - but both files are independently
  complete trial balance exports (same non-P&L rows in both, just
  tagged with a different category column), so this double-counted
  every single Balance Sheet account by exactly 2x. Caught via a
  balance_check that came out as -net_income instead of zero - too
  precise to be a coincidence, traced it back to the concat.

Verified end to end against the real trial balance files: Category
Summary Canada/US reconciliation both MATCH exactly, and the Balance
Sheet balance_check is exactly 0.00 (Assets = Liabilities + Net
Assets). Independently re-resolved every formula (including the
53-term Total Expenses SUM) and confirmed all totals match the API
response: revenue 5,338,866.02 / expense 3,743,572.26 /
surplus 1,595,293.76.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 15:49:12 -04:00
8 changed files with 1533 additions and 0 deletions

1
.gitignore vendored
View File

@ -11,4 +11,5 @@ __pycache__/
!app/tools/eib/merchant_lookup.csv
!app/tools/donor_report/report_summary_template.xlsx
!app/tools/donor_report/donor_merge_map.csv
!app/tools/financial_reports/balance_sheet_account_map.csv
.claude/settings.local.json

View File

@ -3,6 +3,7 @@ from flask import Flask, render_template
from tools.eib import eib_bp
from tools.donor_report import donor_report_bp
from tools.financial_reports import financial_reports_bp
# ── Tool registry ────────────────────────────────────────────────────────────
# Each entry drives one card on the landing page. Add a new tool by
@ -30,6 +31,17 @@ TOOLS = [
"url": "/donor-report/",
"status": "online",
},
{
"name": "Financial Reports",
"tagline": "Trial Balance → Category Summary & Balance Sheet",
"description": (
"Generates a Category Summary (Account/Category/Project Code, "
"Canada/US split) and a Balance Sheet snapshot from the revenue "
"and expense trial balances, reconciled back to the source files."
),
"url": "/financial-reports/",
"status": "online",
},
]
@ -41,6 +53,7 @@ def create_app():
app.register_blueprint(eib_bp)
app.register_blueprint(donor_report_bp)
app.register_blueprint(financial_reports_bp)
@app.route("/")
def home():

View File

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

View File

@ -0,0 +1,28 @@
line_item,section,account_code,sign
Cash,Assets,10000,1
Cash,Assets,10005,1
Cash,Assets,10010,1
Cash,Assets,10015,1
Cash,Assets,10999,1
Cash,Assets,13205,1
Accounts receivable,Assets,12002,1
Accounts receivable,Assets,12010,1
Accounts receivable,Assets,12020,1
Accounts receivable,Assets,12800,1
Prepaids,Assets,13100,1
Due from related companies,Assets,13160,1
Due from related companies,Assets,13170,1
Due from related companies,Assets,14450,1
Due from related companies,Assets,14500,1
Due from related companies,Assets,14599,1
Capital Assets,Assets,17000,1
Capital Assets,Assets,17005,1
Due to related companies,Liabilities,27500,-1
Due to related companies,Liabilities,29000,-1
Accrued Liabilities,Liabilities,20300,-1
Accounts Payable,Liabilities,20000,-1
Accounts Payable,Liabilities,20130,-1
Accounts Payable,Liabilities,20200,-1
Accounts Payable,Liabilities,20100,-1
Unrestricted,NetAssets,36000,-1
Unrestricted,NetAssets,36300,-1
1 line_item section account_code sign
2 Cash Assets 10000 1
3 Cash Assets 10005 1
4 Cash Assets 10010 1
5 Cash Assets 10015 1
6 Cash Assets 10999 1
7 Cash Assets 13205 1
8 Accounts receivable Assets 12002 1
9 Accounts receivable Assets 12010 1
10 Accounts receivable Assets 12020 1
11 Accounts receivable Assets 12800 1
12 Prepaids Assets 13100 1
13 Due from related companies Assets 13160 1
14 Due from related companies Assets 13170 1
15 Due from related companies Assets 14450 1
16 Due from related companies Assets 14500 1
17 Due from related companies Assets 14599 1
18 Capital Assets Assets 17000 1
19 Capital Assets Assets 17005 1
20 Due to related companies Liabilities 27500 -1
21 Due to related companies Liabilities 29000 -1
22 Accrued Liabilities Liabilities 20300 -1
23 Accounts Payable Liabilities 20000 -1
24 Accounts Payable Liabilities 20130 -1
25 Accounts Payable Liabilities 20200 -1
26 Accounts Payable Liabilities 20100 -1
27 Unrestricted NetAssets 36000 -1
28 Unrestricted NetAssets 36300 -1

View File

@ -0,0 +1,819 @@
import os, csv
from datetime import datetime
import pandas as pd
import openpyxl
from openpyxl.styles import Font
ACCOUNT_MAP_PATH = os.path.join(os.path.dirname(__file__), "balance_sheet_account_map.csv")
REVENUE_ACCOUNT_CODES = ("43000", "48000")
# Same expense scope as the donor report - see that tool's logic.py for why
# this covers all P&L expense accounts rather than just "project cost" ones.
EXPENSE_ACCOUNT_CODES = (
"68010", "68020", "68030",
"70000", "70010", "70020", "70030", "71060",
"72000", "72100", "72300", "72400", "72600", "72800", "72900",
"78000", "79000", "81000", "82000",
)
REVENUE_SHEET_NAME = "Revenue TB"
EXPENSE_SHEET_NAME = "Expense TB"
# Accounts that get the full Account -> Category -> Project Code
# breakdown, positioned ahead of the "Project Costs" subtotal. Everything
# else (68020 included) is Account -> Category only, no per-project detail
# rows, and is positioned after "Net Revenues" alongside 70000 and up -
# matching the reference template.
PROJECT_LEVEL_ACCOUNT_CODES = {"43000", "48000", "68010", "68030"}
# The two "Project Costs" accounts specifically - summed into a
# "Project Costs" subtotal, then "Net Revenues" (Total Revenue - Project
# Costs), right after the last project-level account, matching the
# reference template.
PROJECT_COST_ACCOUNT_CODES = ("68010", "68030")
FONT_NAME = "Arial"
FONT_SIZE = 11
REGULAR_FONT = Font(name=FONT_NAME, size=FONT_SIZE, bold=False)
BOLD_FONT = Font(name=FONT_NAME, size=FONT_SIZE, bold=True)
# Matches the accounting number format used in fs.xlsx's Balance Sheet (FS)
# sheet - parens for negative, dash for zero, whole dollars by default.
ACCOUNTING_FORMAT_WHOLE = '_(* #,##0_);_(* (#,##0);_(* "-"??_);_(@_)'
ACCOUNTING_FORMAT_CENTS = '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)'
RECONCILE_TOLERANCE = 0.01
def _load_account_map(path=ACCOUNT_MAP_PATH):
"""
Read the Balance Sheet account-code -> line-item mapping fresh from
balance_sheet_account_map.csv on every call, same bind-mounted-CSV
pattern as the other tools' lookup tables. Returns
{line_item: {"section": ..., "codes": [(code, sign), ...]}}, with
line items in first-seen CSV order.
"""
mapping = {}
if not os.path.exists(path):
return mapping
with open(path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
line_item = row.get("line_item")
if not line_item:
continue
entry = mapping.setdefault(line_item, {"section": row.get("section"), "codes": []})
entry["codes"].append((row.get("account_code", "").strip(), int(row.get("sign", 1))))
return mapping
def classify_trial_balance_file(df):
"""Revenue and expense trial balance exports share every column
except the category one - detect which is which by that column."""
cols = set(df.columns)
if {"Ledger Account", "Project", "Planeterra Foundation", "Revenue Category"} <= cols:
return "revenue"
if {"Ledger Account", "Project", "Planeterra Foundation", "Spend Category"} <= cols:
return "expense"
return None
def full_file_balance(tb_df):
"""Sum every row's combined-entity value across the WHOLE file - a
complete, correctly-exported trial balance nets to zero. Same
integrity check as the donor report, duplicated here since this tool
is deliberately self-contained."""
combined = tb_df["Planeterra Foundation"].fillna(0) + tb_df["Planeterra International Foundation Ltd"].fillna(0)
return round(combined.sum(), 2)
def extract_slob(project):
"""Pull just the strategic-area segment (e.g. 'C&B') out of a Project
string, for sort order only - the full string is always what's
displayed in the Project Code column."""
if not project or not str(project).strip():
return ""
parts = str(project).split(" - ")
return parts[1] if len(parts) >= 2 else ""
def _excel_str(s):
"""Escape a string for safe embedding as an exact-match SUMIFS/SUMIF
criteria: double embedded quotes, and tilde-escape wildcard characters
so a literal '*' or '?' in an account/category/project name is never
mistaken for a SUMIFS wildcard."""
s = str(s)
s = s.replace("~", "~~").replace("*", "~*").replace("?", "~?")
return s.replace('"', '""')
def _join_signed_terms(terms_with_sign):
"""terms_with_sign: [(expr, sign), ...]. Joins into 'A + B - C' style
(never 'A+-B') so the formula string is unambiguous."""
if not terms_with_sign:
return "0"
parts = []
for i, (expr, sign) in enumerate(terms_with_sign):
if i == 0:
parts.append(expr if sign > 0 else f"-{expr}")
else:
parts.append((" + " if sign > 0 else " - ") + expr)
return "".join(parts)
def _canonicalize_text(series):
"""
Collapse case/whitespace-only variants of the same text (e.g.
"OffSite Meetings" vs "Offsite Meetings") to a single canonical label,
chosen as the most frequent original casing for that text (ties go to
whichever sorts first, for determinism).
This matters because SUMIFS/SUMIF text criteria in Excel/Google Sheets
match case-insensitively: if two distinct-case variants were left as
separate groupby rows, each would get its own SUMIFS formula, and each
formula would sum BOTH variants' source rows - silently double-counting
the overlap. Canonicalizing before grouping keeps one row per
case-insensitive value, so the live formula matches only that value.
"""
stripped = series.astype(str).str.strip()
norm = stripped.str.lower()
canonical = stripped.groupby(norm).agg(lambda s: sorted(s.value_counts().items(), key=lambda kv: (-kv[1], kv[0]))[0][0])
return norm.map(canonical)
def _assert_no_case_collisions(df, cols, context):
"""
Defensive regression check for the case-insensitive SUMIFS bug that
_canonicalize_text fixes: verify no two distinct combinations of
`cols` normalize (strip + lowercase) to the same key. A violation
means canonicalization missed something and the live SUMIFS/SUMIF
formulas for these rows would silently double-count each other once
opened in Excel/Sheets - exactly what happened with "OffSite
Meetings" vs "Offsite Meetings" under account 72300, which the old
Python-only reconciliation check (grouped total vs. source total -
mathematically equal no matter how the rows are labeled) could never
have caught. Raises rather than shipping a workbook that won't
reconcile once its formulas are actually evaluated.
"""
tmp = df[cols].copy()
norm_cols = []
for c in cols:
nc = f"{c}__norm"
tmp[nc] = tmp[c].astype(str).str.strip().str.lower()
norm_cols.append(nc)
for _, g in tmp.groupby(norm_cols):
distinct = g[cols].drop_duplicates()
if len(distinct) > 1:
raise ValueError(
f"{context}: found values that differ only by case/whitespace "
f"and would collide under Excel/Sheets' case-insensitive "
f"SUMIFS matching: {distinct.to_dict('records')}. Fix the "
f"source data (or extend _canonicalize_text if this is a "
f"legitimate new case) before generating the report."
)
def process_category_summary(revenue_df, expense_df):
"""
Build the Category Summary rows: one per (account, category, project
code), Canada/US kept as separate columns (not combined, unlike the
donor report). "account" is the full raw "Ledger Account" string
(code:name together, unsplit) - same treatment as Project Code - and
is shown per row but is no longer the grouping/subtotal key (Category
is - see _write_category_section). Returns a dict with 'revenue' and
'expense' DataFrames plus the independently-computed source totals
used for the reconciliation check.
"""
results = {}
source_totals = {}
for key, df, codes, cat_col, flip in [
("revenue", revenue_df, REVENUE_ACCOUNT_CODES, "Revenue Category", True),
("expense", expense_df, EXPENSE_ACCOUNT_CODES, "Spend Category", False),
]:
d = df.copy()
d = d[d["Ledger Account"].astype(str).str.strip().str.startswith(codes)]
d["account"] = _canonicalize_text(d["Ledger Account"])
d["category"] = _canonicalize_text(d[cat_col].fillna("(Uncategorized)"))
d["project_code"] = _canonicalize_text(d["Project"].fillna("(No project)"))
d["slob"] = d["Project"].apply(extract_slob)
canada = d["Planeterra Foundation"].fillna(0)
us = d["Planeterra International Foundation Ltd"].fillna(0)
if flip:
canada, us = -canada, -us
d["canada"] = canada
d["us"] = us
# Source totals, independent of the groupby below, for the
# reconciliation check.
source_totals[f"{key}_canada"] = round(canada.sum(), 2)
source_totals[f"{key}_us"] = round(us.sum(), 2)
grouped = (
d.groupby(["account", "category", "slob", "project_code"], as_index=False)
[["canada", "us"]].sum()
)
grouped = grouped[(grouped["canada"].abs() >= 0.005) | (grouped["us"].abs() >= 0.005)]
grouped = grouped.reset_index(drop=True)
# Two granularities, because the two account groups use different
# SUMIFS criteria: project-level accounts key on all three columns,
# collapsed accounts (68020, 70000 and up) key on account+category
# only (see PROJECT_LEVEL_ACCOUNT_CODES / _write_category_section).
_assert_no_case_collisions(grouped, ["account", "category", "project_code"], f"{key} category summary")
_assert_no_case_collisions(grouped, ["account", "category"], f"{key} category summary (account+category)")
results[key] = grouped
return results, source_totals
def compute_balance_sheet(revenue_tb_df, expense_tb_df, net_income, account_map=None):
"""
Compute each Balance Sheet line item as the combined (Canada + US)
total of its mapped account codes - the Python-side numbers used for
the balance_check/summary reported to the UI (the workbook's own
cells are live SUMIF formulas instead - see build_balance_sheet_sheet
- so this is an independent cross-check, not what the file displays).
Balance Sheet accounts live outside the revenue/expense ranges
entirely, but both uploaded files are full trial balance exports -
the same Balance Sheet rows appear in both (just tagged with a
different category column), so this reads from ONE of them, not both
concatenated, or every account would be double-counted. net_income
(Total Revenue - Total Expense, combined entities) is added into
"Unrestricted" alongside Retained Earnings/CTA, matching how the
source file derives Net Assets.
"""
if account_map is None:
account_map = _load_account_map()
full = revenue_tb_df.copy()
full["_code"] = full["Ledger Account"].astype(str).str.split(":", n=1).str[0].str.strip()
full["_combined"] = full["Planeterra Foundation"].fillna(0) + full["Planeterra International Foundation Ltd"].fillna(0)
by_code = full.groupby("_code")["_combined"].sum()
values = {}
for line_item, entry in account_map.items():
total = 0.0
for code, sign in entry["codes"]:
total += sign * by_code.get(code, 0)
values[line_item] = round(total, 2)
values.setdefault("Deferred Revenue", 0.0)
values["Unrestricted"] = round(values.get("Unrestricted", 0.0) + net_income, 2)
total_current_assets = round(
values.get("Cash", 0) + values.get("Accounts receivable", 0) + values.get("Prepaids", 0), 2
)
total_assets = round(
total_current_assets + values.get("Due from related companies", 0) + values.get("Capital Assets", 0), 2
)
total_current_liabilities = round(
values.get("Due to related companies", 0) + values.get("Accrued Liabilities", 0)
+ values.get("Accounts Payable", 0) + values.get("Deferred Revenue", 0), 2
)
total_net_assets = round(values.get("Unrestricted", 0), 2)
total_liab_and_net_assets = round(total_current_liabilities + total_net_assets, 2)
balance_check = round(total_liab_and_net_assets - total_assets, 2)
return {
"values": values,
"total_current_assets": total_current_assets,
"total_assets": total_assets,
"total_current_liabilities": total_current_liabilities,
"total_net_assets": total_net_assets,
"total_liab_and_net_assets": total_liab_and_net_assets,
"balance_check": balance_check,
}
def _write_cell(ws, row, col, value, bold=False, number_format=None, italic=False):
c = ws.cell(row=row, column=col, value=value)
c.font = Font(name=FONT_NAME, size=FONT_SIZE, bold=bold, italic=italic)
if number_format:
c.number_format = number_format
return c
def write_source_sheet(wb, df, sheet_name):
"""
Dump an uploaded trial balance file into its own sheet, verbatim
(same columns, same order, plain values) - this is what the Category
Summary and Balance Sheet formulas point back at, so the generated
workbook is self-contained and auditable without the original
upload in hand.
"""
ws = wb.create_sheet(sheet_name)
for col_idx, col_name in enumerate(df.columns, start=1):
_write_cell(ws, 1, col_idx, col_name, bold=True)
clean = df.where(pd.notnull(df), None)
for row_idx, row in enumerate(clean.itertuples(index=False), start=2):
for col_idx, val in enumerate(row, start=1):
ws.cell(row=row_idx, column=col_idx, value=val)
for col_idx in range(1, len(df.columns) + 1):
ws.column_dimensions[ws.cell(row=1, column=col_idx).column_letter].width = 22
return ws
def _sumifs_expr(sheet_name, amount_col_letter, account, category, project_code):
"""
A SUMIFS pulling one row-group's amount straight from the raw source
sheet - directly modeled on "1. Summary (Manual)"'s own
sumifs('TB RC & Pr (Manual)'!D:D, ...) formulas. Blank category/
project in the source (our "(Uncategorized)"/"(No project)"
placeholders) match against an empty-string criteria, same as the
template's ISBLANK(...) branches did.
"""
cat_crit = '""' if category == "(Uncategorized)" else f'"{_excel_str(category)}"'
proj_crit = '""' if project_code == "(No project)" else f'"{_excel_str(project_code)}"'
acct_crit = f'"{_excel_str(account)}"'
return (
f"SUMIFS('{sheet_name}'!{amount_col_letter}:{amount_col_letter},"
f"'{sheet_name}'!A:A,{acct_crit},"
f"'{sheet_name}'!C:C,{cat_crit},"
f"'{sheet_name}'!B:B,{proj_crit})"
)
def _sumifs_expr_no_project(sheet_name, amount_col_letter, account, category):
"""
Same as _sumifs_expr but without the Project criterion - used for
accounts that aren't broken out by project (70000 and up), where one
row per category already covers every project it was posted against.
"""
cat_crit = '""' if category == "(Uncategorized)" else f'"{_excel_str(category)}"'
acct_crit = f'"{_excel_str(account)}"'
return (
f"SUMIFS('{sheet_name}'!{amount_col_letter}:{amount_col_letter},"
f"'{sheet_name}'!A:A,{acct_crit},"
f"'{sheet_name}'!C:C,{cat_crit})"
)
def _write_category_section(ws, start_row, df, canada_col, us_col, total_col, number_format,
source_sheet_name, flip_sign, total_revenue_row=None):
"""
Write one section (Revenue or Expenses), nested three levels deep:
Account (bold subtotal row, ascending by account number within two
groups - PROJECT_LEVEL_ACCOUNT_CODES first, everything else after -
see the Project Costs/Net Revenues insertion below) -> Category (bold
subtotal row within that account, sorted alphabetically) -> detail
rows (sorted by strategic area then full project code). Canada/US
detail cells are live SUMIFS formulas
against source_sheet_name rather than precomputed values; category
subtotals SUM their own detail rows, and each account subtotal SUMs
its own category subtotals. Returns (list of account-subtotal row
numbers, next free row, section Canada/US raw totals - the raw
totals are still computed in Python from df, for the reconciliation
check and API response, independent of what the formulas themselves
resolve to).
"""
row = start_row
account_subtotal_rows = []
project_cost_rows = []
canada_total = us_total = 0.0
if df.empty:
return account_subtotal_rows, row, 0.0, 0.0
# Project-level accounts (full Account -> Category -> Project Code
# breakdown) are always written first, ascending among themselves, so
# the "Project Costs"/"Net Revenues" subtotal can sit right after them.
# Everything else (68020 included) follows, ascending among itself -
# physically after Net Revenues, not in its raw numeric position.
all_accounts = sorted(df["account"].unique())
project_accounts = [a for a in all_accounts if a.split(":")[0] in PROJECT_LEVEL_ACCOUNT_CODES]
other_accounts = [a for a in all_accounts if a.split(":")[0] not in PROJECT_LEVEL_ACCOUNT_CODES]
last_project_account = project_accounts[-1] if project_accounts else None
for account in project_accounts + other_accounts:
acct_df = df[df["account"] == account]
account_code = account.split(":")[0]
account_subtotal_row = row
row += 1
if account_code in PROJECT_LEVEL_ACCOUNT_CODES:
# Full Account -> Category -> Project Code breakdown.
category_subtotal_rows = []
for category in sorted(acct_df["category"].unique()):
cat_df = acct_df[acct_df["category"] == category].sort_values(["slob", "project_code"])
cat_first_row = row + 1 # detail rows start after this category's own subtotal row
cat_subtotal_row = row
row += 1
for _, r in cat_df.iterrows():
canada = round(r["canada"], 2)
us = round(r["us"], 2)
sign = "-" if flip_sign else ""
canada_formula = f"={sign}{_sumifs_expr(source_sheet_name, 'D', account, category, r['project_code'])}"
us_formula = f"={sign}{_sumifs_expr(source_sheet_name, 'E', account, category, r['project_code'])}"
_write_cell(ws, row, 1, account)
_write_cell(ws, row, 2, category)
_write_cell(ws, row, 3, r["project_code"])
c = ws.cell(row=row, column=canada_col, value=canada_formula)
c.font, c.number_format = REGULAR_FONT, number_format
c = ws.cell(row=row, column=us_col, value=us_formula)
c.font, c.number_format = REGULAR_FONT, number_format
c = ws.cell(row=row, column=total_col, value=f"={ws.cell(row=row, column=canada_col).coordinate}+{ws.cell(row=row, column=us_col).coordinate}+{ws.cell(row=row, column=total_col - 1).coordinate}")
c.font = REGULAR_FONT
c.number_format = number_format
canada_total += canada
us_total += us
row += 1
cat_last_row = row - 1
_write_cell(ws, cat_subtotal_row, 2, category, bold=True)
for col in (canada_col, us_col, total_col):
letter = ws.cell(row=cat_first_row, column=col).column_letter
c = ws.cell(row=cat_subtotal_row, column=col, value=f"=SUM({letter}{cat_first_row}:{letter}{cat_last_row})")
c.font = BOLD_FONT
c.number_format = number_format
category_subtotal_rows.append(cat_subtotal_row)
_write_cell(ws, account_subtotal_row, 1, account, bold=True)
for col in (canada_col, us_col, total_col):
letter = ws.cell(row=account_subtotal_row, column=col).column_letter
formula = "=" + "+".join(f"{letter}{r}" for r in category_subtotal_rows)
c = ws.cell(row=account_subtotal_row, column=col, value=formula)
c.font = BOLD_FONT
c.number_format = number_format
else:
# 70000 and up: Account -> Category only, no per-project detail -
# one row per category, combining every project it was posted to.
cat_totals = acct_df.groupby("category")[["canada", "us"]].sum()
category_rows = []
for category in sorted(acct_df["category"].unique()):
sign = "-" if flip_sign else ""
canada_formula = f"={sign}{_sumifs_expr_no_project(source_sheet_name, 'D', account, category)}"
us_formula = f"={sign}{_sumifs_expr_no_project(source_sheet_name, 'E', account, category)}"
_write_cell(ws, row, 2, category)
c = ws.cell(row=row, column=canada_col, value=canada_formula)
c.font, c.number_format = REGULAR_FONT, number_format
c = ws.cell(row=row, column=us_col, value=us_formula)
c.font, c.number_format = REGULAR_FONT, number_format
c = ws.cell(row=row, column=total_col, value=f"={ws.cell(row=row, column=canada_col).coordinate}+{ws.cell(row=row, column=us_col).coordinate}+{ws.cell(row=row, column=total_col - 1).coordinate}")
c.font = REGULAR_FONT
c.number_format = number_format
canada_total += round(cat_totals.loc[category, "canada"], 2)
us_total += round(cat_totals.loc[category, "us"], 2)
category_rows.append(row)
row += 1
_write_cell(ws, account_subtotal_row, 1, account, bold=True)
first_r, last_r = category_rows[0], category_rows[-1]
for col in (canada_col, us_col, total_col):
letter = ws.cell(row=account_subtotal_row, column=col).column_letter
c = ws.cell(row=account_subtotal_row, column=col, value=f"=SUM({letter}{first_r}:{letter}{last_r})")
c.font = BOLD_FONT
c.number_format = number_format
account_subtotal_rows.append(account_subtotal_row)
if account_code in PROJECT_COST_ACCOUNT_CODES:
project_cost_rows.append(account_subtotal_row)
# Right after the last project-level account (68010, 68030): a
# "Project Costs" subtotal and "Net Revenues" (Total Revenue -
# Project Costs), matching the reference template. Neither feeds
# into account_subtotal_rows, so Total Expenses (summed from that
# list) isn't double-counting the accounts they roll up.
if account == last_project_account and total_revenue_row is not None:
project_costs_row = row
_write_cell(ws, row, 1, "Project Costs", bold=True)
for col in (canada_col, us_col, total_col):
letter = ws.cell(row=row, column=col).column_letter
formula = "=" + "+".join(f"{letter}{r}" for r in project_cost_rows)
c = ws.cell(row=row, column=col, value=formula)
c.font = BOLD_FONT
c.number_format = number_format
row += 1
_write_cell(ws, row, 1, "Net Revenues", bold=True)
for col in (canada_col, us_col, total_col):
letter = ws.cell(row=row, column=col).column_letter
c = ws.cell(row=row, column=col, value=f"={letter}{total_revenue_row}-{letter}{project_costs_row}")
c.font = BOLD_FONT
c.number_format = number_format
row += 2
return account_subtotal_rows, row, round(canada_total, 2), round(us_total, 2)
def build_category_summary_sheet(wb, revenue_df, expense_df, source_totals, report_date, title,
number_format=ACCOUNTING_FORMAT_WHOLE):
ws = wb.create_sheet("1. Summary (Manual)")
for col, width in zip("ABCDEFGH", (32, 20, 34, 15, 15, 15, 15, 15)):
ws.column_dimensions[col].width = width
_write_cell(ws, 1, 1, title, bold=True)
_write_cell(ws, 2, 1, f"Category Summary — {report_date}", bold=True)
header_row = 4
headers = ["Account", "Category", "Project Code", "Canada YTD", "US YTD",
"Consolidation Adjustments", "Total YTD", "Budget"]
for col, label in enumerate(headers, start=1):
_write_cell(ws, header_row, col, label, bold=True)
CANADA_COL, US_COL, ADJ_COL, TOTAL_COL, BUDGET_COL = 4, 5, 6, 7, 8
row = header_row + 1
_write_cell(ws, row, 1, "Revenue", bold=True)
row += 1
rev_subtotals, row, rev_canada, rev_us = _write_category_section(
ws, row, revenue_df, CANADA_COL, US_COL, TOTAL_COL, number_format,
REVENUE_SHEET_NAME, flip_sign=True,
)
total_revenue_row = row
_write_cell(ws, row, 1, "Total Revenue", bold=True)
for col in (CANADA_COL, US_COL, TOTAL_COL):
letter = ws.cell(row=row, column=col).column_letter
formula = "=" + "+".join(f"{letter}{r}" for r in rev_subtotals) if rev_subtotals else 0
c = ws.cell(row=row, column=col, value=formula)
c.font = BOLD_FONT
c.number_format = number_format
row += 2
_write_cell(ws, row, 1, "Expenses", bold=True)
row += 1
exp_subtotals, row, exp_canada, exp_us = _write_category_section(
ws, row, expense_df, CANADA_COL, US_COL, TOTAL_COL, number_format,
EXPENSE_SHEET_NAME, flip_sign=False, total_revenue_row=total_revenue_row,
)
total_expenses_row = row
_write_cell(ws, row, 1, "Total Expenses", bold=True)
for col in (CANADA_COL, US_COL, TOTAL_COL):
letter = ws.cell(row=row, column=col).column_letter
formula = "=" + "+".join(f"{letter}{r}" for r in exp_subtotals) if exp_subtotals else 0
c = ws.cell(row=row, column=col, value=formula)
c.font = BOLD_FONT
c.number_format = number_format
row += 2
surplus_row = row
_write_cell(ws, row, 1, "Surplus/(Deficit)", bold=True)
for col in (CANADA_COL, US_COL, TOTAL_COL):
letter = ws.cell(row=row, column=col).column_letter
c = ws.cell(row=row, column=col,
value=f"={letter}{total_revenue_row}-{letter}{total_expenses_row}")
c.font = BOLD_FONT
c.number_format = number_format
row += 3
# ── Reconciliation back to the uploaded files ──────────────────────────
report_canada = round(rev_canada + exp_canada, 2)
report_us = round(rev_us + exp_us, 2)
source_canada = round(source_totals["revenue_canada"] + source_totals["expense_canada"], 2)
source_us = round(source_totals["revenue_us"] + source_totals["expense_us"], 2)
# bool(...) here matters: comparisons on pandas-derived floats produce
# numpy.bool_, which isn't JSON-serializable (unlike native Python bool).
canada_ok = bool(abs(report_canada - source_canada) < RECONCILE_TOLERANCE)
us_ok = bool(abs(report_us - source_us) < RECONCILE_TOLERANCE)
_write_cell(ws, row, 1, "Reconciliation to uploaded files", bold=True)
row += 1
_write_cell(ws, row, 1, "Canada — report total"); _write_cell(ws, row, 2, report_canada, number_format=number_format)
_write_cell(ws, row, 3, "Canada — source file total"); _write_cell(ws, row, 4, source_canada, number_format=number_format)
_write_cell(ws, row, 5, "MATCH" if canada_ok else "MISMATCH", bold=True)
row += 1
_write_cell(ws, row, 1, "US — report total"); _write_cell(ws, row, 2, report_us, number_format=number_format)
_write_cell(ws, row, 3, "US — source file total"); _write_cell(ws, row, 4, source_us, number_format=number_format)
_write_cell(ws, row, 5, "MATCH" if us_ok else "MISMATCH", bold=True)
# Report vs. source figures for the three headline metrics (Total
# Income, Total Expenses, Surplus/Deficit) - the "report" side is what
# the 1. Summary (Manual)/Balance Sheet (FS) sheets show (and what the
# Balance Sheet's Net Income term is built from); the "source" side is
# summed directly from the uploaded files, independent of any
# grouping/labeling, so the UI can show the two side by side.
revenue_total = round(rev_canada + rev_us, 2)
expense_total = round(exp_canada + exp_us, 2)
source_revenue_total = round(source_totals["revenue_canada"] + source_totals["revenue_us"], 2)
source_expense_total = round(source_totals["expense_canada"] + source_totals["expense_us"], 2)
surplus_deficit = round(revenue_total - expense_total, 2)
source_surplus_deficit = round(source_revenue_total - source_expense_total, 2)
return {
"revenue_total": revenue_total,
"expense_total": expense_total,
"surplus_deficit": surplus_deficit,
"source_revenue_total": source_revenue_total,
"source_expense_total": source_expense_total,
"source_surplus_deficit": source_surplus_deficit,
"revenue_match": bool(abs(revenue_total - source_revenue_total) < RECONCILE_TOLERANCE),
"expense_match": bool(abs(expense_total - source_expense_total) < RECONCILE_TOLERANCE),
"surplus_match": bool(abs(surplus_deficit - source_surplus_deficit) < RECONCILE_TOLERANCE),
"reconciled": canada_ok and us_ok,
"report_canada": report_canada, "source_canada": source_canada,
"report_us": report_us, "source_us": source_us,
"total_revenue_row": total_revenue_row,
"total_expenses_row": total_expenses_row,
}
BALANCE_SHEET_LAYOUT = [
("Assets", True, None),
("Cash", False, "Cash"),
("Accounts receivable", False, "Accounts receivable"),
("Prepaids", False, "Prepaids"),
(None, False, "__total_current_assets__"),
(None, False, None), # blank spacer row
("Due from related companies", False, "Due from related companies"),
("Capital Assets", False, "Capital Assets"),
(None, False, "__total_assets__"),
(None, False, None),
("Liabilities", True, None),
("Current Liabilities", False, None),
("Due to related companies", False, "Due to related companies"),
("Accrued Liabilities", False, "Accrued Liabilities"),
("Accounts Payable", False, "Accounts Payable"),
("Deferred Revenue", False, "Deferred Revenue"),
(None, False, "__total_current_liabilities__"),
(None, False, None),
("Net Assets", True, None),
("Unrestricted", False, "Unrestricted"),
(None, False, "__total_net_assets__"),
(None, False, "__total_liab_and_net_assets__"),
(None, False, "__balance_check__"),
]
def build_balance_sheet_sheet(wb, bs, net_income, report_date, title, account_map, source_sheet_name,
category_summary_refs=None, number_format=ACCOUNTING_FORMAT_WHOLE):
"""
Fresh sheet matching fs.xlsx's "Balance Sheet (FS)" structure/labels/
fonts (Arial 11, bold section headers), but a single consolidated
(Canada+US combined) column for this period only - the source
file's month-over-month/prior-year comparison columns are static
historical snapshots that can't be regenerated from a single trial
balance upload. Every line and total is a live formula (SUMIF against
source_sheet_name, inspired directly by "Balance Sheet (FS)"'s own
sumif('TB RC & Pr (Manual)'!$A:$A, ...) formulas), not a precomputed
value - `bs` (from compute_balance_sheet) is only used as a fallback
for lines with no account-map entry (e.g. Deferred Revenue).
"""
ws = wb.create_sheet("Balance Sheet (FS)")
ws.column_dimensions["A"].width = 32
ws.column_dimensions["B"].width = 18
_write_cell(ws, 1, 1, title, bold=True)
_write_cell(ws, 2, 1, "Balance Sheet (Consolidated)", bold=True)
_write_cell(ws, 3, 1, f"As of {report_date}", bold=True)
if category_summary_refs:
net_income_formula = (
f"'1. Summary (Manual)'!D{category_summary_refs['total_revenue_row']}"
f"+'1. Summary (Manual)'!E{category_summary_refs['total_revenue_row']}"
f"-'1. Summary (Manual)'!D{category_summary_refs['total_expenses_row']}"
f"-'1. Summary (Manual)'!E{category_summary_refs['total_expenses_row']}"
)
else:
net_income_formula = None
row_by_key = {}
row = 5
for label, is_section, key in BALANCE_SHEET_LAYOUT:
if label is None and key is None:
row += 1
continue
if key == "__total_current_assets__":
f = "=" + "+".join(f"B{row_by_key[k]}" for k in ("Cash", "Accounts receivable", "Prepaids"))
c = ws.cell(row=row, column=2, value=f); c.font = BOLD_FONT; c.number_format = number_format
elif key == "__total_assets__":
_write_cell(ws, row, 1, "Total Assets", bold=True)
tca_row = row_by_key["__total_current_assets__"]
f = "=" + "+".join([f"B{tca_row}"] + [f"B{row_by_key[k]}" for k in ("Due from related companies", "Capital Assets")])
c = ws.cell(row=row, column=2, value=f); c.font = BOLD_FONT; c.number_format = number_format
elif key == "__total_current_liabilities__":
f = "=" + "+".join(f"B{row_by_key[k]}" for k in
("Due to related companies", "Accrued Liabilities", "Accounts Payable", "Deferred Revenue"))
c = ws.cell(row=row, column=2, value=f); c.font = BOLD_FONT; c.number_format = number_format
elif key == "__total_net_assets__":
f = f"=B{row_by_key['Unrestricted']}"
c = ws.cell(row=row, column=2, value=f); c.font = BOLD_FONT; c.number_format = number_format
elif key == "__total_liab_and_net_assets__":
_write_cell(ws, row, 1, "Total Liabilities & Net Assets", bold=True)
f = f"=B{row_by_key['__total_current_liabilities__']}+B{row_by_key['__total_net_assets__']}"
c = ws.cell(row=row, column=2, value=f); c.font = BOLD_FONT; c.number_format = number_format
elif key == "__balance_check__":
_write_cell(ws, row, 1, "Balance check (Assets − Liabilities & Net Assets, should be 0)", italic=True)
f = f"=B{row_by_key['__total_liab_and_net_assets__']}-B{row_by_key['__total_assets__']}"
c = ws.cell(row=row, column=2, value=f); c.font = Font(name=FONT_NAME, size=FONT_SIZE, italic=True); c.number_format = number_format
else:
_write_cell(ws, row, 1, label, bold=is_section)
if key is not None:
entry = account_map.get(key)
if entry and entry["codes"]:
base = _join_signed_terms(
[(f"SUMIF('{source_sheet_name}'!A:A,\"{code}:*\",'{source_sheet_name}'!{col}:{col})", sign)
for code, sign in entry["codes"] for col in ("D", "E")]
)
if key == "Unrestricted":
# Prefer a live cross-sheet reference to Category
# Summary's own totals; if that section isn't part of
# this run, fall back to the precomputed net_income
# figure passed in.
income_term = f"({net_income_formula})" if net_income_formula else str(net_income)
f = f"={base} + {income_term}"
else:
f = f"={base}"
else:
f = bs["values"].get(key, 0.0)
c = ws.cell(row=row, column=2, value=f)
c.font, c.number_format = REGULAR_FONT, number_format
row_by_key[key] = row
row += 1
return ws
def build_report_workbook(revenue_df, expense_df, output_path, sections, report_date, title,
use_cents=False):
"""
sections: {"category_summary": bool, "balance_sheet": bool}
Returns a summary dict for the API response / results screen.
"""
number_format = ACCOUNTING_FORMAT_CENTS if use_cents else ACCOUNTING_FORMAT_WHOLE
wb = openpyxl.Workbook()
wb.remove(wb.active)
# openpyxl writes formula cells with no cached result and leaves
# calcMode unset - fullCalcOnLoad="1" (openpyxl's default) forces a
# full recalc the first time the file is opened, which is why values
# show correctly on first view, but an unset calcMode is ambiguous to
# some apps rather than reliably read as automatic. Set both
# explicitly so edits to the TB sheets keep recalculating the Summary/
# Balance Sheet formulas afterwards too, not just on that first open.
wb.calculation.calcMode = "auto"
wb.calculation.fullCalcOnLoad = True
summary = {"reconciled": True}
category_summary_refs = None
if sections.get("category_summary", True):
grouped, source_totals = process_category_summary(revenue_df, expense_df)
cat_summary = build_category_summary_sheet(
wb, grouped["revenue"], grouped["expense"], source_totals, report_date, title,
number_format=number_format,
)
summary["revenue_total"] = cat_summary["revenue_total"]
summary["expense_total"] = cat_summary["expense_total"]
summary["surplus_deficit"] = cat_summary["surplus_deficit"]
summary["reconciled"] = (
summary["reconciled"] and cat_summary["reconciled"]
and cat_summary["revenue_match"] and cat_summary["expense_match"] and cat_summary["surplus_match"]
)
summary["reconciliation"] = {
"canada": {"report": cat_summary["report_canada"], "source": cat_summary["source_canada"]},
"us": {"report": cat_summary["report_us"], "source": cat_summary["source_us"]},
}
# Report (1. Summary (Manual)/Balance Sheet (FS)) vs. source-file
# figures for the three headline metrics, so the UI can show them
# side by side rather than only the combined Canada/US check above.
summary["headline_comparison"] = {
"income": {
"report": cat_summary["revenue_total"], "source": cat_summary["source_revenue_total"],
"match": cat_summary["revenue_match"],
},
"expenses": {
"report": cat_summary["expense_total"], "source": cat_summary["source_expense_total"],
"match": cat_summary["expense_match"],
},
"surplus": {
"report": cat_summary["surplus_deficit"], "source": cat_summary["source_surplus_deficit"],
"match": cat_summary["surplus_match"],
},
}
net_income = summary["surplus_deficit"]
category_summary_refs = {
"total_revenue_row": cat_summary["total_revenue_row"],
"total_expenses_row": cat_summary["total_expenses_row"],
}
else:
# Balance Sheet still needs Net Income even if Category Summary
# isn't being included in this run's output.
grouped, _ = process_category_summary(revenue_df, expense_df)
rev_total = round(grouped["revenue"]["canada"].sum() + grouped["revenue"]["us"].sum(), 2)
exp_total = round(grouped["expense"]["canada"].sum() + grouped["expense"]["us"].sum(), 2)
net_income = round(rev_total - exp_total, 2)
if sections.get("balance_sheet", True):
account_map = _load_account_map()
bs = compute_balance_sheet(revenue_df, expense_df, net_income, account_map=account_map)
build_balance_sheet_sheet(
wb, bs, net_income, report_date, title, account_map, REVENUE_SHEET_NAME,
category_summary_refs=category_summary_refs, number_format=number_format,
)
summary["balance_check"] = bs["balance_check"]
summary["balance_sheet_balanced"] = bool(abs(bs["balance_check"]) < RECONCILE_TOLERANCE)
summary["reconciled"] = summary["reconciled"] and summary["balance_sheet_balanced"]
# Bring the two uploaded files in as their own sheets - everything
# above ties back to these via formula rather than a baked-in number.
write_source_sheet(wb, revenue_df, REVENUE_SHEET_NAME)
write_source_sheet(wb, expense_df, EXPENSE_SHEET_NAME)
wb.save(output_path)
return summary

View File

@ -0,0 +1,107 @@
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
import pandas as pd
from .logic import (
classify_trial_balance_file,
full_file_balance,
build_report_workbook,
)
financial_reports_bp = Blueprint("financial_reports", __name__, url_prefix="/financial-reports")
BALANCE_TOLERANCE = 0.01
@financial_reports_bp.route("/")
def index():
return render_template("financial_reports/index.html")
@financial_reports_bp.route("/api/process", methods=["POST"])
def api_process():
files = [
f for key, f in request.files.items()
if key.startswith("trial_balance_file") and f.filename
]
if not files:
return jsonify({"error": "No files uploaded"}), 400
by_role = {}
unrecognized = []
for f in files:
path = os.path.join(
current_app.config["UPLOAD_FOLDER"],
f"{uuid.uuid4()}_{secure_filename(f.filename)}",
)
f.save(path)
try:
df = pd.read_excel(path)
except Exception as e:
return jsonify({"error": f"Could not read {f.filename}: {e}"}), 400
role = classify_trial_balance_file(df)
if role is None:
unrecognized.append(f.filename)
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}
missing = [r for r in ("revenue", "expense") if r not in by_role]
if missing:
parts = []
if "revenue" in missing:
parts.append("a revenue trial balance (needs a 'Revenue Category' column)")
if "expense" in missing:
parts.append("an expense trial balance (needs a 'Spend Category' column)")
msg = "Upload " + " and ".join(parts) + " to generate a report."
if unrecognized:
msg += f" Could not recognize: {', '.join(unrecognized)}."
return jsonify({"error": msg}), 400
for role in ("revenue", "expense"):
bal = full_file_balance(by_role[role]["df"])
if abs(bal) > BALANCE_TOLERANCE:
return jsonify({
"error": f"The {role} trial balance ({by_role[role]['name']}) doesn't sum to "
f"zero (off by {bal:,.2f}) — this doesn't look like a complete trial "
f"balance export. Re-export and try again.",
}), 400
sections = {
"category_summary": request.form.get("include_category_summary", "true") == "true",
"balance_sheet": request.form.get("include_balance_sheet", "true") == "true",
}
if not sections["category_summary"] and not sections["balance_sheet"]:
return jsonify({"error": "Include at least one report section"}), 400
report_date = request.form.get("report_date") or datetime.today().strftime("%Y-%m-%d")
title = request.form.get("title") or "Planeterra International Foundation (Group Consolidated)"
use_cents = request.form.get("use_cents", "false") == "true"
fname = f"Financial_Report_{report_date}.xlsx"
fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], fname)
try:
summary = build_report_workbook(
by_role["revenue"]["df"], by_role["expense"]["df"], fpath,
sections, report_date, title, use_cents=use_cents,
)
except ValueError as e:
return jsonify({"error": str(e)}), 400
return jsonify({"status": "ok", "filename": fname, **summary}), 200
@financial_reports_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

@ -26,6 +26,7 @@ services:
- ./outputs:/app/outputs
- ./app/tools/eib/merchant_lookup.csv:/app/app/tools/eib/merchant_lookup.csv
- ./app/tools/donor_report/donor_merge_map.csv:/app/app/tools/donor_report/donor_merge_map.csv
- ./app/tools/financial_reports/balance_sheet_account_map.csv:/app/app/tools/financial_reports/balance_sheet_account_map.csv
environment:
- FLASK_ENV=production
- DOCLING_URL=http://docling:5001

View File

@ -0,0 +1,561 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Financial Reports — 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); }
main {
position: relative; z-index: 1;
flex: 1;
max-width: 760px;
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; max-width: 560px; }
.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: default;
transition: all .2s;
position: relative;
}
.file-zone:hover, .file-zone.drag-over { border-color: var(--cyan); background: var(--cyan-glow); }
.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; }
.tb-file-list { list-style: none; margin-top: 12px; }
.tb-file-list li {
display: flex; align-items: center; justify-content: space-between;
padding: 8px 12px; border: 1px solid var(--border);
border-radius: 6px; margin-bottom: 6px;
font-family: var(--mono); font-size: 11px; color: var(--w2);
background: var(--w5);
}
.tb-file-list li span { color: var(--cyan); margin-right: 8px; }
.tb-remove { background: none; border: none; cursor: pointer; color: var(--w3); font-size: 14px; padding: 0 4px; transition: color .15s; }
.tb-remove:hover { color: var(--red); }
.field-row { display: flex; gap: 12px; margin-bottom: 14px; flex-wrap: wrap; }
.field { flex: 1; min-width: 200px; }
.field label { display: block; font-size: 11px; color: var(--w3); margin-bottom: 6px; }
.field input[type="text"], .field input[type="date"] {
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); }
.check-row { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; cursor: pointer; user-select: none; }
.checkbox {
width: 18px; height: 18px; border-radius: 5px; border: 1px solid var(--border);
background: var(--w5); display: flex; align-items: center; justify-content: center;
flex-shrink: 0; transition: all .15s;
}
.checkbox.checked { background: var(--cyan-dim); border-color: var(--border-c); }
.checkbox svg { width: 11px; height: 11px; color: var(--cyan); display: none; }
.checkbox.checked svg { display: block; }
.check-label { font-size: 13px; color: var(--w2); }
.check-label strong { color: var(--w1); }
.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: 6px;
}
.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;
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; }
.stats-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 16px; }
.stat-box { background: var(--w5); border: 1px solid var(--border); border-radius: 8px; padding: 12px; }
.stat-value { font-family: var(--mono); font-size: 17px; 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; }
.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); }
.compare-table { margin-bottom: 16px; }
.compare-row {
display: grid; grid-template-columns: 1.15fr 1fr 1fr 76px; gap: 10px; align-items: center;
padding: 9px 0; border-bottom: 1px solid var(--w5);
}
.compare-row:last-child { border-bottom: none; }
.compare-row.compare-header {
border-bottom: 1px solid var(--border); padding-bottom: 8px;
font-family: var(--mono); font-size: 9.5px; letter-spacing: .08em;
text-transform: uppercase; color: var(--w3);
}
.compare-label { font-size: 12px; color: var(--w2); }
.compare-value { font-family: var(--mono); font-size: 12px; color: var(--w1); text-align: right; }
.compare-header .compare-value { 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>
Financial <span>Reports</span>
</a>
</header>
<main>
<div class="page-title">
<div class="eyebrow">Planeterra International Foundation</div>
<h1>Financial Reports</h1>
<p>Upload the revenue and expense trial balances to generate a Category Summary and Balance Sheet snapshot.</p>
</div>
<div class="card">
<div class="card-label">Trial Balance Files</div>
<div class="file-zone" id="tbZone">
<input type="file" id="tbFileInput" accept=".xlsx,.xls" multiple style="display:none">
<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="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>
<ul class="tb-file-list" id="tbFileList"></ul>
</div>
<div class="card">
<div class="card-label">Report Options</div>
<div class="check-row" id="checkCategorySummary">
<div class="checkbox checked">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20,6 9,17 4,12"/></svg>
</div>
<div class="check-label"><strong>Category Summary</strong> — Revenue &amp; Expense by Account/Category/Project Code</div>
</div>
<div class="check-row" id="checkBalanceSheet">
<div class="checkbox checked">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20,6 9,17 4,12"/></svg>
</div>
<div class="check-label"><strong>Balance Sheet</strong> — Assets / Liabilities / Net Assets snapshot</div>
</div>
<div class="check-row" id="checkCents" style="margin-top:14px">
<div class="checkbox">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20,6 9,17 4,12"/></svg>
</div>
<div class="check-label">Show cents (default: whole dollars)</div>
</div>
<div class="field-row" style="margin-top:16px">
<div class="field">
<label for="reportDate">Report Date</label>
<input type="date" id="reportDate">
</div>
<div class="field">
<label for="reportTitle">Report Title</label>
<input type="text" id="reportTitle" value="Planeterra International Foundation (Group Consolidated)">
</div>
</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" 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">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="statRevenue">—</div>
<div class="stat-label">Total Revenue</div>
</div>
<div class="stat-box">
<div class="stat-value" id="statExpense">—</div>
<div class="stat-label">Total Expense</div>
</div>
<div class="stat-box">
<div class="stat-value" id="statSurplus">—</div>
<div class="stat-label">Surplus / (Deficit)</div>
</div>
<div class="stat-box">
<div class="stat-value" id="statBalanceCheck">—</div>
<div class="stat-label">Balance Sheet Check</div>
</div>
</div>
<div id="headlineCompareSection" style="display:none">
<div class="card-label" style="margin-top:4px">Report vs. Source Files</div>
<div class="compare-table">
<div class="compare-row compare-header">
<span></span><span class="compare-value">Report</span><span class="compare-value">Source Files</span><span></span>
</div>
<div class="compare-row">
<span class="compare-label">Total Income</span>
<span class="compare-value" id="cmpIncomeReport">—</span>
<span class="compare-value" id="cmpIncomeSource">—</span>
<span class="recon-badge" id="cmpIncomeBadge">—</span>
</div>
<div class="compare-row">
<span class="compare-label">Total Expenses</span>
<span class="compare-value" id="cmpExpensesReport">—</span>
<span class="compare-value" id="cmpExpensesSource">—</span>
<span class="recon-badge" id="cmpExpensesBadge">—</span>
</div>
<div class="compare-row">
<span class="compare-label">Surplus / (Deficit)</span>
<span class="compare-value" id="cmpSurplusReport">—</span>
<span class="compare-value" id="cmpSurplusSource">—</span>
<span class="recon-badge" id="cmpSurplusBadge">—</span>
</div>
</div>
</div>
<div id="reconSection" style="display:none">
<div class="card-label" style="margin-top:4px">Reconciliation to Uploaded Files</div>
<div id="reconRows"></div>
</div>
<button class="btn btn-primary" id="downloadBtn" style="margin-top:16px">Download Report</button>
</div>
</main>
<footer>
Built by <a href="https://undodesigns.com" target="_blank">Undo Designs</a> · Financial Reports v1
</footer>
<script>
const $ = id => document.getElementById(id);
$('reportDate').valueAsDate = new Date();
// ── Checkboxes ──────────────────────────────────────────────────────────────
function toggleCheck(rowId) {
$(rowId).querySelector('.checkbox').classList.toggle('checked');
}
$('checkCategorySummary').addEventListener('click', () => toggleCheck('checkCategorySummary'));
$('checkBalanceSheet').addEventListener('click', () => toggleCheck('checkBalanceSheet'));
$('checkCents').addEventListener('click', () => toggleCheck('checkCents'));
function isChecked(rowId) { return $(rowId).querySelector('.checkbox').classList.contains('checked'); }
// ── Multi-file upload ──────────────────────────────────────────────────────
const tbFiles = [];
function renderFileList() {
const list = $('tbFileList');
list.innerHTML = '';
tbFiles.forEach((file, idx) => {
const li = document.createElement('li');
li.innerHTML = `<span>${idx + 1}</span>${file.name}
<button class="tb-remove" data-idx="${idx}" title="Remove">✕</button>`;
list.appendChild(li);
});
list.querySelectorAll('.tb-remove').forEach(btn => {
btn.addEventListener('click', () => {
tbFiles.splice(+btn.dataset.idx, 1);
renderFileList();
$('processBtn').disabled = tbFiles.length === 0;
});
});
$('tbDropLabel').innerHTML = tbFiles.length
? `<strong>${tbFiles.length} file${tbFiles.length > 1 ? 's' : ''} selected</strong> — <span style="color:var(--cyan);cursor:pointer" id="tbBrowseBtn">add more</span>`
: `<strong>Drop trial balance files here</strong> or <span style="color:var(--cyan);cursor:pointer" id="tbBrowseBtn">browse</span>`;
document.getElementById('tbBrowseBtn')?.addEventListener('click', () => $('tbFileInput').click());
}
$('tbBrowseBtn').addEventListener('click', () => $('tbFileInput').click());
$('tbFileInput').addEventListener('change', () => {
Array.from($('tbFileInput').files).forEach(f => {
if (!tbFiles.find(x => x.name === f.name)) tbFiles.push(f);
});
$('tbFileInput').value = '';
$('processBtn').disabled = tbFiles.length === 0;
renderFileList();
});
const zone = $('tbZone');
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');
Array.from(e.dataTransfer.files)
.filter(f => f.name.endsWith('.xlsx') || f.name.endsWith('.xls'))
.forEach(f => { if (!tbFiles.find(x => x.name === f.name)) tbFiles.push(f); });
$('processBtn').disabled = tbFiles.length === 0;
renderFileList();
});
// ── Process ───────────────────────────────────────────────────────────────
let lastFilename = '';
function fmtMoney(n) {
const sign = n < 0 ? '-' : '';
return sign + '$' + Math.abs(n).toLocaleString('en-US', {minimumFractionDigits: 2});
}
$('processBtn').addEventListener('click', async () => {
if (tbFiles.length === 0) return;
$('processBtn').disabled = true;
$('spinner').classList.add('visible');
$('errorNote').classList.remove('visible');
$('resultCard').classList.remove('visible');
const fd = new FormData();
tbFiles.forEach((f, i) => fd.append(`trial_balance_file_${i}`, f));
fd.append('include_category_summary', isChecked('checkCategorySummary'));
fd.append('include_balance_sheet', isChecked('checkBalanceSheet'));
fd.append('use_cents', isChecked('checkCents'));
fd.append('report_date', $('reportDate').value);
fd.append('title', $('reportTitle').value);
try {
const r = await fetch('/financial-reports/api/process', { method: 'POST', body: fd });
const d = await r.json();
if (d.status === 'ok') {
lastFilename = d.filename;
$('resultSub').textContent = d.filename;
$('statRevenue').textContent = 'revenue_total' in d ? fmtMoney(d.revenue_total) : '—';
$('statExpense').textContent = 'expense_total' in d ? fmtMoney(d.expense_total) : '—';
const surplusEl = $('statSurplus');
if ('surplus_deficit' in d) {
surplusEl.textContent = fmtMoney(d.surplus_deficit);
surplusEl.className = 'stat-value ' + (d.surplus_deficit >= 0 ? 'positive' : 'negative');
} else {
surplusEl.textContent = '—'; surplusEl.className = 'stat-value';
}
const balEl = $('statBalanceCheck');
if ('balance_check' in d) {
balEl.textContent = fmtMoney(d.balance_check);
balEl.className = 'stat-value ' + (d.balance_sheet_balanced ? 'positive' : 'negative');
} else {
balEl.textContent = 'n/a'; balEl.className = 'stat-value';
}
if (d.headline_comparison) {
$('headlineCompareSection').style.display = '';
for (const [key, prefix] of [['income', 'cmpIncome'], ['expenses', 'cmpExpenses'], ['surplus', 'cmpSurplus']]) {
const m = d.headline_comparison[key];
$(prefix + 'Report').textContent = fmtMoney(m.report);
$(prefix + 'Source').textContent = fmtMoney(m.source);
const badge = $(prefix + 'Badge');
badge.textContent = m.match ? 'MATCH' : 'MISMATCH';
badge.className = 'recon-badge ' + (m.match ? 'ok' : 'warn');
}
} else {
$('headlineCompareSection').style.display = 'none';
}
if (d.reconciliation) {
$('reconSection').style.display = '';
const rows = [];
for (const [label, entity] of [['Canada', d.reconciliation.canada], ['US', d.reconciliation.us]]) {
const ok = Math.abs(entity.report - entity.source) < 0.01;
rows.push(`<div class="recon-row"><span>${label}: report ${fmtMoney(entity.report)} vs source ${fmtMoney(entity.source)}</span>
<span class="recon-badge ${ok ? 'ok' : 'warn'}">${ok ? 'MATCH' : 'MISMATCH'}</span></div>`);
}
$('reconRows').innerHTML = rows.join('');
} else {
$('reconSection').style.display = 'none';
}
const icon = $('resultIcon');
if (d.reconciled) {
icon.className = 'result-icon ok';
$('resultTitle').textContent = 'Report generated — reconciled';
} else {
icon.className = 'result-icon warn';
$('resultTitle').textContent = 'Report generated — check reconciliation';
}
$('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 = '/financial-reports/api/download/' + encodeURIComponent(lastFilename);
});
</script>
</body>
</html>