blob: 32f6d94b01a6f23bf58d4e11c578b0eaf2bf5285 (
plain)
1
2
3
4
5
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
# frozen_string_literal: true
module PaymentServices
# PaymentService
class PaymentService
attr_reader :error_messages
def initialize(card_id, user_account)
@user_account = user_account
@card_id = card_id
@service = CartToOrderService.new(@user_account)
@order = @service.call
end
def call
@error_messages = @service.error_messages and return if @order.nil?
@payment = Payment.new(order_id: @order.id, card_id: @card_id, total:)
unless @payment.save
@error_messages = @payment.errors.as_json
@order.destroy
return
end
update_products_available_quantity
update_order
end
private
def update_products_available_quantity
@order.products.joins(:product_orders).select('products.*, product_orders.quantity AS bought_quantity').distinct
.find_each do |product|
product.update(available_quantity: product.available_quantity - product.bought_quantity)
end
end
def update_order
@order.update(payment_id: @payment.id)
@user_account.cart.product_carts.destroy_all
@order
end
def total
total = 0
@order.product_orders.includes(:product).find_each do |product_order|
total += product_order.total
end
total
end
end
end
|