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.

simplify gift cards apply

Damian Legawiecccfb6e06b94f
diff --git a/core/app/models/spree/gift_card.rb b/core/app/models/spree/gift_card.rb
index dd7efee9e8..4cba51be4a 100644
--- a/core/app/models/spree/gift_card.rb
+++ b/core/app/models/spree/gift_card.rb
@@ -127,27 +127,6 @@ module Spree
end
alias_method :amount_used, :used_amount
- def apply!(amount:, user:, currency:)
- amount_applied = [amount, amount_remaining].min
- return unless amount_applied.positive?
-
- transaction do
- store_credit = Spree::StoreCredit.create!(
- gift_card: self,
- store: store,
- user: user,
- amount: amount_applied,
- currency: currency,
- expires_at: expires_at
- )
-
- self.amount_remaining -= amount_applied
- save!
-
- store_credit
- end
- end
-
def undo_apply!(amount:)
transaction do
self.amount_remaining = [amount_remaining + amount, self.amount].min
diff --git a/core/app/services/spree/gift_cards/apply.rb b/core/app/services/spree/gift_cards/apply.rb
index b9b5cf93ea..e0130e9b59 100644
--- a/core/app/services/spree/gift_cards/apply.rb
+++ b/core/app/services/spree/gift_cards/apply.rb
@@ -4,28 +4,42 @@ module Spree
prepend Spree::ServiceModule::Base
def call(gift_card:, order:)
+ # we shouldn't mix an order with a gift card and a store credit
return failure(:gift_card_using_store_credit_error) if order.using_store_credit?
- amount_applied = [gift_card.amount_remaining, order.total].min
+ # we shouldn't allow a gift card to be applied to an order with a different currency
+ return failure(:gift_card_mismatched_currency) if gift_card.currency != order.currency
+
+ amount = [gift_card.amount_remaining, order.total].min
store = order.store
- gift_card.transaction do
- payment_method = ensure_store_credit_payment_method!(store)
- store_credit = gift_card.apply!(amount: amount_applied, user: order.user, currency: order.currency)
+ return failure(:gift_card_no_amount_remaining) unless amount.positive? || order.total.zero?
+
+ payment_method = ensure_store_credit_payment_method!(store)
- return failure(:gift_card_no_amount_remaining) unless store_credit.present?
+ gift_card.lock!
+ order.with_lock do
+ store_credit = gift_card.store_credits.create!(
+ store: store,
+ user: order.user,
+ amount: amount,
+ currency: order.currency,
+ expires_at: gift_card.expires_at
+ )
+ gift_card.amount_remaining -= amount
+ gift_card.save!
order.update!(gift_card: gift_card)
order.payments.create!(
source: store_credit,
payment_method: payment_method,
- amount: amount_applied,
+ amount: amount,
state: 'checkout',
response_code: store_credit.generate_authorization_code
)
-
- success(true)
end
+
+ success(order.reload)
end
private