Class: Vpago::Payments::FindOrCreate

Inherits:
Object
  • Object
show all
Includes:
Spree::ServiceModule::Base
Defined in:
app/services/vpago/payments/find_or_create.rb

Instance Method Summary collapse

Instance Method Details

#call(order:, params: {}) ⇒ Object

rubocop:disable Lint/UnusedMethodArgument



7
8
9
10
11
12
# File 'app/services/vpago/payments/find_or_create.rb', line 7

def call(order:, params: {}) # rubocop:disable Lint/UnusedMethodArgument
  ApplicationRecord.transaction do
    run :find_payment_method
    run :find_or_create_payment
  end
end

#find_or_create_payment(order:, params:, payment_method:) ⇒ Object



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
# File 'app/services/vpago/payments/find_or_create.rb', line 21

def find_or_create_payment(order:, params:, payment_method:)
  payment = order.payments.find_or_initialize_by(
    state: :checkout,
    amount: order.order_total_after_store_credit,
    payment_method: payment_method
  )

  if payment_method&.source_required? && payment.source.blank?
    source_attributes = {
      payment_option: params[:payment_option],
      payment_method_id: payment_method.id,
      user_id: order.user&.id,
      gateway_payment_profile_id: params[:gateway_payment_profile_id],
      gateway_customer_profile_id: params[:gateway_customer_profile_id],
      last_digits: params[:last_digits],
      month: params[:month],
      year: params[:year],
      name: params[:name]
    }.compact

    payment.source = payment_method.payment_source_class.new(source_attributes)
  end

  payment.save!

  return failure(payment) if payment.errors.any?

  success(order: order)
end

#find_payment_method(order:, params:) ⇒ Object



14
15
16
17
18
19
# File 'app/services/vpago/payments/find_or_create.rb', line 14

def find_payment_method(order:, params:)
  payment_method = order.available_payment_methods.find { |pm| pm.id.to_s == params[:payment_method_id]&.to_s }
  return failure(nil, :payment_method_not_found) if payment_method.blank?

  success(order: order, params: params, payment_method: payment_method)
end