# Bring your own screens into the admin

Give a partner's work an area of its own in the OrbCommerce Admin, show it beside the Order it came from, and start it from the Order list, without touching OrbCart's screens.

Your support team hands deliveries to a fleet partner. They open **Fleet** in the admin's sidebar
and see every fleet job. On an Order, a card in its side column shows the job made for it, and
**New fleet job** waits in the head of the Order list. All of it is a module you write: it draws
with the admin's own components, reads your own API, and is gone for anyone who may not see the
fleet.

**You need** the admin's repository, where `apps/admin/src/modules.ts` lists the installed modules,
and an API of your own for the fleet jobs. Below it is a Worker, but any server that checks the
staff token works.

A module is your own trusted code. It runs in the admin with the rights of the person signed in,
sends their staff token to your API and reads whatever that person may read. Install only code
you would deploy yourself.

The screens below use the admin's design system; its rules, and the way over from an earlier
`@orbcommerce/ui`, are in [Move your screens to the admin's design system](/docs/admin/design-system).

## 1. Give the fleet an area of its own

`ownArea("fleet")` makes the area's route. Its id is its address, `/fleet`, and its name in the
staff token. Hang the module's screens beneath it:

```ts title="src/fleet-routes.ts"
import { ownArea } from "@orbcommerce/shell";
import { createRoute, lazyRouteComponent } from "@tanstack/react-router";

const fleetArea = ownArea("fleet");
const jobsPath = createRoute({ getParentRoute: () => fleetArea, path: "jobs" });
const jobsPlace = createRoute({ getParentRoute: () => jobsPath, id: "fleet-jobs" });

export const jobListRoute = createRoute({
  getParentRoute: () => jobsPlace,
  path: "/",
  component: lazyRouteComponent(() => import("./job-list"), "JobList"),
});

export const newJobRoute = createRoute({
  getParentRoute: () => jobsPlace,
  path: "new",
  component: lazyRouteComponent(() => import("./new-job"), "NewJob"),
});

export const jobRoute = createRoute({
  getParentRoute: () => jobsPlace,
  path: "$jobId",
  component: JobPage,
});

function JobPage() {
  const { jobId } = jobRoute.useParams();
  return `Job ${jobId}`;
}

export const jobsRoute = jobsPlace.addChildren([jobListRoute, newJobRoute, jobRoute]);
export const fleetRoutes = fleetArea.addChildren([jobsPath.addChildren([jobsRoute])]);
```

The pathless `jobsPlace` is the registered place. The list, new-job and detail routes all match it,
so the shell recognizes them as part of Jobs instead of redirecting them to the first place.
Its address is `/fleet/jobs`; the list answers that address and the other screens sit beneath it.
Replace the small `JobPage` with your own detail screen.

The module brings the area, names its places for the sidebar, and says which levels your API
checks there. The owner gives them to people under _Settings › Staff_, beside the family's areas:

```ts title="src/fleet.ts"
import { defineModule } from "@orbcommerce/shell";
import { ClipboardList, Truck } from "lucide-react";
import { fleetRoutes, jobsRoute } from "./fleet-routes";

export const fleet = () =>
  defineModule({
    id: "fleet",
    areas: [
      {
        route: fleetRoutes,
        label: () => "Fleet",
        icon: Truck,
        places: [{ label: () => "Jobs", icon: ClipboardList, route: jobsRoute }],
      },
    ],
    roles: { fleet: ["view", "edit"] },
  });
```

The list reads your API through `useApi("fleet")`, which sends the person's staff token to
`/api/fleet` on the admin's own address. `Linked` opens the Order a job came from without knowing
OrbCart's screens; where OrbCart is not installed, the number stays plain text:

```tsx title="src/job-list.tsx"
import { Linked, useApi } from "@orbcommerce/shell";
import { Page, PageHeader } from "@orbcommerce/ui";
import { useSuspenseQuery } from "@tanstack/react-query";
import { fleetJobsQuery } from "./fleet-api";

export function JobList() {
  const jobs = useSuspenseQuery(fleetJobsQuery(useApi("fleet"))).data;
  return (
    <Page header={<PageHeader title="Fleet jobs" />}>
      <ul>
        {jobs.map((job) => (
          <li key={job.id}>
            {job.vehicle} ·{" "}
            <Linked kind="order" at={job.order}>
              {job.order}
            </Linked>
          </li>
        ))}
      </ul>
    </Page>
  );
}
```

The query parses what your API answers, so a screen never shows what it did not expect:

```ts title="src/fleet-api.ts"
import type { ModuleApi } from "@orbcommerce/shell";
import { queryOptions } from "@tanstack/react-query";
import { z } from "zod";

const FleetJob = z.object({ id: z.string(), order: z.string(), vehicle: z.string() });

export const fleetJobsQuery = (api: ModuleApi, order?: string) =>
  queryOptions({
    queryKey: ["fleet", "jobs", order],
    queryFn: async () => {
      const query = order === undefined ? "" : `?order=${encodeURIComponent(order)}`;
      const answer = await api.fetch(new Request(`${api.url}/jobs${query}`));
      if (!answer.ok) throw new Error(`The fleet answered ${answer.status}.`);
      return z.array(FleetJob).parse(await answer.json());
    },
  });
```

## 2. Check the staff token in your API

The admin decides only what it shows. Your API decides every request: it checks the token against
the admin's key set and the person's level in the fleet area, as every product checks its own:

```ts title="fleet-api/src/index.ts" worker
import { may, staffTokens } from "@orbcommerce/kernel";
import { jobsFor, NewJob, planJob } from "./jobs";

// The admin's address, whose key set signs the staff tokens.
const tokens = staffTokens({ issuer: "https://admin.nordgrat.example", clock: Date });

export default {
  async fetch(request) {
    const verified = await tokens.verify(request);
    if (verified.status === "unavailable") return new Response(null, { status: 503 });
    if (verified.status !== "staff") return new Response(null, { status: 401 });
    const { staff } = verified;
    const url = new URL(request.url);
    if (url.pathname !== "/jobs") return new Response(null, { status: 404 });

    if (request.method === "GET") {
      if (!may(staff, "fleet", "view")) return new Response(null, { status: 403 });
      return Response.json(await jobsFor(url.searchParams.get("order")));
    }

    if (!may(staff, "fleet", "edit")) return new Response(null, { status: 403 });
    const job = NewJob.safeParse(await request.json());
    if (!job.success) return new Response(null, { status: 400 });
    return Response.json(await planJob(job.data, staff.id), { status: 201 });
  },
} satisfies ExportedHandler;
```

The owner holds every area, the fleet among them. A token names a person by `staff.id`; keep that
with a job rather than their name, which they may change.

A person also works at some of the merchant's Locations, or at all of them: the owner assigns
them in the Staff section, and the token carries them as `staff.locations`, either `"all"` or a
list of Location ids as the catalog knows them. When your jobs belong to a Location, a person
sees only the jobs of theirs. Ask the kernel instead of comparing the list yourself:
`mayAt(staff, job.location)` is true for the Locations the person works at, and
`holdsEveryLocation(staff)` for a job that belongs to none, which only staff at every Location
(the owner among them) work. Narrow in the query, never over a page you have read, and answer a
job outside their Locations as one that does not exist, so two people with different Locations
cannot find each other's jobs. OrbCart's orders, OrbCatalog's appointments and its resources
already do.

## 3. Show the job beside its Order

OrbCart's Order page names its slots: `order.head`, `order.side`, and `orders.head` on the Order
list. Your module fills one with a component that is handed the Order's number as `at` and, as
`record`, the Order the page already read, which you narrow with the schema of `@orbcart/api/v1`
instead of reading it again. It reads your own API for the rest. The card links to the jobs in your area; it never imports OrbCart's screens:

```tsx title="src/job-card.tsx"
import { useApi } from "@orbcommerce/shell";
import type { SlotProps } from "@orbcommerce/shell";
import { Card, Row, Rows } from "@orbcommerce/ui";
import { useSuspenseQuery } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
import { fleetJobsQuery } from "./fleet-api";
import { jobsRoute } from "./fleet-routes";

export function FleetJobCard({ at }: SlotProps) {
  const jobs = useSuspenseQuery(fleetJobsQuery(useApi("fleet"), at)).data;
  if (jobs.length === 0) return null;
  return (
    <Card title="Fleet" flush>
      <Rows plain>
        {jobs.map((job) => (
          <Row key={job.id} label={job.vehicle}>
            <Link to={jobsRoute.to}>{job.id}</Link>
          </Row>
        ))}
      </Rows>
    </Card>
  );
}
```

A slot shows and links; it decides nothing. A button that changes the Order, such as booking the
pickup and marking units shipped, is an action in your OrbCart code, so OrbCart keeps the rule and
the Order's history learns of it: [Run your own actions on an Order](/docs/integrate/order-actions).

## 4. Start a job from the Order list

The button in the Order list's head opens your own screen:

```tsx title="src/new-job-button.tsx"
import { Button } from "@orbcommerce/ui";
import { Link } from "@tanstack/react-router";
import { Plus } from "lucide-react";
import { newJobRoute } from "./fleet-routes";

export function NewFleetJobButton() {
  return (
    <Button render={<Link to={newJobRoute.to} />}>
      <Plus /> New fleet job
    </Button>
  );
}
```

Both parts go into the module's `slots`. `lazySlotComponent` loads a part's code the first time it
shows, so the Order page never waits for it:

```ts title="src/fleet.ts"
import { defineModule, lazySlotComponent } from "@orbcommerce/shell";
import { ClipboardList, Truck } from "lucide-react";
import { fleetRoutes, jobsRoute } from "./fleet-routes";

export const fleet = () =>
  defineModule({
    id: "fleet",
    areas: [
      {
        route: fleetRoutes,
        label: () => "Fleet",
        icon: Truck,
        places: [{ label: () => "Jobs", icon: ClipboardList, route: jobsRoute }],
      },
    ],
    slots: {
      "order.side": { Component: lazySlotComponent(() => import("./job-card"), "FleetJobCard") },
      "orders.head": {
        Component: lazySlotComponent(() => import("./new-job-button"), "NewFleetJobButton"),
      },
    },
    roles: { fleet: ["view", "edit"] },
  });
```

A part shows only to people who may view the fleet: a module that brings one area of its own
shows its parts to that area's people. One that brings none, or several, names it per part, such
as `{ Component, area: "orders" }`. With nothing to show, the slot takes no space, and the Order
looks as it always did.

Each part stands on its own. If your card throws or its code does not load, only the card is gone:
its place says so quietly with **Retry**, and the Order and every other module's part work on. The
admin logs the failure with your module's id, never the Order's data.

## 5. Install it

Add the module to the admin's list, after the family's modules. Its area follows Search in the
sidebar, in the order of this list:

```ts title="apps/admin/src/modules.ts"
import { fleet } from "./fleet";

export const modules = [/* catalog(), cart(), page(), search(), mail(), */ fleet()] as const;
```

Then let the admin forward `/api/fleet` to your API: add
`fleet: { name: "Fleet", by: "url", address: "FLEET_URL" }` to the modules in
`apps/admin/src/forward/forward.server.ts`, and set `FLEET_URL` to your API's address in the
admin's `wrangler.jsonc`. The forward keeps the staff token and drops the admin's cookie.

The admin refuses to start, with a sentence naming it, a module that fills a slot no installed
module names, such as `order.side` without OrbCart, or that brings an area named like one of the
family's.

## 6. Open an app that is not React

A tool the merchant already runs, in any language, joins the admin as a place that opens it. The
person clicks **Fleet** in the sidebar, lands in your app on its own address, and is signed in:
no second password, no iframe. The admin's sign-in is an OAuth 2.1 authorization server for the
staff, and your app signs in with the authorization code flow and PKCE.

Register the app in the install, beside its place. The client is the app, with the addresses the
sign-in may send a code to. Each belongs to the app's own origin and is matched exactly:

```ts title="apps/admin/src/apps.server.ts"
// A MerchantApp[] of @orbcommerce/auth, which the install hands to the sign-in.
export const merchantApps = [
  {
    id: "fleet",
    name: "Fleet",
    url: "https://fleet.nordgrat.example",
    redirectUris: ["https://fleet.nordgrat.example/callback"],
  },
];
```

```ts title="src/fleet.ts"
import { defineModule } from "@orbcommerce/shell";
import { Truck } from "lucide-react";

export const fleet = () =>
  defineModule({
    id: "fleet",
    apps: {
      orders: [{ label: () => "Fleet", icon: Truck, url: "https://fleet.nordgrat.example" }],
    },
    roles: {},
  });
```

The place shows to whoever may view its area, here Orders; a person without it sees no link. It
is an owner's registration, so nobody is asked to consent to it.

**What your app does.** `apps/example-merchant-app` is the whole flow in about 150 lines: send
the person to the admin, check what comes back, read who they are.

1. Send the browser to `https://admin.nordgrat.example/api/auth/oauth2/authorize` with
   `response_type=code`, your `client_id`, your exact `redirect_uri`, `scope=staff:profile
offline_access`, `resource=` your own address, a random `state` and the PKCE `code_challenge`
   with `code_challenge_method=S256`. Keep the `state` and the verifier in a cookie.
2. The admin answers at your `redirect_uri` with `code`, `state` and `iss`. **Check `iss`** against
   the admin's address and `state` against your cookie before you do anything with the code (RFC
   9207); another admin or a replayed answer fails there.
