summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--app/models/order.rb1
-rw-r--r--app/models/payment.rb7
-rw-r--r--app/services/payment/cart_to_order_service.rb21
-rw-r--r--app/services/payment/payment_service.rb42
4 files changed, 71 insertions, 0 deletions
diff --git a/app/models/order.rb b/app/models/order.rb
index ae5a0d5..213bde9 100644
--- a/app/models/order.rb
+++ b/app/models/order.rb
@@ -7,4 +7,5 @@ class Order < ApplicationRecord
has_one :payment
has_many :product_orders
has_many :products, through: :product_orders
+ accepts_nested_attributes_for :product_orders
end
diff --git a/app/models/payment.rb b/app/models/payment.rb
index 5d5e862..4839de8 100644
--- a/app/models/payment.rb
+++ b/app/models/payment.rb
@@ -5,4 +5,11 @@
class Payment < ApplicationRecord
has_one :order
belongs_to :card
+ validate :card_belongs_to_user
+
+ def card_belongs_to_user
+ return unless order.user_account.cards.find_by(id: card.id).nil?
+
+ errors.add(:card_id, "doesn't belong to user")
+ end
end
diff --git a/app/services/payment/cart_to_order_service.rb b/app/services/payment/cart_to_order_service.rb
new file mode 100644
index 0000000..8dff43e
--- /dev/null
+++ b/app/services/payment/cart_to_order_service.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module Payment
+ # CartToOrderService
+ class CartToOrderService
+ def initialize(user_account)
+ @user_account = user_account
+ @cart = @user_account.cart
+ end
+
+ def call
+ order = Order.create(user_account_id: @user_account.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
+ end
+end
diff --git a/app/services/payment/payment_service.rb b/app/services/payment/payment_service.rb
new file mode 100644
index 0000000..9f44f87
--- /dev/null
+++ b/app/services/payment/payment_service.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+module Payment
+ # PaymentService
+ class PaymentService
+ attr_reader :error_messages
+
+ def initialize(params, user_account)
+ @user_account = user_account
+ @params = params
+ @order = Order.new(params.except(:card_id))
+ @card_id = params[:card_id]
+ @order = CartToOrderService.new(@user_account).call
+ end
+
+ def call
+ payment = Payment.new(order_id: @order.id, card_id: @card_id, total:)
+
+ @error_messages = { errors: @payment.errors.as_json } and return unless payment.save
+
+ @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
+ unitary_price * product_order.quantity
+ else
+ bulk_price * product_order.quantity
+ end
+ end
+ end
+ end
+end