@proveanything/smartlinks 2.1.16 → 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 (60) hide show
  1. package/dist/adminViews.d.ts +85 -0
  2. package/dist/adminViews.js +259 -0
  3. package/dist/api/errors.d.ts +10 -0
  4. package/dist/api/errors.js +17 -0
  5. package/dist/api/index.d.ts +3 -0
  6. package/dist/api/index.js +3 -0
  7. package/dist/api/operations.d.ts +36 -0
  8. package/dist/api/operations.js +56 -0
  9. package/dist/api/order.d.ts +12 -1
  10. package/dist/api/order.js +15 -0
  11. package/dist/api/partner.d.ts +7 -1
  12. package/dist/api/partner.js +9 -0
  13. package/dist/api/userGroups.d.ts +78 -0
  14. package/dist/api/userGroups.js +124 -0
  15. package/dist/docs/API_SUMMARY.md +699 -46
  16. package/dist/docs/admin-views.md +125 -0
  17. package/dist/docs/app-manifest.md +2 -0
  18. package/dist/docs/app-objects.md +23 -0
  19. package/dist/docs/operations.md +281 -0
  20. package/dist/docs/overview.md +3 -0
  21. package/dist/docs/server-functions.md +106 -0
  22. package/dist/docs/tag-ranges.md +8 -0
  23. package/dist/docs/user-groups.md +168 -0
  24. package/dist/docs/utils.md +17 -0
  25. package/dist/http.js +4 -0
  26. package/dist/iframeResponder.d.ts +15 -0
  27. package/dist/iframeResponder.js +39 -1
  28. package/dist/index.d.ts +2 -0
  29. package/dist/index.js +2 -0
  30. package/dist/openapi.yaml +1426 -276
  31. package/dist/testing/index.d.ts +29 -0
  32. package/dist/testing/index.js +178 -1
  33. package/dist/types/appManifest.d.ts +170 -0
  34. package/dist/types/appObjects.d.ts +22 -1
  35. package/dist/types/claimSet.d.ts +2 -0
  36. package/dist/types/clientLog.d.ts +46 -0
  37. package/dist/types/clientLog.js +1 -0
  38. package/dist/types/containers.d.ts +8 -0
  39. package/dist/types/iframeResponder.d.ts +16 -1
  40. package/dist/types/index.d.ts +3 -0
  41. package/dist/types/index.js +3 -0
  42. package/dist/types/operations.d.ts +598 -0
  43. package/dist/types/operations.js +8 -0
  44. package/dist/types/order.d.ts +35 -6
  45. package/dist/types/userGroups.d.ts +103 -0
  46. package/dist/types/userGroups.js +5 -0
  47. package/dist/utils/conditions.d.ts +7 -0
  48. package/dist/utils/conditions.js +16 -9
  49. package/docs/API_SUMMARY.md +699 -46
  50. package/docs/admin-views.md +125 -0
  51. package/docs/app-manifest.md +2 -0
  52. package/docs/app-objects.md +23 -0
  53. package/docs/operations.md +281 -0
  54. package/docs/overview.md +3 -0
  55. package/docs/server-functions.md +106 -0
  56. package/docs/tag-ranges.md +8 -0
  57. package/docs/user-groups.md +168 -0
  58. package/docs/utils.md +17 -0
  59. package/openapi.yaml +1426 -276
  60. 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
 
