@proveanything/smartlinks 2.1.22 → 2.1.23

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.
@@ -116,7 +116,7 @@ export async function cardUnanswered(ctx): Promise<AdminCardPayload> {
116
116
  | `trend` | `{ direction: 'up'\|'down'\|'flat', label?, good? }` — `good` picks the colour |
117
117
  | `status` | `{ tone: 'ok'\|'attention'\|'neutral'\|'error', text }` — `attention`/`error` also go to the To do strip |
118
118
  | `progress` | `{ done, total, label? }` — a progress bar |
119
- | `items` | Up to 5 rows `{ title, subtitle?, meta?, path? }` |
119
+ | `items` | Up to 5 rows `{ title, subtitle?, meta?, path?, image? }` — `image` is an https picture shown small beside the row (a product photo); an ISO-timestamp `meta` reads as a short date |
120
120
  | `todo` | `[{ text, action? }]` — collected into the dashboard's To do strip |
121
121
  | `actions` | Up to 2 buttons `{ label, path? \| url? }` — `path` opens your app's admin at that path |
122
122
  | `empty` | `{ text, action? }` — shown instead of the body when there's nothing yet |
@@ -0,0 +1,187 @@
1
+ # The standard query
2
+
3
+ One request body to **filter, sort, page, count, total and follow links**, the same on every resource
4
+ that takes it. Learn it once.
5
+
6
+ | Resource | Function | Call |
7
+ |---|---|---|
8
+ | Proofs | `proof.query(collectionId, body)` | `POST /admin/collection/:id/proof/query` |
9
+ | Contacts | `contact.query(collectionId, body)` | `POST /admin/collection/:id/contacts/query` |
10
+ | Products | `products.standardQuery(collectionId, body)` | `POST /admin/collection/:id/products/standard/query` |
11
+ | App records | `app.records.query(collectionId, appId, body)` | `POST /admin/collection/:id/app/:appId/records/query` |
12
+
13
+ All are admin calls and read-only. Products also keep `products.query`, whose own body is unchanged;
14
+ `standardQuery` sits beside it.
15
+
16
+ Each resource says what its query can use: `proof.queryFields`, `contact.queryFields`,
17
+ `products.standardQueryFields`, `app.records.queryFields` (a `GET` on the same address). It returns the
18
+ fields, what each can be used for, and the links.
19
+
20
+ ## The body
21
+
22
+ Everything is optional. An empty body returns the first page.
23
+
24
+ ```typescript
25
+ interface StandardQuery {
26
+ where?: QueryWhere
27
+ orderBy?: Array<Record<string, 'asc' | 'desc'>>
28
+ limit?: number // rows: 1–200 (default 50); groups: 1–500
29
+ cursor?: string | null // nextCursor from the previous page
30
+ select?: string[]
31
+ count?: boolean
32
+ groupBy?: string[]
33
+ aggregates?: Record<string, QueryAggregate>
34
+ expand?: string[] | Record<string, string[] | true>
35
+ }
36
+ ```
37
+
38
+ It answers in one of two shapes:
39
+
40
+ ```typescript
41
+ { items: [...], nextCursor: string | null, count?: number } // rows
42
+ { groups: [...], more: boolean } // with groupBy and/or aggregates
43
+ ```
44
+
45
+ ## Filtering: `where`
46
+
47
+ `field: value` means "equal to". `field: { op: value }` uses a comparison. Every entry must hold.
48
+
49
+ | Comparison | Meaning |
50
+ |---|---|
51
+ | `eq`, `ne` | equal, not equal |
52
+ | `gt`, `gte`, `lt`, `lte` | more / less than (numbers, dates, text) |
53
+ | `in`, `nin` | one of / none of a list (1–100 values) |
54
+ | `contains`, `startsWith` | text, in any letter case |
55
+ | `isNull` | `true`: empty; `false`: has a value |
56
+ | `has`, `hasAny`, `hasAll` | a list field (a contact's `tags`) holds one / any / all |
57
+
58
+ Combine with `and`, `or` and `not`, nested up to 4 levels:
59
+
60
+ ```typescript
61
+ await proof.query(collectionId, {
62
+ where: {
63
+ createdAt: { gte: '2026-01-01', lt: '2026-02-01' },
64
+ or: [{ productId: 'toaster' }, { and: [{ productId: 'kettle' }, { claimable: true }] }],
65
+ },
66
+ })
67
+ ```
68
+
69
+ Dates are ISO 8601 text (`"2026-01-31"` or `"2026-01-31T09:00:00Z"`).
70
+
71
+ ### Product facets
72
+
73
+ A product's `facets` are filtered by key. Name the facet by its key or its name, and the value by its
74
+ key or its name, in any letter case. Every facet given must match.
75
+
76
+ ```typescript
77
+ await products.standardQuery(collectionId, {
78
+ where: { facets: { brand: 'Breville', category: { in: ['Toasters', 'Kettles'] } } },
79
+ })
80
+ ```
81
+
82
+ ### An app's own fields: paths into a record
83
+
84
+ An app record keeps the app's own fields inside `data` (and `owner`, `admin`). Reach one by path, as a
85
+ field name:
86
+
87
+ ```typescript
88
+ await app.records.query(collectionId, appId, {
89
+ where: { recordType: 'work_order', 'data.status': 'released', 'data.qty': { gt: 10 } },
90
+ select: ['ref', 'data.status', 'data.line.name'],
91
+ })
92
+ ```
93
+
94
+ - A path can be filtered, selected, grouped and totalled. It cannot be sorted on.
95
+ - It reads as text. Compared with a **number** (`gt`, `gte`, `lt`, `lte`), and in `sum`, `avg`, `min`
96
+ and `max`, it is read as a number; a value that is not a number is left out, it does not fail the
97
+ query.
98
+ - A path follows named fields, up to 4 deep. It does not reach into lists.
99
+ - The documents themselves (`data`, `owner`, `admin`) are returned only when selected.
100
+
101
+ ## Sorting and paging
102
+
103
+ `orderBy` takes up to 3 `{ field: 'asc' | 'desc' }`. Only fields that are never empty can be sorted
104
+ on (ask `queryFields`). Pass the answer's `nextCursor` as `cursor` for the next page, with the **same**
105
+ `where` and `orderBy`; a cursor from a different query is refused.
106
+
107
+ ```typescript
108
+ let cursor: string | null = null
109
+ do {
110
+ const page = await contact.query(collectionId, { orderBy: [{ createdAt: 'asc' }], limit: 200, cursor })
111
+ if (!('items' in page)) break
112
+ // …use page.items
113
+ cursor = page.nextCursor
114
+ } while (cursor)
115
+ ```
116
+
117
+ `count: true` adds how many rows match `where` in all, not just on this page.
118
+
119
+ ## Totals: `groupBy` and `aggregates`
120
+
121
+ ```typescript
122
+ // How many people own each product, and when the latest was registered
123
+ await proof.query(collectionId, {
124
+ where: { userId: { isNull: false } },
125
+ groupBy: ['productId'],
126
+ aggregates: { owners: { countDistinct: 'userId' }, latest: { max: 'createdAt' } },
127
+ })
128
+ // → { groups: [{ productId: 'kettle', owners: 2, latest: '2026-01-06T12:00:00.000Z' }, …], more: false }
129
+ ```
130
+
131
+ - A total is one of `{ count: true }`, `{ countDistinct: field }`, `{ sum | avg | min | max: field }`.
132
+ - `aggregates` without `groupBy` gives one group: the totals over everything matched.
133
+ - Groups come ordered by the first total, largest first, unless `orderBy` names a group field or a
134
+ total. `more: true` means there were more groups than `limit`.
135
+ - A grouped query has no pages, no `select` and no `expand`.
136
+
137
+ ## Following a link: `expand`
138
+
139
+ `expand` returns the thing a row points at, inside the row, under the link's name.
140
+
141
+ ```typescript
142
+ await proof.query(collectionId, {
143
+ where: { productId: 'toaster' },
144
+ select: ['id'],
145
+ expand: { product: ['name', 'sku'], owner: ['firstName', 'email'] },
146
+ })
147
+ // → items: [{ id: 'p1', product: { name: 'Breville Toaster', sku: '…' }, owner: { firstName: 'Ana', email: '…' } }]
148
+ ```
149
+
150
+ | Resource | Links |
151
+ |---|---|
152
+ | Proofs | `product`, `owner` (the contact with the owner's login id) |
153
+ | App records | `product`, `contact` |
154
+
155
+ `expand: ['product']` returns the linked thing's usual fields. A link is null when there is nothing
156
+ linked, and also when the linked thing would not be returned by its own query (a deleted product, an
157
+ erased contact). Up to 3 links, one level deep, rows only.
158
+
159
+ ## What is refused
160
+
161
+ A query that asks for something a resource does not offer is refused with status 400 and a plain
162
+ message saying what is allowed:
163
+
164
+ ```json
165
+ { "errorCode": "INVALID_QUERY", "errorText": "There is no field \"colour\" on proofs. Fields: id, productId, …", "at": "where.colour" }
166
+ ```
167
+
168
+ That includes a field that is not offered (anywhere: filter, sort, group or select), an unknown
169
+ comparison, a value of the wrong type, too many rows or values, and nesting that is too deep. A query
170
+ that runs for more than 5 seconds is stopped with `QUERY_TOO_SLOW`: narrow `where`.
171
+
172
+ ## A question across resources
173
+
174
+ "How many people own a Breville toaster, and who registered one most recently?"
175
+
176
+ ```typescript
177
+ const found = await products.standardQuery(collectionId, {
178
+ where: { facets: { brand: 'Breville', category: 'Toasters' } }, select: ['id'],
179
+ })
180
+ const ids = 'items' in found ? found.items.map((p) => String(p.id)) : []
181
+ const where = { productId: { in: ids }, userId: { isNull: false } }
182
+
183
+ const owners = await proof.query(collectionId, { where, aggregates: { owners: { countDistinct: 'userId' } } })
184
+ const latest = await proof.query(collectionId, {
185
+ where, orderBy: [{ createdAt: 'desc' }], limit: 1, expand: { owner: ['firstName', 'lastName'] },
186
+ })
187
+ ```
package/docs/utils.md CHANGED
@@ -670,8 +670,24 @@ await utils.validateCondition({
670
670
  })
671
671
  ```
672
672
 
673
- #### Nested Conditions
674
- Reference other condition sets for reusability:
673
+ #### Saved Conditions (by id)
674
+ A collection keeps **saved conditions**: named rule sets such as "UK only" or "In the stadium", made in Studio or with the `conditions` API. Check one by id and the SDK loads it from the collection by itself (cached for the page):
675
+
676
+ ```typescript
677
+ import { utils, conditions } from '@proveanything/smartlinks'
678
+
679
+ const show = await utils.validateCondition({
680
+ conditionId: 'nfCmuWDY',
681
+ collection: { id: 'col1' },
682
+ user: { valid: true, location: { country: 'GB' } },
683
+ })
684
+
685
+ // Admin: list, create, change, remove
686
+ const all = await conditions.list('col1', true)
687
+ await conditions.create('col1', { title: 'UK only', type: 'and', conditions: [{ type: 'country', countries: ['GB'], contains: true }] })
688
+ ```
689
+
690
+ A rule can also refer to another saved condition, for reuse:
675
691
 
676
692
  ```typescript
677
693
  await utils.validateCondition({
@@ -683,15 +699,13 @@ await utils.validateCondition({
683
699
  passes: true // true = must pass, false = must fail
684
700
  }]
685
701
  },
686
- conditionId: 'mobile-users-condition',
687
- fetchCondition: async (collectionId, conditionId) => {
688
- // Your logic to fetch condition by ID
689
- return { type: 'and', conditions: [...] }
690
- },
691
- collection: { id: 'col1' }
702
+ collection: { id: 'col1' },
692
703
  })
693
704
  ```
694
705
 
706
+ - A saved condition that's switched off (`disabled: true`) passes for everyone; so does one that can't be found.
707
+ - Pass `fetchCondition: async (collectionId, conditionId) => ConditionSet | null` to load them your own way (from data you already have, or in a test).
708
+
695
709
  ### Combining Conditions (AND/OR Logic)
696
710
 
697
711
  ```typescript