# Use cases

> How to write a use case with Sypnorm, what each part means, and how failures work.

Applies to: the Sypnia engine (open source, self-hosted) and Sypnia Cloud (paid service).  
Source: https://cases.docs.sypnia.com/sypnorm/use-cases/

For agents: useCase(id, { summary, actor, input (zod, or generated from the case file), touches: {reads, writes} (typed tables), preconditions, run(ctx) }) from '@sypnia/cases/sypnorm'. Outcomes and failures are declared in the case file; `npx @sypnia/cases generate` writes their types (src/cases/<area>/<id>.ts skeleton + .sypnia/cases/types.d.ts) so ctx.outcome(name, payload) only accepts declared names and payloads. ctx: input (validated), actor (userId, role, signedIn), db (the transaction: only the tables in touches), outcome(name, payload) (ends the run: an outcome or a declared failure), trace, run_id, event (for event starts: the envelope: data, name, id, cause, depth; with on_all, data keyed by outcome name and by full event name, events lists every envelope, key is the correlation key). Every run must return ctx.outcome(...); thrown errors are bugs (Telemetry problem; retries/dead letters for event runs). The caller gets { ok: true, outcome: 'OrderPlaced', data } or { ok: false, outcome: 'SoldOut', tell, data }. Outcome rows go to the outbox in the same transaction when someone listens, written by the area's service (such a case runs at POST /_cases/<id>, never from the browser). A declared failure undoes the run's own writes (savepoint); its event and the delivery's record still commit. The first argument is the case id on the map (useCase('place-order', …)), no name translation. Each run = Telemetry span `usecase <case id>` with sypnia.case and sypnia.case.outcome.

## A whole use case

The example is La Espiga, a bakery that sells today's batch for pick-up. The case `place-order` is already on its map, with its start, its outcome and its failures:

`cases/orders/place-order.case.yaml`

```yaml
id: place-order
title: Order for today
actor: customer
goal: Get fresh bread reserved for pick-up today
starts: in_app
where: shop.order-for-today
input:
  items: [{ product_id: uuid, qty: int }]
  pickup_at: datetime
outcomes:
  OrderPlaced: { order_id: uuid, pickup_code: string }
failures:
  BakeryClosed: «We are closed at that time. Pick another one.»
  OutOfStock:
    tell: «This one just ran out. The rest of your order is kept.»
    payload: { name: string, left: int }
data:
  reads: [product, opening_hours]
  writes: [order, order_item, product]
allowed: [customer]
```

`npx @sypnia/cases generate` writes the skeleton and the types from that file. You write the rules inside `run`:

`src/cases/orders/place-order.ts`

```ts
import { useCase } from '@sypnia/cases/sypnorm';
import { db } from '../../db';                    // written by `npx @sypnia/cases tables`

export const placeOrder = useCase('place-order', {
  summary: "A customer orders today's bread for pick-up",
  actor: 'customer',
  touches: { reads: [db.products, db.opening_hours], writes: [db.orders, db.order_items, db.products] },
  preconditions: [({ actor }) => actor.signedIn],

  async run(ctx) {
    const { input } = ctx;
    if (!(await ctx.db.opening_hours.isOpenAt(input.pickup_at))) return ctx.outcome('BakeryClosed');
    const products = await ctx.db.products.where({ id: { in: input.items.map(i => i.product_id) } }).forUpdate().all();
    for (const item of input.items) {
      const p = products.find(x => x.id === item.product_id)!;
      if (p.left_today < item.qty) return ctx.outcome('OutOfStock', { name: p.name, left: p.left_today });
    }
    const order = await ctx.db.orders.insert({ customer_id: ctx.actor.userId, pickup_at: input.pickup_at }).returning();
    await ctx.db.order_items.insertMany(input.items.map(i => ({ order_id: order.id, product_id: i.product_id, qty: i.qty })));
    for (const item of input.items) await ctx.db.products.update({ id: item.product_id }).decrement('left_today', item.qty);
    return ctx.outcome('OrderPlaced', { order_id: order.id, pickup_code: order.pickup_code });
  },
});
```

## The parts

