Class: Spree::StoreCredits::Apply

Inherits:
Object
  • Object
show all
Includes:
Spree::ServiceModule::Base
Defined in:
app/services/spree/store_credits/apply.rb

Instance Method Summary collapse

Methods included from Spree::ServiceModule::Base

prepended

Instance Method Details

#call(order:, amount: nil) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'app/services/spree/store_credits/apply.rb', line 6

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

  # Mirrors Spree::GiftCards::Apply, which refuses a gift card once store
  # credit is in use: the two are never combined on one order.
  return failure(nil, I18n.t('spree.store_credit_using_gift_card_error')) if @order.gift_card.present?
  return failure(nil, I18n.t('spree.error_user_does_not_have_any_store_credits')) unless spendable_store_credits.exists?

  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, I18n.t('spree.store_credit_not_applied'))
  end
end