---
url: /reference/SYSTEM_FLOWS.md
---
# System Flows

Each flow in one diagram, a few plain lines and the routes it uses. Built from
`docs/generated/openapi.json`, the controllers, `database/canonical` and the e2e
specs named in each section. Where this page and OpenAPI differ, OpenAPI wins
for a route shape and the code wins for behavior. What is not verified says so.

Every route is under `/api/v1`, needs `Authorization: Bearer <accessToken>`
and, for tenant routes, `X-Organization-Id`. Public routes are marked.
Shared conventions and error codes:
[`CLIENT_INTEGRATION.md`](CLIENT_INTEGRATION.md).

## 1. Sign-up, sign-in, session

```mermaid
sequenceDiagram
    participant F as Front
    participant A as API
    F->>A: POST /sign-ups
    A-->>F: 201 challengeExpiresAt
    A--)F: code by email or phone (async)
    F->>A: POST /sign-ups/confirmations
    A-->>F: 204
    F->>A: POST /sign-ins
    alt second factor active
        A-->>F: kind second_factor_required + ticket
        F->>A: POST /sign-ins/second-factors
    end
    A-->>F: accessToken + refreshToken
    F->>A: GET /session/context
    A-->>F: identity, organizations, access, workspace
```

The first call of every session is `GET /session/context`. It says who the
caller is, whether they belong to an organization, and, with
`X-Organization-Id`, their roles, permissions, plan capabilities, profile and
workspace.

```mermaid
flowchart TD
    C["GET /session/context"] --> Q{"hasAvailableOrganizations"}
    Q -- no --> N["Create an organization (flow 2)"]
    Q -- yes --> S["Pick one, send X-Organization-Id"]
    S --> W["Show actions where permission AND capability hold"]
    W --> E{"401 on a call"}
    E -- yes --> R["POST /sign-ins/renewals"]
    R -- fails --> L["Sign in again"]
```

A renewal spends the refresh token; presenting a spent one ends the session.

| Route                                                                        | Access  |
| ---------------------------------------------------------------------------- | ------- |
| `POST /sign-ups`, `POST /sign-ups/confirmations`                             | public  |
| `POST /provider-nonces` (Google, Apple)                                      | public  |
| `POST /sign-ins`, `POST /sign-ins/second-factors`, `POST /sign-ins/renewals` | public  |
| `GET /session/context`                                                       | session |
| `POST /sign-outs`, `POST /sign-outs/everywhere`                              | session |

Proof: `session-context*.e2e-spec.ts`, `session-renewal.e2e-spec.ts`,
[`IDENTITY_CASE_MATRIX.md`](IDENTITY_CASE_MATRIX.md).

## 2. Organization and guided onboarding

```mermaid
flowchart TD
    A["GET /reference/metadata<br/>GET /plans?country"] --> B["POST /organizations<br/>plan + first business unit"]
    B --> C["POST /organization/onboarding<br/>legal entity, brand, site, outlet"]
    C --> D["GET /organization/setup"]
    D --> E{"complete"}
    E -- no --> F["Create stock location<br/>assign catalog"]
    F --> D
    E -- yes --> G["Ready to sell"]
```

`POST /organizations` makes the caller owner. `POST /organization/onboarding`
creates the first legal entity, brand, site and outlet in one transaction and
the default sales channel; it only works on an empty organization. Setup steps
it does not do: stock location and catalog assignment.
Both need `Idempotency-Key`.

| Route                                   | Permission                      |
| --------------------------------------- | ------------------------------- |
| `GET /reference/metadata`, `GET /plans` | session, public                 |
| `POST /organizations`                   | session, no organization header |
| `POST /organization/onboarding`         | `organization.structure.manage` |
| `GET /organization/setup`               | `organization.structure.view`   |

Errors: `409 organization.first_run_conflict`, `409 organization.plan_limit_reached`,
`422 organization.structure_refused`. Proof: `onboarding.e2e-spec.ts`,
`reference-metadata.e2e-spec.ts`.

## 3. Organization structure

```mermaid
flowchart TD
    O["Organization"] --> BU["Business unit"]
    O --> BR["Brand"]
    O --> LE["Legal entity"]
    O --> SI["Site: country, time zone"]
    BR --> OU["Outlet"]
    SI --> OU
```

```mermaid
flowchart TD
    OU["Outlet"]
    BU["Business unit"] -. "operates, by date" .-> OU
    LE["Legal entity"] -. "sells as, by date" .-> OU
    OG["Outlet group"] -. "members, by date" .-> OU
    LO["Stock location"] -. "issue rules" .-> OU
```

Business unit and legal entity are dated assignments of an outlet, not
columns. Outlet groups may overlap, never twice for the same outlet at once.
A stock location belongs to a legal entity and sits at the organization, a
business unit or an outlet. Plans cap active sites, business units and outlets
(`409 organization.plan_limit_reached`).

