A shop is short, another location has stock. The naive transfer moves min(need, on_hand) units. That is wrong in at least four ways, and each one is easy to encode once you name it.

from dataclasses import dataclass from datetime import date, timedelta @dataclass class Lot: qty: int expires: date | None def transferable(on_hand: int, reserved: int, damaged: int, safety: int) -> int: """Units the source can release without breaking its own commitments.""" return max(0, on_hand - reserved - damaged - safety) def plan(need: int, releasable: int, pack: int, lots: list[Lot], ship_day: date, lead_days: int, min_shelf_days: int, fixed_cost: int, unit_cost: int) -> dict: arrival = ship_day + timedelta(days=lead_days) # 1. lots that would arrive too close to expiry are not candidates ok = [l for l in lots if l.expires is None or l.expires >= arrival + timedelta(days=min_shelf_days)] usable = min(releasable, sum(l.qty for l in ok)) # 2. whole packs only, never more than the source can release packs = min(need, usable) // pack units = packs * pack cost = fixed_cost + unit_cost * units if units else 0 return {"packs": packs, "units": units, "arrival": arrival, "cost": cost, "still_short": need - units} rel = transferable(on_hand=40, reserved=5, damaged=0, safety=15) # 20 print(plan(need=10, releasable=rel, pack=5, lots=[Lot(40, None)], ship_day=date(2026, 12, 8), lead_days=2, min_shelf_days=0, fixed_cost=50, unit_cost=2)) # {'packs': 2, 'units': 10, 'arrival': datetime.date(2026, 12, 10), # 'cost': 70, 'still_short': 0} 

The rules, stated once

  • Release, not on-hand. 40 on hand with 5 reserved and 15 safety stock means 20 can move. Moving 40 just relocates the shortage.
  • Whole packs, rounded down. If the need is 12 and packs are 5, the plan sends 2 packs and reports 2 units still short. It never invents a partial pack.
  • Expiry is checked at arrival plus required shelf life, not today.
  • If the inputs change, the answer may be zero. Raise safety stock to 35 and transferable returns 0; the plan moves nothing and says so, instead of quietly overriding the constraint.

Things a real version adds

Multiple routes with dispatch weekdays and capacity in units, kg or m³; demand scenarios; approval, dispatch and receipt as separate posted events, so a proposal never changes stock on its own; and an honest status: proven optimal within the model, or only feasible within a time limit.

That fuller version is what we built in the Multi-Location Stock Transfer Optimizer (paid, $29, with a free demo of three store scenarios): https://gettidycents.com/product/multi-location-stock-transfer-optimizer