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.
Document Number Customization
Status: Implemented (core + API + dashboard, 2026-08-13)
Target: Spree 6.0
Depends on: 6.0-cart-order-split.md (order creation point), 6.0-store-scoped-configuration.md (settings doctrine), 6.0-returns-exchanges-claims.md (number columns as migration cursor), 6.0-inventory-operations.md (PurchaseOrder born with HasNumber)
Author: Damian Legawiec
Last updated: 2026-08-13
Summary
Human-readable document numbers (R1001, RET1005) are today generated by
Spree::Core::NumberGenerator — a Module subclass whose prefix and length
are frozen into each model at boot (include Spree::Core::NumberGenerator.new(prefix: 'R')). Customizing a number format
requires a decorator that re-includes the module, there is no store awareness,
and every number is random. This plan replaces the module factory with
runtime-resolved generator strategy classes, makes sequential numbering the
default from 6.0 with random as an opt-in, gives merchants a dashboard
setting for the order number format, derives fulfillment and payment
numbers from their parent order (R1001-F1, R1001-P1) instead of storing
them, and keeps every other model's stored number while moving them all onto
one swappable generator.
Key Decisions (do not deviate without discussion)
- Sequential numbers are the 6.0 default; random is opt-in (2026-08-13). Sequential, invoice-like numbers are what merchants expect from every major commerce platform. The settings UI must state plainly that sequential numbers reveal order volume to repeat customers — but the default follows merchant expectations, not the information-hiding argument.
- Only the order number is merchant-customizable (2026-08-13). One "Order numbers" settings card: prefix, suffix, format (sequential | random), and sequence starting value. All other documents keep code-level defaults; developers can swap any generator via the registry. No per-document settings grid.
- One format switch, respected by every independently numbered model
(2026-08-13). The store's
sequential/randomchoice applies to orders, returns, exchanges and claims alike; per-document prefixes remain code defaults (RET,EX,CLM). - Settings live on
Spree::Store, neverSpree::Config— per the store-scoped-configuration doctrine. "Global" means one setting for all document types, not one setting for all stores. - Fulfillment and payment numbers are derived, not stored (2026-08-13).
numberbecomes a method: historical rows return the stored column value unchanged (gateway references and packing slips already in the wild stay stable); new rows derive"#{order.number}-F#{position}"/"#{order.number}-P#{position}"from the parent order and the record's position among its siblings (ordered by id, canceled included). Generation stops entirely — no counter rows, no stored values. Accepted trade-off: a derived number shifts if an earlier sibling is hard-deleted; payments are invalidated rather than deleted and fulfillments cancel rather than delete, so in practice positions are stable. - Gateway references simplify to the derived number (2026-08-13).
GatewayOptions#order_idbecomespayment.numberalone (it already contains the order number — no more"#{order.number}-#{payment.number}"doubling). References already stored at gateways are opaque strings and stay valid. The idempotency key is the exception (revised in review, 2026-08-13):"spree-#{payment.prefixed_id}", never the number — a derived number shifts if an earlier sibling is destroyed, and a shifted idempotency key could collide with one already consumed at the gateway. Display references may shift (accepted trade-off); idempotency keys must not. - Import and Export keep their numbers (revised 2026-08-13 during
implementation, reversing the draft's "drop them"). Both mail the number to
the merchant in a subject line (
Your export EF1001 was successfully processed!), which puts them on the numbered side of the same dividing line that kept StockTransfer and PurchaseOrder: a reference handled outside the dashboard. No model now loses its number — the "back-office models drop numbers" idea did not survive contact with the code. - StockTransfer keeps its stored number; PurchaseOrder is born with one
(2026-08-13). The dividing line is not customer-facing versus staff-facing
but document handled outside the dashboard versus row in an admin
table. Purchase orders are external documents (quoted in supplier emails
and accounts payable); transfer slips travel with physical boxes and are
read by receiving staff at other warehouses and third-party logistics
locations —
6.0-inventory-operations.mdalready assumes both carry numbers. StockTransfer keeps prefixT;Spree::PurchaseOrdergetshas_spree_number prefix: 'PO'from its first migration. Both follow the store's sequential/random format switch with their own counters. - Return, Exchange and Claim keep independent stored numbers
(2026-08-13). They are customer-visible (Store API today, self-service
portal in 6.1), shown on the dashboard post-sale cards, and the preserved
numberunique index is the resume cursor forspree:upgrade:migrate_returns. - Each document type counts independently (2026-08-13): one counter row
per
(store, resource_type). Numbers stay dense within each type (R1001, R1002, …while returns sit atRET1001); a shared chronological counter would put holes in the order sequence, which merchants read as missing orders. - The default sequence starting value is 1001 (2026-08-13) —
industry-familiar, hides that a store is brand new; merchant-editable
until the first number is issued, after which the counter owns the
value. The store serializer exposes
order_number_sequence_startedand the dashboard disables the field with an explanation, because a setting that silently stops working is worse than one that says why it cannot. - The macro is
has_spree_number prefix: 'R'(2026-08-13), matching the existinghas_spree_rich_textnaming.Spree::HasNumberis included intoSpree::Base— likeSpree::PrefixedId— so no model writes its own include and nothing happens until a model calls the macro..has_spree_number?answers whether a model opted in. - Sequence state lives in a
spree_number_sequencescounter table (2026-08-13), not derived from thenumbercolumn. Deriving "next" from data is impossible: legacy random values poison anyMAXparse, text columns don't sort numerically, concurrent writers computingMAX + 1collide, and a merchant-set starting value is not derivable from rows. A counter row incremented underwith_lockis the portable equivalent of a native sequence across PostgreSQL, MySQL and SQLite. - The global unique index on
numberstays. If a sequential candidate collides (with another store's number or a legacy random one), the generator finds the first free value with batched queries and jumps the counter past the taken stretch in one move (revised in review, 2026-08-13 — advancing one retry at a time would exhaust the save's retry budget when a sibling store owns ten or more consecutive numbers, and the counter advances roll back with the failed save, leaving the store permanently stuck). Consequence: sequential numbering is mostly gapless, never guaranteed gapless — this feature must never be marketed as legal invoice numbering. - The starting value applies to orders only (revised in review, 2026-08-13): it belongs to the order-numbers settings card, so returns, transfers and the rest always count from the default. It is also locked server-side once the counter has issued a number — the API rejects a change with a validation error, matching the disabled dashboard field.
- Settings changes affect future numbers only. Existing numbers are permanent identifiers and are never regenerated or rewritten.
Spree::Core::NumberGeneratorremains as a deprecated shell for one release, translating its options into the new concern with aSpree::Deprecationwarning; removed in 6.1.
Design Details
The concern and strategy classes
class Spree::Order < Spree.base_class
has_spree_number prefix: 'R'
end
Spree::HasNumber owns the mechanics that never vary: the
before_validation assignment, the collision retry loop, and a rescue for
the unique-index race (ActiveRecord::RecordNotUnique → regenerate). The
strategy class answers only "give me a candidate string for this record":
module Spree
module NumberGenerators
class Base
# @param record [ActiveRecord::Base] the numbered record (store reachable)
# @return [String] a candidate number; uniqueness is the concern's job
def generate(record); end
end
end
end
Core ships two strategies:
Spree::NumberGenerators::Sequential— the default. Reads the store's prefix/suffix settings (orders) or the model's code-level prefix, takes the next value from the counter table, no zero-padding (R1001,R1002).Spree::NumberGenerators::Random— today's behavior: prefix + 9 random digits, zero-padded.
Generators are resolved at runtime, per record, through a registry:
Spree.number_generators.default # => 'Spree::NumberGenerators::Sequential'
Spree.number_generators[:order] = 'MyApp::OrderNumberGenerator'
Because the record is passed in, a custom generator can read the store, the market, the date — anything — with no decorator and no boot-time freezing.
Derived numbers (Fulfillment, Payment)
Fulfillment and Payment drop HasNumber entirely. number becomes a
stored-else-derived method:
# Spree::Fulfillment
def number
self[:number] || "#{order.number}-F#{position_among_siblings}"
end
position_among_siblings is 1 + the count of sibling rows with a smaller
id (canceled included), so labels are stable across status changes. New rows
never write the column. Serializers keep exposing number — the value just
changes shape for new records (R1001-F1, R1001-P2), grouping visibly
with the parent order and automatically following whatever order format the
merchant configured.
Store settings (orders only)
New Spree::Store preferences, consumed by the default generator:
| Preference | Default |
|---|---|
order_number_prefix |
R |
order_number_suffix |
'' |
document_number_format |
sequential (random opt-in) |
order_number_sequence_start |
1001, editable until the counter starts |
Prefix/suffix validation: 0–10 characters, A–Z, 0–9, -, #. The
combination of empty prefix and empty suffix is allowed (bare integers).
Dashboard: an "Order numbers" card on the store settings page with a live preview of the next number shape, and a note on the volume-disclosure trade-off next to the format switch. Exposed through the existing store settings Admin API surface; no new endpoints.
The counter table
create_table :spree_number_sequences do |t|
t.references :store, null: false
t.string :resource_type, null: false # 'order', 'return', ...
t.bigint :value, null: false, default: 0
t.timestamps
end
add_index :spree_number_sequences, [:store_id, :resource_type], unique: true
Sequential#generate finds-or-creates the row for (store, resource_type)
(seeding value from the store's configured starting value) and increments
under with_lock. Rows exist only for the independently numbered document
types (order, return, exchange, claim, stock transfer, purchase order) on
stores using sequential format; nothing else ever reads them.
Numbered models after 6.0
| Model | Number | Source |
|---|---|---|
| Order | stored, merchant-customizable | store settings + counter |
| Return / Exchange / Claim | stored | code prefixes RET/EX/CLM, store format switch + counters |
| Fulfillment | derived (R1001-F1), stored value honored on legacy rows |
parent order + position |
| Payment | derived (R1001-P1), stored value honored on legacy rows |
parent order + position |
| StockTransfer | stored | code prefix T, store format switch + counter |
PurchaseOrder (new, 6.0-inventory-operations.md) |
stored | code prefix PO, store format switch + counter |
| Import / Export | stored | code prefixes IM/EF (both mail the number) |
Uniqueness has three layers
Each catches what the one before it cannot, and the implementation needs all
three: the generator's number_taken? pre-check (cheap, advisory), the
Spree::NumberIdentifier uniqueness validation, and the database's unique
index. Only the index holds when two writers commit in the same instant, so
HasNumber overrides create_or_update to renumber once on
ActiveRecord::RecordNotUnique. That override must keep Rails' own
(**, &block) signature — an over-broad (*, **) silently drops it out of
the call chain, leaving the retry as dead code that no ordinary test notices.
Two PostgreSQL-specific rules (2026-08-13, from review): the insert must run
in a savepoint (transaction(requires_new: true)), because a constraint
violation poisons the surrounding transaction — without the savepoint the
regenerate queries die with PG::InFailedSqlTransaction instead of
recovering (SQLite hides this, which is why the local suite passed). And the
generator, not the retry loop, must skip stretches of taken numbers: counter
advances made inside a save that ultimately fails roll back with it, so
a store colliding with 10+ consecutive numbers of a sibling store would
retry the same range forever. Sequential scans forward in batches and
jumps the counter past the stretch before the save ever attempts an insert.
The registry is seeded in an engine initializer before: :load_config_initializers — like the subscriber and order-routing
registries — so host apps can register generators from
config/initializers/spree.rb. Seeding it in after_initialize makes every
documented registration crash at boot.
Migration Path
- Additive migration: create
spree_number_sequences. - New code:
Spree::HasNumber,Spree::NumberGenerators::{Base, Sequential, Random}, the registry, store preferences, dashboard card. - Model flips: Order, Return, Exchange, Claim, StockTransfer move to
has_spree_number;Spree::Core::NumberGeneratorbecomes a deprecated shell delegating to the concern.Spree::PurchaseOrderis born with the concern when6.0-inventory-operations.mdlands. - Derived numbers: Fulfillment and Payment drop generation, gain the
stored-else-derived
numbermethod;GatewayOptionsswitches topayment.number/"spree-#{payment.number}". - Callers that save with
validate: false— the sample-data import builder and the returns migrator — callgenerate_numberexplicitly, because the numbering hook isbefore_validationand those saves skip it. - Upgraded stores simply start generating sequential numbers alongside their historical random ones — no data migration, no renumbering. Collisions with legacy numbers are absorbed by the retry loop.
- 6.1: drop the deprecated
Spree::Core::NumberGeneratorshell and the now-unwritten Fulfillment and Paymentnumbercolumns. Every other numbered model keeps its column.
Constraints on Current Work
- New numbered models use
has_spree_number; never instantiateSpree::Core::NumberGeneratorin new code. - Never parse, regex-match, or assume the format of a
numbervalue — formats are now merchant-configurable. Lookups are exact-string only. Spree::PurchaseOrder(from6.0-inventory-operations.md) must be built withhas_spree_number prefix: 'PO'from the start — never a hand-rolled generator.- Code that saves a numbered record with
validate: falsemust callgenerate_numberfirst; the hook it skips is what normally assigns one. - Never write to
spree_fulfillments.numberorspree_payments.number— the columns are frozen legacy data awaiting the 6.1 drop. - New store-visible documents that need a human-readable reference get a
HasNumberinclusion and a registry entry — never a hand-rolledbefore_validationgenerator. Child documents of an order should prefer the derived pattern over a new counter.
Open Questions
None — all four draft questions (fulfillment numbering, starting value, counter granularity, payment number handling) were resolved 2026-08-13 and folded into Key Decisions above.
References
docs/plans/6.0-store-scoped-configuration.md— settings doctrinedocs/plans/6.0-returns-exchanges-claims.md—numberas migration cursordocs/plans/6.0-cart-order-split.md— order creation point (Carts::Complete)docs/plans/6.0-inventory-operations.md— StockTransfer lifecycle + PurchaseOrderspree/core/lib/spree/core/number_generator.rb— legacy implementationspree/core/app/models/spree/payment/gateway_options.rb— gateway references