summaryrefslogtreecommitdiff
path: root/app/services/payment_services/payment_service.rb
blob: 82267d50baf6ddd7b3f3d2c46c146b12c9d92f60 (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
# 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

      @order.update(payment_id: @payment.id)
      @user_account.cart.product_carts.destroy_all
      @order
    end

    private

    def total
      total = 0

      @order.product_orders.joins(:product).select(
        'product_orders.*, products.bulk_price AS bulk_price, products.unitary_price AS unitary_price'
      ).each do |product_order|
        total += if product_order.quantity < 5
                   product_order.unitary_price * product_order.quantity
                 else
                   product_order.bulk_price * product_order.quantity
                 end
      end
      total
    end
  end
end