Skip to content

armgit / spree

Public Imported from GitHub
0

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.

18.8 KB
Raw Blame

Drop Country/State AR Models — ISO Codes Everywhere

Status: Implemented for 6.0 — everything but the 6.1 table drop — see "Implementation status" Target: Spree 6.0 (physical table/column drop: 6.1) Depends on: 6.0-tax-provider.md Phase 5 (amended by this plan — TaxRate columns are born as ISO strings, see Key Decisions; shipped) Author: Damian + Claude Last updated: 2026-08-14

Summary

Delete the Spree::Country and Spree::State ActiveRecord models and their tables. Countries and subdivisions become gem-backed value objects served from the countries gem (ISO3166::Country), and every consumer stores plain ISO codes (country_code, state_abbr) instead of foreign keys. This matches the whole industry: none of Shopify, Medusa, Vendure, or Saleor points an address at a state row, and the two that keep a country table (Medusa, Vendure) treat it as a materialized cache of a static ISO list, not merchant data. Our own public surface is already there — the v3 API exposes no id for either model, serializes addresses as flat country_code/state_abbr/state_name strings, and the dashboard submits ISO codes only — so the change is internal to the Ruby layer apart from the field renames recorded under Naming.

Implementation status (2026-08-14)

Shipped. Spree::Country and Spree::State are plain value objects backed by the countries gem; carmen, the country/state seeds, and the row-creating fallbacks (Store#default_country_code=, Stores::Markets#create_fallback_country) are gone. Every consumer stores and matches on ISO codes: country_code / state_code columns on addresses, delivery zone members, market countries, stock locations and stores, filled by spree:upgrade:migrate_country_state_codes (in the 5.6→6.0 manifest after the delivery-zone conversion). Spree::IsoData is the curated reference registry, covered by a guard spec that replays the old Carmen seed and fails if any code it produced stops resolving. The country endpoints dropped their conditional GETs, the admin address endpoints stopped accepting raw foreign keys, and the test factories build real countries and real subdivisions. The v3 contract changed only in the field names (see Naming below); the suites pass with the renames applied.

Naming (2026-08-14, extended 2026-08-15): country_code + state_code is the one pair — column, model, and v3 API, store side included. Both halves read as one decision; the earlier country_iso/state_code split was defensible (a country code is a complete ISO 3166-1 value, a subdivision code is only the second segment) but nobody reading the API would infer it, and no other platform says country_iso — Shopify, Medusa, Vendure and Saleor all say country_code. 6.0 is the breaking window, so the rename is not hidden behind an alias: stock locations, delivery zone members, market countries, tax rates, tax lines, tax exemption certificates and every new model speak country_code/state_code only, and Market exposes country_codes. The single exception is Spree::Address, which keeps country_iso and state_abbr as deprecated alias_attributes, deprecated read attributes on the store AddressSerializer, and accepted write params — storefronts shipped against those names. 6.1 removes them.

Spree::Store collapses the odd column/virtual split at the same time: the column is default_country_code (was default_country_iso_code) and the market-aware reader carries that name, with default_country_iso_code and the virtual default_country_iso= kept as deprecated shells until 6.1. Promotion::Rules::Country renames its preferences to country_codes/country_code, and because preference keys are stored data rather than schema, reads fall back to the old country_isos/country_iso keys so rules saved earlier keep matching.

One concern, no duplication (2026-08-14): Spree::HasIsoGeography (included into Spree::Base, the has_spree_number pattern) is the single declaration for code-storing models — has_iso_geography gives upcasing normalization, ISO validation of both codes (state checked against its country, gated on change so historical rows stay updatable) and registry-backed country/state readers; state: false for country-only tables. Declared by Address, StockLocation, DeliveryZoneMember, MarketCountry, TaxRate, TaxLine and TaxExemptionCertificate. Only Spree::Address layers object writers (country=/state=) on top — everything else assigns codes; the stock-location, zone-member and market-country object writers are gone, and test factories carry country:/state: as transients mapped to codes.

What became of the tax gate. The tax-provider Phase 5 rewrite shipped on main: TaxRate matches on country_code/state_code scopes and nothing at runtime reads Spree::Zone any more. Spree::Zone/Spree::ZoneMember survive purely as migration-only shells — no polymorphic zoneable association, no matching; the 5.6→6.0 data tasks (migrate_zones_to_delivery_zones, migrate_checkout_zones, migrate_tax_zones) resolve member ids directly against the legacy spree_countries/spree_states tables via SQL. Both shells drop in 6.1 with the tables.

Key Decisions (do not deviate without discussion)

  • The countries gem is the sole data source (resolved 2026-08-07). ISO3166::Country already powers localized names, currency, and locale at runtime today; it also carries subdivisions, so it absorbs what Carmen seeded. carmen is removed from the gemspec entirely. No vendored data file — we accept the gem as a dependency we already have.
  • Spree::Country and Spree::State keep their constant names but become plain Ruby value objects (ActiveModel::Model + ActiveModel::Attributes, same pattern as Spree::PickupPointOption). Spree::Country.by_iso('US'), #name, #states, #states_required?, #zipcode_required?, #localized_name, #default_currency all survive with the same signatures. ActiveRecord calls (.where, .find, associations) fail loudly with NoMethodError — acceptable in the 6.0 breaking window, and better than silently different query semantics.
  • Address validation semantics are preserved exactly (resolved 2026-08-07). For STATES_REQUIRED countries the submitted state_abbr must match a gem subdivision code, and a state_name matching a subdivision name is still promoted to its code; for every other country state_name stays free text. The STATES_REQUIRED and NO_ZIPCODE_ISO_CODES constants on Spree::Address — already the seed-time source of truth — become the runtime source of truth. A Google-address-ruleset upgrade (Saleor's i18naddress approach) is explicitly out of scope; the validation seam is designed so it can slot in later.
  • Tables drop in 6.1, not 6.0 (resolved 2026-08-07, revised 2026-08-13). Code switches to ISO strings in 6.0, but spree_countries/spree_states and every country_id/state_id column survive the release: spree:upgrade:migrate_country_state_codes reads them to fill the ISO columns, so dropping them in the same release would leave the upgrade task nothing to read on exactly the installs that need it. Same pattern as the returns-chain tables. See the Migration Path for the authoritative sequencing.
  • 6.0-tax-provider.md Phase 5 is amended before it ships (resolved 2026-08-07). spree_tax_rates (and later TaxExemptionCertificate) get country_code/state_abbr string columns, never country_id/state_id FKs. Verified 2026-08-07 that the FK columns do not exist yet — amending now converts a double migration into a saving. The "state-level rate overrides country-level" precedence rule carries over to string matching unchanged.
  • Subdivision codes are only meaningful with their country. Every table storing a state_abbr also stores the country_code (spree_addresses, spree_delivery_zone_members, spree_stock_locations, tax rates). Abbreviations are not globally unique (CA is California and several other things); the pair is the identifier. This also fixes the existing bug where the admin delivery-zones controller resolved a bare abbr against Spree::State globally.
  • The v3 API contract does not change. Country/State are already the only v3 resources addressed by natural key with no prefixed ID; serializers keep emitting iso/iso3/name/states_required/zipcode_required and abbr/name. Controllers keep the same routes, params, and caching; only their backing store changes. One accepted value drift: name now comes from the gem's CLDR data instead of the Carmen-seeded column, so a few country names may read slightly differently. The dashboard already prefers the browser's Intl.DisplayNames over the API name, so admin UI display is unaffected.
  • The two admin endpoints that still accept raw country_id/state_id params drop them (admin customer addresses, admin order addresses). They were the only place integer FKs crossed the wire; every other endpoint is already ISO-only.
  • The two ISO→record resolution paths are unified first. Today Spree::Addresses::Helper silently nils an unrecognized ISO while the Address model callbacks no-op; after this plan there is one normalization path on the model, and an unrecognized code is a validation error, never silent data loss.

Design Details

The value objects

# Same constants, no longer ActiveRecord
class Spree::Country
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :iso, :string        # 'US' — the identifier
  attribute :iso3, :string
  attribute :numcode, :integer

  def self.all                # memoized list from ISO3166::Country.all, minus EXCLUDED_COUNTRIES
  def self.by_iso(code)       # matches iso OR iso3, case-insensitive (same as today); nil on miss
  def self.find_by_iso!(code) # raising variant for controllers (404 path)

  def name                    # ISO3166 CLDR translation for the current locale
  def states                  # ISO3166::Country[iso].subdivisions → [Spree::State]
  def states_required?        # Spree::Address::STATES_REQUIRED.include?(iso)
  def zipcode_required?       # !Spree::Address::NO_ZIPCODE_ISO_CODES.include?(iso)
  def default_currency / default_locale / localized_name(locale:)  # unchanged, already gem-backed
end

class Spree::State
  attribute :abbr, :string         # subdivision code without country prefix ('CA', not 'US-CA')
  attribute :name, :string
  attribute :country_code, :string  # always present — abbr alone is ambiguous
end

The country list is process-memoized and immutable. EXCLUDED_COUNTRIES (the nine territories the seeds skip today) moves from Spree::Seeds::Countries onto the registry. Sorting where the DB did order(:name) becomes an in-Ruby sort on localized names — fine at ~250 entries, and now correctly locale-aware where the DB sort never was.

Column conversions

Table Today After
spree_addresses country_id (FK, required), state_id (FK, optional), state_name country_code (null: false), state_code, state_name (unchanged)
spree_delivery_zone_members country_id, state_id country_code, state_code — state members now carry both
spree_market_countries country_id country_code; uniqueness (market_id, country_code)
spree_stock_locations country_id, state_id country_code, state_code
spree_stores default_country_id default_country_code
spree_states country_id table dropped
spree_tax_rates (unshipped) — (plan specced FKs) born as country_code, state_code

ISO codes are stored upcased 2-letter; state_code upcased without the country prefix (matches today's seeded values, the API contract, and what the dashboard submits).

Address

The model keeps its public shape: country_code/state_code stop being buffered virtual writers resolved through before_validation lookups and become the actual columns. country_name, country_iso3, state_text, state_name_text, require_zipcode?, gateway_hash all read through the value objects. state_validate keeps its exact decision tree, backed by country.states from the gem instead of country.states from the DB. Spree::Addresses::Helper's duplicate resolution logic is deleted; Addresses::Create/Update pass the ISO params straight to the model.

Ransack: whitelisted_ransackable_associations drops country/state; country_code and state_code join the ransackable attributes so existing admin filtering keeps working as plain string predicates.

Consumers, converted

  • DeliveryZoneMember#match? — string comparison instead of FK integers: address.country_code == country_code, and for state members country_code + state_code both. range_capable_country_codes is already an ISO allowlist. The admin controller's ISO→FK conversion layer is deleted.
  • Store#countries_with_shipping_coverage — the state→country SQL hop disappears because state members now carry their own country_code: the query becomes a union of member country_code values, hydrated through the registry and sorted by localized name.
  • Market / MarketCountry — country_codes (already the API façade) becomes the storage reality. for_country takes an ISO, default_country picks first by localized name, both cross-market validations (country_unique_per_store, country_covered_by_shipping_zone) become string queries.
  • Store#default_country returns a value object; default_country_code= stops creating rows (it can't — there are no rows), as does the market-bootstrap create_fallback_country. Fallback is simply Spree::Country.by_iso('US'), which always exists.
  • StockLocation — same conversion as Address; its ISO writers already exist.
  • Carts::Update#clear_shipping_address_if_outside_market — compares country_code strings instead of country_ids.
  • Promotion::Rules::Country — already ISO-native; only its display-hydration helper switches to the registry. This class was the template for the whole refactor.
  • Zone / ZoneMember — not converted. They are removed by 6.0-delivery-zones.md Phase D before this plan's final phase; the polymorphic member design never gets a string rewrite.

Seeds, factories, test support

Spree::Seeds::Countries and Spree::Seeds::States are deleted (nothing to seed). The country/state factories are deleted; factories that built them (address, delivery_zone, market, stock_location, zone, cart, order_walkthrough) switch to literal ISO strings — which also kills a long-standing factory smell (every factory country claimed numcode: 840, and the state factory could grab any of them). testing_support/store.rb drops the suite-wide @default_country record.

Migration Path

Sequenced inside 6.0, after 6.0-fulfillment-and-delivery.md's shipped surface and interleaved with the tax/zone work:

  1. ✅ Docs first: amend 6.0-tax-provider.md Phase 5 to string columns, record the decision in decisions.md, superseding notes in 6.0-delivery-zones.md and 6.0-admin-api.md.
  2. ✅ Safe pre-work (independent of everything): close the admin country_id/state_id param leak; unify the two ISO resolution paths onto the Address model.
  3. ✅ The registry: Spree::IsoData plus the guard spec that replays the old seed, and the ISO3166 locale configuration (in after_initialize, not an initializer — Spree.available_locales is not populated that early).
  4. ✅ String columns + backfill: the new *_iso/*_abbr columns; spree:upgrade:migrate_country_state_codes in the 5.6→6.0 manifest, resumable via where(country_code: nil); every reader and validation converted.
  5. ✅ Test data: factories build real countries and real subdivisions, with postal codes their country accepts.
  6. ⏸ Registry swap — blocked on Spree::Zone: replace the AR models with the value objects and delete the seeds, the carmen dependency and the row-creating fallbacks. Needs 6.0-tax-provider.md Phase 5 and then 6.0-delivery-zones.md Phase D.
  7. ⏸ Drop — deferred to 6.1 (2026-08-13): spree_countries, spree_states, and every legacy country_id/state_id/default_country_id column. The tables survive 6.0 as the upgrade task's source data — spree:upgrade:migrate_country_state_codes reads them to fill the ISO columns, and dropping them in the same release would leave the task nothing to read on exactly the installs that need it. Same pattern as the returns-chain tables. Nothing writes them in 6.0; spree_market_countries.country_id is relaxed to nullable since rows are created without it.

Tax Phase 5 slots in wherever it lands on its own schedule — with the amendment it creates string columns directly and needs nothing from steps 3–5. It is, however, what unblocks steps 6 and 7.

Constraints on Current Work

  • No new country_id/state_id FK columns or belongs_to :country/:state associations anywhere. New features store country_code (+ state_code where subdivisions matter, always as a pair) — the Promotion::Rules::Country / DeliveryZoneMember.range_capable_country_codes pattern.
  • Tax-provider Phase 5 implements the amended spec (string columns) — the FK version in older revisions of that plan is superseded.
  • Don't build anything on Country/State being queryable ActiveRecord — no new Ransack predicates through the country/state associations, no new joins to spree_countries/spree_states, no code that creates Country rows.
  • Address-adjacent code reads geography through the model's ISO accessors (country_code, state_code, state_text), never through address.country.id or the state association.

Open Questions

  • Per-country address form rules (Google ruleset / i18naddress) — deliberately deferred. The validation seam (country.states_required? + subdivision list) is where it would plug in; unblocked by real demand for per-country field ordering/labels ("prefecture" vs "state") beyond what STATES_REQUIRED covers.
  • Bundling a static country list in the dashboard instead of the API fetch — deferred; the API contract is unchanged so nothing forces it. Revisit only if the extra request at dashboard boot ever matters.

References

  • docs/plans/decisions.md 2026-08-07 entry (this decision)
  • docs/plans/6.0-tax-provider.md — Phase 5 (amended to string columns)
  • docs/plans/6.0-delivery-zones.md — Phase D is the sequencing gate; member FKs converted here
  • docs/plans/6.0-admin-api.md — countries endpoints (contract unchanged)
  • Competitor survey (2026-08-07): Shopify MailingAddress (countryCodeV2 enum + province strings), Medusa v2 region_country (static 251-entry list upserted at boot, PK iso_2, free-string province), Vendure Country/Province extends Region (Province unseeded and never referenced by Address — province is a string column), Saleor django-countries + i18naddress (no tables at all)