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.

Refine 6.0 tax provider contract after #14056 review

Łukasz Adamczyk8d6754187291
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index 6ab3fd1e12..fc5b47b50d 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -25,7 +25,8 @@
"mcp__scout-apm__get_app_error_groups",
"mcp__scout-apm__get_app_anomaly_events",
"mcp__claude_ai_Spree_Commerce_Docs_MCP__query_docs_filesystem_spree_commerce_documentation",
- "Bash(bundle exec *)"
+ "Bash(bundle exec *)",
+ "Skill(stripe:stripe-docs)"
],
"deny": [
"Bash(sudo *)",
diff --git a/.gitignore b/.gitignore
index 8bde16c029..1c80ba90ce 100644
--- a/.gitignore
+++ b/.gitignore
@@ -66,3 +66,4 @@ packages/cli/templates/dashboard-starter
.claude/worktrees
*.tsbuildinfo
.claude/scheduled_tasks.lock
+CLAUDE.local.md
diff --git a/CLAUDE.md b/CLAUDE.md
index 8f5ace30df..f6c387f2d1 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -23,7 +23,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
- `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, replaces TaxRate.adjust + Calculator; TaxRate gets direct country/state FKs (tax decoupled from Zone; Zone model dropped in 6.0 via `6.0-delivery-zones.md`); reference provider: Avalara (decisions.md 2026-07-30)
+- `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). Pending: Phase 3 contract enrichment, Phase 4 per-Market selection + commit/void/refund wiring, Phase 5 tax-side Zone decoupling (Zone model survives 6.0), Phase 6 `spree_tax_avalara`, Phase 7 exemption certificates (gated on Company from the B2B plan)
- `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider wrapping Stock::Estimator (calculators stay — 2026-07-27 reversal), `store_id` on ShippingMethod, enriched DeliveryRate (carrier/service/date/metadata); monorepo ships one reference multi-carrier provider (Shippo/EasyPost, pick pending — decisions.md 2026-07-29); method rows stay regional (no cross-market method entity)
- `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-rich-text-descriptions.md` — Drop ActionText **entirely** at 6.0 (incl. CustomFields::RichText values + Order/User internal notes; gem dependency removed), store sanitized HTML in text columns, serve `field` + `field_html`, **write via `field_html`** (read/write symmetry). description_html serializer shipped 5.4; sanitizer shipped in **5.6.2** with a permissive-but-safe configurable allowlist + `sanitize_rich_text` step in the 5.5→5.6 upgrade manifest (decisions.md 2026-07-27/28), tightened to the Tiptap set at 6.0
diff --git a/docs/plans/6.0-6.1-split-adjustments.md b/docs/plans/6.0-6.1-split-adjustments.md
index dd4916f3bf..16c253e3d7 100644
--- a/docs/plans/6.0-6.1-split-adjustments.md
+++ b/docs/plans/6.0-6.1-split-adjustments.md
@@ -157,7 +157,9 @@ end
Columns beyond the FKs: `amount`, `rate` (decimal snapshot — enables rate-grouped tax reports and receipts even after TaxRate deletion), `label`, `included`, `provider_id` (string, e.g. `'internal'`, `'avalara'`), `data` (JSON — provider payloads such as jurisdiction breakdowns; jsonb where supported).
-**Write contract:** providers use replace-all set semantics per estimate — delete the target items' existing TaxLines, insert fresh ones. No unique-index-based upsert identity (it only works for Internal-provider lines); plain indexes on the FKs.
+**2026-08-05 additions (from the `6.0-tax-provider.md` contract refinement, driven by the spree/spree#14056 review):** `taxability_reason` (string, nullable — machine-readable cause of the treatment: `standard_rated`, `zero_rated`, `reverse_charge`, `intra_community_supply`, `export`, `customer_exempt`, …; extensible vocabulary + reason→UNTDID 5305/VATEX lookup maps live on the tax-provider plan) and the jurisdiction snapshot `country_iso` / `state_code` (the taxing jurisdiction of the line — OSS returns group per member state of consumption, and origin-taxed cases make it non-derivable from ship-to). EN 16931 category/exemption codes are deliberately NOT columns — derivable at invoicing time from the reason plus order facts.
+
+**Write contract:** providers use replace-all set semantics per estimate — delete the target items' existing TaxLines, insert fresh ones. No unique-index-based upsert identity (it only works for Internal-provider lines); plain indexes on the FKs. **A provider writes a TaxLine for every item it formed a treatment for — including zero-amount treatments** (matched zero-rate, exemption, reverse charge → `amount: 0` row with its reason); an item the provider had no opinion on (Internal with no matching rates) produces no row. TaxLines are the only persisted record of tax treatment — no exemption flags on customer, order or line items.
### Discount
diff --git a/docs/plans/6.0-admin-api.md b/docs/plans/6.0-admin-api.md
index 7137f6555e..1228817f43 100644
--- a/docs/plans/6.0-admin-api.md
+++ b/docs/plans/6.0-admin-api.md
@@ -4,7 +4,7 @@
**Target:** Spree 6.0
**Depends on:** `6.0-admin-spa.md`, `6.0-platform-auth.md`
**Author:** damian
-**Last updated:** 2026-06-25
+**Last updated:** 2026-08-05
## Summary
@@ -776,6 +776,8 @@ API key scopes: `read_vendors` / `write_vendors`, `read_commissions` / `write_co
- [ ] `DELETE /api/v3/admin/tax_rates/:id`
> **6.0:** `zone_id` FK is dropped. `TaxRate` gets direct `country_id` + `state_id` FKs. Tax logic moves behind a `TaxProvider` interface. See `6.0-tax-provider.md`.
+>
+> **Built by the tax-provider plan (2026-08-05), Phase 3.** These rows are the Internal provider's entire configuration, so that plan cannot verify its own tax calculation without them, and it specifies the serializer alongside the provider work. They ship against the `zone_id` shape and switch to `country_id`/`state_id` in its Phase 5 — tick these boxes from there rather than building separately.
### Markets
- [x] `GET /api/v3/admin/markets`
diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.md
index ae9b13da9e..99b1250c9a 100644
--- a/docs/plans/6.0-tax-provider.md
+++ b/docs/plans/6.0-tax-provider.md
@@ -1,52 +1,61 @@
# Tax Provider Interface
-**Status:** Draft
+**Status:** In progress — the provider seam, `Spree::TaxProvider::Internal` and the `TaxLine` write path shipped to 6-0-dev with the core-rewrite waves (see Current State). Remaining: the contract enrichment below (2026-08-05 revision), per-Market provider selection, commit/void/refund lifecycle wiring, Phase 5 Zone decoupling, and the Avalara reference gem.
+
> **Store binding (2026-07-29):** TaxRate and TaxCategory adopt the every-major-model-carries-a-store_id convention as part of this plan's implementation (`Spree::SingleStoreResource`, backfill task, NOT NULL in 6.1) — same treatment DeliveryMethod/StockLocation/DeliveryZone received on the 6.0 core-rewrite branch.
> **Reference provider (2026-07-30):** the first-party reference tax provider is **Avalara** (enterprise-seller target; AvaTax is the enterprise standard). Ships as the canonical Integration-subclass + stateless-provider pair — `Spree::Integrations::Avalara` holding store credentials, the provider writing TaxLines with `provider_id: 'avalara'`. The built-in `'internal'` engine remains the OSS default. Stripe Tax stays third-party territory and carries the merchant-of-record credential caveat (decisions.md 2026-07-30).
> **Provider registry option (2026-07-30):** `TaxLine.provider_id` stays a plain string registry key (`'internal'`, `'avalara'`) — Medusa's tax lines use the identical field name and semantics (`tp_system` for their built-in engine), so the name is the term of art for the audience 6.0 targets; it is deliberately NOT a table reference, preserving the snapshot property after config changes. When this plan is implemented, consider Medusa's shape for the config side: a minimal registry model per engine (identifier + enabled — no credentials) backing per-market provider selection in the admin, with credentialed connections staying `Spree::Integration`. Tax lines keep stamping the string key regardless.
+> **Contract refinement (2026-08-05):** the provider contract was reworked after the community review on spree/spree#14056, with every concern verified against primary sources (EN 16931 / VAT Directive / VIES), the major provider APIs (Avalara, Stripe Tax, TaxJar, Vertex) and platform practice (Medusa, Saleor, commercetools, Shopify, Magento, Odoo). Headlines: tax results carry a **taxability reason**, not just an amount; buyer tax identity becomes a first-class **`Spree::TaxIdentifier`** model with an order-time snapshot; exemption is a **typed estimate input** (the boolean `exempt?` is removed); the **effective date** is an explicit input; providers declare **capability limits** honestly. See Key Decisions.
+
**Target:** Spree 6.0
-**Depends on:** Split Adjustments (6.0-6.1-split-adjustments.md) for TaxLine model, Channels/Catalogs/B2B (6.0-channels-catalogs-b2b.md) for Company.tax_exempt
+**Depends on:** Split Adjustments (6.0-6.1-split-adjustments.md — shipped; provides TaxLine). Phase 7 (exemption certificates) and the Company link in the tax-identifier chain are gated on the B2B plan (6.1-channels-catalogs-b2b.md); nothing in Phases 3–6 waits on it.
**Author:** Damian + Claude
-**Last updated:** 2026-07-27
+**Last updated:** 2026-08-05
## Summary
-Add a pluggable tax provider interface (`Spree::TaxProvider::Base`) that abstracts tax calculation behind a clean contract. The default implementation (`Spree::TaxProvider::Internal`) preserves today's TaxRate + Zone + Calculator behavior. External providers (Avalara, TaxJar, Vertex) implement the same interface, enabling drop-in tax services without changing the checkout flow, adjustment system, or order updater.
+A pluggable tax provider interface (`Spree::TaxProvider::Base`) abstracts tax calculation behind a clean contract. The default implementation (`Spree::TaxProvider::Internal`) computes from TaxRate configuration. External providers (Avalara, TaxJar, Vertex) implement the same interface, enabling drop-in tax services without changing the checkout flow, the typed-adjustment system, or the totals recalculation.
-The interface sits between the adjuster layer ("calculate tax for these items") and the calculation engine ("here's how much tax is owed"). Everything upstream (checkout flow, OrderUpdater, TaxLine creation) and downstream (totals, serializers, reporting) is unchanged.
+The seam itself is live on 6-0-dev: providers are the only sanctioned writers of `Spree::TaxLine` rows, called from the single totals seam (`Carts::RecalculateTotals`). This plan now covers what the seam still owes: a result contract rich enough for EU/US reality (treatment, not just amount), buyer tax identity, exemptions as typed input, transaction dates, per-market selection, and the order lifecycle (commit/void/refund).
## Problem
-1. **No tax provider seam.** `TaxRate.adjust(order, items)` is hardcoded to match rates from the database, compute amounts via `Calculator::DefaultTax`, and create adjustments. There's no point where an external service can intercept. Integrations like Avalara have to monkey-patch `TaxRate` or wrap the entire adjuster.
+1. **No tax provider seam.** Tax calculation was hardcoded to match rates from the database, compute amounts via `Calculator::DefaultTax`, and create adjustments — no point where an external service could intercept. Integrations like Avalara had to monkey-patch `TaxRate` or wrap the entire adjuster.
+
+2. **Internal rates don't scale across jurisdictions.** US merchants with nexus in 30+ states need thousands of rate entries with zip-code-level granularity. The admin UI isn't designed for this, and rates change constantly. External services handle this via API calls with real-time rate lookups. An internal rate table cannot express US local (county/city/district) tax at all — and must say so rather than under-collect silently.
-2. **Internal rates don't scale across jurisdictions.** US merchants with nexus in 30+ states need thousands of rate entries with zip-code-level granularity. The admin UI isn't designed for this, and rates change constantly. External services handle this via API calls with real-time rate lookups.
+3. **Tax results are amount-only.** A 0% from reverse charge, a 0% from an export and a 0% from an exemption are different facts: they land in different boxes of a tax return, and European e-invoices must state which category applied to every line — including the zero ones. An amount-only tax record loses the distinction at the only moment it is knowable.
-3. **No tax exemption flow.** `Company.tax_exempt` exists (from the B2B plan) but there's no exemption certificate management — no storage, validation, or automatic zero-rating based on certificate status. Enterprise B2B requires this.
+4. **No buyer tax identity.** Spree has no field for a customer's VAT/tax registration number anywhere. Even a perfectly good Avalara integration cannot get EU B2B reverse charge right, because the one input the provider needs does not exist (Avalara: `businessIdentificationNo`; Stripe Tax: `customer_details.tax_ids`). Shopify has the same hole and its e-invoicing ecosystem resorts to smuggling VAT IDs through order notes.
-4. **No tax estimation vs commitment distinction.** External providers distinguish between "estimate" (during checkout, reversible) and "commit" (on order completion, creates a tax filing record). Spree treats all tax calculations identically.
+5. **VAT reverse charge is manual.** EU B2B transactions where the buyer is VAT-registered in another member state should reverse-charge (zero VAT from the seller, buyer self-assesses). The decision hinges on the buyer's registration number being valid — for goods, EU law has made that a hard condition of zero-rating since 2020, not a formality — with a fallback to domestic VAT when it is not. The validation result has to be captured at the time of sale, because the EU's verification service only answers "valid right now" and cannot be asked about a past date. This is too complex for static rate tables and today happens entirely outside Spree.
-5. **VAT reverse charge is manual.** EU B2B transactions where the buyer is VAT-registered in another member state should reverse-charge (zero VAT from seller, buyer self-assesses). This requires VAT registration validation and is too complex for static rate tables.
+6. **No tax estimation vs commitment distinction.** External providers distinguish "estimate" (during checkout, reversible) and "commit" (on completion, creates a tax filing record for reporting and filing). Spree treats all tax calculations identically — nothing tells the tax service an order was completed, cancelled, or partially returned.
+
+7. **Dates are implicitly "now".** Every major provider API takes a transaction/tax date (Avalara `date` + `taxOverride.taxDate`, Stripe `tax_date`, TaxJar `transaction_date`, Vertex `documentDate`) because the rate that applies is the one in force when the sale happened, and rates change on ordinary legislative schedules. Tax calculation with no date input cannot price a refund at the original sale date, and silently disagrees with already-filed returns when a rate changes.
+
+8. **No tax exemption flow.** There is no way to pass exemption evidence (entity exemptions, resale certificates) into the calculation, and no record of *why* a line was untaxed afterwards.
## Current State
-| What exists | Where | What it does |
+### Starting point (5.x — the state this plan set out to replace)
+
+| What existed | Where | What it did |
|---|---|---|
-| `TaxRate` model | `core/app/models/spree/tax_rate.rb` | Stores rate %, zone, tax category. `adjust()` is the entry point. |
-| `TaxRate.match(zone)` | TaxRate class method | Finds rates whose zone includes the order's tax zone |
-| `Calculator::DefaultTax` | `core/app/models/spree/calculator/` | Computes tax amount for line items, shipments, shipping rates |
-| `VatPriceCalculation` | `core/app/models/concerns/` | Handles included-in-price tax math |
-| `TaxRate.store_pre_tax_amount` | TaxRate class method | Computes and stores pre-tax amounts for VAT calculations |
-| `Adjuster::Tax` | `core/app/models/spree/adjustable/adjuster/` | Orchestrates tax adjustment updates during recalculation |
-| `TaxCategory` | `core/app/models/spree/tax_category.rb` | Groups products/variants by tax type |
+| `TaxRate` model | `core/app/models/spree/tax_rate.rb` | Stored rate %, zone, tax category. `adjust()` was the entry point. |
+| `TaxRate.match(zone)` | TaxRate class method | Found rates whose zone includes the order's tax zone |
+| `Calculator::DefaultTax` | `core/app/models/spree/calculator/` | Computed tax amount for line items, shipments, shipping rates |
+| `VatPriceCalculation` | `core/app/models/concerns/` | Handled included-in-price tax math |
+| `TaxRate.store_pre_tax_amount` | TaxRate class method | Computed and stored pre-tax amounts for VAT calculations |
+| `Adjuster::Tax` | `core/app/models/spree/adjustable/adjuster/` | Orchestrated tax adjustment updates during recalculation |
+| `TaxCategory` | `core/app/models/spree/tax_category.rb` | Groups products/variants by tax type (unchanged) |
| `Zone.match(address)` | Zone class method | Finds geographic zone for an address |
| `Order#tax_zone` | Order model | Resolves order's zone from ship/bill address + default zone fallback |
| `Spree::Config[:tax_using_ship_address]` | Config | Controls whether ship or bill address determines tax zone |
-| `Spree.adjusters` | Engine config | Registry of adjuster classes (includes Tax adjuster) |
-
-### Key flow today
+| `Spree.adjusters` | Engine config | Registry of adjuster classes (included the Tax adjuster) |
```
OrderUpdater#update
@@ -66,13 +75,13 @@ Order#create_tax_charge!
### 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:
+`Calculator::DefaultTax` was 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.
+4. **Exemption logic** — Exemption evidence must reach the calculation before the API call. Calculators only compute amounts.
+5. **Entry point control** — Calculators were called inside the adjustment flow via `AdjustmentSource.create_adjustment → compute_amount → calculator.compute`. External providers need to intercept at the 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`.
@@ -82,181 +91,398 @@ Provider (order lifecycle)
└─ Avalara provider → Avalara API → writes TaxLine records directly
```
+### Shipped on 6-0-dev (core-rewrite waves)
+
+| What exists | Where | What it does |
+|---|---|---|
+| `Spree::TaxProvider::Base` | `core/app/models/spree/tax_provider/base.rb` | Contract: `estimate(owner, items = nil)`, `commit(owner)`, `void(owner)`, `refund(owner, amount)`, `exempt?(owner)` (stub, uncalled — removed by this revision) |
+| `Spree::TaxProvider::Internal` | `core/app/models/spree/tax_provider/internal.rb` | Computes rate × discounted basis directly from TaxRate rows (VAT included-in-price math backed out of gross); replace-all `delete_all` per estimate; writes snapshot columns; preserves `pre_tax_amount`; **still Zone-based** (`TaxRate.match(owner.tax_zone)`); skips zero amounts (changed by this revision) |
+| `Spree.tax_provider` | `core/lib/spree/core.rb` | Returns a fresh argless instance of the globally configured class (`Rails.application.config.spree.tax_provider`, default Internal). Per-market selection not yet implemented |
+| `Spree::TaxLine` | `core/app/models/spree/tax_line.rb` + `spree_tax_lines` | Typed adjustment row: dual-FK cart/order owner, exactly-one adjustable (line item / fulfillment / fee), `amount`, `rate` + `label` + `provider_id` snapshots, `included`, `data` + `metadata` JSON |
+| Order-level money freeze | `core/app/workflows/spree/carts/recalculate_totals.rb` | `money_frozen?` (completed order) skips `regenerate_typed_rows` — no adjusters, no estimate; `fold_typed_rows` always re-sums totals from rows |
+| `set_tax_line_context` hook | same workflow | Context hook assembled before estimate; **not yet threaded into the provider call** (see Key Decisions — its role narrows to untyped provider extras) |
+| Call sites | `Carts::RecalculateTotals` (full), `Carts::AddItem` / `LineItem` / `Order` (incremental per-item) | The optional `items` parameter is load-bearing — incremental paths estimate a single item |
+| `TaxRate` | `core/app/models/spree/tax_rate.rb` | Pure configuration — no `adjust`, no `CalculatedAdjustments`, no calculator. Still `belongs_to :zone` |
+| Admin API + dashboard | `/api/v3/admin/orders/:id/tax_lines` + panels | The explicit post-placement row-edit path (writes rows directly, then re-runs the fold) |
+
+Fees are taxable items (beyond the original line-items-plus-shipments scope): items without a tax category are taxed with the default tax category's rates.
+
+Not shipped: per-market selection (`Market` has only the Zone-based `tax_zone` reader), commit/void/refund callers, the exemption input, buyer tax identity, Phase 5 Zone decoupling, the Avalara gem, `TaxExemptionCertificate`.
+
+### Key flow today
+
+```
+Carts::RecalculateTotals#perform (single totals seam, cart + order twins)
+ → regenerate_typed_rows unless money_frozen?
+ → Spree.adjusters (discounts/fees on the taxable base)
+ → run_hooks :set_tax_line_context
+ → Spree.tax_provider.estimate(cart) # replace-all TaxLine write
+ → fold_typed_rows always — totals re-summed from rows
+```
+
## Key Decisions (do not deviate without discussion)
### Provider replaces TaxRate.adjust entirely
-- **`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`.
+- **`TaxRate.adjust` is removed.** The provider is the only entry point for tax calculation and the only sanctioned TaxLine writer. No `AdjustmentSource`, no `CalculatedAdjustments` concern on TaxRate, no `Calculator::DefaultTax`.
+- **`TaxRate` stays as pure configuration** (rate %, zone until Phase 5, tax category, included_in_price) — no behavior.
-### Provider contract: estimate and commit
+### Provider contract: estimate/commit/void/refund with explicit dates
```ruby
-# Two-phase: estimate during checkout, commit on completion
-provider.estimate(order, items) # → writes TaxLine records (or Adjustments in 5.4)
-provider.commit(order) # → finalizes with external service, no-op for internal
-provider.void(order) # → cancels committed tax document, no-op for internal
+# Estimate during checkout (idempotent while the owner is a live cart;
+# never runs on completed orders — the money freeze gates it):
+provider.estimate(owner, items = nil,
+ tax_date: nil, # rates-effective date; nil = now
+ tax_identifier: nil, # resolved Spree::TaxIdentifier or nil (B2C)
+ exemptions: [], # Array<Spree::TaxExemption>
+ context: {}) # untyped extras from set_tax_line_context
+
+provider.commit(order) # finalize at completion — no-op for Internal
+provider.void(order) # cancel committed document — no-op for Internal
+provider.refund(order, return_items, tax_date: nil) # partial credit vs the committed document
```
-- **Estimate** is called during checkout recalculation. It's idempotent — repeated calls update amounts.
-- **Commit** is called on order completion. For external providers, this creates a transaction in the tax service (for filing/reporting). For the internal provider, it's a no-op.
-- **Void** is called on order cancellation. Reverses the committed tax document.
+What each method is for:
+
+- **Estimate** is called during checkout recalculation, from the single totals seam. It is idempotent — repeated calls replace the previous result — and it writes the TaxLine rows. Passing `items` limits it to those items; omitting them re-estimates every taxable item on the owner.
+- **Commit** is called when the order is placed. For an external provider this turns the estimate into a recorded transaction in the tax service, which is what the merchant's filing and reporting are built on. For the Internal provider it is a no-op — the TaxLine rows already are the record.
+- **Void** is called when an order is cancelled, and reverses the committed document so it does not appear in a return. A no-op for the Internal provider.
+- **Refund** is called when items come back. It reports a partial credit against the committed document rather than voiding and re-committing, because a return and the original sale can fall in different filing periods.
+
+Decisions about that contract:
+
+- **`estimate` returns nothing meaningful, as it does today.** Its output is the TaxLine rows it wrote. A provider that cannot complete raises, like any failed external call. A structured result — including a channel for "I cannot determine this treatment" — was considered and deliberately deferred; see the note under Capability honesty.
+- **Effective date is an input, not implicitly "now".** Unanimous industry practice (Avalara requires `date`; Stripe `tax_date`; TaxJar `transaction_date`; Vertex `documentDate`), and legally the rate that applies is the one in force when the sale happened. The contract keeps the **rates-effective date** distinct from the document/posting date, the same two-date model as Avalara (`DocDate` vs `TaxOverride.TaxDate`) and Stripe (`tax_date` vs `posted_at`).
+- **Estimate never runs on completed orders.** The order-level money freeze (`money_frozen?` in `Carts::RecalculateTotals`) is the enforcement. Post-placement corrections go through `refund` and the explicit admin row-edit endpoints, never a re-estimate.
+- **Refund receives the return items and the original tax date** (default: the order's completion date) so providers can implement either industry pattern: recompute-at-original-date (Avalara `taxOverride.taxDate`, Vertex) or derive-from-recorded-amounts (Stripe reversals, TaxJar refund transactions). The order is the reference to the original transaction (providers keep their document id in order metadata).
+- **Internal provider refund limit (documented):** TaxRate rows are not versioned — an edit destroys the old value — so the Internal provider can never recompute at a past date. Internal refunds are always derived proportionally from the recorded TaxLines. The snapshot columns are the only rate history internal merchants have.
+- Do **not** adopt "a credit note corrects the original filing period" as a rule — it was checked and is wrong as a general rule: a return-driven adjustment is reported in the period the credit note is issued, and only correcting a genuine error reopens the original period. The contract's job is to link the correction to the original transaction and its date; which period it lands in is the provider's and the merchant's business.
+- **There is no `exempt?` on the contract.** Exemption is an estimate input + a TaxLine output — see below. The boolean shape has the wrong arity (per-jurisdiction, per-item, reason-carrying), and 6.0 is the window to settle the public contract before it freezes.
### Provider writes TaxLine records directly
-With the split-adjustments plan (6.0), tax results are written as `Spree::TaxLine` records — the same data model regardless of whether tax was computed internally or by Avalara. TaxLine is **self-describing**: `tax_rate_id` is nullable (set only by the Internal provider — external providers reference no local rate row and never synthesize one), and every row snapshots `rate`, `label`, `provider_id`, plus a `data` JSON column for provider payloads (jurisdiction breakdowns). Writes use **replace-all set semantics** per estimate: delete the target items' existing tax lines, insert fresh ones — this is also what prevents stale tax after an address change.
+Tax results are written as `Spree::TaxLine` rows — **the same data model whether the tax was computed internally or by Avalara**. Nothing downstream (totals, serializers, reporting, invoicing) needs to know which engine produced a row, and swapping providers doesn't change the shape of the data an integration reads.
-Before split-adjustments ships, the provider writes `Spree::Adjustment` records (backward compatible).
+That works because a TaxLine is **self-describing**. `tax_rate_id` is nullable and set only by the Internal provider; an external provider references no local rate row and never synthesizes one to satisfy the FK. Every row instead snapshots what it needs to stand alone — `rate`, `label`, `provider_id`, the treatment fields below — plus a `data` JSON column for provider payloads such as jurisdiction breakdowns. Because those are snapshots, a row stays truthful after the rate behind it is edited or deleted, and after the merchant switches providers.
-### Credentials live in Spree::Integration, not the provider
+**Write contract:** writes use **replace-all set semantics** per estimate — delete the target items' existing tax lines, insert fresh ones. That is also what prevents stale tax after an address or item change. Additionally, **a provider writes a row for every item it formed a treatment for, including zero-amount treatments.** A matched zero-rate, an exemption and a reverse charge each produce an `amount: 0` row carrying its reason; without that, "exempt", "zero-rated" and "not estimated yet" are indistinguishable, and the per-line treatment record e-invoicing needs is lost. An item the provider had **no opinion on** — Internal with no matching rates, say a merchant with no nexus in the destination — produces no row; external providers always have an opinion and always write. **TaxLines are the only persisted record of tax treatment: no exemption flags on customer, order or line items, ever.**
-Providers are stateless strategy objects — they define behavior (estimate, commit, void). They do **not** store credentials. API keys, secrets, and connection config for external services live in `Spree::Integration` subclasses, which provide:
+### TaxLine carries a treatment, not just an amount
-- **Per-store persistence** — credentials stored in the `preferences` column
-- **Admin UI** — dynamic forms for non-developer configuration
-- **Connection validation** — `can_connect?` hook tests credentials before saving
-- **Activation tracking** — `active` boolean flag
+Why this is needed: European e-invoices must state, for **every** line, which tax category applied — and when the tax was zero, why it was zero. A zero from reverse charge, a zero from an export and a zero from an exemption are three different categories with three different reasons, and an invoice missing them fails the validators merchants have to pass. A reverse-charge invoice must also say so in words, and a court ruling has confirmed that omission cannot be repaired after the fact. Several EU countries require structured e-invoices for business-to-business sales between 2026 and 2028, and the whole EU for cross-border sales from 2030. The commercial tax services already work this way — Stripe Tax returns a reason for every line, Avalara a per-jurisdiction breakdown with exemption reasons — so an amount-only record throws away data we are already being handed. (Citations in **Regulatory background**.)
-A provider gem (e.g., `spree_tax_avalara`) ships **both** an Integration subclass and a Provider subclass:
+**TaxLine gains:**
-```ruby
-# Integration — stores credentials, provides admin UI
-class Spree::Integrations::Avalara < Spree::Integration
- preference :api_key, :string
- preference :environment, :string, default: 'sandbox'
- preference :company_code, :string
+- `taxability_reason` (string, nullable) — machine-readable cause of the treatment. Core vocabulary: `standard_rated`, `reduced_rated`, `zero_rated`, `reverse_charge`, `intra_community_supply`, `export`, `customer_exempt`, `product_exempt`, `not_collecting`, `not_subject_to_tax`. Held in an extensible class-level list on `Spree::TaxLine` (additive registration, `HasStatus`-style) with an inclusion validation allowing nil. Acceptance bar for new values: the reason maps to a distinct invoice category code, or to a distinct box on a tax return. (Vocabulary basis: Stripe's enum with the Stripe-internal mechanics pruned, plus `intra_community_supply` and `export` — Stripe's single `reverse_charge` and `zero_rated` values cannot tell cross-border goods apart from cross-border services, or an export apart from a domestic zero rate, and invoices need both distinctions.)
+- Jurisdiction snapshot: `country_iso` (string), `state_code` (string, nullable) — the taxing jurisdiction of this line. Rationale is **reporting and queryability**, not an invoice requirement: the EU's one-stop-shop return is filed per destination country, one section per country, so "which country's tax was this" has to be a query — and origin-taxed cases (below-threshold consumer digital sales, US states that source to the seller) make it non-derivable from the shipping address. European e-invoices have no place-of-supply field at all; they carry a delivery country for cross-border EU goods, which the order already has.
- def self.integration_group = 'tax'
+**Deliberately NOT columns:** the invoice category code, the exemption reason code and the legal-reference wording. All three follow deterministically at invoicing time from `taxability_reason` plus order facts — the pattern Odoo uses, and Odoo's whole job is producing these invoices: it derives the codes at export from tax configuration and the sale's facts, and stores none of them per line. No surveyed commerce platform (Medusa, Saleor, commercetools, Shopify) stores them either. Storing the reason instead of the legal codes keeps core out of a legal vocabulary that gets revised on someone else's schedule, while still giving e-invoicing integrations everything they need. One-sentence rationale for the field: *a machine-readable reason distinguishes zero-tax causes that land in different boxes of a tax return, and lets e-invoicing integrations derive the category and exemption codes that European invoicing mandates require.*
- def can_connect?
- client = AvaTax::Client.new(api_key: preferred_api_key, environment: preferred_environment)
- client.ping.success?
- rescue => e
- self.connection_error_message = e.message
- false
- end
-end
+**Core ships the lookup maps** as code, not data — updatable with a release: reason → invoice category code, and reason → exemption reason code for the cross-border cases, plus a `TaxLine#category_code` helper. Both target code lists are the ones European e-invoices use (identified in **Regulatory background**).
-# Provider — behavioral contract, reads credentials from Integration at runtime
-class SpreeTaxAvalara::TaxProvider < Spree::TaxProvider::Base
- def estimate(order, items)
- # ...
- response = client.create_transaction(request)
- # ...
- end
+| `taxability_reason` | Invoice category code | Exemption reason code |
+|---|---|---|
+| `standard_rated`, `reduced_rated` | S | — |
+| `zero_rated` | Z | — |
+| `reverse_charge` | AE | VATEX-EU-AE |
+| `intra_community_supply` | K | VATEX-EU-IC |
+| `export` | G | VATEX-EU-G |
+| `customer_exempt`, `product_exempt` | E | not derivable from the reason — depends on which exemption applied (certificate/tax-category config) |
+| `not_subject_to_tax` | O | VATEX-EU-O |
+| `not_collecting` | nil — no meaningful code (not registered in the jurisdiction; no EU VAT invoice to produce) | — |
- private
+The map is not exhaustive of either code list — a treatment core doesn't model needs an extension to register the reason together with its code mapping. The one gap worth naming: for a genuinely exempt supply (healthcare, education, financial services) the exemption reason code cannot come from this map at all, because it depends on *which* exemption applied. That code stays with the exemption input and the tax-category configuration.
- def client
- @client ||= begin
- integration = market.store.integrations.active.find_by!(type: 'Spree::Integrations::Avalara')
- AvaTax::Client.new(
- api_key: integration.preferred_api_key,
- environment: integration.preferred_environment
- )
- end
+Both fields are written by every provider, and both are covered by the write contract above — including on zero-amount rows, which is where the reason does its real work.
+
+### Buyer tax identity: `Spree::TaxIdentifier`
+
+Survey verdict (Magento, Stripe, commercetools, Shopify, Odoo, Medusa/Saleor): column designs either forgo typed multiplicity (Magento, Odoo), forgo validation evidence (commercetools, Shopify), or impose nullable tax columns on every consumer row (Magento — 5–7 per address). Live-read designs (Shopify B2B, Odoo) have documented drift pain: historical documents resolve to the *current* registration. Stripe — the only system designed for the tax-document problem — uses a separate typed `tax_id` object on the customer plus a `{type, value}` snapshot frozen onto the finalized invoice. Spree adopts Stripe's shape with Magento's evidence discipline:
+
+```ruby
+class Spree::TaxIdentifier < Spree.base_class
+ has_prefix_id :txi
+
+ # Owner — exactly one (dual-FK convention, never polymorphic):
+ belongs_to :customer, class_name: 'Spree::Customer', optional: true # durable profile value
+ belongs_to :cart, class_name: 'Spree::Cart', optional: true # checkout-time override
+ belongs_to :order, class_name: 'Spree::Order', optional: true # frozen completion snapshot
+ # + company_id / company_location_id when the B2B plan ships (per-branch
+ # registrations follow Shopify's CompanyLocation.taxRegistrationId precedent)
+
+ # kind: 'eu_vat', 'gb_vat', 'au_abn', … (Stripe's typed-kind model)
+ # value: the registration number
+ # validation_status: nil (not attempted — including "no validator registered
+ # for this kind", which the admin resolves by asking the
+ # registry) / pending (queued) / verified / unverified /
+ # unavailable / unsupported (validator gone by run time)
+ # validated_at: datetime
+ # validation_evidence: JSON — registry, consultation number, verified name,
+ # message, validated country + validated value (Magento's
+ # discipline; the registry only answers "valid now", so
+ # the evidence captured at
+ # validation time is the only proof that will ever exist)
+ # source: 'override' / 'company' / 'customer' — order-owned rows only
+
+ # Order-owned rows are completion snapshots — immutable once written.
+ def readonly?
+ persisted? && order_id.present?
end
end
```
-**Admin flow:**
-1. Admin navigates to Integrations → connects Avalara (enters API key, tests connection)
-2. Admin navigates to Market "US" → selects "Avalara" as tax provider
-3. At runtime, the provider reads credentials from the Integration record
+- **Cart and order tables get zero tax columns; consumer orders carry no row at all.** The customer-level row exists because not every business buyer will have a Company — sole proprietors with VAT IDs are exactly who reverse charge exists for, and the B2B Company model targets bigger businesses.
+- **Resolution chain at estimate:** cart-owned override → (Company, when the B2B plan ships) → customer's row → nil (B2C treatment). This is a fallback chain, so it lives as `#resolved_tax_identifier` on `Spree::Purchase::Taxation` — the concern that already owns `tax_address` for both Cart and Order — not behind a Dependencies seam. A three-link `||` has no swappable behavior worth freezing as public API, and an installation that genuinely needs different selection decorates the method.
+- **Completion copies, never references:** the copy step in `Carts::Complete` calls the same `#resolved_tax_identifier` and duplicates the winning row as a frozen order-owned row with `source` stamped — Stripe's invoice-finalization freeze plus the evidence Stripe drops. Post-completion provider calls (`commit`/`void`/`refund`) read the order-owned snapshot directly; the resolution chain is a checkout-time concern only.
+- **Freeze enforcement, three layers:** single writer (the `Carts::Complete` copy step — nothing else creates order-owned rows), the `readonly?` model backstop above (ActiveRecord refuses save/destroy; customer- and cart-owned rows stay editable), and the API perimeter (identifier params permitted on cart + customer endpoints only, never order endpoints). Deliberately **no correction path**: a wrong ID on a completed order already produced the tax treatment; the remedy is cancel/refund (later the order-change substrate), not editing a frozen snapshot.
+- **The address is an input, never the owner.** A tax ID identifies the legal entity, not a location; Spree addresses are cloned/deduplicated value records and a bad host for identity data (Magento's address-level columns are the cautionary precedent). The billing address's existing `company` field pairs with the ID on invoices — no duplicate field.
+- **Validation belongs to the identifier, not to a tax provider.** A registration number is checked against a registry chosen by its **kind** — an EU VAT number against the EU's verification service, a UK one against the UK's, an Australian one against Australia's — whichever engine happens to price the merchant's orders. Nothing about it is a market decision: a customer saves a tax ID on a profile, long before any order or market exists. Hanging validation off `TaxProvider` would force an arbitrary provider choice (a US sales-tax engine asked to check an EU VAT number, or an EU market on Internal declining to validate while a connected Avalara sits unused), so **`validate_tax_id` is deliberately not on the provider contract**.
+
+ **The seam is a registry keyed by kind**, empty by default — core ships **no registry client** for any jurisdiction:
+
+ ```ruby
+ # Extensions register the kinds they cover; a tax provider gem may register
+ # itself for the kinds its service can check.
+ Spree.tax_id_validators['eu_vat'] = 'SpreeEuVat::TaxIdValidator'
+
+ # Each validator subclasses Spree::TaxIdValidator::Base: a class-level
+ # valid_format? for the synchronous check, and call(tax_identifier:) →
+ # ValidationResult for the registry call. The row carries kind, value and its
+ # owner, so a credentialed validator reaches the store's Integration through
+ # the owner — no extra arguments.
+ ```
+
+ Lookup is deterministic from the row itself, two extensions covering different kinds coexist (a single swappable service would give the second one to load the slot and silently disable the first), and core can answer "can this installation validate this kind?" with `Spree.tax_id_validators.key?(kind)` — which is what the admin needs to distinguish *queued*, *no validator installed* and *checked and not registered*.
+
+ **When it runs:** after the identifier is saved, in a background job — following the address-geocoding precedent (`Spree::Address#async_geocode` → `Spree::Addresses::GeocodeAddressJob`), which solves the same problem of enriching a row from an external lookup:
+
+ ```
+ TaxIdentifier saved (after_commit, only when kind/value actually changed)
+ → Spree::TaxIdentifiers::ValidateJob
+ → Spree.tax_id_validators[kind] → ValidationResult
+ → Spree::TaxIdentifiers::Validate writes status / validated_at /
+ evidence / normalized value with update_columns
+ ```
+
+ The callback only enqueues — the external call happens in the job — and the guard mirrors `should_geocode?`, so a number is re-checked when it changes rather than on every touch, and the `update_columns` write-back cannot retrigger it. A registry that fails to answer is reported via `Rails.error.report` and recorded as `unavailable`, not raised.
+
+ **Registry validation never blocks checkout, and the tax treatment does not wait on it.** This is Stripe's split, adopted deliberately: Stripe checks *format* synchronously during checkout but explicitly not validity, runs registry validation asynchronously, and applies reverse charge or a zero rate "as long as the tax ID conforms to the necessary number format, regardless of its validity". So a sale can complete with `pending` on the row and still be treated correctly — the verdict is evidence for the merchant's records, not an input to the arithmetic. The storefront is not given a way to ask for it either: nothing the buyer could do with the answer differs, so an inline check would only surface registry latency to them. Verdicts and retries are the operator's business.
+
+ **Rejected alternative — Magento's model.** Magento validates against the registry synchronously on address save (with an optional per-transaction re-check), and the result assigns a customer group whose tax rules then decide the treatment, so the answer *does* gate the tax. Two consequences are documented in its own ecosystem: the registry is regularly down or times out, which is why a third-party module exists purely to add caching and an offline fallback for "the unstable VIES database used by Magento"; and with external checkouts (PayPal Express and friends) the per-transaction validation cannot run at all, so the group never changes. Making the treatment depend on a synchronous third-party call turns that party's downtime into checkout downtime. We take the format check from this design and leave the gating behind.
+
+ **Never during estimate.** The estimate path reads the stored result and does not re-check it. That is the whole point of snapshotting: a re-check months later can flip a correctly zero-rated sale, because the registry only ever answers about today. An unvalidated or pending identifier does not block checkout.
+
+ **The answer** is a small value object. It exists so a validator stays a pure function of kind and value — it never touches columns, never has to remember `update_columns`, and is tested by asserting on what it returns. `Spree::TaxIdentifiers::Validate` remains the only writer of the row's validation columns, which is what keeps three installed validator gems from each inventing their own status vocabulary:
+
+ ```ruby
+ # app/models/spree/tax_identifier/validation_result.rb
+ #
+ # Follows Spree::PaymentResponse — the existing precedent for a structured
+ # outcome from an external service (outcome + human-readable message + raw
+ # payload) — built as an ActiveModel value object per
+ # Spree::PickupPointOption. Never persisted, never a Struct.
+ class Spree::TaxIdentifier::ValidationResult
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+
+ # What a validator can legitimately report. Narrower than the row's
+ # validation_status, which also carries nil (not attempted — including
+ # "no validator registered for this kind"), 'pending' (queued) and
+ # 'unsupported' (the validator was gone by the time the job ran) — all
+ # three are states the platform sets, not answers a validator gives.
+ #
+ # Stripe's vocabulary (verification.status), deliberately NOT valid/invalid:
+ # the generated predicates would override ActiveModel's #valid?/#invalid?.
+ # 'verified' is also the more honest word — a registry reports that a number
+ # is registered, not that it is abstractly valid.
+ STATUSES = %w[verified unverified unavailable].freeze
+
+ attribute :status, :string
+ attribute :normalized_value, :string
+ attribute :message, :string # why, in words — stored under
+ # validation_evidence['message'] for the admin
+ attribute :checked_at, :datetime
+ attribute :evidence # Hash — registry, consultation number,
+ # verified name, validated country + value
+
+ validates :status, inclusion: { in: STATUSES }
+
+ STATUSES.each { |value| define_method(:"#{value}?") { status == value } }
+ end
+ ```
+
+ Three outcomes rather than a boolean, because they lead to different behavior and different admin copy: `unavailable` (the registry did not answer — the sale still has to be treated somehow) is not the same as a registry replying that the number is not registered.
+
+ Note this is a validator's return type, not `estimate`'s — `estimate` writes rows and returns nothing meaningful.
+
+ The Avalara gem registers a validator for the kinds Avalara can check. An EU extension registers one against the EU verification service — and can then add reverse charge on top of Internal by supplying only the treatment, since a verified identifier is the piece Internal lacks rather than the logic.
+- **API surface:** singular nested resources on the customer account, the cart and (read-only) the order — see the API surface section for the endpoint list and the store/admin field split.
+- **Provider consumption:** the provider reads `kind` and `value`, never the ownership FKs and never the verdict. Avalara maps to `businessIdentificationNo` (the B2B-VAT-rules switch), Stripe to `tax_ids`; both revalidate server-side regardless. The Internal provider ignores the identifier entirely — reverse charge is on its declared-unsupported list, and charging normal tax when no validated ID is present is the legally safe default: for services, treating an unidentified buyer as a consumer is a presumption EU law explicitly protects, and for goods a valid ID has been a hard condition of zero-rating since 2020.
-**Internal providers don't need an Integration.** `Spree::TaxProvider::Internal` reads TaxRate records directly — no external credentials.
+### Tax exemption is a typed estimate input plus a TaxLine output — not a boolean, not a hook
-**Provider availability depends on Integration status.** The Market admin UI should only offer providers whose Integration is active. Provider classes declare their dependency:
+The removed `exempt?(order) → Boolean` had the wrong arity three ways: exemption is per jurisdiction (a certificate valid in one state, not another), per item (a resale order can contain own-use lines), and the *reason* is the audit artifact. No provider API exposes an "is this exempt?" query — they all take exemption evidence in (Stripe `taxability_override`, Avalara `exemptionNo`/`entityUseCode`, TaxJar `exemption_type`) and return the treatment out. The platform forwards evidence; the provider decides per line and jurisdiction; TaxLines record the outcome.
+
+**Input** — `estimate`'s `exemptions:` parameter, an array of ephemeral value objects (never persisted — the `PickupPointOption` pattern), each mirroring a certificate row:
```ruby
-class SpreeTaxAvalara::TaxProvider < Spree::TaxProvider::Base
- def self.integration_class
- 'Spree::Integrations::Avalara'
- end
+class Spree::TaxExemption
+ include ActiveModel::Model
+ include ActiveModel::Attributes
- # Internal providers override to always return true
- def self.available_for_store?(store)
- store.integrations.active.exists?(type: integration_class)
- end
+ attribute :reason_code, :string # resale, government, … (Avalara entityUseCode territory)
+ attribute :certificate_number, :string # = future TaxExemptionCertificate#certificate_number
+ attribute :country_iso, :string # nil = all countries — mirrors the certificate country FK
+ attribute :state_code, :string # nil = entire country — mirrors the certificate state FK
+
+ attribute :item_overrides # Array<ItemOverride>; empty = applies to all items
+end
+
+class Spree::TaxExemption::ItemOverride
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+
+ attribute :item_id, :string # prefixed line item id
+ attribute :exempt, :boolean # false = carve this line out (own-use in a resale order)
+ attribute :reason_code, :string # optional per-line reason differing from the entry's
end
```
-### Provider is per-Market
+Multiple certificates = multiple entries. Certificate *lifecycle* (verified/expired) is a resolution-time filter — only active certificates produce entries; presence of an entry is the claim. Providers translate: Avalara `reason_code` → `entityUseCode`, `certificate_number` → `exemptionNo`, item overrides → line-level codes (the generalization of what `spree_avatax_official` sends today from its user-level fields); Stripe → `taxability_override`.
+
+**Assembly** — the `tax_resolve_exemptions_service` dependency (`Spree::Tax::ResolveExemptions`, plain Tier 1 service, `call(order:)` → array, **default returns `[]`**). Callers never build exemptions; providers never fetch them. In stock 6.0 the input is empty and the working exemption paths are provider-native certificates (Avalara merchants get durable per-customer exemption through Avalara's certificate store, needing nothing from our schema) and extensions swapping the service — the `spree_tax_avalara` gem keeping the legacy user-level `exemption_number`/`entity_use_code` as gem-owned storage is the seam's first real implementation. Company-backed `TaxExemptionCertificate` records become the default implementation's source in Phase 7, resolving into the same entries.
+
+**Output** — zero-amount TaxLines with `customer_exempt`/`product_exempt` reasons, per the write contract. No flags anywhere: the claim is ephemeral input, the outcome is rows.
+
+**Product-based exemption stays out of this input entirely** — groceries/clothing taxability is a property of the product, riding the existing TaxCategory → provider tax-code mapping (TaxCategory "Clothing" → Avalara `PC040100`), decided per line by the provider's own jurisdiction rules.
+
+**Hook boundary:** the `set_tax_line_context` hook is NOT the exemption channel. Typed inputs — exemptions from `tax_resolve_exemptions_service`, the identifier from `#resolved_tax_identifier`, the tax date from the caller — arrive as named `estimate` parameters: declared shapes, one implementation each, no deep-merge collisions. The hook remains for untyped provider-specific extras only (riding into `TaxLine.data` / provider requests as the `context:` parameter); its doc comment — which currently names "exemption certificates, customer tax IDs" as its payload — must be corrected before the 6.0 hook-contract freeze.
+
+### Provider is per-Market — selection, not construction
-Markets represent regional commerce operations. Each market can have its own tax provider, matching how the hosted market leader and OSS platform A handle it:
+Markets represent regional commerce operations; each market selects its tax engine. The global config class (`Rails.application.config.spree.tax_provider`) stays as the **fallback default** (market with no explicit provider, store without markets).
```ruby
class Spree::Market < Spree.base_class
- attribute :tax_provider, :string, default: 'Spree::TaxProvider::Internal'
+ # Provider class name; nil falls back to the global default.
+ attribute :tax_provider, :string
+ # Providers are stateless and argless — no initialize(market). Every method
+ # receives the owner, and owner.market / owner.store carry the runtime context
+ # a provider needs (credentials, rates). The market selects WHICH class; it is
+ # not constructor state.
def tax_provider_instance
- tax_provider.constantize.new(self)
+ (tax_provider.presence || Rails.application.config.spree.tax_provider.to_s).constantize.new
end
end
```
-TaxRate is an **internal provider concept only**. External providers ignore it — they have their own jurisdiction databases.
+Call sites migrate from `Spree.tax_provider` to the owner's market as per-market selection lands. Provider availability in the Market admin depends on Integration status (`available_for_store?`) and the capability declarations below. The registry shape from the 2026-07-30 note above — a small model per engine, identifier plus enabled — stays an option to weigh at implementation; `TaxLine.provider_id` keeps stamping its plain string key either way.
+
+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 "US" → tax_provider: 'SpreeTaxAvalara::TaxProvider'
+ └─ Avalara API handles every US jurisdiction (state, county, city, district)
+ └─ TaxRate rows may exist in the DB but are not consulted for this market
-Market "EU" → tax_provider: 'Spree::TaxProvider::Internal'
+Market "EU" → tax_provider: 'Spree::TaxProvider::Internal' (or nil → global default)
└─ 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
+ └─ TaxRate: country=Germany, category=Food, rate=7%, included=true
+ └─ TaxRate: country=France, category=Standard, rate=20%, included=true
```
-### Drop TaxZone — TaxRate links directly to country/state
+### Credentials live in Spree::Integration, not the provider
-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:
+Unchanged: providers are stateless strategy objects; API keys and connection config live in `Spree::Integration` subclasses (per-store persistence, admin UI, `can_connect?`, activation). A provider gem ships both an Integration subclass and a Provider subclass:
```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
+# Integration — stores credentials, provides the admin form
+class Spree::Integrations::Avalara < Spree::Integration
+ preference :api_key, :string
+ preference :environment, :string, default: 'sandbox'
+ preference :company_code, :string
- # rate: 0.19, included_in_price: true, name: "DE VAT 19%"
+ def self.integration_group = 'tax'
+
+ def can_connect?
+ client = AvaTax::Client.new(api_key: preferred_api_key, environment: preferred_environment)
+ client.ping.success?
+ rescue => e
+ self.connection_error_message = e.message
+ false
+ end
end
-```
-No zones, no zone members, no indirect lookups. This matches the hosted market leader (rates per country/region) and OSS platform A (TaxRegion per country/province).
+# Provider — behavioral contract, reads credentials from the Integration at runtime.
+# The Market admin only offers a provider whose Integration is connected, so
+# availability is declared on the class.
+class SpreeTaxAvalara::TaxProvider < Spree::TaxProvider::Base
+ def self.integration_class = 'Spree::Integrations::Avalara'
-```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
-}
+ def self.available_for_store?(store)
+ store.integrations.active.exists?(type: integration_class)
+ end
+
+ def estimate(owner, items = nil, **options)
+ # ...
+ response = client_for(owner).create_transaction(request)
+ # ...
+ end
+
+ private
+
+ # The owner carries the store, so credentials are resolved per call — the
+ # provider itself holds no state and no connection.
+ def client_for(owner)
+ integration = owner.store.integrations.active.find_by!(type: self.class.integration_class)
+ AvaTax::Client.new(
+ api_key: integration.preferred_api_key,
+ environment: integration.preferred_environment,
+ company_code: integration.preferred_company_code
+ )
+ end
+end
```
-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.
+**Admin flow:**
-**Tax stops using Zone; the Zone model itself survives 6.0** (decision 2026-07-27, superseding the earlier "dropped entirely"). A data migration (rake task) converts Zone records used by TaxRate into direct country/state FKs, and `zone_id` comes off TaxRate. The generic `Spree::Zone` stays for shipping (`ShippingMethod has_many :zones`) and the request-context surface (`Spree::Current.zone`, `Market#tax_zone`, factories) — the delivery-rate-provider plan descoped its `DeliveryZone` replacement after a review found ~183 unowned references. Full Zone removal gets its own future plan with a complete consumer inventory.
+1. Admin opens Integrations, connects Avalara (enters the API key; the connection is tested before saving).
+2. Admin opens Market "US" and selects Avalara as its tax provider — only connected providers appear in the list.
+3. At estimate time the provider resolves credentials from the Integration record.
-This matches the natural scope hierarchy (all external providers store credentials in `Spree::Integration` — see above):
+**Internal providers need no Integration** — `Spree::TaxProvider::Internal` reads TaxRate rows and has no external credentials, so it is always available.
-| Provider | Scope | Credentials | Why |
-|---|---|---|---|
-| Search | Global (`Spree.search_provider`) | `Spree::Integration` | One search engine per instance |
-| Tax | Per-Market (`Market#tax_provider`) | `Spree::Integration` | Different tax rules/services per region |
-| Delivery rates | Per-DeliveryMethod (`DeliveryMethod#rate_provider`) | `Spree::Integration` | Different carriers per shipping option |
+### Capability honesty
-### Tax exemption is part of the provider contract
+A provider that is honest about its domain beats one that silently under-collects — under-collection lands on the merchant. One mechanism, plus one deliberately not built:
-```ruby
-provider.exempt?(order) # → true if order should be tax-exempt
-```
+1. **Class-level capability declarations** alongside `available_for_store?` (exact shape at implementation — a declared set consulted by the Market admin UI and the validation UX). `Spree::TaxProvider::Internal` declares as **unsupported**: destination-based US local tax (the country/state rate model cannot express county/city/district stacking — pairing Internal with a US market warns or refuses), one-stop-shop threshold tracking (whether the merchant has crossed the EUR 10,000 cross-border threshold depends on their total annual turnover across all destinations, which no single order contains), and EU B2B reverse charge — Internal does not implement the treatment, so an unvalidated or even a validated identifier changes nothing, and charging normal tax is the safe default. (An extension adding reverse charge to Internal gets validation for free from the validator registry; it only has to supply the treatment.) A sub-state jurisdiction level for single-state US merchants is explicitly deferred.
+2. **A runtime indeterminacy channel was considered and deferred.** The review asked for somewhere to put "this provider cannot determine that" — raised for the one-stop-shop threshold (which depends on the merchant's annual cross-border turnover, absent from any single order) and for Internal against US local rates. Both of those are answered by the capability declarations above, at configuration time, where a merchant can still act on the warning — rather than at estimate time with a sale already in flight. Nothing in core would consume a per-calculation verdict today, a provider that genuinely cannot complete raises like any failed external call, and unlike a hook key or a keyword signature a return value can be added later without breaking existing providers or callers. So there is no 6.0 window to catch here: if a provider surfaces a real case, `estimate` gains a return type then.
+
+### Sourcing: config flag is the default, the provider may override
+
+`Spree::Config[:tax_using_ship_address]` stays as the merchant-level default; the Internal provider reads it. A provider can own the sourcing decision per jurisdiction — in the US, origin-vs-destination sourcing is a legal rule that varies by state, not a merchant preference. The flag is the default, not the sole authority.
-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.
+### Drop TaxZone — TaxRate links directly to country/state (Phase 5, pending)
-### Internal provider computes directly from TaxRate data
+Unchanged from the 2026-07-27 decision: merchants think "Germany has 19% VAT", not in zones.
+
+```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
+end
+
+scope :for_address, ->(address) {
+ where(country: [address.country, nil])
+ .where(state: [address.state, nil])
+}
+```
-`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.
+State-level rates override country-level (more specific wins). **Tax stops using Zone; the Zone model itself survives 6.0** — a data migration converts Zone records used by TaxRate into direct country/state FKs, `zone_id` comes off TaxRate, and the generic `Spree::Zone` stays for the request-context surface (`Spree::Current.zone`, `Market#tax_zone`, factories). Full Zone removal gets its own future plan with a complete consumer inventory.
## Design Details
@@ -266,155 +492,399 @@ The provider checks Company.tax_exempt, exemption certificates, and any external
module Spree
module TaxProvider
class Base
- attr_reader :market
-
- def initialize(market)
- @market = market
+ # Domains this provider cannot handle, so the Market admin can warn a
+ # merchant instead of letting it under-collect silently. Internal declares
+ # :us_local_tax, :reverse_charge, :oss_thresholds.
+ #
+ # @return [Array<Symbol>]
+ def self.unsupported_capabilities
+ []
end
- # Estimate tax for items in an order. Called during checkout recalculation.
- # Must be idempotent — repeated calls update existing tax records.
+ # Whether this provider can be selected for a store — external providers
+ # require a connected Integration.
#
- # Creates/updates TaxLine records (6.0) or Adjustment records (5.4).
+ # @param store [Spree::Store]
+ # @return [Boolean]
+ def self.available_for_store?(_store)
+ true
+ end
+
+ # Recomputes tax for the given items and writes the TaxLine rows.
+ # Replace-all set semantics per target item, and one row for every item
+ # the provider formed a treatment for — including zero-amount treatments.
+ # Never called on a completed order; the order-level money freeze gates it.
#
- # @param order [Spree::Order]
- # @param items [Array<Spree::LineItem, Spree::Shipment>] items to tax
- # @return [void]
- def estimate(order, items)
- raise NotImplementedError
+ # @param owner [Spree::Cart, Spree::Order]
+ # @param items [Array<Spree::LineItem, Spree::Fulfillment, Spree::Fee>, nil]
+ # nil = every taxable item on the owner
+ # @param tax_date [Time, nil] date whose rates apply; nil = now
+ # @param tax_identifier [Spree::TaxIdentifier, nil] resolved buyer registration,
+ # nil for a consumer sale
+ # @param exemptions [Array<Spree::TaxExemption>] exemption evidence to apply
+ # @param context [Hash] untyped provider extras from set_tax_line_context
+ # @return [void] the written TaxLine rows are the output; raise if the
+ # calculation cannot be completed
+ def estimate(owner, items = nil, tax_date: nil, tax_identifier: nil, exemptions: [], context: {})
+ raise NotImplementedError, "Please implement 'estimate' in your tax provider: #{self.class.name}"
end
- # Commit tax for a completed order. Creates a tax document in external
- # services for filing/reporting. No-op for internal provider.
+ # Finalizes tax with the provider when the order is placed. No-op for a
+ # provider without a remote ledger — the TaxLine rows are already the record.
#
# @param order [Spree::Order]
# @return [void]
- def commit(order)
- # no-op by default
- end
+ def commit(order); end
- # Void a committed tax document. Called on order cancellation.
+ # Reverses a committed tax document on cancellation.
#
# @param order [Spree::Order]
# @return [void]
- def void(order)
- # no-op by default
- end
+ def void(order); end
- # Refund tax for returned items. Creates an adjustment document in
- # external services. Internal provider recalculates from remaining items.
+ # Reports a partial credit against the committed document, keyed to the
+ # original transaction rather than voiding and re-committing it.
#
# @param order [Spree::Order]
# @param return_items [Array<Spree::ReturnItem>]
+ # @param tax_date [Time, nil] the original supply date; nil = order.completed_at
# @return [void]
- def refund(order, return_items)
- # no-op by default — internal provider handles via recalculation
+ def refund(order, return_items, tax_date: nil); end
+ end
+ end
+end
+```
+
+Two methods are deliberately absent. There is no `exempt?` — exemption enters through `estimate`'s `exemptions:` and leaves as a reason on the written rows. And there is no `validate_tax_id` — validating a registration number is keyed to the number's kind, not to a market's tax engine, so it lives in `Spree.tax_id_validators` (see "Buyer tax identity"). A provider gem may register itself there for the kinds its service can check.
+
+### Estimate flow (the single totals seam)
+
+```ruby
+# Carts::RecalculateTotals#regenerate_typed_rows — conceptually:
+def regenerate_typed_rows
+ Spree.adjusters.each { |adjuster| adjuster.adjust(cart) }
+ refresh_discount_and_fee_columns
+ @tax_line_context = run_hooks :set_tax_line_context # untyped provider extras only
+
+ tax_provider_for(cart).estimate( # cart.market&.tax_provider_instance, else the global default
+ cart,
+ tax_date: Time.current,
+ tax_identifier: cart.resolved_tax_identifier,
+ exemptions: Spree.tax_resolve_exemptions_service.call(order: cart),
+ context: tax_line_context
+ )
+end
+```
+
+Nil identifier and empty exemptions is the ordinary consumer path — zero overhead, B2C treatment. Incremental call sites (`Carts::AddItem`, single-item repricing) pass `items` exactly as today.
+
+### Resolving the two typed inputs
+
+The identifier is a fallback chain, so it is a method on the concern that already owns `tax_address` for both Cart and Order — no seam, per "prefer standard Rails models and concerns":
+
+```ruby
+# app/models/concerns/spree/purchase/taxation.rb
+module Spree
+ module Purchase
+ module Taxation
+ # The registration this sale is priced against. Deliberately not named
+ # #tax_identifier — that is the has_one for the row this record owns (the
+ # cart override, or the order's frozen snapshot), and it must keep meaning
+ # exactly that: an order whose snapshot is missing must not silently fall
+ # back to live customer data.
+ #
+ # @return [Spree::TaxIdentifier, nil] nil = consumer sale
+ def resolved_tax_identifier
+ tax_identifier || # cart-owned override, entered at checkout
+ # company&.tax_identifier — joins here when the B2B plan ships
+ customer&.tax_identifier # durable profile value
end
+ end
+ end
+end
+```
- # Check if an order is tax-exempt.
+Exemptions are different and do get a seam, because the default is genuinely empty and the real implementation is somebody else's: certificate filtering by active status and jurisdiction, with per-item overrides. That is behavior worth swapping, and it is the B2B integration point.
+
+```ruby
+# in Spree::Core::Dependencies
+tax_resolve_exemptions_service: 'Spree::Tax::ResolveExemptions',
+```
+
+```ruby
+# app/services/spree/tax/resolve_exemptions.rb
+module Spree
+ module Tax
+ class ResolveExemptions
+ prepend Spree::ServiceModule::Base
+
+ # @param order [Spree::Cart, Spree::Order]
+ # @return [Array<Spree::TaxExemption>]
+ def call(order:)
+ success([]) # Company certificates become the real implementation (B2B plan)
+ end
+ end
+ end
+end
+```
+
+A plain Tier 1 service per `6.0-service-workflows.md` — hand-written `call`, no hooks, never a workflow.
+
+### Tax identifier validation
+
+The registry is engine config holding **class names**, constantized at call time so registration is initializer-safe and survives dev reloads — the same storage rule `Spree.hooks` uses for handlers. Core registers nothing:
+
+```ruby
+# config/initializers/spree.rb in an app, or the extension's engine
+Spree.tax_id_validators['eu_vat'] = 'SpreeEuVat::TaxIdValidator'
+Spree.tax_id_validators['gb_vat'] = 'SpreeUkVat::TaxIdValidator'
+```
+
+**The contract** — a `Base` like every other pluggable seam, so the defaults live in one place and core never has to `respond_to?`-check. A validator is a provider, not an internal service: a plain class returning a value object, same as `Spree::TaxProvider::Base`.
+
+```ruby
+# app/models/spree/tax_id_validator/base.rb
+module Spree
+ module TaxIdValidator
+ class Base
+ # Synchronous, offline, no network — used by the model's format validation
+ # at entry time. Class-level and cheap, the same shape as
+ # Spree::SearchProvider::Base.indexing_required?, which core calls as
+ # Spree.search_provider.constantize.indexing_required?.
#
- # @param order [Spree::Order]
+ # Permissive by default: a validator that only knows how to talk to a
+ # registry accepts any value core allowed through.
+ #
+ # @param value [String] already normalized (whitespace stripped, upcased)
# @return [Boolean]
- def exempt?(order)
- return true if order.company&.tax_exempt?
- return true if order.company_location&.tax_exempt?
+ def self.valid_format?(_value)
+ true
+ end
+
+ # Asynchronous, hits the registry — used by ValidateJob.
+ #
+ # @param tax_identifier [Spree::TaxIdentifier] carries kind, value and its
+ # owner — reach the store through the owner when the registry needs
+ # credentials (owner.store.integrations…)
+ # @return [Spree::TaxIdentifier::ValidationResult]
+ def call(tax_identifier:)
+ raise NotImplementedError, "Please implement 'call' in your tax ID validator: #{self.class.name}"
+ end
+ end
+ end
+end
+```
+
+**What an implementer writes** — both halves of Stripe's split in one class: the offline format check, and the registry call:
+
+```ruby
+# the extension's app/models/spree_eu_vat/tax_id_validator.rb
+module SpreeEuVat
+ class TaxIdValidator < Spree::TaxIdValidator::Base
+ # 27 member states, each with its own length and letter positions — the
+ # jurisdiction knowledge core deliberately does not carry.
+ PATTERNS = { 'DE' => /\ADE\d{9}\z/, 'FR' => /\AFR\w{2}\d{9}\z/, … }.freeze
+
+ def self.valid_format?(value)
+ PATTERNS[value[0, 2]]&.match?(value) || false
+ end
+
+ def call(tax_identifier:)
+ response = client.check(tax_identifier.value) # country comes from the prefix
+
+ Spree::TaxIdentifier::ValidationResult.new(
+ status: response.registered? ? 'verified' : 'unverified',
+ normalized_value: response.normalized_value,
+ message: response.message,
+ checked_at: Time.current,
+ evidence: {
+ 'registry' => 'eu_vies',
+ 'consultation_number' => response.consultation_number,
+ 'verified_name' => response.name,
+ 'validated_country' => response.country,
+ 'validated_value' => response.queried_value
+ }
+ )
+ rescue SpreeEuVat::RegistryUnavailable => error
+ Spree::TaxIdentifier::ValidationResult.new(
+ status: 'unavailable', message: error.message, checked_at: Time.current
+ )
+ end
+ end
+end
+```
+
+A registry that is down returns `unavailable` rather than raising — the number stays usable and the platform records that nobody could answer.
+
+**Format is checked synchronously, at entry, and it is a hard validation.** A malformed number is a typo to fix, not a fact to record, so it is rejected on save with a field error — the same treatment a bad email address gets. This is the only synchronous check, it makes no network call, and it never depends on a registry being reachable:
+
+```ruby
+# app/models/spree/tax_identifier.rb
+class Spree::TaxIdentifier < Spree.base_class
+ before_validation :normalize_value
+
+ validates :value, :kind, presence: true
+ validates :value, length: { maximum: 64 } # data hygiene, not a format claim
+ validate :value_format
+
+ private
+
+ # Whitespace and case only. Punctuation is deliberately preserved: for several
+ # kinds it is part of the canonical number (Switzerland's CHE-123.456.789 MWST,
+ # Canada's PST-1234-5678), and Stripe keeps the entered value for the same
+ # reason. A validator that needs a different wire format produces it itself,
+ # and reports the registry's canonical form as normalized_value.
+ def normalize_value
+ self.value = value&.gsub(/\s+/, '')&.upcase
+ end
+
+ # Format knowledge lives entirely in the registered validator. Core asserts
+ # nothing about the shape of a number whose rules live in someone else's
+ # statute book — a charset or length rule spanning every tax regime on earth
+ # would be a guess we cannot test, and its failure mode is rejecting a real
+ # business customer rather than catching a typo. Kinds with no validator are
+ # accepted as entered.
+ def value_format
+ validator = Spree.tax_id_validators[kind]
+ return if validator.blank?
+ return if validator.to_s.constantize.valid_format?(value)
+
+ errors.add(:value, :invalid)
+ end
+end
+```
+
+A consequence worth naming: on an installation with no validator for a kind, a customer typing `123456789` instead of `DE123456789` is accepted. That is the honest position — nothing in core can know German VAT format — and it costs little, since the Internal provider ignores identifiers entirely and any installation that cares about reverse charge has a validator registered, which is where format knowledge belongs.
+
+**Where the registry check is called from.** The row itself, following `Spree::Address#async_geocode`:
+
+```ruby
+# app/models/spree/tax_identifier.rb (continued)
+class Spree::TaxIdentifier < Spree.base_class
+ after_commit :async_validate
+
+ def async_validate
+ Spree::TaxIdentifiers::ValidateJob.perform_later(id) if should_validate?
+ end
- false
+ private
+
+ # Mirrors Address#should_geocode? — only when the number itself changed, never
+ # for an order-owned snapshot (frozen by definition), and only when this
+ # installation can actually check this kind. A stock install registers no
+ # validators, so it never enqueues a job that could only write a column.
+ def should_validate?
+ order_id.nil? &&
+ Spree.tax_id_validators.key?(kind) &&
+ (saved_changes.key?('value') || saved_changes.key?('kind'))
+ end
+end
+```
+
+One mechanism covers every entry point — customer profile, cart override, admin, console, seeds — because they all end in a saved row. The callback only enqueues; the external call is the job's.
+
+Because of the registry guard, `validation_status` stays **nil** on an installation with no validator for that kind, and the admin tells the two nil cases apart by asking the registry: `Spree.tax_id_validators.key?(kind)` false means "this installation cannot check this kind", true means "queued, or not yet attempted". That is the discoverability the registry was chosen for. The stored `unsupported` therefore covers only the narrow race where a validator is deregistered between enqueue and run.
+
+```ruby
+# app/jobs/spree/tax_identifiers/validate_job.rb
+module Spree
+ module TaxIdentifiers
+ class ValidateJob < BaseJob
+ queue_as Spree.queues.tax_identifiers # new entry in Spree.queues, defaults to :default
+
+ def perform(tax_identifier_id)
+ tax_identifier = Spree::TaxIdentifier.find_by(id: tax_identifier_id)
+ return if tax_identifier.nil?
+
+ Spree::TaxIdentifiers::Validate.call(tax_identifier: tax_identifier)
+ end
+ end
+ end
+end
+```
+
+```ruby
+# app/services/spree/tax_identifiers/validate.rb
+module Spree
+ module TaxIdentifiers
+ # The ONLY writer of the validation columns. Resolves the validator, records
+ # 'unsupported' when none is registered for the kind, and persists with
+ # update_columns so the write cannot retrigger the after_commit above.
+ class Validate
+ prepend Spree::ServiceModule::Base
+
+ def call(tax_identifier:)
+ validator = Spree.tax_id_validators[tax_identifier.kind]
+ return persist(tax_identifier, unsupported_result) if validator.blank?
+
+ persist(tax_identifier, validator.to_s.constantize.new.call(tax_identifier: tax_identifier))
end
end
end
end
```
+The statuses the platform sets rather than receives: `pending` when the job is enqueued, and `unsupported` if the validator has disappeared by the time the job runs. On an unexpected validator failure the error goes to `Rails.error.report` with the identifier id as context while the row keeps its previous status — exactly as `GeocodeAddressJob` reports a failed lookup instead of raising.
+
### Internal Provider (default)
-Computes tax directly from TaxRate records — no Calculator::DefaultTax:
+Computes tax directly from TaxRate configuration — rate × discounted base, with included-in-price tax backed out of the gross basis. What this revision changes:
+
+- Write zero-amount rows for matched zero-rates and exemption-driven zeros, each carrying its reason. No row at all when no rate matched — that is the "no treatment opinion" case.
+- Stamp `taxability_reason` (`standard_rated` for a positive rate, `zero_rated` for a matched zero rate — finer distinctions such as `reduced_rated` are a rate-configuration concern, not something to infer) and the jurisdiction snapshot: from the matched rate's country/state after Phase 5, from the tax zone's country until then.
+- Honor the `exemptions:` input — entries covering an item produce `amount: 0` rows with `customer_exempt` for the jurisdictions they scope to.
+- Ignore `tax_identifier:` entirely; reverse charge is on the unsupported list, so a buyer registration changes nothing here.
+- Its limits are declared as capabilities and warned about when a market is paired, not reported per calculation — "no rate matched" is a legitimate answer for a merchant with no tax configured in the destination, and simply produces no row.
```ruby
module Spree
module TaxProvider
class Internal < Base
- def estimate(order, items)
- return clear_tax(order, items) if exempt?(order)
-
- address = order.tax_address
- rates = Spree::TaxRate.for_address(address)
-
- items.each do |item|
- applicable_rates = rates.select { |r| r.tax_category_id == item.tax_category_id }
- # Replace-all set semantics (split-adjustments write contract):
- # stale lines from rates that no longer match are removed with the rest
- item.tax_lines.destroy_all
- applicable_rates.each do |rate|
- amount = compute_tax(rate, item)
- create_tax_line(order, item, rate, amount)
- end
- end
+ def self.unsupported_capabilities
+ %i[us_local_tax reverse_charge oss_thresholds]
end
private
- 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 create_tax_line(order, item, rate, amount)
- item.tax_lines.create!(
- order: order,
- tax_rate: rate, # internal lines keep the FK — SQL joinability
- rate: rate.amount, # snapshot — row survives rate edits/deletion
+ def write_tax_line(owner, item, rate, amount, reason)
+ Spree::TaxLine.create!(
+ tax_line_foreign_key(item.class) => item.id,
+ owner_key(owner) => owner,
+ tax_rate: rate, # internal rows keep the FK — external ones leave it nil
amount: amount,
- included: rate.included_in_price?,
- label: rate.name,
- provider_id: 'internal'
+ rate: rate.amount, # snapshot: survives a rate edit or deletion
+ label: rate.adjustment_label,
+ included: rate.included_in_price,
+ provider_id: 'internal',
+ taxability_reason: reason, # 'standard_rated' / 'zero_rated' / 'customer_exempt'
+ country_iso: rate.country&.iso,
+ state_code: rate.state&.abbr
)
end
-
- def clear_tax(order, items)
- items.each do |item|
- item.tax_lines.destroy_all
- item.update_columns(
- included_tax_total: 0,
- additional_tax_total: 0
- )
- end
- end
end
end
end
```
-### External Provider Example (Avalara)
-
-Shows the contract — actual implementation in `spree_tax_avalara` gem. Note how the provider reads credentials from its `Spree::Integration` record (see "Credentials live in Spree::Integration" above):
+### External provider example (Avalara — reference gem)
```ruby
module SpreeTaxAvalara
class TaxProvider < Spree::TaxProvider::Base
def self.integration_class = 'Spree::Integrations::Avalara'
- def self.available_for_store?(store)
- store.integrations.active.exists?(type: integration_class)
- end
-
- def estimate(order, items)
- return clear_tax(order, items) if exempt?(order)
-
- # Build Avalara transaction request
- request = build_transaction(order, items, type: :estimate)
-
- # Call Avalara API
- response = client.create_transaction(request)
+ def estimate(owner, items = nil, tax_date: nil, tax_identifier: nil, exemptions: [], context: {})
+ request = build_transaction(
+ owner, items,
+ date: tax_date,
+ business_identification_no: tax_identifier&.value,
+ exemptions: exemptions, # → entityUseCode / exemptionNo (+ per-line codes)
+ extras: context
+ )
+ response = client_for(owner).create_transaction(request)
- # Write TaxLine records from response — self-describing rows,
- # no local TaxRate is referenced or synthesized (tax_rate_id stays nil)
+ # Replace-all set semantics, then write self-describing rows: no local
+ # TaxRate is referenced or synthesized (tax_rate_id stays nil).
items.each { |item| item.tax_lines.destroy_all }
response.lines.each do |avalara_line|
@@ -422,221 +892,178 @@ module SpreeTaxAvalara
next unless item
item.tax_lines.create!(
- order: order,
- rate: avalara_line.rate,
+ owner_key(owner) => owner,
amount: avalara_line.tax,
- included: avalara_line.tax_included,
+ rate: avalara_line.rate,
label: avalara_line.tax_name,
+ included: avalara_line.tax_included,
provider_id: 'avalara',
+ taxability_reason: taxability_reason_for(avalara_line),
+ country_iso: avalara_line.country,
+ state_code: avalara_line.region,
data: { 'jurisdictions' => avalara_line.details }
)
end
- # Store Avalara transaction ID for commit
- order.update_column(:metadata,
- order.metadata.merge('avalara_transaction_id' => response.id))
+ owner.update_column(:metadata, owner.metadata.merge('avalara_transaction_id' => response.id))
end
def commit(order)
transaction_id = order.metadata&.dig('avalara_transaction_id')
- return unless transaction_id
-
- client.commit_transaction(transaction_id)
+ client_for(order).commit_transaction(transaction_id) if transaction_id
end
def void(order)
transaction_id = order.metadata&.dig('avalara_transaction_id')
- return unless transaction_id
-
- client.void_transaction(transaction_id)
+ client_for(order).void_transaction(transaction_id) if transaction_id
end
- def refund(order, return_items)
- request = build_return_transaction(order, return_items)
- client.create_transaction(request)
+ def refund(order, return_items, tax_date: nil)
+ # ReturnInvoice with taxOverride.taxDate = original date → original rates apply
+ request = build_return_transaction(order, return_items, tax_date: tax_date || order.completed_at)
+ client_for(order).create_transaction(request)
end
- def exempt?(order)
- return true if super # company/location-level exemption
-
- # Avalara-specific: check exemption certificate
- if order.company&.metadata&.dig('avalara_exemption_id')
- validate_exemption(order.company.metadata['avalara_exemption_id'])
- else
- false
- end
- end
+ # Validation is not part of the provider contract — the gem registers a
+ # validator for the kinds Avalara can check:
+ # Spree.tax_id_validators['eu_vat'] = 'SpreeTaxAvalara::TaxIdValidator'
private
- def client
- @client ||= begin
- integration = market.store.integrations.active.find_by!(type: self.class.integration_class)
- AvaTax::Client.new(
- api_key: integration.preferred_api_key,
- environment: integration.preferred_environment,
- company_code: integration.preferred_company_code
- )
- end
+ # Credentials come from the store's Integration record at runtime, and the
+ # owner carries the store — so the client is derived per call rather than
+ # held as instance state (see "Credentials live in Spree::Integration").
+ def client_for(owner)
+ integration = owner.store.integrations.active.find_by!(type: self.class.integration_class)
+ AvaTax::Client.new(
+ api_key: integration.preferred_api_key,
+ environment: integration.preferred_environment,
+ company_code: integration.preferred_company_code
+ )
end
end
end
```
-### Integration Point: Order Tax Calculation
+External providers reference no local TaxRate and never synthesize one (`tax_rate_id` stays nil); rows are self-describing via the snapshots.
-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:
+### API surface
-```ruby
-# 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
+Conventions per `6.0-admin-api.md`: flat params, prefixed IDs, secret-key scopes or JWT + CanCanCan, admin serializers extending their store counterpart.
- def order
- adjustable.respond_to?(:order) ? adjustable.order : adjustable
- end
- end
- end
- end
-end
-```
+**Tax identifiers.** A singular nested resource, since a record owns at most one:
-### Integration Point: Order Completion
+| Endpoint | Verbs | Notes |
+|---|---|---|
+| `/store/customers/me/tax_identifier` | show, create, update, destroy | the customer's durable registration, self-service |
+| `/store/carts/:id/tax_identifier` | show, create, update, destroy | the checkout override; the only path a guest has, since a guest has no durable record |
+| `/store/customers/me/orders/:id` | — | the frozen snapshot, read-only, nested in the order serializer |
+| `/admin/customers/:id/tax_identifier` | show, create, update, destroy | + `POST …/validate` to re-run a check (see below) |
+| `/admin/orders/:id/tax_identifier` | show | read-only — the snapshot is immutable, and no correction path exists by design |
-```ruby
-class Spree::Checkout::Complete
- def call(order:)
- # ... existing completion logic ...
+Serializer split. The **store** side exposes `id`, `kind` and `value` — nothing else. All validation state is admin-only, because none of it is customer-actionable: at entry only the format check has run (a bad format is a 422 with a field error, which is the feedback that matters), and a verdict arriving later changes nothing for the buyer, since the treatment follows the number's format rather than its verdict. Exposing the status would mainly invite storefronts to build polling UX around a field we deliberately made non-blocking. Stripe draws the same line — its `verification` hash is a secret-key resource, absent from the client-side Checkout payload.
- # Commit tax document with provider
- market = order.market || order.store.default_market
- market.tax_provider_instance.commit(order)
+The **admin** side adds `validation_status`, `validated_at`, `validation_evidence`, `source`, timestamps, and a computed **`validatable`** boolean. That flag is admin-only on purpose: it answers "can this installation check this kind at all", which is a fact about the merchant's configuration rather than about the customer's number. It has to exist because the registry lookup core relies on (`Spree.tax_id_validators.key?(kind)`) has no HTTP equivalent — without it the dashboard cannot tell "no validator installed for this kind" from "queued, or not yet attempted", and the discoverability argument that chose a keyed registry over a single swappable service would stop at the API boundary.
- # ... rest of completion ...
- end
-end
-```
+**Tax lines.** The store serializer already exists (`label`, `rate`, `included`, `amount`) but no store endpoint consumes it — only `/admin/orders/:id/tax_lines`. Two changes:
-### Integration Point: Order Cancellation
+- **Expose tax lines on the Store API**, nested on cart and order line items. Totals alone cannot render an order confirmation or an account invoice, and every comparable platform exposes per-line tax to the customer (Medusa, commercetools, Vendure, Shopify's Customer Account API).
+- **`taxability_reason` and the jurisdiction snapshot are admin-only.** No surveyed platform exposes a machine-readable reason to buyers, and the customer-facing need is met by `label`, which is already there. The cost of this choice is asymmetric in our favour: withholding a field and adding it later is additive, exposing one and removing it is breaking. The admin serializer gains `taxability_reason`, `country_iso`, `state_code`, `category_code`, **and `data`** — currently unserialized anywhere, though it is exactly the jurisdiction breakdown an e-invoicing integration needs.
+- **Ransack allowlist** on `Spree::TaxLine` for `taxability_reason`, `country_iso` and `state_code`. Reporting is the stated rationale for those columns — "which country's tax was this, and which sales were reverse-charged" has to be answerable — and without the allowlist they are write-only.
-```ruby
-class Spree::Orders::Cancel
- def call(order:)
- # ... existing cancellation logic ...
+**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.
- market = order.market || order.store.default_market
- market.tax_provider_instance.void(order)
- end
-end
-```
-```
+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.
-Admin API allows setting per store:
+**Provider discovery and selection.**
-```json
-PATCH /api/v3/admin/stores/:id
-{
- "tax_provider": "SpreeTaxAvalara::TaxProvider"
-}
-```
+| Endpoint | Purpose |
+|---|---|
+| `GET /admin/tax_providers` | registry keys, names, `available_for_store?`, and `unsupported_capabilities` |
+| `PATCH /admin/markets/:id` | `tax_provider` becomes writable |
-### Tax Exemption Certificates (B2B extension)
+The dashboard cannot build a provider dropdown, nor warn that Internal should not be paired with a US market, without the declarations reaching it. Note `/admin/markets` is currently `only: [:index, :show]` — Phase 4 adds `update`.
-Building on the Company model from `6.0-channels-catalogs-b2b.md`:
+**Re-validation is admin-only.** `POST /admin/customers/:id/tax_identifier/validate` enqueues `ValidateJob`. Without it, a check that came back `unavailable` because a registry was down could never be retried — the `after_commit` only fires when the value changes. There is deliberately **no storefront equivalent**: a customer has nothing to do with the verdict (the treatment follows the number's format), so an on-demand check would only expose registry latency and downtime to the buyer for no decision they can make. Retrying is an operator's job.
-```ruby
-class Spree::TaxExemptionCertificate < Spree.base_class
- has_prefix_id :cert
+**Exemption certificates** (Phase 7): `/admin/companies/:id/tax_exemption_certificates` full CRUD, plus direct-upload for the attached document.
- belongs_to :company, class_name: 'Spree::Company'
- belongs_to :country, class_name: 'Spree::Country', optional: true # jurisdiction (nil = all countries)
- belongs_to :state, class_name: 'Spree::State', optional: true # state-level (nil = entire country)
+### Lifecycle integration points
- validates :certificate_number, presence: true
- validates :status, presence: true # pending, verified, expired, revoked
+- `Carts::Complete`: copy the resolved `TaxIdentifier` to the order (frozen, `source` stamped); call `provider.commit(order)` as an `external_step` (gateway-style I/O never inside the completion transaction).
+- `Orders::Cancel`: `provider.void(order)` as an `external_step`.
+- Returns flow (`6.0-returns-exchanges-claims.md`): `provider.refund(order, return_items, tax_date:)` from the refund workflow's `external_step`.
- attribute :certificate_number, :string
- attribute :status, :string, default: 'pending'
- attribute :issued_at, :datetime
- attribute :expires_at, :datetime
- attribute :issuing_authority, :string # state/province name
+## Migration Path
- has_one_attached :document # uploaded certificate PDF/image
+### Phases 1–2: seam + Internal provider + TaxLine — SHIPPED (as built)
- scope :active, -> { where(status: 'verified').where('expires_at IS NULL OR expires_at > ?', Time.current) }
- scope :for_address, ->(address) {
- where(country: [address.country, nil])
- .where(state: [address.state, nil])
- }
+Shipped with the core-rewrite waves, not as originally phased: no "Internal delegates to TaxRate.adjust" interim existed — the branch went straight to direct computation writing TaxLine rows, with `TaxRate.adjust`/`Adjuster::Tax`/`Calculator::DefaultTax` removed and the order-level money freeze in `Carts::RecalculateTotals` gating regeneration.
- def active?
- status == 'verified' && (expires_at.nil? || expires_at > Time.current)
- end
-end
-```
+### Phase 3: contract enrichment (this revision)
+
+- TaxLine: `taxability_reason` + vocabulary registry + the invoice-category / exemption-reason lookup maps + `country_iso`/`state_code` columns; zero-amount write contract in the Internal provider.
+- `Spree::TaxIdentifier` model + customer/cart/order FKs + `readonly?` freeze + completion copy step.
+- API: `/admin/tax_rates` CRUD (without it the Internal provider cannot be configured or verified through the API — see the API surface section), tax identifier endpoints (with admin `validatable` + the re-validate action), tax lines exposed on the Store API, admin tax-line serializer gaining `taxability_reason`/jurisdiction/`category_code`/`data`, and the Ransack allowlist for tax reporting.
+- `estimate` signature: `tax_date:`/`tax_identifier:`/`exemptions:`/`context:`; `refund(order, return_items, tax_date:)` replaces `refund(owner, amount)`; `exempt?` removed.
+- `Spree::TaxExemption` + `ItemOverride` value objects; `tax_resolve_exemptions_service` dependency (default empty); `#resolved_tax_identifier` on `Spree::Purchase::Taxation`.
+- `Spree::TaxIdValidator::Base` + `Spree.tax_id_validators` registry (empty by default, class names) + `Spree::TaxIdentifiers::Validate` (sole writer of the validation columns) + `ValidateJob` + `Spree.queues.tax_identifiers` + the `after_commit` enqueue guarded on kind/value changes.
+- Synchronous format validation on `TaxIdentifier`: whitespace/case normalization, presence, and the registered validator's class-level `valid_format?` (no format rules in core). Hard validation — a number a validator rejects never persists.
+- Capability declarations + Internal's unsupported list.
+- **Store binding** (the 2026-07-29 note above): `store_id` on `spree_tax_rates` and `spree_tax_categories` via `Spree::SingleStoreResource`, a backfill rake task, and store-scoped fetching in the endpoints above; `null: false` waits for 6.1 once the backfill has run everywhere. `TaxIdentifier`, `TaxLine` and the other typed rows deliberately get **no** `store_id` — they are owned rows whose owner already carries the store, matching `spree_tax_lines` as shipped; a denormalized copy would only be a second thing to keep in sync.
+- `set_tax_line_context` doc comment narrowed to untyped provider extras (see the Hook boundary paragraph under the exemption decision above).
+
+### Phase 4: per-Market selection + lifecycle wiring
+
+- `Market#tax_provider` + `#tax_provider_instance`, with the global config as fallback; call sites resolve through the owner's market; `GET /admin/tax_providers` discovery plus `update` on the admin markets endpoint (currently `index`/`show` only); Market admin UI gated by `available_for_store?` + capabilities. Whether the admin is backed by a registry model per engine (2026-07-30 note) or a plain class-name list is settled here.
+- `commit` in `Carts::Complete`, `void` in `Orders::Cancel`, `refund` in the returns flow — all `external_step`s.
+
+### Phase 5: decouple tax from Zone (Zone model stays)
-The provider's `exempt?` method checks certificates:
+Tax-side only — shipping keeps Zone untouched; full Zone removal is deferred to its own plan:
```ruby
-def exempt?(order)
- return true if order.company&.tax_exempt?
- return true if order.company_location&.tax_exempt?
-
- # Check for active certificate covering the order's tax address
- if order.company
- order.company.tax_exemption_certificates
- .active
- .for_address(order.tax_address)
- .exists?
- else
- false
- end
-end
+# rake spree:migrate_tax_zones
+# For each Zone used by TaxRate:
+# Extract country/state from ZoneMembers → set TaxRate.country_id / TaxRate.state_id
+# (Zone with multiple countries = one TaxRate per country)
```
-## Migration Path
-
-### Phase 1: Provider interface + Internal provider
+- Add `country_id`/`state_id` to `spree_tax_rates`; run the data task; remove `zone_id`.
+- Update the `/admin/tax_rates` serializer, permitted params and Ransack allowlist from `zone_id` to `country_id`/`state_id` — the only rework those endpoints take, and the reason they are worth building in Phase 3 rather than waiting.
+- Rewrite the tax-side zone readers against `TaxRate.for_address`: `Order#tax_zone`, `Spree::Current.zone`/`default_tax_zone`, `Market#tax_zone` — these feed pre-address tax display and Estimator VAT options, so they move to the provider/`for_address` path rather than being deleted.
+- **Re-point whatever populates `DeliveryRate#tax_rate`.** The Estimator matches that rate through the Zone path this phase removes, so it must move to `for_address` to keep working. Mechanical only — preserving current behavior here does not require answering Open Question 1, though this is the natural moment to.
+- `spree_zones`/`spree_zone_members` are **not** dropped in 6.0.
-- Create `Spree::TaxProvider::Base` and `Spree::TaxProvider::Internal`
-- Internal provider delegates to existing `TaxRate.adjust` — zero behavior change
-- Add `tax_provider` preference to Store
-- **No adjuster changes yet** — just the interface + default implementation
+### Phase 6: Avalara reference gem (`spree_tax_avalara`)
-### Phase 2: Wire into adjuster
+- Integration subclass + provider implementing estimate/commit/void/refund against AvaTax, plus a tax ID validator registered for the kinds Avalara can check.
+- Migrates `spree_avatax_official`'s user-level `exemption_number`/`entity_use_code` into gem-owned storage feeding `tax_resolve_exemptions_service` — the seam's first real implementation.
+- Documents how to build custom providers.
-- Modify `Adjuster::Tax` to delegate to provider instead of calling TaxRate directly
-- 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
+### Phase 7: Tax exemption certificates
-### Phase 3: Tax exemption certificates
+Last, and **gated on Company existing** (`6.1-channels-catalogs-b2b.md`) — the only phase here with an external dependency. Nothing earlier waits on it: until this ships, exemptions work through provider-native certificates and through extensions swapping `tax_resolve_exemptions_service`.
```ruby
-class CreateSpreeTaxExemptionCertificates < ActiveRecord::Migration[7.2]
+class CreateSpreeTaxExemptionCertificates < ActiveRecord::Migration[8.1]
def change
create_table :spree_tax_exemption_certificates do |t|
t.references :company, null: false
- t.references :country
- t.references :state
+ t.references :country # nil = every country
+ t.references :state # nil = the entire country
t.string :certificate_number, null: false
- t.string :status, null: false, default: 'pending'
+ t.string :reason_code, null: false # resale, government, … — becomes the
+ # provider's entity use code
+ t.string :status, null: false # no DB default: set by the creating service
t.datetime :issued_at
t.datetime :expires_at
t.string :issuing_authority
+ if t.respond_to?(:jsonb)
+ t.jsonb :metadata
+ else
+ t.json :metadata
+ end
t.timestamps
end
@@ -645,71 +1072,112 @@ class CreateSpreeTaxExemptionCertificates < ActiveRecord::Migration[7.2]
end
```
-- Create `TaxExemptionCertificate` model
-- Add to Company: `has_many :tax_exemption_certificates`
-- Provider `exempt?` checks certificates
-- Admin API for certificate CRUD
+```ruby
+class Spree::TaxExemptionCertificate < Spree.base_class
+ include Spree::HasStatus
+ include Spree::Metadata
-### Phase 4: Adapt to Split Adjustments
+ has_prefix_id :cert
-When `6.0-6.1-split-adjustments.md` ships:
-- Internal provider writes `TaxLine` records instead of `Adjustment` records (with `tax_rate_id` + `rate`/`label`/`provider_id` snapshots)
-- External providers also write `TaxLine` records — self-describing, `tax_rate_id` nil, never synthesizing local TaxRate rows
-- `OrderUpdater` reads totals from `tax_lines` instead of `adjustments.tax`
-- `TaxRate.adjust` is **not** reimplemented on top of TaxLines — the provider is the only write path (split-adjustments Resolved Question 8)
+ # Unlike the tax identifier's validation status, this one fits HasStatus
+ # exactly: a `status` column with a default, moved between values by workflows
+ # (verifying a certificate is a workflow, not a callback).
+ has_status :pending, :verified, :expired, :revoked, default: :pending
-### Phase 5: Decouple tax from Zone (Zone model stays)
+ belongs_to :company, class_name: 'Spree::Company'
+ belongs_to :country, class_name: 'Spree::Country', optional: true
+ belongs_to :state, class_name: 'Spree::State', optional: true
-Tax-side only — shipping keeps Zone untouched (see the Zones section of `6.0-delivery-rate-provider.md`; full Zone removal is deferred to its own plan):
+ has_one_attached :document # the uploaded certificate PDF or image
-```ruby
-# rake spree:migrate_tax_zones
-#
-# For each Zone used by TaxRate:
-# Extract country/state from ZoneMembers → set TaxRate.country_id / TaxRate.state_id directly
-# (Zone with multiple countries = one TaxRate per country)
+ validates :certificate_number, :reason_code, presence: true
+
+ scope :active, -> { verified.where('expires_at IS NULL OR expires_at > ?', Time.current) }
+ scope :for_address, ->(address) {
+ where(country: [address.country, nil]).where(state: [address.state, nil])
+ }
+end
```
-- Add `country_id` and `state_id` columns to `spree_tax_rates`
-- Run data migration rake task
-- Remove `zone_id` FK from TaxRate
-- Rewrite the tax-side zone readers against direct address matching (`TaxRate.for_address`): `Order#tax_zone`, `Spree::Current.zone`/`default_tax_zone`, `Market#tax_zone` — these feed pre-address tax display and Estimator VAT options, so they move to the provider/`for_address` path rather than being deleted
-- `spree_zones` / `spree_zone_members` tables are **not** dropped in 6.0
+With the model in place, `Spree::Tax::ResolveExemptions` grows the body its empty default was standing in for — and this is the whole point of having built the seam first, since nothing about the provider contract changes:
-### Phase 6: Reference external provider (separate gem)
+```ruby
+def call(order:)
+ company = order.company
+ return success([]) if company.nil?
+
+ success(
+ company.tax_exemption_certificates.active.for_address(order.tax_address).map do |certificate|
+ Spree::TaxExemption.new(
+ reason_code: certificate.reason_code,
+ certificate_number: certificate.certificate_number,
+ country_iso: certificate.country&.iso,
+ state_code: certificate.state&.abbr
+ )
+ end
+ )
+end
+```
-- Create `spree_tax_avalara` gem as reference implementation
-- Implements estimate/commit/void/refund against Avalara AvaTax API
-- Handles: nexus detection, exemption certificate validation, address validation
-- Documents how to build custom providers
+Also in this phase: `has_many :tax_exemption_certificates` on Company, admin API CRUD for certificates, and the admin surface for uploading and verifying them.
## Constraints on Current Work
-- **Don't add new tax logic to TaxRate.adjust.** New tax behavior should be designed for the provider interface. TaxRate.adjust stays as the Internal provider's implementation.
-- **Don't add tax-related configuration beyond `Spree::Config[:tax_using_ship_address]`.** Provider-specific config belongs on the provider (via Store preferences or metadata), not in global Spree config.
-- **Don't monkey-patch TaxRate for external tax services.** The provider interface is the intended seam.
-- **Tax exemption checks should use `provider.exempt?(order)`.** Don't add ad-hoc exemption checks in controllers or services.
-- **TaxCategory stays as the product-level tax classification.** External providers use tax category as the "tax code" mapping (e.g., TaxCategory "Clothing" → Avalara tax code "PC040100").
+- **The provider is the only TaxLine writer.** Don't add tax computation anywhere else; don't reintroduce calculators or adjuster-side tax.
+- **Don't put typed tax inputs in `set_tax_line_context`.** Exemptions, tax identifiers and dates are named `estimate` parameters, assembled by `tax_resolve_exemptions_service` and `#resolved_tax_identifier`; the hook carries untyped provider extras only.
+- **No exemption flags on customer, order or line items.** The claim is an ephemeral `Spree::TaxExemption`; the outcome is TaxLines with reasons. Don't add ad-hoc exemption checks in controllers or services — swap `tax_resolve_exemptions_service`.
+- **Order-owned TaxIdentifier rows are immutable.** No correction path; don't add one. Don't read customer tax data live for anything post-completion — use the order snapshot.
+- **Don't validate a tax ID from the tax provider, and don't validate during estimate.** Register a validator for the kind in `Spree.tax_id_validators`; the estimate path reads the stored result. No registry client (for any jurisdiction) belongs in core.
+- **Don't make a registry call block a save or a checkout, and don't gate the tax treatment on a verdict.** Format is checked synchronously and offline; the registry answer is asynchronous and advisory. Reverse charge follows the number's format, so a `pending` identifier still prices correctly. Making it synchronous imports the registry's downtime into checkout — see the rejected Magento model.
+- **Don't add tax-related global configuration beyond `Spree::Config[:tax_using_ship_address]`** (the sourcing default). Provider-specific config belongs on the Integration.
+- **TaxCategory stays as the product-level tax classification** — external providers use it as the tax-code mapping (e.g. TaxCategory "Clothing" → Avalara `PC040100`). Product taxability never flows through the exemption input.
+- **Don't hardcode invoice category or exemption reason codes outside the core lookup maps.** New taxability reasons register through the additive vocabulary together with their code mappings.
## Open Questions
-1. **Shipping rate tax estimation.** `ShippingRate` currently computes tax via `shipping_rate.tax_rate.calculator.compute_shipping_rate(self)` for display during checkout. Should the provider also handle shipping rate tax estimation? Or keep it as-is since it's display-only and the real tax is computed when the shipment is created? Leaning toward provider handles all tax, including shipping rate display.
+1. **Delivery-rate tax display bypasses the provider.** `DeliveryRate#tax_amount` computes tax itself — `belongs_to :tax_rate` plus the same included/additional formula the Internal provider uses — because options have to show a tax-inclusive price before the customer picks one, and there is nothing to write TaxLine rows against yet. So the calculator indirection went away but the arithmetic was copied into the model, which contradicts "the provider is the only entry point" and returns zero for any market on an external provider.
+
+ The awkward part is that pricing five options means five *hypothetical* computations that must not be persisted, whereas `estimate` is defined as a write. That is a quote, not a write — a different operation. Roughly three ways out: scope the inline math to Internal and show nothing otherwise (honest, cheap); add a read-only `quote` to the contract that returns an amount without writing rows (correct, but earns the provider a second method, and one API call per option is expensive for external providers); or drop tax from the option labels and let it appear once a rate is chosen.
+
+ Deferrable, and deliberately left uncovered while 6.0 is in development: Phases 3–5 neither need nor are blocked by an answer, and the only knock-on is that from Phase 4 a market pointed at an external provider shows no tax on its delivery options while checkout charges the provider's — a display defect, not a collection one, since the money still comes from the provider's TaxLines. Phase 5 re-points the rate matching mechanically. The natural time to settle the design is alongside `6.0-delivery-rate-provider.md`, which owns `DeliveryRate` enrichment.
+
+Resolved (previously open):
+- **Context key discoverability** — no declaration mechanism. `estimate`'s `context:` is the hash produced by the `set_tax_line_context` hook: extensions register handlers, each returns a hash, and `run_hooks` deep-merges them all into one before the provider is called. Whatever rides it is either documented by the gem that reads it, or — if a merchant is meant to configure it — belongs on that provider's `Spree::Integration` as a preference, where it already gets persistence and an admin form. Handlers should namespace their contribution under the provider key (`{ 'avalara' => { … } }`), because unlike `TaxLine.data`, which one provider writes onto a row already stamped with `provider_id`, this hash is merged across every registered handler and same-key contributions overwrite each other in registration order. Declaring keys the way `unsupported_capabilities` is declared was considered and rejected: validating them would make the channel typed, and a typed input deserves a named `estimate` parameter rather than a hash — `context:` exists precisely for what does not warrant a contract. The residual cost is accepted: a mistyped key is silently ignored, which is a bug in an extension that owns both ends.
+- **Estimate return value** — `estimate` returns nothing meaningful; the rows it writes are the output, and a provider that cannot complete raises. The structured result and its indeterminacy channel are deferred, not rejected: both cases that motivated them are covered by capability declarations at configuration time, and a return value can be added later without breaking providers or callers.
+- **Caching for external providers** — left to the provider implementation; different providers have different caching needs.
+- **Tax document ID storage** — `order.metadata` (provider-agnostic, schema stays clean).
+- **Multi-provider per store** — per-Market selection is the answer; one provider per market, markets partition the regions.
-2. **Caching for external providers.** External API calls during every recalculation could be expensive. Should the provider interface include a caching contract (e.g., "cache estimate for 5 minutes unless address changes")? Or leave caching to the provider implementation? Leaning toward leaving it to the implementation — different providers have different caching needs.
+## Regulatory background
-3. **Tax document ID storage.** External providers need to store transaction IDs (for commit/void). Currently the Avalara example uses `order.metadata`. Should there be a dedicated `tax_document_id` column on Order, or is metadata sufficient? Leaning toward metadata — keeps the schema clean and provider-agnostic.
+Sources for the plain-English legal claims made above — for anyone verifying them, or updating this plan when the rules move. **Nothing here is needed to implement the design.** Every entry was checked against a primary source during the 2026-08-05 review.
-4. **Multi-provider per store.** Some merchants use Avalara for US tax and internal rates for EU VAT. Should we support multiple providers per store (e.g., per-zone routing)? This adds significant complexity. Leaning toward single provider per store for 6.0 — the Avalara provider can internally handle multi-jurisdiction via Avalara's own zone logic.
+| Claim in this plan | Source |
+|---|---|
+| Every invoice line must carry a tax category code | EN 16931 (the European e-invoicing standard), field BT-151, made mandatory per line by rule BR-CO-4 |
+| Zero-tax lines need an exemption reason (code or text) | EN 16931 fields BT-121 (code) and BT-120 (text); one of the two is required when the category is E, AE, K, G or O (rules BR-E-10, BR-AE-10, BR-IC-10, BR-G-10, BR-O-10). Category Z — zero-rated — needs no reason |
+| The invoice category code list | UNTDID 5305, narrowed by EN 16931 to S (standard), Z (zero), E (exempt), AE (reverse charge), K (intra-EU supply), G (export), O (outside scope), plus L and M for the Spanish territories |
+| The exemption reason code list | VATEX, maintained by the European Commission and revised roughly twice a year — which is why core stores its own reason string and derives these codes rather than persisting them |
+| Reverse-charge invoices must say so in words, and the omission cannot be repaired later | VAT Directive 2006/112/EC Art. 226(11a); Court of Justice of the EU, case C-247/21 (*Luxury Trust Automobil*, 2022) |
+| The rate that applies is the one in force when the sale happened | VAT Directive Art. 63 (when tax becomes chargeable) and Art. 93 (which rate applies). Recent standard-rate changes confirming this matters: Finland September 2024, Slovakia January 2025, Estonia July 2025 |
+| A valid buyer registration number is a hard condition for zero-rating cross-border EU goods | VAT Directive Art. 138(1) as amended by Directive (EU) 2018/1910 — the "Quick Fixes", in force since January 2020. Before that it was a formality courts would excuse |
+| For services, an unidentified buyer may be treated as a consumer | Implementing Regulation (EU) 282/2011 Art. 18 — a presumption the seller is entitled to rely on, which is why "no validated ID → charge normal tax" is safe rather than merely convenient |
+| The EU verification service cannot confirm past validity | VIES (VAT Information Exchange System) official FAQ: "It is not possible to confirm the validity of a VAT number in the past." It returns a consultation number as evidence that a check was performed on a given date — which is why validation evidence is snapshotted |
+| One-stop-shop returns are filed per destination country | Commission Implementing Regulation (EU) 2020/194, Annex III — one section of the return per country of consumption |
+| A return is reported in the period its credit note is issued, not the original period | VAT Directive Art. 264(2). Correcting a genuine *error* is the separate case that reopens the original period (e.g. Germany § 18a(10) UStG, Austria Art. 21 UStG) |
+| The EUR 10,000 threshold below which home-country tax applies to cross-border consumer sales | VAT Directive Art. 59c — a single EU-wide threshold covering digital services and distance-sold goods combined |
+| Mandate timeline | Belgium January 2026; France September 2026 (receiving) with issuing phased 2026–2027 by company size; Germany issuing 2027–2028 by turnover (receiving already mandatory since January 2025); Poland February/April 2026 on its own national schema rather than EN 16931; EU-wide for cross-border sales from July 2030 under the "VAT in the Digital Age" package (Directive (EU) 2025/516) |
## References
-- Current tax rate: `spree/core/app/models/spree/tax_rate.rb`
-- Current calculator: `spree/core/app/models/spree/calculator/default_tax.rb`
-- Current VAT concern: `spree/core/app/models/concerns/spree/vat_price_calculation.rb`
-- Current tax adjuster: `spree/core/app/models/spree/adjustable/adjuster/tax.rb`
-- Current order updater: `spree/core/app/models/spree/order_updater.rb`
-- Current zone matching: `spree/core/app/models/spree/zone.rb`
-- AdjustmentSource concern: `spree/core/app/models/concerns/spree/adjustment_source.rb`
-- Related plan: `6.0-6.1-split-adjustments.md` (TaxLine model replaces polymorphic Adjustment for tax)
-- Related plan: `6.0-channels-catalogs-b2b.md` (Company.tax_exempt, CompanyLocation.tax_exempt)
-- Related plan: `6.0-returns-exchanges-claims.md` (Return flow triggers provider.refund)
+- Shipped provider seam: `spree/core/app/models/spree/tax_provider/` (`base.rb`, `internal.rb`)
+- Shipped TaxLine: `spree/core/app/models/spree/tax_line.rb`, `spree/core/db/migrate/20260729000001_create_typed_adjustment_tables.rb`
+- Single totals seam + money freeze + `set_tax_line_context`: `spree/core/app/workflows/spree/carts/recalculate_totals.rb`
+- Current tax rate (config-only): `spree/core/app/models/spree/tax_rate.rb`
+- Community review driving the 2026-08-05 revision: spree/spree#14056 (treatment-not-amount, VAT ID validity, immutability, capability honesty)
+- Legacy Avalara integration (field mappings + user-level exemption storage precedent): `spree_avatax_official`
+- Related plan: `6.0-6.1-split-adjustments.md` (TaxLine schema; order-level money freeze)
+- Related plan: `6.1-channels-catalogs-b2b.md` (Company/CompanyLocation — durable tax identifiers, exemption certificates)
+- Related plan: `6.0-service-workflows.md` (workflow tiers, hooks contract, `set_tax_line_context`)
+- Related plan: `6.0-returns-exchanges-claims.md` (returns flow triggers `provider.refund`)
+- Related plan: `6.0-delivery-rate-provider.md` (Zone survival scope; delivery-side rate display)
diff --git a/docs/plans/6.1-channels-catalogs-b2b.md b/docs/plans/6.1-channels-catalogs-b2b.md
index 2c42c83b32..f52c6ad527 100644
--- a/docs/plans/6.1-channels-catalogs-b2b.md
+++ b/docs/plans/6.1-channels-catalogs-b2b.md
@@ -6,7 +6,7 @@
> **Filename note:** this plan keeps its `6.0-` filename for stable cross-references (it's linked from CLAUDE.md and ~10 sibling plans), but the Phase 2 deliverable (Catalog + Company) now targets **6.1**. Don't infer the target from the filename — the header and per-phase headings are authoritative. Phase 1 (5.5) and the 5.6 Gated Access phase are unaffected.
**Depends on:** ProductType (6.0-product-types.md), PriceList system (existing)
**Author:** Damian + Claude
-**Last updated:** 2026-07-09
+**Last updated:** 2026-08-05
## Summary
@@ -120,6 +120,7 @@ Store (who you are — legal entity, config boundary)
- **CompanyLocation** belongs to Company. Represents an office/branch. Has billing address, shipping address, tax exemption settings. Can have assigned Catalogs.
- **CompanyContact** belongs to CompanyLocation. Links to a User (Spree.user_class). A user can be a contact at multiple locations.
- **CustomerGroup is NOT replaced.** Companies and CustomerGroups serve different purposes: CustomerGroup is a flat segmentation tag (VIP, Wholesale). Company is a hierarchical B2B entity. A Company can be IN a CustomerGroup.
+- **Tax obligations from `6.0-tax-provider.md` (2026-08-05):** Company becomes an owner on `spree_tax_identifiers` (`company_id` FK — the durable VAT/tax registration for the entity, joining the resolution chain above the customer's own row), and `CompanyLocation` is the eventual home for per-branch registrations (Shopify's `CompanyLocation.taxRegistrationId` precedent). `Spree::TaxExemptionCertificate` hangs off Company (`has_many :tax_exemption_certificates`) but is **specified and built by the tax-provider plan's last phase**, which is gated on Company shipping — see that plan for the schema and the model. Nothing is owed here beyond the association.
## Design Details
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index efe5610a61..82ba218f17 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -343,6 +343,118 @@ only). The method itself can stay; nothing in core invokes it any more.
Plan: `6.0-service-workflows.md` decision 13.
+## 2026-08-05: Tax provider contract carries treatments, identities and dates — refined after the #14056 community review
+
+The provider contract in `6.0-tax-provider.md` was reworked after two
+outside implementers (an EU VAT decision engine, a US rates API) reviewed
+the RFC on spree/spree#14056. Every concern was verified before adoption:
+against primary legal sources (the European e-invoicing standard, the VAT
+Directive, the EU verification service's own documentation — citations now
+live in the plan's **Regulatory background** section), the major provider
+APIs (Avalara, Stripe Tax, TaxJar, Vertex) and platform practice (Medusa,
+Saleor, commercetools, Shopify, Magento, Odoo). Decisions:
+
+**TaxLine carries a taxability reason, not just an amount.** A zero from
+reverse charge, an export and an exemption are different facts landing in
+different boxes of a tax return, and European e-invoices must state the
+category for every line. New `taxability_reason` column with an additive
+vocabulary (Stripe's enum pruned, plus `intra_community_supply` and
+`export` — Stripe's own values cannot tell cross-border goods from
+services, or an export from a domestic zero rate), plus a jurisdiction
+snapshot (`country_iso`/`state_code` — one-stop-shop returns are filed per
+destination country). The invoice category and exemption reason codes are
+deliberately NOT stored — they derive at invoicing time from the reason
+plus order facts (the Odoo pattern; no surveyed platform stores them).
+Core ships the reason→code lookup maps as code. Write contract: a row for
+every item the provider formed a treatment for, including zero amounts.
+
+**Buyer tax identity is a separate model, `Spree::TaxIdentifier`.**
+Stripe's shape (typed kinds, multiple per customer, verification state)
+with Magento's evidence discipline (VIES consultation number, validated
+country/value — VIES has no historical lookup, so entry-time evidence is
+the only proof that will ever exist). Dual-FK owner: customer (durable —
+sole proprietors will never have a Company), cart (override), order
+(completion snapshot, frozen via `readonly?`, `source`-stamped, no
+correction path); company/company_location FKs arrive with the B2B plan.
+Zero footprint on consumer orders. Live-read designs were rejected on
+documented drift pain (Shopify B2B, Odoo).
+
+**Validating a tax ID belongs to the identifier, not to a tax provider.**
+The registry that can answer is determined by the number's *kind* (EU VAT
+→ the EU service, UK → HMRC, and so on), never by a market — a customer
+saves a tax ID on a profile before any order exists, so a provider-hung
+`validate_tax_id` would force an arbitrary choice (a US sales-tax engine
+asked to check an EU number, or an EU market on Internal declining while
+a connected Avalara sits unused). The seam is therefore
+`Spree.tax_id_validators`, a registry keyed by kind and empty by default —
+core ships no registry client for any jurisdiction — so two extensions
+covering different kinds coexist where a single swappable service would
+let the second loaded silently disable the first. Validation splits the way Stripe's does: **format
+synchronously, the registry asynchronously, and the tax treatment depends
+on neither.** Format is a hard validation on save — whitespace/case
+normalization, presence, then the registered validator's class-level
+`valid_format?` (the `SearchProvider::Base.indexing_required?` shape) — so a
+typo is a field error and never persists. Core asserts no format rules of its
+own: a charset or length range spanning every tax regime would be an untestable
+guess whose failure mode is rejecting a real business customer. The registry check runs after
+commit on the address-geocoding precedent (`after_commit` enqueues, the job
+does the I/O, `update_columns` writes back, a non-answering registry is
+reported and recorded as `unavailable`), never during estimate, which reads
+the stored result. Reverse charge follows the number's format, not its
+verdict — Stripe applies it "regardless of its validity" — so a sale may
+complete with `pending` and still be treated correctly; the verdict is
+evidence, not arithmetic. **Magento's model was rejected:** synchronous
+registry validation gating the treatment through customer groups, whose own
+ecosystem documents the cost (a third-party module exists solely to add
+caching and offline fallback for the unstable registry, and per-transaction
+validation cannot run at all under external checkouts). A tax provider gem
+may register itself as the validator for kinds its service can check.
+
+**Exemption is a typed estimate input plus the TaxLine outcome — the
+boolean `exempt?(order)` is removed** (wrong arity: per jurisdiction, per
+item, and the reason is the audit artifact; no provider API exposes an
+exempt? query). `Spree::TaxExemption` value objects (mirroring the future
+certificate row, with typed per-item overrides) are assembled by the
+`tax_resolve_exemptions_service` dependency (default `[]`) — a seam because
+the real implementation, certificate filtering by active status and
+jurisdiction, is the B2B integration point. The identifier chain gets no
+seam: it is a fallback `||` and lives as `#resolved_tax_identifier` on the
+`Spree::Purchase::Taxation` concern beside `tax_address`. No exemption flags
+on customer, order or line items. The `set_tax_line_context` hook is NOT
+the channel for typed inputs — it narrows to untyped provider extras
+before the 6.0 hook freeze. `TaxExemptionCertificate` stays in the tax plan
+as its last phase, gated on Company existing, and gains `reason_code` — the
+field providers actually consume as an entity use code, missing from the
+original sketch.
+
+**Dates are explicit.** `estimate`/`refund` take the rates-effective tax
+date (unanimous provider practice, and legally the rate in force when the
+sale happened is the one that applies), kept distinct from the
+document/posting date. Refund becomes
+`refund(order, return_items, tax_date:)` — supports both recompute-at-
+original-date (Avalara/Vertex) and derive-from-recorded (Stripe/TaxJar);
+the Internal provider only ever derives (TaxRate rows are unversioned).
+The "credit note corrects the original filing period" claim from the
+thread was checked and not adopted: a return is reported in the period its
+credit note is issued, and only correcting a genuine error reopens the
+original period.
+
+**Capability honesty.** Providers declare unsupported domains; Internal
+declares no destination-based US local tax (state-level rates cannot
+express county/city/district stacking — silently under-collecting lands
+on the merchant), no OSS threshold tracking, no reverse charge (unvalidated
+ID → normal VAT, the protected default), no ID validation. `estimate`
+A runtime indeterminacy channel on `estimate` was
+considered and deferred: both cases the review raised (one-stop-shop
+thresholds, Internal against US local rates) are answered by the capability
+declarations at configuration time, nothing in core would consume a
+per-calculation verdict, and unlike a hook key a return value can be added
+later without breaking providers. `estimate` keeps its current signature —
+the rows it writes are its output. Per-Market provider selection is
+reworded to selection-not-construction: the market names the provider,
+providers stay stateless and argless (the shipped `Base` shape), the
+shipped global config class stays as the fallback.
+
## 2026-08-04: Commerce-behavior globals move to Store preferences; app configuration stays global
A full usage audit of `Spree::Config` (multi-agent trace with adversarial