@stacksjs/defaults 0.75.569 → 0.75.572

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 (77) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-cms/SKILL.md +1 -1
  3. package/ai/skills/stacks-dashboard/SKILL.md +283 -12
  4. package/ai/skills/stacks-database/SKILL.md +50 -0
  5. package/ai/skills/stacks-http/SKILL.md +33 -2
  6. package/ai/skills/stacks-native/CATALOG.md +8 -8
  7. package/ai/skills/stacks-orm/SKILL.md +20 -10
  8. package/ai/skills/stacks-query-builder/SKILL.md +7 -0
  9. package/app/Actions/Dashboard/Commerce/commerce-sql.ts +1 -1
  10. package/app/Actions/Dashboard/Content/CommentUpdateAction.ts +1 -1
  11. package/app/Actions/Dashboard/Content/PostStoreAction.ts +1 -1
  12. package/app/Actions/Dashboard/Content/PostUpdateAction.ts +1 -1
  13. package/app/Actions/Dashboard/Content/comment-list.ts +2 -2
  14. package/app/Actions/Dashboard/Content/page-list.ts +2 -2
  15. package/app/Actions/Dashboard/Content/post-list.ts +2 -2
  16. package/app/Actions/Dashboard/Infrastructure/InsightsAction.ts +24 -19
  17. package/app/Actions/Dashboard/Infrastructure/log-provider.ts +4 -4
  18. package/app/Actions/Dashboard/Jobs/job-list.ts +1 -1
  19. package/app/Actions/Dashboard/Kanban/BoardShowAction.ts +2 -2
  20. package/app/Actions/Dashboard/Kanban/CardShowAction.ts +3 -3
  21. package/app/Actions/Dashboard/Kanban/card-attachments.ts +1 -1
  22. package/app/Actions/Dashboard/Marketing/marketing-list-records.test.ts +2 -2
  23. package/app/Actions/Dashboard/Marketing/marketing-list-records.ts +4 -4
  24. package/app/Actions/Dashboard/Models/ModelShowAction.ts +42 -43
  25. package/app/Actions/Dashboard/Models/ModelUpdateAction.ts +17 -3
  26. package/app/Actions/Dashboard/Models/model-filters.ts +429 -0
  27. package/app/Actions/Dashboard/Models/model-switches.ts +159 -0
  28. package/app/Actions/Dashboard/Models/model-write.ts +6 -0
  29. package/app/Actions/Dashboard/Notifications/NotificationDeliveryOverviewAction.ts +1 -1
  30. package/app/Actions/Dashboard/Queries/query-list.ts +1 -1
  31. package/app/Actions/Dashboard/Queue/queue-stats.ts +2 -2
  32. package/app/Actions/Dashboard/named-search.ts +1 -1
  33. package/app/Models/Comment.ts +3 -3
  34. package/app/Models/Content/Post.ts +3 -3
  35. package/app/Models/EmailList.ts +8 -6
  36. package/app/Models/Subscriber.ts +2 -0
  37. package/app/Models/Team.ts +2 -0
  38. package/app/Models/User.ts +3 -0
  39. package/functions/dashboard-model-filters.ts +219 -0
  40. package/functions/dashboard-model-record.ts +42 -8
  41. package/ide/vscode/package.json +1 -1
  42. package/package.json +3 -3
  43. package/resources/components/Dashboard/Commerce/CommerceCategoryDialog.stx +3 -1
  44. package/resources/components/Dashboard/Commerce/CommerceCouponDialog.stx +3 -1
  45. package/resources/components/Dashboard/Commerce/CommerceGiftCardDialog.stx +9 -3
  46. package/resources/components/Dashboard/Commerce/CommerceManufacturerDialog.stx +3 -4
  47. package/resources/components/Dashboard/Commerce/CommerceProductDialog.stx +3 -1
  48. package/resources/components/Dashboard/Commerce/CommerceReviewEditDialog.stx +6 -8
  49. package/resources/components/Dashboard/Commerce/CommerceTaxDialog.stx +6 -14
  50. package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +3 -7
  51. package/resources/components/Dashboard/Commerce/Delivery/DigitalDeliveryDialog.stx +6 -2
  52. package/resources/components/Dashboard/Content/BlogPostEditorDialog.stx +2 -8
  53. package/resources/components/Dashboard/Content/PageEditorDialog.stx +3 -7
  54. package/resources/components/Dashboard/Content/PostEditorDialog.stx +3 -4
  55. package/resources/components/Dashboard/Data/DataModelRecords.stx +12 -75
  56. package/resources/components/Dashboard/Data/DataStatCards.stx +110 -0
  57. package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +20 -36
  58. package/resources/components/Dashboard/Marketing/MarketingListDialog.stx +7 -14
  59. package/resources/components/Dashboard/Marketing/MarketingListsDashboard.stx +3 -2
  60. package/resources/components/Dashboard/Models/ModelFieldInputs.stx +10 -13
  61. package/resources/components/Dashboard/Models/ModelFilterPanel.stx +166 -0
  62. package/resources/components/Dashboard/Models/ModelRecordDetail.stx +18 -0
  63. package/resources/components/Dashboard/Models/ModelRecordEdit.stx +3 -2
  64. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +96 -29
  65. package/resources/components/Dashboard/Models/ModelRegion.stx +25 -0
  66. package/resources/components/Dashboard/Models/ModelRegionFor.stx +31 -0
  67. package/resources/components/Dashboard/Operations/RecoveryDestinationDialog.stx +2 -2
  68. package/resources/components/Dashboard/Operations/RecoveryPolicyDialog.stx +3 -1
  69. package/resources/components/Dashboard/Operations/RecoveryRestoreDialog.stx +3 -1
  70. package/resources/components/Dashboard/Settings/AppearanceSettingsDashboard.stx +11 -14
  71. package/resources/components/Dashboard/Settings/SettingsDashboard.stx +6 -9
  72. package/resources/components/Dashboard/UI/Toggle.stx +16 -12
  73. package/resources/functions/dashboard/regions.ts +113 -0
  74. package/resources/functions/dashboard/sidebar.ts +2 -0
  75. package/views/dashboard/composables/useModelList.ts +52 -0
  76. package/views/dashboard/composables/useModelRecord.ts +46 -0
  77. package/views/dashboard/stores/model-page.ts +105 -0
