@nauticana/sail 0.6.1 → 0.7.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nauticana/sail",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "Metadata-driven Angular component library for CRUD admin frontends backed by the keel Go backend. Tables, forms, navigation, OTP/2FA/social auth, billing, payout onboarding.",
5
5
  "main": "src/index.ts",
6
6
  "files": [
@@ -1,5 +1,5 @@
1
1
  import { inject } from "@angular/core";
2
- import { ForeignKey, TableColumn, TableDefinition } from "../../model/appdata";
2
+ import { ForeignKey, TableAction, TableColumn, TableDefinition } from "../../model/appdata";
3
3
  import { ConstantValue } from "../../model/common";
4
4
  import { BaseAuthService } from "../../service/auth.service";
5
5
  import { SAIL_GUI_CONFIG, SailGuiConfig, DEFAULT_CONFIG } from "../../config";
@@ -56,6 +56,48 @@ export abstract class BaseTable {
56
56
  return this.cacheService.canDelete(this.tableName);
57
57
  }
58
58
 
59
+ /**
60
+ * Returns the table's registered TableAction list — populated by
61
+ * keel's REST engine from the basis `table_action` table. Empty
62
+ * when the table has no custom actions.
63
+ */
64
+ getActions(recordSpecific?: boolean): TableAction[] {
65
+ const tableDef = this.cacheService.getTableDefinition(this.tableName);
66
+ const actions = tableDef?.Actions ?? [];
67
+ if (recordSpecific === undefined) return [...actions].sort(this.sortActions);
68
+ return actions.filter((a) => a.recordSpecific === recordSpecific).sort(this.sortActions);
69
+ }
70
+
71
+ private sortActions = (a: TableAction, b: TableAction) =>
72
+ (a.displayOrder ?? 0) - (b.displayOrder ?? 0);
73
+
74
+ /**
75
+ * Authorization gate for a TableAction. Mirrors canRead/canCreate
76
+ * etc. — looks up the caller's grant against (authorityObject,
77
+ * authorityCheck) scoped to the table name. Returns true when the
78
+ * action button should render.
79
+ */
80
+ canExecuteAction(action: TableAction): boolean {
81
+ return this.cacheService.canExecute(action.authorityObject, action.authorityCheck, this.tableName);
82
+ }
83
+
84
+ /**
85
+ * Pulls the primary-key column values off a record into a plain
86
+ * object keyed by the columns' PascalName. Used as the request
87
+ * body when a record-specific TableAction fires — the backend
88
+ * handler receives the row's PK exactly the way generic CRUD
89
+ * does for get / delete.
90
+ */
91
+ primaryKeyValues(record: Record<string, unknown>): Record<string, unknown> {
92
+ const tableDef = this.cacheService.getTableDefinition(this.tableName);
93
+ const pk: Record<string, unknown> = {};
94
+ if (!tableDef?.Keys) return pk;
95
+ for (const key of tableDef.Keys) {
96
+ pk[key.PascalName] = record[key.PascalName];
97
+ }
98
+ return pk;
99
+ }
100
+
59
101
  emptyRecord(): any {
60
102
  const record : any = {[this.config.opField]: 'I'}
61
103
  const tableDef = this.cacheService.getTableDefinition(this.tableName);
@@ -4,6 +4,16 @@
4
4
  @if (canCreate()) {
5
5
  <button mat-raised-button class="accent" (click)="addRecord()">New Record</button>
6
6
  }
7
+ @for (action of getActions(false); track action.action) {
8
+ @if (canExecuteAction(action)) {
9
+ <button mat-stroked-button type="button"
10
+ [title]="action.caption"
11
+ (click)="executeAction(action)">
12
+ @if (action.icon) { <mat-icon>{{ action.icon }}</mat-icon> }
13
+ {{ action.caption }}
14
+ </button>
15
+ }
16
+ }
7
17
  </div>
8
18
  <table class="mat-table">
9
19
  <thead>
@@ -44,6 +54,17 @@
44
54
  } @else if (canDelete()) {
45
55
  <button mat-icon-button (click)="deleteRow(record)" title="Delete"><mat-icon>delete</mat-icon></button>
46
56
  }
57
+ @if (record[config.opField] !== 'I') {
58
+ @for (action of getActions(true); track action.action) {
59
+ @if (canExecuteAction(action)) {
60
+ <button mat-icon-button type="button"
61
+ [title]="action.caption"
62
+ (click)="executeAction(action, record)">
63
+ <mat-icon>{{ action.icon || 'play_arrow' }}</mat-icon>
64
+ </button>
65
+ }
66
+ }
67
+ }
47
68
  </td>
48
69
  }
