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
Gift Card fixes (#13819)
Damian Legawieca9ae7d59794e
diff --git a/spree/api/app/controllers/spree/api/v3/base_controller.rb b/spree/api/app/controllers/spree/api/v3/base_controller.rbindex 62c569cd81..1056efd193 100644--- a/spree/api/app/controllers/spree/api/v3/base_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/base_controller.rb@@ -2,6 +2,9 @@ module Spreemodule Apimodule V3class BaseController < ActionController::API+ # API v3 uses flat params — disable Rails' automatic parameter wrapping+ wrap_parameters false+include ActiveStorage::SetCurrentinclude CanCan::ControllerAdditionsinclude Spree::Core::ControllerHelpers::StrongParametersdiff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 6ab0c9d647..dc93471bee 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -53,7 +53,9 @@ module Spreealias display_ship_total display_shipment_totalalias_attribute :ship_total, :shipment_total- alias amount_due total_minus_store_credits+ def amount_due+ outstanding_balance+ end# Transient warnings populated by remove_out_of_stock_items!attribute :warnings, default: -> { [] }diff --git a/spree/core/app/models/spree/order/gift_card.rb b/spree/core/app/models/spree/order/gift_card.rbindex 55a6431930..2ad011f019 100644--- a/spree/core/app/models/spree/order/gift_card.rb+++ b/spree/core/app/models/spree/order/gift_card.rb@@ -34,11 +34,31 @@ module SpreeSpree.gift_card_remove_service.call(order: self)end+ # Recalculates the gift card payment amount based on the current order total.+ # Updates the existing payment in place instead of remove + re-apply+ # to avoid creating unnecessary invalid payment records.def recalculate_gift_card- applied_gift_card = gift_card+ return unless gift_card.present?++ payment = payments.checkout.store_credits.where(source: gift_card.store_credits).first+ return unless payment++ # with_lock acquires a row lock and wraps in a transaction.+ # The entire read-compute-write must be inside the lock to prevent+ # stale amount_remaining from concurrent requests.+ gift_card.with_lock do+ new_amount = [gift_card.amount_remaining + payment.amount, total].min+ next if payment.amount == new_amount- remove_gift_card- apply_gift_card(applied_gift_card)+ difference = new_amount - payment.amount+ # Uses update_column to bypass Payment#max_amount validation which+ # can fail during recalculation due to stale in-memory order state.+ # Bounds are enforced via min() above.+ payment.update_column(:amount, new_amount)+ payment.source.update_column(:amount, new_amount)+ gift_card.amount_used += difference+ gift_card.save!+ endenddef redeem_gift_carddiff --git a/spree/core/app/services/spree/carts/update.rb b/spree/core/app/services/spree/carts/update.rbindex efadfbe3e3..7c6a738934 100644--- a/spree/core/app/services/spree/carts/update.rb+++ b/spree/core/app/services/spree/carts/update.rb@@ -89,18 +89,20 @@ module Spreecart.state = 'address'end- # Auto-advance as far as the checkout state machine allows.- # Loops cart.next until the cart can't progress further (e.g. missing- # payment) or reaches confirm/complete. Stops at the first step whose- # before_transition guard fails — the `requirements` array in the- # serialized response tells the frontend what's still missing.- # Failure is swallowed — the update itself already succeeded.+ # Auto-advance as far as the checkout state machine allows, but never+ # to complete. The complete transition must always be explicit via+ # the /carts/:id/complete endpoint — otherwise gift cards or store+ # credits that fully cover the order total would auto-complete the+ # cart during address/delivery updates.def try_advancereturn if cart.complete? || cart.canceled?+ steps = cart.checkout_stepsloop do+ current_index = steps.index(cart.state).to_i+ next_step = steps[current_index + 1]+ break if next_step.nil? || next_step == 'complete'break unless cart.next- break if cart.confirm? || cart.complete?endrescue StandardError => eRails.error.report(e, context: { order_id: cart.id, state: cart.state }, source: 'spree.checkout')diff --git a/spree/core/app/services/spree/checkout/add_store_credit.rb b/spree/core/app/services/spree/checkout/add_store_credit.rbindex b58e4ff390..a1f9d8f300 100644--- a/spree/core/app/services/spree/checkout/add_store_credit.rb+++ b/spree/core/app/services/spree/checkout/add_store_credit.rb@@ -12,9 +12,13 @@ module Spreereturn failure(nil, Spree.t(:error_user_does_not_have_any_store_credits)) unless @order.user&.store_credits&.any?ApplicationRecord.transaction do- @order.payments.store_credits.where(state: :checkout).map(&:invalidate!)+ existing = @order.payments.store_credits.where(state: :checkout)- apply_store_credits(remaining_total)+ if existing.any?+ update_existing_payments(existing, remaining_total)+ else+ apply_store_credits(remaining_total)+ endendif @order.reload.payments.store_credits.valid.any?@@ -27,6 +31,26 @@ module Spreeprivate+ # 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.firstraise 'Store credit payment method could not be found' unless payment_methoddiff --git a/spree/core/spec/models/spree/promotion_handler/coupon_with_gift_card_spec.rb b/spree/core/spec/models/spree/promotion_handler/coupon_with_gift_card_spec.rbindex cdaed25970..717ff91f1d 100644--- a/spree/core/spec/models/spree/promotion_handler/coupon_with_gift_card_spec.rb+++ b/spree/core/spec/models/spree/promotion_handler/coupon_with_gift_card_spec.rb@@ -94,6 +94,69 @@ describe Spree::PromotionHandler::Coupon, type: :model doendend+ describe '#recalculate_gift_card' do+ let(:store) { Spree::Store.default }+ let(:order) { create(:order_with_line_items, store: store) }+ let(:gift_card) { create(:gift_card, store: store, amount: 50) }+ let(:order_total) { order.total }++ before do+ order.apply_gift_card(gift_card)+ order.reload+ end++ it 'updates payment amount in place without creating new payments' do+ initial_payment_count = order.payments.count++ order.recalculate_gift_card++ expect(order.payments.count).to eq(initial_payment_count)+ expect(order.payments.where(state: 'invalid').count).to eq(0)+ end++ it 'does not change amount when total is unchanged' do+ payment = order.payments.checkout.store_credits.first+ original_amount = payment.amount++ order.recalculate_gift_card++ expect(payment.reload.amount).to eq(original_amount)+ end++ context 'when order total decreases below gift card payment' do+ before do+ # Set total to less than the gift card payment amount+ payment = order.payments.checkout.store_credits.first+ new_total = (payment.amount / 2).round(2)+ order.update_columns(total: new_total, item_total: new_total)+ end++ it 'decreases the payment amount to match new total' do+ order.recalculate_gift_card++ payment = order.payments.checkout.store_credits.first+ expect(payment.reload.amount).to eq(order.total)+ end++ it 'decreases gift card amount_used' do+ order.recalculate_gift_card++ expect(gift_card.reload.amount_used).to eq(order.total)+ end+ end++ context 'when gift card has less remaining than order total' do+ let(:gift_card) { create(:gift_card, store: store, amount: 5) }++ it 'keeps payment capped at gift card amount after recalculation' do+ order.recalculate_gift_card++ payment = order.payments.checkout.store_credits.first+ expect(payment.reload.amount).to eq(5)+ end+ end+ end+describe 'enable_gift_cards option' dolet(:store) { Spree::Store.default }let(:order) { create(:order_with_line_items, store: store) }diff --git a/spree/core/spec/services/spree/carts/update_spec.rb b/spree/core/spec/services/spree/carts/update_spec.rbindex b0fa350ae9..5c891f8f3d 100644--- a/spree/core/spec/services/spree/carts/update_spec.rb+++ b/spree/core/spec/services/spree/carts/update_spec.rb@@ -126,6 +126,26 @@ module Spreeexpect(order.reload.state).to eq('payment')endend++ context 'when order is fully covered by store credit payment' do+ let(:order) { create(:order_with_line_items, user: user, store: store, state: 'cart') }++ before do+ create(:store_credit_payment, order: order, amount: order.total)+ end++ it 'does not auto-complete the order' do+ expect(subject).to be_success+ expect(order.reload.state).not_to eq('complete')+ end++ it 'stops at the last step before complete' do+ expect(subject).to be_success+ steps = order.checkout_steps+ final_step = steps[steps.index('complete') - 1]+ expect(order.reload.state).to eq(final_step)+ end+ endendcontext 'with existing address by nested id' dodiff --git a/spree/core/spec/services/spree/checkout/add_store_credit_spec.rb b/spree/core/spec/services/spree/checkout/add_store_credit_spec.rbindex cecb5b0460..e34a000dd2 100644--- a/spree/core/spec/services/spree/checkout/add_store_credit_spec.rb+++ b/spree/core/spec/services/spree/checkout/add_store_credit_spec.rb@@ -94,6 +94,47 @@ describe Spree::Checkout::AddStoreCredit, type: :service doendend+ context 'when called again with an existing checkout store credit payment' do+ let(:store_credit) { create(:store_credit, amount: 500, store: store) }+ let(:order) { create(:order, user: store_credit.user, total: order_total, store: store) }++ before do+ order.update_column(:total, order_total)+ # First call creates the payment+ described_class.call(order: order)+ order.reload+ end++ it 'updates the existing payment in place instead of creating a new one' do+ expect(order.payments.store_credits.checkout.count).to eq(1)+ original_payment_id = order.payments.store_credits.checkout.first.id++ # Second call should update, not recreate+ described_class.call(order: order.reload)+ order.reload++ expect(order.payments.store_credits.checkout.count).to eq(1)+ expect(order.payments.store_credits.checkout.first.id).to eq(original_payment_id)+ end++ it 'does not create invalid payment records' do+ described_class.call(order: order.reload)+ order.reload++ expect(order.payments.where(state: 'invalid').count).to eq(0)+ end++ it 'adjusts amount when order total changes' do+ order.update_column(:total, 300)++ described_class.call(order: order.reload)+ order.reload++ expect(order.payments.store_credits.checkout.count).to eq(1)+ expect(order.payments.store_credits.checkout.first.amount).to eq(300)+ end+ end+context 'there are multiple store credits' dolet(:amount_difference) { 100 }let!(:primary_store_credit) { create(:store_credit, amount: (order_total - amount_difference), store: store) }