> ## Documentation Index
> Fetch the complete documentation index at: https://spreecommerce.org/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Spree 6 (v6.x) is the current version. Pages with /v5/ in their URL document Spree 5: follow them in a project that runs Spree 5, or to see what an upgrade changes.
> Spree 6 differs greatly from Spree 4 and 5: it is fully headless, and older code and tutorials mostly do not apply. Before relying on what you remember about Spree, read https://spreecommerce.org/docs/developer/upgrades/spree-6-vs-older-versions.md
> The current REST APIs are the Store API (store.yaml), the Admin API (admin.yaml) and the Seller API (seller.yaml), all under /api/v3.
> The specs named legacy-v2-*, the Storefront API and Platform API pages and their tutorials document the older API v2, which Spree 5 and earlier serve. Read them to maintain or migrate an API v2 client, and build new work on the current APIs.

# Build a Custom Tax Provider

> Connect a tax service to Spree so a market's tax is calculated, filed and credited by that service instead of Spree's own tax rates.

## Overview

A tax provider decides **how a market's tax is worked out**. Spree ships with `Spree::TaxProvider::Internal`, which prices from the tax rates you set up in the admin, and with [Avalara AvaTax](https://spreecommerce.org/docs/integrations/tax/avalara.md) as the `spree_avalara` gem. Each [market](https://spreecommerce.org/docs/developer/core-concepts/markets.md) chooses its provider, so one store can use its own rates in a simple market and a tax service in a complicated one.

Write a provider when a service outside Spree should calculate the tax: a tax engine, an ERP, an in-house rules service. `spree_avalara` (`spree/providers/avalara` in the Spree repository) is a complete provider built on this contract, and the best place to see each piece working.

