Skip to content

Commit

Permalink
Update create.rb
Browse files Browse the repository at this point in the history
  • Loading branch information
damianlegawiec committed Oct 28, 2021
1 parent 572849e commit 4a984e7
Showing 1 changed file with 34 additions and 12 deletions.
46 changes: 34 additions & 12 deletions core/app/services/spree/payments/create.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,58 @@ class Create
prepend Spree::ServiceModule::Base

def call(order:, params: {}, user: nil)
payment_method = order.available_payment_methods.find { |pm| pm.id.to_s == params[:payment_method_id]&.to_s }
ApplicationRecord.transaction do
run :prepare_payment_attributes
run :prepare_source_attributes
run :save_payment
end
end

protected

def prepare_payment_attributes(order:, params:, user: nil)
payment_attributes = {
amount: params[:amount] || order.total - order.payment_total,
payment_method: payment_method
payment_method: order.available_payment_methods.find { |pm| pm.id.to_s == params[:payment_method_id]&.to_s }
}

if payment_method.source_required?
success(order: order, params: params, user: user, payment_attributes: payment_attributes)
end

def prepare_source_attributes(order:, params:, payment_attributes:, user: nil)
payment_method = payment_attributes[:payment_method]

if payment_method&.source_required?
if user.present? && params[:source_id].present?
payment_attributes[:source] = payment_method.payment_source_class.find_by(id: params[:source_id])
else
payment_attributes[:source_attributes] = params.permit(
:payment_method_id,
:gateway_payment_profile_id,
:gateway_customer_profile_id,
:last_digits,
:month,
:year,
:name
).merge(user_id: user&.id)
payment_attributes[:source_attributes] = params.permit(permitted_source_attributes).merge(user_id: user&.id)
end
end

success(order: order, payment_attributes: payment_attributes)
end

def save_payment(order:, payment_attributes:)
payment = order.payments.new(payment_attributes)
if payment.save
success(payment)
else
failure(payment)
end
end

def permitted_source_attributes
%i[
payment_method_id
gateway_payment_profile_id
gateway_customer_profile_id
last_digits
month
year
name
]
end
end
end
end

0 comments on commit 4a984e7

Please sign in to comment.