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
expense_books.py · 10.2 KB · 257 lines
1"""system_expense_books -- HANDLES expenses writes; posts the journal.
2
3An approved expense composes one balanced entry:
4
5 DR the expense account (what it was for)
6 CR the clearing account (company card or cash), OR
7 CR the reimbursable liability (when a person paid personally)
8
9That second credit is the whole reason paid_by exists as a field. An
10employee's own card creates a DEBT the business owes them; booking it
11against the company's cash account claims money left an account it never
12left, and the person is left chasing a reimbursement the ledger has no
13record of. Most expense tools model this as a flag on a report; here it
14is the account the credit lands in, which is the only place it can
15actually be true.
16
17Placement follows docs/logic-decisions.md #6: this is a REACTION
18(post-commit, best-effort, never blocks the write), so it lives in an
19event handler rather than the hook. Somebody recording that they bought a
20plane ticket must not be stopped because nobody has mapped a chart of
21accounts yet -- an unconfigured books mapping skips with a reason and the
22expense stands.
23
24Configuration (app_settings):
25 expenses.journal.expense_account default DR when an expense names none
26 expenses.journal.paid_account CR for company-paid spend
27 expenses.journal.reimbursable_account CR for personally-paid spend
28
29The books follow the expense's state, by compensating entries only
30(doctrine #3). An approved (or billed) expense must have exactly one live
31booking matching its amount and accounts; any other status must have none.
32"Live" means posted and not reversed -- a reversal is a journal stamped
33generated_from "reversal:{journal_id}", the same marker
34action_reverse_journal uses, so a hand reversal and this handler never
35reverse one entry twice. So:
36
37 approved -> rejected the booking is reversed (it used to stay on
38 the books: rejected spend nobody approved)
39 rejected -> ... -> approved after a correction, the booking matches
40 nothing live, so a new one is composed for
41 the corrected amount (the old "expenses/{id}"
42 marker used to block it, so the books kept
43 the first amount)
44 an edit while approved reverse the stale booking, book the new one
45
46Idempotency by provenance (doctrine #7): the first booking is
47"expenses/{id}" (as before), the n-th "expenses/{id}:{n}"; n is the count
48of bookings that already exist, so a replayed event finds its own journal
49and composes nothing, and a state that already matches the books is a
50no-op.
51"""
52
53import os
54
55import object_finance
56import object_records
57
58HANDLES = [
59 "expenses.record.created",
60 "expenses.record.updated",
61]
62
63ACTOR = "system_expense_books"
64
65
66def _base_dir():
67 return os.environ.get("DBBASIC_DATA_DIR", "data")
68
69
70def _setting(base, key, default=""):
71 try:
72 for row in object_records.read_collection_records("app_settings", base_dir=base):
73 if row.get("key") == key and str(row.get("value") or "").strip():
74 return row["value"].strip()
75 except Exception:
76 pass
77 return default
78
79
80def _int(value):
81 try:
82 return int(str(value or "0").strip() or 0)
83 except (TypeError, ValueError):
84 return 0
85
86
87def _text(value):
88 return str(value if value is not None else "").strip()
89
90
91def _record_for(request, base):
92 record = request.get("record")
93 if isinstance(record, dict) and record.get("id"):
94 return record
95 record_id = _text(request.get("record_id") or request.get("id"))
96 if not record_id:
97 return None
98 try:
99 return object_records.get_collection_record("expenses", record_id, base_dir=base)
100 except Exception:
101 return None
102
103
104def _category_account(base, category_id):
105 """The account the expense's category debits, "" when it names none,
106 None when the category cannot be read.
107
108 Between the expense's own account and the house default (0.19.0): a
109 category is where "meals go to Meals & Entertainment" is said once. An
110 unreadable category is not "no account": guessing the house default
111 would post to a line the operator may have moved it off, so EVENT skips
112 with a reason, as it does when the books themselves are unreadable."""
113 if not category_id:
114 return ""
115 try:
116 row = object_records.get_collection_record("expense_categories", category_id, base_dir=base)
117 except object_records.RecordNotFoundError:
118 return ""
119 except Exception:
120 return None
121 return _text(row.get("account_id"))
122
123
124_ON_THE_BOOKS = ("approved", "billed")
125
126
127def _bookings(base, expense_id):
128 """(bookings, reversed_ids, lines_by_journal) for one expense, or None
129 when the books cannot be read -- never act on a guess about money."""
130 marker = f"expenses/{expense_id}"
131 try:
132 journals = object_records.read_collection_records("fin_journals", base_dir=base)
133 lines = object_records.read_collection_records("fin_journal_lines", base_dir=base)
134 except Exception:
135 return None
136 bookings = [j for j in journals
137 if j.get("generated_from") == marker
138 or str(j.get("generated_from") or "").startswith(marker + ":")]
139 reversed_ids = {str(j.get("generated_from"))[len("reversal:"):] for j in journals
140 if str(j.get("generated_from") or "").startswith("reversal:")}
141 by_journal = {}
142 for line in lines:
143 by_journal.setdefault(line.get("journal_id"), []).append(line)
144 return bookings, reversed_ids, by_journal
145
146
147def _shape(lines):
148 return sorted((_text(l.get("account_id")), _int(l.get("debit_cents")),
149 _int(l.get("credit_cents"))) for l in lines)
150
151
152def _reverse(base, journal, lines):
153 return object_finance.compose_posted_journal(
154 base,
155 generated_from=f"reversal:{journal['id']}",
156 date=_text(journal.get("date")),
157 description=f"Reversal of {_text(journal.get('description')) or journal['id']}",
158 lines=[{"account_id": l.get("account_id", ""),
159 "debit_cents": l.get("credit_cents", "0"), # swapped
160 "credit_cents": l.get("debit_cents", "0"), # swapped
161 "memo": l.get("memo", ""), "entity_id": l.get("entity_id", "")}
162 for l in lines],
163 owner_id=_text(journal.get("owner_id")),
164 entity_id=_text(journal.get("entity_id")),
165 kind="reversing",
166 actor=ACTOR,
167 )
168
169
170def EVENT(request):
171 base = _base_dir()
172 expense = _record_for(request, base)
173 if not expense:
174 return {"ok": True, "skipped": "no expense in the event"}
175
176 # What the books SHOULD hold for this expense: nothing until somebody
177 # approved it (a draft expense is a note to self), and nothing again
178 # once it is rejected.
179 wanted = None
180 amount = _int(expense.get("amount_cents"))
181 if _text(expense.get("status")) in _ON_THE_BOOKS and amount > 0:
182 debit = _text(expense.get("account_id"))
183 if not debit:
184 debit = _category_account(base, _text(expense.get("category_id")))
185 if debit is None:
186 return {"ok": True, "skipped": "expense category unreadable; not guessing the account"}
187 debit = debit or _setting(base, "expenses.journal.expense_account")
188 personal = _text(expense.get("paid_by")) == "personal"
189 credit = _setting(
190 base,
191 "expenses.journal.reimbursable_account" if personal
192 else "expenses.journal.paid_account")
193 if not debit or not credit:
194 return {"ok": True, "skipped": "accounts unconfigured",
195 "needs": ["expenses.journal.expense_account",
196 "expenses.journal.reimbursable_account" if personal
197 else "expenses.journal.paid_account"]}
198 memo = ("reimbursable to " + _text(expense.get("owner_id")) if personal
199 else "paid by the company")
200 wanted = [
201 {"account_id": debit, "debit_cents": amount, "credit_cents": 0,
202 "memo": _text(expense.get("description"))},
203 {"account_id": credit, "debit_cents": 0, "credit_cents": amount,
204 "memo": memo},
205 ]
206
207 books = _bookings(base, expense["id"])
208 if books is None:
209 return {"ok": True, "skipped": "books unreadable; not risking a duplicate"}
210 bookings, reversed_ids, by_journal = books
211 live = [j for j in bookings
212 if j.get("status") == "posted" and j.get("id") not in reversed_ids]
213
214 reversals = []
215 keep = None
216 for journal in live:
217 lines = by_journal.get(journal.get("id"), [])
218 if wanted is not None and keep is None and _shape(lines) == _shape(wanted):
219 keep = journal # already on the books exactly as wanted
220 continue
221 reversed_entry = _reverse(base, journal, lines)
222 if not reversed_entry.get("ok"):
223 return reversed_entry
224 reversals.append(reversed_entry.get("journal_id", ""))
225
226 if wanted is None or keep is not None:
227 if reversals:
228 return {"ok": True, "reversed": reversals}
229 if wanted is None:
230 return {"ok": True, "skipped": "not approved"
231 if _text(expense.get("status")) not in _ON_THE_BOOKS else "zero amount"}
232 return {"ok": True, "skipped": f"already composed: {keep.get('generated_from')}",
233 "journal_id": keep.get("id"), "posted": True}
234
235 marker = f"expenses/{expense['id']}"
236 if bookings:
237 marker = f"{marker}:{len(bookings) + 1}"
238 composed = object_finance.compose_posted_journal(
239 base,
240 generated_from=marker,
241 date=_text(expense.get("incurred_on")),
242 description=f"Expense: {_text(expense.get('description')) or expense['id']}",
243 lines=wanted,
244 owner_id=_text(expense.get("owner_id")),
245 entity_id=_text(expense.get("entity_id")),
246 actor=ACTOR,
247 )
248 if reversals:
249 composed = {**composed, "reversed": reversals}
250 return composed
251
252
253# EVENT is the verb the change dispatcher calls handlers with (see
254# object_change_dispatch); the same POST-instead-of-EVENT slip as
255# system_shop_fulfillment, fixed the same day. POST stays as an alias so
256# an operator can poke the handler by hand over HTTP.
257POST = EVENT