450 lines
20 KiB
Python
450 lines
20 KiB
Python
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",
|
||
)
|
||
|
||
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)
|
||
TITLE_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 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 the primary grouping/subtotal key, sorted by account number
|
||
(string-sorting the full value works here since every code in this
|
||
chart of accounts is the same 5-digit width). 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"] = d["Ledger Account"].astype(str).str.strip()
|
||
d["category"] = d[cat_col].fillna("(Uncategorized)")
|
||
d["project_code"] = 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)]
|
||
results[key] = grouped.reset_index(drop=True)
|
||
|
||
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. 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_category_section(ws, start_row, df, canada_col, us_col, total_col, number_format):
|
||
"""
|
||
Write one section (Revenue or Expenses): a bold subtotal row per
|
||
account (SUM formula over that account's own detail rows), sorted by
|
||
account number - string-sorting the full "code:name" value works
|
||
since every code in this chart of accounts is the same width - then
|
||
its detail rows sorted by strategic area then full project code.
|
||
Returns (list of account-subtotal row numbers, next free row,
|
||
section Canada/US raw totals).
|
||
"""
|
||
row = start_row
|
||
subtotal_rows = []
|
||
canada_total = us_total = 0.0
|
||
|
||
if df.empty:
|
||
return subtotal_rows, row, 0.0, 0.0
|
||
|
||
for account in sorted(df["account"].unique()):
|
||
acct_df = df[df["account"] == account].sort_values(["slob", "project_code"])
|
||
first_row = row + 1 # detail rows start after this account's own subtotal row
|
||
subtotal_row = row
|
||
row += 1
|
||
|
||
for _, r in acct_df.iterrows():
|
||
canada = round(r["canada"], 2)
|
||
us = round(r["us"], 2)
|
||
_write_cell(ws, row, 1, account)
|
||
_write_cell(ws, row, 2, r["category"])
|
||
_write_cell(ws, row, 3, r["project_code"])
|
||
_write_cell(ws, row, canada_col, canada, number_format=number_format)
|
||
_write_cell(ws, row, us_col, us, number_format=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
|
||
last_row = row - 1
|
||
|
||
_write_cell(ws, subtotal_row, 1, account, bold=True)
|
||
for col in (canada_col, us_col, total_col):
|
||
letter = ws.cell(row=first_row, column=col).column_letter
|
||
c = ws.cell(row=subtotal_row, column=col, value=f"=SUM({letter}{first_row}:{letter}{last_row})")
|
||
c.font = BOLD_FONT
|
||
c.number_format = number_format
|
||
subtotal_rows.append(subtotal_row)
|
||
|
||
return 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("Category Summary")
|
||
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
|
||
)
|
||
|
||
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
|
||
)
|
||
|
||
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)
|
||
|
||
return {
|
||
"revenue_total": round(rev_canada + rev_us, 2),
|
||
"expense_total": round(exp_canada + exp_us, 2),
|
||
"reconciled": canada_ok and us_ok,
|
||
"report_canada": report_canada, "source_canada": source_canada,
|
||
"report_us": report_us, "source_us": source_us,
|
||
}
|
||
|
||
|
||
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, report_date, title, 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.
|
||
"""
|
||
ws = wb.create_sheet("Balance Sheet")
|
||
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)
|
||
|
||
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__":
|
||
_write_cell(ws, row, 2, bs["total_current_assets"], bold=True, number_format=number_format)
|
||
elif key == "__total_assets__":
|
||
_write_cell(ws, row, 1, "Total Assets", bold=True)
|
||
_write_cell(ws, row, 2, bs["total_assets"], bold=True, number_format=number_format)
|
||
elif key == "__total_current_liabilities__":
|
||
_write_cell(ws, row, 2, bs["total_current_liabilities"], bold=True, number_format=number_format)
|
||
elif key == "__total_net_assets__":
|
||
_write_cell(ws, row, 2, bs["total_net_assets"], bold=True, number_format=number_format)
|
||
elif key == "__total_liab_and_net_assets__":
|
||
_write_cell(ws, row, 1, "Total Liabilities & Net Assets", bold=True)
|
||
_write_cell(ws, row, 2, bs["total_liab_and_net_assets"], bold=True, number_format=number_format)
|
||
elif key == "__balance_check__":
|
||
_write_cell(ws, row, 1, "Balance check (Assets − Liabilities & Net Assets, should be 0)", italic=True)
|
||
_write_cell(ws, row, 2, bs["balance_check"], italic=True, number_format=number_format)
|
||
else:
|
||
_write_cell(ws, row, 1, label, bold=is_section)
|
||
if key is not None:
|
||
_write_cell(ws, row, 2, bs["values"].get(key, 0.0), number_format=number_format)
|
||
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)
|
||
|
||
summary = {"reconciled": True}
|
||
|
||
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"] = round(cat_summary["revenue_total"] - cat_summary["expense_total"], 2)
|
||
summary["reconciled"] = summary["reconciled"] and cat_summary["reconciled"]
|
||
summary["reconciliation"] = {
|
||
"canada": {"report": cat_summary["report_canada"], "source": cat_summary["source_canada"]},
|
||
"us": {"report": cat_summary["report_us"], "source": cat_summary["source_us"]},
|
||
}
|
||
net_income = summary["surplus_deficit"]
|
||
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):
|
||
bs = compute_balance_sheet(revenue_df, expense_df, net_income)
|
||
build_balance_sheet_sheet(wb, bs, report_date, title, 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"]
|
||
|
||
wb.save(output_path)
|
||
return summary
|