@stacksjs/defaults 0.75.538 → 0.75.541
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.
- package/ai/AGENTS.md +2 -0
- package/ai/skills/stacks-actions/SKILL.md +1 -1
- package/ai/skills/stacks-auth/SKILL.md +8 -1
- package/ai/skills/stacks-dashboard/SKILL.md +196 -3
- package/ai/skills/stacks-dependencies/SKILL.md +46 -0
- package/ai/skills/stacks-development/SKILL.md +1 -1
- package/ai/skills/stacks-flow/SKILL.md +7 -0
- package/ai/skills/stacks-hq/SKILL.md +146 -0
- package/ai/skills/stacks-models/SKILL.md +21 -3
- package/ai/skills/stacks-native/CATALOG.md +22 -9
- package/ai/skills/stacks-new-app/SKILL.md +175 -0
- package/ai/skills/stacks-repl/SKILL.md +61 -43
- package/ai/skills/stacks-stx/SKILL.md +6 -2
- package/ai/skills/stacks-upstream/SKILL.md +188 -0
- package/ai/skills/stacks-writing-for-agents/SKILL.md +1 -1
- package/app/Actions/Dashboard/Data/UserIndexAction.ts +20 -2
- package/app/Actions/Dashboard/Models/ModelDestroyAction.ts +48 -12
- package/app/Actions/Dashboard/Models/ModelOptionsAction.ts +103 -0
- package/app/Actions/Dashboard/Models/ModelRelatedAction.ts +42 -0
- package/app/Actions/Dashboard/Models/ModelShowAction.ts +75 -12
- package/app/Actions/Dashboard/Models/ModelStoreAction.ts +7 -1
- package/app/Actions/Dashboard/Models/ModelUpdateAction.ts +16 -2
- package/app/Actions/Dashboard/Models/model-destroy.ts +75 -0
- package/app/Actions/Dashboard/Models/model-options.ts +56 -0
- package/app/Actions/Dashboard/Models/model-related.ts +202 -0
- package/app/Actions/Dashboard/Models/model-relations.ts +172 -0
- package/app/Actions/Dashboard/Models/model-write.ts +240 -51
- package/app/Actions/Dashboard/Users/UserInviteAction.ts +50 -0
- package/app/Actions/Dashboard/Users/user-invitation.ts +110 -0
- package/app/Models/Activity.ts +4 -0
- package/app/Models/AnalyticsEvent.ts +4 -0
- package/app/Models/Automation.ts +4 -0
- package/app/Models/AutomationRun.ts +4 -0
- package/app/Models/Board.ts +4 -1
- package/app/Models/BoardColumn.ts +4 -1
- package/app/Models/Campaign.ts +4 -0
- package/app/Models/CampaignSend.ts +4 -0
- package/app/Models/CampaignVariant.ts +4 -0
- package/app/Models/Card.ts +4 -1
- package/app/Models/CardAttachment.ts +4 -0
- package/app/Models/CommunicationSuppression.ts +4 -0
- package/app/Models/ConsentEvent.ts +4 -0
- package/app/Models/Deployment.ts +1 -0
- package/app/Models/EmailList.ts +4 -0
- package/app/Models/EmailListSubscriber.ts +4 -0
- package/app/Models/Error.ts +4 -0
- package/app/Models/FailedJob.ts +4 -0
- package/app/Models/FeedbackToken.ts +4 -0
- package/app/Models/GdprRequest.ts +4 -0
- package/app/Models/Job.ts +4 -0
- package/app/Models/Log.ts +4 -0
- package/app/Models/MagicLinkToken.ts +4 -0
- package/app/Models/MailPreference.ts +4 -0
- package/app/Models/Notification.ts +4 -0
- package/app/Models/NotificationDelivery.ts +4 -0
- package/app/Models/PersonalAccessToken.ts +4 -0
- package/app/Models/QueryLog.ts +4 -0
- package/app/Models/Referral.ts +4 -0
- package/app/Models/Release.ts +1 -0
- package/app/Models/Request.ts +4 -0
- package/app/Models/SenderDomain.ts +4 -0
- package/app/Models/Site.ts +1 -0
- package/app/Models/SiteDomain.ts +4 -0
- package/app/Models/SocialPost.ts +4 -0
- package/app/Models/StorageItemTask.ts +4 -1
- package/app/Models/Subscriber.ts +4 -0
- package/app/Models/Subscription.ts +4 -0
- package/app/Models/Team.ts +1 -0
- package/app/Models/TeamInvitation.ts +1 -0
- package/app/Models/TeamMember.ts +1 -0
- package/app/Models/UsageEvent.ts +4 -0
- package/app/Models/User.ts +15 -3
- package/functions/dashboard-model-record.test.ts +276 -18
- package/functions/dashboard-model-record.ts +412 -55
- package/functions/data.ts +2 -0
- package/ide/vscode/package.json +1 -1
- package/package.json +5 -5
- package/resources/components/Dashboard/Analytics/AnalyticsHub.stx +1 -1
- package/resources/components/Dashboard/Analytics/CampaignAnalytics.stx +1 -1
- package/resources/components/Dashboard/Analytics/EventAnalytics.stx +1 -1
- package/resources/components/Dashboard/Analytics/SalesAnalytics.stx +1 -1
- package/resources/components/Dashboard/Analytics/WebAnalyticsBreakdown.stx +1 -1
- package/resources/components/Dashboard/App/RequestsOverview.stx +1 -1
- package/resources/components/Dashboard/App/SourceInventory.stx +1 -1
- package/resources/components/Dashboard/Auth/AccessTokens.stx +1 -1
- package/resources/components/Dashboard/Buddy/BuddyAssistant.stx +1 -1
- package/resources/components/Dashboard/Ci/CiDashboard.stx +1 -1
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryPagination.stx +1 -1
- package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +1 -1
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +1 -1
- package/resources/components/Dashboard/Content/BlogDashboard.stx +1 -1
- package/resources/components/Dashboard/DashboardLayout.stx +1 -1
- package/resources/components/Dashboard/Data/DataRecords.stx +43 -22
- package/resources/components/Dashboard/Data/UserInvite.stx +107 -0
- package/resources/components/Dashboard/Email/CapturedMailDashboard.stx +1 -1
- package/resources/components/Dashboard/Email/EmailActivityDashboard.stx +1 -1
- package/resources/components/Dashboard/Email/InboxDashboard.stx +1 -1
- package/resources/components/Dashboard/Email/InboxMessageDetail.stx +2 -2
- package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +1 -1
- package/resources/components/Dashboard/Home/DashboardHome.stx +6 -1
- package/resources/components/Dashboard/Infrastructure/CloudDashboard.stx +1 -1
- package/resources/components/Dashboard/Infrastructure/DnsDashboard.stx +1 -1
- package/resources/components/Dashboard/Infrastructure/HealthDashboard.stx +1 -1
- package/resources/components/Dashboard/Infrastructure/InsightsDashboard.stx +1 -1
- package/resources/components/Dashboard/Infrastructure/LogsDashboard.stx +1 -1
- package/resources/components/Dashboard/Infrastructure/MailboxesDashboard.stx +1 -1
- package/resources/components/Dashboard/Infrastructure/ServerDetailsDashboard.stx +1 -1
- package/resources/components/Dashboard/Infrastructure/ServerlessDashboard.stx +1 -1
- package/resources/components/Dashboard/Infrastructure/ServersDashboard.stx +1 -1
- package/resources/components/Dashboard/Jobs/JobDetail.stx +1 -1
- package/resources/components/Dashboard/Jobs/JobTable.stx +2 -2
- package/resources/components/Dashboard/Kanban/KanbanBoardDashboard.stx +1 -1
- package/resources/components/Dashboard/Kanban/KanbanBoardsDashboard.stx +1 -1
- package/resources/components/Dashboard/Management/PermissionsDashboard.stx +1 -1
- package/resources/components/Dashboard/Marketing/AbandonedCartsDashboard.stx +1 -1
- package/resources/components/Dashboard/Marketing/CampaignsDashboard.stx +1 -1
- package/resources/components/Dashboard/Marketing/MarketingListsDashboard.stx +1 -1
- package/resources/components/Dashboard/Marketing/SocialPostsDashboard.stx +1 -1
- package/resources/components/Dashboard/Models/ModelFieldInputs.stx +125 -0
- package/resources/components/Dashboard/Models/ModelRecordCreate.stx +24 -66
- package/resources/components/Dashboard/Models/ModelRecordDetail.stx +36 -8
- package/resources/components/Dashboard/Models/ModelRecordEdit.stx +36 -32
- package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +72 -28
- package/resources/components/Dashboard/Models/ModelRelatedPanels.stx +99 -0
- package/resources/components/Dashboard/Models/ModelRelationPicker.stx +247 -0
- package/resources/components/Dashboard/Models/ModelsOverview.stx +1 -1
- package/resources/components/Dashboard/Notifications/NotificationDeliveries.stx +1 -1
- package/resources/components/Dashboard/Notifications/NotificationDeliveryHistory.stx +1 -1
- package/resources/components/Dashboard/Notifications/NotificationDeliveryOverview.stx +1 -1
- package/resources/components/Dashboard/Queries/QueryDashboard.stx +1 -1
- package/resources/components/Dashboard/Queries/QueryDetail.stx +1 -1
- package/resources/components/Dashboard/Queue/QueueDashboard.stx +1 -1
- package/resources/components/Dashboard/Realtime/RealtimeDashboard.stx +1 -1
- package/resources/components/Dashboard/Releases/ReleaseDashboard.stx +1 -1
- package/resources/components/Dashboard/Search/SearchEngineDashboard.stx +1 -1
- package/resources/components/Dashboard/Settings/MailSettingsDashboard.stx +1 -1
- package/resources/components/Dashboard/Settings/SettingsDashboard.stx +1 -1
- package/resources/components/Dashboard/Teams/TeamPeopleDashboard.stx +1 -1
- package/resources/components/Dashboard/UI/Drawer.stx +1 -1
- package/resources/components/Dashboard/UI/Input.stx +3 -2
- package/resources/components/Dashboard/UI/Modal.stx +1 -1
- package/resources/components/Dashboard/UI/Select.stx +8 -4
- package/resources/components/Dashboard/UI/Textarea.stx +18 -12
- package/resources/emails/password-reset.stx +3 -1
- package/routes/dashboard-api.ts +9 -0
- package/scaffold/config/analytics.ts +5 -3
- package/scaffold/resources/components/NextStep.stx +13 -0
- package/scaffold/resources/partials/head.stx +31 -0
- package/scaffold/resources/views/index.stx +23 -47
- package/scaffold/resources/views/layouts/default.stx +23 -0
- package/views/dashboard/data/users/invite.stx +8 -0
- package/views/dashboard/layouts/default.stx +21 -2
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import type { RequestInstance } from '@stacksjs/types'
|
|
2
2
|
import { Action } from '@stacksjs/actions/runtime'
|
|
3
|
-
import { ModelValidationError, toSnakeCaseKeys } from '@stacksjs/orm'
|
|
3
|
+
import { isUniqueViolation, ModelValidationError, toSnakeCaseKeys } from '@stacksjs/orm'
|
|
4
4
|
import { response } from '@stacksjs/router'
|
|
5
5
|
import { dashboardOperationalError } from '../dashboard-response'
|
|
6
|
-
import {
|
|
6
|
+
import { missingRelationErrors } from './model-relations'
|
|
7
|
+
import { duplicateFieldErrors, humanizeIdentifier, parseRowId, prepareModelFields, resolveWritableModel } from './model-write'
|
|
7
8
|
|
|
8
9
|
interface ModelWriteInput {
|
|
9
10
|
fields?: unknown
|
|
@@ -59,6 +60,19 @@ export default new Action({
|
|
|
59
60
|
// field by field, not a server failure (stacksjs/stacks#3007).
|
|
60
61
|
if (error instanceof ModelValidationError)
|
|
61
62
|
return response.json({ message: 'Validation failed.', errors: error.errors }, 422)
|
|
63
|
+
// A value another row already holds, on a field the model marks unique
|
|
64
|
+
// (a user's email). The person can fix that, so it is named on the field
|
|
65
|
+
// like any other rule, not reported as a failed save.
|
|
66
|
+
if (isUniqueViolation(error)) {
|
|
67
|
+
const errors = duplicateFieldErrors(resolved.Model, Object.keys(changes))
|
|
68
|
+
if (Object.keys(errors).length > 0)
|
|
69
|
+
return response.json({ message: 'Validation failed.', errors }, 422)
|
|
70
|
+
}
|
|
71
|
+
// A record this one points at was deleted while the form was open. The
|
|
72
|
+
// person can pick another, so it is said on that field.
|
|
73
|
+
const missing = missingRelationErrors(resolved.Model, error, Object.keys(changes), humanizeIdentifier)
|
|
74
|
+
if (Object.keys(missing).length > 0)
|
|
75
|
+
return response.json({ message: 'Validation failed.', errors: missing }, 422)
|
|
62
76
|
return dashboardOperationalError(error, 'The model record could not be updated.', 'ModelUpdateAction', 500)
|
|
63
77
|
}
|
|
64
78
|
},
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deleting one record from the dashboard, and what happens when the database
|
|
3
|
+
* will not let it go.
|
|
4
|
+
*
|
|
5
|
+
* A row other records still point at cannot be deleted: the foreign keys
|
|
6
|
+
* refuse, and for most models that is the answer, said plainly. A user is
|
|
7
|
+
* different. Nineteen tables point at `users`, so anyone who has signed in,
|
|
8
|
+
* joined a team or placed an order could never be removed, and deleting
|
|
9
|
+
* through all of those tables from one trash icon would destroy far more
|
|
10
|
+
* than the operator can see.
|
|
11
|
+
*
|
|
12
|
+
* The app already says what removing a person means: each model's `gdpr`
|
|
13
|
+
* trait declares whether their rows are deleted, anonymized or kept, and
|
|
14
|
+
* `eraseSubject` applies it in one transaction with an audit row. So a user
|
|
15
|
+
* who cannot be deleted is erased that way instead. By default that leaves
|
|
16
|
+
* the account in place with its name, email and password removed and its
|
|
17
|
+
* sign-ins revoked, and keeps the records that still refer to it.
|
|
18
|
+
*/
|
|
19
|
+
import { isForeignKeyViolation } from '@stacksjs/error-handling'
|
|
20
|
+
import { isErasureSubject } from './model-write'
|
|
21
|
+
|
|
22
|
+
export interface ErasureOutcome {
|
|
23
|
+
/** What erasure did to the subject's own row. */
|
|
24
|
+
action: 'anonymize' | 'delete' | 'keep'
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface DestroyModelRecordDependencies {
|
|
28
|
+
Model: any
|
|
29
|
+
/** Apply the app's erasure rules to this user, recorded against `actor`. */
|
|
30
|
+
erase: (id: number, actor: string) => Promise<ErasureOutcome>
|
|
31
|
+
/** Who asked, for the erasure's audit row. */
|
|
32
|
+
actor: string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// One member per reason, so checking `reason` narrows to the members that
|
|
36
|
+
// carry a `cause`.
|
|
37
|
+
export type DestroyModelRecordResult
|
|
38
|
+
= | { ok: true, outcome: 'deleted' | 'anonymized' }
|
|
39
|
+
| { ok: false, reason: 'missing' }
|
|
40
|
+
| { ok: false, reason: 'referenced' }
|
|
41
|
+
| { ok: false, reason: 'failed', cause: unknown }
|
|
42
|
+
| { ok: false, reason: 'erasure-failed', cause: unknown }
|
|
43
|
+
|
|
44
|
+
export async function destroyModelRecord(id: number, dependencies: DestroyModelRecordDependencies): Promise<DestroyModelRecordResult> {
|
|
45
|
+
const { Model } = dependencies
|
|
46
|
+
try {
|
|
47
|
+
const row = await Model.find(id)
|
|
48
|
+
if (!row)
|
|
49
|
+
return { ok: false, reason: 'missing' }
|
|
50
|
+
await row.delete()
|
|
51
|
+
return { ok: true, outcome: 'deleted' }
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (!isForeignKeyViolation(error))
|
|
55
|
+
return { ok: false, reason: 'failed', cause: error }
|
|
56
|
+
if (!isErasureSubject(Model))
|
|
57
|
+
return { ok: false, reason: 'referenced' }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
try {
|
|
61
|
+
const { action } = await dependencies.erase(id, dependencies.actor)
|
|
62
|
+
// The rules may say a user's own row is deleted, or kept as it is. Then
|
|
63
|
+
// erasure has done what the app declared and the row is not anonymized;
|
|
64
|
+
// only the default leaves an anonymized account behind.
|
|
65
|
+
if (action === 'keep')
|
|
66
|
+
return { ok: false, reason: 'referenced' }
|
|
67
|
+
return { ok: true, outcome: action === 'delete' ? 'deleted' : 'anonymized' }
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
// Rules that delete the row meet the same foreign keys the delete did.
|
|
71
|
+
if (isForeignKeyViolation(error))
|
|
72
|
+
return { ok: false, reason: 'referenced' }
|
|
73
|
+
return { ok: false, reason: 'erasure-failed', cause: error }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a record is called, for anywhere the dashboard shows one by name: a
|
|
3
|
+
* picker's list, the link on a record's page, a cell in a related-records
|
|
4
|
+
* panel. One place, so a record has one name everywhere.
|
|
5
|
+
*/
|
|
6
|
+
import type { ModelOption } from './model-relations'
|
|
7
|
+
import { anonymizedRows } from '@stacksjs/orm'
|
|
8
|
+
import { safeGet } from '../../../../resources/functions/dashboard/data'
|
|
9
|
+
import { resolveDashboardModel } from '../../../../resources/functions/dashboard/model-access'
|
|
10
|
+
import { modelHintColumn, modelLabelColumn } from './model-relations'
|
|
11
|
+
import { humanizeIdentifier, isErasureSubject } from './model-write'
|
|
12
|
+
|
|
13
|
+
/** A model's rows as the options a picker lists: an id, a name, and a line that tells two apart. */
|
|
14
|
+
export async function optionsFromRows(Model: any, modelName: string, rows: unknown[]): Promise<ModelOption[]> {
|
|
15
|
+
const labelColumn = modelLabelColumn(Model)
|
|
16
|
+
const hintColumn = modelHintColumn(Model)
|
|
17
|
+
const modelLabel = humanizeIdentifier(modelName)
|
|
18
|
+
|
|
19
|
+
// An erased account is stored as placeholders; it is named for what it is.
|
|
20
|
+
const erased = isErasureSubject(Model)
|
|
21
|
+
? await anonymizedRows(modelName, rows.map(row => ({ id: safeGet(row, 'id', 0), name: safeGet(row, 'name', null), email: safeGet(row, 'email', null), avatar: safeGet(row, 'avatar', null) }))).catch(() => [] as boolean[])
|
|
22
|
+
: []
|
|
23
|
+
|
|
24
|
+
return rows.map((row, index) => {
|
|
25
|
+
const id = safeGet(row, 'id', 0) as number | string
|
|
26
|
+
if (erased[index] === true)
|
|
27
|
+
return { id, label: `Anonymized ${modelLabel.toLowerCase()}`, hint: `#${id}` }
|
|
28
|
+
const named = labelColumn ? String(safeGet(row, labelColumn, '') ?? '').trim() : ''
|
|
29
|
+
const hint = hintColumn ? String(safeGet(row, hintColumn, '') ?? '').trim() : ''
|
|
30
|
+
return { id, label: named || `${modelLabel} #${id}`, hint: named ? (hint || `#${id}`) : hint }
|
|
31
|
+
})
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* What the records with these ids are called, by id. A model the dashboard
|
|
36
|
+
* cannot reach, or a lookup that fails, answers with nothing: the caller
|
|
37
|
+
* shows the id, which is still true.
|
|
38
|
+
*/
|
|
39
|
+
export async function recordNames(modelName: string, ids: Array<number | string>): Promise<Map<string, string>> {
|
|
40
|
+
const names = new Map<string, string>()
|
|
41
|
+
const wanted = [...new Set(ids.map(id => Number(id)).filter(id => Number.isSafeInteger(id) && id > 0))]
|
|
42
|
+
if (wanted.length === 0)
|
|
43
|
+
return names
|
|
44
|
+
try {
|
|
45
|
+
const Model = await resolveDashboardModel(modelName)
|
|
46
|
+
if (!Model || typeof Model.query !== 'function')
|
|
47
|
+
return names
|
|
48
|
+
const rows = await Model.query().whereIn('id', wanted).get() as unknown[]
|
|
49
|
+
for (const option of await optionsFromRows(Model, modelName, Array.isArray(rows) ? rows : []))
|
|
50
|
+
names.set(String(option.id), option.label)
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
console.warn(`[dashboard/api] could not name ${modelName} records:`, error)
|
|
54
|
+
}
|
|
55
|
+
return names
|
|
56
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The records that point at a record, for its page: a team's members and
|
|
3
|
+
* invitations, a user's team memberships.
|
|
4
|
+
*
|
|
5
|
+
* A model already says who points at it, in its `hasMany` and `hasOne`. That
|
|
6
|
+
* is all a panel needs: nothing is declared for the dashboard. Each panel is
|
|
7
|
+
* a short table of the newest few with a count, so the page answers "what
|
|
8
|
+
* belongs to this?" without a trip to another list and a filter.
|
|
9
|
+
*/
|
|
10
|
+
import type { ModelHasRelation } from './model-relations'
|
|
11
|
+
import { safeGet } from '../../../../resources/functions/dashboard/data'
|
|
12
|
+
import { resolveDashboardModel } from '../../../../resources/functions/dashboard/model-access'
|
|
13
|
+
import { hiddenModelColumns } from '../../../../resources/functions/dashboard/model-columns'
|
|
14
|
+
import { recordNames } from './model-options'
|
|
15
|
+
import { belongsToRelations, hasRelations, modelLabelColumn, pluralizeLabel, relatedForeignKey } from './model-relations'
|
|
16
|
+
import { humanizeIdentifier, modelCreateFields, modelListColumns, modelSchemaColumns, modelWriteCapabilities } from './model-write'
|
|
17
|
+
|
|
18
|
+
/** How many of a panel's records the page shows before "View all". */
|
|
19
|
+
export const RELATED_PREVIEW = 5
|
|
20
|
+
|
|
21
|
+
export interface RelatedPanelColumn {
|
|
22
|
+
key: string
|
|
23
|
+
label: string
|
|
24
|
+
/** A name or value, a status-like word, or a moment. */
|
|
25
|
+
type: 'text' | 'badge' | 'datetime'
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface RelatedPanel {
|
|
29
|
+
/** Many records point here, or at most one does. */
|
|
30
|
+
kind: 'many' | 'one'
|
|
31
|
+
model: string
|
|
32
|
+
slug: string
|
|
33
|
+
/** The panel's heading: "Team Members", or "Subscriber" for a `hasOne`. */
|
|
34
|
+
title: string
|
|
35
|
+
/** One of them, in words: "Team Member". */
|
|
36
|
+
label: string
|
|
37
|
+
/** The column on the related model that holds this record's id. */
|
|
38
|
+
foreignKey: string
|
|
39
|
+
/** That column as the related model's form field, for a new one that starts here. */
|
|
40
|
+
field: string
|
|
41
|
+
total: number
|
|
42
|
+
columns: RelatedPanelColumn[]
|
|
43
|
+
/** The newest few, each with its `id` and a value per column, ready to show. */
|
|
44
|
+
rows: Array<Record<string, unknown>>
|
|
45
|
+
/** A new one can be added from the dashboard, already pointing at this record. */
|
|
46
|
+
canCreate: boolean
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface SummaryColumn extends RelatedPanelColumn {
|
|
50
|
+
/** For a column that holds another model's id: that model, to name it by. */
|
|
51
|
+
relation?: string
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function snakeCase(name: string): string {
|
|
55
|
+
return name.replace(/([a-z\d])([A-Z])/g, '$1_$2').replace(/[\s-]+/g, '_').toLowerCase()
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The most a panel shows across: enough to tell rows apart, not the whole record. */
|
|
59
|
+
const SUMMARY_LIMIT = 5
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The few columns that say what each related record is.
|
|
63
|
+
*
|
|
64
|
+
* What it is called, the other records it points at (a member's user), its
|
|
65
|
+
* status-like fields, and when it was created. The link back to this record
|
|
66
|
+
* is left out: every row has the same value there. A model with neither a
|
|
67
|
+
* name nor another record to show leads with the id.
|
|
68
|
+
*/
|
|
69
|
+
export function relatedSummaryColumns(Related: any, foreignKey: string, reachable: ReadonlySet<string>): SummaryColumn[] {
|
|
70
|
+
const hidden = hiddenModelColumns(Related)
|
|
71
|
+
|
|
72
|
+
// The model's own choice of list columns, when it made one: the panel is
|
|
73
|
+
// that list, less the column every row here shares.
|
|
74
|
+
const chosen = modelListColumns(Related, modelSchemaColumns(Related).filter(column => !hidden.has(column)))
|
|
75
|
+
if (chosen.declared) {
|
|
76
|
+
const relations = belongsToRelations(Related)
|
|
77
|
+
const attributes = Object.fromEntries(Object.entries((Related?.attributes ?? {}) as Record<string, any>).map(([name, definition]) => [snakeCase(name), definition]))
|
|
78
|
+
return chosen.columns.filter(column => column !== foreignKey).map((column) => {
|
|
79
|
+
const relation = relations.find(candidate => candidate.column === column)
|
|
80
|
+
if (relation)
|
|
81
|
+
return reachable.has(relation.model) ? { key: column, label: humanizeIdentifier(relation.model), type: 'text' as const, relation: relation.model } : { key: column, label: humanizeIdentifier(column), type: 'text' as const }
|
|
82
|
+
const allowed = attributes[column]?.validation?.rule?.allowedValues
|
|
83
|
+
if (Array.isArray(allowed) && allowed.length > 0)
|
|
84
|
+
return { key: column, label: humanizeIdentifier(column), type: 'badge' as const }
|
|
85
|
+
if (/_(?:at|on)$/.test(column))
|
|
86
|
+
return { key: column, label: humanizeIdentifier(column).replace(/\s+(?:At|On)$/, ''), type: 'datetime' as const }
|
|
87
|
+
return { key: column, label: humanizeIdentifier(column), type: 'text' as const }
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const columns: SummaryColumn[] = []
|
|
92
|
+
const label = modelLabelColumn(Related)
|
|
93
|
+
if (label && !hidden.has(label))
|
|
94
|
+
columns.push({ key: label, label: humanizeIdentifier(label), type: 'text' })
|
|
95
|
+
|
|
96
|
+
for (const relation of belongsToRelations(Related)) {
|
|
97
|
+
if (relation.column === foreignKey || hidden.has(relation.column) || !reachable.has(relation.model))
|
|
98
|
+
continue
|
|
99
|
+
columns.push({ key: relation.column, label: humanizeIdentifier(relation.model), type: 'text', relation: relation.model })
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Neither a name of its own nor a record it points at: the id is all there
|
|
103
|
+
// is to tell one row from the next.
|
|
104
|
+
if (columns.length === 0)
|
|
105
|
+
columns.push({ key: 'id', label: 'ID', type: 'text' })
|
|
106
|
+
|
|
107
|
+
for (const [name, definition] of Object.entries((Related?.attributes ?? {}) as Record<string, any>)) {
|
|
108
|
+
const column = snakeCase(name)
|
|
109
|
+
const allowed = definition?.validation?.rule?.allowedValues
|
|
110
|
+
if (!Array.isArray(allowed) || allowed.length === 0 || hidden.has(column) || columns.some(entry => entry.key === column))
|
|
111
|
+
continue
|
|
112
|
+
columns.push({ key: column, label: humanizeIdentifier(name), type: 'badge' })
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const traits = Related?.traits ?? {}
|
|
116
|
+
const kept = columns.slice(0, SUMMARY_LIMIT - 1)
|
|
117
|
+
if ((traits.useTimestamps ?? traits.timestampable) !== false)
|
|
118
|
+
kept.push({ key: 'created_at', label: 'Created', type: 'datetime' })
|
|
119
|
+
return kept
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** One panel's worth, or null when the related model cannot be listed for this record. */
|
|
123
|
+
export async function relatedPanel(parentName: string, parentId: number, relation: ModelHasRelation): Promise<RelatedPanel | null> {
|
|
124
|
+
const Related = await resolveDashboardModel(relation.model).catch(() => null)
|
|
125
|
+
if (!Related || typeof Related.query !== 'function')
|
|
126
|
+
return null
|
|
127
|
+
|
|
128
|
+
const foreignKey = relatedForeignKey(parentName, Related, relation, modelSchemaColumns(Related))
|
|
129
|
+
if (!foreignKey)
|
|
130
|
+
return null
|
|
131
|
+
|
|
132
|
+
// Which of the related model's own relations can be named.
|
|
133
|
+
const reachable = new Set<string>()
|
|
134
|
+
for (const other of belongsToRelations(Related)) {
|
|
135
|
+
if (other.column !== foreignKey && await resolveDashboardModel(other.model).catch(() => null))
|
|
136
|
+
reachable.add(other.model)
|
|
137
|
+
}
|
|
138
|
+
const columns = relatedSummaryColumns(Related, foreignKey, reachable)
|
|
139
|
+
|
|
140
|
+
const total = Number(await Related.query().where(foreignKey, parentId).count()) || 0
|
|
141
|
+
const found = total === 0
|
|
142
|
+
? []
|
|
143
|
+
: await Related.query().where(foreignKey, parentId).orderBy('id', 'desc').take(relation.kind === 'one' ? 1 : RELATED_PREVIEW).get() as unknown[]
|
|
144
|
+
const list = Array.isArray(found) ? found : []
|
|
145
|
+
|
|
146
|
+
// The records these rows point at, named in one lookup per model.
|
|
147
|
+
const names = new Map<string, Map<string, string>>()
|
|
148
|
+
for (const column of columns) {
|
|
149
|
+
if (column.relation)
|
|
150
|
+
names.set(column.key, await recordNames(column.relation, list.map(row => safeGet(row, column.key, null)).filter(id => id !== null) as Array<number | string>))
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const rows = list.map((row) => {
|
|
154
|
+
const shown: Record<string, unknown> = { id: safeGet(row, 'id', 0) }
|
|
155
|
+
for (const column of columns) {
|
|
156
|
+
const stored = safeGet(row, column.key, null)
|
|
157
|
+
if (column.key === 'id')
|
|
158
|
+
shown.id_label = `#${String(stored)}`
|
|
159
|
+
else if (column.relation)
|
|
160
|
+
shown[column.key] = stored === null ? '' : names.get(column.key)?.get(String(stored)) ?? `${column.label} #${String(stored)}`
|
|
161
|
+
else
|
|
162
|
+
shown[column.key] = stored ?? ''
|
|
163
|
+
}
|
|
164
|
+
return shown
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
const label = humanizeIdentifier(relation.model)
|
|
168
|
+
const field = belongsToRelations(Related).find(candidate => candidate.column === foreignKey)?.field ?? null
|
|
169
|
+
return {
|
|
170
|
+
kind: relation.kind,
|
|
171
|
+
model: relation.model,
|
|
172
|
+
slug: relation.slug,
|
|
173
|
+
title: relation.kind === 'one' ? label : pluralizeLabel(label),
|
|
174
|
+
label,
|
|
175
|
+
foreignKey,
|
|
176
|
+
field: field ?? foreignKey,
|
|
177
|
+
total,
|
|
178
|
+
// The id column shows "#12", not a bare number in a text cell.
|
|
179
|
+
columns: columns.map(({ relation: _named, ...column }) => column.key === 'id' ? { ...column, key: 'id_label' } : column),
|
|
180
|
+
rows,
|
|
181
|
+
// Only when the form can be told which record it starts from.
|
|
182
|
+
canCreate: Boolean(field) && modelWriteCapabilities(Related).create && modelCreateFields(Related).some(entry => entry.name === field),
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Every panel a record's page shows, in the order the model declares them. */
|
|
187
|
+
export async function relatedPanels(Model: any, parentName: string, parentId: number): Promise<RelatedPanel[]> {
|
|
188
|
+
const panels: RelatedPanel[] = []
|
|
189
|
+
for (const relation of hasRelations(Model)) {
|
|
190
|
+
try {
|
|
191
|
+
const panel = await relatedPanel(parentName, parentId, relation)
|
|
192
|
+
if (panel)
|
|
193
|
+
panels.push(panel)
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
// One panel that cannot be read (a table not migrated yet) does not
|
|
197
|
+
// take the others, or the page, with it.
|
|
198
|
+
console.warn(`[dashboard/api] related ${relation.model} records could not be listed for ${parentName} ${parentId}:`, error)
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return panels
|
|
202
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The records a model's rows point at, for the dashboard's forms and pages.
|
|
3
|
+
*
|
|
4
|
+
* A `belongsTo` is stored as a number: `team_id: 3`. Asking a person for that
|
|
5
|
+
* number means they leave the form, find the team, read its id off the page
|
|
6
|
+
* and come back to type it. The forms ask for the team instead, by name, and
|
|
7
|
+
* a record's page says which team it is.
|
|
8
|
+
*
|
|
9
|
+
* Only a declared `belongsTo` is a relation here. A model has other fields
|
|
10
|
+
* that end in `Id` (`externalId`, `providerMessageId`, a polymorphic
|
|
11
|
+
* `subjectId`) which are ids of things that live elsewhere or of no one model,
|
|
12
|
+
* and guessing a model from such a name would offer a picker that finds
|
|
13
|
+
* nothing.
|
|
14
|
+
*/
|
|
15
|
+
import { isForeignKeyViolation } from '@stacksjs/error-handling'
|
|
16
|
+
|
|
17
|
+
export interface ModelRelation {
|
|
18
|
+
/** The related model, as declared: `Team`. */
|
|
19
|
+
model: string
|
|
20
|
+
/** Its place in dashboard URLs: `team`, `board-column`. */
|
|
21
|
+
slug: string
|
|
22
|
+
/** The attribute that holds its id on this model: `teamId`. */
|
|
23
|
+
field: string
|
|
24
|
+
/** The column behind that attribute: `team_id`. */
|
|
25
|
+
column: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** One record of a related model, as a picker lists it. */
|
|
29
|
+
export interface ModelOption {
|
|
30
|
+
id: number | string
|
|
31
|
+
/** What the record is called: its name, title or address. */
|
|
32
|
+
label: string
|
|
33
|
+
/** A second line that tells two of the same name apart: a user's email. */
|
|
34
|
+
hint: string
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function snakeCase(name: string): string {
|
|
38
|
+
return name.replace(/([a-z\d])([A-Z])/g, '$1_$2').replace(/[\s-]+/g, '_').toLowerCase()
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function camelCase(name: string): string {
|
|
42
|
+
const words = snakeCase(name).split('_').filter(Boolean)
|
|
43
|
+
return `${words[0] ?? ''}${words.slice(1).map(word => `${word[0]?.toUpperCase()}${word.slice(1)}`).join('')}`
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A model's name as its dashboard URLs spell it: `BoardColumn` is `board-column`. */
|
|
47
|
+
export function modelSlug(name: string): string {
|
|
48
|
+
return snakeCase(name).replace(/_/g, '-')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The models this one belongs to, with where each one's id is kept.
|
|
53
|
+
*
|
|
54
|
+
* A relation is declared as a name (`'Team'`) or as an object naming the
|
|
55
|
+
* model, and optionally the foreign key when it is not the conventional one.
|
|
56
|
+
*/
|
|
57
|
+
export function belongsToRelations(Model: any): ModelRelation[] {
|
|
58
|
+
const relations: ModelRelation[] = []
|
|
59
|
+
for (const declared of Model?.belongsTo ?? []) {
|
|
60
|
+
const model = typeof declared === 'string' ? declared.trim() : String(declared?.model ?? '').trim()
|
|
61
|
+
if (!model)
|
|
62
|
+
continue
|
|
63
|
+
const foreignKey = typeof declared === 'object' && typeof declared?.foreignKey === 'string' ? declared.foreignKey.trim() : ''
|
|
64
|
+
const field = foreignKey ? camelCase(foreignKey) : `${camelCase(model)}Id`
|
|
65
|
+
if (relations.some(relation => relation.field === field))
|
|
66
|
+
continue
|
|
67
|
+
relations.push({ model, slug: modelSlug(model), field, column: snakeCase(field) })
|
|
68
|
+
}
|
|
69
|
+
return relations
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface ModelHasRelation {
|
|
73
|
+
/** Many records point at this one, or at most one does. */
|
|
74
|
+
kind: 'many' | 'one'
|
|
75
|
+
/** The model whose records point here, as declared: `TeamMember`. */
|
|
76
|
+
model: string
|
|
77
|
+
slug: string
|
|
78
|
+
/** The column the declaration names for the link, when it names one. */
|
|
79
|
+
foreignKey: string | null
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* The models whose records point at this one: its `hasMany` and `hasOne`.
|
|
84
|
+
* Declared as a name or as an object naming the model and, optionally, the
|
|
85
|
+
* foreign key on the other side.
|
|
86
|
+
*/
|
|
87
|
+
export function hasRelations(Model: any): ModelHasRelation[] {
|
|
88
|
+
const relations: ModelHasRelation[] = []
|
|
89
|
+
for (const [property, kind] of [['hasMany', 'many'], ['hasOne', 'one']] as const) {
|
|
90
|
+
for (const declared of Model?.[property] ?? []) {
|
|
91
|
+
const model = typeof declared === 'string' ? declared.trim() : String(declared?.model ?? '').trim()
|
|
92
|
+
if (!model || relations.some(relation => relation.model === model))
|
|
93
|
+
continue
|
|
94
|
+
const foreignKey = typeof declared === 'object' && typeof declared?.foreignKey === 'string' && declared.foreignKey.trim()
|
|
95
|
+
? snakeCase(declared.foreignKey.trim())
|
|
96
|
+
: null
|
|
97
|
+
relations.push({ kind, model, slug: modelSlug(model), foreignKey })
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return relations
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The column on the related model that holds this model's id.
|
|
105
|
+
*
|
|
106
|
+
* What the declaration names, else what the related model says of its own
|
|
107
|
+
* `belongsTo`, else the conventional `<model>_id` when the related model has
|
|
108
|
+
* that column. With none of the three there is no knowing which rows are
|
|
109
|
+
* this record's, and the caller shows no panel instead of a wrong one.
|
|
110
|
+
*/
|
|
111
|
+
export function relatedForeignKey(parentName: string, Related: any, relation: ModelHasRelation, relatedColumns: string[]): string | null {
|
|
112
|
+
if (relation.foreignKey)
|
|
113
|
+
return relation.foreignKey
|
|
114
|
+
const declared = belongsToRelations(Related).find(candidate => candidate.model === parentName)
|
|
115
|
+
if (declared)
|
|
116
|
+
return declared.column
|
|
117
|
+
const conventional = `${snakeCase(parentName)}_id`
|
|
118
|
+
return relatedColumns.includes(conventional) ? conventional : null
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** "Team Members" for `Team Member`: the last word made plural. */
|
|
122
|
+
export function pluralizeLabel(label: string): string {
|
|
123
|
+
const words = label.split(' ')
|
|
124
|
+
const last = words.pop() ?? ''
|
|
125
|
+
const lower = last.toLowerCase()
|
|
126
|
+
const plural = lower.endsWith('y') && !/[aeiou]y$/.test(lower)
|
|
127
|
+
? `${last.slice(0, -1)}ies`
|
|
128
|
+
: /(?:s|x|ch|sh)$/.test(lower) ? `${last}es` : `${last}s`
|
|
129
|
+
return [...words, plural].join(' ')
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The columns a record is called by, most telling first. */
|
|
133
|
+
const LABEL_COLUMNS = ['name', 'title', 'label', 'subject', 'email', 'domain', 'code', 'slug'] as const
|
|
134
|
+
|
|
135
|
+
function visibleColumns(Model: any): string[] {
|
|
136
|
+
return Object.entries((Model?.attributes ?? {}) as Record<string, any>)
|
|
137
|
+
.filter(([, definition]) => !definition?.hidden)
|
|
138
|
+
.map(([name]) => snakeCase(name))
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The column whose value names a record of this model, when it has one. */
|
|
142
|
+
export function modelLabelColumn(Model: any): string | null {
|
|
143
|
+
const columns = visibleColumns(Model)
|
|
144
|
+
return LABEL_COLUMNS.find(candidate => columns.includes(candidate)) ?? null
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* A second column that tells two records of the same name apart. Only a
|
|
149
|
+
* person's email does that usefully, and only when the name is not it.
|
|
150
|
+
*/
|
|
151
|
+
export function modelHintColumn(Model: any): string | null {
|
|
152
|
+
return modelLabelColumn(Model) !== 'email' && visibleColumns(Model).includes('email') ? 'email' : null
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Field errors for a write the database refused because a record it points
|
|
157
|
+
* at is not there: the team was deleted while the form was open.
|
|
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.
|
|
162
|
+
*/
|
|
163
|
+
export function missingRelationErrors(Model: any, error: unknown, columns: string[], label: (name: string) => string): Record<string, string[]> {
|
|
164
|
+
if (!isForeignKeyViolation(error))
|
|
165
|
+
return {}
|
|
166
|
+
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
|
+
}
|
|
171
|
+
return errors
|
|
172
|
+
}
|