141 lines
6.1 KiB
Python
141 lines
6.1 KiB
Python
# Validates and shapes incoming request data for the extraction routes - no business logic beyond that.
|
|
import json
|
|
|
|
|
|
class ValidationError(Exception):
|
|
"""Raised when a request doesn't carry what a route needs - routes
|
|
catch this and turn it into a 400, so schemas don't need to know
|
|
about Flask's jsonify/status-code conventions themselves."""
|
|
|
|
|
|
def _opt_float(value):
|
|
"""A form/JSON value to float, or None if it's missing/blank -
|
|
distinct from 0.0, since an opening/closing balance of literally zero
|
|
is a real, valid value a user might type."""
|
|
if value in (None, ""):
|
|
return None
|
|
return float(value)
|
|
|
|
|
|
def parse_process_request(request):
|
|
"""
|
|
Validates and extracts the /api/process multipart form.
|
|
|
|
Data flow:
|
|
request (flask.Request) - the incoming POST request
|
|
returns (tuple) - (file_storage, opening_balance, closing_balance, forced_mapping)
|
|
|
|
Steps:
|
|
1. Require a non-empty "statement_file" field
|
|
2. Parse optional opening_balance/closing_balance form fields
|
|
3. Parse optional forced_mapping form field (layout mapper work -
|
|
a JSON-stringified {"columnMap", "signConvention"?,
|
|
"ignoredRowRules"?, "dateFormat"?}, passed through to
|
|
pipeline_service.run unchanged; absent on every normal upload)
|
|
"""
|
|
file_storage = request.files.get("statement_file")
|
|
if not file_storage or not file_storage.filename:
|
|
raise ValidationError("Upload a statement PDF")
|
|
|
|
opening_balance = _opt_float(request.form.get("opening_balance", "").strip() or None)
|
|
closing_balance = _opt_float(request.form.get("closing_balance", "").strip() or None)
|
|
|
|
forced_mapping = None
|
|
raw_forced_mapping = request.form.get("forced_mapping", "").strip()
|
|
if raw_forced_mapping:
|
|
try:
|
|
forced_mapping = json.loads(raw_forced_mapping)
|
|
except ValueError:
|
|
raise ValidationError("forced_mapping must be valid JSON")
|
|
|
|
return file_storage, opening_balance, closing_balance, forced_mapping
|
|
|
|
|
|
def parse_recheck_request(json_body):
|
|
"""
|
|
Validates and extracts the /api/recheck JSON body.
|
|
|
|
Data flow:
|
|
json_body (dict) - the request's parsed JSON (or {} if absent/invalid)
|
|
returns (dict) - {transactions, page_reports, period, opening_balance,
|
|
closing_balance, narrative_direction}
|
|
"""
|
|
data = json_body or {}
|
|
return {
|
|
"transactions": data.get("transactions", []),
|
|
"page_reports": data.get("page_reports", []),
|
|
"period": data.get("period"),
|
|
"opening_balance": _opt_float(data.get("opening_balance")),
|
|
"closing_balance": _opt_float(data.get("closing_balance")),
|
|
"narrative_direction": data.get("narrative_direction"),
|
|
}
|
|
|
|
|
|
def parse_export_request(json_body):
|
|
"""
|
|
Validates and extracts the /api/export JSON body - same shape as
|
|
parse_recheck_request plus the fields the exported workbook itself
|
|
needs (brought_forward_balance, title, edit_log, categorization).
|
|
|
|
Data flow:
|
|
json_body (dict) - the request's parsed JSON (or {} if absent/invalid)
|
|
returns (dict) - parse_recheck_request's fields plus
|
|
brought_forward_balance, title, edit_log, and
|
|
categorization
|
|
|
|
edit_log is passed through unchanged (a plain list of {index, field,
|
|
oldValue, newValue, at, source} entries, already fully formed on the
|
|
frontend - see extractionStore.js's appendEditLogEntry) - this schema
|
|
doesn't inspect its own shape, same as it already doesn't for
|
|
transactions/page_reports; excel_service.py only writes an "Edits"
|
|
sheet at all when this is non-empty, so an export with no edits
|
|
doesn't gain an empty sheet nobody asked for.
|
|
|
|
categorization follows the exact same pass-through discipline - a
|
|
plain {"matched": [...], "unmatched": [...]} object computed entirely
|
|
client-side (see useCategorization.js), never inspected here;
|
|
excel_service.py only writes a "Categorized Summary" sheet when this
|
|
is present, so a project with no categorization rules yet gains no
|
|
empty sheet either.
|
|
"""
|
|
data = json_body or {}
|
|
parsed = parse_recheck_request(data)
|
|
parsed["brought_forward_balance"] = data.get("brought_forward_balance")
|
|
parsed["title"] = data.get("title") or "Statement Extraction"
|
|
parsed["edit_log"] = data.get("edit_log") or []
|
|
parsed["categorization"] = data.get("categorization") or None
|
|
return parsed
|
|
|
|
|
|
def parse_qbo_export_request(json_body):
|
|
"""
|
|
Validates and extracts the /api/export/qbo JSON body - everything
|
|
parse_export_request already does, plus the one new required field
|
|
this export format needs: `bank_account` ({"bankId", "accountId",
|
|
"accountType"}, resolved from a bankAccountProfiles record the
|
|
FRONTEND already fetched from PocketBase - this backend never talks
|
|
to PocketBase itself, same boundary every other route in this app
|
|
already respects).
|
|
|
|
Unlike every other field on this request, `bank_account` is
|
|
REQUIRED and validated for real (not passed through blindly like
|
|
edit_log/categorization) - a QBO file with a missing/malformed
|
|
<BANKACCTFROM> block is actively worse than no file at all (QuickBooks
|
|
would likely reject the whole import), where an export missing an
|
|
optional Excel sheet is harmless by comparison. (Renamed from this
|
|
function's own earlier parse_qfx_export_request 2026-11-19 - see
|
|
CLAUDE.md's ".qbo export" entry for why.)
|
|
"""
|
|
data = json_body or {}
|
|
parsed = parse_export_request(data)
|
|
bank_account = data.get("bank_account")
|
|
if not isinstance(bank_account, dict):
|
|
raise ValidationError("bank_account is required for a QBO export")
|
|
for field in ("bankId", "accountId", "accountType"):
|
|
if not (bank_account.get(field) or "").strip():
|
|
raise ValidationError(f"bank_account.{field} is required for a QBO export")
|
|
if bank_account["accountType"] not in ("CHECKING", "SAVINGS", "MONEYMRKT", "CREDITLINE"):
|
|
raise ValidationError("bank_account.accountType must be CHECKING, SAVINGS, MONEYMRKT, or CREDITLINE")
|
|
parsed["bank_account"] = bank_account
|
|
return parsed
|