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.

Streamline Cart model + add tests

Damian Legawiec2dc6494093ce
diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rb
index 491e776a97..773d25fd2b 100644
--- a/spree/core/app/models/spree/cart.rb
+++ b/spree/core/app/models/spree/cart.rb
@@ -3,11 +3,6 @@ module Spree
# checkout copies a cart into an immutable {Spree::Order}; the cart is
# retained with +completed_at+ set. Carts have no status column —
# +completed_at+ is the only lifecycle marker.
- #
- # There is no checkout state machine: progression is computed by
- # Spree::Checkout::Requirements against cart data, and recalculation happens
- # on the writes that matter (items, addresses, market) instead of on state
- # transitions. See docs/plans/6.0-cart-order-split.md.
class Cart < Spree.base_class
has_prefix_id :cart
@@ -43,9 +38,8 @@ module Spree
attribute :metadata, default: -> { {} }
attribute :accept_marketing, :boolean, default: false
- # Standardized column names; legacy readers stay as aliases one release.
- alias_attribute :item_count, :total_quantity
- alias_attribute :promo_total, :discount_total
+ # Transient warnings populated by remove_out_of_stock_items!
+ attribute :warnings, default: -> { [] }
money_methods :item_total, :adjustment_total, :included_tax_total, :additional_tax_total,
:discount_total, :fee_total, :delivery_total, :total, :payment_total, :outstanding_balance,
@@ -95,16 +89,12 @@ module Spree
Spree::StockLocation.find_by(id: preferred_stock_location_id)
end
- alias_method :user, :customer
- alias_method :user=, :customer=
- alias_attribute :user_id, :customer_id
alias_method :shipping_address, :ship_address
alias_method :shipping_address=, :ship_address=
alias_attribute :shipping_address_id, :ship_address_id
alias_method :billing_address, :bill_address
alias_method :billing_address=, :bill_address=
alias_attribute :billing_address_id, :bill_address_id
- alias_attribute :customer_note, :special_instructions
has_many :line_items, -> { order(:created_at) }, class_name: 'Spree::LineItem', inverse_of: :cart, dependent: :destroy
has_many :variants, through: :line_items
@@ -117,7 +107,6 @@ module Spree
pluck(:status).uniq
end
end
- has_many :shipments, class_name: 'Spree::Fulfillment', inverse_of: :cart, deprecated: true
has_many :fulfillment_items, through: :fulfillments, class_name: 'Spree::FulfillmentItem'
has_many :order_promotions, class_name: 'Spree::OrderPromotion', inverse_of: :cart, dependent: :destroy
has_many :promotions, through: :order_promotions, class_name: 'Spree::Promotion'
@@ -134,7 +123,6 @@ module Spree
alias_method :shipping_address_attributes=, :ship_address_attributes=
alias_method :billing_address_attributes=, :bill_address_attributes=
- validates :store, :currency, presence: true
scope :complete, -> { where.not(completed_at: nil) }
scope :incomplete, -> { where(completed_at: nil) }
@@ -148,12 +136,6 @@ module Spree
delegate :name, to: :customer, prefix: true, allow_nil: true
- # Public cart identifier on the wire (orders keep R-numbers; carts are
- # identified by token).
- def number
- token
- end
-
# @return [Boolean]
def completed?
completed_at.present?
@@ -179,16 +161,6 @@ module Spree
!completed? && (email.present? || ship_address_id.present?)
end
- # Reservation dispatch parity with the order-based checkout.
- def cart?
- !in_checkout?
- end
-
- # @return [Boolean] carts are never canceled — completion or expiry only
- def canceled?
- false
- end
-
# Recomputes and persists money totals (item, tax, promotion, delivery)
# and derived item counts. Convenience for
# {Spree::Carts::RecalculateTotals}.
@@ -230,12 +202,6 @@ module Spree
fulfillment_items.any?(&:backordered?)
end
- # Fulfillments never dispatch from a cart — determine_state reports
- # 'pending' until completion copies them onto an order.
- def can_ship?
- false
- end
-
def guest_checkout_disallowed?
return false if customer.present?
@@ -309,22 +275,10 @@ module Spree
alias set_shipments_cost set_fulfillments_cost
alias create_proposed_fulfillments rebuild_fulfillments!
- # @deprecated Use {#create_proposed_fulfillments}; removed in 6.1.
- def create_proposed_shipments
- Spree::Deprecation.warn('Spree::Cart#create_proposed_shipments is deprecated and will be removed in Spree 6.1. Use #create_proposed_fulfillments instead.')
- rebuild_fulfillments!
- end
-
def ensure_updated_fulfillments
rebuild_fulfillments! unless completed?
end
- # @deprecated Use {#ensure_updated_fulfillments}; removed in 6.1.
- def ensure_updated_shipments
- Spree::Deprecation.warn('Spree::Cart#ensure_updated_shipments is deprecated and will be removed in Spree 6.1. Use #ensure_updated_fulfillments instead.')
- ensure_updated_fulfillments
- end
-
# Re-prices, re-taxes and rebuilds delivery proposals — the
# recalculation-on-write replacement for transition-triggered rebuilds.
# Called by Carts::Update after address/market changes.
@@ -365,9 +319,6 @@ module Spree
reload
end
- # Transient warnings populated by remove_out_of_stock_items!
- attribute :warnings, default: -> { [] }
-
# Removes out-of-stock/discontinued items and populates warnings
# (mirrors Order#remove_out_of_stock_items!).
def remove_out_of_stock_items!
diff --git a/spree/core/app/models/spree/cart_updater.rb b/spree/core/app/models/spree/cart_updater.rb
deleted file mode 100644
index a8b445d754..0000000000
--- a/spree/core/app/models/spree/cart_updater.rb
+++ /dev/null
@@ -1,61 +0,0 @@
-module Spree
- # Recalculates a cart: same typed-adjustment two-pass as OrderUpdater
- # (adjusters, then the tax provider) but persisting the cart's own column
- # set — carts carry no payment/fulfillment status columns and are never
- # frozen (completion copies them into an immutable order instead).
- class CartUpdater < OrderUpdater
- alias cart order
-
- # Carts have no legacy update hooks.
- def run_hooks; end
-
- def update_payment_total
- cart.payment_total = payments.completed.includes(:refunds).inject(0) { |sum, payment| sum + payment.amount - payment.refunds.sum(:amount) }
- end
-
- def persist_totals
- cart.update_columns(
- item_total: cart.item_total,
- total_quantity: cart.total_quantity,
- adjustment_total: cart.adjustment_total,
- included_tax_total: cart.included_tax_total,
- additional_tax_total: cart.additional_tax_total,
- taxable_adjustment_total: cart.taxable_adjustment_total,
- non_taxable_adjustment_total: cart.non_taxable_adjustment_total,
- payment_total: cart.payment_total,
- delivery_total: cart.delivery_total,
- discount_total: cart.discount_total,
- fee_total: cart.fee_total,
- total: cart.total,
- updated_at: Time.current
- )
- end
-
- # Carts have no completion freeze — they are recalculated until the
- # moment Carts::Complete copies them into an order.
- def recalculate_adjustments
- Spree.adjusters.each { |adjuster| adjuster.adjust(cart) }
- send(:refresh_discount_and_fee_columns)
- Spree.tax_provider.estimate(cart)
- send(:refresh_tax_columns)
- end
-
- def update_adjustment_total
- recalculate_adjustments
-
- discounts_sum = cart.discounts.reload.sum(&:amount)
- cart_fees = cart.fees.reload.to_a
- tax_sums = cart.tax_lines.reload.group_by(&:included?).transform_values { |lines| lines.sum(&:amount) }
-
- cart.discount_total = cart.discounts.select(&:promotion?).sum(&:amount)
- cart.fee_total = cart_fees.sum(&:amount)
- cart.included_tax_total = tax_sums.fetch(true, 0)
- cart.additional_tax_total = tax_sums.fetch(false, 0)
- cart.adjustment_total = discounts_sum + cart.fee_total + cart.additional_tax_total
- cart.taxable_adjustment_total = 0
- cart.non_taxable_adjustment_total = cart_fees.select(&:order_level?).sum(&:amount)
-
- update_order_total
- end
- end
-end
diff --git a/spree/core/db/migrate/20260728000003_create_spree_carts.rb b/spree/core/db/migrate/20260728000003_create_spree_carts.rb
index 92b72bb316..38e859b0f6 100644
--- a/spree/core/db/migrate/20260728000003_create_spree_carts.rb
+++ b/spree/core/db/migrate/20260728000003_create_spree_carts.rb
@@ -6,12 +6,12 @@ class CreateSpreeCarts < ActiveRecord::Migration[7.2]
t.references :channel, null: false
t.references :customer, null: true
t.string :currency, null: false
- t.string :locale
+ t.string :locale, null: false
t.string :email
t.references :ship_address, null: true, index: false
t.references :bill_address, null: true, index: false
t.boolean :accept_marketing
- t.text :special_instructions
+ t.text :customer_note
t.string :last_ip_address
t.string :token, null: false
t.integer :lock_version, default: 0
diff --git a/spree/core/spec/models/spree/cart_spec.rb b/spree/core/spec/models/spree/cart_spec.rb
index 4078235e31..049193cac3 100644
--- a/spree/core/spec/models/spree/cart_spec.rb
+++ b/spree/core/spec/models/spree/cart_spec.rb
@@ -1,6 +1,9 @@
require 'spec_helper'
describe Spree::Cart, type: :model do
+ let(:store) { @default_store }
+ let(:customer) { create(:user) }
+
describe 'lifecycle events' do
it 'publishes cart.* lifecycle events' do
expect(described_class.lifecycle_events_enabled).to be true
@@ -13,14 +16,14 @@ describe Spree::Cart, type: :model do
# The V3 cart serializer resolves by convention when spree_api is loaded;
# core's dummy app only sees the fallback payload.
it 'carries the prefixed id in the event payload' do
- cart = create(:cart, store: @default_store)
+ cart = create(:cart, store: store)
expect(cart.event_payload[:id]).to eq(cart.prefixed_id)
end
end
describe 'readonly after completion' do
- let(:cart) { create(:cart, store: @default_store) }
+ let(:cart) { create(:cart, store: store) }
it 'rejects every write path once completed' do
cart.update_columns(completed_at: Time.current)
@@ -82,4 +85,73 @@ describe Spree::Cart, type: :model do
expect(cart.order).to eq(order)
end
end
+
+ describe '#warnings' do
+ let(:cart) { build(:cart) }
+
+ it 'defaults to empty array' do
+ expect(cart.warnings).to eq([])
+ end
+
+ it 'is a transient attribute (not persisted)' do
+ cart.warnings = [{ code: 'test', message: 'test' }]
+ cart.save!
+ expect(cart.reload.warnings).to eq([])
+ end
+ end
+
+ describe '#remove_out_of_stock_items!' do
+ let(:cart) { create(:cart_with_line_items, store: store, customer: customer) }
+
+ context 'when all items are in stock' do
+ it 'does not remove any items' do
+ expect { cart.remove_out_of_stock_items! }.not_to change { cart.line_items.count }
+ end
+
+ it 'sets warnings to empty array' do
+ cart.remove_out_of_stock_items!
+ expect(cart.warnings).to eq([])
+ end
+ end
+
+ context 'when an item is out of stock' do
+ before do
+ cart.line_items.first.variant.stock_items.update_all(count_on_hand: 0, backorderable: false)
+ end
+
+ it 'removes the out of stock item' do
+ expect { cart.remove_out_of_stock_items! }.to change { cart.reload.line_items.count }.by(-1)
+ end
+
+ it 'populates warnings with structured data' do
+ cart.remove_out_of_stock_items!
+ expect(cart.warnings.length).to eq(1)
+ expect(cart.warnings.first[:code]).to eq('line_item_removed')
+ expect(cart.warnings.first[:message]).to be_present
+ expect(cart.warnings.first[:variant_id]).to start_with('variant_')
+ expect(cart.warnings.first[:line_item_id]).to start_with('li_')
+ end
+ end
+
+ context 'when a product is discontinued' do
+ before do
+ cart.line_items.first.product.update_columns(status: 'discontinued')
+ end
+
+ it 'removes the item and populates warnings' do
+ cart.remove_out_of_stock_items!
+ expect(cart.warnings.length).to eq(1)
+ expect(cart.warnings.first[:code]).to eq('line_item_removed')
+ end
+ end
+
+ context 'when cart is empty' do
+ let(:order) { create(:order, store: store, user: user) }
+
+ it 'does nothing' do
+ cart.remove_out_of_stock_items!
+ expect(cart.warnings).to eq([])
+ end
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/order/adjustments_spec.rb b/spree/core/spec/models/spree/order/adjustments_spec.rb
index ba96038a85..6c7491ccc7 100644
--- a/spree/core/spec/models/spree/order/adjustments_spec.rb
+++ b/spree/core/spec/models/spree/order/adjustments_spec.rb
@@ -15,7 +15,7 @@ describe Spree::Order do
persisted_order.line_items << line_item
persisted_order.update!(ship_address: create(:address))
persisted_order.create_proposed_fulfillments
- persisted_order.set_shipments_cost
+ persisted_order.set_fulfillments_cost
create(:discount, order: persisted_order, line_item: line_item, amount: -line_item.amount, label: 'Promotion', kind: 'manual')
persisted_order.recalculate_totals!
end
@@ -59,7 +59,7 @@ describe Spree::Order do
order.ship_address = address
order.create_proposed_fulfillments
order.send :ensure_available_shipping_rates
- order.set_shipments_cost
+ order.set_fulfillments_cost
order.create_shipment_tax_charge!
end