# Run your own actions on an Order

Give your support team a parcel label, a resent confirmation or a handoff to a branch in the Order's menu, with your code doing the work and the outcome in the Order's history.

Your support person opens an Order, picks **Parcel label** from its menu, and opens the label in a
new tab. Your code made it with your carrier, exactly once, even when the carrier answered too late.
The Order's timeline says who made it and when, with the parcel number. Ship, Cancel, Take back and
Refund stay OrbCart's own; an action is what your business adds beside them.

**You need** a commerce Worker and a carrier client. Below, `carrier` stands for it, as `erp` does in
[Send paid Orders to your ERP](/docs/integrate/erp-order-handoff).

## 1. Say when the Order offers it

An action has an id, a label and `offered`, which answers from the Order alone whether the action
makes sense now. A label makes sense while units still wait to ship:

```ts title="src/parcel-label.ts"
import type { OrderAction } from "@orbcart/runtime";
import { makeLabel } from "./make-label";

export const parcelLabel: OrderAction = {
  label: "Parcel label",
  offered: (order) => order.units.some((unit) => unit.open > 0),
  run: makeLabel,
};
```

OrbCart asks `offered` every time someone on your team opens the Order, so it calls nothing and
answers at once. The admin lists the actions the Order offers in its menu; a run of one it does not
offer is refused on the server, whatever the screen showed.

## 2. Make the label with the run's key

`run` gets the Order and a context with the action's id as `action`, the run's `key`, the person's
ID as `by` and a `signal` for the time budget, ten seconds by default:

```ts title="src/make-label.ts"
import type { OrderActionContract } from "@orbcart/runtime";

export const makeLabel: OrderActionContract = async (order, { key, signal }) => {
  const label = await carrier.createLabel(
    { reference: order.number, shipTo: order.quote.shipTo }, // reference such as NG-2026-004711
    // The same key makes the same label, however often it arrives.
    { idempotencyKey: key, signal },
  );
  if (label.status === "address_rejected") {
    return {
      outcome: "refused",
      reason:
        "The carrier does not know this address. Correct it with the customer, then make the label again.",
    };
  }

  return { outcome: "done", open: label.pdf, reference: label.parcelNumber };
};
```

- **`done`** stands in the timeline with the `reference`, here the parcel number, and `open` is
  offered to the person who ran it, to open in a new tab.
- **`refused`** changes nothing. The admin shows your `reason` as it is, so write what to fix next.
- Anything else, a throw, a spent budget or an answer that breaks the contract, stands as
  **unknown**: the carrier may have made the label, and nobody can tell.

Making one result per key is your one duty. The person resolves an unknown run with **Try again**,
which sends the same key, and OrbCart calls your code again with it, however long after. A carrier
that keeps the key hands back the label it made the first time; one that ignores it prints a second
label for one parcel. A carrier's idempotency window is often only a day, while Try again stays on
offer until someone uses it, so keep each key with its label in your own system and look it up
before you ask the carrier.

Within one key, OrbCart calls your code once an answer stood: a lost answer's resend gets the Order
as it is. While a run waits for your code, the Order does not offer the action again and refuses a
second run of it with another key, so two people cannot make two labels at once.

## Ask first for what the run needs

A label needs the product, the weight and whether the goods are bulky; a confirmation letter needs
the ERP's order number and a delivery date. Declare them as `input`, and the admin asks for them in
a dialog before it runs the action, in the language the person works in:

```ts title="src/parcel-label.ts"
import type { OrderAction } from "@orbcart/runtime";
import { makeLabel } from "./make-label";

export const parcelLabel: OrderAction = {
  label: "Parcel label",
  input: {
    product: {
      kind: "choice",
      label: { en: "Product", de: "Produkt" },
      required: true,
      choices: [
        { value: "paket", label: { en: "Parcel", de: "Paket" } },
        { value: "kleinpaket", label: { en: "Small parcel", de: "Kleinpaket" } },
      ],
    },
    weight: {
      kind: "number",
      label: { en: "Weight", de: "Gewicht" },
      unit: "kg",
      required: true,
      // Read from the Order when it is opened, and offered pre-filled.
      default: (order) => order.units.reduce((sum, unit) => sum + unit.open, 0) * 1.5,
    },
    bulky: { kind: "yesNo", label: { en: "Bulky goods", de: "Sperrgut" } },
  },
  offered: (order) => order.units.some((unit) => unit.open > 0),
  run: makeLabel,
};
```

