@proteinjs/user-ui 1.8.1 → 1.9.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.
@@ -0,0 +1,30 @@
1
+ import React from 'react';
2
+ import { Chip, Stack, Typography } from '@mui/material';
3
+ import { RecordFormFieldProps } from '@proteinjs/db-ui';
4
+ import { User, UserStatus } from '@proteinjs/user';
5
+
6
+ /**
7
+ * The `user.status` slot on the user record form: the account's standing, read-only. Its only
8
+ * writer is the SetUserStatus service (audited per change); an editable box here would take edits
9
+ * the form's save silently drops. A null status (rows predating the column) reads as active —
10
+ * the same reading every gate applies.
11
+ */
12
+ export function UserStatusField({ value, label }: RecordFormFieldProps<User, UserStatus | null | undefined>) {
13
+ const status: UserStatus = value ?? 'active';
14
+
15
+ return (
16
+ <Stack spacing={0.5} data-user-status>
17
+ <Typography variant='caption' color='text.secondary'>
18
+ {label}
19
+ </Typography>
20
+ <Stack direction='row' sx={{ alignItems: 'center', minHeight: 32 }}>
21
+ <Chip
22
+ label={status === 'deactivated' ? 'Deactivated' : 'Active'}
23
+ variant='outlined'
24
+ color={status === 'deactivated' ? 'default' : 'success'}
25
+ size='small'
26
+ />
27
+ </Stack>
28
+ </Stack>
29
+ );
30
+ }
@@ -0,0 +1,242 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ * @jest-environment-options {"customExportConditions": ["node", "node-addons"]}
4
+ *
5
+ * The user record form presents the two service-owned columns instead of hiding or faking them:
6
+ * - `roles` (an ArrayColumn, hidden by the default form — the founder opened the user form to
7
+ * change roles and found no roles at all) renders as chips of the held roles; a holder of the
8
+ * 'roles' permission also gets a grant control fed by the roles catalog and a revoke on each
9
+ * chip. Both write through `RolesService` — the one audited write path — and then reload the
10
+ * record, so the chips show what is stored, not what was asked;
11
+ * - `status` renders read-only (its only writer is SetUserStatus) rather than as an editable box
12
+ * the form's save would silently drop.
13
+ *
14
+ * `UserAuth` reads from a static repo; stubbing it directly is how the invite customization test
15
+ * and the server-side authz tests do it.
16
+ */
17
+ import React from 'react';
18
+ import { createRoot, Root } from 'react-dom/client';
19
+ import { act } from 'react-dom/test-utils';
20
+ import { Column } from '@proteinjs/db';
21
+ import { RecordFormFieldProps } from '@proteinjs/db-ui';
22
+ import { RoleCatalogEntry, RolesCatalog, tables, User, UserAuth } from '@proteinjs/user';
23
+ import { UserRecordFormCustomization } from '../src/form/UserRecordFormCustomization';
24
+
25
+ declare global {
26
+ // eslint-disable-next-line no-var
27
+ var IS_REACT_ACT_ENVIRONMENT: boolean;
28
+ }
29
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
30
+
31
+ /** The stored user row the (stubbed) Roles service writes and `reload` reads back. */
32
+ let stored: User;
33
+
34
+ const rolesService = {
35
+ grantRole: jest.fn(async (userId: string, role: string) => {
36
+ stored = { ...stored, roles: [...(stored.roles ?? []), role] };
37
+ }),
38
+ revokeRole: jest.fn(async (userId: string, role: string) => {
39
+ stored = { ...stored, roles: (stored.roles ?? []).filter((held) => held !== role) };
40
+ }),
41
+ };
42
+
43
+ jest.mock('@proteinjs/user', () => ({
44
+ ...jest.requireActual('@proteinjs/user'),
45
+ getRolesService: () => rolesService,
46
+ }));
47
+
48
+ type UserAuthInternals = {
49
+ userRepo?: { getUser: () => { email: string; roles: string[] } };
50
+ permissionRolesMapping?: { getRoles: (permission: string) => string[] | undefined };
51
+ };
52
+
53
+ const setCallerRoles = (roles: string[]) => {
54
+ (UserAuth as unknown as UserAuthInternals).userRepo = {
55
+ getUser: () => ({ email: 'caller@n3xa.io', roles }),
56
+ };
57
+ };
58
+
59
+ const setMapping = (mapping: { [permission: string]: string[] }) => {
60
+ (UserAuth as unknown as UserAuthInternals).permissionRolesMapping = {
61
+ getRoles: (permission: string) => mapping[permission],
62
+ };
63
+ };
64
+
65
+ const catalog: RoleCatalogEntry[] = [
66
+ { role: 'admin', description: 'Break-glass superuser.', breakGlass: true },
67
+ { role: 'ops', description: 'Runs the product: tickets, issues, cost.' },
68
+ { role: 'dev', description: 'Engineering surfaces.' },
69
+ ];
70
+
71
+ const userRecord = (overrides: Partial<User> = {}): User =>
72
+ ({
73
+ id: 'user-1',
74
+ name: 'Ada',
75
+ email: 'ada@n3xa.io',
76
+ roles: ['ops'],
77
+ status: 'active',
78
+ ...overrides,
79
+ }) as User;
80
+
81
+ describe('User record form customization', () => {
82
+ let container: HTMLDivElement;
83
+ let root: Root;
84
+ const customization = new UserRecordFormCustomization();
85
+
86
+ beforeEach(() => {
87
+ jest.clearAllMocks();
88
+ jest.spyOn(RolesCatalog, 'getEntries').mockReturnValue(catalog);
89
+ setCallerRoles(['admin']);
90
+ stored = userRecord();
91
+ container = document.createElement('div');
92
+ document.body.appendChild(container);
93
+ root = createRoot(container);
94
+ });
95
+
96
+ afterEach(async () => {
97
+ await act(async () => root.unmount());
98
+ container.remove();
99
+ (UserAuth as unknown as UserAuthInternals).userRepo = undefined;
100
+ (UserAuth as unknown as UserAuthInternals).permissionRolesMapping = undefined;
101
+ jest.restoreAllMocks();
102
+ });
103
+
104
+ /**
105
+ * Renders the field the way RecordForm's slot does: value from the record; reload re-reads the
106
+ * stored row and re-renders. Reload runs inside the click's act scope, so it renders bare —
107
+ * a nested act would overlap the outer one.
108
+ */
109
+ const renderField = async (fieldName: 'roles' | 'status') => {
110
+ const Renderer = customization.getFieldRenderer(fieldName, stored);
111
+ if (!Renderer) {
112
+ throw new Error(`No renderer for ${fieldName}`);
113
+ }
114
+
115
+ const element = () => {
116
+ const props: RecordFormFieldProps<User> = {
117
+ table: tables.User,
118
+ column: (tables.User.columns as any)[fieldName] as Column<User, any>,
119
+ fieldName,
120
+ label: fieldName === 'roles' ? 'Roles' : 'Status',
121
+ record: stored,
122
+ value: (stored as any)[fieldName],
123
+ reload: async () => {
124
+ root.render(element());
125
+ },
126
+ };
127
+ return <Renderer {...props} />;
128
+ };
129
+ await act(async () => {
130
+ root.render(element());
131
+ });
132
+ };
133
+
134
+ const chips = () => Array.from(document.querySelectorAll('[data-role-chip]')).map((chip) => chip.textContent);
135
+ const grantControl = () => document.querySelector('[data-grant-role]');
136
+ const revokeButtons = () => Array.from(document.querySelectorAll('[data-role-chip] [data-testid="CancelIcon"]'));
137
+
138
+ const click = async (element: Element) => {
139
+ await act(async () => {
140
+ element.dispatchEvent(new MouseEvent('click', { bubbles: true }));
141
+ });
142
+ await act(async () => {
143
+ await Promise.resolve();
144
+ });
145
+ };
146
+
147
+ it('renders the held roles as chips', async () => {
148
+ stored = userRecord({ roles: ['ops', 'dev'] });
149
+ await renderField('roles');
150
+
151
+ expect(chips()).toEqual(['ops', 'dev']);
152
+ });
153
+
154
+ it('offers the grant control and revoke only to a holder of the roles permission', async () => {
155
+ await renderField('roles');
156
+ expect(grantControl()).not.toBeNull();
157
+ expect(revokeButtons()).toHaveLength(1);
158
+
159
+ setCallerRoles([]);
160
+ await renderField('roles');
161
+ expect(chips()).toEqual(['ops']);
162
+ expect(grantControl()).toBeNull();
163
+ expect(revokeButtons()).toHaveLength(0);
164
+
165
+ setCallerRoles(['support']);
166
+ setMapping({ roles: ['support'] });
167
+ await renderField('roles');
168
+ expect(grantControl()).not.toBeNull();
169
+ });
170
+
171
+ it('grants through the Roles service and shows the stored roles afterwards', async () => {
172
+ await renderField('roles');
173
+
174
+ await click(grantControl()!);
175
+ // The pick-list is the catalog minus what is already held — and never the break-glass role
176
+ const options = Array.from(document.querySelectorAll('[role="menuitem"]'));
177
+ expect(options.map((item) => item.querySelector('.MuiListItemText-primary')?.textContent)).toEqual(['dev']);
178
+ expect(options[0].textContent).toContain('Engineering surfaces.');
179
+ await click(options[0]);
180
+
181
+ expect(rolesService.grantRole).toHaveBeenCalledWith('user-1', 'dev');
182
+ expect(stored.roles).toEqual(['ops', 'dev']);
183
+ expect(chips()).toEqual(['ops', 'dev']);
184
+ });
185
+
186
+ it('revokes through the Roles service from the chip', async () => {
187
+ await renderField('roles');
188
+
189
+ await click(revokeButtons()[0]);
190
+
191
+ expect(rolesService.revokeRole).toHaveBeenCalledWith('user-1', 'ops');
192
+ expect(stored.roles).toEqual([]);
193
+ expect(chips()).toEqual([]);
194
+ });
195
+
196
+ it('shows a machine account read-only: its roles are declared in code', async () => {
197
+ stored = userRecord({ isLoadedFromSource: true });
198
+ await renderField('roles');
199
+
200
+ expect(chips()).toEqual(['ops']);
201
+ expect(grantControl()).toBeNull();
202
+ expect(revokeButtons()).toHaveLength(0);
203
+ expect(document.body.textContent).toContain('machine account');
204
+ });
205
+
206
+ it('renders status read-only (null reads as active), and leaves every other field to the form', async () => {
207
+ await renderField('status');
208
+ expect(document.body.textContent).toContain('Active');
209
+ expect(document.querySelector('input')).toBeNull();
210
+
211
+ stored = userRecord({ status: 'deactivated' });
212
+ await renderField('status');
213
+ expect(document.body.textContent).toContain('Deactivated');
214
+
215
+ stored = userRecord({ status: null });
216
+ await renderField('status');
217
+ expect(document.body.textContent).toContain('Active');
218
+
219
+ for (const fieldName of ['name', 'email', 'emailVerified', 'invitedBy']) {
220
+ expect(customization.getFieldRenderer(fieldName, stored)).toBeUndefined();
221
+ }
222
+ });
223
+
224
+ it('gives roles its own full-width row after the identity row', () => {
225
+ const defaultLayout = [
226
+ ['name', 'email'],
227
+ ['password', 'emailVerified'],
228
+ ['roles', 'invitedBy'],
229
+ ['status', 'created'],
230
+ ['updated'],
231
+ ];
232
+ expect(customization.getFieldLayout(userRecord(), defaultLayout)).toEqual([
233
+ ['name', 'email'],
234
+ ['roles'],
235
+ ['password', 'emailVerified'],
236
+ ['invitedBy', 'status'],
237
+ ['created', 'updated'],
238
+ ]);
239
+ // The new-record form has no roles to show; its layout is untouched
240
+ expect(customization.getFieldLayout(undefined, ['name', 'email'])).toEqual(['name', 'email']);
241
+ });
242
+ });