49
70
  </tr>
@@ -5,6 +5,8 @@ import { BaseForm } from "../abstract/base_form";
5
5
  import { MatDialog } from "@angular/material/dialog";
6
6
  import { TableForm } from "../form/form_table";
7
7
  import { MatIconModule } from "@angular/material/icon";
8
+ import { BackendService } from "../../service/rest_service";
9
+ import { TableAction } from "../../model/appdata";
8
10
 
9
11
  @Component({
10
12
  selector: 'table-detail',
@@ -31,6 +33,34 @@ export class TableDetail extends BaseForm implements OnInit {
31
33
  fkColumns: string[] = [];
32
34
 
33
35
  private readonly dialog = inject(MatDialog);
36
+ private readonly backendService = inject(BackendService);
37
+
38
+ /**
39
+ * Fire a TableAction. Per-row actions require the record to be
40
+ * server-side (not 'I' inserted-locally-not-saved); table-level
41
+ * actions only need the parent to be writable. Action POSTs hit
42
+ * the resolved URL directly — no need to round-trip through the
43
+ * parent form.
44
+ */
45
+ executeAction(action: TableAction, record?: {[key: string]: unknown}): void {
46
+ if (!this.canExecuteAction(action)) {
47
+ alert(`Missing authorization for action ${action.authorityObject}/${action.authorityCheck}`);
48
+ return;
49
+ }
50
+ if (action.recordSpecific && record && record[this.config.opField] === 'I') {
51
+ alert('Save the record first before running this action.');
52
+ return;
53
+ }
54
+ if (action.confirmMessage && !confirm(action.confirmMessage)) return;
55
+ const body = action.recordSpecific && record ? this.primaryKeyValues(record) : {};
56
+ this.backendService.executeAction(action.method, body).subscribe({
57
+ next: () => {/* parent form re-fetches on its own save */},
58
+ error: (err) => {
59
+ console.error(`Action ${action.action} failed`, err);
60
+ alert(err?.error?.detail ?? `Failed to ${action.caption}`);
61
+ },
62
+ });
63
+ }
34
64
 
35
65
  override canCreate() { return !this.parentReadOnly() && super.canCreate(); }
36
66
  override canUpdate() { return !this.parentReadOnly() && super.canUpdate(); }
@@ -1,8 +1,20 @@
1
1
  <h2>{{ getCaption() }}</h2>
2
2
 
3
- @if (canCreate()) {
4
- <button mat-raised-button class="accent" (click)="addRecord()">New Record</button>
5
- }
3
+ <div class="table-list__toolbar">
4
+ @if (canCreate()) {
5
+ <button mat-raised-button class="accent" (click)="addRecord()">New Record</button>
6
+ }
7
+ @for (action of getActions(false); track action.action) {
8
+ @if (canExecuteAction(action)) {
9
+ <button mat-stroked-button type="button"
10
+ [title]="action.caption"
11
+ (click)="executeAction(action)">
12
+ @if (action.icon) { <mat-icon>{{ action.icon }}</mat-icon> }
13
+ {{ action.caption }}
14
+ </button>
15
+ }
16
+ }
17
+ </div>
6
18
 
7
19
  <table>
8
20
  <thead>
@@ -27,6 +39,15 @@
27
39
  } @else {
28
40
  <button mat-icon-button type="button" (click)="editRecord(record)" title="Edit"><mat-icon>edit</mat-icon></button>
29
41
  <button mat-icon-button type="button" (click)="deleteRecord(record)" title="Delete"><mat-icon>delete</mat-icon></button>
42
+ @for (action of getActions(true); track action.action) {
43
+ @if (canExecuteAction(action)) {
44
+ <button mat-icon-button type="button"
45
+ [title]="action.caption"
46
+ (click)="executeAction(action, record)">
47
+ <mat-icon>{{ action.icon || 'play_arrow' }}</mat-icon>
48
+ </button>
49
+ }
50
+ }
30
51
  }
31
52
  </td>
32
53
  }
@@ -4,6 +4,7 @@ import { ActivatedRoute, Params } from "@angular/router";
4
4
  import { BaseView } from "../abstract/base_view";
5
5
  import { TableEdit } from "./table_edit";
6
6
  import { BackendService } from "../../service/rest_service";
7
+ import { TableAction } from "../../model/appdata";
7
8
  import { MatButtonModule } from "@angular/material/button";
8
9
  import { MatCheckboxModule } from "@angular/material/checkbox";
9
10
  import { MatIconModule } from "@angular/material/icon";
@@ -77,6 +78,29 @@ export class TableList extends BaseView implements OnInit {
77
78
  });
