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
Moved Checkout entirely to Cart, add Address Book to Cart
Damian Legawiec41ed45c27920
diff --git a/spree/api/spec/serializers/spree/api/v3/price_gating_spec.rb b/spree/api/spec/serializers/spree/api/v3/price_gating_spec.rbindex 4602db6731..845aa3c6cc 100644--- a/spree/api/spec/serializers/spree/api/v3/price_gating_spec.rb+++ b/spree/api/spec/serializers/spree/api/v3/price_gating_spec.rb@@ -18,8 +18,10 @@ RSpec.describe 'v3 Store serializer price gating' doenddescribe Spree::Api::V3::CartSerializer do+ let(:cart) { create(:cart_with_line_items, store: store, line_items_count: 1) }+it 'nulls totals, store-credit, and nested line-item prices for gated guests' do- hash = serialize(described_class, hide: true)+ hash = serialize(described_class, cart, hide: true)expect(hash['total']).to be_nilexpect(hash['display_total']).to be_nil@@ -33,7 +35,7 @@ RSpec.describe 'v3 Store serializer price gating' doendit 'serializes money fields normally when not gated' do- hash = serialize(described_class, hide: false)+ hash = serialize(described_class, cart, hide: false)expect(hash['total']).to be_presentexpect(hash['items'].first['price']).to be_presentdiff --git a/spree/core/app/models/spree/order/address_book.rb b/spree/core/app/models/concerns/spree/purchase/address_book.rbsimilarity index 66%rename from spree/core/app/models/spree/order/address_book.rbrename to spree/core/app/models/concerns/spree/purchase/address_book.rbindex 8f1bb77128..0be51a7c0a 100644--- a/spree/core/app/models/spree/order/address_book.rb+++ b/spree/core/app/models/concerns/spree/purchase/address_book.rb@@ -1,27 +1,50 @@module Spree- class Order < Spree.base_class+ module Purchase+ # Address-book behavior shared by Spree::Cart and Spree::Order: fills+ # defaults from the customer's saved addresses, deduplicates address+ # rows on write, guards address_id assignment to the owning customer,+ # and promotes checkout addresses to the customer's defaults.module AddressBook+ # Fills any blank bill/ship address from the customer's valid saved+ # defaults. The ship address is skipped when no physical delivery is+ # required, so shipping-address validations never fire on digital-only+ # purchases.+ #+ # @return [void]def assign_default_addresses!return unless userself.bill_address = user.bill_address if !bill_address_id && user.bill_address&.valid?- # Skip the ship address for orders without a delivery step to+ # Skip the ship address for orders without physical delivery to# avoid triggering shipping-address validations- self.ship_address = user.ship_address if !ship_address_id && user.ship_address&.valid? && checkout_steps.include?('delivery')+ self.ship_address = user.ship_address if !ship_address_id && user.ship_address&.valid? && delivery_required?end+ # Copies the ship address onto the bill address and promotes it to the+ # customer's default bill address.+ #+ # @return [true]def clone_shipping_addressself.bill_address = ship_address if ship_addressuser.bill_address = ship_address if should_assign_user_default_address?(ship_address)trueend+ # Copies the bill address onto the ship address and promotes it to the+ # customer's default ship address.+ #+ # @return [true]def clone_billing_addressself.ship_address = bill_address if bill_addressuser.ship_address = bill_address if should_assign_user_default_address?(bill_address)trueend+ # Ownership-guarded writer: the id is applied only when the address+ # belongs to the record's customer; anything else — including any id on+ # a guest record — resolves to nil.+ #+ # @param id [Integer, String, nil]def bill_address_id=(id)return if bill_address_id == id@@ -36,11 +59,19 @@ module Spreereset_bill_addressend+ # Deduplicating writer: reuses or updates an existing address row when+ # possible, then promotes the result to the customer's default bill+ # address.+ #+ # @param attributes [Hash, ActionController::Parameters]def bill_address_attributes=(attributes)self.bill_address = update_or_create_address(attributes)user.bill_address = bill_address if should_assign_user_default_address?(bill_address)end+ # Ownership-guarded writer — see {#bill_address_id=}.+ #+ # @param id [Integer, String, nil]def ship_address_id=(id)return if ship_address_id == id@@ -55,6 +86,11 @@ module Spreereset_ship_addressend+ # Deduplicating writer — see {#bill_address_attributes=}. Quick-checkout+ # (wallet) addresses are never promoted to defaults, and an unpersisted+ # quick-checkout address is discarded.+ #+ # @param attributes [Hash, ActionController::Parameters]def ship_address_attributes=(attributes)self.ship_address = update_or_create_address(attributes)user.ship_address = ship_address if should_assign_user_default_address?(ship_address)diff --git a/spree/core/app/models/concerns/spree/purchase/checkout_steps.rb b/spree/core/app/models/concerns/spree/purchase/checkout_steps.rbindex 8ed4e54311..acaa50e7f4 100644--- a/spree/core/app/models/concerns/spree/purchase/checkout_steps.rb+++ b/spree/core/app/models/concerns/spree/purchase/checkout_steps.rb@@ -1,10 +1,11 @@module Spreemodule Purchase- # Data-driven checkout-step introspection shared by Spree::Cart and- # Spree::Order — computed from what the record actually requires- # (Spree::Checkout::Requirements), never from a state column. The host- # supplies delivery_required? (always true for orders, computed for- # carts).+ # Data-driven checkout-step introspection for Spree::Cart — computed+ # from what the cart actually requires (Spree::Checkout::Requirements),+ # never from a state column. Cart-only: an order is past checkout by+ # definition. The payment predicates the step list reads+ # (payment_required?/confirmation_required?) live in+ # {Spree::Purchase::PaymentProcessing}.module CheckoutSteps# @return [Array<String>]def checkout_steps@@ -16,18 +17,22 @@ module Spreestepsend+ # @param step [String, Symbol]+ # @return [Boolean]def has_checkout_step?(step)step.present? && checkout_steps.include?(step.to_s)end+ # @param step [String]+ # @return [Integer] position of the step, 0 when unknowndef checkout_step_index(step)checkout_steps.index(step).to_iend- # Customer-facing checkout step. Completed/canceled records are past- # checkout; open ones report the first unmet requirement's step- # ('cart' — missing line items — is not customer-facing and reports- # as 'address').+ # Customer-facing checkout step. Completed carts are past checkout;+ # open ones report the first unmet requirement's step ('cart' —+ # missing line items — is not customer-facing and reports as+ # 'address').## @return [String]def current_checkout_step@@ -49,17 +54,6 @@ module Spreeindex = steps.index(current_checkout_step) || 0steps.first(index)end-- # Free checkouts skip the payment step.- def payment_required?- total.to_f > 0.0- end-- # Whether the confirm/review step exists — computed from data only.- def confirmation_required?- Spree::Config[:always_include_confirm_step] ||- payments.valid.map(&:payment_method).compact.any?(&:confirmation_required?)- endendendenddiff --git a/spree/core/app/models/concerns/spree/purchase/payment_processing.rb b/spree/core/app/models/concerns/spree/purchase/payment_processing.rbindex e6281b10d0..b62d441ac5 100644--- a/spree/core/app/models/concerns/spree/purchase/payment_processing.rb+++ b/spree/core/app/models/concerns/spree/purchase/payment_processing.rb@@ -21,6 +21,22 @@ module Spreepayments.pendingend+ # Free checkouts have no money to collect.+ #+ # @return [Boolean]+ def payment_required?+ total.to_f > 0.0+ end++ # Whether a confirm/review pass is expected before completion —+ # computed from data only.+ #+ # @return [Boolean]+ def confirmation_required?+ Spree::Config[:always_include_confirm_step] ||+ payments.valid.map(&:payment_method).compact.any?(&:confirmation_required?)+ end+def unprocessed_paymentspayments.select(&:checkout?)enddiff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rbindex 91a37cccc9..f4d2de4bba 100644--- a/spree/core/app/models/spree/cart.rb+++ b/spree/core/app/models/spree/cart.rb@@ -27,6 +27,7 @@ module Spreeinclude Spree::Purchase::GiftCardsinclude Spree::Purchase::LineItemCurrenciesinclude Spree::Purchase::PaymentProcessing+ include Spree::Purchase::AddressBook# Concurrency is manual (the API's OrderLock semantics — compare# client-sent version, 409 on mismatch); Rails auto-locking must not@@ -123,7 +124,6 @@ module Spreealias items line_itemsaccepts_nested_attributes_for :line_items- accepts_nested_attributes_for :ship_address, :bill_addressaccepts_nested_attributes_for :paymentsalias_method :shipping_address_attributes=, :ship_address_attributes=alias_method :billing_address_attributes=, :bill_address_attributes=@@ -169,6 +169,8 @@ module Spree# Mirrors Order#can_be_deleted? — a completed cart is an immutable audit# record, and settled money must never be deleted.+ #+ # @return [Boolean]def can_be_deleted?!completed? && payments.completed.empty?end@@ -203,6 +205,8 @@ module Spreeend# Total fulfillment discount applied by promotions, as a positive amount.+ #+ # @return [BigDecimal]def fulfillment_discountdiscounts.for_fulfillments.sum(:amount) * -1end@@ -354,12 +358,5 @@ module Spreecartend- private-- # Same-object copy as Spree::Order — the two FKs share one address row.- def clone_shipping_address- self.bill_address = ship_address if ship_address- true- endendenddiff --git a/spree/core/app/models/spree/checkout/default_requirements.rb b/spree/core/app/models/spree/checkout/default_requirements.rbindex 36b1466ec0..7b3ccfb087 100644--- a/spree/core/app/models/spree/checkout/default_requirements.rb+++ b/spree/core/app/models/spree/checkout/default_requirements.rb@@ -2,24 +2,23 @@ module Spreemodule Checkout# Built-in checkout requirements that map to the standard Spree checkout flow.#- # Checks line items, email, shipping address, shipping method, and payment.- # In Spree 6 these same checks will read from the +Cart+ model instead of- # the state machine — the API contract stays identical.+ # Checks line items, email, shipping address, shipping method, and payment+ # against the cart — checkout is a cart-phase concern.## @see Requirementsclass DefaultRequirements- # @param order [Spree::Order]- def initialize(order)- @order = order+ # @param cart [Spree::Cart]+ def initialize(cart)+ @cart = cartend# @return [Array<Hash{Symbol => String}>] unmet default requirements as# +{ step:, field:, message: }+ hashesdef call[].tap do |r|- r << req('cart', 'line_items', Spree.t('checkout_requirements.line_items_required')) unless @order.line_items.any?- r << req('address', 'email', Spree.t('checkout_requirements.email_required')) unless @order.email.present?- r << req('address', 'ship_address', Spree.t('checkout_requirements.ship_address_required')) if @order.requires_ship_address? && @order.ship_address.blank?+ r << req('cart', 'line_items', Spree.t('checkout_requirements.line_items_required')) unless @cart.line_items.any?+ r << req('address', 'email', Spree.t('checkout_requirements.email_required')) unless @cart.email.present?+ r << req('address', 'ship_address', Spree.t('checkout_requirements.ship_address_required')) if @cart.requires_ship_address? && @cart.ship_address.blank?r << req('delivery', 'shipping_method', Spree.t('checkout_requirements.shipping_method_required')) if delivery_required? && !shipping_method_selected?r << req('payment', 'payment', Spree.t('checkout_requirements.payment_required')) if payment_required? && !payment_satisfied?end@@ -28,19 +27,19 @@ module Spreeprivatedef delivery_required?- @order.has_checkout_step?('delivery') && @order.delivery_required?+ @cart.delivery_required?enddef shipping_method_selected?- @order.fulfillments.any? && @order.fulfillments.all? { |fulfillment| fulfillment.delivery_method.present? }+ @cart.fulfillments.any? && @cart.fulfillments.all? { |fulfillment| fulfillment.delivery_method.present? }enddef payment_required?- @order.has_checkout_step?('payment') && @order.payment_required?+ @cart.payment_required?enddef payment_satisfied?- @order.payments.valid.any?+ @cart.payments.valid.any?enddef req(step, field, message)diff --git a/spree/core/app/models/spree/checkout/registry.rb b/spree/core/app/models/spree/checkout/registry.rbindex 2da71c3369..440462fcaf 100644--- a/spree/core/app/models/spree/checkout/registry.rb+++ b/spree/core/app/models/spree/checkout/registry.rb@@ -13,8 +13,8 @@ module Spree# Spree::Checkout::Registry.register_step(# name: :loyalty,# before: :payment,- # satisfied: ->(order) { order.loyalty_verified? },- # requirements: ->(order) { [{ step: 'loyalty', field: 'loyalty_number', message: 'Required' }] }+ # satisfied: ->(cart) { cart.loyalty_verified? },+ # requirements: ->(cart) { [{ step: 'loyalty', field: 'loyalty_number', message: 'Required' }] }# )## @example Add a requirement to an existing step@@ -22,7 +22,7 @@ module Spree# step: :payment,# field: :po_number,# message: 'PO number is required',- # satisfied: ->(order) { order.po_number.present? }+ # satisfied: ->(cart) { cart.po_number.present? }# )## @example Remove a step@@ -32,8 +32,8 @@ module Spree# Register a new custom checkout step.## @param name [String, Symbol] unique step identifier- # @param satisfied [Proc] lambda accepting an order, returns true when step is complete- # @param requirements [Proc] lambda accepting an order, returns Array of requirement hashes+ # @param satisfied [Proc] lambda accepting a cart, returns true when step is complete+ # @param requirements [Proc] lambda accepting a cart, returns Array of requirement hashes# @param options [Hash] additional options forwarded to {Step} (+:before+, +:after+, +:applicable+)# @return [Array<Step>] the updated steps listdef register_step(name:, satisfied:, requirements:, **options)@@ -45,7 +45,7 @@ module Spree# @param step [String, Symbol] checkout step this requirement belongs to# @param field [String, Symbol] field identifier# @param message [String] human-readable validation message- # @param satisfied [Proc] lambda accepting an order, returns true when met+ # @param satisfied [Proc] lambda accepting a cart, returns true when met# @param options [Hash] additional options forwarded to {Requirement} (+:applicable+)# @return [Array<Requirement>] the updated requirements listdef add_requirement(step:, field:, message:, satisfied:, **options)diff --git a/spree/core/app/models/spree/checkout/requirement.rb b/spree/core/app/models/spree/checkout/requirement.rbindex 4e49f2b04e..7f021a0b88 100644--- a/spree/core/app/models/spree/checkout/requirement.rb+++ b/spree/core/app/models/spree/checkout/requirement.rb@@ -10,8 +10,8 @@ module Spree# step: :payment,# field: :po_number,# message: 'PO number is required for business accounts',- # satisfied: ->(order) { order.po_number.present? },- # applicable: ->(order) { order.account&.business? }+ # satisfied: ->(cart) { cart.po_number.present? },+ # applicable: ->(cart) { cart.account&.business? }# )class Requirement# @return [String] checkout step this requirement belongs to@@ -26,8 +26,8 @@ module Spree# @param step [String, Symbol] checkout step this requirement belongs to# @param field [String, Symbol] field identifier# @param message [String] human-readable validation message- # @param satisfied [Proc] lambda accepting an order, returns true when met- # @param applicable [Proc] lambda accepting an order, returns true when this requirement applies+ # @param satisfied [Proc] lambda accepting a cart, returns true when met+ # @param applicable [Proc] lambda accepting a cart, returns true when this requirement applies# (defaults to always applicable)def initialize(step:, field:, message:, satisfied:, applicable: ->(_) { true })@step = step.to_s@@ -37,13 +37,13 @@ module Spree@applicable_proc = applicableend- # @param order [Spree::Order]+ # @param cart [Spree::Cart]# @return [Boolean] whether the requirement has been met- def satisfied?(order) = @satisfied_proc.call(order)+ def satisfied?(cart) = @satisfied_proc.call(cart)- # @param order [Spree::Order]- # @return [Boolean] whether this requirement applies to the given order- def applicable?(order) = @applicable_proc.call(order)+ # @param cart [Spree::Cart]+ # @return [Boolean] whether this requirement applies to the given cart+ def applicable?(cart) = @applicable_proc.call(cart)endendenddiff --git a/spree/core/app/models/spree/checkout/requirements.rb b/spree/core/app/models/spree/checkout/requirements.rbindex 07a6b0d6b0..0b902256f4 100644--- a/spree/core/app/models/spree/checkout/requirements.rb+++ b/spree/core/app/models/spree/checkout/requirements.rb@@ -1,6 +1,6 @@module Spreemodule Checkout- # Aggregates all checkout requirements for an order.+ # Aggregates all checkout requirements for a cart.## Combines built-in checks from {DefaultRequirements} with custom steps and# requirements registered in {Registry}. The resulting array of hashes is@@ -10,13 +10,13 @@ module Spree# { step: String, field: String, message: String }## @example- # reqs = Spree::Checkout::Requirements.new(order)+ # reqs = Spree::Checkout::Requirements.new(cart)# reqs.call # => [{ step: "address", field: "email", message: "Email address is required" }]# reqs.met? # => falseclass Requirements- # @param order [Spree::Order]- def initialize(order)- @order = order+ # @param cart [Spree::Cart]+ def initialize(cart)+ @cart = cartend# @return [Array<Hash{Symbol => String}>] all unmet requirements@@ -33,22 +33,22 @@ module Spree# @return [Array<Hash>] built-in checkout requirementsdef default- DefaultRequirements.new(@order).call+ DefaultRequirements.new(@cart).callend# @return [Array<Hash>] requirements from unsatisfied registered stepsdef from_registered_stepsRegistry.ordered_steps- .select { |s| s.applicable?(@order) }- .reject { |s| s.satisfied?(@order) }- .flat_map { |s| s.requirements(@order) }+ .select { |s| s.applicable?(@cart) }+ .reject { |s| s.satisfied?(@cart) }+ .flat_map { |s| s.requirements(@cart) }end# @return [Array<Hash>] requirements from unsatisfied registered requirementsdef from_additional_requirementsRegistry.requirements- .select { |r| r.applicable?(@order) }- .reject { |r| r.satisfied?(@order) }+ .select { |r| r.applicable?(@cart) }+ .reject { |r| r.satisfied?(@cart) }.map { |r| { step: r.step, field: r.field, message: r.message } }endenddiff --git a/spree/core/app/models/spree/checkout/step.rb b/spree/core/app/models/spree/checkout/step.rbindex 5a48277657..70bc29c57c 100644--- a/spree/core/app/models/spree/checkout/step.rb+++ b/spree/core/app/models/spree/checkout/step.rb@@ -6,8 +6,8 @@ module Spree# Spree::Checkout::Registry.register_step(# name: :loyalty,# before: :payment,- # satisfied: ->(order) { order.loyalty_verified? },- # requirements: ->(order) { [{ step: 'loyalty', field: 'loyalty_number', message: 'Enter loyalty number' }] }+ # satisfied: ->(cart) { cart.loyalty_verified? },+ # requirements: ->(cart) { [{ step: 'loyalty', field: 'loyalty_number', message: 'Enter loyalty number' }] }# )class Step# @return [String] step name@@ -20,10 +20,10 @@ module Spreeattr_reader :before# @param name [String, Symbol] unique step identifier- # @param satisfied [Proc] lambda accepting an order, returns true when the step is complete- # @param requirements [Proc] lambda accepting an order, returns Array of requirement hashes+ # @param satisfied [Proc] lambda accepting a cart, returns true when the step is complete+ # @param requirements [Proc] lambda accepting a cart, returns Array of requirement hashes# (+{ step:, field:, message: }+) describing what is still needed- # @param applicable [Proc] lambda accepting an order, returns true when this step applies+ # @param applicable [Proc] lambda accepting a cart, returns true when this step applies# (defaults to always applicable)# @param after [String, Symbol, nil] place this step after the named checkout step# @param before [String, Symbol, nil] place this step before the named checkout step@@ -36,17 +36,17 @@ module Spree@applicable_proc = applicableend- # @param order [Spree::Order]+ # @param cart [Spree::Cart]# @return [Boolean] whether the step's conditions have been met- def satisfied?(order) = @satisfied_proc.call(order)+ def satisfied?(cart) = @satisfied_proc.call(cart)- # @param order [Spree::Order]+ # @param cart [Spree::Cart]# @return [Array<Hash{Symbol => String}>] outstanding requirement hashes (+{ step:, field:, message: }+)- def requirements(order) = @requirements_proc.call(order)+ def requirements(cart) = @requirements_proc.call(cart)- # @param order [Spree::Order]- # @return [Boolean] whether this step applies to the given order- def applicable?(order) = @applicable_proc.call(order)+ # @param cart [Spree::Cart]+ # @return [Boolean] whether this step applies to the given cart+ def applicable?(cart) = @applicable_proc.call(cart)endendenddiff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rbindex 6a1ffc5c8a..d0be211ae8 100644--- a/spree/core/app/models/spree/line_item.rb+++ b/spree/core/app/models/spree/line_item.rb@@ -51,7 +51,7 @@ module Spreevalidates_with Spree::Stock::AvailabilityValidator, if: -> { variant.present? }validate :ensure_proper_currency, if: -> { owner.present? }- before_destroy :verify_order_inventory_before_destroy, if: -> { order&.has_checkout_step?('delivery') }+ before_destroy :verify_order_inventory_before_destroy, if: -> { order&.delivery_required? }after_save :update_inventoryafter_save :update_adjustments@@ -336,7 +336,7 @@ module Spreeenddef update_inventory- if (saved_changes? || target_fulfillment.present?) && order&.has_checkout_step?('delivery')+ if (saved_changes? || target_fulfillment.present?) && order&.delivery_required?verify_order_inventoryendenddiff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 2de461a07c..f7138151c2 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -23,14 +23,13 @@ module Spreeinclude Spree::Purchase::Marketinclude Spree::Purchase::Currencyinclude Spree::Purchase::Locale- include Spree::Purchase::CheckoutStepsinclude Spree::Purchase::DigitalItemsinclude Spree::Purchase::Taxationinclude Spree::Purchase::StoreCreditsinclude Spree::Purchase::GiftCardsinclude Spree::Purchase::LineItemCurrenciesinclude Spree::Purchase::PaymentProcessing- include Spree::Order::AddressBook+ include Spree::Purchase::AddressBookinclude Spree::Core::NumberGenerator.new(prefix: 'R')include Spree::NumberIdentifier@@ -384,6 +383,8 @@ module Spreeend# Total fulfillment discount applied by promotions, as a positive amount.+ #+ # @return [BigDecimal]def fulfillment_discountdiscounts.for_fulfillments.sum(:amount) * -1end@@ -743,11 +744,6 @@ module SpreeSpree::CouponCodes::CouponCodesHandler.new(order: self).use_all_codesend- def has_step?(step)- checkout_steps.include?(step)- end--def log_state_changes(state_name:, old_state:, new_state:)state_changes.create(previous_state: old_state,diff --git a/spree/core/spec/models/concerns/spree/purchase/address_book_spec.rb b/spree/core/spec/models/concerns/spree/purchase/address_book_spec.rbnew file mode 100644index 0000000000..241067d954--- /dev/null+++ b/spree/core/spec/models/concerns/spree/purchase/address_book_spec.rb@@ -0,0 +1,139 @@+require 'spec_helper'++# Shared battery for Spree::Purchase::AddressBook, run against BOTH hosts.+# Checkout moved from Order to Cart once already and silently lost this+# behavior (dedup, default promotion, ownership guard) — the shared examples+# exist so it cannot happen again without a red suite.+RSpec.shared_examples 'an address book host' do+ let(:store) { @default_store }+ let(:user) { create(:user) }++ let(:address_attributes) do+ attributes_for(:address).merge(user_id: nil)+ end++ describe '#ship_address_attributes=' do+ it 'creates a new address owned by the record user' do+ record.ship_address_attributes = address_attributes++ expect(record.ship_address).to be_persisted+ expect(record.ship_address.user).to eq(user)+ end++ it 'reuses an identical existing address instead of creating a duplicate' do+ existing = Spree::Address.create!(address_attributes.merge(user_id: user.id))++ expect do+ record.ship_address_attributes = address_attributes.merge(user_id: user.id)+ end.not_to change(Spree::Address, :count)++ expect(record.ship_address).to eq(existing)+ end++ it 'updates an editable saved address in place when an id is given' do+ saved = create(:address, user: user)++ record.ship_address_attributes = { id: saved.id, first_name: 'Renamed' }++ expect(record.ship_address.id).to eq(saved.id)+ expect(saved.reload.first_name).to eq('Renamed')+ end++ it 'promotes the address to the user default ship address' do+ record.ship_address_attributes = address_attributes++ expect(user.ship_address).to eq(record.ship_address)+ end++ it 'does not promote a quick-checkout wallet address to the user default' do+ record.ship_address_attributes = address_attributes.merge(quick_checkout: true)++ expect(user.ship_address).to be_nil+ end+ end++ describe '#bill_address_attributes=' do+ it 'promotes the address to the user default bill address' do+ record.bill_address_attributes = address_attributes++ expect(user.bill_address).to eq(record.bill_address)+ end+ end++ describe '#ship_address_id= / #bill_address_id=' do+ let(:own_address) { create(:address, user: user) }+ let(:foreign_address) { create(:address, user: create(:user)) }++ it 'accepts an address owned by the record user' do+ record.ship_address_id = own_address.id++ expect(record.ship_address_id).to eq(own_address.id)+ end++ it 'refuses an address owned by another user' do+ record.ship_address_id = foreign_address.id++ expect(record.ship_address_id).to be_nil+ end++ it 'refuses any address for a guest record' do+ guest_record.ship_address_id = own_address.id++ expect(guest_record.ship_address_id).to be_nil+ end+ end++ describe '#clone_shipping_address' do+ it 'copies the ship address onto the bill address and the user default' do+ ship_address = create(:address, user: user)+ record.ship_address = ship_address++ record.clone_shipping_address++ expect(record.bill_address).to eq(ship_address)+ expect(user.bill_address).to eq(ship_address)+ end+ end++ describe '#assign_default_addresses!' do+ let(:default_bill) { create(:address, user: user) }+ let(:default_ship) { create(:address, user: user) }++ before do+ user.update!(bill_address: default_bill, ship_address: default_ship)+ end++ it 'fills both addresses from the user defaults' do+ allow(record).to receive(:delivery_required?).and_return(true)++ record.assign_default_addresses!++ expect(record.bill_address.id).to eq(default_bill.id)+ expect(record.ship_address.id).to eq(default_ship.id)+ end++ it 'skips the ship address when no physical delivery is required' do+ allow(record).to receive(:delivery_required?).and_return(false)++ record.assign_default_addresses!++ expect(record.ship_address).to be_nil+ end+ end+end++RSpec.describe Spree::Purchase::AddressBook do+ context 'included in Spree::Cart' do+ let(:record) { create(:cart, store: store, customer: user, ship_address: nil, bill_address: nil) }+ let(:guest_record) { create(:cart, store: store, customer: nil) }++ it_behaves_like 'an address book host'+ end++ context 'included in Spree::Order' do+ let(:record) { create(:order, store: store, user: user, ship_address: nil, bill_address: nil) }+ let(:guest_record) { create(:order, store: store, user: nil, email: '[email protected]') }++ it_behaves_like 'an address book host'+ end+enddiff --git a/spree/core/spec/models/spree/cart_spec.rb b/spree/core/spec/models/spree/cart_spec.rbindex 049193cac3..5f63de44f0 100644--- a/spree/core/spec/models/spree/cart_spec.rb+++ b/spree/core/spec/models/spree/cart_spec.rb@@ -4,6 +4,69 @@ describe Spree::Cart, type: :model dolet(:store) { @default_store }let(:customer) { create(:user) }+ describe '#checkout_steps' do+ let(:cart) { build(:cart, store: store) }++ before { allow(cart).to receive_messages(delivery_required?: true) }++ context 'when confirmation not required' do+ before do+ allow(cart).to receive_messages confirmation_required?: false+ allow(cart).to receive_messages payment_required?: true+ end++ specify do+ expect(cart.checkout_steps).to eq(%w(address delivery payment complete))+ end+ end++ context 'when confirmation required' do+ before do+ allow(cart).to receive_messages confirmation_required?: true+ allow(cart).to receive_messages payment_required?: true+ end++ specify do+ expect(cart.checkout_steps).to eq(%w(address delivery payment confirm complete))+ end+ end++ context 'when delivery not required' do+ before { allow(cart).to receive_messages delivery_required?: false }++ specify do+ expect(cart.checkout_steps).to eq(%w(address complete))+ end+ end++ context 'when payment not required' do+ before { allow(cart).to receive_messages payment_required?: false }++ specify do+ expect(cart.checkout_steps).to eq(%w(address delivery complete))+ end+ end++ context 'when payment required' do+ before { allow(cart).to receive_messages payment_required?: true }++ specify do+ expect(cart.checkout_steps).to eq(%w(address delivery payment complete))+ end+ end+ end++ describe '#checkout_step_index' do+ let(:cart) { build(:cart, store: store) }++ before { allow(cart).to receive_messages(delivery_required?: true) }++ it 'always returns an integer' do+ expect(cart.checkout_step_index('imnotthere')).to be_a Integer+ expect(cart.checkout_step_index('delivery')).to be > 0+ end+ end+describe 'lifecycle events' doit 'publishes cart.* lifecycle events' doexpect(described_class.lifecycle_events_enabled).to be true@@ -154,4 +217,334 @@ describe Spree::Cart, type: :model doendendend++ describe '#coupon_code=' do+ it 'normalizes to a stripped, lowercased code' do+ expect(build(:cart, coupon_code: ' SAVE10 ').read_attribute(:coupon_code)).to eq('save10')+ end++ it 'tolerates nil' do+ expect(build(:cart, coupon_code: nil).read_attribute(:coupon_code)).to be_nil+ end+ end++ describe '#number' do+ it 'mirrors the prefixed id (deprecated API bridge)' do+ cart = create(:cart, store: store)++ expect(cart.number).to eq(cart.prefixed_id)+ end+ end++ describe '#preferred_stock_location_id=' do+ let(:cart) { create(:cart, store: store) }+ let(:pickup_location) { create(:stock_location, pickup_enabled: true) }++ it 'accepts a raw id of a pickup-enabled location' do+ cart.preferred_stock_location_id = pickup_location.id++ expect(cart.preferred_stock_location_id).to eq(pickup_location.id)+ expect(cart.preferred_stock_location).to eq(pickup_location)+ end++ it 'accepts a prefixed id' do+ cart.preferred_stock_location_id = pickup_location.prefixed_id++ expect(cart.preferred_stock_location_id).to eq(pickup_location.id)+ end++ it 'clears the preference on blank' do+ cart.preferred_stock_location_id = pickup_location.id+ cart.preferred_stock_location_id = ''++ expect(cart.preferred_stock_location_id).to be_nil+ end++ it 'rejects a location that is not pickup-enabled' do+ not_pickup = create(:stock_location, pickup_enabled: false)++ expect { cart.preferred_stock_location_id = not_pickup.id }.to raise_error(ActiveRecord::RecordNotFound)+ end+ end++ describe '#can_be_deleted?' do+ it 'is true for an open cart without settled payments' do+ expect(build(:cart)).to be_can_be_deleted+ end++ it 'is false once completed' do+ expect(build(:cart, completed_at: Time.current)).not_to be_can_be_deleted+ end++ it 'is false with a completed payment' do+ cart = create(:cart_with_line_items, store: store)+ create(:payment, cart: cart, order: nil, state: 'completed', amount: cart.total)++ expect(cart.reload).not_to be_can_be_deleted+ end+ end++ describe '#in_checkout?' do+ it 'begins once checkout-only data appears and ends at completion' do+ expect(build(:cart)).not_to be_in_checkout+ expect(build(:cart, email: '[email protected]')).to be_in_checkout+ expect(build(:cart, ship_address: create(:address))).to be_in_checkout+ expect(build(:cart, email: '[email protected]', completed_at: Time.current)).not_to be_in_checkout+ end+ end++ describe '#recalculate_totals!' do+ it 'runs the configured totals workflow on itself' do+ cart = create(:cart, store: store)++ expect(Spree.cart_recalculate_totals_workflow).to receive(:call).with(cart: cart)+ cart.recalculate_totals!+ end+ end++ describe '#shipping_eq_billing_address?' do+ it 'compares the two addresses' do+ address = create(:address)+ expect(build(:cart, ship_address: address, bill_address: address).shipping_eq_billing_address?).to be(true)+ expect(build(:cart, ship_address: address, bill_address: create(:address)).shipping_eq_billing_address?).to be(false)+ end+ end++ describe '#use_shipping?' do+ it 'accepts the truthy form values' do+ expect(build(:cart, use_shipping: true).use_shipping?).to be(true)+ expect(build(:cart, use_shipping: 'true').use_shipping?).to be(true)+ expect(build(:cart, use_shipping: '1').use_shipping?).to be(true)+ expect(build(:cart, use_shipping: false).use_shipping?).to be(false)+ expect(build(:cart).use_shipping?).to be(false)+ end+ end++ describe '#quantity' do+ it 'sums line item quantities' do+ cart = create(:cart_with_line_items, line_items_count: 2)+ cart.line_items.first.update_column(:quantity, 3)++ expect(cart.quantity).to eq(4)+ end+ end++ describe 'money readers' do+ let(:cart) { build(:cart, total: 100, payment_total: 40) }++ it '#outstanding_balance is total minus payment_total' do+ expect(cart.outstanding_balance).to eq(60)+ end++ it '#outstanding_balance? reflects a non-zero balance' do+ expect(cart.outstanding_balance?).to be(true)+ expect(build(:cart, total: 40, payment_total: 40).outstanding_balance?).to be(false)+ end++ it '#paid? requires a positive total fully covered by payments' do+ expect(build(:cart, total: 100, payment_total: 100)).to be_paid+ expect(build(:cart, total: 100, payment_total: 40)).not_to be_paid+ expect(build(:cart, total: 0, payment_total: 0)).not_to be_paid+ end++ it '#amount_due nets applied store credit and never goes negative' do+ allow(cart).to receive(:total_applied_store_credit).and_return(70)++ expect(cart.amount_due).to eq(0)++ allow(cart).to receive(:total_applied_store_credit).and_return(10)+ expect(cart.amount_due).to eq(50)+ end+ end++ describe '#fulfillment_discount' do+ it 'sums fulfillment-attached discounts as a positive amount' do+ cart = create(:cart_with_line_items, store: store)+ fulfillment = create(:fulfillment, cart: cart, order: nil)+ create(:discount, order: nil, cart: cart, line_item: nil, fulfillment: fulfillment, amount: -4, kind: 'promotion')++ expect(cart.fulfillment_discount).to eq(4)+ end+ end++ describe '#delivery_required?' do+ it 'is false for an empty cart and true with physical items' do+ expect(build(:cart)).not_to be_delivery_required+ expect(create(:cart_with_line_items)).to be_delivery_required+ end++ it 'is false for a digital-only cart' do+ cart = create(:cart_with_line_items)+ allow(cart).to receive(:digital?).and_return(true)++ expect(cart).not_to be_delivery_required+ end+ end++ describe '#backordered?' do+ let(:cart) { create(:cart_with_line_items, store: store) }+ let!(:fulfillment) { create(:fulfillment, cart: cart, order: nil) }++ it 'reflects backordered fulfillment items' do+ expect(cart.reload).not_to be_backordered++ fulfillment.fulfillment_items.update_all(status: 'backordered')+ expect(Spree::Cart.find(cart.id)).to be_backordered+ end+ end++ describe '#guest_checkout_disallowed?' do+ it 'never blocks a signed-in customer' do+ expect(build(:cart, customer: create(:user)).guest_checkout_disallowed?).to be(false)+ end++ it 'follows the channel guest-checkout flag for guests' do+ cart = create(:cart, store: store, customer: nil)++ allow(cart.channel).to receive(:guest_checkout_enabled?).and_return(false)+ expect(cart.guest_checkout_disallowed?).to be(true)++ allow(cart.channel).to receive(:guest_checkout_enabled?).and_return(true)+ expect(cart.guest_checkout_disallowed?).to be(false)+ end+ end++ describe '#payment_methods' do+ let(:cart) { create(:cart, store: store) }++ it 'lists active front-end methods available for this cart' do+ available = create(:credit_card_payment_method, store: store)+ inactive = create(:credit_card_payment_method, store: store, active: false)++ expect(cart.payment_methods).to include(available)+ expect(cart.payment_methods).not_to include(inactive)+ expect(cart.collect_frontend_payment_methods).to eq(cart.payment_methods)+ end+ end++ describe '#associate_user!' do+ let(:cart) { create(:cart, store: store, customer: nil, email: nil) }+ let(:user) { create(:user, ship_address: create(:address), bill_address: create(:address)) }++ it 'binds the user, takes the email and copies valid default addresses' do+ cart.associate_user!(user)++ expect(cart.reload.customer).to eq(user)+ expect(cart.email).to eq(user.email)+ expect(cart.bill_address_id).to eq(user.bill_address_id)+ end++ it 'keeps an existing email when override is disabled' do+ cart.update!(email: '[email protected]')++ cart.associate_user!(user, false)++ expect(cart.reload.email).to eq('[email protected]')+ end+ end++ describe '#merge!' do+ it 'runs the configured merge strategy and reloads' do+ cart = create(:cart, store: store)+ other_cart = create(:cart, store: store)+ strategy = class_double(Spree::Carts::Merge).as_stubbed_const++ expect(strategy).to receive(:call).with(cart: cart, other_cart: other_cart, user: nil)+ allow(Spree::Dependencies).to receive(:cart_merge_strategy).and_return('Spree::Carts::Merge')++ cart.merge!(other_cart)+ end+ end++ describe 'delivery proposals' do+ let(:country) { @default_country }+ let(:state) { country.states.first || create(:state, country: country) }+ let!(:zone) { create(:zone) }+ let!(:zone_member) { create(:zone_member, zone: zone, zoneable: country) }+ let!(:shipping_method) do+ create(:shipping_method).tap do |method|+ method.calculator.preferred_amount = 5+ method.calculator.save+ end+ end+ let!(:stock_location) { Spree::StockLocation.first || create(:stock_location, country: country, state: state) }+ let(:ship_address) { create(:address, country: country, state: state) }+ let(:cart) { create(:cart_with_line_items, store: store, ship_address: ship_address, email: '[email protected]') }++ describe '#rebuild_fulfillments!' do+ it 'builds cart-owned proposals from the current items and address' do+ cart.rebuild_fulfillments!++ expect(cart.fulfillments).to be_present+ expect(cart.fulfillments.map(&:order_id).uniq).to eq([nil])+ expect(cart.fulfillments.first.address_id).to eq(ship_address.id)+ expect(cart.fulfillments.first.delivery_rates).to be_present+ end++ it 'is idempotent and never touches a completed cart' do+ cart.rebuild_fulfillments!+ expect { cart.rebuild_fulfillments! }.not_to change { cart.fulfillments.count }++ cart.update_columns(completed_at: Time.current)+ expect(Spree::Cart.find(cart.id).rebuild_fulfillments!).to be_nil+ end+ end++ describe '#prune_undeliverable_fulfillments!' do+ it 'drops proposals with no delivery rates and records a warning per line item' do+ cart.rebuild_fulfillments!+ cart.fulfillments.each { |fulfillment| fulfillment.delivery_rates.delete_all }++ cart.prune_undeliverable_fulfillments!++ expect(cart.fulfillments.reload).to be_empty+ expect(cart.warnings.map { |warning| warning[:code] }).to include('delivery_unavailable')+ end+ end++ describe '#ensure_available_shipping_rates' do+ it 'errors when there are no deliverable proposals' do+ expect(cart.ensure_available_shipping_rates).to be(false)+ expect(cart.errors[:base]).to be_present++ cart.errors.clear+ cart.rebuild_fulfillments!+ expect(cart.ensure_available_shipping_rates).to be(true)+ end+ end++ describe '#set_fulfillments_cost' do+ it 'persists the delivery total and grand total from fulfillment costs' do+ cart.rebuild_fulfillments!+ cart.recalculate_totals!++ cart.set_fulfillments_cost++ expect(cart.reload.delivery_total).to eq(cart.fulfillments.sum(&:cost))+ expect(cart.total).to eq(cart.item_total + cart.delivery_total + cart.adjustment_total)+ end+ end++ describe '#ensure_updated_fulfillments' do+ it 'rebuilds for open carts and skips completed ones' do+ expect(cart).to receive(:rebuild_fulfillments!)+ cart.ensure_updated_fulfillments++ cart.update_columns(completed_at: Time.current)+ completed = Spree::Cart.find(cart.id)+ expect(completed).not_to receive(:rebuild_fulfillments!)+ completed.ensure_updated_fulfillments+ end+ end++ describe '#recalculate_for_address_change!' do+ it 'reprices items, rebuilds proposals and recalculates totals' do+ cart.recalculate_for_address_change!++ expect(cart.fulfillments.reload).to be_present+ expect(cart.reload.delivery_total).to be > 0+ expect(cart.total).to eq(cart.item_total + cart.delivery_total + cart.adjustment_total)+ end+ end+ endenddiff --git a/spree/core/spec/models/spree/order/checkout_spec.rb b/spree/core/spec/models/spree/order/checkout_spec.rbindex b7895f1230..4d929a263a 100644--- a/spree/core/spec/models/spree/order/checkout_spec.rb+++ b/spree/core/spec/models/spree/order/checkout_spec.rb@@ -7,61 +7,6 @@ describe Spree::Order, type: :model dolet(:accept_marketing) { false }let!(:state) { country.states.first || create(:state, country: country, name: 'New York', abbr: 'NY') }- describe '#checkout_steps' do- context 'when confirmation not required' do- before do- allow(order).to receive_messages confirmation_required?: false- allow(order).to receive_messages payment_required?: true- end-- specify do- expect(order.checkout_steps).to eq(%w(address delivery payment complete))- end- end-- context 'when confirmation required' do- before do- allow(order).to receive_messages confirmation_required?: true- allow(order).to receive_messages payment_required?: true- end-- specify do- expect(order.checkout_steps).to eq(%w(address delivery payment confirm complete))- end- end-- context 'when delivery not required' do- before { allow(order).to receive_messages delivery_required?: false }-- specify do- expect(order.checkout_steps).to eq(%w(address complete))- end- end-- context 'when payment not required' do- before { allow(order).to receive_messages payment_required?: false }-- specify do- expect(order.checkout_steps).to eq(%w(address delivery complete))- end- end-- context 'when payment required' do- before { allow(order).to receive_messages payment_required?: true }-- specify do- expect(order.checkout_steps).to eq(%w(address delivery payment complete))- end- end- end-- describe '#checkout_step_index' do- it 'always returns an integer' do- expect(order.checkout_step_index('imnotthere')).to be_a Integer- expect(order.checkout_step_index('delivery')).to be > 0- end- end-describe '#assign_default_addresses!' dolet(:default_address) { create(:address, state: state) }let(:order) { create(:order, store: store, ship_address: nil, bill_address: nil, user: user) }