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
Speed-up seed/sample States creation + eliminate duplicates when re-run
Damian Legawiec3681aac3c836
diff --git a/spree/core/app/services/spree/seeds/allowed_origins.rb b/spree/core/app/services/spree/seeds/allowed_origins.rbindex baae605cef..d9b7b60ee9 100644--- a/spree/core/app/services/spree/seeds/allowed_origins.rb+++ b/spree/core/app/services/spree/seeds/allowed_origins.rb@@ -4,10 +4,9 @@ module Spreeprepend Spree::ServiceModule::Basedef call- store = Spree::Store.default- return unless store&.persisted?-- store.allowed_origins.find_or_create_by!(origin: 'http://localhost')+ Spree::Store.all.each do |store|+ store.allowed_origins.find_or_create_by!(origin: 'http://localhost')+ endendendenddiff --git a/spree/core/app/services/spree/seeds/states.rb b/spree/core/app/services/spree/seeds/states.rbindex 4ebc00d473..3db19d5d3b 100644--- a/spree/core/app/services/spree/seeds/states.rb+++ b/spree/core/app/services/spree/seeds/states.rb@@ -10,14 +10,18 @@ module Spreedef callSpree::Country.where(states_required: true).each do |country|- carmen_country = Carmen::Country.named(country.name)+ # Match on ISO code, not name: Spree stores official ISO-3166 names+ # ("United States of America") while Carmen uses common ones+ # ("United States"), and `named` is an exact match — so a name lookup+ # silently skipped the US, leaving it with no states at all.+ carmen_country = Carmen::Country.coded(country.iso) || Carmen::Country.named(country.name)next unless carmen_country- carmen_country.subregions.each do |subregion|+ states = carmen_country.subregions.flat_map do |subregion|if carmen_country.alpha_2_code == 'US'# Produces 50 states, one postal district (Washington DC)# and 3 APO's as you would expect to see on any good U.S. states list.- next if EXCLUDED_US_STATES.include?(subregion.code)+ next [] if EXCLUDED_US_STATES.include?(subregion.code)state_level(country, subregion)elsif carmen_country.alpha_2_code == 'CA' || carmen_country.alpha_2_code == 'MX'@@ -27,7 +31,7 @@ module Spreeelsif carmen_country.alpha_2_code == 'CN'# Removes 3 "States" from that list that are also listed as Countries,# Hong Kong, Taiwan and Macao- next if EXCLUDED_CN_STATES.include?(subregion.code)+ next [] if EXCLUDED_CN_STATES.include?(subregion.code)state_level(country, subregion)elsif subregion.subregions?@@ -36,27 +40,42 @@ module Spreestate_level(country, subregion)endend++ # One upsert per country rather than one per subregion.+ upsert_states(states)endendprotecteddef state_level(country, subregion)- country.states.where(- name: subregion.name,- abbr: subregion.code- ).first_or_create!+ [{ name: subregion.name, abbr: subregion.code, country_id: country.id }]enddef province_level(country, subregion)- new_states = subregion.subregions.map do |province|- Hash[- name: province.name,- abbr: province.code,- country_id: country.id- ]- end.compact.uniq- Spree::State.insert_all(new_states)+ subregion.subregions.map do |province|+ { name: province.name, abbr: province.code, country_id: country.id }+ end+ end++ # Seeds are re-run on every deploy, so this has to converge rather than+ # duplicate: `[country_id, abbr]` is unique, and a name change upstream+ # updates the existing row instead of adding a second one.+ def upsert_states(states)+ states = states.uniq { |state| [state[:country_id], state[:abbr]] }.reject { |state| state[:abbr].blank? }+ return if states.empty?++ now = Time.current+ opts = { update_only: %i[name] }+ # MySQL infers the conflict target from the table's unique constraints+ # and rejects an explicit +unique_by+; PostgreSQL/SQLite require it.+ opts[:unique_by] = %i[country_id abbr] unless mysql_adapter?++ Spree::State.upsert_all(states.map { |state| state.merge(created_at: now, updated_at: now) }, **opts)+ end++ def mysql_adapter?+ ActiveRecord::Base.connection.adapter_name.downcase.include?('mysql')endendenddiff --git a/spree/core/db/migrate/20260727000001_add_unique_country_abbr_index_to_spree_states.rb b/spree/core/db/migrate/20260727000001_add_unique_country_abbr_index_to_spree_states.rbnew file mode 100644index 0000000000..ed910d51f8--- /dev/null+++ b/spree/core/db/migrate/20260727000001_add_unique_country_abbr_index_to_spree_states.rb@@ -0,0 +1,30 @@+class AddUniqueCountryAbbrIndexToSpreeStates < ActiveRecord::Migration[7.2]+ def up+ remove_duplicate_states!++ add_index :spree_states, [:country_id, :abbr],+ unique: true,+ name: 'index_spree_states_on_country_id_and_abbr'+ end++ def down+ remove_index :spree_states, name: 'index_spree_states_on_country_id_and_abbr'+ end++ private++ # `Spree::Seeds::States` used a plain `insert_all` for province-level+ # countries, so re-running the seeds duplicated their states. Keep the oldest+ # row of each group — addresses point at it — and drop the rest.+ def remove_duplicate_states!+ duplicated = Spree::State.group(:country_id, :abbr).having('COUNT(*) > 1').pluck(:country_id, :abbr)++ duplicated.each do |country_id, abbr|+ ids = Spree::State.where(country_id: country_id, abbr: abbr).order(:id).pluck(:id)+ keeper = ids.shift++ Spree::Address.where(state_id: ids).update_all(state_id: keeper) if ids.any?+ Spree::State.where(id: ids).delete_all+ end+ end+enddiff --git a/spree/core/spec/services/spree/seeds/states_spec.rb b/spree/core/spec/services/spree/seeds/states_spec.rbnew file mode 100644index 0000000000..2ae912d9a3--- /dev/null+++ b/spree/core/spec/services/spree/seeds/states_spec.rb@@ -0,0 +1,47 @@+require 'spec_helper'++RSpec.describe Spree::Seeds::States do+ before { Spree::Seeds::Countries.call }++ subject(:seed) { described_class.call }++ # Regression: countries were matched against Carmen by name, but Spree stores+ # the official ISO-3166 name ("United States of America") where Carmen uses+ # the common one ("United States"). The lookup missed, the `next unless`+ # skipped it silently, and the US ended up with zero states — which in turn+ # made every US address invalid ("State can't be blank").+ it 'seeds states for the US' do+ seed++ us = Spree::Country.find_by(iso: 'US')+ expect(us.states.count).to be > 50+ expect(us.states.find_by(abbr: 'IL')&.name).to eq('Illinois')+ end++ it 'seeds states for the other countries that require them' do+ seed++ %w[CA AU].each do |iso|+ expect(Spree::Country.find_by(iso: iso).states).to be_any, "expected states for #{iso}"+ end+ end++ # Seeds re-run on every deploy. The province-level branch used a bare+ # `insert_all`, so each run duplicated those countries' states.+ it 'is idempotent' do+ seed++ expect { described_class.call }.not_to change(Spree::State, :count)+ expect(Spree::State.group(:country_id, :abbr).having('COUNT(*) > 1').count).to be_empty+ end++ it 'refreshes a renamed state in place' do+ seed++ illinois = Spree::Country.find_by(iso: 'US').states.find_by(abbr: 'IL')+ illinois.update!(name: 'Stale Name')++ expect { described_class.call }.not_to change(Spree::State, :count)+ expect(illinois.reload.name).to eq('Illinois')+ end+end