@@ -0,0 +1,429 @@
1
+ /**
2
+ * The filters a model's list offers, and how each narrows the query.
3
+ *
4
+ * Nothing declares a filter. A model already says what its fields are, and
5
+ * that is enough to know which of them a list is worth narrowing by and how
6
+ * to ask: a field with a few allowed values is chosen from them, a yes-or-no
7
+ * is yes or no, a field that points at another record is that record, a
8
+ * moment is a range of days. Three things the model already says decide it:
9
+ *
10
+ * - **what the field is**, from its validation rule;
11
+ * - **what the author thinks results are narrowed by**:
12
+ * `traits.useSearch.filterable`, written for the search engine and true
13
+ * of a list as well;
14
+ * - **what must stay private**: a hidden column is never offered, since
15
+ * narrowing by a value is a way to read it.
16
+ *
17
+ * `dashboard.filters` is the override, in the vocabulary `dashboard.columns`
18
+ * uses: the fields to offer, in order.
19
+ *
20
+ * Free text is not a filter. That is what the search box is for, and a box
21
+ * that only finds an exact match (which is what every column had) finds
22
+ * nothing for "act" under Status.
23
+ */
24
+ import { db, sqlDateTime } from '@stacksjs/database/runtime'
25
+ import { belongsToRelations } from './model-relations'
26
+ import { humanizeIdentifier, modelColumnLabel, modelFieldType } from './model-write'
27
+
28
+ /** How a filter is asked for. `text` is an exact value: only for a field the model named. */
29
+ export type ModelFilterKind = 'choice' | 'boolean' | 'relation' | 'date' | 'datetime' | 'number' | 'text'
30
+
31
+ export interface ModelFilter {
32
+ /** The column it narrows. */
33
+ name: string
34
+ label: string
35
+ kind: ModelFilterKind
36
+ /** For `choice`: the values the field may hold, as stored and as read. */
37
+ options?: Array<{ value: string, label: string }>
38
+ /**
39
+ * For `choice`: the options are the values the table holds now, not ones
40
+ * the model's rule limits the field to. A value that is not among them
41
+ * matches nothing; it is not refused, since the list can be a moment old.
42
+ */
43
+ open?: boolean
44
+ /** For `relation`: the model the column points at, to pick a record of. */
45
+ relation?: { slug: string, label: string }
46
+ }
47
+
48
+ /**
49
+ * A filter's value as it arrives. Plain text is "exactly this" (which is
50
+ * what a link from a record's panel sends: `{ team_id: "3" }`). The rest say
51
+ * how: any of several, between two moments, between two numbers.
52
+ */
53
+ export type ModelFilterValue = string | { in: string[] } | { from?: string, to?: string } | { min?: number, max?: number }
54
+
55
+ /** The most values one "any of" may carry. */
56
+ const IN_LIMIT = 50
57
+
58
+ function snakeCase(name: string): string {
59
+ return name.replace(/([a-z\d])([A-Z])/g, '$1_$2').toLowerCase()
60
+ }
61
+
62
+ /** A model's attributes by the column each is stored in. */
63
+ function attributesByColumn(Model: any): Map<string, { name: string, definition: any }> {
64
+ const byColumn = new Map<string, { name: string, definition: any }>()
65
+ for (const [name, definition] of Object.entries((Model?.attributes ?? {}) as Record<string, any>))
66
+ byColumn.set(snakeCase(name), { name, definition })
67
+ return byColumn
68
+ }
69
+
70
+ /** The columns a model's own search trait says results are narrowed by. */
71
+ function searchFilterable(Model: any): string[] {
72
+ const names = Model?.traits?.useSearch?.filterable
73
+ return Array.isArray(names) ? names.filter((name): name is string => typeof name === 'string' && name.trim() !== '').map(name => snakeCase(name.trim())) : []
74
+ }
75
+
76
+ /**
77
+ * The filters a model's list offers, of the columns the page may see.
78
+ *
79
+ * `allowed` is those columns: the list endpoint has already left out the
80
+ * hidden ones, so a filter is never built for a column it does not hold.
81
+ */
82
+ export function modelFilters(Model: any, allowed: readonly string[]): { filters: ModelFilter[], problems: string[] } {
83
+ const attributes = attributesByColumn(Model)
84
+ const relations = belongsToRelations(Model)
85
+ const has = (column: string) => allowed.includes(column)
86
+ const problems: string[] = []
87
+
88
+ /** The filter for one column, or null when its kind is not one a list narrows by. */
89
+ const filterFor = (column: string, named: boolean): ModelFilter | null => {
90
+ if (!has(column))
91
+ return null
92
+ const relation = relations.find(candidate => candidate.column === column)
93
+ const label = modelColumnLabel(Model, column, relation ? humanizeIdentifier(relation.model) : undefined)
94
+ if (relation)
95
+ return { name: column, label, kind: 'relation', relation: { slug: relation.slug, label: humanizeIdentifier(relation.model) } }
96
+ // The columns a trait adds, which the model's attributes do not list.
97
+ if (column === 'created_at' || column === 'updated_at' || column === 'deleted_at')
98
+ return { name: column, label, kind: 'datetime' }
99
+
100
+ const attribute = attributes.get(column)
101
+ if (!attribute)
102
+ return null
103
+ const kind = modelFieldType(attribute.name, attribute.definition)
104
+ if (kind === 'enum') {
105
+ const values: unknown[] = attribute.definition?.validation?.rule?.allowedValues ?? []
106
+ return { name: column, label, kind: 'choice', options: values.map(value => ({ value: String(value), label: humanizeIdentifier(String(value)) })) }
107
+ }
108
+ if (kind === 'boolean')
109
+ return { name: column, label, kind: 'boolean' }
110
+ if (kind === 'date' || kind === 'datetime')
111
+ return { name: column, label, kind }
112
+ // A number or a line of text is only a filter when the model names it:
113
+ // every count and every name would otherwise be one.
114
+ if (kind === 'number')
115
+ return named ? { name: column, label, kind: 'number' } : null
116
+ if (kind === 'text' || kind === 'email' || kind === 'url')
117
+ return named ? { name: column, label, kind: 'text' } : null
118
+ // Prose and structures are searched, not filtered.
119
+ return null
120
+ }
121
+
122
+ /** A declared name, as `dashboard.columns` reads one: an attribute, a column, or a `belongsTo`. */
123
+ const resolve = (name: string): string | null => {
124
+ const column = snakeCase(name.trim())
125
+ const relation = relations.find(candidate => candidate.column === `${column}_id` || snakeCase(candidate.model) === column)
126
+ return has(column) ? column : relation && has(relation.column) ? relation.column : null
127
+ }
128
+
129
+ const declared = Model?.dashboard?.filters
130
+ if (Array.isArray(declared)) {
131
+ const filters: ModelFilter[] = []
132
+ for (const name of declared) {
133
+ if (typeof name !== 'string' || !name.trim()) {
134
+ problems.push('an entry is not a field name')
135
+ continue
136
+ }
137
+ const column = resolve(name)
138
+ const filter = column ? filterFor(column, true) : null
139
+ if (!column)
140
+ problems.push(`'${name}' is not a field the list has`)
141
+ else if (!filter)
142
+ problems.push(`'${name}' is prose or a structure, which a list is searched for and not filtered by`)
143
+ else if (!filters.some(existing => existing.name === filter.name))
144
+ filters.push(filter)
145
+ }
146
+ return { filters, problems }
147
+ }
148
+
149
+ // Derived. The ones the model's search trait names come first, then the
150
+ // rest in the order that reads best in a menu: what a record is, what it
151
+ // points at, when it happened.
152
+ const filters: ModelFilter[] = []
153
+ const add = (filter: ModelFilter | null) => {
154
+ if (filter && !filters.some(existing => existing.name === filter.name))
155
+ filters.push(filter)
156
+ }
157
+ for (const name of searchFilterable(Model)) {
158
+ const column = resolve(name)
159
+ if (column)
160
+ add(filterFor(column, true))
161
+ }
162
+ const derived = allowed.map(column => filterFor(column, false)).filter((filter): filter is ModelFilter => filter !== null)
163
+ for (const kind of ['choice', 'boolean', 'relation', 'date', 'datetime'] as const) {
164
+ for (const filter of derived.filter(candidate => candidate.kind === kind))
165
+ add(filter)
166
+ }
167
+ return { filters, problems }
168
+ }
169
+
170
+ /**
171
+ * The columns a list may be ordered by, of the ones the page may see.
172
+ *
173
+ * Any stored value that has an order a person would recognise. Not prose or
174
+ * a structure, and not a column that points at another record: the cell
175
+ * shows that record's name, and ordering by its id would look random.
176
+ */
177
+ export function modelSortableColumns(Model: any, allowed: readonly string[]): string[] {
178
+ const attributes = attributesByColumn(Model)
179
+ const relations = new Set(belongsToRelations(Model).map(relation => relation.column))
180
+ return allowed.filter((column) => {
181
+ if (relations.has(column))
182
+ return false
183
+ const attribute = attributes.get(column)
184
+ if (!attribute)
185
+ return true
186
+ const kind = modelFieldType(attribute.name, attribute.definition)
187
+ return kind !== 'json' && kind !== 'longtext' && kind !== 'markdown'
188
+ })
189
+ }
190
+
191
+ /** The most distinct values a field of text may hold and still be chosen from. */
192
+ const CHOICE_LIMIT = 20
193
+ /** How long a table's distinct values are remembered. */
194
+ const CHOICES_TTL = 30_000
195
+ const storedChoices = new Map<string, { at: number, values: string[] | null }>()
196
+
197
+ /** The distinct values a column holds, up to `limit`. */
198
+ async function distinctValues(table: string, column: string, limit: number): Promise<unknown[]> {
199
+ const rows = await db.selectFrom(table as never).select([column] as never).groupBy(column as never).limit(limit).execute() as Array<Record<string, unknown>>
200
+ return rows.map(row => row[column])
201
+ }
202
+
203
+ /**
204
+ * Turn a field of text the model named into a choice, when the table holds
205
+ * few enough values to choose from.
206
+ *
207
+ * A model can name `status` as something results are narrowed by without
208
+ * limiting what it holds (`schema.string()`). Asked for as text, it would be
209
+ * a box that finds only an exact match. What the table holds says what there
210
+ * is to choose: "active" and "inactive". A field with many values (a
211
+ * `source` of a thousand referrers) stays a box.
212
+ *
213
+ * Remembered for half a minute per column: the list is read on every page,
214
+ * sort and keystroke, and a distinct read of a column with no index reads
215
+ * the whole table.
216
+ */
217
+ export async function withStoredChoices(
218
+ table: string,
219
+ filters: ModelFilter[],
220
+ read: (table: string, column: string, limit: number) => Promise<unknown[]> = distinctValues,
221
+ now: number = Date.now(),
222
+ ): Promise<ModelFilter[]> {
223
+ const out: ModelFilter[] = []
224
+ for (const filter of filters) {
225
+ if (filter.kind !== 'text') {
226
+ out.push(filter)
227
+ continue
228
+ }
229
+ const key = `${table}.${filter.name}`
230
+ let known = storedChoices.get(key)
231
+ if (!known || now - known.at > CHOICES_TTL) {
232
+ let values: string[] | null = null
233
+ try {
234
+ const found = (await read(table, filter.name, CHOICE_LIMIT + 1))
235
+ .filter(value => value !== null && value !== undefined && String(value) !== '')
236
+ .map(String)
237
+ values = found.length > 0 && found.length <= CHOICE_LIMIT ? [...new Set(found)].sort((a, b) => a.localeCompare(b)) : null
238
+ }
239
+ catch {
240
+ // The field is still a filter; it is just asked for as text.
241
+ values = null
242
+ }
243
+ known = { at: now, values }
244
+ storedChoices.set(key, known)
245
+ }
246
+ out.push(known.values
247
+ ? { ...filter, kind: 'choice', open: true, options: known.values.map(value => ({ value, label: humanizeIdentifier(value) })) }
248
+ : filter)
249
+ }
250
+ return out
251
+ }
252
+
253
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
254
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
255
+ }
256
+
257
+ /** `filters` arrives as a JSON object so column names stay unambiguous. */
258
+ export function parseFilters(raw: string | null): Record<string, ModelFilterValue> {
259
+ if (!raw) return {}
260
+
261
+ if (raw.length > 8192)
262
+ throw new TypeError('Model filters must be 8 KB or smaller')
263
+
264
+ let parsed: unknown
265
+ try {
266
+ parsed = JSON.parse(raw)
267
+ }
268
+ catch (error) {
269
+ throw new Error(`Could not parse model filters: ${error instanceof Error ? error.message : String(error)}`)
270
+ }
271
+
272
+ if (!isPlainObject(parsed))
273
+ throw new TypeError('Model filters must be a JSON object')
274
+
275
+ const entries = Object.entries(parsed)
276
+ if (entries.length > 50)
277
+ throw new TypeError('Model filters may contain at most 50 columns')
278
+
279
+ const out: Record<string, ModelFilterValue> = {}
280
+ for (const [key, value] of entries) {
281
+ if (!/^\w+$/.test(key))
282
+ throw new TypeError(`Invalid model filter column "${key}"`)
283
+ if (value === null || value === undefined || value === '')
284
+ continue
285
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
286
+ out[key] = String(value)
287
+ continue
288
+ }
289
+ if (!isPlainObject(value))
290
+ throw new TypeError(`Model filter "${key}" must be a value, or an object saying how to compare`)
291
+
292
+ const keys = Object.keys(value)
293
+ if (keys.length === 1 && keys[0] === 'in') {
294
+ const list = value.in
295
+ if (!Array.isArray(list) || list.some(item => typeof item !== 'string' && typeof item !== 'number'))
296
+ throw new TypeError(`Model filter "${key}" must list the values to match`)
297
+ if (list.length > IN_LIMIT)
298
+ throw new TypeError(`Model filter "${key}" may list at most ${IN_LIMIT} values`)
299
+ const values = [...new Set(list.map(String).filter(item => item !== ''))]
300
+ if (values.length > 0)
301
+ out[key] = { in: values }
302
+ continue
303
+ }
304
+ if (keys.length > 0 && keys.every(name => name === 'from' || name === 'to')) {
305
+ const range: { from?: string, to?: string } = {}
306
+ for (const edge of ['from', 'to'] as const) {
307
+ const moment = value[edge]
308
+ if (moment === undefined || moment === null || moment === '')
309
+ continue
310
+ if (typeof moment !== 'string' || moment.length > 40)
311
+ throw new TypeError(`Model filter "${key}" ${edge} must be a date`)
312
+ range[edge] = moment
313
+ }
314
+ if (range.from !== undefined || range.to !== undefined)
315
+ out[key] = range
316
+ continue
317
+ }
318
+ if (keys.length > 0 && keys.every(name => name === 'min' || name === 'max')) {
319
+ const range: { min?: number, max?: number } = {}
320
+ for (const edge of ['min', 'max'] as const) {
321
+ const amount = value[edge]
322
+ if (amount === undefined || amount === null || amount === '')
323
+ continue
324
+ const number = typeof amount === 'number' ? amount : typeof amount === 'string' && amount.trim() !== '' ? Number(amount) : Number.NaN
325
+ if (!Number.isFinite(number))
326
+ throw new TypeError(`Model filter "${key}" ${edge} must be a number`)
327
+ range[edge] = number
328
+ }
329
+ if (range.min !== undefined || range.max !== undefined)
330
+ out[key] = range
331
+ continue
332
+ }
333
+ throw new TypeError(`Model filter "${key}" is not a comparison the list has: use a value, { in }, { from, to } or { min, max }`)
334
+ }
335
+ return out
336
+ }
337
+
338
+ /** A day as a date column stores it. */
339
+ const DAY = /^\d{4}-\d{2}-\d{2}$/
340
+
341
+ /** A model's query, as far as a filter needs it. */
342
+ interface FilterQuery {
343
+ where: (...args: any[]) => FilterQuery
344
+ whereIn: (column: string, values: unknown[]) => FilterQuery
345
+ }
346
+
347
+ /**
348
+ * Narrow a query by the filters that arrived, or say why one cannot be
349
+ * applied. Every column has already been checked against the ones the page
350
+ * may see; what is checked here is that the comparison suits the field.
351
+ */
352
+ export function applyModelFilters<Query extends FilterQuery>(
353
+ query: Query,
354
+ values: Record<string, ModelFilterValue>,
355
+ filters: readonly ModelFilter[],
356
+ label: (column: string) => string = column => column,
357
+ ): { query: Query, error: string | null } {
358
+ let chain: FilterQuery = query
359
+ for (const [column, value] of Object.entries(values)) {
360
+ const filter = filters.find(candidate => candidate.name === column)
361
+ const called = filter?.label ?? label(column)
362
+ // Any column the page may see can be matched exactly, as a link from a
363
+ // record's panel does. Comparing another way is for the list's filters.
364
+ if (!filter && typeof value !== 'string')
365
+ return { query, error: `${called} is not one of this list's filters, so it can only be matched exactly.` }
366
+
367
+ if (typeof value === 'string') {
368
+ if (filter?.kind === 'boolean') {
369
+ const yes = ['true', '1', 'yes'].includes(value.toLowerCase())
370
+ if (!yes && !['false', '0', 'no'].includes(value.toLowerCase()))
371
+ return { query, error: `${called} is yes or no.` }
372
+ chain = chain.where(column, yes)
373
+ }
374
+ else if (filter?.kind === 'choice' && !filter.open && !filter.options!.some(option => option.value === value)) {
375
+ return { query, error: `${called} cannot be "${value}".` }
376
+ }
377
+ else {
378
+ chain = chain.where(column, value)
379
+ }
380
+ continue
381
+ }
382
+
383
+ if ('in' in value) {
384
+ if (filter!.kind !== 'choice' && filter!.kind !== 'relation' && filter!.kind !== 'text')
385
+ return { query, error: `${called} cannot be matched against a list of values.` }
386
+ if (filter!.kind === 'choice' && !filter!.open) {
387
+ const unknown = value.in.find(item => !filter!.options!.some(option => option.value === item))
388
+ if (unknown !== undefined)
389
+ return { query, error: `${called} cannot be "${unknown}".` }
390
+ }
391
+ chain = chain.whereIn(column, value.in)
392
+ continue
393
+ }
394
+
395
+ if ('from' in value || 'to' in value) {
396
+ if (filter!.kind !== 'date' && filter!.kind !== 'datetime')
397
+ return { query, error: `${called} is not a date, so it has no range of days.` }
398
+ for (const edge of ['from', 'to'] as const) {
399
+ const given = value[edge]
400
+ if (given === undefined)
401
+ continue
402
+ if (filter!.kind === 'date') {
403
+ // A day, compared as the column stores days: both ends included.
404
+ if (!DAY.test(given) || Number.isNaN(Date.parse(given)))
405
+ return { query, error: `${called} ${edge} must be a day, as 2026-01-31.` }
406
+ chain = chain.where(column, edge === 'from' ? '>=' : '<=', given)
407
+ }
408
+ else {
409
+ // A moment. The page sends where the viewer's day starts and where
410
+ // the day after their last one does, so "to" is not included.
411
+ const moment = new Date(given)
412
+ if (Number.isNaN(moment.getTime()))
413
+ return { query, error: `${called} ${edge} must be a date and time.` }
414
+ chain = chain.where(column, edge === 'from' ? '>=' : '<', sqlDateTime(moment))
415
+ }
416
+ }
417
+ continue
418
+ }
419
+
420
+ if (filter!.kind !== 'number')
421
+ return { query, error: `${called} is not a number, so it has no minimum or maximum.` }
422
+ const range = value as { min?: number, max?: number }
423
+ if (range.min !== undefined)
424
+ chain = chain.where(column, '>=', range.min)
425
+ if (range.max !== undefined)
426
+ chain = chain.where(column, '<=', range.max)
427
+ }
428
+ return { query: chain as Query, error: null }
429
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * The yes-or-no facts a trait keeps about a record for itself, offered on the
3
+ * record's edit form as switches (stacksjs/stacks#3298).
4
+ *
5
+ * A model's form asks for the model's own fillable attributes. Whether an
6
+ * account's email is confirmed and whether it signs in with two-factor are
7
+ * not attributes: the `useAuth` trait owns those columns, and changing one
8
+ * is more than writing it. Turning two-factor off removes the secret, the
9
+ * recovery codes and any open challenge. So each switch names the function
10
+ * that changes it, and the form's save calls that function instead of
11
+ * writing the column.
12
+ *
13
+ * Derived from the trait, not declared by the model. Only the model the auth
14
+ * package writes (`User`, on `users`) has any.
15
+ */
16
+ import type { ModelCreateField } from './model-write'
17
+ import { db } from '@stacksjs/database/runtime'
18
+ import { isAccountModel, modelColumnLabel } from './model-write'
19
+
20
+ export interface ModelSwitch {
21
+ /** The field, as a form names it: `emailVerifiedAt`. */
22
+ name: string
23
+ /** Where its state is read from: `email_verified_at`. Set when not null, not false and not zero. */
24
+ column: string
25
+ /** The sentence under the switch. */
26
+ help: string
27
+ /** The one way it can be turned from here, when it has only one. */
28
+ only?: 'off' | 'on'
29
+ /** The sentence under it while it cannot be turned. */
30
+ lockedHelp?: string
31
+ /** What changes it. Never a bare write of the column. */
32
+ set: (id: number, on: boolean) => Promise<void>
33
+ }
34
+
35
+ const ACCOUNT_SWITCHES: ModelSwitch[] = [
36
+ {
37
+ name: 'emailVerifiedAt',
38
+ column: 'email_verified_at',
39
+ help: 'On, this address counts as confirmed, as if they had used the emailed link. Off, it does not.',
40
+ async set(id, on) {
41
+ const { setEmailVerified } = await import('@stacksjs/auth')
42
+ await setEmailVerified(id, on)
43
+ },
44
+ },
45
+ {
46
+ name: 'twoFactorEnabled',
47
+ column: 'two_factor_enabled',
48
+ only: 'off',
49
+ help: 'Turn off for someone who lost their device. Their authenticator and recovery codes stop working, and they can set two-factor up again from their own account.',
50
+ lockedHelp: 'Only the account holder can turn this on, by setting up an authenticator from their own account.',
51
+ async set(id) {
52
+ const { disableTwoFactor } = await import('@stacksjs/auth')
53
+ await disableTwoFactor(id)
54
+ },
55
+ },
56
+ ]
57
+
58
+ /** The switches a model's edit form has beside its own fields. */
59
+ export function modelSwitches(Model: any): ModelSwitch[] {
60
+ // The auth package writes `users`, as the invitation does, so this is
61
+ // `User` and not every model with `useAuth`.
62
+ return Model?.name === 'User' && isAccountModel(Model) ? ACCOUNT_SWITCHES : []
63
+ }
64
+
65
+ /** Whether a stored value reads as yes: a moment that is set, a true, a one. */
66
+ export function modelSwitchOn(stored: unknown): boolean {
67
+ return !(stored === null || stored === undefined || stored === false || stored === 0 || stored === '' || stored === '0' || stored === 'false')
68
+ }
69
+
70
+ /** The switches as fields of the edit form. */
71
+ export function modelSwitchFields(Model: any): ModelCreateField[] {
72
+ return modelSwitches(Model).map(entry => ({
73
+ name: entry.name,
74
+ label: modelColumnLabel(Model, entry.name),
75
+ type: 'boolean' as const,
76
+ required: false,
77
+ defaultValue: false,
78
+ options: [],
79
+ help: entry.help,
80
+ switch: {
81
+ ...(entry.only ? { only: entry.only } : {}),
82
+ ...(entry.lockedHelp ? { lockedHelp: entry.lockedHelp } : {}),
83
+ },
84
+ }))
85
+ }
86
+
87
+ /** The columns the switches read, for the page to know they are asked for and not only shown. */
88
+ export function modelSwitchColumns(Model: any): string[] {
89
+ return modelSwitches(Model).map(entry => entry.column)
90
+ }
91
+
92
+ export interface ModelSwitchRequest {
93
+ switch: ModelSwitch
94
+ on: boolean
95
+ }
96
+
97
+ /** What a save can ask of a switch, however a form or an API caller spells yes and no. */
98
+ function askedState(value: unknown): boolean | null {
99
+ if (value === true || value === 1 || value === '1' || value === 'true' || value === 'on')
100
+ return true
101
+ if (value === false || value === 0 || value === '0' || value === 'false' || value === 'off')
102
+ return false
103
+ return null
104
+ }
105
+
106
+ /**
107
+ * The switches a save names, by field or by column, and what it asks of
108
+ * each. A value that is not a yes or a no is refused and not guessed at: a
109
+ * date sent for `email_verified_at` must not read as "off".
110
+ */
111
+ export function requestedSwitches(Model: any, body: Record<string, unknown>): { asked: ModelSwitchRequest[], errors: Record<string, string[]> } {
112
+ const asked: ModelSwitchRequest[] = []
113
+ const errors: Record<string, string[]> = {}
114
+ for (const entry of modelSwitches(Model)) {
115
+ const key = [entry.name, entry.column].find(name => Object.prototype.hasOwnProperty.call(body, name))
116
+ if (key === undefined)
117
+ continue
118
+ const on = askedState(body[key])
119
+ if (on === null)
120
+ errors[entry.name] = [`${modelColumnLabel(Model, entry.name)} is on or off.`]
121
+ else
122
+ asked.push({ switch: entry, on })
123
+ }
124
+ return { asked, errors }
125
+ }
126
+
127
+ /**
128
+ * Of the switches a save asks for, the ones that would change something and
129
+ * the ones that cannot be turned that way.
130
+ *
131
+ * `stored` is the record's row as the database has it. A switch already
132
+ * where it is asked to be is neither: asking twice is not a mistake.
133
+ */
134
+ export function planSwitches(Model: any, asked: ModelSwitchRequest[], stored: Record<string, unknown>): { turning: ModelSwitchRequest[], errors: Record<string, string[]> } {
135
+ const turning: ModelSwitchRequest[] = []
136
+ const errors: Record<string, string[]> = {}
137
+ for (const request of asked) {
138
+ if (modelSwitchOn(stored[request.switch.column]) === request.on)
139
+ continue
140
+ if (request.switch.only && (request.switch.only === 'on') !== request.on) {
141
+ errors[request.switch.name] = [request.switch.lockedHelp ?? `${modelColumnLabel(Model, request.switch.name)} cannot be turned ${request.on ? 'on' : 'off'} from here.`]
142
+ continue
143
+ }
144
+ turning.push(request)
145
+ }
146
+ return { turning, errors }
147
+ }
148
+
149
+ /** What the switches of one record are stored as. Read from the table: the columns are not the model's own. */
150
+ export async function storedSwitches(Model: any, id: number): Promise<Record<string, unknown>> {
151
+ const columns = modelSwitchColumns(Model)
152
+ if (columns.length === 0)
153
+ return {}
154
+ const row = await db.selectFrom(String(Model.table) as never)
155
+ .select(columns as never)
156
+ .where(String(Model.primaryKey || 'id') as never, '=', id as never)
157
+ .executeTakeFirst()
158
+ return (row ?? {}) as Record<string, unknown>
159
+ }
@@ -99,6 +99,12 @@ export interface ModelCreateField {
99
99
  help?: string
100
100
  /** For an `upload`: the kinds of file that may be chosen. */
101
101
  accept?: string
102
+ /**
103
+ * A yes or no a trait keeps for itself, changed by a function of its own
104
+ * and not by writing its column (`./model-switches`): the one way it can
105
+ * be turned, when it has only one, and what is said while it cannot be.
106
+ */
107
+ switch?: { only?: 'off' | 'on', lockedHelp?: string }
102
108
  }
103
109
 
104
110
  export interface PreparedModelFields {
@@ -33,7 +33,7 @@ async function notificationDeliveryOverview() {
33
33
  db
34
34
  .selectFrom('notification_deliveries')
35
35
  .select(db.fn.count('id').as('count'))
36
- .executeTakeFirst() as Promise<CountRow | undefined>,
36
+ .executeTakeFirst() as unknown as CountRow | undefined,
37
37
  db
38
38
  .selectFrom('notification_deliveries')
39
39
  .select(['status', db.fn.count('id').as('count')])
@@ -131,7 +131,7 @@ export async function readQueryLogPage(query: QueryListQuery, now: number = Date
131
131
  FROM query_logs ${filter.all.sql}`,
132
132
  filter.all.values,
133
133
  ).execute(),
134
- db.unsafe(`SELECT DISTINCT connection FROM query_logs ${filter.range.sql} ORDER BY connection`, filter.range.values).execute() as Promise<Array<{ connection: unknown }>>,
134
+ db.unsafe(`SELECT DISTINCT connection FROM query_logs ${filter.range.sql} ORDER BY connection`, filter.range.values).execute() as unknown as Array<{ connection: unknown }>,
135
135
  ])
136
136
 
137
137
  const counts: QueryCounts = {
@@ -44,11 +44,11 @@ export async function readQueueCounts(database: typeof db = db): Promise<QueueCo
44
44
  database.fn.min('id').as('first_id'),
45
45
  ])
46
46
  .groupBy('queue')
47
- .execute() as Promise<Array<{ queue: unknown, total: unknown, active: unknown, first_id: unknown }>>,
47
+ .execute() as unknown as Array<{ queue: unknown, total: unknown, active: unknown, first_id: unknown }>,
48
48
  database.selectFrom('failed_jobs')
49
49
  .select(['queue', database.fn.count('id').as('failed')])
50
50
  .groupBy('queue')
51
- .execute() as Promise<Array<{ queue: unknown, failed: unknown }>>,
51
+ .execute() as unknown as Array<{ queue: unknown, failed: unknown }>,
52
52
  ])
53
53
 
54
54
  const failed = new Map<string, number>()
@@ -31,7 +31,7 @@ export interface NamedRow {
31
31
 
32
32
  /** What runs the two queries: the configured `db`, or a test's own connection. */
33
33
  export interface NamedSearchRunner {
34
- unsafe: (sql: string, values?: unknown[]) => { execute: () => Promise<unknown> }
34
+ unsafe: (sql: string, values?: unknown[]) => { execute: () => unknown }
35
35
  }
36
36
 
37
37
  export function parseNamedSearchQuery(read: QueryReader): NamedSearchQuery | { error: string } {
@@ -104,11 +104,11 @@ export default defineModel({
104
104
  isApproved: {
105
105
  required: false,
106
106
  fillable: true,
107
- default: 0,
107
+ default: false,
108
108
  validation: {
109
- rule: schema.number(),
109
+ rule: schema.boolean(),
110
110
  },
111
- factory: faker => faker.number.int({ min: 0, max: 1 }),
111
+ factory: faker => faker.datatype.boolean(),
112
112
  },
113
113
  },
114
114
 
@@ -227,12 +227,12 @@ export default defineModel({
227
227
  order: 13,
228
228
  fillable: true,
229
229
  validation: {
230
- rule: schema.number(),
230
+ rule: schema.boolean(),
231
231
  message: {
232
- number: 'Featured must be a number value',
232
+ boolean: 'Featured must be yes or no',
233
233
  },
234
234
  },
235
- factory: faker => faker.number.int({ min: 0, max: 1 }),
235
+ factory: faker => faker.datatype.boolean(),
236
236
  },
237
237
  },
238
238