bettersight-statement-extra.../backend/services/excel_service.py

174 lines
7.2 KiB
Python

# Builds the Transactions + Summary Excel workbook, entirely in memory - callers decide where it ends up (an in-memory buffer streamed straight to the client, see routes/extraction.py's /api/export).
import openpyxl
from openpyxl.styles import Font
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)
ACCOUNTING_FORMAT = '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)'
_FLAGGED_INDEXES_BY_CHECK = {
"running_balance": "mismatches", "date_sanity": "issues", "structure_sanity": "issues",
"narrative_direction": "issues",
}
def _write_cell(ws, row, col, value, bold=False, number_format=None):
c = ws.cell(row=row, column=col, value=value)
c.font = BOLD_FONT if bold else REGULAR_FONT
if number_format:
c.number_format = number_format
return c
def _flagged_row_indexes(result):
"""{transaction_index: ["running_balance", ...]} - which checks
flagged which specific row, for the Transactions sheet's own flag
column."""
flags = {}
for check in result["checks"]:
key = _FLAGGED_INDEXES_BY_CHECK.get(check["name"])
if not key:
continue
for item in check.get(key, []):
idx = item.get("index")
if idx is not None:
flags.setdefault(idx, []).append(check["name"])
return flags
def build_workbook(result, title="Statement Extraction"):
"""
Builds the Transactions + Summary workbook in memory - never touches disk itself.
Data flow:
result (dict) - a pipeline_service.run()/recheck() result:
transactions, checks, status, period, etc.
title (str) - statement title shown on the Summary sheet
returns (openpyxl.Workbook) - the built, unsaved workbook
"""
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Transactions"
for col, width in zip("ABCDEF", (14, 60, 14, 16, 16, 16)):
ws.column_dimensions[col].width = width
headers = ["Date", "Description", "Amount", "Balance", "Status", "Check flags"]
for col, label in enumerate(headers, start=1):
_write_cell(ws, 1, col, label, bold=True)
flagged = _flagged_row_indexes(result)
row = 2
for i, t in enumerate(result["transactions"]):
_write_cell(ws, row, 1, t["date"])
_write_cell(ws, row, 2, t["description"])
_write_cell(ws, row, 3, t["amount"], number_format=ACCOUNTING_FORMAT)
_write_cell(ws, row, 4, t["balance"], number_format=ACCOUNTING_FORMAT)
_write_cell(ws, row, 5, t["status"])
_write_cell(ws, row, 6, ", ".join(flagged.get(i, [])))
row += 1
ws2 = wb.create_sheet("Summary")
for col, width in zip("AB", (30, 50)):
ws2.column_dimensions[col].width = width
_write_cell(ws2, 1, 1, title, bold=True)
r = 3
_write_cell(ws2, r, 1, "Status", bold=True)
_write_cell(ws2, r, 2, result["status"], bold=True)
r += 1
if result.get("period"):
_write_cell(ws2, r, 1, "Statement period")
_write_cell(ws2, r, 2, result["period"])
r += 1
if result.get("brought_forward_balance") is not None:
_write_cell(ws2, r, 1, "Statement's own balance brought forward")
_write_cell(ws2, r, 2, result["brought_forward_balance"], number_format=ACCOUNTING_FORMAT)
r += 1
r += 1
_write_cell(ws2, r, 1, "Check results", bold=True)
r += 1
for c in result["checks"]:
_write_cell(ws2, r, 1, c["name"])
_write_cell(ws2, r, 2, f"{c['outcome']}: {c['detail']}")
r += 1
# Optional - only written when the frontend actually sent a non-empty
# edit_log (extractionStore.js's own appendEditLogEntry, see
# CLAUDE.md's "R.5" entry) - an export with no edits made doesn't
# gain an empty sheet nobody asked for. docs/bankstatement.md
# section 8's own spec: "Excel: ... optional Edits sheet."
if result.get("edit_log"):
_write_edits_sheet(wb, result["edit_log"])
# Optional - only written when the frontend sent a non-empty
# categorization object (useCategorization.js's own
# summaryForExport, computed entirely client-side from the current
# project's categorizationRules - see CLAUDE.md's "Transaction
# categorization" entry). A project with no rules yet gains no empty
# sheet, same no-op-by-default discipline as edit_log above.
if result.get("categorization"):
_write_categorized_summary_sheet(wb, result["categorization"])
return wb
def _write_edits_sheet(wb, edit_log):
ws = wb.create_sheet("Edits")
for col, width in zip("ABCDEF", (8, 18, 30, 30, 20, 14)):
ws.column_dimensions[col].width = width
headers = ["Row", "Field", "Old value", "New value", "When", "Source"]
for col, label in enumerate(headers, start=1):
_write_cell(ws, 1, col, label, bold=True)
row = 2
for entry in edit_log:
# 1-based row number for a human reader, matching the
# Transactions sheet's own row numbering - entry["index"] is the
# same 0-based transaction index used everywhere else internally.
row_no = (entry.get("index") or 0) + 1
_write_cell(ws, row, 1, row_no)
_write_cell(ws, row, 2, entry.get("field"))
_write_cell(ws, row, 3, str(entry.get("oldValue")) if entry.get("oldValue") is not None else "")
_write_cell(ws, row, 4, str(entry.get("newValue")) if entry.get("newValue") is not None else "")
_write_cell(ws, row, 5, entry.get("at"))
_write_cell(ws, row, 6, entry.get("source"))
row += 1
def _write_categorized_summary_sheet(wb, categorization):
"""
{"matched": [{"accountingCategory", "bankDescriptions", "count",
"amount"}], "unmatched": [{"description", "count", "amount"}]} -
built entirely client-side (useCategorization.js), already plain
JSON. The unmatched section is always written, even when empty, so
an export with full coverage visibly shows zero unmatched rather
than silently omitting the section - same "never silently exclude
data" governing rule as everywhere else in this app.
"""
ws = wb.create_sheet("Categorized Summary")
for col, width in zip("ABCD", (24, 60, 10, 16)):
ws.column_dimensions[col].width = width
row = 1
for col, label in enumerate(["Accounting Category", "Bank Description(s)", "Count", "Amount"], start=1):
_write_cell(ws, row, col, label, bold=True)
row += 1
for g in categorization.get("matched", []):
_write_cell(ws, row, 1, g.get("accountingCategory"))
_write_cell(ws, row, 2, " / ".join(g.get("bankDescriptions", [])))
_write_cell(ws, row, 3, g.get("count"))
_write_cell(ws, row, 4, g.get("amount"), number_format=ACCOUNTING_FORMAT)
row += 1
row += 1
_write_cell(ws, row, 1, "Unmatched", bold=True)
row += 1
for col, label in enumerate(["Description", "Count", "Amount"], start=1):
_write_cell(ws, row, col, label, bold=True)
row += 1
for g in categorization.get("unmatched", []):
_write_cell(ws, row, 1, g.get("description"))
_write_cell(ws, row, 2, g.get("count"))
_write_cell(ws, row, 3, g.get("amount"), number_format=ACCOUNTING_FORMAT)
row += 1