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.

Fix defects found reviewing the tax provider work

Łukasz Adamczykaf0da7f30001
diff --git a/spree/api/spec/serializers/spree/api/v3/delivery_rate_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/delivery_rate_serializer_spec.rb
index b9e0b698f8..138823bb7a 100644
--- a/spree/api/spec/serializers/spree/api/v3/delivery_rate_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/delivery_rate_serializer_spec.rb
@@ -55,8 +55,7 @@ RSpec.describe Spree::Api::V3::DeliveryRateSerializer do
end
context 'with included tax' do
- let!(:default_zone) { create(:zone, default_tax: true) }
- let(:tax_rate) { create(:tax_rate, amount: 0.1, included_in_price: true, zone: default_zone) }
+ let(:tax_rate) { create(:tax_rate, amount: 0.1, included_in_price: true, country: @default_country) }
before { shipping_rate.update!(tax_rate: tax_rate) }
diff --git a/spree/core/app/models/concerns/spree/purchase/taxation.rb b/spree/core/app/models/concerns/spree/purchase/taxation.rb
index eb0d729f38..4557dbe93c 100644
--- a/spree/core/app/models/concerns/spree/purchase/taxation.rb
+++ b/spree/core/app/models/concerns/spree/purchase/taxation.rb
@@ -33,6 +33,21 @@ module Spree
market&.tax_provider_instance || Spree.tax_provider
end
+ # The typed inputs every +estimate+ call carries. Assembled here rather
+ # than at each call site so a single-item re-estimate reaches the provider
+ # with the same buyer registration and exemption evidence as a full
+ # recalculation — the provider replaces the item's rows either way, so a
+ # partial call missing them would silently re-tax an exempt line.
+ #
+ # @return [Hash]
+ def tax_estimate_inputs
+ {
+ tax_date: Time.current,
+ tax_identifier: resolved_tax_identifier,
+ exemptions: Spree.tax_resolve_exemptions_service.new.call(order: self).value
+ }
+ 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
diff --git a/spree/core/app/models/concerns/spree/vat_price_calculation.rb b/spree/core/app/models/concerns/spree/vat_price_calculation.rb
index 15268d18d9..dc254979a9 100644
--- a/spree/core/app/models/concerns/spree/vat_price_calculation.rb
+++ b/spree/core/app/models/concerns/spree/vat_price_calculation.rb
@@ -40,11 +40,14 @@ module Spree
end
def included_tax_amount(price_options)
- country = price_options[:country] || country_from(price_options)
-
- Spree::TaxRate.included_tax_amount_for(
- country: country, tax_category: price_options[:tax_category]
- ).to_f
+ lookup = { tax_category: price_options[:tax_category] }
+ if price_options[:address]
+ lookup[:address] = price_options[:address]
+ else
+ lookup[:country] = price_options[:country] || country_from(price_options)
+ end
+
+ Spree::TaxRate.included_tax_amount_for(lookup).to_f
end
def country_from(price_options)
@@ -57,12 +60,14 @@ module Spree
zone&.countries&.first
end
- # The country whose VAT the catalogue prices already include — the market
- # being browsed, or the store's own country when there is no market.
+ # The country whose VAT the catalogue prices already include. Deliberately
+ # the store's own country and NOT Spree::Current.market, which follows the
+ # buyer: reading the destination here would make every sale look domestic
+ # and the restatement would never fire.
def default_tax_country
return @default_tax_country if defined?(@default_tax_country)
- @default_tax_country = Spree::Current.market&.default_country || Spree::Current.store&.default_country
+ @default_tax_country = Spree::Current.store&.default_country
end
def round_to_two_places(amount)
diff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rb
index 728742096c..7fe158f6a2 100644
--- a/spree/core/app/models/spree/line_item.rb
+++ b/spree/core/app/models/spree/line_item.rb
@@ -389,7 +389,7 @@ module Spree
def update_tax_charge
return unless owner
- owner.tax_provider.estimate(owner, [self], tax_date: Time.current)
+ owner.tax_provider.estimate(owner, [self], **owner.tax_estimate_inputs)
end
def ensure_proper_currency
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 904f5b7bc2..8afb1ad8fc 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -176,7 +176,9 @@ 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
+ # delete, not destroy: the snapshot is readonly once written, and destroy
+ # refuses readonly records. It has no dependents of its own.
+ has_one :tax_identifier, class_name: 'Spree::TaxIdentifier', dependent: :delete, 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
@@ -519,11 +521,11 @@ module Spree
# Re-estimates tax through the configured provider (writes TaxLine rows
# with replace-all semantics).
def create_tax_charge!
- tax_provider.estimate(self, tax_date: Time.current)
+ tax_provider.estimate(self, **tax_estimate_inputs)
end
def create_shipment_tax_charge!
- tax_provider.estimate(self, fulfillments.to_a, tax_date: Time.current) if fulfillments.any?
+ tax_provider.estimate(self, fulfillments.to_a, **tax_estimate_inputs) if fulfillments.any?
end
def update_line_item_prices!
diff --git a/spree/core/app/models/spree/stock/estimator.rb b/spree/core/app/models/spree/stock/estimator.rb
index ab2c13ff90..a284be0def 100644
--- a/spree/core/app/models/spree/stock/estimator.rb
+++ b/spree/core/app/models/spree/stock/estimator.rb
@@ -65,7 +65,9 @@ module Spree
def first_tax_rate_for(tax_category)
return unless @order.tax_address && tax_category
- Spree::TaxRate.for_tax_category(tax_category).for_address(@order.tax_address).first
+ scope = Spree::TaxRate.for_tax_category(tax_category).for_address(@order.tax_address)
+ scope = scope.for_store(@order.store) if @order.store
+ scope.first
end
# The eligibility seam: every rate consumer (checkout, routing, cart
diff --git a/spree/core/app/models/spree/tax_identifier.rb b/spree/core/app/models/spree/tax_identifier.rb
index de0c5d042e..51c34bfcb1 100644
--- a/spree/core/app/models/spree/tax_identifier.rb
+++ b/spree/core/app/models/spree/tax_identifier.rb
@@ -11,8 +11,6 @@ module Spree
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.
@@ -30,6 +28,10 @@ module Spree
after_commit :async_validate, on: %i[create update]
validates :kind, :value, presence: true
+ # One per kind for a customer — what the storefront upsert assumes, and what
+ # makes resolution deterministic. Cart and order rows are singular by their
+ # own associations.
+ validates :kind, uniqueness: { scope: :customer_id }, if: -> { customer_id.present? }
# 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: true
diff --git a/spree/core/app/models/spree/tax_provider/base.rb b/spree/core/app/models/spree/tax_provider/base.rb
index 22328e5a24..10b2cefb42 100644
--- a/spree/core/app/models/spree/tax_provider/base.rb
+++ b/spree/core/app/models/spree/tax_provider/base.rb
@@ -64,7 +64,7 @@ module Spree
# original transaction rather than voiding and re-committing it.
#
# @param order [Spree::Order]
- # @param return_items [Array<Spree::ReturnItem>]
+ # @param return_items [Array<Spree::ReturnLineItem>] the returned lines
# @param tax_date [Time, nil] the original supply date; nil = order.completed_at
# @return [void]
def refund(order, return_items, tax_date: nil); end
diff --git a/spree/core/app/models/spree/tax_provider/internal.rb b/spree/core/app/models/spree/tax_provider/internal.rb
index 5cda3a7d1f..6c5f947fce 100644
--- a/spree/core/app/models/spree/tax_provider/internal.rb
+++ b/spree/core/app/models/spree/tax_provider/internal.rb
@@ -31,7 +31,7 @@ module Spree
end
items.each do |item|
- relevant_rates = rates.select { |rate| rate.tax_category_id == tax_category_id_for(item) }
+ relevant_rates = rates.select { |rate| rate.tax_category_id == tax_category_id_for(item, owner) }
# A matched rate always produces a row, zero-amount ones included:
# a zero rate is a treatment ("this is zero-rated"), which reporting
@@ -70,18 +70,21 @@ module Spree
end
end
- def tax_category_id_for(item)
+ def tax_category_id_for(item, owner)
if item.respond_to?(:tax_category_id) && item.tax_category_id
item.tax_category_id
else
- default_tax_category&.id
+ default_tax_category(owner)&.id
end
end
- def default_tax_category
+ # The owner's store's default, not any store's: defaults are per store
+ # since 6.0, and a foreign category id would match none of this store's
+ # rates, silently leaving the item untaxed.
+ def default_tax_category(owner)
return @default_tax_category if defined?(@default_tax_category)
- @default_tax_category = Spree::TaxCategory.find_by(is_default: true)
+ @default_tax_category = Spree::TaxCategory.default(owner.store)
end
def taxable_basis(item)
diff --git a/spree/core/app/models/spree/tax_rate.rb b/spree/core/app/models/spree/tax_rate.rb
index 4de2bffa0f..7415c02118 100644
--- a/spree/core/app/models/spree/tax_rate.rb
+++ b/spree/core/app/models/spree/tax_rate.rb
@@ -33,6 +33,7 @@ module Spree
validates :tax_category, :name
end
+ before_validation :resolve_state_code
validate :state_belongs_to_country
# Rates that reach the given address: its own country and state, plus the
@@ -71,10 +72,11 @@ module Spree
self.country = value.present? ? Spree::Country.by_iso(value) : nil
end
- # Looked up within the rate's own country, so assign the country first —
- # state abbreviations repeat across countries.
+ # Resolved in a callback rather than here: state abbreviations repeat across
+ # countries, so the lookup needs the country — and a JSON body can name the
+ # state before the country.
def state_code=(value)
- self.state = value.blank? ? nil : Spree::State.where(country_id: country_id).find_by(abbr: value)
+ @state_code_input = value
end
# The rates that tax a sale delivered to this address.
@@ -96,6 +98,10 @@ module Spree
return 0 unless country && options[:tax_category]
scope = options[:address] ? for_address(options[:address]) : for_country(country)
+ # Per-store tax configuration is the norm since 6.0, so without this the
+ # sum would add up every store's rate for the same country.
+ store = options[:store] || Spree::Current.store
+ scope = scope.for_store(store) if store
scope.included_in_price.for_tax_category(options[:tax_category]).sum(:amount)
end
@@ -119,6 +125,13 @@ module Spree
private
+ def resolve_state_code
+ return unless defined?(@state_code_input)
+
+ self.state = @state_code_input.blank? ? nil : Spree::State.where(country_id: country_id).find_by(abbr: @state_code_input)
+ remove_instance_variable(:@state_code_input)
+ end
+
# A state-level rate whose state sits in another country would never match
# any address — the two columns have to agree.
def state_belongs_to_country
diff --git a/spree/core/app/models/spree/zone.rb b/spree/core/app/models/spree/zone.rb
index 08e1fd559c..53bab7d2af 100644
--- a/spree/core/app/models/spree/zone.rb
+++ b/spree/core/app/models/spree/zone.rb
@@ -4,10 +4,9 @@ module Spree
include Spree::UniqueName
- with_options dependent: :destroy, inverse_of: :zone do
- has_many :zone_members, class_name: 'Spree::ZoneMember'
- has_many :tax_rates
- end
+ # Tax rates named their zone until 6.0; they carry their own country and
+ # state now, so a zone owns nothing tax-side.
+ has_many :zone_members, class_name: 'Spree::ZoneMember', dependent: :destroy, inverse_of: :zone
with_options through: :zone_members, source: :zoneable do
has_many :countries, source_type: 'Spree::Country'
has_many :states, source_type: 'Spree::State'
diff --git a/spree/core/app/services/spree/tax_identifiers/validate.rb b/spree/core/app/services/spree/tax_identifiers/validate.rb
index b037d275e1..31f9ef3916 100644
--- a/spree/core/app/services/spree/tax_identifiers/validate.rb
+++ b/spree/core/app/services/spree/tax_identifiers/validate.rb
@@ -18,15 +18,17 @@ module Spree
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.
+ # A number nobody could check is not a number known to be wrong, so it
+ # is recorded as unanswered rather than rejected — and recorded rather
+ # than left on the `pending` the enqueue stamped. 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'
)
+ persist(tax_identifier, unavailable_result(error.message))
failure(tax_identifier, error.message)
end
@@ -42,6 +44,10 @@ module Spree
def unsupported_result
Spree::TaxIdentifier::ValidationResult.new(status: 'unsupported', checked_at: Time.current)
end
+
+ def unavailable_result(message)
+ Spree::TaxIdentifier::ValidationResult.new(status: 'unavailable', message: message, checked_at: Time.current)
+ end
end
end
end
diff --git a/spree/core/app/workflows/spree/carts/add_item.rb b/spree/core/app/workflows/spree/carts/add_item.rb
index 8909937dd2..92eff15ef5 100644
--- a/spree/core/app/workflows/spree/carts/add_item.rb
+++ b/spree/core/app/workflows/spree/carts/add_item.rb
@@ -72,7 +72,10 @@ module Spree
@line_item.reload.recalculate_price
- @line_item.owner.tax_provider.estimate(@line_item.owner, [@line_item], tax_date: Time.current) if @line_item_created
+ return unless @line_item_created
+
+ owner = @line_item.owner
+ owner.tax_provider.estimate(owner, [@line_item], **owner.tax_estimate_inputs)
end
def handle_stock_reservations
diff --git a/spree/core/app/workflows/spree/carts/recalculate_totals.rb b/spree/core/app/workflows/spree/carts/recalculate_totals.rb
index 37db30fbdb..afa63fa2cf 100644
--- a/spree/core/app/workflows/spree/carts/recalculate_totals.rb
+++ b/spree/core/app/workflows/spree/carts/recalculate_totals.rb
@@ -58,12 +58,7 @@ module Spree
Spree.adjusters.each { |adjuster| adjuster.adjust(cart) }
refresh_discount_and_fee_columns
@tax_line_context = run_hooks :set_tax_line_context
- cart.tax_provider.estimate(
- cart,
- tax_date: Time.current,
- exemptions: Spree.tax_resolve_exemptions_service.new.call(order: cart).value,
- context: tax_line_context
- )
+ cart.tax_provider.estimate(cart, **cart.tax_estimate_inputs, context: tax_line_context)
end
# Re-derives the denormalized per-adjustable columns and the record's
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 7a76450332..57fd00f07f 100644
--- a/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb
+++ b/spree/core/spec/models/concerns/spree/purchase/taxation_spec.rb
@@ -127,6 +127,31 @@ RSpec.shared_examples 'a taxation host' do
end
end
+ describe '#tax_estimate_inputs' do
+ let(:customer) { create(:user) }
+
+ before { record.update!(customer: customer) }
+
+ it 'carries the effective date, the buyer registration and the exemptions' do
+ identifier = create(:tax_identifier, customer: customer)
+ exemption = Spree::TaxExemption.new(reason_code: 'resale')
+ allow(Spree.tax_resolve_exemptions_service).to receive(:new).
+ and_return(instance_double(Spree::Tax::ResolveExemptions,
+ call: Spree::ServiceModule::Result.new(true, [exemption], nil)))
+
+ inputs = record.tax_estimate_inputs
+
+ expect(inputs[:tax_date]).to be_present
+ expect(inputs[:tax_identifier]).to eq(identifier)
+ expect(inputs[:exemptions]).to eq([exemption])
+ end
+
+ it 'is accepted whole by the provider contract' do
+ expect { Spree::TaxProvider::Internal.new.estimate(record, [], **record.tax_estimate_inputs) }.
+ not_to raise_error
+ 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)
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 7f28d46a34..e12dd10dd1 100644
--- a/spree/core/spec/models/spree/tax_provider/internal_spec.rb
+++ b/spree/core/spec/models/spree/tax_provider/internal_spec.rb
@@ -166,6 +166,25 @@ describe Spree::TaxProvider::Internal, type: :model do
end
end
+ context 'when another store holds the default tax category' do
+ let!(:rate) do
+ create(:tax_rate, country: country, amount: 0.1,
+ tax_category: create(:tax_category, is_default: true), included_in_price: false)
+ end
+ let!(:fee) { create(:fee, order: order, amount: 5, kind: 'surcharge', label: 'Handling') }
+
+ it 'reads its own store default rather than any store default' do
+ other_store = create(:store)
+ Spree::Current.store = other_store
+ create(:tax_category, store: other_store, is_default: true)
+ Spree::Current.store = nil
+
+ provider.estimate(order, [fee])
+
+ expect(order.tax_lines.reload.sole.amount).to eq(0.5)
+ end
+ end
+
context 'with a taxable fee' do
let!(:rate) do
create(:tax_rate, country: country, amount: 0.1, tax_category: create(:tax_category, is_default: true), included_in_price: false)
diff --git a/spree/core/spec/services/spree/tax_identifiers/validate_spec.rb b/spree/core/spec/services/spree/tax_identifiers/validate_spec.rb
index 1fd0eb88df..78c2ede119 100644
--- a/spree/core/spec/services/spree/tax_identifiers/validate_spec.rb
+++ b/spree/core/spec/services/spree/tax_identifiers/validate_spec.rb
@@ -88,7 +88,7 @@ describe Spree::TaxIdentifiers::Validate do
tax_identifier.update_columns(validation_status: 'verified')
end
- it 'reports the failure and keeps the previous verdict' do
+ it 'reports the failure and records that nobody could answer' do
expect(Rails.error).to receive(:report).with(
instance_of(Spree::TaxIdentifiers::ValidationError), hash_including(:context)
)
@@ -96,7 +96,9 @@ describe Spree::TaxIdentifiers::Validate do
result = described_class.call(tax_identifier: tax_identifier)
expect(result).to be_failure
- expect(tax_identifier.reload.validation_status).to eq('verified')
+ # Not left on the `pending` the enqueue stamped, and not called wrong.
+ expect(tax_identifier.reload.validation_status).to eq('unavailable')
+ expect(tax_identifier.validation_evidence['message']).to include('boom')
end
end
end