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
invoice_totals.py · 14.2 KB · 308 lines
1"""invoice_totals -- HANDLES invoice_lines writes; recomputes invoice totals.
2
3Registered as a Phase-5a event handler (object_handlers.py,
4docs/event-hooks-decisions.md, docs/upgrade-and-customization.md Rule 4).
5The platform's post-commit dispatcher (object_server.py's
6_dispatch_event_handlers) executes this object's EVENT method whenever a
7client-facing write to invoice_lines commits, but only when the operator
8has DBBASIC_ENABLE_EVENT_HANDLERS set. With the flag unset (the default),
9invoice_lines/invoices writes still succeed -- they just stop getting
10fresher totals until a line is touched again after the flag is turned on.
11Same posture plan/vocabulary/20-invoice-spec.md documents for itself.
12
13Integer-cents arithmetic only, per 00-doctrine-and-contract.md /
1420-invoice-spec.md: money is always a whole number of cents. quantity is
15the one deliberate exception to "never a float" in this package, because
16it is a count/measure (e.g. 2.5 hours), not currency. Line/tax math uses
17Decimal (never a bare Python float) so a fractional quantity can never
18introduce binary-float rounding error, then rounds half-up to a whole
19number of cents, the cart's rule (decision 2, 2026-11-30: it floored, and
20the same line was 54 at checkout and 53 here, finding M18). Tax is
21computed once per rate group and shared out to the lines
22(object_lines.allocate_tax).
23
24**Drafts only.** An issued invoice's total never changes and a stamped
25line tax is never recalculated after issue (the owner's decisions of
262026-11-30), so this handler folds a DRAFT invoice and leaves an issued
27one -- invoice, credit note or quote -- exactly as stamped. It used to
28restate issued checkout invoices on a description edit (M1).
29
30Why these fields are NOT schema `read_only` despite the task brief asking
31for it: verified against object_records.py before writing this file.
32`update_collection_record` has no `preserve_read_only` escape hatch at
33all (only `create_collection_record` does, and even there defaults are
34never stamped onto a read_only field -- see `_apply_schema_defaults`), so
35a genuinely `read_only` field can never be written again after creation,
36by ANY caller, including this handler's own follow-up write. Marking
37subtotal_cents/tax_cents/total_cents/balance_due_cents/line_total_cents/
38line_tax_cents read_only would therefore let this handler compute the
39correct value once and then permanently fail to ever write it again.
40Instead this package follows plan/vocabulary/20-invoice-spec.md's own
41already-reasoned fallback posture for exactly this situation ("Permissions
42Posture"): these stay ordinary owner-writable fields, simply omitted from
43forms.default so the generated form never renders them as editable
44inputs (confirmed against packages/app-theme/objects/site/form.py's own
45`skip()`, which also independently omits any read_only field --
46belt-and-suspenders, not the primary protection); any actual tamper is
47fully visible in record_changes (before/after, actor, timestamp)
48regardless. Detection, not prevention -- the same backstop the platform
49already relies on elsewhere.
50
51Idempotence: every write below is compared against the already-stored
52value first and skipped if unchanged. This platform's dispatch lives in
53object_server.py's HTTP request handlers, not inside object_records.py
54itself (checked: object_records.py has zero references to event
55dispatch), so a handler calling object_records directly -- as this one
56does -- does not currently re-enter the dispatcher and cannot recurse.
57The guard is kept anyway: it is cheap, it avoids a pointless no-op write
58and record_change entry on every re-run, and it is the correct discipline
59regardless of whether a future refactor moves dispatch closer to the
60write path (plan/vocabulary/20-invoice-spec.md calls this out as an open
61question worth a shared helper one day).
62"""
63from __future__ import annotations
64
65import os
66
67import object_record_changes
68import object_finance
69import object_lines
70import object_records
71
72HANDLES = [
73 "invoice_lines.record.created",
74 "invoice_lines.record.updated",
75 "invoice_lines.record.deleted",
76]
77
78ACTOR = "invoice_totals"
79DATA_DIR_ENV = "DBBASIC_DATA_DIR"
80
81
82def _data_dir() -> str:
83 # Mirrors object_handlers.handlers_enabled()'s own note: standalone,
84 # reads os.environ directly rather than depending on object_server.
85 return os.environ.get(DATA_DIR_ENV, object_records.DEFAULT_DATA_DIR)
86
87
88def _to_int(value):
89 """The shared defensive ledger parser (object_finance.to_cents).
90
91 This was a byte-identical private copy in three modules. One
92 shared floor-parser is one place to be right about rounding, and
93 a *_cents field left blank by a half-filled draft still reads 0
94 rather than raising.
95 """
96 return object_finance.to_cents(value)
97
98
99def _line_amounts(line: dict) -> tuple[int, int]:
100 """Return (line_total_cents, line_tax_cents) for one invoice_lines row.
101
102 The arithmetic lives in object_lines, shared with app-orders: the two
103 copies were near enough identical that one was the other plus
104 modifier_cents, and both now subtract a line discount. See that
105 module for the order of operations and why tax is charged on the
106 discounted amount.
107 """
108 amounts = object_lines.line_amounts(line)
109 return amounts["line_total_cents"], amounts["line_tax_cents"]
110
111
112def _line_discount(line: dict) -> int:
113 return object_lines.line_amounts(line)["discount_cents"]
114
115
116def _resolve_invoice_id(record_id: str, action: str, base_dir: str) -> str | None:
117 """Return the invoice_id an invoice_lines write belongs to, or None.
118
119 create/update: the line record still exists -- read it directly.
120 delete: the line is already gone by the time this fires (post-commit
121 dispatch runs after the write), so recover its last known invoice_id
122 from record_changes' own "before" snapshot -- the same "read the
123 change log directly" shape object_server.py's own
124 _record_change_for_publish already uses to recover a just-committed
125 write for its own downstream publish step.
126 """
127 if action == "delete":
128 try:
129 payload = object_record_changes.list_record_changes(
130 "invoice_lines", record_id=record_id, limit=1, base_dir=base_dir
131 )
132 except (OSError, ValueError):
133 return None
134 changes = payload.get("changes") or []
135 if not changes:
136 return None
137 before = changes[0].get("before") or {}
138 invoice_id = before.get("invoice_id")
139 return invoice_id or None
140
141 try:
142 line = object_records.get_collection_record("invoice_lines", record_id, base_dir=base_dir)
143 except (object_records.RecordNotFoundError, object_records.InvalidRecordIdError):
144 return None
145 return line.get("invoice_id") or None
146
147
148def _issued(invoice_id: str, base_dir: str) -> bool:
149 """Is this document issued -- an invoice past draft, or any credit
150 note or quote that is not a draft? Unreadable reads as issued: a fold
151 that cannot tell must not restate money (the closed direction)."""
152 try:
153 invoice = object_records.get_collection_record("invoices", invoice_id, base_dir=base_dir)
154 except (object_records.RecordNotFoundError, object_records.InvalidRecordIdError):
155 return False
156 except Exception:
157 return True
158 status = str(invoice.get("status") or "").strip().lower()
159 return status not in ("", "draft")
160
161
162def _stamp_line(line: dict, line_total_cents: int, line_tax_cents: int, base_dir: str) -> None:
163 """Write back one draft line's net, its share of the document's tax and
164 its discount, unless it already carries them (the idempotence guard).
165
166 The discount is STORED beside the total it produced, not left to be
167 re-derived: an invoice has to be able to print "10% off -2.00" next
168 to the line, and a reader who only has the net total cannot say what
169 was taken off or whether anything was."""
170 line_discount_cents = _line_discount(line)
171 if line_total_cents == _to_int(line.get("line_total_cents")) and \
172 line_tax_cents == _to_int(line.get("line_tax_cents")) and \
173 line_discount_cents == _to_int(line.get("line_discount_cents")):
174 return
175 try:
176 object_records.update_collection_record(
177 "invoice_lines",
178 line["id"],
179 {"line_total_cents": str(line_total_cents),
180 "line_tax_cents": str(line_tax_cents),
181 "line_discount_cents": str(line_discount_cents)},
182 base_dir=base_dir,
183 actor=ACTOR,
184 )
185 except (object_records.RecordNotFoundError, object_records.InvalidRecordPayloadError,
186 object_records.InvalidRecordIdError, object_records.CheckRefusedError):
187 pass
188
189
190def _recompute_invoice(invoice_id: str, base_dir: str) -> bool:
191 """Re-sum every line on invoice_id and stamp the parent invoice.
192
193 Returns True if the invoice row actually changed. A full scan of
194 invoice_lines is the right cost/complexity trade at this collection's
195 expected scale (a handful of lines per invoice, per
196 plan/vocabulary/20-invoice-spec.md) -- no index needed.
197 """
198 try:
199 invoice = object_records.get_collection_record("invoices", invoice_id, base_dir=base_dir)
200 except (object_records.RecordNotFoundError, object_records.InvalidRecordIdError):
201 return False
202
203 lines = [line for line in object_records.read_collection_records("invoice_lines", base_dir=base_dir)
204 if line.get("invoice_id") == invoice_id]
205
206 # Tax once per rate group, shared out to the lines (object_lines.
207 # allocate_tax, decision 2): each line is stamped with its share, so
208 # the lines add up to the document.
209 shares = object_lines.allocate_tax(lines)
210 subtotal_cents = 0
211 line_tax_cents_total = 0
212 any_line_states_a_rate = False
213 for line, share in zip(lines, shares):
214 line_total_cents, _ = _line_amounts(line)
215 subtotal_cents += line_total_cents
216 line_tax_cents_total += share
217 if _to_int(line.get("tax_rate_bps")):
218 any_line_states_a_rate = True
219 _stamp_line(line, line_total_cents, share, base_dir)
220
221 # A fold must not replace a value it cannot reproduce.
222 #
223 # Tax can legitimately live in either of two places: on the LINES (a
224 # rate per line, summed here) or on the DOCUMENT (computed once over
225 # the whole taxable sale, which is how action_checkout does it, so that
226 # four fifty-cent lines at 5% owe 10c rather than the 12c four
227 # separately-rounded lines come to). This handler can only see the
228 # first. When no line states a rate, a recomputed tax of zero is not a
229 # finding -- it is this object looking in the wrong place -- and
230 # writing it destroys real money.
231 #
232 # It did. On the live shop a customer was quoted 2116 at checkout
233 # (1400 goods + 600 postage + 116 tax), and by the time the invoice
234 # lines had been written this pass had restated the invoice to 2000
235 # with tax 0. The tests did not catch it because they never ran with
236 # event handlers enabled; the shop did, and the invoice disagreed with
237 # the price the customer had already agreed to.
238 if any_line_states_a_rate:
239 tax_cents = line_tax_cents_total
240 else:
241 tax_cents = _to_int(invoice.get("tax_cents"))
242
243 total_cents = subtotal_cents + tax_cents
244 # balance_due_cents / amount_paid_cents are formula fields now (invoices
245 # v2, app-payments): the storage layer derives them from total and the
246 # payments/refunds rollups on every write. Writing them here would be
247 # rejected as a computed-field submission -- this object owns only the
248 # line-derived totals until those, too, graduate to rollups.
249
250 changes = {}
251 if _to_int(invoice.get("subtotal_cents")) != subtotal_cents:
252 changes["subtotal_cents"] = str(subtotal_cents)
253 if _to_int(invoice.get("tax_cents")) != tax_cents:
254 changes["tax_cents"] = str(tax_cents)
255 if _to_int(invoice.get("total_cents")) != total_cents:
256 changes["total_cents"] = str(total_cents)
257
258 if not changes:
259 return False
260
261 try:
262 object_records.update_collection_record(
263 "invoices", invoice_id, changes, base_dir=base_dir, actor=ACTOR
264 )
265 except (object_records.RecordNotFoundError, object_records.InvalidRecordPayloadError,
266 object_records.InvalidRecordIdError):
267 return False
268 return True
269
270
271def EVENT(request):
272 """Dispatch entry point. request = {"event","collection","record_id","action"}.
273
274 Post-commit, best-effort: every exception is caught here so a bad row
275 or a race with a concurrent delete never surfaces as a failed write.
276 object_server.py's own dispatcher already wraps this call in a
277 try/except for the same reason -- this is defense in depth, not
278 redundant.
279 """
280 collection = str(request.get("collection") or "")
281 record_id = str(request.get("record_id") or "")
282 action = str(request.get("action") or "")
283 if collection != "invoice_lines" or not record_id:
284 return {"ok": True, "skipped": "not an invoice_lines event"}
285
286 base_dir = _data_dir()
287 try:
288 invoice_id = _resolve_invoice_id(record_id, action, base_dir)
289 if not invoice_id:
290 _logger.info("invoice_totals: no invoice_id resolved", record_id=record_id, action=action)
291 return {"ok": True, "skipped": "no invoice_id"}
292 if _issued(invoice_id, base_dir):
293 # An issued invoice's total never changes, and a line's stamped
294 # tax is never recalculated after issue (the owner's decisions
295 # of 2026-11-30). This fold restated issued checkout invoices --
296 # 2300 became 2090 when only the postage line stated a rate
297 # (finding M1), and a stamped 54 became 53 (M18) -- on nothing
298 # more than a description edit. It folds drafts only now; an
299 # issued invoice changes by a credit note.
300 return {"ok": True, "invoice_id": invoice_id,
301 "skipped": "issued: totals are stamped, not folded"}
302 changed = _recompute_invoice(invoice_id, base_dir)
303 except Exception as exc: # never break the triggering write
304 _logger.warning("invoice_totals recompute failed", error=str(exc))
305 return {"ok": False, "error": str(exc)}
306
307 _logger.info("invoice_totals recomputed", invoice_id=invoice_id, changed=changed)
308 return {"ok": True, "invoice_id": invoice_id, "changed": changed}