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