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

0 downloads

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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
order_totals.py · 11.5 KB · 267 lines
1"""order_totals -- HANDLES order_lines writes; recomputes order 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 order_lines commits, but only when the operator
8has DBBASIC_ENABLE_EVENT_HANDLERS set. With the flag unset (the default),
9order_lines/orders writes still succeed -- they just stop getting fresher
10totals until a line is touched again after the flag is turned on. This is
11a near-identical mirror of packages/app-invoices/objects/system/invoice_totals.py;
12see that file for the fuller rationale this one repeats more briefly.
13
14Integer-cents arithmetic only, per 00-doctrine-and-contract.md: money is
15always a whole number of cents. quantity is the one deliberate exception
16to "never a float" in this package, because it is a count/measure, not
17currency. Line/tax math uses Decimal (never a bare Python float) so a
18fractional quantity can never introduce binary-float rounding error, then
19floors to an integer number of cents -- never rounds up.
20
21Why subtotal_cents/tax_cents/total_cents/line_total_cents/line_tax_cents
22are NOT schema `read_only` despite the task brief asking for it: verified
23against object_records.py before writing this file, exactly as
24invoice_totals.py was. `update_collection_record` has no
25`preserve_read_only` escape hatch at all (only `create_collection_record`
26does, and even there defaults are never stamped onto a read_only field),
27so a genuinely `read_only` field could never be written again after
28creation, by ANY caller, including this handler's own follow-up write.
29These stay ordinary owner-writable fields, simply omitted from
30forms.default so the generated form never renders them as editable
31inputs (confirmed against packages/app-theme/objects/site/form.py's own
32`skip()`, which also independently omits any read_only field --
33belt-and-suspenders, not the primary protection); any actual tamper is
34fully visible in record_changes (before/after, actor, timestamp)
35regardless. Detection, not prevention.
36
37Idempotence: every write below is compared against the already-stored
38value first and skipped if unchanged. This platform's dispatch lives in
39object_server.py's HTTP request handlers, not inside object_records.py
40itself, so a handler calling object_records directly -- as this one does
41-- does not currently re-enter the dispatcher and cannot recurse. The
42guard is kept anyway: it is cheap, it avoids a pointless no-op write and
43record_change entry on every re-run, and it is the correct discipline
44regardless of whether a future refactor moves dispatch closer to the
45write path.
46"""
47from __future__ import annotations
48
49import os
50from decimal import ROUND_FLOOR, Decimal
51
52import object_record_changes
53import object_finance
54import object_lines
55import object_records
56
57HANDLES = [
58 "order_lines.record.created",
59 "order_lines.record.updated",
60 "order_lines.record.deleted",
61]
62
63ACTOR = "order_totals"
64DATA_DIR_ENV = "DBBASIC_DATA_DIR"
65
66
67def _data_dir() -> str:
68 # Mirrors object_handlers.handlers_enabled()'s own note: standalone,
69 # reads os.environ directly rather than depending on object_server.
70 return os.environ.get(DATA_DIR_ENV, object_records.DEFAULT_DATA_DIR)
71
72
73def _to_int(value):
74 """The shared defensive ledger parser (object_finance.to_cents).
75
76 This was a byte-identical private copy in three modules. One
77 shared floor-parser is one place to be right about rounding, and
78 a *_cents field left blank by a half-filled draft still reads 0
79 rather than raising.
80 """
81 return object_finance.to_cents(value)
82
83
84def _line_amounts(line: dict) -> tuple[int, int]:
85 """Return (line_total_cents, line_tax_cents) for one order_lines row.
86
87 The arithmetic itself lives in object_lines, shared with
88 app-invoices, because the two copies of this function were near
89 enough identical that one was the other plus modifier_cents -- and
90 they now both have to subtract a discount. See that module for the
91 order of operations and why tax is charged on the discounted amount.
92 """
93 amounts = object_lines.line_amounts(line)
94 return amounts["line_total_cents"], amounts["line_tax_cents"]
95
96
97def _line_discount(line: dict) -> int:
98 return object_lines.line_amounts(line)["discount_cents"]
99
100
101def _resolve_order_id(record_id: str, action: str, base_dir: str) -> str | None:
102 """Return the order_id an order_lines write belongs to, or None.
103
104 create/update: the line record still exists -- read it directly.
105 delete: the line is already gone by the time this fires (post-commit
106 dispatch runs after the write), so recover its last known order_id
107 from record_changes' own "before" snapshot -- the same "read the
108 change log directly" shape object_server.py's own
109 _record_change_for_publish already uses to recover a just-committed
110 write for its own downstream publish step.
111 """
112 if action == "deleted":
113 try:
114 payload = object_record_changes.list_record_changes(
115 "order_lines", record_id=record_id, limit=1, base_dir=base_dir
116 )
117 except (OSError, ValueError):
118 return None
119 changes = payload.get("changes") or []
120 if not changes:
121 return None
122 before = changes[0].get("before") or {}
123 order_id = before.get("order_id")
124 return order_id or None
125
126 try:
127 line = object_records.get_collection_record("order_lines", record_id, base_dir=base_dir)
128 except (object_records.RecordNotFoundError, object_records.InvalidRecordIdError):
129 return None
130 return line.get("order_id") or None
131
132
133def _sync_triggering_line(record_id: str, action: str, base_dir: str) -> None:
134 """Recompute + write back the one line that triggered this dispatch.
135
136 No-op for delete (nothing left to write) and for a line already
137 carrying the correct stamped values (the idempotence guard).
138 """
139 if action == "deleted":
140 return
141 try:
142 line = object_records.get_collection_record("order_lines", record_id, base_dir=base_dir)
143 except (object_records.RecordNotFoundError, object_records.InvalidRecordIdError):
144 return
145
146 line_total_cents, line_tax_cents = _line_amounts(line)
147 line_discount_cents = _line_discount(line)
148 # The discount is STORED beside the total it produced, not left to be
149 # re-derived: an invoice has to be able to print "10% off -2.00"
150 # next to the line, and a reader who only has the net total cannot
151 # say what was taken off or whether anything was.
152 if line_total_cents == _to_int(line.get("line_total_cents")) and \
153 line_tax_cents == _to_int(line.get("line_tax_cents")) and \
154 line_discount_cents == _to_int(line.get("line_discount_cents")):
155 return
156
157 try:
158 object_records.update_collection_record(
159 "order_lines",
160 record_id,
161 {"line_total_cents": str(line_total_cents),
162 "line_tax_cents": str(line_tax_cents),
163 "line_discount_cents": str(line_discount_cents)},
164 base_dir=base_dir,
165 actor=ACTOR,
166 )
167 except (object_records.RecordNotFoundError, object_records.InvalidRecordPayloadError,
168 object_records.InvalidRecordIdError):
169 pass
170
171
172def _recompute_order(order_id: str, base_dir: str) -> bool:
173 """Re-sum every line on order_id and stamp the parent order.
174
175 Returns True if the order row actually changed. A full scan of
176 order_lines is the right cost/complexity trade at this collection's
177 expected scale (a handful of lines per order) -- no index needed.
178 """
179 try:
180 order = object_records.get_collection_record("orders", order_id, base_dir=base_dir)
181 except (object_records.RecordNotFoundError, object_records.InvalidRecordIdError):
182 return False
183
184 lines = object_records.read_collection_records("order_lines", base_dir=base_dir)
185
186 subtotal_cents = 0
187 line_tax_cents_total = 0
188 any_line_states_a_rate = False
189 for line in lines:
190 if line.get("order_id") != order_id:
191 continue
192 line_total_cents, line_tax_cents = _line_amounts(line)
193 subtotal_cents += line_total_cents
194 line_tax_cents_total += line_tax_cents
195 if _to_int(line.get("tax_rate_bps")):
196 any_line_states_a_rate = True
197
198 # A fold must not replace a value it cannot reproduce -- the same rule,
199 # and the same live bug, as invoice_totals. Tax may be computed once
200 # over the whole sale and stamped on the DOCUMENT (action_checkout) or
201 # stated per line; this pass can only see the second. A recomputed zero
202 # when no line states a rate means this object looked in the wrong
203 # place, not that no tax is owed.
204 if any_line_states_a_rate:
205 tax_cents = line_tax_cents_total
206 else:
207 tax_cents = _to_int(order.get("tax_cents"))
208
209 # The order's total is what its OWN lines come to. Postage lives on the
210 # invoice, because the invoice is the document the customer pays and
211 # carriage is a cost of delivering the order rather than part of what
212 # was ordered. So an order and its invoice can legitimately differ by
213 # the postage, and that is not a discrepancy to paper over here -- a
214 # first attempt at this refused to let a recompute ever shrink a total,
215 # which duly broke the perfectly ordinary case of deleting a line.
216 total_cents = subtotal_cents + tax_cents
217
218 changes = {}
219 if _to_int(order.get("subtotal_cents")) != subtotal_cents:
220 changes["subtotal_cents"] = str(subtotal_cents)
221 if _to_int(order.get("tax_cents")) != tax_cents:
222 changes["tax_cents"] = str(tax_cents)
223 if _to_int(order.get("total_cents")) != total_cents:
224 changes["total_cents"] = str(total_cents)
225
226 if not changes:
227 return False
228
229 try:
230 object_records.update_collection_record(
231 "orders", order_id, changes, base_dir=base_dir, actor=ACTOR
232 )
233 except (object_records.RecordNotFoundError, object_records.InvalidRecordPayloadError,
234 object_records.InvalidRecordIdError):
235 return False
236 return True
237
238
239def EVENT(request):
240 """Dispatch entry point. request = {"event","collection","record_id","action"}.
241
242 Post-commit, best-effort: every exception is caught here so a bad row
243 or a race with a concurrent delete never surfaces as a failed write.
244 object_server.py's own dispatcher already wraps this call in a
245 try/except for the same reason -- this is defense in depth, not
246 redundant.
247 """
248 collection = str(request.get("collection") or "")
249 record_id = str(request.get("record_id") or "")
250 action = str(request.get("action") or "")
251 if collection != "order_lines" or not record_id:
252 return {"ok": True, "skipped": "not an order_lines event"}
253
254 base_dir = _data_dir()
255 try:
256 order_id = _resolve_order_id(record_id, action, base_dir)
257 if not order_id:
258 _logger.info("order_totals: no order_id resolved", record_id=record_id, action=action)
259 return {"ok": True, "skipped": "no order_id"}
260 _sync_triggering_line(record_id, action, base_dir)
261 changed = _recompute_order(order_id, base_dir)
262 except Exception as exc: # never break the triggering write
263 _logger.warning("order_totals recompute failed", error=str(exc))
264 return {"ok": False, "error": str(exc)}
265
266 _logger.info("order_totals recomputed", order_id=order_id, changed=changed)
267 return {"ok": True, "order_id": order_id, "changed": changed}