3. Post the `code`, the `code_verifier`, the same `redirect_uri` and `resource` to
   `/api/auth/oauth2/token`. The answer holds an access token and a refresh token. Keep both in
   HttpOnly cookies. A token never travels in an address.
4. Check the access token on every request. It is a JWT signed with the admin's key set at
   `/api/auth/jwks`, with your address as its only audience, the person's `name` and `roles`, and
   `client_id` and `scope`:

```ts title="app/index.ts" worker
import { delegatedTokens, may } from "@orbcommerce/kernel";

const tokens = delegatedTokens({
  issuer: "https://admin.nordgrat.example",
  resource: "https://fleet.nordgrat.example",
  clock: Date,
});

export default {
  async fetch(request) {
    const verified = await tokens.verify(request);
    if (verified.status === "unavailable") return new Response(null, { status: 503 });
    if (verified.status !== "delegated") return new Response(null, { status: 401 });
    if (!verified.scopes.has("staff:profile")) return new Response(null, { status: 403 });
    if (!may(verified.staff, "orders", "view")) return new Response(null, { status: 403 });
    return Response.json({ name: verified.staff.name, roles: verified.staff.roles });
  },
} satisfies ExportedHandler;
```

**How long a removed person keeps their access.** The sign-in is the only place that knows the
staff, and no product asks it about a person. So a delegated access token lives at most five
minutes, the person's roles are read from the live membership each time one is issued, and so is
each refresh. Remove someone and their next refresh fails with `invalid_grant`; the token they
hold stops working within five minutes. A revoked refresh token (`/api/auth/oauth2/revoke`) fails
the same way. A token for another audience, another client or the panels' staff token is refused,
as is a redirect URI that is not registered exactly: no code is sent to it.

