Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Tax Provider Interface
Status: In Progress — the provider surface, Spree::TaxProvider::Internal and the TaxLine write path were implemented with the core-rewrite waves (see Current State). Phases 3, 4 and 5 are in development (contract enrichment, per-Market selection, commit/void/refund wiring, Zone decoupling). Phase 7 (exemption certificates) is next up and no longer gated — it builds the minimal Company tree itself (2026-08-07, see Key Decisions). Remaining after that: Phase 6 (the Avalara reference gem), Phase 8 (cross-border pricing with tax-inclusive prices — three defects found by the 2026-08-11 live pass) and Phase 9 (the 6.1 cleanup of the schema 6.0 keeps deliberately).
Store binding (2026-07-29): TaxRate and TaxCategory adopt the every-major-model-carries-a-store_id convention as part of this plan's implementation (
Spree::SingleStoreResource, backfill task, NOT NULL in 6.1) — same treatment DeliveryMethod/StockLocation/DeliveryZone received on the 6.0 core-rewrite branch.
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::Avalaraholding store credentials, the provider writing TaxLines withprovider_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_idstays a plain string registry key ('internal','avalara') — Medusa's tax lines use the identical field name and semantics (tp_systemfor 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 stayingSpree::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::TaxIdentifiermodel with an order-time snapshot; exemption is a typed estimate input (the booleanexempt?is removed); the effective date is an explicit input; providers declare capability limits honestly. See Key Decisions.
The market decides tax inclusion (2026-10-16, V-3662): whether a price includes tax is
Market#tax_inclusivealone. Spree's own tables read it and every provider receives it astax_inclusive:onestimateandestimate_replacement;TaxRate#included_in_priceis retired (column dropped in 6.1), and the 2026-08-11 cross-border restatement is removed, so every customer pays the price as entered. See the cross-border Key Decision, Phase 8 and decisions.md.
Post-sale tax (2026-10-01, V-3725): returns, claims and exchanges now give back the tax the customer paid, and the provider decides that figure. The contract gains
estimate_refund(credit rows on return, claim and exchange lines;Internalanswers with the recorded share of the sale's rows),estimate_replacement(an exchange's replacement taxed as a new sale) andcommit_replacement.refundkeeps its signature and files what the credit rows hold. Post-sale rows hang off the order but never count towards its totals. See "Post-sale tax" below and decisions.md 2026-10-01.
Target: Spree 6.0
Depends on: Split Adjustments (6.0-6.1-split-adjustments.md — shipped; provides TaxLine). Phase 7 pulls the Company tree forward out of 6.0-channels-catalogs-b2b.md rather than waiting on it — that plan keeps Catalog, per-company pricing and product visibility, and inherits the models this phase ships.
Author: Damian + Claude
Last updated: 2026-10-16
Summary
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 seam itself is live on main: 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
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-patchTaxRateor wrap the entire adjuster.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.
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.
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.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.
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.
Dates are implicitly "now". Every major provider API takes a transaction/tax date (Avalara
date+taxOverride.taxDate, Stripetax_date, TaxJartransaction_date, VertexdocumentDate) 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.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
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 |
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 (removed 2026-10-16) |
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 (included the Tax adjuster) |
OrderUpdater#update
→ recalculate_adjustments (each line item + shipment)
→ Adjuster::Tax#update
→ adjustment.update! (for each existing tax adjustment)
→ TaxRate#compute_amount(item)
→ Calculator::DefaultTax#compute_shipment_or_line_item(item)
Order#create_tax_charge!
→ TaxRate.adjust(order, line_items)
→ TaxRate.match(order.tax_zone) → find matching rates
→ TaxRate.store_pre_tax_amount(item, rates) → pre-tax for VAT
→ rate.adjust(order, item) → create_adjustment (via AdjustmentSource)
→ TaxRate.adjust(order, shipments)
Why calculators alone can't solve this
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:
- 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.
- Lifecycle events — No hooks for commit (order completed), void (order cancelled), refund (items returned). External services distinguish estimate vs committed transactions for filing/reporting.
- State storage — Calculators are stateless. External providers need to store transaction IDs (e.g.,
avalara_transaction_id) on the order for later commit/void. - Exemption logic — Exemption evidence must reach the calculation before the API call. Calculators only compute amounts.
- 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.
Provider (order lifecycle)
└─ Internal provider → reads TaxRate (rate %, zone, included?) → computes directly
└─ Avalara provider → Avalara API → writes TaxLine records directly
Shipped on main (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; matches on the taxing jurisdiction (TaxRate.for_jurisdiction), not a Zone; skips zero amounts (changed by this revision) |
Spree.default_tax_provider |
core/lib/spree/core.rb |
Returns the globally configured fallback class (default Internal); callers say .new. Renamed from Spree.tax_provider, which returned an instance and implied it was the only provider — selection is per-market, through Spree::Purchase::Taxation#tax_provider |
Spree::TaxLine |
core/app/models/spree/tax_line.rb + spree_tax_lines |
Typed adjustment row: dual-FK cart/order owner, exactly-one adjustable (line item / fulfillment / fee), amount, rate + label + provider_id snapshots, included, data + metadata JSON |
| Order-level money freeze | core/app/workflows/spree/carts/recalculate_totals.rb |
money_frozen? (completed order) skips regenerate_typed_rows — no adjusters, no estimate; fold_typed_rows always re-sums totals from rows |
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 at the time this section was written: per-market selection, commit/void/refund callers, the exemption input, buyer tax identity, Phase 5 Zone decoupling, the Avalara gem, TaxExemptionCertificate. All but the last two are in development on the current branch.
Key flow today
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
→ cart.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.adjustis removed. The provider is the only entry point for tax calculation and the only sanctioned TaxLine writer. NoAdjustmentSource, noCalculatedAdjustmentsconcern on TaxRate, noCalculator::DefaultTax.TaxRatestays as pure configuration (rate %, zone until Phase 5, tax category) — no behavior. Whether its tax sits inside a price is the market'stax_inclusivesince 2026-10-16, not the rate'sincluded_in_price.
Provider contract: estimate/commit/void/refund with explicit dates
# 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
# After the sale — return, claim and exchange lines (see "Post-sale tax"):
provider.estimate_refund(order, items, amounts: nil, tax_date: nil) # credit rows the refund carries
provider.estimate_replacement(order, items, tax_date: nil, # an exchange's replacement,
tax_identifier: nil, exemptions: []) # taxed as a new sale
provider.refund(order, return_items, amount: nil, tax_date: nil) # file the credit — no-op for Internal
provider.commit_replacement(order, items) # file the replacement — no-op for Internal
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
itemslimits 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.
- Estimate refund is called when a return, claim or exchange opens, and again before its money moves. It decides the tax the customer gets back, writing it as credit rows on the post-sale lines. The money refunded is exactly what those rows hold.
- Refund is called once the money has moved. 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. It credits no more than the rows
estimate_refundwrote.
Decisions about that contract:
estimatereturns 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; Stripetax_date; TaxJartransaction_date; VertexdocumentDate), 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 (DocDatevsTaxOverride.TaxDate) and Stripe (tax_datevsposted_at). - Estimate never runs on completed orders. The order-level money freeze (
money_frozen?inCarts::RecalculateTotals) is the enforcement. Post-placement corrections go throughestimate_refund/estimate_replacement,refundand the explicit admin row-edit endpoints, never a re-estimate. The post-sale methods write rows on return, claim and exchange lines and never touch the sale's own rows. - 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. Built as
Internal#estimate_refund, throughSpree::TaxProvider::RecordedShare(2026-10-01). - 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
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.
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.
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.
Post-sale tax: the provider decides what goes back (2026-10-01)
A return, claim or exchange gives back the tax the customer paid on what came back, and the provider decides that figure — the money follows its answer.
- Credit rows.
estimate_refundwritescredit: trueTaxLines onReturnLineItem,ClaimLineItemorExchangeLineItem— three more concrete adjustable keys, plusoriginal_tax_line_idnaming the sale row each credit gives back. They are owned by the order like every other row, butOrder#tax_linesreadssalerows only, so they never reach the order's totals (Carts::RecalculateTotalsre-sums that association on completed orders too). - Internal gives back the recorded share.
Base#estimate_refundhas no default — every provider answers it.Internalanswers withSpree::TaxProvider::RecordedShare, which any provider may reuse: it gives each credited unit its share of every row the sale charged, row by row, rounded once and divided by largest remainder, and never credits a row past what earlier credits left of it. Another provider may use it too, or quote instead — for example at the originaltax_date— but must answer in the same rows. The customer is owed back what they paid, so the recorded share reads the rows rather than today's rates. - When it runs. Once when the record opens, for what was announced, which the line copies onto its own columns (
pre_tax_amountbefore tax,included_tax_total,additional_tax_total— the way an order line carries them). Again before money moves, rewriting the rows for what actually goes back: the units the warehouse counted, and only the share of their worth refunded when a merchant keeps a restocking fee (amounts:, split proportionally). The columns keep what was announced; the rows say what went back. A provider failure refuses the step — no refund carries tax nobody worked out. - Exchanges sell the replacement.
estimate_replacementtaxes it as a sale of its own (credit: falserows on the exchange line); the base class has no default. The swap settles on the difference, tax included on both sides. - Filing.
refundandcommit_replacementrun after the money moves and must credit no more than the rows. Their failures are reported, not raised: the refund has happened. - Lines opened before this recorded no tax against a taxed sale line — read from the line's columns, which settling never rewrites. They are refunded as they were opened and skipped when settling.
- Withdrawing clears without asking. A canceled or denied record's rows are deleted directly: nothing is worked out, so a cancellation never waits on, or fails with, a tax service.
- Opening is atomic.
estimate_refundandestimate_replacementrun inside the transaction that opens the return, claim or exchange, so none ever exists without its tax. A provider that quotes over the network holds that transaction, and the order's row lock, for the call — prefer the recorded share, or keep the quote fast.
TaxLine carries a treatment, not just an amount
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.)
TaxLine gains:
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 onSpree::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, plusintra_community_supplyandexport— Stripe's singlereverse_chargeandzero_ratedvalues 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_code(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.
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.
Core ships no code maps. Deriving the invoice category code and the exemption reason code is
the e-invoicing integration's job, because those code lists belong to a regime rather than to
commerce: VATEX is maintained by the European Commission and revised roughly twice a year, and
the EN 16931 category subset carries EU-only members (K for intra-EU supply, L/M for the
Spanish territories). A merchant invoicing under India's GST, Brazil's NF-e or Saudi ZATCA needs a
different mapping entirely, and a core map named as though it were universal would quietly hand
them European codes.
What core guarantees instead is that taxability_reason distinguishes every case a mapping needs
to tell apart — which is the property that makes an external mapping possible at all. The
correspondence for European invoicing, for reference rather than as shipped code:
taxability_reason |
EN 16931 category code | VATEX 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) | — |
A treatment core does not model needs an extension to register the reason, and that extension owns the mapping for it too.
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
The owner is polymorphic, not a column per owner (RESOLVED 2026-08-22). The original design used the dual-FK convention borrowed from the Cart/Order split. That convention exists for a specific reason — split-adjustments and typed stock movements were removing
adjustable_type/originator_type, where one table meant six different things and a dozen methods dispatched on the type string.TaxIdentifieris not that case: it is one concept (a tax registration) with several owners, which is what polymorphic modelling is for. With a fifth owner arriving (Seller), five nullable FKs plus anexactly_one_ownervalidator were expressing "has an owner" the long way round. So the table carriesowner_type/owner_id, the exactly-one rule becomes structural, the three per-owner uniqueness validations collapse to onescope: [:owner_type, :owner_id], and a sixth owner costs no schema change. Cardinality still differs by owner and is declared owner-side as it always was (has_manyfor customer/company/seller,has_onefor cart/order). The admin serializer keeps exposingcustomer_id/cart_id/order_id— reading the owner and reporting it under the name of what it is — so no client changes.
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:
class Spree::TaxIdentifier < Spree.base_class
has_prefix_id :txi
# Owner — polymorphic (decision 2026-08-22, below):
belongs_to :owner, polymorphic: true, optional: false
# Customer (durable profile value), Company (the entity's registration,
# sitting above the customer's own row in the chain), Seller (the
# marketplace's commission invoice — see 6.0-multi-vendor-marketplace.md
# Decision 12), Cart (checkout-time override), Order (frozen completion
# snapshot). Per-branch registrations stay a 6.1 question (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
- 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.
- A checkout override is a copy of the number, not a link to the customer's row (2026-08-07). The four owners are mutually exclusive, so a cart row cannot reference a customer row:
PUT /store/carts/:id/tax_identifiertakeskindandvalue, and a buyer choosing one of their own registrations fromGET /store/customers/me/tax_identifiersresends the number rather than its id. Two consequences worth knowing: the copy is validated in its own right, so picking an already-verified registration triggers a fresh registry check; and it does not track the original, so correcting the profile afterwards leaves an in-flight cart on the old number. Both follow from the same reasoning as the order snapshot — a claim must not change under a sale in progress — applied one step earlier. - Resolution chain at estimate: cart-owned override → the order's company → customer's row → nil (B2C treatment). The company link arrives with Phase 7. This is a fallback chain, so it lives as
#resolved_tax_identifieronSpree::Purchase::Taxation— the concern that already ownstax_addressfor 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.
Company, pulled forward for exemptions (2026-08-07)
Exemption resolution needs an entity to hang certificates on, and Spree::Company did not exist —
the B2B plan targets 6.1. Rather than leave Phase 7 blocked, this plan builds the minimum tree that
makes exemptions resolvable and hands the rest back. Four decisions settle the shape:
- The Cart and the Order both reference
company_location, notcompany. That is the FK the B2B plan already specifies for orders, so 6.1 adds no second column and moves nothing;#companyderives through the location. The column lands onspree_cartstoo, followingchannel_idandmarket_id— exemption has to resolve during checkout, not only after placement. The alternative, a directcompany_id, is one hop cheaper today and costs a schema reversal later, with per-branch registration having nowhere to go. - All three models ship: Company → CompanyLocation → CompanyContact. The contact is not decoration — it is what lets a logged-in B2B buyer's own cart resolve a company without staff touching the order. Without it, exemption only works on admin-created orders, which is exactly the wrong limitation for a self-serve wholesale channel.
- No
tax_exemptboolean, on either model. This supersedes the B2B plan's Company and CompanyLocation sketches, which both carry one. A flag cannot say which jurisdiction it holds in or which line it covers, and removing the booleanexempt?from the provider contract was the whole point of the 2026-08-05 refinement — reintroducing it one layer down would undo that. Exemption is certificates, resolved into typed entries. - Certificates hang off Company, scoped by jurisdiction. Their own
country/statecolumns already answer "where does this hold", so per-location rows would restate the branch address and force a company-wide certificate to be duplicated per branch. Shopify hangs exemptions on the location; it also has no jurisdiction columns to scope with.
Explicitly still 6.1, and not to be built here: Catalog, CatalogProduct, CatalogAssignment and
default_catalog_id; per-company pricing and Products::ForContext visibility; the Company →
CustomerGroup link; roles, approval workflows, purchase limits and invoicing. Contacts carry a plain
role string with no behavior attached, as the B2B plan specifies.
Completion copies, never references: the copy step in
Carts::Completecalls the same#resolved_tax_identifierand duplicates the winning row as a frozen order-owned row withsourcestamped — 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::Completecopy step — nothing else creates order-owned rows), thereadonly?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
companyfield 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
TaxProviderwould 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), sovalidate_tax_idis deliberately not on the provider contract.The registry is keyed by kind, and core ships exactly one entry: a format-only validator for
eu_vat. Core ships no registry client for any jurisdiction.That split follows the cost, not the jurisdiction. Checking a VAT number's shape is arithmetic — the check digits are published in the directive, they are the same for every installation, and the check needs no credentials, no network and no configuration. Leaving it out means a stock install accepts
DE123as a German VAT number and stores it, which is how a typo reaches an invoice. It is the same reasoning that already puts postal codes onvalidates_zipcode, phone numbers onphoneliband carrier numbers ontracking_number, and core takes the same route here:valvatas a dependency, wrapped inSpree::TaxIdentifiers::Validator::EuVat.Checking whether that number is registered is a call to somebody's government — slow, periodically down, and jurisdiction-specific — so it stays out, exactly as before.
Three consequences worth stating, because each one is a place this could go wrong:
- A passing format check is not a verdict. It writes no validation status. Being well-formed is not evidence that a business exists, and
verifiedcontinues to mean a registry said so. A stock install therefore rejects mistyped numbers on save and still leaves every verdict blank. Validator::Base.checks_registry?tells core whether a validator can answer a registry question at all;EuVatreturns false. Without it, every saved VAT number would enqueue a check that nobody implements, and the job would recordunavailable— which would be a lie, since no registry was asked.TaxIdentifier#validatable?reads this, so it keeps meaning "a registry can be asked here".- Uncheckable member states still pass.
valvathas check-digit algorithms for 24 of the 27 member states and falls back to syntax for Czechia, Latvia and Slovakia. Rejecting what cannot be fully verified would turn away real business customers to catch a typo, which inverts the cost.Valvat::Checksum.validatealready applies this fallback, so there is no country list to maintain. - Greece is matched on its ISO code, not its VAT prefix. It is the one member state where the two differ — it issues
EL…numbers while its ISO code isGR— so a country check written against the prefix refuses every Greek business. Northern Ireland is the mirror image:XIis a VAT prefix with no ISO code of its own, so it is matched on the prefix. - An order's frozen snapshot is never format-checked. It is a copy of a number already accepted at the time, so re-checking it would let a rule tightened later — or a country leaving the VAT area, as Great Britain did — fail a checkout over history rather than over anything the buyer typed.
An extension wanting the registry half re-registers
eu_vatand takes over both halves:# Extensions register the kinds they cover; a tax provider gem may register # itself for the kinds its service can check. Spree.tax_identifier_validators['eu_vat'] = 'SpreeEuVat::TaxIdentifierValidator' # Each validator subclasses Spree::TaxIdentifiers::Validator::Base: a class-level # valid_format? for the synchronous check, checks_registry? to say whether the # second half exists, 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, and two extensions covering different kinds coexist (a single swappable service would give the second one to load the slot and silently disable the first). Core answers "can this installation check this kind against a registry?" with
TaxIdentifier#validatable?— the registered validator'schecks_registry?, not the barekey?(kind), since core now registers a validator that deliberately cannot. That is what the admin needs to distinguish queued, no registry 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_identifier_validators[kind] → ValidationResult → Spree::TaxIdentifiers::Validate writes status / validated_at / evidence / normalized value with update_columnsThe 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 theupdate_columnswrite-back cannot retrigger it. A registry that fails to answer is reported viaRails.error.reportand recorded asunavailable, 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
pendingon 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::Validateremains the only writer of the row's validation columns, which is what keeps three installed validator gems from each inventing their own status vocabulary:# 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::TaxIdentifiers::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 } } endThree 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 —estimatewrites 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.
- A passing format check is not a verdict. It writes no validation status. Being well-formed is not evidence that a business exists, and
API surface: singular nested resources on the customer account, the cart and (read-only) the order, on both the store and admin sides — see the API surface section for the endpoint list and the field split. The cart endpoint reads the resolved registration (override, else the customer's) because that is what the provider will be handed, while writes and deletes touch the cart's own row only: a cleared checkout field must not delete a customer's profile registration.
Provider consumption: the provider reads
kindandvalue, never the ownership FKs and never the verdict. Avalara maps tobusinessIdentificationNo(the B2B-VAT-rules switch), Stripe totax_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.
Tax exemption is a typed estimate input plus a TaxLine output — not a boolean, not a hook
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:
class Spree::TaxExemption
include ActiveModel::Model
include ActiveModel::Attributes
attribute :reason_code, :string # resale, government, … (Avalara entityUseCode territory)
attribute :certificate_number, :string # = future TaxExemptionCertificate#certificate_number
attribute :country_code, :string # nil = all countries — same codes the certificate holds
attribute :state_code, :string # nil = entire country — same codes the certificate holds
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
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. (An earlier sketch had the Avalara gem keeping the legacy user-level exemption_number/entity_use_code as gem-owned storage swapped into this seam; 6.0-avalara-provider-gem.md dropped that on 2026-08-19 — the gem consumes the seam without swapping it, and customer-level exemptions are its open question, preferring a core extension.) Company-backed TaxExemptionCertificate records became the default implementation's source in Phase 7, resolving into the same entries — which is what the empty default was standing in for, and why the seam shipped first.
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.
A placed order keeps the claims it was priced with (2026-09-04). "Never persisted" is narrowed, not reversed: resolution stays live for a cart, there is still no spree_tax_exemptions table and still no FK from a tax row to a certificate — but spree_orders.applied_tax_exemptions holds the resolved entries as plain data, frozen at completion beside the tax identifier and read back by usable_exemptions for a completed order. Re-resolving later is not the same evidence: a certificate lapses on its own expires_at with nothing written to it (scope :active is verified AND not past its date), can be revoked, and is destroyed with its company. An external provider commits and credits after placement, so a credit for an exempt sale was being filed with no entityUseCode at all — declaring tax the sale never collected. Which claims a sale was granted is a fact about that sale, like its registration. Orders placed before the column existed hold nothing and still resolve live.
Two corrections the review caught, both in the first cut of this (2026-09-04): an empty snapshot is
a snapshot. A consumer sale freezes [], which records that the sale resolved and found nothing —
only nil is the legacy no-snapshot state, and the reader tests for that rather than present?.
Skipping the write for an empty result sent those orders back to live resolution, so a certificate
added to the company afterwards would start explaining a sale it was never part of: the same fault as
a lapsed certificate vanishing from one, in the other direction. And a per-item override is
re-owned on the way in. ItemOverride#item_id names its line by prefixed id, and completion gives
every line a new one, so the cart's ids match nothing on the order — and an override that matches
nothing does not narrow its claim, it widens it, which would exempt every line and file away tax the
sale collected. Carts::Complete translates line-item, fulfillment and fee ids through the maps it
already builds; one naming something the sale never had narrowed nothing while the cart was priced
either, so it is kept as-is and reported.
Two more paths the review found (2026-09-04): a draft order never went through the cart copier at
all — Carts::Complete hands it to Orders::Complete, which now pins its own claims, and that is the
path company certificates actually take. And a split hands the cart's snapshot to each sibling
through CARRIED_TO_SIBLING: every child is placed through Orders::Complete and so would pin
something regardless, but a child left to resolve again takes the resolver's cart-side override ids,
which match nothing it owns — widening the claim over every line it holds.
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.
Cross-border pricing: every price is charged as entered (2026-08-11, reversed 2026-10-16)
A tax-inclusive price is expressed in some country's VAT. When the buyer is in another one, the platform must decide whether the shopper's price stays put and the merchant's margin moves, or the merchant's net stays put and the price moves. Both are coherent; the industry ships both.
Spree keeps the shopper's price (2026-10-16, V-3662). Market#tax_inclusive is the only setting
for whether prices include tax: on, every customer of the market pays the price as entered with
their own country's tax inside it; off, tax is added at checkout. Tax rates hold a percentage and a
jurisdiction, nothing else — TaxRate#included_in_price is retired. Spree's own tables read the
setting through Purchase::Taxation#tax_inclusive?, and every provider receives it as
tax_inclusive:. This is Shopify's "Show as included" and "Show as line item".
The 2026-08-11 rule is gone. It derived net-fixed through VatPriceCalculation — the home rate
out of the price, the destination's in — except for a price on a list narrowed by geography
(PriceRule#geographic?, Price#final_for_destination?). V-3662 showed its cost: a US store's
Germany market priced 100.00 charged 119.00 at checkout, because the US's 0% came out and 19% went
in. It also worked only on the Internal provider, since an external engine keeps no rows to read
both rates from; it showed a market of several countries the main country's price until the address
was known; and it turned round prices into odd ones. A merchant who wants a different price in some
countries gives them a market of their own with a price list, and one market applies one convention
to all its countries.
Restatement may return in 6.1 if merchants ask for it: as an Internal-provider option that reads the storefront's country before an address exists, or as a country rule on price lists, which works with every engine.
Provider is per-Market — selection, not construction
Markets represent regional commerce operations; each market selects its tax engine. Spree.default_tax_provider stays as the fallback (market with no explicit provider, store without markets) — one config, returning a class, so a caller that only needs to name the default does not instantiate one.
class Spree::Market < Spree.base_class
# 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.presence || Spree.default_tax_provider.to_s).constantize.new
end
end
Call sites migrate from the global default to the owner's market as per-market selection lands — they call owner.tax_provider, which falls back to Spree.default_tax_provider. 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: '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' (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
Credentials live in Spree::Integration, not the provider
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:
# 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
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
# 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'
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
Admin flow:
- Admin opens Integrations, connects Avalara (enters the API key; the connection is tested before saving).
- Admin opens Market "US" and selects Avalara as its tax provider — only connected providers appear in the list.
- At estimate time the provider resolves credentials from the Integration record.
Internal providers need no Integration — Spree::TaxProvider::Internal reads TaxRate rows and has no external credentials, so it is always available.
Capability honesty
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:
- 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::Internaldeclares 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. - 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,
estimategains 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.
Drop TaxZone — TaxRate links directly to country/state (Phase 5, pending)
Unchanged from the 2026-07-27 decision: merchants think "Germany has 19% VAT", not in zones.
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])
}
State-level rates override country-level (more specific wins). Tax stops using Zone — a data migration converts Zone records used by TaxRate into direct country/state FKs, and no code reads zone_id on TaxRate any more. The request-context readers went too (Spree::Current.zone/default_tax_zone, Market#tax_zone, Purchase::Taxation#tax_zone), replaced by Spree::Current.tax_country; spree_tax_rates.zone_id stays as the conversion source until Phase 9. Dropping the Spree::Zone model itself belongs to 6.0-delivery-zones.md, which owns the full consumer inventory and does it inside 6.0.
spree_tax_rates.zone_id is dropped in 6.1, not 6.0. The column is what spree:migrate_tax_zones converts from, and the manifest runs after db:migrate — so a migration dropping it in the same release would destroy the conversion's own input, and leave no rollback source if a merchant needs to re-run it.
The gap this leaves, and why it stays a gap. Between db:migrate and the conversion task, an unconverted rate has no country_code — and a blank country means everywhere, so a rate configured for one country matches every destination and over-collects until the task runs. The fix is not to move the conversion into the migration: data transformations belong in rake tasks (see CLAUDE.md), the manifest deliberately runs after db:migrate, and migrate_adjustments_to_typed_rows and the delivery migration already carry the same window. Two things keep it small — bin/rake spree:upgrade runs the manifest immediately after migrating, and the task is idempotent, so it can be re-run without thought. An upgrade that serves traffic between the two steps should expect over-collection in that window; failing the other way (treating unconverted rates as taxing nothing) trades a customer-facing error for an under-collection the merchant is liable for, which is the worse of the two. 6.0 therefore severs every reader (the belongs_to :zone, the zone scopes, and Zone#has_many :tax_rates, whose dependent: :destroy would otherwise delete live rates when a shipping zone is destroyed) and leaves the column in place, unread. This matches how spree_adjustments is handled by migrate_adjustments_to_typed_rows. Phase 9 drops the column alongside the other converted-away schema.
Design Details
Provider Base Class
module Spree
module TaxProvider
class Base
# 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,
# :proportional_delivery_tax.
#
# @return [Array<Symbol>]
def self.unsupported_capabilities
[]
end
# Whether this provider can be selected for a store — external providers
# require a connected Integration.
#
# @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 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
# 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); end
# Reverses a committed tax document on cancellation.
#
# @param order [Spree::Order]
# @return [void]
def void(order); end
# 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, 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_identifier_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)
# 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":
# 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
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.
# in Spree::Core::Dependencies
tax_resolve_exemptions_service: 'Spree::Tax::ResolveExemptions',
# 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:
# config/initializers/spree.rb in an app, or the extension's engine
Spree.tax_identifier_validators['eu_vat'] = 'SpreeEuVat::TaxIdentifierValidator'
Spree.tax_identifier_validators['gb_vat'] = 'SpreeUkVat::TaxIdentifierValidator'
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.
# app/models/spree/tax_identifiers/validator/base.rb
module Spree
module TaxIdentifiers
module Validator
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?.
#
# 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 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::TaxIdentifiers::ValidationResult]
def call(tax_identifier:)
raise NotImplementedError, "Please implement 'call' in your tax ID validator: #{self.class.name}"
end
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:
# the extension's app/models/spree_eu_vat/tax_identifier_validator.rb
module SpreeEuVat
class TaxIdentifierValidator < Spree::TaxIdentifiers::Validator::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::TaxIdentifiers::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::TaxIdentifiers::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:
# 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_identifier_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:
# 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
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_identifier_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_identifier_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.
# 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
# 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_identifier_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 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_ratedfor a positive rate,zero_ratedfor a matched zero rate — finer distinctions such asreduced_ratedare 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 produceamount: 0rows withcustomer_exemptfor the jurisdictions they scope to. - Ignore
tax_identifier:entirely; reverse charge is on the unsupported list, so a buyer registration changes nothing here. - Tax delivery at the one rate its delivery method names, never apportioned across the rates of the goods being delivered. Under EU VAT the delivery charge belongs to the same supply as the goods, so a basket mixing rates needs a weighted blend on delivery, and US states apportion by their own varying rules. Declared as
:proportional_delivery_taxrather than approximated: a blend invented in core would be wrong in a different way in each jurisdiction, and an external provider is where that judgement belongs. - 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.
module Spree
module TaxProvider
class Internal < Base
def self.unsupported_capabilities
%i[us_local_tax reverse_charge oss_thresholds proportional_delivery_tax]
end
private
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,
rate: rate.amount, # snapshot: survives a rate edit or deletion
label: rate.adjustment_label(included: tax_inclusive),
included: tax_inclusive, # the market's setting (2026-10-16), not the rate's
provider_id: 'internal',
taxability_reason: reason, # 'standard_rated' / 'zero_rated' / 'customer_exempt'
country_code: rate.country_code,
state_code: rate.state_code
)
end
end
end
end
External provider example (Avalara — reference gem)
module SpreeTaxAvalara
class TaxProvider < Spree::TaxProvider::Base
def self.integration_class = 'Spree::Integrations::Avalara'
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)
# 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|
item = find_item(items, avalara_line.line_number)
next unless item
item.tax_lines.create!(
owner_key(owner) => owner,
amount: avalara_line.tax,
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_code: avalara_line.country,
state_code: avalara_line.region,
data: { 'jurisdictions' => avalara_line.details }
)
end
owner.update_column(:metadata, owner.metadata.merge('avalara_transaction_id' => response.id))
end
def commit(order)
transaction_id = order.metadata&.dig('avalara_transaction_id')
client_for(order).commit_transaction(transaction_id) if transaction_id
end
def void(order)
transaction_id = order.metadata&.dig('avalara_transaction_id')
client_for(order).void_transaction(transaction_id) if transaction_id
end
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
# Validation is not part of the provider contract — the gem registers a
# validator for the kinds Avalara can check:
# Spree.tax_identifier_validators['eu_vat'] = 'SpreeTaxAvalara::TaxIdentifierValidator'
private
# 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
External providers reference no local TaxRate and never synthesize one (tax_rate_id stays nil); rows are self-describing via the snapshots.
API surface
Conventions per 6.0-admin-api.md: flat params, prefixed IDs, secret-key scopes or JWT + CanCanCan, admin serializers extending their store counterpart.
Tax identifiers. A singular nested resource, since a record owns at most one:
| 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 |
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.
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_identifier_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.
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:
- 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_reasonand the jurisdiction snapshot are admin-only. No surveyed platform exposes a machine-readable reason to buyers, and the customer-facing need is met bylabel, 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 gainstaxability_reason,country_code,state_codeanddata— currently unserialized anywhere, though it is exactly the jurisdiction breakdown an e-invoicing integration needs. No derived invoice code is exposed: that mapping belongs to the integration, not to core.- Ransack allowlist on
Spree::TaxLinefortaxability_reason,country_codeandstate_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.
Tax rates. /admin/tax_rates — full CRUD, admin-only (rates are back-office configuration; the storefront never sees them). This plan owns building them even though 6.0-admin-api.md carries the checkboxes, for a blunt reason: TaxRate rows are the Internal provider's entire configuration, so without these endpoints the default tax engine cannot be set up or inspected through the API at all, and nothing about its behavior can be verified outside a console or a spec. Tax categories already have their endpoints; rates are the missing half.
Serializer fields: name, amount (plus amount_percentage, the virtual the admin forms use), show_rate_in_label (included_in_price removed 2026-10-16), 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_code/state_code after it, which is the one place these endpoints get reworked. whitelisted_ransackable_attributes already covers amount, tax_category_id, included_in_price and name, so filtering comes free; Phase 5 swaps zone_id for the country and state codes there too.
Provider discovery and selection.
| Endpoint | Purpose |
|---|---|
GET /admin/tax_providers |
registry keys, names, available_for_store?, and unsupported_capabilities — each limit as {key, label, description}, where the description states what the merchant loses rather than naming the feature, since the point of declaring it is the risk of under-collecting. Strings live in core's spree.tax_capabilities.*; a capability with none degrades to its humanized key, so an extension declaring its own reads sensibly before it ships translations |
PATCH /admin/markets/:id |
tax_provider becomes writable |
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.
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.
Companies and exemption certificates (Phase 7): admin CRUD for the Company tree plus nested /admin/companies/:company_id/tax_exemption_certificates with direct-upload for the document and a verify member action. No Store API — see that phase.
Lifecycle integration points
Carts::Complete: copy the resolvedTaxIdentifierto the order (frozen,sourcestamped); callprovider.commit(order)as anexternal_step(gateway-style I/O never inside the completion transaction).Orders::Cancel:provider.void(order)as anexternal_step.- Returns, claims and exchanges (
6.0-returns-exchanges-claims.md):provider.estimate_refundwhen the record opens and before its money moves,estimate_replacementbeside it for an exchange;provider.refund(order, items, amount:, tax_date:)andcommit_replacementfromexternal_steps after the money moved.
Migration Path
Phases 1–2: seam + Internal provider + TaxLine — SHIPPED (as built)
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.
Phase 3: contract enrichment (this revision)
- TaxLine:
taxability_reason+ vocabulary registry + the invoice-category / exemption-reason lookup maps +country_code/state_codecolumns; zero-amount write contract in the Internal provider. Spree::TaxIdentifiermodel + customer/cart/order FKs +readonly?freeze + completion copy step.- API:
/admin/tax_ratesCRUD (without it the Internal provider cannot be configured or verified through the API — see the API surface section), tax identifier endpoints (with adminvalidatable+ the re-validate action), tax lines exposed on the Store API, admin tax-line serializer gainingtaxability_reason/jurisdiction/data, and the Ransack allowlist for tax reporting. estimatesignature:tax_date:/tax_identifier:/exemptions:/context:;refund(order, return_items, tax_date:)replacesrefund(owner, amount);exempt?removed.Spree::TaxExemption+ItemOverridevalue objects;tax_resolve_exemptions_servicedependency (default empty);#resolved_tax_identifieronSpree::Purchase::Taxation.Spree::TaxIdentifiers::Validator::Base(incl.checks_registry?) +Spree.tax_identifier_validatorsregistry (class names; core registers the format-onlySpree::TaxIdentifiers::Validator::EuVatforeu_vat, backed byvalvat) +Spree::TaxIdentifiers::Validate(sole writer of the validation columns) +ValidateJob+Spree.queues.tax_identifiers+ theafter_commitenqueue guarded on kind/value changes.- Synchronous format validation on
TaxIdentifier: whitespace/case normalization, presence, and the registered validator's class-levelvalid_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_idonspree_tax_ratesandspree_tax_categoriesviaSpree::SingleStoreResource, a backfill rake task, and store-scoped fetching in the endpoints above;null: falsewaits for 6.1 once the backfill has run everywhere.TaxIdentifier,TaxLineand the other typed rows deliberately get nostore_id— they are owned rows whose owner already carries the store, matchingspree_tax_linesas shipped; a denormalized copy would only be a second thing to keep in sync. set_tax_line_contextdoc 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_providersdiscovery plusupdateon the admin markets endpoint (currentlyindex/showonly); Market admin UI gated byavailable_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.commitinCarts::Complete,voidinOrders::Cancel,refundin the returns flow — allexternal_steps.
Phase 5: decouple tax from Zone (Zone model stays)
Tax-side only — shipping keeps Zone untouched; full Zone removal is deferred to its own plan:
# rake spree:migrate_tax_zones
# For each Zone used by TaxRate:
# Extract country/state from ZoneMembers → set TaxRate.country_code / TaxRate.state_code
# (Zone with multiple countries = one TaxRate per country)
- Add
country_code/state_codetospree_tax_rates; run the data task; sever everyzone_idreader. The column itself is dropped in Phase 9, not here — the conversion cannot drop its own input. - Update the
/admin/tax_ratesserializer, permitted params and Ransack allowlist fromzone_idtocountry_code/state_code— the only rework those endpoints take, and the reason they are worth building in Phase 3 rather than waiting. - Retire the tax-side zone readers rather than rewriting them:
Order#tax_zone,Spree::Current.zone/default_tax_zone,Market#tax_zoneandZone.default_taxall answered "where is this buyer taxed", which#tax_countrynow answers directly.Spree::Current.tax_countryreplaces the request attribute, per the ownership table in6.0-delivery-zones.md. Spree::Pricing::Contextkeys on country, not zone — nominally that plan's row, but it cannot be deferred:Context.from_orderreadsorder.tax_zone, so it breaks the moment this phase removes it.PriceRules::ZoneRulecomes with it, deciding by country and keeping its class name because thetypecolumn persists it; the same data task restates its stored zones as countries. Whether that rule deserves promoting to a first-class country rule is the delivery-zones plan's call, not this one's — it stays out of the rule registry either way.- Re-point whatever populates
DeliveryRate#tax_rate. The Estimator matches that rate through the Zone path this phase removes, so it must move tofor_addressto 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_membersare not dropped in 6.0, and neither isspree_tax_rates.zone_id(Phase 9).
Phase 6: Avalara reference gem (spree_tax_avalara)
- 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-levelexemption_number/entity_use_codeinto gem-owned storage feedingtax_resolve_exemptions_service— the seam's first real implementation. - Documents how to build custom providers.
Follow-ups from V-3725 (2026-10-01) — the post-sale contract landed in core after #14467 was written; that branch owes these when it rebases:
- Rebase onto
Spree::Tax::ProviderError(now in core, unchanged) and the new methods.refundkeeps its signature, but its credit must come from the items' credit rows. - Date the credit on the refund day.
RefundPresenteraliasesdocument_datetosupply_date, filing every credit into the original sale's period. Only theTaxDateoverride stays the original sale date. - Build the credit from the rows. Drop
refunded_worth,scaleandcredited_basis: they measure againstline_item.amount, the list price, which went stale when returns moved todiscounted_amount_for(#14776). Send each credit line's tax as a tax-amount override so what Avalara records equals what the customer was refunded; confirm in the sandbox that it combines with theTaxDateoverride. - Implement
estimate_refund— the base class has no default. ReuseSpree::TaxProvider::RecordedShare(what the customer paid, and whatcommitfiled) or quote at the original tax date. - Implement
estimate_replacement(a quote) andcommit_replacement(a document keyed to the exchange number). - Key credit documents to the return, claim or exchange number — not
return_items.first.return— and don't assumereceived_quantityon claim lines.
Phase 7: Company tree + tax exemption certificates
Next up. Ships the minimum Company surface exemptions need (see Key Decisions, 2026-08-07),
then the certificates and the ResolveExemptions body its empty default was standing in for. The
provider contract does not change — that is the payoff for having built the seam first.
Step 1 — the Company tree
class CreateSpreeCompanies < ActiveRecord::Migration[8.1]
def change
create_table :spree_companies do |t|
t.references :store, null: false
t.string :name, null: false
t.string :external_id # ERP/CRM reference — superseded 2026-08-18: `Spree::ExternalReference` (`6.0-third-party-pricing-inventory.md`), column dropped before release
# No tax_exempt boolean — exemption is certificates (Key Decisions).
if t.respond_to?(:jsonb) then t.jsonb :metadata else t.json :metadata end
t.timestamps
end
add_index :spree_companies, [:store_id, :external_id], unique: true,
where: 'external_id IS NOT NULL', name: 'idx_companies_external_id'
create_table :spree_company_locations do |t|
t.references :company, null: false
t.references :billing_address
t.references :shipping_address
t.string :name, null: false
t.string :external_id
if t.respond_to?(:jsonb) then t.jsonb :metadata else t.json :metadata end
t.timestamps
end
create_table :spree_company_contacts do |t|
t.references :company_location, null: false
t.references :user, null: false
t.string :role, null: false, default: 'buyer' # no behavior attached in 6.0
t.timestamps
end
add_index :spree_company_contacts, [:company_location_id, :user_id], unique: true
# Both, following channel_id and market_id: exemption resolves during
# checkout, and completion copies the column onto the order.
add_reference :spree_carts, :company_location
add_reference :spree_orders, :company_location
end
end
Models follow the conventions already in force — Spree::SingleStoreResource on Company (locations
and contacts reach the store through it), Spree::Metafields + Spree::Metadata, has_prefix_id
(comp, cloc, cc), class_name and dependent on every association, Spree.user_class for the
contact's user. Nothing carries a state machine.
A Spree::Purchase::Company concern gives Cart and Order the shared surface, mirroring
Spree::Purchase::Channel:
def company
company_location&.company
end
def b2b?
company_location_id.present?
end
Resolution for a storefront buyer — provisional (2026-08-07). A cart with no company_location
set falls back to the customer's contacts: acting for exactly one branch resolves to it, acting for
several resolves to nothing, so no company applies and no exemption is claimed. Staff set the branch
directly on admin-created orders. Refusing to guess is the point — picking one would invoice one
business for another's purchase.
Choosing between branches is deliberately not answered here. It is the same question
6.0-channels-catalogs-b2b.md leaves open for product visibility — its user_company_location(user, store) helper is called but never defined — and that plan defers buyer authority to a dedicated B2B
plan after 6.1. Whatever it settles on replaces Spree::Purchase::Company#resolved_company_location.
This is the only piece of B2B behavior in the phase; everything else is data.
Step 2 — Company joins the tax identifier chain
spree_tax_identifiers gains company_id as a fourth owner (still exactly one), with the same
(company_id, kind) uniqueness the customer owner has, and #resolved_tax_identifier becomes
cart override → company → customer → nil. A company's registration outranks the buyer's own,
because the invoice is addressed to the entity.
Step 3 — certificates
class CreateSpreeTaxExemptionCertificates < ActiveRecord::Migration[8.1]
def change
create_table :spree_tax_exemption_certificates do |t|
t.references :company, null: false
t.string :country_code # nil = every country
t.string :state_code # nil = the entire country
t.string :certificate_number, null: false
t.references :tax_exemption_reason, null: false # the store's reason (2026-10-17);
# its code 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) then t.jsonb :metadata else t.json :metadata end
t.timestamps
end
add_index :spree_tax_exemption_certificates, [:company_id, :status]
end
end
class Spree::TaxExemptionCertificate < Spree.base_class
include Spree::HasStatus
include Spree::Metadata
has_prefix_id :cert
# 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
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
has_one_attached :document # the uploaded certificate PDF or image
belongs_to :tax_exemption_reason
validates :certificate_number, 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
Step 4 — the resolution body
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.tax_exemption_reason.code,
reason_name: certificate.tax_exemption_reason.name,
certificate_number: certificate.certificate_number,
country_code: certificate.country&.iso,
state_code: certificate.state&.abbr
)
end
)
end
for_address needs an address, so a cart with no address yet resolves nothing — consistent with
tax_country falling back to the market for display while real exemption waits for a destination.
Step 5 — Admin API
GET/POST /api/v3/admin/companies
GET/PATCH/DELETE /api/v3/admin/companies/:id
GET/POST /api/v3/admin/companies/:company_id/locations
GET/PATCH/DELETE /api/v3/admin/company_locations/:id
GET/POST /api/v3/admin/company_locations/:location_id/contacts
GET/DELETE /api/v3/admin/company_contacts/:id
GET/POST /api/v3/admin/companies/:company_id/tax_identifiers
GET/PATCH/DELETE /api/v3/admin/companies/:company_id/tax_identifiers/:id
POST /api/v3/admin/companies/:company_id/tax_identifiers/:id/validate
GET/POST /api/v3/admin/companies/:company_id/tax_exemption_certificates
GET/PATCH/DELETE /api/v3/admin/companies/:company_id/tax_exemption_certificates/:id
PATCH /api/v3/admin/companies/:company_id/tax_exemption_certificates/:id/verify
PATCH /api/v3/admin/companies/:company_id/tax_exemption_certificates/:id/revoke
GET /api/v3/admin/companies/:company_id/tax_exemption_certificates/:id/download
Why children split across two prefixes. A child is listed and created under the parent you arrived
from, then read and written by its own id. That is not inconsistency: contacts cannot nest under
companies/:id/locations/:id without breaching the two-level cap in 6.0-admin-api.md, so
company_locations/:id has to exist as a path regardless — and once it does, the branch's own member
actions belong there. It follows the returns precedent, where a resource lives at both prefixes with a
different job at each. Every record has exactly one show.
Certificate creation takes a direct-upload signed blob for document, as the CSV importer does.
Transitions are member PATCH actions, per the returns plan's convention — no destroy on a verified
certificate, revoke instead. Scope-gated on write_customers (a company is a customer record), and
every lookup goes through current_store.companies so a certificate cannot be read across tenants.
No Store API in this phase. Exemption resolves server-side from the buyer's contacts, so the storefront needs no company endpoint to get correct tax. Exposing a buyer's own company for a B2B account area is a 6.1 question, with the gated-channel work.
No dashboard work in this phase either. The Company tree and certificates ship as API only; managing them in the admin UI belongs to the B2B release.
Phase 8: cross-border pricing with tax-inclusive prices
Reversed 2026-10-16 (V-3662): restatement is removed — every customer pays the price as entered (see the cross-border Key Decision). Work items 1 and 3 below still stand: a cart prices from its own market, and a destination change persists the re-price, which price lists narrowed by market still need. Items 2 and 4, and the restatement cases in 5, went with it.
Ships in 6.0. Three defects found by a live pass against a running server (2026-08-11), all in the same seam: what a customer is charged when the destination's VAT rate differs from the home zone's. None of them is visible in a single-country store, which is why the engine suites never caught them — home zone equal to destination makes restatement a no-op.
The rule this phase establishes, in two tiers (Shopify's model — see Key Decisions):
- A price the merchant set for the buyer's geography is final. Charged exactly as entered, never adjusted. Shopify: "add your prices at exactly the amount you want them to be charged. Adjustments aren't made to fixed prices per region."
- Otherwise derive, net-fixed. Remove the home rate, apply the destination's — what
VatPriceCalculationalready does. The merchant's net is preserved and the gross moves.
The three defects
Cart pricing reads the request, not the cart.
Pricing::Context.from_ordercopiescountry: order.tax_countrybut never the market, so@marketfalls back toSpree::Current.market— which is set only from thex-spree-countryheader or acountryparam, and otherwise defaults to the store's default market. Measured: a catalogue request withx-spree-country: FRcorrectly serves a French price list at 99.00, while a cart on the French market prices the same variant at 100.00 as soon as one request omits the hint — and the wrong figure persists. So the product page and the cart can only agree by coincidence, and a market-scoped price list is unreachable from a cart.The re-price on a destination change is computed and thrown away.
Carts::Update#try_advancecorrectly callscart.recalculate_for_address_change!wheneverdestination_changed?(ship_address_id,market_id,preferred_stock_location_id), and that method's own comment says it "re-prices, re-taxes and rebuilds delivery proposals". It callsline_items.reload.each(&:update_price)— andupdate_priceonly assigns, whererecalculate_pricepersists viaupdate_columns. Measured through the Store API: shipping a US-home cart to Berlin leaves the line at 100.00 while the tax flips to German inclusive 15.97; a later quantity change (which routes throughrecalculate_price) writes the 119.00 the address change should have saved. The fulfillment appearing in the same response proves the method ran — only the price write was lost.Restatement is applied to prices that were already set for the destination.
price_including_vat_forcallsgross_amounton whatever price row won, andnet_amountdivides by the home country's rate — there is nothing on aSpree::Pricerecording which country's VAT its figure includes. An explicit French price of 99.00 would therefore be treated as German-gross and restated to 99.83, destroying the price point the merchant chose.
Delivery is already correct here: rates are re-quoted from scratch on an address change, so a 20.00 flat rate becomes 22.43 for a 20% destination. This phase brings line items up to the behaviour delivery already has.
Work
Pricing::Context.from_orderpassesmarket: order.market. Cart-stage pricing then depends on the cart, not on whether a client remembered a header. Audit the other constructors (from_currencyhas no owner to read a market from — it keeps theSpree::Currentfallback, which is correct for a catalogue request).Spree::PriceRule.geographic?—falseon the base class, and onMarketRule/ZoneRuletrue only when the rule actually names a geography (an empty market or country list matches every buyer, so it names none).Spree::Price#final_for_destination?then needs the list'smatch_policyas well as the presence of such a rule: underallevery rule matched, so the geography is why the price applied; underanythe list may have won on a non-geographic rule alone, so it is final only when every rule is geographic. Bothprice_including_vat_forandcompare_at_price_including_vat_forreturn the stored figure unchanged when it answers true. A volume or customer-group list price is still restated — it was priced for a quantity or a group, not for a country, so its margin needs the same protection as a base price.recalculate_for_address_change!callsrecalculate_price. One word, and the persisting method is already the one a quantity change uses.Restatement runs only where the rate table is the truth — i.e. the Internal provider.
VatPriceCalculationreads nothing butTaxRaterows, and an absent row is overloaded: it means no tax is due here (a zero-rated export — deduct the home VAT, charge net) or tax is computed elsewhere (an external engine — deduct nothing). It always assumes the first. Measured with the German home zone and a Japanese destination: 100.00 becomes 84.03, the home VAT removed and nothing put back. That is exactly right for a real export, and exactly wrong for a market whose engine simply has no rows in this table — there, every foreign destination looks like a zero-rated export, so prices drop by the home VAT and tax reappears only at checkout, which is the wrong display convention for an EU buyer even when the total happens to land right.For Internal the table is complete by definition, so absence really does mean zero-rated and the current behaviour stands. Where the market's provider is not Internal, skip restatement — the rows it would read are not that market's tax. What a given provider gem chooses to say about the limitation is its own business. Shopify draws the same line: dynamic tax-inclusive pricing "uses only the standard tax rates for both the origin country and destination country" and is explicitly "not supported for stores on the Shopify Plus plan that use Avalara AvaTax."
Such a market states its destination prices through a geo-scoped price list — the tier-1 rule. A read-only
rate_foron the provider contract, letting an engine supply display rates, would dissolve the limitation; it stays with Open Question 1, which is the same question for delivery options.Specs for the cross-border matrix, which nothing covers today: home == destination (no movement), home != destination (net-fixed movement, persisted), a geo-scoped list price (no movement), a non-geo list price (movement), a cart whose market differs from the request hint (the cart wins), a zero-rated export under Internal (net charged), and an external-provider market (no movement, capability declared).
What makes the re-pricing safe to disclose
A price moving under a customer mid-checkout is the real objection, not the cents.
Carts::Complete#verify_expected_total already fails with cart_changed and the current total when
the client's expected_total no longer matches, so a storefront gets an explicit "your total
changed" rather than a silent charge. That guard is what makes "re-price when the destination
changes" defensible; it must not be weakened.
Phase 9: 6.1 cleanup — the schema 6.0 deliberately kept
Ships in 6.1, never inside 6.0. Every item here needs a release boundary for one of two
reasons: a 6.0 install may not have run its data task yet, or a third party may still be passing
a shape 6.0 still accepts. The precondition that makes the schema changes safe is that
spree:migrate_tax_zones and spree:backfill_tax_store_ids are both steps in the 5.6→6.0
manifest, so every install arriving at 6.1 has run them.
- Drop
spree_tax_rates.zone_id. Nothing reads it after Phase 5 — the association, the zone scopes andZone#has_many :tax_ratesare gone. It survives 6.0 only as the conversion source forspree:migrate_tax_zones, which runs afterdb:migrate: a 6.0 migration dropping it would destroy its own input and leave a merchant no source to re-run from (decisions.md 2026-08-06). null: falseonspree_tax_rates.store_idandspree_tax_categories.store_id— the store-binding convention's second half, matching DeliveryMethod and StockLocation. Presence is model-enforced from 6.0; the constraint waits for the backfill to have run everywhere.- Drop the vestigial
tax_ratesslot from theSpreeCalculatorsstruct. Tax has had no calculator sinceCalculator::DefaultTaxwas removed; the slot is a public-ish constant, so it gets a boundary rather than a silent edit. - Drop
spree_tax_rates.included_in_price. Decided 2026-10-16:Market#tax_inclusiveis the one setting, read by Internal and passed to every provider, and the rate's flag left the API and the dashboard. The column stays through 6.0 only becausespree:markets:backfill_tax_inclusivereads it afterdb:migrate; drop it once every install has run that step.
Constraints on Current Work
- Cart-stage pricing reads the cart, never
Spree::Current.Pricing::Context.from_ordermust carry the owner's ownmarketalongside itscountry. Anything that prices a cart line from the request context makes the same cart price differently between two requests — measured, and it persists. Catalogue requests keep theSpree::Currentfallback; they have no owner to read. - Whether a price includes tax is the market's. Read it through the owner's
tax_inclusive?or the provider'stax_inclusive:input, never from a tax rate, and never adjust a price for the buyer's country: every customer of a market pays the price as entered. - Re-pricing on a destination change must stay behind the drift guard.
Carts::Complete#verify_expected_totalreturningcart_changedis what makes a mid-checkout price movement disclosable rather than silent. Don't weaken it, and don't add re-pricing paths that skip it. - No
tax_exemptboolean anywhere. Not on Company, not on CompanyLocation, not on Customer. Exemption is aSpree::TaxExemptionentry resolved from a certificate; a flag cannot name its jurisdiction or its lines. This supersedes the Company and CompanyLocation sketches in6.0-channels-catalogs-b2b.md. - Don't build Catalog while building Company. Phase 7 ships Company, CompanyLocation, CompanyContact and
certificates only. Catalog,
default_catalog_id, per-company pricing,Products::ForContextand the CustomerGroup link stay with the B2B release, which inherits these models rather than redefining them. - A B2B order references
company_location, nevercompanydirectly.#companyderives through the location on both Cart and Order. Don't add acompany_idcolumn to either table. - The provider is the only TaxLine writer. Don't add tax computation anywhere else; don't reintroduce calculators or adjuster-side tax. That includes returns, claims and exchanges: they ask
estimate_refund/estimate_replacementand read the rows. - Post-sale rows never count towards an order's totals. Read an order's tax through
Order#tax_lines(sale rows only); a query that sumsspree_tax_linesbyorder_idmust excludepost_salerows. - Don't put typed tax inputs in
set_tax_line_context. Exemptions, tax identifiers and dates are namedestimateparameters, assembled bytax_resolve_exemptions_serviceand#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 — swaptax_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_identifier_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
pendingidentifier 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
Delivery-rate tax display bypasses the provider.
DeliveryRate#tax_amountcomputes tax itself —belongs_to :tax_rateplus 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
estimateis 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-onlyquoteto 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.Still open, and now sequenced after Phase 7 (2026-08-07 — it is one of the two remaining items on PR #14410). Phases 3–5 neither need nor are blocked by an answer, and the only knock-on is that 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-pointed the rate matching mechanically. Dropping tax from the option labels entirely stays on the table as an outcome, not just a fallback; whichever way it lands, it should be settled with
6.0-delivery-rate-provider.md, which ownsDeliveryRateenrichment.
Resolved (previously open):
- Cross-border restatement scope (2026-08-11, reversed 2026-10-16) — derive net-fixed by default; never restate a
price whose winning price list carries a
geographic?rule. Reversed by V-3662: restatement is removed and every price is charged as entered. Settled with the two-tier decision in Key Decisions after surveying seven platforms; the alternative rules considered (anyprice_list_id, an explicitprices_are_finalcolumn) were rejected for letting a non-geographic list erode margin, and for adding a merchant-facing concept where a rule already states the intent. - Context key discoverability — no declaration mechanism.
estimate'scontext:is the hash produced by theset_tax_line_contexthook: extensions register handlers, each returns a hash, andrun_hooksdeep-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'sSpree::Integrationas a preference, where it already gets persistence and an admin form. Handlers should namespace their contribution under the provider key ({ 'avalara' => { … } }), because unlikeTaxLine.data, which one provider writes onto a row already stamped withprovider_id, this hash is merged across every registered handler and same-key contributions overwrite each other in registration order. Declaring keys the wayunsupported_capabilitiesis declared was considered and rejected: validating them would make the channel typed, and a typed input deserves a namedestimateparameter 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 —
estimatereturns 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.
Regulatory background
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.
| 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
- 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.0-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 triggersprovider.refund) - Related plan:
6.0-delivery-rate-provider.md(Zone survival scope; delivery-side rate display)