Skip to content

Instantly share code, notes, and snippets.

@kana-sama
Last active November 20, 2016 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kana-sama/b20004fb326d4b55a7efdb2428cf447d to your computer and use it in GitHub Desktop.
Save kana-sama/b20004fb326d4b55a7efdb2428cf447d to your computer and use it in GitHub Desktop.
class Order
# user
# status %i{ registration payment waiting_products waiting_preorder packing sending complete }
# wait_until_preorder bool - ждать для открыток?
def avaiable?
order_items.all? { |oi| oi.avaiable? }
end
end
class OrderController
def create
order = Order.new(
user: current_user,
status: :registration,
wait_until_preorder: params[:wait],
)
params[:cart].each do |line|
product = Product.find line[:product_id]
count = line[:count]
order.order_items << OrderItem.new(
pruduct: product,
count: count,
)
order.weight += product.weight * count
order.price += product.price * count
end
order.create!
end
def registrate
order = Order.find(params[:order_id])
order.address = params[:addres] # псевдо
order.weight += 100 # за упаковку
order.price += 100 # за упаковку
order.status = :payment
order.save!
end
def pay
order = Order.find(params[:order_id])
order.status = :waiting_products
if order.avaiable?
order.status = :waiting_preorder
end
if order.wait_until_preorder?
unless order.order_items.any? { |oi| oi.preorder? }
order.status = :packing
end
else
order.status = :packing
end
end
end
class OrderItem
# order_id
# product_id
# count
# reserved - сколько было зарезервировано для заказа
# preorder_id
def avaiable?
reserved == count
end
def before_create
if product.preorder?
preorder = product.preorder
end
reserved = min(product.store, count)
product.store -= reserved
end
end
class Product
def before_change_store
product = Product.find(params[:product])
OrderItems
.includes(:order)
.where(order: { status: :waiting_products })
.where(product: product)
.each do |oi|
need = oi.count - oi.reserved
oi.reserved += min(product.store, need)
product.store -= oi.reserved
oi.save!
if oi.order.avaiable? { |oi| oi.avaiable? }
oi.order.status = :waiting_preorder
end
if oi.rder.wait_until_preorder?
unless oi.order.order_items.any? { |oi| oi.preorder? }
oi.order.status = :packing
end
else
oi.order.status = :packing
end
oi.order.save!
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment