Skip to content

Commit

Permalink
Move increment/decrement/supply stock level to dedicated service
Browse files Browse the repository at this point in the history
  • Loading branch information
stolarczykt authored and lukaszreszke committed Sep 25, 2024
1 parent 3c693cd commit 4478999
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
6 changes: 3 additions & 3 deletions rails_application/app/controllers/orders_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def add_item

@order = Order.find(params[:id])
@order.add_item(product)
product.decrement!(:stock_level)
Inventory::ProductService.new.decrement_stock_level(product.id)
@order.save!

redirect_to edit_order_path(params[:id])
Expand All @@ -87,7 +87,7 @@ def remove_item
product = Product.find(params[:product_id])
@order = Order.find(params[:id])
@order.remove_item(product)
product.increment!(:stock_level)
Inventory::ProductService.new.increment_stock_level(product.id)
@order.save!

redirect_to edit_order_path(params[:id])
Expand All @@ -113,7 +113,7 @@ def expire
.where(status: "Draft")
.find_each do |order|
order.order_items.each do |item|
item.product.increment!(:stock_level)
Inventory::ProductService.new.increment_stock_level(item.product.id)
end
order.status = "Expired"
order.save!
Expand Down
4 changes: 1 addition & 3 deletions rails_application/app/controllers/supplies_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ def new
end

def create
product = Product.find(params[:product_id])
product.stock_level == nil ? product.stock_level = params[:quantity].to_i : product.stock_level += params[:quantity].to_i
product.save!
Inventory::ProductService.new.supply(params[:product_id], params[:quantity].to_i)
redirect_to products_path, notice: "Stock level changed"
end
end
22 changes: 22 additions & 0 deletions rails_application/app/models/inventory/product_service.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# frozen_string_literal: true

module Inventory
class ProductService

def decrement_stock_level(product_id)
product = ::Product.find(product_id)
product.decrement!(:stock_level)
end

def increment_stock_level(product_id)
product = ::Product.find(product_id)
product.increment!(:stock_level)
end

def supply(product_id, quantity)
product = ::Product.find(product_id)
product.stock_level == nil ? product.stock_level = quantity : product.stock_level += quantity
product.save!
end
end
end

0 comments on commit 4478999

Please sign in to comment.