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.

Companies and tax exemptions, Phases 4-6: exemption certificates start applying

Łukasz Adamczykc5a2f9e8927d
diff --git a/spree/core/app/models/spree/company.rb b/spree/core/app/models/spree/company.rb
index de63b8f754..79db4ba5c4 100644
--- a/spree/core/app/models/spree/company.rb
+++ b/spree/core/app/models/spree/company.rb
@@ -26,6 +26,8 @@ module Spree
has_many :company_contacts, through: :company_locations
has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', dependent: :destroy,
inverse_of: :company
+ has_many :tax_exemption_certificates, class_name: 'Spree::TaxExemptionCertificate',
+ dependent: :destroy, inverse_of: :company
validates :name, presence: true
# Paired with the partial unique index, per the convention — without it a
diff --git a/spree/core/app/models/spree/tax_exemption_certificate.rb b/spree/core/app/models/spree/tax_exemption_certificate.rb
new file mode 100644
index 0000000000..bcddf1f999
--- /dev/null
+++ b/spree/core/app/models/spree/tax_exemption_certificate.rb
@@ -0,0 +1,57 @@
+module Spree
+ # A business customer's evidence that some or all of its purchases are not
+ # taxed — a resale certificate, a government exemption, a charity's own-use
+ # claim. Resolved into ephemeral {Spree::TaxExemption} entries at estimate
+ # time; the zero-amount tax rows a provider writes are the durable record of
+ # what was claimed.
+ #
+ # Scoped by jurisdiction rather than duplicated per branch: a certificate
+ # valid in one state and not the next is the ordinary case, and the country
+ # and state columns say exactly where it holds.
+ class TaxExemptionCertificate < Spree.base_class
+ has_prefix_id :cert
+
+ include Spree::HasStatus
+ include Spree::Metafields
+
+ attribute :metadata, default: -> { {} }
+
+ # A status column moved between values by a workflow — never a callback,
+ # and never a state machine.
+ has_status :pending, :verified, :expired, :revoked, default: :pending
+
+ belongs_to :company, class_name: 'Spree::Company', inverse_of: :tax_exemption_certificates
+ belongs_to :country, class_name: 'Spree::Country', optional: true
+ belongs_to :state, class_name: 'Spree::State', optional: true
+ belongs_to :verified_by, class_name: Spree.admin_user_class.to_s, optional: true
+
+ # Confidential, so the private service rather than the public one that
+ # serves product images.
+ has_one_attached :document, service: Spree.private_storage_service_name
+
+ validates :certificate_number, :reason_code, presence: true
+
+ # Expiry is decided here rather than persisted: the date is the fact, and a
+ # sweeper writing 'expired' would only restate it. Matches how gift cards
+ # and stock reservations treat their own deadlines.
+ scope :active, -> { verified.where('expires_at IS NULL OR expires_at > ?', Time.current) }
+ scope :for_address, lambda { |address|
+ where(country: [address&.country, nil].uniq).where(state: [address&.state, nil].uniq)
+ }
+
+ self.whitelisted_ransackable_attributes = %w[certificate_number reason_code status expires_at]
+
+ delegate :store, :store_id, to: :company
+
+ # Accepting a certificate is a decision on record; withdrawing it is
+ # revocation, not deletion.
+ def can_be_deleted?
+ !verified?
+ end
+
+ # Whether the date has passed, regardless of what the column says.
+ def lapsed?
+ expires_at.present? && expires_at <= Time.current
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/tax/resolve_exemptions.rb b/spree/core/app/services/spree/tax/resolve_exemptions.rb
index 0bf90112fa..3270ab89b6 100644
--- a/spree/core/app/services/spree/tax/resolve_exemptions.rb
+++ b/spree/core/app/services/spree/tax/resolve_exemptions.rb
@@ -3,26 +3,39 @@ module Spree
# Assembles the exemption evidence for a sale, handed to the tax provider
# as +estimate+'s +exemptions:+ input.
#
- # Returns nothing yet, because core has nothing to read: exemption
- # certificates arrive with +Spree::TaxExemptionCertificate+, which is gated
- # on the B2B Company model (docs/plans/6.0-tax-provider.md, Phase 7). This
- # body then becomes the certificate lookup it is standing in for, and the
- # provider contract does not change — which is the reason the seam ships
- # first rather than alongside.
+ # Reads the certificates the buyer's company holds for where the goods are
+ # going. Only active ones count — verified, and not past their date — so
+ # lifecycle is a filter here rather than something the provider has to
+ # reason about. Multiple certificates mean multiple entries; one claim
+ # reaching an item is enough to exempt it.
#
- # Until then, exemption works two ways without core storing anything:
- # through the provider's own certificate store (Avalara's, for instance),
- # or by swapping this service through
- # +Spree.tax_resolve_exemptions_service+ to read wherever the merchant's
- # certificates already live. Inventing a claim here would be worse than
- # collecting the tax.
+ # A consumer sale, or a cart with no destination yet, resolves nothing and
+ # is taxed normally. Inventing a claim would be worse than collecting the
+ # tax.
+ #
+ # Swap through +Spree.tax_resolve_exemptions_service+ to read certificates
+ # that live somewhere else — a provider's own store (Avalara keeps them),
+ # or wherever the merchant already keeps them.
class ResolveExemptions
prepend Spree::ServiceModule::Base
# @param order [Spree::Cart, Spree::Order]
# @return [Array<Spree::TaxExemption>]
def call(order:)
- success([])
+ company = order.company
+ address = order.tax_address
+ return success([]) if company.nil? || address.nil?
+
+ success(
+ company.tax_exemption_certificates.active.for_address(address).map do |certificate|
+ Spree::TaxExemption.new(
+ reason_code: certificate.reason_code,
+ certificate_number: certificate.certificate_number,
+ country_iso: certificate.country&.iso,
+ state_code: certificate.state&.abbr
+ )
+ end
+ )
end
end
end
diff --git a/spree/core/app/workflows/spree/tax_exemption_certificates/verify.rb b/spree/core/app/workflows/spree/tax_exemption_certificates/verify.rb
new file mode 100644
index 0000000000..fbafd50cb3
--- /dev/null
+++ b/spree/core/app/workflows/spree/tax_exemption_certificates/verify.rb
@@ -0,0 +1,48 @@
+module Spree
+ module TaxExemptionCertificates
+ # Accepts a certificate as evidence, which is what makes it count at
+ # estimate time.
+ #
+ # A workflow rather than a plain update because of the +validate+ hook: a
+ # merchant who checks a resale number against a state registry, or requires
+ # a second pair of eyes above a threshold, needs somewhere to refuse before
+ # the certificate starts exempting sales. Hook keys are public API, so this
+ # one is placed while 6.0 is still open.
+ class Verify < Spree::Workflow
+ hooks :validate, :after_verify
+
+ # @param certificate [Spree::TaxExemptionCertificate]
+ # @param verified_by [Object, nil] the staff member accepting it
+ def perform(certificate:, verified_by: nil)
+ super
+
+ step :ensure_verifiable
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :mark_verified
+ end
+
+ run_hooks :after_verify
+ certificate.publish_event('tax_exemption_certificate.verified')
+ success(certificate.reload)
+ end
+
+ private
+
+ # Only a pending certificate is awaiting a decision. Re-verifying a
+ # revoked one would resurrect evidence somebody withdrew.
+ def ensure_verifiable
+ failure(certificate, :not_pending) unless certificate.pending?
+ end
+
+ def mark_verified
+ certificate.update!(
+ status: 'verified',
+ verified_at: Time.current,
+ verified_by: certificate.verified_by || verified_by
+ )
+ end
+ end
+ end
+end
diff --git a/spree/core/db/migrate/20260807000003_create_spree_tax_exemption_certificates.rb b/spree/core/db/migrate/20260807000003_create_spree_tax_exemption_certificates.rb
new file mode 100644
index 0000000000..a76c18013d
--- /dev/null
+++ b/spree/core/db/migrate/20260807000003_create_spree_tax_exemption_certificates.rb
@@ -0,0 +1,28 @@
+class CreateSpreeTaxExemptionCertificates < ActiveRecord::Migration[8.1]
+ def change
+ create_table :spree_tax_exemption_certificates do |t|
+ t.references :company, null: false
+ t.references :country # nil = every country
+ t.references :state # nil = the entire country
+ t.string :certificate_number, null: false
+ t.string :reason_code, null: false # resale, government, … — becomes the
+ # provider's entity use code
+ t.string :status, null: false # no DB default: set by the creating service
+ t.datetime :issued_at
+ t.datetime :expires_at
+ t.string :issuing_authority
+ # Who accepted the certificate, and when — the same pair every other
+ # reviewed record keeps.
+ t.datetime :verified_at
+ t.references :verified_by
+ if t.respond_to?(:jsonb)
+ t.jsonb :metadata
+ else
+ t.json :metadata
+ end
+ t.timestamps
+ end
+
+ add_index :spree_tax_exemption_certificates, [:company_id, :status]
+ end
+end
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index 9976aad1d4..f61cf08a03 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -89,6 +89,8 @@ module Spree
claim_deny_workflow: 'Spree::Claims::Deny',
claim_cancel_workflow: 'Spree::Claims::Cancel',
+ tax_exemption_certificate_verify_workflow: 'Spree::TaxExemptionCertificates::Verify',
+
# customers
customer_create_workflow: 'Spree::Customers::Create',
diff --git a/spree/core/lib/spree/testing_support/factories/tax_exemption_certificate_factory.rb b/spree/core/lib/spree/testing_support/factories/tax_exemption_certificate_factory.rb
new file mode 100644
index 0000000000..e21940e639
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/tax_exemption_certificate_factory.rb
@@ -0,0 +1,18 @@
+FactoryBot.define do
+ factory :tax_exemption_certificate, class: Spree::TaxExemptionCertificate do
+ company
+ sequence(:certificate_number) { |n| "CERT-#{n}" }
+ reason_code { 'resale' }
+ status { 'pending' }
+
+ trait :verified do
+ status { 'verified' }
+ verified_at { Time.current }
+ end
+
+ trait :expired do
+ status { 'verified' }
+ expires_at { 1.day.ago }
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/tax_exemption_certificate_spec.rb b/spree/core/spec/models/spree/tax_exemption_certificate_spec.rb
new file mode 100644
index 0000000000..351a43b048
--- /dev/null
+++ b/spree/core/spec/models/spree/tax_exemption_certificate_spec.rb
@@ -0,0 +1,97 @@
+require 'spec_helper'
+
+describe Spree::TaxExemptionCertificate, type: :model do
+ let(:store) { @default_store }
+ let(:company) { create(:company, store: store) }
+
+ it 'reaches the store through its company' do
+ expect(create(:tax_exemption_certificate, company: company).store).to eq(store)
+ end
+
+ it 'starts pending' do
+ expect(create(:tax_exemption_certificate, company: company)).to be_pending
+ end
+
+ describe '.active' do
+ it 'includes a verified certificate with no expiry' do
+ certificate = create(:tax_exemption_certificate, :verified, company: company)
+
+ expect(described_class.active).to include(certificate)
+ end
+
+ it 'excludes one that has not been verified' do
+ certificate = create(:tax_exemption_certificate, company: company)
+
+ expect(described_class.active).not_to include(certificate)
+ end
+
+ # The date is the fact — no job writes 'expired', so the scope has to be
+ # what keeps a lapsed certificate out of resolution.
+ it 'excludes a verified certificate whose date has passed' do
+ certificate = create(:tax_exemption_certificate, :expired, company: company)
+
+ expect(certificate).to be_verified
+ expect(certificate).to be_lapsed
+ expect(described_class.active).not_to include(certificate)
+ end
+
+ it 'includes one expiring in the future' do
+ certificate = create(:tax_exemption_certificate, :verified, company: company, expires_at: 1.year.from_now)
+
+ expect(described_class.active).to include(certificate)
+ end
+ end
+
+ describe '.for_address' do
+ let(:germany) { create(:country, iso: 'DE', name: 'Germany') }
+ let(:berlin) { create(:state, country: germany, abbr: 'BE', name: 'Berlin') }
+ let(:address) { create(:address, country: germany, state: berlin) }
+
+ it 'matches a certificate naming no jurisdiction' do
+ certificate = create(:tax_exemption_certificate, company: company)
+
+ expect(described_class.for_address(address)).to include(certificate)
+ end
+
+ it 'matches one naming the country' do
+ certificate = create(:tax_exemption_certificate, company: company, country: germany)
+
+ expect(described_class.for_address(address)).to include(certificate)
+ end
+
+ it 'matches one naming the exact state' do
+ certificate = create(:tax_exemption_certificate, company: company, country: germany, state: berlin)
+
+ expect(described_class.for_address(address)).to include(certificate)
+ end
+
+ it 'excludes one naming another state of the same country' do
+ other = create(:state, country: germany, abbr: 'HH', name: 'Hamburg')
+ certificate = create(:tax_exemption_certificate, company: company, country: germany, state: other)
+
+ expect(described_class.for_address(address)).not_to include(certificate)
+ end
+
+ it 'excludes one naming another country' do
+ certificate = create(:tax_exemption_certificate, company: company, country: create(:country, iso: 'FR'))
+
+ expect(described_class.for_address(address)).not_to include(certificate)
+ end
+ end
+
+ describe '#can_be_deleted?' do
+ it 'refuses once verified — revoke instead' do
+ expect(create(:tax_exemption_certificate, :verified, company: company).can_be_deleted?).to be(false)
+ end
+
+ it 'allows a pending one' do
+ expect(create(:tax_exemption_certificate, company: company).can_be_deleted?).to be(true)
+ end
+ end
+
+ it 'is destroyed with its company' do
+ create(:tax_exemption_certificate, company: company)
+
+ expect { company.destroy }.to change(described_class, :count).by(-1)
+ 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 3342235592..6f738bd945 100644
--- a/spree/core/spec/models/spree/tax_provider/internal_spec.rb
+++ b/spree/core/spec/models/spree/tax_provider/internal_spec.rb
@@ -152,6 +152,41 @@ describe Spree::TaxProvider::Internal, type: :model do
end
end
+ # The whole chain: a certificate the company holds, resolved by the real
+ # service, reaching the provider as a claim.
+ context 'with a certificate the buyer company holds' do
+ let!(:rate) { create(:tax_rate, country: country, amount: 0.1, tax_category: line_item.tax_category, included_in_price: false) }
+ let(:company) { create(:company, store: @default_store) }
+ let(:location) { create(:company_location, company: company) }
+
+ before { order.update!(company_location: location) }
+
+ def resolved_exemptions
+ Spree.tax_resolve_exemptions_service.new.call(order: order.reload).value
+ end
+
+ it 'exempts the sale instead of taxing it' do
+ create(:tax_exemption_certificate, :verified, company: company,
+ reason_code: 'resale', certificate_number: 'CERT-9',
+ country: country)
+
+ provider.estimate(order, exemptions: resolved_exemptions)
+
+ 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.data['exemption']).to eq('reason_code' => 'resale', 'certificate_number' => 'CERT-9')
+ end
+
+ it 'taxes normally while the certificate is still awaiting verification' do
+ create(:tax_exemption_certificate, company: company, country: country)
+
+ provider.estimate(order, exemptions: resolved_exemptions)
+
+ expect(order.tax_lines.reload.sole.amount).to eq(1.0)
+ end
+ end
+
context 'with an exemption against an included (VAT) rate' do
let!(:rate) { create(:tax_rate, country: country, amount: 0.2, tax_category: line_item.tax_category, included_in_price: true) }
diff --git a/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rb b/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rb
index 0b33287f3d..dadbbb2206 100644
--- a/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rb
+++ b/spree/core/spec/services/spree/tax/resolve_exemptions_spec.rb
@@ -3,13 +3,74 @@ 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
+ it 'resolves nothing for a consumer sale' do
result = described_class.call(order: order)
expect(result).to be_success
expect(result.value).to eq([])
end
+ context 'for a business customer' do
+ let(:store) { @default_store }
+ let(:company) { create(:company, store: store) }
+ let(:location) { create(:company_location, company: company) }
+ let(:germany) { create(:country, iso: 'DE', name: 'Germany') }
+ let(:berlin) { create(:state, country: germany, abbr: 'BE', name: 'Berlin') }
+
+ before do
+ order.update!(company_location: location,
+ ship_address: create(:address, country: germany, state: berlin),
+ bill_address: create(:address, country: germany, state: berlin))
+ end
+
+ it 'turns an active certificate into a claim' do
+ create(:tax_exemption_certificate, :verified, company: company,
+ reason_code: 'resale', certificate_number: 'DE-RESALE-1',
+ country: germany, state: berlin)
+
+ exemption = described_class.call(order: order.reload).value.sole
+
+ expect(exemption.reason_code).to eq('resale')
+ expect(exemption.certificate_number).to eq('DE-RESALE-1')
+ expect(exemption.country_iso).to eq('DE')
+ expect(exemption.state_code).to eq('BE')
+ end
+
+ it 'returns one entry per certificate' do
+ create(:tax_exemption_certificate, :verified, company: company, reason_code: 'resale')
+ create(:tax_exemption_certificate, :verified, company: company, reason_code: 'government')
+
+ expect(described_class.call(order: order.reload).value.map(&:reason_code)).
+ to contain_exactly('resale', 'government')
+ end
+
+ it 'ignores a certificate awaiting verification' do
+ create(:tax_exemption_certificate, company: company)
+
+ expect(described_class.call(order: order.reload).value).to eq([])
+ end
+
+ it 'ignores one whose date has passed' do
+ create(:tax_exemption_certificate, :expired, company: company)
+
+ expect(described_class.call(order: order.reload).value).to eq([])
+ end
+
+ it 'ignores one held for another jurisdiction' do
+ create(:tax_exemption_certificate, :verified, company: company, country: create(:country, iso: 'FR'))
+
+ expect(described_class.call(order: order.reload).value).to eq([])
+ end
+
+ # Tax needs a destination before an exemption can be scoped to one.
+ it 'resolves nothing before the buyer gives an address' do
+ order.update!(ship_address: nil, bill_address: nil)
+ create(:tax_exemption_certificate, :verified, company: company)
+
+ expect(described_class.call(order: order.reload).value).to eq([])
+ end
+ end
+
it 'is the registered seam merchants swap' do
expect(Spree.tax_resolve_exemptions_service).to eq(described_class)
end
diff --git a/spree/core/spec/workflows/spree/tax_exemption_certificates/verify_spec.rb b/spree/core/spec/workflows/spree/tax_exemption_certificates/verify_spec.rb
new file mode 100644
index 0000000000..b96fd07989
--- /dev/null
+++ b/spree/core/spec/workflows/spree/tax_exemption_certificates/verify_spec.rb
@@ -0,0 +1,74 @@
+require 'spec_helper'
+
+RSpec.describe Spree::TaxExemptionCertificates::Verify do
+ let(:store) { @default_store }
+ let(:company) { create(:company, store: store) }
+ let(:certificate) { create(:tax_exemption_certificate, company: company) }
+ let(:staff) { create(:admin_user) }
+
+ before { Spree.hooks.clear! }
+ after { Spree.hooks.clear! }
+
+ it 'accepts a pending certificate and records who did' do
+ result = described_class.call(certificate: certificate, verified_by: staff)
+
+ expect(result).to be_success
+ expect(result.value).to be_verified
+ expect(result.value.verified_at).to be_present
+ expect(result.value.verified_by).to eq(staff)
+ end
+
+ it 'makes the certificate count at estimate time' do
+ expect { described_class.call(certificate: certificate) }.
+ to change { Spree::TaxExemptionCertificate.active.include?(certificate.reload) }.from(false).to(true)
+ end
+
+ it 'refuses anything not pending' do
+ revoked = create(:tax_exemption_certificate, company: company, status: 'revoked')
+
+ result = described_class.call(certificate: revoked)
+
+ expect(result).to be_failure
+ expect(revoked.reload).to be_revoked
+ end
+
+ it 'publishes the event', :events do
+ allow(Spree::Events).to receive(:publish)
+
+ described_class.call(certificate: certificate)
+
+ expect(Spree::Events).to have_received(:publish).with('tax_exemption_certificate.verified', any_args)
+ end
+
+ # The reason this is a workflow at all: somewhere to refuse before the
+ # certificate starts exempting sales.
+ describe 'the validate hook' do
+ it 'lets a handler veto, writing nothing' do
+ Spree.hooks.register('tax_exemption_certificates.verify.validate') do |flow|
+ flow.reject!('registry check failed')
+ end
+
+ result = described_class.call(certificate: certificate)
+
+ expect(result).to be_failure
+ expect(result.error.value).to eq('registry check failed')
+ expect(certificate.reload).to be_pending
+ expect(certificate.verified_at).to be_nil
+ end
+
+ it 'runs after_verify once accepted' do
+ seen = nil
+ Spree.hooks.register('tax_exemption_certificates.verify.after_verify') do |flow|
+ seen = flow.certificate.status
+ end
+
+ described_class.call(certificate: certificate)
+
+ expect(seen).to eq('verified')
+ end
+ end
+
+ it 'is reachable through the dependency seam' do
+ expect(Spree.tax_exemption_certificate_verify_workflow).to eq(described_class)
+ end
+end