@stacksjs/defaults 0.75.618 → 0.75.621

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 (84) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-auth/SKILL.md +12 -1
  3. package/ai/skills/stacks-auto-imports/SKILL.md +1 -1
  4. package/ai/skills/stacks-commerce/SKILL.md +78 -4
  5. package/ai/skills/stacks-dashboard/SKILL.md +2 -2
  6. package/ai/skills/stacks-database/SKILL.md +1 -1
  7. package/ai/skills/stacks-migrations/SKILL.md +10 -2
  8. package/ai/skills/stacks-mobile/SKILL.md +21 -2
  9. package/ai/skills/stacks-models/SKILL.md +2 -2
  10. package/ai/skills/stacks-native/CATALOG.md +11 -11
  11. package/ai/skills/stacks-orm/SKILL.md +2 -2
  12. package/app/Actions/Dashboard/Commerce/CommerceDiscountDestroyAction.ts +27 -0
  13. package/app/Actions/Dashboard/Commerce/CommerceDiscountStoreAction.ts +28 -0
  14. package/app/Actions/Dashboard/Commerce/CommerceDiscountUpdateAction.ts +30 -0
  15. package/app/Actions/Dashboard/Commerce/CommerceDiscountsAction.ts +42 -0
  16. package/app/Actions/Dashboard/Commerce/CommerceUpsellDestroyAction.ts +31 -0
  17. package/app/Actions/Dashboard/Commerce/CommerceUpsellDetailAction.ts +28 -0
  18. package/app/Actions/Dashboard/Commerce/CommerceUpsellStoreAction.ts +26 -0
  19. package/app/Actions/Dashboard/Commerce/CommerceUpsellUpdateAction.ts +29 -0
  20. package/app/Actions/Dashboard/Commerce/CommerceUpsellsAction.ts +40 -0
  21. package/app/Actions/Dashboard/Commerce/commerce-discount-list.ts +204 -0
  22. package/app/Actions/Dashboard/Commerce/commerce-discount-write.ts +53 -0
  23. package/app/Actions/Dashboard/Commerce/commerce-discounts-upsells.test.ts +228 -0
  24. package/app/Actions/Dashboard/Commerce/commerce-upsell-list.ts +289 -0
  25. package/app/Actions/Dashboard/Commerce/discount-records.ts +392 -0
  26. package/app/Actions/Dashboard/Commerce/upsell-offer-records.ts +307 -0
  27. package/app/Actions/Dashboard/Models/ModelSaveAction.ts +6 -1
  28. package/app/Actions/Dashboard/Models/model-relations.ts +17 -7
  29. package/app/Actions/Dashboard/Models/model-row-writes.ts +9 -8
  30. package/app/Actions/Dashboard/Models/model-write.ts +51 -2
  31. package/app/Actions/Dashboard/Remote/RemoteCommandRunAction.ts +1 -2
  32. package/app/Actions/Dashboard/Remote/RemoteTerminalCloseAction.ts +1 -2
  33. package/app/Actions/Dashboard/Remote/RemoteTerminalInputAction.ts +1 -2
  34. package/app/Actions/Dashboard/Remote/RemoteTerminalOpenAction.ts +1 -2
  35. package/app/Actions/Dashboard/Remote/RemoteTerminalResizeAction.ts +1 -2
  36. package/app/Actions/Dashboard/Remote/RemoteTerminalStreamAction.ts +1 -2
  37. package/app/Actions/Dashboard/Remote/remote-commands.test.ts +2 -2
  38. package/app/Actions/Dashboard/Remote/remote-commands.ts +4 -4
  39. package/app/Actions/Dashboard/Remote/remote-terminal.test.ts +45 -25
  40. package/app/Actions/Dashboard/Remote/remote-terminal.ts +9 -9
  41. package/app/Actions/Storefront/AcceptOrderOfferAction.ts +68 -0
  42. package/app/Actions/Storefront/ApplyDiscountCodeAction.ts +83 -0
  43. package/app/Actions/Storefront/DeclineOrderOfferAction.ts +25 -0
  44. package/app/Actions/Storefront/PlaceOrderAction.ts +135 -72
  45. package/app/Gates.ts +4 -4
  46. package/app/Mail/OrderConfirmation.ts +7 -1
  47. package/app/Models/commerce/Cart.ts +14 -0
  48. package/app/Models/commerce/Discount.ts +255 -0
  49. package/app/Models/commerce/PostPurchaseOffer.ts +175 -0
  50. package/app/Models/commerce/PostPurchaseOfferResponse.ts +145 -0
  51. package/app/Policies/PostPolicy.ts +11 -11
  52. package/app/Storefront/DiscountCodeMessages.ts +12 -0
  53. package/app/Storefront/OrderKey.ts +29 -0
  54. package/app/Storefront/StorefrontPricing.ts +211 -0
  55. package/app/Storefront/UpsellCharge.ts +43 -0
  56. package/ide/vscode/package.json +1 -1
  57. package/package.json +7 -7
  58. package/resources/components/Dashboard/Commerce/CommerceDiscountBreakdown.stx +72 -0
  59. package/resources/components/Dashboard/Commerce/CommerceDiscountDeleteDialog.stx +19 -0
  60. package/resources/components/Dashboard/Commerce/CommerceDiscountDetailsDialog.stx +110 -0
  61. package/resources/components/Dashboard/Commerce/CommerceDiscountDialog.stx +353 -0
  62. package/resources/components/Dashboard/Commerce/CommerceDiscountsDashboard.stx +211 -0
  63. package/resources/components/Dashboard/Commerce/CommerceDiscountsTable.stx +105 -0
  64. package/resources/components/Dashboard/Commerce/CommerceProductPicker.stx +115 -0
  65. package/resources/components/Dashboard/Commerce/CommerceUpsellDeleteDialog.stx +21 -0
  66. package/resources/components/Dashboard/Commerce/CommerceUpsellDetailsDialog.stx +153 -0
  67. package/resources/components/Dashboard/Commerce/CommerceUpsellDialog.stx +191 -0
  68. package/resources/components/Dashboard/Commerce/CommerceUpsellsDashboard.stx +214 -0
  69. package/resources/components/Dashboard/Commerce/CommerceUpsellsTable.stx +91 -0
  70. package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +4 -19
  71. package/resources/components/Dashboard/Settings/SettingsDashboard.stx +5 -3
  72. package/resources/components/Dashboard/UI/SearchFilter.stx +7 -4
  73. package/resources/components/Storefront/OrderSummary.stx +17 -0
  74. package/resources/functions/dashboard/sidebar.ts +4 -1
  75. package/resources/views/cart.stx +50 -16
  76. package/resources/views/checkout/contact.stx +11 -5
  77. package/resources/views/checkout/payment.stx +11 -5
  78. package/resources/views/checkout/shipping.stx +11 -5
  79. package/resources/views/orders/[id].stx +227 -50
  80. package/routes/dashboard-api.ts +12 -0
  81. package/routes/dashboard.ts +2 -0
  82. package/routes/storefront.ts +8 -0
  83. package/views/dashboard/commerce/discounts/index.stx +10 -0
  84. package/views/dashboard/commerce/upsells/index.stx +10 -0
