2022-08-19 19:59:13 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
# Provides methods for add order item to cart
|
|
|
|
class Cart::AddItemService
|
|
|
|
def call(order, orderable, quantity = 1)
|
|
|
|
return order if quantity.to_i.zero?
|
|
|
|
|
2022-12-28 17:51:27 +01:00
|
|
|
item = case orderable
|
|
|
|
when Product
|
|
|
|
add_product(order, orderable, quantity)
|
2022-12-30 15:29:52 +01:00
|
|
|
when /^CartItem::/
|
|
|
|
add_cart_item(order, orderable)
|
2022-12-28 17:51:27 +01:00
|
|
|
else
|
|
|
|
raise Cart::UnknownItemError
|
|
|
|
end
|
2022-08-19 19:59:13 +02:00
|
|
|
|
2023-02-14 13:10:58 +01:00
|
|
|
order.created_at = Time.current if order.order_items.length.zero?
|
2022-10-04 17:42:32 +02:00
|
|
|
|
2022-12-28 17:51:27 +01:00
|
|
|
ActiveRecord::Base.transaction do
|
|
|
|
item.save
|
|
|
|
Cart::UpdateTotalService.new.call(order)
|
|
|
|
order.save
|
|
|
|
end
|
|
|
|
order.reload
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def add_product(order, orderable, quantity)
|
|
|
|
raise Cart::InactiveProductError unless orderable.is_active
|
|
|
|
|
2022-09-14 09:26:29 +02:00
|
|
|
item = order.order_items.find_by(orderable: orderable)
|
|
|
|
quantity = orderable.quantity_min > quantity.to_i && item.nil? ? orderable.quantity_min : quantity.to_i
|
2022-09-13 16:36:44 +02:00
|
|
|
|
2022-08-19 19:59:13 +02:00
|
|
|
if item.nil?
|
2022-09-19 19:27:11 +02:00
|
|
|
item = order.order_items.new(quantity: quantity, orderable: orderable, amount: orderable.amount || 0)
|
2022-08-19 19:59:13 +02:00
|
|
|
else
|
2022-10-14 10:52:24 +02:00
|
|
|
item.quantity += quantity
|
2022-08-19 19:59:13 +02:00
|
|
|
end
|
2022-09-16 17:10:13 +02:00
|
|
|
raise Cart::OutStockError if item.quantity > orderable.stock['external']
|
|
|
|
|
2022-12-28 17:51:27 +01:00
|
|
|
item
|
|
|
|
end
|
|
|
|
|
2022-12-30 15:29:52 +01:00
|
|
|
def add_cart_item(order, orderable)
|
|
|
|
order.order_items.new(quantity: 1, orderable: orderable, amount: orderable.price.amount || 0)
|
2022-08-19 19:59:13 +02:00
|
|
|
end
|
|
|
|
end
|