@stacksjs/defaults 0.75.613 → 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 +1 -1
- package/ai/skills/stacks-dashboard/SKILL.md +41 -9
- package/ai/skills/stacks-database/SKILL.md +4 -2
- package/ai/skills/stacks-email/SKILL.md +15 -0
- package/ai/skills/stacks-native/CAPABILITIES.md +1 -1
- 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/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/Models/ModelRecordEdit.stx +240 -28
- package/routes/dashboard-api.ts +2 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: stacks-actions
|
|
3
|
-
description: Use when working with Stacks server actions - creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the
|
|
3
|
+
description: Use when working with Stacks server actions - creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 761 default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/app/Actions/.
|
|
4
4
|
license: MIT
|
|
5
5
|
compatibility: Bun >= 1.3.0, TypeScript
|
|
6
6
|
allowed-tools: Read Edit Write Bash Grep Glob
|
|
@@ -1319,12 +1319,45 @@ pages use (`POST`, `PATCH` and `DELETE /api/dashboard/models/{slug}`), so
|
|
|
1319
1319
|
casts, observers, validation and soft deletes apply and nothing new is
|
|
1320
1320
|
opened. The panels are read again afterwards.
|
|
1321
1321
|
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1322
|
+
Here each row is saved on its own, and stays saved when the next is
|
|
1323
|
+
refused. To change a record and its rows together, use its edit page.
|
|
1324
|
+
|
|
1325
|
+
### The edit page saves a record and its rows together
|
|
1326
|
+
|
|
1327
|
+
A record's edit page (`ModelRecordEdit.stx`) shows the same panels under its
|
|
1328
|
+
fields, wherever the related model lets the dashboard write its rows
|
|
1329
|
+
(stacksjs/stacks#3315). There, adding, editing or deleting a row does not
|
|
1330
|
+
write it: the row is kept as a draft (`functions/dashboard-model-drafts.ts`),
|
|
1331
|
+
marked New, Edited or Will be deleted, and "Save changes" sends the record's
|
|
1332
|
+
changed fields and every panel's drafts in one request:
|
|
1333
|
+
|
|
1334
|
+
```
|
|
1335
|
+
PATCH /api/dashboard/models/{slug}/{id}/save
|
|
1336
|
+
{ fields: { status: 'paid' },
|
|
1337
|
+
related: [{ slug: 'order-line',
|
|
1338
|
+
create: [{ key: 'new-1', fields: { sku: 'A-1' } }],
|
|
1339
|
+
update: [{ id: 5, fields: { quantity: 2 } }],
|
|
1340
|
+
destroy: [7] }] }
|
|
1341
|
+
```
|
|
1342
|
+
|
|
1343
|
+
`ModelSaveAction` runs every write inside one `transaction()`, through the
|
|
1344
|
+
same steps the single-row endpoints use (`model-row-writes.ts`), so each row
|
|
1345
|
+
gets every rule a single save has. The first refusal rolls all of it back,
|
|
1346
|
+
and the answer says where it was, in `at`:
|
|
1347
|
+
|
|
1348
|
+
- `{ operation: 'update' }` for the record's own fields;
|
|
1349
|
+
- `{ operation, panel, row }` for one row: its id, or the key a new row was
|
|
1350
|
+
sent with.
|
|
1351
|
+
|
|
1352
|
+
The page then says "Nothing was saved." It shows the record's messages under
|
|
1353
|
+
its fields, and a row's message on that row and in its form.
|
|
1354
|
+
|
|
1355
|
+
It allows no more than the record's page does. A panel must be one of the
|
|
1356
|
+
record's `hasMany`/`hasOne` that allows that write, decided by `relatedPanel`
|
|
1357
|
+
as the page decides it. A row edited or deleted must point at this record,
|
|
1358
|
+
and a new one is pointed at it: the link back is never taken from the form,
|
|
1359
|
+
so no row moves to another record from here. Bulk actions on a list stay one
|
|
1360
|
+
record at a time (below).
|
|
1328
1361
|
|
|
1329
1362
|
The link between the two models is the foreign key the declaration names,
|
|
1330
1363
|
else the related model's own `belongsTo`, else the conventional
|
|
@@ -1474,9 +1507,8 @@ applies to each record (`when`, `authorize`, `validations`, the self-delete
|
|
|
1474
1507
|
guard, anonymizing a user others refer to), and the page shows how far it
|
|
1475
1508
|
has got.
|
|
1476
1509
|
|
|
1477
|
-
It is not all or nothing, and does not claim to be:
|
|
1478
|
-
|
|
1479
|
-
happened: how many were done and, for the rest, which and why ("Order 8:
|
|
1510
|
+
It is not all or nothing, and does not claim to be: one record refused does
|
|
1511
|
+
not take back the others. The toast says what happened: how many were done and, for the rest, which and why ("Order 8:
|
|
1480
1512
|
Already shipped."). A refusal about the record (any 4xx) goes on to the
|
|
1481
1513
|
next. A failure that is not (a 5xx, no answer at all) stops the run and says
|
|
1482
1514
|
where, so a broken backend is not pressed once per row.
|
|
@@ -334,7 +334,8 @@ SQLite's SQL on a Turso or `sqld` server. Configure `TURSO_DATABASE_URL`
|
|
|
334
334
|
`stacks_migration_lock` (`acquireLibsqlMigrationLock`), since migrating hosts share no filesystem.
|
|
335
335
|
- libSQL rejects SQLite's double-quoted-string fallback, so a statement naming a missing column fails
|
|
336
336
|
instead of storing the column name as text. `tests/corpus-rebuild-sources.test.ts` guards the corpus.
|
|
337
|
-
- Inside `transaction()`, write through the `tx` handle
|
|
337
|
+
- Inside `transaction()`, write through the `tx` handle: a model write made from the callback is part of
|
|
338
|
+
the transaction on SQLite, PostgreSQL and MySQL (stacksjs/stacks#3269), but that is not measured on libSQL.
|
|
338
339
|
|
|
339
340
|
## config/database.ts Shape
|
|
340
341
|
```typescript
|
|
@@ -413,7 +414,8 @@ are experimental with explicit service/topology limits. DynamoDB helpers are a
|
|
|
413
414
|
separate entity API and cannot be selected as the SQL/ORM default.
|
|
414
415
|
|
|
415
416
|
Turso's libsql alias shares SQLite rendering, but uses remote Hrana transport.
|
|
416
|
-
Transactions
|
|
417
|
+
Transactions write through the tx handle (model writes inside one are not
|
|
418
|
+
measured on libSQL); no embedded replicas or native
|
|
417
419
|
file backup are provided. Scheduler locks remain per host. Read the registry's
|
|
418
420
|
provider versions and retained evidence rather than equating an available adapter
|
|
419
421
|
with an unrestricted supported service.
|
|
@@ -244,6 +244,21 @@ abstract class BaseEmailDriver {
|
|
|
244
244
|
}
|
|
245
245
|
```
|
|
246
246
|
|
|
247
|
+
### A mailbox from config, in one deploy
|
|
248
|
+
|
|
249
|
+
Declare the address the app sends from and let the deploy make it:
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
{
|
|
253
|
+
from: { name: 'Votescape', address: 'hello@votescape.org' },
|
|
254
|
+
domain: 'votescape.org',
|
|
255
|
+
mailboxes: ['hello'],
|
|
256
|
+
server: { enabled: true, generatePasswords: true },
|
|
257
|
+
}
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
`buddy deploy` generates `MAIL_PASSWORD_HELLO` before the environment ships (saved encrypted to the environment file, never printed in CI), creates `hello@votescape.org` on the mail server with it, and publishes the mail DNS below. The SMTP driver signs in as `from.address` with that password, and with no `MAIL_HOST` set it uses `mail.<domain>` on port 587 with STARTTLS in production and staging (`ownMailHost` in `core/email/src/drivers/smtp.ts`); elsewhere the default stays loopback. Set `MAIL_MAILER=smtp` to send through the mailbox when the app is also connected to CommsHQ, which otherwise carries its mail.
|
|
261
|
+
|
|
247
262
|
### Mail DNS a deploy publishes
|
|
248
263
|
|
|
249
264
|
With `server.enabled`, `buddy deploy` reconciles the mail domain's DNS through whichever configured provider holds the zone: MX, SPF, DKIM at the selector the server signs under, DMARC (`server.dmarc`), `mail.<domain>`, and the Gmail Postmaster Tools verification TXT when `server.postmaster.google` is set. Writes are surgical: only records the deploy owns are replaced, so other apex TXT (Search Console, other verifications) survive.
|
|
@@ -115,7 +115,7 @@ Limitations:
|
|
|
115
115
|
- SQLite SQL over Hrana HTTP: each statement outside a transaction is one request, and a transaction holds one server stream for its duration.
|
|
116
116
|
- sqld refuses VACUUM, ATTACH, temporary tables and every PRAGMA except the read-only ones and foreign_keys.
|
|
117
117
|
- Embedded replicas are not supported; the connection is always remote.
|
|
118
|
-
-
|
|
118
|
+
- Model writes inside transaction() have not been measured on libSQL: on SQLite, PostgreSQL and MySQL they are part of the transaction (stacksjs/stacks#3269), but here write through the tx handle until a live sqld test shows the same.
|
|
119
119
|
- Scheduler onOneServer() locks stay per-host, as they are on SQLite.
|
|
120
120
|
- `buddy db:backup` does not dump a Turso database; rely on Turso's own point-in-time restore.
|
|
121
121
|
|
|
@@ -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'
|