@stacksjs/defaults 0.75.612 → 0.75.614
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/skills/stacks-actions/SKILL.md +209 -1
- package/ai/skills/stacks-api/SKILL.md +1 -1
- package/ai/skills/stacks-buddy/SKILL.md +1 -1
- package/ai/skills/stacks-dashboard/SKILL.md +120 -9
- package/ai/skills/stacks-database/SKILL.md +4 -2
- package/ai/skills/stacks-email/SKILL.md +15 -0
- package/ai/skills/stacks-middleware/SKILL.md +4 -1
- package/ai/skills/stacks-native/CAPABILITIES.md +1 -1
- package/ai/skills/stacks-native/CATALOG.md +12 -12
- package/ai/skills/stacks-validation/SKILL.md +7 -0
- package/app/Actions/Dashboard/Models/ModelDestroyAction.ts +4 -47
- package/app/Actions/Dashboard/Models/ModelSaveAction.ts +257 -0
- package/app/Actions/Dashboard/Models/ModelStoreAction.ts +4 -31
- package/app/Actions/Dashboard/Models/ModelUpdateAction.ts +5 -61
- package/app/Actions/Dashboard/Models/model-related.ts +2 -3
- package/app/Actions/Dashboard/Models/model-row-writes.ts +188 -0
- package/app/Actions/Storefront/AddToCartAction.ts +12 -15
- package/app/Actions/Storefront/CheckoutContactAction.ts +18 -10
- package/app/Actions/Storefront/CheckoutShippingAction.ts +20 -10
- package/app/Actions/Storefront/PlaceOrderAction.ts +9 -12
- package/app/Actions/Storefront/UpdateCartItemAction.ts +11 -9
- package/app/Middleware/Abilities.ts +4 -3
- package/app/Middleware/Csrf.ts +10 -1
- package/app/Middleware/Throttle.ts +4 -4
- package/functions/dashboard-api.ts +9 -3
- package/functions/dashboard-model-bulk.ts +3 -3
- package/functions/dashboard-model-drafts.test.ts +122 -0
- package/functions/dashboard-model-drafts.ts +228 -0
- package/functions/dashboard-model-record.ts +1 -1
- package/ide/vscode/package.json +1 -1
- package/package.json +5 -5
- package/resources/components/Dashboard/Analytics/AnalyticsPageHeader.stx +3 -13
- package/resources/components/Dashboard/App/RequestsOverview.stx +3 -20
- package/resources/components/Dashboard/App/SourceInventory.stx +1 -5
- package/resources/components/Dashboard/Auth/AccessTokenCreateDialog.stx +11 -28
- package/resources/components/Dashboard/Commerce/CommerceCategoriesDashboard.stx +4 -8
- package/resources/components/Dashboard/Commerce/CommerceCategoryDialog.stx +9 -9
- package/resources/components/Dashboard/Commerce/CommerceCouponDialog.stx +14 -14
- package/resources/components/Dashboard/Commerce/CommerceCouponsDashboard.stx +5 -9
- package/resources/components/Dashboard/Commerce/CommerceCustomerDialog.stx +7 -7
- package/resources/components/Dashboard/Commerce/CommerceCustomersDashboard.stx +3 -7
- package/resources/components/Dashboard/Commerce/CommerceGiftCardDialog.stx +15 -15
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +5 -9
- package/resources/components/Dashboard/Commerce/CommerceManufacturerDialog.stx +12 -15
- package/resources/components/Dashboard/Commerce/CommerceManufacturersDashboard.stx +4 -28
- package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +15 -15
- package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +4 -8
- package/resources/components/Dashboard/Commerce/CommerceOverviewDashboard.stx +3 -11
- package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +8 -9
- package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +3 -20
- package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +4 -4
- package/resources/components/Dashboard/Commerce/CommerceProductDialog.stx +14 -14
- package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +4 -8
- package/resources/components/Dashboard/Commerce/CommerceReviewEditDialog.stx +14 -24
- package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +5 -43
- package/resources/components/Dashboard/Commerce/CommerceTaxDialog.stx +22 -38
- package/resources/components/Dashboard/Commerce/CommerceTaxesDashboard.stx +5 -33
- package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +16 -30
- package/resources/components/Dashboard/Commerce/CommerceUnitsDashboard.stx +4 -28
- package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +15 -9
- package/resources/components/Dashboard/Commerce/CommerceVariantsDashboard.stx +8 -9
- package/resources/components/Dashboard/Commerce/Delivery/CourierDialog.stx +14 -12
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRouteDialog.stx +9 -11
- package/resources/components/Dashboard/Commerce/Delivery/DigitalDeliveryDialog.stx +15 -9
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +11 -7
- package/resources/components/Dashboard/Commerce/Delivery/ShippingMethodDialog.stx +14 -8
- package/resources/components/Dashboard/Commerce/Delivery/ShippingRateDialog.stx +11 -17
- package/resources/components/Dashboard/Commerce/Delivery/ShippingZoneDialog.stx +18 -12
- package/resources/components/Dashboard/Commerce/PaymentRefundDialog.stx +1 -1
- package/resources/components/Dashboard/Commerce/PrintDeviceDialog.stx +5 -5
- package/resources/components/Dashboard/Commerce/PrintDevicesDashboard.stx +4 -8
- package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +5 -9
- package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +2 -10
- package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +14 -67
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +3 -18
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +23 -69
- package/resources/components/Dashboard/Content/AuthorEditorDialog.stx +4 -16
- package/resources/components/Dashboard/Content/BlogDashboard.stx +2 -19
- package/resources/components/Dashboard/Content/BlogPostEditorDialog.stx +31 -51
- package/resources/components/Dashboard/Content/CommentsDashboard.stx +1 -1
- package/resources/components/Dashboard/Content/ContentDashboard.stx +1 -11
- package/resources/components/Dashboard/Content/CreateFolderDialog.stx +1 -4
- package/resources/components/Dashboard/Content/FileManagerDashboard.stx +2 -2
- package/resources/components/Dashboard/Content/PageEditorDialog.stx +8 -17
- package/resources/components/Dashboard/Content/PostEditorDialog.stx +35 -45
- package/resources/components/Dashboard/Content/PostsDashboard.stx +1 -13
- package/resources/components/Dashboard/Content/SeoDashboard.stx +2 -20
- package/resources/components/Dashboard/Content/SeoEditorDialog.stx +4 -38
- package/resources/components/Dashboard/Content/TaxonomyEditorDialog.stx +8 -15
- package/resources/components/Dashboard/Data/ActivityLog.stx +1 -5
- package/resources/components/Dashboard/Deployments/DeploymentList.stx +2 -11
- package/resources/components/Dashboard/Email/InboxMessageList.stx +1 -5
- package/resources/components/Dashboard/Infrastructure/DnsDashboard.stx +2 -16
- package/resources/components/Dashboard/Infrastructure/LogsDashboard.stx +6 -10
- package/resources/components/Dashboard/Infrastructure/MailboxesDashboard.stx +1 -5
- package/resources/components/Dashboard/Infrastructure/ServersDashboard.stx +1 -5
- package/resources/components/Dashboard/Jobs/JobHistory.stx +3 -12
- package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +57 -51
- package/resources/components/Dashboard/Library/ComponentsDashboard.stx +4 -14
- package/resources/components/Dashboard/Library/DependenciesDashboard.stx +2 -15
- package/resources/components/Dashboard/Library/PackagesDashboard.stx +1 -8
- package/resources/components/Dashboard/Library/SourceScaffoldDialog.stx +1 -12
- package/resources/components/Dashboard/Management/PermissionsDashboard.stx +3 -3
- package/resources/components/Dashboard/Marketing/AbandonedCartsDashboard.stx +4 -4
- package/resources/components/Dashboard/Marketing/CampaignDeliveryDialog.stx +3 -5
- package/resources/components/Dashboard/Marketing/CampaignDialog.stx +59 -93
- package/resources/components/Dashboard/Marketing/CampaignsDashboard.stx +5 -5
- package/resources/components/Dashboard/Marketing/MarketingListDialog.stx +12 -26
- package/resources/components/Dashboard/Marketing/MarketingListsDashboard.stx +4 -4
- package/resources/components/Dashboard/Marketing/RecoveryCampaignDialog.stx +12 -43
- package/resources/components/Dashboard/Marketing/SocialPostDialog.stx +7 -41
- package/resources/components/Dashboard/Marketing/SocialPostsDashboard.stx +5 -5
- package/resources/components/Dashboard/Models/ModelRecordEdit.stx +240 -28
- package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +7 -23
- package/resources/components/Dashboard/Models/ModelsOverview.stx +2 -12
- package/resources/components/Dashboard/Notifications/NotificationDeliveries.stx +4 -27
- package/resources/components/Dashboard/Notifications/NotificationDeliveryHistory.stx +4 -36
- package/resources/components/Dashboard/Operations/RecoveryDestinationDialog.stx +18 -47
- package/resources/components/Dashboard/Operations/RecoveryPolicyDialog.stx +24 -78
- package/resources/components/Dashboard/Operations/RecoveryRestoreDialog.stx +8 -19
- package/resources/components/Dashboard/Queries/QueryDashboard.stx +3 -21
- package/resources/components/Dashboard/Releases/ReleaseDashboard.stx +2 -9
- package/resources/components/Dashboard/Settings/SettingsDashboard.stx +1 -11
- package/resources/components/Dashboard/UI/Input.stx +50 -1
- package/resources/components/Dashboard/UI/SearchFilter.stx +27 -17
- package/resources/components/Dashboard/UI/Select.stx +4 -1
- package/resources/components/Dashboard/UI/Textarea.stx +16 -1
- package/resources/views/cart.stx +14 -0
- package/resources/views/checkout/contact.stx +15 -1
- package/resources/views/checkout/payment.stx +7 -0
- package/resources/views/checkout/shipping.stx +39 -5
- package/routes/dashboard-api.ts +2 -0
|
@@ -1,23 +1,8 @@
|
|
|
1
1
|
import type { RequestInstance } from '@stacksjs/types'
|
|
2
2
|
import { Action } from '@stacksjs/actions/runtime'
|
|
3
|
-
import { eraseSubject, GDPR_SUBJECT_MODEL } from '@stacksjs/orm'
|
|
4
3
|
import { response } from '@stacksjs/router'
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { isAccountModel, parseRowId, resolveWritableModel } from './model-write'
|
|
8
|
-
|
|
9
|
-
/** The id of the account making this request, when there is one. */
|
|
10
|
-
async function signedInId(request: RequestInstance): Promise<number | null> {
|
|
11
|
-
try {
|
|
12
|
-
const id = Number((await request.user())?.id)
|
|
13
|
-
return Number.isSafeInteger(id) && id > 0 ? id : null
|
|
14
|
-
}
|
|
15
|
-
catch {
|
|
16
|
-
// The local dashboard runs without a session, and then there is no
|
|
17
|
-
// account to protect.
|
|
18
|
-
return null
|
|
19
|
-
}
|
|
20
|
-
}
|
|
4
|
+
import { destroyModelRow, requestAccountId, rowRefusalResponse } from './model-row-writes'
|
|
5
|
+
import { parseRowId, resolveWritableModel } from './model-write'
|
|
21
6
|
|
|
22
7
|
/**
|
|
23
8
|
* `DELETE /api/dashboard/models/{slug}/{id}`.
|
|
@@ -41,35 +26,7 @@ export default new Action({
|
|
|
41
26
|
if (id === null)
|
|
42
27
|
return response.json({ message: 'A numeric row id is required.' }, 400)
|
|
43
28
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
const viewer = await signedInId(request)
|
|
47
|
-
if (isAccountModel(resolved.Model) && viewer === id)
|
|
48
|
-
return response.json({ message: 'You are signed in with this account, so it cannot be deleted from here. Ask another admin to remove it.' }, 409)
|
|
49
|
-
|
|
50
|
-
const result = await destroyModelRecord(id, {
|
|
51
|
-
Model: resolved.Model,
|
|
52
|
-
actor: viewer === null ? 'dashboard' : `dashboard:user:${viewer}`,
|
|
53
|
-
erase: async (subject, actor) => {
|
|
54
|
-
const erased = await eraseSubject(subject, { actor })
|
|
55
|
-
const own = erased.changes.find(change => change.model === GDPR_SUBJECT_MODEL)
|
|
56
|
-
return { action: (own?.action ?? 'keep') as 'anonymize' | 'delete' | 'keep' }
|
|
57
|
-
},
|
|
58
|
-
})
|
|
59
|
-
|
|
60
|
-
if (result.ok)
|
|
61
|
-
return { ok: true, id, anonymized: result.outcome === 'anonymized' }
|
|
62
|
-
if (result.reason === 'missing')
|
|
63
|
-
return response.json({ message: `${resolved.modelName} ${id} not found.` }, 404)
|
|
64
|
-
// The database kept the row because others still point at it. Nothing
|
|
65
|
-
// failed: the answer is to deal with those records first, and saying
|
|
66
|
-
// "could not be deleted" sent people to the server logs for it.
|
|
67
|
-
if (result.reason === 'referenced')
|
|
68
|
-
return response.json({ message: `This ${resolved.modelName.toLowerCase()} cannot be deleted while other records still refer to it. Remove or reassign those records first.` }, 409)
|
|
69
|
-
// Erasure is one transaction and repeating it changes nothing it already
|
|
70
|
-
// changed, so "try again" is a real answer here.
|
|
71
|
-
if (result.reason === 'erasure-failed')
|
|
72
|
-
return dashboardOperationalError(result.cause, 'Other records still refer to this user, and anonymizing the account did not finish. Try again: repeating it is safe.', 'ModelDestroyAction.erase', 500)
|
|
73
|
-
return dashboardOperationalError(result.cause, 'The model record could not be deleted.', 'ModelDestroyAction', 500)
|
|
29
|
+
const result = await destroyModelRow(resolved, id, await requestAccountId(request))
|
|
30
|
+
return result.ok ? { ok: true, id, anonymized: result.anonymized } : rowRefusalResponse(result)
|
|
74
31
|
},
|
|
75
32
|
})
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import type { RequestInstance } from '@stacksjs/types'
|
|
2
|
+
import { Action } from '@stacksjs/actions/runtime'
|
|
3
|
+
import { transaction } from '@stacksjs/orm'
|
|
4
|
+
import { response } from '@stacksjs/router'
|
|
5
|
+
import { safeGet } from '../../../../resources/functions/dashboard/data'
|
|
6
|
+
import { dashboardOperationalError } from '../dashboard-response'
|
|
7
|
+
import type { RelatedPanel } from './model-related'
|
|
8
|
+
import { relatedPanel } from './model-related'
|
|
9
|
+
import { hasRelations } from './model-relations'
|
|
10
|
+
import type { RowRefusal } from './model-row-writes'
|
|
11
|
+
import { destroyModelRow, formFields, requestAccountId, storeModelRow, updateModelRow } from './model-row-writes'
|
|
12
|
+
import type { ResolvedModel } from './model-write'
|
|
13
|
+
import { isValidModelSlug, parseRowId, resolveWritableModel } from './model-write'
|
|
14
|
+
|
|
15
|
+
/** What one related panel is asked to change. */
|
|
16
|
+
interface PanelChanges {
|
|
17
|
+
/** The related model's slug: which panel. */
|
|
18
|
+
slug: string
|
|
19
|
+
/** New rows. `key` is the form's own name for each, so a refusal can say which. */
|
|
20
|
+
create: Array<{ key: string, fields: Record<string, unknown> }>
|
|
21
|
+
update: Array<{ id: number, fields: Record<string, unknown> }>
|
|
22
|
+
destroy: number[]
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Where a save was refused: the record's own fields, or one row of one panel. */
|
|
26
|
+
interface SaveLocation {
|
|
27
|
+
operation: 'update' | 'create' | 'destroy'
|
|
28
|
+
/** The panel's slug, for a row. */
|
|
29
|
+
panel?: string
|
|
30
|
+
/** The row: its id, or the key a new row was sent with. */
|
|
31
|
+
row?: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface PanelPlan {
|
|
35
|
+
changes: PanelChanges
|
|
36
|
+
panel: RelatedPanel
|
|
37
|
+
target: ResolvedModel
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface SavedPanel {
|
|
41
|
+
slug: string
|
|
42
|
+
created: Array<{ key: string, id: unknown }>
|
|
43
|
+
updated: number[]
|
|
44
|
+
destroyed: number[]
|
|
45
|
+
/** Of the destroyed: kept, with their personal details removed. */
|
|
46
|
+
anonymized: number[]
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Thrown inside the transaction to roll it back at the first refusal, carrying where it was. */
|
|
50
|
+
class SaveStopped extends Error {
|
|
51
|
+
constructor(readonly refusal: RowRefusal, readonly at: SaveLocation) {
|
|
52
|
+
super(refusal.message)
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
57
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The related changes the form sent, checked for shape before anything is
|
|
62
|
+
* read or written. A string is what is wrong with them.
|
|
63
|
+
*/
|
|
64
|
+
function readRelatedChanges(raw: unknown): PanelChanges[] | string {
|
|
65
|
+
if (raw === undefined || raw === null)
|
|
66
|
+
return []
|
|
67
|
+
if (!Array.isArray(raw))
|
|
68
|
+
return '`related` must be a list of panels.'
|
|
69
|
+
const panels: PanelChanges[] = []
|
|
70
|
+
for (const entry of raw) {
|
|
71
|
+
if (!isRecord(entry) || typeof entry.slug !== 'string' || !isValidModelSlug(entry.slug))
|
|
72
|
+
return 'Each related panel needs the related model\'s slug.'
|
|
73
|
+
if (panels.some(panel => panel.slug === entry.slug))
|
|
74
|
+
return `The ${entry.slug} panel was sent twice.`
|
|
75
|
+
const create: PanelChanges['create'] = []
|
|
76
|
+
for (const row of Array.isArray(entry.create) ? entry.create : []) {
|
|
77
|
+
if (!isRecord(row) || typeof row.key !== 'string' || row.key === '' || !isRecord(row.fields))
|
|
78
|
+
return `Each new ${entry.slug} row needs a key and its fields.`
|
|
79
|
+
if (create.some(other => other.key === row.key))
|
|
80
|
+
return `Two new ${entry.slug} rows were sent as ${row.key}.`
|
|
81
|
+
create.push({ key: row.key, fields: row.fields })
|
|
82
|
+
}
|
|
83
|
+
const update: PanelChanges['update'] = []
|
|
84
|
+
for (const row of Array.isArray(entry.update) ? entry.update : []) {
|
|
85
|
+
const id = isRecord(row) ? parseRowId(row.id) : null
|
|
86
|
+
if (id === null || !isRecord(row.fields))
|
|
87
|
+
return `Each edited ${entry.slug} row needs its id and its fields.`
|
|
88
|
+
if (update.some(other => other.id === id))
|
|
89
|
+
return `${entry.slug} ${id} was edited twice.`
|
|
90
|
+
update.push({ id, fields: row.fields })
|
|
91
|
+
}
|
|
92
|
+
const destroy: number[] = []
|
|
93
|
+
for (const raw of Array.isArray(entry.destroy) ? entry.destroy : []) {
|
|
94
|
+
const id = parseRowId(raw)
|
|
95
|
+
if (id === null)
|
|
96
|
+
return `Each deleted ${entry.slug} row needs its id.`
|
|
97
|
+
if (update.some(row => row.id === id))
|
|
98
|
+
return `${entry.slug} ${id} cannot be both edited and deleted.`
|
|
99
|
+
if (!destroy.includes(id))
|
|
100
|
+
destroy.push(id)
|
|
101
|
+
}
|
|
102
|
+
panels.push({ slug: entry.slug, create, update, destroy })
|
|
103
|
+
}
|
|
104
|
+
return panels
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The fields a related row may be given here: the panel's form, which leaves
|
|
109
|
+
* out the link back to this record. A row is not moved to another record
|
|
110
|
+
* from this one's page, and a new row belongs to this one whatever was sent.
|
|
111
|
+
*/
|
|
112
|
+
function panelFields(panel: RelatedPanel, fields: Record<string, unknown>): Record<string, unknown> {
|
|
113
|
+
const allowed = new Set(panel.fields.map(field => field.name))
|
|
114
|
+
return Object.fromEntries(Object.entries(fields).filter(([name]) => allowed.has(name)))
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function refusal(status: RowRefusal['status'], message: string): RowRefusal {
|
|
118
|
+
return { ok: false, status, message }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** A refusal before anything was written, said the way a stopped save says it. */
|
|
122
|
+
function refusedBefore(status: RowRefusal['status'], message: string, at: SaveLocation): Response {
|
|
123
|
+
return response.json({ message, at }, status)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function stoppedResponse(stopped: SaveStopped): Response {
|
|
127
|
+
const { refusal: refused, at } = stopped
|
|
128
|
+
// A failure of the server is logged as one. Either way nothing was kept.
|
|
129
|
+
if (refused.where)
|
|
130
|
+
return dashboardOperationalError(refused.cause, `${refused.message} Nothing was saved.`, `ModelSaveAction (${refused.where})`, refused.status)
|
|
131
|
+
return response.json({ message: refused.message, ...(refused.errors ? { errors: refused.errors } : {}), at }, refused.status)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* `PATCH /api/dashboard/models/{slug}/{id}/save`.
|
|
136
|
+
*
|
|
137
|
+
* Saves a record and its related rows together, all or nothing
|
|
138
|
+
* (stacksjs/stacks#3315). The body is the record's changed `fields` and, per
|
|
139
|
+
* related panel, the rows to add, edit and delete:
|
|
140
|
+
*
|
|
141
|
+
* { fields: { status: 'paid' },
|
|
142
|
+
* related: [{ slug: 'order-line', create: [{ key: 'new-1', fields: { sku: 'A-1' } }],
|
|
143
|
+
* update: [{ id: 5, fields: { quantity: 2 } }], destroy: [7] }] }
|
|
144
|
+
*
|
|
145
|
+
* Every write runs inside one `transaction()`, through the same steps the
|
|
146
|
+
* single-row endpoints use (`./model-row-writes`), so each row gets every
|
|
147
|
+
* rule a single save has. The first refusal rolls them all back and the
|
|
148
|
+
* answer says where (`at`): the record, or a row of a panel.
|
|
149
|
+
*
|
|
150
|
+
* It allows no more than the record's page does. A panel must be one of the
|
|
151
|
+
* record's `hasMany`/`hasOne` that allows the write, decided as the page
|
|
152
|
+
* decides it (`relatedPanel`). A row edited or deleted must point at this
|
|
153
|
+
* record, and a new one is pointed at it.
|
|
154
|
+
*/
|
|
155
|
+
export default new Action({
|
|
156
|
+
name: 'Dashboard Model Save',
|
|
157
|
+
description: 'Saves a record and its related rows together, all or nothing, from the dashboard.',
|
|
158
|
+
method: 'PATCH',
|
|
159
|
+
apiResponse: true,
|
|
160
|
+
async handle(request: RequestInstance) {
|
|
161
|
+
const id = parseRowId(request.getParam('id'))
|
|
162
|
+
if (id === null)
|
|
163
|
+
return response.json({ message: 'A numeric row id is required.' }, 400)
|
|
164
|
+
|
|
165
|
+
const input = request.all()
|
|
166
|
+
const fields = formFields(input.fields)
|
|
167
|
+
const related = readRelatedChanges(input.related)
|
|
168
|
+
if (typeof related === 'string')
|
|
169
|
+
return response.json({ message: related }, 422)
|
|
170
|
+
const editsRecord = Object.keys(fields).length > 0
|
|
171
|
+
if (!editsRecord && related.every(panel => panel.create.length + panel.update.length + panel.destroy.length === 0))
|
|
172
|
+
return response.json({ message: 'Nothing to save.' }, 422)
|
|
173
|
+
|
|
174
|
+
// Editing the record's own fields needs its model to allow edits. Saving
|
|
175
|
+
// only its rows asks that of the rows' models instead.
|
|
176
|
+
const resolved = await resolveWritableModel(request.getParam('slug'), editsRecord ? 'update' : undefined)
|
|
177
|
+
if ('error' in resolved)
|
|
178
|
+
return response.json({ message: resolved.error }, resolved.status)
|
|
179
|
+
|
|
180
|
+
try {
|
|
181
|
+
if (!(await resolved.Model.find(id)))
|
|
182
|
+
return response.json({ message: `${resolved.modelName} ${id} not found.` }, 404)
|
|
183
|
+
|
|
184
|
+
// Each panel is planned before anything is written.
|
|
185
|
+
const plans: PanelPlan[] = []
|
|
186
|
+
for (const changes of related) {
|
|
187
|
+
const relation = hasRelations(resolved.Model).find(candidate => candidate.slug === changes.slug)
|
|
188
|
+
const panel = relation ? await relatedPanel(resolved.modelName, id, relation) : null
|
|
189
|
+
if (!panel)
|
|
190
|
+
return refusedBefore(422, `A ${resolved.modelName.toLowerCase()} has no ${changes.slug} rows to save from here.`, { operation: 'update', panel: changes.slug })
|
|
191
|
+
if (changes.create.length > 0 && !panel.canCreate)
|
|
192
|
+
return refusedBefore(405, `${panel.title} cannot be added from here.`, { operation: 'create', panel: changes.slug })
|
|
193
|
+
if (changes.update.length > 0 && !panel.canUpdate)
|
|
194
|
+
return refusedBefore(405, `${panel.title} cannot be edited from here.`, { operation: 'update', panel: changes.slug })
|
|
195
|
+
if (changes.destroy.length > 0 && !panel.canDestroy)
|
|
196
|
+
return refusedBefore(405, `${panel.title} cannot be deleted from here.`, { operation: 'destroy', panel: changes.slug })
|
|
197
|
+
const target = await resolveWritableModel(changes.slug)
|
|
198
|
+
if ('error' in target)
|
|
199
|
+
return response.json({ message: target.error, at: { operation: 'update', panel: changes.slug } }, target.status)
|
|
200
|
+
plans.push({ changes, panel, target })
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const viewer = await requestAccountId(request)
|
|
204
|
+
const own = async (plan: PanelPlan, rowId: number, operation: SaveLocation['operation']): Promise<void> => {
|
|
205
|
+
const row = await plan.target.Model.find(rowId)
|
|
206
|
+
if (!row || String(safeGet(row, plan.panel.foreignKey, '')) !== String(id))
|
|
207
|
+
throw new SaveStopped(refusal(404, `${plan.panel.label} ${rowId} is not one of this ${resolved.modelName.toLowerCase()}'s.`), { operation, panel: plan.changes.slug, row: String(rowId) })
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return await transaction(async () => {
|
|
211
|
+
let changed: string[] = []
|
|
212
|
+
if (editsRecord) {
|
|
213
|
+
const saved = await updateModelRow(resolved, id, fields)
|
|
214
|
+
if (!saved.ok)
|
|
215
|
+
throw new SaveStopped(saved, { operation: 'update' })
|
|
216
|
+
changed = saved.changed
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const panels: SavedPanel[] = []
|
|
220
|
+
for (const plan of plans) {
|
|
221
|
+
const at = (operation: SaveLocation['operation'], row: string): SaveLocation => ({ operation, panel: plan.changes.slug, row })
|
|
222
|
+
const saved: SavedPanel = { slug: plan.changes.slug, created: [], updated: [], destroyed: [], anonymized: [] }
|
|
223
|
+
// Deleted first, so a new row may take a value one being removed held.
|
|
224
|
+
for (const rowId of plan.changes.destroy) {
|
|
225
|
+
await own(plan, rowId, 'destroy')
|
|
226
|
+
const done = await destroyModelRow(plan.target, rowId, viewer)
|
|
227
|
+
if (!done.ok)
|
|
228
|
+
throw new SaveStopped(done, at('destroy', String(rowId)))
|
|
229
|
+
saved.destroyed.push(rowId)
|
|
230
|
+
if (done.anonymized)
|
|
231
|
+
saved.anonymized.push(rowId)
|
|
232
|
+
}
|
|
233
|
+
for (const row of plan.changes.update) {
|
|
234
|
+
await own(plan, row.id, 'update')
|
|
235
|
+
const done = await updateModelRow(plan.target, row.id, panelFields(plan.panel, row.fields))
|
|
236
|
+
if (!done.ok)
|
|
237
|
+
throw new SaveStopped(done, at('update', String(row.id)))
|
|
238
|
+
saved.updated.push(row.id)
|
|
239
|
+
}
|
|
240
|
+
for (const row of plan.changes.create) {
|
|
241
|
+
const done = await storeModelRow(plan.target, panelFields(plan.panel, row.fields), { [plan.panel.foreignKey]: id })
|
|
242
|
+
if (!done.ok)
|
|
243
|
+
throw new SaveStopped(done, at('create', row.key))
|
|
244
|
+
saved.created.push({ key: row.key, id: done.id })
|
|
245
|
+
}
|
|
246
|
+
panels.push(saved)
|
|
247
|
+
}
|
|
248
|
+
return { ok: true, id, changed, related: panels }
|
|
249
|
+
})
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
if (error instanceof SaveStopped)
|
|
253
|
+
return stoppedResponse(error)
|
|
254
|
+
return dashboardOperationalError(error, 'The record and its rows could not be saved. Nothing was saved.', 'ModelSaveAction', 500)
|
|
255
|
+
}
|
|
256
|
+
},
|
|
257
|
+
})
|
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import type { RequestInstance } from '@stacksjs/types'
|
|
2
2
|
import { Action } from '@stacksjs/actions/runtime'
|
|
3
|
-
import { ModelValidationError, toSnakeCaseKeys } from '@stacksjs/orm'
|
|
4
3
|
import { response } from '@stacksjs/router'
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { humanizeIdentifier, prepareModelFields, resolveWritableModel } from './model-write'
|
|
4
|
+
import { formFields, rowRefusalResponse, storeModelRow } from './model-row-writes'
|
|
5
|
+
import { resolveWritableModel } from './model-write'
|
|
8
6
|
|
|
9
7
|
interface ModelWriteInput {
|
|
10
8
|
fields?: unknown
|
|
@@ -20,32 +18,7 @@ export default new Action({
|
|
|
20
18
|
if ('error' in resolved)
|
|
21
19
|
return response.json({ message: resolved.error }, resolved.status)
|
|
22
20
|
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
const body = (raw && typeof raw === 'object' && !Array.isArray(raw)) ? raw as Record<string, unknown> : {}
|
|
26
|
-
const { data, errors } = prepareModelFields(resolved.Model, body)
|
|
27
|
-
|
|
28
|
-
if (Object.keys(errors).length > 0)
|
|
29
|
-
return response.json({ message: 'Validation failed.', errors }, 422)
|
|
30
|
-
if (Object.keys(data).length === 0)
|
|
31
|
-
return response.json({ message: 'No fillable fields in the request body.' }, 422)
|
|
32
|
-
|
|
33
|
-
try {
|
|
34
|
-
const row = await resolved.Model.create(toSnakeCaseKeys(data))
|
|
35
|
-
const id = row?.id ?? row?.attributes?.id ?? null
|
|
36
|
-
return { ok: true, id }
|
|
37
|
-
}
|
|
38
|
-
catch (error) {
|
|
39
|
-
// The model's own rules rejected the row: the caller's mistake, named
|
|
40
|
-
// field by field, not a server failure (stacksjs/stacks#3007).
|
|
41
|
-
if (error instanceof ModelValidationError)
|
|
42
|
-
return response.json({ message: 'Validation failed.', errors: error.errors }, 422)
|
|
43
|
-
// A record this one points at was deleted while the form was open. The
|
|
44
|
-
// person can pick another, so it is said on that field.
|
|
45
|
-
const missing = missingRelationErrors(resolved.Model, error, Object.keys(toSnakeCaseKeys(data)), humanizeIdentifier)
|
|
46
|
-
if (Object.keys(missing).length > 0)
|
|
47
|
-
return response.json({ message: 'Validation failed.', errors: missing }, 422)
|
|
48
|
-
return dashboardOperationalError(error, 'The model record could not be created.', 'ModelStoreAction', 500)
|
|
49
|
-
}
|
|
21
|
+
const result = await storeModelRow(resolved, formFields(request.all().fields))
|
|
22
|
+
return result.ok ? { ok: true, id: result.id } : rowRefusalResponse(result)
|
|
50
23
|
},
|
|
51
24
|
})
|
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
import type { RequestInstance } from '@stacksjs/types'
|
|
2
2
|
import { Action } from '@stacksjs/actions/runtime'
|
|
3
|
-
import { isUniqueViolation, ModelValidationError, toSnakeCaseKeys } from '@stacksjs/orm'
|
|
4
3
|
import { response } from '@stacksjs/router'
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { planSwitches, requestedSwitches, storedSwitches } from './model-switches'
|
|
8
|
-
import { duplicateFieldErrors, humanizeIdentifier, parseRowId, prepareModelFields, resolveWritableModel } from './model-write'
|
|
4
|
+
import { formFields, rowRefusalResponse, updateModelRow } from './model-row-writes'
|
|
5
|
+
import { parseRowId, resolveWritableModel } from './model-write'
|
|
9
6
|
|
|
10
7
|
interface ModelWriteInput {
|
|
11
8
|
fields?: unknown
|
|
@@ -33,61 +30,8 @@ export default new Action({
|
|
|
33
30
|
if (id === null)
|
|
34
31
|
return response.json({ message: 'A numeric row id is required.' }, 400)
|
|
35
32
|
|
|
36
|
-
//
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
// columns — and `slug` is a real column on plenty of models, so it
|
|
40
|
-
// cannot simply be blocklisted. One level of nesting keeps the two
|
|
41
|
-
// namespaces apart.
|
|
42
|
-
const input = request.all()
|
|
43
|
-
const raw = input.fields
|
|
44
|
-
const body = (raw && typeof raw === 'object' && !Array.isArray(raw)) ? raw as Record<string, unknown> : {}
|
|
45
|
-
const prepared = prepareModelFields(resolved.Model, body, true)
|
|
46
|
-
if (Object.keys(prepared.errors).length > 0)
|
|
47
|
-
return response.json({ message: 'Validation failed.', errors: prepared.errors }, 422)
|
|
48
|
-
const changes = toSnakeCaseKeys(prepared.data)
|
|
49
|
-
// What a trait keeps for itself (a confirmed email, two-factor) is asked
|
|
50
|
-
// for as a switch and changed by the trait's own function.
|
|
51
|
-
const { asked, errors: unreadable } = requestedSwitches(resolved.Model, body)
|
|
52
|
-
if (Object.keys(unreadable).length > 0)
|
|
53
|
-
return response.json({ message: 'Validation failed.', errors: unreadable }, 422)
|
|
54
|
-
if (Object.keys(changes).length === 0 && asked.length === 0)
|
|
55
|
-
return response.json({ message: 'No writable fields in the request body.' }, 422)
|
|
56
|
-
|
|
57
|
-
try {
|
|
58
|
-
const row = await resolved.Model.find(id)
|
|
59
|
-
if (!row)
|
|
60
|
-
return response.json({ message: `${resolved.modelName} ${id} not found.` }, 404)
|
|
61
|
-
// Refused before anything is written: a switch that cannot be turned
|
|
62
|
-
// that way refuses the whole save, like any other field's rule.
|
|
63
|
-
const { turning, errors } = planSwitches(resolved.Model, asked, asked.length > 0 ? await storedSwitches(resolved.Model, id) : {})
|
|
64
|
-
if (Object.keys(errors).length > 0)
|
|
65
|
-
return response.json({ message: 'Validation failed.', errors }, 422)
|
|
66
|
-
if (Object.keys(changes).length > 0)
|
|
67
|
-
await resolved.Model.update(id, changes)
|
|
68
|
-
for (const request of turning)
|
|
69
|
-
await request.switch.set(id, request.on)
|
|
70
|
-
return { ok: true, id, changed: [...Object.keys(changes), ...turning.map(request => request.switch.column)] }
|
|
71
|
-
}
|
|
72
|
-
catch (error) {
|
|
73
|
-
// The model's own rules rejected the row: the caller's mistake, named
|
|
74
|
-
// field by field, not a server failure (stacksjs/stacks#3007).
|
|
75
|
-
if (error instanceof ModelValidationError)
|
|
76
|
-
return response.json({ message: 'Validation failed.', errors: error.errors }, 422)
|
|
77
|
-
// A value another row already holds, on a field the model marks unique
|
|
78
|
-
// (a user's email). The person can fix that, so it is named on the field
|
|
79
|
-
// like any other rule, not reported as a failed save.
|
|
80
|
-
if (isUniqueViolation(error)) {
|
|
81
|
-
const errors = duplicateFieldErrors(resolved.Model, Object.keys(changes))
|
|
82
|
-
if (Object.keys(errors).length > 0)
|
|
83
|
-
return response.json({ message: 'Validation failed.', errors }, 422)
|
|
84
|
-
}
|
|
85
|
-
// A record this one points at was deleted while the form was open. The
|
|
86
|
-
// person can pick another, so it is said on that field.
|
|
87
|
-
const missing = missingRelationErrors(resolved.Model, error, Object.keys(changes), humanizeIdentifier)
|
|
88
|
-
if (Object.keys(missing).length > 0)
|
|
89
|
-
return response.json({ message: 'Validation failed.', errors: missing }, 422)
|
|
90
|
-
return dashboardOperationalError(error, 'The model record could not be updated.', 'ModelUpdateAction', 500)
|
|
91
|
-
}
|
|
33
|
+
// Nested under `fields`, apart from the URL's params (see `formFields`).
|
|
34
|
+
const result = await updateModelRow(resolved, id, formFields(request.all().fields))
|
|
35
|
+
return result.ok ? { ok: true, id, changed: result.changed } : rowRefusalResponse(result)
|
|
92
36
|
},
|
|
93
37
|
})
|
|
@@ -11,9 +11,8 @@
|
|
|
11
11
|
* also where they are managed: it carries that model's form fields and each
|
|
12
12
|
* listed row's values, so a row is added, edited and deleted from this page.
|
|
13
13
|
* Each of those is a write of its own through the related model's own
|
|
14
|
-
* endpoints
|
|
15
|
-
*
|
|
16
|
-
* (stacksjs/stacks#3269).
|
|
14
|
+
* endpoints, so a row saved stays saved when the next one is refused. A form
|
|
15
|
+
* that saves a record and its rows together, all or nothing, is not offered.
|
|
17
16
|
*/
|
|
18
17
|
import type { ModelHasRelation } from './model-relations'
|
|
19
18
|
import { safeGet } from '../../../../resources/functions/dashboard/data'
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One row created, edited or deleted from the dashboard, as an outcome
|
|
3
|
+
* rather than a response.
|
|
4
|
+
*
|
|
5
|
+
* The create, edit and delete endpoints each answer for one row. Saving a
|
|
6
|
+
* record and its related rows together runs the same steps several times
|
|
7
|
+
* inside one transaction, and has to stop at the first refusal and say where
|
|
8
|
+
* it was. So the steps live here, each returning what happened, and every
|
|
9
|
+
* endpoint turns that into its answer the same way (`rowRefusalResponse`).
|
|
10
|
+
* Every rule a single save has applies to each row of a combined one.
|
|
11
|
+
*/
|
|
12
|
+
import type { ResponseStatus } from '@stacksjs/bun-router'
|
|
13
|
+
import type { RequestInstance } from '@stacksjs/types'
|
|
14
|
+
import { eraseSubject, GDPR_SUBJECT_MODEL, isUniqueViolation, ModelValidationError, toSnakeCaseKeys } from '@stacksjs/orm'
|
|
15
|
+
import { response } from '@stacksjs/router'
|
|
16
|
+
import { dashboardOperationalError } from '../dashboard-response'
|
|
17
|
+
import { destroyModelRecord } from './model-destroy'
|
|
18
|
+
import { missingRelationErrors } from './model-relations'
|
|
19
|
+
import { planSwitches, requestedSwitches, storedSwitches } from './model-switches'
|
|
20
|
+
import type { ResolvedModel } from './model-write'
|
|
21
|
+
import { duplicateFieldErrors, humanizeIdentifier, isAccountModel, prepareModelFields } from './model-write'
|
|
22
|
+
|
|
23
|
+
/** Why a row was not written: what the visitor is told, and for a failure, what went wrong. */
|
|
24
|
+
export interface RowRefusal {
|
|
25
|
+
ok: false
|
|
26
|
+
status: ResponseStatus
|
|
27
|
+
message: string
|
|
28
|
+
/** The model's own words, field by field. */
|
|
29
|
+
errors?: Record<string, string[]>
|
|
30
|
+
/** A failure of the server rather than of the input: logged, and answered as one. */
|
|
31
|
+
cause?: unknown
|
|
32
|
+
/** Where it failed, for the log line. Set on a failure, never on a refusal. */
|
|
33
|
+
where?: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type RowWrite<T> = ({ ok: true } & T) | RowRefusal
|
|
37
|
+
|
|
38
|
+
function refused(status: ResponseStatus, message: string, errors?: Record<string, string[]>): RowRefusal {
|
|
39
|
+
return { ok: false, status, message, ...(errors ? { errors } : {}) }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function failed(cause: unknown, message: string, where: string): RowRefusal {
|
|
43
|
+
return { ok: false, status: 500, message, cause, where }
|
|
44
|
+
}
|
|
45
|
+
|
|
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 {
|
|
48
|
+
// The model's own rules rejected the row: the caller's mistake, named
|
|
49
|
+
// field by field, not a server failure (stacksjs/stacks#3007).
|
|
50
|
+
if (error instanceof ModelValidationError)
|
|
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)
|
|
57
|
+
if (Object.keys(errors).length > 0)
|
|
58
|
+
return refused(422, 'Validation failed.', errors)
|
|
59
|
+
}
|
|
60
|
+
// A record this one points at was deleted while the form was open. The
|
|
61
|
+
// person can pick another, so it is said on that field.
|
|
62
|
+
const missing = missingRelationErrors(resolved.Model, error, columns, humanizeIdentifier)
|
|
63
|
+
if (Object.keys(missing).length > 0)
|
|
64
|
+
return refused(422, 'Validation failed.', missing)
|
|
65
|
+
return null
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The fields a form sent. Edits arrive nested under `fields`: the router's
|
|
70
|
+
* input bag merges the body with route params and query, so a flat payload
|
|
71
|
+
* would pick up the `slug` and `id` from the URL and try to write them as
|
|
72
|
+
* columns, and `slug` is a real column on plenty of models.
|
|
73
|
+
*/
|
|
74
|
+
export function formFields(raw: unknown): Record<string, unknown> {
|
|
75
|
+
return (raw && typeof raw === 'object' && !Array.isArray(raw)) ? raw as Record<string, unknown> : {}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Create one row. `fixed` are columns set by where it is created, not by the form: a related row's link back. */
|
|
79
|
+
export async function storeModelRow(resolved: ResolvedModel, body: Record<string, unknown>, fixed: Record<string, unknown> = {}): Promise<RowWrite<{ id: unknown }>> {
|
|
80
|
+
const { data, errors } = prepareModelFields(resolved.Model, body)
|
|
81
|
+
if (Object.keys(errors).length > 0)
|
|
82
|
+
return refused(422, 'Validation failed.', errors)
|
|
83
|
+
if (Object.keys(data).length === 0)
|
|
84
|
+
return refused(422, 'No fillable fields in the request body.')
|
|
85
|
+
|
|
86
|
+
const values = { ...toSnakeCaseKeys(data), ...fixed }
|
|
87
|
+
try {
|
|
88
|
+
const row = await resolved.Model.create(values)
|
|
89
|
+
return { ok: true, id: row?.id ?? row?.attributes?.id ?? null }
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
return fieldRefusal(resolved, error, Object.keys(values), false)
|
|
93
|
+
?? failed(error, 'The model record could not be created.', 'ModelStoreAction')
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Edit one row with the fields that changed, and the switches a trait keeps for itself. */
|
|
98
|
+
export async function updateModelRow(resolved: ResolvedModel, id: number, body: Record<string, unknown>): Promise<RowWrite<{ id: number, changed: string[] }>> {
|
|
99
|
+
const prepared = prepareModelFields(resolved.Model, body, true)
|
|
100
|
+
if (Object.keys(prepared.errors).length > 0)
|
|
101
|
+
return refused(422, 'Validation failed.', prepared.errors)
|
|
102
|
+
const changes = toSnakeCaseKeys(prepared.data)
|
|
103
|
+
// What a trait keeps for itself (a confirmed email, two-factor) is asked
|
|
104
|
+
// for as a switch and changed by the trait's own function.
|
|
105
|
+
const { asked, errors: unreadable } = requestedSwitches(resolved.Model, body)
|
|
106
|
+
if (Object.keys(unreadable).length > 0)
|
|
107
|
+
return refused(422, 'Validation failed.', unreadable)
|
|
108
|
+
if (Object.keys(changes).length === 0 && asked.length === 0)
|
|
109
|
+
return refused(422, 'No writable fields in the request body.')
|
|
110
|
+
|
|
111
|
+
try {
|
|
112
|
+
const row = await resolved.Model.find(id)
|
|
113
|
+
if (!row)
|
|
114
|
+
return refused(404, `${resolved.modelName} ${id} not found.`)
|
|
115
|
+
// Refused before anything is written: a switch that cannot be turned
|
|
116
|
+
// that way refuses the whole save, like any other field's rule.
|
|
117
|
+
const { turning, errors } = planSwitches(resolved.Model, asked, asked.length > 0 ? await storedSwitches(resolved.Model, id) : {})
|
|
118
|
+
if (Object.keys(errors).length > 0)
|
|
119
|
+
return refused(422, 'Validation failed.', errors)
|
|
120
|
+
if (Object.keys(changes).length > 0)
|
|
121
|
+
await resolved.Model.update(id, changes)
|
|
122
|
+
for (const request of turning)
|
|
123
|
+
await request.switch.set(id, request.on)
|
|
124
|
+
return { ok: true, id, changed: [...Object.keys(changes), ...turning.map(request => request.switch.column)] }
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
return fieldRefusal(resolved, error, Object.keys(changes), true)
|
|
128
|
+
?? failed(error, 'The model record could not be updated.', 'ModelUpdateAction')
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The id of the account making this request, when there is one. */
|
|
133
|
+
export async function requestAccountId(request: RequestInstance): Promise<number | null> {
|
|
134
|
+
try {
|
|
135
|
+
const id = Number((await request.user())?.id)
|
|
136
|
+
return Number.isSafeInteger(id) && id > 0 ? id : null
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
// The local dashboard runs without a session, and then there is no
|
|
140
|
+
// account to protect.
|
|
141
|
+
return null
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Delete one row through the model, so soft deletes, observers and cascades
|
|
147
|
+
* apply. A user other records still point at is anonymized instead: see
|
|
148
|
+
* `./model-destroy`. `viewer` is the account making the request, which is
|
|
149
|
+
* not deleted from here.
|
|
150
|
+
*/
|
|
151
|
+
export async function destroyModelRow(resolved: ResolvedModel, id: number, viewer: number | null): Promise<RowWrite<{ id: number, anonymized: boolean }>> {
|
|
152
|
+
// Deleting the account you are signed in with ends your own access in the
|
|
153
|
+
// middle of using it, and for the last admin there is no way back in.
|
|
154
|
+
if (isAccountModel(resolved.Model) && viewer === id)
|
|
155
|
+
return refused(409, 'You are signed in with this account, so it cannot be deleted from here. Ask another admin to remove it.')
|
|
156
|
+
|
|
157
|
+
const result = await destroyModelRecord(id, {
|
|
158
|
+
Model: resolved.Model,
|
|
159
|
+
actor: viewer === null ? 'dashboard' : `dashboard:user:${viewer}`,
|
|
160
|
+
erase: async (subject, actor) => {
|
|
161
|
+
const erased = await eraseSubject(subject, { actor })
|
|
162
|
+
const own = erased.changes.find(change => change.model === GDPR_SUBJECT_MODEL)
|
|
163
|
+
return { action: (own?.action ?? 'keep') as 'anonymize' | 'delete' | 'keep' }
|
|
164
|
+
},
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
if (result.ok)
|
|
168
|
+
return { ok: true, id, anonymized: result.outcome === 'anonymized' }
|
|
169
|
+
if (result.reason === 'missing')
|
|
170
|
+
return refused(404, `${resolved.modelName} ${id} not found.`)
|
|
171
|
+
// The database kept the row because others still point at it. Nothing
|
|
172
|
+
// failed: the answer is to deal with those records first, and saying
|
|
173
|
+
// "could not be deleted" sent people to the server logs for it.
|
|
174
|
+
if (result.reason === 'referenced')
|
|
175
|
+
return refused(409, `This ${resolved.modelName.toLowerCase()} cannot be deleted while other records still refer to it. Remove or reassign those records first.`)
|
|
176
|
+
// Erasure is one transaction and repeating it changes nothing it already
|
|
177
|
+
// changed, so "try again" is a real answer here.
|
|
178
|
+
if (result.reason === 'erasure-failed')
|
|
179
|
+
return failed(result.cause, 'Other records still refer to this user, and anonymizing the account did not finish. Try again: repeating it is safe.', 'ModelDestroyAction.erase')
|
|
180
|
+
return failed(result.cause, 'The model record could not be deleted.', 'ModelDestroyAction')
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** A refusal as an endpoint answers it: the visitor's words, or a logged failure of the server. */
|
|
184
|
+
export function rowRefusalResponse(refusal: RowRefusal): Response {
|
|
185
|
+
if (refusal.where)
|
|
186
|
+
return dashboardOperationalError(refusal.cause, refusal.message, refusal.where, refusal.status)
|
|
187
|
+
return response.json({ message: refusal.message, ...(refusal.errors ? { errors: refusal.errors } : {}) }, refusal.status)
|
|
188
|
+
}
|