1
0
mirror of https://github.com/LaCasemate/fab-manager.git synced 2025-02-26 20:54:21 +01:00

(quality) refactoring cart add/remove/set_quantity item total compute

This commit is contained in:
Du Peng 2022-10-14 10:52:24 +02:00
parent 6dea7ba6b3
commit 1b7c4862c5
7 changed files with 21 additions and 12 deletions

View File

@ -15,13 +15,13 @@ class Cart::AddItemService
if item.nil?
item = order.order_items.new(quantity: quantity, orderable: orderable, amount: orderable.amount || 0)
else
item.quantity += quantity.to_i
item.quantity += quantity
end
raise Cart::OutStockError if item.quantity > orderable.stock['external']
order.total += (item.amount * item.quantity.to_i) unless item.is_offered
ActiveRecord::Base.transaction do
item.save
Cart::UpdateTotalService.new.call(order)
order.save
end
order.reload

View File

@ -18,6 +18,7 @@ class Cart::FindOrCreateService
clean_old_cart if @user
@order.update(statistic_profile_id: @user.statistic_profile.id) if @order.statistic_profile_id.nil? && @user&.member?
@order.update(operator_profile_id: @user.invoicing_profile.id) if @order.operator_profile_id.nil? && @user&.privileged?
Cart::UpdateTotalService.new.call(@order)
return @order
end

View File

@ -9,11 +9,10 @@ class Cart::RefreshItemService
raise ActiveRecord::RecordNotFound if item.nil?
order.total -= (item.amount * item.quantity.to_i) unless item.is_offered
item.amount = orderable.amount || 0
order.total += (item.amount * item.quantity.to_i) unless item.is_offered
ActiveRecord::Base.transaction do
item.save
Cart::UpdateTotalService.new.call(order)
order.save
end
order.reload

View File

@ -7,9 +7,9 @@ class Cart::RemoveItemService
raise ActiveRecord::RecordNotFound if item.nil?
order.total -= (item.amount * item.quantity.to_i) unless item.is_offered
ActiveRecord::Base.transaction do
item.destroy!
Cart::UpdateTotalService.new.call(order)
order.save
end
order.reload

View File

@ -7,14 +7,10 @@ class Cart::SetOfferService
raise ActiveRecord::RecordNotFound if item.nil?
if !item.is_offered && is_offered
order.total -= (item.amount * item.quantity)
elsif item.is_offered && !is_offered
order.total += (item.amount * item.quantity)
end
item.is_offered = is_offered
ActiveRecord::Base.transaction do
item.save
Cart::UpdateTotalService.new.call(order)
order.save
end
order.reload

View File

@ -13,10 +13,9 @@ class Cart::SetQuantityService
raise ActiveRecord::RecordNotFound if item.nil?
different_quantity = quantity.to_i - item.quantity
order.total += (item.amount * different_quantity) unless item.is_offered
ActiveRecord::Base.transaction do
item.update(quantity: quantity.to_i)
Cart::UpdateTotalService.new.call(order)
order.save
end
order.reload

View File

@ -0,0 +1,14 @@
# frozen_string_literal: true
# Provides methods for update total of cart
class Cart::UpdateTotalService
def call(order)
total = 0
order.order_items.each do |item|
total += (item.amount * item.quantity) unless item.is_offered
end
order.total = total
order.save
order
end
end