## 7. Let an AI assistant use a product, with a person's consent

An MCP client that identifies itself with a Client ID Metadata Document needs no registration. It
finds the sign-in from the product's own Protected Resource Metadata (RFC 9728), asks for the
product's address as the `resource` (RFC 8707) and the scopes it needs, and the person consents
on the admin's own screen, in words, with **Allow** or **Deny**. The token it gets names that
product alone and only the scopes consented to, and the product checks the scope of each tool:

```text
GET https://catalog.nordgrat.example/.well-known/oauth-protected-resource/mcp
GET https://admin.nordgrat.example/.well-known/oauth-authorization-server
```

Authors of clients: the sign-in answers `iss` in every authorization response and says so in its
metadata (`authorization_response_iss_parameter_supported`). Record the issuer before you open
the browser and refuse an answer that carries another. Dynamic client registration is not
offered; a `localhost` redirect follows the `application_type` the document declares.

**Adding a product's scope.** The sign-in knows its scopes and resources in one place,
`packages/auth/src/delegation.ts`: add the scope with the words the consent screen shows, and the
product's MCP address to `productResources`. The product accepts the token with
`delegatedTokens` from the kernel, as above, and checks its scope per tool. The admin's own chat
is such a client, registered by the admin itself and never asked to consent; it gets a
five-minute token for the signed-in person, never their session.

## What the team sees

- **Fleet in the sidebar,** after Search, for everyone with Fleet view; the owner gives it under
  _Settings › Staff_.
- **The fleet card on an Order,** below its details, once a job was made for it, and only for
  people who see the fleet.
- **New fleet job in the Order list's head,** for the same people.
- **Retry in the card's place,** when your API or your code fails, with the Order untouched.
- **Fleet in the sidebar, opening your own app,** signed in without a password, for the same people.

## Next

- [Run your own actions on an Order](/docs/integrate/order-actions): what changes an Order runs on
  OrbCart's server and stands in its history.
- [The catalog in the admin](/docs/admin/catalog): the product page names `product.side` for a part of
  yours beside a product.