@@ -0,0 +1,307 @@
1
+ import { commerceIdentifier, commerceTimestamp, commerceValue } from './commerce-record'
2
+
3
+ /**
4
+ * Post-purchase offers as the dashboard shows and writes them (the
5
+ * PostPurchaseOffer model, `commerce.upsells`), each with the funnel its
6
+ * responses add up to: shown, taken, turned down, and what it added to orders.
7
+ */
8
+
9
+ export const UPSELL_STATES = ['running', 'scheduled', 'ended', 'disabled'] as const
10
+ export type UpsellState = typeof UPSELL_STATES[number]
11
+
12
+ export interface UpsellProductRef {
13
+ id: string
14
+ label: string
15
+ /** False when the product has been deleted since the offer was made. */
16
+ exists: boolean
17
+ }
18
+
19
+ export interface UpsellStats {
20
+ /** Products shown, one per order and product. */
21
+ views: number
22
+ accepted: number
23
+ declined: number
24
+ pending: number
25
+ failed: number
26
+ /** Accepted over shown, 0 to 1. */
27
+ conversionRate: number
28
+ /** Minor units added to orders. */
29
+ revenue: number
30
+ units: number
31
+ }
32
+
33
+ export interface UpsellOfferRecord {
34
+ id: string
35
+ name: string
36
+ headline: string
37
+ message: string
38
+ products: UpsellProductRef[]
39
+ discountPercent: number
40
+ minQuantity: number
41
+ defaultQuantity: number
42
+ maxQuantity: number | null
43
+ triggerProducts: UpsellProductRef[]
44
+ /** Minor units, or null for any order. */
45
+ minOrderTotal: number | null
46
+ windowMinutes: number
47
+ priority: number
48
+ isActive: boolean
49
+ startsAt: string
50
+ endsAt: string
51
+ state: UpsellState
52
+ stats: UpsellStats
53
+ createdAt: string
54
+ }
55
+
56
+ export interface UpsellSummary {
57
+ total: number
58
+ running: number
59
+ views: number
60
+ accepted: number
61
+ declined: number
62
+ conversionRate: number
63
+ revenue: number
64
+ units: number
65
+ /** The five offers that added the most, by name on a tie. */
66
+ top: Array<{ id: string, name: string, revenue: number, conversionRate: number }>
67
+ }
68
+
69
+ export interface UpsellResponseRecord {
70
+ id: string
71
+ orderId: string
72
+ status: 'viewed' | 'pending' | 'accepted' | 'declined' | 'failed'
73
+ productId: string
74
+ productLabel: string
75
+ variantId: string
76
+ quantity: number | null
77
+ unitPrice: number | null
78
+ compareAtPrice: number | null
79
+ amount: number | null
80
+ currency: string
81
+ failureReason: string
82
+ respondedAt: string
83
+ createdAt: string
84
+ }
85
+
86
+ export function emptyUpsellStats(): UpsellStats {
87
+ return { views: 0, accepted: 0, declined: 0, pending: 0, failed: 0, conversionRate: 0, revenue: 0, units: 0 }
88
+ }
89
+
90
+ export function emptyUpsellSummary(): UpsellSummary {
91
+ return { total: 0, running: 0, views: 0, accepted: 0, declined: 0, conversionRate: 0, revenue: 0, units: 0, top: [] }
92
+ }
93
+
94
+ /** A JSON array of ids as numbers, ignoring anything else. */
95
+ export function parseIdList(raw: unknown): number[] {
96
+ if (Array.isArray(raw))
97
+ return [...new Set(raw.map(Number).filter(n => Number.isSafeInteger(n) && n > 0))]
98
+ if (typeof raw !== 'string' || raw.trim() === '')
99
+ return []
100
+ try {
101
+ return parseIdList(JSON.parse(raw))
102
+ }
103
+ catch {
104
+ return []
105
+ }
106
+ }
107
+
108
+ function day(value: unknown): string {
109
+ const text = value == null ? '' : String(value).trim()
110
+ return /^\d{4}-\d{2}-\d{2}/.test(text) ? text.slice(0, 10) : ''
111
+ }
112
+
113
+ function whole(value: unknown, fallback: number): number {
114
+ const n = Number(value)
115
+ return Number.isFinite(n) ? Math.round(n) : fallback
116
+ }
117
+
118
+ function truthy(value: unknown): boolean {
119
+ return value == null || value === true || value === 1 || String(value) === '1' || String(value) === 'true'
120
+ }
121
+
122
+ export function upsellState(row: Record<string, unknown>, now: string): UpsellState {
123
+ if (!truthy(row.is_active))
124
+ return 'disabled'
125
+ if (row.starts_at && String(row.starts_at) > now)
126
+ return 'scheduled'
127
+ if (row.ends_at && String(row.ends_at) < now)
128
+ return 'ended'
129
+ return 'running'
130
+ }
131
+
132
+ /** One `post_purchase_offers` row as a record, given product names and its funnel. */
133
+ export function normalizeUpsellOfferRecord(
134
+ row: Record<string, unknown>,
135
+ now: string,
136
+ productNames: ReadonlyMap<number, string>,
137
+ stats: UpsellStats = emptyUpsellStats(),
138
+ ): UpsellOfferRecord {
139
+ const id = commerceIdentifier(commerceValue(row, 'id'), 'PostPurchaseOffer')
140
+ const ref = (productId: number): UpsellProductRef => {
141
+ const name = productNames.get(productId)
142
+ return { id: String(productId), label: name ?? `Deleted product #${productId}`, exists: name !== undefined }
143
+ }
144
+ const minQuantity = Math.max(1, whole(row.min_quantity, 1))
145
+ return {
146
+ id,
147
+ name: String(row.name ?? '').trim() || `Offer ${id}`,
148
+ headline: String(row.headline ?? ''),
149
+ message: String(row.message ?? ''),
150
+ products: parseIdList(row.product_ids).map(ref),
151
+ discountPercent: Math.min(100, Math.max(0, whole(row.discount_percent, 0))),
152
+ minQuantity,
153
+ defaultQuantity: Math.max(minQuantity, whole(row.default_quantity, minQuantity)),
154
+ maxQuantity: row.max_quantity == null || row.max_quantity === '' ? null : whole(row.max_quantity, minQuantity),
155
+ triggerProducts: parseIdList(row.trigger_product_ids).map(ref),
156
+ minOrderTotal: row.min_order_total == null || row.min_order_total === '' ? null : whole(row.min_order_total, 0),
157
+ windowMinutes: Math.max(1, whole(row.window_minutes, 30)),
158
+ priority: whole(row.priority, 0),
159
+ isActive: truthy(row.is_active),
160
+ startsAt: day(row.starts_at),
161
+ endsAt: day(row.ends_at),
162
+ state: upsellState(row, now),
163
+ stats,
164
+ createdAt: commerceTimestamp(commerceValue(row, 'created_at', 'createdAt'), `PostPurchaseOffer ${id}`),
165
+ }
166
+ }
167
+
168
+ /** Funnel counts from `(status, rows, amount, units)` groups of one offer's responses. */
169
+ export function statsFrom(groups: ReadonlyArray<{ status: string, rows: number, amount: number, units: number }>): UpsellStats {
170
+ const stats = emptyUpsellStats()
171
+ for (const group of groups) {
172
+ stats.views += group.rows
173
+ if (group.status === 'accepted') {
174
+ stats.accepted += group.rows
175
+ stats.revenue += group.amount
176
+ stats.units += group.units
177
+ }
178
+ else if (group.status === 'declined') {
179
+ stats.declined += group.rows
180
+ }
181
+ else if (group.status === 'pending') {
182
+ stats.pending += group.rows
183
+ }
184
+ else if (group.status === 'failed') {
185
+ stats.failed += group.rows
186
+ }
187
+ }
188
+ stats.conversionRate = stats.views ? stats.accepted / stats.views : 0
189
+ return stats
190
+ }
191
+
192
+ export interface UpsellWritePayload {
193
+ name?: unknown
194
+ headline?: unknown
195
+ message?: unknown
196
+ productIds?: unknown
197
+ discountPercent?: unknown
198
+ minQuantity?: unknown
199
+ defaultQuantity?: unknown
200
+ maxQuantity?: unknown
201
+ triggerProductIds?: unknown
202
+ minOrderTotal?: unknown
203
+ windowMinutes?: unknown
204
+ priority?: unknown
205
+ isActive?: unknown
206
+ startsAt?: unknown
207
+ endsAt?: unknown
208
+ }
209
+
210
+ export type UpsellWriteResult =
211
+ | { ok: true, data: Record<string, unknown>, productIds: number[] }
212
+ | { ok: false, errors: Record<string, string> }
213
+
214
+ /** One week: longer than any post-purchase page stays open. */
215
+ const MAX_WINDOW_MINUTES = 7 * 24 * 60
216
+
217
+ function optionalWhole(value: unknown, field: string, errors: Record<string, string>, min: number, max = Number.MAX_SAFE_INTEGER): number | null {
218
+ if (value === undefined || value === null || value === '')
219
+ return null
220
+ const n = Number(value)
221
+ if (!Number.isSafeInteger(n) || n < min || n > max) {
222
+ errors[field] = max === Number.MAX_SAFE_INTEGER ? `must be a whole number of at least ${min}` : `must be a whole number from ${min} to ${max}`
223
+ return null
224
+ }
225
+ return n
226
+ }
227
+
228
+ function dateColumn(value: unknown, field: string, endOfDay: boolean, errors: Record<string, string>): string | null {
229
+ const text = value == null ? '' : String(value).trim()
230
+ if (!text)
231
+ return null
232
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(text) || Number.isNaN(Date.parse(text))) {
233
+ errors[field] = 'must be a date'
234
+ return null
235
+ }
236
+ return `${text} ${endOfDay ? '23:59:59' : '00:00:00'}`
237
+ }
238
+
239
+ /**
240
+ * A dialog payload as the columns to write, or the field errors. The product
241
+ * ids are returned too, for the caller to check they exist.
242
+ */
243
+ export function upsellWriteData(payload: UpsellWritePayload): UpsellWriteResult {
244
+ const errors: Record<string, string> = {}
245
+ const name = String(payload.name ?? '').trim()
246
+ if (!name)
247
+ errors.name = 'is required'
248
+ else if (name.length > 255)
249
+ errors.name = 'must be 255 characters or fewer'
250
+
251
+ const headline = String(payload.headline ?? '').trim()
252
+ if (headline.length > 255)
253
+ errors.headline = 'must be 255 characters or fewer'
254
+ const message = String(payload.message ?? '').trim()
255
+ if (message.length > 2000)
256
+ errors.message = 'must be 2000 characters or fewer'
257
+
258
+ const productIds = parseIdList(payload.productIds)
259
+ if (productIds.length === 0)
260
+ errors.productIds = 'choose at least one product to offer'
261
+ else if (productIds.length > 12)
262
+ errors.productIds = 'offer at most 12 products'
263
+
264
+ const discountPercent = optionalWhole(payload.discountPercent, 'discountPercent', errors, 0, 100) ?? 0
265
+ const minQuantity = optionalWhole(payload.minQuantity, 'minQuantity', errors, 1) ?? 1
266
+ const defaultQuantity = optionalWhole(payload.defaultQuantity, 'defaultQuantity', errors, 1) ?? minQuantity
267
+ const maxQuantity = optionalWhole(payload.maxQuantity, 'maxQuantity', errors, 1)
268
+ if (!errors.defaultQuantity && defaultQuantity < minQuantity)
269
+ errors.defaultQuantity = 'must be at least the minimum quantity'
270
+ if (maxQuantity !== null && !errors.maxQuantity && maxQuantity < minQuantity)
271
+ errors.maxQuantity = 'must be at least the minimum quantity'
272
+ if (maxQuantity !== null && !errors.defaultQuantity && defaultQuantity > maxQuantity)
273
+ errors.defaultQuantity = 'must be at most the maximum quantity'
274
+
275
+ const windowMinutes = optionalWhole(payload.windowMinutes, 'windowMinutes', errors, 1, MAX_WINDOW_MINUTES) ?? 30
276
+ const priority = payload.priority === undefined || payload.priority === null || payload.priority === '' ? 0 : Number(payload.priority)
277
+ if (!Number.isSafeInteger(priority))
278
+ errors.priority = 'must be a whole number'
279
+
280
+ const startsAt = dateColumn(payload.startsAt, 'startsAt', false, errors)
281
+ const endsAt = dateColumn(payload.endsAt, 'endsAt', true, errors)
282
+ if (startsAt && endsAt && endsAt < startsAt)
283
+ errors.endsAt = 'must be on or after the start date'
284
+
285
+ const triggers = parseIdList(payload.triggerProductIds)
286
+ const data = {
287
+ name,
288
+ headline: headline || null,
289
+ message: message || null,
290
+ product_ids: JSON.stringify(productIds),
291
+ discount_percent: discountPercent,
292
+ min_quantity: minQuantity,
293
+ default_quantity: defaultQuantity,
294
+ max_quantity: maxQuantity,
295
+ trigger_product_ids: triggers.length ? JSON.stringify(triggers) : null,
296
+ min_order_total: optionalWhole(payload.minOrderTotal, 'minOrderTotal', errors, 0),
297
+ window_minutes: windowMinutes,
298
+ priority: Number.isSafeInteger(priority) ? priority : 0,
299
+ is_active: payload.isActive !== false,
300
+ starts_at: startsAt,
301
+ ends_at: endsAt,
302
+ }
303
+
304
+ if (Object.keys(errors).length > 0)
305
+ return { ok: false, errors }
306
+ return { ok: true, data, productIds: [...new Set([...productIds, ...triggers])] }
307
+ }
@@ -238,7 +238,12 @@ export default new Action({
238
238
  saved.updated.push(row.id)
239
239
  }
240
240
  for (const row of plan.changes.create) {
241
- const done = await storeModelRow(plan.target, panelFields(plan.panel, row.fields), { [plan.panel.foreignKey]: id })
241
+ // The link to this record is the server's to set, and it is
242
+ // validated with the row: a model that declares it required (a
243
+ // team member's userId) refused every row added here as missing
244
+ // it when it was only set after validation.
245
+ const fields = { ...panelFields(plan.panel, row.fields), [plan.panel.field]: id }
246
+ const done = await storeModelRow(plan.target, fields, { [plan.panel.foreignKey]: id })
242
247
  if (!done.ok)
243
248
  throw new SaveStopped(done, at('create', row.key))
244
249
  saved.created.push({ key: row.key, id: done.id })
@@ -156,17 +156,27 @@ export function modelHintColumn(Model: any): string | null {
156
156
  * Field errors for a write the database refused because a record it points
157
157
  * at is not there: the team was deleted while the form was open.
158
158
  *
159
- * The driver names the constraint, not the field. The model knows which of
160
- * the fields being written are relations, and the one in the request is the
161
- * one that is gone. With several, each is named, because any of them may be.
159
+ * Postgres and MySQL say which key it was: the constraint
160
+ * (`team_members_team_id_fkey`) and Postgres's detail (`Key (team_id)=(7) is
161
+ * not present`) name the column. When they do, only that field is named; a
162
+ * team member whose team was deleted used to be told its user was gone too.
163
+ * SQLite names nothing, so there every relation being written is named,
164
+ * because any of them may be the one.
162
165
  */
163
166
  export function missingRelationErrors(Model: any, error: unknown, columns: string[], label: (name: string) => string): Record<string, string[]> {
164
167
  if (!isForeignKeyViolation(error))
165
168
  return {}
169
+ const written = belongsToRelations(Model).filter(relation => columns.includes(relation.column) || columns.includes(relation.field))
170
+ const said = foreignKeyErrorText(error)
171
+ const named = written.filter(relation => new RegExp(`(^|[^a-z0-9])${relation.column}([^a-z0-9]|$)`, 'i').test(said))
166
172
  const errors: Record<string, string[]> = {}
167
- for (const relation of belongsToRelations(Model)) {
168
- if (columns.includes(relation.column) || columns.includes(relation.field))
169
- errors[relation.field] = [`That ${label(relation.model).toLowerCase()} no longer exists. Choose another.`]
170
- }
173
+ for (const relation of named.length > 0 ? named : written)
174
+ errors[relation.field] = [`That ${label(relation.model).toLowerCase()} no longer exists. Choose another.`]
171
175
  return errors
172
176
  }
177
+
178
+ /** Everything a driver says about a refused key, where it might name the column. */
179
+ function foreignKeyErrorText(error: unknown): string {
180
+ const e = error as { message?: unknown, detail?: unknown, constraint?: unknown, constraint_name?: unknown }
181
+ return [e?.message, e?.detail, e?.constraint, e?.constraint_name].filter(part => typeof part === 'string').join(' ')
182
+ }
@@ -44,16 +44,17 @@ function failed(cause: unknown, message: string, where: string): RowRefusal {
44
44
  }
45
45
 
46
46
  /** The refusals a person can act on, read out of an error a write threw. */
47
- function fieldRefusal(resolved: ResolvedModel, error: unknown, columns: string[], unique: boolean): RowRefusal | null {
47
+ function fieldRefusal(resolved: ResolvedModel, error: unknown, columns: string[]): RowRefusal | null {
48
48
  // The model's own rules rejected the row: the caller's mistake, named
49
49
  // field by field, not a server failure (stacksjs/stacks#3007).
50
50
  if (error instanceof ModelValidationError)
51
51
  return refused(422, 'Validation failed.', error.errors)
52
- // A value another row already holds, on a field the model marks unique
53
- // (a user's email). The person can fix that, so it is named on the field
54
- // like any other rule, not reported as a failed save.
55
- if (unique && isUniqueViolation(error)) {
56
- const errors = duplicateFieldErrors(resolved.Model, columns)
52
+ // A value another row already holds, on a field the model marks unique (a
53
+ // user's email) or a pair a unique index covers (a team member's team and
54
+ // user), whether the row is new or edited. The person can fix that, so it
55
+ // is named on the field like any other rule, not reported as a failed save.
56
+ if (isUniqueViolation(error)) {
57
+ const errors = duplicateFieldErrors(resolved.Model, columns, error)
57
58
  if (Object.keys(errors).length > 0)
58
59
  return refused(422, 'Validation failed.', errors)
59
60
  }
@@ -89,7 +90,7 @@ export async function storeModelRow(resolved: ResolvedModel, body: Record<string
89
90
  return { ok: true, id: row?.id ?? row?.attributes?.id ?? null }
90
91
  }
91
92
  catch (error) {
92
- return fieldRefusal(resolved, error, Object.keys(values), false)
93
+ return fieldRefusal(resolved, error, Object.keys(values))
93
94
  ?? failed(error, 'The model record could not be created.', 'ModelStoreAction')
94
95
  }
95
96
  }
@@ -124,7 +125,7 @@ export async function updateModelRow(resolved: ResolvedModel, id: number, body:
124
125
  return { ok: true, id, changed: [...Object.keys(changes), ...turning.map(request => request.switch.column)] }
125
126
  }
126
127
  catch (error) {
127
- return fieldRefusal(resolved, error, Object.keys(changes), true)
128
+ return fieldRefusal(resolved, error, Object.keys(changes))
128
129
  ?? failed(error, 'The model record could not be updated.', 'ModelUpdateAction')
129
130
  }
130
131
  }
@@ -342,13 +342,62 @@ export function isErasureSubject(Model: any): boolean {
342
342
  * named, because any of them may be. Keyed by attribute name, like every
343
343
  * other field error these endpoints return.
344
344
  */
345
- export function duplicateFieldErrors(Model: any, columns: string[]): Record<string, string[]> {
345
+ export function duplicateFieldErrors(Model: any, columns: string[], error?: unknown): Record<string, string[]> {
346
346
  const errors: Record<string, string[]> = {}
347
347
  for (const [name, definition] of Object.entries((Model?.attributes ?? {}) as Record<string, any>)) {
348
348
  if (definition?.unique === true && columns.includes(snakeCase(name)))
349
349
  errors[name] = [`${modelColumnLabel(Model, name)} is already in use.`]
350
350
  }
351
- return errors
351
+ if (Object.keys(errors).length > 0)
352
+ return errors
353
+ return duplicateIndexErrors(Model, columns, error)
354
+ }
355
+
356
+ /**
357
+ * The refusal of a unique index over several columns: a team member's
358
+ * (team, user). No one field is in use; the pair is. Found by the dashboard's
359
+ * end-to-end tests (stacksjs/stacks#3319): adding a team a user already
360
+ * belonged to said only "The model record could not be created."
361
+ *
362
+ * Which index refused it is read off the driver's error: Postgres and MySQL
363
+ * name the index, and Postgres's detail and SQLite's message name the
364
+ * columns. Without a match nothing is claimed, and the save reports a failure
365
+ * as before.
366
+ */
367
+ function duplicateIndexErrors(Model: any, columns: string[], error: unknown): Record<string, string[]> {
368
+ const said = sqlErrorText(error)
369
+ if (!said)
370
+ return {}
371
+ const relations = belongsToRelations(Model)
372
+ for (const index of (Model?.indexes ?? []) as Array<{ name?: unknown, columns?: unknown, unique?: unknown }>) {
373
+ if (index?.unique !== true || !Array.isArray(index.columns) || index.columns.length < 2)
374
+ continue
375
+ const indexColumns = index.columns.map(column => snakeCase(String(column)))
376
+ if (!indexColumns.every(column => columns.includes(column)))
377
+ continue
378
+ const named = (typeof index.name === 'string' && said.includes(index.name))
379
+ || indexColumns.every(column => new RegExp(`(^|[^a-z0-9])${column}([^a-z0-9]|$)`, 'i').test(said))
380
+ if (!named)
381
+ continue
382
+ const attributes = Object.keys((Model?.attributes ?? {}) as Record<string, unknown>)
383
+ const fields = indexColumns.map(column => relations.find(relation => relation.column === column)?.field
384
+ ?? attributes.find(name => snakeCase(name) === column) ?? column)
385
+ const labels = indexColumns.map((column, at) => {
386
+ const relation = relations.find(candidate => candidate.column === column)
387
+ return (relation ? humanizeIdentifier(relation.model) : modelColumnLabel(Model, fields[at]!)).toLowerCase()
388
+ })
389
+ // On the first field only: the form shows one message per row, and
390
+ // repeating it on each column of the pair would say it twice.
391
+ return { [fields[0]!]: [`That ${labels.join(' and ')} combination is already in use.`] }
392
+ }
393
+ return {}
394
+ }
395
+
396
+ /** Everything a driver says about a refused write, where it may name an index or its columns. */
397
+ function sqlErrorText(error: unknown): string {
398
+ const e = error as { message?: unknown, detail?: unknown, constraint?: unknown, constraint_name?: unknown, cause?: unknown }
399
+ const own = [e?.message, e?.detail, e?.constraint, e?.constraint_name].filter(part => typeof part === 'string').join(' ')
400
+ return e?.cause && e.cause !== error ? `${own} ${sqlErrorText(e.cause)}` : own
352
401
  }
353
402
 
354
403
  /** Rule names the migrations store as a moment: a `timestamp` or `datetime` column. */
@@ -1,4 +1,3 @@
1
- import type { UserModel } from '@stacksjs/orm'
2
1
  import type { RequestInstance } from '@stacksjs/types'
3
2
  import { Action } from '@stacksjs/actions/runtime'
4
3
  import { Gate } from '@stacksjs/auth'
@@ -23,7 +22,7 @@ export default new Action({
23
22
  try {
24
23
  // `request.user()` answers `AuthenticatedUser | undefined`; the gate and
25
24
  // the audit identity both want the model or an explicit null.
26
- const user = (await request.user() ?? null) as UserModel | null
25
+ const user = (await request.user()) ?? null
27
26
  const hostKey = request.get('host')
28
27
  const commandKey = request.get('command')
29
28
 
@@ -1,4 +1,3 @@
1
- import type { UserModel } from '@stacksjs/orm'
2
1
  import type { RequestInstance } from '@stacksjs/types'
3
2
  import { Action } from '@stacksjs/actions/runtime'
4
3
  import { response } from '@stacksjs/router'
@@ -12,7 +11,7 @@ export default new Action({
12
11
  method: 'DELETE',
13
12
  async handle(request: RequestInstance) {
14
13
  try {
15
- const user = (await request.user() ?? null) as UserModel | null
14
+ const user = (await request.user()) ?? null
16
15
  await terminalSessions.close(request.getParam('id'), user)
17
16
  return response.json({ ok: true })
18
17
  }
@@ -1,4 +1,3 @@
1
- import type { UserModel } from '@stacksjs/orm'
2
1
  import type { RequestInstance } from '@stacksjs/types'
3
2
  import { Action } from '@stacksjs/actions/runtime'
4
3
  import { response } from '@stacksjs/router'
@@ -12,7 +11,7 @@ export default new Action({
12
11
  method: 'POST',
13
12
  async handle(request: RequestInstance) {
14
13
  try {
15
- const user = (await request.user() ?? null) as UserModel | null
14
+ const user = (await request.user()) ?? null
16
15
  await terminalSessions.input(request.getParam('id'), user, request.get('data'))
17
16
  return response.json({ ok: true })
18
17
  }
@@ -1,4 +1,3 @@
1
- import type { UserModel } from '@stacksjs/orm'
2
1
  import type { RequestInstance } from '@stacksjs/types'
3
2
  import { Action } from '@stacksjs/actions/runtime'
4
3
  import { hosts } from '~/config/remote'
@@ -19,7 +18,7 @@ export default new Action({
19
18
  method: 'POST',
20
19
  async handle(request: RequestInstance) {
21
20
  try {
22
- const user = (await request.user() ?? null) as UserModel | null
21
+ const user = (await request.user()) ?? null
23
22
  const session = await terminalSessions.open({
24
23
  user,
25
24
  hosts,
@@ -1,4 +1,3 @@
1
- import type { UserModel } from '@stacksjs/orm'
2
1
  import type { RequestInstance } from '@stacksjs/types'
3
2
  import { Action } from '@stacksjs/actions/runtime'
4
3
  import { response } from '@stacksjs/router'
@@ -12,7 +11,7 @@ export default new Action({
12
11
  method: 'POST',
13
12
  async handle(request: RequestInstance) {
14
13
  try {
15
- const user = (await request.user() ?? null) as UserModel | null
14
+ const user = (await request.user()) ?? null
16
15
  terminalSessions.resize(request.getParam('id'), user, request.get('cols'), request.get('rows'))
17
16
  return response.json({ ok: true })
18
17
  }
@@ -1,4 +1,3 @@
1
- import type { UserModel } from '@stacksjs/orm'
2
1
  import type { RequestInstance } from '@stacksjs/types'
3
2
  import { Action } from '@stacksjs/actions/runtime'
4
3
  import { response, stream } from '@stacksjs/router'
@@ -17,7 +16,7 @@ export default new Action({
17
16
  method: 'GET',
18
17
  async handle(request: RequestInstance) {
19
18
  try {
20
- const user = (await request.user() ?? null) as UserModel | null
19
+ const user = (await request.user()) ?? null
21
20
  const resumeFrom = request.get('after') ?? request.headers.get('last-event-id') ?? 0
22
21
  const after = Number(resumeFrom)
23
22
  const events = terminalSessions.watch(request.getParam('id'), user, Number.isInteger(after) && after > 0 ? after : 0)
@@ -14,7 +14,7 @@
14
14
  // - authorization fails CLOSED when no gate is configured
15
15
  // - a run is recorded before it starts, not only when it finishes
16
16
 
17
- import type { UserModel } from '@stacksjs/orm'
17
+ import type { GateUser } from '@stacksjs/auth'
18
18
  import type { RemoteAuditSink, RemoteCommand, RemoteHost } from './remote-commands'
19
19
  import { beforeEach, describe, expect, it } from 'bun:test'
20
20
  import {
@@ -46,7 +46,7 @@ const commands: RemoteCommand[] = [
46
46
  { key: 'restart-api', description: 'Restart the API', argv: ['systemctl', 'restart', 'api'], hosts: ['app'] },
47
47
  ]
48
48
 
49
- const user = { id: 1, email: 'ops@example.com' } as unknown as UserModel
49
+ const user = { id: 1, email: 'ops@example.com' } as unknown as GateUser
50
50
 
51
51
  let recorded: string[] = []
52
52
  const audit: RemoteAuditSink = {
@@ -1,4 +1,4 @@
1
- import type { UserModel } from '@stacksjs/orm'
1
+ import type { GateUser } from '@stacksjs/auth'
2
2
  import type { ResponseStatus } from '@stacksjs/bun-router'
3
3
 
4
4
  /**
@@ -233,12 +233,12 @@ export function resolveCommand(commands: readonly RemoteCommand[], key: unknown,
233
233
  * `role:admin` is one bit. The gate receives both keys, so an application can
234
234
  * scope by host, by command, or by both without this file knowing how.
235
235
  */
236
- export type RemoteAuthorizer = (user: UserModel | null, hostKey: string, commandKey: string) => Promise<boolean> | boolean
236
+ export type RemoteAuthorizer = (user: GateUser | null, hostKey: string, commandKey: string) => Promise<boolean> | boolean
237
237
 
238
238
  /** Refuses when no authorizer is configured. */
239
239
  export async function authorize(
240
240
  authorizer: RemoteAuthorizer | undefined,
241
- user: UserModel | null,
241
+ user: GateUser | null,
242
242
  host: RemoteHost,
243
243
  command: RemoteCommand,
244
244
  ): Promise<void> {
@@ -281,7 +281,7 @@ export function normalizeTimeout(value: number | undefined): number {
281
281
  export async function runRemoteCommand(
282
282
  input: { hostKey: unknown, commandKey: unknown },
283
283
  context: {
284
- user: UserModel | null
284
+ user: GateUser | null
285
285
  hosts: readonly RemoteHost[]
286
286
  commands: readonly RemoteCommand[]
287
287
  authorizer?: RemoteAuthorizer