Scoped admin: `organization.structure.view` and `.manage` work at a scope. A
viewer scoped to a business unit sees its outlets and their site and brand,
nothing else. A scoped manager may rename inside the scope; creating a site,
brand or business unit needs organization-wide rights; a site or brand scope may
open outlets. Outside the scope the
answer is the same `403` as for an unknown id.

| Route                                                                                        | Permission                                                                                            |
| -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `GET /organization/structure`, `GET /outlet-groups`, `GET /schedules`, `GET /sales-channels` | `organization.structure.view`                                                                         |
| `POST/PATCH /outlet-groups`, `PUT /outlet-groups/{id}/members`                               | `organization.structure.manage`                                                                       |
| `POST /schedules`, `PUT /schedules/{id}/windows`, `GET .../occurrences`                      | `organization.structure.manage` (read: view)                                                          |
| `POST/PATCH /sales-channels`                                                                 | `organization.structure.manage`                                                                       |
| `PUT /legal-entities/{id}/tax-identifiers` (configuration only)                              | `organization.structure.manage`                                                                       |
| `POST/PATCH /locations`, `.../deactivation`, `.../reactivation`                              | `inventory.locations.manage`                                                                          |
| `GET /locations`                                                                             | `inventory.locations.view`                                                                            |
| `PUT /outlets/{id}/issue-location-rules`                                                     | `inventory.locations.manage` at the outlet                                                            |
| `PATCH` and deactivate or reactivate of sites, outlets (and `POST /outlets`)                 | `organization.account.manage` or `organization.structure.manage`, the latter also scoped to the place |
| `POST` of sites, brands, business units, legal entities                                      | `organization.account.manage`, organization-wide                                                      |

Proof: `structure-scoped-reads`, `structure-scoped-writes`, `structure-plan-limits`,
`outlet-groups*`, `locations-*`, `issue-location-rules`, `schedules`,
`sales-channels`, `legal-entity-tax-identifiers` (`test/e2e/*.e2e-spec.ts`).

## 4. Roles, permissions, scopes, invitations

```mermaid
flowchart TD
    I["POST /invitations<br/>1-5 roles + scope"] --> M["Membership"]
    M --> RA["POST /memberships/{id}/role-assignments"]
    RA --> P["Permission counts only<br/>inside the scope"]
    AD["Administrator"] -->|"step-up + reason"| OG["POST /memberships/{id}/ownership-grants"]
    OG --> M2["Second administrator"]
    RA -. "admin role: 403" .-> X["refused"]
    I -. "admin role: 403" .-> X
```

A role is held at a scope: organization, business unit, legal entity, brand,
site, outlet or outlet group. Critical rule: a role that grants
`organization.account.manage` is never offered by invitation or role
assignment. The only way to make another administrator is the ownership grant,
by an organization-wide administrator, with a live step-up
(`x-elevation-token`), a reason and `Idempotency-Key`.

Admin permissions: `organization.account.manage` is the superset of
`organization.structure.view/manage` and `identity.team.manage`. The code
accepts `identity.team.manage` in place of the administrator permission on
invitations, the member list, member control and role assignments
(`can-manage-organization.ts`); the OpenAPI text still names only
`organization.account.manage`. Whether a scoped (not organization-wide) holder
passes: not verified.

| Route                                                                                        | Permission                                              |
| -------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
| `GET /permissions`, `GET/POST /roles`, `PUT /roles/{id}`, `GET /offerable-roles`             | `organization.account.manage`                           |
| `POST /invitations`, `.../reissue`, `.../revocation`, `GET /invitations`, `GET /memberships` | `organization.account.manage` or `identity.team.manage` |
| `POST /memberships/{id}/role-assignments`, `PATCH/DELETE /role-assignments/{id}`             | same                                                    |
| `POST /step-ups`, `POST /step-ups/confirmations`                                             | session                                                 |
| `POST /memberships/{id}/ownership-grants`                                                    | organization-wide administrator + elevation             |

Errors: `403 identity.role_assignment_privilege_exceeded`,
`403 identity.invitation_privilege_exceeded`, `403 identity.elevation_required`,
`422 identity.ownership_grant_refused`. Proof: [`ACCESS_CASE_MATRIX.md`](ACCESS_CASE_MATRIX.md),
`scoped-admin`, `ownership-grants*` e2e specs.

## 5. Approvals by PIN

```mermaid
sequenceDiagram
    participant Ad as Admin
    participant Rq as Requester
    participant Ap as Approver
    participant A as API
    Ad->>A: PUT /approvals/settings (switch, rules, thresholds)
    Ap->>A: PUT /memberships/{own}/pin
    Rq->>A: POST /approvals (approver, permission, action key, pin)
    A-->>Rq: 201 approvalId, ttl 1-900s
    Rq->>A: the guarded action with approvalId
    Note over A: SQL consumes it once
```

