# Prices and stock from your ERP

Answer OrbCart's offers and inventory contracts from an ERP over HTTP, with one request per call, parsed answers and a reservation that never sells the last unit twice.

You connect the ERP that already knows your articles, prices and stock. Every price a buyer sees
comes from it, a sold-out article is never sold, and the last unit is held for the buyer who is
paying. There is no catalog import and nothing to sync.

**You need** a commerce Worker from the [Configuration](/configuration) page, and an ERP with an HTTP
API for articles, stock and reservations. Store its address and token as Worker variables, such as
`wrangler secret put ERP_TOKEN`.

## 1. The ERP adapter

One file speaks to the ERP. It asks once per call for every Line together, parses what comes back
and throws when the ERP fails:

```ts title="src/erp.ts"
import { env } from "cloudflare:workers";
import type { InventoryContract, OffersContract } from "@orbcart/runtime";
import { z } from "zod";

// What the ERP answers, parsed at the border: a malformed answer fails loudly instead of selling at a wrong price.
const Article = z.object({
  sku: z.string(),
  name: z.string(),
  priceInCents: z.int().nonnegative(),
  vatClass: z.enum(["standard", "reduced"]),
  weightInGrams: z.int().nonnegative(),
  discontinued: z.boolean(),
});
const Quantity = z.object({ sku: z.string(), quantity: z.int().nonnegative() });

async function ask<T>(path: string, body: unknown, answer: z.ZodType<T>, signal: AbortSignal) {
  const response = await fetch(new URL(path, env.ERP_URL), {
    method: "POST",
    headers: { "Content-Type": "application/json", Authorization: `Bearer ${env.ERP_TOKEN}` },
    body: JSON.stringify(body),
    signal,
  });
  // Throwing tells OrbCart the ERP is unreachable. Nothing is sold at a guess.
  if (!response.ok) throw new Error(`ERP ${path} answered ${response.status}`);
  return answer.parse(await response.json());
}

const items = (references: readonly { reference: string; quantity: number }[]) =>
  references.map(({ reference, quantity }) => ({ sku: reference, quantity }));

export const offers: OffersContract = async (lines, { currency, signal }) => {
  const skus = [...new Set(lines.map((line) => line.reference))];
  const articles = await ask("/articles", { skus, currency }, z.array(Article), signal);

  return articles.map((article) =>
    article.discontinued
      ? { reference: article.sku, unavailable: "discontinued" }
      : {
          reference: article.sku,
          title: article.name,
          price: { amount: article.priceInCents, currency },
          taxCategory: article.vatClass,
          shipping: { weightInGrams: article.weightInGrams },
        },
  );
};

export const inventory: InventoryContract = {
  check: async (references, { signal }) => {
    const skus = references.map(({ reference }) => reference);
    const stock = await ask("/stock", { skus }, z.array(Quantity), signal);
    return stock.map(({ sku, quantity }) => ({ reference: sku, available: quantity }));
  },
  // Called again with the same hold.id after a timeout: the ERP must hold the stock once.
  reserve: async (hold, { signal }) => {
    const body = { id: hold.id, items: items(hold.references), until: hold.expiresAt };
    const held = await ask("/reservations", body, z.array(Quantity), signal);
    return held.map(({ sku, quantity }) => ({ reference: sku, reserved: quantity }));
  },
  release: async (holdId, { signal }) => {
    await ask(`/reservations/${holdId}/release`, {}, z.unknown(), signal);
  },
  commit: async (holdId, orderId, { signal }) => {
    const booked = await ask(
      `/reservations/${holdId}/commit`,
      { orderId },
      z.array(Quantity),
      signal,
    );
    return booked.map(({ sku, quantity }) => ({ reference: sku, committed: quantity }));
  },
};
```

Your ERP's paths and field names differ; the shape stays. Three rules carry it:

* **One request per call.** `offers` gets every Line of the Cart at once. A request per Line would
  spend the 3-second budget.
* **Unit prices in minor units.** OrbCart applies quantity, discounts and tax. `8990` is €89.90.
* **Tax categories your Channel can quote.** `eu-standard` quotes only `standard`. Selling `reduced`
  articles needs a [`tax` function](/integrations/tax#your-own-tax-function).
* **Fail honestly.** An empty answer would tell every buyer that everything is sold out. Throw instead.

## 2. Attach it

```ts title="src/worker.ts"
import { defineCommerce } from "@orbcart/runtime";
import { inventory, offers } from "./erp";

export * from "@orbcart/runtime/objects";

export default defineCommerce({ channels, offers, inventory });
```

Need more than 3 seconds? Attach `offers: { run: offers, timeoutMs: 5_000 }`
([Time budgets](/configuration#time-budgets)).

## 3. Try it

Add an article to a Cart and quote it, as in the [Quickstart](/getting-started).
The Worker log shows each call to the ERP. Then set an article's stock to 1 in the ERP and ask for 3.

## What the buyer sees

| In the ERP                            | The buyer sees                                                            |
| ------------------------------------- | ------------------------------------------------------------------------- |
| A price                               | That price, in the bag and in the Quote.                                  |
| `discontinued: true`                  | The Line as unavailable, with the reason, and no way to buy it.           |
| Stock of 1 for a quantity of 3        | The Quote takes 1 and says why (`quantity_changed`).                      |
| Stock of 0                            | The Line as sold out. The Quote leaves it out.                            |
| The last unit, held for another buyer | Sold out while that buyer's hold lasts.                                   |
| The ERP is down                       | "Our systems are not responding right now. Please try again in a moment." |

## Variations

* **Your middleware already speaks OrbCart's contract?** Attach it as `offers: http("https://…")`
  and skip the adapter: [Contracts in another system](/integrations/remote-contracts).
* **Prices and facts in two systems,** such as a pricing service beside the ERP? Ask both in
  `offers` with `Promise.all`, as Nordgrat does in `examples/nordgrat/src/offers.ts`.
* **Customer-group prices?** `offers` gets `buyer` for a [signed-in buyer](/integrations/identity#prices-per-customer-group).

## Next

* [Offers](/integrations): every field an Offer can carry, such as `image`, `compareAt` and `tags`.
* [Stock & ERP hand-off](/integrations/inventory): when OrbCart calls `check`, `reserve`, `release` and `commit`.
* [Send paid Orders to your ERP](/recipes/erp-order-handoff): the other direction.