78
79
  }
79
80
 
81
+ /**
82
+ * Fire a TableAction. For record-specific actions, `record` carries
83
+ * the row's primary key columns (lifted via BaseTable.primaryKeyValues).
84
+ * For table-level actions, `record` is undefined and the body is empty.
85
+ * Refreshes the row list on success — most actions mutate visible
86
+ * state (set_default flipping defaults, etc.).
87
+ */
88
+ executeAction(action: TableAction, record?: {[key: string]: unknown}): void {
89
+ if (!this.canExecuteAction(action)) {
90
+ alert(`Missing authorization for action ${action.authorityObject}/${action.authorityCheck}`);
91
+ return;
92
+ }
93
+ if (action.confirmMessage && !confirm(action.confirmMessage)) return;
94
+ const body = action.recordSpecific && record ? this.primaryKeyValues(record) : {};
95
+ this.backendService.executeAction(action.method, body).subscribe({
96
+ next: () => this.fetchRecords(),
97
+ error: (err) => {
98
+ console.error(`Action ${action.action} failed`, err);
99
+ alert(err?.error?.detail ?? `Failed to ${action.caption}`);
100
+ },
101
+ });
102
+ }
103
+
80
104
  handleQueryParams(params: Params) {
81
105
  const newSearchTerms: {[key: string]: string} = {};
82
106
  let hasSearchTerms = false;
@@ -14,4 +14,14 @@
14
14
  @if (canCreate()) {
15
15
  <button mat-raised-button class="accent" (click)="onAddRecord()">New Record</button>
16
16
  }
17
+ @for (action of getActions(false); track action.action) {
18
+ @if (canExecuteAction(action)) {
19
+ <button mat-stroked-button type="button"
20
+ [title]="action.caption"
21
+ (click)="executeAction(action)">
22
+ @if (action.icon) { <mat-icon>{{ action.icon }}</mat-icon> }
23
+ {{ action.caption }}
24
+ </button>
25
+ }
26
+ }
17
27
  </div>
@@ -1,9 +1,12 @@
1
1
  import { ChangeDetectionStrategy, ChangeDetectorRef, Component, inject, Input, OnInit, ViewEncapsulation } from "@angular/core";
2
2
  import { MatButtonModule } from "@angular/material/button";
3
+ import { MatIconModule } from "@angular/material/icon";
3
4
  import { ActivatedRoute, Router } from "@angular/router";
4
5
  import { BaseForm } from "../abstract/base_form";
5
6
  import { RecordForm } from "../form/form_record";
6
7
  import { ApplicationMenu } from "../../model/common";
8
+ import { TableAction } from "../../model/appdata";
9
+ import { BackendService } from "../../service/rest_service";
7
10
 
8
11
  @Component({
9
12
  selector: 'table-search',
@@ -12,6 +15,7 @@ import { ApplicationMenu } from "../../model/common";
12
15
  templateUrl: './table_search.html',
13
16
  imports: [
14
17
  MatButtonModule,
18
+ MatIconModule,
15
19
  RecordForm,
16
20
  ],
17
21
  })
@@ -24,6 +28,27 @@ export class TableSearch extends BaseForm implements OnInit {
24
28
  private readonly router = inject(Router);
25
29
  private readonly route = inject(ActivatedRoute);
26
30
  private readonly cdr = inject(ChangeDetectorRef);
31
+ private readonly backendService = inject(BackendService);
32
+
33
+ /**
34
+ * Fire a table-level TableAction from the search-screen toolbar.
35
+ * Record-specific actions never show up here — search has no
36
+ * row context.
37
+ */
38
+ executeAction(action: TableAction): void {
39
+ if (!this.canExecuteAction(action)) {
40
+ alert(`Missing authorization for action ${action.authorityObject}/${action.authorityCheck}`);
41
+ return;
42
+ }
43
+ if (action.confirmMessage && !confirm(action.confirmMessage)) return;
44
+ this.backendService.executeAction(action.method, {}).subscribe({
45
+ next: () => {/* no-op — search screen has no list to refresh */},
46
+ error: (err) => {
47
+ console.error(`Action ${action.action} failed`, err);
48
+ alert(err?.error?.detail ?? `Failed to ${action.caption}`);
49
+ },
50
+ });
51
+ }
27
52
 
28
53
  ngOnInit() {
29
54
  const data = this.route.snapshot.data;
@@ -56,13 +56,27 @@ export interface TableColumn {
56
56
  Validators?: AbstractControlOptions['validators'];
57
57
  }
58
58
 
59
+ // One custom button registered against a table via the basis
60
+ // table_action seed. Auth gating uses the existing
61
+ // authorization_role_permission path against (authorityObject,
62
+ // authorityCheck, low_limit=tableName) — see canExecute() in
63
+ // BaseAuthService.
64
+ //
65
+ // recordSpecific=true → button renders next to per-row edit/delete.
66
+ // recordSpecific=false → button renders next to the "New Record" toolbar.
67
+ //
68
+ // `method` is the URL POST target the click should hit (resolved by
69
+ // keel from table_name + action_name + optional method_name override).
59
70
  export interface TableAction {
60
- action: string;
61
- caption: string;
62
- method: string;
63
- enable: string;
64
- authorityCheck: string;
65
- recordSpecific: string;
71
+ action: string; // lowercase action_name
72
+ caption: string;
73
+ method: string; // resolved URL path (POST target)
74
+ icon?: string; // Material icon name; falsy → label-only
75
+ recordSpecific: boolean;
76
+ displayOrder?: number;
77
+ confirmMessage?: string;
78
+ authorityObject: string; // uppercased table_name — for canExecute()
79
+ authorityCheck: string; // uppercased action_name — for canExecute()
66
80
  }
67
81
 
68
82
  export interface ForeignKey {
@@ -471,6 +471,15 @@ export abstract class BaseAuthService {
471
471
  canCreate(tableName: string) { return this.checkPermission('TABLE', 'INSERT', tableName); }
472
472
  canUpdate(tableName: string) { return this.checkPermission('TABLE', 'UPDATE', tableName); }
473
473
  canDelete(tableName: string) { return this.checkPermission('TABLE', 'DELETE', tableName); }
474
+ /**
475
+ * Authorization check for a custom TableAction. authorityObject is the
476
+ * uppercased table_name; activity is the uppercased action_name. The
477
+ * grant's low_limit is checked against the table_name (lowercase) —
478
+ * matching the convention populated by keel's loadTableActions.
479
+ */
480
+ canExecute(authorityObject: string, activity: string, tableName: string): boolean {
481
+ return this.checkPermission(authorityObject, activity, tableName);
482
+ }
474
483
  canAccess(pageName: string) { return this.checkPermission('PAGE', 'ACCESS', pageName); }
475
484
  canReport(reportName: string) { return this.checkPermission('REPORT', 'ACCESS', reportName); }
476
485
 
@@ -91,4 +91,16 @@ export class BackendService {
91
91
  delete(apiName: string, filter?: {[key: string]: string}): Observable<{message: string}> {
92
92
  return this.http.delete<{message: string}>(this.apiUrl(apiName + '/delete'), {params: this.toParams(filter)}).pipe(catchError(this.handleError));
93
93
  }
94
+
95
+ /**
96
+ * Fire a TableAction button. `actionPath` is the resolved URL path
97
+ * the keel REST engine pre-computed onto TableAction.method
98
+ * (e.g. "/user_payment_method/set_default"); pass it verbatim and
99
+ * the call will POST to {host}{api_prefix}{actionPath} with the
100
+ * supplied body. For record-specific actions the body carries the
101
+ * primary key values; for table-level actions it is typically `{}`.
102
+ */
103
+ executeAction<T = unknown>(actionPath: string, body: Record<string, unknown> = {}): Observable<T> {
104
+ return this.http.post<T>(this.apiUrl(actionPath), body).pipe(catchError(this.handleError));
105
+ }
94
106
  }
@@ -37,9 +37,10 @@ export const RestURL = {
37
37
  payoutReusableLinkURL: '/api/v1/payout/reusable/link',
38
38
  payoutStatusURL: '/api/v1/payout/status',
39
39
  // User payment methods — list/delete go through keel's generic REST
40
- // CRUD against the UserSpecific basis table; only set-default has a
41
- // custom endpoint (atomic multi-row UPDATE).
42
- paymentMethodSetDefaultURL: '/api/v1/payment-methods/set-default',
40
+ // CRUD against the UserSpecific basis table; set-default is a
41
+ // TableAction (basis table_action row), mounted at the conventional
42
+ // URL POST /api/v1/user_payment_method/set_default.
43
+ paymentMethodSetDefaultURL: '/api/v1/user_payment_method/set_default',
43
44
  };
44
45
 
45
46
  /** Call this at app startup to set the backend host URL */