Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Added the 6.0 money correctness plan
Damian Legawiecccfbb62e2ba5
diff --git a/docs/plans/5.5-client-side-money-normalization.md b/docs/plans/5.5-client-side-money-normalization.mdindex 3c64b055c6..27be30f5ee 100644--- a/docs/plans/5.5-client-side-money-normalization.md+++ b/docs/plans/5.5-client-side-money-normalization.md@@ -49,7 +49,7 @@ Consequences (binding):- **Admin API money contract is canonical decimal strings.** Read and write: `"19.99"` — period decimal, no thousands separator, matching what serializers already emit (see `docs/api-reference/admin-api/monetary-amounts.mdx`). This is already the *read* format; this plan makes it the explicit *write* format too.- **The React dashboard normalizes localized input → canonical before sending.** A shared util parses the merchant's input in the active display locale (currency's market locale) and emits `"1234.56"`. Built on `Intl.NumberFormat(...).formatToParts` to derive the locale's separators, then strip grouping and standardize the decimal to `.`.- **No `x-spree-locale` is sent to drive money parsing.** Revert the per-form locale overrides AND the client-level admin-sdk locale support added on the feature branch. The admin-sdk has no `setLocale`/`setCurrency`/`AdminClientConfig.locale` (see "Two independent locales" above) — deliberate per-locale/per-currency calls use the generic per-request `options.locale`/`options.currency`.-- **`Spree::LocalizedNumber.parse` is NOT removed and NOT changed.** It remains the parser for the legacy Rails admin and any other locale-formatted caller. Because canonical `"19.99"` is locale-invariant, no model/controller change is required for the dashboard pivot.+- **Superseded 2026-10-09 (`6.0-money-correctness.md`): the locale-parsing setters are removed and `LocalizedNumber` is deprecated, because the legacy admin is gone and the setters corrupted canonical input in comma-decimal stores.** Original decision: **`Spree::LocalizedNumber.parse` is NOT removed and NOT changed.** It remains the parser for the legacy Rails admin and any other locale-formatted caller. Because canonical `"19.99"` is locale-invariant, no model/controller change is required for the dashboard pivot.- **Rails admin (legacy `spree/admin`) is out of scope.** It keeps submitting locale-formatted values parsed server-side under the session locale. Untouched.- **Store API is out of scope.** Audited: the Store API v3 accepts no client-supplied amount that reaches a `LocalizedNumber`-guarded setter (amounts are derived server-side; `Spree::Payment#amount=` has its own parser). No change needed.@@ -134,6 +134,7 @@ The dashboard's own UI language (i18next `i18n.language`) is unaffected by this## Open Questions- Should the normalize util live in `dashboard-ui` (so the MoneyCell owns it end-to-end) or `dashboard` (form layer)? Leaning `dashboard-ui` since the cell already owns display formatting.+- **Superseded 2026-10-08 by `6.0-money-correctness.md`:** 6.0 is strict — Admin and Seller writes reject JSON numbers and non-canonical or over-precise strings with 422 `invalid_money_format`, and percentages become decimal strings.- Long-term: do we want the Admin API to *reject* non-canonical money strings (strict `^\d+(\.\d+)?$` validation) to make the contract explicit, or keep tolerating localized input server-side (via the models' `LocalizedNumber`) as a lenient fallback? Strict is more Shopify-like; lenient is backward-compatible. Recommend lenient now, revisit.## Referencesdiff --git a/docs/plans/6.0-money-correctness.md b/docs/plans/6.0-money-correctness.mdnew file mode 100644index 0000000000..df189bb4b4--- /dev/null+++ b/docs/plans/6.0-money-correctness.md@@ -0,0 +1,228 @@+# Money Correctness++**Status:** In Progress — building PR A (floats out); A2 (gateway amounts), B (wire contract) and C (precision) follow+**Target:** Spree 6.0+**Depends on:** `5.5-client-side-money-normalization.md` (canonical decimal-string contract), `6.0-6.1-split-adjustments.md` (typed `spree_tax_lines` / `spree_discounts` / `spree_fees` — landed, so they are in scope), `6.0-json-preferences.md` (decimal preferences are exact strings), `6.0-payment-gateways-monorepo.md` (Stripe lives in the monorepo; Adyen and PayPal Checkout are separate gems patched in the same release)+**Author:** Damian + Claude+**Last updated:** 2026-10-09+**Tracking:** Linear V-3738 · GitHub spree/spree#14848++## Summary++Spree stores money in decimal columns, but four things still make amounts wrong or ambiguous before 6.0. Some money paths pass through floats (`.to_f` in Ruby, `parseFloat` in the dashboard), so a captured `"1.15"` can become `114` cents. The API does not agree with itself on what a money field looks like: most fields are strings, a few are JSON numbers, and the strings are not normalized (`"10.0"`, never `"10.00"`). Payment gateways receive a bare integer in hundredths of the currency, which is the right unit only for two-decimal currencies, while Stripe sessions use ISO minor units — and Stripe's own units are neither (ISK, HUF, TWD carry special rules). And the columns are `decimal(10, 2)`, which cannot hold a Kuwaiti dinar's third decimal, a sub-cent B2B unit price, or a large Vietnamese dong order. This plan removes floats from money paths in Ruby and TypeScript and writes the rule into `CLAUDE.md`, hands gateways an amount with its currency and lets each adapter convert to its provider's unit, makes every money field on the wire a decimal string written to a published per-currency exponent, and widens the money columns to `decimal(19, 4)`. It ships as four pull requests: A (floats out), A2 (gateway amounts), B (wire contract), C (precision).++## Key Decisions (do not deviate without discussion)++All decided 2026-10-08; the ones marked *review* were changed or added after the design review that day.++- **Decimal strings, not integer minor units.** Money stays a canonical decimal string on the wire (`5.5-client-side-money-normalization.md`). No integer minor-unit field appears in the API; the integer `amount_in_cents` / `compare_at_amount_in_cents` fields leave the Price and PriceHistory serializers.+- **BigDecimal end to end, Ruby and TypeScript.** Money is never a `Float` / JS `number` between parsing and persisting or between reading and comparing. Stated as a rule in `CLAUDE.md` ("Money").+- **The currency exponent is ISO 4217, from one Spree-owned file** (*review*). `spree/core/config/currency_exponents.json` holds the ISO 4217 minor-unit table, pinned to a dated list. Ruby registers it over the Money gem at boot, so `Spree::Money::Rounding.precision`, `Money#cents` and `Money#format` agree; `@spree/sdk-core` imports the same file; `CurrencySerializer` exposes it as `decimal_places`. Where the Money gem differs today (HUF 0 → 2, MGA and MRU 1 → 2) Spree follows ISO. Why: the exponent is now part of the contract (`"100.5"` JPY is a 422), so a client must be able to read it, and the TypeScript side must use exactly the same table. Accepted trade-off: Spree stops rounding HUF to whole forints; stored HUF values are already at two decimals and do not change. Upgrade-guide entry.+- **Gateways receive a `Spree::Money`, not an integer** (*review*; supersedes "gateways receive true minor units" from the first pass). Core passes amount and currency; each adapter converts to its provider's unit. Stripe's adapter owns Stripe's rules (zero-decimal list, ISK sent in a two-decimal representation divisible by 100, HUF and TWD whole-amount rules). Why: no single integer unit is right for every provider, and this gives the TypeScript rewrite a gateway interface whose unit does not depend on the currency.+- **Old gateways keep today's behaviour for one release** (*review*). A gateway opts in with `self.accepts_money_amounts = true`. Core keeps passing the integer in hundredths, exactly as today, to any gateway that has not opted in, with a deprecation warning; the bridge is removed in 6.1. Stripe (monorepo), `spree_adyen` and `spree_paypal_checkout` opt in in the same release. Shipped alone as PR A2, so reverting it restores today's behaviour.+- **Two precisions on write** (*review*). Unit-price fields — `price` and `compare_at_amount` on prices (base and price-list prices, which carry price breaks), `price` on line items, `cost_price`, `unit_cost` — accept up to 4 decimals (`"0.0125"` USD). Every other money field — totals, payments, refunds, captures, adjustments, discounts, fees, tax lines, gift cards, store credit, payouts — accepts at most the currency's exponent. Line amounts are `price × quantity` rounded to the exponent when persisted. Why: B2B unit pricing and price breaks ship in 6.0 and need sub-cent unit prices; money that changes hands never has sub-minor-unit amounts.+- **Writes are strict strings.** The Admin and Seller APIs parse money with `BigDecimal(str)` and reject a JSON number, a non-canonical string (`"1,99"`, `"1e3"`, `" 5"`, `"+5"`), or an over-precise string (by the rule above) with 422 `invalid_money_format`, naming the field. Top-level fields and the money keys inside `preferences`. Supersedes "JSON numbers are also accepted" in `monetary-amounts.mdx` and the 5.5 plan's "lenient now" leaning. Accepted trade-off: breaking for integrators sending numbers.+- **Canonical read format.** A money field is a string matching `^-?\d+(\.\d+)?$`. Exponent fields carry exactly the currency's decimal places (`"10.00"`, `"1.500"`, `"100"`). Unit-price fields carry at least the exponent and at most 4, with zeros beyond the exponent stripped (`"19.99"`, `"0.0125"`, `"19.9950"` → `"19.995"`). `display_*` companions are unchanged.+- **Rates and percentages are canonical decimal strings** (*review*: canonical form and naming rule added). No fixed exponent, trailing zeros and a trailing `.` stripped (`decimal(8,5)` `0.23000` → `"0.23"`, `23.00` → `"23"`), top-level and inside `preferences`. Naming rule, enforced by the contract spec: a name ending `_percent` or `_percentage` is 0–100; a name that is `rate` or ends `_rate` is a fraction (0.23). A field may not be named like money (`amount`, `value`) when it holds a rate. So the Admin tax rate's `amount` (fraction) becomes `rate` and `amount_percentage` becomes `rate_percent`, with model aliases per the read/write-symmetry rule. Discount `value` is the one documented exception: money or percent by its `value_type`.+- **Round only at boundaries; the rounding mode is a parameter** (*review*). Intermediate math keeps full precision. `Spree::Money::Rounding.to_currency(amount, currency, mode: :half_up)` is called when a total or line amount is persisted, when a gateway adapter converts, and when an amount is serialized. Tax providers own their rounding (per line or per invoice, and the mode); the internal provider keeps per-line half-up.+- **Columns become `decimal(19, 4)`.** Every money column, including the typed adjustment tables. Rate and percentage columns keep their current scale. Widening changes no stored value.+- **The column migration is idempotent and has a documented online path** (*review*). It skips a column already at `(19, 4)`, so an install that widened large tables ahead of the upgrade (shadow column plus backfill) runs it as a no-op for those. Default path: one migration in the 6.0 upgrade window, accepting the table rewrite under lock.+- **Wrong capture events are reported, not repaired.** `spree:money:audit_capture_events` lists payments in non-two-decimal currencies whose capture events disagree with the corrected value, and writes nothing. Spree never rewrites money on completed orders.+- **The rule lives in `CLAUDE.md`, not in a lint tool** (decided 2026-10-09; supersedes the first pass's RuboCop cop and Biome twin). A cop was built and then dropped: the repository runs no RuboCop, and a name-matching rule needs an allowlist that is mostly noise. `CLAUDE.md` "Money" states it for people and agents alike.+- **Open carts in zero- and three-decimal currencies change on their next recalculation.** Accepted trade-off: a yen total can move by under one yen mid-checkout. Completed orders are frozen and do not change.+- **Spree stops parsing numbers by locale** (decided 2026-10-09; supersedes the 5.5 plan's "`LocalizedNumber` is not removed" and this plan's first-pass "out of scope"). The model setters that re-parsed strings with `Spree::LocalizedNumber` under the request locale are removed, and Rails' decimal type reads the value as sent. Why: the legacy admin they served is gone, and under a store whose language writes a comma decimal they misread the dashboard's canonical `"49.50"` as 4950 and grew an untouched `"99.0"` tenfold on every save (a reported bug). `Spree::LocalizedNumber.parse` stays one release as a deprecated method nothing in Spree calls, and is removed in 6.1. The variant's `cost_price`/`weight`/`width`/`height`/`depth` writers keep ignoring a blank value. Ships in PR A.+- **PR A applies the ISO table to Spree's own rounding only; registering it over the Money gem moves to A2** (decided 2026-10-09). Registering changes `Money#cents` for HUF, which Stripe payment sessions read, and A2 is the only PR that may change what a gateway receives.++## Design Details++### Inventory: every `.to_f` and `Float(` outside specs (58 sites at `4ca24b8`)++Verdict **money** means it is fixed in PR A. **Not money** sites stay as they are. **Boundary** means a third party requires a JSON number; the value is computed in BigDecimal and converted once, on the line that hands it over, with a comment saying why.++| Site | What it is | Verdict |+|---|---|---|+| `api/…/admin/orders/payments_controller.rb:55` | capture amount: `(params[:amount].to_f * 100).round` — float, and hard-coded hundredths | **money** |+| `core/…/workflows/spree/payments/capture.rb:89` | capture event: `::Money.new(@amount, currency).to_f` — float, and reads hundredths as true minor units (see "Gateway unit") | **money** |+| `core/…/models/spree/refund.rb:124` | refund credit cents via `amount.to_f` | **money** |+| `core/lib/spree/money.rb:106` | `amount_in_cents`: `cents / subunit_to_unit.to_f * 100` | **money** |+| `core/…/models/spree/tax_rate.rb:69` | `amount_percentage=`: `value.to_f / 100` | **money** (rate) |+| `core/…/concerns/spree/vat_price_calculation.rb:69` | included VAT rate `.to_f`, multiplied into a price | **money** (rate) |+| `core/…/models/spree/order.rb:420` | `analytics_subtotal` returns a Float | **money** |+| `core/…/models/spree/order.rb:1277` | `attributes[:amount].to_f.zero?` | **money** |+| `core/…/purchase/payment_processing.rb:49` | `total.to_f > 0.0` | **money** |+| `core/…/calculator/shipping/flat_percent_item_total.rb:16` | `(value * 100).round.to_f / 100` | **money** |+| `core/…/services/spree/stores/provision_defaults.rb:263` | `preferences[:amount].to_f.zero?` | **money** |+| `core/…/csv/order_line_item_presenter.rb:99,100,101,108` | item/delivery/tax/grand total in CSV | **money** |+| `core/…/csv/order_line_item_presenter.rb:110` | total weight | not money |+| `core/…/csv/product_variant_presenter.rb:101,102,178,179` | price / compare-at in CSV | **money** |+| `core/lib/spree/reporting/adapters/base.rb:25` | `:money`/`:decimal`/`:percent` metrics cast `to_f.round(2)` | **money** |+| `core/lib/spree/reporting/adapters/base.rb:38` | derived ratio (average order value is money ÷ count) | **money** |+| `core/lib/spree/reporting/adapters/base.rb:66` | period-over-period growth percentage | not money |+| `api/…/v3/cart_serializer.rb:109,113` | `order_minimum_amount`, `order_minimum_shortfall` emitted as numbers | **money** |+| `api/…/v3/admin/store_serializer.rb:129` | `preferred_default_minimum_payout_amount` as number | **money** |+| `api/…/v3/admin/store_serializer.rb:133` | `preferred_default_commission_tax_rate` as number | **money** (rate) |+| `api/…/v3/admin/tax_rate_serializer.rb:30` | `amount_percentage` as number | **money** (rate) |+| `api/…/services/spree/api/v3/filters_aggregator.rb:66,67` | price-range filter `min`/`max` as numbers | **money** |+| `providers/easypost/lib/spree_easypost.rb:179,198` | customs declared value: `item.price.to_f * quantity` | **money** (boundary at the EasyPost call) |+| `providers/meilisearch/…/product_presenter.rb:67,68` | indexed `price` / `compare_at_price` | **boundary** — Meilisearch numeric filters and sort need numbers |+| `providers/meilisearch/…/search_provider.rb:389,391,443` | price filter value parsed with `to_f` / `Float(` | **money** (parse with `parse_canonical`, emit at boundary) |+| `providers/meilisearch/…/search_provider.rb:584,585` | price facet min/max read back from the index | **money** (become strings on the wire with the filters aggregator) |+| `providers/meilisearch/…/product_presenter.rb:109` | number custom field | not money |+| `core/…/models/spree/variant.rb:1077`, `freight_summary/line.rb:171` | carton counts | not money |+| `core/…/models/spree/package_type.rb:128,130`, `providers/easypost/lib/spree_easypost.rb:27,39` | dimensions and weights | not money |+| `api/…/v3/variant_serializer.rb:44,48,52,56` | weight / height / width / depth | not money |+| `api/…/v3/admin/address_serializer.rb:20,24`, `api/…/store/delivery_methods_controller.rb:32,33` | latitude / longitude | not money |+| `core/…/concerns/spree/stores/setup.rb:52` | setup percent complete | not money |+| `core/…/services/spree/generate_token.rb:17` | timestamp | not money |+| `core/lib/spree/translations.rb:84` | translation coverage ratio | not money |+| `core/…/serializers/spree/emails/store_serializer.rb:22` | logo height | not money |++**Hard-coded hundredths** (not `.to_f`, same class of bug — fixed in PR A because the float fix touches the same lines):++| Site | Code |+|---|---|+| `core/…/adjusters/promotion.rb:152,157` | promotion distribution in `* 100` cents |+| `core/…/services/spree/orders/discounts/create.rb:55,60,66` | manual discount distribution in `* 100` cents; percent `.round(2)` |+| `core/…/payment_method/store_credit.rb:29,41,52,79` | `amount_in_cents / 100.0.to_d` |+| `core/…/calculator/tiered_percent.rb:18`, `flat_percent_item_total.rb:10`, `percent_on_line_item.rb:14` | `.round(2)` |+| `core/…/tax_provider/internal.rb:178,180`, `delivery_rate.rb:83,85` | tax `.round(2)` |+| `core/…/stock/estimator.rb:124` | markup `.round(2)` |++The store credit gateway's `amount_in_cents / 100.0.to_d` (`payment_method/store_credit.rb:29,41,52,79`) is fixed in PR A2, where it opts into `Spree::Money` amounts. The rest of the hard-coded hundredths (promotion and manual discount distribution, `.round(2)` in calculators, tax and markup) are fixed in PR A.++### TypeScript inventory++About 50–65 `Number(...)` / `parseFloat(...)` calls in `packages/dashboard`, `dashboard-core`, `dashboard-ui` and `seller-dashboard` touch money, depending on how they are counted (64 by a name filter on `amount|price|total|cost|fee|discount|tax|refund|balance`). Representative: `orders/order-adjustments-cards.tsx:436` sums `parseFloat`s of `discounted_amount`; `orders/fulfillment-edit-dialog.tsx:61` compares `parseFloat(rate.cost) === 0`. Both `monetary-amounts.mdx` pages tell integrators to `parseFloat(order.total)`. Every money site is fixed in PR B.++### Gateway amounts++Today `payment_method.authorize/purchase/capture/credit` receive `Spree::Money#amount_in_cents`, the amount in hundredths for every currency (1000 JPY → `100000`; 1.505 KWD → `151`), while Stripe sessions use `Money#cents`, the ISO minor unit (1000 JPY → `1000`). The capture event then reads the hundredths value back as minor units: a 1000 JPY capture records 100,000 JPY, a 1.500 KWD capture records 0.150 KWD. `Payment#captured_amount` sums those events and the capture flow resizes the payment from that sum, so the error can reach the payment's own amount.++PR A fixes the recording without touching what any gateway receives: the capture event is the hundredths integer divided by 100, in BigDecimal, which is correct for every currency the hundredths unit can express. PR A2 then changes the interface:++```ruby+class Spree::Gateway+ class_attribute :accepts_money_amounts, default: false+end++# core, one place (Spree::Payment#gateway_amount):+amount = payment_method.accepts_money_amounts ? money : legacy_hundredths(money)++class SpreeStripe::Gateway < Spree::Gateway+ self.accepts_money_amounts = true++ def capture(money, payment_intent_id, options = {})+ Stripe::PaymentIntent.capture(payment_intent_id, { amount_to_capture: stripe_units(money) }, opts)+ end+end+```++`stripe_units` lives in the Stripe gem and is also what payment sessions use, so a session and its capture always agree. `spree_adyen` (Adyen minor units, its own currency table) and `spree_paypal_checkout` (PayPal decimal strings) opt in in releases cut alongside 6.0. The store credit gateway opts in and reads `money.amount` directly.++### Strict parsing at the API boundary++`Spree::Money::Rounding.parse_canonical(value, currency, unit_price: false)` returns a `BigDecimal` for a `String` matching `^-?\d+(\.\d+)?$` with at most the currency's decimal places (4 with `unit_price: true`), and `nil` for `nil`. Anything else raises `Spree::Money::InvalidFormat`, which the v3 base controller renders as 422 with code `invalid_money_format` and the field in `details`. Rates use `parse_canonical_decimal(value)`: same shape, no decimal limit beyond the column's. Admin and Seller controllers validate every declared money and rate field, including the money and percentage keys of `preferences`, before assignment, so a model setter only ever sees a canonical string. The Store API takes no client amounts (5.5 audit) and is unchanged.++### Wire contract++`BaseSerializer.money_attributes` is the only way to declare a money field, with the currency read from the record:++```ruby+money_attributes :total, :item_total # currency from object.currency+money_attributes :amount, :compare_at_amount, unit_price: true+money_attributes :cost_price, currency: :cost_currency, unit_price: true+money_attributes :minimum_payout_amount, currency: ->(store) { store.default_currency }+rate_attributes :rate, :rate_percent # canonical decimal, zeros stripped+```++Both format through `Spree::Money::Rounding.format(amount, currency, unit_price:)` / `format_decimal`, keep `hide_prices`, and type the field `string | null`. `CurrencySerializer` gains `decimal_places`.++The contract spec loads every v3 serializer (Store, Admin, Seller), builds each resource from its factory in USD, KWD and JPY, and asserts: every `money_attributes` field matches `^-?\d+(\.\d+)?$` with exactly the currency's decimal places (or within exponent..4 for unit prices); every `rate_attributes` field has no trailing zeros; no attribute whose name matches the money pattern is declared any other way; no rate is named like money; `_percent`/`_percentage` fields fall in 0–100 and `rate`/`_rate` fields in 0–1 on the factory data.++Known non-conforming fields today: `cart.order_minimum_amount` / `order_minimum_shortfall` (numbers), admin store `preferred_default_minimum_payout_amount` / `preferred_default_commission_tax_rate` (numbers), admin tax rate `amount` (fraction named like money) and `amount_percentage` (number), product filter price range `min`/`max` (numbers), report money metrics (numbers), `price.amount_in_cents` / `compare_at_amount_in_cents` / `price_history.amount_in_cents` (removed). Every other money field is already a string, but unnormalized.++### TypeScript money++`@spree/sdk-core` gains a small decimal helper over strings, built on the same `currency_exponents.json`: `compareMoney(a, b)`, `sumMoney(values, currency)`, `isZeroMoney(value)`, `decimalPlaces(currency)`. It works on scaled `bigint`s internally and returns canonical strings, so no money value passes through a JS `number`. The dashboard's money sites move onto it; display keeps `Intl.NumberFormat` on the `display_*` fields or on the string. Both `monetary-amounts.mdx` pages replace `parseFloat` with the helper.++### Precision migration++One migration, `ChangeMoneyColumnsToDecimal194`, changes every money column below to `decimal(19, 4)`, keeping each column's `null` and `default`, and **skips any column already at `(19, 4)`**. Its `down` restores each original type. Values do not change: every stored `decimal(10,2)` / `(8,2)` / `(12,4)` value is exactly representable.++Columns (from `server/db/schema.rb` at `4ca24b8`): `spree_adjustments.amount`; all `*_total`, `cost`, `price`, `cost_price`, `pre_tax_amount`, `amount*`, `refund_amount`, `tax_amount`, `unit_cost`, `revenue`, `settled_amount`, `minimum_payout_amount`, `min_amount`/`max_amount`, `markup_flat` columns on carts, orders, line items, fulfillments, payments, payment splits, payment sessions, payment capture events, refunds, reimbursements and reimbursement credits, return / claim / exchange line items, return items, prices and price histories, gift cards and batches, store credits and events (today `8,2`), tax lines, discounts (`amount`; `value` is percent-or-amount and widens with it), fees, commission lines and rate values, seller payouts and transfers, sellers, catalog order minimums, delivery methods and their services, delivery rates (today `8,2`), shipping labels, purchase order items, stock movements, variants (`cost_price`), products and products-stores (`revenue`), Stripe payment intents. Extension tables (`spree_paypal_checkout_orders`) are listed in the upgrade guide for their gem to follow. Not changed: `tax_rates.amount`, `tax_lines.rate`, `commission_*.rate`/`tax_rate`/`commission_tax_rate`/`value`, `price_adjustment_*percentage`, `markup_percent`, dimensions, weights, coordinates, focal points.++Cost: a scale change rewrites the table under an exclusive lock on PostgreSQL, and every `ALTER` rewrites on MySQL. The upgrade guide documents the default (run it in the upgrade window) and an online path for large installs: add a `(19,4)` shadow column, backfill in batches, swap names in one short transaction for `spree_orders`, `spree_line_items` and `spree_adjustments`; the migration then finds those columns already widened and skips them.++### Value-changing cases++None changes a stored value of an existing two-decimal order.++1. **New capture events in zero- and three-decimal currencies** are recorded correctly (PR A). Old rows are reported by `spree:money:audit_capture_events`, never rewritten.+2. **What opted-in gateways receive** changes for every currency's representation (a `Spree::Money` instead of an integer); the amount charged changes only where it was wrong (JPY captures at Stripe). Un-opted gateways see no change until 6.1.+3. **Open carts in zero- and three-decimal currencies** recalculate with exponent rounding (`123.40` JPY → `123`). Accepted.+4. **Promotion and manual discount distribution in JPY/KWD** splits in whole yen / thousandths of a dinar on new orders.+5. **HUF** stops rounding to whole forints (ISO 4217 says two decimals).+6. **CSV exports and reports** print canonical strings instead of floats.+7. **Every money string on the wire** is written to its exponent (`"10.0"` → `"10.00"`, JPY `"1000.0"` → `"1000"`); rates lose trailing zeros; the tax rate fields are renamed.++## Migration Path++**PR A — floats out.** No wire, schema or gateway-interface change.+1. Add `currency_exponents.json` and read it in `Spree::Money::Rounding`; add `parse_canonical`, `parse_canonical_decimal`, `format`, `format_decimal`, and a `mode:` parameter on `to_currency`.+2. Fix every **money** row of the Ruby inventory and the hard-coded hundredths. Capture events record `hundredths / 100` in BigDecimal.+3. Remove the locale-parsing model setters and deprecate `Spree::LocalizedNumber`.+4. Add `spree:money:audit_capture_events` (report only).+5. Add the "Money" rule to `CLAUDE.md`.+6. Rounding conformance specs that do not depend on column width.+7. Upgrade guide: HUF exponent, open-cart rounding, the audit task, `LocalizedNumber` deprecation.++**PR A2 — gateway amounts.** Revertible on its own.+1. Register `currency_exponents.json` over the Money gem; `Spree::Gateway.accepts_money_amounts`, the hundredths bridge with its deprecation warning, `Spree::Payment#gateway_amount`.+2. Stripe adapter opts in with `stripe_units` (zero-decimal list, ISK, HUF, TWD rules), used by sessions and by capture/refund; store credit gateway opts in.+3. Patch and release `spree_adyen` and `spree_paypal_checkout` alongside 6.0.+4. Upgrade guide and changelog: the extension API change and the 6.1 removal of the bridge.++**PR B — wire contract (breaking).**+1. `money_attributes` (exponent and unit-price formats) and `rate_attributes`; convert the non-conforming fields; rename the tax rate fields with model aliases; remove the `*_in_cents` fields; `decimal_places` on currencies.+2. Strict `invalid_money_format` parsing on Admin and Seller writes, including `preferences`.+3. Contract spec over every v3 serializer.+4. Regenerate Typelizer types and Zod schemas for `sdk`, `admin-sdk`, `seller-sdk`; regenerate `docs/api-reference/*.yaml` through rswag.+5. `@spree/sdk-core` decimal helper; move the dashboard and seller panel money sites onto it.+6. Both `monetary-amounts.mdx` pages (remove "JSON numbers are also accepted", "percentage keys stay numbers" and `parseFloat`; document `invalid_money_format`, `decimal_places`, unit-price precision and the rate naming rule), `docs/developer/upgrades/5.6-to-6.0.mdx`, `docs/changelog.mdx`, a changeset for the SDKs.++**PR C — precision.**+1. The idempotent column migration; `pnpm wt:template`.+2. Remove the "money columns are `decimal(_, 2)`" caveat from `Spree::Money::Rounding.precision`.+3. Specs that only pass after widening: KWD three-decimal order, VND order above 100,000,000, a `"0.0125"` USD unit price.+4. Upgrade guide: the migration window, the online path, extension tables to widen (`spree_paypal_checkout_orders`).++**Rounding conformance specs** (each states the exact expected `BigDecimal`): tax-inclusive VAT pricing; split payments summing exactly to the order total; partial refunds leaving the exact residual; largest-remainder promotion distribution summing to the promotion amount; captures of `"0.29"`, `"1.15"`, `"1234567.89"`; a KWD three-decimal order end to end; a JPY zero-decimal order end to end; a VND order above 100,000,000; a sub-cent unit price whose line total rounds to the exponent.++Verification per PR: the changed specs locally, then `pnpm test:rspec core` and `pnpm test:rspec api` one at a time; for A2 also `pnpm test:rspec stripe`; for B `pnpm typecheck` and `pnpm test` in `packages/sdk-core`, `sdk`, `admin-sdk`, `seller-sdk`, and `pnpm exec tsc -b` in the dashboard.++## Constraints on Current Work++- **No float on a money path, in Ruby or TypeScript.** Parse with `parse_canonical`, compute in `BigDecimal` (or the sdk-core helper), never `* 100`, never `.round(2)` — round with `to_currency(amount, currency)`.+- **Exponents come from `currency_exponents.json`**, never from a hard-coded 2 or straight from the Money gem's defaults.+- **Declare money fields with `money_attributes`** (with `unit_price: true` for unit prices) **and rates with `rate_attributes`.** Never a plain `attribute`, never `.to_f`, never typed `:number`.+- **Name rates by the rule**: `_percent`/`_percentage` is 0–100, `rate`/`_rate` is a fraction, and a rate is never named like money.+- **New gateways set `accepts_money_amounts = true`** and convert `Spree::Money` to their provider's unit in the adapter.+- **New money columns are `decimal(19, 4)`**, `null: false, default: 0` where required. Rates are `decimal(8, 5)`.+- **Do not round in intermediate math** — only when persisting, in a gateway adapter, or when serializing. Tax providers choose their own rounding.+- **Money writes are strict.** A new Admin or Seller endpoint taking an amount parses it with `parse_canonical(value, currency)`; never `.to_d`, `BigDecimal(x.to_s)` on a raw param, or `LocalizedNumber`.+- **No locale parsing on the server.** A model setter never re-parses a number by locale; localized input is normalized by the client.++## Open Questions++None. Everything raised by the draft and by the review was settled on 2026-10-08 and is recorded in Key Decisions.++## References++- `docs/plans/5.5-client-side-money-normalization.md`+- `docs/plans/6.0-6.1-split-adjustments.md`+- `docs/plans/6.0-payment-gateways-monorepo.md`+- `docs/plans/6.0-multi-vendor-marketplace.md` — commission rounding already specified as half-up to the currency exponent+- `docs/plans/6.0-json-preferences.md` — decimal preferences stored as exact strings+- `docs/api-reference/admin-api/monetary-amounts.mdx`, `docs/api-reference/store-api/monetary-amounts.mdx`+- `spree/core/lib/spree/money.rb` — `Spree::Money::Rounding`+- ISO 4217 minor units; Stripe's currency rules (zero-decimal and special cases)diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 19ab661823..3154c410de 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,21 @@+## 2026-10-09: Spree stops parsing numbers by locale++**Context:** Price, variant, payment, refund, store credit, gift card and adjustment setters re-parsed every string with `Spree::LocalizedNumber` under the request's locale, for the legacy Rails admin. That admin is gone. In a store whose language writes a comma decimal (nl, de, fr) the setters read the dashboard's canonical `"49.50"` as 4950, and an untouched `"99.0"` grew tenfold on every save.++**Decision:** The locale-parsing setters are removed; Rails' decimal type stores the value as sent. `Spree::LocalizedNumber.parse` is deprecated with a warning and removed in 6.1. Clients normalize localized input before sending (5.5 plan).++**Consequences:** A localized string sent to a model (`"1.234,56"`) is no longer understood; the Admin API never accepted it by contract. Supersedes the 5.5 plan's "`LocalizedNumber.parse` is NOT removed". See `6.0-money-correctness.md`.++## 2026-10-08: Money is BigDecimal end to end, gateways get amount plus currency, strict canonical strings on the wire, and decimal(19,4) in the database++**Context:** Money columns were already decimal, but several money paths went through floats (Ruby `.to_f`, dashboard `parseFloat`). A few serializers emitted JSON numbers while the rest emitted unnormalized strings (`"10.0"`). Every gateway call was made in hundredths of the currency while Stripe sessions used ISO minor units, so yen captures recorded 100× the amount and dinar captures a tenth, and Stripe's own units differ from both for ISK, HUF and TWD. `decimal(10,2)` could hold neither a dinar's third decimal, a sub-cent unit price, nor a large dong order.++**Decision:** No float on a money path in Ruby or TypeScript, stated as a rule in `CLAUDE.md` (a lint cop was tried and dropped on 2026-10-09); `@spree/sdk-core` gets a string-based decimal helper. Currency exponents are ISO 4217 from one Spree-owned file, registered over the Money gem, imported by sdk-core and exposed as `decimal_places` on currencies. Gateways receive a `Spree::Money` and each adapter converts to its provider's unit; gateways that have not opted in keep receiving hundredths with a deprecation warning until 6.1. Every money field in every v3 serializer is a decimal string: exactly the exponent for totals and money that changes hands, up to four decimals for unit prices. Rates and percentages are decimal strings with trailing zeros stripped; `_percent` means 0–100, `rate` means a fraction, and no rate is named like money. Admin and Seller writes reject JSON numbers, non-canonical strings and over-precise strings with 422 `invalid_money_format`. Money columns become `decimal(19,4)` in one idempotent migration with a documented online path. Rounding happens only when persisting, in a gateway adapter, or when serializing, with the mode a parameter and tax providers owning theirs. Existing wrong capture events are reported, never rewritten.++**Consequences:** Breaking for API clients sending numbers or comparing money strings, for clients reading the removed `*_in_cents` fields or the renamed tax rate fields, and (from 6.1) for gateways that never opt in. HUF stops rounding to whole forints. Open carts in zero- and three-decimal currencies change on their next recalculation; completed orders do not. Integer minor units are rejected as an API contract. Ships as four PRs: floats out, gateway amounts, wire contract, precision.++**Plans amended:** `5.5-client-side-money-normalization.md` (its "lenient now" open question is settled as strict). See `6.0-money-correctness.md`.+## 2026-10-07: Translations move into core, and `Spree.t` is deprecated for `I18n.t`**Context:** `Spree.t` ran through Rails' view translation helper, so it needed Action View and returned `<span class="translation_missing">` markup for a missing key, which leaked into JSON errors and dashboard notifications. Every language but English lived in `spree_i18n`: 6.5 MB of locale files, about 60% for the removed admin and storefront, plus `kaminari-i18n` (which requires the full `rails` gem), `i18n_data` (which swaps the global `I18n.backend`) and `spree_extension`.