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.

Add Exchange and Claim as first-class models with their workflows

Damian Legawiec352885a019c6
diff --git a/spree/core/app/models/spree/claim.rb b/spree/core/app/models/spree/claim.rb
new file mode 100644
index 0000000000..89c4f20f9b
--- /dev/null
+++ b/spree/core/app/models/spree/claim.rb
@@ -0,0 +1,65 @@
+module Spree
+ # A customer reports a problem — damaged, missing or wrong item — and the
+ # merchant makes it right without necessarily asking for the goods back.
+ #
+ # This has no equivalent in the legacy chain: merchants either created a
+ # manual order or faked it through a return authorization received
+ # immediately. Transitions are workflows
+ # (docs/plans/6.0-returns-exchanges-claims.md).
+ class Claim < Spree.base_class
+ has_prefix_id :claim
+
+ include Spree::Core::NumberGenerator.new(prefix: 'CLM', length: 9)
+ include Spree::NumberIdentifier
+ include Spree::SingleStoreResource
+ include Spree::HasStatus
+ include Spree::Metadata
+
+ publishes_lifecycle_events
+
+ has_status :open, :approved, :resolved, :denied, :canceled, default: :open
+
+ # Configuration, not a frozen constant — a merchant can add a type
+ # without reopening core. Types are pure labels with no per-type
+ # behaviour, so extending the list needs no accompanying workflow.
+ class_attribute :claim_types, default: %w[damaged missing wrong_item other]
+
+ # Unlike claim types, each resolution drives real behaviour in
+ # Spree::Claims::Resolve, so this stays closed — an unrecognised value
+ # would silently do nothing.
+ RESOLUTIONS = %w[refund replacement refund_and_replacement].freeze
+
+ belongs_to :store, class_name: 'Spree::Store'
+ belongs_to :order, class_name: 'Spree::Order', inverse_of: :claims
+ belongs_to :reason, class_name: 'Spree::ReturnAuthorizationReason', optional: true
+ belongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: true
+
+ has_many :claim_line_items, class_name: 'Spree::ClaimLineItem',
+ dependent: :destroy, inverse_of: :claim
+ has_many :refunds, class_name: 'Spree::Refund', as: :originator, dependent: :nullify
+
+ validates :order, :claim_type, presence: true
+ validates :claim_line_items, presence: true, on: :create
+ validates :claim_type, inclusion: { in: ->(record) { record.class.claim_types } }
+ validates :resolution, inclusion: { in: RESOLUTIONS }, allow_nil: true
+
+ accepts_nested_attributes_for :claim_line_items, allow_destroy: true
+
+ delegate :currency, to: :order
+
+ self.whitelisted_ransackable_attributes = %w[number status claim_type created_at]
+ self.whitelisted_ransackable_associations = %w[order reason]
+
+ def refund_total
+ claim_line_items.sum(&:refund_amount)
+ end
+
+ def display_refund_total
+ Spree::Money.new(refund_total, currency: currency)
+ end
+
+ def replacement_line_items
+ claim_line_items.select(&:send_replacement)
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/claim_line_item.rb b/spree/core/app/models/spree/claim_line_item.rb
new file mode 100644
index 0000000000..1cd4e13c61
--- /dev/null
+++ b/spree/core/app/models/spree/claim_line_item.rb
@@ -0,0 +1,47 @@
+module Spree
+ # One problem item on a {Spree::Claim}, and how it is being made right:
+ # money back, a replacement, or both.
+ class ClaimLineItem < Spree.base_class
+ has_prefix_id :cli
+
+ belongs_to :claim, class_name: 'Spree::Claim', inverse_of: :claim_line_items
+ belongs_to :line_item, class_name: 'Spree::LineItem'
+ belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'
+ # Nil means "send the same thing again"; a different variant swaps it.
+ belongs_to :replacement_variant, -> { with_deleted }, class_name: 'Spree::Variant', optional: true
+
+ # Photographic evidence of damage, supplied by the customer.
+ has_many_attached :images
+
+ validates :line_item, :variant, presence: true
+ validates :quantity, numericality: { greater_than: 0 }
+ validates :refund_amount, numericality: { greater_than_or_equal_to: 0 }
+
+ before_validation :set_variant_from_line_item, on: :create
+
+ delegate :order, :currency, to: :claim
+
+ # What the customer paid for the affected units, after discounts — the
+ # ceiling for a refund on this line.
+ def paid_amount
+ return 0 if line_item.nil? || line_item.quantity.to_i.zero?
+
+ (line_item.amount / line_item.quantity) * quantity.to_i
+ end
+
+ def display_refund_amount
+ Spree::Money.new(refund_amount, currency: currency)
+ end
+
+ # What actually ships when the claim is resolved with a replacement.
+ def variant_to_send
+ replacement_variant || variant
+ end
+
+ private
+
+ def set_variant_from_line_item
+ self.variant ||= line_item&.variant
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/exchange.rb b/spree/core/app/models/spree/exchange.rb
index 7185840e34..480b56eea8 100644
--- a/spree/core/app/models/spree/exchange.rb
+++ b/spree/core/app/models/spree/exchange.rb
@@ -1,50 +1,56 @@
module Spree
- class Exchange
- class UnableToCreateShipments < StandardError; end
-
- def initialize(order, reimbursement_objects)
- @order = order
- @reimbursement_objects = reimbursement_objects
- end
-
- def description
- @reimbursement_objects.map do |reimbursement_object|
- "#{reimbursement_object.variant.options_text} => #{reimbursement_object.exchange_variant.options_text}"
- end.join(' | ')
- end
-
- def display_amount
- Spree::Money.new @reimbursement_objects.sum(&:total)
- end
-
- def perform!
- new_exchange_inventory_units = @reimbursement_objects.map(&:build_default_exchange_inventory_unit)
- shipments = Spree::Stock::Coordinator.new(@order, new_exchange_inventory_units).shipments
- shipments_units = shipments.flat_map(&:fulfillment_items)
-
- if shipments_units.sum(&:quantity) != new_exchange_inventory_units.sum(&:quantity)
- raise UnableToCreateShipments, 'Could not generate shipments for all items. Out of stock?'
- end
-
- @order.fulfillments += shipments
- @order.save!
-
- shipments.each do |shipment|
- shipment.update!(@order)
- shipment.finalize!
- end
- end
-
- def to_key
- nil
- end
-
- def self.param_key
- 'spree_exchange'
+ # A customer sends items back and gets different ones — a different size,
+ # colour or product.
+ #
+ # First-class rather than the legacy "a ReturnItem that happens to carry an
+ # exchange_variant_id, processed through ReimbursementType::Exchange": you
+ # can now ask for all exchanges this month, or every exchange awaiting
+ # fulfillment, without digging through return items.
+ #
+ # Transitions are workflows (docs/plans/6.0-returns-exchanges-claims.md).
+ class Exchange < Spree.base_class
+ has_prefix_id :exch
+
+ include Spree::Core::NumberGenerator.new(prefix: 'EX', length: 9)
+ include Spree::NumberIdentifier
+ include Spree::SingleStoreResource
+ include Spree::HasStatus
+ include Spree::Metadata
+
+ publishes_lifecycle_events
+
+ has_status :requested, :approved, :received, :fulfilled, :canceled,
+ default: :requested
+
+ belongs_to :store, class_name: 'Spree::Store'
+ belongs_to :order, class_name: 'Spree::Order', inverse_of: :exchanges
+ belongs_to :stock_location, class_name: 'Spree::StockLocation'
+ belongs_to :reason, class_name: 'Spree::ReturnAuthorizationReason', optional: true
+ belongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: true
+
+ has_many :exchange_line_items, class_name: 'Spree::ExchangeLineItem',
+ dependent: :destroy, inverse_of: :exchange
+ has_many :refunds, class_name: 'Spree::Refund', as: :originator, dependent: :nullify
+
+ validates :order, :stock_location, presence: true
+ validates :exchange_line_items, presence: true, on: :create
+
+ accepts_nested_attributes_for :exchange_line_items, allow_destroy: true
+
+ delegate :currency, to: :order
+
+ self.whitelisted_ransackable_attributes = %w[number status created_at]
+ self.whitelisted_ransackable_associations = %w[order reason]
+
+ # Positive when the replacements cost more than what came back (the
+ # customer owes the difference), negative when they cost less (a refund
+ # is due).
+ def price_difference
+ exchange_line_items.sum(&:price_difference)
end
- def self.model_name
- Spree::Exchange
+ def display_price_difference
+ Spree::Money.new(price_difference, currency: currency)
end
end
end
diff --git a/spree/core/app/models/spree/exchange_line_item.rb b/spree/core/app/models/spree/exchange_line_item.rb
new file mode 100644
index 0000000000..8f986c749d
--- /dev/null
+++ b/spree/core/app/models/spree/exchange_line_item.rb
@@ -0,0 +1,53 @@
+module Spree
+ # One swap on a {Spree::Exchange}: a quantity of one variant going back,
+ # the same quantity of another coming out.
+ class ExchangeLineItem < Spree.base_class
+ has_prefix_id :eli
+
+ belongs_to :exchange, class_name: 'Spree::Exchange', inverse_of: :exchange_line_items
+ belongs_to :fulfillment_item, class_name: 'Spree::FulfillmentItem'
+ belongs_to :line_item, class_name: 'Spree::LineItem'
+ belongs_to :original_variant, -> { with_deleted }, class_name: 'Spree::Variant'
+ belongs_to :new_variant, -> { with_deleted }, class_name: 'Spree::Variant'
+
+ validates :fulfillment_item, :line_item, :original_variant, :new_variant, presence: true
+ validates :quantity, numericality: { greater_than: 0 }
+ validates :received_quantity, numericality: { greater_than_or_equal_to: 0 }
+
+ validate :replacement_must_differ
+
+ before_validation :set_original_variant_from_line_item, on: :create
+
+ delegate :order, :currency, to: :exchange
+
+ # What the customer paid for the units coming back, after discounts —
+ # not the list price, which would over-credit a discounted line.
+ def original_price
+ return 0 if line_item.nil? || line_item.quantity.to_i.zero?
+
+ (line_item.amount / line_item.quantity) * quantity.to_i
+ end
+
+ def new_variant_price
+ new_variant.price_in(currency)&.amount.to_d * quantity.to_i
+ end
+
+ def price_difference
+ new_variant_price - original_price
+ end
+
+ private
+
+ def set_original_variant_from_line_item
+ self.original_variant ||= line_item&.variant
+ end
+
+ # Swapping a variant for itself is a return, not an exchange.
+ def replacement_must_differ
+ return if original_variant_id.blank? || new_variant_id.blank?
+ return if original_variant_id != new_variant_id
+
+ errors.add(:new_variant, :must_differ_from_original)
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 3b00c0fff4..200684db70 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -164,6 +164,8 @@ module Spree
has_many :payment_sessions, inverse_of: :order, class_name: 'Spree::PaymentSession'
has_many :return_authorizations, inverse_of: :order, class_name: 'Spree::ReturnAuthorization'
has_many :returns, -> { order(:created_at) }, inverse_of: :order, class_name: 'Spree::Return'
+ has_many :exchanges, -> { order(:created_at) }, inverse_of: :order, class_name: 'Spree::Exchange'
+ has_many :claims, -> { order(:created_at) }, inverse_of: :order, class_name: 'Spree::Claim'
has_many :cancellations, -> { order(:created_at) }, inverse_of: :order, class_name: 'Spree::OrderCancellation'
has_many :approvals, -> { order(:created_at) }, inverse_of: :order, class_name: 'Spree::OrderApproval'
end
diff --git a/spree/core/app/models/spree/permission_sets/order_display.rb b/spree/core/app/models/spree/permission_sets/order_display.rb
index 660afb70e5..2ba4c5211b 100644
--- a/spree/core/app/models/spree/permission_sets/order_display.rb
+++ b/spree/core/app/models/spree/permission_sets/order_display.rb
@@ -21,6 +21,8 @@ module Spree
can [:read, :admin], Spree::CustomerReturn
can [:read, :admin], Spree::Reimbursement
can [:read, :admin], Spree::Return
+ can [:read, :admin], Spree::Exchange
+ can [:read, :admin], Spree::Claim
can [:read, :admin], Spree::Refund
can [:read, :admin], Spree::StoreCredit
can [:read, :admin], Spree::GiftCard
diff --git a/spree/core/app/models/spree/permission_sets/order_management.rb b/spree/core/app/models/spree/permission_sets/order_management.rb
index 8d6b1bda9a..4d2473dc1f 100644
--- a/spree/core/app/models/spree/permission_sets/order_management.rb
+++ b/spree/core/app/models/spree/permission_sets/order_management.rb
@@ -21,6 +21,8 @@ module Spree
can :manage, Spree::CustomerReturn
can :manage, Spree::Reimbursement
can :manage, Spree::Return
+ can :manage, Spree::Exchange
+ can :manage, Spree::Claim
can :manage, Spree::Refund
can :manage, Spree::StoreCredit
can :manage, Spree::GiftCard
diff --git a/spree/core/app/models/spree/reimbursement_type/exchange.rb b/spree/core/app/models/spree/reimbursement_type/exchange.rb
index 2a79bc8732..ecaae98d27 100644
--- a/spree/core/app/models/spree/reimbursement_type/exchange.rb
+++ b/spree/core/app/models/spree/reimbursement_type/exchange.rb
@@ -2,7 +2,7 @@ class Spree::ReimbursementType::Exchange < Spree::ReimbursementType
def self.reimburse(reimbursement, return_items, simulate)
return [] unless return_items.present?
- exchange = Spree::Exchange.new(reimbursement.order, return_items)
+ exchange = Spree::ReimbursementType::ExchangeProcessor.new(reimbursement.order, return_items)
exchange.perform! unless simulate
[exchange]
end
diff --git a/spree/core/app/models/spree/reimbursement_type/exchange_processor.rb b/spree/core/app/models/spree/reimbursement_type/exchange_processor.rb
new file mode 100644
index 0000000000..7fcb1e08b6
--- /dev/null
+++ b/spree/core/app/models/spree/reimbursement_type/exchange_processor.rb
@@ -0,0 +1,56 @@
+module Spree
+ class ReimbursementType
+ # Legacy exchange execution for the ReturnAuthorization/Reimbursement
+ # chain. Renamed out of Spree::Exchange, which is now the first-class
+ # exchange model (docs/plans/6.0-returns-exchanges-claims.md); this stays
+ # until that chain is dropped.
+ class ExchangeProcessor
+ class UnableToCreateShipments < StandardError; end
+
+ def initialize(order, reimbursement_objects)
+ @order = order
+ @reimbursement_objects = reimbursement_objects
+ end
+
+ def description
+ @reimbursement_objects.map do |reimbursement_object|
+ "#{reimbursement_object.variant.options_text} => #{reimbursement_object.exchange_variant.options_text}"
+ end.join(' | ')
+ end
+
+ def display_amount
+ Spree::Money.new @reimbursement_objects.sum(&:total)
+ end
+
+ def perform!
+ new_exchange_inventory_units = @reimbursement_objects.map(&:build_default_exchange_inventory_unit)
+ shipments = Spree::Stock::Coordinator.new(@order, new_exchange_inventory_units).shipments
+ shipments_units = shipments.flat_map(&:fulfillment_items)
+
+ if shipments_units.sum(&:quantity) != new_exchange_inventory_units.sum(&:quantity)
+ raise UnableToCreateShipments, 'Could not generate shipments for all items. Out of stock?'
+ end
+
+ @order.fulfillments += shipments
+ @order.save!
+
+ shipments.each do |shipment|
+ shipment.update!(@order)
+ shipment.finalize!
+ end
+ end
+
+ def to_key
+ nil
+ end
+
+ def self.param_key
+ 'spree_exchange'
+ end
+
+ def self.model_name
+ Spree::ReimbursementType::ExchangeProcessor
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/claims/approve.rb b/spree/core/app/workflows/spree/claims/approve.rb
new file mode 100644
index 0000000000..d3c0d4dfea
--- /dev/null
+++ b/spree/core/app/workflows/spree/claims/approve.rb
@@ -0,0 +1,38 @@
+module Spree
+ module Claims
+ class Approve < Spree::Workflow
+ hooks :validate, :after_approve
+
+ # @param claim [Spree::Claim]
+ # @param approver [Object, nil]
+ def perform(claim:, approver: nil)
+ super
+
+ step :ensure_approvable
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :mark_approved
+ end
+
+ run_hooks :after_approve
+ claim.publish_event('claim.approved')
+ success(claim.reload)
+ end
+
+ private
+
+ def ensure_approvable
+ failure(claim, :not_open) unless claim.open?
+ end
+
+ def mark_approved
+ claim.update!(
+ status: 'approved',
+ approved_at: Time.current,
+ created_by: claim.created_by || approver
+ )
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/claims/cancel.rb b/spree/core/app/workflows/spree/claims/cancel.rb
new file mode 100644
index 0000000000..927831256d
--- /dev/null
+++ b/spree/core/app/workflows/spree/claims/cancel.rb
@@ -0,0 +1,37 @@
+module Spree
+ module Claims
+ class Cancel < Spree::Workflow
+ hooks :validate, :after_cancel
+
+ # @param claim [Spree::Claim]
+ # @param reason [String, nil]
+ def perform(claim:, reason: nil)
+ super
+
+ step :ensure_cancellable
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :mark_canceled
+ end
+
+ run_hooks :after_cancel
+ claim.publish_event('claim.canceled')
+ success(claim.reload)
+ end
+
+ private
+
+ def ensure_cancellable
+ return if claim.open? || claim.approved?
+
+ failure(claim, :not_cancellable)
+ end
+
+ def mark_canceled
+ memo = [claim.memo, reason].compact_blank.join("\n")
+ claim.update!(status: 'canceled', canceled_at: Time.current, memo: memo.presence)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/claims/create.rb b/spree/core/app/workflows/spree/claims/create.rb
new file mode 100644
index 0000000000..e3d447acc2
--- /dev/null
+++ b/spree/core/app/workflows/spree/claims/create.rb
@@ -0,0 +1,83 @@
+module Spree
+ module Claims
+ # Opens a claim: the customer reports damaged, missing or wrong items.
+ #
+ # No goods come back — that is the point of a claim — so there is nothing
+ # to receive and nothing to restock.
+ class Create < Spree::Workflow
+ hooks :validate, :after_create
+
+ attr_reader :claim
+
+ # @param order [Spree::Order]
+ # @param items [Array<Hash>] `[{ line_item:, quantity:, description:,
+ # send_replacement:, replacement_variant:, refund_amount: }]`
+ # @param claim_type [String] one of Spree::Claim.claim_types
+ # @param reason [Spree::ReturnAuthorizationReason, nil]
+ # @param memo [String, nil]
+ # @param created_by [Object, nil] nil for customer self-service
+ def perform(order:, items:, claim_type: 'other', reason: nil, memo: nil, created_by: nil)
+ super
+
+ step :ensure_claimable
+ step :normalize_items
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :build_claim
+ end
+
+ run_hooks :after_create
+ claim.publish_event('claim.opened')
+ success(claim.reload)
+ end
+
+ private
+
+ def ensure_claimable
+ failure(order, :order_not_completed) unless order.completed?
+ failure(order, :order_canceled) if order.canceled?
+ failure(order, :no_items_to_claim) if items.blank?
+ failure(order, :invalid_claim_type) unless Spree::Claim.claim_types.include?(claim_type.to_s)
+ end
+
+ def normalize_items
+ @normalized_items = items.map do |item|
+ line_item = item[:line_item]
+ quantity = item[:quantity].to_i
+
+ failure(order, :invalid_quantity) unless quantity.positive?
+ failure(order, :item_not_on_order) unless line_item&.order_id == order.id
+ failure(order, :invalid_quantity) if quantity > line_item.quantity.to_i
+
+ item.merge(line_item: line_item, quantity: quantity)
+ end
+ end
+
+ def build_claim
+ @claim = order.claims.new(
+ store: order.store,
+ claim_type: claim_type,
+ reason: reason,
+ memo: memo,
+ created_by: created_by,
+ status: Spree::Claim.default_status
+ )
+
+ @normalized_items.each do |item|
+ @claim.claim_line_items.build(
+ line_item: item[:line_item],
+ variant: item[:line_item].variant,
+ quantity: item[:quantity],
+ description: item[:description],
+ send_replacement: item.fetch(:send_replacement, false),
+ replacement_variant: item[:replacement_variant],
+ refund_amount: item[:refund_amount] || 0
+ )
+ end
+
+ failure(@claim) unless @claim.save
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/claims/deny.rb b/spree/core/app/workflows/spree/claims/deny.rb
new file mode 100644
index 0000000000..514f032f66
--- /dev/null
+++ b/spree/core/app/workflows/spree/claims/deny.rb
@@ -0,0 +1,35 @@
+module Spree
+ module Claims
+ class Deny < Spree::Workflow
+ hooks :validate, :after_deny
+
+ # @param claim [Spree::Claim]
+ # @param reason [String, nil] recorded on the claim for the customer
+ def perform(claim:, reason: nil)
+ super
+
+ step :ensure_deniable
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :mark_denied
+ end
+
+ run_hooks :after_deny
+ claim.publish_event('claim.denied')
+ success(claim.reload)
+ end
+
+ private
+
+ def ensure_deniable
+ failure(claim, :not_open) unless claim.open?
+ end
+
+ def mark_denied
+ memo = [claim.memo, reason].compact_blank.join("\n")
+ claim.update!(status: 'denied', denied_at: Time.current, memo: memo.presence)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/claims/resolve.rb b/spree/core/app/workflows/spree/claims/resolve.rb
new file mode 100644
index 0000000000..c98f41070a
--- /dev/null
+++ b/spree/core/app/workflows/spree/claims/resolve.rb
@@ -0,0 +1,141 @@
+module Spree
+ module Claims
+ # Makes a claim right: money back, a replacement shipment, or both.
+ #
+ # The resolution is an argument rather than something read off the record,
+ # so the caller's intent is explicit at the call site and an admin can
+ # decide at resolution time rather than at claim creation.
+ class Resolve < Spree::Workflow
+ hooks :validate, :before_settle, :after_resolve
+
+ attr_reader :refunds, :fulfillments
+
+ # @param claim [Spree::Claim] must be approved
+ # @param resolution [String] one of Spree::Claim::RESOLUTIONS
+ # @param refund_method [String] 'store_credit' or 'original_payment'
+ # @param amount [BigDecimal, Numeric, nil] defaults to the claim total
+ # @param resolver [Object, nil]
+ def perform(claim:, resolution:, refund_method: 'store_credit', amount: nil, resolver: nil)
+ super
+
+ @refunds = []
+ @fulfillments = []
+ step :ensure_resolvable
+ step :resolve_amount if refunding?
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ run_hooks :before_settle
+ step :build_replacement_fulfillments if replacing?
+ step :issue_store_credit if refunding? && internal_refund?
+ step :mark_resolved
+ end
+
+ external_step :refund_at_gateway if refunding? && !internal_refund?
+
+ step :recalculate_order
+ run_hooks :after_resolve
+ claim.publish_event('claim.resolved')
+ success(claim.reload)
+ end
+
+ private
+
+ def refunding?
+ resolution.to_s.include?('refund')
+ end
+
+ def replacing?
+ resolution.to_s.include?('replacement')
+ end
+
+ def internal_refund?
+ refund_method.to_s == 'store_credit'
+ end
+
+ def ensure_resolvable
+ failure(claim, :invalid_resolution) unless Spree::Claim::RESOLUTIONS.include?(resolution.to_s)
+ failure(claim, :not_approved) unless claim.approved?
+ end
+
+ # A claim can never refund more than the customer paid for the affected
+ # items.
+ def resolve_amount
+ @amount_to_refund = (amount || claim.refund_total).to_d
+ ceiling = claim.claim_line_items.sum(&:paid_amount).to_d
+
+ failure(claim, :nothing_to_refund) unless @amount_to_refund.positive?
+ failure(claim, :refund_exceeds_paid) if @amount_to_refund > ceiling
+ end
+
+ def build_replacement_fulfillments
+ units = claim.replacement_line_items.map do |line|
+ claim.order.fulfillment_items.new(
+ variant: line.variant_to_send,
+ quantity: line.quantity,
+ line_item: line.line_item,
+ order: claim.order,
+ status: 'on_hand'
+ )
+ end
+
+ failure(claim, :nothing_to_replace) if units.empty?
+
+ @fulfillments = Spree::Stock::Coordinator.new(claim.order, units).shipments
+ if @fulfillments.flat_map(&:fulfillment_items).sum(&:quantity) != units.sum(&:quantity)
+ failure(claim, :replacement_out_of_stock)
+ end
+
+ claim.order.fulfillments += @fulfillments
+ claim.order.save!
+ @fulfillments.each { |fulfillment| fulfillment.update!(claim.order) }
+ end
+
+ def issue_store_credit
+ @refunds = [
+ Spree::StoreCredit.create!(
+ store: claim.store,
+ user: claim.order.user,
+ amount: @amount_to_refund,
+ currency: claim.currency,
+ category: Spree::StoreCreditCategory.default_reimbursement_category,
+ created_by: resolver,
+ originator: claim,
+ memo: "Claim #{claim.number}"
+ )
+ ]
+ end
+
+ def refund_at_gateway
+ remaining = @amount_to_refund
+
+ claim.order.payments.completed.each do |payment|
+ break unless remaining.positive?
+
+ creditable = [payment.credit_allowed.to_d, remaining].min
+ next unless creditable.positive?
+
+ @refunds << payment.refunds.create!(
+ amount: creditable,
+ reason: Spree::RefundReason.return_processing_reason,
+ refunder: resolver,
+ originator: claim
+ )
+ remaining -= creditable
+ end
+
+ failure(claim, :no_refundable_payments) if @refunds.empty?
+ rescue Spree::Core::GatewayError => error
+ failure(claim, error.message)
+ end
+
+ def mark_resolved
+ claim.update!(status: 'resolved', resolution: resolution, resolved_at: Time.current)
+ end
+
+ def recalculate_order
+ claim.order.recalculate_totals!
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/exchanges/approve.rb b/spree/core/app/workflows/spree/exchanges/approve.rb
new file mode 100644
index 0000000000..b13404d8c0
--- /dev/null
+++ b/spree/core/app/workflows/spree/exchanges/approve.rb
@@ -0,0 +1,38 @@
+module Spree
+ module Exchanges
+ class Approve < Spree::Workflow
+ hooks :validate, :after_approve
+
+ # @param exchange [Spree::Exchange]
+ # @param approver [Object, nil]
+ def perform(exchange:, approver: nil)
+ super
+
+ step :ensure_approvable
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :mark_approved
+ end
+
+ run_hooks :after_approve
+ exchange.publish_event('exchange.approved')
+ success(exchange.reload)
+ end
+
+ private
+
+ def ensure_approvable
+ failure(exchange, :not_requested) unless exchange.requested?
+ end
+
+ def mark_approved
+ exchange.update!(
+ status: 'approved',
+ approved_at: Time.current,
+ created_by: exchange.created_by || approver
+ )
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/exchanges/cancel.rb b/spree/core/app/workflows/spree/exchanges/cancel.rb
new file mode 100644
index 0000000000..8e6248c4db
--- /dev/null
+++ b/spree/core/app/workflows/spree/exchanges/cancel.rb
@@ -0,0 +1,40 @@
+module Spree
+ module Exchanges
+ # Withdraws an exchange before the goods arrive. Once received, the
+ # merchant holds the customer's items and must either fulfill the
+ # replacement or refund.
+ class Cancel < Spree::Workflow
+ hooks :validate, :after_cancel
+
+ # @param exchange [Spree::Exchange]
+ # @param reason [String, nil]
+ def perform(exchange:, reason: nil)
+ super
+
+ step :ensure_cancellable
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :mark_canceled
+ end
+
+ run_hooks :after_cancel
+ exchange.publish_event('exchange.canceled')
+ success(exchange.reload)
+ end
+
+ private
+
+ def ensure_cancellable
+ return if exchange.requested? || exchange.approved?
+
+ failure(exchange, :not_cancellable)
+ end
+
+ def mark_canceled
+ memo = [exchange.memo, reason].compact_blank.join("\n")
+ exchange.update!(status: 'canceled', canceled_at: Time.current, memo: memo.presence)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/exchanges/create.rb b/spree/core/app/workflows/spree/exchanges/create.rb
new file mode 100644
index 0000000000..426ce9649d
--- /dev/null
+++ b/spree/core/app/workflows/spree/exchanges/create.rb
@@ -0,0 +1,90 @@
+module Spree
+ module Exchanges
+ # Opens an exchange request: items coming back, and what should go out
+ # in their place.
+ class Create < Spree::Workflow
+ hooks :validate, :after_create
+
+ attr_reader :exchange
+
+ # @param order [Spree::Order]
+ # @param items [Array<Hash>] `[{ fulfillment_item:, new_variant:, quantity: }]`
+ # @param stock_location [Spree::StockLocation, nil]
+ # @param reason [Spree::ReturnAuthorizationReason, nil]
+ # @param memo [String, nil]
+ # @param created_by [Object, nil] nil for customer self-service
+ def perform(order:, items:, stock_location: nil, reason: nil, memo: nil, created_by: nil)
+ super
+
+ step :ensure_exchangeable
+ step :normalize_items
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :build_exchange
+ end
+
+ run_hooks :after_create
+ exchange.publish_event('exchange.requested')
+ success(exchange.reload)
+ end
+
+ private
+
+ def ensure_exchangeable
+ failure(order, :order_not_completed) unless order.completed?
+ failure(order, :order_canceled) if order.canceled?
+ failure(order, :no_items_to_exchange) if items.blank?
+ end
+
+ def normalize_items
+ @normalized_items = items.map do |item|
+ fulfillment_item = item[:fulfillment_item]
+ new_variant = item[:new_variant]
+ quantity = item[:quantity].to_i
+
+ failure(order, :invalid_quantity) unless quantity.positive?
+ failure(order, :item_not_on_order) unless fulfillment_item&.order_id == order.id
+ failure(order, :replacement_required) if new_variant.blank?
+
+ # A replacement nobody can ship is not an exchange the merchant can
+ # honour — catch it now rather than at fulfillment time.
+ unless new_variant.purchasable?
+ failure(order, "#{new_variant.name} is not available")
+ end
+
+ { fulfillment_item: fulfillment_item, new_variant: new_variant, quantity: quantity }
+ end
+ end
+
+ def build_exchange
+ @exchange = order.exchanges.new(
+ store: order.store,
+ stock_location: stock_location || default_stock_location,
+ reason: reason,
+ memo: memo,
+ created_by: created_by,
+ status: Spree::Exchange.default_status
+ )
+
+ @normalized_items.each do |item|
+ fulfillment_item = item[:fulfillment_item]
+ @exchange.exchange_line_items.build(
+ fulfillment_item: fulfillment_item,
+ line_item: fulfillment_item.line_item,
+ original_variant: fulfillment_item.variant,
+ new_variant: item[:new_variant],
+ quantity: item[:quantity]
+ )
+ end
+
+ failure(@exchange) unless @exchange.save
+ end
+
+ def default_stock_location
+ @normalized_items.first[:fulfillment_item].fulfillment&.stock_location ||
+ order.store.stock_locations.first
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/exchanges/fulfill.rb b/spree/core/app/workflows/spree/exchanges/fulfill.rb
new file mode 100644
index 0000000000..9c1c06f4e1
--- /dev/null
+++ b/spree/core/app/workflows/spree/exchanges/fulfill.rb
@@ -0,0 +1,135 @@
+module Spree
+ module Exchanges
+ # Ships the replacements and settles the difference in price.
+ #
+ # The money branch mirrors Returns::Refund: a credit the customer is owed
+ # can be store credit (an internal ledger write, inside the transaction)
+ # or a gateway refund (outside it). A balance the customer owes is left
+ # for the merchant to collect — charging a stored card without a fresh
+ # authorization is not something core should do silently.
+ class Fulfill < Spree::Workflow
+ hooks :validate, :before_settle, :after_fulfill
+
+ # Fulfillments created for the replacement items.
+ attr_reader :fulfillments, :refunds
+
+ # @param exchange [Spree::Exchange] must be received
+ # @param refund_method [String] how a credit is returned when the
+ # replacements are cheaper: 'store_credit' or 'original_payment'
+ # @param refunder [Object, nil]
+ def perform(exchange:, refund_method: 'store_credit', refunder: nil)
+ super
+
+ @fulfillments = []
+ @refunds = []
+ step :ensure_fulfillable
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :build_replacement_fulfillments
+ run_hooks :before_settle
+ step :issue_store_credit if credit_due? && internal_refund?
+ step :mark_fulfilled
+ end
+
+ external_step :refund_at_gateway if credit_due? && !internal_refund?
+
+ step :recalculate_order
+ run_hooks :after_fulfill
+ exchange.publish_event('exchange.fulfilled')
+ success(exchange.reload)
+ end
+
+ private
+
+ def internal_refund?
+ refund_method.to_s == 'store_credit'
+ end
+
+ # Negative price difference means the replacements cost less than what
+ # came back, so the customer is owed the difference.
+ def credit_due?
+ exchange.price_difference.to_d.negative?
+ end
+
+ def credit_amount
+ exchange.price_difference.to_d.abs
+ end
+
+ def ensure_fulfillable
+ failure(exchange, :not_received) unless exchange.received?
+ end
+
+ # Only lines that actually came back are replaced — a customer who
+ # returned two of three items gets two replacements.
+ def build_replacement_fulfillments
+ units = exchange.exchange_line_items.filter_map do |line|
+ next if line.received_quantity.to_i.zero?
+
+ exchange.order.fulfillment_items.new(
+ variant: line.new_variant,
+ quantity: line.received_quantity,
+ line_item: line.line_item,
+ order: exchange.order,
+ status: 'on_hand'
+ )
+ end
+
+ failure(exchange, :nothing_to_fulfill) if units.empty?
+
+ @fulfillments = Spree::Stock::Coordinator.new(exchange.order, units).shipments
+ if @fulfillments.flat_map(&:fulfillment_items).sum(&:quantity) != units.sum(&:quantity)
+ failure(exchange, :replacement_out_of_stock)
+ end
+
+ exchange.order.fulfillments += @fulfillments
+ exchange.order.save!
+ @fulfillments.each { |fulfillment| fulfillment.update!(exchange.order) }
+ end
+
+ def issue_store_credit
+ @refunds = [
+ Spree::StoreCredit.create!(
+ store: exchange.store,
+ user: exchange.order.user,
+ amount: credit_amount,
+ currency: exchange.currency,
+ category: Spree::StoreCreditCategory.default_reimbursement_category,
+ created_by: refunder,
+ originator: exchange,
+ memo: "Exchange #{exchange.number}"
+ )
+ ]
+ end
+
+ def refund_at_gateway
+ remaining = credit_amount
+
+ exchange.order.payments.completed.each do |payment|
+ break unless remaining.positive?
+
+ creditable = [payment.credit_allowed.to_d, remaining].min
+ next unless creditable.positive?
+
+ @refunds << payment.refunds.create!(
+ amount: creditable,
+ reason: Spree::RefundReason.return_processing_reason,
+ refunder: refunder,
+ originator: exchange
+ )
+ remaining -= creditable
+ end
+ rescue Spree::Core::GatewayError => error
+ failure(exchange, error.message)
+ end
+
+ def mark_fulfilled
+ exchange.update!(status: 'fulfilled', fulfilled_at: Time.current)
+ end
+
+ def recalculate_order
+ exchange.order.recalculate_totals!
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/exchanges/receive.rb b/spree/core/app/workflows/spree/exchanges/receive.rb
new file mode 100644
index 0000000000..9fe5cf2a18
--- /dev/null
+++ b/spree/core/app/workflows/spree/exchanges/receive.rb
@@ -0,0 +1,86 @@
+module Spree
+ module Exchanges
+ # Records what came back. Same partial-receipt shape as returns: the
+ # warehouse enters actual quantities and flags anything unsellable.
+ class Receive < Spree::Workflow
+ hooks :validate, :before_restock, :after_receive
+
+ # @param exchange [Spree::Exchange]
+ # @param items [Array<Hash>, nil] `[{ exchange_line_item:, quantity:, resellable: }]`
+ # @param received_by [Object, nil]
+ def perform(exchange:, items: nil, received_by: nil)
+ super
+
+ step :ensure_receivable
+ step :normalize_items
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :record_receipt
+ run_hooks :before_restock
+ step :restock_resellable_items
+ step :mark_received
+ end
+
+ run_hooks :after_receive
+ exchange.publish_event('exchange.received')
+ success(exchange.reload)
+ end
+
+ private
+
+ def ensure_receivable
+ failure(exchange, :not_approved) unless exchange.approved?
+ end
+
+ def normalize_items
+ @normalized_items =
+ if items.nil?
+ exchange.exchange_line_items.map do |line|
+ { exchange_line_item: line, quantity: line.quantity, resellable: true }
+ end
+ else
+ items.map { |item| normalize_item(item) }
+ end
+
+ failure(exchange, :no_items_received) if @normalized_items.sum { |item| item[:quantity] }.zero?
+ end
+
+ def normalize_item(item)
+ line = item[:exchange_line_item]
+ quantity = item[:quantity].to_i
+
+ failure(exchange, :item_not_on_exchange) unless line&.exchange_id == exchange.id
+ failure(exchange, :invalid_quantity) if quantity.negative? || quantity > line.quantity
+
+ { exchange_line_item: line, quantity: quantity, resellable: item.fetch(:resellable, true) }
+ end
+
+ def record_receipt
+ @normalized_items.each do |item|
+ item[:exchange_line_item].update!(
+ received_quantity: item[:quantity],
+ resellable: item[:resellable]
+ )
+ end
+ end
+
+ def restock_resellable_items
+ @normalized_items.each do |item|
+ next unless item[:resellable]
+ next unless item[:quantity].positive?
+
+ exchange.stock_location.restock(
+ item[:exchange_line_item].original_variant,
+ item[:quantity],
+ exchange
+ )
+ end
+ end
+
+ def mark_received
+ exchange.update!(status: 'received', received_at: Time.current)
+ end
+ end
+ end
+end
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 44f2a9cf3c..91fb58f3e5 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -253,6 +253,10 @@ en:
attributes:
origin:
must_be_origin_only: must be an origin (scheme and host) without path, query, or fragment
+ spree/exchange_line_item:
+ attributes:
+ new_variant:
+ must_differ_from_original: must be different from the item being returned
spree/calculator/tiered_flat_rate:
attributes:
base:
diff --git a/spree/core/db/migrate/20260802210001_create_spree_exchanges_and_claims.rb b/spree/core/db/migrate/20260802210001_create_spree_exchanges_and_claims.rb
new file mode 100644
index 0000000000..95f41c6d08
--- /dev/null
+++ b/spree/core/db/migrate/20260802210001_create_spree_exchanges_and_claims.rb
@@ -0,0 +1,80 @@
+class CreateSpreeExchangesAndClaims < ActiveRecord::Migration[8.1]
+ def change
+ create_table :spree_exchanges do |t|
+ t.string :number, null: false
+ t.references :store, null: false
+ t.references :order, null: false
+ t.references :stock_location, null: false
+ t.references :reason
+ t.references :created_by
+ t.string :status, null: false
+ t.text :memo
+ t.datetime :approved_at
+ t.datetime :received_at
+ t.datetime :fulfilled_at
+ t.datetime :canceled_at
+ if t.respond_to?(:jsonb)
+ t.jsonb :metadata
+ else
+ t.json :metadata
+ end
+ t.timestamps
+ end
+
+ add_index :spree_exchanges, :number, unique: true
+ add_index :spree_exchanges, :status
+
+ create_table :spree_exchange_line_items do |t|
+ t.references :exchange, null: false
+ t.references :fulfillment_item, null: false
+ t.references :line_item, null: false
+ # The variant coming back and the one going out — an exchange is a
+ # swap, so both sides live on the row.
+ t.references :original_variant, null: false
+ t.references :new_variant, null: false
+ t.integer :quantity, null: false, default: 1
+ t.integer :received_quantity, null: false, default: 0
+ t.boolean :resellable, null: false, default: true
+ t.timestamps
+ end
+
+ create_table :spree_claims do |t|
+ t.string :number, null: false
+ t.references :store, null: false
+ t.references :order, null: false
+ t.references :reason
+ t.references :created_by
+ t.string :status, null: false
+ t.string :claim_type, null: false
+ t.string :resolution
+ t.text :memo
+ t.datetime :approved_at
+ t.datetime :resolved_at
+ t.datetime :denied_at
+ t.datetime :canceled_at
+ if t.respond_to?(:jsonb)
+ t.jsonb :metadata
+ else
+ t.json :metadata
+ end
+ t.timestamps
+ end
+
+ add_index :spree_claims, :number, unique: true
+ add_index :spree_claims, :status
+
+ create_table :spree_claim_line_items do |t|
+ t.references :claim, null: false
+ t.references :line_item, null: false
+ t.references :variant, null: false
+ # Optional: a replacement may be a different variant, or none at all
+ # when the claim is resolved with money only.
+ t.references :replacement_variant
+ t.integer :quantity, null: false, default: 1
+ t.boolean :send_replacement, null: false, default: false
+ t.decimal :refund_amount, precision: 10, scale: 2, null: false, default: 0
+ t.text :description
+ t.timestamps
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index 540e7bfa76..f6b79b0b34 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -78,6 +78,20 @@ module Spree
return_refund_workflow: 'Spree::Returns::Refund',
return_cancel_workflow: 'Spree::Returns::Cancel',
+ # exchanges
+ exchange_create_workflow: 'Spree::Exchanges::Create',
+ exchange_approve_workflow: 'Spree::Exchanges::Approve',
+ exchange_receive_workflow: 'Spree::Exchanges::Receive',
+ exchange_fulfill_workflow: 'Spree::Exchanges::Fulfill',
+ exchange_cancel_workflow: 'Spree::Exchanges::Cancel',
+
+ # claims
+ claim_create_workflow: 'Spree::Claims::Create',
+ claim_approve_workflow: 'Spree::Claims::Approve',
+ claim_resolve_workflow: 'Spree::Claims::Resolve',
+ claim_deny_workflow: 'Spree::Claims::Deny',
+ claim_cancel_workflow: 'Spree::Claims::Cancel',
+
# tracking numbers
tracking_number_service: 'Spree::TrackingNumbers::BaseService',
diff --git a/spree/core/lib/spree/testing_support/factories/claim_factory.rb b/spree/core/lib/spree/testing_support/factories/claim_factory.rb
new file mode 100644
index 0000000000..fcf38914a2
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/claim_factory.rb
@@ -0,0 +1,34 @@
+FactoryBot.define do
+ factory :claim, class: Spree::Claim do
+ transient do
+ line_items_count { 1 }
+ send_replacement { false }
+ end
+
+ association(:order, factory: :shipped_order)
+ store { order.store }
+ status { Spree::Claim.default_status }
+ claim_type { 'damaged' }
+ memo { 'Arrived with a cracked screen' }
+
+ after(:build) do |claim, evaluator|
+ next if claim.claim_line_items.any?
+
+ claim.order.line_items.limit(evaluator.line_items_count).each do |line_item|
+ claim.claim_line_items.build(
+ line_item: line_item,
+ variant: line_item.variant,
+ quantity: 1,
+ send_replacement: evaluator.send_replacement,
+ refund_amount: evaluator.send_replacement ? 0 : line_item.price,
+ description: 'Screen is cracked'
+ )
+ end
+ end
+
+ factory :approved_claim do
+ status { 'approved' }
+ approved_at { Time.current }
+ end
+ end
+end
diff --git a/spree/core/lib/spree/testing_support/factories/exchange_factory.rb b/spree/core/lib/spree/testing_support/factories/exchange_factory.rb
new file mode 100644
index 0000000000..3090dd8956
--- /dev/null
+++ b/spree/core/lib/spree/testing_support/factories/exchange_factory.rb
@@ -0,0 +1,50 @@
+FactoryBot.define do
+ factory :exchange, class: Spree::Exchange do
+ transient do
+ line_items_count { 1 }
+ # The variant going out. Defaults to a fresh one on the same product so
+ # the swap is meaningful without the caller building a catalog.
+ replacement_variant { nil }
+ end
+
+ association(:order, factory: :shipped_order)
+ store { order.store }
+ stock_location { order.shipments.first&.stock_location || create(:stock_location) }
+ status { Spree::Exchange.default_status }
+ memo { 'Wrong size' }
+
+ after(:build) do |exchange, evaluator|
+ next if exchange.exchange_line_items.any?
+
+ exchange.order.fulfillment_items.limit(evaluator.line_items_count).each do |fulfillment_item|
+ replacement = evaluator.replacement_variant ||
+ create(:variant, product: fulfillment_item.variant.product)
+
+ exchange.exchange_line_items.build(
+ fulfillment_item: fulfillment_item,
+ line_item: fulfillment_item.line_item,
+ original_variant: fulfillment_item.variant,
+ new_variant: replacement,
+ quantity: 1
+ )
+ end
+ end
+
+ factory :approved_exchange do
+ status { 'approved' }
+ approved_at { Time.current }
+ end
+
+ factory :received_exchange do
+ status { 'received' }
+ approved_at { 1.day.ago }
+ received_at { Time.current }
+
+ after(:create) do |exchange|
+ exchange.exchange_line_items.each do |line|
+ line.update!(received_quantity: line.quantity)
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/claim_spec.rb b/spree/core/spec/models/spree/claim_spec.rb
new file mode 100644
index 0000000000..d93087c5ef
--- /dev/null
+++ b/spree/core/spec/models/spree/claim_spec.rb
@@ -0,0 +1,64 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Claim do
+ let(:store) { @default_store }
+
+ it 'generates a prefixed number and starts open' do
+ claim = create(:claim, store: store)
+
+ expect(claim.number).to start_with('CLM')
+ expect(claim).to be_open
+ end
+
+ it 'is reachable from its order' do
+ claim = create(:claim, store: store)
+
+ expect(claim.order.reload.claims).to include(claim)
+ end
+
+ describe 'claim types' do
+ around do |example|
+ original = described_class.claim_types
+ example.run
+ described_class.claim_types = original
+ end
+
+ it 'rejects a type outside the configured list' do
+ expect(build(:claim, store: store, claim_type: 'teleported')).not_to be_valid
+ end
+
+ # Types are labels with no per-type behaviour, so extending needs no
+ # accompanying workflow.
+ it 'accepts a type an extension added' do
+ described_class.claim_types += ['late_delivery']
+
+ expect(create(:claim, store: store, claim_type: 'late_delivery')).to be_persisted
+ end
+ end
+
+ it 'rejects a resolution outside the closed set' do
+ expect(build(:claim, store: store, resolution: 'apologize')).not_to be_valid
+ end
+
+ describe Spree::ClaimLineItem do
+ let(:claim) { create(:claim, store: store) }
+ let(:line) { claim.claim_line_items.first }
+
+ it 'caps a refund at what the customer paid for the units' do
+ line_item = line.line_item
+
+ expect(line.paid_amount).to eq(line_item.amount / line_item.quantity)
+ end
+
+ it 'sends the original variant when no replacement is named' do
+ expect(line.variant_to_send).to eq(line.variant)
+ end
+
+ it 'sends the replacement when one is named' do
+ replacement = create(:variant)
+ line.update!(replacement_variant: replacement)
+
+ expect(line.variant_to_send).to eq(replacement)
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/exchange_spec.rb b/spree/core/spec/models/spree/exchange_spec.rb
index 3932621089..7366e4e689 100644
--- a/spree/core/spec/models/spree/exchange_spec.rb
+++ b/spree/core/spec/models/spree/exchange_spec.rb
@@ -1,76 +1,59 @@
require 'spec_helper'
-module Spree
- describe Exchange, type: :model do
- let(:order) { Spree::Order.new }
-
- let(:return_item_1) { build(:exchange_return_item) }
- let(:return_item_2) { build(:exchange_return_item) }
- let(:return_items) { [return_item_1, return_item_2] }
- let(:exchange) { Exchange.new(order, return_items) }
-
- describe '#description' do
- before do
- allow(return_item_1).to receive(:variant) { double(options_text: 'foo') }
- allow(return_item_1).to receive(:exchange_variant) { double(options_text: 'bar') }
- allow(return_item_2).to receive(:variant) { double(options_text: 'baz') }
- allow(return_item_2).to receive(:exchange_variant) { double(options_text: 'qux') }
- end
-
- it "describes the return items' change in options" do
- expect(exchange.description).to match(/foo => bar/)
- expect(exchange.description).to match(/baz => qux/)
- end
- end
+RSpec.describe Spree::Exchange do
+ let(:store) { @default_store }
+
+ it 'generates a prefixed number and starts as requested' do
+ exchange = create(:exchange, store: store)
+
+ expect(exchange.number).to start_with('EX')
+ expect(exchange).to be_requested
+ end
+
+ it 'is reachable from its order' do
+ exchange = create(:exchange, store: store)
+
+ expect(exchange.order.reload.exchanges).to include(exchange)
+ end
- describe '#display_amount' do
- it 'is the total amount of all return items' do
- expect(exchange.display_amount).to eq Spree::Money.new(0.0)
- end
+ describe '#price_difference' do
+ let(:exchange) { create(:exchange, store: store) }
+ let(:line) { exchange.exchange_line_items.first }
+
+ it 'is positive when the replacement costs more' do
+ line.new_variant.prices.first.update!(amount: line.original_price + 25)
+
+ expect(exchange.reload.price_difference).to be > 0
end
- describe '#perform!' do
- subject { exchange.perform! }
-
- let(:return_item) { create(:exchange_return_item) }
- let(:return_items) { [return_item] }
- let(:order) { return_item.return_authorization.order }
-
- before { return_item.exchange_variant.stock_items.first.adjust_count_on_hand(20) }
-
- it 'creates shipments for the order with the return items exchange inventory units' do
- expect { subject }.to change { order.shipments.count }.by(1)
- new_shipment = order.shipments.last
- expect(new_shipment).to be_ready
- new_inventory_units = new_shipment.inventory_units
- expect(new_inventory_units.count).to eq 1
- expect(new_inventory_units.first.original_return_item).to eq return_item
- expect(new_inventory_units.first.line_item).to eq return_item.inventory_unit.line_item
- end
-
- context 'when it cannot create shipments for all items' do
- before do
- StockItem.where(variant_id: return_item.exchange_variant_id).delete_all
- end
-
- it 'raises an UnableToCreateShipments error' do
- expect do
- subject
- end.to raise_error(Spree::Exchange::UnableToCreateShipments)
- end
- end
+ it 'is negative when the replacement costs less' do
+ line.new_variant.prices.first.update!(amount: 0.01)
+
+ expect(exchange.reload.price_difference).to be < 0
end
+ end
- describe '#to_key' do # for dom_id
- it { expect(Exchange.new(nil, nil).to_key).to be_nil }
+ describe Spree::ExchangeLineItem do
+ let(:exchange) { create(:exchange, store: store) }
+ let(:line) { exchange.exchange_line_items.first }
+
+ # Swapping something for itself is a return, not an exchange.
+ it 'rejects a replacement identical to the original' do
+ line.new_variant = line.original_variant
+
+ expect(line).not_to be_valid
+ expect(line.errors[:new_variant]).to be_present
end
- describe '.param_key' do # for dom_id
- it { expect(Exchange.param_key).to eq 'spree_exchange' }
+ # Crediting the list price would over-refund a discounted line.
+ it 'values the returned units at what the customer paid' do
+ line_item = line.line_item
+
+ expect(line.original_price).to eq(line_item.amount / line_item.quantity)
end
- describe '.model_name' do # for dom_id
- it { expect(Exchange.model_name).to eq Spree::Exchange }
+ it 'starts with nothing received' do
+ expect(line.received_quantity).to eq(0)
end
end
end
diff --git a/spree/core/spec/models/spree/reimbursement_type/exchange_processor_spec.rb b/spree/core/spec/models/spree/reimbursement_type/exchange_processor_spec.rb
new file mode 100644
index 0000000000..240fa474ab
--- /dev/null
+++ b/spree/core/spec/models/spree/reimbursement_type/exchange_processor_spec.rb
@@ -0,0 +1,76 @@
+require 'spec_helper'
+
+module Spree
+ describe ReimbursementType::ExchangeProcessor, type: :model do
+ let(:order) { Spree::Order.new }
+
+ let(:return_item_1) { build(:exchange_return_item) }
+ let(:return_item_2) { build(:exchange_return_item) }
+ let(:return_items) { [return_item_1, return_item_2] }
+ let(:exchange) { ReimbursementType::ExchangeProcessor.new(order, return_items) }
+
+ describe '#description' do
+ before do
+ allow(return_item_1).to receive(:variant) { double(options_text: 'foo') }
+ allow(return_item_1).to receive(:exchange_variant) { double(options_text: 'bar') }
+ allow(return_item_2).to receive(:variant) { double(options_text: 'baz') }
+ allow(return_item_2).to receive(:exchange_variant) { double(options_text: 'qux') }
+ end
+
+ it "describes the return items' change in options" do
+ expect(exchange.description).to match(/foo => bar/)
+ expect(exchange.description).to match(/baz => qux/)
+ end
+ end
+
+ describe '#display_amount' do
+ it 'is the total amount of all return items' do
+ expect(exchange.display_amount).to eq Spree::Money.new(0.0)
+ end
+ end
+
+ describe '#perform!' do
+ subject { exchange.perform! }
+
+ let(:return_item) { create(:exchange_return_item) }
+ let(:return_items) { [return_item] }
+ let(:order) { return_item.return_authorization.order }
+
+ before { return_item.exchange_variant.stock_items.first.adjust_count_on_hand(20) }
+
+ it 'creates shipments for the order with the return items exchange inventory units' do
+ expect { subject }.to change { order.shipments.count }.by(1)
+ new_shipment = order.shipments.last
+ expect(new_shipment).to be_ready
+ new_inventory_units = new_shipment.inventory_units
+ expect(new_inventory_units.count).to eq 1
+ expect(new_inventory_units.first.original_return_item).to eq return_item
+ expect(new_inventory_units.first.line_item).to eq return_item.inventory_unit.line_item
+ end
+
+ context 'when it cannot create shipments for all items' do
+ before do
+ StockItem.where(variant_id: return_item.exchange_variant_id).delete_all
+ end
+
+ it 'raises an UnableToCreateShipments error' do
+ expect do
+ subject
+ end.to raise_error(Spree::ReimbursementType::ExchangeProcessor::UnableToCreateShipments)
+ end
+ end
+ end
+
+ describe '#to_key' do # for dom_id
+ it { expect(ReimbursementType::ExchangeProcessor.new(nil, nil).to_key).to be_nil }
+ end
+
+ describe '.param_key' do # for dom_id
+ it { expect(ReimbursementType::ExchangeProcessor.param_key).to eq 'spree_exchange' }
+ end
+
+ describe '.model_name' do # for dom_id
+ it { expect(ReimbursementType::ExchangeProcessor.model_name).to eq Spree::ReimbursementType::ExchangeProcessor }
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/reimbursement_type/exchange_spec.rb b/spree/core/spec/models/spree/reimbursement_type/exchange_spec.rb
index 7a4533a2d0..b4208a5721 100644
--- a/spree/core/spec/models/spree/reimbursement_type/exchange_spec.rb
+++ b/spree/core/spec/models/spree/reimbursement_type/exchange_spec.rb
@@ -12,7 +12,7 @@ module Spree
context 'return items are supplied' do
before do
- expect(Spree::Exchange).to receive(:new).with(reimbursement.order, return_items).and_return(new_exchange)
+ expect(Spree::ReimbursementType::ExchangeProcessor).to receive(:new).with(reimbursement.order, return_items).and_return(new_exchange)
end
context 'simulate is true' do
diff --git a/spree/core/spec/workflows/spree/claims/lifecycle_spec.rb b/spree/core/spec/workflows/spree/claims/lifecycle_spec.rb
new file mode 100644
index 0000000000..e29f0ce01d
--- /dev/null
+++ b/spree/core/spec/workflows/spree/claims/lifecycle_spec.rb
@@ -0,0 +1,122 @@
+require 'spec_helper'
+
+RSpec.describe 'Spree::Claims workflows' do
+ let(:store) { @default_store }
+ let(:order) { create(:shipped_order, store: store, line_items_count: 2) }
+ let(:line_item) { order.line_items.first }
+
+ before { Spree.hooks.clear! }
+ after { Spree.hooks.clear! }
+
+ def create_claim(**overrides)
+ Spree::Claims::Create.call(
+ order: order,
+ claim_type: 'damaged',
+ items: [{ line_item: line_item, quantity: 1, description: 'Cracked', refund_amount: line_item.price }],
+ **overrides
+ )
+ end
+
+ describe Spree::Claims::Create do
+ it 'opens a claim' do
+ result = create_claim
+
+ expect(result).to be_success
+ expect(result.value).to be_open
+ expect(result.value.claim_type).to eq('damaged')
+ end
+
+ it 'refuses an unknown claim type' do
+ expect(create_claim(claim_type: 'teleported')).to be_failure
+ end
+
+ it 'refuses claiming more than was ordered' do
+ result = Spree::Claims::Create.call(
+ order: order,
+ items: [{ line_item: line_item, quantity: line_item.quantity + 5 }]
+ )
+
+ expect(result).to be_failure
+ end
+
+ it 'lets a validate handler gate self-service claims' do
+ Spree.hooks.register('claims.create.validate') { |flow| flow.reject!('claims disabled') }
+
+ expect(create_claim).to be_failure
+ end
+ end
+
+ describe Spree::Claims::Approve do
+ it 'approves an open claim' do
+ claim = create_claim.value
+
+ expect(Spree::Claims::Approve.call(claim: claim).value).to be_approved
+ end
+ end
+
+ describe Spree::Claims::Resolve do
+ let(:claim) { create(:approved_claim, store: store, order: order) }
+
+ it 'refuses an unapproved claim' do
+ open_claim = create_claim.value
+
+ expect(Spree::Claims::Resolve.call(claim: open_claim, resolution: 'refund')).to be_failure
+ end
+
+ it 'refuses an unknown resolution' do
+ expect(Spree::Claims::Resolve.call(claim: claim, resolution: 'apologize')).to be_failure
+ end
+
+ it 'refunds to store credit' do
+ result = Spree::Claims::Resolve.call(claim: claim, resolution: 'refund')
+
+ expect(result).to be_success
+ expect(result.value).to be_resolved
+ expect(result.value.resolution).to eq('refund')
+ expect(Spree::StoreCredit.find_by(originator: claim)).to be_present
+ end
+
+ it 'refuses to refund more than the customer paid' do
+ result = Spree::Claims::Resolve.call(claim: claim, resolution: 'refund', amount: 10_000)
+
+ expect(result).to be_failure
+ expect(result.error.value).to eq(:refund_exceeds_paid)
+ end
+
+ it 'ships a replacement' do
+ claim = create(:approved_claim, store: store, order: order, send_replacement: true)
+ claim.claim_line_items.each { |line| line.variant.stock_items.first&.set_count_on_hand(10) }
+
+ result = Spree::Claims::Resolve.call(claim: claim, resolution: 'replacement')
+
+ expect(result).to be_success
+ expect(result.value).to be_resolved
+ end
+ end
+
+ describe Spree::Claims::Deny do
+ it 'denies an open claim with a reason' do
+ claim = create_claim.value
+
+ result = Spree::Claims::Deny.call(claim: claim, reason: 'Outside warranty')
+
+ expect(result.value).to be_denied
+ expect(result.value.memo).to include('Outside warranty')
+ end
+ end
+
+ describe Spree::Claims::Cancel do
+ it 'cancels an open claim' do
+ claim = create_claim.value
+
+ expect(Spree::Claims::Cancel.call(claim: claim).value).to be_canceled
+ end
+
+ it 'refuses a resolved claim' do
+ claim = create(:approved_claim, store: store, order: order)
+ Spree::Claims::Resolve.call(claim: claim, resolution: 'refund')
+
+ expect(Spree::Claims::Cancel.call(claim: claim.reload)).to be_failure
+ end
+ end
+end
diff --git a/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb b/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb
new file mode 100644
index 0000000000..b477561bdd
--- /dev/null
+++ b/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb
@@ -0,0 +1,123 @@
+require 'spec_helper'
+
+RSpec.describe 'Spree::Exchanges workflows' do
+ let(:store) { @default_store }
+ let(:order) { create(:shipped_order, store: store, line_items_count: 2) }
+ let(:fulfillment_item) { order.fulfillment_items.first }
+ let(:replacement) { create(:variant, product: fulfillment_item.variant.product) }
+
+ before { Spree.hooks.clear! }
+ after { Spree.hooks.clear! }
+
+ def create_exchange(**overrides)
+ Spree::Exchanges::Create.call(
+ order: order,
+ items: [{ fulfillment_item: fulfillment_item, new_variant: replacement, quantity: 1 }],
+ **overrides
+ )
+ end
+
+ describe Spree::Exchanges::Create do
+ it 'opens a requested exchange' do
+ result = create_exchange
+
+ expect(result).to be_success
+ expect(result.value).to be_requested
+ expect(result.value.exchange_line_items.count).to eq(1)
+ end
+
+ it 'refuses a replacement that cannot be sold' do
+ allow_any_instance_of(Spree::Variant).to receive(:purchasable?).and_return(false)
+
+ expect(create_exchange).to be_failure
+ end
+
+ it 'refuses an order that was never completed' do
+ cart_order = create(:order, store: store)
+
+ expect(Spree::Exchanges::Create.call(order: cart_order, items: [])).to be_failure
+ end
+
+ it 'lets a validate handler veto' do
+ Spree.hooks.register('exchanges.create.validate') { |flow| flow.reject!('no exchanges') }
+
+ result = create_exchange
+
+ expect(result).to be_failure
+ expect(order.reload.exchanges).to be_empty
+ end
+ end
+
+ describe Spree::Exchanges::Approve do
+ it 'approves a requested exchange' do
+ exchange = create_exchange.value
+
+ result = Spree::Exchanges::Approve.call(exchange: exchange)
+
+ expect(result).to be_success
+ expect(result.value).to be_approved
+ end
+ end
+
+ describe Spree::Exchanges::Receive do
+ let(:exchange) { create(:approved_exchange, store: store) }
+
+ it 'receives and restocks the returned variant' do
+ line = exchange.exchange_line_items.first
+ stock_item = exchange.stock_location.stock_item_or_create(line.original_variant)
+
+ expect { Spree::Exchanges::Receive.call(exchange: exchange) }.
+ to change { stock_item.reload.count_on_hand }.by(line.quantity)
+
+ expect(exchange.reload).to be_received
+ end
+
+ it 'does not restock what came back damaged' do
+ line = exchange.exchange_line_items.first
+ stock_item = exchange.stock_location.stock_item_or_create(line.original_variant)
+
+ Spree::Exchanges::Receive.call(
+ exchange: exchange,
+ items: [{ exchange_line_item: line, quantity: 1, resellable: false }]
+ )
+
+ expect(stock_item.reload.count_on_hand).to eq(stock_item.count_on_hand)
+ expect(line.reload.resellable).to be(false)
+ end
+ end
+
+ describe Spree::Exchanges::Fulfill do
+ let(:exchange) { create(:received_exchange, store: store) }
+
+ it 'refuses an exchange that has not been received' do
+ approved = create(:approved_exchange, store: store)
+
+ expect(Spree::Exchanges::Fulfill.call(exchange: approved)).to be_failure
+ end
+
+ it 'creates a replacement fulfillment and marks it fulfilled' do
+ exchange.exchange_line_items.each do |line|
+ line.new_variant.stock_items.first&.set_count_on_hand(10)
+ end
+
+ result = Spree::Exchanges::Fulfill.call(exchange: exchange)
+
+ expect(result).to be_success
+ expect(result.value).to be_fulfilled
+ end
+ end
+
+ describe Spree::Exchanges::Cancel do
+ it 'cancels before the goods arrive' do
+ exchange = create_exchange.value
+
+ expect(Spree::Exchanges::Cancel.call(exchange: exchange).value).to be_canceled
+ end
+
+ it 'refuses once received' do
+ received = create(:received_exchange, store: store)
+
+ expect(Spree::Exchanges::Cancel.call(exchange: received)).to be_failure
+ end
+ end
+end