Class: Spree::GiftCards::Remove

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

Instance Method Summary collapse

Methods included from ServiceModule::Base

prepended

Instance Method Details

#call(order:) ⇒ 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
# File 'app/services/spree/gift_cards/remove.rb', line 6

def call(order:)
  return failure(:remove_gift_card_on_completed_order_error) if order.completed?
  return success(true) if order.gift_card.nil?

  gift_card = order.gift_card

  return failure(:gift_card_not_found) if gift_card.nil?

  order.with_lock do
    payments = order.payments.checkout.store_credits.where(source: gift_card.store_credits)
    payment_total = payments.sum(:amount)
    payments.each(&:invalidate!)

    gift_card.with_lock do
      gift_card.amount_used -= payment_total
      gift_card.save!
    end

    # we need to destroy the store credits here because they are not associated with the order
    # and we need to remove them from the gift card
    # TODO: rather than destroying the store credits, we should void them
    payments.each do |payment|
      payment.source.destroy!
    end

    order.update!(gift_card: nil)
    order.update_with_updater!
  end

  success(true)
end