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
Recalculate tax from the discounted basis for all promotion types (#14295)
Damian Legawiecc0d86e097728
diff --git a/spree/core/app/models/spree/calculator/default_tax.rb b/spree/core/app/models/spree/calculator/default_tax.rbindex 645cfe18e8..a52fcf955b 100644--- a/spree/core/app/models/spree/calculator/default_tax.rb+++ b/spree/core/app/models/spree/calculator/default_tax.rb@@ -24,11 +24,21 @@ module Spreeend# When it comes to computing shipments or line items: same same.+ #+ # Both tax modes are computed from the item's live taxable basis, which+ # follows every discount: item-level promotions and the item's share of+ # whole-order promotions (see LineItem#taxable_basis). Included+ # (VAT-style) tax intentionally does not read the stored pre_tax_amount+ # column — that column is only refreshed by Spree::TaxRate.adjust on+ # checkout transitions, so it goes stale the moment a promotion is+ # applied or removed.def compute_shipment_or_line_item(item)+ basis = item.taxable_basis+if rate.included_in_price- deduced_total_by_rate(item.pre_tax_amount, rate)+ deduced_total_by_rate(net_basis(item, basis), rate)else- round_to_two_places(item.discounted_amount * rate.amount)+ round_to_two_places(basis * rate.amount)endend@@ -54,5 +64,24 @@ module Spreedef deduced_total_by_rate(pre_tax_amount, rate)round_to_two_places(pre_tax_amount * rate.amount)end++ # Backs all included-in-price rates out of the gross basis, mirroring+ # Spree::TaxRate.store_pre_tax_amount (several rates can share a tax+ # category, e.g. MOSS VAT). Falls back to this rate's amount when no+ # rate matches the item, e.g. in bare setups without matching zones.+ def net_basis(item, basis)+ included = included_rates_amount(item)+ included = rate.amount if included.zero?++ basis / (1 + included)+ end++ # Memoized per tax category: tax rate and zone rows are configuration,+ # invariant within a recalculation pass.+ def included_rates_amount(item)+ @included_rates_amount ||= {}+ @included_rates_amount[item.tax_category_id] ||=+ Spree::TaxRate.included_tax_amount_for(tax_zone: rate.zone, tax_category: item.tax_category)+ endendenddiff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rbindex 3640f913c6..9887f3b1b9 100644--- a/spree/core/app/models/spree/line_item.rb+++ b/spree/core/app/models/spree/line_item.rb@@ -146,6 +146,29 @@ module Spreealias discounted_money display_discounted_amountalias discounted_amount taxable_amount+ # Returns the amount this line item is taxed on: the discounted amount+ # reduced further by the line item's proportional share of any+ # whole-order promotions, which are adjustments on the order itself and+ # therefore not part of +taxable_adjustment_total+. Never negative.+ #+ # @return [BigDecimal]+ def taxable_basis+ basis = taxable_amount+ return basis if basis <= 0++ order_discount = order.order_level_promo_total+ return basis if order_discount.zero?++ # summed in SQL so the allocation uses the persisted adjustment totals+ # of all line items, not a possibly stale cached association+ items_total = order.line_items.reorder(nil).pick(+ Arel.sql('COALESCE(SUM(price * quantity + taxable_adjustment_total), 0)')+ )+ return basis if items_total <= 0++ [basis + (order_discount * basis / items_total), BigDecimal(0)].max+ end+# Returns the final amount of the line item## @return [BigDecimal]diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 630a1a6fdc..2d08a35a86 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -360,6 +360,16 @@ module Spreeline_items.sum(:pre_tax_amount)end+ # Sum of the eligible promotion adjustments applied to the order itself+ # (whole-order discounts created by Promotion::Actions::CreateAdjustment),+ # as opposed to promotions applied to individual line items or shipments.+ # Zero or negative.+ #+ # @return [BigDecimal]+ def order_level_promo_total+ adjustments.promotion.eligible.sum(:amount)+ end+# Sum of all line item and shipment pre-taxdef pre_tax_totalpre_tax_item_amount + shipments.sum(:pre_tax_amount)diff --git a/spree/core/app/models/spree/shipment.rb b/spree/core/app/models/spree/shipment.rbindex d56b5e113d..8e7a5f60bf 100644--- a/spree/core/app/models/spree/shipment.rb+++ b/spree/core/app/models/spree/shipment.rb@@ -207,6 +207,15 @@ module Spreeendalias discounted_amount discounted_cost+ # Returns the amount this shipment is taxed on: its discounted cost,+ # never negative (stacked shipping promotions can push discounted_cost+ # below zero). Whole-order promotions are not allocated to shipments.+ #+ # @return [BigDecimal]+ def taxable_basis+ [discounted_cost, BigDecimal(0)].max+ end+def final_pricecost + adjustment_totalenddiff --git a/spree/core/app/models/spree/tax_rate.rb b/spree/core/app/models/spree/tax_rate.rbindex f735dd44fe..d9bc6f1c9d 100644--- a/spree/core/app/models/spree/tax_rate.rb+++ b/spree/core/app/models/spree/tax_rate.rb@@ -54,6 +54,13 @@ module Spree# Pre-tax amounts must be stored so that we can calculate# correct rate amounts in the future. For example:# https://github.com/spree/spree/issues/4318#issuecomment-34723428+ #+ # NOTE: this deliberately excludes the item's share of whole-order+ # promotions and is therefore NOT the basis tax is computed on (that is+ # LineItem#taxable_basis / Shipment#taxable_basis). Refund and reporting+ # code (e.g. Calculator::Returns::DefaultRefundAmount) weighs order-level+ # adjustments separately on top of this column, so allocating them here+ # would double-count discounts.def self.store_pre_tax_amount(item, rates)pre_tax_amount = case item.class.to_swhen 'Spree::LineItem' then item.discounted_amountdiff --git a/spree/core/spec/models/spree/promotion_tax_recalculation_spec.rb b/spree/core/spec/models/spree/promotion_tax_recalculation_spec.rbnew file mode 100644index 0000000000..a7b8da020f--- /dev/null+++ b/spree/core/spec/models/spree/promotion_tax_recalculation_spec.rb@@ -0,0 +1,253 @@+require 'spec_helper'++# Covers the discount x calculator x tax-mode matrix of the promotion /+# taxable-basis bug: applying any promotion must move the taxable basis, for+# line-item and whole-order adjustments, percent and flat-rate calculators,+# additional (US-style) and included (VAT-style) tax — and the corrected+# figures must survive the checkout tax rebuild (create_tax_charge!) that+# writes the totals persisted onto completed orders.+describe 'Promotion discounts and the taxable basis', type: :model do+ let(:store) { @default_store }+ let(:tax_category) { create(:tax_category) }++ let!(:zone) do+ create(:zone, name: 'Default tax zone', kind: 'country', default_tax: true).tap do |zone|+ zone.zone_members.create!(zoneable: @default_country)+ end+ end++ let(:product) { create(:product, price: item_price, tax_category: tax_category, store: store) }+ let(:order) { create(:order, store: store, currency: 'USD') }+ # Lazy on purpose: the tax rate must exist before the line item is created,+ # because Spree only creates tax adjustments from LineItem#update_tax_charge.+ # Each tax-mode context forces it in a before hook after its tax rate.+ let(:line_item) { create(:line_item, order: order, variant: product.master, price: item_price, quantity: 1) }++ def build_cart!+ line_item+ # the order instance may hold a stale (empty) cached line_items association+ order.reload+ order.update_with_updater!+ order.reload+ end++ def line_item_promotion(calculator)+ create(:promotion, code: 'DISCOUNT', store: store).tap do |promotion|+ Spree::Promotion::Actions::CreateItemAdjustments.create!(calculator: calculator, promotion: promotion)+ end+ end++ def whole_order_promotion(calculator)+ create(:promotion, code: 'DISCOUNT', store: store).tap do |promotion|+ Spree::Promotion::Actions::CreateAdjustment.create!(calculator: calculator, promotion: promotion)+ end+ end++ def apply_coupon!+ order.coupon_code = 'DISCOUNT'+ handler = Spree::PromotionHandler::Coupon.new(order).apply+ expect(handler.successful?).to be(true), "coupon was not applied: #{handler.error}"+ order.reload+ end++ # The checkout state machine rebuilds all tax adjustments through+ # Spree::TaxRate.adjust before payment; whatever it computes is what a+ # completed order keeps.+ def rebuild_tax_like_checkout!+ order.create_tax_charge!+ order.update_with_updater!+ order.reload+ end++ def percent_calculator(percent)+ Spree::Calculator::PercentOnLineItem.new(preferred_percent: percent)+ end++ def flat_calculator(amount)+ Spree::Calculator::FlatRate.new(preferred_amount: amount)+ end++ def flat_percent_calculator(percent)+ Spree::Calculator::FlatPercentItemTotal.new(preferred_flat_percent: percent)+ end++ context 'with additional (US-style) tax of 10%' do+ let(:item_price) { 250 }+ let!(:tax_rate) do+ create(:tax_rate, zone: zone, tax_category: tax_category, amount: 0.10, included_in_price: false)+ end++ before { build_cart! }++ it 'starts from tax on the full amount' do+ expect(order.additional_tax_total).to eq(25.00)+ expect(order.total).to eq(275.00)+ end++ context 'with a 50% line-item promotion' do+ let!(:promotion) { line_item_promotion(percent_calculator(50)) }++ it 'computes tax on the discounted amount' do+ apply_coupon!++ expect(order.promo_total).to eq(-125.00)+ expect(order.additional_tax_total).to eq(12.50)+ expect(order.total).to eq(137.50)+ end+ end++ context 'with a flat 50 line-item promotion' do+ let!(:promotion) { line_item_promotion(flat_calculator(50)) }++ it 'computes tax on the discounted amount' do+ apply_coupon!++ expect(order.promo_total).to eq(-50.00)+ expect(order.additional_tax_total).to eq(20.00)+ expect(order.total).to eq(220.00)+ end+ end++ context 'with a 50% whole-order promotion' do+ let!(:promotion) { whole_order_promotion(flat_percent_calculator(50)) }++ it 'computes tax on the discounted amount' do+ apply_coupon!++ expect(order.promo_total).to eq(-125.00)+ expect(order.additional_tax_total).to eq(12.50)+ expect(order.total).to eq(137.50)+ end++ it 'keeps the discounted tax through the checkout tax rebuild' do+ apply_coupon!+ rebuild_tax_like_checkout!++ expect(order.additional_tax_total).to eq(12.50)+ expect(order.total).to eq(137.50)+ end+ end++ context 'with a flat 50 whole-order promotion' do+ let!(:promotion) { whole_order_promotion(flat_calculator(50)) }++ it 'computes tax on the discounted amount' do+ apply_coupon!++ expect(order.promo_total).to eq(-50.00)+ expect(order.additional_tax_total).to eq(20.00)+ expect(order.total).to eq(220.00)+ end+ end++ context 'with a whole-order promotion and several line items' do+ let(:other_product) { create(:product, price: 150, tax_category: tax_category, store: store) }+ let!(:other_line_item) do+ create(:line_item, order: order, variant: other_product.master, price: 150, quantity: 1)+ end+ let!(:promotion) { whole_order_promotion(flat_calculator(80)) }++ it 'allocates the discount across line items proportionally' do+ apply_coupon!++ # 400 total, discount 80 -> line bases 200 and 120+ expect(line_item.reload.additional_tax_total).to eq(20.00)+ expect(other_line_item.reload.additional_tax_total).to eq(12.00)+ expect(order.additional_tax_total).to eq(32.00)+ expect(order.total).to eq(352.00)+ end+ end+ end++ context 'with included (VAT-style) tax of 20%' do+ let(:item_price) { 350 }+ let!(:tax_rate) do+ create(:tax_rate, zone: zone, tax_category: tax_category, amount: 0.20, included_in_price: true)+ end++ before { build_cart! }++ it 'starts from VAT on the full amount' do+ expect(order.included_tax_total).to eq(58.33)+ expect(order.total).to eq(350.00)+ end++ context 'with a 50% line-item promotion' do+ let!(:promotion) { line_item_promotion(percent_calculator(50)) }++ it 'reports VAT on the discounted amount' do+ apply_coupon!++ expect(order.promo_total).to eq(-175.00)+ expect(order.included_tax_total).to eq(29.17)+ expect(order.total).to eq(175.00)+ end++ it 'keeps the discounted VAT through the checkout tax rebuild' do+ apply_coupon!+ rebuild_tax_like_checkout!++ expect(order.included_tax_total).to eq(29.17)+ expect(order.total).to eq(175.00)+ end+ end++ context 'with a flat 50 line-item promotion' do+ let!(:promotion) { line_item_promotion(flat_calculator(50)) }++ it 'reports VAT on the discounted amount' do+ apply_coupon!++ expect(order.promo_total).to eq(-50.00)+ expect(order.included_tax_total).to eq(50.00)+ expect(order.total).to eq(300.00)+ end+ end++ context 'with a 50% whole-order promotion' do+ let!(:promotion) { whole_order_promotion(flat_percent_calculator(50)) }++ it 'reports VAT on the discounted amount' do+ apply_coupon!++ expect(order.promo_total).to eq(-175.00)+ expect(order.included_tax_total).to eq(29.17)+ expect(order.total).to eq(175.00)+ end++ it 'keeps the discounted VAT through the checkout tax rebuild' do+ apply_coupon!+ rebuild_tax_like_checkout!++ expect(order.included_tax_total).to eq(29.17)+ expect(order.total).to eq(175.00)+ end+ end++ context 'with a flat 50 whole-order promotion' do+ let!(:promotion) { whole_order_promotion(flat_calculator(50)) }++ it 'reports VAT on the discounted amount' do+ apply_coupon!++ expect(order.promo_total).to eq(-50.00)+ expect(order.included_tax_total).to eq(50.00)+ expect(order.total).to eq(300.00)+ end+ end++ context 'when the promotion is removed again' do+ let!(:promotion) { whole_order_promotion(flat_percent_calculator(50)) }++ it 'restores VAT on the full amount' do+ apply_coupon!+ Spree::PromotionHandler::Coupon.new(order).remove('DISCOUNT')+ order.reload++ expect(order.promo_total).to eq(0)+ expect(order.included_tax_total).to eq(58.33)+ expect(order.total).to eq(350.00)+ end+ end+ end+enddiff --git a/spree/core/spec/models/spree/shipment_spec.rb b/spree/core/spec/models/spree/shipment_spec.rbindex 07a54725ba..4b05723f17 100644--- a/spree/core/spec/models/spree/shipment_spec.rb+++ b/spree/core/spec/models/spree/shipment_spec.rb@@ -283,6 +283,20 @@ describe Spree::Shipment, type: :model doexpect(shipment.discounted_cost).to eq(9)end+ describe '#taxable_basis' do+ let(:shipment) { create(:shipment).tap { |s| s.cost = 10 } }++ it 'is the discounted cost' do+ shipment.promo_total = -1+ expect(shipment.taxable_basis).to eq(9)+ end++ it 'never goes below zero when discounts exceed the cost' do+ shipment.promo_total = -15+ expect(shipment.taxable_basis).to eq(0)+ end+ end+it '#tax_total with included taxes' doshipment = Spree::Shipment.newexpect(shipment.tax_total).to eq(0)