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.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
object_lines.py · 6.1 KB · 155 lines
| 1 | """Line arithmetic: one implementation of what a document line costs. |
| 2 | |
| 3 | app-orders and app-invoices each carried their own `_line_amounts`, near |
| 4 | enough identical that the orders one is the invoices one plus |
| 5 | `modifier_cents`. That duplication was survivable while the answer was |
| 6 | "quantity times price"; it stops being survivable the moment a discount |
| 7 | has to be subtracted in both, and app-shop, the cart, the emails and the |
| 8 | document renderer all restate the same number too. |
| 9 | |
| 10 | So the math lives here, once, pure -- no I/O, no clock, testable without |
| 11 | a data directory, same posture as object_promotions and object_cart. The |
| 12 | totals handlers become callers rather than authors. |
| 13 | |
| 14 | ## What a discount is here, and what it is NOT |
| 15 | |
| 16 | This is a LINE discount: a negotiated reduction on one row -- ex-display |
| 17 | stock, a trade rate, ten per cent off this item and nothing else. It is |
| 18 | recorded on the line and prints on the invoice beside what it reduced. |
| 19 | |
| 20 | It is not a promotion. object_promotions owns those: a code somebody |
| 21 | types, applied to the whole basket and ROUNDED ONCE, deliberately, so |
| 22 | four separately-rounded lines cannot accumulate an error nobody can |
| 23 | reconcile against the percentage printed on the receipt. The two compose |
| 24 | -- a line discount changes the line, a promotion then comes off the |
| 25 | discounted subtotal -- and keeping them apart is what stops "10% off" |
| 26 | meaning two different numbers depending on which layer applied it. |
| 27 | |
| 28 | ## The order of operations, which is the whole specification |
| 29 | |
| 30 | gross = floor(quantity x (unit_price + modifier)) |
| 31 | discount = gross x discount_bps // 10000 |
| 32 | net = gross - discount |
| 33 | tax = net x tax_rate_bps // 10000 |
| 34 | |
| 35 | Three things about that, each of which would be a bug the other way: |
| 36 | |
| 37 | **Tax is charged on the DISCOUNTED amount.** A discount on goods reduces |
| 38 | the taxable base -- object_promotions.applies_to says the same thing for |
| 39 | promotions, and the two must not disagree about it. Taxing the gross |
| 40 | would charge a customer tax on money nobody ever asked them for. |
| 41 | |
| 42 | **The discount floors off the already-floored gross**, not off a |
| 43 | fractional intermediate. This is what makes a zero discount arithmetically |
| 44 | invisible: every existing line total is bit-identical to what it was |
| 45 | before this module existed, which is the only acceptable behaviour for a |
| 46 | change that touches every historical document. |
| 47 | |
| 48 | **A discount can never make a line negative.** 12000 basis points is a |
| 49 | typo, not a refund, and a line that pays the customer is not something to |
| 50 | infer from a mistyped rate. |
| 51 | |
| 52 | Basis points, matching `tax_rate_bps`: 1000 = 10%. A flat per-unit |
| 53 | reduction already has a home in `modifier_cents`, which is signed -- the |
| 54 | percentage is what nothing could express. |
| 55 | """ |
| 56 | |
| 57 | from __future__ import annotations |
| 58 | |
| 59 | from decimal import Decimal, InvalidOperation, ROUND_FLOOR |
| 60 | from typing import Any |
| 61 | |
| 62 | #: 100% off. Anything above this is a typo rather than an intention. |
| 63 | MAX_DISCOUNT_BPS = 10000 |
| 64 | |
| 65 | |
| 66 | def _int(value: Any, default: int = 0) -> int: |
| 67 | try: |
| 68 | return int(str(value if value is not None else "").strip() or default) |
| 69 | except (TypeError, ValueError): |
| 70 | return default |
| 71 | |
| 72 | |
| 73 | def _decimal(value: Any) -> Decimal: |
| 74 | text = str(value if value is not None else "").strip() |
| 75 | if not text: |
| 76 | return Decimal("0") |
| 77 | try: |
| 78 | return Decimal(text) |
| 79 | except InvalidOperation: |
| 80 | return Decimal("0") |
| 81 | |
| 82 | |
| 83 | def line_amounts(line: Any) -> dict: |
| 84 | """Every money number one document line implies. |
| 85 | |
| 86 | Returns {"gross_cents", "discount_cents", "line_total_cents", |
| 87 | "line_tax_cents"}. `line_total_cents` is the NET of discount, because |
| 88 | that is the number every existing caller already stores under that |
| 89 | name and the number a customer is asked to pay. |
| 90 | |
| 91 | Reads every field with .get and a zero default, so a row written |
| 92 | before any of these columns existed folds exactly as it always did. |
| 93 | """ |
| 94 | line = line or {} |
| 95 | quantity = _decimal(line.get("quantity")) |
| 96 | unit_price = _decimal(line.get("unit_price_cents")) |
| 97 | # A per-unit delta ("oat milk +60c"), added to the UNIT price because |
| 98 | # two oat lattes are two lots of oat milk. Signed, so it is also how a |
| 99 | # flat per-unit reduction is expressed. |
| 100 | modifier = _decimal(line.get("modifier_cents")) |
| 101 | |
| 102 | gross_cents = int((quantity * (unit_price + modifier)).to_integral_value( |
| 103 | rounding=ROUND_FLOOR)) |
| 104 | |
| 105 | discount_bps = _int(line.get("discount_bps")) |
| 106 | if discount_bps < 0: |
| 107 | discount_bps = 0 |
| 108 | if discount_bps > MAX_DISCOUNT_BPS: |
| 109 | discount_bps = MAX_DISCOUNT_BPS |
| 110 | |
| 111 | # Integer floor division on an already-integer gross: with no |
| 112 | # discount this is exactly zero and every historical total is |
| 113 | # untouched. |
| 114 | discount_cents = (gross_cents * discount_bps) // 10000 |
| 115 | if gross_cents < 0: |
| 116 | # A negative line (a credit row) is not discountable; taking a |
| 117 | # percentage off it would make the credit smaller, which is the |
| 118 | # opposite of what anyone typing "10% off" means. |
| 119 | discount_cents = 0 |
| 120 | discount_cents = min(discount_cents, max(gross_cents, 0)) |
| 121 | |
| 122 | line_total_cents = gross_cents - discount_cents |
| 123 | tax_rate_bps = _int(line.get("tax_rate_bps")) |
| 124 | line_tax_cents = (line_total_cents * tax_rate_bps) // 10000 |
| 125 | |
| 126 | return { |
| 127 | "gross_cents": gross_cents, |
| 128 | "discount_cents": discount_cents, |
| 129 | "line_total_cents": line_total_cents, |
| 130 | "line_tax_cents": line_tax_cents, |
| 131 | } |
| 132 | |
| 133 | |
| 134 | def totals(lines: Any) -> dict: |
| 135 | """Fold many lines into document-level sums. |
| 136 | |
| 137 | Kept beside the per-line math so a caller cannot fold with one rule |
| 138 | and display with another -- the failure the orders handler's own |
| 139 | docstring warns about, where a fold that cannot reproduce the number |
| 140 | it restates quietly replaces a correct total with a smaller one. |
| 141 | """ |
| 142 | gross = discount = subtotal = tax = 0 |
| 143 | for line in lines or (): |
| 144 | amounts = line_amounts(line) |
| 145 | gross += amounts["gross_cents"] |
| 146 | discount += amounts["discount_cents"] |
| 147 | subtotal += amounts["line_total_cents"] |
| 148 | tax += amounts["line_tax_cents"] |
| 149 | return { |
| 150 | "gross_cents": gross, |
| 151 | "discount_cents": discount, |
| 152 | "subtotal_cents": subtotal, |
| 153 | "tax_cents": tax, |
| 154 | "total_cents": subtotal + tax, |
| 155 | } |