# Stock & ERP hand-off

Limit purchases to what you can ship, hold it during checkout, and hand every Order to your ERP.

Both are optional. Without `inventory`, stock never limits a purchase. Without
`deliverOrder`, your ERP [fetches Orders](#or-let-your-erp-fetch-orders) itself.

## Check stock

Start with `check`. It answers how many units you can supply right now:

```ts title="src/worker.ts"
export default defineCommerce({
  channels,
  offers,
  inventory: {
    check: async (references, { signal }) => {
      const stock = await erp.stock(
        references.map((r) => r.reference),
        { signal },
      );
      return stock.map((item) => ({ reference: item.sku, available: item.quantity }));
    },
  },
});
```

OrbCart calls `check` for the binding Quote (with a reservation, `reserve` answers
instead, [see below](#reserve-stock-during-checkout)). A reference you do not name is
unlimited, like an e-book. The buyer sees the result in `cart.changes`:

| Stock  | What the buyer sees                                           |
| ------ | ------------------------------------------------------------- |
| Enough | Nothing. The Quote takes the full quantity.                   |
| Some   | `quantity_changed` from 3 to 2. The Quote takes 2.            |
| None   | `unavailable` with reason `sold_out`. The Line is not quoted. |

## Reserve stock during checkout

`check` alone can sell the last unit twice when two buyers pay at the same moment.
Add `reserve`, `release`, `commit` and `restock` to hold stock from Quote to Order
and take it back when it returns. The four come together:

```ts members="CommerceConfig"
inventory: {
  check: (references) => erp.stock(references),
  reserve: (hold) => erp.reserve(hold),
  release: (holdId) => erp.release(holdId),
  commit: (holdId, orderId) => erp.commit(holdId, orderId),
  restock: (restock) => erp.restock(restock),
},
```

| Function  | When OrbCart calls it                                                             | Your job                                                            |
| --------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| `reserve` | A Quote is created.                                                               | Hold `hold.references` until `hold.expiresAt`.                      |
| `release` | The hold runs out without an Order, or support cancels the Order before `commit`. | Free the hold. A second call must do no harm.                       |
| `commit`  | The Order is placed.                                                              | Turn the hold into a booking for `orderId`.                         |
| `restock` | Support cancels booked units, or takes returned units back into stock.            | Add `restock.references` back to your count, once per `restock.id`. |

Each hold has its own `hold.id`. OrbCart may call again with the same ID after a
timeout. Reserving the same ID twice must hold stock once. A later `expiresAt`
extends the hold.

A restock has its own `restock.id`, one per cancellation or return of the Order.
Units your `commit` could not book are never given back. A second call with the same
ID must add nothing.

While stock is held, `quote.hold.expiresAt` is set. Use it for a countdown if you like.

## Hand Orders to your ERP

`deliverOrder` receives every new Order, after the buyer has paid:

```ts members="CommerceConfig"
deliverOrder: async (order, { signal }) => {
  const salesOrder = await erp.createSalesOrder(order, { signal });
  return { reference: salesOrder.number };
},
```

- **Called at least once.** Until your ERP answers, OrbCart retries, from every second up to every hour. An ERP that is down for an hour gets the Order when it is back.
- **Deduplicate by `order.id`.** It is always the same for one Order. This is your only duty.
- **Return your own number** as `reference`. It appears on the Order's hand-off.

The budget is 30 seconds per attempt. The buyer never waits for it: they see
their confirmation as soon as the payment is through. The recipe
[Send paid Orders to your ERP](/docs/integrate/erp-order-handoff) maps an Order to a sales order and
reports shipments back.

### What's in the Order

Everything your ERP needs, frozen at the moment the buyer agreed:

```ts
order.number; // "NG-2026-004711"
order.contact.email; // the buyer's email
order.quote.lines; // reference, quantity, configuration, offer, totals, taxes
order.quote.shipTo; // delivery address
order.quote.shipping; // the chosen method and its price
order.quote.totals; // subtotal, discount, shipping, tax, total
order.quote.extensions; // your cart extensions, such as a gift message
order.payment; // method, provider and its reference
```

## Or let your ERP fetch Orders

Some ERPs poll instead of receiving. Leave out `deliverOrder` and say so with
`fetchOrders`:

```ts
export default defineCommerce({
  channels,
  offers,
  fetchOrders: true,
});
```

Every new Order then waits as `handoff: "pending"` until you acknowledge it. Read
the waiting Orders with the [Admin SDK](/docs/integrate/orders-and-refunds) and take each once:

```ts
let page = await admin.orders.list({ handoff: ["pending"] });

while (true) {
  for (const summary of page.data) {
    const order = await admin.orders.get(summary.id);
    if (order.handoff === "delivered") continue; // taken, the list is just behind

    const salesOrder = await erp.createSalesOrder(order); // keyed by order.id
    await admin.orders.acknowledge(order.id, { reference: salesOrder.number });
  }
  if (!page.next) break;
  page = await admin.orders.list({ handoff: ["pending"], after: page.next });
}
```

- **The list is a fast index, seconds behind.** An Order you just acknowledged may still be listed on the next poll, and a brand-new one may not be listed yet. `get()` is always current, so check `handoff` there. Poll again later for what is not listed yet.
- **Deduplicate by `order.id`** in your ERP, as with `deliverOrder`. If you crash between `createSalesOrder` and `acknowledge`, the next poll takes the Order again and must find the sales order it already made.
- **Acknowledging twice changes nothing.** The first `reference` stays.
- **A waiting Order is not a failure.** Unlike `deliverOrder`, which raises `handoff_failed` after 30 minutes, a fetching ERP may wait as long as it likes. Filter with `handoff: ["pending"]` to see the queue.

## Report shipments back

When your ERP ships units, record them with
[`admin.orders.fulfill()`](/docs/integrate/orders-and-refunds#report-shipments).

[Choose where tax comes from →](/docs/integrate/tax)