@nest-my-admin/core 0.9.1 → 0.10.3

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/README.md CHANGED
@@ -768,7 +768,7 @@ AdminModule.forRoot({
768
768
  - Five wrong passwords lock an account for 15 minutes. Sign-in attempts are limited to 20 per minute per IP, with 429 and `Retry-After`.
769
769
  - Unknown users, wrong passwords and locked accounts get the same answer.
770
770
  - The account page changes the password (which signs out every other session), lists signed-in devices, and signs out one or all others.
771
- - **Two-factor sign-in** (TOTP, any authenticator app). A user turns it on from the account page by scanning a QR code and confirming a code, and gets 10 one-time recovery codes. After the password, sign-in answers 401 `TWO_FACTOR_REQUIRED` until the request also carries `otp` (a code or a recovery code). Each code works once, wrong codes count toward the lockout, and turning it on signs out every other session. Turning it off or issuing new recovery codes needs the password; an admin can reset a lost second factor from the Users page. Set `secretKey` (32 bytes, base64: `openssl rand -base64 32`) to encrypt the keys at rest with AES-256-GCM. `issuer` names the app in authenticators. Upgrading from 0.0.x adds four nullable columns to `nma_user` (`totpSecret`, `totpPending`, `totpLastStep`, `recoveryCodes`).
771
+ - **Two-factor sign-in** (TOTP, any authenticator app). A user turns it on from the account page by scanning a QR code and confirming a code, and gets 10 one-time recovery codes. After the password, sign-in answers 401 `TWO_FACTOR_REQUIRED` until the request also carries `otp` (a code or a recovery code). Each code works once, wrong codes count toward the lockout, and turning it on signs out every other session. Turning it off or issuing new recovery codes needs the password; an admin can reset a lost second factor from the Users page. Set `secretKey` (32 bytes, base64: `openssl rand -base64 32`) to encrypt the keys at rest with AES-256-GCM. `issuer` names the app in authenticators. `issuerImage` (an http(s) URL) adds `image=` to the QR code for the apps that read it; others, Ente Auth among them, show their own icons, matched on `issuer`. Upgrading from 0.0.x adds four nullable columns to `nma_user` (`totpSecret`, `totpPending`, `totpLastStep`, `recoveryCodes`).
772
772
  - `bootstrapSuperuser` creates the first user when `nma_user` is empty (it runs in module init, so call `app.init()` before seeding other users). `createAdminUser(dataSource, { … })` adds more.
773
773
  - **CSRF.** Every POST, PATCH and DELETE of a cookie session must send the session's token as `X-CSRF-Token` (the UI does). The API also accepts only `application/json` bodies.
774
774
  - **Your own users:**
@@ -976,6 +976,22 @@ Things hosts tend to write by hand that the admin already does:
976
976
  - **Inline children stay out of the sidebar** by default (`nav: false` unless they set `nav`): no extra group to hide them in.
977
977
  - **Labels in one language** are plain strings; other languages can come from `translate` (see Languages, theme and branding).
978
978
 
979
+ ## Upgrading to 0.10.3
980
+
981
+ Nothing to change. What you may notice:
982
+
983
+ - A save with inline rows now answers with every refused row at once: each row runs in a savepoint, and the save still fails as a whole. One refused row keeps its own status and message; several are one 422 with every row's `fields`.
984
+ - Filter chips are no longer dashed «+» buttons (they read as "add"): a funnel and an arrow, after a «Filter:» caption, and a title in the popover. A yes/no filter is a switch on the chip (one click on, one click off); «No» is behind its arrow. An editable yes/no list cell is a switch that saves on click.
985
+ - Money inputs group digits as they are typed, and a `money` widget also fits a string DTO property.
986
+ - Calendars are always six rows, the column menu scrolls inside the window, a field's `warnIf` no longer remounts its input (the input lost its focus after the first letter), and native controls follow the dark theme (`color-scheme`).
987
+ - In Persian, the server's own texts are translated by the UI, class-validator's default messages included («must not be greater than 5»), without the property's name. English shows them exactly as sent, and a host's own words are never touched. A field the form does not show gives its message without its name.
988
+
989
+ New: `@AdminResource({ creatable: false })` (no «New», a create is refused, records can still be edited), `{ inline, existingOnly: true }` (rows only on an existing parent), `form.afterCreate: 'edit'` (saving a new record opens it), and `afterInlines(record, dto, ctx)` on a resource (a rule about a record and its rows, after both are written, inside the transaction).
990
+
991
+ ## Upgrading to 0.10.2
992
+
993
+ Nothing to change. New: `builtinAuth({ issuerImage })`, an http(s) URL of your logo, sent as `image=` in the two-factor QR code. Only some authenticator apps read it; others, Ente Auth among them, show their own icons, matched on `issuer`. A value that is not an absolute http(s) URL fails at boot.
994
+
979
995
  ## Upgrading to 0.9.1
980
996
 
981
997
  Nothing to change. New: `@AdminAction({ choices })` (see Actions): an input field whose dropdown a resource method fills when the dialog opens, re-checked when the action runs. Every dropdown in the dashboard (forms, filters, sort, page size, inline cell edits, language, roles, audit, debugger, the editor's heading level) is now the dashboard's own list, styled like the rest and right to left in Persian, instead of the browser's native `<select>`. Tests that drove a native select (`selectOption`) click the field, then the option (`getByRole('option', { name })`).
@@ -525,7 +525,7 @@ let AdminApiService = class AdminApiService {
525
525
  .list()
526
526
  .filter((candidate) => entry.metadata.childEntityMetadatas.some((child) => child.target === candidate.entity))
527
527
  .map((candidate) => candidate.schema.label);
528
- throw new AdminBadRequestError(`${schema.label} records are created as one of their kinds${children.length > 0 ? `: ${children.join(', ')}` : ''}`);
528
+ throw new AdminBadRequestError(children.length > 0 ? `${schema.label} records are created as one of their kinds: ${children.join(', ')}` : `${schema.label} records are not created here`);
529
529
  }
530
530
  const { own, inlines } = splitInlines(entry, body);
531
531
  this.policy.checkWriteFields(entry, own, entry.schema.form.create, ctx);
@@ -545,6 +545,7 @@ let AdminApiService = class AdminApiService {
545
545
  });
546
546
  if (plan)
547
547
  await this.inlineWriter.apply(plan, checked, created, tx);
548
+ await resource.afterInlines(created, dto, tx);
548
549
  return this.withInlineRows(entry, created, tx);
549
550
  });