| Part            | Says                                                                                                                     | Checked                                                                       |
| --------------- | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------- |
| `id`            | the case's id on the map, written as it is there (`place-order`); this is how the code and its case file find each other | a case on the map, once in the app                                            |
| `summary`       | one sentence a client would understand                                                                                   | compared with the case's title                                                |
| `actor`         | who does it: a role of **your app** (customer, baker, admin, a machine)                                                  | by `preconditions` and your database's policies                               |
| `input`         | what it receives. Generated from the case's `input`; you may pass a zod schema instead                                   | before `run`; invalid input never reaches your code                           |
| `touches`       | the tables it reads and writes                                                                                           | at runtime: touching another table is an error                                |
| `preconditions` | what must be true before                                                                                                 | before `run`                                                                  |
| `run(ctx)`      | the steps                                                                                                                | in one transaction ([Runners](https://cases.docs.sypnia.com/sypnorm/runners)) |

`touches` and the outcomes are exactly what the map's `data`, `outcomes` and `failures` say for this case. When they differ, the check reports [drift](https://cases.docs.sypnia.com/contract/the-check).

## `ctx`

|                              | What it is                                                                                                                                                                                                                                                                                              |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ctx.input`                  | the input, already checked and typed                                                                                                                                                                                                                                                                    |
| `ctx.actor`                  | who is running it: `userId`, `role`, `signedIn`                                                                                                                                                                                                                                                         |
| `ctx.db`                     | the transaction: typed tables, limited to `touches` ([Tables and queries](https://cases.docs.sypnia.com/sypnorm/tables-and-queries))                                                                                                                                                                    |
| `ctx.outcome(name, payload)` | ends the run with one of the case's outcomes or failures. Only declared names and payloads type-check                                                                                                                                                                                                   |
| `ctx.event`                  | for a case that starts on an event: the event's envelope; `ctx.event.data` is its payload. With `on_all`, `ctx.event.data` holds every payload, keyed both by outcome name (`PaymentTaken`) and by full event name, `ctx.event.events` lists every envelope, and `ctx.event.key` is the correlation key |
| `ctx.run_id`, `ctx.trace`    | the run's id and its trace, for logs and calls to other services                                                                                                                                                                                                                                        |

## Every run ends in `ctx.outcome`

`run` must return `ctx.outcome(…)`. A run that returns anything else does not type-check, so a case can never end in silence. Failures are ended the same way, because [failures are outcomes too](https://cases.docs.sypnia.com/map/outcomes-and-events).

The caller gets the outcome, typed:

```ts
{ ok: true,  outcome: 'OrderPlaced', data: { order_id, pickup_code } }
{ ok: false, outcome: 'OutOfStock',  tell: 'This one just ran out. The rest of your order is kept.', data: { name, left } }
```

The words a person reads (`tell`) come from the map, so the words people approved are the words people see.

When some case listens to the outcome, the area's service writes it to the outbox **in the same transaction** as the run's rows ([Delivery](https://cases.docs.sypnia.com/runtime/delivery)). You never publish an event by hand. Such a case runs in its area's service, called at `POST /_cases/<case-id>`, never from the browser ([Runners](https://cases.docs.sypnia.com/sypnorm/runners#a-case-someone-listens-to-runs-on-the-server)).

A **declared failure** undoes the run's own writes: the body runs under a savepoint, and ending in a failure rolls it back, on every runner (the Data API runner sends no writes for it). The failure's event, when some case listens to it, and the record of the delivery still commit. So «Out of stock» never leaves half an order behind.

A **thrown** error means a bug: the transaction rolls back, nothing is published, the person sees a short generic message with a reference, and Telemetry records a problem. It is never shown as if it were an expected failure.

## A case that starts on an event

`src/cases/deliveries/pause-deliveries.ts`

```ts
import { useCase } from '@sypnia/cases/sypnorm';
import { addHours } from 'date-fns';
import { db } from '../../db';

export const pauseDeliveries = useCase('pause-deliveries', {
  actor: 'system',
  touches: { writes: [db.delivery_pauses] },
  async run(ctx) {
    const { from } = ctx.event.data;                 // weather.check-weather.RainExpected.v1
    const until = addHours(from, 3);
    await ctx.db.delivery_pauses.insert({ from, until });
    return ctx.outcome('DeliveriesPaused', { until });
  },
});
```

The runtime has already checked that this event was not handled before; if it arrives twice, the second time does nothing ([Delivery](https://cases.docs.sypnia.com/runtime/delivery#getting-an-event-twice-does-what-getting-it-once-does)).

## Seen in production

When `@sypnia/telemetry` is installed, each run is a span `usecase place-order` with the attributes `sypnia.case=place-order` and `sypnia.case.outcome=OrderPlaced` (or `OutOfStock`, `BakeryClosed`, `error`). You read your traces by use case and by how they end, not by URL.
