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.
books.py · 19.2 KB · 381 lines
| 1 | """system_books -- HANDLES payments/refunds/invoices writes; composes journal |
| 2 | entries (the books spine, plan/books-spine-spec.md). |
| 3 | |
| 4 | The billing ledger's reaction layer: when money moves operationally, the |
| 5 | matching double-entry lands in fin_journals -- posted, provenance-stamped, |
| 6 | idempotent. Placement per docs/logic-decisions.md #6: this is a REACTION |
| 7 | (post-commit, best-effort, never blocks or fails the source write), so it |
| 8 | lives in an event handler, not a hook. |
| 9 | |
| 10 | Basis and account mapping are configuration (app_settings): |
| 11 | payments.accounting_basis cash (default) | accrual |
| 12 | payments.journal.cash_account fin_accounts id |
| 13 | payments.journal.receivable_account fin_accounts id (accrual) |
| 14 | payments.journal.revenue_account fin_accounts id |
| 15 | payments.journal.tax_account fin_accounts id (Sales Tax Payable) |
| 16 | |
| 17 | Tax posts to Sales Tax Payable, never to revenue (decision 2, owner, |
| 18 | 2026-11-30). Accrual: an issued invoice is DR receivable (total) / CR |
| 19 | revenue (total - tax) / CR tax (tax). Cash: each payment carries its pro-rata |
| 20 | share of the invoice's stamped tax (half-up), and a refund or bounce takes |
| 21 | its share back (a refund paying out a credit note at the credit note's own |
| 22 | rate). A sale that carries tax with no tax account set is NOT booked: the |
| 23 | result names the setting, rather than booking tax as revenue. |
| 24 | Soft dependency: missing fin_journals collection or unmapped accounts -> |
| 25 | skip with a reason in the result; billing works without books. |
| 26 | |
| 27 | Idempotency by provenance: every composed journal stamps generated_from |
| 28 | ("payments/{id}", "refunds/{id}", "payments/{id}:bounced", |
| 29 | "invoices/{id}:issued", "invoices/{id}:credited" for a credit note, which |
| 30 | reverses revenue and tax at its own stamped rate and cancels receivable); |
| 31 | an existing stamp means a replayed event composes |
| 32 | nothing. Entries are balanced BY CONSTRUCTION (one amount, two lines) and |
| 33 | this composer re-verifies before posting -- note: direct object_records |
| 34 | writes bypass the HTTP-only balance hook, so the composer carries its own |
| 35 | check; the hook remains the gate for human entries. |
| 36 | """ |
| 37 | |
| 38 | import os |
| 39 | from decimal import ROUND_HALF_UP, Decimal |
| 40 | |
| 41 | import object_finance |
| 42 | import object_records |
| 43 | |
| 44 | HANDLES = [ |
| 45 | "payments.record.created", |
| 46 | "payments.record.updated", |
| 47 | "refunds.record.created", |
| 48 | "invoices.record.created", |
| 49 | "invoices.record.updated", |
| 50 | ] |
| 51 | |
| 52 | ACTOR = "system_books" |
| 53 | |
| 54 | |
| 55 | def _base_dir(): |
| 56 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 57 | |
| 58 | |
| 59 | def _setting(base, key, default=""): |
| 60 | try: |
| 61 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 62 | if row.get("key") == key and row.get("value"): |
| 63 | return row["value"].strip() |
| 64 | except Exception: |
| 65 | pass |
| 66 | return default |
| 67 | |
| 68 | |
| 69 | def _books_ready(base): |
| 70 | try: |
| 71 | object_records.read_collection_records("fin_journals", base_dir=base) |
| 72 | object_records.read_collection_records("fin_journal_lines", base_dir=base) |
| 73 | except Exception: |
| 74 | return False |
| 75 | return True |
| 76 | |
| 77 | |
| 78 | def _compose(base, *, generated_from, date, description, debit_account, |
| 79 | credit_account, amount_cents, owner_id, entity_id="", kind="standard", |
| 80 | tax_cents=0, tax_account="", tax_side="credit"): |
| 81 | """One balanced entry: DR debit_account / CR credit_account, posted -- |
| 82 | with the tax part of the amount, when there is one, on the Sales Tax |
| 83 | Payable account instead (decision 2, 2026-11-30: tax posts to Sales Tax |
| 84 | Payable, not to revenue). `tax_side` says which side the tax line is |
| 85 | on: "credit" when the revenue side is credited (a sale, a payment on |
| 86 | cash basis), "debit" when it is debited (a refund, a bounce, a credit |
| 87 | note). |
| 88 | |
| 89 | Mechanics live in object_finance.compose_posted_journal (the shared |
| 90 | composer this module's hand-rolled version was extracted into). |
| 91 | """ |
| 92 | if amount_cents <= 0: |
| 93 | return {"ok": True, "skipped": "zero amount"} |
| 94 | tax_cents = max(0, min(int(tax_cents or 0), amount_cents)) |
| 95 | debit_lines = [{"account_id": debit_account, "debit_cents": amount_cents, "credit_cents": 0}] |
| 96 | credit_lines = [{"account_id": credit_account, "debit_cents": 0, "credit_cents": amount_cents}] |
| 97 | if tax_cents and tax_side == "credit": |
| 98 | credit_lines = [ |
| 99 | {"account_id": credit_account, "debit_cents": 0, |
| 100 | "credit_cents": amount_cents - tax_cents}, |
| 101 | {"account_id": tax_account, "debit_cents": 0, "credit_cents": tax_cents, |
| 102 | "memo": "Sales tax"}] |
| 103 | elif tax_cents: |
| 104 | debit_lines = [ |
| 105 | {"account_id": debit_account, "debit_cents": amount_cents - tax_cents, |
| 106 | "credit_cents": 0}, |
| 107 | {"account_id": tax_account, "debit_cents": tax_cents, "credit_cents": 0, |
| 108 | "memo": "Sales tax"}] |
| 109 | return object_finance.compose_posted_journal( |
| 110 | base, |
| 111 | generated_from=generated_from, |
| 112 | date=date, |
| 113 | description=description, |
| 114 | lines=[line for line in debit_lines + credit_lines |
| 115 | if line["debit_cents"] or line["credit_cents"]], |
| 116 | owner_id=owner_id, |
| 117 | entity_id=entity_id, |
| 118 | kind=kind, |
| 119 | actor=ACTOR, |
| 120 | ) |
| 121 | |
| 122 | |
| 123 | def tax_share(amount_cents, invoice): |
| 124 | """The tax part of `amount_cents` of money received on (or returned |
| 125 | against) an invoice: its share of the invoice's stamped tax, pro rata, |
| 126 | rounded half-up. On cash basis revenue and tax are recognised when the |
| 127 | money arrives, so each payment carries its share; never more than the |
| 128 | invoice's tax.""" |
| 129 | try: |
| 130 | total = int(invoice.get("total_cents") or 0) |
| 131 | tax = int(invoice.get("tax_cents") or 0) |
| 132 | except (TypeError, ValueError): |
| 133 | return 0 |
| 134 | if total <= 0 or tax <= 0 or amount_cents <= 0: |
| 135 | return 0 |
| 136 | share = (Decimal(amount_cents) * Decimal(tax) / Decimal(total)).to_integral_value( |
| 137 | rounding=ROUND_HALF_UP) |
| 138 | return min(int(share), tax, amount_cents) |
| 139 | |
| 140 | |
| 141 | def _needs_tax_account(record_label, tax, tax_account): |
| 142 | if tax and not tax_account: |
| 143 | return {"ok": False, "skipped": "tax account unconfigured", |
| 144 | "needs_settings": ["payments.journal.tax_account"], |
| 145 | "error": (f"{record_label} carries {tax} of sales tax and was not booked: set " |
| 146 | f"payments.journal.tax_account in app_settings to the Sales Tax " |
| 147 | f"Payable account, so tax is not booked as revenue.")} |
| 148 | return None |
| 149 | |
| 150 | |
| 151 | def _get(base, collection, record_id): |
| 152 | try: |
| 153 | return object_records.get_collection_record(collection, record_id, base_dir=base) |
| 154 | except Exception: |
| 155 | return None |
| 156 | |
| 157 | |
| 158 | def EVENT(request): |
| 159 | """request = {"event","collection","record_id","action"} (no body -- |
| 160 | refetch post-commit). Best-effort: every failure returns a reason, never |
| 161 | raises into the dispatcher.""" |
| 162 | collection = str(request.get("collection") or "") |
| 163 | record_id = str(request.get("record_id") or "") |
| 164 | # The dispatcher's payload carries the RAW action ("create"); the event |
| 165 | # NAME uses the participle ("...record.created"). Accept both. |
| 166 | action = str(request.get("action") or "") |
| 167 | action = {"create": "created", "update": "updated", "delete": "deleted"}.get(action, action) |
| 168 | if not record_id: |
| 169 | return {"ok": True, "skipped": "no record id"} |
| 170 | |
| 171 | base = _base_dir() |
| 172 | if not _books_ready(base): |
| 173 | return {"ok": True, "skipped": "books not installed (fin_journals absent)"} |
| 174 | |
| 175 | basis = _setting(base, "payments.accounting_basis", "cash") |
| 176 | cash = _setting(base, "payments.journal.cash_account") |
| 177 | receivable = _setting(base, "payments.journal.receivable_account") |
| 178 | revenue = _setting(base, "payments.journal.revenue_account") |
| 179 | tax_account = _setting(base, "payments.journal.tax_account") |
| 180 | |
| 181 | try: |
| 182 | if collection == "payments": |
| 183 | payment = _get(base, "payments", record_id) |
| 184 | if payment is None: |
| 185 | return {"ok": True, "skipped": "payment gone"} |
| 186 | invoice = _get(base, "invoices", payment.get("invoice_id", "")) or {} |
| 187 | amount = int(payment.get("amount_cents") or 0) |
| 188 | entity = invoice.get("entity_id", "") |
| 189 | counter = receivable if basis == "accrual" else revenue |
| 190 | if not cash or not counter: |
| 191 | return {"ok": True, "skipped": "accounts unconfigured"} |
| 192 | # Cash basis recognises revenue -- and the tax in it -- when the |
| 193 | # money arrives; accrual already did at issue. |
| 194 | tax = tax_share(amount, invoice) if basis != "accrual" else 0 |
| 195 | if action == "created" and (payment.get("status") or "received") == "received": |
| 196 | refusal = _needs_tax_account(f"Payment {record_id}", tax, tax_account) |
| 197 | if refusal: |
| 198 | return refusal |
| 199 | return _compose( |
| 200 | base, generated_from=f"payments/{record_id}", |
| 201 | date=payment.get("received_on"), |
| 202 | description=f"Payment {payment.get('reference') or record_id} " |
| 203 | f"for {invoice.get('number') or payment.get('invoice_id')}", |
| 204 | debit_account=cash, credit_account=counter, |
| 205 | amount_cents=amount, owner_id=payment.get("owner_id"), |
| 206 | entity_id=entity, tax_cents=tax, tax_account=tax_account, |
| 207 | ) |
| 208 | if action == "updated" and payment.get("status") == "bounced": |
| 209 | original = object_finance.find_journal_by_provenance(base, f"payments/{record_id}") |
| 210 | if original is None: |
| 211 | return {"ok": True, "skipped": "no original entry to reverse"} |
| 212 | # Reverse exactly what the receipt booked: its tax line, if |
| 213 | # it had one, comes back off Sales Tax Payable. |
| 214 | booked_tax = _booked_tax(base, original, tax_account) |
| 215 | return _compose( |
| 216 | base, generated_from=f"payments/{record_id}:bounced", |
| 217 | date=payment.get("received_on"), |
| 218 | description=f"Bounce reversal of payment {record_id}", |
| 219 | debit_account=counter, credit_account=cash, |
| 220 | amount_cents=amount, owner_id=payment.get("owner_id"), |
| 221 | entity_id=entity, kind="reversing", |
| 222 | tax_cents=booked_tax, tax_account=tax_account, tax_side="debit", |
| 223 | ) |
| 224 | return {"ok": True, "skipped": "no entry for this payment event"} |
| 225 | |
| 226 | if collection == "refunds" and action == "created": |
| 227 | refund = _get(base, "refunds", record_id) |
| 228 | if refund is None: |
| 229 | return {"ok": True, "skipped": "refund gone"} |
| 230 | invoice = _get(base, "invoices", refund.get("invoice_id", "")) or {} |
| 231 | counter = receivable if basis == "accrual" else revenue |
| 232 | if not cash or not counter: |
| 233 | # Loud (Corner Cup): money went back to a customer and the |
| 234 | # books, which are installed, recorded nothing. Name what |
| 235 | # to set; the refund itself stands. |
| 236 | needed = [key for key, value in ( |
| 237 | ("payments.journal.cash_account", cash), |
| 238 | ("payments.journal.receivable_account" if basis == "accrual" |
| 239 | else "payments.journal.revenue_account", counter)) if not value] |
| 240 | return {"ok": False, "skipped": "accounts unconfigured", |
| 241 | "needs_settings": needed, |
| 242 | "error": (f"Refund {record_id} was not booked: set " |
| 243 | f"{' and '.join(needed)} in app_settings to accounts in " |
| 244 | f"the chart of accounts.")} |
| 245 | amount = int(refund.get("amount_cents") or 0) |
| 246 | tax = 0 |
| 247 | if basis != "accrual": |
| 248 | # The tax given back is the tax in what is given back: at |
| 249 | # the credit note's own rate when the refund pays one out |
| 250 | # (never recalculated after issue), else the invoice's. |
| 251 | note = _get(base, "invoices", refund.get("credit_note_id", "")) \ |
| 252 | if refund.get("credit_note_id") else None |
| 253 | tax = tax_share(amount, note or invoice) |
| 254 | refusal = _needs_tax_account(f"Refund {record_id}", tax, tax_account) |
| 255 | if refusal: |
| 256 | return refusal |
| 257 | return _compose( |
| 258 | base, generated_from=f"refunds/{record_id}", |
| 259 | date=refund.get("refunded_on"), |
| 260 | description=f"Refund on payment {refund.get('payment_id')}", |
| 261 | debit_account=counter, credit_account=cash, |
| 262 | amount_cents=amount, |
| 263 | owner_id=refund.get("owner_id"), |
| 264 | entity_id=invoice.get("entity_id", ""), |
| 265 | tax_cents=tax, tax_account=tax_account, tax_side="debit", |
| 266 | ) |
| 267 | |
| 268 | if collection == "invoices": |
| 269 | if basis != "accrual": |
| 270 | # Cash basis: revenue and tax move with the money. A credit |
| 271 | # note moves no money; the refund that pays one out is |
| 272 | # booked (at the credit note's rate) when it is recorded. |
| 273 | return {"ok": True, "skipped": "cash basis: no issue entry"} |
| 274 | invoice = _get(base, "invoices", record_id) |
| 275 | doc_type = (invoice or {}).get("doc_type") or "invoice" |
| 276 | if invoice is None or invoice.get("status") in ("", "draft", "void") or \ |
| 277 | doc_type not in ("invoice", "credit_note"): |
| 278 | return {"ok": True, "skipped": "not an issued invoice or credit note"} |
| 279 | if doc_type == "invoice" and invoice.get("status") != "sent": |
| 280 | return {"ok": True, "skipped": "not an issued invoice"} |
| 281 | if not receivable or not revenue: |
| 282 | return {"ok": True, "skipped": "accounts unconfigured"} |
| 283 | tax = int(invoice.get("tax_cents") or 0) |
| 284 | label = ("Credit note" if doc_type == "credit_note" else "Invoice") |
| 285 | refusal = _needs_tax_account(f"{label} {invoice.get('number') or record_id}", |
| 286 | tax, tax_account) |
| 287 | if refusal: |
| 288 | return refusal |
| 289 | if doc_type == "credit_note": |
| 290 | # A credit note reverses revenue and tax at the ORIGINAL |
| 291 | # rate -- the tax stamped on it, never recalculated -- and |
| 292 | # cancels that much receivable (decision 1: a debt is |
| 293 | # cancelled only by a credit note). It was never journaled, |
| 294 | # so an accrual book kept the credited sale as revenue and |
| 295 | # the customer's balance as owed. |
| 296 | return _compose( |
| 297 | base, generated_from=f"invoices/{record_id}:credited", |
| 298 | date=invoice.get("issue_date"), |
| 299 | description=(f"Credit note {invoice.get('number') or record_id}" |
| 300 | + (f" against {invoice.get('credits_invoice_id')}" |
| 301 | if invoice.get("credits_invoice_id") else "")), |
| 302 | debit_account=revenue, credit_account=receivable, |
| 303 | amount_cents=int(invoice.get("total_cents") or 0), |
| 304 | owner_id=invoice.get("owner_id"), |
| 305 | entity_id=invoice.get("entity_id", ""), |
| 306 | tax_cents=tax, tax_account=tax_account, tax_side="debit", |
| 307 | ) |
| 308 | deferred = _billed_in_advance(base, invoice) |
| 309 | if deferred: |
| 310 | # Decision 4 (2026-11-30): a subscription's base fee is |
| 311 | # billed in advance; on accrual books what is billed before |
| 312 | # the service is delivered is Deferred Revenue, released |
| 313 | # month by month as it is earned (system_billing_runner). |
| 314 | deferred_account = _setting(base, "payments.journal.deferred_revenue_account") |
| 315 | if not deferred_account: |
| 316 | return {"ok": False, "skipped": "deferred revenue account unconfigured", |
| 317 | "needs_settings": ["payments.journal.deferred_revenue_account"], |
| 318 | "error": (f"Invoice {invoice.get('number') or record_id} bills " |
| 319 | f"{deferred} in advance and was not booked: set " |
| 320 | f"payments.journal.deferred_revenue_account in " |
| 321 | f"app_settings, so revenue not yet earned is not " |
| 322 | f"booked as earned.")} |
| 323 | total = int(invoice.get("total_cents") or 0) |
| 324 | earned = total - tax - deferred |
| 325 | lines = [{"account_id": receivable, "debit_cents": total, "credit_cents": 0}, |
| 326 | {"account_id": revenue, "debit_cents": 0, "credit_cents": earned}, |
| 327 | {"account_id": deferred_account, "debit_cents": 0, |
| 328 | "credit_cents": deferred, "memo": "Billed in advance"}, |
| 329 | {"account_id": tax_account, "debit_cents": 0, "credit_cents": tax, |
| 330 | "memo": "Sales tax"}] |
| 331 | return object_finance.compose_posted_journal( |
| 332 | base, generated_from=f"invoices/{record_id}:issued", |
| 333 | date=invoice.get("issue_date"), |
| 334 | description=f"Invoice {invoice.get('number') or record_id} issued", |
| 335 | lines=[line for line in lines if line["debit_cents"] or line["credit_cents"]], |
| 336 | owner_id=invoice.get("owner_id"), entity_id=invoice.get("entity_id", ""), |
| 337 | actor=ACTOR) |
| 338 | return _compose( |
| 339 | base, generated_from=f"invoices/{record_id}:issued", |
| 340 | date=invoice.get("issue_date"), |
| 341 | description=f"Invoice {invoice.get('number') or record_id} issued", |
| 342 | debit_account=receivable, credit_account=revenue, |
| 343 | amount_cents=int(invoice.get("total_cents") or 0), |
| 344 | owner_id=invoice.get("owner_id"), |
| 345 | entity_id=invoice.get("entity_id", ""), |
| 346 | tax_cents=tax, tax_account=tax_account, |
| 347 | ) |
| 348 | except Exception as exc: # never break the dispatcher |
| 349 | return {"ok": False, "error": str(exc)[:200]} |
| 350 | return {"ok": True, "skipped": "unhandled event"} |
| 351 | |
| 352 | |
| 353 | def _billed_in_advance(base, invoice): |
| 354 | """The part of an invoice that bills service not yet delivered when it |
| 355 | is issued: its lines whose service period ends after the issue date |
| 356 | (invoice_lines.service_start/service_end, stamped by the subscription |
| 357 | biller). 0 for goods and one-off work, which carry no service period.""" |
| 358 | issued = str(invoice.get("issue_date") or "")[:10] |
| 359 | try: |
| 360 | lines = object_records.read_collection_records("invoice_lines", base_dir=base) |
| 361 | except Exception: |
| 362 | return 0 |
| 363 | return sum(int(line.get("line_total_cents") or 0) for line in lines |
| 364 | if line.get("invoice_id") == invoice.get("id") |
| 365 | and str(line.get("service_end") or "")[:10] > issued |
| 366 | and str(line.get("service_start") or "")) |
| 367 | |
| 368 | |
| 369 | def _booked_tax(base, journal_id, tax_account): |
| 370 | """The tax a composed journal credited to the tax account, so its |
| 371 | reversal takes back exactly that.""" |
| 372 | if not tax_account: |
| 373 | return 0 |
| 374 | try: |
| 375 | lines = object_records.read_collection_records("fin_journal_lines", base_dir=base) |
| 376 | except Exception: |
| 377 | return 0 |
| 378 | journal_id = journal_id.get("id") if isinstance(journal_id, dict) else journal_id |
| 379 | return sum(int(line.get("credit_cents") or 0) for line in lines |
| 380 | if line.get("journal_id") == journal_id |
| 381 | and line.get("account_id") == tax_account) |