550
551
  }
@@ -622,6 +623,7 @@ let AdminApiService = class AdminApiService {
622
623
  });
623
624
  if (plan)
624
625
  await this.inlineWriter.apply(plan, checked, updated, tx);
626
+ await resource.afterInlines(updated, dto, tx);
625
627
  return this.withInlineRows(entry, updated, tx);
626
628
  });
627
629
  }
@@ -153,6 +153,8 @@ export interface FormLayoutInline {
153
153
  computed?: string[];
154
154
  /** A marker on the first card by `order` («Main picture»). */
155
155
  markFirst?: string;
156
+ /** Not on the form of a new record (rows are added once the parent exists). */
157
+ existingOnly?: true;
156
158
  }
157
159
  /** Label and value rows in a card (an order's totals): a field of the record, or one of its computed columns (`_computed`). */
158
160
  export interface FormLayoutSummary {
@@ -524,6 +526,8 @@ export interface ResourceSchema {
524
526
  aside?: AsideCardSchema[];
525
527
  /** `view`: an existing record opens as text until «Edit». */
526
528
  mode?: 'view';
529
+ /** `edit`: saving a new record opens it instead of going back to the list. */
530
+ afterCreate?: 'edit';
527
531
  /** The record's header: badge fields, and a subtitle of field values and computed columns (`_computed`). */
528
532
  header?: {
529
533
  badges?: string[];
@@ -40,6 +40,8 @@ export interface AdminResourceOptions {
40
40
  * records only the host's own code writes.
41
41
  */
42
42
  readonly?: boolean;
43
+ /** `false`: records of this resource come from elsewhere (no «New», a create is refused); they can still be edited. */
44
+ creatable?: boolean;
43
45
  /** Custom permission codes of this resource: `['view_all']` declares `<name>.view_all` for roles and `ctx.can()`. */
44
46
  permissions?: string[];
45
47
  }
@@ -50,6 +50,7 @@ export function toLayoutInline(inline, label, text, childLabel) {
50
50
  link: inline.link,
51
51
  ...(inline.readonly ? { readonly: true } : {}),
52
52
  ...(inline.computed.length > 0 ? { computed: [...inline.computed] } : {}),
53
+ ...(inline.node.existingOnly ? { existingOnly: true } : {}),
53
54
  ...(inline.node.cards?.markFirst !== undefined ? { markFirst: text(inline.node.cards.markFirst, inline.node.key === undefined ? undefined : `form.${inline.node.key}.markFirst`) } : {}),
54
55
  };
55
56
  }
@@ -41,11 +41,13 @@ export class InlineWriter {
41
41
  // An inline the user cannot view is not there for them (as in the schema).
42
42
  if (!viewable.some((inline) => inline.name === name))
43
43
  shape[`_inlines.${name}`] = [`is not an inline of ${parent.schema.label}`];
44
+ if (creating && viewable.find((inline) => inline.name === name)?.node.existingOnly)
45
+ shape[`_inlines.${name}`] = ['can be added once the record exists'];
44
46
  }
45
47
  if (Object.keys(shape).length > 0)
46
48
  throw new AdminValidationError(shape);
47
49
  // A new parent checks every inline it shows (`min` counts rows that will exist); an update only those it changes.
48
- const inlines = viewable.filter((inline) => creating || Object.hasOwn(sent, inline.name));
50
+ const inlines = viewable.filter((inline) => (creating ? !inline.node.existingOnly : Object.hasOwn(sent, inline.name)));
49
51
  const parsed = inlines.map((inline) => parseChanges(inline, sent[inline.name] ?? {}, shape));
50
52
  if (Object.keys(shape).length > 0)
51
53
  throw new AdminValidationError(shape, 'The inline changes are malformed');
@@ -309,6 +311,7 @@ export class InlineWriter {
309
311
  // The parent's values as the user sees them, body over stored (`values._parent` of relationOptions()).
310
312
  const withParent = async (values) => ({ ...values, _parent: (parentValues ??= { _resource: parent.schema.name, ...(await this.deps.values(parent, parentEntity, tx)) }) });
311
313
  const hasIds = (ids) => [...ids.values()].some((list) => list.length > 0);
314
+ const refusals = [];
312
315
  for (const { planned, rows, moves, positions } of checked) {
313
316
  const { inline, creates, updates, deletes } = planned;
314
317
  const { child } = inline;
@@ -318,12 +321,21 @@ export class InlineWriter {
318
321
  // transaction, so a refusal here undoes the parent too.
319
322
  if (creates.length > 0 && !this.deps.policy.createRule(child, parentEntity, tx))
320
323
  throw new AdminForbiddenError(`You may not add ${child.schema.label} rows here`);
324
+ // Each row in a savepoint, so one refused row (a unique violation included) does not end the others' checks: the
325
+ // user sees what is wrong with all of them at once. Any failure still fails the whole save, below.
321
326
  const run = async (path, change, method) => {
327
+ const runner = tx.manager?.queryRunner;
328
+ await runner?.startTransaction();
322
329
  try {
323
- return await this.deps.change({ ...change, parent: parentRef }, tx, method);
330
+ await this.deps.change({ ...change, parent: parentRef }, tx, method);
331
+ await runner?.commitTransaction();
324
332
  }
325
333
  catch (error) {
326
- throw atRow(error, path, child, this.deps.errorMapper);
334
+ await runner?.rollbackTransaction();
335
+ const placed = atRow(error, path, child, this.deps.errorMapper);
336
+ if (!isRowRefusal(placed))
337
+ throw placed;
338
+ refusals.push(placed);
327
339
  }
328
340
  };
329
341
  for (const entry of deletes) {
@@ -363,8 +375,17 @@ export class InlineWriter {
363
375
  });
364
376
  }
365
377
  }
378
+ // One refusal keeps its own status and message; several are one answer with every row's fields.
379
+ if (refusals.length === 1)
380
+ throw refusals[0];
381
+ if (refusals.length > 1)
382
+ throw new AdminValidationError(Object.assign({}, ...refusals.map((refusal) => refusal.fields)));
366
383
  }
367
384
  }
385
+ /** A row the host or the database refused for its values: worth telling together with the other rows' problems. */
386
+ function isRowRefusal(error) {
387
+ return error instanceof AdminError && (error.status === 422 || error.status === 409 || error.status === 400) && Object.keys(error.fields ?? {}).length > 0;
388
+ }
368
389
  /** The shape of one inline's changes; problems go to `errors` by path. Invalid `_id`s are 404s, as on the child's own routes. */
369
390
  function parseChanges(inline, raw, errors) {
370
391
  const { child } = inline;
@@ -176,6 +176,8 @@ export interface FormConfig {
176
176
  };
177
177
  /** `view`: an existing record opens as text, and «Edit» turns its editable fields into inputs. Default `edit`. */
178
178
  mode?: 'edit' | 'view';
179
+ /** `edit`: saving a new record opens it, for what can only be added once it exists. Default: back to the list. */
180
+ afterCreate?: 'list' | 'edit';
179
181
  /**
180
182
  * The record's header: `badges` (fields shown as badges next to the title; default: every badge-widget field) and a
181
183
  * `subtitle` line of field values and computed list columns (`{ computed: '<list.computed key>' }`), joined by «·».
@@ -286,6 +288,11 @@ export declare abstract class AdminResourceBase<T extends ObjectLiteral = Object
286
288
  * so a write's check sees its own transaction. Default: all records.
287
289
  */
288
290
  relationOptions(_field: string, qb: SelectQueryBuilder<any>, _ctx: AdminContext, _values: Record<string, unknown>): SelectQueryBuilder<any> | Promise<SelectQueryBuilder<any>>;
291
+ /**
292
+ * After a create or update and its inline rows, inside the same transaction: for a rule about the record and its
293
+ * rows together (a product may be published only with its required values). A throw undoes the whole save.
294
+ */
295
+ afterInlines(_record: T, _dto: Record<string, unknown>, _ctx: AdminContext): Promise<void>;
289
296
  /**
290
297
  * Overriding this skips the @BeforeSave/@AfterSave hooks; call `this.runHooks(...)` yourself to keep them.
291
298
  * Relation fields arrive as ids (`customer: 3`, `tags: ['a', 'b']`), already checked to exist; the default
@@ -160,6 +160,11 @@ export class AdminResourceBase {
160
160
  relationOptions(_field, qb, _ctx, _values) {
161
161
  return qb;
162
162
  }
163
+ /**
164
+ * After a create or update and its inline rows, inside the same transaction: for a rule about the record and its
165
+ * rows together (a product may be published only with its required values). A throw undoes the whole save.
166
+ */
167
+ async afterInlines(_record, _dto, _ctx) { }
163
168
  /**
164
169
  * Overriding this skips the @BeforeSave/@AfterSave hooks; call `this.runHooks(...)` yourself to keep them.
165
170
  * Relation fields arrive as ids (`customer: 3`, `tags: ['a', 'b']`), already checked to exist; the default
@@ -349,7 +349,7 @@ export function buildResourceSchema(input) {
349
349
  group: definition.group ?? moduleGroup,
350
350
  ...(definition.icon ? { icon: definition.icon } : {}),
351
351
  primaryKeys,
352
- creatable: children.length === 0 && !definition.readonly,
352
+ creatable: children.length === 0 && !definition.readonly && definition.creatable !== false,
353
353
  ...(definition.readonly ? { readonly: true } : {}),
354
354
  related: [], // filled in by the registry once every resource is known
355
355
  actions: [], // filled in by the registry from the resource's @AdminAction methods
@@ -408,6 +408,7 @@ export function buildResourceSchema(input) {
408
408
  ...(layout ? { layout: localizeLayout(layout, bootLayoutText) } : {}),
409
409
  ...(aside ? { aside } : {}),
410
410
  ...(mode === 'view' ? { mode: 'view' } : {}),
411
+ ...(resource.form?.afterCreate === 'edit' ? { afterCreate: 'edit' } : {}),
411
412
  ...(headerConfig
412
413
  ? {
413
414
  header: {
@@ -50,6 +50,8 @@ export interface LayoutInlineConfig {
50
50
  max?: number;
51
51
  /** Shown, never edited here (a write to it is refused with 422): an order's lines once it is placed. */
52
52
  readonly?: boolean;
53
+ /** Only on an existing parent: a new record's form leaves it out and a create refuses its rows (422). */
54
+ existingOnly?: boolean;
53
55
  /** Computed columns of the child (`list.computed` keys) shown in the table, before its fields (a line's product thumbnail). */
54
56
  computed?: string[];
55
57
  /** Cards: a marker on the first card in `order` (the product's «main picture»). */
@@ -24,7 +24,8 @@ const WIDGET_TYPES = {
24
24
  text: ['string', 'text', 'uuid', 'other'],
25
25
  textarea: ['string', 'text'],
26
26
  number: ['number'],
27
- money: ['decimal', 'number', 'bigint'],
27
+ // A string too: a DTO property holding an amount as text (toman as a bigint string).
28
+ money: ['decimal', 'number', 'bigint', 'string'],
28
29
  switch: ['boolean'],
29
30
  checkbox: ['boolean'],
30
31
  select: ['enum'],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nest-my-admin/core",
3
- "version": "0.9.1",
3
+ "version": "0.10.3",
4
4
  "description": "Django-admin-class admin panel for NestJS + TypeORM",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -35,7 +35,7 @@
35
35
  "typecheck": "tsc -p tsconfig.json --noEmit"
36
36
  },
37
37
  "dependencies": {
38
- "@nest-my-admin/ui": "0.9.1"
38
+ "@nest-my-admin/ui": "0.10.3"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "@nestjs/common": "^11.0.0 || ^12.0.0",