@stacksjs/defaults 0.75.539 → 0.75.542

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 (152) hide show
  1. package/ai/AGENTS.md +2 -0
  2. package/ai/skills/stacks-actions/SKILL.md +1 -1
  3. package/ai/skills/stacks-auth/SKILL.md +8 -1
  4. package/ai/skills/stacks-dashboard/SKILL.md +196 -3
  5. package/ai/skills/stacks-dependencies/SKILL.md +46 -0
  6. package/ai/skills/stacks-development/SKILL.md +1 -1
  7. package/ai/skills/stacks-flow/SKILL.md +7 -0
  8. package/ai/skills/stacks-hq/SKILL.md +146 -0
  9. package/ai/skills/stacks-models/SKILL.md +21 -3
  10. package/ai/skills/stacks-native/CATALOG.md +22 -9
  11. package/ai/skills/stacks-new-app/SKILL.md +175 -0
  12. package/ai/skills/stacks-repl/SKILL.md +76 -43
  13. package/ai/skills/stacks-stx/SKILL.md +6 -2
  14. package/ai/skills/stacks-upstream/SKILL.md +188 -0
  15. package/ai/skills/stacks-writing-for-agents/SKILL.md +1 -1
  16. package/app/Actions/Dashboard/Data/UserIndexAction.ts +20 -2
  17. package/app/Actions/Dashboard/Models/ModelDestroyAction.ts +48 -12
  18. package/app/Actions/Dashboard/Models/ModelOptionsAction.ts +103 -0
  19. package/app/Actions/Dashboard/Models/ModelRelatedAction.ts +42 -0
  20. package/app/Actions/Dashboard/Models/ModelShowAction.ts +75 -12
  21. package/app/Actions/Dashboard/Models/ModelStoreAction.ts +7 -1
  22. package/app/Actions/Dashboard/Models/ModelUpdateAction.ts +16 -2
  23. package/app/Actions/Dashboard/Models/model-destroy.ts +75 -0
  24. package/app/Actions/Dashboard/Models/model-options.ts +56 -0
  25. package/app/Actions/Dashboard/Models/model-related.ts +202 -0
  26. package/app/Actions/Dashboard/Models/model-relations.ts +172 -0
  27. package/app/Actions/Dashboard/Models/model-write.ts +240 -51
  28. package/app/Actions/Dashboard/Users/UserInviteAction.ts +50 -0
  29. package/app/Actions/Dashboard/Users/user-invitation.ts +110 -0
  30. package/app/Models/Activity.ts +4 -0
  31. package/app/Models/AnalyticsEvent.ts +4 -0
  32. package/app/Models/Automation.ts +4 -0
  33. package/app/Models/AutomationRun.ts +4 -0
  34. package/app/Models/Board.ts +4 -1
  35. package/app/Models/BoardColumn.ts +4 -1
  36. package/app/Models/Campaign.ts +4 -0
  37. package/app/Models/CampaignSend.ts +4 -0
  38. package/app/Models/CampaignVariant.ts +4 -0
  39. package/app/Models/Card.ts +4 -1
  40. package/app/Models/CardAttachment.ts +4 -0
  41. package/app/Models/CommunicationSuppression.ts +4 -0
  42. package/app/Models/ConsentEvent.ts +4 -0
  43. package/app/Models/Deployment.ts +1 -0
  44. package/app/Models/EmailList.ts +4 -0
  45. package/app/Models/EmailListSubscriber.ts +4 -0
  46. package/app/Models/Error.ts +4 -0
  47. package/app/Models/FailedJob.ts +4 -0
  48. package/app/Models/FeedbackToken.ts +4 -0
  49. package/app/Models/GdprRequest.ts +4 -0
  50. package/app/Models/Job.ts +4 -0
  51. package/app/Models/Log.ts +4 -0
  52. package/app/Models/MagicLinkToken.ts +4 -0
  53. package/app/Models/MailPreference.ts +4 -0
  54. package/app/Models/Notification.ts +4 -0
  55. package/app/Models/NotificationDelivery.ts +4 -0
  56. package/app/Models/PersonalAccessToken.ts +4 -0
  57. package/app/Models/QueryLog.ts +4 -0
  58. package/app/Models/Referral.ts +4 -0
  59. package/app/Models/Release.ts +1 -0
  60. package/app/Models/Request.ts +4 -0
  61. package/app/Models/SenderDomain.ts +4 -0
  62. package/app/Models/Site.ts +1 -0
  63. package/app/Models/SiteDomain.ts +4 -0
  64. package/app/Models/SocialPost.ts +4 -0
  65. package/app/Models/StorageItemTask.ts +4 -1
  66. package/app/Models/Subscriber.ts +4 -0
  67. package/app/Models/Subscription.ts +4 -0
  68. package/app/Models/Team.ts +1 -0
  69. package/app/Models/TeamInvitation.ts +1 -0
  70. package/app/Models/TeamMember.ts +1 -0
  71. package/app/Models/UsageEvent.ts +4 -0
  72. package/app/Models/User.ts +15 -3
  73. package/functions/dashboard-model-record.test.ts +276 -18
  74. package/functions/dashboard-model-record.ts +412 -55
  75. package/functions/data.ts +2 -0
  76. package/ide/vscode/package.json +1 -1
  77. package/package.json +5 -5
  78. package/resources/components/Dashboard/Analytics/AnalyticsHub.stx +1 -1
  79. package/resources/components/Dashboard/Analytics/CampaignAnalytics.stx +1 -1
  80. package/resources/components/Dashboard/Analytics/EventAnalytics.stx +1 -1
  81. package/resources/components/Dashboard/Analytics/SalesAnalytics.stx +1 -1
  82. package/resources/components/Dashboard/Analytics/WebAnalyticsBreakdown.stx +1 -1
  83. package/resources/components/Dashboard/App/RequestsOverview.stx +1 -1
  84. package/resources/components/Dashboard/App/SourceInventory.stx +1 -1
  85. package/resources/components/Dashboard/Auth/AccessTokens.stx +1 -1
  86. package/resources/components/Dashboard/Buddy/BuddyAssistant.stx +1 -1
  87. package/resources/components/Dashboard/Ci/CiDashboard.stx +1 -1
  88. package/resources/components/Dashboard/Commerce/Delivery/DeliveryPagination.stx +1 -1
  89. package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +1 -1
  90. package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +1 -1
  91. package/resources/components/Dashboard/Content/BlogDashboard.stx +1 -1
  92. package/resources/components/Dashboard/DashboardLayout.stx +1 -1
  93. package/resources/components/Dashboard/Data/DataRecords.stx +43 -22
  94. package/resources/components/Dashboard/Data/UserInvite.stx +107 -0
  95. package/resources/components/Dashboard/Email/CapturedMailDashboard.stx +1 -1
  96. package/resources/components/Dashboard/Email/EmailActivityDashboard.stx +1 -1
  97. package/resources/components/Dashboard/Email/InboxDashboard.stx +1 -1
  98. package/resources/components/Dashboard/Email/InboxMessageDetail.stx +2 -2
  99. package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +1 -1
  100. package/resources/components/Dashboard/Home/DashboardHome.stx +6 -1
  101. package/resources/components/Dashboard/Infrastructure/CloudDashboard.stx +1 -1
  102. package/resources/components/Dashboard/Infrastructure/DnsDashboard.stx +1 -1
  103. package/resources/components/Dashboard/Infrastructure/HealthDashboard.stx +1 -1
  104. package/resources/components/Dashboard/Infrastructure/InsightsDashboard.stx +1 -1
  105. package/resources/components/Dashboard/Infrastructure/LogsDashboard.stx +1 -1
  106. package/resources/components/Dashboard/Infrastructure/MailboxesDashboard.stx +1 -1
  107. package/resources/components/Dashboard/Infrastructure/ServerDetailsDashboard.stx +1 -1
  108. package/resources/components/Dashboard/Infrastructure/ServerlessDashboard.stx +1 -1
  109. package/resources/components/Dashboard/Infrastructure/ServersDashboard.stx +1 -1
  110. package/resources/components/Dashboard/Jobs/JobDetail.stx +1 -1
  111. package/resources/components/Dashboard/Jobs/JobTable.stx +2 -2
  112. package/resources/components/Dashboard/Kanban/KanbanBoardDashboard.stx +1 -1
  113. package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +1 -1
  114. package/resources/components/Dashboard/Management/PermissionsDashboard.stx +1 -1
  115. package/resources/components/Dashboard/Marketing/AbandonedCartsDashboard.stx +1 -1
  116. package/resources/components/Dashboard/Marketing/CampaignsDashboard.stx +1 -1
  117. package/resources/components/Dashboard/Marketing/MarketingListsDashboard.stx +1 -1
  118. package/resources/components/Dashboard/Marketing/SocialPostsDashboard.stx +1 -1
  119. package/resources/components/Dashboard/Models/ModelFieldInputs.stx +125 -0
  120. package/resources/components/Dashboard/Models/ModelRecordCreate.stx +24 -66
  121. package/resources/components/Dashboard/Models/ModelRecordDetail.stx +36 -8
  122. package/resources/components/Dashboard/Models/ModelRecordEdit.stx +36 -32
  123. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +72 -28
  124. package/resources/components/Dashboard/Models/ModelRelatedPanels.stx +99 -0
  125. package/resources/components/Dashboard/Models/ModelRelationPicker.stx +247 -0
  126. package/resources/components/Dashboard/Models/ModelsOverview.stx +1 -1
  127. package/resources/components/Dashboard/Notifications/NotificationDeliveries.stx +1 -1
  128. package/resources/components/Dashboard/Notifications/NotificationDeliveryHistory.stx +1 -1
  129. package/resources/components/Dashboard/Notifications/NotificationDeliveryOverview.stx +1 -1
  130. package/resources/components/Dashboard/Queries/QueryDashboard.stx +1 -1
  131. package/resources/components/Dashboard/Queries/QueryDetail.stx +1 -1
  132. package/resources/components/Dashboard/Queue/QueueDashboard.stx +1 -1
  133. package/resources/components/Dashboard/Realtime/RealtimeDashboard.stx +1 -1
  134. package/resources/components/Dashboard/Releases/ReleaseDashboard.stx +1 -1
  135. package/resources/components/Dashboard/Search/SearchEngineDashboard.stx +1 -1
  136. package/resources/components/Dashboard/Settings/MailSettingsDashboard.stx +1 -1
  137. package/resources/components/Dashboard/Settings/SettingsDashboard.stx +1 -1
  138. package/resources/components/Dashboard/Teams/TeamPeopleDashboard.stx +1 -1
  139. package/resources/components/Dashboard/UI/Drawer.stx +1 -1
  140. package/resources/components/Dashboard/UI/Input.stx +3 -2
  141. package/resources/components/Dashboard/UI/Modal.stx +1 -1
  142. package/resources/components/Dashboard/UI/Select.stx +8 -4
  143. package/resources/components/Dashboard/UI/Textarea.stx +18 -12
  144. package/resources/emails/password-reset.stx +3 -1
  145. package/routes/dashboard-api.ts +9 -0
  146. package/scaffold/config/analytics.ts +5 -3
  147. package/scaffold/resources/components/NextStep.stx +13 -0
  148. package/scaffold/resources/partials/head.stx +31 -0
  149. package/scaffold/resources/views/index.stx +23 -47
  150. package/scaffold/resources/views/layouts/default.stx +23 -0
  151. package/views/dashboard/data/users/invite.stx +8 -0
  152. package/views/dashboard/layouts/default.stx +21 -2
