@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
@@ -28,6 +28,13 @@ export { createQueryBuilder as QueryBuilder } from 'bun-query-builder'
28
28
 
29
29
  ## Usage
30
30
 
31
+ A query answers where it is written: `get()`, `first()`, `execute()`, `count()`
32
+ and the rest return the rows, the row or the number, and a transaction is done
33
+ when it returns. The `await` in the examples below is optional (`await` on a
34
+ value is that value); a failure is thrown where the call stands. The full rule,
35
+ including what still returns a promise, is in `stacks-database` under "Values,
36
+ not promises".
37
+
31
38
  ```typescript
32
39
  import { db } from '@stacksjs/database/runtime'
33
40
 
@@ -9,7 +9,7 @@ import { sqlHelpers } from '@stacksjs/database/runtime'
9
9
 
10
10
  /** What runs the queries: the configured `db`, or a test's own connection. */
11
11
  export interface CommerceSqlRunner {
12
- unsafe: (sql: string, values?: unknown[]) => { execute: () => Promise<unknown> }
12
+ unsafe: (sql: string, values?: unknown[]) => { execute: () => unknown }
13
13
  }
14
14
 
15
15
  /** A result as rows, whatever the driver returned for an empty one. */
@@ -89,7 +89,7 @@ export default new Action({
89
89
  .updateTable('comments')
90
90
  .set({
91
91
  status,
92
- is_approved: status === 'approved' ? 1 : 0,
92
+ is_approved: status === 'approved',
93
93
  updated_at: timestamp(),
94
94
  } as any)
95
95
  .where('id', '=', id)
@@ -44,7 +44,7 @@ export default new Action({
44
44
  poster: payload.poster,
45
45
  status: payload.status,
46
46
  author_id: payload.authorId,
47
- is_featured: payload.featured ? 1 : 0,
47
+ is_featured: Boolean(payload.featured),
48
48
  views: 0,
49
49
  published_at: publishedAtFor(payload.status, null, now),
50
50
  created_at: now,
@@ -54,7 +54,7 @@ export default new Action({
54
54
  poster: payload.poster,
55
55
  status: payload.status,
56
56
  author_id: payload.authorId,
57
- is_featured: payload.featured ? 1 : 0,
57
+ is_featured: Boolean(payload.featured),
58
58
  published_at: publishedAtFor(payload.status, existing.published_at, timestamp()),
59
59
  updated_at: timestamp(),
60
60
  } as any)
@@ -254,8 +254,8 @@ async function prepareCommentables(query: CommentListQuery): Promise<Commentable
254
254
  const columns = await ownerLabelColumns(types)
255
255
  const where = commentableWhere(query, columns, guestAuthors)
256
256
  const [[counted], statusRows] = await Promise.all([
257
- db.unsafe(`SELECT COUNT(id) AS count FROM commentables ${where.sql}`, where.values).execute() as Promise<Array<{ count: unknown }>>,
258
- db.unsafe('SELECT status, COUNT(id) AS count FROM commentables GROUP BY status').execute() as Promise<Array<{ status: unknown, count: unknown }>>,
257
+ db.unsafe(`SELECT COUNT(id) AS count FROM commentables ${where.sql}`, where.values).execute() as unknown as Array<{ count: unknown }>,
258
+ db.unsafe('SELECT status, COUNT(id) AS count FROM commentables GROUP BY status').execute() as unknown as Array<{ status: unknown, count: unknown }>,
259
259
  ])
260
260
 
261
261
  return { columns, guestAuthors, where, total: countOf(counted?.count), statusRows }
@@ -92,8 +92,8 @@ export async function readPageListPage(query: PageListQuery, database: typeof db
92
92
  database.fn.count('id').as('count'),
93
93
  database.fn.sum('views').as('views'),
94
94
  database.fn.sum('conversions').as('conversions'),
95
- ]).executeTakeFirst() as Promise<{ count?: unknown, views?: unknown, conversions?: unknown } | undefined>,
96
- database.selectFrom('pages').select(['title']).orderBy('created_at', 'desc').orderBy('id', 'desc').limit(1).executeTakeFirst() as Promise<{ title?: string | null } | undefined>,
95
+ ]).executeTakeFirst() as unknown as { count?: unknown, views?: unknown, conversions?: unknown } | undefined,
96
+ database.selectFrom('pages').select(['title']).orderBy('created_at', 'desc').orderBy('id', 'desc').limit(1).executeTakeFirst() as unknown as { title?: string | null } | undefined,
97
97
  ])
98
98
 
99
99
  return {
@@ -119,8 +119,8 @@ export async function readPostPage(query: PostListQuery, database: typeof db = d
119
119
  .execute() as PostListRow[]
120
120
 
121
121
  const [byStatus, views] = await Promise.all([
122
- database.selectFrom('posts').select(['status', database.fn.count('id').as('count')]).groupBy('status').execute() as Promise<Array<{ status: string, count: unknown }>>,
123
- database.selectFrom('posts').select(database.fn.sum('views').as('views')).executeTakeFirst() as Promise<{ views?: unknown } | undefined>,
122
+ database.selectFrom('posts').select(['status', database.fn.count('id').as('count')]).groupBy('status').execute() as unknown as Array<{ status: string, count: unknown }>,
123
+ database.selectFrom('posts').select(database.fn.sum('views').as('views')).executeTakeFirst() as unknown as { views?: unknown } | undefined,
124
124
  ])
125
125
 
126
126
  const statusCount = (status: PostStatus) => byStatus
@@ -24,9 +24,14 @@ interface SourceResult<T> {
24
24
  error: string
25
25
  }
26
26
 
27
- async function inspectSource<T>(work: Promise<T>, fallback: T, message: string, source: string): Promise<SourceResult<T>> {
27
+ /**
28
+ * One source of the page, read on its own: a failure costs that source its
29
+ * numbers and says why, and the others still answer. The work is handed over
30
+ * unstarted, because a query answers (or fails) where it is written.
31
+ */
32
+ async function inspectSource<T>(work: () => T | Promise<T>, fallback: T, message: string, source: string): Promise<SourceResult<T>> {
28
33
  try {
29
- return { value: await work, error: '' }
34
+ return { value: await work(), error: '' }
30
35
  }
31
36
  catch (error) {
32
37
  return {
@@ -49,7 +54,7 @@ export default new Action({
49
54
  const cpu = process.cpuUsage()
50
55
  const databaseDriver = String(config.database?.default || 'unknown')
51
56
 
52
- const requestSummaryQuery = db
57
+ const requestSummaryQuery = () => db
53
58
  .selectFrom('requests')
54
59
  .select([
55
60
  db.fn.count('id').as('total'),
@@ -58,16 +63,16 @@ export default new Action({
58
63
  db.fn.max('created_at').as('latest'),
59
64
  ])
60
65
  .whereNull('deleted_at')
61
- .executeTakeFirst() as Promise<NumericSummaryRow | undefined>
66
+ .executeTakeFirst() as unknown as NumericSummaryRow | undefined
62
67
 
63
- const requestSuccessQuery = db
68
+ const requestSuccessQuery = () => db
64
69
  .selectFrom('requests')
65
70
  .select(db.fn.count('id').as('count'))
66
71
  .whereNull('deleted_at')
67
72
  .where('status_code', '<', 400)
68
- .executeTakeFirst() as Promise<{ count: number | string } | undefined>
73
+ .executeTakeFirst() as unknown as { count: number | string } | undefined
69
74
 
70
- const slowRequestsQuery = db
75
+ const slowRequestsQuery = () => db
71
76
  .selectFrom('requests')
72
77
  .select(['id', 'method', 'path', 'status_code', 'duration_ms', 'created_at'])
73
78
  .whereNull('deleted_at')
@@ -76,7 +81,7 @@ export default new Action({
76
81
  .limit(5)
77
82
  .execute()
78
83
 
79
- const querySummaryQuery = db
84
+ const querySummaryQuery = () => db
80
85
  .selectFrom('query_logs')
81
86
  .select([
82
87
  db.fn.count('id').as('total'),
@@ -84,15 +89,15 @@ export default new Action({
84
89
  db.fn.max('duration').as('maximum'),
85
90
  db.fn.max('executed_at').as('latest'),
86
91
  ])
87
- .executeTakeFirst() as Promise<NumericSummaryRow | undefined>
92
+ .executeTakeFirst() as unknown as NumericSummaryRow | undefined
88
93
 
89
- const queryStatusesQuery = db
94
+ const queryStatusesQuery = () => db
90
95
  .selectFrom('query_logs')
91
96
  .select(['status', db.fn.count('id').as('count')])
92
97
  .groupBy('status')
93
- .execute() as Promise<StatusCountRow[]>
98
+ .execute() as unknown as StatusCountRow[]
94
99
 
95
- const slowQueriesQuery = db
100
+ const slowQueriesQuery = () => db
96
101
  .selectFrom('query_logs')
97
102
  .select(['id', 'query', 'duration', 'status', 'connection', 'executed_at'])
98
103
  .where('duration', '>=', slowThresholdMs)
@@ -101,15 +106,15 @@ export default new Action({
101
106
  .limit(5)
102
107
  .execute()
103
108
 
104
- const errorSummaryQuery = db
109
+ const errorSummaryQuery = () => db
105
110
  .selectFrom('errors')
106
111
  .select([
107
112
  db.fn.count('id').as('total'),
108
113
  db.fn.max('created_at').as('latest'),
109
114
  ])
110
- .executeTakeFirst() as Promise<NumericSummaryRow | undefined>
115
+ .executeTakeFirst() as unknown as NumericSummaryRow | undefined
111
116
 
112
- const recentErrorsQuery = db
117
+ const recentErrorsQuery = () => db
113
118
  .selectFrom('errors')
114
119
  .select(['id', 'type', 'message', 'status', 'created_at'])
115
120
  .orderBy('created_at', 'desc')
@@ -144,10 +149,10 @@ export default new Action({
144
149
  inspectSource(slowQueriesQuery, [], 'Query telemetry is unavailable.', 'queries.slowest'),
145
150
  inspectSource(errorSummaryQuery, undefined, 'Error telemetry is unavailable.', 'errors.summary'),
146
151
  inspectSource(recentErrorsQuery, [], 'Error telemetry is unavailable.', 'errors.recent'),
147
- inspectSource(checkQueueHealth(), null, 'Queue telemetry is unavailable.', 'queue'),
148
- inspectSource(cache.getStats(), null, 'Cache telemetry is unavailable.', 'cache'),
149
- inspectSource(filesystemQuery, null, 'Filesystem telemetry is unavailable.', 'filesystem'),
150
- inspectSource(databaseFileQuery, null, 'Database file telemetry is unavailable.', 'database-file'),
152
+ inspectSource(() => checkQueueHealth(), null, 'Queue telemetry is unavailable.', 'queue'),
153
+ inspectSource(() => cache.getStats(), null, 'Cache telemetry is unavailable.', 'cache'),
154
+ inspectSource(() => filesystemQuery, null, 'Filesystem telemetry is unavailable.', 'filesystem'),
155
+ inspectSource(() => databaseFileQuery, null, 'Database file telemetry is unavailable.', 'database-file'),
151
156
  ])
152
157
 
153
158
  const requestTotal = countValue(requestSummary.value?.total)
@@ -125,12 +125,12 @@ export const localLogsProvider: DashboardLogsProvider = {
125
125
 
126
126
  const [countRow, typeRows, sourceRows, projectRows] = await Promise.all([
127
127
  applyFilters(db.selectFrom('logs').select(db.fn.count('id').as('count')))
128
- .executeTakeFirst() as Promise<{ count: number | string } | undefined>,
128
+ .executeTakeFirst() as unknown as { count: number | string } | undefined,
129
129
  applyFilters(db.selectFrom('logs').select(['type', db.fn.count('id').as('count')]))
130
130
  .groupBy('type')
131
- .execute() as Promise<Array<{ type: string, count: number | string }>>,
132
- db.selectFrom('logs').select('source').distinct().orderBy('source', 'asc').limit(100).execute() as Promise<Array<{ source: string }>>,
133
- db.selectFrom('logs').select('project').distinct().orderBy('project', 'asc').limit(500).execute() as Promise<Array<{ project: string }>>,
131
+ .execute() as unknown as Array<{ type: string, count: number | string }>,
132
+ db.selectFrom('logs').select('source').distinct().orderBy('source', 'asc').limit(100).execute() as unknown as Array<{ source: string }>,
133
+ db.selectFrom('logs').select('project').distinct().orderBy('project', 'asc').limit(500).execute() as unknown as Array<{ project: string }>,
134
134
  ])
135
135
 
136
136
  const total = Number(countRow?.count || 0)
@@ -143,7 +143,7 @@ export async function readJobPage(query: JobListQuery): Promise<JobListPage> {
143
143
  const [activeTotal, failedTotal, queueRows] = await Promise.all([
144
144
  countOf(active),
145
145
  countOf(failed),
146
- db.unsafe('SELECT DISTINCT queue FROM jobs UNION SELECT DISTINCT queue FROM failed_jobs').execute() as Promise<Array<{ queue: unknown }>>,
146
+ db.unsafe('SELECT DISTINCT queue FROM jobs UNION SELECT DISTINCT queue FROM failed_jobs').execute() as unknown as Array<{ queue: unknown }>,
147
147
  ])
148
148
 
149
149
  const total = activeTotal + failedTotal
@@ -122,14 +122,14 @@ export default new Action({
122
122
  WHERE cl.card_id IN (SELECT id FROM cards WHERE board_id = ${param(1)} AND archived = false)
123
123
  ORDER BY l.name ASC`,
