Class: Spree::GiftCards::Apply

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

Instance Method Summary collapse

Methods included from ServiceModule::Base

prepended

Instance Method Details

#call(gift_card:, order:) ⇒ Object



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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'app/services/spree/gift_cards/apply.rb', line 13

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?

  # 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

  # gift card requires logged user
  if gift_card.user.present?
    # user must be logged in
    return failure(:gift_card_customer_not_logged_in) if order.user.blank?
    # user must be the same as the gift card user
    return failure(:gift_card_mismatched_customer) if gift_card.user != order.user
  end

  amount = [gift_card.amount_remaining, order.total].min
  store = order.store

  return failure(:gift_card_no_amount_remaining) unless amount.positive? || order.total.zero?

  payment_method = ensure_store_credit_payment_method!(store)

  gift_card.lock!
  order.with_lock do
    store_credit = gift_card.store_credits.create!(
      store: store,
      user: order.user,
      amount: amount,
      currency: order.currency,
      originator: gift_card,
      action_originator: gift_card
    )
    gift_card.amount_used += amount
    gift_card.save!

    order.update!(gift_card: gift_card)
    order.payments.create!(
      source: store_credit,
      payment_method: payment_method,
      amount: amount,
      state: 'checkout',
      response_code: store_credit.generate_authorization_code
    )
    order.update_with_updater!
  end

  success(order.reload)
end