# 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