A rule says "this permission needs another member's approval", for the whole
organization or for one business unit, outlet or outlet group. A threshold
(`amount`, `percent` or `units`) asks for approval only above the value.
The approver types their own PIN; the approval is bound to the requester, the
action key and an optional payload hash, expires, and is spent once.
Five wrong PINs per pair lock it for 15 minutes.
Built: settings, PIN, grant, `can-approve`. Not built: no business route
consumes an approval yet; `identity.require_approval` is only called in SQL.

| Route                           | Permission                                                                    |
| ------------------------------- | ----------------------------------------------------------------------------- |
| `GET/PUT /approvals/settings`   | `organization.account.manage`                                                 |
| `PUT /memberships/{own id}/pin` | the caller                                                                    |
| `POST /approvals`               | session; `409 identity.approval_not_required`, `403 identity.approval_denied` |
| `GET /approvals/can-approve`    | session                                                                       |

Proof: `approvals`, `approval-settings*`, `member-pin` e2e specs.

## 6. Settings and the business day

```mermaid
flowchart TD
    D["Default"] --> OR["Organization"] --> BU["Business unit"] --> GR["Outlet group"] --> OU["Outlet"]
    OU --> V(["Effective value"])
    L["Lock at business unit or group"] -. "ignores everything below" .-> V
```

The most specific override wins: outlet, then outlet group, then business
unit, then organization, then the default. A lock set on a business unit or
outlet group freezes the scopes below it (`409 settings.locked_by_parent`).
Every answer says where the value came from (`origin`). Writes need
`If-Match` with the ETag of the list.

Three settings exist: `inventory.negative_stock_mode` (prevent, allow),
`operations.business_day.cutoff_minutes` (0 to 1439, default 0) and
`inventory.default_receiving_location`.

```mermaid
flowchart TD
    N["now"] --> T["site time zone"] --> C["minus cutoff"] --> BD["businessDate"]
    OT["Outlet"] --> ST["Site: country, time zone"]
    ST --> CU["currency, locale<br/>site override, else organization"]
```

At 01:30 with a 02:00 cutoff, the order belongs to the previous business day.
A sale uses the currency of the outlet.

| Route                                                                                                        | Permission                                |
| ------------------------------------------------------------------------------------------------------------ | ----------------------------------------- |
| `GET /settings`                                                                                              | `settings.assignments.view` (+ ETag, 304) |
| `PUT/DELETE /settings/{code}/assignment`                                                                     | `settings.assignments.manage`             |
| `PATCH /organization` (default currency, locale), `POST/PATCH /sites` (country, time zone, currency, locale) | `organization.account.manage`             |

Scope `organization` or `business_unit` or `outlet_group` needs the permission
organization-wide; `outlet` needs it at that outlet. Errors:
`403 settings.action_forbidden`, `404 settings.scope_not_found`,
`422 settings.value_invalid`. Proof: `settings-*`, `sites-regional`,
`sales-regional-profile` e2e specs.

## 7. Catalog to price, quota, supply and sale

```mermaid
flowchart TD
    SR["PUT /inventory/supply-routes/{variantId}<br/>stock, recipe, untracked"] --> SALE
    PB["POST /pricing/books, PUT .../assignments<br/>PATCH /price-list (bookId)<br/>POST /pricing/rules (schedule)"] --> RES["POST /pricing/resolve<br/>the price a sale will charge"]
    QP["POST /operations/pools, PUT .../members, POST .../rules"] --> SALE
    BL["POST /catalog/outlets/{id}/blocks<br/>manual 86"] --> AV
    RES --> SALE["POST /outlets/{id}/sales"]
    SALE --> AV["GET /outlets/{id}/availability<br/>remaining, limited by quota, stock or block"]
```

```mermaid
sequenceDiagram
    participant F as Front
    participant A as API
    participant S as SQL (one transaction)
    F->>A: POST /outlets/{id}/sales + Idempotency-Key
    A->>A: permission, replay by key
    A->>A: Catalog: is each line sellable here
    A->>S: sales.take_order
    S->>S: pricing.resolve_cart: books, rules, options, combo choices
    S->>S: operations.take_capacity: draw the quota pools
    S->>S: number and date the order, store the service mode
    S->>S: reserve stock, close order, consume reservation
    S-->>A: order
    A-->>F: 201 order (audited)
```

The client sends variants, quantities, options, combo choices, `channelId`,
`serviceMode`, `menuId` and quota `overrides`; never a price or a currency. The
server prices the cart once (outlet book, then channel, menu and service mode,
the rule in force and its schedule), draws the quota pools and stores the
`serviceMode` on the order, unchangeable after the sale. A variant with no
price is refused with `422 sales.price_unresolvable`; an explicit price of `0`
sells at zero. An exhausted blocking pool is `409
sales.capacity_exceeded`; a warning pool lets the sale through with a `warnings`
entry; an override needs an approval of `operations.quotas.override`. Not
enough stock aborts the whole sale. The same key and request replays the order
with `200`; the same key with another `serviceMode` is `409
idempotency.key_reused`.

| Route                                     | Permission                                                      |
| ----------------------------------------- | --------------------------------------------------------------- |
| Catalog admin (items, variants, menus)    | `catalog.*`, see [`CATALOG_USE_CASES.md`](CATALOG_USE_CASES.md) |
| `GET/PUT/PATCH /price-list`, `/pricing/*` | `pricing.prices.view` / `manage` (`POST /pricing/resolve` also `sales.orders.take` at the outlet) |
| `/operations/pools`                       | `operations.quotas.view` / `manage`                             |
| `/outlets/{id}/availability`              | `operations.availability.view` at the outlet                    |
| `/catalog/outlets/{id}/blocks`            | `operations.availability.block` at the outlet                   |
| `/inventory/supply-routes`                | `inventory.supply_routes.view` / `manage`                       |
| `POST /outlets/{id}/sales`                | `sales.orders.take` at the outlet                               |
| `GET /outlets/{id}/sales/{orderId}`       | `sales.orders.read`                                             |

| Status | Code                                                                                                           |
| ------ | -------------------------------------------------------------------------------------------------------------- |
| 400    | `foundation.validation_failed` (no key, unknown field, a price)                                                |
| 403    | `sales.action_forbidden` (also unknown or foreign outlet), `sales.approval_required`, `sales.approval_invalid` |
| 409    | `sales.insufficient_stock`, `sales.capacity_exceeded`, `sales.currency_mismatch`, `idempotency.key_reused`     |
| 422    | `sales.lines_not_sellable`, `sales.price_unresolvable`, `sales.order_refused`                                  |

Detail: [`SALES_USE_CASES.md`](SALES_USE_CASES.md).

## 8. Price edit

```mermaid
flowchart TD
    M["GET /price-list/items/{id}<br/>price now + next, per variant"] --> E["PATCH /price-list<br/>set, remove, validFrom"]
    E --> Q{"validFrom in the future"}
    Q -- no --> NW["Close current price, open new one"]
    Q -- yes --> SC["Scheduled: current stays until it starts"]
    NW --> H["GET /price-list/variants/{id}/history"]
    SC --> H
```

`PATCH` is a delta (up to 500 changes): variants not named keep their price,
an equal price changes nothing, a different one closes the old entry as
history. Another schedule for a variant that has one is `409
pricing.price_schedule_conflict`. `PUT` still replaces the whole list. One list
per currency, tax exclusive. Needs `pricing.prices.manage` (owner, manager);
reads need `pricing.prices.view`. Proof: `price-list-edit`, `price-list-reads`
e2e specs; [`PRICING_USE_CASES.md`](PRICING_USE_CASES.md).

## 9. Stock today

```mermaid
flowchart TD
    SR["Supply route<br/>stock, recipe, untracked"] --> RS["reserve_stock"]
    RS --> CR["consume_reservation"]
    CR --> LG["Stock ledger"]
    RC["receive_stock<br/>lots, expiry, serials"] --> LG
    LO["Locations + issue rules<br/>(REST, flow 3)"] --> RS
```

In SQL: supply routes, reservations, the ledger, goods receiving and the
negative-stock mode. Through REST, stock only moves inside a sale, and
locations, issue rules and supply routes are administered (flows 3 and 7). No
REST route exists for receiving, balances or counts.

## 10. Audit read

`GET /audit-events` (`audit.events.view`, held by the owner role by default):
newest first, keyset cursor, filters `resourceKind`, `actorIdentityId`,
`outletId`, `from`, `to`. It never returns network addresses or the changed
values. A holder at one outlet must name that outlet.
Proof: `audit-events.e2e-spec.ts`.

## 11. Not built yet

* Payments, till and cash shifts, credit and receivables.
* Promotions and discounts.
* Receiving and purchase orders over REST (built on unmerged branches).
* E-invoicing and country tax: an external service; this API only holds
  configuration (legal entity tax identifiers). A sale carries no tax.

Roadmap: R1 (the foundation above: reference data, settings, audit read,
locations, onboarding, structure, approvals, plan limits, price edit) is
merged. The R2 to R6 plan is kept outside this repository, so its content is
not verified here. The phase order is in [`ROADMAP.md`](ROADMAP.md).
