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.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
books.py · 8.4 KB · 193 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 | Soft dependency: missing fin_journals collection or unmapped accounts -> |
| 16 | skip with a reason in the result; billing works without books. |
| 17 | |
| 18 | Idempotency by provenance: every composed journal stamps generated_from |
| 19 | ("payments/{id}", "refunds/{id}", "payments/{id}:bounced", |
| 20 | "invoices/{id}:issued"); an existing stamp means a replayed event composes |
| 21 | nothing. Entries are balanced BY CONSTRUCTION (one amount, two lines) and |
| 22 | this composer re-verifies before posting -- note: direct object_records |
| 23 | writes bypass the HTTP-only balance hook, so the composer carries its own |
| 24 | check; the hook remains the gate for human entries. |
| 25 | """ |
| 26 | |
| 27 | import os |
| 28 | |
| 29 | import object_finance |
| 30 | import object_records |
| 31 | |
| 32 | HANDLES = [ |
| 33 | "payments.record.created", |
| 34 | "payments.record.updated", |
| 35 | "refunds.record.created", |
| 36 | "invoices.record.created", |
| 37 | "invoices.record.updated", |
| 38 | ] |
| 39 | |
| 40 | ACTOR = "system_books" |
| 41 | |
| 42 | |
| 43 | def _base_dir(): |
| 44 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 45 | |
| 46 | |
| 47 | def _setting(base, key, default=""): |
| 48 | try: |
| 49 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 50 | if row.get("key") == key and row.get("value"): |
| 51 | return row["value"].strip() |
| 52 | except Exception: |
| 53 | pass |
| 54 | return default |
| 55 | |
| 56 | |
| 57 | def _books_ready(base): |
| 58 | try: |
| 59 | object_records.read_collection_records("fin_journals", base_dir=base) |
| 60 | object_records.read_collection_records("fin_journal_lines", base_dir=base) |
| 61 | except Exception: |
| 62 | return False |
| 63 | return True |
| 64 | |
| 65 | |
| 66 | def _compose(base, *, generated_from, date, description, debit_account, |
| 67 | credit_account, amount_cents, owner_id, entity_id="", kind="standard"): |
| 68 | """One balanced entry: DR debit_account / CR credit_account, posted. |
| 69 | |
| 70 | Mechanics live in object_finance.compose_posted_journal (the shared |
| 71 | composer this module's hand-rolled version was extracted into); this |
| 72 | wrapper keeps the two-line one-amount policy shape the payment/refund/ |
| 73 | bounce/issue entries all share. |
| 74 | """ |
| 75 | if amount_cents <= 0: |
| 76 | return {"ok": True, "skipped": "zero amount"} |
| 77 | return object_finance.compose_posted_journal( |
| 78 | base, |
| 79 | generated_from=generated_from, |
| 80 | date=date, |
| 81 | description=description, |
| 82 | lines=[ |
| 83 | {"account_id": debit_account, "debit_cents": amount_cents, "credit_cents": 0}, |
| 84 | {"account_id": credit_account, "debit_cents": 0, "credit_cents": amount_cents}, |
| 85 | ], |
| 86 | owner_id=owner_id, |
| 87 | entity_id=entity_id, |
| 88 | kind=kind, |
| 89 | actor=ACTOR, |
| 90 | ) |
| 91 | |
| 92 | |
| 93 | def _get(base, collection, record_id): |
| 94 | try: |
| 95 | return object_records.get_collection_record(collection, record_id, base_dir=base) |
| 96 | except Exception: |
| 97 | return None |
| 98 | |
| 99 | |
| 100 | def EVENT(request): |
| 101 | """request = {"event","collection","record_id","action"} (no body -- |
| 102 | refetch post-commit). Best-effort: every failure returns a reason, never |
| 103 | raises into the dispatcher.""" |
| 104 | collection = str(request.get("collection") or "") |
| 105 | record_id = str(request.get("record_id") or "") |
| 106 | # The dispatcher's payload carries the RAW action ("create"); the event |
| 107 | # NAME uses the participle ("...record.created"). Accept both. |
| 108 | action = str(request.get("action") or "") |
| 109 | action = {"create": "created", "update": "updated", "delete": "deleted"}.get(action, action) |
| 110 | if not record_id: |
| 111 | return {"ok": True, "skipped": "no record id"} |
| 112 | |
| 113 | base = _base_dir() |
| 114 | if not _books_ready(base): |
| 115 | return {"ok": True, "skipped": "books not installed (fin_journals absent)"} |
| 116 | |
| 117 | basis = _setting(base, "payments.accounting_basis", "cash") |
| 118 | cash = _setting(base, "payments.journal.cash_account") |
| 119 | receivable = _setting(base, "payments.journal.receivable_account") |
| 120 | revenue = _setting(base, "payments.journal.revenue_account") |
| 121 | |
| 122 | try: |
| 123 | if collection == "payments": |
| 124 | payment = _get(base, "payments", record_id) |
| 125 | if payment is None: |
| 126 | return {"ok": True, "skipped": "payment gone"} |
| 127 | invoice = _get(base, "invoices", payment.get("invoice_id", "")) or {} |
| 128 | amount = int(payment.get("amount_cents") or 0) |
| 129 | entity = invoice.get("entity_id", "") |
| 130 | counter = receivable if basis == "accrual" else revenue |
| 131 | if not cash or not counter: |
| 132 | return {"ok": True, "skipped": "accounts unconfigured"} |
| 133 | if action == "created" and (payment.get("status") or "received") == "received": |
| 134 | return _compose( |
| 135 | base, generated_from=f"payments/{record_id}", |
| 136 | date=payment.get("received_on"), |
| 137 | description=f"Payment {payment.get('reference') or record_id} " |
| 138 | f"for {invoice.get('number') or payment.get('invoice_id')}", |
| 139 | debit_account=cash, credit_account=counter, |
| 140 | amount_cents=amount, owner_id=payment.get("owner_id"), |
| 141 | entity_id=entity, |
| 142 | ) |
| 143 | if action == "updated" and payment.get("status") == "bounced": |
| 144 | if object_finance.find_journal_by_provenance(base, f"payments/{record_id}") is None: |
| 145 | return {"ok": True, "skipped": "no original entry to reverse"} |
| 146 | return _compose( |
| 147 | base, generated_from=f"payments/{record_id}:bounced", |
| 148 | date=payment.get("received_on"), |
| 149 | description=f"Bounce reversal of payment {record_id}", |
| 150 | debit_account=counter, credit_account=cash, |
| 151 | amount_cents=amount, owner_id=payment.get("owner_id"), |
| 152 | entity_id=entity, kind="reversing", |
| 153 | ) |
| 154 | return {"ok": True, "skipped": "no entry for this payment event"} |
| 155 | |
| 156 | if collection == "refunds" and action == "created": |
| 157 | refund = _get(base, "refunds", record_id) |
| 158 | if refund is None: |
| 159 | return {"ok": True, "skipped": "refund gone"} |
| 160 | invoice = _get(base, "invoices", refund.get("invoice_id", "")) or {} |
| 161 | counter = receivable if basis == "accrual" else revenue |
| 162 | if not cash or not counter: |
| 163 | return {"ok": True, "skipped": "accounts unconfigured"} |
| 164 | return _compose( |
| 165 | base, generated_from=f"refunds/{record_id}", |
| 166 | date=refund.get("refunded_on"), |
| 167 | description=f"Refund on payment {refund.get('payment_id')}", |
| 168 | debit_account=counter, credit_account=cash, |
| 169 | amount_cents=int(refund.get("amount_cents") or 0), |
| 170 | owner_id=refund.get("owner_id"), |
| 171 | entity_id=invoice.get("entity_id", ""), |
| 172 | ) |
| 173 | |
| 174 | if collection == "invoices": |
| 175 | if basis != "accrual": |
| 176 | return {"ok": True, "skipped": "cash basis: no issue entry"} |
| 177 | invoice = _get(base, "invoices", record_id) |
| 178 | if invoice is None or invoice.get("status") != "sent": |
| 179 | return {"ok": True, "skipped": "not an issued invoice"} |
| 180 | if not receivable or not revenue: |
| 181 | return {"ok": True, "skipped": "accounts unconfigured"} |
| 182 | return _compose( |
| 183 | base, generated_from=f"invoices/{record_id}:issued", |
| 184 | date=invoice.get("issue_date"), |
| 185 | description=f"Invoice {invoice.get('number') or record_id} issued", |
| 186 | debit_account=receivable, credit_account=revenue, |
| 187 | amount_cents=int(invoice.get("total_cents") or 0), |
| 188 | owner_id=invoice.get("owner_id"), |
| 189 | entity_id=invoice.get("entity_id", ""), |
| 190 | ) |
| 191 | except Exception as exc: # never break the dispatcher |
| 192 | return {"ok": False, "error": str(exc)[:200]} |
| 193 | return {"ok": True, "skipped": "unhandled event"} |