@terreno/admin-frontend 57.19.2 → 57.20.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.
Files changed (149) hide show
  1. package/CHANGELOG.md +393 -0
  2. package/dist/AdminFieldRenderer.d.ts +3 -2
  3. package/dist/AdminFieldRenderer.d.ts.map +1 -1
  4. package/dist/AdminFieldRenderer.js +12 -5
  5. package/dist/AdminFieldRenderer.js.map +1 -1
  6. package/dist/AdminFieldRendererCore.d.ts +6 -3
  7. package/dist/AdminFieldRendererCore.d.ts.map +1 -1
  8. package/dist/AdminFieldRendererCore.js +10 -7
  9. package/dist/AdminFieldRendererCore.js.map +1 -1
  10. package/dist/AdminFilterDrawer.d.ts.map +1 -1
  11. package/dist/AdminFilterDrawer.js +2 -3
  12. package/dist/AdminFilterDrawer.js.map +1 -1
  13. package/dist/AdminHome.d.ts.map +1 -1
  14. package/dist/AdminHome.js +5 -2
  15. package/dist/AdminHome.js.map +1 -1
  16. package/dist/AdminModelForm.d.ts.map +1 -1
  17. package/dist/AdminModelForm.js +4 -0
  18. package/dist/AdminModelForm.js.map +1 -1
  19. package/dist/AdminNestedArrayField.d.ts +2 -0
  20. package/dist/AdminNestedArrayField.d.ts.map +1 -1
  21. package/dist/AdminNestedArrayField.js +51 -25
  22. package/dist/AdminNestedArrayField.js.map +1 -1
  23. package/dist/AdminNestedObjectField.d.ts +43 -0
  24. package/dist/AdminNestedObjectField.d.ts.map +1 -0
  25. package/dist/AdminNestedObjectField.js +72 -0
  26. package/dist/AdminNestedObjectField.js.map +1 -0
  27. package/dist/AdminRolesField.d.ts +3 -1
  28. package/dist/AdminRolesField.d.ts.map +1 -1
  29. package/dist/AdminRolesField.js +6 -2
  30. package/dist/AdminRolesField.js.map +1 -1
  31. package/dist/AdminShell.d.ts +3 -3
  32. package/dist/AdminShell.d.ts.map +1 -1
  33. package/dist/AdminShell.js +4 -6
  34. package/dist/AdminShell.js.map +1 -1
  35. package/dist/ConfigurationScreen.d.ts.map +1 -1
  36. package/dist/ConfigurationScreen.js +3 -3
  37. package/dist/ConfigurationScreen.js.map +1 -1
  38. package/dist/ConsentHistory.d.ts.map +1 -1
  39. package/dist/ConsentHistory.js +17 -2
  40. package/dist/ConsentHistory.js.map +1 -1
  41. package/dist/ConsentResponseViewer.d.ts.map +1 -1
  42. package/dist/ConsentResponseViewer.js +20 -2
  43. package/dist/ConsentResponseViewer.js.map +1 -1
  44. package/dist/Constants.d.ts +5 -2
  45. package/dist/Constants.d.ts.map +1 -1
  46. package/dist/Constants.js +5 -2
  47. package/dist/Constants.js.map +1 -1
  48. package/dist/UserSecurityScreen.d.ts +45 -0
  49. package/dist/UserSecurityScreen.d.ts.map +1 -0
  50. package/dist/UserSecurityScreen.js +66 -0
  51. package/dist/UserSecurityScreen.js.map +1 -0
  52. package/dist/consentPdfTemplates.d.ts +64 -0
  53. package/dist/consentPdfTemplates.d.ts.map +1 -0
  54. package/dist/consentPdfTemplates.js +160 -0
  55. package/dist/consentPdfTemplates.js.map +1 -0
  56. package/dist/generateConsentHistoryPdf.d.ts.map +1 -1
  57. package/dist/generateConsentHistoryPdf.js +7 -55
  58. package/dist/generateConsentHistoryPdf.js.map +1 -1
  59. package/dist/generateConsentPdf.d.ts +1 -26
  60. package/dist/generateConsentPdf.d.ts.map +1 -1
  61. package/dist/generateConsentPdf.js +7 -69
  62. package/dist/generateConsentPdf.js.map +1 -1
  63. package/dist/index.d.ts +3 -0
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +3 -0
  66. package/dist/index.js.map +1 -1
  67. package/dist/orgs/MemberSecurityPanel.d.ts +34 -0
  68. package/dist/orgs/MemberSecurityPanel.d.ts.map +1 -0
  69. package/dist/orgs/MemberSecurityPanel.js +204 -0
  70. package/dist/orgs/MemberSecurityPanel.js.map +1 -0
  71. package/dist/orgs/OrgMembersScreen.d.ts.map +1 -1
  72. package/dist/orgs/OrgMembersScreen.js +33 -6
  73. package/dist/orgs/OrgMembersScreen.js.map +1 -1
  74. package/dist/orgs/adminModelEndpoints.d.ts +13 -1
  75. package/dist/orgs/adminModelEndpoints.d.ts.map +1 -1
  76. package/dist/orgs/adminModelEndpoints.js +30 -13
  77. package/dist/orgs/adminModelEndpoints.js.map +1 -1
  78. package/dist/orgs/useMemberSecurityApi.d.ts +97 -0
  79. package/dist/orgs/useMemberSecurityApi.d.ts.map +1 -0
  80. package/dist/orgs/useMemberSecurityApi.js +98 -0
  81. package/dist/orgs/useMemberSecurityApi.js.map +1 -0
  82. package/dist/pdfUtils.d.ts +15 -0
  83. package/dist/pdfUtils.d.ts.map +1 -1
  84. package/dist/pdfUtils.js +70 -0
  85. package/dist/pdfUtils.js.map +1 -1
  86. package/dist/types.d.ts +5 -1
  87. package/dist/types.d.ts.map +1 -1
  88. package/dist/types.js.map +1 -1
  89. package/dist/useAdminApi.d.ts +8 -2
  90. package/dist/useAdminApi.d.ts.map +1 -1
  91. package/dist/useAdminApi.js +11 -46
  92. package/dist/useAdminApi.js.map +1 -1
  93. package/dist/useAdminRoles.d.ts +5 -1
  94. package/dist/useAdminRoles.d.ts.map +1 -1
  95. package/dist/useAdminRoles.js +3 -3
  96. package/dist/useAdminRoles.js.map +1 -1
  97. package/dist/useAdminRpc.d.ts.map +1 -1
  98. package/dist/useAdminRpc.js +18 -3
  99. package/dist/useAdminRpc.js.map +1 -1
  100. package/dist/useConsentHistory.d.ts +7 -0
  101. package/dist/useConsentHistory.d.ts.map +1 -1
  102. package/dist/useConsentHistory.js.map +1 -1
  103. package/package.json +2 -2
  104. package/src/AdminFieldRenderer.tsx +48 -3
  105. package/src/AdminFieldRendererCore.tsx +12 -5
  106. package/src/AdminFilterDrawer.tsx +2 -2
  107. package/src/AdminHome.test.tsx +64 -1
  108. package/src/AdminHome.tsx +14 -6
  109. package/src/AdminModelForm.tsx +4 -0
  110. package/src/AdminNestedArrayField.tsx +116 -44
  111. package/src/AdminNestedObjectField.test.tsx +239 -0
  112. package/src/AdminNestedObjectField.tsx +145 -0
  113. package/src/AdminRolesField.tsx +6 -2
  114. package/src/AdminRolesList.test.tsx +25 -1
  115. package/src/AdminShell.test.tsx +15 -1
  116. package/src/AdminShell.tsx +5 -8
  117. package/src/ConfigurationScreen.tsx +6 -2
  118. package/src/ConsentHistory.test.tsx +69 -1
  119. package/src/ConsentHistory.tsx +39 -1
  120. package/src/ConsentResponseViewer.test.tsx +113 -1
  121. package/src/ConsentResponseViewer.tsx +106 -8
  122. package/src/Constants.ts +5 -2
  123. package/src/UserSecurityScreen.tsx +184 -0
  124. package/src/consentPdfTemplates.test.ts +180 -0
  125. package/src/consentPdfTemplates.ts +228 -0
  126. package/src/generateConsentHistoryPdf.ts +9 -63
  127. package/src/generateConsentPdf.ts +14 -107
  128. package/src/index.tsx +18 -0
  129. package/src/isolated/AdminNestedArrayField.isolated.tsx +93 -1
  130. package/src/isolated/UserSecurityScreen.isolated.tsx +365 -0
  131. package/src/isolated/generateConsentHistoryPdf.isolated.ts +33 -0
  132. package/src/isolated/generateConsentPdf.isolated.ts +47 -0
  133. package/src/isolated/generateConsentPdfMobile.isolated.ts +28 -0
  134. package/src/isolated/generateConsentPdfsMobile.isolated.ts +36 -0
  135. package/src/isolated/hooks.isolated.tsx +97 -0
  136. package/src/orgs/MemberSecurityPanel.test.tsx +584 -0
  137. package/src/orgs/MemberSecurityPanel.tsx +520 -0
  138. package/src/orgs/OrgManagementScreens.test.tsx +120 -1
  139. package/src/orgs/OrgMembersScreen.tsx +71 -4
  140. package/src/orgs/adminModelEndpoints.ts +56 -15
  141. package/src/orgs/useMemberSecurityApi.ts +198 -0
  142. package/src/pdfUtils.test.ts +24 -1
  143. package/src/pdfUtils.ts +93 -0
  144. package/src/types.ts +5 -1
  145. package/src/useAdminApi.ts +23 -3
  146. package/src/useAdminRoles.ts +11 -3
  147. package/src/useAdminRpc.test.tsx +115 -1
  148. package/src/useAdminRpc.ts +19 -3
  149. package/src/useConsentHistory.ts +5 -0
