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
wallet_books.py · 5.0 KB · 137 lines
| 1 | """system_wallet_books -- wallet money reaching the double-entry books. |
| 2 | |
| 3 | The prepaid twin of app-payments' system_books. That composer books |
| 4 | payments, refunds and invoices; nothing booked the WALLET, so a server |
| 5 | that charged real money for template runs showed zero revenue on the |
| 6 | profit and loss and neither the cash nor the customer liability on the |
| 7 | balance sheet. Every movement was recorded operationally in |
| 8 | wallet_entries and none of it reached fin_journals. |
| 9 | |
| 10 | Placement per docs/logic-decisions.md #6: a REACTION (post-commit, |
| 11 | best-effort, never blocks or fails the source write), so an event |
| 12 | handler rather than a hook. Billing keeps working with no books |
| 13 | installed; the books simply learn nothing. |
| 14 | |
| 15 | The accounting policy is NOT here -- object_billing.wallet_posting owns |
| 16 | it, pure and exhaustively testable without a data directory. This module |
| 17 | resolves settings, refetches the record, and posts. The one thing worth |
| 18 | repeating from there: **a top-up is not revenue.** Money taken before |
| 19 | the service is rendered is money owed back, and it becomes revenue only |
| 20 | when the work is done. |
| 21 | |
| 22 | Account mapping is configuration (app_settings): |
| 23 | billing.journal.cash_account fin_accounts id (asset) |
| 24 | billing.journal.customer_funds_account fin_accounts id (LIABILITY) |
| 25 | billing.journal.revenue_account fin_accounts id |
| 26 | billing.journal.promo_expense_account fin_accounts id (optional) |
| 27 | billing.journal.adjustment_account fin_accounts id (optional) |
| 28 | |
| 29 | Idempotency by provenance, the house rule: every composed journal stamps |
| 30 | generated_from "wallet_entries/{id}", so a replayed event composes |
| 31 | nothing. Entries are balanced by construction (one amount, two lines). |
| 32 | """ |
| 33 | |
| 34 | import os |
| 35 | |
| 36 | import object_billing |
| 37 | import object_finance |
| 38 | import object_records |
| 39 | |
| 40 | HANDLES = [ |
| 41 | "wallet_entries.record.created", |
| 42 | ] |
| 43 | |
| 44 | ACTOR = "system_wallet_books" |
| 45 | |
| 46 | SETTING_PREFIX = "billing.journal." |
| 47 | |
| 48 | |
| 49 | def _base_dir(): |
| 50 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 51 | |
| 52 | |
| 53 | def _setting(base, key, default=""): |
| 54 | try: |
| 55 | for row in object_records.read_collection_records("app_settings", base_dir=base): |
| 56 | if row.get("key") == key and row.get("value"): |
| 57 | return row["value"].strip() |
| 58 | except Exception: |
| 59 | pass |
| 60 | return default |
| 61 | |
| 62 | |
| 63 | def _books_ready(base): |
| 64 | try: |
| 65 | object_records.read_collection_records("fin_journals", base_dir=base) |
| 66 | object_records.read_collection_records("fin_journal_lines", base_dir=base) |
| 67 | except Exception: |
| 68 | return False |
| 69 | return True |
| 70 | |
| 71 | |
| 72 | def _accounts(base): |
| 73 | return { |
| 74 | name: _setting(base, f"{SETTING_PREFIX}{name}_account") |
| 75 | for name in object_billing.WALLET_ACCOUNT_KEYS |
| 76 | } |
| 77 | |
| 78 | |
| 79 | def EVENT(request): |
| 80 | """request = {"event","collection","record_id","action"} (no body -- |
| 81 | refetch post-commit). Best-effort: every failure returns a reason, |
| 82 | never raises into the dispatcher.""" |
| 83 | record_id = str(request.get("record_id") or "") |
| 84 | action = str(request.get("action") or "") |
| 85 | action = {"create": "created", "update": "updated", |
| 86 | "delete": "deleted"}.get(action, action) |
| 87 | if not record_id: |
| 88 | return {"ok": True, "skipped": "no record id"} |
| 89 | if action != "created": |
| 90 | # Entries are an append-only ledger; an edit to one is not a |
| 91 | # second economic event, and composing for it would double-book. |
| 92 | return {"ok": True, "skipped": "only new entries compose"} |
| 93 | |
| 94 | base = _base_dir() |
| 95 | if not _books_ready(base): |
| 96 | return {"ok": True, "skipped": "books not installed (fin_journals absent)"} |
| 97 | |
| 98 | try: |
| 99 | entry = object_records.get_collection_record( |
| 100 | "wallet_entries", record_id, base_dir=base) |
| 101 | except Exception: |
| 102 | return {"ok": True, "skipped": "entry gone"} |
| 103 | if entry is None: |
| 104 | return {"ok": True, "skipped": "entry gone"} |
| 105 | |
| 106 | try: |
| 107 | posting = object_billing.wallet_posting( |
| 108 | entry.get("kind"), entry.get("amount_minor"), _accounts(base)) |
| 109 | if "skip" in posting: |
| 110 | return {"ok": True, "skipped": posting["skip"]} |
| 111 | |
| 112 | wallet = {} |
| 113 | try: |
| 114 | wallet = object_records.get_collection_record( |
| 115 | "wallets", str(entry.get("wallet_id") or ""), base_dir=base) or {} |
| 116 | except Exception: |
| 117 | wallet = {} |
| 118 | |
| 119 | description = (str(entry.get("description") or "").strip() |
| 120 | or f"Wallet {entry.get('kind')}") |
| 121 | return object_finance.compose_posted_journal( |
| 122 | base, |
| 123 | generated_from=f"wallet_entries/{record_id}", |
| 124 | date=str(entry.get("created_at") or "")[:10], |
| 125 | description=description, |
| 126 | lines=[ |
| 127 | {"account_id": posting["debit"], |
| 128 | "debit_cents": posting["amount_minor"], "credit_cents": 0}, |
| 129 | {"account_id": posting["credit"], |
| 130 | "debit_cents": 0, "credit_cents": posting["amount_minor"]}, |
| 131 | ], |
| 132 | owner_id=entry.get("owner_id") or wallet.get("owner_id"), |
| 133 | entity_id=wallet.get("entity_id", ""), |
| 134 | actor=ACTOR, |
| 135 | ) |
| 136 | except Exception as exc: # never break the dispatcher |
| 137 | return {"ok": False, "error": str(exc)[:200]} |