Money in a Rails quote-to-invoice app: integer cents, one rounding rule, and a browser total that doesn't count
Disclosure: this article was created with the help of AI. AI tools drafted it from my codebase and project notes, and I edited it and checked it against the code before publishing. I'm the founder of the app it describes
Disclosure: this article was created with the help of AI. AI tools drafted it from my codebase and project notes, and I edited it and checked it against the code before publishing. I'm the founder of the app it describes.
I'm building an estimate and invoice app for small trade businesses, crews of one to five people. The contractor writes an estimate, the customer opens a link, picks an option, signs and pays a deposit. Later the same numbers become an invoice.
So one price shows up in a lot of places: the editor, the customer's page, the PDF, the email, the signature record and the invoice. If two of them disagree by one cent, the customer has a reason to doubt the rest. This post is about how money works in that Rails 8 app: how it's stored, where it gets rounded, how tax and deposits are calculated, and why the total the browser shows doesn't count.
Integer cents and a currency code
Every amount in the database is an integer column that ends in _cents. The currency is its own column on the document. There are no floats and no decimal money columns. Here is part of the line items table:
quantity numeric(12,3) DEFAULT 1.0 NOT NULL,
unit_price_cents bigint,
taxes jsonb DEFAULT '[]'::jsonb NOT NULL,
CONSTRAINT line_items_non_negative CHECK (
quantity >= 0 AND (unit_price_cents IS NULL OR unit_price_cents >= 0)),
CONSTRAINT line_items_taxes_shape CHECK (
jsonb_typeof(taxes) = 'array' AND jsonb_array_length(taxes) <= 2)
Quantity is the one number that isn't an integer, because people sell 2.5 hours of labor. A NULL price is allowed on purpose. It means "needs price", and the app treats it very differently from zero.
In Ruby, amounts go into a small value object. I didn't add a gem for this. The class is about 70 lines:
class Money
def initialize(cents, currency)
raise ArgumentError, "unknown currency #{currency.inspect}" unless CURRENCIES.include?(currency)
raise ArgumentError, "cents must be an Integer" unless cents.is_a?(Integer)
@cents, @currency = cents, currency
end
def +(other) = Money.new(cents + same_currency!(other).cents, currency)
# Half up to whole cents: qty x unit price, tax, percent deposits.
def self.round_cents(value)
decimal = value.is_a?(Rational) ? BigDecimal(value, 40) : BigDecimal(value.to_s)
decimal.round(0, BigDecimal::ROUND_HALF_UP).to_i
end
end
Pass it a Float and it raises. Add two amounts in different currencies and it raises. round_cents is the only rounding rule in the app, and every rounded number goes through it.
Models don't build Money by hand. A concern turns *_cents columns into readers, and line totals are rounded once, right after quantity times price:
module PricedLine
include MoneyColumns
included do
money :unit_price, :unit_cost # line.unit_price => Money or nil
end
def line_total_cents
return nil if needs_price?
Money.round_cents(quantity.to_d * unit_price_cents)
end
end
Views use one helper:
def money(amount_cents, currency = "USD")
return "\u2014" if amount_cents.nil?
number_to_currency(amount_cents / 100.0, unit: "$")
end
Yes, there's a float in there. It's the last step, after all the math, and it only feeds the formatter. The nil case is the part I care about more. A missing price prints as a dash, never as $0.00. A $0.00 line looks like a free item, and a customer can sign that.
One class adds up the lines
QuoteTotals takes a quote and the lines of one option and returns subtotal, discount, tax, total and deposit, all in cents. The editor, the customer page, the PDF and the email either call it or read a snapshot it wrote. The invoice has its own recalculate!, because it also subtracts payments, but it copies its lines and taxes from the signed version and uses the same tax code and the same rounding.
If any line has no price, there is no total:
@needs_price_count = lines.count(&:needs_price?)
return if @needs_price_count.positive?
@gross_cents = lines.sum(&:line_total_cents)
@discount_cents = [quote.discount_cents.to_i, @gross_cents].min
@subtotal_cents = @gross_cents - @discount_cents
The editor then shows a dash for the total and tells the contractor how many prices to fix. A total that skips one line without saying so would be worse. The discount is capped at the gross amount, so the subtotal can't go below zero.
When an estimate is sent, its totals are written into the version snapshot as integers, and that version is frozen in the database (I wrote about the Postgres triggers for that in a separate post). From then on every page reads the stored numbers. Changing a tax rate in settings can't move money on an estimate the customer already has.
Tax on each line, rounded once per bucket
At first an estimate had one tax rate and each line had a taxable flag. Since early November each line can carry up to two taxes. Each one is a snapshot copied onto the line: the rate's id, name and percent. If the contractor edits the rate later, lines already using it don't change silently.
Rounding was the part that took thought. If you round the tax on every line and then add the results, the tax rows on the PDF can drift a few cents away from the tax on the total. So lines go into buckets by tax name and rate, the document discount is spread across lines in proportion to their size, and each bucket is rounded once:
@lines.each do |line|
net = Rational(line.line_total_cents * @subtotal, @gross) # discount spread pro rata
Array(line.taxes).each do |t|
buckets[[t["name"], BigDecimal(t["rate_percent"])]] += net
end
end
buckets.map do |(name, rate), base|
{ "name" => name, "rate_percent" => rate.to_s("F"),
"tax_cents" => Money.round_cents(BigDecimal(base, 40) * rate / 100) }
end
The base stays a Rational until the last line. A line's share of a discount is almost never a whole number of cents, and rounding it early would add a second rounding step. Buckets use the name and rate, not the id, so two lines with the same "Sales tax 8.25%" share one row. The tax total is the sum of the rows, so the printed rows always add up to the printed total. There are no compound taxes: every tax on a line uses the same base.
The tests for this compute the expected numbers by hand with Rational and BigDecimal and compare the editor, the customer page, the signature record and the invoice, to the cent. The fixtures use awkward amounts on purpose, like lines of 333,333 and 77,777 cents with a 12,345-cent discount.
Deposits
A deposit is either a percent or a fixed amount:
def compute_deposit(quote)
return nil unless quote.deposit_enabled
if quote.deposit_percent?
Money.round_cents(BigDecimal(@total_cents.to_s) * quote.deposit_percent / 100)
else
[quote.deposit_fixed_cents.to_i, @total_cents].min
end
end
The percent is taken from the total with tax and rounded half up, once. A fixed deposit can't be larger than the total, and the form only accepts a positive whole number of cents. One test sends "1455.5", "-100", "abc" and "0" and expects all four to be refused. Another sets a 33.33% deposit on $4,850.00 and checks that 161,651 cents ($1,616.51) appears on the review screen, the customer page, the signature and the payment record.
On the invoice, "less deposit" means money that was actually received. When the customer taps "I've paid", that's recorded, but it isn't subtracted until the contractor confirms it or marks it paid.
The browser total is for display only
On the customer page, picking an option or ticking an add-on updates the total and the deposit right away. A Stimulus controller does that math with values the server rendered into the page: each option's total and each add-on's price for that option. It uses plain JavaScript numbers and Math.round.
Most of the time that matches the server. But Math.round(1.005 * 100) returns 100, because 1.005 * 100 is 100.49999999999999 in floating point, and half-up rounding on the server gives 101. I don't want two rounding rules that have to agree forever.
So when the customer taps Accept & sign, the form sends only the choice: the option, the add-ons and their quantities. The server never reads a total from the browser. It works it out again from the frozen snapshot:
chosen = page.addons.select { |a| addon_keys.include?(a[:id]) }.to_h { |a| [a, addon_qty(a)] }
total = option[:price_cents] + chosen.sum { |a, q| a[:increments][option[:id]].to_i * q }
Signature.create!(signable: @version, selected_option_key: option[:id], selected_addons:,
total_cents: total, deposit_cents: page.deposit? ? page.deposit_from(total) : nil)
The browser doesn't compute tax at all. The tax rows for the current choice come from a small server endpoint, and it returns them only when its total equals the one the snapshot gives for that choice. The contractor's editor works the same way: a changed cell submits its row, and the server sends back the re-rendered document with new totals through a Turbo Stream.
Those parity tests have already caught one real bug. While per-line tax was still behind a feature flag, a test showed that on a signed estimate with an add-on, the tax rows and the total in the breakdown left the add-on out. The page showed less than the customer had signed for. That's when the tax rows moved to the server endpoint above.
If you've built invoicing: do you round tax per line or per rate, and has an accountant ever pushed back on your choice?
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.