Architecture

Calculation engine

The data model, the allocation algorithm and every rule that turns a bill into per-person totals.

A documentação técnica está em inglês.

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 / formatAmount use cached Intl.NumberFormat instances.

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:

  1. An item's price is the line total, not a unit price. Receipts print line totals, and a unit price like 10,00 / 3 cannot be represented exactly. quantity is informational; the UI derives the unit price for display (unitPrice(item)).
  2. shares maps person id → portions. { ana: 2, bia: 1 } means Ana pays two thirds. A person missing from the map (or with 0) 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:

  1. Give each part the floor of its exact share: ⌊total × wᵢ / Σw⌋.
  2. Count the units left over (always fewer than the number of parts).
  3. 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.

KindExampleRule
percentService 10%, a taxRound the group total once: round(Σbase × rate), then allocate it by each applicable person's subtotal.
fixed + equalDelivery feeAllocate the amount equally among applicable people.
fixed + proportionalA couponAllocate by subtotal. If every applicable subtotal is 0, fall back to equal parts.
perPersonCover 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.

ItemPriceWho (portions)
4× Chopp59,60Ana ×2, Bruno, Davi
Pizza89,00everyone
2× Água10,00Carla
Sobremesa25,00nobody → 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.

ItemsServiceCoverCouponTotal
Ana52,055,2112,00−3,2865,98
Bruno37,153,7212,00−2,3450,53
Carla32,253,2212,00−2,0445,43
Davi37,15—12,00−2,3446,81
158,6012,1548,00−10,00208,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

SituationBehavior
Item with no consumersExcluded from totals, listed in unassigned, highlighted in the UI.
Adjustment applies to nobodyContributes 0; the UI says so.
Percentage with all subtotals 0Total is 0.
Discount bigger than someone's subtotalTheir total can go negative. The math stays honest; the UI shows it as is.
Person removedRemoved from every item, adjustment, payment, settled flag and Pix entry (one reducer action).
Late arrivalAdded automatically to items and adjustments that were shared by the whole table; custom subsets are left alone.
Duplicate namesRejected case- and accent-insensitively ("Ana" = "ána").

Where the code lives

FileResponsibility
src/lib/money.tsParsing, formatting, minor digits, currencies
src/lib/allocate.tsLargest-remainder allocation
src/lib/bill/types.tsThe model
src/lib/bill/engine.tscomputeBreakdown
src/lib/bill/reducer.tsEvery state change, as a pure reducer
src/lib/bill/settle.tsPayments and transfers
src/lib/bill/parse-item.tsReceipt shorthand ("2x Chopp 14,90") and name lists
Editar esta página no GitHub