Class: Spree::TaxProvider::Base

Inherits:
Object
  • Object
show all
Extended by:
ApiTyped
Defined in:
app/models/spree/tax_provider/base.rb

Overview

Contract for tax providers — the only sanctioned writers of Spree::TaxLine rows. estimate must use replace-all set semantics per target item (delete the item's stale lines, insert fresh ones); that is what keeps tax correct after address or item changes, and the post-sale estimate_refund / estimate_replacement follow the same rule. Commit/void/refund/commit_replacement are lifecycle no-ops for providers without a remote ledger.

Providers are stateless and constructed without arguments, so anything request-specific arrives as an argument rather than through the instance.

Direct Known Subclasses

Internal

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ApiTyped

api_type, api_type_for, api_typed_family, class_name_for, find, registered_class

Class Method Details

.available_for_store?(_store) ⇒ Boolean

Whether this provider can be selected for a store. External providers override it to require a connected integration or credentials.

Parameters:

Returns:

  • (Boolean)


31
32
33
# File 'app/models/spree/tax_provider/base.rb', line 31

def self.available_for_store?(_store)
  true
end

.display_name ⇒ String

The name a merchant sees when choosing an engine. Override in a provider gem — a class name mangled into words rarely matches what the service is actually called.

Returns:

  • (String)


40
41
42
# File 'app/models/spree/tax_provider/base.rb', line 40

def self.display_name
  name.demodulize.titleize
end

.exemption_reason_codes ⇒ Hash{String => String}?

The exemption reason codes this engine understands, { code => label }, offered to a merchant adding a Spree::TaxExemptionReason. Nil for an engine that does not read the code, Spree's own included: any code a merchant chooses is then as good as another.

Returns:

  • (Hash{String => String}, nil)


50
51
52
# File 'app/models/spree/tax_provider/base.rb', line 50

def self.exemption_reason_codes
  nil
end

.registered(api_type) ⇒ Class?

The registered engine an API caller names by its shorthand, or nil. Matches the shorthand only, so a Ruby class name arriving over the API is unknown.

Parameters:

  • api_type (String) —

    e.g. "internal", "avalara"

Returns:

  • (Class, nil)


59
60
61
# File 'app/models/spree/tax_provider/base.rb', line 59

def self.registered(api_type)
  Spree::ApiTyped.find(Spree.tax_providers, api_type)
end

.tax_code_lookup? ⇒ Boolean

Whether this engine offers tax_codes, which decides whether the admin searches as a merchant types a tax category's code.

Returns:

  • (Boolean)


78
79
80
# File 'app/models/spree/tax_provider/base.rb', line 78

def self.tax_code_lookup?
  method(:tax_codes).owner != Spree::TaxProvider::Base.singleton_class
end

.tax_codes(_store, query:) ⇒ Array<Hash>?

Tax codes a merchant can search when classifying a tax category, as [{ code:, description: }]. Nil for an engine with no catalogue of codes to search, Spree's own included.

Parameters:

Returns:

  • (Array<Hash>, nil)


70
71
72
# File 'app/models/spree/tax_provider/base.rb', line 70

def self.tax_codes(_store, query:)
  nil
end

.to_api_hash(store) ⇒ Hash

How this engine describes itself to the admin, mirroring Spree::PreferenceSchema#subclasses_with_preference_schema: the class being described owns its own presentation, not the controller.

Parameters:

Returns:

  • (Hash)


104
105
106
107
108
109
110
111
112
113
114
# File 'app/models/spree/tax_provider/base.rb', line 104

def self.to_api_hash(store)
  {
    id: api_type,
    name: display_name,
    available: available_for_store?(store),
    unsupported_capabilities: unsupported_capability_details,
    exemption_reason_codes: exemption_reason_codes&.map { |code, label| { value: code.to_s, label: label.to_s } },
    tax_code_lookup: tax_code_lookup?,
    default: name == Spree.default_tax_provider.to_s
  }
end

.unsupported_capabilities ⇒ Array<Symbol>

Domains this provider cannot handle, so a merchant is warned when pairing it with a market instead of silently under-collecting. Declared on the class because core reads it while presenting the choice, before any provider is instantiated.

Returns:

  • (Array<Symbol>)


22
23
24
# File 'app/models/spree/tax_provider/base.rb', line 22

def self.unsupported_capabilities
  []
end

.unsupported_capability_details ⇒ Array<Hash>

The declared limits with the strings a merchant can act on. A capability with no translation degrades to its humanized key rather than a missing translation, so an extension that declares one without shipping strings still reads sensibly.

Returns:

  • (Array<Hash>)


88
89
90
91
92
93
94
95
96
# File 'app/models/spree/tax_provider/base.rb', line 88

def self.unsupported_capability_details
  unsupported_capabilities.map do |capability|
    {
      key: capability.to_s,
      label: I18n.t("spree.tax_capabilities.#{capability}.label", default: capability.to_s.humanize),
      description: I18n.t("spree.tax_capabilities.#{capability}.description", default: nil)
    }.compact
  end
end

Instance Method Details

#commit(order) ⇒ void

This method returns an undefined value.

Finalizes tax with the provider when the order is placed. No-op for a provider without a remote ledger — the rows are already the record.

Must be idempotent. Completion is replayable: a crash between the order commit and the cart stamp leaves Carts::Complete to re-run its finalize phase, which calls this again for an order already committed. Key the filing on the order and treat a duplicate as success, rather than filing a second document for one sale.

Parameters:



154
# File 'app/models/spree/tax_provider/base.rb', line 154

def commit(order); end

#commit_replacement(order, items) ⇒ void

This method returns an undefined value.

Files an exchange's replacement as a sale. Called once the exchange is fulfilled; must be idempotent, keyed on the exchange. No-op for a provider without a remote ledger.

Parameters:



236
# File 'app/models/spree/tax_provider/base.rb', line 236

def commit_replacement(order, items); end

#estimate(owner, items = nil, tax_date: nil, tax_identifier: nil, exemptions: [], tax_inclusive: nil, context: {}) ⇒ void

This method returns an undefined value.

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 — zero-amount treatments included. Never called on a completed order; the order-level money freeze gates it.

Parameters:

  • owner (Spree::Cart, Spree::Order)
  • items (Array<Spree::LineItem, Spree::Fulfillment, Spree::Fee>, nil) (defaults to: nil) —

    nil = every taxable item on the owner

  • tax_date (Time, nil) (defaults to: nil) —

    date whose rates apply; nil = now

  • tax_identifier (Spree::TaxIdentifier, nil) (defaults to: nil) —

    resolved buyer registration, nil for a consumer sale

  • exemptions (Array) (defaults to: []) —

    exemption evidence to apply

  • tax_inclusive (Boolean, nil) (defaults to: nil) —

    whether the owner's prices already include tax, which its market decides (Spree::Market#tax_inclusive); nil = ask the owner (+owner.tax_inclusive?+)

  • context (Hash) (defaults to: {}) —

    untyped provider extras from set_tax_line_context

Raises:

  • (Spree::Tax::ProviderUnavailable) —

    when the engine could not answer — refused, timed out, unreachable. Raise this (or a subclass, as a provider's own request error may) rather than a bare error: core turns it into a refusal the customer can retry, where anything else reaches them as a broken checkout. A provider a merchant switched off is not this — it has no opinion and writes no rows.



139
140
141
# File 'app/models/spree/tax_provider/base.rb', line 139

def estimate(owner, items = nil, tax_date: nil, tax_identifier: nil, exemptions: [], tax_inclusive: nil, context: {})
  raise NotImplementedError, "Please implement 'estimate' in your tax provider: #{self.class.name}"
end

#estimate_refund(order, items, amounts: nil, tax_date: nil) ⇒ void

This method returns an undefined value.

Works out the tax given back on lines of a return, claim or exchange, and writes it as credit TaxLine rows on them. The customer is refunded exactly what these rows hold, so this — not refund — decides the figure.

Each item credits its credited_quantity, and zero means no rows. Replace-all per item, as estimate: the rows are rewritten when the warehouse counts what arrived and again when the money goes back.

A provider may quote the credit, for example at the original tax_date, or give back the recorded share of what the sale charged — RecordedShare, which Internal uses. Either way it answers in the same rows.

Parameters:

  • order (Spree::Order) —

    a placed order

  • items (Array<Spree::ReturnLineItem, Spree::ClaimLineItem, Spree::ExchangeLineItem>)
  • amounts (Hash{Object => BigDecimal}, nil) (defaults to: nil) —

    the money refunded per item when it is less than the item's worth — a restocking fee, a part refund. Tax is then credited in the same proportion. Nil credits every item's full worth.

  • tax_date (Time, nil) (defaults to: nil) —

    the date whose rates apply; nil = order.completed_at

Raises:



206
207
208
# File 'app/models/spree/tax_provider/base.rb', line 206

def estimate_refund(order, items, amounts: nil, tax_date: nil)
  raise NotImplementedError, "Please implement 'estimate_refund' in your tax provider: #{self.class.name}"
end

#estimate_replacement(order, items, tax_date: nil, tax_identifier: nil, exemptions: [], tax_inclusive: nil) ⇒ void

This method returns an undefined value.

Taxes the replacement an exchange sends out, as a new sale, and writes it as charge TaxLine rows on the exchange lines. Never touches the order's own rows, which stay as the sale was placed. Replace-all per item; each item is taxed on its taxable_basis under its tax_category_id, and one whose credited_quantity is zero ships nothing and ends with no rows.

Parameters:

  • order (Spree::Order) —

    a placed order

  • items (Array<Spree::ExchangeLineItem>)
  • tax_date (Time, nil) (defaults to: nil) —

    date whose rates apply; nil = now

  • tax_identifier (Spree::TaxIdentifier, nil) (defaults to: nil) —

    the order's frozen registration

  • exemptions (Array) (defaults to: []) —

    exemption evidence to apply

  • tax_inclusive (Boolean, nil) (defaults to: nil) —

    as for estimate

Raises:



225
226
227
# File 'app/models/spree/tax_provider/base.rb', line 225

def estimate_replacement(order, items, tax_date: nil, tax_identifier: nil, exemptions: [], tax_inclusive: nil)
  raise NotImplementedError, "Please implement 'estimate_replacement' in your tax provider: #{self.class.name}"
end

#refund(order, return_items, amount: nil, tax_date: nil) ⇒ void

This method returns an undefined value.

Reports a partial credit against the committed document, keyed to the original transaction rather than voiding and re-committing it. Called after the money has moved.

By then each item's credit rows hold what went back (see estimate_refund), and a provider must credit no more than they do: the customer was repaid that tax and no more. amount is the money refunded, which may be less than the items are worth when an admin kept a restocking fee or refunded a goodwill figure of their own.

Parameters:



253
# File 'app/models/spree/tax_provider/base.rb', line 253

def refund(order, return_items, amount: nil, tax_date: nil); end

#service_tax_rate(address:, store:) ⇒ BigDecimal?

The tax rate, as a fraction, on a service the platform itself supplies and invoices — today only a marketplace's commission to a seller.

Distinct from estimate because nothing here is a sale: there is no order, no buyer and no item, only a B2B supply between the platform and a business it invoices. Returning a rate rather than writing rows is deliberate for the same reason — the caller snapshots the number onto its own ledger row, which is not a TaxLine.

Providers that cannot price a service supply return nil rather than zero: zero is the claim that the supply is untaxed, and the caller has a configured default to fall back on that a wrong zero would silence.

Parameters:

  • address (Spree::Address, nil) —

    where the business being invoiced is established — for commission, the seller's billing address

  • store (Spree::Store)

Returns:

  • (BigDecimal, nil) —

    e.g. 0.21 for 21%; nil if it has no opinion



179
180
181
# File 'app/models/spree/tax_provider/base.rb', line 179

def service_tax_rate(address:, store:)
  nil
end

#void(order) ⇒ void

This method returns an undefined value.

Reverses a committed tax document on cancellation.

Parameters:



160
# File 'app/models/spree/tax_provider/base.rb', line 160

def void(order); end