summaryrefslogtreecommitdiff
path: root/app/services/payment_services/cart_to_order_service.rb
blob: 3985f901ff1d29101d9d683930d433e5d50ce858 (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
# frozen_string_literal: true

module PaymentServices
  # CartToOrderService
  class CartToOrderService
    attr_reader :error_messages

    def initialize(user_account)
      @user_account = user_account
      @cart = @user_account.cart
    end

    def call
      @error_messages = { errors: 'Cart is empty' } and return if @cart.product_carts.empty?

      order = Order.create(user_account_id: @user_account.id, public_id: generate_public_id)

      @cart.product_carts.pluck(:product_id, :quantity).each do |data|
        ProductOrder.create(order_id: order.id, product_id: data[0], quantity: data[1])
      end

      order
    end

    private

    def generate_public_id
      public_id = SecureRandom.hex(12)
      public_id = SecureRandom.hex(12) while Order.exists?(public_id:)
      public_id
    end
  end
end