AlgoViz

Design an inventory management system

medium 80 min

Count goods in several places, promise them to orders without ever promising too much, ship or let go, and explain every count.

Watch lesson4:28

Inventory with reservations

Read it, run it, change a line and run it again.

Loading editor…

Python, C++ and TypeScript were run. The Java version is the same design for Java 17 or later.

The same in Java
import java.util.*;import java.util.concurrent.locks.ReentrantLock;import java.util.function.LongSupplier;class OutOfStock extends RuntimeException {    OutOfStock(String message) { super(message); }}class NotHeld extends RuntimeException {    NotHeld(String message) { super(message); }}enum Kind { RECEIVED, SHIPPED, COUNTED }enum Status { HELD, SHIPPED, RELEASED, EXPIRED }record Movement(int seq, Kind kind, String sku, String place, int change, String ref) {}record Pick(String sku, String place, int qty) {}record LineKey(String sku, String place) {}final class Reservation {    final int id;    final String orderId;    final List<Pick> picks;    final long expiresAt;    private Status status = Status.HELD;    Reservation(int id, String orderId, List<Pick> picks, long expiresAt) {        this.id = id;        this.orderId = orderId;        this.picks = List.copyOf(picks);        this.expiresAt = expiresAt;    }    Status status() { return status; }    void finish(Status next) { status = next; }   // only Inventory calls it, under its lock}final class StockLine {    final String sku;    final String place;    private final int lowAt;    private int onHand;    private int held;    private boolean warned;    StockLine(String sku, String place, int lowAt) {        this.sku = sku;        this.place = place;        this.lowAt = lowAt;    }    int available() { return onHand - held; }    void add(int qty) {        if (qty <= 0) throw new IllegalArgumentException("a delivery has at least one piece");        onHand = Math.addExact(onHand, qty);    }    void hold(int qty) {        if (qty <= 0 || qty > available()) throw new OutOfStock(sku + " in " + place);        held += qty;    }    void letGo(int qty) {        if (qty <= 0 || qty > held) throw new IllegalStateException("cannot let go of more than is held");        held -= qty;    }    void take(int qty) {        letGo(qty);        onHand -= qty;    }    boolean becameLow() {        boolean low = available() <= lowAt;        boolean news = low && !warned;        warned = low;        return news;    }}interface PickPolicy {    Optional<List<Pick>> plan(int qty, List<StockLine> lines);    static Optional<List<Pick>> fill(int qty, List<StockLine> lines) {        List<Pick> picks = new ArrayList<>();        for (StockLine line : lines) {            int part = Math.min(qty, line.available());            if (part > 0) {                picks.add(new Pick(line.sku, line.place, part));                qty -= part;            }            if (qty == 0) return Optional.of(picks);        }        return Optional.empty();    }}final class FewestParcels implements PickPolicy {    private static final Comparator<StockLine> SMALLEST =        Comparator.comparingInt(StockLine::available).thenComparing(x -> x.place);    private static final Comparator<StockLine> LARGEST =        Comparator.comparingInt((StockLine x) -> -x.available()).thenComparing(x -> x.place);    public Optional<List<Pick>> plan(int qty, List<StockLine> lines) {        Optional<StockLine> enough = lines.stream().filter(x -> x.available() >= qty).min(SMALLEST);        if (enough.isPresent()) return PickPolicy.fill(qty, List.of(enough.get()));        return PickPolicy.fill(qty, lines.stream().sorted(LARGEST).toList());    }}final class InOrder implements PickPolicy {    private final List<String> places;    InOrder(List<String> places) { this.places = List.copyOf(places); }    private int rank(StockLine line) {        int i = places.indexOf(line.place);        return i < 0 ? places.size() : i;    }    public Optional<List<Pick>> plan(int qty, List<StockLine> lines) {        Comparator<StockLine> order = Comparator.comparingInt(this::rank);        return PickPolicy.fill(qty, lines.stream().sorted(order.thenComparing(x -> x.place)).toList());    }}interface LowStock {    void low(String sku, String place, int left);}final class Inventory {    private final PickPolicy policy;    private final LongSupplier now;    private final LowStock onLow;    private final Map<LineKey, StockLine> lines = new LinkedHashMap<>();    private final Map<Integer, Reservation> reservations = new HashMap<>();    private final List<Movement> movements = new ArrayList<>();    private final ReentrantLock lock = new ReentrantLock();    private int nextId = 1;    Inventory(PickPolicy policy, LongSupplier now, LowStock onLow) {        this.policy = policy;        this.now = now;        this.onLow = onLow;    }    void addLine(String sku, String place, int lowAt) {        lock.lock();        try {            StockLine old = lines.putIfAbsent(new LineKey(sku, place), new StockLine(sku, place, lowAt));            if (old != null) throw new IllegalArgumentException("this product is already kept in this place");        } finally {            lock.unlock();        }    }    void receive(String sku, String place, int qty, String ref) {        lock.lock();        try {            StockLine line = line(sku, place);            line.add(qty);            write(Kind.RECEIVED, line, qty, ref);            line.becameLow();        } finally {            lock.unlock();        }    }    int available(String sku) {        lock.lock();        try {            return linesOf(sku).stream().mapToInt(StockLine::available).sum();        } finally {            lock.unlock();        }    }    private StockLine line(String sku, String place) {        StockLine line = lines.get(new LineKey(sku, place));        if (line == null) throw new NoSuchElementException(sku + " is not kept in " + place);        return line;    }    private List<StockLine> linesOf(String sku) {        return lines.values().stream().filter(x -> x.sku.equals(sku)).toList();    }    private void write(Kind kind, StockLine line, int change, String ref) {        movements.add(new Movement(movements.size() + 1, kind, line.sku, line.place, change, ref));    }    Reservation reserve(String orderId, Map<String, Integer> wanted, long seconds) {        if (wanted.isEmpty() || wanted.values().stream().anyMatch(q -> q <= 0)) {            throw new IllegalArgumentException("ask for at least one piece of something");        }        Reservation res;        List<Runnable> news = new ArrayList<>();        lock.lock();        try {            List<Pick> picks = new ArrayList<>();            for (var want : wanted.entrySet()) {                picks.addAll(policy.plan(want.getValue(), linesOf(want.getKey()))                    .orElseThrow(() -> new OutOfStock(want.getKey())));            }            for (Pick p : picks) line(p.sku(), p.place()).hold(p.qty());            res = new Reservation(nextId++, orderId, picks, now.getAsLong() + seconds);            reservations.put(res.id, res);            for (Pick p : picks) {                StockLine line = line(p.sku(), p.place());                if (line.becameLow()) {                    int left = line.available();                    news.add(() -> onLow.low(line.sku, line.place, left));                }            }        } finally {            lock.unlock();        }        news.forEach(Runnable::run);   // outside the lock        return res;    }    Reservation ship(int reservationId) {        lock.lock();        try {            Reservation res = held(reservationId);            for (Pick p : res.picks) {                StockLine line = line(p.sku(), p.place());                line.take(p.qty());                write(Kind.SHIPPED, line, -p.qty(), res.orderId);            }            res.finish(Status.SHIPPED);            return res;        } finally {            lock.unlock();        }    }    void release(int reservationId) {        lock.lock();        try {            giveBack(held(reservationId), Status.RELEASED);        } finally {            lock.unlock();        }    }    int expireDue() {        lock.lock();        try {            long at = now.getAsLong();            List<Reservation> due = reservations.values().stream()                .filter(r -> r.status() == Status.HELD && r.expiresAt <= at).toList();            due.forEach(r -> giveBack(r, Status.EXPIRED));            return due.size();        } finally {            lock.unlock();        }    }    private Reservation held(int id) {        Reservation res = reservations.get(id);        if (res == null || res.status() != Status.HELD) throw new NotHeld("reservation " + id);        if (res.expiresAt <= now.getAsLong()) {            giveBack(res, Status.EXPIRED);            throw new NotHeld("reservation " + id + " has expired");        }        return res;    }    private void giveBack(Reservation res, Status status) {        for (Pick p : res.picks) {            StockLine line = line(p.sku(), p.place());            line.letGo(p.qty());            line.becameLow();        }        res.finish(status);    }}public class Main {    static long time = 0;    public static void main(String[] args) {        List<String> alerts = new ArrayList<>();        Inventory shop = new Inventory(new FewestParcels(), () -> time,            (sku, place, left) -> alerts.add(sku + " " + place + " " + left));        shop.addLine("plum", "cellar", 2);        shop.receive("plum", "cellar", 6, "first delivery");        shop.addLine("plum", "shed", 1);        shop.receive("plum", "shed", 3, "first delivery");        shop.addLine("fig", "cellar", 1);        shop.receive("fig", "cellar", 4, "first delivery");        Reservation a = shop.reserve("order-a", Map.of("plum", 2, "fig", 1), 900);        System.out.println(a.picks + " " + shop.available("plum") + " " + shop.available("fig") + " " + alerts);        try {            shop.reserve("order-b", Map.of("fig", 1, "plum", 9), 900);        } catch (OutOfStock err) {            System.out.println("refused " + err.getMessage() + ", fig is still " + shop.available("fig"));        }        shop.ship(a.id);        Reservation c = shop.reserve("order-c", Map.of("plum", 5), 900);        time = 1000;        System.out.println(shop.expireDue() + " " + shop.available("plum"));        try {            shop.ship(c.id);        } catch (NotHeld err) {            System.out.println("too late: " + err.getMessage());        }    }}
The same in C++
#include <algorithm>#include <functional>#include <iostream>#include <map>#include <memory>#include <mutex>#include <optional>#include <stdexcept>#include <string>#include <tuple>#include <utility>#include <vector>struct OutOfStock : std::runtime_error { using runtime_error::runtime_error; };struct NotHeld : std::runtime_error { using runtime_error::runtime_error; };enum class Kind { received, shipped, counted };enum class Status { held, shipped, released, expired };struct Movement { int seq; Kind kind; std::string sku, place; int change; std::string ref; };struct Pick { std::string sku, place; int qty; };struct Reservation {    int id;    std::string order_id;    std::vector<Pick> picks;    long expires_at;    Status status = Status::held;};class StockLine {    int low_at_;    int on_hand_ = 0;    int held_ = 0;    bool warned_ = false;public:    const std::string sku, place;    StockLine(std::string s, std::string p, int low_at) : low_at_(low_at), sku(std::move(s)), place(std::move(p)) {}    int available() const { return on_hand_ - held_; }    void add(int qty) {        if (qty <= 0) throw std::invalid_argument("a delivery has at least one piece");        on_hand_ += qty;    }    void hold(int qty) {        if (qty <= 0 || qty > available()) throw OutOfStock(sku + " in " + place);        held_ += qty;    }    void let_go(int qty) {        if (qty <= 0 || qty > held_) throw std::logic_error("cannot let go of more than is held");        held_ -= qty;    }    void take(int qty) {        let_go(qty);        on_hand_ -= qty;    }    bool became_low() {        const bool low = available() <= low_at_;        const bool news = low && !warned_;        warned_ = low;        return news;    }};using Lines = std::vector<const StockLine*>;   // borrowed: the inventory owns themusing Plan = std::optional<std::vector<Pick>>;struct PickPolicy {    virtual ~PickPolicy() = default;    virtual Plan plan(int qty, Lines lines) const = 0;};Plan fill(int qty, const Lines& lines) {    std::vector<Pick> picks;    for (const auto* line : lines) {        const int part = std::min(qty, line->available());        if (part > 0) {            picks.push_back({line->sku, line->place, part});            qty -= part;        }        if (qty == 0) return picks;    }    return std::nullopt;}struct FewestParcels : PickPolicy {    Plan plan(int qty, Lines lines) const override {        Lines enough;        for (const auto* x : lines) if (x->available() >= qty) enough.push_back(x);        if (!enough.empty()) {            const auto best = std::min_element(enough.begin(), enough.end(), [](auto* a, auto* b) {                return std::forward_as_tuple(a->available(), a->place) < std::forward_as_tuple(b->available(), b->place);            });            return fill(qty, {*best});        }        std::sort(lines.begin(), lines.end(), [](auto* a, auto* b) {            return std::forward_as_tuple(-a->available(), a->place) < std::forward_as_tuple(-b->available(), b->place);        });        return fill(qty, lines);    }};struct InOrder : PickPolicy {    std::vector<std::string> places;    explicit InOrder(std::vector<std::string> p) : places(std::move(p)) {}    Plan plan(int qty, Lines lines) const override {        const auto rank = [&](auto* x) { return std::find(places.begin(), places.end(), x->place) - places.begin(); };        std::sort(lines.begin(), lines.end(), [&](auto* a, auto* b) {            return std::forward_as_tuple(rank(a), a->place) < std::forward_as_tuple(rank(b), b->place);        });        return fill(qty, lines);    }};using LowStock = std::function<void(const std::string&, const std::string&, int)>;class Inventory {    std::unique_ptr<PickPolicy> policy_;    std::function<long()> now_;    LowStock on_low_;    std::map<std::pair<std::string, std::string>, StockLine> lines_;    std::map<int, Reservation> reservations_;    std::vector<Movement> movements_;    int next_id_ = 1;    mutable std::mutex mutex_;    StockLine& line(const std::string& sku, const std::string& place) { return lines_.at({sku, place}); }    Lines lines_of(const std::string& sku) const {        Lines out;        for (const auto& [key, x] : lines_) if (key.first == sku) out.push_back(&x);        return out;    }    void write(Kind kind, const StockLine& x, int change, const std::string& ref) {        movements_.push_back({static_cast<int>(movements_.size()) + 1, kind, x.sku, x.place, change, ref});    }public:    Inventory(std::unique_ptr<PickPolicy> policy, std::function<long()> now, LowStock on_low)        : policy_(std::move(policy)), now_(std::move(now)), on_low_(std::move(on_low)) {}    void add_line(const std::string& sku, const std::string& place, int low_at = 0) {        std::lock_guard lock(mutex_);        if (!lines_.try_emplace({sku, place}, sku, place, low_at).second)            throw std::invalid_argument("this product is already kept in this place");    }    void receive(const std::string& sku, const std::string& place, int qty, const std::string& ref) {        std::lock_guard lock(mutex_);        auto& x = line(sku, place);        x.add(qty);        write(Kind::received, x, qty, ref);        x.became_low();    }    int available(const std::string& sku) const {        std::lock_guard lock(mutex_);        int sum = 0;        for (const auto* x : lines_of(sku)) sum += x->available();        return sum;    }    Reservation reserve(const std::string& order_id, const std::map<std::string, int>& wanted, long seconds) {        if (wanted.empty() || std::any_of(wanted.begin(), wanted.end(), [](const auto& w) { return w.second <= 0; }))            throw std::invalid_argument("ask for at least one piece of something");        std::vector<std::tuple<std::string, std::string, int>> news;        Reservation res;        {            std::lock_guard lock(mutex_);            std::vector<Pick> picks;            for (const auto& [sku, qty] : wanted) {                const auto plan = policy_->plan(qty, lines_of(sku));                if (!plan) throw OutOfStock(sku);                picks.insert(picks.end(), plan->begin(), plan->end());            }            for (const auto& p : picks) line(p.sku, p.place).hold(p.qty);            res = {next_id_++, order_id, picks, now_() + seconds, Status::held};            reservations_.emplace(res.id, res);            for (const auto& p : picks) {                auto& x = line(p.sku, p.place);                if (x.became_low()) news.emplace_back(x.sku, x.place, x.available());            }        }        for (const auto& [sku, place, left] : news) on_low_(sku, place, left);   // outside the lock        return res;    }    Reservation ship(int reservation_id) {        std::lock_guard lock(mutex_);        auto& res = held(reservation_id);        for (const auto& p : res.picks) {            auto& x = line(p.sku, p.place);            x.take(p.qty);            write(Kind::shipped, x, -p.qty, res.order_id);        }        res.status = Status::shipped;        return res;    }    void release(int reservation_id) {        std::lock_guard lock(mutex_);        give_back(held(reservation_id), Status::released);    }    int expire_due() {        std::lock_guard lock(mutex_);        int count = 0;        for (auto& [id, res] : reservations_) {            if (res.status != Status::held || res.expires_at > now_()) continue;            give_back(res, Status::expired);            ++count;        }        return count;    }private:    Reservation& held(int id) {        const auto it = reservations_.find(id);        if (it == reservations_.end() || it->second.status != Status::held)            throw NotHeld("reservation " + std::to_string(id));        if (it->second.expires_at <= now_()) {            give_back(it->second, Status::expired);            throw NotHeld("reservation " + std::to_string(id) + " has expired");        }        return it->second;    }    void give_back(Reservation& res, Status status) {        for (const auto& p : res.picks) {            auto& x = line(p.sku, p.place);            x.let_go(p.qty);            x.became_low();        }        res.status = status;    }};int main() {    long time = 0;    Inventory shop(std::make_unique<FewestParcels>(), [&] { return time; },                   [](const std::string& sku, const std::string& place, int left) { std::cout << "low: " << sku << ' ' << place << ' ' << left << '\n'; });    shop.add_line("plum", "cellar", 2);    shop.receive("plum", "cellar", 6, "first delivery");    shop.add_line("plum", "shed", 1);    shop.receive("plum", "shed", 3, "first delivery");    shop.add_line("fig", "cellar", 1);    shop.receive("fig", "cellar", 4, "first delivery");    const auto a = shop.reserve("order-a", {{"plum", 2}, {"fig", 1}}, 900);    for (const auto& p : a.picks) std::cout << p.sku << ' ' << p.place << ' ' << p.qty << '\n';    try {        shop.reserve("order-b", {{"fig", 1}, {"plum", 9}}, 900);    } catch (const OutOfStock& err) {        std::cout << "refused " << err.what() << ", fig is still " << shop.available("fig") << '\n';    }    shop.ship(a.id);    const auto c = shop.reserve("order-c", {{"plum", 5}}, 900);    time = 1000;    std::cout << shop.expire_due() << ' ' << shop.available("plum") << '\n';    try {        shop.ship(c.id);    } catch (const NotHeld& err) {        std::cout << "too late: " << err.what() << '\n';    }}
The same in TypeScript
export class OutOfStock extends Error {}export class NotHeld extends Error {}export type Kind = "received" | "shipped" | "counted";export type Status = "held" | "shipped" | "released" | "expired";export interface Movement {  readonly seq: number;  readonly kind: Kind;  readonly sku: string;  readonly place: string;  readonly change: number;  readonly ref: string;}export interface Pick {  readonly sku: string;  readonly place: string;  readonly qty: number;}export interface Reservation {  readonly id: number;  readonly orderId: string;  readonly picks: readonly Pick[];  readonly expiresAt: number;  status: Status;}export class StockLine {  private onHandQty = 0;  private heldQty = 0;  private warned = false;  constructor(readonly sku: string, readonly place: string, readonly lowAt = 0) {}  get onHand(): number { return this.onHandQty; }  get available(): number { return this.onHandQty - this.heldQty; }  add(qty: number): void {    if (!Number.isInteger(qty) || qty <= 0) throw new RangeError("a delivery has at least one piece");    this.onHandQty += qty;  }  hold(qty: number): void {    if (!(qty > 0 && qty <= this.available)) throw new OutOfStock(`${this.sku} in ${this.place}`);    this.heldQty += qty;  }  letGo(qty: number): void {    if (!(qty > 0 && qty <= this.heldQty)) throw new RangeError("cannot let go of more than is held");    this.heldQty -= qty;  }  take(qty: number): void {    this.letGo(qty);    this.onHandQty -= qty;  }  becameLow(): boolean {    const low = this.available <= this.lowAt;    const news = low && !this.warned;    this.warned = low;    return news;  }}export interface PickPolicy {  plan(qty: number, lines: readonly StockLine[]): Pick[] | null;}function fill(qty: number, lines: readonly StockLine[]): Pick[] | null {  const picks: Pick[] = [];  for (const line of lines) {    const part = Math.min(qty, line.available);    if (part > 0) {      picks.push({ sku: line.sku, place: line.place, qty: part });      qty -= part;    }    if (qty === 0) return picks;  }  return null;}const byPlace = (a: StockLine, b: StockLine) => (a.place < b.place ? -1 : a.place > b.place ? 1 : 0);export class FewestParcels implements PickPolicy {  plan(qty: number, lines: readonly StockLine[]): Pick[] | null {    const enough = lines.filter((x) => x.available >= qty).sort((a, b) => a.available - b.available || byPlace(a, b));    if (enough.length > 0) return fill(qty, enough.slice(0, 1));    return fill(qty, [...lines].sort((a, b) => b.available - a.available || byPlace(a, b)));  }}export class InOrder implements PickPolicy {  constructor(private readonly places: readonly string[]) {}  plan(qty: number, lines: readonly StockLine[]): Pick[] | null {    const rank = (x: StockLine) => {      const i = this.places.indexOf(x.place);      return i < 0 ? this.places.length : i;    };    return fill(qty, [...lines].sort((a, b) => rank(a) - rank(b) || byPlace(a, b)));  }}export type LowStock = (sku: string, place: string, left: number) => void;export class Inventory {  private readonly lines = new Map<string, StockLine>();  private readonly reservations = new Map<number, Reservation>();  private readonly movements: Movement[] = [];  private nextId = 1;  constructor(    private readonly policy: PickPolicy,    private readonly now: () => number,    private readonly onLow: LowStock,  ) {}  addLine(sku: string, place: string, lowAt = 0): void {    const key = JSON.stringify([sku, place]);    if (this.lines.has(key)) throw new Error("this product is already kept in this place");    this.lines.set(key, new StockLine(sku, place, lowAt));  }  receive(sku: string, place: string, qty: number, ref: string): void {    const line = this.line(sku, place);    line.add(qty);    this.write("received", line, qty, ref);    line.becameLow();  }  available(sku: string): number {    return this.linesOf(sku).reduce((sum, x) => sum + x.available, 0);  }  private line(sku: string, place: string): StockLine {    const line = this.lines.get(JSON.stringify([sku, place]));    if (!line) throw new Error(`${sku} is not kept in ${place}`);    return line;  }  private linesOf(sku: string): StockLine[] {    return [...this.lines.values()].filter((x) => x.sku === sku);  }  private write(kind: Kind, line: StockLine, change: number, ref: string): void {    this.movements.push({ seq: this.movements.length + 1, kind, sku: line.sku, place: line.place, change, ref });  }  reserve(orderId: string, wanted: ReadonlyMap<string, number>, seconds: number): Reservation {    if (wanted.size === 0 || [...wanted.values()].some((q) => !Number.isInteger(q) || q <= 0)) {      throw new RangeError("ask for at least one piece of something");    }    // One thread and no await: the plan and the hold cannot be separated.    const picks: Pick[] = [];    for (const [sku, qty] of wanted) {      const plan = this.policy.plan(qty, this.linesOf(sku));      if (!plan) throw new OutOfStock(sku);      picks.push(...plan);    }    for (const p of picks) this.line(p.sku, p.place).hold(p.qty);    const res: Reservation = { id: this.nextId++, orderId, picks, expiresAt: this.now() + seconds, status: "held" };    this.reservations.set(res.id, res);    for (const p of picks) {      const line = this.line(p.sku, p.place);      if (line.becameLow()) this.onLow(line.sku, line.place, line.available);    }    return res;  }  ship(reservationId: number): Reservation {    const res = this.held(reservationId);    for (const p of res.picks) {      const line = this.line(p.sku, p.place);      line.take(p.qty);      this.write("shipped", line, -p.qty, res.orderId);    }    res.status = "shipped";    return res;  }  release(reservationId: number): void {    this.giveBack(this.held(reservationId), "released");  }  expireDue(): number {    const due = [...this.reservations.values()].filter((r) => r.status === "held" && r.expiresAt <= this.now());    for (const res of due) this.giveBack(res, "expired");    return due.length;  }  private held(id: number): Reservation {    const res = this.reservations.get(id);    if (!res || res.status !== "held") throw new NotHeld(`reservation ${id}`);    if (res.expiresAt <= this.now()) {      this.giveBack(res, "expired");      throw new NotHeld(`reservation ${id} has expired`);    }    return res;  }  private giveBack(res: Reservation, status: Status): void {    for (const p of res.picks) {      const line = this.line(p.sku, p.place);      line.letGo(p.qty);      line.becameLow();    }    res.status = status;  }}let time = 0;const alerts: string[] = [];const shop = new Inventory(new FewestParcels(), () => time, (sku, place, left) => alerts.push(`${sku} ${place} ${left}`));for (const [sku, place, lowAt, qty] of [["plum", "cellar", 2, 6], ["plum", "shed", 1, 3], ["fig", "cellar", 1, 4]] as const) {  shop.addLine(sku, place, lowAt);  shop.receive(sku, place, qty, "first delivery");}const a = shop.reserve("order-a", new Map([["plum", 2], ["fig", 1]]), 900);console.log(a.picks, shop.available("plum"), shop.available("fig"), alerts);try {  shop.reserve("order-b", new Map([["fig", 1], ["plum", 9]]), 900);} catch (err) {  console.log("refused", (err as Error).message, shop.available("fig"));}shop.ship(a.id);const c = shop.reserve("order-c", new Map([["plum", 5]]), 900);time = 1000;console.log(shop.expireDue(), shop.available("plum"));try {  shop.ship(c.id);} catch (err) {  console.log("too late", (err as Error).message);}