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.
fin_journals.py · 10.8 KB · 251 lines
| 1 | """Pre-write hook for fin_journals: balance before posting, closed periods |
| 2 | stay closed, and provenance markers are the machine's. |
| 3 | |
| 4 | Two cross-record gates here, both therefore hook territory |
| 5 | (plan/pre-write-hook-spec.md), a third rule that is NOT here, and a |
| 6 | fourth gate on who may write the provenance marker: |
| 7 | |
| 8 | 1. **A journal must balance before it posts.** The aggregate block on the |
| 9 | journal detail SHOWS debits vs credits, but nothing else stops an |
| 10 | unbalanced draft -> posted move -- the predecessor's own documented |
| 11 | weak spot. |
| 12 | |
| 13 | 2. **A closed period is closed.** Once a stretch of the books is settled |
| 14 | (fin_closed_periods), no journal may be created dated inside it, no |
| 15 | journal dated inside it may be edited, and none may be moved in or out |
| 16 | by changing its date. Without this, last year's "final" numbers stay |
| 17 | quietly editable forever -- the filed statements and the live books |
| 18 | drift apart with nobody deciding they should. Reopening is a deliberate |
| 19 | act (delete the period row, attributed in the change log), never a |
| 20 | side effect of an edit. |
| 21 | |
| 22 | That used to say "edited" and mean it literally: the delete path ran |
| 23 | no hook, so a journal dated in a closed year could not be re-described |
| 24 | but could be removed. A delete is now refused the same way. |
| 25 | |
| 26 | 3. **Posted is final** -- but not here. A posted journal cannot be edited |
| 27 | or deleted by anybody; that is the schema's `locked_when` rule on |
| 28 | `status: posted`, checked by object_records inside the write lock for |
| 29 | every writer, the composers included. It replaced nothing in this |
| 30 | hook: this hook never froze a posted journal at all, so its owner |
| 31 | could re-date one into another month's figures or delete it and leave |
| 32 | its lines pointing at nothing. |
| 33 | |
| 34 | 4. **A provenance marker is the machine's.** `generated_from` is how every |
| 35 | composer knows it has already booked a fact (object_finance. |
| 36 | compose_posted_journal scans for it, and the schema declares it |
| 37 | unique), so a journal carrying `payments/<id>` IS that payment's |
| 38 | journal as far as the books are concerned. It is not read_only -- |
| 39 | object_materialize and the composers write it through ordinary |
| 40 | storage-level calls -- and nothing stopped a person setting it: anybody |
| 41 | who could create a journal could plant `payments/<id>` (or |
| 42 | `fin_journals/<id>/reversal`, or a count's marker) on a draft of their |
| 43 | own, and that payment, reversal or variance was then never booked, |
| 44 | whoever owned it, because the composer answered "already composed". |
| 45 | Blanking the marker on a machine-made draft was the opposite hole: the |
| 46 | next pass composes the same fact again. Somebody who is not an admin |
| 47 | now may not set, change or clear it; a journal they type keeps it |
| 48 | blank. The composers write below this hook and are unaffected, and an |
| 49 | existing journal keeps editing normally as long as the marker is sent |
| 50 | back as it is. |
| 51 | |
| 52 | Rejection-only; never transforms. Ordinary edits to a draft journal in an |
| 53 | open period pass untouched. |
| 54 | |
| 55 | Gate 2 is also LOCKED_CHECK below, and that is the one that holds. This |
| 56 | hook runs only for HTTP writes, before the write lock; every composer |
| 57 | (payments, expenses, stock, wallets, bank lines, counts, recurring |
| 58 | entries) writes at the storage level, so until 2026-11-30 a period gate |
| 59 | here was a gate for human hands only: an expense incurred on the 15th and |
| 60 | approved after the month was closed posted into the closed month, and so |
| 61 | did a payment received on the 29th and recorded late (bug report |
| 62 | 2026-11-30-01-58-25-CST). The docstring used to call that "a case that |
| 63 | should surface"; it surfaced as a filed month that changed. fin_journals. |
| 64 | json now declares the rule as `locked_checks.closed_period`, which |
| 65 | object_records calls inside the write lock for every writer -- composers, |
| 66 | materialize, imports, MCP, seeds -- holding the `fin_periods` lock that |
| 67 | every write to fin_journal_lines and fin_closed_periods also takes, so a |
| 68 | period closed while a journal is being written is decided against, not |
| 69 | raced. The hook keeps its copy for the early answer (and so an HTTP write |
| 70 | is refused with this module's message rather than the locked check's |
| 71 | identical one). What a composer does INSTEAD of writing into a closed |
| 72 | period is object_finance.compose_posted_journal's decision: the first |
| 73 | open day after it, flagged period_review=pending. |
| 74 | |
| 75 | The period read is strict: if fin_closed_periods cannot be read the |
| 76 | answer is a 503, not "nothing is closed". The lock on settled books must |
| 77 | not open exactly when it cannot see. |
| 78 | """ |
| 79 | |
| 80 | import os |
| 81 | |
| 82 | import object_finance |
| 83 | import object_records |
| 84 | import object_schemas |
| 85 | |
| 86 | |
| 87 | def _base_dir(): |
| 88 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 89 | |
| 90 | |
| 91 | def _period_error(period, date): |
| 92 | reason = str(period.get("reason") or "").strip() |
| 93 | label = f" ({reason})" if reason else "" |
| 94 | return { |
| 95 | "error": (f"The books from {period.get('start_date')} to {period.get('end_date')} " |
| 96 | f"are closed{label}; {date} falls inside. Corrections to a settled " |
| 97 | "period are new journals dated in the current period -- or, " |
| 98 | "deliberately, reopen the period by removing its fin_closed_periods " |
| 99 | "row (that act is attributed in the change log)."), |
| 100 | "status": 409, |
| 101 | } |
| 102 | |
| 103 | |
| 104 | _PERIODS_UNREADABLE = { |
| 105 | "error": ("The closed periods could not be read, so nothing can say whether this " |
| 106 | "journal falls inside settled books. Nothing was changed."), |
| 107 | "status": 503, |
| 108 | } |
| 109 | |
| 110 | |
| 111 | def _is_admin(request): |
| 112 | roles = (request.get("subject") or {}).get("roles") or [] |
| 113 | return "admin" in roles |
| 114 | |
| 115 | |
| 116 | def _marker(row): |
| 117 | return str((row or {}).get("generated_from") or "").strip() |
| 118 | |
| 119 | |
| 120 | def BEFORE_WRITE(request): |
| 121 | action = request.get("action") |
| 122 | if action not in ("create", "update", "delete"): |
| 123 | return None |
| 124 | record = request.get("record") or {} |
| 125 | existing = request.get("existing") or {} |
| 126 | changes = request.get("changes") or {} |
| 127 | base = _base_dir() |
| 128 | |
| 129 | # --- gate 4: the provenance marker ------------------------------------- |
| 130 | # Compared as values, not by presence in `changes`: a form or client |
| 131 | # that sends the whole row back unchanged edits nothing. |
| 132 | if action in ("create", "update") and not _is_admin(request): |
| 133 | before = _marker(existing) if action == "update" else "" |
| 134 | after = _marker(record) |
| 135 | if after != before: |
| 136 | return { |
| 137 | "error": ("generated_from is the provenance marker a composer stamps on " |
| 138 | "the journal it books for a payment, a count, a reversal or a " |
| 139 | "schedule; it is not set or changed by hand. A journal you " |
| 140 | "type leaves it blank."), |
| 141 | "status": 409, |
| 142 | } |
| 143 | |
| 144 | # --- gate 2: closed periods ------------------------------------------ |
| 145 | owner = record.get("owner_id") or existing.get("owner_id") or "" |
| 146 | entity = record.get("entity_id") or existing.get("entity_id") or "" |
| 147 | |
| 148 | if action == "create": |
| 149 | dates = (record.get("date"),) |
| 150 | elif action == "update": |
| 151 | # Editing anything about a journal dated in a closed period is |
| 152 | # rewriting settled books; moving a date INTO one is backdating. |
| 153 | dates = (existing.get("date"), changes.get("date")) |
| 154 | else: |
| 155 | # Removing a journal dated in a closed period rewrites them more |
| 156 | # thoroughly than any edit. |
| 157 | dates = (existing.get("date"),) |
| 158 | for date in dates: |
| 159 | if not date: |
| 160 | continue |
| 161 | try: |
| 162 | period = object_finance.closed_period_for( |
| 163 | date, base_dir=base, owner_id=owner, entity_id=entity, strict=True) |
| 164 | except Exception: |
| 165 | return dict(_PERIODS_UNREADABLE) |
| 166 | if period is not None: |
| 167 | return _period_error(period, date) |
| 168 | |
| 169 | # --- gate 1: balance before posting ----------------------------------- |
| 170 | if action != "update": |
| 171 | return None |
| 172 | if changes.get("status") != "posted" or existing.get("status") == "posted": |
| 173 | return None |
| 174 | |
| 175 | journal_id = record.get("id") or existing.get("id") |
| 176 | lines = [ |
| 177 | line |
| 178 | for line in object_records.read_collection_records("fin_journal_lines", base_dir=base) |
| 179 | if line.get("journal_id") == journal_id |
| 180 | ] |
| 181 | if not lines: |
| 182 | return {"error": "Cannot post an empty journal - add lines first.", "status": 409} |
| 183 | |
| 184 | debits = sum(object_finance.to_cents(line.get("debit_cents")) for line in lines) |
| 185 | credits = sum(object_finance.to_cents(line.get("credit_cents")) for line in lines) |
| 186 | if debits != credits: |
| 187 | return { |
| 188 | "error": ( |
| 189 | "Journal must balance before posting: " |
| 190 | f"debits {debits} != credits {credits} (cents)." |
| 191 | ), |
| 192 | "status": 409, |
| 193 | } |
| 194 | return None |
| 195 | |
| 196 | |
| 197 | def _derived_fields(base): |
| 198 | """Fields no writer edits: computed rollups (debit/credit totals, |
| 199 | refreshed whenever a line moves) and read_only stamps. A change to |
| 200 | only these is the platform keeping a derived value current, not |
| 201 | somebody rewriting settled books -- the same exemption locked_when |
| 202 | makes. An unreadable schema exempts nothing (fail closed).""" |
| 203 | try: |
| 204 | schema = object_schemas.get_schema("fin_journals", base_dir=base) |
| 205 | except Exception: |
| 206 | return frozenset() |
| 207 | return frozenset( |
| 208 | field["name"] for field in schema.get("fields") or [] |
| 209 | if field.get("type") == "computed" or field.get("read_only")) |
| 210 | |
| 211 | |
| 212 | def LOCKED_CHECK(request): |
| 213 | """Gate 2, decided by object_records inside the write lock for every |
| 214 | writer (fin_journals.json `locked_checks.closed_period`; see the module |
| 215 | docstring). Reads only, and never asks who is writing: a closed period |
| 216 | binds the owner, an admin and a composer alike. |
| 217 | |
| 218 | Each side of the write is judged by its OWN owner, entity and date -- |
| 219 | the row on file (update, delete) and the row as it would be stored |
| 220 | (create, update) -- so moving a journal out of a closed period by |
| 221 | re-dating it, or by re-pointing its entity, is refused like moving one |
| 222 | in.""" |
| 223 | action = request.get("action") |
| 224 | record = request.get("record") or {} |
| 225 | existing = request.get("existing") or {} |
| 226 | base = request.get("base_dir") or _base_dir() |
| 227 | |
| 228 | sides = [] |
| 229 | if action in ("update", "delete"): |
| 230 | sides.append(existing) |
| 231 | if action in ("create", "update"): |
| 232 | sides.append(record) |
| 233 | if action == "update": |
| 234 | derived = _derived_fields(base) |
| 235 | names = (set(existing) | set(record)) - derived - {"id"} |
| 236 | if all(str(existing.get(n) or "") == str(record.get(n) or "") for n in names): |
| 237 | return None |
| 238 | |
| 239 | for row in sides: |
| 240 | date = row.get("date") |
| 241 | if not date: |
| 242 | continue |
| 243 | try: |
| 244 | period = object_finance.closed_period_for( |
| 245 | date, base_dir=base, owner_id=row.get("owner_id") or "", |
| 246 | entity_id=row.get("entity_id") or "", strict=True) |
| 247 | except Exception: |
| 248 | return dict(_PERIODS_UNREADABLE) |
| 249 | if period is not None: |
| 250 | return _period_error(period, date) |
| 251 | return None |