Which lot fills which order, and what it really cost.
As Vice President of Rehan Spices, I work in import and distribution. Here I work through one question from that trade: which receipt lot can fill which order, and how much of the purchase and freight cost goes with each unit shipped.
01 Receipt lots and customer orders
The lots, customers and charges are made up, and everything runs in your browser: nothing you type is stored or sent.
The opening example defeats a simple greedy assignment: the flexible order must leave the early receipt for an order shipping before the second lot is available. The solver can reverse an earlier assignment. All amounts are USD cents.
Loading or resetting replaces your edits, and reloading the page clears them. A loaded scenario waits until you compute it.
Edit the source: lots, demand and inbound charges
At most 12 lots, 12 orders, 6 inbound charges. Quantities are whole units, 0..1,000 per record. Missing or unknown fields, unsafe integers and invalid dates block the entire run. See the complete schema below. Edit quarantined in a lot to test withholding or releasing that lot.
JavaScript is needed to compute. No allocation has run.
02 The fill and its trade-off
03 Units and cents, lot by lot
| Lot / SKU | Receipt / expiry | Units: stock / allocated / remaining | Purchase | Inbound | Allocated landed | Remaining landed | Evidence |
|---|
| Lot → order | Units | Rank cost / unit | Purchase | Inbound | Landed | Revenue | Gross margin |
|---|
04 Why an order is short
05 Where every cent goes
Purchase plus shared inbound charges equals assigned cost plus remaining inventory cost. Revenue minus assigned cost is modeled gross margin, before outbound delivery, overhead, returns or tax.
Scroll horizontally on a small screen. Every amount is also reconciled in the ledger below.
| Charge / source | Lot | Basis weight | Floor cents | Remainder / denominator | Extra cent | Final cents |
|---|
Cost split rounding: allocations versus remaining inventory
| Lot / pool | Bucket | Units | Floor cents | Remainder / denominator | Extra cent | Final cents |
|---|
06 The pairs the rules exclude
Every lot/order pair and all exclusion reasons
| Lot → order | Eligibility | Shelf days at ship | Rank key / allocated | Receipt evidence | Demand evidence |
|---|
Augmenting paths, minimum cut and residual cost certificate
How this run was reached
Replay the downloaded audit with CommerceEngine.compute(CommerceEngine.parseSnapshot(rawInput)). The call recomputes everything from the exported rawInput text.
The inputs, each solver step and the abstentions, in order. Any edit hides this notebook until you run again. Download recomputes from the current text and writes no file when that text is invalid.
Method and limits
Eligibility and the actual optimization objective
SKU matching is exact and case sensitive. A lot is eligible only if it is not quarantined, has positive quantity, is available on or before the order's ship date, expires on or after that date, and has at least the requested whole remaining shelf days. Zero-demand orders have no edges. All dates are UTC calendar days; expiry on the ship date is allowed only when minimum shelf life is zero. Availability equal to ship date is allowed. Dates are plain calendar days; time zones, transit time and inspection calendars are outside the model.
First maximize the total filled whole units across all orders. Among maximum fills, minimize the sum of quantity × (orderRank × (lotCount + 1) + lotRank). Zero-based order ranks sort by priority (1 first), then ship date, then ID. Lot ranks sort by expiry, then availability date, then ID. Ranks include zero and quarantined records. This weighted score leans toward priority and earlier expiry without enforcing either strictly, so an order can receive a later-expiring lot; fairness and profit are outside the objective.
The integer network is source → receipt lots → eligible orders → sink. Successive shortest augmenting paths use Bellman-Ford and reverse residual arcs to revise assignments. Node and adjacency construction uses ascending ASCII IDs; equal-distance relaxations retain the first predecessor. Results are invariant to array order, but changing IDs can change ties. Exported rankKeys list the order fields (priority, ship date, id) and lot fields (expiry, availability, id) beside each rank. Apportionment rows export tieKey and tieRank for remainder ties. The final source-reachable residual cut certifies maximum flow. Nonnegative reduced costs under the exported residual potentials certify minimum cost for that flow. Certificates describe this model only.
Exact cents, rounding and cost boundaries
Each inbound line is allocated independently over all lots, including quarantined, future and expired stock, by quantity times unit grams or by total purchase cents. Integer floors are followed by largest fractional remainders. Ties use ascending lot ID. A positive charge with a zero total basis is rejected; zero charges with zero basis allocate zero. A zero-quantity lot must have zero purchase value. Zero weight on a positive lot is permitted and contributes no weight basis.
Within each lot, split purchase cents and each allocated inbound line independently across delivered order buckets and the remaining-inventory bucket in proportion to units, again using largest remainder. Ties sort keys order:ID then remaining in ASCII order. This two-stage convention is intentional, can create a one-cent difference between otherwise similar deliveries, and conserves every pool. No rounded unit landed price is multiplied back into quantity. Exact intermediate products use BigInt; exported cents are safe integers. Display-only percentages are rounded to one decimal; zero revenue has no margin percentage.
Inbound charges are amounts you supply; customs, duty and tax are never estimated. FX, outbound costs, tax treatment, discounts, returns, partial-case constraints, reservations, substitution, multi-warehouse transfers and stock consumed outside this worksheet are outside the model. All lots and orders form one static planning horizon.
Schema, bounds and zero cases
Root schema: {version:1, basis:"weight"|"value", lots:[], orders:[], inboundCosts:[]}. Empty lists are valid. IDs and SKUs are 1..32 ASCII letters, digits, underscores or hyphens, starting with a letter or digit; IDs must be unique within their list. Labels and customers are nonblank text up to 80 characters, source references up to 160. Control characters and unpaired surrogates are rejected. Unknown fields are rejected at every record level. Duplicate fields, including a JSON escape of the same name, are rejected before parsing. Nesting deeper than 16 levels is rejected. Numbers must be JSON integers, so numeric strings and fractional cents are rejected.
Every lot requires id, sku, quantity, unitWeightGrams, purchaseCents, availableOn, expiresOn, quarantined, source. Quantity: 0..1,000. Unit grams: 0..1,000,000. Purchase cents (for the whole lot): 0..100,000,000. Quarantined must be true or false. Real dates must be YYYY-MM-DD in 2000..2100, with availability no later than expiry.
Every order requires id, customer, sku, quantity, shipOn, minShelfDays, priority, unitPriceCents, source. Quantity: 0..1,000; shelf days: 0..3,660; priority: 1..9; unit price cents: 0..100,000,000. Every inbound charge requires id, label, cents, source, with cents 0..100,000,000. Limits: 12 lots, 12 orders, 6 charges, 144 possible lot/order edges and 12,000 total units. Editor limits are 24,000 characters each for lots and orders, 8,000 for charges.
A zero quantity is an explicit inactive record. Negative prices, negative charges, negative zero, non-finite or unsafe integers and malformed dates fail closed. A zero denominator or a failed rule is reported as it is, with nothing substituted.
Evidence, export and implementation
Source of truth: the editable records above. Source labels point back to those records and are taken as typed. Every excluded pair lists all failed rules. Unfilled orders show eligible capacity and which other orders consumed it; they explain this solution, and another optimal solution could be explained differently. The global residual cut is the capacity certificate.
The engine and the interface are plain JavaScript, self-contained in two files. I checked the engine against hand-worked allocations, against every feasible allocation of small cases, for cent conservation and for invariance to the order of the input arrays. Those checks test the arithmetic of this model, a worksheet for one planning question.
Editing hides the last result, including the notebook. Run and download always read all current controls, including programmatic changes without an input event. Download recomputes before creating a JSON file; invalid current text writes no file, so a stale result cannot be exported. The file contains exact editor strings, parsed inputs, rank keys, abstentions and the full result. Replay it with CommerceEngine.compute(CommerceEngine.parseSnapshot(rawInput)). A short current-input check also hides silently stale displays. Textarea line endings are browser-normalized. Raw strings otherwise preserve whitespace and array ordering. Matching snapshots show consistency and carry no signature.