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
Retire zone price rules onto markets and shell the Zone model
Damian Legawiecc01bbd4fdf06
diff --git a/docs/plans/6.0-delivery-zones.md b/docs/plans/6.0-delivery-zones.mdindex 1459dbebbd..dff73935fe 100644--- a/docs/plans/6.0-delivery-zones.md+++ b/docs/plans/6.0-delivery-zones.md@@ -32,10 +32,10 @@ Two more surfaced when tax let go of Zone (2026-08-07), both needing a decisionThe `Pricing::Context` zone dimension went with them rather than waiting for this plan: `Context.from_order` read `order.tax_zone`, so it could not outlive that method's removal. Two consequences land in this plan's lap:-- **`Spree::Current.tax_country` returns a `Spree::Country`, not the ISO string** the constraint above originally specified (now corrected there). It matches the already-shipped `Purchase::Taxation#tax_country`, and `PriceRules::ZoneRule` compares stored ids.-- **`PriceRules::ZoneRule` now decides by country**, keeping its class name (persisted in `type`) and staying out of the rule registry, with `spree:migrate_tax_zones` restating each row's stored zones as the countries they contained. State-level zones widen to their whole country, which the task reports. Whether this becomes a first-class `CountryRule` in the picker is **this plan's** decision — the tax work deliberately stopped at not-crashing.+- **`Spree::Current.tax_country` returns a `Spree::Country`, not the ISO string** the constraint above originally specified (now corrected there). It matches the already-shipped `Purchase::Taxation#tax_country`.+- **`PriceRules::ZoneRule` is retired (2026-08-14, decisions.md).** `spree:migrate_tax_zones` converts each rule to a `MarketRule` where the zone's countries exactly match a store market, and otherwise deactivates the price list with a per-list report — no replacement geography class; MarketRule is it. ZoneRule survives only as a bare STI shell for pre-task rows, deleted in 6.1 with the other shells below.-Phase D — dropping `spree_zones`/`spree_zone_members`, the `Zone`/`ZoneMember` models and `Country#zones`/`State#zones` — is now unblocked on the tax side.+**Phase D is mostly done (2026-08-14, decisions.md):** `Zone`/`ZoneMember` are migration-only shells (bare AR + `country_list`), and `Country#zones`/`State#zones`, `Store#checkout_zone`, `Seeds::Zones` and the permission-catalog entries are deleted. Left for 6.1: drop the shells and the `spree_zones`/`spree_zone_members` tables — which first means switching the readers in `migrate_tax_zones`, `migrate_zones_to_delivery_zones` and `backfill_order_markets` to anonymous AR classes (the `ReturnsMigrator` precedent: migrations must outlive the models they read).## Key Decisions (do not deviate without discussion)diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex d86f61d49f..97aba7564f 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,34 @@+## 2026-08-14: ZoneRule retired by migration; Zone shelled to a migration-only reader++Two amendments to the 2026-08-12 jurisdiction-as-codes entry, both Damian's+call, finishing what "kept because it is persisted in the type column" left+hanging.++**`PriceRules::ZoneRule` is retired — onto MarketRule, with no replacement+class.** Markets are how pricing targets geography, so `spree:migrate_tax_zones`+converts each zone rule to a `MarketRule` where the zone's countries exactly+match one of the store's markets — the one mapping that provably keeps the+same buyers on the same prices. Where no market matches, the restriction is+unrepresentable: the price list is **deactivated**, the rule row removed, and+the task reports each list with the ISO codes it named so the merchant can+create the market and rebuild. Deactivating errs on buyers briefly losing a+discount over a restricted list quietly widening to everyone. A CountryRule+carrier class was written and then rejected the same day — it preserved data+at the cost of a second, half-alive geography concept beside markets.+ZoneRule survives as a bare STI shell (rows keep the old type until the task+runs; a 6.0 deployment boots before its upgrade tasks do), deleted in 6.1.++**`Spree::Zone` and `ZoneMember` are shells.** Bare ActiveRecord — the+associations plus a `country_list` — kept solely so the 5.6→6.0 upgrade tasks+(`migrate_tax_zones`, `migrate_zones_to_delivery_zones`,+`backfill_order_markets`) can read the rows they convert. Everything else+went: the matching/inclusion logic, seeds (`Seeds::Zones` and its EU_VAT+groupings — the markets sample data now names its ISO lists directly), the+permission-catalog entries, Country/State's zone associations, and Store's+`checkout_zone` bridge (deprecated since 5.4 with a 5.5 deadline, two+releases overdue). `6.0-delivery-zones.md` still owns dropping the classes+and tables in 6.1; what remains for it is deletion, not untangling.+## 2026-08-13: Document numbers — sequential by default, store-configurable orders, derived child numbers`Spree::Core::NumberGenerator` (the boot-frozen `Module` factory) is replaceddiff --git a/spree/core/app/models/spree/country.rb b/spree/core/app/models/spree/country.rbindex dd782ea998..9493980f5f 100644--- a/spree/core/app/models/spree/country.rb+++ b/spree/core/app/models/spree/country.rb@@ -7,12 +7,6 @@ module Spree-> { order name: :asc },inverse_of: :country,dependent: :destroy- has_many :zone_members,- -> { where(zoneable_type: 'Spree::Country') },- class_name: 'Spree::ZoneMember',- dependent: :destroy,- foreign_key: :zoneable_id- has_many :zones, through: :zone_members, class_name: 'Spree::Zone'has_many :market_countries, class_name: 'Spree::MarketCountry', dependent: :destroyhas_many :markets, through: :market_countries, class_name: 'Spree::Market'diff --git a/spree/core/app/models/spree/price_rules/zone_rule.rb b/spree/core/app/models/spree/price_rules/zone_rule.rbindex a0dc9cacf5..aec0eff8ad 100644--- a/spree/core/app/models/spree/price_rules/zone_rule.rb+++ b/spree/core/app/models/spree/price_rules/zone_rule.rb@@ -1,48 +1,11 @@module Spreemodule PriceRules- # Restricts a price list by where the buyer is. Named for the zones it read- # before 6.0: tax and pricing no longer speak in zones, so eligibility is- # decided by country and `spree:migrate_tax_zones` restates each row's- # stored zones as the countries they contained. The class name stays because- # it is persisted in the +type+ column.- #- # Kept out of the default registry, so it never appears under "Add rule" —- # MarketRule covers geography for new price lists. Whether this becomes a- # first-class country rule belongs to docs/plans/6.0-delivery-zones.md,- # which owns the removal of Zone itself.+ # Deprecated STI shell, removed in Spree 6.1. Exists only so price-rule+ # rows created before `spree:migrate_tax_zones` runs still load — the task+ # converts each row to a {MarketRule} where the zone's countries match a+ # market exactly, and otherwise deactivates the price list and removes the+ # row, reporting what it named. Never create rows with this class.class ZoneRule < Spree::PriceRule- # Held as ISO codes rather than country rows: Spree::Country is on its way- # out, and "DE" is what a merchant means. Comma-separated input is split- # and everything upcased, so a rule entered in lowercase still matches.- #- # Unlike MarketRule, an unknown code is not rejected — there is no country- # table to check it against, and an unmatched code narrows the price list- # to nothing rather than widening it.- preference :country_isos, :array, default: [],- parse_on_set: lambda { |values, _owner = nil|- Array(values).- flat_map { |value| value.to_s.split(',') }.- compact_blank.- map { |iso| iso.strip.upcase }.- uniq- }-- def applicable?(context)- return false if context.country_iso.blank?- return true if preferred_country_isos.empty?-- preferred_country_isos.include?(context.country_iso.to_s.upcase)- end-- # An empty country list matches every buyer (see #applicable?), so it names- # no geography.- def geographic?- preferred_country_isos.present?- end-- def self.description- 'Apply pricing based on the destination country'- endendendenddiff --git a/spree/core/app/models/spree/state.rb b/spree/core/app/models/spree/state.rbindex 979645fbfd..ba27ef2caf 100644--- a/spree/core/app/models/spree/state.rb+++ b/spree/core/app/models/spree/state.rb@@ -3,14 +3,6 @@ module Spreebelongs_to :country, class_name: 'Spree::Country'has_many :addresses, dependent: :restrict_with_error- has_many :zone_members,- -> { where(zoneable_type: 'Spree::State') },- class_name: 'Spree::ZoneMember',- dependent: :destroy,- foreign_key: :zoneable_id-- has_many :zones, through: :zone_members, class_name: 'Spree::Zone'-validates :country, :name, presence: truevalidates :name, :abbr, uniqueness: { case_sensitive: false, scope: :country_id }, allow_blank: truediff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex e5624713ea..929cd99a3a 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -179,7 +179,6 @@ module Spreehas_many :data_feeds, class_name: 'Spree::DataFeed'belongs_to :default_country, class_name: 'Spree::Country'- belongs_to :checkout_zone, class_name: 'Spree::Zone'has_many :reports, class_name: 'Spree::Report'has_many :exports, class_name: 'Spree::Export'@@ -296,18 +295,6 @@ module Spreechannels.default.first || channels.active.firstend- # @deprecated Use Markets instead. Will be removed in Spree 5.5.- def checkout_zone- Spree::Deprecation.warn('Store#checkout_zone is deprecated and will be removed in Spree 5.5. Use Markets instead.')- super- end-- # @deprecated Use Markets instead. Will be removed in Spree 5.5.- def checkout_zone=(zone)- Spree::Deprecation.warn('Store#checkout_zone= is deprecated and will be removed in Spree 5.5. Use Markets instead.')- super- end-# Virtual attribute — sets the country for the default market created on store creation.# Not persisted on the store itself; only used by the after_create callback.attr_reader :default_country_isodiff --git a/spree/core/app/models/spree/zone.rb b/spree/core/app/models/spree/zone.rbindex 29fb658e45..1fcfa33f90 100644--- a/spree/core/app/models/spree/zone.rb+++ b/spree/core/app/models/spree/zone.rb@@ -1,204 +1,29 @@module Spree+ # Migration-only shell, removed in Spree 6.1 together with its tables.+ # Delivery coverage lives on {Spree::DeliveryZone}, tax rates carry their own+ # country and state codes, and zone-scoped price rules were converted to+ # market rules (or their lists deactivated) — nothing at runtime reads a+ # zone. The+ # class survives only so the 5.6→6.0 upgrade tasks+ # (`spree:migrate_tax_zones`, `spree:migrate_zones_to_delivery_zones`,+ # `spree:backfill_order_markets`) can still read the rows they convert.class Zone < Spree.base_class- has_prefix_id :zone-- include Spree::UniqueName-- # Tax rates named their zone until 6.0; they carry their own country and- # state now, so a zone owns nothing tax-side.has_many :zone_members, class_name: 'Spree::ZoneMember', dependent: :destroy, inverse_of: :zone- with_options through: :zone_members, source: :zoneable do- has_many :countries, source_type: 'Spree::Country'- has_many :states, source_type: 'Spree::State'- end-- scope :with_default_tax, -> { where(default_tax: true) }-- after_save :remove_defunct_members- after_save :remove_previous_default, if: %i[default_tax? saved_change_to_default_tax?]-alias members zone_members- accepts_nested_attributes_for :zone_members, allow_destroy: true, reject_if: proc { |a| a['zoneable_id'].blank? }-- self.whitelisted_ransackable_attributes = ['description']-- def self.potential_matching_zones(zone)- if zone.country?- # Match zones of the same kind with similar countries- joins(countries: :zones).- where('zone_members_spree_countries_join.zone_id = ?', zone.id).- distinct- else- # Match zones of the same kind with similar states in AND match zones- # that have the states countries in- joins(:zone_members).where(- "(spree_zone_members.zoneable_type = 'Spree::State' AND- spree_zone_members.zoneable_id IN (?))- OR (spree_zone_members.zoneable_type = 'Spree::Country' AND- spree_zone_members.zoneable_id IN (?))",- zone.state_ids,- zone.states.pluck(:country_id)- ).distinct- end- end-- # Returns the matching zone with the highest priority zone type (State, Country, Zone.)- # Returns nil in the case of no matches.- # Accepts either an address (with country_id/state_id) or a Spree::Country directly.- def self.match(address_or_country)- return unless address_or_country-- if address_or_country.is_a?(Spree::Country)- country_id = address_or_country.id- state_id = nil- else- country_id = address_or_country.country_id- state_id = address_or_country.state_id- end-- matches = includes(:zone_members).- order('spree_zones.zone_members_count', 'spree_zones.created_at').- where("(spree_zone_members.zoneable_type = 'Spree::Country' AND " \- 'spree_zone_members.zoneable_id = ?) OR ' \- "(spree_zone_members.zoneable_type = 'Spree::State' AND " \- 'spree_zone_members.zoneable_id = ?)', country_id, state_id).- references(:zones)-- return if matches.empty?- %w[state country].each do |zone_kind|- if match = matches.detect { |zone| zone_kind == zone.kind }- return match- end- end- matches.first- end-- def kind- if self[:kind].present?- self[:kind]- else- not_nil_scope = members.where.not(zoneable_type: nil)- zone_type = not_nil_scope.order('created_at ASC').pluck(:zoneable_type).last- zone_type&.demodulize&.underscore- end- end-- def country?- kind == 'country'- end-- def state?- kind == 'state'- end-- def include?(address)- return false unless address-- members.any? do |zone_member|- case zone_member.zoneable_type- when 'Spree::Country'- zone_member.zoneable_id == address.country_id- when 'Spree::State'- zone_member.zoneable_id == address.state_id- end- end- end-- # convenience method for returning the countries contained within a zone+ # The countries the zone contained — directly, or through its states for a+ # state-kind zone. Resolved through the live tables so a member pointing at+ # a deleted country or state drops out.def country_list- @countries ||= case kind- when 'country' then- Country.where(id: country_ids)- when 'state' then- Country.where(id: zoneables.collect(&:country_id))- end- end-- def <=>(other)- name <=> other.name+ Spree::Country.where(+ id: zone_members.where(zoneable_type: 'Spree::Country').select(:zoneable_id)+ ).or(+ Spree::Country.where(+ id: Spree::State.where(+ id: zone_members.where(zoneable_type: 'Spree::State').select(:zoneable_id)+ ).select(:country_id)+ )+ )end-- # All zoneables belonging to the zone members. Will be a collection of either- # countries or states depending on the zone type.- def zoneables- members.includes(:zoneable).collect(&:zoneable)- end-- def country_ids- if country?- members.pluck(:zoneable_id)- else- []- end- end-- def state_ids- if state?- members.pluck(:zoneable_id)- else- []- end- end-- def country_ids=(ids)- set_zone_members(ids, 'Spree::Country')- end-- def state_ids=(ids)- set_zone_members(ids, 'Spree::State')- end-- # Indicates whether the specified zone falls entirely within the zone performing- # the check.- def contains?(target)- return false if state? && target.country?- return false if zone_members.empty? || target.zone_members.empty?-- if kind == target.kind- if state?- return false if (target.states.pluck(:id) - states.pluck(:id)).present?- elsif country?- return false if (target.countries.pluck(:id) - countries.pluck(:id)).present?- end- else- return false if (target.states.pluck(:country_id) - countries.pluck(:id)).present?- end- true- end-- def state_list- case kind- when 'country'- zoneables.map(&:states)- when 'state'- zoneables- end.flatten.compact.uniq- end-- def state_list_for(country)- state_list.select { |state| state.country == country }- end-- private-- def remove_defunct_members- zone_members.defunct_without_kind(kind).destroy_all if zone_members.any?- end-- def remove_previous_default- Spree::Zone.with_default_tax.where.not(id: id).update_all(default_tax: false)- end-- def set_zone_members(ids, type)- zone_members.destroy_all- ids.reject(&:blank?).map do |id|- member = ZoneMember.new- member.zoneable_type = type- member.zoneable_id = id- members << member- end- end-endenddiff --git a/spree/core/app/models/spree/zone_member.rb b/spree/core/app/models/spree/zone_member.rbindex 34d7a12311..1122b4bc66 100644--- a/spree/core/app/models/spree/zone_member.rb+++ b/spree/core/app/models/spree/zone_member.rb@@ -1,13 +1,9 @@module Spree+ # Migration-only shell, removed in Spree 6.1 with {Spree::Zone}.class ZoneMember < Spree.base_class- belongs_to :zone, class_name: 'Spree::Zone', counter_cache: true, inverse_of: :zone_members+ belongs_to :zone, class_name: 'Spree::Zone', inverse_of: :zone_membersbelongs_to :zoneable, polymorphic: truevalidates :zone, :zoneable, presence: true- validates :zoneable_id, uniqueness: { scope: spree_base_uniqueness_scope + [:zone_id, :zoneable_type] }-- scope :defunct_without_kind, ->(kind) do- where('zoneable_id IS NULL OR zoneable_type != ?', "Spree::#{kind.classify}")- endendenddiff --git a/spree/core/app/services/spree/seeds/all.rb b/spree/core/app/services/spree/seeds/all.rbindex d80fa94f4a..0a60c603d9 100644--- a/spree/core/app/services/spree/seeds/all.rb+++ b/spree/core/app/services/spree/seeds/all.rb@@ -9,7 +9,6 @@ module Spree# GEOCountries.callStates.call- Zones.call# user rolesRoles.calldiff --git a/spree/core/app/services/spree/seeds/zones.rb b/spree/core/app/services/spree/seeds/zones.rbdeleted file mode 100644index d98fe4d0cc..0000000000--- a/spree/core/app/services/spree/seeds/zones.rb+++ /dev/null@@ -1,52 +0,0 @@-module Spree- module Seeds- class Zones- prepend Spree::ServiceModule::Base-- def call- eu_vat = Spree::Zone.where(name: 'EU_VAT', description: 'Countries that make up the EU VAT zone.', kind: 'country').first_or_create!- uk_vat = Spree::Zone.where(name: 'UK_VAT', kind: 'country').first_or_create!- north_america = Spree::Zone.where(name: 'North America', description: 'USA + Canada', kind: 'country').first_or_create!- central_america_and_caribbean = Spree::Zone.where(name: 'Central America and Caribbean', description: 'Central America and Caribbean', kind: 'country').first_or_create!- south_america = Spree::Zone.where(name: 'South America', description: 'South America', kind: 'country').first_or_create!- middle_east = Spree::Zone.where(name: 'Middle East', description: 'Middle East', kind: 'country').first_or_create!- africa = Spree::Zone.where(name: 'Africa', description: 'Africa', kind: 'country').first_or_create!- asia = Spree::Zone.where(name: 'Asia', description: 'Asia', kind: 'country').first_or_create!- australia_and_oceania = Spree::Zone.where(name: 'Australia and Oceania', description: 'Australia and Oceania', kind: 'country').first_or_create!-- create_zone_members(eu_vat, %w(PL FI PT RO DE FR SK HU SI IE AT ES IT BE SE LV BG LT CY LU MT DK NL EE HR CZ GR))- create_zone_members(north_america, %w(US CA))- create_zone_members(central_america_and_caribbean, %w(MX GT BZ SV HN NI CR PA CU DO HT JM BS BB TT PR AG DM GD KN LC VC AI AW BM KY CW GP MQ MS BL MF SX TC VG VI))- create_zone_members(south_america, %w(AR BO BR CL CO EC FK GF GY PY PE SR UY VE))- create_zone_members(middle_east, %w(BH CY EG IR IQ IL JO KW LB OM QA SA SY TR AE YE))- create_zone_members(africa, %w(DZ AO BJ BW BF BI CV CM CF TD KM CG CD CI DJ EG GQ ER SZ ET GA GM GH GN GW KE LS LR LY- MG MW ML MR MU YT MA MZ NA NE NG RE RW SH ST SN SC SL SO ZA SS SD TZ TG TN UG ZM ZW))- create_zone_members(asia, %w(AF AM AZ BH BD BT BN KH CN CX CC GE HK IN ID IR IQ IL JP JO KZ KW KG LA LB MO MY MV MN MM NP- KP OM PK PS PH QA SA SG KR LK SY TW TJ TH TR TM AE UZ VN YE))- create_zone_members(australia_and_oceania, %w(AU NZ PG FJ SB VU NC PF WS AS GU KI MH FM NR NU NF MP PW PN TK TO TV WF CK))- uk_vat.zone_members.where(zoneable: Spree::Country.find_by(iso: 'GB')).first_or_create!- end-- protected-- def create_zone_members(zone, country_codes)- countries_ids = Spree::Country.where(iso: country_codes).ids- existing_ids = zone.zone_members.where(zoneable_type: 'Spree::Country', zoneable_id: countries_ids).pluck(:zoneable_id)- new_ids = countries_ids - existing_ids-- return if new_ids.empty?-- zone_members = new_ids.map do |country_id|- {- zoneable_id: country_id,- zoneable_type: 'Spree::Country',- zone_id: zone.id,- created_at: Time.current,- updated_at: Time.current- }- end- Spree::ZoneMember.insert_all(zone_members)- end- end- end-enddiff --git a/spree/core/db/sample_data/markets.rb b/spree/core/db/sample_data/markets.rbindex b2c76998d6..15eb891ae8 100644--- a/spree/core/db/sample_data/markets.rb+++ b/spree/core/db/sample_data/markets.rb@@ -14,37 +14,36 @@ if usus_market.save!end-eu_zone = Spree::Zone.find_by(name: 'EU_VAT')--if eu_zone- eu_countries = eu_zone.zone_members.where(zoneable_type: 'Spree::Country').map(&:zoneable).uniq.compact-- if eu_countries.any?- eu_market = store.markets.find_or_initialize_by(name: 'Europe')- eu_market.currency = 'EUR'- eu_market.default_locale = 'de'- eu_market.supported_locales = 'de,fr,es,it'- eu_market.countries = eu_countries- eu_market.save!- end+# Each market names its countries as ISO codes directly — the zone seeds these+# groupings used to come from are gone. Countries already assigned to another+# market in the store are skipped, because Spree::MarketCountry requires each+# country to belong to at most one market per store.+EU_ISOS = %w[PL FI PT RO DE FR SK HU SI IE AT ES IT BE SE LV BG LT CY LU MT DK NL EE HR CZ GR].freeze++eu_countries = Spree::Country.where(iso: EU_ISOS).to_a+if eu_countries.any?+ eu_market = store.markets.find_or_initialize_by(name: 'Europe')+ eu_market.currency = 'EUR'+ eu_market.default_locale = 'de'+ eu_market.supported_locales = 'de,fr,es,it'+ eu_market.countries = eu_countries+ eu_market.save!end-# Additional sample markets for the remaining continents. Each market pulls-# its countries from the matching shipping zone so it only includes countries-# with shipping coverage (and therefore valid market countries). Countries-# already assigned to another market in the store are skipped, because-# Spree::MarketCountry requires each country to belong to at most one market-# per store.[- { name: 'South America', zone: 'South America', currency: 'USD', default_locale: 'es', supported_locales: 'es,pt' },- { name: 'Middle East', zone: 'Middle East', currency: 'USD', default_locale: 'en', supported_locales: 'en,ar' },- { name: 'Africa', zone: 'Africa', currency: 'USD', default_locale: 'en', supported_locales: 'en,fr,ar' },- { name: 'Asia', zone: 'Asia', currency: 'USD', default_locale: 'en', supported_locales: 'en' },- { name: 'Oceania', zone: 'Australia and Oceania', currency: 'AUD', default_locale: 'en', supported_locales: 'en' }+ { name: 'South America', isos: %w[AR BO BR CL CO EC FK GF GY PY PE SR UY VE],+ currency: 'USD', default_locale: 'es', supported_locales: 'es,pt' },+ { name: 'Middle East', isos: %w[BH EG IR IQ IL JO KW LB OM QA SA SY TR AE YE],+ currency: 'USD', default_locale: 'en', supported_locales: 'en,ar' },+ { name: 'Africa', isos: %w[DZ AO BJ BW BF BI CV CM CF TD KM CG CD CI DJ GQ ER SZ ET GA GM GH GN GW KE LS LR LY+ MG MW ML MR MU YT MA MZ NA NE NG RE RW SH ST SN SC SL SO ZA SS SD TZ TG TN UG ZM ZW],+ currency: 'USD', default_locale: 'en', supported_locales: 'en,fr,ar' },+ { name: 'Asia', isos: %w[AF AM AZ BD BT BN KH CN CX CC GE HK IN ID JP KZ KG LA MO MY MV MN MM NP+ KP PK PS PH SG KR LK TW TJ TH TM UZ VN],+ currency: 'USD', default_locale: 'en', supported_locales: 'en' },+ { name: 'Oceania', isos: %w[AU NZ PG FJ SB VU NC PF WS AS GU KI MH FM NR NU NF MP PW PN TK TO TV WF CK],+ currency: 'AUD', default_locale: 'en', supported_locales: 'en' }].each do |attrs|- zone = Spree::Zone.find_by(name: attrs[:zone])- next unless zone-market = store.markets.find_or_initialize_by(name: attrs[:name])assigned_scope = Spree::MarketCountry.joins(:market).@@ -52,8 +51,7 @@ endassigned_scope = assigned_scope.where.not(market_id: market.id) if market.persisted?assigned_country_ids = assigned_scope.pluck(:country_id).to_set- countries = zone.zone_members.where(zoneable_type: 'Spree::Country').map(&:zoneable).uniq.compact- countries = countries.reject { |c| assigned_country_ids.include?(c.id) }+ countries = Spree::Country.where(iso: attrs[:isos]).reject { |c| assigned_country_ids.include?(c.id) }next if countries.empty?market.currency = attrs[:currency]diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rbindex a5bf76f223..c3ea0e6ab5 100644--- a/spree/core/lib/spree/core/engine.rb+++ b/spree/core/lib/spree/core/engine.rb@@ -312,13 +312,10 @@ module SpreeSpree::Promotion::Rules::OptionValue,]- # Default registry. MarketRule is included so existing installs- # don't lose access to saved rule rows in the admin. ZoneRule is- # intentionally excluded: it decides by country now that tax and- # pricing no longer read zones, survives only to keep pre-6.0 data- # working, and- # MarketRule already covers geography for new price lists. The- # class loads; it just doesn't show up under "Add rule".+ # Default registry. MarketRule is the only geography rule: price+ # lists that were zone-scoped before 6.0 are converted onto it by+ # `spree:migrate_tax_zones` where the countries match a market, and+ # deactivated with a report where they don't.Rails.application.config.spree.pricing.rules.concat [Spree::PriceRules::UserRule,Spree::PriceRules::CustomerGroupRule,diff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rbindex dcb7d5ccb9..58d092731b 100644--- a/spree/core/lib/spree/core/permission_configuration.rb+++ b/spree/core/lib/spree/core/permission_configuration.rb@@ -273,7 +273,7 @@ module Spreeregister_resource(:settings, group: :settings, subjects: -> {[Spree::Store, Spree::PaymentMethod, Spree::Gateway, Spree::DeliveryMethod,Spree::DeliveryMethodRule, Spree::DeliveryZone, Spree::DeliveryZoneMember,- Spree::StockLocation, Spree::DeliveryProfile, Spree::Zone, Spree::ZoneMember,+ Spree::StockLocation, Spree::DeliveryProfile,Spree::Market, Spree::TaxCategory, Spree::TaxRate, Spree::AllowedOrigin,Spree::RefundReason, Spree::ReturnReason, Spree::ClaimReason, Spree::Channel,Spree::OrderRoutingRule, Spree::CustomFieldDefinition, Spree::Policy,diff --git a/spree/core/lib/spree/testing_support/factories.rb b/spree/core/lib/spree/testing_support/factories.rbindex 43c5a465e7..5c2fb9f775 100644--- a/spree/core/lib/spree/testing_support/factories.rb+++ b/spree/core/lib/spree/testing_support/factories.rb@@ -1,11 +1,5 @@require 'factory_bot'-Spree::Zone.class_eval do- def self.global- find_by(name: 'GlobalZone') || FactoryBot.create(:global_zone, name: 'GlobalZone')- end-end-Dir["#{File.dirname(__FILE__)}/factories/**"].each do |f|load File.expand_path(f)enddiff --git a/spree/core/lib/spree/testing_support/factories/price_rule_factory.rb b/spree/core/lib/spree/testing_support/factories/price_rule_factory.rbindex b4700c779f..c27aeb7c86 100644--- a/spree/core/lib/spree/testing_support/factories/price_rule_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/price_rule_factory.rb@@ -2,16 +2,6 @@ FactoryBot.define dofactory :price_rule, class: Spree::PriceRule doprice_list- factory :zone_price_rule, class: Spree::PriceRules::ZoneRule do- after(:build) do |rule, evaluator|- rule.preferred_country_isos = evaluator.country_isos if evaluator.respond_to?(:country_isos)- end-- transient do- country_isos { [] }- end- end-factory :volume_price_rule, class: Spree::PriceRules::VolumeRule doafter(:build) do |rule, evaluator|rule.preferred_min_quantity = evaluator.min_quantity if evaluator.min_quantity.present?diff --git a/spree/core/lib/spree/testing_support/factories/zone_factory.rb b/spree/core/lib/spree/testing_support/factories/zone_factory.rbindex adccd9be60..a29c23ebf7 100644--- a/spree/core/lib/spree/testing_support/factories/zone_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/zone_factory.rb@@ -1,31 +1,8 @@+# Migration-only shell (see Spree::Zone) — used solely by the 5.6→6.0+# data-migration specs to build legacy rows.FactoryBot.define dofactory :zone, class: Spree::Zone doname { generate(:random_string) }description { generate(:random_string) }-- factory :zone_with_country do- kind { :country }-- zone_members do |proxy|- zone = proxy.instance_eval { @instance }-- [Spree::ZoneMember.create(zoneable: create(:country), zone: zone)]- end-- factory :global_zone, class: Spree::Zone do- name { 'GlobalZone' }-- after(:create) do |zone|- country_ids = Spree::Country.pluck(:id)- existing_ids = zone.zone_members.where(zoneable_type: 'Spree::Country').pluck(:zoneable_id)- new_ids = country_ids - existing_ids-- if new_ids.any?- records = new_ids.map { |id| { zoneable_type: 'Spree::Country', zoneable_id: id, zone_id: zone.id, created_at: Time.current, updated_at: Time.current } }- Spree::ZoneMember.insert_all(records)- end- end- end- endendenddiff --git a/spree/core/lib/spree/testing_support/order_walkthrough.rb b/spree/core/lib/spree/testing_support/order_walkthrough.rbindex a41303badf..e763b31edd 100644--- a/spree/core/lib/spree/testing_support/order_walkthrough.rb+++ b/spree/core/lib/spree/testing_support/order_walkthrough.rb@@ -16,10 +16,7 @@ class OrderWalkthroughFactoryBot.create(:check_payment_method)end- # Need to create a valid zone too...- zone = FactoryBot.create(:zone)country = FactoryBot.create(:country)- zone.members << Spree::ZoneMember.create(zoneable: country)country.states << FactoryBot.create(:state, country: country)# A delivery method must exist for rates to be displayed on checkout page@@ -51,8 +48,9 @@ class OrderWalkthroughenddef self.address(cart)- cart.bill_address = FactoryBot.create(:address, country_id: Spree::Zone.global.members.first.zoneable.id)- cart.ship_address = FactoryBot.create(:address, country_id: Spree::Zone.global.members.first.zoneable.id)+ country = Spree::Country.first || FactoryBot.create(:country)+ cart.bill_address = FactoryBot.create(:address, country_id: country.id)+ cart.ship_address = FactoryBot.create(:address, country_id: country.id)cart.save!cart.rebuild_fulfillments!cart.set_fulfillments_costdiff --git a/spree/core/lib/tasks/tax_zones_migration.rake b/spree/core/lib/tasks/tax_zones_migration.rakeindex 624a4dd199..5881c07486 100644--- a/spree/core/lib/tasks/tax_zones_migration.rake+++ b/spree/core/lib/tasks/tax_zones_migration.rake@@ -66,54 +66,72 @@ namespace :spree doputs " Converted #{converted} tax rates, split #{duplicated} extra rate(s) off multi-jurisdiction zones, " \"skipped #{skipped}."- # Price lists could also be restricted by zone. Those rules now decide by- # country, so restate each one as the countries its zones contained. A- # zone that named individual states becomes those states' countries, which- # widens the rule — reported below so the merchant can narrow it by hand.- # Both lists resolve through their model on the way out, so a member- # pointing at a deleted country or state drops out instead of being written- # back as a code nothing issued.- countries_for = lambda do |zone_ids|+ # Price lists could also be restricted by zone. Markets are how pricing+ # targets geography now, so each zone rule becomes a MarketRule where the+ # zone's countries exactly match one of the store's markets — the one+ # mapping that provably keeps the same buyers on the same prices. A rule+ # whose countries match no market cannot be restated without silently+ # re-scoping who pays what, so its price list is deactivated instead and+ # reported with the countries it named, for the merchant to rebuild as a+ # market. Zones naming states resolve to those states' countries.+ zone_country_ids = lambda do |zone_ids|members = Spree::ZoneMember.where(zone_id: zone_ids)- country_isos = Spree::Country.where(- id: members.where(zoneable_type: 'Spree::Country').pluck(:zoneable_id)- ).pluck(:iso)- state_country_isos = Spree::Country.where(+ country_ids = Spree::Country.where(+ id: members.where(zoneable_type: 'Spree::Country').select(:zoneable_id)+ ).ids+ state_country_ids = Spree::Country.where(id: Spree::State.where(- id: members.where(zoneable_type: 'Spree::State').pluck(:zoneable_id)+ id: members.where(zoneable_type: 'Spree::State').select(:zoneable_id)).select(:country_id)- ).pluck(:iso)+ ).ids- [(country_isos + state_country_isos).compact.uniq.map(&:upcase), state_country_isos.any?]+ (country_ids + state_country_ids).uniq.sortend- rules_converted = 0- rules_widened = 0- rules_unrestricted = 0+ rules_matched = 0+ lists_deactivated = []- Spree::PriceRules::ZoneRule.find_each do |rule|+ Spree::PriceRule.where(type: 'Spree::PriceRules::ZoneRule').find_each do |rule|stored = rule.preferences.with_indifferent_accesszone_ids = Array(stored[:zone_ids]).reject(&:blank?)- next if stored[:country_isos].present? || zone_ids.empty?+ country_ids = zone_country_ids.call(zone_ids)- country_isos, from_states = countries_for.call(zone_ids)- rule.update_columns(- preferences: stored.except(:zone_ids).merge(country_isos: country_isos).to_h.symbolize_keys,- updated_at: Time.current- )- rules_converted += 1- rules_widened += 1 if from_states- # A zone that was deleted, or had no members, leaves nothing to restrict- # by, so the rule stops narrowing its price list at all. Called out- # because it is the one outcome here a merchant would not predict.- rules_unrestricted += 1 if country_isos.empty?+ price_list = Spree::PriceList.with_deleted.find_by(id: rule.price_list_id)+ market = if price_list && country_ids.any?+ price_list.store.markets.find do |candidate|+ candidate.market_countries.pluck(:country_id).uniq.sort == country_ids+ end+ end++ if market+ rule.update_columns(+ type: 'Spree::PriceRules::MarketRule',+ preferences: stored.except(:zone_ids, :country_isos).+ merge(market_ids: [market.id.to_s]).to_h.symbolize_keys,+ updated_at: Time.current+ )+ rules_matched += 1+ else+ # Without a matching market the restriction is unrepresentable; the+ # list must not quietly widen to every buyer, so it goes dark until+ # the merchant rebuilds the geography as a market.+ if price_list && !price_list.deleted? && price_list.status != 'inactive'+ price_list.update_columns(status: 'inactive', updated_at: Time.current)+ end+ isos = Spree::Country.where(id: country_ids).pluck(:iso).sort+ lists_deactivated << [price_list, isos]+ rule.delete+ endend- puts " Restated #{rules_converted} zone price rule(s) as countries " \- "(#{rules_widened} widened from state-level zones — review those price lists)."- if rules_unrestricted.positive?- puts " #{rules_unrestricted} of them named zones that no longer resolve to any country, so " \- 'those price lists now apply everywhere — set their countries by hand.'+ puts " Converted #{rules_matched} zone price rule(s) to market rules." if rules_matched.positive?+ if lists_deactivated.any?+ puts " Deactivated #{lists_deactivated.size} price list(s) whose zone matched no market — " \+ 'create a market for the countries, then re-add the rule and reactivate:'+ lists_deactivated.each do |list, isos|+ label = list ? "#{list.name} (#{list.id})" : 'deleted price list'+ puts " - #{label}: #{isos.any? ? isos.join(', ') : 'no resolvable countries'}"+ endendendenddiff --git a/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb b/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rbindex 3dffdbaff0..2d7341ef86 100644--- a/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb+++ b/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb@@ -274,62 +274,86 @@ describe '6.0 data migration tasks' doendcontext 'price rules restricted by zone' do- let(:price_list) { create(:price_list) }-- def legacy_rule(zone)- create(:zone_price_rule, price_list: price_list).tap do |rule|- rule.update_columns(preferences: { zone_ids: [zone.id.to_s] })+ let(:price_list) { create(:price_list, status: 'active') }++ # A pre-upgrade row: ZoneRule-typed with zone ids in its preferences.+ # Written with update_columns because 6.0 code never creates such rows.+ def legacy_rule(zone, list: price_list)+ create(:market_price_rule, price_list: list).tap do |rule|+ rule.update_columns(+ type: 'Spree::PriceRules::ZoneRule',+ preferences: { zone_ids: [zone.id.to_s] }+ )endend- it 'restates the zone as the countries it contained' do+ def market_for(*countries)+ create(:market, store: price_list.store, countries: countries)+ end++ it 'converts a rule whose zone matches a market exactly' do+ market = market_for(germany, france)rule = legacy_rule(zone_with(germany, france))run_task('spree:migrate_tax_zones')- expect(rule.reload.preferred_country_isos).to contain_exactly(germany.iso, france.iso)+ rule.reload+ expect(rule.type).to eq('Spree::PriceRules::MarketRule')+ expect(rule.preferred_market_ids.map(&:to_s)).to eq([market.id.to_s])+ expect(price_list.reload.status).to eq('active')end- # A state-level zone can only be expressed as its states' countries,- # which lets the rule through for the rest of that country too.- it 'widens a state-level zone to the country' do+ # A state-level zone resolves to its states' countries before matching.+ it 'matches a state-level zone through its country' do+ market = market_for(germany)state = create(:state, country: germany, abbr: 'BE', name: 'Berlin')rule = legacy_rule(zone_with(state))run_task('spree:migrate_tax_zones')- expect(rule.reload.preferred_country_isos).to eq([germany.iso])+ rule.reload+ expect(rule.type).to eq('Spree::PriceRules::MarketRule')+ expect(rule.preferred_market_ids.map(&:to_s)).to eq([market.id.to_s])end- it 'is idempotent over a legacy row' do- rule = legacy_rule(zone_with(germany))+ it 'deactivates the list and removes the rule when no market matches' do+ market_for(germany)+ rule = legacy_rule(zone_with(germany, france))+run_task('spree:migrate_tax_zones')- converted = rule.reload.preferred_country_isos++ expect(Spree::PriceRule.exists?(rule.id)).to be(false)+ expect(price_list.reload.status).to eq('inactive')+ end++ # A zone that was deleted or memberless resolves to nothing — the one+ # outcome that must never widen the list to every buyer.+ it 'deactivates a list whose zones resolve to no country' do+ rule = legacy_rule(zone_with)run_task('spree:migrate_tax_zones')- expect(rule.reload.preferred_country_isos).to eq(converted)- expect(rule.reload.preferences).not_to have_key(:zone_ids)+ expect(Spree::PriceRule.exists?(rule.id)).to be(false)+ expect(price_list.reload.status).to eq('inactive')end- it 'leaves a rule the merchant already set countries on alone' do- rule = create(:zone_price_rule, price_list: price_list, country_isos: [france.iso])+ it 'is idempotent over a converted row' do+ market_for(germany)+ rule = legacy_rule(zone_with(germany))+ run_task('spree:migrate_tax_zones')run_task('spree:migrate_tax_zones')- expect(rule.reload.preferred_country_isos).to eq([france.iso])+ expect(rule.reload.type).to eq('Spree::PriceRules::MarketRule')+ expect(price_list.reload.status).to eq('active')end- # A zone that was deleted and one that never had members both leave no- # country to restrict by, so the rule stops narrowing its price list.- # The task reports the count; there is nothing to fall back on.- it 'clears a rule whose zones resolve to no country' do- rule = legacy_rule(zone_with)+ it 'does not touch other rule types' do+ market_rule = create(:market_price_rule, price_list: price_list)run_task('spree:migrate_tax_zones')- expect(rule.reload.preferred_country_isos).to be_empty- expect(rule.preferences).not_to have_key(:zone_ids)+ expect(market_rule.reload.type).to eq('Spree::PriceRules::MarketRule')endendenddiff --git a/spree/core/spec/models/spree/price_list_spec.rb b/spree/core/spec/models/spree/price_list_spec.rbindex ea7b51d24a..a352af81ea 100644--- a/spree/core/spec/models/spree/price_list_spec.rb+++ b/spree/core/spec/models/spree/price_list_spec.rb@@ -129,7 +129,7 @@ describe Spree::PriceList, type: :model doendcontext 'with rules and match_policy = all' do- let!(:passing_rule) { create(:zone_price_rule, price_list: price_list) }+ let!(:passing_rule) { create(:market_price_rule, price_list: price_list) }let!(:failing_rule) { create(:user_price_rule, price_list: price_list) }before do@@ -145,7 +145,7 @@ describe Spree::PriceList, type: :model doendcontext 'with rules and match_policy = any' do- let!(:passing_rule) { create(:zone_price_rule, price_list: price_list) }+ let!(:passing_rule) { create(:market_price_rule, price_list: price_list) }let!(:failing_rule) { create(:user_price_rule, price_list: price_list) }before dodiff --git a/spree/core/spec/models/spree/price_rules/zone_rule_spec.rb b/spree/core/spec/models/spree/price_rules/zone_rule_spec.rbdeleted file mode 100644index c01b9ca08b..0000000000--- a/spree/core/spec/models/spree/price_rules/zone_rule_spec.rb+++ /dev/null@@ -1,80 +0,0 @@-require 'spec_helper'--describe Spree::PriceRules::ZoneRule, type: :model do- let(:price_list) { create(:price_list) }- let(:rule) { create(:zone_price_rule, price_list: price_list) }- let(:country) { create(:country, iso: 'DE', name: 'Germany') }- let(:variant) { create(:variant) }-- def context_for(country_record = nil)- Spree::Pricing::Context.new(variant: variant, currency: 'USD', country: country_record)- end-- describe '#applicable?' do- context 'when no country is named' do- before { rule.preferred_country_isos = [] }-- it 'returns true for any country' do- expect(rule.applicable?(context_for(country))).to be true- end- end-- context 'when a country is named' do- before { rule.preferred_country_isos = [country.iso] }-- it 'returns true when the context country matches' do- expect(rule.applicable?(context_for(country))).to be true- end-- it 'returns false when the context country does not match' do- expect(rule.applicable?(context_for(create(:country, iso: 'FR', name: 'France')))).to be false- end-- # A context built without a country falls back to the store's, so nil only- # reaches the guard when there is no store country either.- it 'returns false when the context has no country at all' do- allow(Spree::Current).to receive(:tax_country).and_return(nil)-- context = Spree::Pricing::Context.new(variant: variant, currency: 'USD')-- expect(context.country).to be_nil- expect(rule.applicable?(context)).to be false- end- end-- # Codes arrive from merchants, so case is not guaranteed either way.- context 'when the code was entered in lowercase' do- before { rule.preferred_country_isos = ['de'] }-- it 'returns true when the context country matches' do- expect(rule.applicable?(context_for(country))).to be true- end-- it 'returns false when the context country does not match' do- expect(rule.applicable?(context_for(create(:country, iso: 'FR', name: 'France')))).to be false- end- end-- # There is no country table to check a code against, so an unknown one has- # to narrow the price list to nothing rather than widen it to everywhere.- context 'when the code is one nothing issued' do- before { rule.preferred_country_isos = ['ZZ'] }-- it 'returns false for every country' do- expect(rule.applicable?(context_for(country))).to be false- end- end- end- describe '#geographic?' do- it 'is true once countries are named' do- rule = described_class.new(price_list: price_list)- rule.preferred_country_isos = [country.iso]-- expect(rule.geographic?).to be(true)- end-- it 'is false while no country is named' do- expect(described_class.new(price_list: price_list).geographic?).to be(false)- end- end-enddiff --git a/spree/core/spec/models/spree/zone_member_spec.rb b/spree/core/spec/models/spree/zone_member_spec.rbdeleted file mode 100644index 9bf0d302a3..0000000000--- a/spree/core/spec/models/spree/zone_member_spec.rb+++ /dev/null@@ -1,46 +0,0 @@-require 'spec_helper'--describe Spree::ZoneMember, type: :model do- let(:country) { create(:country) }- let(:state) { create(:state) }- let(:zone) { create(:zone, kind: 'country') }- let(:zone_member) { create(:zone_member, zone: zone, zoneable: country) }-- describe 'validations' do- it 'does not allow duplicate zoneable in the same zone' do- zone_member- duplicate = build(:zone_member, zone: zone, zoneable: country)- expect(duplicate).not_to be_valid- expect(duplicate.errors[:zoneable_id]).to be_present- end-- it 'allows the same zoneable in different zones' do- zone_member- other_zone = create(:zone, kind: 'country')- other_member = build(:zone_member, zone: other_zone, zoneable: country)- expect(other_member).to be_valid- end- end-- describe 'scopes' do- describe '.defunct_without_kind' do- let(:defunct_without_kind) { Spree::ZoneMember.defunct_without_kind('country') }-- context 'zoneable is present and is of defunct kind' do- it { expect(defunct_without_kind).not_to include(zone_member) }- end-- context 'zoneable is not of defunct kind' do- before { zone_member.update(zoneable: state) }-- it { expect(defunct_without_kind).to include(zone_member) }- end-- context 'zoneable is absent' do- before { zone_member.update_column(:zoneable_id, nil) }-- it { expect(defunct_without_kind).to include(zone_member) }- end- end- end-enddiff --git a/spree/core/spec/models/spree/zone_spec.rb b/spree/core/spec/models/spree/zone_spec.rbdeleted file mode 100644index ae5cef9b3c..0000000000--- a/spree/core/spec/models/spree/zone_spec.rb+++ /dev/null@@ -1,528 +0,0 @@-require 'spec_helper'--describe Spree::Zone, type: :model do- context '#match' do- let(:country_zone) { create(:zone, kind: 'country') }-- let(:country) do- create(:country)- end-- let(:state) do- create(:state, country: country)- end-- before { country_zone.members.create(zoneable: country) }-- describe 'scopes' do- describe '.remove_previous_default' do- subject { Spree::Zone.with_default_tax }-- let(:zone_with_default_tax) { create(:zone, kind: 'country', default_tax: true) }- let(:zone_not_with_default_tax) { create(:zone, kind: 'country', default_tax: false) }-- it 'is expected to include zone with default tax' do- expect(subject).to include(zone_with_default_tax)- end-- it 'is expected to not include zone with default tax' do- expect(subject).not_to include(zone_not_with_default_tax)- end- end- end-- describe 'callbacks' do- describe '#remove_previous_default' do- let!(:zone_with_default_tax) { create(:zone, kind: 'country', default_tax: true) }- let!(:zone_not_with_default_tax) { create(:zone, kind: 'country', default_tax: false) }-- it 'is expected to make previous default tax zones to non default tax zones' do- expect(zone_with_default_tax).to be_default_tax- zone_not_with_default_tax.update(default_tax: true)- expect(zone_with_default_tax.reload).not_to be_default_tax- end- end-- end-- context 'when there is only one qualifying zone' do- let(:address) { create(:address, country: country, state: state) }-- it 'returns the qualifying zone' do- expect(Spree::Zone.match(address)).to eq(country_zone)- end- end-- context 'when there are two qualified zones with same member type' do- let(:address) { create(:address, country: country, state: state) }- let(:second_zone) { create(:zone, name: 'SecondZone', kind: 'country') }-- before { second_zone.members.create(zoneable: country) }-- context 'when both zones have the same number of members' do- it 'returns the zone that was created first' do- Timecop.scale(100) do- expect(Spree::Zone.match(address)).to eq(country_zone)- end- end- end-- context 'when one of the zones has fewer members' do- let(:country2) { create(:country) }-- before { country_zone.members.create(zoneable: country2) }-- it 'returns the zone with fewer members' do- expect(Spree::Zone.match(address)).to eq(second_zone)- end- end- end-- context 'when there are two qualified zones with different member types' do- let(:state_zone) { create(:zone, kind: 'state') }- let(:address) { create(:address, country: country, state: state) }-- before { state_zone.members.create!(zoneable: state) }-- it 'returns the zone with the more specific member type' do- expect(Spree::Zone.match(address)).to eq(state_zone)- end- end-- context 'when there are no qualifying zones' do- it 'returns nil' do- expect(Spree::Zone.match(Spree::Address.new)).to be_nil- end- end- end-- context '#country_list' do- let(:state) { create(:state) }- let(:country) { state.country }-- context 'when zone consists of countries' do- let(:country_zone) { create(:zone, kind: 'country') }-- before { country_zone.members.create(zoneable: country) }-- it 'returns a list of countries' do- expect(country_zone.country_list).to eq([country])- end- end-- context 'when zone consists of states' do- let(:state_zone) { create(:zone, kind: 'state') }-- before { state_zone.members.create(zoneable: state) }-- it 'returns a list of countries' do- expect(state_zone.country_list).to eq([state.country])- end- end- end-- context '#include?' do- let(:state) { create(:state) }- let(:country) { state.country }- let(:address) { create(:address, state: state) }-- context 'when zone is country type' do- let(:country_zone) { create(:zone, kind: 'country') }-- before { country_zone.members.create(zoneable: country) }-- it 'is true' do- expect(country_zone.include?(address)).to be true- end- end-- context 'when zone is state type' do- let(:state_zone) { create(:zone, kind: 'state') }-- before { state_zone.members.create(zoneable: state) }-- it 'is true' do- expect(state_zone.include?(address)).to be true- end- end- end-- context '#contains?' do- let(:country1) { create(:country) }- let(:country2) { create(:country) }- let(:country3) { create(:country) }-- let(:state1) { create(:state) }- let(:state2) { create(:state) }- let(:state3) { create(:state) }-- let(:source) { create(:zone, name: 'source', kind: 'country', zone_members: []) }- let(:target) { create(:zone, name: 'target', kind: 'country', zone_members: []) }-- context 'when the target has no members' do- before { source.members.create(zoneable: country1) }-- it 'is false' do- expect(source.contains?(target)).to be false- end- end-- context 'when the source has no members' do- before { target.members.create(zoneable: country1) }-- it 'is false' do- expect(source.contains?(target)).to be false- end- end-- context 'when both zones are the same zone' do- before do- source.members.create(zoneable: country1)- target.members.create(zoneable: country1)- end-- it 'is true' do- expect(source.contains?(target)).to be true- end- end-- context 'when checking countries against countries' do- before do- source.members.create(zoneable: country1)- source.members.create(zoneable: country2)- end-- context 'when all members are included in the zone we check against' do- before do- target.members.create(zoneable: country1)- target.members.create(zoneable: country2)- end-- it 'is true' do- expect(source.contains?(target)).to be true- end- end-- context 'when some members are included in the zone we check against' do- before do- target.members.create(zoneable: country1)- target.members.create(zoneable: country2)- target.members.create(zoneable: create(:country))- end-- it 'is false' do- expect(source.contains?(target)).to be false- end- end-- context 'when none of the members are included in the zone we check against' do- before do- target.members.create(zoneable: create(:country))- target.members.create(zoneable: create(:country))- end-- it 'is false' do- expect(source.contains?(target)).to be false- end- end- end-- context 'when checking states against states' do- let(:source) { create(:zone, name: 'source', kind: 'state', zone_members: []) }- let(:target) { create(:zone, name: 'target', kind: 'state', zone_members: []) }-- before do- source.members.create(zoneable: state1)- source.members.create(zoneable: state2)- end-- context 'when all members are included in the zone we check against' do- before do- target.members.create(zoneable: state1)- target.members.create(zoneable: state2)- end-- it 'is true' do- expect(source.contains?(target)).to be true- end- end-- context 'when some members are included in the zone we check against' do- before do- target.members.create(zoneable: state1)- target.members.create(zoneable: state2)- target.members.create(zoneable: create(:state))- end-- it 'is false' do- expect(source.contains?(target)).to be false- end- end-- context 'when none of the members are included in the zone we check against' do- before do- target.members.create(zoneable: create(:state))- target.members.create(zoneable: create(:state))- end-- it 'is false' do- expect(source.contains?(target)).to be false- end- end- end-- context 'when checking country against state' do- let(:source) { create(:zone, name: 'source', kind: 'state', zone_members: []) }- let(:target) { create(:zone, name: 'target', kind: 'country', zone_members: []) }-- before do- source.members.create(zoneable: create(:state))- target.members.create(zoneable: country1)- end-- it 'is false' do- expect(source.contains?(target)).to be false- end- end-- context 'when checking state against country' do- let(:source) { create(:zone, name: 'source', kind: 'country', zone_members: []) }- let(:target) { create(:zone, name: 'target', kind: 'state', zone_members: []) }-- before { source.members.create(zoneable: country1) }-- context 'when all states contained in one of the countries we check against' do- before do- state1 = create(:state, country: country1)- target.members.create(zoneable: state1)- end-- it 'is true' do- expect(source.contains?(target)).to be true- end- end-- context 'when some states contained in one of the countries we check against' do- before do- state1 = create(:state, country: country1)- target.members.create(zoneable: state1)- target.members.create(zoneable: create(:state, country: country2))- end-- it 'is false' do- expect(source.contains?(target)).to be false- end- end-- context 'when none of the states contained in any of the countries we check against' do- before do- target.members.create(zoneable: create(:state, country: country2))- target.members.create(zoneable: create(:state, country: country2))- end-- it 'is false' do- expect(source.contains?(target)).to be false- end- end- end- end-- context '#save' do- context 'when default_tax is true' do- it 'clears previous default tax zone' do- zone1 = create(:zone, name: 'foo', default_tax: true)- create(:zone, name: 'bar', default_tax: true)- expect(zone1.reload.default_tax).to be false- end- end-- context 'when a zone member country is added to an existing zone consisting of state members' do- it 'removes existing country members' do- zone = create(:zone, name: 'foo', kind: 'state', zone_members: [])- state = create(:state)- country = create(:country)-- state_member = zone.members.create(zoneable: state)- _country_member = zone.members.create(zoneable: country)-- zone.save-- expect(zone.reload.members).to eq([state_member])- end- end- end-- context '#kind' do- it 'returns whatever value you set' do- zone = Spree::Zone.new kind: 'city'- expect(zone.kind).to eq 'city'- end-- context 'when the zone consists of country zone members' do- let(:zone) { create(:zone, name: 'country', kind: 'country', zone_members: []) }-- before do- zone.members.create(zoneable: create(:country))- end-- it 'returns the kind of zone member' do- expect(zone.kind).to eq('country')- end- end- end-- context '#potential_matching_zones' do- let!(:country) { create(:country) }- let!(:country2) { create(:country, name: 'OtherCountry') }- let!(:country3) { create(:country, name: 'TaxCountry') }- let!(:default_tax_zone) do- create(:zone, default_tax: true).tap { |z| z.members.create(zoneable: country3) }- end-- context 'finding potential matches for a country zone' do- let!(:zone) do- create(:zone, kind: 'country').tap do |z|- z.members.create(zoneable: country)- z.members.create(zoneable: country2)- z.save!- end- end- let!(:zone2) do- create(:zone, kind: 'country').tap do |zone|- zone.members.create(zoneable: country)- end- end- let(:result) { Spree::Zone.potential_matching_zones(zone) }--- it 'will find all zones with countries covered by the passed in zone' do- expect(result).to include(zone, zone2)- end-- it 'only returns each zone once' do- expect(result.select { |z| z == zone }.size).to be 1- end- end-- context 'finding potential matches for a state zone' do- let!(:state) { create(:state, country: country) }- let!(:state2) { create(:state, country: country2, name: 'OtherState') }- let!(:state3) { create(:state, country: country2, name: 'State') }- let!(:zone) do- create(:zone).tap do |z|- z.members.create(zoneable: state)- z.members.create(zoneable: state2)- z.save!- end- end- let!(:zone2) do- create(:zone).tap { |z| z.members.create(zoneable: state) && z.save! }- end- let!(:zone3) do- create(:zone).tap { |z| z.members.create(zoneable: state2) && z.save! }- end-- before { @result = Spree::Zone.potential_matching_zones(zone) }-- it 'will find all zones which share states covered by passed in zone' do- expect(@result).to include(zone, zone2)- end-- it 'will find zones that share countries with any states of the passed in zone' do- expect(@result).to include(zone3)- end-- it 'only returns each zone once' do- expect(@result.select { |z| z == zone }.size).to be 1- end- end- end-- context 'state and country associations' do- let!(:country) { create(:country) }-- context 'has countries associated' do- let!(:zone) do- create(:zone, countries: [country])- end-- it 'can access associated countries' do- expect(zone.countries).to include(country)- end- end-- context 'has states associated' do- let!(:state) { create(:state, country: country) }- let!(:zone) do- create(:zone, states: [state])- end-- it 'can access associated states' do- expect(zone.states).to include(state)- end- end- end-- describe '#state_list' do- let!(:country) { create(:country) }- let!(:state) { create(:state, country: country) }-- context 'has countries associated' do- let(:country_zone) do- create(:zone, kind: 'country').tap do |zone|- zone.members.create(zoneable: country)- end- end-- it 'returns states associated to that countries' do- expect(country_zone.state_list).to contain_exactly(state)- end- end-- context 'has states associated' do- let(:state_zone) do- create(:zone, kind: 'state').tap do |zone|- zone.members.create(zoneable: state)- end- end-- it 'returns that states' do- expect(state_zone.state_list).to contain_exactly(state)- end- end- end-- describe '#state_list_for' do- let!(:country1) { create(:country) }- let!(:country2) { create(:country) }-- let!(:state1) { create(:state, country: country1) }- let!(:state2) { create(:state, country: country2) }-- context 'has countries associated' do- let(:country_zone) do- create(:zone, kind: 'country').tap do |zone|- zone.members.create(zoneable: country1)- zone.members.create(zoneable: country2)- end- end-- it 'returns states associated with the country' do- expect(country_zone.state_list_for(country1)).to contain_exactly(state1)- end- end-- context 'has states associated' do- let(:state_zone) do- create(:zone, kind: 'state').tap do |zone|- zone.members.create(zoneable: state1)- zone.members.create(zoneable: state2)- end- end-- it 'returns states associated with the country' do- expect(state_zone.state_list_for(country1)).to contain_exactly(state1)- end- end- end-end