Skip to content

Instantly share code, notes, and snippets.

@hooopo hooopo/package_generator_service.rb Secret
Last active Aug 29, 2015

Embed
What would you like to do?
# -*- encoding : utf-8 -*-
# 下单成功之后初始化Package过程
# 1. 初始化Package
# 2. 初始化Package Item
# 3. 实时同步库存数量
class PackageGenerator
attr_accessor :order, :package, :pickup_customer
def initialize(order, pickup_customer)
@order = order
@pickup_customer = pickup_customer
end
def run
generate_package
generate_package_items
sync_warehouse_stock_quantity
package
end
private
def generate_package
@package ||= order.packages.create!(:warehouse_id => get_warehouse_id, :state => get_init_state)
end
def get_init_state
return Package::STATE_VALUES[:awaiting_process] if pickup_customer || order.metro_pickup?
return Package::STATE_VALUES[:awaiting_stock]
end
def get_warehouse_id
return Warehouse::CENTERS[:Mtl] if order.metro_pickup?
return pickup_customer.scm_distribution_center_id if pickup_customer
return nil
end
def generate_package_items
order.order_items.includes(:product).each do |order_item|
if product = order_item.product
if product.is_value_pack?
add_virtual_product_to_package_item(order_item, package, product)
else
add_product_to_package_item(order_item, package, product)
end
end
end
end
def add_product_to_package_item(order_item, package, product)
exist_package_item = package.items.where(:product_id => product.id).first
if exist_package_item
exist_package_item.update_column(:quantity, exist_package_item.quantity.to_i + order_item.quantity)
exist_package_item
else
package.items.create!(
:product_id => product.id,
:order_id => package.order_id,
:order_item_id => order_item.id,
:quantity => order_item.quantity
)
end
end
def add_virtual_product_to_package_item(order_item, package, product)
product.virtual_product_items.each do |virtual_product_item|
exist_package_item = package.items.where(:product_id => virtual_product_item.product_id).first
if exist_package_item
exist_package_item.update_column(:quantity, exist_package_item.quantity.to_i + virtual_product_item.quantity * order_item.quantity)
exist_package_item
else
package.items.create!(
:product_id => virtual_product_item.product_id,
:order_id => package.order_id,
:order_item_id => order_item.id,
:quantity => virtual_product_item.quantity * order_item.quantity
)
end
end
end
def sync_warehouse_stock_quantity
StockUpdater::PackageItemsChanging.update(package) if package.processing_stock?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.