@@ -89,12 +89,18 @@ def run_tracking_inventory
8989 available_quantity = get_available_quantity
9090 new_on_hand_quantity = [ available_quantity , quantity ] . min
9191 backordered_quantity = get_backordered_quantity ( available_quantity , new_on_hand_quantity )
92- unstock_quantity = desired_shipment . stock_location . backorderable? ( variant ) ? quantity : new_on_hand_quantity
92+
93+ # Determine how many backordered and on_hand items we'll need to move. We
94+ # don't want to move more than what's being asked. And we can't move a
95+ # negative amount, which is why we need to perform our min/max logic here.
96+ backordered_quantity_to_move = [ backordered_quantity , quantity ] . min
97+ on_hand_quantity_to_move = [ quantity - backordered_quantity_to_move , 0 ] . max
9398
9499 ActiveRecord ::Base . transaction do
95100 if handle_stock_counts?
96101 # We only run this query if we need it.
97102 current_on_hand_quantity = [ current_shipment . inventory_units . pre_shipment . size , quantity ] . min
103+ unstock_quantity = desired_shipment . stock_location . backorderable? ( variant ) ? quantity : new_on_hand_quantity
98104
99105 # Restock things we will not fulfil from the current shipment anymore
100106 current_stock_location . restock ( variant , current_on_hand_quantity , current_shipment )
@@ -111,14 +117,14 @@ def run_tracking_inventory
111117 inventory_units .
112118 where ( variant :) .
113119 order ( state : :asc ) .
114- limit ( backordered_quantity ) .
120+ limit ( backordered_quantity_to_move ) .
115121 update_all ( shipment_id : desired_shipment . id , state : :backordered )
116122
117123 current_shipment .
118124 inventory_units .
119125 where ( variant :) .
120126 order ( state : :asc ) .
121- limit ( quantity - backordered_quantity ) .
127+ limit ( on_hand_quantity_to_move ) .
122128 update_all ( shipment_id : desired_shipment . id , state : :on_hand )
123129 end
124130 end
0 commit comments