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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Phase 7: check tax registrations where the knowledge lives
Łukasz Adamczyk21a6fed35f04
diff --git a/spree/core/app/jobs/spree/tax_identifiers/validate_job.rb b/spree/core/app/jobs/spree/tax_identifiers/validate_job.rbnew file mode 100644index 0000000000..0bb90de458--- /dev/null+++ b/spree/core/app/jobs/spree/tax_identifiers/validate_job.rb@@ -0,0 +1,14 @@+module Spree+ module TaxIdentifiers+ class ValidateJob < BaseJob+ queue_as Spree.queues.tax_identifiers++ def perform(tax_identifier_id)+ tax_identifier = Spree::TaxIdentifier.find_by(id: tax_identifier_id)+ return if tax_identifier.nil?++ Spree::TaxIdentifiers::Validate.call(tax_identifier: tax_identifier)+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/tax_id_validator/base.rb b/spree/core/app/models/spree/tax_id_validator/base.rbnew file mode 100644index 0000000000..946cf3fdfd--- /dev/null+++ b/spree/core/app/models/spree/tax_id_validator/base.rb@@ -0,0 +1,40 @@+module Spree+ module TaxIdValidator+ # Contract for checking a buyer's tax registration. Registered per kind in+ # {Spree.tax_id_validators}, because whether a number is well-formed and+ # whether it is really registered are questions for the jurisdiction that+ # issued it — not for the market's tax engine.+ #+ # Two halves, deliberately split by cost: the format check is synchronous,+ # offline and cheap enough to run on every save; the registry check makes a+ # network call and runs in a job.+ class Base+ # Whether the value looks like a number of this kind. Called on save, so+ # it must not touch the network.+ #+ # Permissive by default: a validator that only knows how to talk to a+ # registry accepts anything core allowed through.+ #+ # @param value [String] already normalized (whitespace stripped, upcased)+ # @return [Boolean]+ def self.valid_format?(_value)+ true+ end++ # Asks the registry whether the number is registered. Runs in+ # {Spree::TaxIdentifiers::ValidateJob}.+ #+ # A registry that cannot answer must return an +unavailable+ result rather+ # than raise: the number stays usable and the platform records that nobody+ # could answer.+ #+ # @param tax_identifier [Spree::TaxIdentifier] carries the kind, the value+ # and its owner — reach the store through the owner when the registry+ # needs credentials+ # @return [Spree::TaxIdentifier::ValidationResult]+ def call(tax_identifier:)+ raise NotImplementedError, "Please implement 'call' in your tax ID validator: #{self.class.name}"+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/tax_identifier.rb b/spree/core/app/models/spree/tax_identifier.rbindex 0716cbb60a..de0c5d042e 100644--- a/spree/core/app/models/spree/tax_identifier.rb+++ b/spree/core/app/models/spree/tax_identifier.rb@@ -26,10 +26,16 @@ module Spreebelongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :tax_identifierbelongs_to :order, class_name: 'Spree::Order', optional: true, inverse_of: :tax_identifier+ before_validation :normalize_value+ after_commit :async_validate, on: %i[create update]+validates :kind, :value, presence: true+ # Data hygiene, not a format claim — no tax regime issues numbers this long.+ validates :value, length: { maximum: 64 }validates :validation_status, inclusion: { in: VALIDATION_STATUSES }, allow_nil: truevalidates :source, inclusion: { in: SOURCES }, allow_nil: truevalidate :exactly_one_owner+ validate :value_formatscope :for_kind, ->(kind) { where(kind: kind) }scope :verified, -> { where(validation_status: 'verified') }@@ -57,8 +63,57 @@ module Spree{ kind: kind, value: value }end+ # Queues the registry check. Public for the same reason+ # {Spree::Address#async_geocode} is: an admin re-validate action calls it.+ def async_validate+ return unless should_validate?++ # update_columns, not update — this runs inside after_commit, and the+ # verdict columns are never the buyer's input.+ update_columns(validation_status: 'pending', validated_at: nil, updated_at: Time.current)+ Spree::TaxIdentifiers::ValidateJob.perform_later(id)+ end++ # Whether this installation can check a number of this kind at all. What+ # tells the admin apart the two reasons a row has no verdict: not attempted+ # yet, or nothing here knows how to ask.+ #+ # @return [Boolean]+ def validatable?+ order_id.nil? && Spree.tax_id_validators.key?(kind)+ end+private+ # Whitespace and case only. Punctuation is deliberately kept: for several+ # kinds it is part of the canonical number (Switzerland's CHE-123.456.789+ # MWST, Canada's PST-1234-5678), and the buyer's own spelling is what they+ # will recognise on an invoice. A validator needing a different wire format+ # produces it itself.+ def normalize_value+ self.value = value&.gsub(/\s+/, '')&.upcase+ end++ # Format knowledge lives entirely in the registered validator. Core asserts+ # nothing about the shape of a number whose rules live in someone else's+ # statute book: a rule spanning every tax regime on earth would be a guess,+ # and its failure mode is turning away a real business customer. Kinds with+ # no validator are accepted as entered.+ def value_format+ validator = Spree.tax_id_validators[kind]+ return if validator.blank?+ return if validator.to_s.constantize.valid_format?(value)++ errors.add(:value, :invalid)+ end++ # Mirrors Address#should_geocode? — only when the number itself changed,+ # never for an order snapshot, and only when a validator exists. A stock+ # install registers none, so it never enqueues a job with nothing to do.+ def should_validate?+ validatable? && (saved_changes.key?('value') || saved_changes.key?('kind'))+ end+def exactly_one_ownerreturn if [customer, cart, order].compact.one?diff --git a/spree/core/app/models/spree/tax_identifier/validation_result.rb b/spree/core/app/models/spree/tax_identifier/validation_result.rbnew file mode 100644index 0000000000..1d96eed523--- /dev/null+++ b/spree/core/app/models/spree/tax_identifier/validation_result.rb@@ -0,0 +1,41 @@+module Spree+ class TaxIdentifier+ # What a validator reports back about a registration. Ephemeral: the+ # validation service is what writes it onto the row.+ class ValidationResult+ include ActiveModel::Model+ include ActiveModel::Attributes++ STATUSES = %w[verified unverified unavailable unsupported].freeze++ attribute :status, :string+ # The registry's canonical form of the number, when it reports one. Never+ # written over the entered value — the buyer's own spelling is what they+ # will recognise on an invoice.+ attribute :normalized_value, :string+ attribute :message, :string+ attribute :checked_at, :datetime++ # What was asked and what came back — the registry only ever answers+ # "valid now", so this is the only proof a past sale will have.+ attribute :evidence, default: -> { {} }++ validates :status, inclusion: { in: STATUSES }++ def verified?+ status == 'verified'+ end++ # @return [Hash] the columns {Spree::TaxIdentifiers::Validate} persists+ def to_columns+ {+ validation_status: status,+ validated_at: checked_at || Time.current,+ validation_evidence: evidence.to_h.merge(+ { 'message' => message, 'normalized_value' => normalized_value }.compact+ )+ }+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/tax_identifiers/validate.rb b/spree/core/app/services/spree/tax_identifiers/validate.rbnew file mode 100644index 0000000000..b037d275e1--- /dev/null+++ b/spree/core/app/services/spree/tax_identifiers/validate.rb@@ -0,0 +1,47 @@+module Spree+ module TaxIdentifiers+ class ValidationError < StandardError; end++ # The only writer of the validation columns. Writes with +update_columns+ so+ # recording a verdict cannot re-trigger the callback that asked for it.+ class Validate+ prepend Spree::ServiceModule::Base++ # @param tax_identifier [Spree::TaxIdentifier]+ # @return [Spree::TaxIdentifier]+ def call(tax_identifier:)+ validator = Spree.tax_id_validators[tax_identifier.kind]++ # Narrow race: the validator was deregistered between enqueue and run.+ return persist(tax_identifier, unsupported_result) if validator.blank?++ result = validator.to_s.constantize.new.call(tax_identifier: tax_identifier)+ persist(tax_identifier, result)+ rescue StandardError => error+ # A validator that fails unexpectedly leaves the previous verdict+ # standing — a number nobody could check is not a number known to be+ # wrong. Reported rather than raised, as a failed geocode is.+ Rails.error.report(+ ValidationError.new("Cannot validate tax identifier ID: #{tax_identifier.id} (#{error.message})"),+ handled: false,+ context: { tax_identifier_id: tax_identifier.id, kind: tax_identifier.kind },+ source: 'spree.core'+ )+ failure(tax_identifier, error.message)+ end++ private++ def persist(tax_identifier, result)+ return failure(tax_identifier, result.errors.full_messages.to_sentence) unless result.valid?++ tax_identifier.update_columns(result.to_columns.merge(updated_at: Time.current))+ success(tax_identifier)+ end++ def unsupported_result+ Spree::TaxIdentifier::ValidationResult.new(status: 'unsupported', checked_at: Time.current)+ end+ end+ end+enddiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 4310eea92b..360de3eecb 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -129,7 +129,8 @@ module Spreepayment_webhooks: :default,api_keys: :default,search: :default,- stock_reservations: :default+ stock_reservations: :default,+ tax_identifiers: :default).tap do |queues|# @deprecated The taxons queue was renamed to categories in 6.0; removed in 6.1.queues.define_singleton_method(:taxons) do@@ -151,6 +152,22 @@ module Spree@@search_provider = value.to_send+ # Tax ID validators, keyed by registration kind. Empty by default: core ships+ # no registry client, because VAT number rules live in 27 different statute+ # books and a guess would reject real business customers.+ #+ # Spree.tax_id_validators['eu_vat'] = 'SpreeEuVat::TaxIdValidator'+ #+ # Class names are stored as strings and constantized at call time, so an+ # initializer can register a validator before its class is autoloaded.+ # Whether a kind has a validator is also what tells the admin apart the two+ # reasons a registration has no verdict: unchecked, or uncheckable here.+ #+ # @return [Hash{String => String}]+ def self.tax_id_validators+ @@tax_id_validators ||= {}+ end+# Returns the events adapter class used for publishing and subscribing to events.## @example Using a custom adapterdiff --git a/spree/core/spec/jobs/spree/tax_identifiers/validate_job_spec.rb b/spree/core/spec/jobs/spree/tax_identifiers/validate_job_spec.rbnew file mode 100644index 0000000000..182493e675--- /dev/null+++ b/spree/core/spec/jobs/spree/tax_identifiers/validate_job_spec.rb@@ -0,0 +1,34 @@+require 'spec_helper'++describe Spree::TaxIdentifiers::ValidateJob do+ let(:customer) { create(:user) }+ let(:tax_identifier) { create(:tax_identifier, customer: customer, kind: 'eu_vat') }++ before do+ stub_const('SpecJobValidator', Class.new(Spree::TaxIdValidator::Base) do+ def call(tax_identifier:)+ Spree::TaxIdentifier::ValidationResult.new(status: 'verified', checked_at: Time.current)+ end+ end)+ Spree.tax_id_validators['eu_vat'] = 'SpecJobValidator'+ end++ after { Spree.tax_id_validators.delete('eu_vat') }++ it 'records the registry verdict on the row' do+ described_class.perform_now(tax_identifier.id)++ expect(tax_identifier.reload.validation_status).to eq('verified')+ end++ it 'runs on its own queue' do+ expect(described_class.new.queue_name).to eq(Spree.queues.tax_identifiers.to_s)+ end++ it 'does nothing when the row was deleted before the job ran' do+ id = tax_identifier.id+ tax_identifier.destroy!++ expect { described_class.perform_now(id) }.not_to raise_error+ end+enddiff --git a/spree/core/spec/models/spree/tax_identifier_spec.rb b/spree/core/spec/models/spree/tax_identifier_spec.rbindex f8dbf50d1b..201f28af47 100644--- a/spree/core/spec/models/spree/tax_identifier_spec.rb+++ b/spree/core/spec/models/spree/tax_identifier_spec.rb@@ -43,6 +43,107 @@ describe Spree::TaxIdentifier, type: :model doexpect(create(:tax_identifier, :on_cart, cart: cart)).not_to be_readonlyend+ describe 'normalization' do+ it 'strips whitespace and upcases, keeping punctuation' do+ identifier = create(:tax_identifier, customer: customer, kind: 'ch_vat', value: ' che-123.456.789 mwst ')++ expect(identifier.value).to eq('CHE-123.456.789MWST')+ end++ it 'rejects a number longer than any real registration' do+ expect(build(:tax_identifier, value: 'D' * 65)).not_to be_valid+ end+ end++ describe 'format validation' do+ let(:validator) do+ Class.new(Spree::TaxIdValidator::Base) do+ def self.valid_format?(value)+ value.start_with?('DE')+ end+ end+ end++ before { stub_const('SpecEuVatValidator', validator) }++ around do |example|+ Spree.tax_id_validators['eu_vat'] = 'SpecEuVatValidator'+ example.run+ ensure+ Spree.tax_id_validators.delete('eu_vat')+ end++ it 'rejects a malformed number as a typo to fix' do+ identifier = build(:tax_identifier, customer: customer, kind: 'eu_vat', value: '123456789')++ expect(identifier).not_to be_valid+ expect(identifier.errors[:value]).to be_present+ end++ it 'accepts a well-formed one' do+ expect(build(:tax_identifier, customer: customer, kind: 'eu_vat', value: 'DE123456789')).to be_valid+ end++ it 'accepts any number for a kind nothing here can check' do+ expect(build(:tax_identifier, customer: customer, kind: 'au_abn', value: 'anything')).to be_valid+ end+ end++ describe 'the registry check' do+ around do |example|+ Spree.tax_id_validators['eu_vat'] = 'Spree::TaxIdValidator::Base'+ example.run+ ensure+ Spree.tax_id_validators.delete('eu_vat')+ end++ it 'is queued when a checkable number is entered, and marked pending' do+ identifier = nil++ expect { identifier = create(:tax_identifier, customer: customer, kind: 'eu_vat') }.to(+ have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)+ )+ expect(identifier.reload.validation_status).to eq('pending')+ end++ it 'is not queued again when something else on the row changes' do+ identifier = create(:tax_identifier, customer: customer, kind: 'eu_vat')++ expect { identifier.update!(source: nil) }.not_to have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)+ end++ it 'is queued again when the number changes' do+ identifier = create(:tax_identifier, customer: customer, kind: 'eu_vat')++ expect { identifier.update!(value: 'DE987654321') }.to have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)+ end++ it 'is skipped for a kind nothing here can check' do+ expect { create(:tax_identifier, customer: customer, kind: 'au_abn') }.not_to(+ have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)+ )+ expect(described_class.last.validation_status).to be_nil+ end++ it 'is skipped for an order snapshot, frozen by definition' do+ expect { create(:tax_identifier, :on_order, order: order, kind: 'eu_vat') }.not_to(+ have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)+ )+ end+ end++ describe '#validatable?' do+ it 'reports whether this installation can check the kind' do+ identifier = create(:tax_identifier, customer: customer, kind: 'eu_vat')+ expect(identifier).not_to be_validatable++ Spree.tax_id_validators['eu_vat'] = 'Spree::TaxIdValidator::Base'+ expect(identifier).to be_validatable+ ensure+ Spree.tax_id_validators.delete('eu_vat')+ end+ end+it 'hands a provider the kind and number only' doidentifier = create(:tax_identifier, :verified, customer: customer, kind: 'eu_vat', value: 'DE123456789')diff --git a/spree/core/spec/services/spree/tax_identifiers/validate_spec.rb b/spree/core/spec/services/spree/tax_identifiers/validate_spec.rbnew file mode 100644index 0000000000..1fd0eb88df--- /dev/null+++ b/spree/core/spec/services/spree/tax_identifiers/validate_spec.rb@@ -0,0 +1,102 @@+require 'spec_helper'++describe Spree::TaxIdentifiers::Validate do+ let(:customer) { create(:user) }+ let(:tax_identifier) { create(:tax_identifier, customer: customer, kind: 'eu_vat', value: 'DE123456789') }++ def register(validator_class)+ stub_const('SpecRegistryValidator', validator_class)+ Spree.tax_id_validators['eu_vat'] = 'SpecRegistryValidator'+ end++ after { Spree.tax_id_validators.delete('eu_vat') }++ context 'when the registry answers' do+ before do+ register(Class.new(Spree::TaxIdValidator::Base) do+ def call(tax_identifier:)+ Spree::TaxIdentifier::ValidationResult.new(+ status: 'verified',+ normalized_value: tax_identifier.value,+ checked_at: Time.current,+ evidence: { 'registry' => 'spec_vies', 'consultation_number' => 'WAPI-1' }+ )+ end+ end)+ end++ it 'records the verdict and the evidence behind it' do+ described_class.call(tax_identifier: tax_identifier)++ tax_identifier.reload+ expect(tax_identifier.validation_status).to eq('verified')+ expect(tax_identifier).to be_verified+ expect(tax_identifier.validated_at).to be_present+ expect(tax_identifier.validation_evidence['consultation_number']).to eq('WAPI-1')+ end++ it 'leaves the number as the buyer entered it' do+ described_class.call(tax_identifier: tax_identifier)++ expect(tax_identifier.reload.value).to eq('DE123456789')+ end++ it 'does not queue itself again' do+ tax_identifier # created (and queued) before the block, so only the write is measured+ clear_enqueued_jobs++ expect { described_class.call(tax_identifier: tax_identifier) }.not_to(+ have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)+ )+ end+ end++ context 'when the registry cannot answer' do+ before do+ register(Class.new(Spree::TaxIdValidator::Base) do+ def call(tax_identifier:)+ Spree::TaxIdentifier::ValidationResult.new(status: 'unavailable', message: 'VIES timed out',+ checked_at: Time.current)+ end+ end)+ end++ it 'records that nobody could answer, leaving the number usable' do+ described_class.call(tax_identifier: tax_identifier)++ tax_identifier.reload+ expect(tax_identifier.validation_status).to eq('unavailable')+ expect(tax_identifier.validation_evidence['message']).to eq('VIES timed out')+ end+ end++ context 'when the validator disappeared between enqueue and run' do+ it 'records unsupported' do+ described_class.call(tax_identifier: tax_identifier)++ expect(tax_identifier.reload.validation_status).to eq('unsupported')+ end+ end++ context 'when the validator raises' do+ before do+ register(Class.new(Spree::TaxIdValidator::Base) do+ def call(tax_identifier:)+ raise 'boom'+ end+ end)+ tax_identifier.update_columns(validation_status: 'verified')+ end++ it 'reports the failure and keeps the previous verdict' do+ expect(Rails.error).to receive(:report).with(+ instance_of(Spree::TaxIdentifiers::ValidationError), hash_including(:context)+ )++ result = described_class.call(tax_identifier: tax_identifier)++ expect(result).to be_failure+ expect(tax_identifier.reload.validation_status).to eq('verified')+ end+ end+end