@@ -6,9 +6,11 @@
6
6
  * casts and no observers; writing to it from a generic admin screen would
7
7
  * bypass every guarantee the ORM makes. Those rows stay read-only.
8
8
  */
9
+ import { GDPR_SUBJECT_MODEL } from '@stacksjs/orm'
9
10
  import { resolveDashboardModel } from '../../../../resources/functions/dashboard/model-access'
10
11
  import { dashboardOperationalIssue } from '../dashboard-response'
11
12
  import { modelApiConfiguration } from './model-api'
13
+ import { belongsToRelations } from './model-relations'
12
14
 
13
15
  /** Never writable from a generic admin table, whatever the model declares. */
14
16
  export const PROTECTED_COLUMNS: ReadonlySet<string> = new Set([
@@ -54,15 +56,41 @@ export interface ModelWriteCapabilities {
54
56
  create: boolean
55
57
  update: boolean
56
58
  destroy: boolean
59
+ /**
60
+ * New rows are added by invitation: the account is created and its holder
61
+ * is mailed a link to choose their password. True for `User` when the
62
+ * dashboard may create one, since no form can supply a password for it.
63
+ */
64
+ invite: boolean
65
+ /**
66
+ * A delete the database refuses, because other records still point at the
67
+ * row, anonymizes it instead: its personal details are removed and the
68
+ * records are kept. True for the model the app's erasure rules are about
69
+ * (`User`), so the confirmation can say so before anything is pressed.
70
+ */
71
+ anonymize: boolean
57
72
  }
58
73
 
74
+ /**
75
+ * How a field is asked for in a form.
76
+ *
77
+ * `longtext` is prose (a description, a message body) and gets a multi-line
78
+ * box; `json` is a structured value the app reads back, edited as text and
79
+ * checked before it is stored; `datetime` is a moment, picked in the visitor's
80
+ * own time zone; `relation` is another model's record, picked by name and
81
+ * stored as its id.
82
+ */
83
+ export type ModelFieldType = 'boolean' | 'date' | 'datetime' | 'email' | 'enum' | 'json' | 'longtext' | 'number' | 'relation' | 'text'
84
+
59
85
  export interface ModelCreateField {
60
86
  name: string
61
87
  label: string
62
- type: 'boolean' | 'date' | 'datetime' | 'email' | 'enum' | 'number' | 'text'
88
+ type: ModelFieldType
63
89
  required: boolean
64
90
  defaultValue: unknown
65
91
  options: string[]
92
+ /** For a `relation`: the model whose records the picker lists. */
93
+ relation?: { model: string, slug: string, label: string }
66
94
  }
67
95
 
68
96
  export interface PreparedModelFields {
@@ -77,14 +105,41 @@ function snakeCase(name: string): string {
77
105
  .toLowerCase()
78
106
  }
79
107
 
80
- function humanize(name: string): string {
108
+ /** Initialisms a label keeps in capitals: "Image URL", not "Image Url". */
109
+ const INITIALISMS: ReadonlySet<string> = new Set([
110
+ 'api', 'css', 'csv', 'dns', 'html', 'id', 'ip', 'json', 'mfa', 'otp', 'pdf',
111
+ 'seo', 'sku', 'sms', 'ssl', 'tls', 'uri', 'url', 'utm', 'uuid', 'vat',
112
+ ])
113
+
114
+ /**
115
+ * A model, attribute or column name as a person reads it: `SocialPost` is
116
+ * "Social Post", `imageUrl` and `image_url` are both "Image URL", `userIds`
117
+ * is "User IDs".
118
+ *
119
+ * One function for every label the model pages show. There were two, one
120
+ * that knew "URL" and one that did not, so a field was "Image URL" on its
121
+ * record's page and "Image Url" in its form.
122
+ */
123
+ export function humanizeIdentifier(name: string): string {
81
124
  return name
82
125
  .replace(/([a-z\d])([A-Z])/g, '$1 $2')
83
- .replace(/_/g, ' ')
84
- .replace(/\b\w/g, character => character.toUpperCase())
85
- .replace(/\bId\b/g, 'ID')
126
+ .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')
127
+ .replace(/[_\s-]+/g, ' ')
128
+ .trim()
129
+ .split(' ')
130
+ .map((word) => {
131
+ const lower = word.toLowerCase()
132
+ if (INITIALISMS.has(lower))
133
+ return lower.toUpperCase()
134
+ if (lower.endsWith('s') && INITIALISMS.has(lower.slice(0, -1)))
135
+ return `${lower.slice(0, -1).toUpperCase()}s`
136
+ return word.charAt(0).toUpperCase() + word.slice(1)
137
+ })
138
+ .join(' ')
86
139
  }
87
140
 
141
+ const humanize = humanizeIdentifier
142
+
88
143
  /**
89
144
  * Derive the physical columns declared by a model when its table has no rows
90
145
  * to inspect. This mirrors model-driven migrations closely enough for the
@@ -121,6 +176,37 @@ export function modelSchemaColumns(Model: any): string[] {
121
176
  return columns
122
177
  }
123
178
 
179
+ /**
180
+ * The columns a model's list shows, from the ones its table has.
181
+ *
182
+ * `dashboard.columns` when the model names them, in its order; every column
183
+ * otherwise. A name may be the attribute, the column, or a `belongsTo`
184
+ * (`team` for `team_id`). Anything the table does not have is reported back
185
+ * instead of drawn as an empty column, and a list of nothing but such names
186
+ * falls back to every column: a typo should not empty the page.
187
+ */
188
+ export function modelListColumns(Model: any, available: string[]): { columns: string[], unknown: string[], declared: boolean } {
189
+ const names = Model?.dashboard?.columns
190
+ if (!Array.isArray(names) || names.length === 0)
191
+ return { columns: available, unknown: [], declared: false }
192
+
193
+ const relations = belongsToRelations(Model)
194
+ const columns: string[] = []
195
+ const unknown: string[] = []
196
+ for (const name of names) {
197
+ if (typeof name !== 'string' || !name.trim())
198
+ continue
199
+ const column = snakeCase(name.trim())
200
+ const relation = relations.find(candidate => candidate.column === `${column}_id` || snakeCase(candidate.model) === column)
201
+ const resolved = available.includes(column) ? column : relation && available.includes(relation.column) ? relation.column : null
202
+ if (!resolved)
203
+ unknown.push(name)
204
+ else if (!columns.includes(resolved))
205
+ columns.push(resolved)
206
+ }
207
+ return columns.length > 0 ? { columns, unknown, declared: true } : { columns: available, unknown, declared: false }
208
+ }
209
+
124
210
  function isProtectedField(name: string): boolean {
125
211
  const column = name
126
212
  .replace(/([a-z\d])([A-Z])/g, '$1_$2')
@@ -151,25 +237,114 @@ export function uncollectableRequiredFields(Model: any): string[] {
151
237
  return names
152
238
  }
153
239
 
240
+ const MODEL_WRITE_OPERATIONS: readonly ModelWriteOperation[] = ['store', 'update', 'destroy']
241
+
242
+ /**
243
+ * The writes the dashboard offers for a model.
244
+ *
245
+ * `dashboard.writes` when the model names them, and otherwise the write
246
+ * routes its `useApi` trait declares. The two are separate on purpose: the
247
+ * API is what a client may do to its own data, the dashboard is what an
248
+ * operator may do to anyone's. `User` keeps `update` and `destroy` off its
249
+ * API, where they would let a caller change their own email and password
250
+ * outside the flows that verify them, and still has to be editable here.
251
+ *
252
+ * Anything in the list that is not a write is ignored rather than trusted,
253
+ * and a value that is not a list reads as unset.
254
+ */
255
+ export function modelDashboardWrites(Model: any): ModelWriteOperation[] {
256
+ const declared = Model?.dashboard?.writes
257
+ const source: unknown[] = Array.isArray(declared) ? declared : modelApiConfiguration(Model).routes
258
+ return MODEL_WRITE_OPERATIONS.filter(operation => source.includes(operation))
259
+ }
260
+
261
+ /** Whether rows of this model are the accounts people sign in with. */
262
+ export function isAccountModel(Model: any): boolean {
263
+ const traits = Model?.traits ?? {}
264
+ return Boolean(traits.useAuth ?? traits.authenticatable)
265
+ }
266
+
154
267
  export function modelWriteCapabilities(Model: any): ModelWriteCapabilities {
155
- const routes = modelApiConfiguration(Model).routes
268
+ const writes = modelDashboardWrites(Model)
156
269
  return {
157
- // A store route is not enough: the form has to be able to supply every
158
- // field a new row requires.
159
- create: routes.includes('store') && uncollectableRequiredFields(Model).length === 0,
160
- update: routes.includes('update'),
161
- destroy: routes.includes('destroy'),
270
+ // Being allowed to create is not enough: the form has to be able to
271
+ // supply every field a new row requires.
272
+ create: writes.includes('store') && uncollectableRequiredFields(Model).length === 0,
273
+ update: writes.includes('update'),
274
+ destroy: writes.includes('destroy'),
275
+ // The invitation mails the framework's account-setup link, which is the
276
+ // `users` table's, so this is `User` and not every model with `useAuth`.
277
+ invite: writes.includes('store') && Model?.name === 'User' && isAccountModel(Model),
278
+ anonymize: writes.includes('destroy') && isErasureSubject(Model),
162
279
  }
163
280
  }
164
281
 
165
- function relationFieldName(relation: string): string {
166
- const words = relation
167
- .trim()
168
- .replace(/([a-z\d])([A-Z])/g, '$1_$2')
169
- .toLowerCase()
170
- .split('_')
171
- .filter(Boolean)
172
- return `${words[0]}${words.slice(1).map(word => `${word[0]?.toUpperCase()}${word.slice(1)}`).join('')}Id`
282
+ /**
283
+ * Whether this is the model the app's erasure rules are about: the person a
284
+ * data-subject request names, whose rows every other model's `gdpr` trait
285
+ * says to delete, anonymize or keep. `User`, by `GDPR_SUBJECT_MODEL`.
286
+ */
287
+ export function isErasureSubject(Model: any): boolean {
288
+ return Model?.name === GDPR_SUBJECT_MODEL
289
+ }
290
+
291
+ /**
292
+ * Field errors for a write the database refused as a duplicate.
293
+ *
294
+ * The driver names the constraint, not the field, and not in one spelling
295
+ * across SQLite, MySQL and Postgres. The model does know which of the columns
296
+ * being written it marks `unique`, and that is who the message is for: the
297
+ * one unique field in the request is the duplicate. With several, each is
298
+ * named, because any of them may be. Keyed by attribute name, like every
299
+ * other field error these endpoints return.
300
+ */
301
+ export function duplicateFieldErrors(Model: any, columns: string[]): Record<string, string[]> {
302
+ const errors: Record<string, string[]> = {}
303
+ for (const [name, definition] of Object.entries((Model?.attributes ?? {}) as Record<string, any>)) {
304
+ if (definition?.unique === true && columns.includes(snakeCase(name)))
305
+ errors[name] = [`${humanize(name)} is already in use.`]
306
+ }
307
+ return errors
308
+ }
309
+
310
+ /** Rule names the migrations store as a moment: a `timestamp` or `datetime` column. */
311
+ const MOMENT_RULES: ReadonlySet<string> = new Set(['timestamp', 'timestampTz', 'datetime'])
312
+
313
+ /** Rule names stored as a number, and refused when sent as a string. */
314
+ const NUMBER_RULES: ReadonlySet<string> = new Set(['number', 'integer', 'float', 'unix'])
315
+
316
+ /**
317
+ * How a model attribute is asked for in a form, from its validation rule.
318
+ *
319
+ * Three of these used to be wrong in ways that failed on save, not only in
320
+ * how they looked. A `timestamp` was a number box, though its column is a
321
+ * timestamp and the number it invited was refused by the database. A `float`
322
+ * and a `unix` time were text boxes, and the text they sent was refused by
323
+ * their own rule. And prose and JSON shared one line of text with a name.
324
+ */
325
+ export function modelFieldType(name: string, definition: any): ModelFieldType {
326
+ const rule = definition?.validation?.rule
327
+ const ruleName = String(rule?.name || definition?.type || 'string')
328
+ const declared = String(definition?.type || '').toLowerCase()
329
+ if ((Array.isArray(rule?.allowedValues) && rule.allowedValues.length > 0) || ruleName === 'enum')
330
+ return 'enum'
331
+ if (ruleName === 'boolean')
332
+ return 'boolean'
333
+ if (NUMBER_RULES.has(ruleName))
334
+ return 'number'
335
+ if (ruleName === 'date')
336
+ return 'date'
337
+ if (MOMENT_RULES.has(ruleName))
338
+ return 'datetime'
339
+ if (ruleName === 'json' || declared === 'json' || declared === 'jsonb')
340
+ return 'json'
341
+ // The attribute's own `type: 'text'` is what makes its column TEXT and not a
342
+ // short string: the model saying the value is long.
343
+ if (ruleName === 'text' || declared === 'text')
344
+ return 'longtext'
345
+ if (name.toLowerCase().includes('email'))
346
+ return 'email'
347
+ return 'text'
173
348
  }
174
349
 
175
350
  export function modelCreateFields(Model: any): ModelCreateField[] {
@@ -180,21 +355,8 @@ export function modelCreateFields(Model: any): ModelCreateField[] {
180
355
  if (!definition?.fillable || definition.hidden || isProtectedField(name))
181
356
  continue
182
357
  const rule = definition.validation?.rule
183
- const ruleName = String(rule?.name || definition.type || 'string')
184
358
  const options = Array.isArray(rule?.allowedValues) ? rule.allowedValues.map(String) : []
185
- let type: ModelCreateField['type'] = 'text'
186
- if (options.length > 0 || ruleName === 'enum')
187
- type = 'enum'
188
- else if (ruleName === 'number' || ruleName === 'integer' || ruleName === 'timestamp')
189
- type = 'number'
190
- else if (ruleName === 'boolean')
191
- type = 'boolean'
192
- else if (ruleName === 'date')
193
- type = 'date'
194
- else if (ruleName === 'datetime' || ruleName === 'timestampTz')
195
- type = 'datetime'
196
- else if (name.toLowerCase().includes('email'))
197
- type = 'email'
359
+ const type = modelFieldType(name, definition)
198
360
 
199
361
  fields.push({
200
362
  name,
@@ -206,20 +368,19 @@ export function modelCreateFields(Model: any): ModelCreateField[] {
206
368
  })
207
369
  }
208
370
 
209
- for (const relation of Model?.belongsTo ?? []) {
210
- if (typeof relation !== 'string' || !relation.trim())
371
+ // A `belongsTo` is asked for as the record it points at, by name. Whether
372
+ // the model also spells the key out as an attribute (`userId`) or leaves it
373
+ // to the relation, it is one field, and it is the picker.
374
+ for (const relation of belongsToRelations(Model)) {
375
+ if (isProtectedField(relation.field))
211
376
  continue
212
- const name = relationFieldName(relation)
213
- if (fields.some(field => field.name === name) || isProtectedField(name))
377
+ const asRelation = { type: 'relation' as const, label: humanize(relation.model), relation: { model: relation.model, slug: relation.slug, label: humanize(relation.model) } }
378
+ const declared = fields.find(field => field.name === relation.field)
379
+ if (declared) {
380
+ Object.assign(declared, asRelation, { options: [] })
214
381
  continue
215
- fields.push({
216
- name,
217
- label: humanize(name),
218
- type: 'number',
219
- required: false,
220
- defaultValue: '',
221
- options: [],
222
- })
382
+ }
383
+ fields.push({ name: relation.field, required: false, defaultValue: '', options: [], ...asRelation })
223
384
  }
224
385
 
225
386
  return fields.sort((left, right) => {
@@ -234,8 +395,13 @@ export function modelWritableColumns(Model: any): string[] {
234
395
  return modelCreateFields(Model).map(field => snakeCase(field.name))
235
396
  }
236
397
 
237
- function normalizeModelValue(type: ModelCreateField['type'], value: unknown): unknown {
238
- if (type === 'number') {
398
+ /** A moment as the framework stores one: UTC, `YYYY-MM-DD HH:MM:SS`. */
399
+ function storedMoment(date: Date): string {
400
+ return date.toISOString().slice(0, 19).replace('T', ' ')
401
+ }
402
+
403
+ function normalizeModelValue(type: ModelCreateField['type'], value: unknown, rule?: any): unknown {
404
+ if (type === 'number' || type === 'relation') {
239
405
  if (value === '' || value === null || value === undefined)
240
406
  return null
241
407
  const number = Number(value)
@@ -243,6 +409,20 @@ function normalizeModelValue(type: ModelCreateField['type'], value: unknown): un
243
409
  }
244
410
  if (type === 'boolean')
245
411
  return value === true || value === 1 || value === '1' || value === 'true' || value === 'on'
412
+ if (type === 'datetime' && typeof value === 'string' && value.trim()) {
413
+ // The form sends the instant with its offset, so the visitor's zone is
414
+ // already accounted for. Stored the way the framework writes every other
415
+ // timestamp; a `T` and a `Z` are not a datetime to MySQL. The one rule
416
+ // that keeps a zone gets the full ISO string it asks for.
417
+ const moment = new Date(value)
418
+ if (Number.isNaN(moment.getTime()))
419
+ return value
420
+ return rule?.name === 'timestampTz' ? moment.toISOString() : storedMoment(moment)
421
+ }
422
+ if (type === 'json' && value !== null && value !== undefined && typeof value !== 'string') {
423
+ // An API caller may send the value itself; the rule and the column take text.
424
+ return JSON.stringify(value)
425
+ }
246
426
  return value
247
427
  }
248
428
 
@@ -287,7 +467,7 @@ export function prepareModelFields(
287
467
  }
288
468
 
289
469
  const rawValue = hasAttribute ? body[field.name] : body[column]
290
- const value = normalizeModelValue(field.type, rawValue)
470
+ const value = normalizeModelValue(field.type, rawValue, attributes[field.name]?.validation?.rule)
291
471
  if ((value === '' || value === null || value === undefined) && field.required) {
292
472
  errors[field.name] = [`${field.label} is required.`]
293
473
  continue
@@ -298,6 +478,13 @@ export function prepareModelFields(
298
478
  continue
299
479
  }
300
480
 
481
+ // An id is a whole number above zero, whatever else the field's own rule
482
+ // allows. Whether that record exists is the database's to say.
483
+ if (field.type === 'relation' && !(typeof value === 'number' && Number.isSafeInteger(value) && value > 0)) {
484
+ errors[field.name] = [`${field.label} must be chosen from the list.`]
485
+ continue
486
+ }
487
+
301
488
  const definition = attributes[field.name]
302
489
  const rule = definition?.validation?.rule
303
490
  if (rule && typeof rule.validate === 'function') {
@@ -339,13 +526,15 @@ export async function resolveWritableModel(slug: string, operation?: ModelWriteO
339
526
  if (!Model || typeof Model.find !== 'function')
340
527
  return { error: `No ORM model named ${modelName}. Rows from tables without a model are read-only.`, status: 404 }
341
528
  if (operation) {
342
- if (!modelApiConfiguration(Model).routes.includes(operation))
343
- return { error: `${modelName} does not declare the ${operation} route in its useApi trait.`, status: 405 }
529
+ if (!modelDashboardWrites(Model).includes(operation)) {
530
+ const verb = { store: 'created', update: 'edited', destroy: 'deleted' }[operation]
531
+ return { error: `${modelName} records cannot be ${verb} from the dashboard: the model allows it in neither \`dashboard.writes\` nor its \`useApi\` routes.`, status: 405 }
532
+ }
344
533
  if (operation === 'store') {
345
534
  const missing = uncollectableRequiredFields(Model)
346
535
  if (missing.length > 0) {
347
536
  return {
348
- error: `${modelName} records cannot be created from the dashboard: ${missing.map(humanize).join(', ')} ${missing.length === 1 ? 'is' : 'are'} required and the create form does not collect ${missing.length === 1 ? 'it' : 'them'}.`,
537
+ error: `${modelName} records cannot be created from the dashboard: ${missing.map(humanize).join(', ')} ${missing.length === 1 ? 'is' : 'are'} required and the create form does not collect ${missing.length === 1 ? 'it' : 'them'}.${modelWriteCapabilities(Model).invite ? ' Invite the user instead.' : ''}`,
349
538
  status: 405,
350
539
  }
351
540
  }
@@ -0,0 +1,50 @@
1
+ import type { RequestInstance } from '@stacksjs/types'
2
+ import type { InviteUserInput } from './user-invitation'
3
+ import { Action } from '@stacksjs/actions/runtime'
4
+ import { findAuthUserRowByEmail, passwordResets } from '@stacksjs/auth'
5
+ import { db } from '@stacksjs/database/runtime'
6
+ import { response } from '@stacksjs/router'
7
+ import { dashboardOperationalError } from '../dashboard-response'
8
+ import { modelWriteCapabilities, resolveWritableModel } from '../Models/model-write'
9
+ import { inviteUser, USER_INVITATION_DAYS } from './user-invitation'
10
+
11
+ /**
12
+ * `POST /api/dashboard/users/invitations`.
13
+ *
14
+ * Adds a user from the dashboard: creates the account and mails its holder a
15
+ * link to choose their password. See `./user-invitation` for why a user is
16
+ * invited and not typed in.
17
+ */
18
+ export default new Action({
19
+ name: 'Dashboard User Invite',
20
+ description: 'Creates a user account and emails its holder a link to choose their password.',
21
+ method: 'POST',
22
+ apiResponse: true,
23
+ async handle(request: RequestInstance<InviteUserInput>) {
24
+ const resolved = await resolveWritableModel('user')
25
+ if ('error' in resolved)
26
+ return response.json({ message: resolved.error }, resolved.status)
27
+ if (!modelWriteCapabilities(resolved.Model).invite)
28
+ return response.json({ message: 'Users cannot be invited from the dashboard: the User model does not allow `store` in `dashboard.writes`.' }, 405)
29
+
30
+ const input = request.all()
31
+ const result = await inviteUser({ name: input.name, email: input.email }, {
32
+ Model: resolved.Model,
33
+ findUserByEmail: findAuthUserRowByEmail,
34
+ clearSetupLinks: async (email) => {
35
+ await db.deleteFrom('password_resets').where('email', '=', email).execute()
36
+ },
37
+ sendSetupLink: (email, expiresAt) => passwordResets(email).sendEmail({ purpose: 'setup', expiresAt }),
38
+ })
39
+
40
+ if (result.ok)
41
+ return { ok: true, id: result.id, email: result.email, expiresInDays: USER_INVITATION_DAYS }
42
+ if (result.reason === 'invalid')
43
+ return response.json({ message: 'Validation failed.', errors: result.errors }, 422)
44
+ if (result.reason === 'undelivered')
45
+ return dashboardOperationalError(result.cause, 'The invitation email could not be sent, so no account was created. Check the mail settings and try again.', 'UserInviteAction.deliver', 502)
46
+ if (result.reason === 'stranded')
47
+ return dashboardOperationalError(result.cause, 'The account was created, but the invitation email could not be sent. The person can choose a password with "Forgot password" on the sign-in page.', 'UserInviteAction.cleanup', 500)
48
+ return dashboardOperationalError(result.cause, 'The user could not be created.', 'UserInviteAction', 500)
49
+ },
50
+ })
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Adding a user from the dashboard, by invitation.
3
+ *
4
+ * An account's password is its holder's to choose, so an operator cannot type
5
+ * a new user in: the form has no password to give, and one typed by somebody
6
+ * else would have to travel to the person some other way. Instead the account
7
+ * is created with a password nobody knows and the person is mailed a link to
8
+ * choose their own, the framework's account-setup link
9
+ * (`passwordResets().sendEmail({ purpose: 'setup' })`).
10
+ *
11
+ * An invitation that was not delivered leaves no account behind. Otherwise a
12
+ * mail outage would fill the Users page with accounts whose holders were
13
+ * never told they exist, and the operator's retry would be refused as a
14
+ * duplicate.
15
+ */
16
+ import { randomBytes } from 'node:crypto'
17
+ import { isUniqueViolation, ModelValidationError, toSnakeCaseKeys } from '@stacksjs/orm'
18
+ import { prepareModelFields } from '../Models/model-write'
19
+
20
+ /** How long the link in the invitation works. Long enough to survive a weekend. */
21
+ export const USER_INVITATION_DAYS = 7
22
+
23
+ const DAY_MS = 86_400_000
24
+
25
+ export interface InviteUserInput {
26
+ name?: unknown
27
+ email?: unknown
28
+ }
29
+
30
+ export interface InviteUserDependencies {
31
+ /** The `User` model: validates, hashes the password and writes the row. */
32
+ Model: any
33
+ /** The account that already holds this address, when there is one. */
34
+ findUserByEmail: (email: string) => Promise<unknown>
35
+ /**
36
+ * Remove setup and reset links left for this address. It has no account at
37
+ * this point, so any that exist belong to an account that is gone: left
38
+ * alone, one would throttle this invitation, or open the new account to
39
+ * whoever still holds the old mail.
40
+ */
41
+ clearSetupLinks: (email: string) => Promise<void>
42
+ /** Mail the link. False when none was sent; throws when the mailer does. */
43
+ sendSetupLink: (email: string, expiresAt: Date) => Promise<boolean>
44
+ now?: () => Date
45
+ }
46
+
47
+ export type InviteUserResult
48
+ = | { ok: true, id: number | string, email: string, expiresAt: Date }
49
+ | { ok: false, reason: 'invalid', errors: Record<string, string[]> }
50
+ | { ok: false, reason: 'undelivered' | 'stranded' | 'failed', cause: unknown }
51
+
52
+ function normalizeEmail(value: unknown): string {
53
+ return typeof value === 'string' ? value.trim().toLowerCase() : ''
54
+ }
55
+
56
+ const TAKEN = 'A user with this email already exists.'
57
+
58
+ export async function inviteUser(input: InviteUserInput, dependencies: InviteUserDependencies): Promise<InviteUserResult> {
59
+ const { Model } = dependencies
60
+ const email = normalizeEmail(input.email)
61
+ const name = typeof input.name === 'string' ? input.name.trim() : input.name
62
+ const { data, errors } = prepareModelFields(Model, { name, email })
63
+ if (Object.keys(errors).length > 0)
64
+ return { ok: false, reason: 'invalid', errors }
65
+
66
+ if (await dependencies.findUserByEmail(email))
67
+ return { ok: false, reason: 'invalid', errors: { email: [TAKEN] } }
68
+
69
+ let id: number | string
70
+ try {
71
+ await dependencies.clearSetupLinks(email)
72
+ // Never shown, mailed or logged: it only has to satisfy the column until
73
+ // the person replaces it. The model hashes it like any other password.
74
+ const password = randomBytes(24).toString('base64url')
75
+ const row = await Model.create({ ...toSnakeCaseKeys(data), password })
76
+ id = row?.id ?? row?.attributes?.id
77
+ if (id === undefined || id === null)
78
+ throw new Error('The created user came back without an id.')
79
+ }
80
+ catch (error) {
81
+ if (error instanceof ModelValidationError)
82
+ return { ok: false, reason: 'invalid', errors: error.errors }
83
+ // Two operators inviting one address at once: the second loses here.
84
+ if (isUniqueViolation(error))
85
+ return { ok: false, reason: 'invalid', errors: { email: [TAKEN] } }
86
+ return { ok: false, reason: 'failed', cause: error }
87
+ }
88
+
89
+ const now = dependencies.now?.() ?? new Date()
90
+ const expiresAt = new Date(now.getTime() + USER_INVITATION_DAYS * DAY_MS)
91
+ let cause: unknown = new Error('No setup link was issued for the new account.')
92
+ try {
93
+ if (await dependencies.sendSetupLink(email, expiresAt))
94
+ return { ok: true, id, email, expiresAt }
95
+ }
96
+ catch (error) {
97
+ cause = error
98
+ }
99
+
100
+ try {
101
+ const row = await Model.find(id)
102
+ await row?.delete()
103
+ await dependencies.clearSetupLinks(email)
104
+ }
105
+ catch (error) {
106
+ // The account exists and its holder was never told. Say exactly that.
107
+ return { ok: false, reason: 'stranded', cause: new AggregateError([cause, error], 'The invitation was not delivered and its account could not be removed.') }
108
+ }
109
+ return { ok: false, reason: 'undelivered', cause }
110
+ }
@@ -95,4 +95,8 @@ export default defineModel({
95
95
  factory: faker => faker.internet.ip(),
96
96
  },
97
97
  },
98
+
99
+ dashboard: {
100
+ columns: ['description', 'type', 'subjectType', 'causer', 'createdAt'],
101
+ },
98
102
  } as const)
@@ -73,4 +73,8 @@ export default defineModel({
73
73
  },
74
74
  },
75
75
  },
76
+
77
+ dashboard: {
78
+ columns: ['name', 'category', 'path', 'value', 'createdAt'],
79
+ },
76
80
  } as const)
@@ -20,4 +20,8 @@ export default defineModel({
20
20
  graph: { required: true, fillable: true, validation: { rule: schema.json() }, factory: () => JSON.stringify({ nodes: [], edges: [] }) },
21
21
  publishedAt: { required: false, fillable: true, validation: { rule: schema.timestamp() }, factory: () => null },
22
22
  },
23
+
24
+ dashboard: {
25
+ columns: ['name', 'status', 'version', 'team', 'publishedAt'],
26
+ },
23
27
  } as const)
@@ -23,4 +23,8 @@ export default defineModel({
23
23
  finishedAt: { required: false, fillable: true, validation: { rule: schema.timestamp() }, factory: () => null },
24
24
  error: { type: 'text', required: false, fillable: true, validation: { rule: schema.string() }, factory: () => null },
25
25
  },
26
+
27
+ dashboard: {
28
+ columns: ['automation', 'status', 'subjectType', 'startedAt', 'finishedAt'],
29
+ },
26
30
  } as const)
@@ -113,5 +113,8 @@ export default defineModel({
113
113
  // not the auto-derived `/models/board` viewer — the sidebar entry is
114
114
  // hand-added in `dashboard-utils.ts` / `sidebar.ts` and points at
115
115
  // the real page. Hiding the auto-row keeps it from double-listing.
116
- dashboard: { enabled: false },
116
+ dashboard: {
117
+ columns: ['name', 'team', 'archived', 'createdAt'],
118
+ enabled: false,
119
+ },
117
120
  } as const)
@@ -86,5 +86,8 @@ export default defineModel({
86
86
  },
87
87
  },
88
88
 
89
- dashboard: { enabled: false },
89
+ dashboard: {
90
+ columns: ['name', 'board', 'position', 'cardLimit'],
91
+ enabled: false,
92
+ },
90
93
  } as const)
@@ -323,4 +323,8 @@ export default defineModel({
323
323
  },
324
324
  },
325
325
  },
326
+
327
+ dashboard: {
328
+ columns: ['name', 'type', 'status', 'emailList', 'scheduledAt', 'sentCount'],
329
+ },
326
330
  } as const)
@@ -190,4 +190,8 @@ export default defineModel({
190
190
  factory: () => JSON.stringify({}),
191
191
  },
192
192
  },
193
+
194
+ dashboard: {
195
+ columns: ['recipient', 'campaign', 'channel', 'status', 'sentAt', 'openedAt'],
196
+ },
193
197
  } as const)
@@ -22,4 +22,8 @@ export default defineModel({
22
22
  conversionCount: { required: true, fillable: true, default: 0, validation: { rule: schema.number().min(0) }, factory: () => 0 },
23
23
  isWinner: { required: true, fillable: true, default: false, validation: { rule: schema.boolean() }, factory: () => false },
24
24
  },
25
+
26
+ dashboard: {
27
+ columns: ['name', 'campaign', 'allocation', 'sentCount', 'openCount', 'clickCount', 'isWinner'],
28
+ },
25
29
  } as const)
@@ -114,5 +114,8 @@ export default defineModel({
114
114
  },
115
115
  },
116
116
 
117
- dashboard: { enabled: false },
117
+ dashboard: {
118
+ columns: ['title', 'board', 'boardColumn', 'user', 'dueDate', 'archived'],
119
+ enabled: false,
120
+ },
118
121
  } as const)