124
124
  [id],
125
- ).execute() as Promise<Array<{ card_id: number, id: number, name: string, color: string }>>,
125
+ ).execute() as unknown as Array<{ card_id: number, id: number, name: string, color: string }>,
126
126
  db.unsafe(
127
127
  `SELECT ca.card_id, ca.user_id, u.name, u.email
128
128
  FROM card_assignees ca
129
129
  LEFT JOIN users u ON u.id = ca.user_id
130
130
  WHERE ca.card_id IN (SELECT id FROM cards WHERE board_id = ${param(1)} AND archived = false)`,
131
131
  [id],
132
- ).execute() as Promise<Array<{ card_id: number, user_id: number, name: string | null, email: string | null }>>,
132
+ ).execute() as unknown as Array<{ card_id: number, user_id: number, name: string | null, email: string | null }>,
133
133
  ])
134
134
 
135
135
  const labelsByCard = new Map<number, Array<{ id: number, name: string, color: string }>>()
@@ -69,14 +69,14 @@ export default new Action({
69
69
  WHERE cl.card_id = ${param(1)}
70
70
  ORDER BY l.name ASC`,
71
71
  [id],
72
- ).execute() as Promise<Array<{ id: number, name: string, color: string }>>,
72
+ ).execute() as unknown as Array<{ id: number, name: string, color: string }>,
73
73
  db.unsafe(
74
74
  `SELECT ca.user_id, ca.assigned_by_user_id, ca.created_at, u.name, u.email
75
75
  FROM card_assignees ca
76
76
  LEFT JOIN users u ON u.id = ca.user_id
77
77
  WHERE ca.card_id = ${param(1)}`,
78
78
  [id],
79
- ).execute() as Promise<Array<{ user_id: number, assigned_by_user_id: number | null, created_at: string | null, name: string | null, email: string | null }>>,
79
+ ).execute() as unknown as Array<{ user_id: number, assigned_by_user_id: number | null, created_at: string | null, name: string | null, email: string | null }>,
80
80
  db.unsafe(
81
81
  `SELECT cc.id, cc.uuid, cc.user_id, cc.body, cc.created_at, cc.updated_at, u.name, u.email
82
82
  FROM card_comments cc
@@ -84,7 +84,7 @@ export default new Action({
84
84
  WHERE cc.card_id = ${param(1)}
85
85
  ORDER BY cc.created_at ASC, cc.id ASC`,
86
86
  [id],
87
- ).execute() as Promise<Array<{ id: number, uuid: string | null, user_id: number | null, body: string, created_at: string | null, updated_at: string | null, name: string | null, email: string | null }>>,
87
+ ).execute() as unknown as Array<{ id: number, uuid: string | null, user_id: number | null, body: string, created_at: string | null, updated_at: string | null, name: string | null, email: string | null }>,
88
88
  // Each one carries a freshly signed, expiring URL: the bytes are on a
89
89
  // private disk, so there is no path the browser could fetch.
90
90
  cardAttachments(id),
@@ -108,7 +108,7 @@ export async function signCardAttachmentUrl(
108
108
 
109
109
  /** What `removeCardAttachments` runs its two statements through: `db`, or a transaction. */
110
110
  export interface AttachmentStatementRunner {
111
- unsafe: (sql: string, params?: unknown[]) => { execute: () => Promise<unknown> }
111
+ unsafe: (sql: string, params?: unknown[]) => { execute: () => unknown }
112
112
  }
113
113
 
114
114
  /**
@@ -65,8 +65,8 @@ describe('marketing list records', () => {
65
65
  slug: 'product-news',
66
66
  description: 'Weekly updates',
67
67
  status: 'active',
68
- isPublic: 1,
69
- doubleOptIn: 0,
68
+ isPublic: true,
69
+ doubleOptIn: false,
70
70
  })
71
71
  })
72
72
 
@@ -145,8 +145,8 @@ export function marketingListWriteData(input: Record<string, unknown>): {
145
145
  slug: string
146
146
  description: string
147
147
  status: MarketingListStatus
148
- isPublic: number
149
- doubleOptIn: number
148
+ isPublic: boolean
149
+ doubleOptIn: boolean
150
150
  } {
151
151
  const name = text(input.name).trim()
152
152
  const slug = slugifyMarketingList(text(input.slug).trim() || name)
@@ -155,8 +155,8 @@ export function marketingListWriteData(input: Record<string, unknown>): {
155
155
  slug,
156
156
  description: text(input.description).trim(),
157
157
  status: status(input.status),
158
- isPublic: boolean(input.isPublic ?? input.is_public) ? 1 : 0,
159
- doubleOptIn: boolean(input.doubleOptIn ?? input.double_opt_in) ? 1 : 0,
158
+ isPublic: boolean(input.isPublic ?? input.is_public),
159
+ doubleOptIn: boolean(input.doubleOptIn ?? input.double_opt_in),
160
160
  }
161
161
  }
162
162
 
@@ -7,9 +7,11 @@ import { safeGet } from '../../../../resources/functions/dashboard/data'
7
7
  import { resolveDashboardModel } from '../../../../resources/functions/dashboard/model-access'
8
8
  import { dashboardOperationalError } from '../dashboard-response'
9
9
  import { type ModelCustomAction, modelActionApplies, modelActions, publicModelAction } from './model-actions'
10
+ import { applyModelFilters, type ModelFilter, type ModelFilterValue, modelFilters, modelSortableColumns, parseFilters, withStoredChoices } from './model-filters'
10
11
  import { modelFormFields, reachableRelations } from './model-forms'
11
12
  import { isUnmigratedTable } from './model-migration'
12
13
  import { recordNames } from './model-options'
14
+ import { modelSwitchColumns, modelSwitchFields } from './model-switches'
13
15
  import type { ModelFieldDisplay } from './model-fields'
14
16
  import { humanizeIdentifier, isErasureSubject, isValidModelSlug, type ModelCreateField, type ModelWriteCapabilities, modelColumnDisplay, modelColumnLabel, modelFieldProblems, modelListColumns, modelSchemaColumns, modelWritableColumns, modelWriteCapabilities, slugToPascal } from './model-write'
15
17
 
@@ -17,6 +19,7 @@ import { humanizeIdentifier, isErasureSubject, isValidModelSlug, type ModelCreat
17
19
  const warnedColumns = new Set<string>()
18
20
  /** Models already told, this process, what is wrong with their `dashboard.fields`. */
19
21
  const warnedFields = new Set<string>()
22
+ const warnedFilters = new Set<string>()
20
23
 
21
24
  /**
22
25
  * `GET /api/dashboard/models/{slug}` (stacksjs/stacks#1838).
@@ -66,7 +69,11 @@ interface ResponseShape {
66
69
  sort: string
67
70
  dir: 'asc' | 'desc'
68
71
  q: string
69
- filters: Record<string, string>
72
+ filters: Record<string, ModelFilterValue>
73
+ /** What the list can be narrowed by, derived from the model's fields: see `./model-filters`. */
74
+ filterable: ModelFilter[]
75
+ /** The columns the list can be ordered by. */
76
+ sortable: string[]
70
77
  writable: boolean
71
78
  writeCapabilities: ModelWriteCapabilities
72
79
  createFields: ModelCreateField[]
@@ -160,40 +167,8 @@ function queryValue(request: RequestInstance, key: string, fallback = ''): strin
160
167
  return value == null ? fallback : String(value)
161
168
  }
162
169
 
163
- /** `filters` arrives as a JSON object so column names stay unambiguous. */
164
- export function parseFilters(raw: string | null): Record<string, string> {
165
- if (!raw) return {}
166
-
167
- if (raw.length > 8192)
168
- throw new TypeError('Model filters must be 8 KB or smaller')
169
-
170
- let parsed: unknown
171
- try {
172
- parsed = JSON.parse(raw)
173
- }
174
- catch (error) {
175
- throw new Error(`Could not parse model filters: ${error instanceof Error ? error.message : String(error)}`)
176
- }
177
-
178
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
179
- throw new TypeError('Model filters must be a JSON object')
180
-
181
- const entries = Object.entries(parsed)
182
- if (entries.length > 50)
183
- throw new TypeError('Model filters may contain at most 50 columns')
184
-
185
- const out: Record<string, string> = {}
186
- for (const [key, value] of entries) {
187
- if (!/^\w+$/.test(key))
188
- throw new TypeError(`Invalid model filter column "${key}"`)
189
- if (value === null || value === undefined || value === '')
190
- continue
191
- if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean')
192
- throw new TypeError(`Model filter "${key}" must be a scalar value`)
193
- out[key] = String(value)
194
- }
195
- return out
196
- }
170
+ // Where it used to live, and where its callers still look for it.
171
+ export { parseFilters }
197
172
 
198
173
  export default new Action({
199
174
  name: 'Dashboard Model Show',
@@ -213,7 +188,7 @@ export default new Action({
213
188
  const requestedSort = queryValue(request, 'sort').trim()
214
189
  const dir: 'asc' | 'desc' = queryValue(request, 'dir') === 'asc' ? 'asc' : 'desc'
215
190
  const q = queryValue(request, 'q').trim()
216
- let filters: Record<string, string>
191
+ let filters: Record<string, ModelFilterValue>
217
192
  try {
218
193
  filters = parseFilters(queryValue(request, 'filters') || null)
219
194
  }
@@ -240,6 +215,8 @@ export default new Action({
240
215
  dir,
241
216
  q,
242
217
  filters,
218
+ filterable: [],
219
+ sortable: [],
243
220
  writable: false,
244
221
  writeCapabilities: { create: false, update: false, destroy: false, invite: false, anonymize: false },
245
222
  createFields: [],
@@ -293,12 +270,25 @@ export default new Action({
293
270
  response.sort = sort
294
271
  const searchColumns = searchColumnsFor(allowed, first)
295
272
 
273
+ // What the list offers to be narrowed and ordered by, from the model's
274
+ // own fields. Read before the query: a comparison that does not suit a
275
+ // field (a range of days on a name) is refused, not sent to the database.
276
+ const offered = modelFilters(Model, response.columns)
277
+ offered.filters = await withStoredChoices(response.tableName, offered.filters)
278
+ response.filterable = offered.filters
279
+ response.sortable = modelSortableColumns(Model, response.columns)
280
+ if (offered.problems.length > 0 && !warnedFilters.has(modelName)) {
281
+ warnedFilters.add(modelName)
282
+ for (const problem of offered.problems)
283
+ console.warn(`[dashboard] ${modelName} dashboard.filters: ${problem}. It is left out.`)
284
+ }
285
+ const called = (column: string) => modelColumnLabel(Model, column)
286
+ const narrowed = applyModelFilters(Model.query() as any, filters, offered.filters, called)
287
+ if (narrowed.error)
288
+ return routerResponse.json({ message: narrowed.error }, 422)
289
+
296
290
  const build = () => {
297
- let chain = Model.query() as any
298
- for (const [column, value] of Object.entries(filters)) {
299
- if (!isSafeColumn(column, allowed)) continue
300
- chain = chain.where(column, value)
301
- }
291
+ let chain = applyModelFilters(Model.query() as any, filters, offered.filters).query as any
302
292
  if (q && searchColumns.length > 0) {
303
293
  // Lowercased on both sides, so the search ignores case on every
304
294
  // dialect. A model query's whereLike is a plain LIKE, which is
@@ -372,8 +362,10 @@ export default new Action({
372
362
  }
373
363
  const formFields = (): ModelCreateField[] => modelFormFields(Model, reachable)
374
364
  response.createFields = response.writeCapabilities.create ? formFields() : []
375
- response.updateColumns = response.writeCapabilities.update ? modelWritableColumns(Model) : []
376
- response.updateFields = response.writeCapabilities.update ? formFields() : []
365
+ // An edit form also has the switches a trait keeps for itself: a
366
+ // confirmed email, two-factor. Asked for, so no longer shown as read only.
367
+ response.updateColumns = response.writeCapabilities.update ? [...modelWritableColumns(Model), ...modelSwitchColumns(Model)] : []
368
+ response.updateFields = response.writeCapabilities.update ? [...formFields(), ...modelSwitchFields(Model)] : []
377
369
  response.displayColumns = response.columns.filter(col => !col.startsWith('_'))
378
370
  response.columnMeta = response.displayColumns.map((name) => {
379
371
  const format = modelColumnDisplay(Model, name)
@@ -406,6 +398,13 @@ export default new Action({
406
398
  // read "3", and a record's page has its names without asking again.
407
399
  for (const [column, relation] of Object.entries(response.relations)) {
408
400
  const ids = response.rows.map(row => row[column]).filter(id => id !== null && id !== undefined && id !== '') as Array<number | string>
401
+ // And the records the list is narrowed by, which a list with no rows
402
+ // has none of: "Team: PrimeSoft Ltd" in the filter's chip, not "#1".
403
+ const narrowedBy = filters[column]
404
+ if (typeof narrowedBy === 'string')
405
+ ids.push(narrowedBy)
406
+ else if (narrowedBy && 'in' in narrowedBy)
407
+ ids.push(...narrowedBy.in)
409
408
  if (ids.length > 0)
410
409
  response.relationNames[column] = Object.fromEntries(await recordNames(relation.model, ids))
411
410
  }
@@ -4,6 +4,7 @@ import { isUniqueViolation, ModelValidationError, toSnakeCaseKeys } from '@stack
4
4
  import { response } from '@stacksjs/router'
5
5
  import { dashboardOperationalError } from '../dashboard-response'
6
6
  import { missingRelationErrors } from './model-relations'
7
+ import { planSwitches, requestedSwitches, storedSwitches } from './model-switches'
7
8
  import { duplicateFieldErrors, humanizeIdentifier, parseRowId, prepareModelFields, resolveWritableModel } from './model-write'
8
9
 
9
10
  interface ModelWriteInput {
@@ -45,15 +46,28 @@ export default new Action({
45
46
  if (Object.keys(prepared.errors).length > 0)
46
47
  return response.json({ message: 'Validation failed.', errors: prepared.errors }, 422)
47
48
  const changes = toSnakeCaseKeys(prepared.data)
48
- if (Object.keys(changes).length === 0)
49
+ // What a trait keeps for itself (a confirmed email, two-factor) is asked
50
+ // for as a switch and changed by the trait's own function.
51
+ const { asked, errors: unreadable } = requestedSwitches(resolved.Model, body)
52
+ if (Object.keys(unreadable).length > 0)
53
+ return response.json({ message: 'Validation failed.', errors: unreadable }, 422)
54
+ if (Object.keys(changes).length === 0 && asked.length === 0)
49
55
  return response.json({ message: 'No writable fields in the request body.' }, 422)
50
56
 
51
57
  try {
52
58
  const row = await resolved.Model.find(id)
53
59
  if (!row)
54
60
  return response.json({ message: `${resolved.modelName} ${id} not found.` }, 404)
55
- await resolved.Model.update(id, changes)
56
- return { ok: true, id, changed: Object.keys(changes) }
61
+ // Refused before anything is written: a switch that cannot be turned
62
+ // that way refuses the whole save, like any other field's rule.
63
+ const { turning, errors } = planSwitches(resolved.Model, asked, asked.length > 0 ? await storedSwitches(resolved.Model, id) : {})
64
+ if (Object.keys(errors).length > 0)
65
+ return response.json({ message: 'Validation failed.', errors }, 422)
66
+ if (Object.keys(changes).length > 0)
67
+ await resolved.Model.update(id, changes)
68
+ for (const request of turning)
69
+ await request.switch.set(id, request.on)
70
+ return { ok: true, id, changed: [...Object.keys(changes), ...turning.map(request => request.switch.column)] }
57
71
  }
58
72
  catch (error) {
59
73
  // The model's own rules rejected the row: the caller's mistake, named