Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Phase 5: take exemption as typed evidence, not a yes-or-no answer

Łukasz Adamczyk91d68b12b331
diff --git a/spree/core/app/models/spree/tax_exemption.rb b/spree/core/app/models/spree/tax_exemption.rb
new file mode 100644
index 0000000000..543f456fa1
--- /dev/null
+++ b/spree/core/app/models/spree/tax_exemption.rb
@@ -0,0 +1,70 @@
+module Spree
+ # A claim that a sale, or part of one, is exempt from tax — resale,
+ # government purchase, a charity's own use. Ephemeral evidence handed to a
+ # tax provider through {Spree::TaxProvider::Base#estimate}, never persisted:
+ # the claim is the input, the zero-amount TaxLine rows are the record.
+ #
+ # Exemption is per jurisdiction (a certificate valid in one state and not the
+ # next) and per item (a resale order can hold own-use lines), which is why
+ # this is a scoped entry rather than a flag. One entry per certificate.
+ class TaxExemption
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+
+ # Why the sale is exempt, in the provider's vocabulary — Avalara's
+ # entityUseCode territory.
+ attribute :reason_code, :string
+ attribute :certificate_number, :string
+
+ # Where the claim holds. Nil country = everywhere the provider taxes,
+ # nil state = the whole country.
+ attribute :country_iso, :string
+ attribute :state_code, :string
+
+ # Per-line departures from the entry. Empty = the whole order is claimed.
+ attribute :item_overrides, default: -> { [] }
+
+ validates :reason_code, presence: true
+
+ # Whether this entry claims exemption for the given item.
+ #
+ # @param item [Spree::LineItem, Spree::Fulfillment, Spree::Fee]
+ # @return [Boolean]
+ def covers_item?(item)
+ override = override_for(item)
+ return override.exempt? unless override.nil?
+
+ true
+ end
+
+ # Whether this entry's scope reaches the given jurisdiction. An entry with
+ # no country claims every jurisdiction; one with a country but no state
+ # claims every state within it.
+ #
+ # @param country_iso [String, nil]
+ # @param state_code [String, nil]
+ # @return [Boolean]
+ def covers_jurisdiction?(country_iso, state_code = nil)
+ return true if self.country_iso.blank?
+ return false unless self.country_iso.casecmp?(country_iso.to_s)
+ return true if self.state_code.blank?
+
+ self.state_code.casecmp?(state_code.to_s)
+ end
+
+ # The reason to record for an item — the per-line override's when it names
+ # one, the entry's otherwise.
+ #
+ # @param item [Spree::LineItem, Spree::Fulfillment, Spree::Fee]
+ # @return [String, nil]
+ def reason_code_for(item)
+ override_for(item)&.reason_code.presence || reason_code
+ end
+
+ private
+
+ def override_for(item)
+ item_overrides.to_a.find { |override| override.item_id.to_s == item.prefixed_id.to_s }
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/tax_exemption/item_override.rb b/spree/core/app/models/spree/tax_exemption/item_override.rb
new file mode 100644
index 0000000000..9f947f5e5d
--- /dev/null
+++ b/spree/core/app/models/spree/tax_exemption/item_override.rb
@@ -0,0 +1,22 @@
+module Spree
+ class TaxExemption
+ # A single line's departure from its exemption entry — most often carving a
+ # line out (+exempt: false+ for the own-use item in a resale order), and
+ # optionally giving it a reason of its own.
+ class ItemOverride
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+
+ # Prefixed id of the line item, fulfillment or fee this applies to.
+ attribute :item_id, :string
+ attribute :exempt, :boolean, default: true
+ attribute :reason_code, :string
+
+ validates :item_id, presence: true
+
+ def exempt?
+ exempt
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/tax_provider/internal.rb b/spree/core/app/models/spree/tax_provider/internal.rb
index c6d0e08199..d52f684ca1 100644
--- a/spree/core/app/models/spree/tax_provider/internal.rb
+++ b/spree/core/app/models/spree/tax_provider/internal.rb
@@ -23,6 +23,7 @@ module Spree
return if items.empty?
rates = Spree::TaxRate.match(owner.tax_zone)
+ jurisdiction = jurisdiction_for(owner)
items.group_by(&:class).each do |klass, group|
# Replace-all set semantics per estimate: stale lines die with the
@@ -32,15 +33,23 @@ module Spree
items.each do |item|
relevant_rates = rates.select { |rate| rate.tax_category_id == tax_category_id_for(item) }
- store_pre_tax_amount(item, relevant_rates)
+ exemption = exemption_for(item, exemptions, jurisdiction)
+ # An exempt item has no tax to back out of its price, so the whole
+ # basis is pre-tax.
+ store_pre_tax_amount(item, exemption ? [] : relevant_rates)
# A matched rate always produces a row, zero-amount ones included:
# a zero rate is a treatment ("this is zero-rated"), which reporting
# and e-invoicing both need to see. No matched rate means no opinion,
# and writes nothing.
relevant_rates.each do |rate|
- amount = compute_tax(rate, item, relevant_rates)
- write_tax_line(owner, item, rate, amount, reason_for(rate))
+ if exemption
+ write_tax_line(owner, item, rate, 0, 'customer_exempt', jurisdiction,
+ data: exemption_data(exemption, item))
+ else
+ write_tax_line(owner, item, rate, compute_tax(rate, item, relevant_rates),
+ reason_for(rate), jurisdiction)
+ end
end
end
end
@@ -115,7 +124,29 @@ module Spree
{ country_iso: address.country&.iso, state_code: address.state&.abbr }
end
- def write_tax_line(owner, item, rate, amount, reason)
+ # The first exemption entry that claims both this item and the
+ # jurisdiction being taxed. Multiple certificates mean multiple entries,
+ # and one claim is enough.
+ def exemption_for(item, exemptions, jurisdiction)
+ Array(exemptions).find do |exemption|
+ exemption.covers_item?(item) &&
+ exemption.covers_jurisdiction?(jurisdiction[:country_iso], jurisdiction[:state_code])
+ end
+ end
+
+ # Keeps the claim with the row it produced: the invoice exemption code for
+ # a genuinely exempt supply depends on which exemption applied, which the
+ # reason alone cannot say.
+ def exemption_data(exemption, item)
+ {
+ 'exemption' => {
+ 'reason_code' => exemption.reason_code_for(item),
+ 'certificate_number' => exemption.certificate_number
+ }.compact
+ }
+ end
+
+ def write_tax_line(owner, item, rate, amount, reason, jurisdiction, data: {})
owner_key = owner.is_a?(Spree::Order) ? :order : :cart
Spree::TaxLine.create!(
{
@@ -127,8 +158,9 @@ module Spree
label: rate.adjustment_label,
included: rate.included_in_price,
provider_id: 'internal',
- taxability_reason: reason
- }.merge(jurisdiction_for(owner))
+ taxability_reason: reason,
+ data: data
+ }.merge(jurisdiction)
)
end
end
diff --git a/spree/core/app/services/spree/tax/resolve_exemptions.rb b/spree/core/app/services/spree/tax/resolve_exemptions.rb
new file mode 100644
index 0000000000..7aee20ebee
--- /dev/null
+++ b/spree/core/app/services/spree/tax/resolve_exemptions.rb
@@ -0,0 +1,22 @@
+module Spree
+ module Tax
+ # Assembles the exemption evidence for a sale, handed to the tax provider
+ # as +estimate+'s +exemptions:+ input.
+ #
+ # Core resolves nothing: stock Spree stores no exemption certificates, and
+ # inventing a claim would be worse than collecting tax. Merchants get
+ # working exemption either from their provider's own certificate store
+ # (Avalara's, for instance) or by swapping this service through
+ # +Spree.tax_resolve_exemptions_service+ to read wherever their
+ # certificates live.
+ class ResolveExemptions
+ prepend Spree::ServiceModule::Base
+
+ # @param order [Spree::Cart, Spree::Order]
+ # @return [Array<Spree::TaxExemption>]
+ def call(order:)
+ success([])
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/carts/recalculate_totals.rb b/spree/core/app/workflows/spree/carts/recalculate_totals.rb
index e19c0f46e3..3e3f967de3 100644
--- a/spree/core/app/workflows/spree/carts/recalculate_totals.rb
+++ b/spree/core/app/workflows/spree/carts/recalculate_totals.rb
@@ -58,7 +58,12 @@ module Spree
Spree.adjusters.each { |adjuster| adjuster.adjust(cart) }
refresh_discount_and_fee_columns
@tax_line_context = run_hooks :set_tax_line_context
- Spree.tax_provider.estimate(cart, tax_date: Time.current, context: tax_line_context)
+ Spree.tax_provider.estimate(
+ cart,
+ tax_date: Time.current,
+ exemptions: Spree.tax_resolve_exemptions_service.new.call(order: cart).value,
+ context: tax_line_context
+ )
end
# Re-derives the denormalized per-adjustable columns and the record's
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index 108e421c92..9976aad1d4 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -113,7 +113,11 @@ module Spree
line_item_by_variant_finder: 'Spree::LineItems::FindByVariant',
# search
- search_product_presenter: 'Spree::SearchProvider::ProductPresenter'
+ search_product_presenter: 'Spree::SearchProvider::ProductPresenter',
+
+ # tax — assembles the exemption evidence handed to the tax provider.
+ # Core resolves none; swap this to read wherever certificates live.
+ tax_resolve_exemptions_service: 'Spree::Tax::ResolveExemptions'
}.freeze
include Spree::DependenciesHelper
diff --git a/spree/core/spec/models/spree/tax_exemption_spec.rb b/spree/core/spec/models/spree/tax_exemption_spec.rb
new file mode 100644
index 0000000000..2710fe2e30
--- /dev/null
+++ b/spree/core/spec/models/spree/tax_exemption_spec.rb
@@ -0,0 +1,81 @@
+require 'spec_helper'
+
+describe Spree::TaxExemption, type: :model do
+ let(:order) { create(:order_with_line_items, line_items_count: 2) }
+ let(:line_item) { order.line_items.first }
+ let(:other_line_item) { order.line_items.last }
+
+ it 'requires a reason' do
+ expect(described_class.new(reason_code: 'resale')).to be_valid
+ expect(described_class.new).not_to be_valid
+ end
+
+ it 'is never persisted' do
+ expect(described_class.new).not_to respond_to(:save)
+ end
+
+ describe '#covers_jurisdiction?' do
+ it 'claims every jurisdiction without a country' do
+ exemption = described_class.new(reason_code: 'resale')
+
+ expect(exemption.covers_jurisdiction?('US', 'NY')).to be(true)
+ expect(exemption.covers_jurisdiction?(nil, nil)).to be(true)
+ end
+
+ it 'claims a whole country without a state' do
+ exemption = described_class.new(reason_code: 'resale', country_iso: 'US')
+
+ expect(exemption.covers_jurisdiction?('US', 'NY')).to be(true)
+ expect(exemption.covers_jurisdiction?('us', nil)).to be(true)
+ expect(exemption.covers_jurisdiction?('DE', nil)).to be(false)
+ end
+
+ it 'claims one state when it names one' do
+ exemption = described_class.new(reason_code: 'resale', country_iso: 'US', state_code: 'NY')
+
+ expect(exemption.covers_jurisdiction?('US', 'NY')).to be(true)
+ expect(exemption.covers_jurisdiction?('US', 'CA')).to be(false)
+ expect(exemption.covers_jurisdiction?('US', nil)).to be(false)
+ end
+ end
+
+ describe '#covers_item?' do
+ it 'claims every item without overrides' do
+ expect(described_class.new(reason_code: 'resale').covers_item?(line_item)).to be(true)
+ end
+
+ it 'carves out a line the buyer bought for their own use' do
+ exemption = described_class.new(
+ reason_code: 'resale',
+ item_overrides: [Spree::TaxExemption::ItemOverride.new(item_id: line_item.prefixed_id, exempt: false)]
+ )
+
+ expect(exemption.covers_item?(line_item)).to be(false)
+ expect(exemption.covers_item?(other_line_item)).to be(true)
+ end
+ end
+
+ describe '#reason_code_for' do
+ it 'prefers the line override reason over the entry reason' do
+ exemption = described_class.new(
+ reason_code: 'resale',
+ item_overrides: [Spree::TaxExemption::ItemOverride.new(item_id: line_item.prefixed_id, reason_code: 'government')]
+ )
+
+ expect(exemption.reason_code_for(line_item)).to eq('government')
+ expect(exemption.reason_code_for(other_line_item)).to eq('resale')
+ end
+ end
+
+ describe Spree::TaxExemption::ItemOverride do
+ it 'requires the item it applies to' do
+ expect(described_class.new(item_id: 'li_abc')).to be_valid
+ expect(described_class.new).not_to be_valid
+ end
+
+ it 'is exempt unless it says otherwise' do
+ expect(described_class.new(item_id: 'li_abc')).to be_exempt
+ expect(described_class.new(item_id: 'li_abc', exempt: false)).not_to be_exempt
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/tax_provider/internal_spec.rb b/spree/core/spec/models/spree/tax_provider/internal_spec.rb
index 3132959700..d02da044d8 100644
--- a/spree/core/spec/models/spree/tax_provider/internal_spec.rb
+++ b/spree/core/spec/models/spree/tax_provider/internal_spec.rb
@@ -129,6 +129,51 @@ describe Spree::TaxProvider::Internal, type: :model do
end
end
+ context 'with an exemption covering the sale' do
+ let!(:rate) { create(:tax_rate, zone: zone, amount: 0.1, tax_category: line_item.tax_category, included_in_price: false) }
+ let(:exemption) { Spree::TaxExemption.new(reason_code: 'resale', certificate_number: 'CERT-1') }
+
+ it 'writes a zero row recording the claim' do
+ provider.estimate(order, exemptions: [exemption])
+
+ tax_line = order.tax_lines.reload.sole
+ expect(tax_line.amount).to eq(0)
+ expect(tax_line.taxability_reason).to eq('customer_exempt')
+ expect(tax_line.category_code).to eq('E')
+ expect(tax_line.data['exemption']).to eq('reason_code' => 'resale', 'certificate_number' => 'CERT-1')
+ end
+
+ it 'ignores an exemption scoped to another jurisdiction' do
+ elsewhere = Spree::TaxExemption.new(reason_code: 'resale', country_iso: 'DE')
+
+ provider.estimate(order, exemptions: [elsewhere])
+
+ expect(order.tax_lines.reload.sole.amount).to eq(1.0)
+ end
+
+ it 'taxes a line the buyer carved out for their own use' do
+ carved_out = Spree::TaxExemption.new(
+ reason_code: 'resale',
+ item_overrides: [Spree::TaxExemption::ItemOverride.new(item_id: line_item.prefixed_id, exempt: false)]
+ )
+
+ provider.estimate(order, exemptions: [carved_out])
+
+ expect(order.tax_lines.reload.sole.taxability_reason).to eq('standard_rated')
+ end
+ end
+
+ context 'with an exemption against an included (VAT) rate' do
+ let!(:rate) { create(:tax_rate, zone: zone, amount: 0.2, tax_category: line_item.tax_category, included_in_price: true) }
+
+ it 'leaves the whole basis pre-tax, having no tax to back out' do
+ provider.estimate(order, exemptions: [Spree::TaxExemption.new(reason_code: 'government')])
+
+ expect(order.tax_lines.reload.sole.amount).to eq(0)
+ expect(line_item.reload.pre_tax_amount).to eq(10)
+ end
+ end
+
context 'with a taxable fee' do
let!(:rate) do
create(:tax_rate, zone: zone, amount: 0.1, tax_category: create(:tax_category, is_default: true), included_in_price: false)
diff --git a/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rb b/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rb
new file mode 100644
index 0000000000..0b33287f3d
--- /dev/null
+++ b/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rb
@@ -0,0 +1,37 @@
+require 'spec_helper'
+
+describe Spree::Tax::ResolveExemptions do
+ let(:order) { create(:order_with_line_items, line_items_count: 1) }
+
+ it 'resolves nothing, core storing no certificates' do
+ result = described_class.call(order: order)
+
+ expect(result).to be_success
+ expect(result.value).to eq([])
+ end
+
+ it 'is the registered seam merchants swap' do
+ expect(Spree.tax_resolve_exemptions_service).to eq(described_class)
+ end
+
+ context 'when an application swaps the seam' do
+ let(:custom_service) do
+ Class.new do
+ prepend Spree::ServiceModule::Base
+
+ def call(order:)
+ success([Spree::TaxExemption.new(reason_code: 'resale', certificate_number: 'CERT-1')])
+ end
+ end
+ end
+
+ before { Spree::Dependencies.tax_resolve_exemptions_service = custom_service }
+ after { Spree::Dependencies.tax_resolve_exemptions_service = described_class }
+
+ it 'returns the application entries to the caller' do
+ exemptions = Spree.tax_resolve_exemptions_service.new.call(order: order).value
+
+ expect(exemptions.map(&:reason_code)).to eq(['resale'])
+ end
+ end
+end