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 1: Cart pricing follows the cart, persists, and respects explicit market prices
Łukasz Adamczyk058984f18516
diff --git a/spree/core/app/models/concerns/spree/vat_price_calculation.rb b/spree/core/app/models/concerns/spree/vat_price_calculation.rbindex 2fef336a8b..589b286d9d 100644--- a/spree/core/app/models/concerns/spree/vat_price_calculation.rb+++ b/spree/core/app/models/concerns/spree/vat_price_calculation.rb@@ -3,13 +3,28 @@ module Spree# home-country VAT comes out, the destination's goes on.module VatPriceCalculationdef gross_amount(amount, price_options)- return amount if amount.nil? || !outside_default_vat_zone?(price_options)+ return amount if amount.nil? || !restatement_available?(price_options)+ return amount unless outside_default_vat_zone?(price_options)round_to_two_places(add_foreign_vat_for(amount, price_options))endprivate+ # Restatement reads nothing but TaxRate rows, for both halves of the sum, so+ # it only means anything where those rows are the whole truth — the Internal+ # provider. Elsewhere an absent row is ambiguous: it reads as "no tax is due+ # here" and deducts the home VAT, when it may only mean "this market's tax is+ # computed by an engine that keeps no rows here". A market on such an engine+ # would see every foreign destination treated as a zero-rated export. It+ # states its destination prices through a geo-scoped price list instead.+ def restatement_available?(price_options)+ market = price_options[:market] || Spree::Current.market+ provider = market&.tax_provider_instance || Spree.default_tax_provider.new++ provider.is_a?(Spree::TaxProvider::Internal)+ end+def add_foreign_vat_for(amount, price_options)amount = net_amount(amount, price_options[:tax_category])amount_with_foreign_vat(amount, price_options)diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rbindex 650082063e..b697d9e4b8 100644--- a/spree/core/app/models/spree/cart.rb+++ b/spree/core/app/models/spree/cart.rb@@ -205,7 +205,11 @@ module Spree# recalculation-on-write replacement for transition-triggered rebuilds.# Called by Carts::Update after address/market changes.def recalculate_for_address_change!- line_items.reload.each(&:update_price)+ # recalculate_price, not update_price: the latter only assigns, and nothing+ # here saves the line items — rebuild_fulfillments! and recalculate_totals!+ # reset the association cache and drop the new figures. Order#update_line_item_prices!+ # gets away with update_price because it follows it with save!.+ line_items.reload.each(&:recalculate_price)rebuild_fulfillments!set_fulfillments_costrecalculate_totals!diff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rbindex cea8cb2611..5f16752aaf 100644--- a/spree/core/app/models/spree/line_item.rb+++ b/spree/core/app/models/spree/line_item.rb@@ -134,7 +134,7 @@ module Spreecontext = Spree::Pricing::Context.from_order(variant, owner, quantity: quantity)currency_price = variant.price_for(context)- self.price = currency_price.price_including_vat_for(address: owner&.tax_address) if currency_price.present?+ self.price = currency_price.price_including_vat_for(address: owner&.tax_address, market: owner&.market) if currency_price.present?self.price_list_id = currency_price.price_list_id if currency_price.present?end@@ -320,7 +320,7 @@ module Spreereturn unless currency_price.present?- new_price = currency_price.price_including_vat_for(address: owner&.tax_address)+ new_price = currency_price.price_including_vat_for(address: owner&.tax_address, market: owner&.market)return unless new_price.present?diff --git a/spree/core/app/models/spree/price.rb b/spree/core/app/models/spree/price.rbindex ea37cea693..a926ea2379 100644--- a/spree/core/app/models/spree/price.rb+++ b/spree/core/app/models/spree/price.rb@@ -119,12 +119,28 @@ module Spreealias_attribute :compare_at_price, :compare_at_amountalias_method :compare_at_price=, :compare_at_amount=+ # Whether this figure is the merchant's answer for the buyer's geography+ # already. A price list narrowed by market or country states its prices for+ # that geography, so they are charged exactly as entered — restating one would+ # net it out with the *home* rate and destroy the price point the merchant+ # chose. Lists narrowed by anything else (a quantity, a group) were not set+ # for a country, so their prices restate like any other.+ #+ # @return [Boolean]+ def final_for_destination?+ price_list&.price_rules&.any?(&:geographic?) || false+ end+def price_including_vat_for(price_options)+ return price if final_for_destination?+options = price_options.merge(tax_category: variant.tax_category)gross_amount(price, options)enddef compare_at_price_including_vat_for(price_options)+ return compare_at_price if final_for_destination?+options = price_options.merge(tax_category: variant.tax_category)gross_amount(compare_at_price, options)enddiff --git a/spree/core/app/models/spree/price_rule.rb b/spree/core/app/models/spree/price_rule.rbindex 8b97769da9..dee76e0d5a 100644--- a/spree/core/app/models/spree/price_rule.rb+++ b/spree/core/app/models/spree/price_rule.rb@@ -16,6 +16,18 @@ module Spreeraise NotImplementedError, "#{self.class.name} must implement #applicable?"end+ # Whether this rule narrows its price list by geography. A list carrying one+ # states the price for that geography outright, so its prices are charged as+ # entered and never restated for the buyer's VAT rate+ # (Spree::VatPriceCalculation). A rule that narrows by anything else — a+ # quantity, a group, a channel — leaves its prices open to restatement, since+ # they were not set for a country.+ #+ # @return [Boolean]+ def geographic?+ false+ end+# Returns the human name of the price rule# @return [String]def self.human_namediff --git a/spree/core/app/models/spree/price_rules/market_rule.rb b/spree/core/app/models/spree/price_rules/market_rule.rbindex d7d7928638..792accbbc6 100644--- a/spree/core/app/models/spree/price_rules/market_rule.rb+++ b/spree/core/app/models/spree/price_rules/market_rule.rb@@ -26,6 +26,10 @@ module Spreepreferred_market_ids.map(&:to_s).include?(context.market.id.to_s)end+ def geographic?+ true+ end+def self.description'Apply pricing based on the market'enddiff --git a/spree/core/app/models/spree/price_rules/zone_rule.rb b/spree/core/app/models/spree/price_rules/zone_rule.rbindex b6d5f97003..f3a8b59b97 100644--- a/spree/core/app/models/spree/price_rules/zone_rule.rb+++ b/spree/core/app/models/spree/price_rules/zone_rule.rb@@ -26,6 +26,10 @@ module Spreepreferred_country_ids.map(&:to_s).include?(context.country.id.to_s)end+ def geographic?+ true+ end+def self.description'Apply pricing based on the destination country'enddiff --git a/spree/core/app/models/spree/stock/estimator.rb b/spree/core/app/models/spree/stock/estimator.rbindex 661e01fa1e..2ae82abe02 100644--- a/spree/core/app/models/spree/stock/estimator.rb+++ b/spree/core/app/models/spree/stock/estimator.rb@@ -58,7 +58,8 @@ module Spree{tax_category: delivery_method.tax_category,address: @order.tax_address,- country: @order.tax_country+ country: @order.tax_country,+ market: @order.market}enddiff --git a/spree/core/lib/spree/core/pricing/context.rb b/spree/core/lib/spree/core/pricing/context.rbindex ae8a0d0dc7..9b2da2aa88 100644--- a/spree/core/lib/spree/core/pricing/context.rb+++ b/spree/core/lib/spree/core/pricing/context.rb@@ -35,12 +35,18 @@ module Spreenew(variant: variant, currency: currency)end+ # The owner's own market, not Spree::Current's: a cart carries the market it+ # was placed on, and pricing a line from the request context instead makes+ # the same cart price differently between two requests depending on whether+ # the client sent a country hint. Catalogue requests have no owner and keep+ # the Spree::Current fallback.def self.from_order(variant, order, quantity: nil)new(variant: variant,currency: order.currency,store: order.store,country: order.tax_country,+ market: order.market,channel: order.channel,user: order.user,quantity: quantity || order.line_items.find_by(variant: variant)&.quantity,diff --git a/spree/core/spec/lib/spree/core/pricing/context_spec.rb b/spree/core/spec/lib/spree/core/pricing/context_spec.rbindex da09652a31..66704bc0f6 100644--- a/spree/core/spec/lib/spree/core/pricing/context_spec.rb+++ b/spree/core/spec/lib/spree/core/pricing/context_spec.rb@@ -168,6 +168,19 @@ module Spreeexpect(subject.store).to eq(order.store)end+ it "sets market from the order, not from Spree::Current" do+ other_market = create(:market, store: order.store, name: "Elsewhere #{Time.current.to_f}",+ currency: order.currency, default_locale: 'en')+ Spree::Current.market = other_market++ # Pricing a cart line must follow the cart's own market, or the same cart+ # prices differently between requests depending on the country hint.+ expect(subject.market).to eq(order.market)+ expect(subject.market).not_to eq(other_market)+ ensure+ Spree::Current.market = nil+ end+it 'sets user from order' doexpect(subject.user).to eq(order.user)enddiff --git a/spree/core/spec/models/concerns/spree/vat_price_calculation_spec.rb b/spree/core/spec/models/concerns/spree/vat_price_calculation_spec.rbnew file mode 100644index 0000000000..b824307d27--- /dev/null+++ b/spree/core/spec/models/concerns/spree/vat_price_calculation_spec.rb@@ -0,0 +1,112 @@+require 'spec_helper'++# The cross-border matrix. A tax-inclusive price is expressed in some country's+# VAT, so shipping elsewhere has to restate it: the home rate out, the+# destination's on. Nothing covered this from the cart side before — the existing+# coverage in tax_rate_spec.rb drives the order path.+describe Spree::VatPriceCalculation, type: :model do+ let(:store) { @default_store }+ let(:germany) { Spree::Country.find_by(iso: 'DE') || create(:country, iso: 'DE', name: 'Germany') }+ let(:france) { Spree::Country.find_by(iso: 'FR') || create(:country, iso: 'FR', name: 'France') }+ let(:japan) { Spree::Country.find_by(iso: 'JP') || create(:country, iso: 'JP', name: 'Japan') }+ let(:category) { create(:tax_category, name: "Goods #{Time.current.to_f}") }++ # Prices are quoted including German VAT, so Germany is the home zone.+ let(:home_market) { store.default_market }++ before do+ home_market.update!(countries: [germany])+ create(:tax_rate, name: 'DE 19% incl', amount: 0.19, tax_category: category,+ country: germany, included_in_price: true, store: store)+ end++ let(:variant) { create(:variant, price: 100, product: create(:product, tax_category: category)) }+ let(:price) { variant.prices.find_by(currency: 'USD', price_list_id: nil) }++ def gross_for(country, market: home_market)+ price.price_including_vat_for(country: country, market: market)+ end++ it 'leaves the price alone when the destination is the home country' do+ expect(gross_for(germany)).to eq(100.00)+ end++ it 'restates for a destination with its own rate, preserving the net' do+ create(:tax_rate, name: 'FR 20% incl', amount: 0.20, tax_category: category,+ country: france, included_in_price: true, store: store)++ # net 100 / 1.19 = 84.0336, grossed by 1.20+ expect(gross_for(france)).to eq(100.84)+ end++ it 'charges the net where the destination levies nothing — a zero-rated export' do+ expect(gross_for(japan)).to eq(84.03)+ end++ # The rate table is the whole truth only for the built-in engine. Elsewhere an+ # absent row means "computed by something that keeps no rows here", not "no tax+ # due", so deducting the home VAT would turn every foreign sale into an export.+ context 'when the market is on an external tax provider' do+ let(:external_market) do+ stub_const('SpecExternalTaxProvider', Class.new(Spree::TaxProvider::Base) do+ def estimate(*); end+ end)+ # Market validates tax_provider against the registry.+ Spree.tax_providers << SpecExternalTaxProvider++ create(:market, store: store, name: "External #{Time.current.to_f}", currency: 'USD',+ default_locale: 'en', tax_provider: 'SpecExternalTaxProvider')+ end++ after { Spree.tax_providers.delete(SpecExternalTaxProvider) if defined?(SpecExternalTaxProvider) }++ it 'does not restate at all' do+ create(:tax_rate, name: 'FR 20% incl', amount: 0.20, tax_category: category,+ country: france, included_in_price: true, store: store)++ expect(gross_for(france, market: external_market)).to eq(100.00)+ end++ it 'does not turn a rate-less destination into an export' do+ expect(gross_for(japan, market: external_market)).to eq(100.00)+ end+ end++ describe 'a price the merchant set for the destination' do+ let(:french_market) do+ create(:market, store: store, name: "France #{Time.current.to_f}", currency: 'USD',+ default_locale: 'en', countries: [france])+ end++ let(:price_list) do+ create(:price_list, store: store).tap do |list|+ list.price_rules.create!(type: 'Spree::PriceRules::MarketRule',+ preferences: { market_ids: [french_market.id] })+ end+ end++ let(:list_price) do+ create(:price, variant: variant, currency: 'USD', amount: 99, price_list: price_list)+ end++ before do+ create(:tax_rate, name: 'FR 20% incl', amount: 0.20, tax_category: category,+ country: france, included_in_price: true, store: store)+ end++ it 'is charged exactly as entered' do+ expect(list_price.price_including_vat_for(country: france, market: french_market)).to eq(99.00)+ end++ it 'would otherwise have been restated' do+ # Same figure on a list with no geographic rule: 99 / 1.19 * 1.20 = 99.83.+ plain_list = create(:price_list, store: store)+ plain_list.price_rules.create!(type: 'Spree::PriceRules::VolumeRule',+ preferences: { min_quantity: 1 })+ volume_price = create(:price, variant: variant, currency: 'USD', amount: 99,+ price_list: plain_list)++ expect(volume_price.price_including_vat_for(country: france, market: french_market)).to eq(99.83)+ end+ end+enddiff --git a/spree/core/spec/models/spree/cart_spec.rb b/spree/core/spec/models/spree/cart_spec.rbindex fa55beb959..2de3022afa 100644--- a/spree/core/spec/models/spree/cart_spec.rb+++ b/spree/core/spec/models/spree/cart_spec.rb@@ -403,6 +403,22 @@ describe Spree::Cart, type: :model doexpect(cart.reload.delivery_total).to be > 0expect(cart.total).to eq(cart.item_total + cart.delivery_total + cart.adjustment_total)end++ # The re-price used to be computed into memory and dropped: nothing here+ # saves the line items, and the recalculation that follows resets the+ # association cache. A destination change has to leave the new figure in the+ # column, or the customer is charged the price quoted for the old country.+ it 'persists the repriced line item, not just the in-memory attribute' do+ line_item = cart.line_items.first+ line_item.update_columns(price: 1)++ cart.recalculate_for_address_change!++ expect(cart.line_items.reload.first.price).not_to eq(1)+ expect(line_item.reload.price).to eq(line_item.variant.price_for(+ Spree::Pricing::Context.from_order(line_item.variant, cart)+ ).amount)+ endendendenddiff --git a/spree/core/spec/models/spree/price_rules/market_rule_spec.rb b/spree/core/spec/models/spree/price_rules/market_rule_spec.rbindex c9aae034d1..78154c0086 100644--- a/spree/core/spec/models/spree/price_rules/market_rule_spec.rb+++ b/spree/core/spec/models/spree/price_rules/market_rule_spec.rb@@ -102,4 +102,11 @@ describe Spree::PriceRules::MarketRule, type: :model doexpect(rule.markets).to be_emptyendend+ describe '#geographic?' do+ it 'is true' do+ # A list narrowed by geography states its prices for that geography, so+ # they are charged as entered rather than restated for the buyer's VAT.+ expect(described_class.new.geographic?).to be(true)+ end+ endenddiff --git a/spree/core/spec/models/spree/price_rules/volume_rule_spec.rb b/spree/core/spec/models/spree/price_rules/volume_rule_spec.rbindex abddda4534..64a5e9b746 100644--- a/spree/core/spec/models/spree/price_rules/volume_rule_spec.rb+++ b/spree/core/spec/models/spree/price_rules/volume_rule_spec.rb@@ -55,4 +55,10 @@ describe Spree::PriceRules::VolumeRule, type: :model doexpect(rule.applicable?(context)).to be falseendend+ describe '#geographic?' do+ it 'is false' do+ # Narrowed by quantity, not by a country — its prices still restate.+ expect(described_class.new.geographic?).to be(false)+ end+ endenddiff --git a/spree/core/spec/models/spree/price_rules/zone_rule_spec.rb b/spree/core/spec/models/spree/price_rules/zone_rule_spec.rbindex 6647fb844b..b316f7c386 100644--- a/spree/core/spec/models/spree/price_rules/zone_rule_spec.rb+++ b/spree/core/spec/models/spree/price_rules/zone_rule_spec.rb@@ -55,4 +55,11 @@ describe Spree::PriceRules::ZoneRule, type: :model doendendend+ describe '#geographic?' do+ it 'is true' do+ # A list narrowed by geography states its prices for that geography, so+ # they are charged as entered rather than restated for the buyer's VAT.+ expect(described_class.new.geographic?).to be(true)+ end+ endenddiff --git a/spree/core/spec/models/spree/price_spec.rb b/spree/core/spec/models/spree/price_spec.rbindex b4cac99e27..343cec1f10 100644--- a/spree/core/spec/models/spree/price_spec.rb+++ b/spree/core/spec/models/spree/price_spec.rb@@ -485,4 +485,36 @@ describe Spree::Price, type: :model doendendend+ describe '#final_for_destination?' do+ let(:store) { @default_store }+ let(:variant) { create(:variant) }++ it 'is true for a price on a list narrowed by market' do+ market = create(:market, store: store, name: "M #{Time.current.to_f}", currency: 'USD',+ default_locale: 'en')+ list = create(:price_list, store: store)+ list.price_rules.create!(type: 'Spree::PriceRules::MarketRule',+ preferences: { market_ids: [market.id] })++ price = create(:price, variant: variant, currency: 'USD', amount: 99, price_list: list)++ expect(price.final_for_destination?).to be(true)+ end++ it 'is false for a price on a list narrowed by something other than geography' do+ list = create(:price_list, store: store)+ list.price_rules.create!(type: 'Spree::PriceRules::VolumeRule',+ preferences: { min_quantity: 1 })++ price = create(:price, variant: variant, currency: 'USD', amount: 99, price_list: list)++ expect(price.final_for_destination?).to be(false)+ end++ it 'is false for a base price' do+ base = variant.prices.find_by(currency: 'USD', price_list_id: nil)++ expect(base.final_for_destination?).to be(false)+ end+ endend