Add transaction categorization (project-scoped, client-side rules)
A deliberate scope expansion past this product's original "does not categorize transactions" boundary: project-scoped categorizationRules (PocketBase), pure-JS matching (longest-pattern-wins, case-insensitive substring), a Categorization tab beside Transactions, and an optional "Categorized Summary" sheet in the Excel export. Categorization is computed live from current rules and never persisted on the document itself - only the rules persist. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
620944373a
commit
0c66edf48b
|
|
@ -101,6 +101,15 @@ def build_workbook(result, title="Statement Extraction"):
|
||||||
if result.get("edit_log"):
|
if result.get("edit_log"):
|
||||||
_write_edits_sheet(wb, result["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
|
return wb
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -124,3 +133,41 @@ def _write_edits_sheet(wb, edit_log):
|
||||||
_write_cell(ws, row, 5, entry.get("at"))
|
_write_cell(ws, row, 5, entry.get("at"))
|
||||||
_write_cell(ws, row, 6, entry.get("source"))
|
_write_cell(ws, row, 6, entry.get("source"))
|
||||||
row += 1
|
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
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,3 @@
|
||||||
|
from .routes import bank_statement_categorizer_bp
|
||||||
|
|
||||||
|
__all__ = ["bank_statement_categorizer_bp"]
|
||||||
|
|
@ -0,0 +1,419 @@
|
||||||
|
import os, re
|
||||||
|
import pdfplumber
|
||||||
|
import openpyxl
|
||||||
|
from openpyxl.styles import Font
|
||||||
|
|
||||||
|
import common
|
||||||
|
|
||||||
|
RULES_PATH = os.path.join(os.path.dirname(__file__), "description_rules.csv")
|
||||||
|
|
||||||
|
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);_(* "-"??_);_(@_)'
|
||||||
|
|
||||||
|
RECONCILE_TOLERANCE = 0.01
|
||||||
|
|
||||||
|
# RBC Business Account Statement's own column layout (confirmed against
|
||||||
|
# a real statement with pdfplumber - see _extract_words). Words are
|
||||||
|
# classified into a column by their own x-position, not by line order,
|
||||||
|
# since the table has no gridlines and the Balance column in particular
|
||||||
|
# is only populated on a day's LAST line (see _group_into_transactions).
|
||||||
|
# Values are right-aligned within each zone, so matching on x1 (the
|
||||||
|
# word's right edge) is what actually distinguishes "0.60" that's part
|
||||||
|
# of a fee-breakdown description ("Drs @ 0.60", x1 ~244 - nowhere near
|
||||||
|
# any zone) from a real column value. These three zones are wide enough
|
||||||
|
# to hold steady across the whole statement; the Date/Description split
|
||||||
|
# is NOT (confirmed for real: continuation pages shift their entire
|
||||||
|
# table ~27pt left of page 1's own margin, so a single fixed threshold
|
||||||
|
# there misreads "Misc" as date text on every continuation page) - see
|
||||||
|
# _date_col_max_x, computed fresh per page instead.
|
||||||
|
DEBIT_ZONE = (300, 400)
|
||||||
|
CREDIT_ZONE = (405, 500)
|
||||||
|
BALANCE_ZONE = (540, 600)
|
||||||
|
# pdfplumber's default word-gap threshold (x_tolerance=3) merges this
|
||||||
|
# statement's own words together ("Misc"+"Payment" have only a 2pt real
|
||||||
|
# gap) - confirmed by inspecting page.chars directly. 1.5 splits exactly
|
||||||
|
# on real word boundaries without over-splitting inside a single word
|
||||||
|
# (those gaps are consistently 0).
|
||||||
|
X_TOLERANCE = 1.5
|
||||||
|
_MONEY_RE = re.compile(r"^-?[\d,]+\.\d{2}$")
|
||||||
|
|
||||||
|
|
||||||
|
def _row_amount(text, x1):
|
||||||
|
"""None unless text is money-shaped AND positioned inside one of
|
||||||
|
the three real value columns - see the zone constants above."""
|
||||||
|
if not _MONEY_RE.match(text):
|
||||||
|
return None
|
||||||
|
value = float(text.replace(",", ""))
|
||||||
|
if DEBIT_ZONE[0] <= x1 <= DEBIT_ZONE[1]:
|
||||||
|
return "debit", value
|
||||||
|
if CREDIT_ZONE[0] <= x1 <= CREDIT_ZONE[1]:
|
||||||
|
return "credit", value
|
||||||
|
if BALANCE_ZONE[0] <= x1 <= BALANCE_ZONE[1]:
|
||||||
|
return "balance", value
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _date_col_max_x(words):
|
||||||
|
"""
|
||||||
|
The x-position splitting the Date column from the Description
|
||||||
|
column, derived from THIS page's own "Date"/"Description" header
|
||||||
|
words (the midpoint between them) - see the module-level comment on
|
||||||
|
why this can't be a fixed constant. Falls back to 85 (page 1's own
|
||||||
|
layout) if a page is ever missing its header row entirely.
|
||||||
|
"""
|
||||||
|
date_w = next((w for w in words if w["text"] == "Date"), None)
|
||||||
|
desc_w = next((w for w in words if w["text"] == "Description"), None)
|
||||||
|
if date_w and desc_w:
|
||||||
|
return (date_w["x1"] + desc_w["x0"]) / 2
|
||||||
|
return 85
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_rows(page):
|
||||||
|
"""
|
||||||
|
One dict per physical line on this page: {"top", "date", "desc",
|
||||||
|
"debit", "credit", "balance"}. Words are grouped into lines by their
|
||||||
|
"top" coordinate (small tolerance - pdfplumber gives highly
|
||||||
|
consistent values per visual row in this statement), then each
|
||||||
|
word is bucketed into Date/Description/Debit/Credit/Balance by
|
||||||
|
position (see _date_col_max_x / _row_amount).
|
||||||
|
"""
|
||||||
|
# Some bank-generated PDFs fake bold text by printing it twice at
|
||||||
|
# the exact same position (confirmed here: a continuation page's
|
||||||
|
# repeated date label, e.g. "14 Sep" at the top of a day's block
|
||||||
|
# that spans a page break) - left alone, pdfplumber's word-builder
|
||||||
|
# interleaves the duplicate characters into garbage ("1144 SSeepp").
|
||||||
|
# dedupe_chars() is pdfplumber's own fix for exactly this.
|
||||||
|
page = page.dedupe_chars()
|
||||||
|
words = page.extract_words(x_tolerance=X_TOLERANCE)
|
||||||
|
date_col_max_x = _date_col_max_x(words)
|
||||||
|
lines = {}
|
||||||
|
for w in words:
|
||||||
|
key = round(w["top"])
|
||||||
|
lines.setdefault(key, []).append(w)
|
||||||
|
|
||||||
|
rows = []
|
||||||
|
for top in sorted(lines.keys()):
|
||||||
|
line_words = sorted(lines[top], key=lambda w: w["x0"])
|
||||||
|
date_parts, desc_parts = [], []
|
||||||
|
debit = credit = balance = None
|
||||||
|
for w in line_words:
|
||||||
|
amount = _row_amount(w["text"], w["x1"])
|
||||||
|
if amount:
|
||||||
|
kind, value = amount
|
||||||
|
if kind == "debit":
|
||||||
|
debit = value
|
||||||
|
elif kind == "credit":
|
||||||
|
credit = value
|
||||||
|
else:
|
||||||
|
balance = value
|
||||||
|
continue
|
||||||
|
if w["x1"] <= date_col_max_x:
|
||||||
|
date_parts.append(w["text"])
|
||||||
|
else:
|
||||||
|
desc_parts.append(w["text"])
|
||||||
|
rows.append({
|
||||||
|
"top": top,
|
||||||
|
"date": " ".join(date_parts).strip(),
|
||||||
|
"desc": " ".join(desc_parts).strip(),
|
||||||
|
"debit": debit, "credit": credit, "balance": balance,
|
||||||
|
})
|
||||||
|
|
||||||
|
# Everything above the "Date / Description / ..." table header - the
|
||||||
|
# letterhead and "Account Summary for this Period" block on page 1,
|
||||||
|
# repeated page furniture on every page - is NOT part of the
|
||||||
|
# transaction table and must be excluded, or its own numbers (e.g.
|
||||||
|
# the summary's own "Total deposits & credits (54) + 26,956.19"
|
||||||
|
# line) get misread as transaction amounts. The header row's own
|
||||||
|
# text splits across two of our rounded-top buckets here ("Description"
|
||||||
|
# alone, then "Date ...Cheques & Debits..." one bucket below it) -
|
||||||
|
# take the LATER of the two as the real cutoff.
|
||||||
|
header_idx = -1
|
||||||
|
for i, r in enumerate(rows):
|
||||||
|
if r["desc"] == "Description" or r["date"] == "Date":
|
||||||
|
header_idx = i
|
||||||
|
rows = rows[header_idx + 1:] if header_idx >= 0 else rows
|
||||||
|
|
||||||
|
# Drop page furniture below the table too: the "N of M" page-number
|
||||||
|
# footer (no amount of its own, so left alone it gets silently
|
||||||
|
# absorbed as a continuation line into the NEXT page's first real
|
||||||
|
# transaction - see _group_into_transactions) and anything after a
|
||||||
|
# "Closing balance" row on the statement's last page (e.g. an
|
||||||
|
# "Account Fees: $58.35" footer line).
|
||||||
|
cleaned = []
|
||||||
|
for r in rows:
|
||||||
|
if re.match(r"^\d+ of \d+$", r["desc"]):
|
||||||
|
continue
|
||||||
|
cleaned.append(r)
|
||||||
|
if r["desc"].strip().lower() == "closing balance" and r["balance"] is not None:
|
||||||
|
break
|
||||||
|
return cleaned
|
||||||
|
|
||||||
|
|
||||||
|
def _group_into_transactions(rows):
|
||||||
|
"""
|
||||||
|
Walk a statement's rows (already in top-to-bottom order, across all
|
||||||
|
pages concatenated) and turn them into individual transactions plus
|
||||||
|
the opening/closing balance.
|
||||||
|
|
||||||
|
Date is forward-filled (blank on every row after a day's first
|
||||||
|
transaction - see the module docstring-level comment on
|
||||||
|
DATE_COL_MAX_X). A row with no Debit/Credit amount is a continuation
|
||||||
|
of the NEXT amount-bearing row's description (e.g. "Regular
|
||||||
|
transaction fee 43 Drs @ 0.60" / "48 Crs @ 0.60 54.60" is one
|
||||||
|
$54.60 transaction, not two) - text accumulates across consecutive
|
||||||
|
amount-less rows and the transaction completes the moment a row
|
||||||
|
with a real Debit or Credit is reached. The header row ("Date
|
||||||
|
Description...", repeated on every page) and blank/noise rows are
|
||||||
|
skipped by virtue of having no date, no amount, and description
|
||||||
|
text that never matches a real transaction shape - harmless no-ops
|
||||||
|
since they contribute nothing to accumulate.
|
||||||
|
|
||||||
|
Returns (opening_balance, closing_balance, transactions) where each
|
||||||
|
transaction is {"date", "description", "amount"} - amount signed
|
||||||
|
(credit positive, debit negative).
|
||||||
|
"""
|
||||||
|
opening_balance = closing_balance = None
|
||||||
|
transactions = []
|
||||||
|
pending_desc = []
|
||||||
|
last_date = ""
|
||||||
|
|
||||||
|
for row in rows:
|
||||||
|
if row["date"]:
|
||||||
|
last_date = row["date"]
|
||||||
|
desc = row["desc"].strip()
|
||||||
|
norm = desc.lower()
|
||||||
|
|
||||||
|
if norm == "opening balance" and row["balance"] is not None:
|
||||||
|
opening_balance = row["balance"]
|
||||||
|
continue
|
||||||
|
if norm == "closing balance" and row["balance"] is not None:
|
||||||
|
closing_balance = row["balance"]
|
||||||
|
continue
|
||||||
|
if norm in ("date description", "description") or desc == "":
|
||||||
|
continue
|
||||||
|
|
||||||
|
if row["debit"] is None and row["credit"] is None:
|
||||||
|
# Continuation line - no amount yet, keep accumulating.
|
||||||
|
if desc:
|
||||||
|
pending_desc.append(desc)
|
||||||
|
continue
|
||||||
|
|
||||||
|
full_desc = " ".join(pending_desc + [desc]).strip()
|
||||||
|
pending_desc = []
|
||||||
|
amount = row["credit"] if row["credit"] is not None else -row["debit"]
|
||||||
|
transactions.append({"date": last_date, "description": full_desc, "amount": round(amount, 2)})
|
||||||
|
|
||||||
|
return opening_balance, closing_balance, transactions
|
||||||
|
|
||||||
|
|
||||||
|
_SUMMARY_RE = re.compile(
|
||||||
|
r"Total (deposits & credits|cheques & debits)\s*\((\d+)\)\s*[+-]\s*([\d,]+\.\d{2})",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_summary_totals(full_text):
|
||||||
|
"""
|
||||||
|
The statement's own "Account Summary for this Period" block states
|
||||||
|
its transaction counts and totals directly (e.g. "Total deposits &
|
||||||
|
credits (54) + 26,956.19") - an independent cross-check on the
|
||||||
|
parsed transaction list, same idea as app/tools/eib/logic.py's
|
||||||
|
extract_balances_from_markdown pulling a stated total to verify
|
||||||
|
against. Returns {"credit_count", "credit_total", "debit_count",
|
||||||
|
"debit_total"} - any key missing if that line wasn't found.
|
||||||
|
"""
|
||||||
|
result = {}
|
||||||
|
for m in _SUMMARY_RE.finditer(full_text):
|
||||||
|
kind = "credit" if "deposits" in m.group(1) else "debit"
|
||||||
|
result[f"{kind}_count"] = int(m.group(2))
|
||||||
|
result[f"{kind}_total"] = float(m.group(3).replace(",", ""))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def parse_rbc_statement(pdf_path):
|
||||||
|
"""
|
||||||
|
Parse an RBC Business Account Statement PDF (text-based, not
|
||||||
|
scanned - confirmed real statements extract cleanly with
|
||||||
|
pdfplumber) into individual transactions plus opening/closing
|
||||||
|
balance. See _extract_rows/_group_into_transactions for the actual
|
||||||
|
column-position and multi-line-continuation handling this requires.
|
||||||
|
|
||||||
|
Returns {"opening_balance", "closing_balance", "transactions":
|
||||||
|
[{"date","description","amount"}...], "summary_totals": {...}}.
|
||||||
|
Raises ValueError if this doesn't look like a parseable RBC
|
||||||
|
statement (no opening/closing balance found at all).
|
||||||
|
"""
|
||||||
|
all_rows = []
|
||||||
|
full_text_parts = []
|
||||||
|
with pdfplumber.open(pdf_path) as pdf:
|
||||||
|
for page in pdf.pages:
|
||||||
|
all_rows.extend(_extract_rows(page))
|
||||||
|
full_text_parts.append(page.extract_text(x_tolerance=X_TOLERANCE) or "")
|
||||||
|
|
||||||
|
opening_balance, closing_balance, transactions = _group_into_transactions(all_rows)
|
||||||
|
if opening_balance is None or closing_balance is None:
|
||||||
|
raise ValueError(
|
||||||
|
"Could not find an Opening balance and Closing balance row - this doesn't look like "
|
||||||
|
"a parseable RBC Business Account Statement."
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"opening_balance": opening_balance,
|
||||||
|
"closing_balance": closing_balance,
|
||||||
|
"transactions": transactions,
|
||||||
|
"summary_totals": _extract_summary_totals("\n".join(full_text_parts)),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Categorization rules (description_rules.csv) ───────────────────────────
|
||||||
|
# Read/write/match mechanics live in app/common.py - shared with
|
||||||
|
# app/tools/hsbc_statement_categorizer/, the second tool to need this
|
||||||
|
# exact shape (see common.py's own comment on the "lift once a second
|
||||||
|
# tool duplicates something" trigger). Each tool keeps its own
|
||||||
|
# description_rules.csv path, passed in below.
|
||||||
|
|
||||||
|
def list_rules():
|
||||||
|
return common.load_description_rules(RULES_PATH)
|
||||||
|
|
||||||
|
|
||||||
|
def upsert_rules(entries):
|
||||||
|
common.upsert_description_rules(RULES_PATH, entries)
|
||||||
|
|
||||||
|
|
||||||
|
def delete_rule(pattern):
|
||||||
|
common.delete_description_rule(RULES_PATH, pattern)
|
||||||
|
|
||||||
|
|
||||||
|
def match_rule(description, rules):
|
||||||
|
return common.match_description_rule(description, rules)
|
||||||
|
|
||||||
|
|
||||||
|
def categorize(description, rules):
|
||||||
|
"""Just the accounting_description half of match_rule() - kept for
|
||||||
|
callers that don't need to know which pattern actually matched."""
|
||||||
|
rule = match_rule(description, rules)
|
||||||
|
return rule["accounting_description"] if rule else None
|
||||||
|
|
||||||
|
|
||||||
|
# ── Aggregation + reconciliation ────────────────────────────────────────────
|
||||||
|
|
||||||
|
def build_categorized_summary(parsed, rules):
|
||||||
|
"""
|
||||||
|
Categorize every parsed transaction, group by accounting_description
|
||||||
|
and sum - this is what makes two differently-matched transactions
|
||||||
|
that happen to share similar raw text (see categorize) land in
|
||||||
|
separate output rows automatically, with no special "keep separate"
|
||||||
|
case needed anywhere in this function.
|
||||||
|
|
||||||
|
Returns {"rows": [{"bank_description","accounting_description",
|
||||||
|
"amount"}...] (one per distinct accounting_description, sorted by
|
||||||
|
first appearance in the statement), "unmapped": [{"description",
|
||||||
|
"amount", "count"}...] (grouped by distinct raw description text -
|
||||||
|
see routes.py's review gate), "opening_balance", "closing_balance",
|
||||||
|
"reconciled", "credit_total", "debit_total", "summary_totals"}.
|
||||||
|
"""
|
||||||
|
opening = parsed["opening_balance"]
|
||||||
|
closing = parsed["closing_balance"]
|
||||||
|
transactions = parsed["transactions"]
|
||||||
|
|
||||||
|
groups = {} # accounting_description -> {"amount": float, "bank_descriptions": set}
|
||||||
|
unmapped = {} # raw description -> {"amount": total, "count": n}
|
||||||
|
credit_total = debit_total = 0.0
|
||||||
|
|
||||||
|
for t in transactions:
|
||||||
|
if t["amount"] >= 0:
|
||||||
|
credit_total += t["amount"]
|
||||||
|
else:
|
||||||
|
debit_total += t["amount"]
|
||||||
|
|
||||||
|
rule = match_rule(t["description"], rules)
|
||||||
|
if rule is None:
|
||||||
|
entry = unmapped.setdefault(t["description"], {"description": t["description"], "amount": 0.0, "count": 0})
|
||||||
|
entry["amount"] = round(entry["amount"] + t["amount"], 2)
|
||||||
|
entry["count"] += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
target = rule["accounting_description"]
|
||||||
|
entry = groups.setdefault(target, {"amount": 0.0, "bank_descriptions": [], "first_seen": len(groups)})
|
||||||
|
entry["amount"] = round(entry["amount"] + t["amount"], 2)
|
||||||
|
# The matched PATTERN, not the raw description - a dozen "Misc
|
||||||
|
# Payment MC FEE..." lines with different trailing reference
|
||||||
|
# numbers all collapse to one clean "Misc Payment MC FEE" label
|
||||||
|
# instead of a long slash-joined wall of near-duplicate text.
|
||||||
|
if rule["pattern"] not in entry["bank_descriptions"]:
|
||||||
|
entry["bank_descriptions"].append(rule["pattern"])
|
||||||
|
|
||||||
|
rows = [
|
||||||
|
{
|
||||||
|
"bank_description": " / ".join(v["bank_descriptions"]),
|
||||||
|
"accounting_description": target,
|
||||||
|
"amount": v["amount"],
|
||||||
|
}
|
||||||
|
for target, v in sorted(groups.items(), key=lambda kv: kv[1]["first_seen"])
|
||||||
|
]
|
||||||
|
|
||||||
|
net = round(credit_total + debit_total, 2)
|
||||||
|
reconciled = bool(abs(opening + net - closing) < RECONCILE_TOLERANCE) if not unmapped else False
|
||||||
|
|
||||||
|
return {
|
||||||
|
"rows": rows,
|
||||||
|
"unmapped": sorted(unmapped.values(), key=lambda u: u["description"]),
|
||||||
|
"opening_balance": opening,
|
||||||
|
"closing_balance": closing,
|
||||||
|
"reconciled": reconciled,
|
||||||
|
"credit_total": round(credit_total, 2),
|
||||||
|
"debit_total": round(debit_total, 2),
|
||||||
|
"summary_totals": parsed["summary_totals"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Output workbook ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
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 write_output_workbook(summary, output_path, title="Bank Statement Categorizer"):
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "Categorized"
|
||||||
|
for col, width in zip("ABC", (46, 56, 16)):
|
||||||
|
ws.column_dimensions[col].width = width
|
||||||
|
|
||||||
|
_write_cell(ws, 1, 1, title, bold=True)
|
||||||
|
row = 3
|
||||||
|
for col, label in enumerate(["Bank Description", "Accounting Description", "Amount"], start=1):
|
||||||
|
_write_cell(ws, row, col, label, bold=True)
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
_write_cell(ws, row, 1, "Opening balance", bold=True)
|
||||||
|
_write_cell(ws, row, 2, "Opening balance", bold=True)
|
||||||
|
_write_cell(ws, row, 3, summary["opening_balance"], bold=True, number_format=ACCOUNTING_FORMAT)
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
for r in summary["rows"]:
|
||||||
|
_write_cell(ws, row, 1, r["bank_description"])
|
||||||
|
_write_cell(ws, row, 2, r["accounting_description"])
|
||||||
|
_write_cell(ws, row, 3, r["amount"], number_format=ACCOUNTING_FORMAT)
|
||||||
|
row += 1
|
||||||
|
|
||||||
|
_write_cell(ws, row, 1, "Closing balance", bold=True)
|
||||||
|
_write_cell(ws, row, 2, "Closing balance", bold=True)
|
||||||
|
_write_cell(ws, row, 3, summary["closing_balance"], bold=True, number_format=ACCOUNTING_FORMAT)
|
||||||
|
row += 2
|
||||||
|
|
||||||
|
_write_cell(ws, row, 1, "Reconciled" if summary["reconciled"] else "NOT RECONCILED", bold=True)
|
||||||
|
row += 1
|
||||||
|
_write_cell(ws, row, 1, "Opening + categorized net")
|
||||||
|
_write_cell(ws, row, 3, round(summary["opening_balance"] + summary["credit_total"] + summary["debit_total"], 2), number_format=ACCOUNTING_FORMAT)
|
||||||
|
row += 1
|
||||||
|
_write_cell(ws, row, 1, "Closing balance (per statement)")
|
||||||
|
_write_cell(ws, row, 3, summary["closing_balance"], number_format=ACCOUNTING_FORMAT)
|
||||||
|
|
||||||
|
wb.save(output_path)
|
||||||
|
|
@ -0,0 +1,137 @@
|
||||||
|
import os, uuid
|
||||||
|
from flask import Blueprint, request, jsonify, send_file, render_template, current_app
|
||||||
|
from werkzeug.utils import secure_filename
|
||||||
|
|
||||||
|
from .logic import (
|
||||||
|
parse_rbc_statement,
|
||||||
|
build_categorized_summary,
|
||||||
|
write_output_workbook,
|
||||||
|
list_rules,
|
||||||
|
upsert_rules,
|
||||||
|
delete_rule,
|
||||||
|
)
|
||||||
|
|
||||||
|
bank_statement_categorizer_bp = Blueprint(
|
||||||
|
"bank_statement_categorizer", __name__, url_prefix="/bank-statement-categorizer"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Parsed transactions for a run paused awaiting unmapped-description
|
||||||
|
# review, keyed by a one-time token - same explicit single-job/single-
|
||||||
|
# user shortcut as every other tool's PENDING_RUNS in this app (see
|
||||||
|
# app/tools/financial_reports/routes.py), not safe for concurrent runs,
|
||||||
|
# not meant to be. Avoids re-parsing the PDF on every round of mapping.
|
||||||
|
PENDING_RUNS = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _check_and_respond(parsed, title):
|
||||||
|
rules = list_rules()
|
||||||
|
summary = build_categorized_summary(parsed, rules)
|
||||||
|
if summary["unmapped"]:
|
||||||
|
token = str(uuid.uuid4())
|
||||||
|
PENDING_RUNS[token] = {"parsed": parsed, "title": title}
|
||||||
|
return jsonify({
|
||||||
|
"status": "needs_review",
|
||||||
|
"token": token,
|
||||||
|
"unmapped": summary["unmapped"],
|
||||||
|
}), 200
|
||||||
|
|
||||||
|
fname = f"Bank_Statement_Categorized_{uuid.uuid4().hex[:8]}.xlsx"
|
||||||
|
fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], fname)
|
||||||
|
write_output_workbook(summary, fpath, title=title)
|
||||||
|
calculated_closing_balance = round(summary["opening_balance"] + summary["credit_total"] + summary["debit_total"], 2)
|
||||||
|
return jsonify({
|
||||||
|
"status": "ok",
|
||||||
|
"filename": fname,
|
||||||
|
"reconciled": summary["reconciled"],
|
||||||
|
"opening_balance": summary["opening_balance"],
|
||||||
|
"closing_balance": summary["closing_balance"],
|
||||||
|
"calculated_closing_balance": calculated_closing_balance,
|
||||||
|
"credit_total": summary["credit_total"],
|
||||||
|
"debit_total": summary["debit_total"],
|
||||||
|
"rows": summary["rows"],
|
||||||
|
}), 200
|
||||||
|
|
||||||
|
|
||||||
|
@bank_statement_categorizer_bp.route("/")
|
||||||
|
def index():
|
||||||
|
return render_template("bank_statement_categorizer/index.html")
|
||||||
|
|
||||||
|
|
||||||
|
@bank_statement_categorizer_bp.route("/api/process", methods=["POST"])
|
||||||
|
def api_process():
|
||||||
|
f = request.files.get("statement_file")
|
||||||
|
if not f or not f.filename:
|
||||||
|
return jsonify({"error": "Upload a bank statement PDF"}), 400
|
||||||
|
|
||||||
|
path = os.path.join(current_app.config["UPLOAD_FOLDER"], f"{uuid.uuid4()}_{secure_filename(f.filename)}")
|
||||||
|
f.save(path)
|
||||||
|
try:
|
||||||
|
parsed = parse_rbc_statement(path)
|
||||||
|
except ValueError as e:
|
||||||
|
return jsonify({"error": str(e)}), 400
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({"error": f"Could not parse {f.filename}: {e}"}), 400
|
||||||
|
finally:
|
||||||
|
os.remove(path)
|
||||||
|
|
||||||
|
title = request.form.get("title") or "Bank Statement Categorizer"
|
||||||
|
return _check_and_respond(parsed, title)
|
||||||
|
|
||||||
|
|
||||||
|
@bank_statement_categorizer_bp.route("/api/confirm-mappings", methods=["POST"])
|
||||||
|
def api_confirm_mappings():
|
||||||
|
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:
|
||||||
|
pattern = str(d.get("pattern", "")).strip()
|
||||||
|
target = str(d.get("accounting_description", "")).strip()
|
||||||
|
if not pattern or not target:
|
||||||
|
return jsonify({"error": "Every mapped description needs both a pattern and an accounting description."}), 400
|
||||||
|
|
||||||
|
del PENDING_RUNS[token]
|
||||||
|
entries = [(d["pattern"].strip(), d["accounting_description"].strip()) for d in decisions]
|
||||||
|
if entries:
|
||||||
|
upsert_rules(entries)
|
||||||
|
|
||||||
|
return _check_and_respond(pending["parsed"], pending["title"])
|
||||||
|
|
||||||
|
|
||||||
|
@bank_statement_categorizer_bp.route("/api/rules", methods=["GET", "POST"])
|
||||||
|
def api_rules():
|
||||||
|
if request.method == "GET":
|
||||||
|
return jsonify({"rules": list_rules()}), 200
|
||||||
|
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
pattern = str(data.get("pattern", "")).strip()
|
||||||
|
target = str(data.get("accounting_description", "")).strip()
|
||||||
|
if not pattern or not target:
|
||||||
|
return jsonify({"error": "pattern and accounting_description are required"}), 400
|
||||||
|
upsert_rules([(pattern, target)])
|
||||||
|
return jsonify({"status": "ok", "rules": list_rules()}), 200
|
||||||
|
|
||||||
|
|
||||||
|
@bank_statement_categorizer_bp.route("/api/rules/delete", methods=["POST"])
|
||||||
|
def api_delete_rule():
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
pattern = str(data.get("pattern", "")).strip()
|
||||||
|
if not pattern:
|
||||||
|
return jsonify({"error": "pattern is required"}), 400
|
||||||
|
delete_rule(pattern)
|
||||||
|
return jsonify({"status": "ok", "rules": list_rules()}), 200
|
||||||
|
|
||||||
|
|
||||||
|
@bank_statement_categorizer_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)
|
||||||
|
|
@ -0,0 +1,248 @@
|
||||||
|
<script setup>
|
||||||
|
/**
|
||||||
|
* CategorizationPanel.vue
|
||||||
|
*
|
||||||
|
* The Categorization tab's body (TransactionsTable.vue's own tab bar) -
|
||||||
|
* a compact rules list + inline "add rule" form, a "Categorized" table
|
||||||
|
* grouped by accounting category, and an "Unmatched" section where each
|
||||||
|
* group of identically-described, unmatched transactions gets its own
|
||||||
|
* inline "assign a category" control. See CLAUDE.md's "Transaction
|
||||||
|
* categorization" entry for the full design (matching stays entirely
|
||||||
|
* client-side, rules recompute live, nothing is ever silently hidden).
|
||||||
|
*
|
||||||
|
* `categorization` is the useCategorization() instance - instantiated
|
||||||
|
* ONCE at TransactionsTable.vue's level (so the export handler there and
|
||||||
|
* this panel share one computed state, never two independent fetches)
|
||||||
|
* and passed down as a prop. It's a plain object of refs/computeds/
|
||||||
|
* functions, not itself wrapped in reactive() - every nested ref is
|
||||||
|
* accessed with an explicit `.value` here rather than relying on
|
||||||
|
* auto-unwrapping through a plain prop object.
|
||||||
|
*
|
||||||
|
* Also shows a reconciliation walk at the bottom of the "Categorized"
|
||||||
|
* card once every transaction has been categorized (no unmatched
|
||||||
|
* groups left) - opening balance, then each matched category's own net
|
||||||
|
* total (not a credit/debit split - the category breakdown IS the
|
||||||
|
* categorized total, itemized by what it actually is), closing
|
||||||
|
* balance, then whether that ties back to the statement. The pass/fail
|
||||||
|
* judgment itself still comes from the backend's OWN already-computed
|
||||||
|
* statement_balance check (same one the Transactions tab's own balance
|
||||||
|
* fields already reflect) rather than re-deriving it from the displayed
|
||||||
|
* category sums - the category breakdown is just a transparent
|
||||||
|
* itemization of the same total, not a second, independently-judged
|
||||||
|
* number.
|
||||||
|
*/
|
||||||
|
import { computed, reactive, ref } from 'vue'
|
||||||
|
import { useExtractionStore } from '../stores/extractionStore'
|
||||||
|
import { fmtMoney, fmtNum } from '../services/formatService'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
categorization: { type: Object, required: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
const extractionStore = useExtractionStore()
|
||||||
|
const balanceCheck = computed(() => extractionStore.currentResult?.checks?.find((c) => c.name === 'statement_balance'))
|
||||||
|
const openingBalance = computed(() => extractionStore.effectiveOpeningBalance)
|
||||||
|
const closingBalance = computed(() => extractionStore.effectiveClosingBalance)
|
||||||
|
const showReconciliation = computed(() =>
|
||||||
|
props.categorization.unmatched.value.length === 0 && props.categorization.matched.value.length > 0,
|
||||||
|
)
|
||||||
|
const reconciliationOutcome = computed(() => balanceCheck.value?.outcome ?? 'not_available')
|
||||||
|
const RECONCILIATION_TEXT = {
|
||||||
|
pass: 'Reconciled to source document', fail: 'Does not reconcile to source document',
|
||||||
|
not_available: 'No stated closing balance to reconcile against',
|
||||||
|
}
|
||||||
|
const RECONCILIATION_ICON = { pass: 'fa-circle-check', fail: 'fa-circle-xmark', not_available: 'fa-circle-info' }
|
||||||
|
|
||||||
|
// Collapsed by default - the rules list + "add rule" form stay hidden
|
||||||
|
// until the user clicks the chevron to view or create one, same
|
||||||
|
// clickable-heading-with-chevron pattern LayoutsView.vue already uses
|
||||||
|
// for its own per-mapping detail panel.
|
||||||
|
const rulesExpanded = ref(false)
|
||||||
|
|
||||||
|
const newPattern = ref('')
|
||||||
|
const newCategory = ref('')
|
||||||
|
const addingRule = ref(false)
|
||||||
|
const addError = ref('')
|
||||||
|
|
||||||
|
async function handleAddRule() {
|
||||||
|
const pattern = newPattern.value.trim()
|
||||||
|
const accountingCategory = newCategory.value.trim()
|
||||||
|
if (!pattern || !accountingCategory) return
|
||||||
|
addingRule.value = true
|
||||||
|
addError.value = ''
|
||||||
|
try {
|
||||||
|
await props.categorization.addRule({ pattern, accountingCategory })
|
||||||
|
newPattern.value = ''
|
||||||
|
newCategory.value = ''
|
||||||
|
} catch (e) {
|
||||||
|
addError.value = 'Could not save this rule: ' + e.message
|
||||||
|
}
|
||||||
|
addingRule.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
const removingRuleId = ref(null)
|
||||||
|
async function handleRemoveRule(id) {
|
||||||
|
removingRuleId.value = id
|
||||||
|
addError.value = ''
|
||||||
|
try {
|
||||||
|
await props.categorization.removeRule(id)
|
||||||
|
} catch (e) {
|
||||||
|
addError.value = 'Could not delete this rule: ' + e.message
|
||||||
|
}
|
||||||
|
removingRuleId.value = null
|
||||||
|
}
|
||||||
|
|
||||||
|
// Per-unmatched-group inline form state, keyed by that group's own raw
|
||||||
|
// description text (groups can reorder/disappear as rules change, so an
|
||||||
|
// array index would be the wrong key) - same independent-per-row
|
||||||
|
// reactive({}) pattern LayoutsView.vue already uses for its own
|
||||||
|
// per-mapping test/rollback state, so one row's save doesn't disable or
|
||||||
|
// block any other row.
|
||||||
|
const unmatchedForms = reactive({})
|
||||||
|
function formFor(group) {
|
||||||
|
if (!unmatchedForms[group.description]) {
|
||||||
|
unmatchedForms[group.description] = { category: '', pattern: group.description, saving: false, error: '' }
|
||||||
|
}
|
||||||
|
return unmatchedForms[group.description]
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleResolveUnmatched(group) {
|
||||||
|
const form = formFor(group)
|
||||||
|
const pattern = form.pattern.trim()
|
||||||
|
const accountingCategory = form.category.trim()
|
||||||
|
if (!pattern || !accountingCategory) return
|
||||||
|
form.saving = true
|
||||||
|
form.error = ''
|
||||||
|
try {
|
||||||
|
await props.categorization.addRule({ pattern, accountingCategory })
|
||||||
|
delete unmatchedForms[group.description]
|
||||||
|
} catch (e) {
|
||||||
|
form.error = 'Could not save this rule: ' + e.message
|
||||||
|
form.saving = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div v-if="categorization.loading.value" class="empty-panel empty-panel-table">
|
||||||
|
<p>Loading categorization rules…</p>
|
||||||
|
</div>
|
||||||
|
<div v-else class="categorization-panel">
|
||||||
|
<div v-if="categorization.error.value" class="error-note visible">{{ categorization.error.value }}</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<h2 class="cat-rules-toggle" @click="rulesExpanded = !rulesExpanded">
|
||||||
|
<i class="fa-solid" :class="rulesExpanded ? 'fa-chevron-down' : 'fa-chevron-right'"></i>
|
||||||
|
Categorization rules
|
||||||
|
<span class="cat-rules-count">({{ categorization.rules.value.length }})</span>
|
||||||
|
</h2>
|
||||||
|
<template v-if="rulesExpanded">
|
||||||
|
<div v-if="categorization.rules.value.length === 0" class="note" style="margin-bottom:12px;">
|
||||||
|
No categorization rules yet for this project - add one below, or assign a category to an unmatched description further down.
|
||||||
|
</div>
|
||||||
|
<ul v-else class="cat-rules-list">
|
||||||
|
<li v-for="rule in categorization.rules.value" :key="rule.id">
|
||||||
|
<span class="cat-rule-pattern">{{ rule.pattern }}</span>
|
||||||
|
<i class="fa-solid fa-arrow-right-long"></i>
|
||||||
|
<span class="cat-rule-category">{{ rule.accountingCategory }}</span>
|
||||||
|
<button
|
||||||
|
type="button" class="cat-rule-delete" title="Delete this rule"
|
||||||
|
:disabled="removingRuleId === rule.id"
|
||||||
|
@click="handleRemoveRule(rule.id)"
|
||||||
|
>
|
||||||
|
<i class="fa-solid" :class="removingRuleId === rule.id ? 'fa-spinner fa-spin' : 'fa-trash'"></i>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
<div class="cat-add-rule">
|
||||||
|
<input v-model="newPattern" type="text" placeholder="Description contains…" :disabled="addingRule">
|
||||||
|
<i class="fa-solid fa-arrow-right-long"></i>
|
||||||
|
<input v-model="newCategory" type="text" placeholder="Accounting category" :disabled="addingRule">
|
||||||
|
<button type="button" class="btn-toggle" :disabled="addingRule || !newPattern.trim() || !newCategory.trim()" @click="handleAddRule">
|
||||||
|
<i class="fa-solid" :class="addingRule ? 'fa-spinner fa-spin' : 'fa-plus'"></i>
|
||||||
|
Add rule
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div v-if="addError" class="error-note visible">{{ addError }}</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<h2>Categorized</h2>
|
||||||
|
<div v-if="categorization.matched.value.length === 0" class="note">No transactions matched a rule yet.</div>
|
||||||
|
<div v-else class="cat-table-wrap">
|
||||||
|
<table class="cat-table">
|
||||||
|
<colgroup>
|
||||||
|
<col>
|
||||||
|
<col>
|
||||||
|
<col style="width:70px">
|
||||||
|
<col style="width:110px">
|
||||||
|
</colgroup>
|
||||||
|
<thead>
|
||||||
|
<tr><th>Accounting category</th><th>Bank description(s)</th><th class="amt">Count</th><th class="amt">Amount</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="g in categorization.matched.value" :key="g.accountingCategory">
|
||||||
|
<td>{{ g.accountingCategory }}</td>
|
||||||
|
<td class="cat-bank-desc">{{ g.bankDescriptions.join(' / ') }}</td>
|
||||||
|
<td class="amt">{{ g.count }}</td>
|
||||||
|
<td class="amt">{{ fmtNum(g.amount) }}</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!--
|
||||||
|
Shown only once nothing is left unmatched - reuses the backend's
|
||||||
|
own already-computed statement_balance check for the pass/fail
|
||||||
|
judgment (see this file's own top comment for why), itemized by
|
||||||
|
each matched category's own net total rather than a credit/debit
|
||||||
|
split, so the walk reads as "what it actually is," not just
|
||||||
|
"positive vs. negative."
|
||||||
|
-->
|
||||||
|
<div v-if="showReconciliation" class="cat-recon">
|
||||||
|
<div class="cat-recon-title">Summary</div>
|
||||||
|
<ul class="cat-recon-list">
|
||||||
|
<li><span>Opening balance</span><span>{{ fmtMoney(openingBalance) }}</span></li>
|
||||||
|
<li v-for="g in categorization.matched.value" :key="'recon-' + g.accountingCategory" class="cat-recon-indent">
|
||||||
|
<span>{{ g.accountingCategory }}</span>
|
||||||
|
<span :class="g.amount >= 0 ? 'cat-recon-credit' : 'cat-recon-debit'">{{ fmtMoney(g.amount) }}</span>
|
||||||
|
</li>
|
||||||
|
<li class="cat-recon-total"><span>Closing balance</span><span>{{ fmtMoney(closingBalance) }}</span></li>
|
||||||
|
</ul>
|
||||||
|
<div class="cat-recon-result" :class="reconciliationOutcome">
|
||||||
|
<i class="fa-solid" :class="RECONCILIATION_ICON[reconciliationOutcome]"></i>
|
||||||
|
{{ RECONCILIATION_TEXT[reconciliationOutcome] }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<h2>Unmatched</h2>
|
||||||
|
<div v-if="categorization.unmatched.value.length === 0" class="note">Every transaction matched a rule.</div>
|
||||||
|
<ul v-else class="cat-unmatched-list">
|
||||||
|
<li v-for="g in categorization.unmatched.value" :key="g.description">
|
||||||
|
<div class="cat-unmatched-head">
|
||||||
|
<span class="cat-unmatched-desc">{{ g.description || '(blank description)' }}</span>
|
||||||
|
<span class="note" style="margin:0;">{{ g.count }} transaction(s), {{ fmtNum(g.amount) }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="cat-add-rule">
|
||||||
|
<input v-model="formFor(g).pattern" type="text" placeholder="Pattern to match" :disabled="formFor(g).saving">
|
||||||
|
<i class="fa-solid fa-arrow-right-long"></i>
|
||||||
|
<input v-model="formFor(g).category" type="text" placeholder="Accounting category" :disabled="formFor(g).saving">
|
||||||
|
<button
|
||||||
|
type="button" class="btn-toggle"
|
||||||
|
:disabled="formFor(g).saving || !formFor(g).pattern.trim() || !formFor(g).category.trim()"
|
||||||
|
@click="handleResolveUnmatched(g)"
|
||||||
|
>
|
||||||
|
<i class="fa-solid" :class="formFor(g).saving ? 'fa-spinner fa-spin' : 'fa-check'"></i>
|
||||||
|
Save rule
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div v-if="formFor(g).error" class="error-note visible">{{ formFor(g).error }}</div>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
@ -0,0 +1,104 @@
|
||||||
|
/**
|
||||||
|
* Groups the active document's own already-extracted transactions
|
||||||
|
* against the current project's categorizationRules - entirely
|
||||||
|
* client-side (see categorizationRulesService.js's own matchDescription),
|
||||||
|
* recomputed live from whatever rules exist right now rather than
|
||||||
|
* persisted on the document, so adding/removing a rule re-buckets
|
||||||
|
* everything immediately with no refetch of the transactions themselves.
|
||||||
|
*
|
||||||
|
* `projectId` is the ACTIVE DOCUMENT's own `project` field
|
||||||
|
* (extractionStore.activeDocument.project), not projectsStore
|
||||||
|
* .activeProjectId - the sidebar's "All" filter can be active while a
|
||||||
|
* specific document (which still belongs to exactly one project) is
|
||||||
|
* open, and it's that document's own project whose rules apply.
|
||||||
|
*/
|
||||||
|
import { ref, computed, watch } from 'vue'
|
||||||
|
import * as categorizationRulesService from '../services/categorizationRulesService'
|
||||||
|
|
||||||
|
function round2(n) {
|
||||||
|
return Math.round(n * 100) / 100
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useCategorization(transactionsRef, projectIdRef) {
|
||||||
|
const rules = ref([])
|
||||||
|
const loading = ref(false)
|
||||||
|
const error = ref(null)
|
||||||
|
|
||||||
|
async function loadRules() {
|
||||||
|
const projectId = projectIdRef.value
|
||||||
|
if (!projectId) {
|
||||||
|
rules.value = []
|
||||||
|
return
|
||||||
|
}
|
||||||
|
loading.value = true
|
||||||
|
error.value = null
|
||||||
|
try {
|
||||||
|
rules.value = await categorizationRulesService.listForProject(projectId)
|
||||||
|
} catch (e) {
|
||||||
|
error.value = e.message || 'Could not load categorization rules.'
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(projectIdRef, loadRules, { immediate: true })
|
||||||
|
|
||||||
|
// One pass over the transactions, bucketing each into either a
|
||||||
|
// matched-by-category group or an unmatched-by-raw-description group.
|
||||||
|
const grouped = computed(() => {
|
||||||
|
const matchedGroups = new Map()
|
||||||
|
const unmatchedGroups = new Map()
|
||||||
|
for (const t of transactionsRef.value || []) {
|
||||||
|
const rule = categorizationRulesService.matchDescription(t.description, rules.value)
|
||||||
|
if (rule) {
|
||||||
|
const key = rule.accountingCategory
|
||||||
|
if (!matchedGroups.has(key)) {
|
||||||
|
matchedGroups.set(key, { accountingCategory: key, amount: 0, count: 0, bankDescriptions: new Set() })
|
||||||
|
}
|
||||||
|
const g = matchedGroups.get(key)
|
||||||
|
g.amount += t.amount || 0
|
||||||
|
g.count += 1
|
||||||
|
g.bankDescriptions.add(rule.pattern)
|
||||||
|
} else {
|
||||||
|
const key = t.description || ''
|
||||||
|
if (!unmatchedGroups.has(key)) {
|
||||||
|
unmatchedGroups.set(key, { description: key, amount: 0, count: 0 })
|
||||||
|
}
|
||||||
|
const g = unmatchedGroups.get(key)
|
||||||
|
g.amount += t.amount || 0
|
||||||
|
g.count += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
matched: [...matchedGroups.values()].map((g) => ({
|
||||||
|
...g, amount: round2(g.amount), bankDescriptions: [...g.bankDescriptions],
|
||||||
|
})),
|
||||||
|
unmatched: [...unmatchedGroups.values()].map((g) => ({ ...g, amount: round2(g.amount) })),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const matched = computed(() => grouped.value.matched)
|
||||||
|
const unmatched = computed(() => grouped.value.unmatched)
|
||||||
|
// The exact shape backend/services/excel_service.py's
|
||||||
|
// _write_categorized_summary_sheet expects - plain arrays, already
|
||||||
|
// JSON-serializable as-is.
|
||||||
|
const summaryForExport = computed(() => grouped.value)
|
||||||
|
|
||||||
|
/** Saves a new rule and re-buckets everything immediately - no refetch. */
|
||||||
|
async function addRule({ pattern, accountingCategory }) {
|
||||||
|
const projectId = projectIdRef.value
|
||||||
|
if (!projectId) throw new Error('No project to save this rule to.')
|
||||||
|
const rule = await categorizationRulesService.createRule({ project: projectId, pattern, accountingCategory })
|
||||||
|
rules.value = [rule, ...rules.value]
|
||||||
|
return rule
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeRule(id) {
|
||||||
|
await categorizationRulesService.deleteRule(id)
|
||||||
|
rules.value = rules.value.filter((r) => r.id !== id)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
rules, loading, error, matched, unmatched, summaryForExport, addRule, removeRule, reloadRules: loadRules,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,49 @@
|
||||||
|
/**
|
||||||
|
* Transaction categorization - thin PocketBase wrapper over the
|
||||||
|
* project-scoped categorizationRules collection, same convention as
|
||||||
|
* layoutMappingsService.js. The matching logic lives here too, as a
|
||||||
|
* pure, non-PocketBase export (matchDescription) - same precedent
|
||||||
|
* layoutMappingsService.js sets with scoreNearMatch/findBestMatch - so
|
||||||
|
* it's directly testable without a PocketBase instance.
|
||||||
|
*
|
||||||
|
* Deliberately no sharing/promotion concept (unlike layoutMappings) - a
|
||||||
|
* client's own chart-of-accounts mapping has no cross-user "two
|
||||||
|
* independent confirmations" scenario, so rules stay owner-scoped with
|
||||||
|
* no hook involved.
|
||||||
|
*/
|
||||||
|
import { pb } from '../repositories/pocketbaseRepository'
|
||||||
|
|
||||||
|
/** Every rule for one project, newest first. */
|
||||||
|
export async function listForProject(projectId) {
|
||||||
|
return pb.collection('categorizationRules').getFullList({
|
||||||
|
filter: `project = "${projectId}"`,
|
||||||
|
sort: '-created',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Creates a new rule, owned by the logged-in user. */
|
||||||
|
export async function createRule({ project, pattern, accountingCategory }) {
|
||||||
|
return pb.collection('categorizationRules').create({
|
||||||
|
owner: pb.authStore.record.id,
|
||||||
|
project,
|
||||||
|
pattern,
|
||||||
|
accountingCategory,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteRule(id) {
|
||||||
|
return pb.collection('categorizationRules').delete(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Matches a raw transaction description against a list of rules -
|
||||||
|
* case-insensitive substring match, longest matching pattern wins when
|
||||||
|
* more than one rule matches (most specific, deterministic - no fuzzy
|
||||||
|
* tie-break). Returns the winning rule, or null if nothing matches.
|
||||||
|
*/
|
||||||
|
export function matchDescription(description, rules) {
|
||||||
|
const text = (description || '').toLowerCase()
|
||||||
|
const hits = rules.filter((r) => text.includes(r.pattern.toLowerCase()))
|
||||||
|
if (!hits.length) return null
|
||||||
|
return hits.reduce((best, r) => (r.pattern.length > best.pattern.length ? r : best))
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,43 @@
|
||||||
|
/// <reference path="../pb_data/types.d.ts" />
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schema for transaction categorization (see CLAUDE.md's "Transaction
|
||||||
|
* categorization" entry) - one new collection, categorizationRules.
|
||||||
|
*
|
||||||
|
* Project-scoped, not fingerprint/shared like layoutMappings - a client's
|
||||||
|
* own chart-of-accounts mapping has no cross-user "two independent
|
||||||
|
* confirmations" promotion scenario, so no hook is needed here (unlike
|
||||||
|
* promote_shared_layout_mapping.pb.js). Scoped by `owner` directly on
|
||||||
|
* every rule (the same choice `documents` makes despite also carrying a
|
||||||
|
* `project` relation), not by reaching through the project relation the
|
||||||
|
* way layoutMappingVersions has to reach through layoutMapping.owner.
|
||||||
|
*
|
||||||
|
* `project` mirrors documents.project's own shape exactly (required,
|
||||||
|
* maxSelect 1) - this is the very relation migration 1's own comment
|
||||||
|
* anticipated this feature would need.
|
||||||
|
*/
|
||||||
|
migrate((app) => {
|
||||||
|
let users = app.findCollectionByNameOrId('users')
|
||||||
|
let projects = app.findCollectionByNameOrId('projects')
|
||||||
|
|
||||||
|
let categorizationRules = new Collection({
|
||||||
|
type: 'base',
|
||||||
|
name: 'categorizationRules',
|
||||||
|
listRule: 'owner = @request.auth.id',
|
||||||
|
viewRule: 'owner = @request.auth.id',
|
||||||
|
createRule: 'owner = @request.auth.id',
|
||||||
|
updateRule: 'owner = @request.auth.id',
|
||||||
|
deleteRule: 'owner = @request.auth.id',
|
||||||
|
fields: [
|
||||||
|
{ type: 'relation', name: 'owner', collectionId: users.id, required: true, maxSelect: 1 },
|
||||||
|
{ type: 'relation', name: 'project', collectionId: projects.id, required: true, maxSelect: 1 },
|
||||||
|
{ type: 'text', name: 'pattern', required: true },
|
||||||
|
{ type: 'text', name: 'accountingCategory', required: true },
|
||||||
|
{ type: 'autodate', name: 'created', onCreate: true },
|
||||||
|
{ type: 'autodate', name: 'updated', onCreate: true, onUpdate: true },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
app.save(categorizationRules)
|
||||||
|
}, (app) => {
|
||||||
|
try { app.delete(app.findCollectionByNameOrId('categorizationRules')) } catch (e) {}
|
||||||
|
})
|
||||||
Loading…
Reference in New Issue