@@ -807,6 +807,29 @@ await app.records.upsert(collectionId, appId, {
807
807
  // customId is stored for later reverse-lookup via ?customId=&sourceSystem=
808
808
  ```
809
809
 
810
+ ### Totals over data (sum, average, min, max)
811
+
812
+ Records also total the numbers in their `data`, grouped by top-level data keys, with data filters and
813
+ numeric ranges. Stock per location, forecast per SKU:
814
+
815
+ ```typescript
816
+ const stock = await app.records.aggregate(collectionId, appId, {
817
+ groupBy: ['data.location'], // up to 5: columns or 'data.<key>'
818
+ metrics: ['count', 'sum:qty', 'min:qty'], // count; sum: / avg: / min: / max: + a data key
819
+ filters: {
820
+ record_type: 'bin',
821
+ data: { warehouse: ['north', 'south'] }, // exact match, one value or any of several
822
+ dataRange: { qty: { gt: 0 } }, // gte / gt / lte / lt, numbers only
823
+ updated_at: { gte: '2026-11-01T00:00:00Z' },
824
+ },
825
+ }, true)
826
+ // stock.groups → [{ 'data.location': 'A1', count: 12, sum_qty: 340, min_qty: 2 }, …]
827
+ ```
828
+
829
+ Values that aren't numbers are left out of sums and averages. To CHANGE numbers safely (stock moves,
830
+ counts), use a server function: `ctx.sl.appRecords.adjust` and `ctx.sl.transaction`
831
+ ([server-functions.md](server-functions.md)).
832
+
810
833
  ### Counts by Record Type
811
834
 
812
835
  `aggregate()` returns counts grouped by `record_type` in a single round-trip — no separate endpoint needed:
@@ -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,14 @@ 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` |
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` |
536
+ | Several record writes that land together or not at all (a stock move) | `ctx.sl.transaction([ops], { idempotencyKey })` — see below | `sl:records:write` |
537
+ | Totals: stock per location, forecast per SKU | `ctx.sl.appRecords.aggregate({ groupBy: ['data.location'], metrics: ['sum:qty'] })` | `sl:records:read` |
538
+ | Keep a history of what happened (stock moves, counts) without growing your records | `ctx.sl.history.log('stock.moved', {…})`, or a `log` op in a transaction; read with `ctx.sl.history.query({…})` | `sl:history:write` / `sl:history:read` |
517
539
  | Check a tapped tag is real | `ctx.sl.tags.resolve(proofId)` → `{ id, claimSetId, code }` or `null` | `sl:tags:read` |
518
540
  | Put a visitor's details on a contact | `ctx.sl.contacts.upsert({ email, firstName, … })` → `{ contactId, created }` (fills empty fields only) | `sl:contacts:write` |
519
541
  | Record "they did X" | `ctx.sl.interactions.record({ interactionId, contactId, outcome, metadata })` | `sl:interactions:write` |
@@ -579,6 +601,90 @@ reads the last value handed out (`null` before the first). Name a new counter to
579
601
  `customId: String(n)`. If the claim says `conflict: 'customId'`, take `next()` again. A failed or raced
580
602
  attempt only leaves a gap — never a duplicate.
581
603
 
604
+ ### `appRecords.adjust(id, by, { atLeast?, atMost? })` — numbers that never lose an update
605
+
606
+ Adds to numbers in a record's `data` in ONE statement, so twenty scanners taking from the same bin at
607
+ once each land: no read-then-write, no lost counts. A missing value counts as 0. `atLeast` / `atMost` are
608
+ checked on the values **after** the change, inside the same statement:
609
+
610
+ ```ts
611
+ // Take 5 from bin A — refused (nothing changes) if it would go below zero.
612
+ await ctx.sl.appRecords.adjust(binA, { qty: -5 }, { atLeast: { qty: 0 } })
613
+ ```
614
+
615
+ Refusals carry `code`: `NOT_FOUND` (not this app's record in this collection, or deleted), `NOT_A_NUMBER`
616
+ (the key holds something else), `CONDITION_FAILED` (409, with the `current` values). Only top-level data
617
+ keys; a key named only in a condition is checked as it stands.
618
+
619
+ ### `transaction(ops, { idempotencyKey? })` — all or nothing
620
+
621
+ Several writes as ONE transaction: every op lands, or none does. The classic: take stock out of bin A,
622
+ put it on order line B, and log the move.
623
+
624
+ ```ts
625
+ const { results, replayed } = await ctx.sl.transaction([
626
+ { op: 'adjust', recordId: binA, by: { qty: -5 }, atLeast: { qty: 0 } },
627
+ { op: 'adjust', recordId: orderLineB, by: { picked: 5 } },
628
+ { op: 'create', record: { recordType: 'movement', data: { from: binA, to: orderLineB, qty: 5 } } },
629
+ ], { idempotencyKey: scanId })
630
+ ```
631
+
632
+ - Ops: `create` (`record`), `update` (`recordId`, `fields`), `adjust` (`recordId`, `by`, `atLeast?`,
633
+ `atMost?`), `delete` (`recordId`), `log` (`type`, `data`, `entityId?`: a history event, see below).
634
+ Up to 50, run in order. This app's records in this collection only.
635
+ - A failing op rolls everything back. The error says which op (`opIndex`) and why (its `code`).
636
+ - Change events and realtime updates go out only after the transaction commits, never for a rollback.
637
+ - **`idempotencyKey`** ("this was already done"): recorded in the same commit, with what was written
638
+ (ids only). The same key again within 7 days doesn't write; it returns those records as they are now,
639
+ with `replayed: true`. So a handheld that retries after a dropped signal never moves stock twice. Two
640
+ calls with one key at the same moment: one commits, the other replays it. A transaction that failed
641
+ leaves its key free, so a retry can still succeed.
642
+ - Use the scan's or the request's own id as the key (one key = one intended change).
643
+ - Browser code never writes stock directly: a warehouse screen calls your function.
644
+
645
+ ### `history` — what happened, kept without growing your records
646
+
647
+ Keep **current state** in records (a bin's quantity, an order's status) and **what happened** in the app's
648
+ history: append-only events in SmartLinks' analytics store, kept for good, cheap however many there
649
+ are. Picking every order line for years would bloat records; as history it costs nothing operational.
650
+
651
+ ```ts
652
+ // In a transaction: commits with the stock change, or not at all.
653
+ await ctx.sl.transaction([
654
+ { op: 'adjust', recordId: binA, by: { qty: -5 }, atLeast: { qty: 0 } },
655
+ { op: 'log', type: 'stock.moved', entityId: binA, data: { sku: 'EDP-50', from: 'A1', to: orderId, qty: 5 } },
656
+ ], { idempotencyKey: scanId })
657
+
658
+ // On its own:
659
+ await ctx.sl.history.log('count.taken', { bin: 'A1', counted: 40, expected: 42 }, { entityId: binA })
660
+
661
+ // Reading back: this app's events in this collection, newest first (default last 30 days, max 400).
662
+ const moves = await ctx.sl.history.query({ types: 'stock.moved', entityId: binA, limit: 20 })
663
+ // → [{ id, at, type, entityId, data, actorType, actorId }]
664
+ ```
665
+
666
+ - `type`: lowercase letters, digits and `. _ -` (`stock.moved`). `data`: up to 32 KB, so **log a summary**:
667
+ one line for "5 of EDP-50", not five; one line for an RFID count, not one per tag.
668
+ - Delivery takes seconds and is retried until it lands; a logged event is never lost. A query reads the
669
+ analytics store, so expect about a second: right for a history panel, not for a hot path.
670
+ - The person who called your function is recorded as the actor.
671
+
672
+ ### `appRecords.aggregate(params)` — totals
673
+
674
+ Counts and sums over your app's records, worked out in the database:
675
+
676
+ ```ts
677
+ await ctx.sl.appRecords.aggregate({
678
+ groupBy: ['data.location', 'data.sku'], // columns, or top-level data keys
679
+ metrics: ['count', 'sum:qty'], // sum: / avg: / min: / max: over data numbers
680
+ filters: { record_type: 'bin', data: { warehouse: 'north' }, dataRange: { qty: { gt: 0 } } },
681
+ })
682
+ // → { groups: [{ 'data.location': 'A1', 'data.sku': 'EDP-50', count: 3, sum_qty: 42 }, …] }
683
+ ```
684
+
685
+ Non-numbers are ignored by `sum`/`avg`/`min`/`max`. The same request works from the browser through
686
+ `app.records.aggregate` (admin) — see [app-objects.md](app-objects.md).
687
+
582
688
  ### `tags.resolve(id)` — is this tap real?
583
689
 
584
690
  A tap hands your app the virtual-proof id `<claimSetId>-<code>`. `resolve` returns
@@ -76,6 +76,14 @@ has a `kind`:
76
76
 
77
77
  Status reads `open` or `group` for these (and `assigned` once every member of a group is assigned).
78
78
 
79
+ ## When a tag fails on the phone
80
+
81
+ `errors.report({ app: 'sidekick', operation: 'tag.program', errorCode: 'TAG_LOST', message, entityType: 'tag',
82
+ entityId: chipUid, labels: { claimSetId, code, failedStep }, context: { steps, timings, hostLog } })` keeps what
83
+ the phone saw in the platform's one error log (never a key: fields that look like one are dropped).
84
+ `partner.tagAttempts(partner.id, chipUid)` and the platform's tag lookup read it back, newest first, so a
85
+ failing chip can be understood by its UID without the phone's console.
86
+
79
87
  ## The printer file
80
88
 
81
89
  One row per tag, in index order. The manufacturer fills in `UID` and sends the same file back; rows are