Architecture
Calculation engine
The data model, the allocation algorithm and every rule that turns a bill into per-person totals.
Everything in this page lives in src/lib/ and is pure: no React, no storage, no clock. The UI only ever calls computeBreakdown(bill) and renders the result.
Money is integers
All amounts are integer minor units (Cents in the code): centavos for BRL, cents for USD/EUR, whole pesos for CLP. The number of decimals comes from Intl.NumberFormat(...).resolvedOptions().maximumFractionDigits, so the code never hard-codes "2".
Floats only appear at the two edges:
- Input —
parseAmount(text, digits)reads what a person typed and returns minor units. It accepts both decimal conventions (12,50,12.50,1.234,56,1,234.56). A single separator followed by exactly three digits (1.500) is read as a thousands separator, because no supported currency has three decimals. - Output —
formatMoney/formatAmountuse cachedIntl.NumberFormatinstances.
The model
interface Bill {
people: Person[]; // { id, name, color }
items: Item[]; // { id, name, quantity, price, shares }
adjustments: Adjustment[]; // service charge, cover, delivery, discounts…
payment: PaymentPlan; // how it was paid at the venue
settled: Record<string, boolean>;
pix: Record<PersonId, PixInfo>;
currency: CurrencyCode;
// + id, title, createdAt, updatedAt, v: 2
}
Two decisions shape everything else:
- An item's
priceis the line total, not a unit price. Receipts print line totals, and a unit price like10,00 / 3cannot be represented exactly.quantityis informational; the UI derives the unit price for display (unitPrice(item)). sharesmaps person id → portions.{ ana: 2, bia: 1 }means Ana pays two thirds. A person missing from the map (or with0) did not have the item. The default when an item is added is "everyone, one portion each".
Allocation: the largest-remainder method
allocate(total, weights) splits an integer total into integer parts proportional to integer weights and guarantees the parts sum to the total:
- Give each part the floor of its exact share:
⌊total × wᵢ / Σw⌋. - Count the units left over (always fewer than the number of parts).
- Hand them out one by one to the parts with the largest fractional remainders. Ties go to the earlier position.
allocate(10000, [1, 1, 1]) → [3334, 3333, 3333] R$ 100,00 ÷ 3
allocate(5960, [2, 1, 1]) → [2980, 1490, 1490] Chopp: Ana had two
allocate(1, [0, 0, 1, 0]) → [0, 0, 1, 0] zero weight never gets a cent
The tie-break makes results deterministic: the same bill always gives the same cents to the same people, which matters when a group compares phones. When total × Σw would exceed Number.MAX_SAFE_INTEGER, the function switches to BigInt for that call.
Computing a breakdown
computeBreakdown(bill) runs three passes.
1. Items
For each item, the consumers are the people with portions > 0, in bill order. The item price is allocated over their portions. Items with no consumers are reported in breakdown.unassigned and left out of the total — the UI warns about them and offers "split among everyone" rather than silently charging someone.
A person's subtotal is the sum of their item lines. It is the base for every percentage and proportional rule below.
2. Adjustments
Adjustments never compound: they are all computed on item subtotals, in any order, with the same result.
| Kind | Example | Rule |
|---|---|---|
percent | Service 10%, a tax | Round the group total once: round(Σbase × rate), then allocate it by each applicable person's subtotal. |
fixed + equal | Delivery fee | Allocate the amount equally among applicable people. |
fixed + proportional | A coupon | Allocate by subtotal. If every applicable subtotal is 0, fall back to equal parts. |
perPerson | Cover charge (couvert) | Every applicable person pays the full amount. |
discount: true flips the sign of every part. Percentages are stored in basis points (1000 = 10%) so a rate like 12.5% stays an integer.
Rounding the group total once is what keeps the receipt honest: the "SERVIÇO 10%" line printed on the receipt is exactly the sum of what each person pays for service. Rounding per person would let the two drift apart by a cent or two.
3. Totals
total = subtotal + Σ adjustment lines. The engine also exposes grandTotal = Σ totals, and by construction:
grandTotal === assignedTotal + Σ adjustment totals
This invariant is asserted in the tests for every scenario.
A worked example
Ana, Bruno, Carla and Davi at a bar. Service is 10% but Davi doesn't pay it; there's a R$ 12,00 cover per person and a R$ 10,00 coupon split by consumption.
| Item | Price | Who (portions) |
|---|---|---|
| 4× Chopp | 59,60 | Ana ×2, Bruno, Davi |
| Pizza | 89,00 | everyone |
| 2× Água | 10,00 | Carla |
| Sobremesa | 25,00 | nobody → unassigned |
Subtotals — Ana 29,80 + 22,25 = 52,05; Bruno 14,90 + 22,25 = 37,15; Carla 22,25 + 10,00 = 32,25; Davi 37,15. Assigned total 158,60 (the dessert's 25,00 is excluded and flagged).
Service — base 52,05 + 37,15 + 32,25 = 121,45 → 10% = 12,145 → rounded once to 12,15. Allocated by subtotal: exact shares 5,207 / 3,716 / 3,226 → floors 5,20 / 3,71 / 3,22 (12,13) → the two leftover cents go to the largest remainders, Ana and Bruno → 5,21 / 3,72 / 3,22.
Cover — 12,00 × 4 = 48,00.
Coupon — −10,00 by subtotal (52,05 / 37,15 / 32,25 / 37,15) → −3,28 / −2,34 / −2,04 / −2,34. Carla gets the extra cent: her remainder was largest.
| Items | Service | Cover | Coupon | Total | |
|---|---|---|---|---|---|
| Ana | 52,05 | 5,21 | 12,00 | −3,28 | 65,98 |
| Bruno | 37,15 | 3,72 | 12,00 | −2,34 | 50,53 |
| Carla | 32,25 | 3,22 | 12,00 | −2,04 | 45,43 |
| Davi | 37,15 | — | 12,00 | −2,34 | 46,81 |
| 158,60 | 12,15 | 48,00 | −10,00 | 208,75 |
This exact scenario is the fixture in src/lib/__tests__/engine.test.ts.
Settlement
Who owes whom is a separate step on top of the breakdown — see settlement and Pix.
Edge cases and their behavior
| Situation | Behavior |
|---|---|
| Item with no consumers | Excluded from totals, listed in unassigned, highlighted in the UI. |
| Adjustment applies to nobody | Contributes 0; the UI says so. |
| Percentage with all subtotals 0 | Total is 0. |
| Discount bigger than someone's subtotal | Their total can go negative. The math stays honest; the UI shows it as is. |
| Person removed | Removed from every item, adjustment, payment, settled flag and Pix entry (one reducer action). |
| Late arrival | Added automatically to items and adjustments that were shared by the whole table; custom subsets are left alone. |
| Duplicate names | Rejected case- and accent-insensitively ("Ana" = "ána"). |
Where the code lives
| File | Responsibility |
|---|---|
src/lib/money.ts | Parsing, formatting, minor digits, currencies |
src/lib/allocate.ts | Largest-remainder allocation |
src/lib/bill/types.ts | The model |
src/lib/bill/engine.ts | computeBreakdown |
src/lib/bill/reducer.ts | Every state change, as a pure reducer |
src/lib/bill/settle.ts | Payments and transfers |
src/lib/bill/parse-item.ts | Receipt shorthand ("2x Chopp 14,90") and name lists |