The fields come in the order you list them, each under its `id`. A field is one of six kinds:

| `kind`     | The person…                                  | `run` gets                            |
| ---------- | -------------------------------------------- | ------------------------------------- |
| `text`     | types a line (`maxLength`)                   | a string                              |
| `number`   | types a figure, shown with its `unit`        | a number (`min`, `max`)               |
| `date`     | picks a day                                  | `"2026-11-14"`                        |
| `dateTime` | picks a day and a time                       | `"2026-11-14T14:30"`, your local time |
| `choice`   | picks one of `choices`, each with its labels | the choice's `value`                  |
| `yesNo`    | switches it on or off                        | `true` or `false`, always given       |

Every `label` is a text per language, by tag such as `en` and `de`; the admin shows its own
language's text, else English. Text, number, date, time and choice are `required: true` or left
out when empty. A `default` is a function of the Order, so it is read when the Order is. Keep
the fields to what the action cannot know itself: at most 20.

`run` gets what was entered as `input`, already checked on the server against your declaration,
so a missing required value, a wrong kind of value or a field you never declared never reaches your
code:

```ts title="src/make-label.ts"
import type { OrderActionContract } from "@orbcart/runtime";

export const makeLabel: OrderActionContract = async (order, { key, input, signal }) => {
  const label = await carrier.createLabel(
    {
      reference: order.number,
      shipTo: order.quote.shipTo,
      product: input["product"],
      weightKg: input["weight"],
      bulky: input["bulky"],
    },
    { idempotencyKey: key, signal },
  );
  if (label.status === "address_rejected") {
    return { outcome: "refused", reason: "The carrier does not know this address." };
  }

  return { outcome: "done", open: label.pdf, reference: label.parcelNumber };
};
```

The key covers the values. Try again sends the same key with the same values, which the Order's
history keeps, so your code makes nothing twice; the same key with other values is refused as a
conflict and never runs. Called over the API, the values are the `input` of the body of
`POST /v1/orders/:order/actions/:action`, and a field the server refuses is named by its pointer
in `errors`, such as `#/body/input/weight` with `required`, `too_small` or `invalid_type`. An
action attached with `http()` receives them as `context.input`.

## 3. Attach it

Actions sit beside the channels, in the order the menu shows them:

```ts title="src/worker.ts"
import { defineCommerce } from "@orbcart/runtime";
import { parcelLabel } from "./parcel-label";

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

export default defineCommerce({ channels, offers, orderActions: { parcelLabel } });
```

Does the label come from your middleware? Attach `run` remotely and keep `offered` in the Worker,
since it answers on every read:

```ts title="src/order-actions.ts"
import { http } from "@orbcart/runtime";
import { parcelLabel } from "./parcel-label";

export const orderActions = {
  parcelLabel: {
    label: "Parcel label",
    offered: parcelLabel.offered,
    run: http("https://middleware.example/labels", { timeoutMs: 20_000 }),
  },
};
```

The call carries the Order and the context as JSON, with the action's id as `context.action`, so one
endpoint can serve several actions, and the key as its `Idempotency-Key` header. Check each call with
`verifyRequest()` ([Contracts in another system](/docs/integrate/remote-contracts)).

## What the support person sees

- **Parcel label in the Order's menu,** after Take back and Cancel, while units are open, for
  everyone with Orders edit. Orders view reads what each run came to and runs none.
- **A dialog with your fields,** when the action declares `input`: your labels in their language,
  your defaults filled in, and the run goes out when they confirm. An action without `input` runs
  at once.
- **Open, for the label,** in the toast and in the timeline, beside the parcel number and their
  name.
- **Your reason,** when your code refused, with nothing else changed.
- **Got no answer, with Try again,** when the carrier was too slow. Try again settles the same run,
  and Open offers the label made the first time.

## Next

- [Orders & refunds](/docs/integrate/orders-and-refunds): refunds by Line, partial shipments and the Order list.
- [Order events](/docs/integrate/order-events): an action tells no event; the history keeps it.