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
Let core create the session payment, and Stripe only say what paid (#14473)
Damian Legawieca051c1e78e77
diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/store_credits_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/store_credits_controller.rbindex aa6cff7429..2178a78d1c 100644--- a/spree/api/app/controllers/spree/api/v3/admin/orders/store_credits_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/store_credits_controller.rb@@ -14,7 +14,7 @@ module Spree# credit up to the order total.def createwith_order_lock do- result = Spree.checkout_add_store_credit_service.call(+ result = Spree.store_credit_apply_service.call(order: @parent,amount: params[:amount].try(:to_f))@@ -30,7 +30,7 @@ module Spree# DELETE /api/v3/admin/orders/:order_id/store_creditsdef destroywith_order_lock do- result = Spree.checkout_remove_store_credit_service.call(order: @parent)+ result = Spree.store_credit_remove_service.call(order: @parent)if result.success?head :no_contentdiff --git a/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rbindex 9b0b6d27f1..3f6f0c98ef 100644--- a/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/carts/store_credits_controller.rb@@ -13,7 +13,7 @@ module Spree# POST /api/v3/store/carts/:cart_id/store_creditsdef createwith_order_lock do- result = Spree.checkout_add_store_credit_service.call(+ result = Spree.store_credit_apply_service.call(order: @cart,amount: params[:amount].try(:to_f))@@ -29,7 +29,7 @@ module Spree# DELETE /api/v3/store/carts/:cart_id/store_creditsdef destroywith_order_lock do- result = Spree.checkout_remove_store_credit_service.call(order: @cart)+ result = Spree.store_credit_remove_service.call(order: @cart)if result.success?render_cartdiff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/gift_cards_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/gift_cards_controller_spec.rbindex 286b25677d..dae6227506 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/gift_cards_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/gift_cards_controller_spec.rb@@ -72,7 +72,7 @@ RSpec.describe Spree::Api::V3::Admin::Orders::GiftCardsController, type: :controlet!(:order) { create(:order_with_line_items, store: store, customer: customer) }let!(:store_credit) { create(:store_credit, store: store, customer: customer, amount: 100) }- before { Spree.checkout_add_store_credit_service.call(order: order) }+ before { Spree.store_credit_apply_service.call(order: order) }it 'returns 422 (cannot mix gift card and store credit)' dopost :create, params: { order_id: order.prefixed_id, code: gift_card.code }, as: :jsondiff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/store_credits_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/store_credits_controller_spec.rbindex 7e837ad59d..00d1f9466e 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/store_credits_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/store_credits_controller_spec.rb@@ -77,7 +77,7 @@ RSpec.describe Spree::Api::V3::Admin::Orders::StoreCreditsController, type: :condescribe 'DELETE #destroy' docontext 'when store credit was applied' dobefore do- Spree.checkout_add_store_credit_service.call(order: order)+ Spree.store_credit_apply_service.call(order: order)endit 'removes store credit from the order' dodiff --git a/spree/api/spec/controllers/spree/api/v3/store/carts/store_credits_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/store_credits_controller_spec.rbindex 06c0f1faf3..4b221acfad 100644--- a/spree/api/spec/controllers/spree/api/v3/store/carts/store_credits_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/store_credits_controller_spec.rb@@ -50,7 +50,7 @@ RSpec.describe Spree::Api::V3::Store::Carts::StoreCreditsController, type: :contdescribe 'DELETE #destroy' doit 'removes store credit and returns updated cart' do- Spree.checkout_add_store_credit_service.call(order: order, amount: 10)+ Spree.store_credit_apply_service.call(order: order, amount: 10)delete :destroy, params: { cart_id: order.prefixed_id }diff --git a/spree/api/spec/integration/spree/api/v3/admin/orders/store_credits_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/orders/store_credits_spec.rbindex 0268bcf623..82f828bb72 100644--- a/spree/api/spec/integration/spree/api/v3/admin/orders/store_credits_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/orders/store_credits_spec.rb@@ -65,7 +65,7 @@ RSpec.describe 'Admin Order Store Credits API', type: :request, swagger_doc: 'apresponse '204', 'store credit removed' dolet(:'x-spree-api-key') { secret_api_key.plaintext_token }- before { Spree.checkout_add_store_credit_service.call(order: order) }+ before { Spree.store_credit_apply_service.call(order: order) }run_test!enddiff --git a/spree/core/app/models/concerns/spree/purchase/store_credits.rb b/spree/core/app/models/concerns/spree/purchase/store_credits.rbindex 762a91ee7b..cc21df448e 100644--- a/spree/core/app/models/concerns/spree/purchase/store_credits.rb+++ b/spree/core/app/models/concerns/spree/purchase/store_credits.rb@@ -4,11 +4,11 @@ module Spree# Spree::Order (carts reach user through the customer alias).module StoreCreditsdef add_store_credit_payments(amount = nil)- Spree.checkout_add_store_credit_service.call(order: self, amount: amount)+ Spree.store_credit_apply_service.call(order: self, amount: amount)enddef remove_store_credit_payments- Spree.checkout_remove_store_credit_service.call(order: self)+ Spree.store_credit_remove_service.call(order: self)enddef covered_by_store_credit?diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex e00ee4ac4e..a1f7c20716 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -1093,7 +1093,7 @@ module Spreeif gift_card.present?recalculate_gift_cardelsif using_store_credit?- Spree.checkout_add_store_credit_service.call(order: self)+ Spree.store_credit_apply_service.call(order: self)endenddiff --git a/spree/core/app/models/spree/payment_session.rb b/spree/core/app/models/spree/payment_session.rbindex 417049df41..2b6f41cc37 100644--- a/spree/core/app/models/spree/payment_session.rb+++ b/spree/core/app/models/spree/payment_session.rb@@ -52,22 +52,34 @@ module Spree# @param metadata [Hash] gateway-specific metadata# @return [Spree::Payment] the payment recorddef find_or_create_payment!(metadata = {})- # Session payments carry no Spree-side source (the gateway holds the- # instrument), so the requirement is skipped on every load, not just at- # creation — a later capture webhook transitions the same row and would- # otherwise fail source validation.+ # An unsaved session has no identity to key a payment to, and nothing+ # has settled against it.+ return unless persisted?++ # Session payments carry no Spree-side source unless the gateway builds+ # one, so the requirement is skipped on every load, not just at creation+ # — a later capture webhook transitions the same row and would otherwise+ # fail source validation.return skip_source_requirement(payment) if payment.present?- skip_source_requirement(- owner.payments.find_or_create_by!(- payment_method: payment_method,- response_code: external_id,- ) do |p|- p.amount = amount- p.skip_source_requirement = true- end- )+ # Keyed on the gateway's own identifier alone. Never on the amount: a+ # session whose amount moved is still the same intent, and a second row+ # for it would both double the order's money and collide with the unique+ # index on (owner, payment_method, response_code).+ created = owner.payments.find_or_create_by!(+ payment_method: payment_method,+ response_code: external_id+ ) do |new_payment|+ new_payment.amount = amount+ new_payment.skip_source_requirement = true+ new_payment.source = payment_source_for_settlement+ apply_settlement_metadata(new_payment, metadata)+ end++ skip_source_requirement(created)rescue ActiveRecord::RecordNotUnique+ # The webhook and the customer's synchronous return race by design;+ # whoever loses the insert finds the row the winner created.skip_source_requirement(owner.payments.find_by!(payment_method: payment_method,@@ -76,6 +88,29 @@ module Spree)end+ # The payment source to attach when the payment row is first created.+ # Gateways holding the instrument (a card, a mandate) build one here so+ # the payment shows a brand and last four digits; those with nothing to+ # represent return nil and the payment stands on its own.+ #+ # Called inside the settlement lock, so it must not perform provider I/O+ # — warm anything it needs in +prepare_for_settlement!+.+ #+ # @return [Spree::PaymentSource, nil]+ def payment_source_for_settlement+ nil+ end++ # Records gateway-specific detail on the new payment. Overridden by+ # gateways that carry references worth keeping (a charge id, a mandate).+ #+ # @param payment [Spree::Payment] unsaved+ # @param metadata [Hash] whatever the settling caller passed+ # @return [void]+ def apply_settlement_metadata(payment, metadata)+ payment.metadata.merge!(metadata.stringify_keys) if metadata.present?+ end+# Fetches whatever settlement will need from the provider, so a caller# that settles inside a lock (the webhook path) holds it across no# provider I/O. Gateway session subclasses override; no-op by default.diff --git a/spree/core/app/services/spree/checkout/add_store_credit.rb b/spree/core/app/services/spree/checkout/add_store_credit.rbindex 3a5d8ef727..d905b61a8c 100644--- a/spree/core/app/services/spree/checkout/add_store_credit.rb+++ b/spree/core/app/services/spree/checkout/add_store_credit.rb@@ -1,84 +1,15 @@module Spreemodule Checkout- class AddStoreCredit- prepend Spree::ServiceModule::Base-- def call(order:, amount: nil)- @order = order- return failed unless @order-- remaining_total = amount ? [amount, @order.outstanding_balance].min : @order.outstanding_balance-- return failure(nil, Spree.t(:error_user_does_not_have_any_store_credits)) unless @order.customer&.store_credits&.any?-- ApplicationRecord.transaction do- existing = @order.payments.store_credits.where(status: :checkout)-- if existing.any?- update_existing_payments(existing, remaining_total)- else- apply_store_credits(remaining_total)- end- end-- if @order.reload.payments.store_credits.valid.any?- # Legacy update hooks are an order-side extension seam; carts have none.- @order.update_hooks.each { |hook| @order.send(hook) } if @order.respond_to?(:update_hooks)- success(@order)- else- failure(@order)- end- end-- private-- # Update existing checkout store credit payments in place to avoid- # creating unnecessary invalid payment records on every recalculation.- def update_existing_payments(payments, remaining_total)- payments.each do |payment|- credit = payment.source- available = credit.amount_remaining + payment.amount- new_amount = [available, remaining_total].min-- if new_amount.positive?- payment.update_column(:amount, new_amount)- remaining_total -= new_amount- else- payment.invalidate!- end- end-- # If there's still remaining total, apply from additional store credits- apply_store_credits(remaining_total) if remaining_total.positive?- end-- def apply_store_credits(remaining_total)- payment_method = Spree::PaymentMethod::StoreCredit.available.first- raise 'Store credit payment method could not be found' unless payment_method-- @order.customer.store_credits.for_store(@order.store).oldest_first.each do |credit|- break if remaining_total.zero?- next if credit.amount_remaining.zero?-- amount_to_take = store_credit_amount(credit, remaining_total)- create_store_credit_payment(payment_method, credit, amount_to_take)- remaining_total -= amount_to_take- end- end-- def create_store_credit_payment(payment_method, credit, amount)- @order.payments.create!(- source: credit,- payment_method: payment_method,- amount: amount,- state: 'checkout',- response_code: credit.generate_authorization_code- )- end-- def store_credit_amount(credit, total)- [credit.amount_remaining, total].min- end- end+ # Deprecation alias for Spree::StoreCredits::Apply, renamed in 6.0 for+ # symmetry with Spree::GiftCards::Apply. Retained one release so existing+ # code and extensions keep working. A constant assignment rather than a+ # subclass, so is_a? and class_name: references keep resolving; the file+ # is named for the constant because Zeitwerk requires it. Removed in 6.1.+ AddStoreCredit = Spree::StoreCredits::Apply++ Spree::Deprecation.warn(+ 'Spree::Checkout::AddStoreCredit is deprecated and will be removed in Spree 6.1. ' \+ 'Use Spree::StoreCredits::Apply instead.'+ )endenddiff --git a/spree/core/app/services/spree/checkout/remove_store_credit.rb b/spree/core/app/services/spree/checkout/remove_store_credit.rbindex d7e2e8023d..e3581f3174 100644--- a/spree/core/app/services/spree/checkout/remove_store_credit.rb+++ b/spree/core/app/services/spree/checkout/remove_store_credit.rb@@ -1,17 +1,12 @@module Spreemodule Checkout- class RemoveStoreCredit- prepend Spree::ServiceModule::Base+ # Deprecation alias for Spree::StoreCredits::Remove — see+ # Spree::Checkout::AddStoreCredit. Removed in 6.1.+ RemoveStoreCredit = Spree::StoreCredits::Remove- def call(order:)- return failed unless order-- ApplicationRecord.transaction do- order.payments.checkout.store_credits.map(&:invalidate!) unless order.completed?- end-- order.reload.payments.store_credits.valid.any? ? failure(order) : success(order)- end- end+ Spree::Deprecation.warn(+ 'Spree::Checkout::RemoveStoreCredit is deprecated and will be removed in Spree 6.1. ' \+ 'Use Spree::StoreCredits::Remove instead.'+ )endenddiff --git a/spree/core/app/services/spree/payments/create.rb b/spree/core/app/services/spree/payments/create.rbindex c509c3321f..479c0541fb 100644--- a/spree/core/app/services/spree/payments/create.rb+++ b/spree/core/app/services/spree/payments/create.rb@@ -1,5 +1,16 @@module Spreemodule Payments+ # @deprecated Unused since 6.0 and removed in 7.0. Nothing in Spree+ # calls this: the storefront creates payments through the Store API+ # controller, store credit through Spree::Checkout::AddStoreCredit,+ # gift cards through Spree::GiftCards::Apply, and a partial capture's+ # remainder through Spree::Payment#split_uncaptured_amount.+ #+ # It also cannot serve those callers as written — it resolves the+ # payment method from +params[:payment_method_id]+ against the+ # storefront-visible list and builds a source from client attributes,+ # while they already hold both (the gift card flow creates its payment+ # method by type when the store has none).class Createprepend Spree::ServiceModule::Basediff --git a/spree/core/app/services/spree/store_credits/apply.rb b/spree/core/app/services/spree/store_credits/apply.rbnew file mode 100644index 0000000000..fb1e4fb8c7--- /dev/null+++ b/spree/core/app/services/spree/store_credits/apply.rb@@ -0,0 +1,93 @@+module Spree+ module StoreCredits+ class Apply+ prepend Spree::ServiceModule::Base++ def call(order:, amount: nil)+ @order = order+ return failed unless @order++ # Never negative: a paid or overpaid order has a zero-or-negative+ # outstanding balance, and this service runs on every recalculation.+ # Without the clamp the loop below would keep going and write a store+ # credit payment for a negative amount.+ remaining_total = [amount ? [amount, @order.outstanding_balance].min : @order.outstanding_balance, 0].max++ return failure(nil, Spree.t(:error_user_does_not_have_any_store_credits)) unless @order.customer&.store_credits&.any?++ ApplicationRecord.transaction do+ existing = @order.payments.store_credits.where(status: :checkout)++ if existing.any?+ update_existing_payments(existing, remaining_total)+ else+ apply_store_credits(remaining_total)+ end+ end++ if @order.reload.payments.store_credits.valid.any?+ # Legacy update hooks are an order-side extension seam; carts have none.+ @order.update_hooks.each { |hook| @order.send(hook) } if @order.respond_to?(:update_hooks)+ success(@order)+ else+ failure(@order)+ end+ end++ private++ # Update existing checkout store credit payments in place to avoid+ # creating unnecessary invalid payment records on every recalculation.+ def update_existing_payments(payments, remaining_total)+ payments.each do |payment|+ credit = payment.source+ available = credit.amount_remaining + payment.amount+ new_amount = [available, remaining_total].min++ if new_amount.positive?+ payment.update_column(:amount, new_amount)+ remaining_total -= new_amount+ else+ payment.invalidate!+ end+ end++ # If there's still remaining total, apply from additional store credits+ apply_store_credits(remaining_total) if remaining_total.positive?+ end++ def apply_store_credits(remaining_total)+ payment_method = Spree::PaymentMethod::StoreCredit.available.first+ raise 'Store credit payment method could not be found' unless payment_method++ # Only credits in the order's own currency: an older credit in another+ # currency would be drawn against first and, being unusable, either+ # overshoot the allowed amount or persist a payment that fails later+ # at authorization. This matches what the order already counts as+ # available (Purchase::StoreCredits#total_available_store_credit).+ @order.customer.store_credits.for_store(@order.store).where(currency: @order.currency).oldest_first.each do |credit|+ break unless remaining_total.positive?+ next if credit.amount_remaining.zero?++ amount_to_take = store_credit_amount(credit, remaining_total)+ create_store_credit_payment(payment_method, credit, amount_to_take)+ remaining_total -= amount_to_take+ end+ end++ def create_store_credit_payment(payment_method, credit, amount)+ @order.payments.create!(+ source: credit,+ payment_method: payment_method,+ amount: amount,+ status: 'checkout',+ response_code: credit.generate_authorization_code+ )+ end++ def store_credit_amount(credit, total)+ [credit.amount_remaining, total].min+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/store_credits/remove.rb b/spree/core/app/services/spree/store_credits/remove.rbnew file mode 100644index 0000000000..bef153f1a9--- /dev/null+++ b/spree/core/app/services/spree/store_credits/remove.rb@@ -0,0 +1,17 @@+module Spree+ module StoreCredits+ class Remove+ prepend Spree::ServiceModule::Base++ def call(order:)+ return failed unless order++ ApplicationRecord.transaction do+ order.payments.checkout.store_credits.map(&:invalidate!) unless order.completed?+ end++ order.reload.payments.store_credits.valid.any? ? failure(order) : success(order)+ end+ end+ end+enddiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 4fea548de5..54c672648a 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -709,7 +709,8 @@ module SpreeSpree::Dependencies.class::INJECTION_POINTS.include?(name) ||Spree::Dependencies.class::LEGACY_WORKFLOW_KEYS.key?(name) ||- Spree::Dependencies.class::LEGACY_SERVICE_KEYS.key?(name)+ Spree::Dependencies.class::LEGACY_SERVICE_KEYS.key?(name) ||+ Spree::Dependencies.class::RENAMED_SERVICE_KEYS.key?(name)endenddiff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex 9432e5cb4d..ce1a9c784f 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -49,8 +49,8 @@ module Spree# checkoutcheckout_advance_service: 'Spree::Checkout::Advance',- checkout_add_store_credit_service: 'Spree::Checkout::AddStoreCredit',- checkout_remove_store_credit_service: 'Spree::Checkout::RemoveStoreCredit',+ store_credit_apply_service: 'Spree::StoreCredits::Apply',+ store_credit_remove_service: 'Spree::StoreCredits::Remove',# gift cardsgift_card_apply_workflow: 'Spree::GiftCards::Apply',@@ -234,6 +234,43 @@ module Spreegift_card_redeem_service: :gift_card_redeem_workflow}.freeze+ # Pure renames: the class, its contract and its keyword vocabulary are+ # unchanged, so unlike LEGACY_WORKFLOW_KEYS an override written against+ # the old name IS applied — there is nothing incompatible about it.+ # Removed in 6.1.+ RENAMED_SERVICE_KEYS = {+ checkout_add_store_credit_service: :store_credit_apply_service,+ checkout_remove_store_credit_service: :store_credit_remove_service+ }.freeze++ RENAMED_SERVICE_KEYS.each do |legacy, current|+ define_method("#{legacy}=") do |value|+ Spree::Deprecation.warn(+ "Spree::Dependencies##{legacy}= is deprecated and will be removed in Spree 6.1. " \+ "Use #{current}= instead."+ )+ send("#{current}=", value)+ end++ define_method(legacy) do+ Spree::Deprecation.warn(+ "Spree::Dependencies##{legacy} is deprecated and will be removed in Spree 6.1. " \+ "Use #{current} instead."+ )+ send(current)+ end++ # Spree.<name> resolves through <name>_class, so the rename needs the+ # constantized reader too.+ define_method("#{legacy}_class") do+ Spree::Deprecation.warn(+ "Spree::Dependencies##{legacy} is deprecated and will be removed in Spree 6.1. " \+ "Use #{current} instead."+ )+ send("#{current}_class")+ end+ end+def legacy_workflow_overrides@legacy_workflow_overrides ||= {}enddiff --git a/spree/core/spec/services/spree/checkout/add_store_credit_spec.rb b/spree/core/spec/services/spree/store_credits/apply_spec.rbsimilarity index 68%rename from spree/core/spec/services/spree/checkout/add_store_credit_spec.rbrename to spree/core/spec/services/spree/store_credits/apply_spec.rbindex aa1ddfe7ee..64100f0e7d 100644--- a/spree/core/spec/services/spree/checkout/add_store_credit_spec.rb+++ b/spree/core/spec/services/spree/store_credits/apply_spec.rb@@ -1,7 +1,7 @@require 'spec_helper'-describe Spree::Checkout::AddStoreCredit, type: :service do+describe Spree::StoreCredits::Apply, type: :service dolet(:store) { @default_store }describe '#call' do@@ -156,4 +156,59 @@ describe Spree::Checkout::AddStoreCredit, type: :service doendendend++ # Regression: outstanding_balance is zero or negative on a paid or overpaid+ # order, and this service runs on every recalculation. The loop used to+ # break only on exactly zero, so a negative balance wrote a store credit+ # payment for a negative amount.+ context 'when the order is already overpaid' do+ let(:overpaid_customer) { create(:customer) }+ let(:overpaid_order) { create(:order_with_line_items, store: store, customer: overpaid_customer) }++ before do+ create(:store_credit_payment_method)+ create(:store_credit, customer: overpaid_customer, amount: 50, store: store)+ overpaid_order.update_columns(total: 10, item_total: 10, payment_total: 40)+ end++ it 'writes no store credit payment' do+ described_class.call(order: overpaid_order)++ expect(overpaid_order.reload.payments.store_credits).to be_empty+ end+ end++ # Regression: credits were drawn oldest-first with no currency filter, so an+ # older credit in another currency was picked ahead of a usable one. Being+ # unusable it overshot the order's allowed amount and raised, aborting the+ # whole apply transaction.+ context 'when an older credit is in another currency' do+ let(:mixed_customer) { create(:customer) }+ let(:mixed_order) { create(:order_with_line_items, store: store, customer: mixed_customer) }++ # Derived, never hard-coded: the order's currency comes from its store, so+ # naming a fixed code here risks the "foreign" credit matching the order+ # and the example passing without exercising the filter at all.+ let(:foreign_currency) { mixed_order.currency == 'EUR' ? 'USD' : 'EUR' }++ before do+ create(:store_credit_payment_method)+ mixed_order.update_columns(total: 100, item_total: 100, payment_total: 0)+ create(:store_credit, customer: mixed_customer, amount: 50, store: store,+ currency: foreign_currency, created_at: 2.days.ago)+ create(:store_credit, customer: mixed_customer, amount: 30, store: store,+ currency: mixed_order.currency, created_at: 1.day.ago)+ end++ it 'draws only against the credit in the order currency' do+ expect(foreign_currency).not_to eq(mixed_order.currency)++ described_class.call(order: mixed_order)++ payments = mixed_order.reload.payments.store_credits+ expect(payments.count).to eq(1)+ expect(payments.first.source.currency).to eq(mixed_order.currency)+ expect(payments.first.amount).to eq(30)+ end+ endenddiff --git a/spree/core/spec/services/spree/checkout/remove_store_credit_spec.rb b/spree/core/spec/services/spree/store_credits/remove_spec.rbsimilarity index 94%rename from spree/core/spec/services/spree/checkout/remove_store_credit_spec.rbrename to spree/core/spec/services/spree/store_credits/remove_spec.rbindex 81bb0ba625..35c091ec3d 100644--- a/spree/core/spec/services/spree/checkout/remove_store_credit_spec.rb+++ b/spree/core/spec/services/spree/store_credits/remove_spec.rb@@ -1,6 +1,6 @@require 'spec_helper'-describe Spree::Checkout::RemoveStoreCredit, type: :service do+describe Spree::StoreCredits::Remove, type: :service dodescribe '#call' dosubject { described_class.call(order: order) }diff --git a/spree/core/spec/subscribers/spree/dispatch_spec.rb b/spree/core/spec/subscribers/spree/dispatch_spec.rbnew file mode 100644index 0000000000..4d7695a529--- /dev/null+++ b/spree/core/spec/subscribers/spree/dispatch_spec.rb@@ -0,0 +1,102 @@+require 'spec_helper'++# Subscriber specs call their handler methods directly, which proves the body+# works but never that the event reaches it. Events are disabled by default in+# the test environment, so the dispatch itself — the declared pattern, the+# payload the publisher sends, and the record lookup the handler does with it —+# runs unexercised until production.+#+# This publishes each declared event for real and asserts the handler ran.+RSpec.describe 'subscriber dispatch', events: true do+ include ActiveJob::TestHelper++ # @param klass [Class] the subscriber+ # @param method_name [Symbol] whatever it declares — #handle, or the named+ # method registered through `on`+ # @return [Boolean] whether publishing reached the handler+ def reaches_handler?(klass, method_name, event_name)+ reached = false+ original = klass.instance_method(method_name)+ klass.define_method(method_name) do |event|+ reached = true if event.name == event_name+ original.bind(self).call(event)+ end++ # Async subscribers dispatch through ActiveJob, so the job has to run+ # before the handler is reached at all.+ perform_enqueued_jobs { yield }+ reached+ ensure+ klass.define_method(method_name, original)+ end++ let(:store) { @default_store }++ describe 'order.placed' do+ let(:order) { create(:order_with_line_items, store: store) }++ it 'reaches the synchronous completion subscriber' do+ expect(reaches_handler?(Spree::OrderPlacedSubscriber, :handle, 'order.placed') do+ order.publish_event('order.placed')+ end).to be(true)+ end++ it 'reaches the asynchronous product metrics subscriber' do+ expect(reaches_handler?(Spree::ProductMetricsSubscriber, :refresh_product_metrics, 'order.placed') do+ order.publish_event('order.placed')+ end).to be(true)+ end+ end++ describe 'payment events' do+ let(:order) { create(:order_with_line_items, store: store) }++ # Regression guard for the four-recomputations-per-capture duplication:+ # this subscriber is the only writer of payment_status now, so its+ # dispatch has to survive refactors of the payment lifecycle.+ it 'reaches the order status subscriber when a payment settles' do+ payment = create(:payment, order: order, amount: order.total, status: 'checkout')++ expect(reaches_handler?(Spree::OrderStatusSubscriber, :handle, 'payment.completed') do+ payment.complete!+ end).to be(true)+ end+ end++ # Cart-owned payments were where the events-off blind spot bit hardest:+ # a subscriber reached for order.paid? on a payment whose order is nil,+ # and nothing caught it because the handler never ran in test.+ describe 'a payment that settles on a cart' do+ let(:cart) { create(:cart, store: store) }++ before do+ create(:line_item, order: cart, price: 10, quantity: 1)+ cart.recalculate_totals!+ end++ it 'settles without reaching for the order it does not have' do+ payment = create(:payment, order: nil, cart: cart, amount: 10,+ payment_method: create(:check_payment_method, store: store),+ status: 'checkout')++ # The subscriber has to actually run: without asserting delivery this+ # would still pass if it were never registered, and the money assertion+ # below would be proving nothing.+ expect(reaches_handler?(Spree::OrderStatusSubscriber, :handle, 'payment.completed') do+ payment.complete!+ end).to be(true)++ expect(cart.reload.payment_total).to eq(10)+ end+ end++ describe 'invitation events' do+ it 'reaches the invitation email subscriber on create' do+ inviter = create(:admin_user)++ expect(reaches_handler?(Spree::InvitationEmailSubscriber, :send_invitation_email, 'invitation.created') do+ create(:invitation, inviter: inviter, resource: store)+ end).to be(true)+ end+ end+enddiff --git a/spree/providers/stripe/app/models/spree/payment_sessions/stripe.rb b/spree/providers/stripe/app/models/spree/payment_sessions/stripe.rbindex acddfc61f9..f523efd02d 100644--- a/spree/providers/stripe/app/models/spree/payment_sessions/stripe.rb+++ b/spree/providers/stripe/app/models/spree/payment_sessions/stripe.rb@@ -46,18 +46,42 @@ module Spreeselfend- # Builds the payment together with a Stripe-specific source (card, Klarna,- # SEPA, …), which core's generic implementation cannot do.- def find_or_create_payment!(metadata = {})- return unless persisted?- return payment if payment.present?-- SpreeStripe::CreatePayment.new(- owner: owner,- payment_session: self,- gateway: payment_method,- amount: amount- ).call+ # Core creates the payment; Stripe only says what instrument it was paid+ # with. The charge and customer are already warmed by+ # +prepare_for_settlement!+, so this does no Stripe I/O inside the lock.+ #+ # @return [Spree::PaymentSource, nil]+ def payment_source_for_settlement+ charge = stripe_charge++ if charge.present?+ SpreeStripe::CreateSource.new(+ owner: owner,+ stripe_payment_method_details: charge.payment_method_details,+ stripe_payment_method_id: charge.payment_method,+ stripe_billing_details: charge.billing_details,+ gateway: payment_method+ ).call+ elsif charge_not_required?+ # Bank transfers settle with no charge object, so the instrument has+ # to come off the intent instead.+ intent = stripe_payment_intent++ SpreeStripe::CreateSource.new(+ owner: owner,+ stripe_payment_method_details: intent.payment_method,+ stripe_payment_method_id: intent.payment_method.id,+ stripe_billing_details: nil,+ gateway: payment_method+ ).call+ end+ end++ # Keeps the charge reference alongside whatever the caller passed.+ def apply_settlement_metadata(payment, metadata)+ super+ charge = stripe_charge+ payment.metadata['stripe_charge_id'] = charge.id if charge.present?endendenddiff --git a/spree/providers/stripe/app/services/spree_stripe/create_payment.rb b/spree/providers/stripe/app/services/spree_stripe/create_payment.rbindex 8af5ba68f1..43da8a297e 100644--- a/spree/providers/stripe/app/services/spree_stripe/create_payment.rb+++ b/spree/providers/stripe/app/services/spree_stripe/create_payment.rb@@ -1,6 +1,14 @@module SpreeStripe- # Builds the Spree::Payment for a completed payment session, together with the- # Stripe-specific payment source.+ # @deprecated Unused since 6.0 and removed in 7.0. Core's+ # Spree::PaymentSession#find_or_create_payment! creates the payment now;+ # this gem only supplies the source, through+ # Spree::PaymentSessions::Stripe#payment_source_for_settlement.+ #+ # It diverged from core in three ways that this consolidation fixed: it+ # never set skip_source_requirement (so a session with no charge raised+ # "Source can't be blank"), it keyed idempotency on the amount as well as+ # the intent (so an amount change minted a second payment), and it did not+ # rescue RecordNotUnique (so the webhook/return race could crash).class CreatePayment# @param owner [Spree::Cart, Spree::Order]# @param payment_session [Spree::PaymentSessions::Stripe]diff --git a/spree/providers/stripe/spec/models/spree/payment_sessions/stripe_spec.rb b/spree/providers/stripe/spec/models/spree/payment_sessions/stripe_spec.rbindex edaad09f21..df3c2f5175 100644--- a/spree/providers/stripe/spec/models/spree/payment_sessions/stripe_spec.rb+++ b/spree/providers/stripe/spec/models/spree/payment_sessions/stripe_spec.rb@@ -157,25 +157,41 @@ RSpec.describe Spree::PaymentSessions::Stripe, type: :model doexpect(payment_session.reload.find_or_create_payment!).to eq(payment)end- it 'creates payment via CreatePayment service' do- mock_payment = build(:payment, order: order, payment_method: gateway)- service = instance_double(SpreeStripe::CreatePayment, call: mock_payment)- expect(SpreeStripe::CreatePayment).to receive(:new).with(- owner: order,- payment_session: payment_session,- gateway: gateway,- amount: payment_session.amount- ).and_return(service)+ # Core creates the payment now; this gem contributes the source and the+ # charge reference.+ it 'creates the payment keyed on the intent, with the Stripe source' do+ allow(payment_session).to receive(:stripe_charge).and_return(nil)+ allow(payment_session).to receive(:charge_not_required?).and_return(false)- expect(payment_session.find_or_create_payment!).to eq(mock_payment)+ payment = payment_session.find_or_create_payment!++ expect(payment).to be_persisted+ expect(payment.response_code).to eq(payment_session.external_id)+ expect(payment.amount).to eq(payment_session.amount)+ end++ it 'records the caller metadata on the new payment' do+ allow(payment_session).to receive(:stripe_charge).and_return(nil)+ allow(payment_session).to receive(:charge_not_required?).and_return(false)++ payment = payment_session.find_or_create_payment!(charge_id: 'ch_123')++ expect(payment.metadata['charge_id']).to eq('ch_123')end- it 'accepts metadata argument without error' do- mock_payment = build(:payment, order: order, payment_method: gateway)- service = instance_double(SpreeStripe::CreatePayment, call: mock_payment)- allow(SpreeStripe::CreatePayment).to receive(:new).and_return(service)+ # Regression: the old gem-side implementation keyed idempotency on the+ # amount too, so a session whose amount moved minted a second payment for+ # the same intent — doubling the order's money.+ it 'does not mint a second payment when the amount changes' do+ allow(payment_session).to receive(:stripe_charge).and_return(nil)+ allow(payment_session).to receive(:charge_not_required?).and_return(false)++ first = payment_session.find_or_create_payment!+ payment_session.update!(amount: payment_session.amount - 10)+ second = payment_session.reload.find_or_create_payment!- expect(payment_session.find_or_create_payment!(charge_id: 'ch_123')).to eq(mock_payment)+ expect(second.id).to eq(first.id)+ expect(order.payments.count).to eq(1)endend