Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Tax rates name their jurisdiction by code

Łukasz Adamczyka66bad2496dd
diff --git a/CLAUDE.md b/CLAUDE.md
index c6b64174a6..f7716ea791 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -25,7 +25,7 @@ Active plans (6.0 target, work pending):
- `6.0-fulfillment-and-delivery.md` — Shipment→Fulfillment, ShippingMethod→DeliveryMethod, drop ShippingCategory, FulfillmentProvider strategy, pickup (merchant StockLocation) + pickup_point (third-party PickupPointProvider). **Shipped to 6-0-dev (Waves 2+4+6):** renames + deprecated twins, providers (Manual/Digital/Pickup/PickupPoint), dual-emit events, store pickup discovery endpoints, admin delivery_methods/delivery_zones CRUD + dashboard settings pages, FulfillmentMailer; Wave 7 shipping→delivery data migration remains. Pickup work beyond shipped code deferred to 6.1 (2026-08-06): contract hardening (`new(delivery_method)` ctor, `find_nearby` zipcode/query) + how-to guide; `PickupPointProvider::Base` stays **undocumented in 6.0** (v6 docs cover only the delivery rate provider interface) — never add pickup-provider docs in 6.0 work. Delivery mechanics live on provider classes (`pickup_point` provider ships but stays unregistered until 6.1; `local_delivery` cut = shipping + postal-code zone); the string fulfillment-type registry was deleted by `6.0-delivery-profiles.md`. **Partial fulfillment (2026-08-10, resolved question 12):** shipping a subset is `Spree::Fulfillments::Fulfill` (optional per-line-item `items:` + `tracking:` + `notify_customer:`; splits then fulfills in one transaction) — never a state-machine event, since split-then-ship in an `after_transition` is what service-workflows prohibits. **Side effects left the machine (2026-08-10, question 13):** `after_cancel`/`after_resume` are gone as transition callbacks — restock + carrier stand-down live in `Fulfillments::Cancel`/`::Resume` as inline steps (provider call is an `external_step`; `notify_provider: false` lets `Orders::Cancel` delegate and batch carrier I/O after its own transaction), `after_cancel`/`after_resume` are deprecated shells and the only trace left on the model — never add public model methods for workflows to call. **Status model (2026-08-11, question 14): the machine is REMOVED.** `status` = plain `HasStatus` `unfulfilled → fulfilled → delivered | canceled` (`pending`/`ready`/`ready_for_pickup` collapse — payment/stock gating is a `Fulfillments::Fulfill` validate guard, pickup renders modality-aware labels); `delivered` = confirmed receipt (`Fulfillments::MarkDelivered`, `delivered_at`, `fulfillment.delivered`) — the returns window + EU withdrawal anchor; carrier truth is the separate `tracking_status` axis (data, never a machine) written by `Fulfillments::UpdateTracking`, fed by EasyPost tracker webhooks (opt-in trackers for hand-entered numbers). Rollup domain `backorder | canceled | partial | unfulfilled | fulfilled | delivered`. **Phase 7 shipped 2026-08-11** (core + API + dashboard + EasyPost tracker webhook + `spree:migrate_fulfillment_statuses`); **label leads, fulfilled follows (2026-08-12):** `Fulfillments::PurchaseLabel` = explicit pre-ship label buy (loud failure, no email); `Fulfill` buys label BEFORE marking fulfilled (email always carries tracking; post-split failure keeps the split, never rolls it back); providers declare `generates_labels?` + idempotent `create_fulfillment`. **One tracking number per fulfillment (2026-08-11, question 15):** diverging parcels are split fulfillments; a `spree_fulfillment_trackings` model is 6.1 work and must absorb the entire carrier axis (per-row status/`delivered_at`, webhook matching by row) — never split the axis across fulfillment and tracking rows
- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain. **COMPLETE (2026-08-05):** all three entities (+ permanent `ReturnLineItem`/`ExchangeLineItem`/`ClaimLineItem` line items), `Spree::HasStatus`, all fifteen workflows (each with a leading `validate` hook), `Refund#originator`, admin + store v3 APIs (transitions as PATCH member actions; no destroy — cancel instead), dashboard pages. Legacy chain **removed**: ReturnAuthorization/CustomerReturn/Reimbursement/ReimbursementType/legacy ReturnItem + eligibility validators + ReturnsCalculator classes all deleted, but their **tables deliberately survive to 6.1** as the data migration's source and rollback path. `spree:upgrade:migrate_returns` (`Spree::ReturnsMigrator`, defined in the rake file like its sibling upgrade tasks; anonymous-AR readers) is in the 5.6→6.0 manifest after the adjustments step; it needs no cursor because the preserved `number` is uniquely indexed on the new tables, so "what's left" is a `where.not(number: ...)` query and an interrupted run resumes for free. `ReturnAuthorizationReason`→`ReturnReason` (alias one release) + new `ClaimReason`; `Metafields` on all three. Capability replacements: `Spree::ReturnMailer#refunded_email` on `return.refunded` (replaces the reimbursement email), `Order#outstanding_balance` drops the reimbursement term (refunds already net out of `payment_total`), `Return#refunded_total` counts store credits too, `StoreCreditCategory.default_refund_category` (alias kept). **Reasons** ship admin-only CRUD (`/api/v3/admin/{return,claim,refund}_reasons`, `settings` scope) + a combined Settings → Reasons dashboard page + reason pickers on the create dialogs; `mutable` is never client-writable and the immutability guard lives on `Spree::NamedType` (`can_be_deleted?` + rename/destroy guards) because secret API keys authorize by scope and never consult CanCanCan. **No state machines (2026-08-02):** plain `status` string + inclusion validation; all fifteen transitions are workflows (`Returns::Receive`, `Exchanges::Fulfill`, `Claims::Resolve`, …) with `validate` hooks for return-eligibility policy and refunds as `external_step`. Nothing happens in a model or transition callback. Statuses live in a `class_attribute` via the core `Spree::HasStatus` concern (`has_status` + additive `add_status(value, after:)`, generating predicates and scopes) — extensible by design, additive only, and no transition graph (that would be a state machine again). **Return eligibility is a hook, not a policy engine (2026-08-03):** no window/restocking-fee/final-sale flag in core — a `validate` handler decides, enforcing for customers while letting staff override (it reads `created_by`), and region-varying policy reads `order.market`. Medusa/Saleor/Vendure ship no policy at all; Shopify's engine has no API. A `ReturnPolicy` model can arrive later behind the same hook.
- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename (RefreshToken shipped in 5.4)
-- `6.0-tax-provider.md` — Per-Market TaxProvider (market selects the provider, providers stateless/argless; global config class stays as fallback), replaces TaxRate.adjust + Calculator; reference provider: Avalara (decisions.md 2026-07-30). **Shipped to 6-0-dev (core-rewrite waves):** `Spree::TaxProvider::Base`/`Internal` as the sole TaxLine write path, called from `Carts::RecalculateTotals` behind the `money_frozen?` freeze. **Contract refined 2026-08-05 after the spree/spree#14056 review (decisions.md):** TaxLine gains `taxability_reason` + jurisdiction snapshot (e-invoice category/exemption codes derived at invoicing time, never stored); new `Spree::TaxIdentifier` model (customer/cart/order dual-FK, frozen order snapshot; validation via the kind-keyed `Spree.tax_id_validators` registry + async job on the geocoding precedent — NOT a provider method, and no registry client in core); exemptions = typed `estimate` input via `tax_resolve_exemptions_service` (boolean `exempt?` removed, no flags anywhere); explicit `tax_date:`; `refund(order, return_items, tax_date:)`; capability declarations (Internal declares no US local tax / no reverse charge / no one-stop-shop thresholds; `estimate` keeps its no-op return — a structured result + indeterminacy channel deferred as safely additive). **Phases 3-5 in development:** the enriched contract, `Spree::TaxIdentifier` + validator registry, exemption value objects, per-Market selection with commit/void/refund as external steps, and the Zone decoupling (rates carry `country_id`/`state_id`; `spree_tax_rates.zone_id` stays through 6.0 as the conversion source). **Phases 3-5 + the Zone decoupling shipped to `feature/v-3526` (PR #14410).** **Phase 7 is next and no longer gated (2026-08-07):** it pulls the minimal Company tree forward out of the B2B plan — Company → CompanyLocation → CompanyContact, `company_location_id` on both carts and orders, `company_id` as a fourth TaxIdentifier owner, `Spree::TaxExemptionCertificate` hanging off Company scoped by country/state, and the `ResolveExemptions` body; **no `tax_exempt` boolean anywhere** (supersedes the B2B plan's sketches), and Catalog/pricing/visibility stay 6.1. Pending after that: Phase 6 `spree_tax_avalara`, **Phase 8 cross-border pricing with tax-inclusive prices** (2026-08-11 live pass: `Pricing::Context.from_order` never carried the cart's market so market-scoped price lists were unreachable from a cart; `recalculate_for_address_change!` called the non-persisting `update_price`; restatement was applied even to prices set for the destination — the rule is now derive net-fixed unless the winning price list carries a `geographic?` rule, Shopify's model), Phase 9 6.1 cleanup (drop `zone_id`, `null: false` on the tax `store_id`s, decide `Market#tax_inclusive`). Still open: delivery-rate tax display bypasses the provider
+- `6.0-tax-provider.md` — Per-Market TaxProvider (market selects the provider, providers stateless/argless; global config class stays as fallback), replaces TaxRate.adjust + Calculator; reference provider: Avalara (decisions.md 2026-07-30). **Shipped to 6-0-dev (core-rewrite waves):** `Spree::TaxProvider::Base`/`Internal` as the sole TaxLine write path, called from `Carts::RecalculateTotals` behind the `money_frozen?` freeze. **Contract refined 2026-08-05 after the spree/spree#14056 review (decisions.md):** TaxLine gains `taxability_reason` + jurisdiction snapshot (e-invoice category/exemption codes derived at invoicing time, never stored); new `Spree::TaxIdentifier` model (customer/cart/order dual-FK, frozen order snapshot; validation via the kind-keyed `Spree.tax_id_validators` registry + async job on the geocoding precedent — NOT a provider method, and no registry client in core); exemptions = typed `estimate` input via `tax_resolve_exemptions_service` (boolean `exempt?` removed, no flags anywhere); explicit `tax_date:`; `refund(order, return_items, tax_date:)`; capability declarations (Internal declares no US local tax / no reverse charge / no one-stop-shop thresholds; `estimate` keeps its no-op return — a structured result + indeterminacy channel deferred as safely additive). **Phases 3-5 in development:** the enriched contract, `Spree::TaxIdentifier` + validator registry, exemption value objects, per-Market selection with commit/void/refund as external steps, and the Zone decoupling (rates carry `country_iso`/`state_code` — codes, not FKs, since Country/State are being dropped; `spree_tax_rates.zone_id` stays through 6.0 as the conversion source). **Phases 3-5 + the Zone decoupling shipped to `feature/v-3526` (PR #14410).** **Phase 7 is next and no longer gated (2026-08-07):** it pulls the minimal Company tree forward out of the B2B plan — Company → CompanyLocation → CompanyContact, `company_location_id` on both carts and orders, `company_id` as a fourth TaxIdentifier owner, `Spree::TaxExemptionCertificate` hanging off Company scoped by country/state, and the `ResolveExemptions` body; **no `tax_exempt` boolean anywhere** (supersedes the B2B plan's sketches), and Catalog/pricing/visibility stay 6.1. Pending after that: Phase 6 `spree_tax_avalara`, **Phase 8 cross-border pricing with tax-inclusive prices** (2026-08-11 live pass: `Pricing::Context.from_order` never carried the cart's market so market-scoped price lists were unreachable from a cart; `recalculate_for_address_change!` called the non-persisting `update_price`; restatement was applied even to prices set for the destination — the rule is now derive net-fixed unless the winning price list carries a `geographic?` rule, Shopify's model), Phase 9 6.1 cleanup (drop `zone_id`, `null: false` on the tax `store_id`s, decide `Market#tax_inclusive`). Still open: delivery-rate tax display bypasses the provider
- `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider wrapping Stock::Estimator (calculators stay — 2026-07-27 reversal), `store_id` on ShippingMethod; monorepo ships one reference multi-carrier provider (**EasyPost** — decisions.md 2026-08-06 reversal: BYOCA fit for larger merchants + only maintained official Ruby SDK; Shippo's ruby gem dead since 2020); method rows stay regional (no cross-market method entity). **Dynamic carrier rates (2026-08-09):** a carrier method is the carrier connection — `estimates(package)` returns one Estimate per service, each becoming its own named DeliveryRate (unique (fulfillment, method) rate index dropped; `DeliveryRate#name` falls back to the method name); `Spree::DeliveryMethodService` rows narrow/rename/mark-up services (no rows = all, method-level markup columns as default); selection + EasyPost label buy key off the selected rate's carrier/service; seeds/sample data reshaped Shopify-style (Domestic + International zones with basic methods)
- `6.0-delivery-zones.md` — Zone → DeliveryZone with postal-code-range/prefix members (country-scoped); owns the full ~183-reference Zone consumer inventory; `Spree::Zone` dropped entirely by end of 6.0 (2026-07-27 — 6.0 is the breaking-change window)
- `6.0-integrations-admin.md` — **Implemented (2026-08-06).** `Spree::Integration` as the single credential surface for all provider seams (delivery rates/tax/fulfillment/pickup points): explicit `Spree.integrations` registry, Admin API v3 CRUD + types discovery (reusing `PreferenceSchema`/`Masking` — secrets are `:password` preferences), dashboard `/settings/integrations` gallery grouped by `integration_group`. Verify-before-activate (`active: true` runs `can_connect?`, 422 on failure), ephemeral connection status. Constraints now: provider gems ship an Integration subclass (no env-var credential contracts for per-store providers); no per-provider credential UIs — pickers deep-link to the integrations page.
diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.md
index 06d7ce8fbd..6063f4c3ea 100644
--- a/docs/plans/6.0-tax-provider.md
+++ b/docs/plans/6.0-tax-provider.md
@@ -1061,7 +1061,7 @@ The **admin** side adds `validation_status`, `validated_at`, `validation_evidenc
**Tax rates.** `/admin/tax_rates` — full CRUD, admin-only (rates are back-office configuration; the storefront never sees them). This plan owns building them even though `6.0-admin-api.md` carries the checkboxes, for a blunt reason: **TaxRate rows are the Internal provider's entire configuration**, so without these endpoints the default tax engine cannot be set up or inspected through the API at all, and nothing about its behavior can be verified outside a console or a spec. Tax categories already have their endpoints; rates are the missing half.
-Serializer fields: `name`, `amount` (plus `amount_percentage`, the virtual the admin forms use), `included_in_price`, `show_rate_in_label`, `tax_category_id`, `store_id`, `metadata`, timestamps and `deleted_at` (the model is paranoid). The jurisdiction field follows the schema of the moment — `zone_id` until Phase 5, `country_id`/`state_id` after it, which is the one place these endpoints get reworked. `whitelisted_ransackable_attributes` already covers `amount`, `tax_category_id`, `included_in_price` and `name`, so filtering comes free; Phase 5 swaps `zone_id` for the country/state pair there too.
+Serializer fields: `name`, `amount` (plus `amount_percentage`, the virtual the admin forms use), `included_in_price`, `show_rate_in_label`, `tax_category_id`, `store_id`, `metadata`, timestamps and `deleted_at` (the model is paranoid). The jurisdiction field follows the schema of the moment — `zone_id` until Phase 5, `country_iso`/`state_code` after it, which is the one place these endpoints get reworked. `whitelisted_ransackable_attributes` already covers `amount`, `tax_category_id`, `included_in_price` and `name`, so filtering comes free; Phase 5 swaps `zone_id` for the country and state codes there too.
**Provider discovery and selection.**
@@ -1113,13 +1113,13 @@ Tax-side only — shipping keeps Zone untouched; full Zone removal is deferred t
```ruby
# rake spree:migrate_tax_zones
# For each Zone used by TaxRate:
-# Extract country/state from ZoneMembers → set TaxRate.country_id / TaxRate.state_id
+# Extract country/state from ZoneMembers → set TaxRate.country_iso / TaxRate.state_code
# (Zone with multiple countries = one TaxRate per country)
```
-- Add `country_id`/`state_id` to `spree_tax_rates`; run the data task; sever every `zone_id` reader.
+- Add `country_iso`/`state_code` to `spree_tax_rates`; run the data task; sever every `zone_id` reader.
The column itself is dropped in **Phase 9**, 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.
+- Update the `/admin/tax_rates` serializer, permitted params and Ransack allowlist from `zone_id` to `country_iso`/`state_code` — the only rework those endpoints take, and the reason they are worth building in Phase 3 rather than waiting.
- 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`
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 3622f43b9d..743cb71320 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,26 @@
+## 2026-08-12: A tax rate names its jurisdiction by code, not by foreign key
+
+Amends 2026-08-06 ("Converted-away columns outlive the release that converts
+them"), which had tax rates gaining `country_id`/`state_id`. They gain
+`country_iso` and `state_code` instead — plain strings, upcased on write. The
+reason is that `Spree::Country` and `Spree::State` are themselves on the way out,
+so a rate pointing at their rows would need converting a second time; and "DE"
+is what a merchant recognises, where a row id is not. It also matches the
+jurisdiction snapshot `spree_tax_lines` already carries, so a rate and the line
+it produced now speak in the same terms.
+
+Everything else in that entry stands: `spree_tax_rates.zone_id` still survives
+through 6.0 as `spree:migrate_tax_zones`'s input, and the task now writes codes.
+
+**The cost, accepted:** the `state_belongs_to_country` validation is gone. With
+codes there is no country row to check a state against, and keeping the guard
+would mean keeping the `Spree::State` lookup this removes. A mismatched pair is
+simply a rate that never matches an address — which is what the mismatch always
+meant in practice, minus the early warning.
+
+Because the columns had not shipped, the original migration was amended rather
+than followed by a second one.
+
## 2026-08-12: The label leads, fulfilled follows (amends the Phase 7 fulfill flow)
A warehouse prints the label, sticks it on the box, hands the box over — and
@@ -2305,7 +2328,8 @@ generalizes: a data task named in the upgrade manifest runs *after*
`db:migrate`, so a migration that removes the task's input column in the
same release destroys the data the task exists to convert — and leaves a
merchant no source to re-run from if the conversion needs repeating.
-Tax rates therefore gain `country_id`/`state_id`, every `zone_id` reader
+Tax rates therefore gain a jurisdiction of their own (`country_id`/`state_id`
+here; changed to `country_iso`/`state_code` on 2026-08-12, see above), every `zone_id` reader
is severed (the association, the zone scopes, and `Zone#has_many
:tax_rates`, whose `dependent: :destroy` would otherwise delete live
rates when a shipping zone is destroyed), and the column is left in
diff --git a/packages/admin-sdk/src/types/generated/TaxRate.ts b/packages/admin-sdk/src/types/generated/TaxRate.ts
index 1807655113..5d77530242 100644
--- a/packages/admin-sdk/src/types/generated/TaxRate.ts
+++ b/packages/admin-sdk/src/types/generated/TaxRate.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 207cd4838d5488ee10ad59a154e0e6e7
+// Typelizer digest 27339acd4f535352c55ee15119f8662c
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -15,8 +15,6 @@ interface TaxRate {
amount_percentage: number | null;
tax_category_id: string | null;
store_id: string | null;
- country_id: number | null;
- state_id: number | null;
country_iso: string | null;
state_code: string | null;
}
diff --git a/spree/api/app/controllers/spree/api/v3/admin/tax_rates_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/tax_rates_controller.rb
index 272b8c0289..ff172990cc 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/tax_rates_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/tax_rates_controller.rb
@@ -18,13 +18,13 @@ module Spree
end
def collection_includes
- [:tax_category, :country, :state]
+ [:tax_category]
end
def permitted_params
params.permit(:name, :amount, :amount_percentage, :included_in_price,
:show_rate_in_label, :tax_category_id,
- :country_id, :state_id, :country_iso, :state_code, metadata: {})
+ :country_iso, :state_code, metadata: {})
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/tax_rate_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/tax_rate_serializer.rb
index 58ca41fb4c..f9d3e0b455 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/tax_rate_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/tax_rate_serializer.rb
@@ -12,9 +12,7 @@ module Spree
show_rate_in_label: :boolean,
tax_category_id: [:string, nullable: true],
store_id: [:string, nullable: true],
- country_id: [:number, nullable: true],
country_iso: [:string, nullable: true],
- state_id: [:number, nullable: true],
state_code: [:string, nullable: true],
metadata: ['Record<string, unknown>', nullable: true],
deleted_at: [:string, nullable: true]
@@ -40,19 +38,10 @@ module Spree
tax_rate.store&.prefixed_id
end
- # The jurisdiction the rate taxes. A null country means every country,
- # and a country with no state means the whole country. Countries and
- # states are the two models without prefixed ids, so these are raw —
- # write with `country_iso`/`state_code` instead.
- attributes :country_id, :state_id
-
- attribute :country_iso do |tax_rate|
- tax_rate.country&.iso
- end
-
- attribute :state_code do |tax_rate|
- tax_rate.state&.abbr
- end
+ # The jurisdiction the rate taxes, as codes: a null country means every
+ # country, and a country with no state means the whole country. Read
+ # and written under the same two names.
+ attributes :country_iso, :state_code
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/tax_rates_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/tax_rates_controller_spec.rb
index 031516a4c7..9bcf658332 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/tax_rates_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/tax_rates_controller_spec.rb
@@ -7,8 +7,7 @@ RSpec.describe Spree::Api::V3::Admin::TaxRatesController, type: :controller do
let!(:tax_category) { create(:tax_category) }
let!(:germany) { Spree::Country.find_by(iso: 'DE') || create(:country, iso: 'DE', name: 'Germany') }
- let!(:berlin) { create(:state, country: germany, abbr: 'BE', name: 'Berlin') }
- let!(:tax_rate) { create(:tax_rate, tax_category: tax_category, country: germany, amount: 0.19, included_in_price: true) }
+ let!(:tax_rate) { create(:tax_rate, tax_category: tax_category, country_iso: germany&.iso, amount: 0.19, included_in_price: true) }
before { request.headers.merge!(headers) }
@@ -35,9 +34,8 @@ RSpec.describe Spree::Api::V3::Admin::TaxRatesController, type: :controller do
expect(json_response['amount_percentage']).to eq(19.0)
expect(json_response['included_in_price']).to be(true)
expect(json_response['tax_category_id']).to eq(tax_category.prefixed_id)
- expect(json_response['country_id']).to eq(germany.id)
expect(json_response['country_iso']).to eq('DE')
- expect(json_response['state_id']).to be_nil
+ expect(json_response['state_code']).to be_nil
expect(json_response['state_code']).to be_nil
expect(json_response['store_id']).to eq(@default_store.prefixed_id)
end
@@ -69,16 +67,15 @@ RSpec.describe Spree::Api::V3::Admin::TaxRatesController, type: :controller do
expect(response).to have_http_status(:created)
expect(json_response['state_code']).to eq('BE')
- expect(Spree::TaxRate.last.state).to eq(berlin)
+ expect(Spree::TaxRate.last.state_code).to eq('BE')
end
- it 'rejects a state that is not in the named country' do
- france = create(:country, iso: 'FR', name: 'France')
-
- post :create, params: create_params.merge(country_iso: 'FR', state_id: berlin.id), as: :json
+ it 'stores the jurisdiction upcased however it was sent' do
+ post :create, params: create_params.merge(country_iso: 'de', state_code: 'be'), as: :json
- expect(response).to have_http_status(:unprocessable_content)
- expect(france.reload).to be_present
+ expect(response).to have_http_status(:created)
+ expect(json_response['country_iso']).to eq('DE')
+ expect(json_response['state_code']).to eq('BE')
end
it 'rejects a rate with no category' do
diff --git a/spree/api/spec/integration/spree/api/v3/admin/tax_rates_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/tax_rates_spec.rb
index 678c86e130..a3460a2886 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/tax_rates_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/tax_rates_spec.rb
@@ -7,7 +7,7 @@ RSpec.describe 'Admin Tax Rates API', type: :request, swagger_doc: 'api-referenc
let!(:tax_category) { create(:tax_category) }
let!(:germany) { Spree::Country.find_by(iso: 'DE') || create(:country, iso: 'DE', name: 'Germany') }
- let!(:tax_rate) { create(:tax_rate, tax_category: tax_category, country: germany, amount: 0.19, included_in_price: true) }
+ let!(:tax_rate) { create(:tax_rate, tax_category: tax_category, country_iso: germany&.iso, amount: 0.19, included_in_price: true) }
let(:Authorization) { "Bearer #{admin_jwt_token}" }
path '/api/v3/admin/tax_rates' do
diff --git a/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rb b/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rb
index dd5f176332..7b15030b1c 100644
--- a/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rb
+++ b/spree/api/spec/requests/spree/api/v3/store/tax_identifiers_spec.rb
@@ -95,7 +95,7 @@ RSpec.describe 'Store tax identifiers', type: :request do
describe 'the re-costing it triggers' do
let(:line_item) { cart.line_items.first }
let!(:tax_rate) do
- create(:tax_rate, store: store, country: cart.tax_country,
+ create(:tax_rate, store: store, country_iso: cart.tax_country&.iso,
tax_category: line_item.tax_category, amount: 0.1, included_in_price: false)
end
diff --git a/spree/api/spec/serializers/spree/api/v3/delivery_rate_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/delivery_rate_serializer_spec.rb
index a393775c0d..0ea9bb9d8c 100644
--- a/spree/api/spec/serializers/spree/api/v3/delivery_rate_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/delivery_rate_serializer_spec.rb
@@ -77,7 +77,7 @@ RSpec.describe Spree::Api::V3::DeliveryRateSerializer do
end
context 'with included tax' do
- let(:tax_rate) { create(:tax_rate, amount: 0.1, included_in_price: true, country: @default_country) }
+ let(:tax_rate) { create(:tax_rate, amount: 0.1, included_in_price: true, country_iso: @default_country&.iso) }
before { shipping_rate.update!(tax_rate: tax_rate) }
diff --git a/spree/core/app/models/spree/tax_provider/internal.rb b/spree/core/app/models/spree/tax_provider/internal.rb
index 6ef12fa699..2b9345d310 100644
--- a/spree/core/app/models/spree/tax_provider/internal.rb
+++ b/spree/core/app/models/spree/tax_provider/internal.rb
@@ -23,7 +23,7 @@ module Spree
items ||= owner.line_items.to_a + owner.fulfillments.to_a + owner.fees.to_a
return if items.empty?
- rates = Spree::TaxRate.for_store(owner.store).for_jurisdiction(owner.tax_country, owner.tax_address&.state).to_a
+ rates = Spree::TaxRate.for_store(owner.store).for_jurisdiction(owner.tax_country&.iso, owner.tax_address&.state_abbr).to_a
items.group_by(&:class).each do |klass, group|
# Replace-all set semantics per estimate: stale lines die with the
@@ -127,8 +127,8 @@ module Spree
# still say where the sale was taxed.
def jurisdiction_for(rate, owner)
{
- country_iso: (rate.country || owner.tax_country)&.iso,
- state_code: (rate.state || owner.tax_address&.state)&.abbr
+ country_iso: rate.country_iso.presence || owner.tax_country&.iso,
+ state_code: rate.state_code.presence || owner.tax_address&.state_abbr
}
end
diff --git a/spree/core/app/models/spree/tax_rate.rb b/spree/core/app/models/spree/tax_rate.rb
index e78c356682..c0fd34365b 100644
--- a/spree/core/app/models/spree/tax_rate.rb
+++ b/spree/core/app/models/spree/tax_rate.rb
@@ -21,11 +21,6 @@ module Spree
class_name: 'Spree::TaxCategory'
end
- # The jurisdiction this rate applies in. Nil country means everywhere, and a
- # country with no state means the whole country.
- belongs_to :country, class_name: 'Spree::Country', optional: true
- belongs_to :state, class_name: 'Spree::State', optional: true
-
has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :nullify
with_options presence: true do
@@ -33,8 +28,11 @@ module Spree
validates :tax_category, :name
end
- before_validation :resolve_state_code
- validate :state_belongs_to_country
+ # The jurisdiction this rate applies in, held as codes: a blank country_iso
+ # means everywhere, and a country with no state_code means the whole
+ # country. Upcased on the way in so a rate entered as "de" still matches an
+ # address from Germany.
+ normalizes :country_iso, :state_code, with: ->(value) { value.presence&.to_s&.upcase }
# The primitive: rates that reach a jurisdiction, which is a country and
# optionally one of its states. Rates naming neither are included, since a
@@ -42,20 +40,22 @@ module Spree
# address because tax applies before a customer has given one — the
# provider falls back to the market's country (see
# Spree::Purchase::Taxation#tax_country).
- scope :for_jurisdiction, lambda { |country, state = nil|
- where(country_id: [country&.id, nil].uniq).where(state_id: [state&.id, nil].uniq)
+ # +normalizes+ above applies to query values too, so a caller passing "de"
+ # still matches a rate stored as "DE".
+ scope :for_jurisdiction, lambda { |country_iso, state_code = nil|
+ where(country_iso: [country_iso.presence, nil].uniq).where(state_code: [state_code.presence, nil].uniq)
}
# The same question asked with an address in hand.
- scope :for_address, ->(address) { for_jurisdiction(address&.country, address&.state) }
- # Country-wide: unlike for_jurisdiction(country, nil) this leaves the state
- # unconstrained, so it sums a country's state-level rates too. Used where the
- # state is irrelevant — backing VAT out of a gross price.
- scope :for_country, ->(country) { where(country_id: [country&.id, nil].uniq) }
+ scope :for_address, ->(address) { for_jurisdiction(address&.country_iso, address&.state_abbr) }
+ # Country-wide: unlike for_jurisdiction(country_iso, nil) this leaves the
+ # state unconstrained, so it sums a country's state-level rates too. Used
+ # where the state is irrelevant — backing VAT out of a gross price.
+ scope :for_country, ->(country_iso) { where(country_iso: [country_iso.presence, nil].uniq) }
scope :for_tax_category,
->(category) { where(tax_category_id: category.try(:id)) }
scope :included_in_price, -> { where(included_in_price: true) }
- self.whitelisted_ransackable_attributes = %w[amount country_id state_id tax_category_id included_in_price name]
+ self.whitelisted_ransackable_attributes = %w[amount country_iso state_code tax_category_id included_in_price name]
# Virtual attribute for percentage display in admin forms
def amount_percentage
@@ -68,29 +68,18 @@ module Spree
self.amount = value.present? ? (value.to_f / 100) : nil
end
- # Countries and states are addressed by their codes across the v3 API —
- # neither model carries a prefixed id, and the codes are what a merchant
- # recognises. The numeric FKs stay writable for internal callers.
- def country_iso=(value)
- self.country = value.present? ? Spree::Country.by_iso(value) : nil
- end
-
- # Resolved in a callback rather than here: state abbreviations repeat across
- # countries, so the lookup needs the country — and a JSON body can name the
- # state before the country.
- def state_code=(value)
- @state_code_input = value
- end
-
# The included-in-price rate to back out of a gross price.
#
# @param options [Hash] +:country+ (or +:address+) and +:tax_category+
# @return [BigDecimal] 0 when the jurisdiction or category is unknown
def self.included_tax_amount_for(options)
- country = options[:country] || options[:address]&.country
- return 0 unless country && options[:tax_category]
+ # +:country+ is a documented override point and the VAT path still hands
+ # it a Spree::Country, so take the code off whichever arrives.
+ country = options[:country]
+ country_iso = country.try(:iso) || country.presence || options[:address]&.country_iso
+ return 0 unless country_iso && options[:tax_category]
- scope = options[:address] ? for_address(options[:address]) : for_country(country)
+ scope = options[:address] ? for_address(options[:address]) : for_country(country_iso)
# Per-store tax configuration is the norm since 6.0, so without this the
# sum would add up every store's rate for the same country.
store = options[:store] || Spree::Current.store
@@ -118,21 +107,6 @@ module Spree
private
- def resolve_state_code
- return unless defined?(@state_code_input)
-
- self.state = @state_code_input.blank? ? nil : Spree::State.where(country_id: country_id).find_by(abbr: @state_code_input)
- remove_instance_variable(:@state_code_input)
- end
-
- # A state-level rate whose state sits in another country would never match
- # any address — the two columns have to agree.
- def state_belongs_to_country
- return if state.nil? || country.nil? || state.country_id == country_id
-
- errors.add(:state, :invalid)
- end
-
def amount_for_label
return '' unless show_rate_in_label?
return '' if amount.zero?
diff --git a/spree/core/db/migrate/20260806000005_add_country_and_state_to_spree_tax_rates.rb b/spree/core/db/migrate/20260806000005_add_country_and_state_to_spree_tax_rates.rb
index 43d188e116..cd96144032 100644
--- a/spree/core/db/migrate/20260806000005_add_country_and_state_to_spree_tax_rates.rb
+++ b/spree/core/db/migrate/20260806000005_add_country_and_state_to_spree_tax_rates.rb
@@ -4,11 +4,17 @@ class AddCountryAndStateToSpreeTaxRates < ActiveRecord::Migration[8.1]
# its jurisdiction directly: nil country means everywhere, and a country
# with no state means the whole country.
#
+ # Stored as codes rather than references to Country and State, which are on
+ # their way out — and "DE"/"NY" is what a merchant recognises anyway. Same
+ # shape as the jurisdiction snapshot on spree_tax_lines.
+ #
# Zones were also the reason a tax line could not say which country taxed
# it — one zone can span several. Existing rows are converted by
# `spree:migrate_tax_zones`, which splits a multi-country zone into one rate
# per country, before `zone_id` comes off.
- add_reference :spree_tax_rates, :country, null: true
- add_reference :spree_tax_rates, :state, null: true
+ add_column :spree_tax_rates, :country_iso, :string
+ add_column :spree_tax_rates, :state_code, :string
+
+ add_index :spree_tax_rates, [:country_iso, :state_code]
end
end
diff --git a/spree/core/lib/spree/testing_support/factories/tax_rate_factory.rb b/spree/core/lib/spree/testing_support/factories/tax_rate_factory.rb
index 9cc03415a9..38105209b0 100644
--- a/spree/core/lib/spree/testing_support/factories/tax_rate_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/tax_rate_factory.rb
@@ -1,13 +1,13 @@
FactoryBot.define do
factory :tax_rate, class: Spree::TaxRate do
name { "TaxRate - #{rand(999_999)}" }
- country { Spree::Country.find_by(iso: 'US') || association(:country) }
+ country_iso { 'US' }
tax_category
amount { 0.1 }
# Taxes every country — what a single-market store configures.
trait :worldwide do
- country { nil }
+ country_iso { nil }
end
end
end
diff --git a/spree/core/lib/tasks/tax_zones_migration.rake b/spree/core/lib/tasks/tax_zones_migration.rake
index 5c604a3716..c066ff0384 100644
--- a/spree/core/lib/tasks/tax_zones_migration.rake
+++ b/spree/core/lib/tasks/tax_zones_migration.rake
@@ -1,8 +1,8 @@
namespace :spree do
desc <<~DESC
- Converts the zones tax rates were configured against into direct
- country/state references (Spree 6.0). A zone spanning several countries
- becomes one rate per country, since a rate can now name only one
+ Converts the zones tax rates were configured against into the country and
+ state codes a rate now carries (Spree 6.0). A zone spanning several
+ countries becomes one rate per country, since a rate can name only one
jurisdiction — which is what lets a tax line report the country that taxed
it. Idempotent: rates that already carry a country or state are skipped, and
so are rates whose zone had no members, which stay as "everywhere" rates.
@@ -14,10 +14,11 @@ namespace :spree do
zone.zone_members.filter_map do |member|
case member.zoneable_type
when 'Spree::Country'
- { country_id: member.zoneable_id, state_id: nil }
+ country = Spree::Country.find_by(id: member.zoneable_id)
+ { country_iso: country.iso, state_code: nil } if country
when 'Spree::State'
state = Spree::State.find_by(id: member.zoneable_id)
- { country_id: state.country_id, state_id: state.id } if state
+ { country_iso: state.country&.iso, state_code: state.abbr } if state&.country
end
end.uniq
end
@@ -27,7 +28,7 @@ namespace :spree do
skipped = 0
Spree::TaxRate.with_deleted.
- where(country_id: nil, state_id: nil).where.not(zone_id: nil).find_each do |rate|
+ where(country_iso: nil, state_code: nil).where.not(zone_id: nil).find_each do |rate|
zone = Spree::Zone.find_by(id: rate.zone_id)
jurisdictions = zone ? jurisdictions_for.call(zone) : []
@@ -37,14 +38,14 @@ namespace :spree do
end
first, *rest = jurisdictions
- rate.update_columns(country_id: first[:country_id], state_id: first[:state_id], updated_at: Time.current)
+ rate.update_columns(country_iso: first[:country_iso], state_code: first[:state_code], updated_at: Time.current)
converted += 1
rest.each do |jurisdiction|
Spree::TaxRate.insert(
rate.attributes.slice(*Spree::TaxRate.column_names).except('id', 'created_at', 'updated_at').merge(
- 'country_id' => jurisdiction[:country_id],
- 'state_id' => jurisdiction[:state_id],
+ 'country_iso' => jurisdiction[:country_iso],
+ 'state_code' => jurisdiction[:state_code],
'created_at' => Time.current,
'updated_at' => Time.current
)
diff --git a/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb b/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb
index 0afbc7d5ea..c5e0c0ff2b 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
@@ -224,7 +224,7 @@ describe '6.0 data migration tasks' do
def unconverted_rate(zone, **attributes)
create(:tax_rate, **attributes).tap do |rate|
- rate.update_columns(country_id: nil, state_id: nil, zone_id: zone.id)
+ rate.update_columns(country_iso: nil, state_code: nil, zone_id: zone.id)
end
end
@@ -233,8 +233,8 @@ describe '6.0 data migration tasks' do
run_task('spree:migrate_tax_zones')
- expect(rate.reload.country).to eq(germany)
- expect(rate.state).to be_nil
+ expect(rate.reload.country_iso).to eq(germany.iso)
+ expect(rate.state_code).to be_nil
end
it 'splits a multi-country zone into one rate per country' do
@@ -242,8 +242,8 @@ describe '6.0 data migration tasks' do
expect { run_task('spree:migrate_tax_zones') }.to change(Spree::TaxRate, :count).by(1)
- countries = Spree::TaxRate.where(name: rate.name).map(&:country)
- expect(countries).to contain_exactly(germany, france)
+ countries = Spree::TaxRate.where(name: rate.name).map(&:country_iso)
+ expect(countries).to contain_exactly(germany.iso, france.iso)
expect(Spree::TaxRate.where(name: rate.name).map(&:amount).uniq).to eq([0.19])
end
@@ -253,8 +253,8 @@ describe '6.0 data migration tasks' do
run_task('spree:migrate_tax_zones')
- expect(rate.reload.country).to eq(germany)
- expect(rate.state).to eq(state)
+ expect(rate.reload.country_iso).to eq(germany.iso)
+ expect(rate.state_code).to eq(state.abbr)
end
it 'leaves a memberless zone as an every-country rate' do
@@ -262,7 +262,7 @@ describe '6.0 data migration tasks' do
run_task('spree:migrate_tax_zones')
- expect(rate.reload.country).to be_nil
+ expect(rate.reload.country_iso).to be_nil
end
it 'is idempotent' do
diff --git a/spree/core/spec/models/concerns/spree/vat_price_calculation_spec.rb b/spree/core/spec/models/concerns/spree/vat_price_calculation_spec.rb
index af39349de2..fe02673f05 100644
--- a/spree/core/spec/models/concerns/spree/vat_price_calculation_spec.rb
+++ b/spree/core/spec/models/concerns/spree/vat_price_calculation_spec.rb
@@ -17,7 +17,7 @@ describe Spree::VatPriceCalculation, type: :model do
before do
home_market.update!(countries: [germany])
create(:tax_rate, name: 'DE 19% incl', amount: 0.19, tax_category: category,
- country: germany, included_in_price: true, store: store)
+ country_iso: germany&.iso, included_in_price: true, store: store)
end
let(:variant) { create(:variant, price: 100, product: create(:product, tax_category: category)) }
@@ -33,7 +33,7 @@ describe Spree::VatPriceCalculation, type: :model do
it 'restates for a destination with its own rate, preserving the net' do
create(:tax_rate, name: 'FR 20% incl', amount: 0.20, tax_category: category,
- country: france, included_in_price: true, store: store)
+ country_iso: france&.iso, included_in_price: true, store: store)
# net 100 / 1.19 = 84.0336, grossed by 1.20
expect(gross_for(france)).to eq(100.84)
@@ -62,7 +62,7 @@ describe Spree::VatPriceCalculation, type: :model do
it 'does not restate at all' do
create(:tax_rate, name: 'FR 20% incl', amount: 0.20, tax_category: category,
- country: france, included_in_price: true, store: store)
+ country_iso: france&.iso, included_in_price: true, store: store)
expect(gross_for(france, market: external_market)).to eq(100.00)
end
@@ -83,7 +83,7 @@ describe Spree::VatPriceCalculation, type: :model do
before do
create(:tax_rate, name: 'FR 20% incl', amount: 0.20, tax_category: category,
- country: france, included_in_price: true, store: store)
+ country_iso: france&.iso, included_in_price: true, store: store)
end
it 'restates from the market country, keeping the net intact' do
@@ -116,7 +116,7 @@ describe Spree::VatPriceCalculation, type: :model do
before do
create(:tax_rate, name: 'FR 20% incl', amount: 0.20, tax_category: category,
- country: france, included_in_price: true, store: store)
+ country_iso: france&.iso, included_in_price: true, store: store)
end
it 'is charged exactly as entered' do
@@ -142,7 +142,7 @@ describe Spree::VatPriceCalculation, type: :model do
before do
create(:tax_rate, name: 'FR 20% incl', amount: 0.20, tax_category: category,
- country: france, included_in_price: true, store: store)
+ country_iso: france&.iso, included_in_price: true, store: store)
end
# A market rule with nothing selected matches everyone, which is the state the
diff --git a/spree/core/spec/models/spree/concerns/vat_price_calculation_spec.rb b/spree/core/spec/models/spree/concerns/vat_price_calculation_spec.rb
index 04b7753908..6561afb122 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
@@ -56,9 +56,9 @@ module Spree
context 'and the destination is elsewhere' do
it 'takes the home VAT out and puts the destination VAT on' do
- create(:tax_rate, country: home_country, tax_category: tax_category, amount: 0.19,
+ create(:tax_rate, country_iso: home_country&.iso, tax_category: tax_category, amount: 0.19,
included_in_price: true)
- create(:tax_rate, country: destination, tax_category: tax_category, amount: 0.25,
+ create(:tax_rate, country_iso: destination&.iso, tax_category: tax_category, amount: 0.25,
included_in_price: true)
# 100 gross at 19% is 84.03 net, which is 105.04 gross at 25%.
diff --git a/spree/core/spec/models/spree/delivery_rate_spec.rb b/spree/core/spec/models/spree/delivery_rate_spec.rb
index d298d495ea..cf6ed9be1d 100644
--- a/spree/core/spec/models/spree/delivery_rate_spec.rb
+++ b/spree/core/spec/models/spree/delivery_rate_spec.rb
@@ -30,7 +30,7 @@ describe Spree::DeliveryRate, type: :model do
name: 'VAT',
amount: 0.1,
included_in_price: true,
- country: @default_country
+ country_iso: @default_country&.iso
end
context 'when the rate taxes the home country' do
@@ -58,7 +58,7 @@ describe Spree::DeliveryRate, type: :model do
name: 'VAT',
amount: 0.2,
included_in_price: true,
- country: create(:country, iso: 'FR', name: 'France')
+ country_iso: create(:country, iso: 'FR', name: 'France')&.iso
end
before { shipping_rate.tax_rate = non_default_tax_rate }
diff --git a/spree/core/spec/models/spree/line_item_spec.rb b/spree/core/spec/models/spree/line_item_spec.rb
index 42a81e1cde..eeb20e30a6 100644
--- a/spree/core/spec/models/spree/line_item_spec.rb
+++ b/spree/core/spec/models/spree/line_item_spec.rb
@@ -265,7 +265,7 @@ describe Spree::LineItem, type: :model do
let(:variant) { create(:variant) }
before do
- create(:tax_rate, country: rate_country, tax_category: variant.tax_category)
+ create(:tax_rate, country_iso: rate_country&.iso, tax_category: variant.tax_category)
end
context 'when a rate covers the order destination' do
diff --git a/spree/core/spec/models/spree/order/adjustments_spec.rb b/spree/core/spec/models/spree/order/adjustments_spec.rb
index 02d77bcfbd..b0e67d1fd7 100644
--- a/spree/core/spec/models/spree/order/adjustments_spec.rb
+++ b/spree/core/spec/models/spree/order/adjustments_spec.rb
@@ -38,7 +38,7 @@ describe Spree::Order do
amount: 0.2,
included_in_price: true,
tax_category: tax_category,
- country: country
+ country_iso: country&.iso
)
}
let!(:shipping_method) do
diff --git a/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb b/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
index 6e22cff145..44b61c3445 100644
--- a/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
+++ b/spree/core/spec/models/spree/promotion_handler/coupon_spec.rb
@@ -225,7 +225,7 @@ module Spree
context 'for an order with taxable line items' do
let!(:order) { create(:order, line_items_price: 0.0, store: store) }
let!(:tax_category) { create(:tax_category, name: 'Taxable Foo') }
- let!(:rate) { create(:tax_rate, amount: 0.10, tax_category: tax_category, country: @default_country) }
+ let!(:rate) { create(:tax_rate, amount: 0.10, tax_category: tax_category, country_iso: @default_country&.iso) }
context 'and the product price is less than promo discount' do
diff --git a/spree/core/spec/models/spree/promotion_tax_recalculation_spec.rb b/spree/core/spec/models/spree/promotion_tax_recalculation_spec.rb
index b4c18d146a..72b4977ace 100644
--- a/spree/core/spec/models/spree/promotion_tax_recalculation_spec.rb
+++ b/spree/core/spec/models/spree/promotion_tax_recalculation_spec.rb
@@ -69,7 +69,7 @@ describe 'Promotion discounts and the taxable basis', type: :model do
context 'with additional (US-style) tax of 10%' do
let(:item_price) { 250 }
let!(:tax_rate) do
- create(:tax_rate, country: @default_country, tax_category: tax_category, amount: 0.10, included_in_price: false)
+ create(:tax_rate, country_iso: @default_country&.iso, tax_category: tax_category, amount: 0.10, included_in_price: false)
end
before { build_cart! }
@@ -157,7 +157,7 @@ describe 'Promotion discounts and the taxable basis', type: :model do
context 'with included (VAT-style) tax of 20%' do
let(:item_price) { 350 }
let!(:tax_rate) do
- create(:tax_rate, country: @default_country, tax_category: tax_category, amount: 0.20, included_in_price: true)
+ create(:tax_rate, country_iso: @default_country&.iso, tax_category: tax_category, amount: 0.20, included_in_price: true)
end
before { build_cart! }
diff --git a/spree/core/spec/models/spree/stock/estimator_spec.rb b/spree/core/spec/models/spree/stock/estimator_spec.rb
index 5e62a04aae..b7f168fa60 100644
--- a/spree/core/spec/models/spree/stock/estimator_spec.rb
+++ b/spree/core/spec/models/spree/stock/estimator_spec.rb
@@ -195,7 +195,7 @@ module Spree
end
context 'includes tax adjustments if applicable' do
- let!(:tax_rate) { create(:tax_rate, country: order.tax_address.country) }
+ let!(:tax_rate) { create(:tax_rate, country_iso: order.tax_address.country&.iso) }
before do
Spree::ShippingMethod.all.each do |sm|
@@ -220,7 +220,7 @@ module Spree
let!(:default_vat) do
create :tax_rate,
included_in_price: true,
- country: home_country,
+ country_iso: home_country&.iso,
amount: 0.2,
tax_category: shipping_method.tax_category
end
@@ -258,7 +258,7 @@ module Spree
let!(:other_vat) do
create :tax_rate,
included_in_price: true,
- country: other_country,
+ country_iso: other_country&.iso,
amount: 0.3,
tax_category: shipping_method.tax_category
end
diff --git a/spree/core/spec/models/spree/tax_provider/internal_spec.rb b/spree/core/spec/models/spree/tax_provider/internal_spec.rb
index 6639bdbeaf..da66e09f36 100644
--- a/spree/core/spec/models/spree/tax_provider/internal_spec.rb
+++ b/spree/core/spec/models/spree/tax_provider/internal_spec.rb
@@ -10,7 +10,7 @@ describe Spree::TaxProvider::Internal, type: :model do
describe '#estimate' do
context 'with an additional rate' do
- let!(:rate) { create(:tax_rate, country: country, amount: 0.1, tax_category: line_item.tax_category, included_in_price: false) }
+ let!(:rate) { create(:tax_rate, country_iso: country&.iso, amount: 0.1, tax_category: line_item.tax_category, included_in_price: false) }
it 'writes a tax line with snapshots' do
provider.estimate(order)
@@ -51,7 +51,7 @@ describe Spree::TaxProvider::Internal, type: :model do
provider.estimate(order)
expect(order.tax_lines.reload.count).to eq(1)
- rate.update!(country: create(:country, iso: 'JP', name: 'Japan'))
+ rate.update!(country_iso: 'JP')
provider.estimate(order)
expect(order.tax_lines.reload).to be_empty
end
@@ -66,7 +66,7 @@ describe Spree::TaxProvider::Internal, type: :model do
end
context 'with an included (VAT) rate' do
- let!(:rate) { create(:tax_rate, country: country, amount: 0.2, tax_category: line_item.tax_category, included_in_price: true) }
+ let!(:rate) { create(:tax_rate, country_iso: country&.iso, amount: 0.2, tax_category: line_item.tax_category, included_in_price: true) }
it 'backs the tax out of the gross basis' do
provider.estimate(order)
@@ -79,7 +79,7 @@ describe Spree::TaxProvider::Internal, type: :model do
end
context 'with a matched zero rate' do
- let!(:rate) { create(:tax_rate, country: country, amount: 0, tax_category: line_item.tax_category, included_in_price: false) }
+ let!(:rate) { create(:tax_rate, country_iso: country&.iso, amount: 0, tax_category: line_item.tax_category, included_in_price: false) }
it 'still writes a row, marked zero-rated' do
provider.estimate(order)
@@ -92,7 +92,7 @@ describe Spree::TaxProvider::Internal, type: :model do
end
context 'with no matching rate' do
- let!(:rate) { create(:tax_rate, country: country, amount: 0.1, tax_category: create(:tax_category), included_in_price: false) }
+ let!(:rate) { create(:tax_rate, country_iso: country&.iso, amount: 0.1, tax_category: create(:tax_category), included_in_price: false) }
it 'writes nothing, having formed no opinion' do
provider.estimate(order)
@@ -106,7 +106,7 @@ describe Spree::TaxProvider::Internal, type: :model do
let(:cart_line_item) { cart.line_items.first }
let(:cart_country) { cart.tax_address.country }
let!(:rate) do
- create(:tax_rate, country: cart_country, amount: 0.1, tax_category: cart_line_item.tax_category, included_in_price: false)
+ create(:tax_rate, country_iso: cart_country&.iso, amount: 0.1, tax_category: cart_line_item.tax_category, included_in_price: false)
end
it 'owns the row through the cart FK' do
@@ -120,7 +120,7 @@ describe Spree::TaxProvider::Internal, type: :model do
end
context 'with an exemption covering the sale' do
- let!(:rate) { create(:tax_rate, country: country, amount: 0.1, tax_category: line_item.tax_category, included_in_price: false) }
+ let!(:rate) { create(:tax_rate, country_iso: country&.iso, amount: 0.1, tax_category: line_item.tax_category, included_in_price: false) }
let(:exemption) { Spree::TaxExemption.new(reason_code: 'resale', certificate_number: 'CERT-1') }
it 'writes a zero row recording the claim' do
@@ -155,7 +155,7 @@ describe Spree::TaxProvider::Internal, type: :model do
# The whole chain: a certificate the company holds, resolved by the real
# service, reaching the provider as a claim.
context 'with a certificate the buyer company holds' do
- let!(:rate) { create(:tax_rate, country: country, amount: 0.1, tax_category: line_item.tax_category, included_in_price: false) }
+ let!(:rate) { create(:tax_rate, country_iso: country&.iso, amount: 0.1, tax_category: line_item.tax_category, included_in_price: false) }
let(:company) { create(:company, store: @default_store) }
let(:location) { create(:company_location, company: company) }
@@ -188,7 +188,7 @@ describe Spree::TaxProvider::Internal, type: :model do
end
context 'with an exemption against an included (VAT) rate' do
- let!(:rate) { create(:tax_rate, country: country, amount: 0.2, tax_category: line_item.tax_category, included_in_price: true) }
+ let!(:rate) { create(:tax_rate, country_iso: country&.iso, amount: 0.2, tax_category: line_item.tax_category, included_in_price: true) }
it 'leaves the whole basis pre-tax, having no tax to back out' do
provider.estimate(order, exemptions: [Spree::TaxExemption.new(reason_code: 'government')])
@@ -200,7 +200,7 @@ describe Spree::TaxProvider::Internal, type: :model do
context 'when another store holds the default tax category' do
let!(:rate) do
- create(:tax_rate, country: country, amount: 0.1,
+ create(:tax_rate, country_iso: country&.iso, amount: 0.1,
tax_category: create(:tax_category, is_default: true), included_in_price: false)
end
let!(:fee) { create(:fee, order: order, amount: 5, kind: 'surcharge', label: 'Handling') }
@@ -229,13 +229,13 @@ describe Spree::TaxProvider::Internal, type: :model do
# recalculate the order and estimate tax a second time.
fulfillment.update_columns(cost: 10)
# A store default exists, so falling back to it is a visible wrong answer.
- create(:tax_rate, country: country, amount: 0.2, included_in_price: false,
+ create(:tax_rate, country_iso: country&.iso, amount: 0.2, included_in_price: false,
tax_category: create(:tax_category, is_default: true))
fulfillment.reload
end
it "taxes delivery at its delivery method's category" do
- reduced_rate = create(:tax_rate, country: country, amount: 0.05, included_in_price: false,
+ reduced_rate = create(:tax_rate, country_iso: country&.iso, amount: 0.05, included_in_price: false,
tax_category: reduced_rate_category)
provider.estimate(order, [fulfillment])
@@ -258,7 +258,7 @@ describe Spree::TaxProvider::Internal, type: :model do
context 'with a taxable fee' do
let!(:rate) do
- create(:tax_rate, country: country, amount: 0.1, tax_category: create(:tax_category, is_default: true), included_in_price: false)
+ create(:tax_rate, country_iso: country&.iso, amount: 0.1, tax_category: create(:tax_category, is_default: true), included_in_price: false)
end
let!(:fee) { create(:fee, order: order, amount: 5, kind: 'surcharge', label: 'Handling') }
diff --git a/spree/core/spec/models/spree/tax_rate_spec.rb b/spree/core/spec/models/spree/tax_rate_spec.rb
index cf0c612a8d..524d371cd1 100644
--- a/spree/core/spec/models/spree/tax_rate_spec.rb
+++ b/spree/core/spec/models/spree/tax_rate_spec.rb
@@ -10,7 +10,7 @@ describe Spree::TaxRate, type: :model do
it 'falls back to rates that tax everywhere when the jurisdiction is unknown' do
worldwide = create(:tax_rate, :worldwide, tax_category: tax_category)
- create(:tax_rate, country: germany, tax_category: tax_category)
+ create(:tax_rate, country_iso: germany&.iso, tax_category: tax_category)
# A rate naming no country taxes everywhere, so it still applies when we
# cannot say where the sale is — a country-specific one does not.
@@ -18,22 +18,22 @@ describe Spree::TaxRate, type: :model do
end
it 'reads a jurisdiction off an address, or takes the pair directly' do
- rate = create(:tax_rate, country: germany, tax_category: tax_category)
+ rate = create(:tax_rate, country_iso: germany&.iso, tax_category: tax_category)
expect(described_class.for_address(german_address)).to eq([rate])
- expect(described_class.for_jurisdiction(germany)).to eq([rate])
+ expect(described_class.for_jurisdiction(germany.iso)).to eq([rate])
end
it 'matches a rate for the address country' do
- rate = create(:tax_rate, country: germany, tax_category: tax_category)
- create(:tax_rate, country: france, tax_category: tax_category)
+ rate = create(:tax_rate, country_iso: germany&.iso, tax_category: tax_category)
+ create(:tax_rate, country_iso: france&.iso, tax_category: tax_category)
expect(described_class.for_address(german_address)).to eq([rate])
end
it 'matches every rate configured for that country' do
- standard = create(:tax_rate, country: germany, amount: 0.19, tax_category: tax_category)
- reduced = create(:tax_rate, country: germany, amount: 0.07, tax_category: create(:tax_category))
+ standard = create(:tax_rate, country_iso: germany&.iso, amount: 0.19, tax_category: tax_category)
+ reduced = create(:tax_rate, country_iso: germany&.iso, amount: 0.07, tax_category: create(:tax_category))
expect(described_class.for_address(german_address)).to match_array([standard, reduced])
end
@@ -48,31 +48,40 @@ describe Spree::TaxRate, type: :model do
let(:berlin_address) { create(:address, country: germany, state: berlin) }
it 'matches the state rate alongside the country rate' do
- country_rate = create(:tax_rate, country: germany, tax_category: tax_category)
- state_rate = create(:tax_rate, country: germany, state: berlin, tax_category: create(:tax_category))
+ country_rate = create(:tax_rate, country_iso: germany&.iso, tax_category: tax_category)
+ state_rate = create(:tax_rate, country_iso: germany&.iso, state_code: berlin&.abbr, tax_category: create(:tax_category))
expect(described_class.for_address(berlin_address)).to match_array([country_rate, state_rate])
end
it 'does not match another state rate' do
hamburg = create(:state, country: germany, abbr: 'HH', name: 'Hamburg')
- create(:tax_rate, country: germany, state: hamburg, tax_category: tax_category)
+ create(:tax_rate, country_iso: germany&.iso, state_code: hamburg&.abbr, tax_category: tax_category)
expect(described_class.for_address(berlin_address)).to be_empty
end
it 'does not match a state rate for an address with no state' do
- create(:tax_rate, country: germany, state: berlin, tax_category: tax_category)
+ create(:tax_rate, country_iso: germany&.iso, state_code: berlin&.abbr, tax_category: tax_category)
expect(described_class.for_address(german_address)).to be_empty
end
end
- it 'rejects a state that is not in the rate country' do
- rate = build(:tax_rate, country: france, state: berlin)
+ # A state code that belongs to another country is no longer rejected on
+ # write — with codes there is no Country row to check it against. It simply
+ # never matches an address, which is what the mismatch always meant.
+ it 'never matches when the state code belongs to another country' do
+ create(:tax_rate, country_iso: 'FR', state_code: berlin&.abbr, tax_category: tax_category)
- expect(rate).not_to be_valid
- expect(rate.errors[:state]).to be_present
+ expect(described_class.for_address(german_address)).to be_empty
+ end
+
+ it 'matches regardless of the case a code was entered in' do
+ rate = create(:tax_rate, country_iso: 'de', tax_category: tax_category)
+
+ expect(rate.country_iso).to eq('DE')
+ expect(described_class.for_address(german_address)).to eq([rate])
end
end
@@ -89,21 +98,21 @@ describe Spree::TaxRate, type: :model do
let!(:german_vat) do
create(:tax_rate, name: 'German VAT', amount: 0.19, tax_category: moss_category,
- country: germany, included_in_price: true)
+ country_iso: germany&.iso, included_in_price: true)
end
let!(:french_vat) do
create(:tax_rate, name: 'French VAT', amount: 0.25, tax_category: moss_category,
- country: france, included_in_price: true)
+ country_iso: france&.iso, included_in_price: true)
end
# Physical goods are taxed where they ship from, so both EU countries
# carry the same rate — one row each, a zone spanning both being gone.
let!(:german_goods_vat) do
create(:tax_rate, name: 'EU VAT (DE)', amount: 0.19, tax_category: normal_category,
- country: germany, included_in_price: true)
+ country_iso: germany&.iso, included_in_price: true)
end
let!(:french_goods_vat) do
create(:tax_rate, name: 'EU VAT (FR)', amount: 0.19, tax_category: normal_category,
- country: france, included_in_price: true)
+ country_iso: france&.iso, included_in_price: true)
end
let(:download) { create(:product, tax_category: moss_category, price: 100) }
@@ -188,7 +197,7 @@ describe Spree::TaxRate, type: :model do
let!(:order) { create(:order, ship_address: create(:address, country: country)) }
let(:category) { create(:tax_category, name: 'Taxable Foo') }
let!(:rate) do
- create(:tax_rate, name: 'Tax Rate #1', amount: 0.1, tax_category: category, country: country)
+ create(:tax_rate, name: 'Tax Rate #1', amount: 0.1, tax_category: category, country_iso: country&.iso)
end
let(:taxable) { create(:product, tax_category: category) }
let!(:line_item) { Spree::Orders::AddItem.call(order: order, variant: taxable.default_variant).value }
@@ -221,20 +230,20 @@ describe Spree::TaxRate, type: :model do
let!(:included_tax_rate) do
create(:tax_rate, included_in_price: true, tax_category: line_item.tax_category,
- country: country, amount: 0.4)
+ country_iso: country&.iso, amount: 0.4)
end
let!(:other_included_tax_rate) do
create(:tax_rate, included_in_price: true, tax_category: line_item.tax_category,
- country: country, amount: 0.05)
+ country_iso: country&.iso, amount: 0.05)
end
# Additional tax is added to the price rather than sitting inside it.
let!(:additional_tax_rate) do
create(:tax_rate, included_in_price: false, tax_category: line_item.tax_category,
- country: country, amount: 0.2)
+ country_iso: country&.iso, amount: 0.2)
end
let!(:included_tax_rate_from_somewhere_else) do
create(:tax_rate, included_in_price: true, tax_category: line_item.tax_category,
- country: create(:country, iso: 'JP', name: 'Japan'), amount: 0.1)
+ country_iso: create(:country, iso: 'JP', name: 'Japan')&.iso, amount: 0.1)
end
let(:price_options) { { country: country, tax_category: line_item.tax_category } }
diff --git a/spree/core/spec/workflows/spree/carts/add_item_spec.rb b/spree/core/spec/workflows/spree/carts/add_item_spec.rb
index ed4ba504f2..3d2abc1c75 100644
--- a/spree/core/spec/workflows/spree/carts/add_item_spec.rb
+++ b/spree/core/spec/workflows/spree/carts/add_item_spec.rb
@@ -89,7 +89,7 @@ module Spree
amount: 0.25,
included_in_price: true,
tax_category: category,
- country: @default_country
+ country_iso: @default_country&.iso
)
end
let(:variant) { create(:variant, price: 1000) }
diff --git a/spree/core/spec/workflows/spree/carts/complete_spec.rb b/spree/core/spec/workflows/spree/carts/complete_spec.rb
index 698b80e45f..520b18263f 100644
--- a/spree/core/spec/workflows/spree/carts/complete_spec.rb
+++ b/spree/core/spec/workflows/spree/carts/complete_spec.rb
@@ -115,7 +115,7 @@ module Spree
context 'when the cart carries tax rows' do
let(:tax_category) { create(:tax_category) }
let!(:rate) do
- create(:tax_rate, store: store, country: ready_cart.tax_country, amount: 0.1,
+ create(:tax_rate, store: store, country_iso: ready_cart.tax_country&.iso, amount: 0.1,
included_in_price: false, tax_category: tax_category)
end