Skip to content

Instantly share code, notes, and snippets.

@stuartbates
Last active December 17, 2015 20:43
Show Gist options
  • Select an option

  • Save stuartbates/c7f2704ec321aa073f35 to your computer and use it in GitHub Desktop.

Select an option

Save stuartbates/c7f2704ec321aa073f35 to your computer and use it in GitHub Desktop.
WALKTHROUGH: Creating new shipment from admin panel
# api/app/controllers/spree/api/shipments_controller.rb
def create
variant = Spree::Variant.find(params[:variant_id])
quantity = params[:quantity].to_i
@shipment = @order.shipments.create(:stock_location_id => params[:stock_location_id])
@order.contents.add(variant, quantity, nil, @shipment)
@shipment.refresh_rates
@shipment.save!
respond_with(@shipment.reload, :default_template => :show)
end
# core/app/models/spree/order_contents.rb
def add(variant, quantity=1, currency=nil, shipment=nil)
line_item = order.find_line_item_by_variant(variant)
add_to_line_item(line_item, variant, quantity, currency, shipment)
end
# core/app/models/spree/order_contents.rb
def add_to_line_item(line_item, variant, quantity, currency=nil, shipment=nil)
if line_item
line_item.target_shipment = shipment
line_item.quantity += quantity.to_i
line_item.currency = currency unless currency.nil?
line_item.save
else
line_item = LineItem.new(quantity: quantity)
line_item.target_shipment = shipment
line_item.variant = variant
if currency
line_item.currency = currency unless currency.nil?
line_item.price = variant.price_in(currency).amount
else
line_item.price = variant.price
end
order.line_items << line_item
line_item
end
order.reload
line_item
end
# core/app/models/spree/line_item.rb
def update_inventory
if changed?
Spree::OrderInventory.new(self.order).verify(self, target_shipment)
end
end
# core/app/models/spree/order_inventory.rb
def verify(line_item, shipment = nil)
if order.completed? || shipment.present?
variant_units = inventory_units_for(line_item.variant)
if variant_units.size < line_item.quantity
quantity = line_item.quantity - variant_units.size
shipment = determine_target_shipment(line_item.variant) unless shipment
add_to_shipment(shipment, line_item.variant, quantity)
elsif variant_units.size > line_item.quantity
remove(line_item, variant_units, shipment)
end
else
true
end
end
# core/app/models/spree/order_inventory.rb
def add_to_shipment(shipment, variant, quantity)
if variant.should_track_inventory?
on_hand, back_order = shipment.stock_location.fill_status(variant, quantity)
on_hand.times { shipment.set_up_inventory('on_hand', variant, order) }
back_order.times { shipment.set_up_inventory('backordered', variant, order) }
else
quantity.times { shipment.set_up_inventory('on_hand', variant, order) }
end
# adding to this shipment, and removing from stock_location
if order.completed?
shipment.stock_location.unstock(variant, quantity, shipment)
end
quantity
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment