@proveanything/smartlinks 2.1.17 → 2.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/adminViews.d.ts +85 -0
  2. package/dist/adminViews.js +259 -0
  3. package/dist/api/index.d.ts +2 -0
  4. package/dist/api/index.js +2 -0
  5. package/dist/api/operations.d.ts +36 -0
  6. package/dist/api/operations.js +56 -0
  7. package/dist/api/order.d.ts +12 -1
  8. package/dist/api/order.js +15 -0
  9. package/dist/api/userGroups.d.ts +78 -0
  10. package/dist/api/userGroups.js +124 -0
  11. package/dist/docs/API_SUMMARY.md +604 -42
  12. package/dist/docs/admin-views.md +125 -0
  13. package/dist/docs/app-manifest.md +2 -0
  14. package/dist/docs/operations.md +281 -0
  15. package/dist/docs/overview.md +3 -0
  16. package/dist/docs/server-functions.md +18 -0
  17. package/dist/docs/user-groups.md +168 -0
  18. package/dist/docs/utils.md +17 -0
  19. package/dist/http.js +4 -0
  20. package/dist/iframeResponder.d.ts +15 -0
  21. package/dist/iframeResponder.js +39 -1
  22. package/dist/index.d.ts +2 -0
  23. package/dist/index.js +2 -0
  24. package/dist/openapi.yaml +1238 -276
  25. package/dist/testing/index.d.ts +13 -0
  26. package/dist/testing/index.js +55 -0
  27. package/dist/types/appManifest.d.ts +83 -0
  28. package/dist/types/containers.d.ts +8 -0
  29. package/dist/types/iframeResponder.d.ts +16 -1
  30. package/dist/types/index.d.ts +2 -0
  31. package/dist/types/index.js +2 -0
  32. package/dist/types/operations.d.ts +598 -0
  33. package/dist/types/operations.js +8 -0
  34. package/dist/types/order.d.ts +35 -6
  35. package/dist/types/userGroups.d.ts +103 -0
  36. package/dist/types/userGroups.js +5 -0
  37. package/dist/utils/conditions.d.ts +7 -0
  38. package/dist/utils/conditions.js +16 -9
  39. package/docs/API_SUMMARY.md +604 -42
  40. package/docs/admin-views.md +125 -0
  41. package/docs/app-manifest.md +2 -0
  42. package/docs/operations.md +281 -0
  43. package/docs/overview.md +3 -0
  44. package/docs/server-functions.md +18 -0
  45. package/docs/user-groups.md +168 -0
  46. package/docs/utils.md +17 -0
  47. package/openapi.yaml +1238 -276
  48. package/package.json +1 -1
@@ -0,0 +1,125 @@
1
+ # Admin views
2
+
3
+ An app's **admin views** are its admin screens by name: "the campaigns list", "one campaign", "bookings
4
+ for a day". The app declares them once, in `app.manifest.json#adminViews`, and three things read the same
5
+ list:
6
+
7
+ | Reader | What it does with the views |
8
+ |---|---|
9
+ | **The app's own side menu** | areas (`main`) in order, Settings (`settings`) at the bottom; opening a record swaps in that record's views |
10
+ | **Studio's workspace menu** (coming) | lifts an app's areas into the business's own menu, then opens the app with `chrome=none` |
11
+ | **The Studio assistant** | opens a view while it talks: "here are Saturday's bookings" |
12
+
13
+ Admin views are not portal pages (`linkable`, see [deep-link-discovery.md](deep-link-discovery.md)) and
14
+ not standalone screens (`publicViews`). They are the admin side only.
15
+
16
+ Core apps with three or more areas follow prove `server/docs/design/core-app-layout.md`. Their side menu
17
+ is built from these views.
18
+
19
+ ---
20
+
21
+ ## Declaring views
22
+
23
+ ```json
24
+ "adminViews": [
25
+ { "id": "campaigns", "title": "Campaigns", "path": "/campaigns", "icon": "megaphone",
26
+ "description": "Campaigns: drafts, scheduled and sent, with their results.",
27
+ "params": { "status": "draft | scheduled | sent" } },
28
+ { "id": "campaign", "title": "Campaign", "path": "/campaigns/{campaignId}", "group": "record",
29
+ "within": "campaigns", "params": { "campaignId": "a campaign's id" },
30
+ "description": "One campaign: its message, who it goes to, and how it landed." },
31
+ { "id": "log", "title": "Message log", "path": "/log", "icon": "scroll-text" },
32
+ { "id": "settings", "title": "Settings", "path": "/settings", "icon": "settings", "group": "settings" }
33
+ ]
34
+ ```
35
+
36
+ | Field | Meaning |
37
+ |---|---|
38
+ | `id` | Stable, unique in the app. Hosts and the assistant keep it, so never reuse one for another screen. |
39
+ | `title` | The menu label, in the business's words. |
40
+ | `path` | Hash route in the admin page. `{name}` marks a required param. |
41
+ | `group` | `main` (default), an area in the menu. `settings`, pinned at the bottom. `record`, a screen inside one record, never in the main menu. |
42
+ | `within` | The view this one sits in. A record's first view names its area. The record's other views name the record's first view. |
43
+ | `icon` | A [Lucide](https://lucide.dev/icons) name, kebab-case. |
44
+ | `description` | One line on what the screen shows. The assistant reads it to choose a view. |
45
+ | `params` | Each param, with a few words on what it is. `{name}` params are required; the rest are optional query params. Never list platform context (`collectionId`, `appId`, …). |
46
+
47
+ **A record with several screens** (a product with details, proofs and variants):
48
+
49
+ ```json
50
+ { "id": "product", "title": "Details", "path": "/products/{productId}", "group": "record", "within": "products" },
51
+ { "id": "product.proofs", "title": "Proofs", "path": "/products/{productId}/proofs", "group": "record", "within": "product" },
52
+ { "id": "product.variants", "title": "Variants", "path": "/products/{productId}/variants", "group": "record", "within": "product" }
53
+ ```
54
+
55
+ While a product is open, the menu reads "← Products", then Details, Proofs, Variants.
56
+
57
+ Declare only screens worth opening by name. A dialog, a step inside a form or a filter state is not a
58
+ view; it is a param of one (`status`, `tab`).
59
+
60
+ ---
61
+
62
+ ## Building the menu from them
63
+
64
+ Import the manifest so there is one list, and use the helpers:
65
+
66
+ ```ts
67
+ import * as SL from '@proveanything/smartlinks'
68
+ import manifest from '../public/app.manifest.json'
69
+
70
+ const views = manifest.adminViews as SL.AdminView[]
71
+
72
+ SL.adminViews.menu(views) // { main: [...areas], settings: [...] }
73
+ SL.adminViews.match(views, location.pathname) // { view, params } | null — what screen this is
74
+ SL.adminViews.trail(views, 'campaign') // [campaigns, campaign] — campaigns is the current menu item
75
+ SL.adminViews.recordMenu(views, 'campaign') // { back: campaigns, record, items } — the swapped menu
76
+ SL.adminViews.pathFor(views[1], { campaignId }) // '/campaigns/c_1'
77
+ ```
78
+
79
+ Route the app by these paths, not by a `?tab=` param. The host keeps the path in its own address
80
+ (`?path=`), so a screen survives a reload and can be shared.
81
+
82
+ ---
83
+
84
+ ## Following the host: `smartlinks:navigate`
85
+
86
+ The host (Studio, the assistant) asks the app to open a screen without reloading it:
87
+
88
+ ```
89
+ host → app { type: 'smartlinks:navigate', view?: 'campaign', params?: { campaignId: 'c_1' }, path?: '/log', highlight?: 'row-id' }
90
+ ```
91
+
92
+ Register once, near the router:
93
+
94
+ ```ts
95
+ const navigate = useNavigate()
96
+ useEffect(() => SL.adminViews.onNavigate(views, (to) => navigate(to.path)), [navigate])
97
+ ```
98
+
99
+ - Registering posts `smartlinks:navigable` to the host. A host that never hears it (an older build)
100
+ reloads the frame at the new path instead.
101
+ - Only messages from the parent window are taken. A `view` is resolved to its path, and a raw `path`
102
+ must be a hash route of this app.
103
+ - After each request the app posts `smartlinks:navigate-result` `{ ok, view, path, reason? }`, so the
104
+ assistant can say when a screen couldn't be opened.
105
+ - `highlight` is optional. It is an id the app understands, such as a row to point at; ignore it if you
106
+ have nothing to point at.
107
+
108
+ Hosts on the SDK use `IframeResponder.navigate(req)`, which returns `false` when the app isn't
109
+ navigable. Hosts with their own frame code use `SL.adminViews.postNavigate(frame.contentWindow, req)`.
110
+
111
+ ---
112
+
113
+ ## `chrome=none`: the host carries the menu
114
+
115
+ When a host's own menu already lists an app's views, it opens the app with `chrome=none`. The app then
116
+ hides its side menu and the bar holding its toggle, and shows only the content. The page header
117
+ (`AdminPageHeader`) stays: it is content.
118
+
119
+ ```ts
120
+ const bare = SL.adminViews.hostChrome() === 'none'
121
+ ```
122
+
123
+ `hostChrome()` reads the address the page was first opened at, so the app's own navigation can't lose it.
124
+ With `chrome=none` the app moves between areas only when the host says so (`smartlinks:navigate`).
125
+ Links inside the content, such as opening a campaign from the list, still work as normal.
@@ -390,6 +390,7 @@ An app can have any combination of three setup styles. Only public views are ext
390
390
  | **Portal components** — where the app renders inside portal (collection / product / batch / variant / proof) | module registry `components.*` (set at publish) | Inside portal | Physical twin (QR/NFC scan) |
391
391
  | **App pages** — the entry points portal menus/tabs link to and websites embed (e.g. list vs calendar; book vs my bookings) | `linkable` / `DeepLinkEntry` | Inside a host: portal or a website | The host: its signed-in session, plus the page's `accepts` params |
392
392
  | **Public views** — standalone external screens | `publicViews` (this block) | Outside portal | URL params only |
393
+ | **Admin views** — the admin side's screens by name, for its side menu, Studio's menu and the assistant | `adminViews` ([admin-views.md](admin-views.md)) | The admin page, in Studio | Studio's session; `chrome=none` when Studio carries the menu |
393
394
 
394
395
  #### `records`
395
396
 
@@ -450,6 +451,7 @@ this is just the manifest shape.
450
451
  | `definitions[].name` | string | Function name; also the handler export name (override with `handler`) |
451
452
  | `definitions[].trigger` | object | `{ type: "http"|"event"|"cron", … }` |
452
453
  | `definitions[].visibility` | string | `admin` \| `public` (http only) — who may call it |
454
+ | `definitions[].userGroups` | string[] | http only — the [user groups](user-groups.md) (by key) allowed to call it; the caller must be in at least one, or be a collection admin |
453
455
  | `definitions[].authority` | string | `caller` \| `collection` — whose authority it runs as |
454
456
  | `definitions[].capabilities` | string[] | Least-privilege grants (`sl:<res>:<read\|write>`, `network[:<host>]`, `secrets:<ref>`) |
455
457
 
@@ -0,0 +1,281 @@
1
+ # Operations: work orders, stock, what things are made of
2
+
3
+ For apps that run a factory floor, a warehouse or any place where things are made, stored and moved.
4
+ These are platform objects, so every app in a collection shares one picture: one count of the caps,
5
+ one list of the jobs.
6
+
7
+ | Question | Object | Reach it as |
8
+ |---|---|---|
9
+ | What work is under way? | **Work orders** | `ctx.sl.workOrders` |
10
+ | Where is it? | **Containers** (a bin, a rack, a pallet, a drum) | `SL.containers` |
11
+ | How much is there? | **Stock**: a quantity of a product in a container | `ctx.sl.stock` |
12
+ | What is it made of? | **Bill of materials** (the recipe) and **made from** (what a batch really used) | `ctx.sl.boms`, `ctx.sl.madeFrom` |
13
+ | What is wanted, and what is coming? | **Orders**, sales and purchase, with quantities | `SL.order` |
14
+ | Will we run short? | A product's **position** | `ctx.sl.stock.position` |
15
+
16
+ > Don't keep your own stock counts, job tables or component lists in app records. Other apps, the
17
+ > reports and the assistant can't see those, and you end up with two answers to "how many do we have".
18
+
19
+ ## Reaching them
20
+
21
+ **In a server function.** Declare the capability, and run with collection authority:
22
+
23
+ ```jsonc
24
+ {
25
+ "name": "finishPick",
26
+ "trigger": { "type": "http", "methods": ["POST"] },
27
+ "visibility": "public",
28
+ "authority": "collection",
29
+ "elevated": true,
30
+ "userGroups": ["warehouse", "manager"],
31
+ "capabilities": ["sl:stock:write", "sl:workorders:write"]
32
+ }
33
+ ```
34
+
35
+ | Capability | Covers |
36
+ |---|---|
37
+ | `sl:workorders:read` / `:write` | `ctx.sl.workOrders` |
38
+ | `sl:stock:read` / `:write` | `ctx.sl.stock`, including `position` and `short` |
39
+ | `sl:boms:read` / `:write` | `ctx.sl.boms` |
40
+ | `sl:madefrom:read` / `:write` | `ctx.sl.madeFrom` |
41
+
42
+ - **`authority: "collection"` is required.** This is the collection's shared operational data, never a
43
+ visitor's own. A function running as the caller gets `NEEDS_COLLECTION_AUTHORITY`, whatever it declares.
44
+ - **Say who may call it** with [`userGroups`](user-groups.md). `write` implies `read`.
45
+
46
+ **From an admin screen.** The same calls, same arguments, same results:
47
+
48
+ ```ts
49
+ import { operations } from '@proveanything/smartlinks'
50
+
51
+ const ops = operations.admin(collectionId, { appId: 'production' })
52
+ await ops.stock.position({ productId: 'brass-cap', horizonDays: 90 })
53
+ ```
54
+
55
+ **In a site.** A site's server code has all of these on its own cloud: `slServer().stock.move({ … })`.
56
+
57
+ ## Work orders
58
+
59
+ The shared skeleton of a "job": what is being made, how many, by when, for which order line, and an
60
+ ordered list of stages with planned and actual times and quantities done and scrapped.
61
+
62
+ ```ts
63
+ const job = await ctx.sl.workOrders.create({
64
+ ref: '19264', // the number people use; unique in the collection
65
+ kind: 'decoration-boxing-wrapping', // your own type
66
+ productId, quantity: 900, dueAt: '2026-12-05', priority: 2,
67
+ orderItemId, // the order line it fulfils
68
+ stages: ['picking', 'decoration', { key: 'boxing', plannedStart, plannedEnd }, 'wrapping'],
69
+ data: { gmpReference: 'GMP-1', testers: 90 }, // anything else you keep on it
70
+ })
71
+
72
+ await ctx.sl.workOrders.startStage(job.id, 'picking')
73
+ await ctx.sl.workOrders.progress(job.id, 'decoration', { done: 50, scrapped: 1 }, { note: 'first box' })
74
+ await ctx.sl.workOrders.completeStage(job.id, 'wrapping', { closeWorkOrder: true })
75
+ ```
76
+
77
+ **The platform keeps the shape and three rules. Your app keeps the meaning.**
78
+
79
+ | The platform | Your app |
80
+ |---|---|
81
+ | A `ref` is unique among live work orders | Which stages exist, and in what order |
82
+ | A stage's figures change atomically and never go below zero | What must be true before a stage starts or finishes |
83
+ | A work order that isn't `open` is **frozen** | Who may do each thing (`userGroups`) |
84
+
85
+ - **Nothing starts or finishes by itself.** `progress` adds to the figures; it doesn't complete the
86
+ stage. Your code decides when enough is enough, then calls `completeStage`.
87
+ - **Frozen** means: while the status is `on-hold`, `blocked`, `done` or `cancelled`, no stage can start,
88
+ progress or finish, and no stock can be moved for it. The error is `WORK_ORDER_FROZEN` (409) and says
89
+ why. Re-planning a stage is still allowed while it waits.
90
+ - `setStatus(id, 'on-hold', { reason })`: `on-hold`, `blocked` and `cancelled` need a reason.
91
+ - Changing `quantity` needs `{ reason }`, and taking figures down (`progress` with a negative) does too.
92
+ - **Any app can read a work order; only the app that created it can change it** (`NOT_YOURS`).
93
+ - A split is a new work order with `parentId`. A `get` takes the id or the ref.
94
+ - `list({ status, productId, late: true, dueFrom, dueTo, q, sort: 'due' | 'priority' })`.
95
+
96
+ ## Stock
97
+
98
+ **A stock line is a quantity of one product, in one container, in one state.** A container holds as
99
+ many lines as it has different things. A product's total is a sum, worked out when you ask.
100
+
101
+ States: `available`, `allocated` (set aside for something), `held`, `quarantine`.
102
+
103
+ A quantity changes only through a **movement**:
104
+
105
+ ```ts
106
+ await ctx.sl.stock.receive({ containerId: bin, productId: 'brass-cap', quantity: 5000, note: 'PO-2041' })
107
+ await ctx.sl.stock.allocate({ containerId: bin, productId: 'brass-cap', quantity: 900, to: { type: 'workOrder', id: job.id } })
108
+ await ctx.sl.stock.move({ from: bin, to: cage, productId: 'brass-cap', quantity: 900, allocatedTo: { type: 'workOrder', id: job.id } })
109
+ await ctx.sl.stock.consume({ containerId: cage, productId: 'brass-cap', quantity: 880, allocatedTo: { type: 'workOrder', id: job.id } })
110
+ await ctx.sl.stock.release({ containerId: cage, productId: 'brass-cap', quantity: 20, from: { type: 'workOrder', id: job.id } })
111
+ await ctx.sl.stock.produce({ containerId: pallet, productId, batchId: '26-1001', quantity: 880, workOrderId: job.id })
112
+ await ctx.sl.stock.hold({ containerId: drum, productId: 'juice', batchId: 'B-77', quantity: 200, state: 'quarantine', reason: 'Smell test failed' })
113
+ await ctx.sl.stock.adjust({ containerId: bin, productId: 'brass-cap', by: -3, reason: 'Counted 4097' })
114
+ ```
115
+
116
+ | Movement | From → to | Needs |
117
+ |---|---|---|
118
+ | `receive`, `produce` | nowhere → a container | |
119
+ | `consume` | a container → nowhere | |
120
+ | `move` | container → container, same state | |
121
+ | `allocate` / `release` | available ↔ allocated to something | `to` / `from`: `{ type, id }` |
122
+ | `hold` / `unhold` | available ↔ `held` or `quarantine` | a `reason` |
123
+ | `adjust` | a correction, `by` + or − | a `reason` |
124
+
125
+ - **It never goes below zero.** Taking more than a line holds is `INSUFFICIENT_STOCK` (409), with what
126
+ is there in `details`. Twenty people taking one from a bin of ten: ten succeed.
127
+ - **One unit per product** in a collection (`each`, `kg`, `l`): the first stock of a product sets it,
128
+ and another unit is `UNIT_MISMATCH`.
129
+ - **A movement for a work order is refused while that work order is frozen.**
130
+ - **A scanner that retries:** pass `{ idempotencyKey }` as the second argument. The same key again
131
+ moves nothing and returns `replayed: true`.
132
+ - Putting a pallet away is not a stock movement: move the container (`containers.update(id, { parentContainerId })`).
133
+ - Every movement is recorded with who, when, from, to and why.
134
+
135
+ ### Several writes at once
136
+
137
+ All or nothing, across stock, work orders, bills of materials and made-from:
138
+
139
+ ```ts
140
+ await ctx.sl.operations.transaction([
141
+ { op: 'stock.move', args: [{ from: bin, to: cage, productId: 'brass-cap', quantity: 900 }] },
142
+ { op: 'stock.move', args: [{ from: bin2, to: cage, productId: 'pump', quantity: 900 }] },
143
+ { op: 'workOrders.completeStage', args: [job.id, 'picking'] },
144
+ ])
145
+ ```
146
+
147
+ A failing step undoes them all; the error's `details.step` says which. Up to 50 steps, writes only.
148
+
149
+ ### Reading
150
+
151
+ ```ts
152
+ await ctx.sl.stock.totals({ productId: 'brass-cap' })
153
+ // { available: 4100, allocated: 900, held: 0, quarantine: 0, total: 5000, unit: 'each' }
154
+
155
+ await ctx.sl.stock.where({ productId: 'brass-cap' })
156
+ // [{ quantity: 4100, state: 'available', path: ['Warehouse A', 'Rack 3', 'Bin 12'], place: { name: 'Bin 12', … } }, …]
157
+
158
+ await ctx.sl.stock.lines({ containerId: bin }) // what is in this bin
159
+ ```
160
+
161
+ ### Containers as places
162
+
163
+ A container with `fixed: true` is a place (a site, a rack, a bin); without it, something carried (a
164
+ pallet, a cage, a drum). `where` reports the first fixed container above each line as its `place`.
165
+ Suggested `containerType` names, so apps agree: `site`, `zone`, `rack`, `bin`, `pallet`, `cage`,
166
+ `drum`, `tank`.
167
+
168
+ ## The position: will we run short?
169
+
170
+ One answer with fixed fields, for a screen, a report or an assistant:
171
+
172
+ ```ts
173
+ const p = await ctx.sl.stock.position({ productId: 'brass-cap', horizonDays: 90 })
174
+
175
+ p.onHand // { available: 400, allocated: 100, held: 0, quarantine: 40, total: 540, unit: 'each' }
176
+ p.where // each line, with its path
177
+ p.onOrder // { total: 60, lines: [{ orderRef: 'PO-1', supplier, quantity: 60, dueAt }] }
178
+ p.beingMade // open work orders that make it, and how many each still has to finish
179
+ p.needed // { total: 600, lines: [{ why: 'work order', ref: 'J-1', quantity: 200, neededBy }, { why: 'order, not yet in production', … }] }
180
+ p.projected // [{ date: '2026-11-14', balance: 400 }, { date: '2026-11-24', balance: 200 }, …]
181
+ p.shortfall // { quantity: 140, firstShortOn: '2026-12-14' } or null
182
+ p.asOf, p.sources
183
+ ```
184
+
185
+ - **Needed** counts the product ordered by customers, and, as a component, what open work orders and
186
+ orders not yet in production still need, worked through the bill of materials. An order line that a
187
+ work order already fulfils is counted once, through the work order.
188
+ - **Nothing is stored.** It is worked out when you ask, and says when (`asOf`).
189
+ - `ctx.sl.stock.short({ horizonDays })` lists everything that will run short, soonest first.
190
+
191
+ ## Bill of materials
192
+
193
+ The recipe. A component is a product, and can have a recipe of its own.
194
+
195
+ ```ts
196
+ await ctx.sl.boms.set({
197
+ productId: 'perfume-100',
198
+ lines: [
199
+ { componentProductId: 'bottle-100', quantity: 1 },
200
+ { componentProductId: 'brass-cap', quantity: 1 },
201
+ { componentProductId: 'juice', quantity: 0.1, unit: 'kg' },
202
+ { componentProductId: 'gift-ribbon', quantity: 1, optional: true },
203
+ ],
204
+ })
205
+
206
+ const need = await ctx.sl.boms.explode({ productId: 'perfume-100', quantity: 500 })
207
+ need.materials // [{ productId: 'bottle-100', quantity: 500, unit: 'each' }, …, { productId: 'juice', quantity: 50, unit: 'kg' }]
208
+ ```
209
+
210
+ - **Never edited.** `set` writes a new version that takes over from `validFrom` (now by default); the
211
+ one before ends then. `current({ productId, at })` answers for any date, which a product passport needs.
212
+ - `yields`: how many the recipe makes (`100` for a batch recipe).
213
+ - A variant's own recipe wins; a variant without one uses the product's.
214
+ - A recipe that leads back to its own product is refused (`BOM_LOOP`).
215
+ - `whereUsed({ componentProductId })`: which products use this.
216
+
217
+ ## Made from
218
+
219
+ What a batch, or one item, was **really** made from. The bill of materials is the recipe; this is the record.
220
+
221
+ ```ts
222
+ await ctx.sl.madeFrom.record({
223
+ subject: { type: 'batch', id: '26-1001' },
224
+ sources: [
225
+ { type: 'batch', id: 'JUICE-7', productId: 'juice', quantity: 50, unit: 'kg' },
226
+ { type: 'batch', id: 'CAP-LOT-9', productId: 'brass-cap', quantity: 500 },
227
+ ],
228
+ workOrderId: job.id,
229
+ })
230
+
231
+ await ctx.sl.madeFrom.trace({ type: 'batch', id: '26-1001' }) // back through every level
232
+ await ctx.sl.madeFrom.usedIn({ type: 'batch', id: 'CAP-LOT-9' }) // everything that used this lot
233
+ ```
234
+
235
+ - `subject` is a `batch` or a `proof` (one item: "this boat has engine 123").
236
+ - **Append-only.** A part swapped later: `end(id, { reason })` the old entry and `record` the new one.
237
+ `of(subject, { at })` still answers for the earlier date.
238
+
239
+ ## Orders with quantities
240
+
241
+ An order has a `direction`: `sales` (someone wants it from us, the default) or `purchase` (we want it
242
+ from a supplier, `partyId`). A line can be a quantity of a product:
243
+
244
+ ```ts
245
+ await SL.order.create(collectionId, {
246
+ direction: 'purchase', partyId: 'tagworks', orderRef: 'PO-2041',
247
+ items: [{ productId: 'brass-cap', quantity: 5000, dueAt: '2026-12-01' }],
248
+ })
249
+ await SL.order.lineDone(collectionId, orderId, lineId, 2000) // 2,000 arrived
250
+ ```
251
+
252
+ Open sales lines are what is wanted; open purchase lines are what is coming. Both feed the position.
253
+
254
+ ## Errors
255
+
256
+ | Code | Status | Meaning |
257
+ |---|---|---|
258
+ | `INSUFFICIENT_STOCK` | 409 | The line doesn't hold that much (`details.available`) |
259
+ | `WORK_ORDER_FROZEN` | 409 | The work order isn't open (`details.status`, `details.reason`) |
260
+ | `UNIT_MISMATCH` | 409 | The product is held in another unit |
261
+ | `REF_TAKEN` | 409 | Another live work order has that ref |
262
+ | `NOT_YOURS` | 403 | Another app owns this work order |
263
+ | `NEEDS_COLLECTION_AUTHORITY` | 403 | The function runs as the caller |
264
+ | `REASON_REQUIRED` | 400 | This change needs a reason |
265
+ | `BELOW_ZERO`, `STAGE_CLOSED`, `STAGE_IN_USE`, `NO_SUCH_STAGE` | 409 / 404 | Stage changes |
266
+ | `BOM_LOOP` | 409 | The recipe leads back to itself |
267
+
268
+ ## Testing
269
+
270
+ ```ts
271
+ import { createFunctionTestContext } from '@proveanything/smartlinks/testing'
272
+
273
+ const ctx = createFunctionTestContext({
274
+ def: { trigger: { type: 'http' }, authority: 'collection', capabilities: ['sl:stock:write'] },
275
+ sl: { stock: { move: async (input) => ({ movementId: 'm1', kind: 'move', productId: input.productId, quantity: input.quantity, unit: 'each', replayed: false }) } },
276
+ })
277
+ ```
278
+
279
+ The test context enforces the capability and collection authority, as the platform does. It has no
280
+ in-memory stock or work orders: give stand-ins for the calls your function makes, and any other call
281
+ returns a stub echo.
@@ -65,6 +65,7 @@ The SmartLinks SDK (`@proveanything/smartlinks`) includes comprehensive document
65
65
  | **Host Dependency Contract (R5)** | `docs/host-dependency-contract.md` | The libraries the host provides (React 19, Router 7, Radix, liquidjs, …), the externalise-don't-bundle rule + Vite config, and React-18 backwards-compat |
66
66
  | **CSS Baseline** (`sl-baseline` v1) | `docs/css-baseline.md` | A small, frozen, `sl-`-namespaced set of structural helpers (layout, spacing, responsive flow, type scale, motion) the SDK ships (`@proveanything/smartlinks/baseline.css`) and the host guarantees — a teachable floor for apps + AI content. No colours/fonts/components. Opt-in via `meta.cssBaseline` |
67
67
  | **Deep Linking** | `docs/deep-link-discovery.md` | URL state management, navigable states, portal menus, AI nav |
68
+ | **Admin Views** | `docs/admin-views.md` | The admin side's screens by name (`adminViews`): the app's side menu, Studio's menu and the assistant; host → app `smartlinks:navigate`; `chrome=none` |
68
69
  | **Portal Back Button** | `docs/portal-back-button.md` | Hierarchy-aware "up" navigation inside embedded apps |
69
70
  | **Portal Request Action** | `docs/portal-request-action.md` | Triggering portal built-in actions (__qrScanner, __share, __logout, etc.) from sub-apps |
70
71
  | **Interactions** | `docs/interactions.md` | Business events, outcomes, voting, competitions, and journey triggers |
@@ -89,6 +90,8 @@ The SmartLinks SDK (`@proveanything/smartlinks`) includes comprehensive document
89
90
  | **appConfig / Feature Flags** | `docs/appConfig.md` | `appConfig` settings contract — installed apps, `system.features`/`entitledAppGroups`/`meters`, `isFeatureEnabled()` helper |
90
91
  | **App Objects** | `docs/app-objects.md` | Queryable domain objects — `app.records` / `app.cases` / `app.threads`: JSONB zones, visibility, policies, aggregations |
91
92
  | **Bookings** | `docs/bookings.md` | Slots, bookings and allocations for events and appointments: no double-booking, holds, per-app public rules, `utils.freeTimes` |
93
+ | **User groups** | `docs/user-groups.md` | Who may do what: named lists of people (staff who aren't admins, third parties), `userGroups` on a server function, `ctx.caller.userGroups`, `userGroups.mine()` |
94
+ | **Operations** | `docs/operations.md` | Factory floor and warehouse: work orders with stages, stock as quantities in containers, movements, bills of materials, made-from, sales and purchase orders, and a product's position (on hand, on order, needed, when it runs short) |
92
95
  | **App Data Storage** | `docs/app-data-storage.md` | Decision guide: pick between `appConfiguration` / `userAppData` / `app.records` |
93
96
  | **Attestations** | `docs/attestations.md` | Postgres attestations API (proof-level user/admin data; replaces the legacy Firestore path) |
94
97
  | **Caching** | `docs/caching.md` | SDK GET cache tiers + TTLs, `invalidateCache({ exact })`, and `force`/push guidance |
@@ -134,6 +134,19 @@ This decides what `ctx.sl` can do.
134
134
  `authority` **defaults to `caller`** — secure by default. `event`- and `cron`-triggered
135
135
  functions have no external caller, so they always run as `collection`.
136
136
 
137
+ ### Limiting it to some people: `userGroups`
138
+
139
+ An `http` function can name the [user groups](user-groups.md) allowed to call it:
140
+
141
+ ```jsonc
142
+ "userGroups": ["qc-controller", "manager"] // the caller must be in at least one
143
+ ```
144
+
145
+ The platform checks this before your code runs. A signed-in caller in none of them gets
146
+ `403 NOT_IN_USER_GROUP`; an anonymous one gets `401 SIGN_IN_REQUIRED`; a collection admin always
147
+ passes. Inside any function, `ctx.caller.userGroups` lists the caller's own keys for finer rules.
148
+ `userGroups` doesn't replace `elevated: true` on a `public` + `collection` function.
149
+
137
150
  ### The combinations
138
151
 
139
152
  - **`http` + `admin` + `caller`** — a delegated admin function; runs as the signed-in admin.
@@ -203,6 +216,7 @@ interface ServerFunctionContext {
203
216
  origin?: string | null // http
204
217
  ip?: string | null // http
205
218
  via: 'http' | 'event' | 'cron'
219
+ userGroups: readonly string[] // keys of the user groups the caller is in ([] when anonymous)
206
220
  }
207
221
 
208
222
  /** Outbound HTTP — present only if you declared `network` (host-scoped if `network:<host>`). */
@@ -514,6 +528,10 @@ Prefer the platform primitives above over a dependency; when you do need one, pi
514
528
  | Read ANOTHER app's data (as the caller may see it) | `ctx.sl.app('other-app').data.get()` — caller-authority, this collection, public-filtered, read-only | `sl:data:read` |
515
529
  | Guarantee a UNIQUE claim (one entry per tag, one-per-user, idempotency key, a number nobody else holds) | `ctx.sl.appRecords.claim({ …, singletonPer, customId })` → `{ record, created, conflict? }` — see below | `sl:records:write` |
516
530
  | Hand out the next number (tickets, order numbers) | `ctx.sl.counters.next('tickets')` — atomic, distinct per caller | `sl:data:write` |
531
+ | Track a job through its stages (a production job, a repair, a fulfilment) | `ctx.sl.workOrders` — the shared work order; stages, holds, progress → `operations.md` | `sl:workorders:write` |
532
+ | Know how much of something there is and where; move, allocate, hold or count it | `ctx.sl.stock` — quantities in containers, changed by movements, never below zero → `operations.md` | `sl:stock:write` |
533
+ | Ask whether you will run short, and when | `ctx.sl.stock.position({ productId, horizonDays })` — on hand, on order, being made, needed, first short day | `sl:stock:read` |
534
+ | Say what a product is made of, or what a batch really used | `ctx.sl.boms`, `ctx.sl.madeFrom` → `operations.md` | `sl:boms:write`, `sl:madefrom:write` |
517
535
  | Change numbers in a record (stock, counts, balances) without losing updates | `ctx.sl.appRecords.adjust(id, { qty: -5 }, { atLeast: { qty: 0 } })` — in place, conditions checked after the change | `sl:records:write` |
518
536
  | Several record writes that land together or not at all (a stock move) | `ctx.sl.transaction([ops], { idempotencyKey })` — see below | `sl:records:write` |
519
537
  | Totals: stock per location, forecast per SKU | `ctx.sl.appRecords.aggregate({ groupBy: ['data.location'], metrics: ['sum:qty'] })` | `sl:records:read` |
@@ -0,0 +1,168 @@
1
+ # User groups
2
+
3
+ A **user group** is a named list of people in a collection: "QC Controllers", "Warehouse", "Approved
4
+ partners". Use them to say who may do what, for staff who aren't collection admins and for third
5
+ parties alike.
6
+
7
+ > There is no separate "roles" object. A role is a user group: "Sam has the QC role" and "Sam is in
8
+ > the QC Controllers user group" are the same fact.
9
+
10
+ ## The three things you do with them
11
+
12
+ | You want to… | Use |
13
+ |---|---|
14
+ | **Protect** an action, so only some people can do it | `userGroups` on the server function's declaration |
15
+ | **Decide** something finer inside a function | `ctx.caller.userGroups` |
16
+ | **Show or hide** a button or a screen | `userGroups.mine(collectionId)`, or a `group` condition |
17
+
18
+ Only the first two protect anything. Hiding a button doesn't stop someone calling the function behind
19
+ it, so limit the function as well.
20
+
21
+ ## A user group
22
+
23
+ ```ts
24
+ {
25
+ id: 'k3Jd…', // random, never changes
26
+ key: 'qc-controller', // the name code uses; set once, kept through a rename
27
+ name: 'QC Controllers', // what people see; free to change
28
+ description: 'Sign off finished batches',
29
+ members: ['uid_1', 'uid_2'] // user ids
30
+ }
31
+ ```
32
+
33
+ - **Refer to user groups by `key`** in code and manifests, never by name or id.
34
+ - A key is lowercase letters, digits and hyphens. It's made from the name when you don't give one
35
+ ("QC Controllers" → `qc-controllers`), and it's unique in the collection.
36
+ - Members are people who sign in: on the site's own login, or with a SmartLinks account.
37
+ - Collection admins pass every user group check. They don't need adding.
38
+
39
+ ## Limit a server function
40
+
41
+ In the manifest (see [server-functions.md](server-functions.md)):
42
+
43
+ ```jsonc
44
+ {
45
+ "name": "releaseBatch",
46
+ "trigger": { "type": "http", "methods": ["POST"] },
47
+ "visibility": "public",
48
+ "authority": "collection",
49
+ "elevated": true,
50
+ "userGroups": ["qc-controller", "manager"], // in at least ONE of these
51
+ "capabilities": ["sl:records:write"]
52
+ }
53
+ ```
54
+
55
+ The platform checks this before any of your code runs:
56
+
57
+ | Caller | Result |
58
+ |---|---|
59
+ | In one of the user groups, or a collection admin | The function runs |
60
+ | Signed in, in none of them | `403 { error: 'NOT_IN_USER_GROUP' }` |
61
+ | Not signed in | `401 { error: 'SIGN_IN_REQUIRED' }` |
62
+
63
+ - `http` functions only: `event` and `cron` functions have no caller.
64
+ - `userGroups` doesn't replace `elevated: true` on a `public` + `collection` function. Declare both.
65
+
66
+ ## Decide inside a function
67
+
68
+ Every function sees the caller's keys:
69
+
70
+ ```ts
71
+ export async function adjustQuantity(ctx, event) {
72
+ const isManager = ctx.caller.userGroups.includes('manager')
73
+ if (event.body.delta > 100 && !isManager) {
74
+ return new Response(JSON.stringify({ error: 'Over 100 needs a manager' }), { status: 403 })
75
+ }
76
+ // …
77
+ }
78
+ ```
79
+
80
+ `ctx.caller.userGroups` is `[]` when nobody is signed in, and for `event` / `cron` runs.
81
+
82
+ ## Show or hide in a screen
83
+
84
+ ```ts
85
+ import { userGroups } from '@proveanything/smartlinks'
86
+
87
+ const { userGroups: mine } = await userGroups.mine(collectionId)
88
+ const showReleaseButton = mine.includes('qc-controller')
89
+ ```
90
+
91
+ - `mine()` returns `{ userGroups: string[], userGroupIds: string[] }`: keys for code, and ids for
92
+ older saved conditions. Both are empty when nobody is signed in.
93
+ - It is never cached, so a change an admin makes shows on the next call.
94
+ - A person can only ask about themselves.
95
+
96
+ With conditions (see [utils.md](utils.md)):
97
+
98
+ ```ts
99
+ const { userGroups: keys, userGroupIds } = await userGroups.mine(collectionId)
100
+
101
+ await utils.validateCondition({
102
+ condition: { type: 'and', conditions: [{ type: 'user', userType: 'group', groupIds: ['qc-controller'] }] },
103
+ user: { valid: true, uid, groups: [...keys, ...userGroupIds] },
104
+ })
105
+ ```
106
+
107
+ ## Manage them (admin)
108
+
109
+ ```ts
110
+ const qc = await userGroups.create(collectionId, { name: 'QC Controllers' }) // key: 'qc-controllers'
111
+
112
+ await userGroups.addMember(collectionId, qc.id, { email: 'sam@example.com', name: 'Sam' })
113
+ await userGroups.addMember(collectionId, qc.id, { userId: 'uid_2' })
114
+ await userGroups.removeMember(collectionId, qc.id, 'uid_2')
115
+
116
+ await userGroups.members(collectionId, qc.id) // [{ uid, name, email }]
117
+ await userGroups.ofUser(collectionId, 'uid_1') // [{ id, key, name }]
118
+ await userGroups.list(collectionId)
119
+ await userGroups.update(collectionId, qc.id, { name: 'Quality control' }) // key stays 'qc-controllers'
120
+ await userGroups.remove(collectionId, qc.id)
121
+ ```
122
+
123
+ - **Add and remove one person at a time** with `addMember` / `removeMember`. Saving a whole `members`
124
+ list through `update` can overwrite a change someone else made at the same moment.
125
+ - Adding by email finds the person in the collection's logins, or adds them. No welcome email is sent.
126
+ - A change takes up to a minute to reach function checks.
127
+
128
+ Errors: `KEY_INVALID`, `KEY_TAKEN` (409), `KEY_FIXED` (409, a key can't be changed once set),
129
+ `MISSING_FIELDS`, `NOT_FOUND`.
130
+
131
+ ## Who changed what
132
+
133
+ Every change is recorded: a user group created, renamed or deleted, and each person added or removed,
134
+ with the admin who did it and when.
135
+
136
+ ```ts
137
+ await userGroups.history(collectionId, { userGroupId: qc.id }) // one user group
138
+ await userGroups.history(collectionId, { userId: 'uid_1' }) // everything about one person
139
+ // [{ at, type: 'usergroup.member-added', actorId: 'uid_admin', data: { key: 'qc-controllers', userId: 'uid_1', … } }]
140
+ ```
141
+
142
+ It covers the last 30 days unless you pass `from` / `to` (up to 400 days), and takes about a second.
143
+ Entries hold ids only, never names or emails.
144
+
145
+ ## In a site
146
+
147
+ It works the same way. A site's functions run in the site's own worker, and the site's function
148
+ runtime applies `userGroups` from `public/app.manifest.json` before your handler runs, with the same
149
+ `401` / `403` answers. `ctx.caller.userId` and `ctx.caller.userGroups` are filled in for a signed-in
150
+ visitor.
151
+
152
+ A site made before this existed has no `src/site/lib/fn-access.ts`. There, `userGroups` in the
153
+ manifest is ignored until the site is updated.
154
+
155
+ ## Testing
156
+
157
+ ```ts
158
+ import { createFunctionTestContext } from '@proveanything/smartlinks/testing'
159
+
160
+ const ctx = createFunctionTestContext({
161
+ def: { trigger: { type: 'http' }, capabilities: ['sl:records:write'] },
162
+ caller: { userId: 'sam', userGroups: ['qc-controller'] },
163
+ })
164
+ ctx.caller.userGroups // ['qc-controller']
165
+ ```
166
+
167
+ The test context gives your handler the caller you describe. It doesn't apply the declaration's
168
+ `userGroups` limit: that check happens on the platform before your handler is called.