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.
object_lines.py · 9.0 KB · 210 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 = round_half_up(quantity x (unit_price + modifier)) |
| 31 | discount = round_half_up(gross x discount_bps / 10000) |
| 32 | net = gross - discount |
| 33 | tax = round_half_up(net x tax_rate_bps / 10000) (one line alone) |
| 34 | |
| 35 | Every rounding is half-up (the owner's decisions of 2026-11-30: tax is |
| 36 | rounded half-up, and a division into an integer field rounds half-up). |
| 37 | These used to FLOOR, while object_cart rounds half-up, so the same 650 |
| 38 | cents of postage at 8.25% was 54 at checkout and 53 when invoice_totals |
| 39 | restated the line, and 1.5 kg at 3.33 was 500 in the basket and 499 on the |
| 40 | order (findings M18). One rule now, in both places. |
| 41 | |
| 42 | Three things about that order, each of which would be a bug the other way: |
| 43 | |
| 44 | **Tax is charged on the DISCOUNTED amount.** A discount on goods reduces |
| 45 | the taxable base -- object_promotions.applies_to says the same thing for |
| 46 | promotions, and the two must not disagree about it. Taxing the gross |
| 47 | would charge a customer tax on money nobody ever asked them for. |
| 48 | |
| 49 | **The discount comes off the already-rounded gross**, not off a |
| 50 | fractional intermediate, so a zero discount is arithmetically invisible. |
| 51 | |
| 52 | **A discount can never make a line negative.** 12000 basis points is a |
| 53 | typo, not a refund, and a line that pays the customer is not something to |
| 54 | infer from a mistyped rate. |
| 55 | |
| 56 | Basis points, matching `tax_rate_bps`: 1000 = 10%. A flat per-unit |
| 57 | reduction already has a home in `modifier_cents`, which is signed -- the |
| 58 | percentage is what nothing could express. |
| 59 | |
| 60 | ## Tax on a DOCUMENT: once per rate group (decision 2, 2026-11-30) |
| 61 | |
| 62 | A document's tax is not the sum of separately rounded lines: four |
| 63 | fifty-cent lines at 5% owe 10c, not the 12c four rounded 2.5c come to. |
| 64 | The rate is STAMPED on each line when the document is issued, and the tax |
| 65 | is computed once per rate group -- the sum of the group's net amounts |
| 66 | times the rate, rounded half-up -- then shared out to the lines so that |
| 67 | each line says what it carries and the lines add up to the document: every |
| 68 | line gets the floor of its exact share, and the cents left over go one each |
| 69 | to the lines with the largest remainders (ties to the earlier line). That |
| 70 | is `allocate_tax`. A line's tax is never recalculated after issue: a |
| 71 | credit note uses the original rate (object_corrections), and the totals |
| 72 | handlers stop folding an issued document. |
| 73 | """ |
| 74 | |
| 75 | from __future__ import annotations |
| 76 | |
| 77 | from decimal import Decimal, InvalidOperation, ROUND_FLOOR, ROUND_HALF_UP |
| 78 | from typing import Any |
| 79 | |
| 80 | #: 100% off. Anything above this is a typo rather than an intention. |
| 81 | MAX_DISCOUNT_BPS = 10000 |
| 82 | |
| 83 | |
| 84 | def _int(value: Any, default: int = 0) -> int: |
| 85 | try: |
| 86 | return int(str(value if value is not None else "").strip() or default) |
| 87 | except (TypeError, ValueError): |
| 88 | return default |
| 89 | |
| 90 | |
| 91 | def _decimal(value: Any) -> Decimal: |
| 92 | text = str(value if value is not None else "").strip() |
| 93 | if not text: |
| 94 | return Decimal("0") |
| 95 | try: |
| 96 | return Decimal(text) |
| 97 | except InvalidOperation: |
| 98 | return Decimal("0") |
| 99 | |
| 100 | |
| 101 | def half_up(value: Decimal) -> int: |
| 102 | """Round to a whole number of minor units, half away from zero.""" |
| 103 | return int(value.to_integral_value(rounding=ROUND_HALF_UP)) |
| 104 | |
| 105 | |
| 106 | def line_amounts(line: Any) -> dict: |
| 107 | """Every money number one document line implies, the line taken alone. |
| 108 | |
| 109 | Returns {"gross_cents", "discount_cents", "line_total_cents", |
| 110 | "line_tax_cents"}. `line_total_cents` is the NET of discount, because |
| 111 | that is the number every existing caller already stores under that |
| 112 | name and the number a customer is asked to pay. `line_tax_cents` is |
| 113 | the line's tax rounded on its own; on a document of several lines the |
| 114 | stamped share comes from allocate_tax instead. |
| 115 | |
| 116 | Reads every field with .get and a zero default, so a row written |
| 117 | before any of these columns existed folds exactly as it always did. |
| 118 | """ |
| 119 | line = line or {} |
| 120 | quantity = _decimal(line.get("quantity")) |
| 121 | unit_price = _decimal(line.get("unit_price_cents")) |
| 122 | # A per-unit delta ("oat milk +60c"), added to the UNIT price because |
| 123 | # two oat lattes are two lots of oat milk. Signed, so it is also how a |
| 124 | # flat per-unit reduction is expressed. |
| 125 | modifier = _decimal(line.get("modifier_cents")) |
| 126 | |
| 127 | gross_cents = half_up(quantity * (unit_price + modifier)) |
| 128 | |
| 129 | discount_bps = _int(line.get("discount_bps")) |
| 130 | if discount_bps < 0: |
| 131 | discount_bps = 0 |
| 132 | if discount_bps > MAX_DISCOUNT_BPS: |
| 133 | discount_bps = MAX_DISCOUNT_BPS |
| 134 | |
| 135 | discount_cents = half_up(Decimal(gross_cents * discount_bps) / 10000) |
| 136 | if gross_cents < 0: |
| 137 | # A negative line (a credit row) is not discountable; taking a |
| 138 | # percentage off it would make the credit smaller, which is the |
| 139 | # opposite of what anyone typing "10% off" means. |
| 140 | discount_cents = 0 |
| 141 | discount_cents = min(discount_cents, max(gross_cents, 0)) |
| 142 | |
| 143 | line_total_cents = gross_cents - discount_cents |
| 144 | tax_rate_bps = _int(line.get("tax_rate_bps")) |
| 145 | line_tax_cents = half_up(Decimal(line_total_cents * tax_rate_bps) / 10000) |
| 146 | |
| 147 | return { |
| 148 | "gross_cents": gross_cents, |
| 149 | "discount_cents": discount_cents, |
| 150 | "line_total_cents": line_total_cents, |
| 151 | "line_tax_cents": line_tax_cents, |
| 152 | } |
| 153 | |
| 154 | |
| 155 | def allocate_tax(lines: Any) -> list[int]: |
| 156 | """Each line's share of its document's tax, in the lines' order. |
| 157 | |
| 158 | Lines are grouped by their stamped tax_rate_bps (0 = untaxed). Each |
| 159 | group's tax is round_half_up(sum of its nets x rate / 10000), once; it |
| 160 | is shared out by giving every line the floor of its exact share and |
| 161 | the remaining cents, one each, to the lines with the largest |
| 162 | remainders (ties to the earlier line). So the shares always add up to |
| 163 | the group's single rounding, and no line is ever more than a cent from |
| 164 | its exact share. A negative line (a discount carrying the rate of what |
| 165 | it discounts) takes a negative share.""" |
| 166 | lines = list(lines or ()) |
| 167 | nets = [line_amounts(line)["line_total_cents"] for line in lines] |
| 168 | rates = [_int((line or {}).get("tax_rate_bps")) for line in lines] |
| 169 | shares = [0] * len(lines) |
| 170 | groups: dict[int, list[int]] = {} |
| 171 | for index, rate in enumerate(rates): |
| 172 | if rate > 0: |
| 173 | groups.setdefault(rate, []).append(index) |
| 174 | for rate, members in groups.items(): |
| 175 | exact = {i: Decimal(nets[i] * rate) / 10000 for i in members} |
| 176 | group_tax = half_up(sum(exact.values(), Decimal(0))) |
| 177 | floors = {i: int(exact[i].to_integral_value(rounding=ROUND_FLOOR)) for i in members} |
| 178 | left = group_tax - sum(floors.values()) |
| 179 | order = sorted(members, key=lambda i: (-(exact[i] - floors[i]), i)) |
| 180 | for i in members: |
| 181 | shares[i] = floors[i] |
| 182 | for i in order[:max(left, 0)]: |
| 183 | shares[i] += 1 |
| 184 | return shares |
| 185 | |
| 186 | |
| 187 | def totals(lines: Any) -> dict: |
| 188 | """Fold many lines into document-level sums, with the tax computed |
| 189 | once per rate group (allocate_tax), not summed from rounded lines. |
| 190 | |
| 191 | Kept beside the per-line math so a caller cannot fold with one rule |
| 192 | and display with another -- the failure the orders handler's own |
| 193 | docstring warns about, where a fold that cannot reproduce the number |
| 194 | it restates quietly replaces a correct total with a smaller one. |
| 195 | """ |
| 196 | lines = list(lines or ()) |
| 197 | gross = discount = subtotal = 0 |
| 198 | for line in lines: |
| 199 | amounts = line_amounts(line) |
| 200 | gross += amounts["gross_cents"] |
| 201 | discount += amounts["discount_cents"] |
| 202 | subtotal += amounts["line_total_cents"] |
| 203 | tax = sum(allocate_tax(lines)) |
| 204 | return { |
| 205 | "gross_cents": gross, |
| 206 | "discount_cents": discount, |
| 207 | "subtotal_cents": subtotal, |
| 208 | "tax_cents": tax, |
| 209 | "total_cents": subtotal + tax, |
| 210 | } |