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
Scope reason lookups to the current store and validate refund_method
Damian Legawiec68dfb3e1034a
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/claims_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/claims_controller.rbindex 130e0f55d4..85717820a7 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders/claims_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/claims_controller.rb@@ -141,7 +141,7 @@ module Spreedef reason_for_createreturn nil if create_params[:reason_id].blank?- Spree::ClaimReason.find_by_prefix_id!(create_params[:reason_id])+ current_store.claim_reasons.find_by_prefix_id!(create_params[:reason_id])endendenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/exchanges_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/exchanges_controller.rbindex f8927ac495..2c44b48ac4 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders/exchanges_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/exchanges_controller.rb@@ -127,14 +127,14 @@ module Spreedef stock_location_for_createreturn nil if create_params[:stock_location_id].blank?- Spree::StockLocation.accessible_by(current_ability, :show).+ current_store.stock_locations.accessible_by(current_ability, :show).find_by_prefix_id!(create_params[:stock_location_id])enddef reason_for_createreturn nil if create_params[:reason_id].blank?- Spree::ReturnReason.find_by_prefix_id!(create_params[:reason_id])+ current_store.return_reasons.find_by_prefix_id!(create_params[:reason_id])endendenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/returns_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/returns_controller.rbindex d37abad5df..f44e19f6a4 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders/returns_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/returns_controller.rb@@ -135,14 +135,14 @@ module Spreedef stock_location_for_createreturn nil if create_params[:stock_location_id].blank?- Spree::StockLocation.accessible_by(current_ability, :show).+ current_store.stock_locations.accessible_by(current_ability, :show).find_by_prefix_id!(create_params[:stock_location_id])enddef reason_for_createreturn nil if create_params[:reason_id].blank?- Spree::ReturnReason.find_by_prefix_id!(create_params[:reason_id])+ current_store.return_reasons.find_by_prefix_id!(create_params[:reason_id])endendenddiff --git a/spree/api/app/controllers/spree/api/v3/store/orders/returns_controller.rb b/spree/api/app/controllers/spree/api/v3/store/orders/returns_controller.rbindex 1cef96fb17..110cdd103d 100644--- a/spree/api/app/controllers/spree/api/v3/store/orders/returns_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/orders/returns_controller.rb@@ -96,7 +96,7 @@ module Spreedef reason_for_createreturn nil if create_params[:reason_id].blank?- Spree::ReturnReason.find_by_prefix_id!(create_params[:reason_id])+ current_store.return_reasons.find_by_prefix_id!(create_params[:reason_id])endendenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/return_reasons_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/return_reasons_controller_spec.rbindex 339e069b7a..6d8a8412b7 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/return_reasons_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/return_reasons_controller_spec.rb@@ -28,6 +28,24 @@ RSpec.describe Spree::Api::V3::Admin::ReturnReasonsController, type: :controllerendend+ # The reason lookup on create is scoped to current_store, so a reason id+ # from another store is simply not found rather than silently accepted.+ describe 'store scoping' do+ let!(:other_store_reason) { create(:return_reason, store: create(:store), name: 'Other store reason') }++ it 'excludes another store\'s reasons from the listing' do+ get :index, as: :json++ expect(json_response['data'].map { |r| r['id'] }).not_to include(other_store_reason.prefixed_id)+ end++ it 'cannot fetch another store\'s reason by id' do+ get :show, params: { id: other_store_reason.prefixed_id }, as: :json++ expect(response).to have_http_status(:not_found)+ end+ end+describe 'GET #show' doit 'returns the reason' doget :show, params: { id: reason.prefixed_id }, as: :jsondiff --git a/spree/core/app/models/concerns/spree/refund_methods.rb b/spree/core/app/models/concerns/spree/refund_methods.rbnew file mode 100644index 0000000000..7b5715c96c--- /dev/null+++ b/spree/core/app/models/concerns/spree/refund_methods.rb@@ -0,0 +1,19 @@+module Spree+ # The ways money goes back to a customer on a post-sale record.+ #+ # A closed set, unlike claim types: each value picks a different code path —+ # `store_credit` is an internal ledger write inside the status transaction,+ # `original_payment` is a gateway call outside it. An unrecognised value+ # would otherwise fall through the `internal_refund?` branch to the gateway,+ # moving money by a route the caller did not ask for, so the workflows that+ # accept one reject anything not listed here.+ module RefundMethods+ METHODS = %w[original_payment store_credit].freeze++ # @param value [String, Symbol, nil]+ # @return [Boolean]+ def self.valid?(value)+ METHODS.include?(value.to_s)+ end+ end+enddiff --git a/spree/core/app/models/spree/claim_reason.rb b/spree/core/app/models/spree/claim_reason.rbindex 3b7147bb00..cba7aa6297 100644--- a/spree/core/app/models/spree/claim_reason.rb+++ b/spree/core/app/models/spree/claim_reason.rb@@ -7,6 +7,11 @@ module Spreehas_prefix_id :clrinclude Spree::NamedType+ include Spree::SingleStoreResource++ # Names are unique per store, not globally — two stores can each have+ # their own "Damaged" without colliding.+ validates :name, uniqueness: { case_sensitive: false, scope: :store_id }self.whitelisted_ransackable_attributes = %w[name active mutable]diff --git a/spree/core/app/models/spree/return_reason.rb b/spree/core/app/models/spree/return_reason.rbindex 849fb0eca2..a62106cf5f 100644--- a/spree/core/app/models/spree/return_reason.rb+++ b/spree/core/app/models/spree/return_reason.rb@@ -9,6 +9,11 @@ module Spreehas_prefix_id :rarinclude Spree::NamedType+ include Spree::SingleStoreResource++ # Names are unique per store, not globally — two stores can each have+ # their own "Damaged" without colliding.+ validates :name, uniqueness: { case_sensitive: false, scope: :store_id }self.whitelisted_ransackable_attributes = %w[name active mutable]diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex 704729d977..c0f29d6582 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -82,6 +82,8 @@ module Spreehas_many :returns, class_name: 'Spree::Return', inverse_of: :storehas_many :exchanges, class_name: 'Spree::Exchange', inverse_of: :storehas_many :claims, class_name: 'Spree::Claim', inverse_of: :store+ has_many :return_reasons, class_name: 'Spree::ReturnReason', inverse_of: :store, dependent: :destroy+ has_many :claim_reasons, class_name: 'Spree::ClaimReason', inverse_of: :store, dependent: :destroy# :nullify (not :destroy) — clearing the collection must not cascade into# Promotion#not_used? / payment records; orphaned rows are detached, not deleted.diff --git a/spree/core/app/services/spree/seeds/returns_environment.rb b/spree/core/app/services/spree/seeds/returns_environment.rbindex aa90d6b567..77514b36d6 100644--- a/spree/core/app/services/spree/seeds/returns_environment.rb+++ b/spree/core/app/services/spree/seeds/returns_environment.rb@@ -31,8 +31,11 @@ module Spree# silently create a second, unfindable reason if the name ever moves.Spree::RefundReason.return_processing_reason- RETURN_REASONS.each { |name| Spree::ReturnReason.find_or_create_by!(name: name) }- CLAIM_REASONS.each { |name| Spree::ClaimReason.find_or_create_by!(name: name) }+ # Reasons are store-owned, so every store gets its own vocabulary.+ Spree::Store.all.find_each do |store|+ RETURN_REASONS.each { |name| Spree::ReturnReason.where(store: store).find_or_create_by!(name: name) }+ CLAIM_REASONS.each { |name| Spree::ClaimReason.where(store: store).find_or_create_by!(name: name) }+ endendendenddiff --git a/spree/core/app/workflows/spree/claims/resolve.rb b/spree/core/app/workflows/spree/claims/resolve.rbindex d47d1e12aa..925ba7eaa9 100644--- a/spree/core/app/workflows/spree/claims/resolve.rb+++ b/spree/core/app/workflows/spree/claims/resolve.rb@@ -61,6 +61,14 @@ module Spreedef ensure_resolvablefailure(claim, :invalid_resolution) unless Spree::Claim::RESOLUTIONS.include?(resolution.to_s)+ if refunding? && !Spree::RefundMethods.valid?(refund_method)+ # :base, not :refund_method — it is a workflow argument, not an+ # attribute, and ActiveModel raises when an error names one that+ # does not exist on the record.+ claim.errors.add(:base, :invalid_refund_method,+ message: Spree.t('errors.messages.invalid_refund_method'))+ failure(claim)+ endfailure(claim, :not_approved) unless claim.approved?enddiff --git a/spree/core/app/workflows/spree/exchanges/fulfill.rb b/spree/core/app/workflows/spree/exchanges/fulfill.rbindex c625d8a1f6..a50c1bc02e 100644--- a/spree/core/app/workflows/spree/exchanges/fulfill.rb+++ b/spree/core/app/workflows/spree/exchanges/fulfill.rb@@ -57,6 +57,14 @@ module Spreeenddef ensure_fulfillable+ if credit_due? && !Spree::RefundMethods.valid?(refund_method)+ # :base, not :refund_method — it is a workflow argument, not an+ # attribute, and ActiveModel raises when an error names one that+ # does not exist on the record.+ exchange.errors.add(:base, :invalid_refund_method,+ message: Spree.t('errors.messages.invalid_refund_method'))+ failure(exchange)+ endfailure(exchange, :not_received) unless exchange.received?enddiff --git a/spree/core/app/workflows/spree/returns/refund.rb b/spree/core/app/workflows/spree/returns/refund.rbindex a6558b65dd..3beeac5fcd 100644--- a/spree/core/app/workflows/spree/returns/refund.rb+++ b/spree/core/app/workflows/spree/returns/refund.rb@@ -8,8 +8,6 @@ module Spree# a pure database write outside the transaction would open a window where# a crash leaves a refunded return with no credit issued.class Refund < Spree::Workflow- METHODS = %w[original_payment store_credit].freeze-hooks :validate, :before_refund, :after_refund# Refunds created by this run — hook handlers read them.@@ -52,7 +50,14 @@ module Spreeenddef ensure_refundable- failure(return_record, :invalid_refund_method) unless METHODS.include?(refund_method.to_s)+ unless Spree::RefundMethods.valid?(refund_method)+ # :base, not :refund_method — it is a workflow argument, not an+ # attribute, and ActiveModel raises when an error names one that+ # does not exist on the record.+ return_record.errors.add(:base, :invalid_refund_method,+ message: Spree.t('errors.messages.invalid_refund_method'))+ failure(return_record)+ endfailure(return_record, :not_received) unless return_record.received?enddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 6dfc36b4b0..99b6c069ee 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -893,6 +893,7 @@ en:invalid_oauth_state: Invalid or expired authentication state. Please start the sign-in again.invalid_order_routing_rule: is not a registered order routing ruleinvalid_order_routing_strategy: is not a registered order routing strategy+ invalid_refund_method: must be one of original_payment, store_creditinvalid_storefront_access: is not a valid storefront access levelmust_be_origin_only: must be an origin (scheme and host) without path, query, or fragmentno_pickup_point_provider: this delivery method has no pickup point provider configureddiff --git a/spree/core/db/migrate/20260805100001_rename_return_authorization_reasons_to_return_reasons.rb b/spree/core/db/migrate/20260805100001_rename_return_authorization_reasons_to_return_reasons.rbindex 4662b117a5..ea6f7e2ec3 100644--- a/spree/core/db/migrate/20260805100001_rename_return_authorization_reasons_to_return_reasons.rb+++ b/spree/core/db/migrate/20260805100001_rename_return_authorization_reasons_to_return_reasons.rb@@ -8,11 +8,19 @@ class RenameReturnAuthorizationReasonsToReturnReasons < ActiveRecord::Migration[# generic reason_id; it now points here instead of at return reasons.create_table :spree_claim_reasons do |t|t.string :name, null: false+ t.references :store, null: falset.boolean :active, null: false, default: truet.boolean :mutable, null: false, default: truet.timestampsend- add_index :spree_claim_reasons, :name, unique: true+ # Store-owned like every other reason vocabulary, so two stores can each+ # have their own "Damaged" without colliding. The uniqueness scope moves+ # with it: name is unique per store, not globally.+ add_reference :spree_return_reasons, :store++ remove_index :spree_return_reasons, :name+ add_index :spree_return_reasons, [:store_id, :name], unique: true+ add_index :spree_claim_reasons, [:store_id, :name], unique: trueendenddiff --git a/spree/core/lib/spree/testing_support/factories/return_reason_factory.rb b/spree/core/lib/spree/testing_support/factories/return_reason_factory.rbindex 7d2953b23b..2b4c96dedc 100644--- a/spree/core/lib/spree/testing_support/factories/return_reason_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/return_reason_factory.rb@@ -1,11 +1,13 @@FactoryBot.define dofactory :return_reason, class: Spree::ReturnReason do+ store { Spree::Store.find_by(default: true) || association(:store) }sequence(:name) { |n| "Return Reason #{n}" }active { true }mutable { true }endfactory :claim_reason, class: Spree::ClaimReason do+ store { Spree::Store.find_by(default: true) || association(:store) }sequence(:name) { |n| "Claim Reason #{n}" }active { true }mutable { true }diff --git a/spree/core/spec/workflows/spree/claims/lifecycle_spec.rb b/spree/core/spec/workflows/spree/claims/lifecycle_spec.rbindex e29f0ce01d..45fa9730b5 100644--- a/spree/core/spec/workflows/spree/claims/lifecycle_spec.rb+++ b/spree/core/spec/workflows/spree/claims/lifecycle_spec.rb@@ -67,6 +67,24 @@ RSpec.describe 'Spree::Claims workflows' doexpect(Spree::Claims::Resolve.call(claim: claim, resolution: 'apologize')).to be_failureend+ # Unguarded, an unrecognised method falls through internal_refund? to the+ # gateway branch — money moving by a route the caller never asked for.+ it 'refuses an unknown refund method when refunding' do+ result = Spree::Claims::Resolve.call(claim: claim, resolution: 'refund', refund_method: 'crypto')++ expect(result).to be_failure+ expect(result.error.value[:base].join).to include('original_payment')+ end++ it 'ignores the refund method when the resolution moves no money' do+ replacing = create(:approved_claim, store: store, order: order, send_replacement: true)+ replacing.claim_line_items.each { |line| line.variant.stock_items.first&.set_count_on_hand(10) }++ result = Spree::Claims::Resolve.call(claim: replacing, resolution: 'replacement', refund_method: 'crypto')++ expect(result).to be_success+ end+it 'refunds to store credit' doresult = Spree::Claims::Resolve.call(claim: claim, resolution: 'refund')diff --git a/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb b/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rbindex b477561bdd..b06660f97b 100644--- a/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb+++ b/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb@@ -105,6 +105,32 @@ RSpec.describe 'Spree::Exchanges workflows' doexpect(result).to be_successexpect(result.value).to be_fulfilledend++ # The guard only matters when money moves: a cheaper replacement owes the+ # customer the difference, and an unrecognised method would otherwise fall+ # through to the gateway instead of store credit.+ context 'when the replacement is cheaper, so a credit is due' do+ let(:cheap_exchange) do+ exchange.exchange_line_items.each do |line|+ line.new_variant.stock_items.first&.set_count_on_hand(10)+ line.new_variant.prices.first&.update!(amount: 1)+ end+ exchange+ end++ it 'refuses an unknown refund method' do+ result = Spree::Exchanges::Fulfill.call(exchange: cheap_exchange, refund_method: 'crypto')++ expect(result).to be_failure+ expect(result.error.value[:base].join).to include('original_payment')+ end++ it 'accepts store credit' do+ result = Spree::Exchanges::Fulfill.call(exchange: cheap_exchange, refund_method: 'store_credit')++ expect(result).to be_success+ end+ endenddescribe Spree::Exchanges::Cancel dodiff --git a/spree/core/spec/workflows/spree/returns/lifecycle_spec.rb b/spree/core/spec/workflows/spree/returns/lifecycle_spec.rbindex 67ab0a1594..12b318aed6 100644--- a/spree/core/spec/workflows/spree/returns/lifecycle_spec.rb+++ b/spree/core/spec/workflows/spree/returns/lifecycle_spec.rb@@ -150,7 +150,7 @@ RSpec.describe 'Spree::Returns workflows' doresult = Spree::Returns::Refund.call(return_record: return_record, refund_method: 'crypto')expect(result).to be_failure- expect(result.error.value).to eq(:invalid_refund_method)+ expect(result.error.value[:base].join).to include('original_payment')endit 'refuses more than the return is owed' do