From 0c66edf48b4a09d16658fff98d102d1dab99aeb5 Mon Sep 17 00:00:00 2001 From: JasonFraser Date: Tue, 24 Nov 2026 08:15:20 -0400 Subject: [PATCH] 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 --- backend/services/excel_service.py | 47 ++ docs/bank_statement_categorizer/__init__.py | 3 + docs/bank_statement_categorizer/logic.py | 419 ++++++++++++++++++ docs/bank_statement_categorizer/routes.py | 137 ++++++ .../src/components/CategorizationPanel.vue | 248 +++++++++++ frontend/src/composables/useCategorization.js | 104 +++++ .../services/categorizationRulesService.js | 49 ++ .../11_add_categorization_rules.js | 43 ++ 8 files changed, 1050 insertions(+) create mode 100644 docs/bank_statement_categorizer/__init__.py create mode 100644 docs/bank_statement_categorizer/logic.py create mode 100644 docs/bank_statement_categorizer/routes.py create mode 100644 frontend/src/components/CategorizationPanel.vue create mode 100644 frontend/src/composables/useCategorization.js create mode 100644 frontend/src/services/categorizationRulesService.js create mode 100644 pocketbase/pb_migrations/11_add_categorization_rules.js diff --git a/backend/services/excel_service.py b/backend/services/excel_service.py index 8e28e13..bc195ec 100644 --- a/backend/services/excel_service.py +++ b/backend/services/excel_service.py @@ -101,6 +101,15 @@ def build_workbook(result, title="Statement Extraction"): 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 @@ -124,3 +133,41 @@ def _write_edits_sheet(wb, edit_log): _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 diff --git a/docs/bank_statement_categorizer/__init__.py b/docs/bank_statement_categorizer/__init__.py new file mode 100644 index 0000000..36614f3 --- /dev/null +++ b/docs/bank_statement_categorizer/__init__.py @@ -0,0 +1,3 @@ +from .routes import bank_statement_categorizer_bp + +__all__ = ["bank_statement_categorizer_bp"] diff --git a/docs/bank_statement_categorizer/logic.py b/docs/bank_statement_categorizer/logic.py new file mode 100644 index 0000000..f95d251 --- /dev/null +++ b/docs/bank_statement_categorizer/logic.py @@ -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) diff --git a/docs/bank_statement_categorizer/routes.py b/docs/bank_statement_categorizer/routes.py new file mode 100644 index 0000000..ff3faeb --- /dev/null +++ b/docs/bank_statement_categorizer/routes.py @@ -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/") +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) diff --git a/frontend/src/components/CategorizationPanel.vue b/frontend/src/components/CategorizationPanel.vue new file mode 100644 index 0000000..52045ca --- /dev/null +++ b/frontend/src/components/CategorizationPanel.vue @@ -0,0 +1,248 @@ + + + diff --git a/frontend/src/composables/useCategorization.js b/frontend/src/composables/useCategorization.js new file mode 100644 index 0000000..93b4d7c --- /dev/null +++ b/frontend/src/composables/useCategorization.js @@ -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, + } +} diff --git a/frontend/src/services/categorizationRulesService.js b/frontend/src/services/categorizationRulesService.js new file mode 100644 index 0000000..4c9916c --- /dev/null +++ b/frontend/src/services/categorizationRulesService.js @@ -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)) +} diff --git a/pocketbase/pb_migrations/11_add_categorization_rules.js b/pocketbase/pb_migrations/11_add_categorization_rules.js new file mode 100644 index 0000000..c3aa490 --- /dev/null +++ b/pocketbase/pb_migrations/11_add_categorization_rules.js @@ -0,0 +1,43 @@ +/// + +/** + * 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) {} +})