From 9607fcb5a9cdc7595633336881cc0dd8aa9fb8ca Mon Sep 17 00:00:00 2001 From: HombreLaser Date: Fri, 14 Apr 2023 20:52:50 -0600 Subject: Corrige errores de OrdersController --- app/services/payment_services/payment_service.rb | 48 ++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 app/services/payment_services/payment_service.rb (limited to 'app/services/payment_services/payment_service.rb') diff --git a/app/services/payment_services/payment_service.rb b/app/services/payment_services/payment_service.rb new file mode 100644 index 0000000..82267d5 --- /dev/null +++ b/app/services/payment_services/payment_service.rb @@ -0,0 +1,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 -- cgit v1.2.3