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
Phase 11: answer "where is this buyer taxed" with a country everywhere
Łukasz Adamczykc6c68e0c0d4f
diff --git a/docs/plans/6.0-delivery-zones.md b/docs/plans/6.0-delivery-zones.mdindex 3705dadfce..0e8806d153 100644--- a/docs/plans/6.0-delivery-zones.md+++ b/docs/plans/6.0-delivery-zones.md@@ -1,10 +1,10 @@# Delivery Zones (Zone → DeliveryZone)-**Status:** Phases A and B shipped, C mostly shipped; `Spree::Zone` removal (Phase D) blocked on the tax provider — see "Implementation status"+**Status:** Phases A and B shipped, C mostly shipped; `Spree::Zone` removal (Phase D) unblocked on the tax side as of 2026-08-07 — see "Implementation status"**Target:** Spree 6.0-**Depends on:** `6.0-tax-provider.md` Phase 5 (tax decoupled from Zone — prerequisite for dropping the model; **not yet shipped, this is the live blocker**), `6.0-fulfillment-and-delivery.md` Phase 1 (`spree_delivery_method_zones` born pointing at DeliveryZone — **shipped**). Coordinates with: `6.0-delivery-rate-provider.md` (the Estimator's zone check swaps to DeliveryZone matching; provider interface unaffected).+**Depends on:** `6.0-tax-provider.md` Phase 5 (tax decoupled from Zone — prerequisite for dropping the model; **cleared 2026-08-07**, see below), `6.0-fulfillment-and-delivery.md` Phase 1 (`spree_delivery_method_zones` born pointing at DeliveryZone — **shipped**). Coordinates with: `6.0-delivery-rate-provider.md` (the Estimator's zone check swaps to DeliveryZone matching; provider interface unaffected).**Author:** Damian + Claude-**Last updated:** 2026-08-05+**Last updated:** 2026-08-07## Summary@@ -20,7 +20,19 @@ Postal-code zones unlock what Zone structurally cannot express: "free local deli**Remaining, unblocked (this plan's own consumers):** permission sets (`default_customer`, `configuration_management`) still grant on `Spree::Zone`; `Spree::Seeds::Zones` still exists; and the test-support surface still carries the `Zone.global` monkey-patch in `factories.rb`, `zone_factory`, `zone_member_factory`, the `GlobalZone` lookup used by `shipping_method_factory`, and `order_walkthrough`.-**Remaining, blocked on `6.0-tax-provider.md` Phase 5:** `Spree::Current.zone` → `tax_country`, the `Pricing::Context` zone dimension, and the tax-side readers (`TaxRate`, `Market#tax_zone`, `VatPriceCalculation`, `Purchase::Taxation`, `controller_helpers/store`). Phase D — dropping `spree_zones`/`spree_zone_members`, the `Zone`/`ZoneMember` models and `Country#zones`/`State#zones` — cannot start until both of the above are clear. `Spree::Zone` still has roughly eighteen non-spec consumer files today.+Two more surfaced when tax let go of Zone (2026-08-07), both needing a decision here:++- **`Zone#default_tax` is now a writable no-op.** Nothing reads the flag, yet `Spree::Zone` still enforces the single-default invariant on save, `permitted_attributes.rb` still permits it, and `en.yml` still ships "Default Tax"/"Default Tax Zone" labels. A merchant can keep flipping a setting that does nothing. Drop the column with the model, or sooner.+- **Both upgrade tasks name `Spree::Zone`/`Spree::ZoneMember`/`Spree::State` constants.** `spree:migrate_tax_zones` and `spree:migrate_zones_to_delivery_zones` are 5.6→6.0 manifest steps that run *after* `db:migrate`, so they must outlive the models they read. Phase D breaks both unless they first move to anonymous-AR readers over the surviving tables — the precedent is `Spree::ReturnsMigrator`, which does exactly this for the same reason.++**Cleared 2026-08-07 by `6.0-tax-provider.md` Phase 5:** `Spree::Current.zone`/`default_tax_zone` → `Spree::Current.tax_country`, `Market#tax_zone`, `Zone.default_tax`, `Purchase::Taxation#tax_zone` (plus its `LineItem` delegate and `Order::MEMOIZED_METHODS` entry), `VatPriceCalculation`, `Stock::Estimator#taxation_options_for` and `controller_helpers/store`. No shipped code reads a Zone for tax or pricing purposes any more.++The `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.++Phase D — dropping `spree_zones`/`spree_zone_members`, the `Zone`/`ZoneMember` models and `Country#zones`/`State#zones` — is now unblocked on the tax side.## Key Decisions (do not deviate without discussion)@@ -28,7 +40,7 @@ Postal-code zones unlock what Zone structurally cannot express: "free local deli- **Postal matching is prefix-or-range, always country-scoped** (resolved 2026-07-27). Numeric-format countries (US, DE, PL, FR…) support lexicographic ranges on normalized codes (strip spaces/dashes, upcase); ranges are **gated by a numeric-postal country allowlist** — validation rejects range members for countries outside it. Non-numeric formats (UK, CA, NL, IE) get **prefix lists only** (`SW1`, `EC`, `M5V` — how merchants actually think there; UK outward codes and CA FSAs are inherently prefix-shaped). No per-country matcher strategies and no glob wildcards at launch: `DeliveryZoneMember#match?(address)` is one Ruby method with normalization in one place (`Spree::Address#normalized_zipcode`), so per-country matchers can be layered in later with zero schema change if real demand appears.- **Empty zone list on a DeliveryMethod = worldwide** (unchanged semantics from today's zone-less methods).- **`Spree::Zone` and `Spree::ZoneMember` are dropped in 6.0** — tables, models, `Country#zones`/`State#zones`, admin CRUD, factories. Nothing may keep a Zone reference past this plan's final phase.-- **`Spree::Current.zone` / `Pricing::Context` lose the zone dimension.** The browsing tax context becomes market/country-based (`Market#default_country` + `TaxRate.for_address`), per `6.0-tax-provider.md`. `Spree::Current.tax_country` (ISO) replaces `Spree::Current.zone` as the request-context attribute; `Pricing::Context` keys on country, not zone.+- **`Spree::Current.zone` / `Pricing::Context` lose the zone dimension.** The browsing tax context becomes market/country-based (`Market#default_country` + `TaxRate.for_address`), per `6.0-tax-provider.md`. `Spree::Current.tax_country` replaces `Spree::Current.zone` as the request-context attribute — a `Spree::Country`, not an ISO code, matching `Purchase::Taxation#tax_country` (shipped 2026-08-07); `Pricing::Context` keys on country, not zone.- **`Zone.global` factory pattern is retired.** The `factories.rb` monkey-patch and `shipping_method_factory`'s `zones { [Spree::Zone.global] }` are replaced by zone-less methods (worldwide by default) — most specs don't care about geography; the few that do build an explicit `:delivery_zone`.## Design Details@@ -79,7 +91,7 @@ Verified 2026-07-27 (~183 non-spec references: core/app 109, core/lib 37, admin/|---|---|| `TaxRate` zone FK, `TaxRate.match`, tax display readers (`Order#tax_zone`, `Spree::Current.zone`/`default_tax_zone`, `Market#tax_zone`, `VatPriceCalculation` taxation options, `Stock::Estimator#taxation_options_for`/`first_tax_rate_for`) | `6.0-tax-provider.md` Phase 5 (rewritten onto `TaxRate.for_address` / `Spree::Current.tax_country`) || `ShippingMethod has_many :zones`, `#include?`, `spree_shipping_method_zones` | **This plan** (join re-pointed to DeliveryZone; born correct if fulfillment Phase 1 lands first) |-| `Spree::Pricing::Context` zone dimension, `Spree::Current` zone attribute + resets | **This plan** (country-based, with tax-provider) |+| `Spree::Pricing::Context` zone dimension, `Spree::Current` zone attribute + resets | ~~This plan~~ — **shipped by `6.0-tax-provider.md` Phase 5** (2026-08-07), forced by the removal of `Order#tax_zone` || Admin `zones_controller` + views, `@available_zones` in shipping-method form, nav/table registry entries | **This plan** (replaced by DeliveryZones CRUD + picker) || Permission sets (`default_customer`, `configuration_management`) | **This plan** || `Country#zones` / `State#zones` / `ZoneMember` | **This plan** (removed) |@@ -102,7 +114,7 @@ For each Zone referenced by a shipping/delivery method: create a DeliveryZone wiAdmin API v3 delivery-zone CRUD (+ nested on delivery method) with admin-sdk resource and a **React dashboard** page under delivery settings (zone list + typed-member editor incl. postal ranges/prefixes; the legacy Rails `zones_controller` + views are deleted with `spree/admin` at 6.0, not rebuilt). Estimator/DeliveryMethod matching, `Spree::Current.tax_country` + `Pricing::Context` country key (jointly with tax-provider), `Store#countries_with_shipping_coverage`, permission sets, factories + test support, seeds, type pipeline regeneration.-### Phase D — drop (end of 6.0) — blocked on `6.0-tax-provider.md` Phase 5+### Phase D — drop (end of 6.0)Drop `spree_zones` + `spree_zone_members`, remove `Zone`/`ZoneMember` models, `Country#zones`/`State#zones`, zone factories and the `Zone.global` monkey-patch. Grep-clean: zero `Spree::Zone` references outside the migration task.diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.mdindex d01584a515..32468a46ae 100644--- a/docs/plans/6.0-tax-provider.md+++ b/docs/plans/6.0-tax-provider.md@@ -1,6 +1,6 @@# Tax Provider Interface-**Status:** In progress — the provider seam, `Spree::TaxProvider::Internal` and the `TaxLine` write path shipped to 6-0-dev with the core-rewrite waves (see Current State). **Phases 3, 4 and 5 are in development** (contract enrichment, per-Market selection, commit/void/refund wiring, Zone decoupling). Remaining: Phase 6 (the Avalara reference gem), Phase 7 (exemption certificates, gated on Company) and Phase 8 (the 6.1 cleanup of the schema and bridges 6.0 keeps deliberately).+**Status:** In progress — the provider seam, `Spree::TaxProvider::Internal` and the `TaxLine` write path shipped to 6-0-dev with the core-rewrite waves (see Current State). **Phases 3, 4 and 5 are in development** (contract enrichment, per-Market selection, commit/void/refund wiring, Zone decoupling). Remaining: Phase 6 (the Avalara reference gem), Phase 7 (exemption certificates, gated on Company) and Phase 8 (the 6.1 cleanup of the schema 6.0 keeps deliberately).> **Store binding (2026-07-29):** TaxRate and TaxCategory adopt the every-major-model-carries-a-store_id convention as part of this plan's implementation (`Spree::SingleStoreResource`, backfill task, NOT NULL in 6.1) — same treatment DeliveryMethod/StockLocation/DeliveryZone received on the 6.0 core-rewrite branch.@@ -13,7 +13,7 @@**Target:** Spree 6.0**Depends on:** Split Adjustments (6.0-6.1-split-adjustments.md — shipped; provides TaxLine). Phase 7 (exemption certificates) and the Company link in the tax-identifier chain are gated on the B2B plan (6.1-channels-catalogs-b2b.md); nothing in Phases 3–6 waits on it.**Author:** Damian + Claude-**Last updated:** 2026-08-05+**Last updated:** 2026-08-07## Summary@@ -96,7 +96,7 @@ Provider (order lifecycle)| What exists | Where | What it does ||---|---|---|| `Spree::TaxProvider::Base` | `core/app/models/spree/tax_provider/base.rb` | Contract: `estimate(owner, items = nil)`, `commit(owner)`, `void(owner)`, `refund(owner, amount)`, `exempt?(owner)` (stub, uncalled — removed by this revision) |-| `Spree::TaxProvider::Internal` | `core/app/models/spree/tax_provider/internal.rb` | Computes rate × discounted basis directly from TaxRate rows (VAT included-in-price math backed out of gross); replace-all `delete_all` per estimate; writes snapshot columns; preserves `pre_tax_amount`; **still Zone-based** (`TaxRate.match(owner.tax_zone)`); skips zero amounts (changed by this revision) |+| `Spree::TaxProvider::Internal` | `core/app/models/spree/tax_provider/internal.rb` | Computes rate × discounted basis directly from TaxRate rows (VAT included-in-price math backed out of gross); replace-all `delete_all` per estimate; writes snapshot columns; preserves `pre_tax_amount`; matches on the taxing jurisdiction (`TaxRate.for_jurisdiction`), not a Zone; skips zero amounts (changed by this revision) || `Spree.default_tax_provider` | `core/lib/spree/core.rb` | Returns the globally configured fallback **class** (default Internal); callers say `.new`. Renamed from `Spree.tax_provider`, which returned an instance and implied it was the only provider — selection is per-market, through `Spree::Purchase::Taxation#tax_provider` || `Spree::TaxLine` | `core/app/models/spree/tax_line.rb` + `spree_tax_lines` | Typed adjustment row: dual-FK cart/order owner, exactly-one adjustable (line item / fulfillment / fee), `amount`, `rate` + `label` + `provider_id` snapshots, `included`, `data` + `metadata` JSON || Order-level money freeze | `core/app/workflows/spree/carts/recalculate_totals.rb` | `money_frozen?` (completed order) skips `regenerate_typed_rows` — no adjusters, no estimate; `fold_typed_rows` always re-sums totals from rows |@@ -107,7 +107,7 @@ Provider (order lifecycle)Fees are taxable items (beyond the original line-items-plus-shipments scope): items without a tax category are taxed with the default tax category's rates.-Not shipped: per-market selection (`Market` has only the Zone-based `tax_zone` reader), commit/void/refund callers, the exemption input, buyer tax identity, Phase 5 Zone decoupling, the Avalara gem, `TaxExemptionCertificate`.+Not shipped at the time this section was written: per-market selection, commit/void/refund callers, the exemption input, buyer tax identity, Phase 5 Zone decoupling, the Avalara gem, `TaxExemptionCertificate`. All but the last two are in development on the current branch.### Key flow today@@ -493,7 +493,7 @@ scope :for_address, ->(address) {}```-State-level rates override country-level (more specific wins). **Tax stops using Zone; the Zone model itself survives 6.0** — a data migration converts Zone records used by TaxRate into direct country/state FKs, no code reads `zone_id` on TaxRate any more, and the generic `Spree::Zone` stays for the request-context surface (`Spree::Current.zone`, `Market#tax_zone`, factories). Full Zone removal gets its own future plan with a complete consumer inventory.+State-level rates override country-level (more specific wins). **Tax stops using Zone** — a data migration converts Zone records used by TaxRate into direct country/state FKs, and no code reads `zone_id` on TaxRate any more. The request-context readers went too (`Spree::Current.zone`/`default_tax_zone`, `Market#tax_zone`, `Purchase::Taxation#tax_zone`), replaced by `Spree::Current.tax_country`; `spree_tax_rates.zone_id` stays as the conversion source until Phase 8. Dropping the `Spree::Zone` model itself belongs to `6.0-delivery-zones.md`, which owns the full consumer inventory and does it inside 6.0.**`spree_tax_rates.zone_id` is dropped in 6.1, not 6.0.** The column is what `spree:migrate_tax_zones` converts *from*, and the manifest runs after `db:migrate` — so a migration dropping it in the same release would destroy the conversion's own input, and leave no rollback source if a merchant needs to re-run it. 6.0 therefore severs every reader (the `belongs_to :zone`, the zone scopes, and `Zone#has_many :tax_rates`, whose `dependent: :destroy` would otherwise delete live rates when a shipping zone is destroyed) and leaves the column in place, unread. This matches how `spree_adjustments` is handled by `migrate_adjustments_to_typed_rows`. **Phase 8** drops the column alongside the other converted-away schema.@@ -1047,7 +1047,16 @@ Tax-side only — shipping keeps Zone untouched; full Zone removal is deferred t- Add `country_id`/`state_id` to `spree_tax_rates`; run the data task; sever every `zone_id` reader.The column itself is dropped in **Phase 8**, not here — the conversion cannot drop its own input.- Update the `/admin/tax_rates` serializer, permitted params and Ransack allowlist from `zone_id` to `country_id`/`state_id` — the only rework those endpoints take, and the reason they are worth building in Phase 3 rather than waiting.-- Rewrite the tax-side zone readers against `TaxRate.for_address`: `Order#tax_zone`, `Spree::Current.zone`/`default_tax_zone`, `Market#tax_zone` — these feed pre-address tax display and Estimator VAT options, so they move to the provider/`for_address` path rather than being deleted.+- Retire the tax-side zone readers rather than rewriting them: `Order#tax_zone`,+ `Spree::Current.zone`/`default_tax_zone`, `Market#tax_zone` and `Zone.default_tax` all answered+ "where is this buyer taxed", which `#tax_country` now answers directly. `Spree::Current.tax_country`+ replaces the request attribute, per the ownership table in `6.0-delivery-zones.md`.+- **`Spree::Pricing::Context` keys on country, not zone** — nominally that plan's row, but it cannot+ be deferred: `Context.from_order` reads `order.tax_zone`, so it breaks the moment this phase+ removes it. `PriceRules::ZoneRule` comes with it, deciding by country and keeping its class name+ because the `type` column persists it; the same data task restates its stored zones as countries.+ Whether that rule deserves promoting to a first-class country rule is the delivery-zones plan's+ call, not this one's — it stays out of the rule registry either way.- **Re-point whatever populates `DeliveryRate#tax_rate`.** The Estimator matches that rate through the Zone path this phase removes, so it must move to `for_address` to keep working. Mechanical only — preserving current behavior here does not require answering Open Question 1, though this is the natural moment to.- `spree_zones`/`spree_zone_members` are **not** dropped in 6.0, and neither is`spree_tax_rates.zone_id` (Phase 8).@@ -1138,7 +1147,7 @@ endAlso in this phase: `has_many :tax_exemption_certificates` on Company, admin API CRUD for certificates, and the admin surface for uploading and verifying them.-### Phase 8: 6.1 cleanup — the schema and bridges 6.0 deliberately kept+### Phase 8: 6.1 cleanup — the schema 6.0 deliberately kept**Ships in 6.1, never inside 6.0.** Every item here needs a release boundary for one of tworeasons: a 6.0 install may not have run its data task yet, or a third party may still be passing@@ -1154,16 +1163,10 @@ manifest, so every install arriving at 6.1 has run them.2. **`null: false` on `spree_tax_rates.store_id` and `spree_tax_categories.store_id`** — thestore-binding convention's second half, matching DeliveryMethod and StockLocation. Presenceis model-enforced from 6.0; the constraint waits for the backfill to have run everywhere.-3. **Remove the two tax-zone bridges,** which exist so a host app or extension still passing- `tax_zone:` keeps working for one release:- - `Spree::VatPriceCalculation#country_from`'s `price_options[:tax_zone]` branch, which reads- the first country off a zone.- - `Stock::Estimator#taxation_options_for`'s `tax_zone:` key, redundant beside `address:`.- Removing them makes `country`/`address` the only accepted shape.-4. **Drop the vestigial `tax_rates` slot from the `SpreeCalculators` struct.** Tax has had no+3. **Drop the vestigial `tax_rates` slot from the `SpreeCalculators` struct.** Tax has had nocalculator since `Calculator::DefaultTax` was removed; the slot is a public-ish constant, soit gets a boundary rather than a silent edit.-5. **Decide `Market#tax_inclusive`.** A dead boolean with no reader in `app/` that the API still+4. **Decide `Market#tax_inclusive`.** A dead boolean with no reader in `app/` that the API stillserializes and permits. 6.0 left it alone deliberately — Internal derivesinclusive-vs-additive per rate from `TaxRate#included_in_price`, which is finer-grained thana market-wide flag. Either wire it for external providers or drop it together with its APIdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 26520b4d98..48837e9316 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,40 @@+## 2026-08-07: The pricing zone dimension ships with the tax provider, but the price-rule design stays with delivery-zones++`6.0-delivery-zones.md`'s ownership table gives the `Pricing::Context` zone+dimension and the `Spree::Current` zone attribute to that plan, "with+tax-provider". It landed in the tax provider work instead, because the two+cannot be separated: `Pricing::Context.from_order` read `order.tax_zone`, so it+broke the moment `Purchase::Taxation#tax_zone` was removed — which the same+table assigns to the tax plan.++`Spree::Current.tax_country` returns a `Spree::Country` rather than the ISO+string that plan's constraints section specified, matching the already-shipped+`Purchase::Taxation#tax_country`. An ISO code would mean a country lookup on+every read, and the price rule compares stored ids.++**Where the line was drawn.** `PriceRules::ZoneRule` also reads the zone+dimension, so it had to change or crash. It now decides by country, keeps its+class name (the `type` column persists it), stays out of the rule registry, and+`spree:migrate_tax_zones` restates each row's stored zones as the countries they+contained — state-level zones widen to the whole country, which the task+reports. What was **not** done: promoting it to a first-class `CountryRule` with+a factory and a registry entry. That is a customer-visible pricing feature no+plan called for, and it belongs to the plan that owns Zone's removal.++**Constraint going forward:** "something must change or it crashes" licenses the+minimum that keeps it working, not a redesign. When a forced edit reaches into+another plan's surface, do the minimum and hand the design decision back in that+plan's own document.++**Corollary (2026-08-07).** The same reasoning ruled out guarding the window+between `db:migrate` and the data task. A review found that an unconverted rule+matches every country, and the first fix made such a row refuse to apply. That+was also scope creep: the 6.0 data tasks are steps in the upgrade manifest, so+"code deployed, task not yet run" is not a state Spree supports, and inventing+behaviour for it adds a permanent branch to a hot path to cover a transient.+Don't design for half-upgraded installs; make the task correct and say what it+did.+## 2026-08-06: A product type's `required` custom field is advisory — no server-side enforcementReverses the "enforced at activation" position taken earlier the same daydiff --git a/spree/core/app/models/concerns/spree/purchase/taxation.rb b/spree/core/app/models/concerns/spree/purchase/taxation.rbindex bffc4e6f00..dd1afcfc78 100644--- a/spree/core/app/models/concerns/spree/purchase/taxation.rb+++ b/spree/core/app/models/concerns/spree/purchase/taxation.rb@@ -10,11 +10,6 @@ module SpreeSpree::Config[:tax_using_ship_address] ? ship_address : bill_addressend- # @return [Spree::Zone, nil]- def tax_zone- @tax_zone ||= Spree::Zone.match(tax_address) || Spree::Zone.default_tax- end-# The country whose tax applies. Before the customer enters an address# that is the market's own country, which is what lets a storefront show# tax-inclusive prices from the first page view.diff --git a/spree/core/app/models/concerns/spree/vat_price_calculation.rb b/spree/core/app/models/concerns/spree/vat_price_calculation.rbindex dc254979a9..2fef336a8b 100644--- a/spree/core/app/models/concerns/spree/vat_price_calculation.rb+++ b/spree/core/app/models/concerns/spree/vat_price_calculation.rb@@ -31,8 +31,7 @@ module Spreeamount * (1 + foreign_vat(price_options))end- # Whether the price has to be restated at all. The zone in price_options is- # the browsing context's; what matters for tax is the country behind it.+ # Whether the price has to be restated at all.def outside_default_vat_zone?(price_options)country = country_from(price_options)@@ -44,20 +43,24 @@ module Spreeif price_options[:address]lookup[:address] = price_options[:address]else- lookup[:country] = price_options[:country] || country_from(price_options)+ lookup[:country] = country_from(price_options)endSpree::TaxRate.included_tax_amount_for(lookup).to_fend+ # +current_price_options+ is documented as an override point, so an app may+ # still be handing us the pre-6.0 zone. Say so instead of quietly reporting+ # no country, which would leave a foreign customer looking at home VAT.def country_from(price_options)- return price_options[:country] if price_options[:country]- return price_options[:address].country if price_options[:address]+ if price_options[:tax_zone].present? && price_options[:country].blank? && price_options[:address].blank?+ Spree::Deprecation.warn(+ 'Passing tax_zone: in price options no longer determines tax and is ignored. ' \+ 'Pass country: (a Spree::Country) or address: instead.'+ )+ end- # A zone can span several countries; its own country list is the only- # thing to read, and a single-country zone is the case that matters here.- zone = price_options[:tax_zone]- zone&.countries&.first+ price_options[:country] || price_options[:address]&.countryend# The country whose VAT the catalogue prices already include. Deliberatelydiff --git a/spree/core/app/models/spree/current.rb b/spree/core/app/models/spree/current.rbindex 844358b775..a959d16582 100644--- a/spree/core/app/models/spree/current.rb+++ b/spree/core/app/models/spree/current.rb@@ -4,9 +4,7 @@ module Spree# All attributes are automatically reset between requests by Rails.# Fallback chains ensure sensible defaults when attributes are not explicitly set.class Current < ::ActiveSupport::CurrentAttributes- attribute :store, :channel, :market, :currency, :locale, :content_locale, :zone, :default_tax_zone, :price_lists, :global_pricing_context-- resets { @default_tax_zone_loaded = false }+ attribute :store, :channel, :market, :currency, :locale, :content_locale, :tax_country, :price_lists, :global_pricing_context# Returns the current store, falling back to the default store.# @return [Spree::Store]@@ -49,21 +47,17 @@ module Spreesuper.presence || I18n.default_locale.nameend- # Returns the current tax zone.- # Fallback: market's tax zone (from default country) -> global default tax zone.- # @return [Spree::Zone, nil]- def zone- super || market&.tax_zone || default_tax_zone- end-- # Returns the default tax zone (memoized per request).- # @return [Spree::Zone, nil]- def default_tax_zone- result = super- return result if result || @default_tax_zone_loaded-- @default_tax_zone_loaded = true- self.default_tax_zone = Spree::Zone.find_by(default_tax: true)+ # The country whose tax applies while browsing, before any address exists.+ # Fallback: the market being browsed -> the store's own country. An order+ # in hand answers this better (Spree::Purchase::Taxation#tax_country reads+ # its address first); this is the storefront's answer without one.+ #+ # Assigns the resolved country the way #channel does, because the fallback+ # costs a query: a product listing builds one pricing context per variant,+ # and each would otherwise re-ask the market for its default country.+ # @return [Spree::Country, nil]+ def tax_country+ super || (self.tax_country = market&.default_country || store&.default_country)end# Returns the current price lists for the global pricing context.@@ -75,14 +69,14 @@ module Spreeendend- # Returns the current global pricing context, built from store, currency, zone, and market.+ # Returns the current global pricing context, built from store, currency, country, and market.# @return [Spree::Pricing::Context]def global_pricing_contextsuper || beginself.global_pricing_context = Spree::Pricing::Context.new(currency: currency,store: store,- zone: zone,+ country: tax_country,market: market,channel: channel)diff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rbindex 7fe158f6a2..4c69cc6b77 100644--- a/spree/core/app/models/spree/line_item.rb+++ b/spree/core/app/models/spree/line_item.rb@@ -71,7 +71,6 @@ module Spreedef thumbnailvariant.primary_media || product.primary_mediaend- delegate :tax_zone, to: :ownerdelegate :digital?, :can_supply?, to: :variantscope :with_digital_assets, -> { joins(:variant).merge(Spree::Variant.with_digital_assets) }diff --git a/spree/core/app/models/spree/market.rb b/spree/core/app/models/spree/market.rbindex ef3b37b8b5..1064adfa22 100644--- a/spree/core/app/models/spree/market.rb+++ b/spree/core/app/models/spree/market.rb@@ -93,14 +93,6 @@ module Spreecountries.order(:name).firstend- # Returns the tax zone matching this market's default country.- # Used by Spree::Current to determine the browsing tax zone before a customer enters an address.- #- # @return [Spree::Zone, nil]- def tax_zone- @tax_zone ||= Spree::Zone.match(default_country)- end-# The tax engine that computes for this market. A fresh instance per call:# providers are stateless and argless, so the market selects which class# rather than constructing state — everything request-specific arrives as andiff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 8afb1ad8fc..eae767c8c8 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -38,7 +38,6 @@ module Spreeinclude Spree::NumberIdentifierpublishes_lifecycle_events- include Spree::MemoizedDatainclude Spree::Metafieldsinclude Spree::Metadatainclude Spree::Searchable@@ -52,8 +51,6 @@ module Spreehas_secure_token :token, length: 35has_rich_text :internal_note- MEMOIZED_METHODS = %w(tax_zone)-money_methods :outstanding_balance, :item_total, :adjustment_total,:included_tax_total, :additional_tax_total, :tax_total,:delivery_total, :discount_total, :total,diff --git a/spree/core/app/models/spree/price_rules/zone_rule.rb b/spree/core/app/models/spree/price_rules/zone_rule.rbindex 9d9b40230a..b6d5f97003 100644--- a/spree/core/app/models/spree/price_rules/zone_rule.rb+++ b/spree/core/app/models/spree/price_rules/zone_rule.rb@@ -1,18 +1,33 @@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.class ZoneRule < Spree::PriceRule- preference :zone_ids, :array, default: []+ # Stored as raw IDs. Accepts prefixed IDs from API callers and decodes+ # them on write, so eligibility compares against raw country_id rows.+ # Countries are global reference data, so unlike MarketRule there is no+ # store scope to confine the existence check to.+ preference :country_ids, :array, default: [],+ parse_on_set: normalize_id_preference(klass: Spree::Country)def applicable?(context)- return false unless context.zone- return true if preferred_zone_ids.empty?+ return false unless context.country+ return true if preferred_country_ids.empty?# Compare as strings to support both integer and UUID primary keys- preferred_zone_ids.map(&:to_s).include?(context.zone.id.to_s)+ preferred_country_ids.map(&:to_s).include?(context.country.id.to_s)enddef self.description- 'Apply pricing based on the tax/shipping zone'+ 'Apply pricing based on the destination country'endendenddiff --git a/spree/core/app/models/spree/stock/estimator.rb b/spree/core/app/models/spree/stock/estimator.rbindex a284be0def..661e01fa1e 100644--- a/spree/core/app/models/spree/stock/estimator.rb+++ b/spree/core/app/models/spree/stock/estimator.rb@@ -58,7 +58,7 @@ module Spree{tax_category: delivery_method.tax_category,address: @order.tax_address,- tax_zone: @order.tax_zone+ country: @order.tax_country}enddiff --git a/spree/core/app/models/spree/zone.rb b/spree/core/app/models/spree/zone.rbindex 53bab7d2af..29fb658e45 100644--- a/spree/core/app/models/spree/zone.rb+++ b/spree/core/app/models/spree/zone.rb@@ -22,10 +22,6 @@ module Spreeself.whitelisted_ransackable_attributes = ['description']- def self.default_tax- Spree::Current.default_tax_zone- end-def self.potential_matching_zones(zone)if zone.country?# Match zones of the same kind with similar countriesdiff --git a/spree/core/lib/spree/core/controller_helpers/store.rb b/spree/core/lib/spree/core/controller_helpers/store.rbindex fff6881aad..f323a19f92 100644--- a/spree/core/lib/spree/core/controller_helpers/store.rb+++ b/spree/core/lib/spree/core/controller_helpers/store.rb@@ -37,8 +37,8 @@ module Spree# Return a Hash of things that influence the prices displayed in your shop.#- # By default, the only thing that influences prices that is the current order's +tax_zone+- # (to facilitate differing prices depending on VAT rate for digital products in Europe, see+ # By default, the only thing that influences prices is the country whose tax applies (to+ # facilitate differing prices depending on VAT rate for digital products in Europe, see# https://github.com/spree/spree/pull/6295 and https://github.com/spree/spree/pull/6662).## If your prices depend on something else, overwrite this method and add@@ -52,17 +52,17 @@ module Spree#def current_price_options{- tax_zone: current_tax_zone+ country: current_tax_country}endprivate- def current_tax_zone- @current_tax_zone ||= begin- zone = @current_order&.tax_zone || Spree::Zone.default_tax- Spree::Current.zone = zone- zone+ def current_tax_country+ @current_tax_country ||= begin+ country = @current_order&.tax_country || Spree::Current.tax_country+ Spree::Current.tax_country = country+ countryendenddiff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rbindex ce7a27a060..6e2dd050c8 100644--- a/spree/core/lib/spree/core/engine.rb+++ b/spree/core/lib/spree/core/engine.rb@@ -249,11 +249,11 @@ module Spree# Default registry. MarketRule is included so existing installs# don't lose access to saved rule rows in the admin. ZoneRule is- # intentionally excluded — Zones are being removed in 6.0 (see- # docs/plans/6.0-tax-provider.md) and we don't want to invest- # in admin UI for a model on its way out. The class itself- # stays so legacy data continues to load; it just doesn't show- # up in the "Add rule" picker.+ # 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".Rails.application.config.spree.pricing.rules.concat [Spree::PriceRules::UserRule,Spree::PriceRules::CustomerGroupRule,diff --git a/spree/core/lib/spree/core/pricing/context.rb b/spree/core/lib/spree/core/pricing/context.rbindex a4dac72b24..ae8a0d0dc7 100644--- a/spree/core/lib/spree/core/pricing/context.rb+++ b/spree/core/lib/spree/core/pricing/context.rb@@ -1,24 +1,24 @@module Spreemodule Pricingclass Context- attr_reader :variant, :currency, :store, :zone, :market, :channel, :user, :quantity, :date, :order+ attr_reader :variant, :currency, :store, :country, :market, :channel, :user, :quantity, :date, :order# Initializes the context# @param variant [Spree::Variant]# @param currency [String]# @param store [Spree::Store]- # @param zone [Spree::Zone]+ # @param country [Spree::Country] where the buyer is taxed# @param market [Spree::Market]# @param channel [Spree::Channel]# @param user [Spree::User]# @param quantity [Integer]# @param date [Time]# @param order [Spree::Order]- def initialize(variant: nil, currency:, store: nil, zone: nil, market: nil, channel: nil, user: nil, quantity: nil, date: nil, order: nil)+ def initialize(variant: nil, currency:, store: nil, country: nil, market: nil, channel: nil, user: nil, quantity: nil, date: nil, order: nil)@variant = variant@currency = currency@store = store || Spree::Current.store- @zone = zone || Spree::Current.zone+ @country = country || Spree::Current.tax_country@market = market || Spree::Current.market@channel = channel || Spree::Current.channel@user = user@@ -40,7 +40,7 @@ module Spreevariant: variant,currency: order.currency,store: order.store,- zone: order.tax_zone || Spree::Zone.default_tax,+ country: order.tax_country,channel: order.channel,user: order.user,quantity: quantity || order.line_items.find_by(variant: variant)&.quantity,@@ -57,7 +57,7 @@ module Spreevariant.id,currency,store&.id,- zone&.id,+ country&.id,market&.id,channel&.id,user&.id,diff --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 8e2a12507c..8e53ae1857 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@@ -4,11 +4,11 @@ FactoryBot.define dofactory :zone_price_rule, class: Spree::PriceRules::ZoneRule doafter(:build) do |rule, evaluator|- rule.preferred_zone_ids = evaluator.zone_ids if evaluator.respond_to?(:zone_ids)+ rule.preferred_country_ids = evaluator.country_ids if evaluator.respond_to?(:country_ids)endtransient do- zone_ids { [] }+ country_ids { [] }endenddiff --git a/spree/core/lib/tasks/tax_zones_migration.rake b/spree/core/lib/tasks/tax_zones_migration.rakeindex 9b20f45f85..5c604a3716 100644--- a/spree/core/lib/tasks/tax_zones_migration.rake+++ b/spree/core/lib/tasks/tax_zones_migration.rake@@ -55,5 +55,53 @@ 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 id lists go through their model, so a member pointing at a deleted+ # country or state drops out instead of being written back as a live+ # reference.+ countries_for = lambda do |zone_ids|+ members = Spree::ZoneMember.where(zone_id: zone_ids)+ country_ids = Spree::Country.where(+ id: members.where(zoneable_type: 'Spree::Country').pluck(:zoneable_id)+ ).pluck(:id)+ state_country_ids = Spree::State.where(+ id: members.where(zoneable_type: 'Spree::State').pluck(:zoneable_id)+ ).pluck(:country_id)++ [(country_ids + state_country_ids).uniq.map(&:to_s), state_country_ids.any?]+ end++ rules_converted = 0+ rules_widened = 0+ rules_unrestricted = 0++ Spree::PriceRules::ZoneRule.find_each do |rule|+ stored = rule.preferences.with_indifferent_access+ zone_ids = Array(stored[:zone_ids]).reject(&:blank?)+ next if stored[:country_ids].present? || zone_ids.empty?++ country_ids, from_states = countries_for.call(zone_ids)+ rule.update_columns(+ preferences: stored.except(:zone_ids).merge(country_ids: country_ids).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_ids.empty?+ end++ 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.'+ endendenddiff --git a/spree/core/spec/lib/spree/core/controller_helpers/store_spec.rb b/spree/core/spec/lib/spree/core/controller_helpers/store_spec.rbindex a28bc31b6e..99430ac37a 100644--- a/spree/core/spec/lib/spree/core/controller_helpers/store_spec.rb+++ b/spree/core/spec/lib/spree/core/controller_helpers/store_spec.rb@@ -110,76 +110,44 @@ describe Spree::Core::ControllerHelpers::Store, type: :controller doafter { Spree::Current.reset }- context 'when there is a default tax zone' do- let(:default_zone) { Spree::Zone.new }+ context 'without a current order' do+ let(:browsing_country) { create(:country) }- before do- allow(Spree::Zone).to receive(:default_tax).and_return(default_zone)- end+ it 'falls back to the browsing context' do+ Spree::Current.tax_country = browsing_country- context 'when there is no current order' do- it 'returns the default tax zone' do- expect(subject).to include(tax_zone: default_zone)- end-- it 'sets Spree::Current.zone to the default tax zone' do- subject- expect(Spree::Current.zone).to eq(default_zone)- end+ expect(subject).to include(country: browsing_country)end- context 'when there is a current order' do- let(:other_zone) { Spree::Zone.new }- let(:current_order) { Spree::Order.new }-- before do- allow(current_order).to receive(:tax_zone).and_return(other_zone)- allow(controller).to receive(:current_order).and_return(current_order)- controller.instance_variable_set(:@current_order, current_order)- end+ # The resolved country is written back so everything later in the request+ # prices against the same one.+ it 'resolves and publishes the store country when nothing is set yet' do+ expect(subject[:country]).to eq(Spree::Store.default.default_country)+ expect(Spree::Current.attributes[:tax_country]).to eq(subject[:country])+ end- it { is_expected.to include(tax_zone: other_zone) }+ it 'reports no country when there is none to resolve' do+ allow(Spree::Current).to receive(:tax_country).and_return(nil)- it 'sets Spree::Current.zone to the order tax zone' do- subject- expect(Spree::Current.zone).to eq(other_zone)- end+ expect(subject).to include(country: nil)endend- context 'when there is no default tax zone' do- before do- allow(Spree::Zone).to receive(:default_tax).and_return(nil)- end-- context 'when there is no current order' do- it 'returns nil when asked for the current tax zone' do- expect(current_price_options[:tax_zone]).to be_nil- end+ context 'with a current order' do+ let(:order_country) { create(:country) }+ let(:current_order) { Spree::Order.new }- it 'sets Spree::Current.zone to nil' do- subject- # Spree::Current.zone will call default_tax again, so we check the attributes hash- expect(Spree::Current.attributes[:zone]).to be_nil- end+ before do+ allow(current_order).to receive(:tax_country).and_return(order_country)+ allow(controller).to receive(:current_order).and_return(current_order)+ controller.instance_variable_set(:@current_order, current_order)end- context 'when there is a current order' do- let(:other_zone) { Spree::Zone.new }- let(:current_order) { Spree::Order.new }+ it { is_expected.to include(country: order_country) }- before do- allow(current_order).to receive(:tax_zone).and_return(other_zone)- allow(controller).to receive(:current_order).and_return(current_order)- controller.instance_variable_set(:@current_order, current_order)- end-- it { is_expected.to include(tax_zone: other_zone) }-- it 'sets Spree::Current.zone to the order tax zone' do- subject- expect(Spree::Current.zone).to eq(other_zone)- end+ it 'publishes the order country to the request context' do+ subject+ expect(Spree::Current.tax_country).to eq(order_country)endendenddiff --git a/spree/core/spec/lib/spree/core/pricing/context_spec.rb b/spree/core/spec/lib/spree/core/pricing/context_spec.rbindex 4395a4b054..da09652a31 100644--- a/spree/core/spec/lib/spree/core/pricing/context_spec.rb+++ b/spree/core/spec/lib/spree/core/pricing/context_spec.rb@@ -6,7 +6,7 @@ module Spreelet(:variant) { create(:variant) }let(:currency) { 'USD' }let(:store) { @default_store }- let(:zone) { create(:zone) }+ let(:country) { create(:country) }let(:market) { create(:market, store: store) }let(:channel) { create(:channel, store: store) }let(:user) { create(:user) }@@ -22,7 +22,7 @@ module Spreevariant: variant,currency: currency,store: store,- zone: zone,+ country: country,market: market,channel: channel,user: user,@@ -35,7 +35,7 @@ module Spreeexpect(subject.variant).to eq(variant)expect(subject.currency).to eq(currency)expect(subject.store).to eq(store)- expect(subject.zone).to eq(zone)+ expect(subject.country).to eq(country)expect(subject.market).to eq(market)expect(subject.channel).to eq(channel)expect(subject.user).to eq(user)@@ -58,8 +58,8 @@ module Spreeexpect(subject.store).to eq(Spree::Current.store)end- it 'defaults zone to Spree::Current.zone' do- expect(subject.zone).to eq(Spree::Current.zone)+ it 'defaults country to Spree::Current.tax_country' do+ expect(subject.country).to eq(Spree::Current.tax_country)endit 'defaults market to Spree::Current.market' do@@ -95,17 +95,17 @@ module Spreeendend- context 'when Spree::Current.zone is set' do- let(:current_zone) { create(:zone) }+ context 'when Spree::Current.tax_country is set' do+ let(:current_country) { create(:country) }- before { Spree::Current.zone = current_zone }+ before { Spree::Current.tax_country = current_country }subject dodescribed_class.new(variant: variant, currency: currency)end- it 'uses Spree::Current.zone as default' do- expect(subject.zone).to eq(current_zone)+ it 'uses Spree::Current.tax_country as default' do+ expect(subject.country).to eq(current_country)endend@@ -180,27 +180,30 @@ module Spreeexpect(subject.quantity).to eq(order_quantity)end- context 'with zone from order tax_zone' do- let(:tax_zone) { create(:zone) }+ context 'with country from order tax_country' do+ let(:tax_country) { create(:country) }before do- allow(order).to receive(:tax_zone).and_return(tax_zone)+ allow(order).to receive(:tax_country).and_return(tax_country)end- it 'sets zone from order tax_zone' do- expect(subject.zone).to eq(tax_zone)+ it 'sets country from order tax_country' do+ expect(subject.country).to eq(tax_country)endend- context 'when order has no tax zone' do- let!(:default_tax_zone) { create(:zone, default_tax: true) }+ context 'when the order has no tax country' do+ let!(:browsing_country) { create(:country, iso: 'PT', name: 'Portugal') }before do- allow(order).to receive(:tax_zone).and_return(nil)+ allow(order).to receive(:tax_country).and_return(nil)+ Spree::Current.tax_country = browsing_countryend- it 'falls back to default tax zone' do- expect(subject.zone).to eq(default_tax_zone)+ after { Spree::Current.reset }++ it 'falls back to the browsing context' do+ expect(subject.country).to eq(browsing_country)endend@@ -232,7 +235,7 @@ module Spreevariant: variant,currency: currency,store: store,- zone: zone,+ country: country,market: market,channel: channel,user: user,@@ -248,7 +251,7 @@ module Spreevariant.id,currency,store.id,- zone.id,+ country.id,market.id,channel.id,user.id,@@ -274,7 +277,7 @@ module Spreecurrency,Spree::Current.store.id]- expected_parts << Spree::Current.zone.id if Spree::Current.zone+ expected_parts << Spree::Current.tax_country.id if Spree::Current.tax_countryexpected_parts << Spree::Current.market.id if Spree::Current.marketexpected_parts << Spree::Current.channel.id if Spree::Current.channelexpected_parts << Time.current.to_i@@ -303,7 +306,7 @@ module Spreecurrency,Spree::Current.store.id]- expected_parts << Spree::Current.zone.id if Spree::Current.zone+ expected_parts << Spree::Current.tax_country.id if Spree::Current.tax_countryexpected_parts << Spree::Current.market.id if Spree::Current.marketexpected_parts << Spree::Current.channel.id if Spree::Current.channelexpected_parts << user.iddiff --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 833f9221c0..d581975ba9 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@@ -195,6 +195,66 @@ describe '6.0 data migration tasks' doexpect { run_task('spree:migrate_tax_zones') }.not_to change(Spree::TaxRate, :count)end++ context '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] })+ end+ end++ it 'restates the zone as the countries it contained' do+ rule = legacy_rule(zone_with(germany, france))++ run_task('spree:migrate_tax_zones')++ expect(rule.reload.preferred_country_ids).to contain_exactly(germany.id.to_s, france.id.to_s)+ 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+ 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_ids).to eq([germany.id.to_s])+ end++ it 'is idempotent over a legacy row' do+ rule = legacy_rule(zone_with(germany))+ run_task('spree:migrate_tax_zones')+ converted = rule.reload.preferred_country_ids++ run_task('spree:migrate_tax_zones')++ expect(rule.reload.preferred_country_ids).to eq(converted)+ expect(rule.reload.preferences).not_to have_key(:zone_ids)+ end++ it 'leaves a rule the merchant already set countries on alone' do+ rule = create(:zone_price_rule, price_list: price_list, country_ids: [france.id])++ run_task('spree:migrate_tax_zones')++ expect(rule.reload.preferred_country_ids).to eq([france.id.to_s])+ 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)++ run_task('spree:migrate_tax_zones')++ expect(rule.reload.preferred_country_ids).to be_empty+ expect(rule.preferences).not_to have_key(:zone_ids)+ end+ endenddescribe 'spree:migrate_zones_to_delivery_zones' dodiff --git a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rbindex 57fd00f07f..75f13d5daa 100644--- a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb+++ b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb@@ -15,78 +15,6 @@ RSpec.shared_examples 'a taxation host' doendend- describe '#tax_zone' do- let(:zone) { create(:zone) }-- context 'when no zones exist' do- it 'returns nil' do- expect(record.tax_zone).to be_nil- end- end-- context 'when tax_using_ship_address: true' do- before { Spree::Config.set(tax_using_ship_address: true) }-- it 'calculates using ship_address' do- expect(Spree::Zone).to receive(:match).at_least(:once).with(ship_address)- expect(Spree::Zone).not_to receive(:match).with(bill_address)- record.tax_zone- end- end-- context 'when tax_using_ship_address: false' do- before { Spree::Config.set(tax_using_ship_address: false) }-- it 'calculates using bill_address' do- expect(Spree::Zone).to receive(:match).at_least(:once).with(bill_address)- expect(Spree::Zone).not_to receive(:match).with(ship_address)- record.tax_zone- end- end-- context 'when there is a default tax zone' do- let!(:default_zone) { create(:zone, name: 'foo_zone') }-- before { allow(Spree::Zone).to receive_messages default_tax: default_zone }-- context 'when there is a matching zone' do- before { allow(Spree::Zone).to receive_messages(match: zone) }-- it 'returns the matching zone' do- expect(record.tax_zone).to eq(zone)- end- end-- context 'when there is no matching zone' do- before { allow(Spree::Zone).to receive_messages(match: nil) }-- it 'returns the default tax zone' do- expect(record.tax_zone).to eq(default_zone)- end- end- end-- context 'when no default tax zone' do- before { allow(Spree::Zone).to receive_messages default_tax: nil }-- context 'when there is a matching zone' do- before { allow(Spree::Zone).to receive_messages(match: zone) }-- it 'returns the matching zone' do- expect(record.tax_zone).to eq(zone)- end- end-- context 'when there is no matching zone' do- before { allow(Spree::Zone).to receive_messages(match: nil) }-- it 'returns nil' do- expect(record.tax_zone).to be_nil- end- end- end- end-describe '#tax_total' doit 'sums included and additional tax' dorecord.included_tax_total = 5diff --git a/spree/core/spec/models/spree/concerns/vat_price_calculation_spec.rb b/spree/core/spec/models/spree/concerns/vat_price_calculation_spec.rbindex 9804ae4681..04b7753908 100644--- a/spree/core/spec/models/spree/concerns/vat_price_calculation_spec.rb+++ b/spree/core/spec/models/spree/concerns/vat_price_calculation_spec.rb@@ -70,22 +70,6 @@ module Spreegross_amountendend-- context 'and the destination came in as a zone' do- let(:price_options) { { tax_zone: zone, tax_category: tax_category } }- let(:zone) do- create(:zone, kind: 'country').tap { |zone| zone.zone_members.create!(zoneable: destination) }- end-- it 'still restates the price, reading the country off the zone' do- create(:tax_rate, country: home_country, tax_category: tax_category, amount: 0.19,- included_in_price: true)- create(:tax_rate, country: destination, tax_category: tax_category, amount: 0.25,- included_in_price: true)-- expect(gross_amount).to eq(105.04)- end- endendendenddiff --git a/spree/core/spec/models/spree/current_spec.rb b/spree/core/spec/models/spree/current_spec.rbindex 780a615f3a..8acba06c6d 100644--- a/spree/core/spec/models/spree/current_spec.rb+++ b/spree/core/spec/models/spree/current_spec.rb@@ -41,74 +41,32 @@ RSpec.describe Spree::Current doendend- describe '#zone' do- context 'when zone is set' do- let(:zone) { create(:zone) }+ describe '#tax_country' do+ context 'when tax_country is set' do+ let(:country) { create(:country) }- before { described_class.zone = zone }+ before { described_class.tax_country = country }- it 'returns the set zone' do- expect(described_class.zone).to eq(zone)+ it 'returns the set country' do+ expect(described_class.tax_country).to eq(country)endend- context 'when zone is not set' do- let!(:default_zone) { create(:zone, default_tax: true) }-- it 'returns the default tax zone' do- expect(described_class.zone).to eq(default_zone)- end- end-- context 'when zone is not set and no default tax zone exists' do- before do- Spree::Zone.update_all(default_tax: false)- end-- it 'returns nil' do- expect(described_class.zone).to be_nil- end- end- end-- describe '#default_tax_zone' do- context 'when default_tax_zone is explicitly set' do- let(:zone) { create(:zone) }-- before { described_class.default_tax_zone = zone }-- it 'returns the set zone' do- expect(described_class.default_tax_zone).to eq(zone)- end- end-- context 'when default_tax_zone is not set' do- let!(:default_zone) { create(:zone, default_tax: true) }-- it 'returns the default tax zone from the database' do- expect(described_class.default_tax_zone).to eq(default_zone)- end-- it 'memoizes the result' do- described_class.default_tax_zone-- expect(Spree::Zone).not_to receive(:find_by)- described_class.default_tax_zone- end- end+ context 'when tax_country is not set' do+ let!(:store) { create(:store, default: true) }+ let(:market) { create(:market, store: store) }- context 'when no default tax zone exists' do- before { Spree::Zone.update_all(default_tax: false) }+ it 'falls back to the market being browsed' do+ described_class.market = market- it 'returns nil' do- expect(described_class.default_tax_zone).to be_nil+ expect(described_class.tax_country).to eq(market.default_country)end- it 'does not re-query on subsequent calls' do- described_class.default_tax_zone+ it 'falls back to the store country when the market has none' do+ allow(market).to receive(:default_country).and_return(nil)+ described_class.market = market- expect(Spree::Zone).not_to receive(:find_by)- described_class.default_tax_zone+ expect(described_class.tax_country).to eq(store.default_country)endendend@@ -203,13 +161,11 @@ RSpec.describe Spree::Current dodescribe '#global_pricing_context' dolet!(:store) { create(:store, default: true, default_currency: 'USD') }- let(:zone) { create(:zone, default_tax: true) }let(:market) { create(:market, store: store) }before dodescribed_class.store = storedescribed_class.currency = 'USD'- described_class.zone = zonedescribed_class.market = marketend@@ -225,8 +181,15 @@ RSpec.describe Spree::Current doexpect(described_class.global_pricing_context.currency).to eq('USD')end- it 'uses the current zone' do- expect(described_class.global_pricing_context.zone).to eq(zone)+ it 'uses the country whose tax applies' do+ described_class.tax_country = create(:country, iso: 'PT', name: 'Portugal')++ expect(described_class.global_pricing_context.country.iso).to eq('PT')+ end++ it 'falls back to the market country when none was set' do+ expect(described_class.global_pricing_context.country).to eq(market.default_country)+ expect(described_class.global_pricing_context.country).to be_presentendit 'uses the current market' do@@ -282,12 +245,12 @@ RSpec.describe Spree::Current dodescribe '.reset' dolet(:store) { create(:store) }- let(:zone) { create(:zone) }+ let(:country) { create(:country) }before dodescribed_class.store = storedescribed_class.currency = 'EUR'- described_class.zone = zone+ described_class.tax_country = countryendit 'resets all attributes' do@@ -300,8 +263,8 @@ RSpec.describe Spree::Current do# Currency falls back to store defaultexpect(described_class.currency).not_to eq('EUR')- # Zone falls back to default tax zone- expect(described_class.zone).not_to eq(zone)+ # Tax country falls back to the store's own+ expect(described_class.tax_country).not_to eq(country)endit 'clears memoized price_lists' do@@ -323,14 +286,5 @@ RSpec.describe Spree::Current do# After reset, global_pricing_context should be fetched freshexpect(described_class.instance_variable_get(:@global_pricing_context)).to be_nilend-- it 'clears memoized default_tax_zone' do- create(:zone, default_tax: true)- described_class.default_tax_zone-- described_class.reset-- expect(described_class.instance.instance_variable_get(:@default_tax_zone_loaded)).to be false- endendenddiff --git a/spree/core/spec/models/spree/price_rules/zone_rule_spec.rb b/spree/core/spec/models/spree/price_rules/zone_rule_spec.rbindex 93eb36ec58..6647fb844b 100644--- a/spree/core/spec/models/spree/price_rules/zone_rule_spec.rb+++ b/spree/core/spec/models/spree/price_rules/zone_rule_spec.rb@@ -3,51 +3,55 @@ require 'spec_helper'describe Spree::PriceRules::ZoneRule, type: :model dolet(:price_list) { create(:price_list) }let(:rule) { create(:zone_price_rule, price_list: price_list) }- let(:zone) { create(:zone) }+ let(:country) { create(:country) }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 zone_ids preference is empty' do- before { rule.preferred_zone_ids = [] }+ context 'when country_ids preference is empty' do+ before { rule.preferred_country_ids = [] }- it 'returns true for any zone' do- context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', zone: zone)- expect(rule.applicable?(context)).to be true+ it 'returns true for any country' do+ expect(rule.applicable?(context_for(country))).to be trueendend- context 'when zone_ids preference is set' do- before { rule.preferred_zone_ids = [zone.id] }+ context 'when country_ids preference is set' do+ before { rule.preferred_country_ids = [country.id] }- it 'returns true when context zone matches' do- context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', zone: zone)- expect(rule.applicable?(context)).to be true+ it 'returns true when the context country matches' do+ expect(rule.applicable?(context_for(country))).to be trueend- it 'returns false when context zone does not match' do- other_zone = create(:zone)- context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', zone: other_zone)- expect(rule.applicable?(context)).to be false+ it 'returns false when the context country does not match' do+ expect(rule.applicable?(context_for(create(:country)))).to be falseend- it 'returns false when context has no zone' do+ # 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_nilexpect(rule.applicable?(context)).to be falseendend- context 'when zone_ids preference contains strings' do- before { rule.preferred_zone_ids = [zone.id.to_s] }+ # UUID primary keys mean an id may arrive as either type.+ context 'when country_ids preference contains strings' do+ before { rule.preferred_country_ids = [country.id.to_s] }- it 'returns true when context zone matches' do- context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', zone: zone)- expect(rule.applicable?(context)).to be true+ it 'returns true when the context country matches' do+ expect(rule.applicable?(context_for(country))).to be trueend- it 'returns false when context zone does not match' do- other_zone = create(:zone)- context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', zone: other_zone)- expect(rule.applicable?(context)).to be false+ it 'returns false when the context country does not match' do+ expect(rule.applicable?(context_for(create(:country)))).to be falseendendenddiff --git a/spree/core/spec/models/spree/stock/estimator_spec.rb b/spree/core/spec/models/spree/stock/estimator_spec.rbindex 0652a3f2ce..7103fcfae2 100644--- a/spree/core/spec/models/spree/stock/estimator_spec.rb+++ b/spree/core/spec/models/spree/stock/estimator_spec.rb@@ -158,11 +158,6 @@ module Spreeendcontext 'includes tax adjustments if applicable' do- let!(:default_tax_zone) do- create(:zone, default_tax: true, kind: 'country').tap do |zone|- zone.zone_members.create!(zoneable: ship_address.country)- end- endlet!(:tax_rate) { create(:tax_rate, country: order.tax_address.country) }before dodiff --git a/spree/core/spec/models/spree/zone_spec.rb b/spree/core/spec/models/spree/zone_spec.rbindex 727a92c005..ae5cef9b3c 100644--- a/spree/core/spec/models/spree/zone_spec.rb+++ b/spree/core/spec/models/spree/zone_spec.rb@@ -147,23 +147,6 @@ describe Spree::Zone, type: :model doendend- context '.default_tax' do- context 'when there is a default tax zone specified' do- before { @foo_zone = create(:zone, name: 'whatever', default_tax: true) }-- it 'is the correct zone' do- create(:zone, name: 'foo')- expect(Spree::Zone.default_tax).to eq(@foo_zone)- end- end-- context 'when there is no default tax zone specified' do- it 'is nil' do- expect(Spree::Zone.default_tax).to be_nil- end- end- end-context '#contains?' dolet(:country1) { create(:country) }let(:country2) { create(:country) }