Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

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