askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
bank_lines.py · 2.4 KB · 53 lines
| 1 | """Pre-write hook for bank_lines: what a schema cannot say. |
| 2 | |
| 3 | One job remains, and it is small. |
| 4 | |
| 5 | **On CREATE, stamp the line hash.** A CSV export rarely carries the bank's |
| 6 | own transaction id, so the fallback key is a content hash of date, amount |
| 7 | and description (plan/bank-import-reconciliation-spec.md section 2). The |
| 8 | schema declares `line_hash` unique per bank account, but a unique key |
| 9 | compares a stored value, and a line POSTed without one has none: this hook |
| 10 | computes it so that the key has something to hold. Nobody can write a |
| 11 | formula that is a sha256, so this stays code. |
| 12 | |
| 13 | Everything else this hook used to do is declared: |
| 14 | |
| 15 | - *A line marked `matched` must say what it matched* -- `required_when` on |
| 16 | `matched_to` (a status with no substance is a claim without evidence), for |
| 17 | every writer, on create as well as update, judged on the line as it will |
| 18 | be stored. |
| 19 | - *A statement line lands exactly once per bank account* -- the schema's two |
| 20 | `unique` keys (`external_id`, `line_hash`, each scoped to the bank |
| 21 | account), checked inside the write lock for every writer. The hook's own |
| 22 | read ran before the lock, so two overlapping posts of one line both |
| 23 | landed. |
| 24 | - *The bank's words are immutable* -- `locked_when` freezes every field |
| 25 | except the reconciliation work (`match_status`, `matched_to`, |
| 26 | `resolved_as`, `suggestions`, `owner_id`, `entity_id`), for every writer |
| 27 | and not only the public one. A correction comes from re-importing a |
| 28 | corrected statement, never from reshaping the evidence to agree with the |
| 29 | books. Deleting stays a permissions matter (`allow_delete`; the owner |
| 30 | fallback is denied in the rules). |
| 31 | - *matched_to is `collection/id`* -- `validation.pattern` on the field. |
| 32 | """ |
| 33 | |
| 34 | import object_banking |
| 35 | |
| 36 | |
| 37 | def BEFORE_WRITE(request): |
| 38 | if request.get("action") != "create": |
| 39 | return None |
| 40 | record = request.get("record") or {} |
| 41 | |
| 42 | if str(record.get("line_hash") or "").strip(): |
| 43 | return None |
| 44 | if not str(record.get("bank_account_id") or "").strip(): |
| 45 | return None # required-field validation owns this |
| 46 | try: |
| 47 | amount = int(record.get("amount_cents") or 0) |
| 48 | except (TypeError, ValueError): |
| 49 | return None # schema validation reports the type error properly |
| 50 | stamped = dict(record) |
| 51 | stamped["line_hash"] = object_banking.line_hash( |
| 52 | str(record.get("posted_on") or ""), amount, str(record.get("description") or "")) |
| 53 | return {"record": stamped} |