76 lines
2.8 KiB
Python
76 lines
2.8 KiB
Python
# Validates and shapes incoming request data for the extraction routes - no business logic beyond that.
|
|
|
|
|
|
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)
|
|
|
|
Steps:
|
|
1. Require a non-empty "statement_file" field
|
|
2. Parse optional opening_balance/closing_balance form fields
|
|
"""
|
|
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)
|
|
return file_storage, opening_balance, closing_balance
|
|
|
|
|
|
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).
|
|
|
|
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 and title
|
|
"""
|
|
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"
|
|
return parsed
|