@@ -13,6 +13,7 @@ import {
13
13
  import React, {useCallback, useMemo, useState} from "react";
14
14
  import {AdminScreenPage} from "../AdminScreenPage";
15
15
  import type {AdminApi} from "../types";
16
+ import {MemberSecurityPanel} from "./MemberSecurityPanel";
16
17
  import {normalizeListData} from "./normalizeListData";
17
18
  import {useOrganizationsApi} from "./useOrganizationsApi";
18
19
 
@@ -42,7 +43,7 @@ const COLUMNS: DataTableColumn[] = [
42
43
  {columnType: "text", sortable: false, title: "Email", width: 240},
43
44
  {columnType: "text", sortable: false, title: "Role", width: 130},
44
45
  {columnType: "text", sortable: false, title: "Status", width: 120},
45
- {columnType: ACTION_COLUMN, sortable: false, title: "", width: 320},
46
+ {columnType: ACTION_COLUMN, sortable: false, title: "", width: 420},
46
47
  ];
47
48
 
48
49
  const mutationErrorTitle = (error: unknown, fallback: string): string => {
@@ -57,6 +58,9 @@ const mutationErrorTitle = (error: unknown, fallback: string): string => {
57
58
  return typeof title === "string" ? title : fallback;
58
59
  };
59
60
 
61
+ const memberLabel = (user: MembershipUser): string =>
62
+ user.name ?? user.email ?? user._id ?? "Unknown user";
63
+
60
64
  const membershipUser = (membership: OrgMembership): MembershipUser => {
61
65
  if (typeof membership.userId === "string") {
62
66
  return {_id: membership.userId};
@@ -74,13 +78,14 @@ export const OrgMembersScreen: React.FC<OrgMembersScreenProps> = ({
74
78
  const [email, setEmail] = useState("");
75
79
  const [attachError, setAttachError] = useState<string>();
76
80
  const [actionError, setActionError] = useState<string>();
81
+ const [securityMember, setSecurityMember] = useState<MembershipUser>();
77
82
  const {
78
83
  useMemberAttachMutation,
79
84
  useMemberRemoveMutation,
80
85
  useMemberUpdateMutation,
81
86
  useMembersQuery,
82
87
  } = useOrganizationsApi(api, basePath, organizationId);
83
- const {data, error, isLoading} = useMembersQuery(organizationId);
88
+ const {data, error, isLoading, refetch} = useMembersQuery(organizationId);
84
89
  const memberships = normalizeListData<OrgMembership>(data);
85
90
  const [attachMember, {isLoading: isAttaching}] = useMemberAttachMutation();
86
91
  const [updateMember, {isLoading: isUpdating}] = useMemberUpdateMutation();
@@ -127,6 +132,31 @@ export const OrgMembersScreen: React.FC<OrgMembersScreenProps> = ({
127
132
  [organizationId, updateMember]
128
133
  );
129
134
 
135
+ const handleReactivate = useCallback(
136
+ async (membership: OrgMembership): Promise<void> => {
137
+ try {
138
+ setActionError(undefined);
139
+ await updateMember({
140
+ body: {status: "active"},
141
+ id: organizationId,
142
+ memberId: membership._id,
143
+ }).unwrap();
144
+ } catch (mutationError) {
145
+ setActionError(mutationErrorTitle(mutationError, "Could not reactivate member."));
146
+ }
147
+ },
148
+ [organizationId, updateMember]
149
+ );
150
+
151
+ const handleSecurityClose = useCallback((): void => {
152
+ setSecurityMember(undefined);
153
+ }, []);
154
+
155
+ // A security action can change a membership (suspend-membership), so reload the list.
156
+ const handleSecurityActionComplete = useCallback((): void => {
157
+ refetch?.();
158
+ }, [refetch]);
159
+
130
160
  const handleRemove = useCallback(
131
161
  async (membership: OrgMembership): Promise<void> => {
132
162
  try {
@@ -149,8 +179,33 @@ export const OrgMembersScreen: React.FC<OrgMembersScreenProps> = ({
149
179
  }> = useCallback(
150
180
  ({cellData}) => {
151
181
  const membership = cellData.value as OrgMembership;
182
+ const user = membershipUser(membership);
183
+ const isActive = membership.status === "active";
152
184
  return (
153
185
  <Box direction="row" gap={2}>
186
+ {isActive && user._id ? (
187
+ <Button
188
+ accessibilityLabel={`Security for ${memberLabel(user)}`}
189
+ onClick={() => setSecurityMember(user)}
190
+ size="sm"
191
+ testID={`org-members-security-${user._id}`}
192
+ text="Security"
193
+ variant="outline"
194
+ />
195
+ ) : null}
196
+ {isActive ? null : (
197
+ <Button
198
+ accessibilityLabel={`Reactivate ${memberLabel(user)}`}
199
+ disabled={isUpdating}
200
+ onClick={() => {
201
+ void handleReactivate(membership);
202
+ }}
203
+ size="sm"
204
+ testID={`org-members-reactivate-${user._id ?? membership._id}`}
205
+ text="Reactivate"
206
+ variant="outline"
207
+ />
208
+ )}
154
209
  <Button
155
210
  disabled={isUpdating}
156
211
  onClick={() => {
@@ -172,7 +227,7 @@ export const OrgMembersScreen: React.FC<OrgMembersScreenProps> = ({
172
227
  </Box>
173
228
  );
174
229
  },
175
- [handleRemove, handleToggleRole, isRemoving, isUpdating]
230
+ [handleReactivate, handleRemove, handleToggleRole, isRemoving, isUpdating]
176
231
  );
177
232
  const customColumns: DataTableCustomComponentMap = useMemo(
178
233
  () => ({[ACTION_COLUMN]: ActionsCell}),
@@ -181,7 +236,7 @@ export const OrgMembersScreen: React.FC<OrgMembersScreenProps> = ({
181
236
  const rows = memberships.map((membership) => {
182
237
  const user = membershipUser(membership);
183
238
  return [
184
- {value: user.name ?? user.email ?? user._id ?? "Unknown user"},
239
+ {value: memberLabel(user)},
185
240
  {value: user.email ?? ""},
186
241
  {value: membership.roleName},
187
242
  {value: membership.status},
@@ -228,6 +283,18 @@ export const OrgMembersScreen: React.FC<OrgMembersScreenProps> = ({
228
283
  testID="org-members-table"
229
284
  />
230
285
  )}
286
+ {securityMember?._id ? (
287
+ <MemberSecurityPanel
288
+ baseURL={basePath}
289
+ key={securityMember._id}
290
+ memberLabel={memberLabel(securityMember)}
291
+ onActionComplete={handleSecurityActionComplete}
292
+ onClose={handleSecurityClose}
293
+ orgId={organizationId}
294
+ testID="org-members-security-panel"
295
+ userId={securityMember._id}
296
+ />
297
+ ) : null}
231
298
  </Box>
232
299
  <Modal
233
300
  onDismiss={handleDismiss}
@@ -20,6 +20,28 @@ export const adminOrganizationHeaders = (
20
20
  return {"X-Organization-Id": organizationId};
21
21
  };
22
22
 
23
+ /**
24
+ * A list or read argument that carries the organization it was asked under. `useAdminApi` passes
25
+ * this shape so an organization switch changes the query argument itself: RTK Query then
26
+ * subscribes to the new organization's cache entry instead of waiting on one it never requests.
27
+ * A bare argument (direct endpoint callers) uses the organization the endpoints were built with.
28
+ */
29
+ interface AdminOrgScopedArg<T> {
30
+ adminOrganizationScope: true;
31
+ args: T;
32
+ organizationId: string | undefined;
33
+ }
34
+
35
+ export const adminOrgScopedArg = <T>(
36
+ args: T,
37
+ organizationId: string | undefined
38
+ ): AdminOrgScopedArg<T> => ({adminOrganizationScope: true, args, organizationId});
39
+
40
+ const isAdminOrgScopedArg = <T>(value: unknown): value is AdminOrgScopedArg<T> =>
41
+ typeof value === "object" &&
42
+ value !== null &&
43
+ (value as {adminOrganizationScope?: unknown}).adminOrganizationScope === true;
44
+
23
45
  export const buildAdminModelEndpoints = (
24
46
  build: EndpointBuilder,
25
47
  context: AdminModelEndpointContext
@@ -31,28 +53,47 @@ export const buildAdminModelEndpoints = (
31
53
  const deleteKey = `adminDelete_${context.modelName}`;
32
54
  const bulkPatchKey = `adminBulkPatch_${context.modelName}`;
33
55
  const {headers, organizationId, routePath} = context;
56
+ // The arguments and organization one list or read call was asked with.
57
+ const unwrap = <T>(
58
+ value: T | AdminOrgScopedArg<T>
59
+ ): {args: T; headers: Record<string, string> | undefined; organizationId: string | undefined} =>
60
+ isAdminOrgScopedArg<T>(value)
61
+ ? {
62
+ args: value.args,
63
+ headers: adminOrganizationHeaders(value.organizationId),
64
+ organizationId: value.organizationId,
65
+ }
66
+ : {args: value, headers, organizationId};
34
67
 
35
68
  return {
36
69
  [listKey]: build.query({
37
70
  providesTags: [`admin_${context.modelName}`],
38
- query: (params: Record<string, unknown> | undefined) => ({
39
- ...buildAdminApiListQueryRequest(routePath, params),
40
- headers,
41
- }),
42
- serializeQueryArgs: ({endpointName, queryArgs}) =>
43
- `${endpointName}:${organizationId ?? ""}:${JSON.stringify(queryArgs ?? {})}`,
71
+ query: (
72
+ arg:
73
+ | Record<string, unknown>
74
+ | undefined
75
+ | AdminOrgScopedArg<Record<string, unknown> | undefined>
76
+ ) => {
77
+ const scoped = unwrap(arg);
78
+ return {...buildAdminApiListQueryRequest(routePath, scoped.args), headers: scoped.headers};
79
+ },
80
+ serializeQueryArgs: ({endpointName, queryArgs}) => {
81
+ const scoped = unwrap(queryArgs);
82
+ return `${endpointName}:${scoped.organizationId ?? ""}:${JSON.stringify(scoped.args ?? {})}`;
83
+ },
44
84
  }),
45
85
  [readKey]: build.query({
46
- providesTags: (_result: TagArg, _error: TagArg, id: string) => [
47
- {id, type: `admin_${context.modelName}`},
86
+ providesTags: (_result: TagArg, _error: TagArg, arg: string | AdminOrgScopedArg<string>) => [
87
+ {id: unwrap(arg).args, type: `admin_${context.modelName}`},
48
88
  ],
49
- query: (id: string) => ({
50
- headers,
51
- method: "GET",
52
- url: `${routePath}/${id}`,
53
- }),
54
- serializeQueryArgs: ({endpointName, queryArgs}) =>
55
- `${endpointName}:${organizationId ?? ""}:${String(queryArgs)}`,
89
+ query: (arg: string | AdminOrgScopedArg<string>) => {
90
+ const scoped = unwrap(arg);
91
+ return {headers: scoped.headers, method: "GET", url: `${routePath}/${scoped.args}`};
92
+ },
93
+ serializeQueryArgs: ({endpointName, queryArgs}) => {
94
+ const scoped = unwrap(queryArgs);
95
+ return `${endpointName}:${scoped.organizationId ?? ""}:${String(scoped.args)}`;
96
+ },
56
97
  }),
57
98
  [createKey]: build.mutation({
58
99
  invalidatesTags: [`admin_${context.modelName}`],
@@ -0,0 +1,198 @@
1
+ import {useCallback, useMemo, useState} from "react";
2
+ import type {AdminRpc} from "../adminRpc";
3
+ import {useAdminRpc, useAdminRpcQuery} from "../useAdminRpc";
4
+
5
+ /** One recovery action from the security summary (`GET .../security` `actions`). */
6
+ export interface MemberSecurityAction {
7
+ destructive: boolean;
8
+ id: string;
9
+ label: string;
10
+ /** HTTP method, when the server sends it. Known actions and the fallback (`POST`) cover its absence. */
11
+ method?: string;
12
+ /** Path under `.../security`, such as `/passkeys/:passkeyId`, when the server sends it. */
13
+ path?: string;
14
+ }
15
+
16
+ /** The body of `GET /users/:id/security` and `GET /orgs/:orgId/members/:userId/security`. */
17
+ export interface MemberSecuritySummary {
18
+ actions: MemberSecurityAction[];
19
+ betterAuthLinked: boolean;
20
+ disabled: boolean;
21
+ emailVerified: boolean;
22
+ lastSignIn: {at: string | null; method: string | null};
23
+ legacyPassword: boolean;
24
+ passkeys: {count: number; items: {createdAt: string | null; id: string; name: string | null}[]};
25
+ password: boolean;
26
+ providers: {linkedAt: string | null; providerId: string}[];
27
+ sessions: {active: number};
28
+ twoFactor: {backupCodesRemaining: number | null; enabled: boolean};
29
+ userId: string;
30
+ }
31
+
32
+ /** What an action route answers inside `{data}`: the action id, whether it changed anything, and extras. */
33
+ export interface MemberSecurityActionResult {
34
+ [key: string]: unknown;
35
+ action: string;
36
+ changed: boolean;
37
+ }
38
+
39
+ export interface MemberSecurityRequest {
40
+ method: string;
41
+ path: string;
42
+ }
43
+
44
+ /** Method and path of the built-in actions, for servers whose summary does not carry them. */
45
+ const KNOWN_ACTION_ROUTES: Record<string, MemberSecurityRequest> = {
46
+ disable: {method: "POST", path: "/disable"},
47
+ enable: {method: "POST", path: "/enable"},
48
+ "issue-sign-in-link": {method: "POST", path: "/issue-sign-in-link"},
49
+ "remove-passkey": {method: "DELETE", path: "/passkeys/:passkeyId"},
50
+ "reset-two-factor": {method: "POST", path: "/reset-two-factor"},
51
+ "revoke-sessions": {method: "POST", path: "/revoke-sessions"},
52
+ "send-password-reset": {method: "POST", path: "/send-password-reset"},
53
+ "suspend-membership": {method: "POST", path: "/suspend-membership"},
54
+ "unlink-provider": {method: "DELETE", path: "/accounts/:providerId"},
55
+ };
56
+
57
+ /**
58
+ * The security base path for a user: `{baseURL}/{orgId}/members/{userId}/security` under an
59
+ * organization (`baseURL` defaults to `/orgs`), otherwise `{baseURL}/{userId}/security`
60
+ * (`baseURL` defaults to `/users`).
61
+ */
62
+ export const memberSecurityPath = ({
63
+ baseURL,
64
+ orgId,
65
+ userId,
66
+ }: {
67
+ baseURL?: string;
68
+ orgId?: string;
69
+ userId: string;
70
+ }): string => {
71
+ const user = encodeURIComponent(userId);
72
+ if (orgId) {
73
+ return `${baseURL ?? "/orgs"}/${encodeURIComponent(orgId)}/members/${user}/security`;
74
+ }
75
+ return `${baseURL ?? "/users"}/${user}/security`;
76
+ };
77
+
78
+ /**
79
+ * Method and path for an action: the server's own `method`/`path` when sent, else the built-in
80
+ * route, else `POST /{id}` (the convention every parameterless action follows).
81
+ */
82
+ const resolveSecurityActionRoute = (action: MemberSecurityAction): MemberSecurityRequest => {
83
+ const known = KNOWN_ACTION_ROUTES[action.id];
84
+ return {
85
+ method: (action.method ?? known?.method ?? "POST").toUpperCase(),
86
+ path: action.path ?? known?.path ?? `/${action.id}`,
87
+ };
88
+ };
89
+
90
+ /** Path params (`:passkeyId`) an action's path needs. */
91
+ export const securityActionParams = (action: MemberSecurityAction): string[] => {
92
+ const {path} = resolveSecurityActionRoute(action);
93
+ return Array.from(path.matchAll(/:([A-Za-z0-9_]+)/g), (match) => match[1] ?? "");
94
+ };
95
+
96
+ /** Fills `:param` segments from `params`; throws when one is missing so no request hits a literal `:param`. */
97
+ export const resolveSecurityActionRequest = ({
98
+ action,
99
+ params = {},
100
+ }: {
101
+ action: MemberSecurityAction;
102
+ params?: Record<string, string>;
103
+ }): MemberSecurityRequest => {
104
+ const route = resolveSecurityActionRoute(action);
105
+ const path = route.path.replace(/:([A-Za-z0-9_]+)/g, (_segment, name: string) => {
106
+ const value = params[name];
107
+ if (!value) {
108
+ throw new Error(`${action.id} needs ${name}`);
109
+ }
110
+ return encodeURIComponent(value);
111
+ });
112
+ return {method: route.method, path};
113
+ };
114
+
115
+ const unwrapData = <T>(body: unknown): T => {
116
+ if (body && typeof body === "object" && "data" in body) {
117
+ return (body as {data: T}).data;
118
+ }
119
+ return body as T;
120
+ };
121
+
122
+ export interface UseMemberSecurityApiArgs {
123
+ /** Route prefix: defaults to `/orgs` with `orgId`, `/users` without. */
124
+ baseURL?: string;
125
+ /** Organization id for the org-admin routes. Omit for the platform `/users/:id/security` routes. */
126
+ orgId?: string;
127
+ userId: string;
128
+ }
129
+
130
+ export interface UseMemberSecurityApiResult {
131
+ error: unknown;
132
+ isFetching: boolean;
133
+ isLoading: boolean;
134
+ isRunning: boolean;
135
+ refetch: () => void;
136
+ runAction: (args: {
137
+ action: MemberSecurityAction;
138
+ params?: Record<string, string>;
139
+ }) => Promise<MemberSecurityActionResult>;
140
+ securityPath: string;
141
+ summary: MemberSecuritySummary | undefined;
142
+ }
143
+
144
+ /**
145
+ * Reads a user's security summary and runs its recovery actions through the host-bound
146
+ * `adminRequest` (AdminProvider `credentials` / `getAuthHeaders`), against either the org-admin
147
+ * prefix or the platform prefix.
148
+ */
149
+ export const useMemberSecurityApi = ({
150
+ baseURL,
151
+ orgId,
152
+ userId,
153
+ }: UseMemberSecurityApiArgs): UseMemberSecurityApiResult => {
154
+ const rpc: AdminRpc | undefined = useAdminRpc();
155
+ const securityPath = useMemo(
156
+ () => memberSecurityPath({baseURL, orgId, userId}),
157
+ [baseURL, orgId, userId]
158
+ );
159
+ const query = useAdminRpcQuery<unknown>({rpc, skip: !userId, url: securityPath});
160
+ const [isRunning, setIsRunning] = useState(false);
161
+ const summary =
162
+ query.data === undefined ? undefined : unwrapData<MemberSecuritySummary>(query.data);
163
+ const error = rpc ? query.error : new Error("Admin RPC client is unavailable");
164
+
165
+ const runAction = useCallback(
166
+ async ({
167
+ action,
168
+ params,
169
+ }: {
170
+ action: MemberSecurityAction;
171
+ params?: Record<string, string>;
172
+ }): Promise<MemberSecurityActionResult> => {
173
+ if (!rpc) {
174
+ throw new Error("Admin RPC client is unavailable");
175
+ }
176
+ const request = resolveSecurityActionRequest({action, params});
177
+ setIsRunning(true);
178
+ try {
179
+ const body = await rpc({method: request.method, url: `${securityPath}${request.path}`});
180
+ return unwrapData<MemberSecurityActionResult>(body) ?? {action: action.id, changed: true};
181
+ } finally {
182
+ setIsRunning(false);
183
+ }
184
+ },
185
+ [rpc, securityPath]
186
+ );
187
+
188
+ return {
189
+ error,
190
+ isFetching: query.isFetching,
191
+ isLoading: query.isLoading,
192
+ isRunning,
193
+ refetch: query.refetch,
194
+ runAction,
195
+ securityPath,
196
+ summary,
197
+ };
198
+ };
@@ -1,7 +1,7 @@
1
1
  import {describe, expect, it, mock} from "bun:test";
2
2
  import {DateTime} from "luxon";
3
3
 
4
- import {ensureSpace, formatDate} from "./pdfUtils";
4
+ import {ensureSpace, formatDate, provisionalPdfSignature, provisionalSignerName} from "./pdfUtils";
5
5
 
6
6
  describe("formatDate", () => {
7
7
  it("returns an empty string for missing values", () => {
@@ -35,3 +35,26 @@ describe("ensureSpace", () => {
35
35
  expect(addPage).not.toHaveBeenCalled();
36
36
  });
37
37
  });
38
+
39
+ describe("provisionalSignerName", () => {
40
+ it("uses the name, then the email, then Staff", () => {
41
+ expect(provisionalSignerName({email: "dana@example.com", name: "Dana"})).toBe("Dana");
42
+ expect(provisionalSignerName({email: "dana@example.com"})).toBe("dana@example.com");
43
+ expect(provisionalSignerName("staff-1")).toBe("Staff");
44
+ expect(provisionalSignerName(null)).toBe("Staff");
45
+ });
46
+ });
47
+
48
+ describe("provisionalPdfSignature", () => {
49
+ it("returns undefined without a section", () => {
50
+ expect(provisionalPdfSignature(undefined)).toBeUndefined();
51
+ });
52
+
53
+ it("keeps the section and defaults a missing signedAt to an empty string", () => {
54
+ expect(provisionalPdfSignature({note: "Phone", signedByName: "Dana"})).toEqual({
55
+ note: "Phone",
56
+ signedAt: "",
57
+ signedByName: "Dana",
58
+ });
59
+ });
60
+ });
package/src/pdfUtils.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type {PdfTemplateData} from "@terreno/ui";
1
2
  import type {jsPDF} from "jspdf";
2
3
  import {DateTime} from "luxon";
3
4
 
@@ -26,3 +27,95 @@ export const ensureSpace = (doc: jsPDF, y: number, needed: number): number => {
26
27
  }
27
28
  return y;
28
29
  };
30
+
31
+ /** A provisional signature as printed. `note` and `signerIp` belong on admin printouts only. */
32
+ export interface PdfProvisionalSignatureSection {
33
+ signedAt?: string;
34
+ signedByName: string;
35
+ note?: string;
36
+ signerIp?: string;
37
+ voidedAt?: string;
38
+ }
39
+
40
+ /** The display name of a populated provisional signer, falling back to email, then "Staff". */
41
+ export const provisionalSignerName = (signer: unknown): string => {
42
+ if (signer && typeof signer === "object") {
43
+ const {email, name} = signer as {email?: string; name?: string};
44
+ return name || email || "Staff";
45
+ }
46
+ return "Staff";
47
+ };
48
+
49
+ /** Draw the "Provisional signature" section on a jsPDF page and return the next y. */
50
+ export const drawProvisionalSignature = (
51
+ doc: jsPDF,
52
+ startY: number,
53
+ signature: PdfProvisionalSignatureSection
54
+ ): number => {
55
+ let y = ensureSpace(doc, startY, 20);
56
+ doc.setFontSize(12);
57
+ doc.setFont("helvetica", "bold");
58
+ doc.setTextColor(0, 0, 0);
59
+ doc.text("Provisional signature", MARGIN_LEFT, y);
60
+ y += 8;
61
+
62
+ const fields: Array<[string, string]> = [["Signed by:", signature.signedByName]];
63
+ if (signature.signedAt) {
64
+ fields.push(["Signed at:", formatDate(signature.signedAt)]);
65
+ }
66
+ if (signature.signerIp) {
67
+ fields.push(["Signer IP:", signature.signerIp]);
68
+ }
69
+ for (const [label, value] of fields) {
70
+ y = ensureSpace(doc, y, 8);
71
+ doc.setFontSize(9);
72
+ doc.setFont("helvetica", "bold");
73
+ doc.setTextColor(100, 100, 100);
74
+ doc.text(label, MARGIN_LEFT, y);
75
+ doc.setFont("helvetica", "normal");
76
+ doc.setTextColor(0, 0, 0);
77
+ doc.setFontSize(10);
78
+ doc.text(value, MARGIN_LEFT + 45, y);
79
+ y += 6;
80
+ }
81
+
82
+ if (signature.note) {
83
+ y = ensureSpace(doc, y, 8);
84
+ doc.setFontSize(9);
85
+ doc.setFont("helvetica", "bold");
86
+ doc.setTextColor(100, 100, 100);
87
+ doc.text("Note:", MARGIN_LEFT, y);
88
+ doc.setFont("helvetica", "normal");
89
+ doc.setTextColor(0, 0, 0);
90
+ doc.setFontSize(10);
91
+ const lines = doc.splitTextToSize(signature.note, CONTENT_WIDTH - 45);
92
+ for (const line of lines) {
93
+ y = ensureSpace(doc, y, 5);
94
+ doc.text(line, MARGIN_LEFT + 45, y);
95
+ y += 5;
96
+ }
97
+ y += 1;
98
+ }
99
+
100
+ if (signature.voidedAt) {
101
+ y = ensureSpace(doc, y, 8);
102
+ doc.setFontSize(10);
103
+ doc.setFont("helvetica", "bold");
104
+ doc.setTextColor(160, 0, 0);
105
+ doc.text(`Voided ${formatDate(signature.voidedAt)}`, MARGIN_LEFT, y);
106
+ doc.setTextColor(0, 0, 0);
107
+ y += 6;
108
+ }
109
+
110
+ return y + 4;
111
+ };
112
+
113
+ /** The `@terreno/ui` template shape for a provisional section; `signedAt` falls back to "". */
114
+ export const provisionalPdfSignature = (
115
+ section: PdfProvisionalSignatureSection | undefined
116
+ ): PdfTemplateData["provisionalSignature"] => {
117
+ if (!section) {
118
+ return undefined;
119
+ }
120
+ return {...section, signedAt: section.signedAt ?? ""};
121
+ };
package/src/types.ts CHANGED
@@ -56,7 +56,11 @@ export interface AdminFieldConfig {
56
56
  ref?: string;
57
57
  searchable?: boolean;
58
58
  widget?: string;
59
- /** For array fields of sub-documents: metadata about each item's sub-fields */
59
+ /**
60
+ * Subfield metadata. For array fields of sub-documents, each item's subfields; for nested
61
+ * (non-array) `object` fields, the object's own subfields, rendered as a grouped fieldset.
62
+ * Absent for Mixed and Map fields, which use the JSON editor.
63
+ */
60
64
  items?: Record<string, AdminFieldConfig>;
61
65
  /** For array fields of primitives: the item type (string/number/boolean/objectid) */
62
66
  itemType?: string;
@@ -1,6 +1,10 @@
1
1
  import {useMemo} from "react";
2
2
  import {asDynamicHookApi} from "./dynamicHookApi";
3
- import {adminOrganizationHeaders, buildAdminModelEndpoints} from "./orgs/adminModelEndpoints";
3
+ import {
4
+ adminOrganizationHeaders,
5
+ adminOrgScopedArg,
6
+ buildAdminModelEndpoints,
7
+ } from "./orgs/adminModelEndpoints";
4
8
  import {useOptionalOrgContext} from "./orgs/useOrgContext";
5
9
  import type {AdminApi, EndpointBuilder} from "./types";
6
10
 
@@ -47,6 +51,12 @@ import type {AdminApi, EndpointBuilder} from "./types";
47
51
  * @see useAdminConfig for fetching model configurations
48
52
  * @see AdminModelTable for usage in the table view
49
53
  */
54
+ /** RTK Query hook options (`skip`, `pollingInterval`, ...), passed through as given. */
55
+ interface AdminQueryHookOptions {
56
+ skip?: boolean;
57
+ [option: string]: unknown;
58
+ }
59
+
50
60
  export const useAdminApi = (api: AdminApi, routePath: string, modelName: string) => {
51
61
  const organizationId = useOptionalOrgContext()?.organizationId;
52
62
  const headers = useMemo(() => adminOrganizationHeaders(organizationId), [organizationId]);
@@ -68,12 +78,22 @@ export const useAdminApi = (api: AdminApi, routePath: string, modelName: string)
68
78
  const bulkPatchKey = `adminBulkPatch_${modelName}`;
69
79
 
70
80
  const enhanced = asDynamicHookApi(enhancedApi);
81
+ const useRawListQuery = enhanced[`use${capitalize(listKey)}Query`];
82
+ const useRawReadQuery = enhanced[`use${capitalize(readKey)}Query`];
83
+ // The organization rides in the argument, so switching it (such as the org switcher settling
84
+ // on a default after a read started) changes the argument and RTK Query fetches the new
85
+ // organization's entry. Kept in the closure only, the cache key moved while the subscription
86
+ // stayed on the old entry and the screen waited on a request that never went out.
87
+ const useListQuery = (params?: Record<string, unknown>, options?: AdminQueryHookOptions) =>
88
+ useRawListQuery(adminOrgScopedArg(params, organizationId), options);
89
+ const useReadQuery = (id: string, options?: AdminQueryHookOptions) =>
90
+ useRawReadQuery(adminOrgScopedArg(id, organizationId), options);
71
91
  return {
72
92
  useBulkPatchMutation: enhanced[`use${capitalize(bulkPatchKey)}Mutation`],
73
93
  useCreateMutation: enhanced[`use${capitalize(createKey)}Mutation`],
74
94
  useDeleteMutation: enhanced[`use${capitalize(deleteKey)}Mutation`],
75
- useListQuery: enhanced[`use${capitalize(listKey)}Query`],
76
- useReadQuery: enhanced[`use${capitalize(readKey)}Query`],
95
+ useListQuery,
96
+ useReadQuery,
77
97
  useUpdateMutation: enhanced[`use${capitalize(updateKey)}Mutation`],
78
98
  };
79
99
  };
@@ -47,6 +47,11 @@ interface StatementsQueryResult {
47
47
  */
48
48
  export type RolesQueryData = RbacRoleRow[] | {data?: RbacRoleRow[]} | undefined;
49
49
 
50
+ /** Options for `useListRolesQuery`. `skip` leaves `/rbac/roles` unrequested. */
51
+ interface ListRolesQueryOptions {
52
+ skip?: boolean;
53
+ }
54
+
50
55
  /** @internal */
51
56
  export interface RolesQueryResult {
52
57
  data: RolesQueryData;
@@ -148,9 +153,10 @@ export const useAdminRoles = (api: AdminApi, apiBase: string) => {
148
153
  meta,
149
154
  ] as CreateRoleMutation;
150
155
  },
151
- useListRolesQuery: () =>
156
+ useListRolesQuery: (_arg?: undefined, options?: ListRolesQueryOptions) =>
152
157
  useAdminRpcQuery<RolesQueryData>({
153
158
  rpc,
159
+ skip: options?.skip,
154
160
  url: `${rbacBase}/rbac/roles`,
155
161
  }),
156
162
  useListStatementsQuery: () =>
@@ -176,8 +182,10 @@ export const useAdminRoles = (api: AdminApi, apiBase: string) => {
176
182
  return {
177
183
  useCreateRoleMutation: (enhanced?.useAdminCreateRbacRoleMutation ??
178
184
  EMPTY_CREATE_MUTATION_HOOK) as () => CreateRoleMutation,
179
- useListRolesQuery: (enhanced?.useAdminListRbacRolesQuery ??
180
- EMPTY_ROLES_HOOK) as () => RolesQueryResult,
185
+ useListRolesQuery: (enhanced?.useAdminListRbacRolesQuery ?? EMPTY_ROLES_HOOK) as (
186
+ arg?: undefined,
187
+ options?: ListRolesQueryOptions
188
+ ) => RolesQueryResult,
181
189
  useListStatementsQuery: (enhanced?.useAdminListRbacStatementsQuery ??
182
190
  EMPTY_STATEMENTS_HOOK) as () => StatementsQueryResult,
183
191
  useUpdateRoleMutation: (enhanced?.useAdminUpdateRbacRoleMutation ??