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.
object_finance.py · 41.8 KB · 925 lines
| 1 | """Pure computed helpers over packages/app-finance's collections. |
| 2 | |
| 3 | Mirrors the predecessor system's own design for its finance app (reconciled |
| 4 | against a private predecessor-system audit, not part of this repo): journal |
| 5 | totals and the trial balance were COMPUTED PROPERTIES, folded from journal |
| 6 | lines on read, never stored or enforced. This module keeps that exact |
| 7 | posture: |
| 8 | |
| 9 | - journal_totals() folds fin_journal_lines for one journal into |
| 10 | (total_debits_cents, total_credits_cents, is_balanced). Nothing writes |
| 11 | these numbers back onto the journal record -- there is no totals- |
| 12 | stamping HANDLES handler in this package, unlike app-invoices' |
| 13 | invoice_totals or app-orders' order_totals. That absence is |
| 14 | deliberate: the source's own posting flow never enforced or cached a |
| 15 | balance either (posting is a bare draft->posted status flip -- see |
| 16 | packages/app-finance/schemas/fin_journals.json's status field help and |
| 17 | dbbasic-package.json's Deferred list). A future slice could add a |
| 18 | HANDLES handler that stamps a balance-check warning, but that would be |
| 19 | new behavior the source never had, so it stays out of this migration. |
| 20 | |
| 21 | - trial_balance() is the one report this v1 slice ships (the predecessor |
| 22 | system's own reports "filter posted lines", per the same reconciled |
| 23 | source audit). Profit & loss, balance sheet, and cash flow are the same |
| 24 | fold shape |
| 25 | over the same posted-lines data and are DEFERRED -- not built here |
| 26 | (see dbbasic-package.json's description). |
| 27 | |
| 28 | Both functions are read-only folds over object_records.read_collection_ |
| 29 | records(); base_dir is the caller's responsibility, same convention as |
| 30 | packages/app-invoices/objects/system/invoice_totals.py's own _data_dir() |
| 31 | helper (this module is a plain library, not a DBBASIC object, so it has |
| 32 | no request payload to read an identity or base_dir override from -- see |
| 33 | this module's own callers for how each resolves base_dir). |
| 34 | |
| 35 | Integer-cents arithmetic only, per 00-doctrine-and-contract.md: money is |
| 36 | always a whole number of cents, parsed defensively (blank/None -> 0) |
| 37 | since a hand-edited TSV row or a partially-filled form draft can leave a |
| 38 | *_cents field blank. |
| 39 | |
| 40 | compose_posted_journal() joined this module later, at the doctrine-#4 |
| 41 | extraction threshold (docs/logic-decisions.md): once system_books |
| 42 | (payments/refunds/bounces/issues), fin_recurring_runner (adjusting |
| 43 | entries), and action_reverse_journal (mirrors) had each hand-rolled the |
| 44 | same create-journal -> create-lines -> verify -> post sequence, the third |
| 45 | composer (system_stock_books, inventory losses) triggered the extraction. |
| 46 | Callers own POLICY (which accounts, what amount, when to compose); this |
| 47 | function owns MECHANICS (idempotency by provenance, draft -> lines -> |
| 48 | re-read -> verify balance -> post). Composed entries are storage-level |
| 49 | writes that bypass the HTTP-only balance hook, so the re-verify here is |
| 50 | the gate for every generated journal; the hook remains the gate for |
| 51 | human entries. |
| 52 | |
| 53 | profit_and_loss() and balance_sheet() close the gap this module's own |
| 54 | docstring flagged as deferred above and that plan/accounting-coverage- |
| 55 | and-usability.md's M1 calls the highest-value missing piece: the two |
| 56 | financial statements everything else in this codebase has been building |
| 57 | toward. Both are the same fold shape as trial_balance() -- posted-only, |
| 58 | owner-scoped the same non-negotiable way -- just re-bucketed by sign |
| 59 | convention per account type instead of by raw debit/credit columns. |
| 60 | Neither stores or caches anything; call them again and the numbers are |
| 61 | whatever the ledger says right now. |
| 62 | """ |
| 63 | from __future__ import annotations |
| 64 | |
| 65 | import datetime as _dt |
| 66 | from decimal import ROUND_FLOOR, Decimal |
| 67 | from pathlib import Path |
| 68 | from typing import Any, Iterable |
| 69 | |
| 70 | import object_collections |
| 71 | import object_ids |
| 72 | import object_records |
| 73 | from object_versions import DEFAULT_DATA_DIR |
| 74 | |
| 75 | # Chart-of-accounts display order for trial_balance rows: the conventional |
| 76 | # accounting statement order (assets, liabilities, equity, then income, |
| 77 | # expense), matching fin_accounts.json's account_type enum order. Any |
| 78 | # account_type not in this map (should not happen -- the schema enum is |
| 79 | # closed) sorts last rather than raising. |
| 80 | _ACCOUNT_TYPE_ORDER = { |
| 81 | "asset": 0, |
| 82 | "liability": 1, |
| 83 | "equity": 2, |
| 84 | "income": 3, |
| 85 | "expense": 4, |
| 86 | } |
| 87 | |
| 88 | _STATUS_POSTED = "posted" |
| 89 | |
| 90 | |
| 91 | def to_cents(value: Any) -> int: |
| 92 | """Parse a stored numeric string as an integer number of cents. |
| 93 | |
| 94 | THE defensive ledger parser for this codebase. Public because three |
| 95 | other modules had byte-identical private copies of it (app-invoices' |
| 96 | invoice_totals._to_int, app-orders' order_totals._to_int, and an |
| 97 | inlined bare int() in object_banking.reconciliation) -- one shared |
| 98 | floor-parser is one place to be right about rounding. |
| 99 | |
| 100 | Deliberately NOT the same function as object_money.to_minor (which |
| 101 | refuses inexact input) or object_money.quantize_minor (which rounds |
| 102 | half-up on request) or object_banking.parse_cents (which also strips |
| 103 | currency symbols and locale separators from bank exports). Those are |
| 104 | three different policies for three different jobs, and merging them |
| 105 | would silently change what a number means somewhere. |
| 106 | |
| 107 | Decimal (never a bare float) so a stray fractional value in a |
| 108 | hand-edited row can't introduce binary-float rounding error before |
| 109 | the floor -- same discipline invoice_totals.py's own _to_int uses. |
| 110 | Blank/None -> 0. |
| 111 | """ |
| 112 | text = str(value or "").strip() |
| 113 | if not text: |
| 114 | return 0 |
| 115 | return int(Decimal(text).to_integral_value(rounding=ROUND_FLOOR)) |
| 116 | |
| 117 | |
| 118 | # Historical private name, kept so this module's own callers stay unchanged. |
| 119 | _to_cents = to_cents |
| 120 | |
| 121 | |
| 122 | def journal_totals( |
| 123 | journal_id: str, |
| 124 | *, |
| 125 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 126 | roots: Iterable[Path] | None = None, |
| 127 | ) -> dict[str, Any]: |
| 128 | """Fold fin_journal_lines for one journal into computed totals. |
| 129 | |
| 130 | Returns {"total_debits_cents", "total_credits_cents", "is_balanced"}. |
| 131 | is_balanced is total_debits_cents == total_credits_cents -- true for |
| 132 | a journal with zero lines (0 == 0), same as any other computed- |
| 133 | property equality check. Nothing here checks whether journal_id |
| 134 | actually refers to an existing fin_journals record: a dangling or |
| 135 | unknown id simply folds zero matching lines and returns a balanced |
| 136 | zero total, the same graceful-empty behavior a fresh draft journal |
| 137 | (no lines yet) gets. |
| 138 | """ |
| 139 | lines = object_records.read_collection_records("fin_journal_lines", base_dir=base_dir, roots=roots) |
| 140 | |
| 141 | total_debits_cents = 0 |
| 142 | total_credits_cents = 0 |
| 143 | for line in lines: |
| 144 | if line.get("journal_id") != journal_id: |
| 145 | continue |
| 146 | total_debits_cents += _to_cents(line.get("debit_cents")) |
| 147 | total_credits_cents += _to_cents(line.get("credit_cents")) |
| 148 | |
| 149 | return { |
| 150 | "total_debits_cents": total_debits_cents, |
| 151 | "total_credits_cents": total_credits_cents, |
| 152 | "is_balanced": total_debits_cents == total_credits_cents, |
| 153 | } |
| 154 | |
| 155 | |
| 156 | def trial_balance( |
| 157 | *, |
| 158 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 159 | roots: Iterable[Path] | None = None, |
| 160 | owner: str | None = None, |
| 161 | ) -> list[dict[str, Any]]: |
| 162 | """Per-account debit/credit totals over POSTED journals only. |
| 163 | |
| 164 | Matches the source's own report semantics (reconciled against a |
| 165 | private predecessor-system audit, not part of this repo: reports |
| 166 | filter posted lines) -- a draft journal's lines never contribute, |
| 167 | with no separate "is this journal balanced" check |
| 168 | at all (that would be enforcement; the source never added it here |
| 169 | either, see this module's docstring). |
| 170 | |
| 171 | owner, when given, restricts the fold to journals owned by that |
| 172 | user (fin_journals.owner_id == owner) before any line is summed. |
| 173 | This is NOT a convenience filter -- callers that read a specific |
| 174 | user's financial data (e.g. packages/app-finance/objects/site/ |
| 175 | trial_balance.py) MUST pass owner=<that user's id>, because this |
| 176 | function reads collections directly via object_records and is not |
| 177 | itself subject to the row_filter owner_id=$user_id permission rule |
| 178 | that packages/app-finance/permissions/rules.json enforces on the |
| 179 | HTTP /collections/* API. Passing owner=None folds every owner's |
| 180 | posted journals together and is only appropriate for an operator/ |
| 181 | admin-level caller (nothing in this package calls it that way yet). |
| 182 | |
| 183 | Returns a list of {"account_id", "account_name", "account_code", |
| 184 | "account_type", "debit_total_cents", "credit_total_cents"} rows, one |
| 185 | per account that has at least one posted line -- accounts with zero |
| 186 | posted activity are omitted rather than listed at zero, since this |
| 187 | is a fold over lines, not an enumeration of the chart of accounts. |
| 188 | Sorted in conventional statement order (asset, liability, equity, |
| 189 | income, expense), then by account code/name within each type. |
| 190 | """ |
| 191 | journals = object_records.read_collection_records("fin_journals", base_dir=base_dir, roots=roots) |
| 192 | posted_journal_ids = { |
| 193 | journal.get("id") |
| 194 | for journal in journals |
| 195 | if journal.get("status") == _STATUS_POSTED |
| 196 | and (owner is None or journal.get("owner_id") == owner) |
| 197 | } |
| 198 | if not posted_journal_ids: |
| 199 | return [] |
| 200 | |
| 201 | lines = object_records.read_collection_records("fin_journal_lines", base_dir=base_dir, roots=roots) |
| 202 | totals_by_account: dict[str, list[int]] = {} |
| 203 | for line in lines: |
| 204 | if line.get("journal_id") not in posted_journal_ids: |
| 205 | continue |
| 206 | account_id = line.get("account_id") |
| 207 | if not account_id: |
| 208 | continue |
| 209 | bucket = totals_by_account.setdefault(account_id, [0, 0]) |
| 210 | bucket[0] += _to_cents(line.get("debit_cents")) |
| 211 | bucket[1] += _to_cents(line.get("credit_cents")) |
| 212 | |
| 213 | if not totals_by_account: |
| 214 | return [] |
| 215 | |
| 216 | accounts_by_id = { |
| 217 | account.get("id"): account |
| 218 | for account in object_records.read_collection_records("fin_accounts", base_dir=base_dir, roots=roots) |
| 219 | } |
| 220 | |
| 221 | rows = [] |
| 222 | for account_id, (debit_total_cents, credit_total_cents) in totals_by_account.items(): |
| 223 | account = accounts_by_id.get(account_id, {}) |
| 224 | rows.append({ |
| 225 | "account_id": account_id, |
| 226 | "account_name": account.get("name", ""), |
| 227 | "account_code": account.get("code", ""), |
| 228 | "account_type": account.get("account_type", ""), |
| 229 | "debit_total_cents": debit_total_cents, |
| 230 | "credit_total_cents": credit_total_cents, |
| 231 | }) |
| 232 | |
| 233 | rows.sort(key=lambda row: ( |
| 234 | _ACCOUNT_TYPE_ORDER.get(row["account_type"], 99), |
| 235 | row["account_code"], |
| 236 | row["account_name"], |
| 237 | )) |
| 238 | return rows |
| 239 | |
| 240 | |
| 241 | _UNREADABLE = object() # sentinel: could not scan fin_journals for a marker |
| 242 | |
| 243 | |
| 244 | def _scan_provenance(base_dir, generated_from): |
| 245 | try: |
| 246 | for row in object_records.read_collection_records("fin_journals", base_dir=base_dir): |
| 247 | if row.get("generated_from") == generated_from: |
| 248 | return row |
| 249 | except Exception: |
| 250 | return _UNREADABLE |
| 251 | return None |
| 252 | |
| 253 | |
| 254 | def find_journal_by_provenance(base_dir, generated_from): |
| 255 | """The fin_journals row stamped with this generated_from, else None. |
| 256 | |
| 257 | Unreadable books also return None -- callers that need the |
| 258 | do-not-risk-a-duplicate posture get it inside compose_posted_journal, |
| 259 | which distinguishes 'absent' from 'could not tell'. |
| 260 | """ |
| 261 | row = _scan_provenance(base_dir, generated_from) |
| 262 | return None if row is _UNREADABLE else row |
| 263 | |
| 264 | |
| 265 | UNREADABLE = _UNREADABLE |
| 266 | |
| 267 | |
| 268 | def accounts_missing(base_dir, account_ids): |
| 269 | """Public name of _accounts_missing, for a caller that wants to say |
| 270 | BEFORE writing anything whether its journal could be booked |
| 271 | (app-counter's waste action). UNREADABLE when the chart cannot be read.""" |
| 272 | return _accounts_missing(base_dir, account_ids) |
| 273 | |
| 274 | |
| 275 | def _accounts_missing(base_dir, account_ids): |
| 276 | """The account ids (in order, once each) the chart of accounts does not |
| 277 | have; [] when all exist; _UNREADABLE when fin_accounts cannot be read. |
| 278 | A blank id is missing.""" |
| 279 | try: |
| 280 | chart = {str(row.get("id") or "") for row in |
| 281 | object_records.read_collection_records("fin_accounts", base_dir=base_dir)} |
| 282 | except Exception: |
| 283 | return _UNREADABLE |
| 284 | out = [] |
| 285 | for account_id in account_ids: |
| 286 | if (not account_id or account_id not in chart) and account_id not in out: |
| 287 | out.append(account_id) |
| 288 | return out |
| 289 | |
| 290 | |
| 291 | def compose_posted_journal(base_dir, *, generated_from, date, description, |
| 292 | lines, owner_id, entity_id="", kind="standard", |
| 293 | actor="object_finance", post=True, if_closed="next_open"): |
| 294 | """Compose one journal from line specs and post it when balanced. |
| 295 | |
| 296 | lines: iterable of {"account_id", "debit_cents", "credit_cents", |
| 297 | optional "memo", optional "entity_id" (defaults to the journal's)}. |
| 298 | Returns {"ok": True, ...} shapes: |
| 299 | already composed -> {"ok", "skipped", "journal_id", "posted"} |
| 300 | nothing to book -> {"ok", "skipped"} |
| 301 | composed -> {"ok", "journal_id", "posted", maybe "note", |
| 302 | maybe "redated"} |
| 303 | and {"ok": False, "error"} for unusable line amounts, or (if_closed= |
| 304 | "refuse") a date inside a closed period. post=False composes but |
| 305 | always leaves the draft (recurring templates without auto_post). |
| 306 | |
| 307 | A date inside a closed period (fin_closed_periods) is never written. |
| 308 | Every composer used to write it anyway: they write below the HTTP hook |
| 309 | that holds the period lock, so a payment received on the 29th and |
| 310 | recorded after the month was closed posted into the closed month, and |
| 311 | nothing told anybody (bug report 2026-11-30-01-58-25-CST, composed |
| 312 | journals post into closed periods). The lock itself is now the schema's locked check |
| 313 | (hook_fin_journals.LOCKED_CHECK), so a write into a closed period is |
| 314 | refused whoever makes it; this function decides what a composer does |
| 315 | instead, before it gets that far: |
| 316 | |
| 317 | if_closed="next_open" (the default): book on the first day after the |
| 318 | closed period(s) covering the natural date -- the ordinary practice |
| 319 | for a late-arriving fact in settled books, and the only answer for |
| 320 | a reaction nobody is watching (refusing would leave a payment that |
| 321 | really arrived off the books for good). The journal says so three |
| 322 | ways: occurred_on keeps the natural date, period_review is |
| 323 | "pending" (counted on the attention board until somebody marks it |
| 324 | reviewed), and the description names the closed period. The |
| 325 | result carries "redated". |
| 326 | if_closed="refuse": answer {"ok": False, "error", "closed_period"} |
| 327 | and write nothing -- for a person at the keyboard who can pick the |
| 328 | date (action_reverse_journal). |
| 329 | |
| 330 | The period read is strict: closed periods that cannot be read raise |
| 331 | (as the locked check would at the write) rather than read as open. |
| 332 | """ |
| 333 | normalized, debits, credits = [], 0, 0 |
| 334 | for spec in lines or []: |
| 335 | if not isinstance(spec, dict): |
| 336 | continue |
| 337 | try: |
| 338 | dr = int(spec.get("debit_cents") or 0) |
| 339 | cr = int(spec.get("credit_cents") or 0) |
| 340 | except (TypeError, ValueError): |
| 341 | return {"ok": False, "error": "line amounts must be integer cents"} |
| 342 | if dr < 0 or cr < 0: |
| 343 | return {"ok": False, "error": "line amounts must not be negative"} |
| 344 | debits += dr |
| 345 | credits += cr |
| 346 | normalized.append({ |
| 347 | "account_id": str(spec.get("account_id") or ""), |
| 348 | "debit_cents": str(dr), |
| 349 | "credit_cents": str(cr), |
| 350 | "memo": str(spec.get("memo") or ""), |
| 351 | "entity_id": str(spec.get("entity_id") or entity_id or ""), |
| 352 | }) |
| 353 | |
| 354 | if generated_from: |
| 355 | existing = _scan_provenance(base_dir, generated_from) |
| 356 | if existing is _UNREADABLE: |
| 357 | return {"ok": True, "skipped": "books unreadable; not risking a duplicate"} |
| 358 | if existing is not None: |
| 359 | return {"ok": True, "skipped": f"already composed: {generated_from}", |
| 360 | "journal_id": existing.get("id"), |
| 361 | "posted": existing.get("status") == "posted"} |
| 362 | |
| 363 | if not normalized or (debits == 0 and credits == 0): |
| 364 | return {"ok": True, "skipped": "zero amount"} |
| 365 | |
| 366 | # Every account must exist in the chart BEFORE the header is written. |
| 367 | # A line naming an account the chart does not have is refused by the |
| 368 | # line's relation check -- after the header already landed -- so a box |
| 369 | # with account settings but no chart of accounts got a silent EMPTY |
| 370 | # draft journal for every waste move (Corner Cup, a Haiku simulation of |
| 371 | # a counter cafe): nothing booked, and nothing said so. Now nothing is |
| 372 | # written and the answer names the accounts the chart lacks. |
| 373 | missing = _accounts_missing(base_dir, [spec["account_id"] for spec in normalized]) |
| 374 | if missing is _UNREADABLE: |
| 375 | return {"ok": False, "error": ("The chart of accounts (fin_accounts) could not be " |
| 376 | "read, so nothing was booked."), |
| 377 | "books_unreadable": True} |
| 378 | if missing: |
| 379 | return {"ok": False, "missing_accounts": missing, |
| 380 | "error": (f"The chart of accounts has no account " |
| 381 | f"{', '.join(repr(a) for a in missing)}, so nothing was booked. " |
| 382 | f"Set up the chart of accounts (fin_accounts) or point the " |
| 383 | f"setting at an account that exists.")} |
| 384 | |
| 385 | journal_id = object_ids.new_uuid4() |
| 386 | natural = str(date or "") |
| 387 | redated = None |
| 388 | # Two looks at most: the second only when a period was closed between |
| 389 | # the first look and the header write (the locked check refused it). |
| 390 | for attempt in (1, 2): |
| 391 | booked, passed = (next_open_date(natural, base_dir=base_dir, |
| 392 | owner_id=owner_id or "", entity_id=entity_id or "") |
| 393 | if natural else ("", [])) |
| 394 | if passed and if_closed == "refuse": |
| 395 | first = passed[0] |
| 396 | return {"ok": False, |
| 397 | "error": (f"{natural[:10]} falls in a closed period ({first.get('start_date')} " |
| 398 | f"to {first.get('end_date')}); nothing was booked."), |
| 399 | "closed_period": {"id": first.get("id", ""), |
| 400 | "start_date": first.get("start_date", ""), |
| 401 | "end_date": first.get("end_date", "")}} |
| 402 | journal = { |
| 403 | "id": journal_id, |
| 404 | "date": booked if passed else natural, |
| 405 | "description": description or "", |
| 406 | "status": "draft", |
| 407 | "generated_from": generated_from or "", |
| 408 | "kind": kind, |
| 409 | "owner_id": owner_id or "", |
| 410 | } |
| 411 | redated = None |
| 412 | if passed: |
| 413 | redated = _redated(natural, booked, passed) |
| 414 | journal["description"] = _redated_description(description or "", redated) |
| 415 | journal["occurred_on"] = redated["occurred_on"] |
| 416 | journal["period_review"] = "pending" |
| 417 | if entity_id: |
| 418 | journal["entity_id"] = entity_id |
| 419 | try: |
| 420 | object_records.create_collection_record( |
| 421 | "fin_journals", journal, base_dir=base_dir, actor=actor, |
| 422 | allow_computed_submission=False, |
| 423 | # occurred_on is read_only: no client sets it, a composer does. |
| 424 | preserve_read_only=bool(passed), |
| 425 | ) |
| 426 | except object_records.CheckRefusedError as exc: |
| 427 | if (attempt == 2 or exc.check != PERIOD_CHECK |
| 428 | or exc.code != "check_refused"): |
| 429 | raise |
| 430 | continue |
| 431 | except object_records.UniqueConstraintError as exc: |
| 432 | break_with = _already_composed(base_dir, generated_from, exc) |
| 433 | if break_with is None: |
| 434 | raise |
| 435 | return break_with |
| 436 | break |
| 437 | for spec in normalized: |
| 438 | line = { |
| 439 | "id": object_ids.new_uuid4(), |
| 440 | "journal_id": journal_id, |
| 441 | "account_id": spec["account_id"], |
| 442 | "debit_cents": spec["debit_cents"], |
| 443 | "credit_cents": spec["credit_cents"], |
| 444 | "owner_id": owner_id or "", |
| 445 | } |
| 446 | if spec["memo"]: |
| 447 | line["memo"] = spec["memo"] |
| 448 | if spec["entity_id"]: |
| 449 | line["entity_id"] = spec["entity_id"] |
| 450 | object_records.create_collection_record( |
| 451 | "fin_journal_lines", line, base_dir=base_dir, actor=actor |
| 452 | ) |
| 453 | |
| 454 | # Balanced by construction; verify by RE-READING what actually landed |
| 455 | # before posting (a failed line write must never post a lopsided entry). |
| 456 | landed = journal_totals(journal_id, base_dir=base_dir) |
| 457 | extra = {"redated": redated} if redated else {} |
| 458 | if (post and landed["is_balanced"] and landed["total_debits_cents"] > 0): |
| 459 | object_records.update_collection_record( |
| 460 | "fin_journals", journal_id, {"status": "posted"}, |
| 461 | base_dir=base_dir, actor=actor, |
| 462 | ) |
| 463 | return {"ok": True, "journal_id": journal_id, "posted": True, **extra} |
| 464 | note = ("left draft: did not balance" if not landed["is_balanced"] |
| 465 | else "left draft: post not requested") |
| 466 | return {"ok": True, "journal_id": journal_id, "posted": False, "note": note, **extra} |
| 467 | |
| 468 | |
| 469 | def _already_composed(base_dir, generated_from, exc): |
| 470 | """The answer for a header refused by the unique generated_from, or |
| 471 | None for any other unique key (which stays an error).""" |
| 472 | # fin_journals declares generated_from unique, checked inside the |
| 473 | # write lock. The provenance scan above runs before it, so two |
| 474 | # callers that overlapped (two clicks on Reverse, a handler and a |
| 475 | # replay of the same event) both found nothing and both composed: |
| 476 | # four mirrors of one journal posted. The header is written before |
| 477 | # any line, so the one that loses here has written nothing; it is |
| 478 | # answered exactly as a later call would be. |
| 479 | if "generated_from" not in exc.fields: |
| 480 | return None |
| 481 | holder = {} |
| 482 | try: |
| 483 | holder = object_records.get_collection_record( |
| 484 | "fin_journals", exc.existing_id, base_dir=base_dir) |
| 485 | except Exception: |
| 486 | pass |
| 487 | return {"ok": True, "skipped": f"already composed: {generated_from}", |
| 488 | "journal_id": exc.existing_id, |
| 489 | "posted": holder.get("status") == "posted"} |
| 490 | |
| 491 | |
| 492 | # The name of hook_fin_journals' locked check (fin_journals.json |
| 493 | # `locked_checks`), so a refusal from it is told apart from any other. |
| 494 | PERIOD_CHECK = "closed_period" |
| 495 | |
| 496 | # description's schema max_length; a redated note must fit inside it. |
| 497 | _DESCRIPTION_MAX = 300 |
| 498 | |
| 499 | |
| 500 | def next_open_date(date_text, *, base_dir: Path | str = DEFAULT_DATA_DIR, |
| 501 | owner_id: str = "", entity_id: str = "") -> tuple[str, list[dict]]: |
| 502 | """(the first date on or after date_text no closed period covers, the |
| 503 | closed periods passed over to reach it -- empty when date_text is open). |
| 504 | |
| 505 | "The next open period" is the day after the covering period ends, and |
| 506 | again after that if the next stretch is closed too (November closed, |
| 507 | then December: a late November payment lands on January 1). Each step |
| 508 | moves strictly forward, so it ends. Always strict: an unreadable |
| 509 | fin_closed_periods raises, because an answer of "open" from books it |
| 510 | cannot see is exactly the write the lock exists to stop. |
| 511 | """ |
| 512 | current = str(date_text or "").strip()[:10] |
| 513 | passed: list[dict] = [] |
| 514 | while current: |
| 515 | period = closed_period_for(current, base_dir=base_dir, owner_id=owner_id, |
| 516 | entity_id=entity_id, strict=True) |
| 517 | if period is None: |
| 518 | break |
| 519 | passed.append(period) |
| 520 | end = _dt.date.fromisoformat(str(period.get("end_date") or "")[:10]) |
| 521 | current = (end + _dt.timedelta(days=1)).isoformat() |
| 522 | return current, passed |
| 523 | |
| 524 | |
| 525 | def _redated(natural, booked, passed): |
| 526 | return { |
| 527 | "occurred_on": str(natural)[:10], |
| 528 | "date": booked, |
| 529 | "closed_periods": [{"id": p.get("id", ""), "start_date": p.get("start_date", ""), |
| 530 | "end_date": p.get("end_date", ""), "reason": p.get("reason", "")} |
| 531 | for p in passed], |
| 532 | "message": (f"{str(natural)[:10]} falls in the closed period " |
| 533 | f"{passed[0].get('start_date')} to {passed[-1].get('end_date')}; " |
| 534 | f"booked on {booked}, the first open day, and flagged for review."), |
| 535 | } |
| 536 | |
| 537 | |
| 538 | def _redated_description(description, redated): |
| 539 | suffix = (f" [{redated['occurred_on']} fell in closed period " |
| 540 | f"{redated['closed_periods'][0]['start_date']} to " |
| 541 | f"{redated['closed_periods'][-1]['end_date']}]") |
| 542 | return description[:max(0, _DESCRIPTION_MAX - len(suffix))] + suffix |
| 543 | |
| 544 | |
| 545 | def _date_in_range(date_value: Any, start: str, end: str) -> bool: |
| 546 | """True when a journal's date string falls within the closed range |
| 547 | [start, end], where either bound blank means "unbounded on that side" |
| 548 | -- the same convention the page-level query params (?start=&end=& |
| 549 | as_of=) use: an unset param means "don't filter this side", not some |
| 550 | sentinel date. |
| 551 | |
| 552 | Dates are stored as plain ISO 8601 strings (fin_journals.date, schema |
| 553 | type "date"), and ISO 8601 dates sort correctly as plain strings, so |
| 554 | this is a string comparison, never a date-parsing exercise -- the |
| 555 | same "don't reach for machinery you don't need" posture the rest of |
| 556 | this module takes with money (Decimal only where floor-rounding |
| 557 | actually matters, plain int/str everywhere else). A journal with a |
| 558 | blank date (should not happen -- the schema marks it required, but a |
| 559 | hand-edited TSV row or a partially-written draft can still produce |
| 560 | one) sorts before every real date string and is therefore excluded by |
| 561 | any non-blank start, which is the conservative choice for a report: |
| 562 | an ambiguous-dated entry should not silently count as "in period" |
| 563 | just because blank comes first alphabetically. |
| 564 | """ |
| 565 | date_text = str(date_value or "") |
| 566 | if start and date_text < start: |
| 567 | return False |
| 568 | if end and date_text > end: |
| 569 | return False |
| 570 | return True |
| 571 | |
| 572 | |
| 573 | def _posted_journal_ids( |
| 574 | journals: list[dict[str, Any]], *, owner: str | None, entity_id: str, start: str, end: str, |
| 575 | ) -> set[str]: |
| 576 | """Shared posted+owner+entity+date filter for profit_and_loss/balance_sheet. |
| 577 | |
| 578 | Factored out of trial_balance's inline version (which has no date or |
| 579 | entity filter -- it folds every posted journal an owner has ever |
| 580 | made) because both statements below need the identical four-way |
| 581 | filter and a subtle bug in one copy silently disagreeing with the |
| 582 | other would be far worse here than in trial_balance's simpler case: |
| 583 | the balance sheet's whole reason to exist is to say, loudly, when the |
| 584 | ledger disagrees with itself. |
| 585 | """ |
| 586 | return { |
| 587 | journal.get("id") |
| 588 | for journal in journals |
| 589 | if journal.get("status") == _STATUS_POSTED |
| 590 | and (owner is None or journal.get("owner_id") == owner) |
| 591 | and (not entity_id or journal.get("entity_id") == entity_id) |
| 592 | and _date_in_range(journal.get("date"), start, end) |
| 593 | } |
| 594 | |
| 595 | |
| 596 | def _fold_account_totals( |
| 597 | posted_journal_ids: set[str], *, base_dir, roots, |
| 598 | ) -> dict[str, list[int]]: |
| 599 | """Fold fin_journal_lines into {account_id: [debit_cents, credit_cents]} |
| 600 | for exactly the given set of already-filtered posted journal ids. |
| 601 | Lines with no account_id are skipped (same defensive posture as |
| 602 | trial_balance -- a hand-edited or partially-written row should not |
| 603 | crash a report). Returns an empty dict, not an error, when the id set |
| 604 | or the resulting totals are empty -- an empty ledger is a normal |
| 605 | input to a report, not a failure. |
| 606 | """ |
| 607 | totals_by_account: dict[str, list[int]] = {} |
| 608 | if not posted_journal_ids: |
| 609 | return totals_by_account |
| 610 | lines = object_records.read_collection_records("fin_journal_lines", base_dir=base_dir, roots=roots) |
| 611 | for line in lines: |
| 612 | if line.get("journal_id") not in posted_journal_ids: |
| 613 | continue |
| 614 | account_id = line.get("account_id") |
| 615 | if not account_id: |
| 616 | continue |
| 617 | bucket = totals_by_account.setdefault(account_id, [0, 0]) |
| 618 | bucket[0] += _to_cents(line.get("debit_cents")) |
| 619 | bucket[1] += _to_cents(line.get("credit_cents")) |
| 620 | return totals_by_account |
| 621 | |
| 622 | |
| 623 | def profit_and_loss( |
| 624 | *, |
| 625 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 626 | owner: str | None = None, |
| 627 | roots: Iterable[Path] | None = None, |
| 628 | start: str = "", |
| 629 | end: str = "", |
| 630 | entity_id: str = "", |
| 631 | ) -> dict[str, Any]: |
| 632 | """Income statement: income and expense accounts, folded over POSTED |
| 633 | journals dated within [start, end] (either bound blank = unbounded). |
| 634 | |
| 635 | Sign convention -- the one thing a P&L must get exactly right, since |
| 636 | getting it backwards silently reports a profit as a loss and vice |
| 637 | versa: income accounts are CREDIT-normal (a sale credits revenue), so |
| 638 | each income row's amount_cents is (credit_total - debit_total) for |
| 639 | that account. Expense accounts are DEBIT-normal (a purchase debits |
| 640 | the expense), so each expense row's amount_cents is (debit_total - |
| 641 | credit_total). Both are reported as the account's activity in its |
| 642 | OWN natural direction -- a normal, healthy account of either type |
| 643 | therefore shows a positive amount_cents; a negative amount_cents is |
| 644 | not a bug, it is the report correctly saying that account ran |
| 645 | contra to its own type (e.g. a revenue account with more debits than |
| 646 | credits, from refunds booked straight to it rather than to a contra- |
| 647 | revenue account -- this package has no contra-account convention, so |
| 648 | that is exactly what a heavy refund period looks like here). |
| 649 | |
| 650 | owner, when given, restricts the fold to journals owned by that user |
| 651 | -- the same non-negotiable contract trial_balance() documents: this |
| 652 | function reads collections directly via object_records and is NOT |
| 653 | subject to permissions/rules.json's row_filter the way the HTTP |
| 654 | /collections/* API is, so any caller serving one user's data MUST |
| 655 | pass owner=<that user's id>. entity_id, when given, additionally |
| 656 | restricts to journals tagged with that entity (65 multi-entity); |
| 657 | blank means "don't filter by entity" -- the same posture as a plain |
| 658 | text field with no relation enforcement elsewhere in this schema. |
| 659 | |
| 660 | Returns {"period": {"start", "end"}, "income": [rows], "expenses": |
| 661 | [rows], "total_income_cents", "total_expenses_cents", |
| 662 | "net_income_cents"} where each row is {"account_id", "account_name", |
| 663 | "account_code", "amount_cents"}. net_income_cents is |
| 664 | total_income_cents - total_expenses_cents (a negative value is a net |
| 665 | loss for the period, reported as-is, never clamped to zero). Accounts |
| 666 | with zero net posted activity in the period are omitted, matching |
| 667 | trial_balance's "fold over lines, not an enumeration of the chart of |
| 668 | accounts" posture. Rows are sorted by account code then name. An |
| 669 | empty or nonexistent ledger returns all-zero totals and empty row |
| 670 | lists rather than raising. |
| 671 | """ |
| 672 | journals = object_records.read_collection_records("fin_journals", base_dir=base_dir, roots=roots) |
| 673 | posted_journal_ids = _posted_journal_ids( |
| 674 | journals, owner=owner, entity_id=entity_id, start=start, end=end) |
| 675 | |
| 676 | period = {"start": start, "end": end} |
| 677 | empty = { |
| 678 | "period": period, |
| 679 | "income": [], |
| 680 | "expenses": [], |
| 681 | "total_income_cents": 0, |
| 682 | "total_expenses_cents": 0, |
| 683 | "net_income_cents": 0, |
| 684 | } |
| 685 | if not posted_journal_ids: |
| 686 | return empty |
| 687 | |
| 688 | totals_by_account = _fold_account_totals(posted_journal_ids, base_dir=base_dir, roots=roots) |
| 689 | if not totals_by_account: |
| 690 | return empty |
| 691 | |
| 692 | accounts_by_id = { |
| 693 | account.get("id"): account |
| 694 | for account in object_records.read_collection_records("fin_accounts", base_dir=base_dir, roots=roots) |
| 695 | } |
| 696 | |
| 697 | income_rows: list[dict[str, Any]] = [] |
| 698 | expense_rows: list[dict[str, Any]] = [] |
| 699 | total_income_cents = 0 |
| 700 | total_expenses_cents = 0 |
| 701 | for account_id, (debit_total_cents, credit_total_cents) in totals_by_account.items(): |
| 702 | account = accounts_by_id.get(account_id, {}) |
| 703 | account_type = account.get("account_type", "") |
| 704 | row = { |
| 705 | "account_id": account_id, |
| 706 | "account_name": account.get("name", ""), |
| 707 | "account_code": account.get("code", ""), |
| 708 | } |
| 709 | if account_type == "income": |
| 710 | amount_cents = credit_total_cents - debit_total_cents |
| 711 | income_rows.append({**row, "amount_cents": amount_cents}) |
| 712 | total_income_cents += amount_cents |
| 713 | elif account_type == "expense": |
| 714 | amount_cents = debit_total_cents - credit_total_cents |
| 715 | expense_rows.append({**row, "amount_cents": amount_cents}) |
| 716 | total_expenses_cents += amount_cents |
| 717 | # asset/liability/equity accounts don't belong on a P&L at all -- |
| 718 | # skipped here, not an error; they surface on balance_sheet(). |
| 719 | |
| 720 | def _sort_key(entry: dict[str, Any]) -> tuple[str, str]: |
| 721 | return (entry["account_code"], entry["account_name"]) |
| 722 | |
| 723 | income_rows.sort(key=_sort_key) |
| 724 | expense_rows.sort(key=_sort_key) |
| 725 | |
| 726 | return { |
| 727 | "period": period, |
| 728 | "income": income_rows, |
| 729 | "expenses": expense_rows, |
| 730 | "total_income_cents": total_income_cents, |
| 731 | "total_expenses_cents": total_expenses_cents, |
| 732 | "net_income_cents": total_income_cents - total_expenses_cents, |
| 733 | } |
| 734 | |
| 735 | |
| 736 | def balance_sheet( |
| 737 | *, |
| 738 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 739 | owner: str | None = None, |
| 740 | roots: Iterable[Path] | None = None, |
| 741 | as_of: str = "", |
| 742 | entity_id: str = "", |
| 743 | ) -> dict[str, Any]: |
| 744 | """Balance sheet: assets, liabilities, and equity as of a date (blank |
| 745 | as_of = every posted journal, no upper bound). |
| 746 | |
| 747 | Sign convention: asset accounts are DEBIT-normal, so each asset row's |
| 748 | amount_cents is (debit_total - credit_total). Liability and equity |
| 749 | accounts are CREDIT-normal, so each of their rows is (credit_total - |
| 750 | debit_total). Same "own natural direction" reporting posture as |
| 751 | profit_and_loss() -- a negative amount_cents means that account ran |
| 752 | contra to its own type, which is reported plainly rather than hidden. |
| 753 | |
| 754 | CRITICAL, and the reason this docstring is long: the fundamental |
| 755 | accounting equation (assets == liabilities + equity) only holds once |
| 756 | the CURRENT period's net income is folded into equity. A stored |
| 757 | equity account only accumulates what has actually been posted TO it |
| 758 | (owner contributions, prior retained earnings, draws) -- nothing in |
| 759 | this package's posting flow ever sweeps a period's income and |
| 760 | expense accounts into an equity account, because that sweep is a |
| 761 | year-end CLOSE, and fin_journals.kind's "closing" enum value is |
| 762 | reserved for exactly that close and is deliberately not built yet |
| 763 | (see this module's and dbbasic-package.json's Deferred notes). Until |
| 764 | a real close exists, this function computes net income itself (via |
| 765 | profit_and_loss() over every posted journal up to as_of, no lower |
| 766 | bound -- life-to-date earnings, not just one period) and adds it as |
| 767 | ONE SYNTHETIC LINE in the equity section, labelled "Current period |
| 768 | earnings" with an empty account_id/account_code. This line is |
| 769 | DERIVED, not a stored fin_accounts row -- it does not appear in the |
| 770 | chart of accounts, has no journal lines of its own, and would |
| 771 | disappear (correctly) the moment a real close journal swept income |
| 772 | and expense into retained earnings and this function were pointed at |
| 773 | books that had already been closed. Treat it as a plug that keeps |
| 774 | the equation honest pre-close, not as a feature to build further |
| 775 | reports on top of. |
| 776 | |
| 777 | owner and entity_id have the same contract as profit_and_loss(): pass |
| 778 | owner=<user id> to scope to that user's books (this function is NOT |
| 779 | subject to permissions/rules.json's row_filter, same non-negotiable |
| 780 | posture as trial_balance() and profit_and_loss()); entity_id, when |
| 781 | given, additionally restricts to one set of books. |
| 782 | |
| 783 | Returns {"as_of", "assets": [rows], "liabilities": [rows], "equity": |
| 784 | [rows] (stored equity accounts, then the synthetic earnings line |
| 785 | last), "total_assets_cents", "total_liabilities_cents", |
| 786 | "total_equity_cents" (includes the synthetic line), |
| 787 | "balances": bool, "difference_cents"}. "balances" is exactly |
| 788 | total_assets_cents == total_liabilities_cents + total_equity_cents. |
| 789 | difference_cents is total_assets_cents - (total_liabilities_cents + |
| 790 | total_equity_cents), signed and exact -- NEVER rounded, abs()'d, or |
| 791 | silently swallowed. THIS IS THE SINGLE MOST VALUABLE THING THIS |
| 792 | FUNCTION DOES: a balance sheet that does not balance means the ledger |
| 793 | itself is broken (a line written with only one side, a partial write |
| 794 | that lost its balancing leg, a bypass of compose_posted_journal's |
| 795 | re-verify-before-post gate) and callers MUST surface "balances" and |
| 796 | "difference_cents" prominently rather than rendering the statement as |
| 797 | if everything is fine -- silence here is the failure mode this |
| 798 | function exists to prevent. |
| 799 | """ |
| 800 | journals = object_records.read_collection_records("fin_journals", base_dir=base_dir, roots=roots) |
| 801 | posted_journal_ids = _posted_journal_ids( |
| 802 | journals, owner=owner, entity_id=entity_id, start="", end=as_of) |
| 803 | |
| 804 | totals_by_account = _fold_account_totals(posted_journal_ids, base_dir=base_dir, roots=roots) |
| 805 | |
| 806 | accounts_by_id = { |
| 807 | account.get("id"): account |
| 808 | for account in object_records.read_collection_records("fin_accounts", base_dir=base_dir, roots=roots) |
| 809 | } |
| 810 | |
| 811 | assets: list[dict[str, Any]] = [] |
| 812 | liabilities: list[dict[str, Any]] = [] |
| 813 | equity: list[dict[str, Any]] = [] |
| 814 | total_assets_cents = 0 |
| 815 | total_liabilities_cents = 0 |
| 816 | total_equity_cents = 0 |
| 817 | for account_id, (debit_total_cents, credit_total_cents) in totals_by_account.items(): |
| 818 | account = accounts_by_id.get(account_id, {}) |
| 819 | account_type = account.get("account_type", "") |
| 820 | row = { |
| 821 | "account_id": account_id, |
| 822 | "account_name": account.get("name", ""), |
| 823 | "account_code": account.get("code", ""), |
| 824 | } |
| 825 | if account_type == "asset": |
| 826 | amount_cents = debit_total_cents - credit_total_cents |
| 827 | assets.append({**row, "amount_cents": amount_cents}) |
| 828 | total_assets_cents += amount_cents |
| 829 | elif account_type == "liability": |
| 830 | amount_cents = credit_total_cents - debit_total_cents |
| 831 | liabilities.append({**row, "amount_cents": amount_cents}) |
| 832 | total_liabilities_cents += amount_cents |
| 833 | elif account_type == "equity": |
| 834 | amount_cents = credit_total_cents - debit_total_cents |
| 835 | equity.append({**row, "amount_cents": amount_cents}) |
| 836 | total_equity_cents += amount_cents |
| 837 | # income/expense accounts don't get their own balance-sheet row -- |
| 838 | # their life-to-date net folds into the synthetic earnings line |
| 839 | # below instead, per this function's docstring. |
| 840 | |
| 841 | def _sort_key(entry: dict[str, Any]) -> tuple[str, str]: |
| 842 | return (entry["account_code"], entry["account_name"]) |
| 843 | |
| 844 | assets.sort(key=_sort_key) |
| 845 | liabilities.sort(key=_sort_key) |
| 846 | equity.sort(key=_sort_key) |
| 847 | |
| 848 | pl = profit_and_loss(base_dir=base_dir, owner=owner, roots=roots, start="", end=as_of, entity_id=entity_id) |
| 849 | net_income_cents = pl["net_income_cents"] |
| 850 | equity.append({ |
| 851 | "account_id": "", |
| 852 | "account_name": "Current period earnings", |
| 853 | "account_code": "", |
| 854 | "amount_cents": net_income_cents, |
| 855 | }) |
| 856 | total_equity_cents += net_income_cents |
| 857 | |
| 858 | difference_cents = total_assets_cents - (total_liabilities_cents + total_equity_cents) |
| 859 | |
| 860 | return { |
| 861 | "as_of": as_of, |
| 862 | "assets": assets, |
| 863 | "liabilities": liabilities, |
| 864 | "equity": equity, |
| 865 | "total_assets_cents": total_assets_cents, |
| 866 | "total_liabilities_cents": total_liabilities_cents, |
| 867 | "total_equity_cents": total_equity_cents, |
| 868 | "balances": difference_cents == 0, |
| 869 | "difference_cents": difference_cents, |
| 870 | } |
| 871 | |
| 872 | CLOSED_PERIODS_COLLECTION = "fin_closed_periods" |
| 873 | |
| 874 | |
| 875 | def closed_period_for(date_text, *, base_dir: Path | str = DEFAULT_DATA_DIR, |
| 876 | owner_id: str = "", entity_id: str = "", |
| 877 | strict: bool = False) -> dict | None: |
| 878 | """The closed period covering a date, if any -- the period-lock check. |
| 879 | |
| 880 | A closed period is the line under settled books: from start_date |
| 881 | through end_date INCLUSIVE, nothing may be written, edited, or posted |
| 882 | (the predecessor system modeled exactly this control -- reconciled |
| 883 | against a private source audit, not part of this repo -- and it was |
| 884 | the one it had that this system lacked). Scoping mirrors how |
| 885 | books are scoped everywhere else: a period closes ONE owner's books, |
| 886 | and an entity-specific period closes only that entity's journals while |
| 887 | an entity-blank period closes the owner's unscoped journals. |
| 888 | |
| 889 | Plain string comparison on ISO dates, same as every date filter in |
| 890 | this module. A journal with no date cannot be inside a closed period |
| 891 | -- validation owns whether dates are required, not this check. |
| 892 | |
| 893 | `strict`: raise when fin_closed_periods cannot be read. Without it an |
| 894 | unreadable collection answers None -- "not closed" -- and the period |
| 895 | lock, the one gate on settled books, opens exactly when it cannot see. |
| 896 | Under strict a collection that is not installed is still None: books |
| 897 | that have never had a period closed have no closed periods, and that |
| 898 | is a fact rather than an unknown. Every caller that gates on this |
| 899 | asks strictly today (hook_fin_journals, hook_fin_journal_lines, |
| 900 | action_reverse_journal); a new caller that GATES on the answer must |
| 901 | pass strict=True as well. Same note as object_banking's gate reads. |
| 902 | """ |
| 903 | date = str(date_text or "").strip()[:10] |
| 904 | if not date: |
| 905 | return None |
| 906 | try: |
| 907 | rows = object_records.read_collection_records( |
| 908 | CLOSED_PERIODS_COLLECTION, base_dir=base_dir) |
| 909 | except object_collections.CollectionNotFoundError: |
| 910 | return None |
| 911 | except Exception: |
| 912 | if strict: |
| 913 | raise |
| 914 | return None |
| 915 | for row in rows: |
| 916 | if owner_id and row.get("owner_id") and row["owner_id"] != owner_id: |
| 917 | continue |
| 918 | row_entity = str(row.get("entity_id") or "") |
| 919 | if row_entity != str(entity_id or ""): |
| 920 | continue |
| 921 | start = str(row.get("start_date") or "")[:10] |
| 922 | end = str(row.get("end_date") or "")[:10] |
| 923 | if start and end and start <= date <= end: |
| 924 | return row |
| 925 | return None |