2022-09-27 19:44:39 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2023-01-02 16:59:41 +01:00
|
|
|
# Provides methods to check cart's items (available, price, stock, quantity_min)
|
2022-09-27 19:44:39 +02:00
|
|
|
class Cart::CheckCartService
|
|
|
|
def call(order)
|
|
|
|
res = { order_id: order.id, details: [] }
|
|
|
|
order.order_items.each do |item|
|
2023-01-02 16:59:41 +01:00
|
|
|
errors = case item.orderable_type
|
|
|
|
when 'Product'
|
|
|
|
check_product(item)
|
|
|
|
when /^CartItem::/
|
|
|
|
check_cart_item(item, order)
|
|
|
|
else
|
|
|
|
[]
|
|
|
|
end
|
2022-09-27 19:44:39 +02:00
|
|
|
res[:details].push({ item_id: item.id, errors: errors })
|
|
|
|
end
|
|
|
|
res
|
|
|
|
end
|
2023-01-02 16:59:41 +01:00
|
|
|
|
|
|
|
def check_product(item)
|
|
|
|
errors = []
|
|
|
|
errors.push({ error: 'is_active', value: false }) unless item.orderable.is_active
|
|
|
|
if item.quantity > item.orderable.stock['external'] || item.orderable.stock['external'] < item.orderable.quantity_min
|
|
|
|
value = item.orderable.stock['external'] < item.orderable.quantity_min ? 0 : item.orderable.stock['external']
|
|
|
|
errors.push({ error: 'stock', value: value })
|
|
|
|
end
|
|
|
|
orderable_amount = item.orderable.amount || 0
|
|
|
|
errors.push({ error: 'amount', value: orderable_amount / 100.0 }) if item.amount != orderable_amount
|
|
|
|
errors.push({ error: 'quantity_min', value: item.orderable.quantity_min }) if item.quantity < item.orderable.quantity_min
|
|
|
|
errors
|
|
|
|
end
|
|
|
|
|
|
|
|
def check_cart_item(item, order)
|
|
|
|
item.valid?(order.order_items)
|
|
|
|
item.errors.to_a
|
|
|
|
end
|
2022-09-27 19:44:39 +02:00
|
|
|
end
|