1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2024-12-03 14:24:23 +01:00
fab-manager/app/services/cart/add_item_service.rb

30 lines
897 B
Ruby
Raw Normal View History

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?
raise Cart::InactiveProductError unless orderable.is_active
order.created_at = Time.current if order.order_items.length.zero?
item = order.order_items.find_by(orderable: orderable)
quantity = orderable.quantity_min > quantity.to_i && item.nil? ? orderable.quantity_min : quantity.to_i
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
item.quantity += quantity
2022-08-19 19:59:13 +02:00
end
raise Cart::OutStockError if item.quantity > orderable.stock['external']
2022-08-19 19:59:13 +02:00
ActiveRecord::Base.transaction do
item.save
Cart::UpdateTotalService.new.call(order)
2022-08-19 19:59:13 +02:00
order.save
end
order.reload
end
end