See [Taxes](https://spreecommerce.org/docs/developer/core-concepts/taxes.md) for how tax lines, tax categories and markets fit together.

## What you will build

| Piece | Responsibility |
| - | - |
| `Spree::Integration` subclass | Holds the store's credentials, managed from the admin dashboard, and records calls to your service |
| `Spree::TaxProvider::Base` subclass | Turns a cart or order into tax lines, and files, voids and credits documents |
| An initializer | Registers both so a market can choose them |

The provider is a stateless strategy object. It never stores credentials: those belong to the integration, which is what gives merchants one place to see everything connected to their store.

## 1. Store credentials in an integration

```ruby theme={"theme":"night-owl"}
module SpreeAcmeTax
  class Integration < Spree::Integration
    preference :api_key, :password
    preference :company, :string
    preference :logging_enabled, :boolean, default: false

    def self.integration_group = 'tax'
    def self.call_log? = true

    def self.active_for(store)
      store&.integrations&.active&.find_by(type: name)
    end

    def can_connect?
      client.ping
      true
    rescue AcmeTax::Error => e
      self.connection_error_message = e.message
      false
    end

    def client
      @client ||= AcmeTax::Client.new(
        api_key: preferred_api_key,
        log: (->(**entry) { log_call(**entry) } if preferred_logging_enabled)
      )
    end
  end
end
```

Declare secrets as `:password` preferences: Spree masks them on read and keeps the stored value when the masked one comes back.

`can_connect?` runs when an admin activates the integration or clicks **Test connection**. Return false with a `connection_error_message` and activation is refused with your message.

### Record calls to your service

`call_log? = true` tells the admin that this integration keeps a call log: the integration's sheet in the dashboard shows its latest calls, and its call log page lists them all. A call's request and response are shown only to staff who also hold `read_orders`, because they carry what your service was sent; override `self.call_log_body_permission` when another permission covers that data. Write each call with `log_call`:

```ruby theme={"theme":"night-owl"}
integration.log_call(
  operation: 'quote',
  status: 200,            # nil when nothing answered
  duration_ms: 142,
  request: request_body,
  response: response_body,
  error: nil              # what failed: the network error when nothing answered, or a refusal in a 2xx answer
)
```

The row is written once the caller's database transaction has ended, committed or rolled back, so a call that fails inside a checkout transaction is still recorded. A failure to write is reported and swallowed: the log never breaks the call it records. Never record credentials, and record only while the merchant has switched logging on, because tax requests carry customer addresses. Rows are deleted after `Spree::Config.integration_log_retention_days` (30 by default) by `Spree::Integrations::PurgeLogsJob`, which the host app schedules daily.

## 2. Implement the provider

```ruby theme={"theme":"night-owl"}
module SpreeAcmeTax
  class TaxProvider < Spree::TaxProvider::Base
    PROVIDER_ID = 'acme_tax'.freeze

    def self.display_name = 'Acme Tax'

    def estimate(owner, items = nil, tax_date: nil, tax_identifier: nil, exemptions: [], tax_inclusive: nil, context: {})
      integration = Integration.active_for(owner.store)
      taxable = owner.taxable_items
      tax_inclusive = owner.tax_inclusive? if tax_inclusive.nil?

      if integration.nil? || taxable.empty? || owner.tax_address.nil?
        sweep!(owner)
        taxable.each { |item| store_pre_tax_amount(item, 0) }
        return
      end

      quote = integration.client.quote(
        lines: taxable, ship_to: owner.tax_address, date: tax_date || Time.current,
        registration: tax_identifier&.value, prices_include_tax: tax_inclusive
      )

      ApplicationRecord.transaction do
        sweep!(owner)
        quote.lines.each { |line| write_tax_line(owner, line, tax_inclusive) }

        # An item taxed by several jurisdictions has a line for each.
        included = tax_inclusive ? quote.lines.group_by(&:item).transform_values { |lines| lines.sum(&:tax) } : {}
        taxable.each { |item| store_pre_tax_amount(item, included.fetch(item, 0)) }
      end
    rescue AcmeTax::Unavailable => e
      raise Spree::Tax::ProviderUnavailable.new(e.message, provider_key: PROVIDER_ID)
    rescue AcmeTax::Rejected => e
      raise Spree::Tax::CalculationRefused.new(e.message, provider_key: PROVIDER_ID)
    end

    private

    # Only this provider's rows: another engine's rows on the same owner,
    # such as import VAT on a duty, are not ours to delete.
    def sweep!(owner)
      owner.tax_lines.where(provider_id: PROVIDER_ID).delete_all
    end

    # What the item is worth before tax: its price less the tax inside it.
    # Additional tax sits on top, and an item left untaxed keeps its whole
    # price, so a stale amount from an earlier quote never stays behind.
    def store_pre_tax_amount(item, included_tax)
      return unless item.respond_to?(:pre_tax_amount)

      basis = item.respond_to?(:taxable_basis) ? item.taxable_basis : item.amount
      item.update_column(:pre_tax_amount, basis - included_tax)
    end

    def write_tax_line(owner, line, tax_inclusive)
      Spree::TaxLine.create!(
        Spree::TaxLine.adjustable_key_for(line.item.class) => line.item.id,
        (owner.is_a?(Spree::Order) ? :order : :cart) => owner,
        amount: line.tax,
        rate: line.rate,
        label: line.name,
        included: tax_inclusive,
        provider_id: PROVIDER_ID,
        taxability_reason: line.reason,   # one of Spree::TaxLine.taxability_reasons
        country_code: line.country_code,
        data: { 'jurisdiction' => line.jurisdiction }
      )
    end
  end
end
```

### The contract

Every method below is defined on `Spree::TaxProvider::Base`. Core calls them; you never call them yourself.

| Method | When core calls it | What it must do |
| - | - | - |
| `estimate(owner, items = nil, tax_date: nil, tax_identifier: nil, exemptions: [], tax_inclusive: nil, context: {})` | Whenever a cart or an unplaced order changes: items, addresses, delivery, discounts | Replace this provider's tax lines on the owner. Required. |
| `commit(order)` | Once the order is placed | File the sale with your service. Must be idempotent: completion can replay, so key the document on the order number and treat a duplicate as success. |
| `void(order)` | When the order is cancelled | Reverse the filed document. A document that was never filed counts as voided. |
| `estimate_refund(order, items, amounts: nil, tax_date: nil)` | Before money goes back on a return, claim or exchange | Answer the tax to give back. Required. |
| `refund(order, return_items, amount: nil, tax_date: nil)` | Once the money has gone back | File the credit with your service. |
| `estimate_replacement(order, items, tax_date: nil, tax_identifier: nil, exemptions: [], tax_inclusive: nil)` | When an exchange's replacement is priced | Write charge rows on the exchange lines for the replacement's tax. Required. |
| `commit_replacement(order, items)` | Once the replacement ships | File the replacement as a sale of its own. |

`commit`, `void`, `refund` and `commit_replacement` do nothing by default, which is right for a provider whose rows are the whole record. `estimate`, `estimate_refund` and `estimate_replacement` raise until you implement them.

### Rules for estimate

* **Rewrite everything you delete.** `items` names what changed, but a service that prices a whole document may rewrite every row on the owner, provided it writes a row for each item it swept. Delete only rows whose `provider_id` is yours.
* **Write a row for every item you formed a treatment for,** zero-amount ones included: a zero-rated line says why it is zero in `taxability_reason`.
* **Follow `tax_inclusive:`.** It says whether the market's prices include tax. Pass it to your service and mark the rows `included` to match. When it is nil, ask the owner (`owner.tax_inclusive?`). Set each item's `pre_tax_amount` too, to its price less any included tax, as `Spree::TaxProvider::Internal` does: the order's pre-tax totals and product revenue read it.
* **Fail closed, but only when the service fails.** Raise `Spree::Tax::ProviderUnavailable` when your service could not answer (timeout, outage, rate limit): core refuses the checkout and the customer can retry. Raise `Spree::Tax::CalculationRefused` when it answered no (an address it will not accept): core shows your message so the customer can correct it. Anything else reaches the customer as a broken checkout.
* **Have no opinion when disconnected.** With no active integration, sweep your rows and return. Report the misconfiguration to your error tracker if you like, but never block a cart because a merchant switched an integration off.
* `estimate` is never called on a placed order. The order's money is frozen once it is placed.

### Refunds

The customer is owed the tax they paid. `Spree::TaxProvider::RecordedShare` answers each returned unit's share of the tax the sale actually charged, which is what `spree_avalara` uses:

```ruby theme={"theme":"night-owl"}
def estimate_refund(order, items, amounts: nil, tax_date: nil)
  Spree::TaxProvider::RecordedShare.new(order: order, items: items, amounts: amounts).call
end
```

Compute it yourself only when your service must price the credit, for example at the rates in force on the day of the sale (`tax_date`). If your service cannot be reached, raise `Spree::Tax::ProviderUnavailable`: the return is refused until it can, rather than refunding tax nobody worked out.

### Optional declarations

These are class methods, read while the admin presents the provider.

```ruby theme={"theme":"night-owl"}
# Tax domains you cannot handle, so the market form warns a merchant who
# pairs you with a market that needs them.
def self.unsupported_capabilities
  %i[reverse_charge]
end

# Problems in the store's own setup that stop you calculating, shown as a
# warning on the market form. Worked out from the store on every request.
# `highlights` are the parts of the label the form shows in bold.
def self.setup_issues(store)
  missing = store.stock_locations.first_party.active.select { |location| location.address1.blank? }
  return [] if missing.empty?

  names = missing.map(&:name)
  [{ key: 'origin_address_incomplete', label: "#{names.to_sentence} has no address", highlights: names }]
end

# Whether a store can choose you: hide the provider until it is connected.
def self.available_for_store?(store)
  Integration.active_for(store).present?
end

# The exemption reason codes your service reads, offered when a merchant
# adds an exemption reason. nil when any code will do.
def self.exemption_reason_codes
  { 'G' => 'Resale', 'E' => 'Charitable organization' }
end

# Your service's own tax codes, searched as a merchant types a tax
# category's code. Defining it turns the search on.
def self.tax_codes(store, query:)
  Integration.active_for(store)&.client&.tax_codes(query)&.map do |code|
    { code: code.id, description: code.name }
  end || []
end
```

## 3. Register both classes

```ruby theme={"theme":"night-owl"}
# config/initializers/spree.rb
Rails.application.config.after_initialize do
  Spree.tax_providers << SpreeAcmeTax::TaxProvider
  Spree.integrations << 'SpreeAcmeTax::Integration'
end
```

Register inside `after_initialize`: Spree sets up its own lists after your initializers run, so an entry added at the top level of the file would be dropped. A gem registers from its engine's `config.after_initialize` block in the same way.

The provider's API name comes from its module: `SpreeAcmeTax::TaxProvider` is `acme_tax`. That is the value a market's `tax_provider` takes, and what `GET /api/v3/admin/tax_providers` lists.

## 4. Use it

A merchant connects the integration under **Settings → Integrations**, then opens a market under **Settings → Markets** and picks your provider as its **Tax engine**. Markets left alone keep the store's default provider.

## Testing

Test the provider directly, with your service's client stubbed:

```ruby theme={"theme":"night-owl"}
RSpec.describe SpreeAcmeTax::TaxProvider do
  let(:store) { Spree::Store.default }
  let!(:integration) { SpreeAcmeTax::Integration.create!(store: store, preferred_api_key: 'test') }
  let(:cart) { create(:cart, store: store, ship_address: create(:address)) }
  let!(:line_item) { create(:line_item, cart: cart, order: nil, price: 100) }

  before { allow(integration.class).to receive(:active_for).and_return(integration) }

  it 'writes one tax line per item the service taxed' do
    allow(integration.client).to receive(:quote).and_return(quote_with(line_item, tax: 8.25))

    described_class.new.estimate(cart)

    expect(cart.tax_lines.where(provider_id: 'acme_tax').sum(:amount)).to eq(8.25)
  end

  it 'refuses the checkout when the service is down' do
    allow(integration.client).to receive(:quote).and_raise(AcmeTax::Unavailable, 'timeout')

    expect { described_class.new.estimate(cart) }.to raise_error(Spree::Tax::ProviderUnavailable)
  end
end
```

To check your request and response shapes against the real service, record its answers once against the vendor's sandbox, for example with VCR, and replay them in CI. Record them rather than writing them by hand, so the tests prove what the service actually answers.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.