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 6: give the buyer's tax registration a home

Łukasz Adamczyk8def766aa1df
diff --git a/spree/core/app/models/concerns/spree/customer_methods.rb b/spree/core/app/models/concerns/spree/customer_methods.rb
index 97a995f1ed..8c9ecc1b6d 100644
--- a/spree/core/app/models/concerns/spree/customer_methods.rb
+++ b/spree/core/app/models/concerns/spree/customer_methods.rb
@@ -67,6 +67,9 @@ module Spree
has_many :customer_group_users, class_name: 'Spree::CustomerGroupUser', as: :customer, dependent: :destroy
has_many :customer_groups, through: :customer_group_users, class_name: 'Spree::CustomerGroup'
has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroy
+ # One per registration kind — a business can hold both an EU and a UK VAT number.
+ has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', foreign_key: :customer_id,
+ dependent: :destroy, inverse_of: :customer
belongs_to :ship_address, class_name: 'Spree::Address', optional: true
belongs_to :bill_address, class_name: 'Spree::Address', optional: true
diff --git a/spree/core/app/models/concerns/spree/purchase/taxation.rb b/spree/core/app/models/concerns/spree/purchase/taxation.rb
index 007a4ca329..117df1c69e 100644
--- a/spree/core/app/models/concerns/spree/purchase/taxation.rb
+++ b/spree/core/app/models/concerns/spree/purchase/taxation.rb
@@ -15,6 +15,26 @@ module Spree
@tax_zone ||= Spree::Zone.match(tax_address) || Spree::Zone.default_tax
end
+ # The buyer's tax registration to compute against: a checkout-time
+ # override first, then the customer's own. Nil means treat the sale as a
+ # consumer sale, which is the legally safe default — charging normal tax
+ # to an unidentified buyer is a presumption EU law explicitly protects.
+ #
+ # A completed order reads its own frozen snapshot instead of resolving
+ # again, so its tax can still be explained after the customer edits or
+ # withdraws the registration.
+ #
+ # Among a customer's registrations a verified one wins, then the most
+ # recent — a plain fallback chain, which is why this is an overridable
+ # method rather than a Dependencies seam.
+ #
+ # @return [Spree::TaxIdentifier, nil]
+ def resolved_tax_identifier
+ return tax_identifier if is_a?(Spree::Order) && completed?
+
+ tax_identifier || customer_tax_identifier
+ end
+
def tax_total
included_tax_total + additional_tax_total
end
@@ -28,6 +48,13 @@ module Spree
def pre_tax_total
pre_tax_item_amount + fulfillments.sum(:pre_tax_amount)
end
+
+ private
+
+ def customer_tax_identifier
+ identifiers = customer&.tax_identifiers.to_a
+ identifiers.find(&:verified?) || identifiers.max_by(&:created_at)
+ end
end
end
end
diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rb
index 3026ed66c2..042df04afb 100644
--- a/spree/core/app/models/spree/cart.rb
+++ b/spree/core/app/models/spree/cart.rb
@@ -72,6 +72,7 @@ module Spree
has_many :variants, through: :line_items
has_many :products, through: :variants
has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy, inverse_of: :cart
+ has_one :tax_identifier, class_name: 'Spree::TaxIdentifier', dependent: :destroy, inverse_of: :cart
has_many :discounts, class_name: 'Spree::Discount', dependent: :destroy, inverse_of: :cart
has_many :fees, class_name: 'Spree::Fee', dependent: :destroy, inverse_of: :cart
has_many :fulfillments, class_name: 'Spree::Fulfillment', dependent: :destroy, inverse_of: :cart do
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 91233c4ec8..afe0143320 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -176,6 +176,7 @@ module Spree
# Typed adjustment rows owned by this order (line-, fulfillment- and
# order-level). See docs/plans/6.0-6.1-split-adjustments.md.
has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy, inverse_of: :order
+ has_one :tax_identifier, class_name: 'Spree::TaxIdentifier', dependent: :destroy, inverse_of: :order
has_many :discounts, class_name: 'Spree::Discount', dependent: :destroy, inverse_of: :order
has_many :fees, class_name: 'Spree::Fee', dependent: :destroy, inverse_of: :order
diff --git a/spree/core/app/models/spree/tax_identifier.rb b/spree/core/app/models/spree/tax_identifier.rb
new file mode 100644
index 0000000000..0716cbb60a
--- /dev/null
+++ b/spree/core/app/models/spree/tax_identifier.rb
@@ -0,0 +1,68 @@
+module Spree
+ # The buyer's tax registration — a VAT or business number, typed by kind.
+ # Handed to a tax provider through {Spree::TaxProvider::Base#estimate}, where
+ # it is what makes EU B2B reverse charge possible.
+ #
+ # Three owners, exactly one per row: a customer (the durable profile value), a
+ # cart (an override entered during checkout) or an order (the frozen snapshot
+ # taken at completion). Orders keep a copy rather than a reference because a
+ # registration can be changed or withdrawn later, and an invoice must still
+ # show what was true when it was issued.
+ class TaxIdentifier < Spree.base_class
+ has_prefix_id :txi
+
+ include Spree::Metadata
+
+ # Statuses the platform records rather than the buyer chooses: nil means
+ # validation was never attempted, which includes having no validator
+ # registered for the kind.
+ VALIDATION_STATUSES = %w[pending verified unverified unavailable unsupported].freeze
+
+ # Which link of the resolution chain produced an order's snapshot.
+ SOURCES = %w[override company customer].freeze
+
+ # Owner — exactly one
+ belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true, inverse_of: :tax_identifiers
+ belongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :tax_identifier
+ belongs_to :order, class_name: 'Spree::Order', optional: true, inverse_of: :tax_identifier
+
+ validates :kind, :value, presence: true
+ validates :validation_status, inclusion: { in: VALIDATION_STATUSES }, allow_nil: true
+ validates :source, inclusion: { in: SOURCES }, allow_nil: true
+ validate :exactly_one_owner
+
+ scope :for_kind, ->(kind) { where(kind: kind) }
+ scope :verified, -> { where(validation_status: 'verified') }
+
+ # An order-owned row is a completion snapshot: immutable once written, so
+ # the tax treatment of a placed order can always be explained.
+ def readonly?
+ persisted? && order_id.present?
+ end
+
+ # @return [Spree::Customer, Spree::Cart, Spree::Order, nil]
+ def owner
+ customer || cart || order
+ end
+
+ def verified?
+ validation_status == 'verified'
+ end
+
+ # The provider-facing shape: a provider reads the kind and the number, never
+ # the ownership or the verdict.
+ #
+ # @return [Hash]
+ def to_provider_params
+ { kind: kind, value: value }
+ end
+
+ private
+
+ def exactly_one_owner
+ return if [customer, cart, order].compact.one?
+
+ errors.add(:base, Spree.t('errors.messages.exactly_one_tax_identifier_owner'))
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rb
index 4c6c9398ac..52c5ef58b1 100644
--- a/spree/core/app/workflows/spree/carts/complete.rb
+++ b/spree/core/app/workflows/spree/carts/complete.rb
@@ -192,6 +192,7 @@ module Spree
fulfillment_map = copy_fulfillments!(cart, order, line_item_map)
copy_typed_lines!(cart, order, line_item_map, fulfillment_map)
copy_promotions!(cart, order)
+ copy_tax_identifier!(cart, order)
repoint_money_records!(cart, order)
order.update_columns(
@@ -212,6 +213,20 @@ module Spree
order
end
+ # Freezes the buyer's tax registration onto the order, stamped with which
+ # link of the chain won. A copy rather than a reference: the customer can
+ # change or withdraw the number later, and the placed order's tax still
+ # has to be explainable. Consumer sales copy nothing.
+ def copy_tax_identifier!(cart, order)
+ resolved = cart.resolved_tax_identifier
+ return if resolved.nil?
+
+ attributes = resolved.attributes.except('id', 'customer_id', 'cart_id', 'created_at', 'updated_at')
+ order.create_tax_identifier!(
+ attributes.merge('source' => resolved.cart_id.present? ? 'override' : 'customer')
+ )
+ end
+
def copy_line_items!(cart, order)
cart.line_items.reload.index_with do |cart_line_item|
attributes = cart_line_item.attributes.except('id', 'cart_id', 'created_at', 'updated_at')
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index acda43ee47..55ac0924c5 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -892,6 +892,7 @@ en:
discount_value_type_invalid: value_type must be flat or percent
exactly_one_adjustable: must be attached to exactly one adjustable
exactly_one_of_cart_or_order: must belong to exactly one of cart or order
+ exactly_one_tax_identifier_owner: must belong to exactly one of customer, cart or order
invalid_delivery_method_rule: is not a registered delivery method rule
invalid_oauth_state: Invalid or expired authentication state. Please start the sign-in again.
invalid_order_routing_rule: is not a registered order routing rule
diff --git a/spree/core/db/migrate/20260806000003_create_spree_tax_identifiers.rb b/spree/core/db/migrate/20260806000003_create_spree_tax_identifiers.rb
new file mode 100644
index 0000000000..d7ebb3e382
--- /dev/null
+++ b/spree/core/db/migrate/20260806000003_create_spree_tax_identifiers.rb
@@ -0,0 +1,39 @@
+class CreateSpreeTaxIdentifiers < ActiveRecord::Migration[8.1]
+ def change
+ # The buyer's tax registration — a VAT number and its kind. Without it no
+ # provider can apply EU B2B reverse charge, because Spree had nowhere to put
+ # a customer's VAT number at all.
+ #
+ # No store_id: the row belongs to a customer, cart or order that already
+ # carries the store, matching spree_tax_lines.
+ create_table :spree_tax_identifiers do |t|
+ # Owner — exactly one (enforced at model level). The customer row is the
+ # durable profile value, the cart row a checkout-time override, the order
+ # row a frozen completion snapshot.
+ t.references :customer, null: true
+ t.references :cart, null: true
+ t.references :order, null: true
+
+ t.string :kind, null: false
+ t.string :value, null: false
+
+ # Written only by the validation service. A registry answers "valid now",
+ # so the evidence captured at validation time is the only proof that will
+ # ever exist for a past sale.
+ t.string :validation_status
+ t.datetime :validated_at
+ if t.respond_to?(:jsonb)
+ t.jsonb :validation_evidence
+ else
+ t.json :validation_evidence
+ end
+
+ # Which link of the resolution chain won — order-owned snapshots only.
+ t.string :source
+
+ t.timestamps
+ end
+
+ add_index :spree_tax_identifiers, [:customer_id, :kind]
+ end
+end
diff --git a/spree/core/lib/spree/testing_support/factories/tax_identifier_factory.rb b/spree/core/lib/spree/testing_support/factories/tax_identifier_factory.rb
new file mode 100644
index 0000000000..4dd7910950
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/tax_identifier_factory.rb
@@ -0,0 +1,26 @@
+FactoryBot.define do
+ factory :tax_identifier, class: Spree::TaxIdentifier do
+ customer
+ kind { 'eu_vat' }
+ sequence(:value) { |n| "DE#{123_456_780 + n}" }
+
+ trait :verified do
+ validation_status { 'verified' }
+ validated_at { Time.current }
+ validation_evidence { { 'registry' => 'vies', 'name' => 'Musterfirma GmbH' } }
+ end
+
+ # A number entered during checkout, overriding the customer's own.
+ trait :on_cart do
+ customer { nil }
+ cart
+ end
+
+ # The frozen snapshot taken when the order was placed.
+ trait :on_order do
+ customer { nil }
+ order
+ source { 'customer' }
+ end
+ end
+end
diff --git a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb
index 04d9f4f1e4..7a76450332 100644
--- a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb
+++ b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb
@@ -96,6 +96,37 @@ RSpec.shared_examples 'a taxation host' do
end
end
+ describe '#resolved_tax_identifier' do
+ let(:customer) { create(:user) }
+
+ before { record.update!(customer: customer) }
+
+ it 'treats a buyer with no registration as a consumer' do
+ expect(record.resolved_tax_identifier).to be_nil
+ end
+
+ it 'falls back to the customer registration' do
+ identifier = create(:tax_identifier, customer: customer)
+
+ expect(record.resolved_tax_identifier).to eq(identifier)
+ end
+
+ it 'prefers a verified registration over a newer unverified one' do
+ verified = create(:tax_identifier, :verified, customer: customer, kind: 'eu_vat')
+ create(:tax_identifier, customer: customer, kind: 'gb_vat')
+
+ expect(record.resolved_tax_identifier).to eq(verified)
+ end
+
+ it 'prefers the record own override over the customer registration' do
+ create(:tax_identifier, customer: customer)
+ owner_key = record.is_a?(Spree::Cart) ? :cart : :order
+ override = create(:tax_identifier, { customer: nil, kind: 'eu_vat', value: 'DE555555555', owner_key => record })
+
+ expect(record.resolved_tax_identifier).to eq(override)
+ end
+ end
+
describe '#pre_tax_item_amount / #pre_tax_total' do
it 'sums line item and fulfillment pre-tax amounts' do
create(:line_item, record.is_a?(Spree::Cart) ? { cart: record, order: nil } : { order: record }).update_column(:pre_tax_amount, 7)
@@ -117,5 +148,19 @@ RSpec.describe Spree::Purchase::Taxation do
let(:record) { create(:order, store: store, ship_address: ship_address, bill_address: bill_address) }
it_behaves_like 'a taxation host'
+
+ describe '#resolved_tax_identifier on a placed order' do
+ let(:customer) { create(:user) }
+ let(:record) { create(:completed_order_with_totals, customer: customer) }
+
+ it 'reads its own snapshot and never re-resolves' do
+ create(:tax_identifier, customer: customer)
+
+ expect(record.resolved_tax_identifier).to be_nil
+
+ snapshot = create(:tax_identifier, :on_order, order: record)
+ expect(record.reload.resolved_tax_identifier).to eq(snapshot)
+ end
+ end
end
end
diff --git a/spree/core/spec/models/spree/tax_identifier_spec.rb b/spree/core/spec/models/spree/tax_identifier_spec.rb
new file mode 100644
index 0000000000..f8dbf50d1b
--- /dev/null
+++ b/spree/core/spec/models/spree/tax_identifier_spec.rb
@@ -0,0 +1,51 @@
+require 'spec_helper'
+
+describe Spree::TaxIdentifier, type: :model do
+ let(:customer) { create(:user) }
+ let(:cart) { create(:cart, customer: customer) }
+ let(:order) { create(:order, customer: customer) }
+
+ it 'requires a kind and a value' do
+ expect(build(:tax_identifier)).to be_valid
+ expect(build(:tax_identifier, kind: nil)).not_to be_valid
+ expect(build(:tax_identifier, value: nil)).not_to be_valid
+ end
+
+ it 'belongs to exactly one owner' do
+ expect(build(:tax_identifier, customer: customer)).to be_valid
+ expect(build(:tax_identifier, customer: nil, cart: cart)).to be_valid
+
+ expect(build(:tax_identifier, customer: customer, cart: cart)).not_to be_valid
+ expect(build(:tax_identifier, customer: nil)).not_to be_valid
+ end
+
+ it 'rejects a validation status the platform never sets' do
+ expect(build(:tax_identifier, validation_status: 'verified')).to be_valid
+ expect(build(:tax_identifier, validation_status: nil)).to be_valid
+ expect(build(:tax_identifier, validation_status: 'probably_fine')).not_to be_valid
+ end
+
+ describe 'the order snapshot' do
+ it 'is immutable once written' do
+ snapshot = create(:tax_identifier, :on_order, order: order)
+
+ expect(snapshot).to be_readonly
+ expect { snapshot.update!(value: 'DE999999999') }.to raise_error(ActiveRecord::ReadOnlyRecord)
+ end
+
+ it 'is writable while unsaved' do
+ expect(build(:tax_identifier, :on_order, order: order)).not_to be_readonly
+ end
+ end
+
+ it 'is editable while owned by a customer or a cart' do
+ expect(create(:tax_identifier, customer: customer)).not_to be_readonly
+ expect(create(:tax_identifier, :on_cart, cart: cart)).not_to be_readonly
+ end
+
+ it 'hands a provider the kind and number only' do
+ identifier = create(:tax_identifier, :verified, customer: customer, kind: 'eu_vat', value: 'DE123456789')
+
+ expect(identifier.to_provider_params).to eq(kind: 'eu_vat', value: 'DE123456789')
+ end
+end
diff --git a/spree/core/spec/workflows/spree/carts/complete_spec.rb b/spree/core/spec/workflows/spree/carts/complete_spec.rb
index a9e10d5510..488c1b9aae 100644
--- a/spree/core/spec/workflows/spree/carts/complete_spec.rb
+++ b/spree/core/spec/workflows/spree/carts/complete_spec.rb
@@ -85,6 +85,39 @@ module Spree
end
end
+ describe 'tax identifier snapshot' do
+ let(:customer) { create(:user) }
+
+ before { ready_cart.update!(customer: customer) }
+
+ it 'freezes the customer registration onto the order' do
+ create(:tax_identifier, customer: customer, kind: 'eu_vat', value: 'DE123456789')
+
+ order = described_class.call(cart: ready_cart).value
+
+ snapshot = order.tax_identifier
+ expect(snapshot.value).to eq('DE123456789')
+ expect(snapshot.source).to eq('customer')
+ expect(snapshot).to be_readonly
+ end
+
+ it 'records a checkout override as such' do
+ create(:tax_identifier, customer: customer, kind: 'eu_vat', value: 'DE123456789')
+ create(:tax_identifier, customer: nil, cart: ready_cart, kind: 'eu_vat', value: 'DE999999999')
+
+ order = described_class.call(cart: ready_cart).value
+
+ expect(order.tax_identifier.value).to eq('DE999999999')
+ expect(order.tax_identifier.source).to eq('override')
+ end
+
+ it 'copies nothing for a consumer sale' do
+ order = described_class.call(cart: ready_cart).value
+
+ expect(order.tax_identifier).to be_nil
+ end
+ end
+
describe 'guest checkout policy' do
it 'fails when the channel forbids guest checkout and the cart has no customer' do
allow_any_instance_of(Spree::Cart).to receive(:guest_checkout_disallowed?).and_return(true)