bettersight-statement-extra.../backend/schemas/extraction_schema.py

99 lines
3.9 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).
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, and edit_log
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.
"""
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 []
return parsed