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.

Add 6.0 delivery rate provider plan, update tax provider plan

Damian Legawiec3f5cf65401ed
diff --git a/CLAUDE.md b/CLAUDE.md
index 70fee2a5dd..758985c8e7 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -25,7 +25,8 @@ Current plans:
- `6.0-channels-catalogs-b2b.md` — Channel, Catalog, ProductListing (replaces StoreProduct), Company/CompanyLocation/CompanyContact for B2B
- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename
- `6.0-search-provider.md` — Pluggable SearchProvider interface (Database default, Meilisearch/Elasticsearch/Algolia adapters), MetafieldDefinition faceting, autocomplete endpoint
-- `6.0-tax-provider.md` — Pluggable TaxProvider interface (Internal default, Avalara/TaxJar/Vertex adapters), estimate/commit/void lifecycle, tax exemption certificates
+- `6.0-tax-provider.md` — Per-Market TaxProvider, replaces TaxRate.adjust + Calculator, TaxZone for internal provider only
+- `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider, replaces Estimator + Calculator, DeliveryZone with postal code support
- `5.x-store-api-bridges.md` — Bridge 6.0 naming into 5.5 Store API (fulfillments, delivery, status, remove master_variant)
- `5.x-store-api-naming-standardization.md` — Standardize API naming against industry (address fields, discounts, customer_note, label, brand/last4, etc.)
- `spree-starter-and-create-spree-app.md` — Replace monorepo server/ with spree-starter template repo, always include backend/ in create-spree-app, add spree eject
diff --git a/docs/plans/6.0-delivery-rate-provider.md b/docs/plans/6.0-delivery-rate-provider.md
new file mode 100644
index 0000000000..eca293b031
--- /dev/null
+++ b/docs/plans/6.0-delivery-rate-provider.md
@@ -0,0 +1,450 @@
+# Delivery Rate Provider Interface
+
+**Status:** Draft
+**Target:** Spree 6.0
+**Depends on:** Fulfillment & Delivery (6.0-fulfillment-and-delivery.md) for DeliveryMethod rename
+**Author:** Damian + Claude
+**Last updated:** 2026-03-20
+
+## Summary
+
+Add a pluggable delivery rate provider interface (`Spree::DeliveryRateProvider::Base`) that abstracts shipping rate calculation behind a clean contract. The default implementation (`Spree::DeliveryRateProvider::Internal`) preserves today's `ShippingCalculator` behavior (flat rate, per-item, weight-based — configured in admin). External providers (EasyPost, ShipStation, Shippo) implement the same interface, enabling real-time carrier rate lookups without monkey-patching.
+
+This follows the same open-closed provider pattern as `SearchProvider` (shipped in 5.4) and `TaxProvider` (planned for 6.0).
+
+## Problem
+
+1. **Calculators can't call external APIs.** `ShippingCalculator.compute_package(package) → BigDecimal` is a synchronous, stateless computation. There's no way to call EasyPost/UPS/FedEx for real-time rates, handle API failures, or cache responses.
+
+2. **Calculators return a single number.** External carriers return multiple service levels (Ground, Express, Overnight) with delivery dates, carrier names, and tracking capabilities. A calculator returns one `BigDecimal` — it can't model "UPS Ground: $8.99, arrives Thu" vs "UPS Express: $24.99, arrives tomorrow".
+
+3. **No lifecycle hooks.** When a customer selects a rate, external services need to "book" it. When an order ships, they need to create a shipment and generate labels. Calculators have no hooks for these events. (The FulfillmentProvider in `6.0-fulfillment-and-delivery.md` handles post-purchase lifecycle but NOT rate calculation.)
+
+4. **One calculator per shipping method.** Each `ShippingMethod` has exactly one calculator. But EasyPost returns rates for all carriers/services in one API call. You'd need N shipping methods (one per carrier service) each with a custom calculator that calls the same API — wasteful and fragile.
+
+5. **No access to order context.** Calculators receive a `Stock::Package` with items and weights. But external APIs need: origin address (stock location), destination address, package dimensions, declared value, insurance requirements, residential/commercial flag, hazmat indicators.
+
+## Current State
+
+| What exists | Where | What it does |
+|---|---|---|
+| `ShippingCalculator` | Base class | `compute_package(package) → BigDecimal` |
+| `Calculator::Shipping::FlatRate` | Built-in | Fixed amount per order |
+| `Calculator::Shipping::PerItem` | Built-in | Price × quantity |
+| `Calculator::Shipping::FlexiRate` | Built-in | Tiered pricing (first item + additional) |
+| `Calculator::Shipping::FlatPercentItemTotal` | Built-in | Percentage of cart total |
+| `Calculator::Shipping::PriceSack` | Built-in | Conditional pricing by threshold |
+| `Calculator::Shipping::DigitalDelivery` | Built-in | Zero cost for digital products |
+| `Stock::Estimator` | Rate engine | Iterates shipping methods, calls calculators, creates ShippingRates |
+| `Stock::Package` | Input model | Items + stock location → passed to calculators |
+| `ShippingMethod` | Config model | Zone + calculator + display settings |
+| `ShippingRate` | Result model | cost + tax_rate + selected flag |
+
+### Key flow today
+
+```
+Checkout::GetShippingRates
+ → Stock::Coordinator.packages(order)
+ → Packer → Splitters → Package objects
+ → Stock::Estimator.shipping_rates(package)
+ → shipping_methods(package) # filter by zone, availability, currency
+ → shipping_method.calculator.compute(package) # ONE number per method
+ → ShippingRate.new(cost: result)
+ → Customer sees list of rates, selects one
+```
+
+### Why calculators alone can't solve this
+
+Same pattern as tax — calculators answer "how much?" but can't answer "what options are available?" or "what happens after selection?":
+
+1. **Stateless per-item** — Calculator gets a Package, returns a BigDecimal. Can't make API calls, handle errors, cache results, or return structured data (carrier, service level, delivery date).
+2. **One result per method** — Each ShippingMethod + Calculator = one rate. External APIs return multiple rates per call.
+3. **No booking/lifecycle** — After customer selects a rate, external services need to book it, generate labels, track shipment. Calculators have no post-selection hooks.
+4. **No provider initialization** — Calculators don't receive API credentials, can't be configured per-store.
+
+**The provider replaces calculators entirely in 6.0:**
+
+```
+Provider (rate calculation)
+ └─ Internal provider → reads DeliveryMethod pricing config → computes directly
+ └─ EasyPost provider → EasyPost API → returns multiple DeliveryRate objects
+```
+
+The `Calculator` base class, `ShippingCalculator`, `CalculatedAdjustments` concern, and all `Calculator::Shipping::*` classes are removed. The Internal provider implements rate computation directly from DeliveryMethod preferences (flat rate amount, per-item amount, weight thresholds).
+
+## Key Decisions (do not deviate without discussion)
+
+### Provider replaces Stock::Estimator and Calculator entirely
+
+- **`Stock::Estimator` is removed.** The provider is the only entry point for delivery rate estimation. Zone filtering and method availability are handled inside the provider (or as shared utilities).
+- **`ShippingCalculator` and all `Calculator::Shipping::*` classes are removed.** No more polymorphic `has_one :calculator` on DeliveryMethod.
+- **DeliveryMethod becomes pure configuration** — stores name, zone, fulfillment type, pricing preferences (flat amount, per-item amount, weight thresholds, etc.) as preferences or JSON columns. No calculator association.
+- **All call sites** that called `Stock::Estimator` (Checkout::GetShippingRates, Cart::EstimateShippingRates) call the provider via `Spree.delivery_rate_provider`.
+
+### Provider returns structured rate objects, not BigDecimal
+
+```ruby
+provider.estimate_rates(package, delivery_methods)
+# → [
+# DeliveryRateEstimate.new(
+# delivery_method: method,
+# cost: 8.99,
+# carrier: 'UPS',
+# service_level: 'Ground',
+# estimated_delivery_date: Date.parse('2026-03-25'),
+# metadata: { easypost_rate_id: 'rate_abc' }
+# ),
+# ...
+# ]
+```
+
+The Internal provider wraps each `calculator.compute(package)` result in a `DeliveryRateEstimate` with no carrier/service metadata (same as today).
+
+### Provider is per delivery method
+
+Unlike search (global) and tax (per-store), delivery rate providers are **per delivery method**. One store can have:
+
+- "Free Shipping" → `Spree::DeliveryRateProvider::Internal` (flat rate: $0)
+- "Standard Shipping" → `SpreeEasyPost::DeliveryRateProvider` (UPS Ground rates)
+- "Express Shipping" → `SpreeEasyPost::DeliveryRateProvider` (UPS Express rates)
+- "Local Pickup" → `Spree::DeliveryRateProvider::Internal` (flat rate: $0)
+
+```ruby
+class Spree::DeliveryMethod < Spree.base_class
+ # Replaces the old calculator association
+ attribute :rate_provider, :string, default: 'Spree::DeliveryRateProvider::Internal'
+
+ def rate_provider_instance
+ rate_provider.constantize.new(self)
+ end
+end
+```
+
+The provider receives the **DeliveryMethod** (not store) — it reads API keys, carrier config, and pricing from the method's preferences/metadata.
+
+### FulfillmentProvider handles post-purchase, DeliveryRateProvider handles pre-purchase
+
+- **DeliveryRateProvider** — "What shipping options are available and how much do they cost?" (checkout)
+- **FulfillmentProvider** — "Create a shipment, generate labels, track delivery" (post-purchase)
+
+These are separate concerns. A store might use EasyPost for rates but manual fulfillment, or internal rates but ShipStation for fulfillment.
+
+### One rate per delivery method, cached API calls across methods
+
+Each DeliveryMethod returns one rate. But multiple DeliveryMethods can share the same external provider (e.g., "UPS Ground" and "UPS Express" both use the EasyPost provider). The provider should cache the API call per package (using `RequestStore` or similar) so a single EasyPost API call serves rates for all UPS methods.
+
+```
+DeliveryMethod "UPS Ground" → EasyPost provider → API call (cached) → extract Ground rate
+DeliveryMethod "UPS Express" → EasyPost provider → API call (cached) → extract Express rate
+DeliveryMethod "Free Shipping"→ Internal provider → flat rate: $0
+```
+
+## Design Details
+
+### Provider Base Class
+
+```ruby
+module Spree
+ module DeliveryRateProvider
+ class Base
+ attr_reader :delivery_method
+
+ def initialize(delivery_method)
+ @delivery_method = delivery_method
+ end
+
+ # Estimate delivery rate for a package.
+ # Returns a DeliveryRateEstimate or nil if not available.
+ #
+ # @param package [Spree::Stock::Package] items + stock location
+ # @return [DeliveryRateEstimate, nil]
+ def estimate(package)
+ raise NotImplementedError
+ end
+ end
+
+ DeliveryRateEstimate = Struct.new(
+ :delivery_method,
+ :cost,
+ :carrier,
+ :service_level,
+ :estimated_delivery_date,
+ :estimated_transit_days,
+ :metadata,
+ keyword_init: true
+ )
+ end
+end
+```
+
+### Internal Provider (default)
+
+Computes rate directly from DeliveryMethod pricing preferences — no Calculator indirection:
+
+```ruby
+module Spree
+ module DeliveryRateProvider
+ class Internal < Base
+ def estimate(package)
+ cost = compute_cost(package)
+ return nil unless cost
+
+ DeliveryRateEstimate.new(
+ delivery_method: delivery_method,
+ cost: cost,
+ carrier: nil,
+ service_level: nil,
+ estimated_delivery_date: estimated_date,
+ estimated_transit_days: delivery_method.estimated_transit_business_days_min,
+ metadata: {}
+ )
+ end
+
+ private
+
+ def compute_cost(package)
+ case delivery_method.pricing_type
+ when 'flat_rate'
+ delivery_method.preferred_amount
+ when 'per_item'
+ delivery_method.preferred_amount * package.quantity
+ when 'weight'
+ delivery_method.preferred_amount * package.weight
+ when 'percent'
+ package.item_total * (delivery_method.preferred_amount / 100.0)
+ when 'free'
+ 0
+ end
+ end
+
+ def estimated_date
+ return nil unless delivery_method.estimated_transit_business_days_min
+
+ delivery_method.estimated_transit_business_days_min.business_days.from_now
+ end
+ end
+ end
+end
+```
+
+`DeliveryMethod#pricing_type` and `#preferred_amount` replace the polymorphic calculator association with simple columns/preferences.
+
+### External Provider Example (EasyPost)
+
+Each EasyPost-backed DeliveryMethod stores its carrier + service in metadata:
+
+```ruby
+module SpreeEasyPost
+ class DeliveryRateProvider < Spree::DeliveryRateProvider::Base
+ def estimate(package)
+ # Get rate for this specific carrier+service from EasyPost
+ shipment = find_or_create_easypost_shipment(package)
+ rate = shipment.rates.detect do |r|
+ r.carrier == delivery_method.metadata['carrier'] &&
+ r.service == delivery_method.metadata['service']
+ end
+
+ return nil unless rate
+
+ Spree::DeliveryRateProvider::DeliveryRateEstimate.new(
+ delivery_method: delivery_method,
+ cost: rate.rate.to_d,
+ carrier: rate.carrier,
+ service_level: rate.service,
+ estimated_delivery_date: rate.delivery_date,
+ estimated_transit_days: rate.delivery_days,
+ metadata: { easypost_rate_id: rate.id, easypost_shipment_id: shipment.id }
+ )
+ end
+
+ private
+
+ # Cache the EasyPost shipment per package to avoid duplicate API calls
+ # (multiple DeliveryMethods may share the same EasyPost provider)
+ def find_or_create_easypost_shipment(package)
+ cache_key = "easypost_shipment_#{package.stock_location.id}_#{package.order.id}"
+ RequestStore.store[cache_key] ||= EasyPost::Shipment.create(
+ from_address: address_from_stock_location(package.stock_location),
+ to_address: address_from_order(package.order),
+ parcel: parcel_from_package(package)
+ )
+ end
+ end
+end
+```
+
+Admin setup: create DeliveryMethods for each carrier+service, set `rate_provider: 'SpreeEasyPost::DeliveryRateProvider'` and `metadata: { carrier: 'UPS', service: 'Ground' }`.
+
+### Integration Point: Checkout Services
+
+Each DeliveryMethod's provider is called directly — no Estimator intermediary:
+
+```ruby
+class Spree::Checkout::GetDeliveryRates
+ def call(order:)
+ order.fulfillments.each do |fulfillment|
+ package = fulfillment.to_package
+ methods = available_delivery_methods(order, fulfillment)
+
+ rates = methods.filter_map do |method|
+ provider = method.rate_provider_instance # each method has its own provider
+ estimate = provider.estimate(package)
+ next unless estimate
+
+ fulfillment.delivery_rates.build(
+ delivery_method: estimate.delivery_method,
+ cost: estimate.cost,
+ carrier: estimate.carrier,
+ service_level: estimate.service_level,
+ estimated_delivery_date: estimate.estimated_delivery_date,
+ metadata: estimate.metadata
+ )
+ end
+
+ # Select cheapest as default
+ rates.min_by(&:cost)&.update(selected: true) if rates.any?
+ end
+ end
+end
+```
+
+Each DeliveryMethod returns one rate from its provider. The checkout service collects all rates and lets the customer choose.
+
+## Migration Path
+
+### Phase 1: Provider interface + Internal provider
+
+- Create `Spree::DeliveryRateProvider::Base`, `::Internal`, `::DeliveryRateEstimate`
+- Register `Spree.delivery_rate_provider` on Spree module
+- Internal provider wraps existing `calculator.compute(package)` — zero behavior change
+- **No changes to Estimator yet** — just the interface
+
+### Phase 2: Wire into Estimator
+
+- Modify `Stock::Estimator#calculate_shipping_rates` to delegate to provider
+- Internal provider produces identical results to current calculator flow
+- All existing tests pass unchanged
+
+### Phase 3: Enrich DeliveryRate/ShippingRate model
+
+- Add `carrier`, `service_level`, `estimated_delivery_date`, `metadata` columns to ShippingRate (or DeliveryRate after rename)
+- Serialize provider-specific data in metadata (e.g., `easypost_rate_id`)
+- Update Store API serializer to expose new fields
+
+### Phase 4: Reference external provider
+
+- Document how to build an EasyPost/Shippo provider
+- Ship as a how-to guide (like custom-search-provider)
+
+## Relationship to Other 6.0 Plans
+
+### Fulfillment & Delivery (6.0-fulfillment-and-delivery.md)
+
+That plan renames models and adds `FulfillmentProvider` for post-purchase lifecycle (create shipment, track, cancel). This plan adds `DeliveryRateProvider` for pre-purchase rate calculation. They're complementary:
+
+```
+Pre-purchase: DeliveryRateProvider → "How much does shipping cost?"
+Post-purchase: FulfillmentProvider → "Create shipment, generate label, track delivery"
+```
+
+A DeliveryMethod has both:
+- `rate_provider` (for rate calculation) — replaces `calculator` association
+- `fulfillment_provider` (for post-purchase) — from fulfillment plan
+- Rate provider is per-method (different methods can use different providers)
+
+### Tax Provider (6.0-tax-provider.md)
+
+Same open-closed pattern:
+- Tax: `TaxProvider::Internal` wraps `TaxRate + Calculator::DefaultTax`
+- Delivery: `DeliveryRateProvider::Internal` wraps `ShippingMethod.calculator`
+- Both have lifecycle methods the internal provider no-ops on
+
+### Search Provider (shipped in 5.4)
+
+Established the pattern. All three follow the same open-closed architecture:
+
+| | Search | Tax | Delivery Rates |
+|---|---|---|---|
+| **Scope** | Global (`Spree.search_provider`) | Per-Market (`Market#tax_provider`) | Per-method (`DeliveryMethod#rate_provider`) |
+| **Replaces** | Ransack/ILIKE | `TaxRate.adjust` + Calculator | `Stock::Estimator` + Calculator |
+| **Internal** | Database (SQL) | Reads TaxRate data directly | Reads DeliveryMethod prefs directly |
+| **External** | Meilisearch | Avalara / TaxJar | EasyPost / Shippo |
+| **Calculators** | N/A | Removed in 6.0 | Removed in 6.0 |
+
+### DeliveryZone replaces Zone for shipping
+
+The current generic `Zone` (country or state members) is replaced by `DeliveryZone` which adds postal code range support:
+
+```ruby
+class Spree::DeliveryZone < Spree.base_class
+ has_prefix_id :dz
+
+ has_many :delivery_zone_members, dependent: :destroy
+ has_many :delivery_method_zones, dependent: :destroy
+ has_many :delivery_methods, through: :delivery_method_zones
+
+ validates :name, presence: true
+
+ def include?(address)
+ delivery_zone_members.any? { |member| member.match?(address) }
+ end
+end
+
+class Spree::DeliveryZoneMember < Spree.base_class
+ belongs_to :delivery_zone
+
+ # Polymorphic: country, state, or postal code range
+ attribute :member_type, :string # 'country', 'state', 'postal_code'
+ belongs_to :country, class_name: 'Spree::Country', optional: true
+ belongs_to :state, class_name: 'Spree::State', optional: true
+
+ # For postal code ranges
+ attribute :postal_code_from, :string
+ attribute :postal_code_to, :string
+
+ def match?(address)
+ case member_type
+ when 'country'
+ address.country_id == country_id
+ when 'state'
+ address.state_id == state_id
+ when 'postal_code'
+ address.zipcode.to_s >= postal_code_from.to_s &&
+ address.zipcode.to_s <= postal_code_to.to_s
+ end
+ end
+end
+```
+
+This enables delivery scenarios that the current Zone model can't handle:
+- "Free delivery to postcodes 10001-10099" (local delivery)
+- "Express available in London only" (state + postal code)
+- "International shipping to EU countries" (country-level, same as today)
+
+Tax doesn't use zones at all — TaxRate links directly to country/state (see `6.0-tax-provider.md`). The generic `Zone` model is removed in 6.0, replaced by `DeliveryZone` for delivery and direct country/state FKs on TaxRate for tax.
+
+## Constraints on Current Work
+
+- **Don't add new shipping calculators for external carrier APIs.** The calculator pattern can't support them properly. Use the provider interface instead.
+- **Don't monkey-patch Stock::Estimator.** The provider interface is the intended seam.
+- **New ShippingRate/DeliveryRate fields should be designed for the enriched model** (carrier, service_level, estimated_delivery_date, metadata).
+- **FulfillmentProvider is separate.** Don't mix rate calculation into the fulfillment provider.
+
+## Open Questions
+
+1. **Rate caching.** External API calls during checkout are expensive (~500ms). Should the provider cache rates for a configurable TTL (e.g., 5 minutes)? Or should caching be the provider's responsibility? Leaning toward provider responsibility — different APIs have different caching needs.
+
+2. **Multi-package rates.** Some carriers offer discounts for shipping multiple packages together. Should the provider receive all packages at once, or one at a time? Current Estimator processes packages independently. Leaning toward provider receives one package at a time (simpler, matches current flow), with a future enhancement for multi-package optimization.
+
+3. **Rate validation at completion.** Rates can expire between checkout and payment. Should the provider have a `validate_rate(shipping_rate)` method called at order completion? Or re-estimate and compare?
+
+## References
+
+- Current estimator: `spree/core/app/models/spree/stock/estimator.rb`
+- Current calculators: `spree/core/app/models/spree/calculator/shipping/`
+- Current shipping method: `spree/core/app/models/spree/shipping_method.rb`
+- Current shipping rate: `spree/core/app/models/spree/shipping_rate.rb`
+- Stock coordinator: `spree/core/app/models/spree/stock/coordinator.rb`
+- Fulfillment plan: `6.0-fulfillment-and-delivery.md`
+- Tax provider plan: `6.0-tax-provider.md`
+- Search provider (reference implementation): `spree/core/app/models/spree/search_provider/`
diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.md
index 2fad2d25e3..015615d944 100644
--- a/docs/plans/6.0-tax-provider.md
+++ b/docs/plans/6.0-tax-provider.md
@@ -4,7 +4,7 @@
**Target:** Spree 6.0
**Depends on:** Split Adjustments (6.0-split-adjustments.md) for TaxLine model, Channels/Catalogs/B2B (6.0-channels-catalogs-b2b.md) for Company.tax_exempt
**Author:** Damian + Claude
-**Last updated:** 2026-03-18
+**Last updated:** 2026-03-20
## Summary
@@ -58,13 +58,32 @@ Order#create_tax_charge!
→ TaxRate.adjust(order, shipments)
```
+### Why calculators alone can't solve this
+
+The current `Calculator::DefaultTax` is a stateless per-item computation: `calculator.compute(item) → BigDecimal`. Calculators handle "how much tax is owed on this item?" but cannot handle:
+
+1. **Order-level transactions** — Avalara/TaxJar price the entire order in one API call, returning tax per line item. Calculators work item-by-item with no cross-item coordination.
+2. **Lifecycle events** — No hooks for commit (order completed), void (order cancelled), refund (items returned). External services distinguish estimate vs committed transactions for filing/reporting.
+3. **State storage** — Calculators are stateless. External providers need to store transaction IDs (e.g., `avalara_transaction_id`) on the order for later commit/void.
+4. **Exemption logic** — Need to check company exemption certificates before calling the API. Calculators only compute amounts.
+5. **Entry point control** — Calculators are called inside the adjustment flow via `AdjustmentSource.create_adjustment → compute_amount → calculator.compute`. External providers need to intercept at the `TaxRate.adjust` entry point to decide whether to use internal rates or call their API.
+
+**The provider replaces calculators entirely in 6.0.** The Internal provider implements the tax math directly (rate × amount, VAT inclusion) — no `Calculator::DefaultTax` indirection. External providers call their API directly. The `Calculator` base class and `CalculatedAdjustments` concern are removed from `TaxRate`.
+
+```
+Provider (order lifecycle)
+ └─ Internal provider → reads TaxRate (rate %, zone, included?) → computes directly
+ └─ Avalara provider → Avalara API → writes TaxLine records directly
+```
+
## Key Decisions (do not deviate without discussion)
-### Provider replaces TaxRate.adjust, not TaxRate
+### Provider replaces TaxRate.adjust entirely
-- **TaxRate stays as-is.** Rates, zones, categories, calculators — all unchanged. The internal provider uses them.
-- **The provider replaces `TaxRate.adjust(order, items)` as the entry point.** Instead of calling `TaxRate.adjust` directly, the adjuster calls the provider.
-- **TaxRate.adjust becomes an internal implementation detail** of `TaxProvider::Internal`, not a public API that integrations need to understand.
+- **`TaxRate.adjust` is removed.** The provider is the only entry point for tax calculation. No more `AdjustmentSource`, no more `CalculatedAdjustments` concern on TaxRate, no more `Calculator::DefaultTax`.
+- **`TaxRate` stays as a data model** — stores rate %, zone, tax category, included_in_price flag. The Internal provider reads it to compute tax. But `TaxRate` no longer has behavior — it's pure configuration.
+- **`Calculator::DefaultTax` is removed.** The Internal provider implements the tax math directly (rate × discounted_amount for additional tax, deduced_total for included tax).
+- **All call sites that called `TaxRate.adjust`** (Order, LineItem, checkout services) now call the provider via `Spree.tax_provider`.
### Provider contract: estimate and commit
@@ -85,15 +104,68 @@ With the split-adjustments plan (6.0), tax results are written as `Spree::TaxLin
Before split-adjustments ships, the provider writes `Spree::Adjustment` records (backward compatible).
-### Provider is per-store
+### Provider is per-Market
-Different stores may use different tax services (US store uses Avalara, EU store uses internal VAT rates). Configuration is on the Store model:
+Markets represent regional commerce operations. Each market can have its own tax provider, matching how Shopify and Medusa handle it:
```ruby
-store.preferred_tax_provider = 'Spree::TaxProvider::Internal' # default
+class Spree::Market < Spree.base_class
+ attribute :tax_provider, :string, default: 'Spree::TaxProvider::Internal'
+
+ def tax_provider_instance
+ tax_provider.constantize.new(self)
+ end
+end
+```
+
+TaxRate is an **internal provider concept only**. External providers ignore it — they have their own jurisdiction databases.
+
+```
+Market "US" → tax_provider: 'SpreeAvalara::TaxProvider'
+ └─ Avalara API handles all US jurisdictions
+ └─ TaxRates exist in DB but not used for this market
+
+Market "EU" → tax_provider: 'Spree::TaxProvider::Internal'
+ └─ TaxRate: country=Germany, category=Standard, rate=19%, included=true
+ └─ TaxRate: country=Germany, category=Food, rate=7%, included=true
+ └─ TaxRate: country=France, category=Standard, rate=20%, included=true
```
-This is a preference (Spree::Preferences), not a global Dependency, because it varies per store.
+### Drop TaxZone — TaxRate links directly to country/state
+
+The current `Zone` model is an unnecessary indirection for tax. Merchants don't think in "zones" — they think "Germany has 19% VAT". The Internal provider matches TaxRates directly by country/state on the order address:
+
+```ruby
+class Spree::TaxRate < Spree.base_class
+ belongs_to :tax_category
+ belongs_to :country, class_name: 'Spree::Country', optional: true # nil = all countries
+ belongs_to :state, class_name: 'Spree::State', optional: true # nil = entire country
+
+ # rate: 0.19, included_in_price: true, name: "DE VAT 19%"
+end
+```
+
+No zones, no zone members, no indirect lookups. This matches Shopify (rates per country/region) and Medusa (TaxRegion per country/province).
+
+```ruby
+# TaxRate.for_address(address) — finds applicable rates
+scope :for_address, ->(address) {
+ where(country: [address.country, nil]) # country-specific or global
+ .where(state: [address.state, nil]) # state-specific or country-wide
+}
+```
+
+State-level rates override country-level (more specific wins). A rate with `country=US, state=CA` takes precedence over `country=US, state=nil` for California addresses.
+
+The generic `Zone` model is replaced by `DeliveryZone` for shipping (see `6.0-delivery-rate-provider.md`) — delivery needs country grouping and postal code granularity that tax doesn't.
+
+This matches the natural scope hierarchy:
+
+| Provider | Scope | Why |
+|---|---|---|
+| Search | Global (`Spree.search_provider`) | One search engine per instance |
+| Tax | Per-Market (`Market#tax_provider`) | Different tax rules/services per region |
+| Delivery rates | Per-DeliveryMethod (`DeliveryMethod#rate_provider`) | Different carriers per shipping option |
### Tax exemption is part of the provider contract
@@ -103,9 +175,9 @@ provider.exempt?(order) # → true if order should be tax-exempt
The provider checks Company.tax_exempt, exemption certificates, and any external validation. If exempt, `estimate` returns zero amounts. This keeps exemption logic in one place instead of scattered across models.
-### Internal provider preserves all existing behavior
+### Internal provider computes directly from TaxRate data
-`TaxProvider::Internal` delegates to `TaxRate.match`, `TaxRate.store_pre_tax_amount`, and `Calculator::DefaultTax`. The behavior is identical to today — same rates, same zones, same VAT math. No regressions.
+`TaxProvider::Internal` reads `TaxRate` records (rate %, zone, included_in_price) and computes tax directly — no `Calculator::DefaultTax` indirection. The math is the same (rate × discounted_amount for additional, deduced_total for VAT), just implemented in the provider instead of a calculator.
## Design Details
@@ -115,10 +187,10 @@ The provider checks Company.tax_exempt, exemption certificates, and any external
module Spree
module TaxProvider
class Base
- attr_reader :store
+ attr_reader :market
- def initialize(store)
- @store = store
+ def initialize(market)
+ @market = market
end
# Estimate tax for items in an order. Called during checkout recalculation.
@@ -177,40 +249,52 @@ end
### Internal Provider (default)
+Computes tax directly from TaxRate records — no Calculator::DefaultTax:
+
```ruby
module Spree
module TaxProvider
class Internal < Base
- # Wraps existing TaxRate.adjust logic
def estimate(order, items)
return clear_tax(order, items) if exempt?(order)
- line_items = items.select { |i| i.is_a?(Spree::LineItem) }
- shipments = items.select { |i| i.is_a?(Spree::Shipment) }
+ address = order.tax_address
+ rates = Spree::TaxRate.for_address(address)
- Spree::TaxRate.adjust(order, line_items) if line_items.any?
- Spree::TaxRate.adjust(order, shipments) if shipments.any?
+ items.each do |item|
+ applicable_rates = rates.select { |r| r.tax_category_id == item.tax_category_id }
+ applicable_rates.each do |rate|
+ amount = compute_tax(rate, item)
+ upsert_tax_line(order, item, rate, amount)
+ end
+ end
end
- # Internal rates need no commit — no external service to notify
- def commit(order)
- # no-op
- end
+ private
- def void(order)
- # no-op
+ def compute_tax(rate, item)
+ if rate.included_in_price?
+ # VAT: deduced from price
+ pre_tax = item.discounted_amount / (1 + rate.amount)
+ (pre_tax * rate.amount).round(2)
+ else
+ # Sales tax: added on top
+ (item.discounted_amount * rate.amount).round(2)
+ end
end
- def refund(order, return_items)
- # Recalculation handles this — when items are returned,
- # the next estimate() call recomputes with reduced amounts
+ def upsert_tax_line(order, item, rate, amount)
+ # Creates or updates TaxLine (6.0) for this item + rate
+ tax_line = item.tax_lines.find_or_initialize_by(tax_rate: rate, order: order)
+ tax_line.amount = amount
+ tax_line.included = rate.included_in_price?
+ tax_line.label = rate.name
+ tax_line.save!
end
- private
-
def clear_tax(order, items)
items.each do |item|
- item.adjustments.tax.destroy_all
+ item.tax_lines.destroy_all
item.update_columns(
included_tax_total: 0,
additional_tax_total: 0
@@ -291,36 +375,25 @@ module SpreeTaxAvalara
end
```
-### Integration Point: Tax Adjuster
+### Integration Point: Order Tax Calculation
-The Tax adjuster (which coordinates tax recalculation) delegates to the provider instead of calling TaxRate directly:
+The order resolves its market, then calls the market's tax provider. No more `Adjuster::Tax` — the provider is called directly from the order update flow:
```ruby
-module Spree
- module Adjustable
- module Adjuster
- class Tax < Base
- def update
- provider = tax_provider
-
- # Delegate to provider
- provider.estimate(order, [adjustable])
-
- # Read back results for totals
- tax = adjustable.adjustments.tax
- included = tax.select(&:included?).sum(&:amount)
- additional = tax.reject(&:included?).sum(&:amount)
-
- @totals[:included_tax_total] = included
- @totals[:additional_tax_total] = additional
- end
-
- private
-
- def tax_provider
- store = order.store
- provider_class = store.preferred_tax_provider || 'Spree::TaxProvider::Internal'
- provider_class.constantize.new(store)
+# In OrderUpdater or checkout service
+class Spree::OrderUpdater
+ def update_tax
+ market = order.market || order.store.default_market
+ provider = market.tax_provider_instance
+
+ items = order.line_items + order.shipments
+ provider.estimate(order, items)
+
+ # Read totals from TaxLines
+ order.included_tax_total = order.tax_lines.included_in_price.sum(:amount)
+ order.additional_tax_total = order.tax_lines.additional.sum(:amount)
+ end
+end
end
def order
@@ -332,42 +405,16 @@ module Spree
end
```
-After split-adjustments (6.0), this becomes:
-
-```ruby
-# Post-split-adjustments version
-module Spree
- module Adjustable
- module Adjuster
- class Tax < Base
- def update
- provider = tax_provider
- provider.estimate(order, [adjustable])
-
- # Read from typed TaxLine records
- included = adjustable.tax_lines.included_in_price.sum(:amount)
- additional = adjustable.tax_lines.additional.sum(:amount)
-
- @totals[:included_tax_total] = included
- @totals[:additional_tax_total] = additional
- end
- end
- end
- end
-end
-```
-
### Integration Point: Order Completion
```ruby
-# In Spree::Checkout::Complete (or order completion flow)
class Spree::Checkout::Complete
def call(order:)
# ... existing completion logic ...
# Commit tax document with provider
- tax_provider = order.store.preferred_tax_provider&.constantize || Spree::TaxProvider::Internal
- tax_provider.new(order.store).commit(order)
+ market = order.market || order.store.default_market
+ market.tax_provider_instance.commit(order)
# ... rest of completion ...
end
@@ -377,24 +424,15 @@ end
### Integration Point: Order Cancellation
```ruby
-# In Spree::Orders::Cancel
class Spree::Orders::Cancel
def call(order:)
# ... existing cancellation logic ...
- # Void tax document
- tax_provider = order.store.preferred_tax_provider&.constantize || Spree::TaxProvider::Internal
- tax_provider.new(order.store).void(order)
+ market = order.market || order.store.default_market
+ market.tax_provider_instance.void(order)
end
end
```
-
-### Store Configuration
-
-```ruby
-class Spree::Store < Spree.base_class
- preference :tax_provider, :string, default: 'Spree::TaxProvider::Internal'
-end
```
Admin API allows setting per store:
@@ -468,7 +506,7 @@ end
### Phase 2: Wire into adjuster
- Modify `Adjuster::Tax` to delegate to provider instead of calling TaxRate directly
-- Add `commit` call to `Checkout::Complete`
+- Add `commit` call to `Carts::Complete`
- Add `void` call to `Orders::Cancel`
- Add `refund` hook to returns flow
- All existing behavior preserved via Internal provider