equals-wd-card-expense-proc.../app/tools/financial_reports/routes.py

609 lines
28 KiB
Python

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,
load_gl_dump,
load_budget_file,
find_unmapped_bs_accounts,
append_to_account_map,
find_unmapped_budget_lines,
append_to_budget_key_map,
process_category_summary,
budget_is_detailed,
find_unmatched_budget_projects,
find_budget_rows_missing_account,
load_stored_budget_file,
save_stored_budget_file,
stored_budget_file_status,
STORED_BUDGET_PATH,
budget_options_by_account,
find_unmapped_tb_categories,
find_unmapped_tb_projects,
category_mapping_lookup,
project_mapping_lookup,
list_category_mappings,
upsert_category_mapping,
upsert_category_mappings,
delete_category_mapping,
list_project_mappings,
upsert_project_mapping,
upsert_project_mappings,
delete_project_mapping,
)
financial_reports_bp = Blueprint("financial_reports", __name__, url_prefix="/financial-reports")
BALANCE_TOLERANCE = 0.01
VALID_SECTIONS = {"Assets", "Liabilities", "NetAssets"}
# Holds the parsed inputs for a run that's paused awaiting account-map or
# budget-key-map review (see find_unmapped_bs_accounts/
# find_unmapped_budget_lines), keyed by a one-time token, so the confirm
# endpoints can finish the run without a re-upload. Same explicit single-
# job/single-user shortcut as the EIB tool's LAST_RESULT - not safe for
# concurrent runs, not meant to be.
PENDING_RUNS = {}
def _generate_report(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents):
fname = f"Financial_Report_{report_date}.xlsx"
fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], fname)
try:
summary = build_report_workbook(
revenue_df, expense_df, fpath,
sections, report_date, title, use_cents=use_cents,
gl_df=schedules_gl_df, budget_df=budget_df, budget_file_path=budget_file_path,
)
except ValueError as e:
return jsonify({"error": str(e)}), 400
summary["schedules_included"] = schedules_gl_df is not None
summary["budget_included"] = budget_df is not None
return jsonify({"status": "ok", "filename": fname, **summary}), 200
def _stash_pending_run(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents):
token = str(uuid.uuid4())
PENDING_RUNS[token] = {
"revenue_df": revenue_df, "expense_df": expense_df,
"schedules_gl_df": schedules_gl_df, "budget_df": budget_df, "budget_file_path": budget_file_path,
"sections": sections, "report_date": report_date, "title": title, "use_cents": use_cents,
}
return token
def _check_gates_and_respond(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents,
skip_accounts_gate=False, skip_budget_gate=False, skip_budget_projects_gate=False,
skip_category_mapping_gate=False, skip_project_mapping_gate=False):
"""
Independent review gates, checked in order, each pausing the run
(see _stash_pending_run) rather than silently dropping data: unmapped
Balance Sheet accounts (find_unmapped_bs_accounts), then - only for a
detailed-format Budget file (see budget_is_detailed) - TB categories
with no home in the budget (find_unmapped_tb_categories), then TB
project codes with no home in the budget on the now-recategorized
picture (find_unmapped_tb_projects), then unmatched budget projects
(find_unmatched_budget_projects) - or, for the older Budget format,
unmapped budget lines (find_unmapped_budget_lines). All confirm
endpoints call back into this same function after applying their own
mapping (or, for budget_projects, just acknowledging), so a run
needing more than one review naturally proceeds from one to the next
instead of skipping the rest.
skip_*_gate: set by a confirm endpoint for the gate it just handled,
so that submitting fewer mappings than there were unmapped items
(deliberately leaving some unmapped for now) proceeds with the run
instead of re-showing the identical review - confirmed as a real bug
for the accounts/budget_lines gates: without this, an empty or
partial mappings list looped forever, since the same items are still
genuinely unmapped in the CSV and would otherwise be found again.
The OTHER gates are still checked normally either way.
"""
if sections["balance_sheet"] and not skip_accounts_gate:
unmapped_accounts = find_unmapped_bs_accounts(revenue_df)
if unmapped_accounts:
token = _stash_pending_run(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents)
return jsonify({
"status": "needs_review", "review_type": "accounts",
"token": token, "unmapped_accounts": unmapped_accounts,
}), 200
if budget_df is not None and budget_is_detailed(budget_df) and not skip_category_mapping_gate:
unmapped_categories = find_unmapped_tb_categories(revenue_df, expense_df, budget_df)
if unmapped_categories:
token = _stash_pending_run(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents)
return jsonify({
"status": "needs_review", "review_type": "category_mapping",
"token": token, "unmapped_categories": unmapped_categories,
}), 200
if budget_df is not None and budget_is_detailed(budget_df) and not skip_project_mapping_gate:
unmapped_projects = find_unmapped_tb_projects(revenue_df, expense_df, budget_df)
if unmapped_projects:
token = _stash_pending_run(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents)
return jsonify({
"status": "needs_review", "review_type": "project_mapping",
"token": token, "unmapped_projects": unmapped_projects,
}), 200
if budget_df is not None and budget_is_detailed(budget_df) and not skip_budget_projects_gate:
grouped, _ = process_category_summary(
revenue_df, expense_df,
category_map=category_mapping_lookup(), project_map=project_mapping_lookup(),
)
unmatched_budget_projects = find_unmatched_budget_projects(budget_df, grouped, report_date)
missing_account_rows = find_budget_rows_missing_account(budget_df, report_date)
if unmatched_budget_projects or missing_account_rows:
token = _stash_pending_run(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents)
return jsonify({
"status": "needs_review", "review_type": "budget_projects",
"token": token, "unmatched_budget_projects": unmatched_budget_projects,
"missing_account_rows": missing_account_rows,
}), 200
if budget_df is not None and not budget_is_detailed(budget_df) and not skip_budget_gate:
unmapped_budget_lines = find_unmapped_budget_lines(budget_df, report_date)
if unmapped_budget_lines:
token = _stash_pending_run(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents)
return jsonify({
"status": "needs_review", "review_type": "budget_lines",
"token": token, "unmapped_budget_lines": unmapped_budget_lines,
}), 200
return _generate_report(revenue_df, expense_df, schedules_gl_df, budget_df, budget_file_path, sections, report_date, title, use_cents)
@financial_reports_bp.route("/")
def index():
return render_template("financial_reports/index.html")
@financial_reports_bp.route("/api/budget-status")
def api_budget_status():
return jsonify(stored_budget_file_status()), 200
@financial_reports_bp.route("/api/budget-options")
def api_budget_options():
"""Every account's real budget categories/projects, from the
stored Budget file (see budget_options_by_account) - powers the
Manage Mappings panel's inline reassignment dropdowns, which (unlike
the review gates) aren't tied to any particular TB upload."""
return jsonify({"by_account": budget_options_by_account(load_stored_budget_file())}), 200
@financial_reports_bp.route("/api/upload-budget", methods=["POST"])
def api_upload_budget():
f = request.files.get("budget_file")
if not f or not f.filename:
return jsonify({"error": "Upload a Budget file"}), 400
path = os.path.join(current_app.config["UPLOAD_FOLDER"], f"{uuid.uuid4()}_{secure_filename(f.filename)}")
f.save(path)
try:
save_stored_budget_file(path)
except ValueError as e:
return jsonify({"error": str(e)}), 400
finally:
os.remove(path)
return jsonify({"status": "ok", **stored_budget_file_status()}), 200
@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 = {}
gl_dump = None # {"df": ..., "name": ...} - optional, enables per-account supporting schedules
budget_dump = None # {"df": ..., "name": ...} - optional, enables Budget vs Actual
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 not None:
if role in by_role:
return jsonify({
"error": f"Got two {role} trial balance files "
f"({by_role[role]['name']}, {f.filename}) — upload exactly one of each.",
}), 400
by_role[role] = {"df": df, "name": f.filename}
continue
# Not a trial balance - see if it's a GL Dump (enables per-account
# Balance Sheet supporting schedules, optional) before giving up.
gl_df = load_gl_dump(path)
if gl_df is not None:
if gl_dump is not None:
return jsonify({
"error": f"Got two GL Dump files ({gl_dump['name']}, {f.filename}) — "
f"upload at most one.",
}), 400
gl_dump = {"df": gl_df, "name": f.filename}
continue
# Not a GL Dump either - see if it's a Budget file (enables
# Budget vs Actual, optional) before giving up.
budget_df = load_budget_file(path)
if budget_df is not None:
if budget_dump is not None:
return jsonify({
"error": f"Got two Budget files ({budget_dump['name']}, {f.filename}) — "
f"upload at most one.",
}), 400
budget_dump = {"df": budget_df, "name": f.filename, "path": path}
continue
unrecognized.append(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
include_schedules = request.form.get("include_schedules", "true") == "true"
include_budget = request.form.get("include_budget", "true") == "true"
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"
schedules_gl_df = gl_dump["df"] if (gl_dump is not None and include_schedules) else None
# A budget file uploaded THIS run takes precedence (a deliberate
# one-off override); otherwise, if the box is checked, fall back to
# whatever's persisted via /api/upload-budget - the whole point being
# nobody has to re-upload the same Budget file on every single run.
# budget_file_path tracks the real .xlsx behind budget_df either way
# (this run's own temp upload, or the stored file) - see
# build_report_workbook's budget_file_path for what it's used for.
budget_df = None
budget_file_path = None
if include_budget:
if budget_dump is not None:
budget_df = budget_dump["df"]
budget_file_path = budget_dump["path"]
else:
budget_df = load_stored_budget_file()
budget_file_path = STORED_BUDGET_PATH if os.path.exists(STORED_BUDGET_PATH) else None
return _check_gates_and_respond(
by_role["revenue"]["df"], by_role["expense"]["df"], schedules_gl_df, budget_df, budget_file_path,
sections, report_date, title, use_cents,
)
@financial_reports_bp.route("/api/confirm-accounts", methods=["POST"])
def api_confirm_accounts():
data = request.get_json(silent=True) or {}
token = data.get("token")
mappings = data.get("mappings", [])
# Look up without popping yet: a validation failure below must leave
# the pending run intact so the user can correct the payload and
# resubmit the same token, rather than burning their one confirm
# attempt on a rejected request (confirmed as a real bug: an invalid
# first submission silently invalidated the token, making a
# corrected retry fail with "session expired" even though the run
# was still sitting right there).
pending = PENDING_RUNS.get(token)
if pending is None:
return jsonify({
"error": "This review session has expired or wasn't found - please re-upload and try again.",
}), 400
for m in mappings:
code = str(m.get("account_code", "")).strip()
line_item = str(m.get("line_item", "")).strip()
section = m.get("section")
sign = m.get("sign")
if not code or not line_item:
return jsonify({"error": f"Every included account needs a line item name (account {code or '?'})."}), 400
if section not in VALID_SECTIONS:
return jsonify({"error": f"Invalid section '{section}' for account {code}."}), 400
if sign not in (1, -1):
return jsonify({"error": f"Invalid sign '{sign}' for account {code} - must be 1 or -1."}), 400
del PENDING_RUNS[token]
if mappings:
append_to_account_map(mappings)
return _check_gates_and_respond(
pending["revenue_df"], pending["expense_df"], pending["schedules_gl_df"], pending["budget_df"], pending["budget_file_path"],
pending["sections"], pending["report_date"], pending["title"], pending["use_cents"],
skip_accounts_gate=True,
)
@financial_reports_bp.route("/api/confirm-budget-lines", methods=["POST"])
def api_confirm_budget_lines():
data = request.get_json(silent=True) or {}
token = data.get("token")
mappings = data.get("mappings", [])
pending = PENDING_RUNS.get(token)
if pending is None:
return jsonify({
"error": "This review session has expired or wasn't found - please re-upload and try again.",
}), 400
for m in mappings:
gl_name = str(m.get("budget_gl_name", "")).strip()
account = str(m.get("summary_account", "")).strip()
if not gl_name or not account:
return jsonify({"error": f"Every included budget line needs a target account (line {gl_name or '?'})."}), 400
del PENDING_RUNS[token]
if mappings:
append_to_budget_key_map(mappings)
return _check_gates_and_respond(
pending["revenue_df"], pending["expense_df"], pending["schedules_gl_df"], pending["budget_df"], pending["budget_file_path"],
pending["sections"], pending["report_date"], pending["title"], pending["use_cents"],
skip_budget_gate=True,
)
@financial_reports_bp.route("/api/confirm-budget-projects", methods=["POST"])
def api_confirm_budget_projects():
"""
Acknowledge-only gate (see find_unmatched_budget_projects) - unlike
the other two gates, there's no mapping to add: a detailed-format
Budget file already self-describes its (account, category, project)
key, so a flagged line is either a genuinely new/not-yet-spent
project (nothing to fix - proceed as-is) or a real typo that needs
correcting in the source Budget workbook itself, not patched around
here. This endpoint just needs the token to resume the run.
"""
data = request.get_json(silent=True) or {}
token = data.get("token")
pending = PENDING_RUNS.get(token)
if pending is None:
return jsonify({
"error": "This review session has expired or wasn't found - please re-upload and try again.",
}), 400
del PENDING_RUNS[token]
return _check_gates_and_respond(
pending["revenue_df"], pending["expense_df"], pending["schedules_gl_df"], pending["budget_df"], pending["budget_file_path"],
pending["sections"], pending["report_date"], pending["title"], pending["use_cents"],
skip_budget_projects_gate=True,
)
@financial_reports_bp.route("/api/confirm-category-mapping", methods=["POST"])
def api_confirm_category_mapping():
"""
Resolve the category_mapping gate (see find_unmapped_tb_categories):
each decision either maps a TB category to an existing budget
category (persisted to category_reassignment_map.csv, applied on
every future run - see upsert_category_mapping) or explicitly leaves
it as-is (also persisted, as a blank target, so it's never
re-flagged). A category simply left off the decisions list entirely
is NOT recorded either way, so it WILL be re-flagged next time -
the difference between "reviewed, leave as is" and "didn't get to
it yet". Each decision can ALSO carry a project reassignment
alongside the category one - symmetric with
api_confirm_project_mapping's category_action - since the row's
project is shown right there for context (see
find_unmapped_tb_categories). project_action defaults to "keep" (no
project change); "map" applies target_project via
upsert_project_mapping, the exact same mechanism the
project_mapping gate itself uses.
"""
data = request.get_json(silent=True) or {}
token = data.get("token")
decisions = data.get("decisions", [])
pending = PENDING_RUNS.get(token)
if pending is None:
return jsonify({
"error": "This review session has expired or wasn't found - please re-upload and try again.",
}), 400
for d in decisions:
account_code = str(d.get("account_code", "")).strip()
source = str(d.get("source", "")).strip()
action = d.get("action")
if not account_code or not source:
return jsonify({"error": "Every decision needs an account and a category."}), 400
if action not in ("map", "leave_as_is"):
return jsonify({"error": f"Invalid action '{action}' for '{source}'."}), 400
if action == "map" and not str(d.get("target_category", "")).strip():
return jsonify({"error": f"Pick a target category for '{source}'."}), 400
project_action = d.get("project_action", "keep")
if project_action not in ("keep", "map"):
return jsonify({"error": f"Invalid project_action '{project_action}' for '{source}'."}), 400
if project_action == "map" and not str(d.get("target_project", "")).strip():
return jsonify({"error": f"Pick a target project for '{source}'."}), 400
del PENDING_RUNS[token]
category_entries = [
(d["account_code"], d["source"], str(d.get("target_category", "")).strip() if d["action"] == "map" else "")
for d in decisions
]
upsert_category_mappings(category_entries)
project_entries = [
(d["account_code"], d.get("project", ""), str(d.get("target_project", "")).strip())
for d in decisions if d.get("project_action") == "map"
]
if project_entries:
upsert_project_mappings(project_entries)
return _check_gates_and_respond(
pending["revenue_df"], pending["expense_df"], pending["schedules_gl_df"], pending["budget_df"], pending["budget_file_path"],
pending["sections"], pending["report_date"], pending["title"], pending["use_cents"],
skip_category_mapping_gate=True,
)
@financial_reports_bp.route("/api/confirm-project-mapping", methods=["POST"])
def api_confirm_project_mapping():
"""
Project-code equivalent of api_confirm_category_mapping - see
find_unmapped_tb_projects/upsert_project_mapping. Each decision can
ALSO carry a category reassignment alongside the project one -
"keep it in the same category, or move it to another category" -
since the row's category is shown right there for context (see
find_unmapped_tb_projects). category_action defaults to "keep" (no
category change, just the project); "map" applies target_category
via upsert_category_mapping, the exact same mechanism the
category_mapping gate itself uses, just triggered from this screen
since the two decisions are naturally made together here.
"""
data = request.get_json(silent=True) or {}
token = data.get("token")
decisions = data.get("decisions", [])
pending = PENDING_RUNS.get(token)
if pending is None:
return jsonify({
"error": "This review session has expired or wasn't found - please re-upload and try again.",
}), 400
for d in decisions:
account_code = str(d.get("account_code", "")).strip()
source = str(d.get("source", "")).strip()
action = d.get("action")
if not account_code or not source:
return jsonify({"error": "Every decision needs an account and a project."}), 400
if action not in ("map", "leave_as_is"):
return jsonify({"error": f"Invalid action '{action}' for '{source}'."}), 400
if action == "map" and not str(d.get("target_project", "")).strip():
return jsonify({"error": f"Pick a target project for '{source}'."}), 400
category_action = d.get("category_action", "keep")
if category_action not in ("keep", "map"):
return jsonify({"error": f"Invalid category_action '{category_action}' for '{source}'."}), 400
if category_action == "map" and not str(d.get("target_category", "")).strip():
return jsonify({"error": f"Pick a target category for '{source}'."}), 400
del PENDING_RUNS[token]
project_entries = [
(d["account_code"], d["source"], str(d.get("target_project", "")).strip() if d["action"] == "map" else "")
for d in decisions
]
upsert_project_mappings(project_entries)
category_entries = [
(d["account_code"], d.get("category", ""), str(d.get("target_category", "")).strip())
for d in decisions if d.get("category_action") == "map"
]
if category_entries:
upsert_category_mappings(category_entries)
return _check_gates_and_respond(
pending["revenue_df"], pending["expense_df"], pending["schedules_gl_df"], pending["budget_df"], pending["budget_file_path"],
pending["sections"], pending["report_date"], pending["title"], pending["use_cents"],
skip_project_mapping_gate=True,
)
@financial_reports_bp.route("/api/category-mappings", methods=["GET", "POST"])
def api_category_mappings():
"""
GET: list every category reassignment on file (see
list_category_mappings). POST: add or update one directly - the
Manage Mappings panel's own affordance for editing decisions at any
time, independent of a run (unlike /api/confirm-category-mapping,
which only ever resolves items a review gate just surfaced).
"""
if request.method == "GET":
return jsonify({"mappings": list_category_mappings()}), 200
data = request.get_json(silent=True) or {}
account_code = str(data.get("account_code", "")).strip()
source = str(data.get("source", "")).strip()
if not account_code or not source:
return jsonify({"error": "account_code and source are required"}), 400
upsert_category_mapping(account_code, source, str(data.get("target", "")).strip())
return jsonify({"status": "ok", "mappings": list_category_mappings()}), 200
@financial_reports_bp.route("/api/category-mappings/delete", methods=["POST"])
def api_delete_category_mapping():
data = request.get_json(silent=True) or {}
account_code = str(data.get("account_code", "")).strip()
source = str(data.get("source", "")).strip()
if not account_code or not source:
return jsonify({"error": "account_code and source are required"}), 400
delete_category_mapping(account_code, source)
return jsonify({"status": "ok", "mappings": list_category_mappings()}), 200
@financial_reports_bp.route("/api/project-mappings", methods=["GET", "POST"])
def api_project_mappings():
"""Project-code equivalent of api_category_mappings."""
if request.method == "GET":
return jsonify({"mappings": list_project_mappings()}), 200
data = request.get_json(silent=True) or {}
account_code = str(data.get("account_code", "")).strip()
source = str(data.get("source", "")).strip()
if not account_code or not source:
return jsonify({"error": "account_code and source are required"}), 400
upsert_project_mapping(account_code, source, str(data.get("target", "")).strip())
return jsonify({"status": "ok", "mappings": list_project_mappings()}), 200
@financial_reports_bp.route("/api/project-mappings/delete", methods=["POST"])
def api_delete_project_mapping():
data = request.get_json(silent=True) or {}
account_code = str(data.get("account_code", "")).strip()
source = str(data.get("source", "")).strip()
if not account_code or not source:
return jsonify({"error": "account_code and source are required"}), 400
delete_project_mapping(account_code, source)
return jsonify({"status": "ok", "mappings": list_project_mappings()}), 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)