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.

Ask the registry from a subscriber, not a model callback

Łukasz Adamczykb6960d76dcac
diff --git a/spree/core/app/models/spree/tax_identifier.rb b/spree/core/app/models/spree/tax_identifier.rb
index bd4b61b129..f8c7dc5de2 100644
--- a/spree/core/app/models/spree/tax_identifier.rb
+++ b/spree/core/app/models/spree/tax_identifier.rb
@@ -44,8 +44,18 @@ module Spree
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
- before_validation :normalize_value
- after_commit :async_validate, on: %i[create update]
+ # 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.
+ normalizes :value, with: ->(value) { value&.to_s&.gsub(/\s+/, '')&.upcase }
+
+ # The verdict resets as part of the write, not afterwards: the response to
+ # the request that changed the number has to say "we're checking this"
+ # rather than report a stale verdict or a blank one.
+ before_save :reset_validation_verdict, if: :number_changing?
+ after_commit :publish_number_changed, on: %i[create update]
validates :kind, :value, presence: true
# One per kind for a customer — what the storefront upsert assumes, and what
@@ -78,17 +88,6 @@ module Spree
validation_status == 'verified'
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.
@@ -100,15 +99,6 @@ module Spree
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,
@@ -122,11 +112,22 @@ module Spree
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'))
+ def number_changing?
+ validatable? && (will_save_change_to_value? || will_save_change_to_kind?)
+ end
+
+ def reset_validation_verdict
+ self.validation_status = 'pending'
+ self.validated_at = nil
+ end
+
+ # Announces the fact; Spree::TaxIdentifierValidationSubscriber decides what
+ # to do about it. Published only when the number itself changed, so the
+ # verdict the check writes back cannot trigger another check.
+ def publish_number_changed
+ return unless saved_changes.key?('value') || saved_changes.key?('kind')
+
+ publish_event('tax_identifier.number_changed')
end
def exactly_one_owner
diff --git a/spree/core/app/subscribers/spree/tax_identifier_validation_subscriber.rb b/spree/core/app/subscribers/spree/tax_identifier_validation_subscriber.rb
new file mode 100644
index 0000000000..d70e2af0f3
--- /dev/null
+++ b/spree/core/app/subscribers/spree/tax_identifier_validation_subscriber.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module Spree
+ # Asks the registry whether a buyer's tax number is real, whenever that number
+ # changes.
+ #
+ # Runs synchronously: the row has to read +pending+ in the same request that
+ # wrote it, so the buyer sees "we're checking this" rather than a blank verdict
+ # that fills in later. The check itself is the background job.
+ class TaxIdentifierValidationSubscriber < Spree::Subscriber
+ subscribes_to 'tax_identifier.number_changed', async: false
+
+ def call(event)
+ identifier = Spree::TaxIdentifier.find_by_prefix_id(event.payload['id'])
+ return if identifier.nil?
+
+ # Nothing to ask when no validator is registered for this kind — a stock
+ # install registers none — and an order's snapshot is never re-checked.
+ return unless identifier.validatable?
+
+ # The row is already marked pending by the write that published this;
+ # queueing the registry call is all that is left.
+ Spree::TaxIdentifiers::ValidateJob.perform_later(identifier.id)
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 9296cfa15f..ed524def7b 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -472,7 +472,8 @@ module Spree
Spree::ReportSubscriber,
Spree::InvitationEmailSubscriber,
Spree::AdminUserEmailSubscriber,
- Spree::ProductMetricsSubscriber
+ Spree::ProductMetricsSubscriber,
+ Spree::TaxIdentifierValidationSubscriber
]
# Pre-load authentication strategy classes to avoid reflection at request time
diff --git a/spree/core/spec/models/spree/tax_identifier_spec.rb b/spree/core/spec/models/spree/tax_identifier_spec.rb
index b9383faffd..68293643c5 100644
--- a/spree/core/spec/models/spree/tax_identifier_spec.rb
+++ b/spree/core/spec/models/spree/tax_identifier_spec.rb
@@ -89,7 +89,9 @@ describe Spree::TaxIdentifier, type: :model do
end
end
- describe 'the registry check' do
+ # The check now runs from Spree::TaxIdentifierValidationSubscriber, so these
+ # need the event bus the suite disables by default.
+ describe 'the registry check', events: true do
around do |example|
Spree.tax_identifier_validators['eu_vat'] = 'Spree::TaxIdentifiers::Validator::Base'
example.run
@@ -118,6 +120,26 @@ describe Spree::TaxIdentifier, type: :model do
expect { identifier.update!(value: 'DE987654321') }.to have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)
end
+ # The stamp is part of the write, not the subscriber's doing: the response to
+ # the request that changed the number must not report a stale verdict, and it
+ # must hold even where the event bus is switched off.
+ it 'marks the row pending on the object that was saved, without reloading' do
+ identifier = Spree::Events.disable { create(:tax_identifier, customer: customer, kind: 'eu_vat') }
+
+ expect(identifier.validation_status).to eq('pending')
+ expect(identifier.validated_at).to be_nil
+ end
+
+ it 'clears an earlier verdict when the number changes' do
+ identifier = create(:tax_identifier, customer: customer, kind: 'eu_vat')
+ identifier.update_columns(validation_status: 'verified', validated_at: Time.current)
+
+ identifier.update!(value: 'DE987654321')
+
+ expect(identifier.validation_status).to eq('pending')
+ expect(identifier.validated_at).to be_nil
+ 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)
diff --git a/spree/core/spec/subscribers/spree/tax_identifier_validation_subscriber_spec.rb b/spree/core/spec/subscribers/spree/tax_identifier_validation_subscriber_spec.rb
new file mode 100644
index 0000000000..d7cd70644c
--- /dev/null
+++ b/spree/core/spec/subscribers/spree/tax_identifier_validation_subscriber_spec.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+require 'spec_helper'
+
+RSpec.describe Spree::TaxIdentifierValidationSubscriber do
+ include ActiveJob::TestHelper
+
+ let(:store) { @default_store }
+ let(:customer) { create(:customer) }
+
+ around do |example|
+ Spree.tax_identifier_validators['eu_vat'] = 'Spree::TaxIdentifiers::Validator::Base'
+ example.run
+ ensure
+ Spree.tax_identifier_validators.delete('eu_vat')
+ end
+
+ describe '.subscription_patterns' do
+ it 'subscribes to the number-changed event' do
+ expect(described_class.subscription_patterns).to include('tax_identifier.number_changed')
+ end
+ end
+
+ describe '#call' do
+ let(:identifier) { create(:tax_identifier, customer: customer, kind: 'eu_vat') }
+ let(:event) { Spree::Event.new(name: 'tax_identifier.number_changed', payload: { 'id' => identifier.prefixed_id }) }
+
+ it 'queues the registry check' do
+ expect { described_class.new.call(event) }.to have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)
+ end
+
+ it 'does nothing for a kind nothing here can check' do
+ identifier.update_columns(kind: 'au_abn')
+
+ expect { described_class.new.call(event) }.not_to have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)
+ end
+
+ # A placed order's number is a snapshot: re-checking it could contradict
+ # what the order was taxed under.
+ it 'does nothing for an order snapshot' do
+ snapshot = create(:tax_identifier, :on_order, order: create(:order, store: store), kind: 'eu_vat')
+ snapshot_event = Spree::Event.new(name: 'tax_identifier.number_changed', payload: { 'id' => snapshot.prefixed_id })
+
+ expect { described_class.new.call(snapshot_event) }.not_to have_enqueued_job(Spree::TaxIdentifiers::ValidateJob)
+ end
+
+ it 'ignores a row deleted between publish and handling' do
+ missing = Spree::Event.new(name: 'tax_identifier.number_changed', payload: { 'id' => 'txi_missing' })
+
+ expect { described_class.new.call(missing) }.not_to raise_error
+ end
+ end
+end