Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 60 additions & 1 deletion apps/web/src/routes/_app/admin/users/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import '@/services/i18n';
const mocks = vi.hoisted(() => ({
archiveUser: vi.fn(),
currentUser: null as null | { username: string },
groups: [] as { id: string; name: string }[],
groupsQueryOptions: vi.fn(() => ({ queryKey: ['groups'] })),
navigate: vi.fn(),
unarchiveUser: vi.fn(),
users: [] as User[],
Expand All @@ -28,6 +30,10 @@ vi.mock('@/hooks/useUsersQuery', () => ({
usersQueryOptions: mocks.usersQueryOptions,
useUsersQuery: () => ({ data: mocks.users })
}));
vi.mock('@/hooks/useGroupsQuery', () => ({
groupsQueryOptions: mocks.groupsQueryOptions,
useGroupsQuery: () => ({ data: mocks.groups })
}));
vi.mock('@/hooks/useArchiveUserMutation', () => ({ useArchiveUserMutation: () => ({ mutate: mocks.archiveUser }) }));
vi.mock('@/hooks/useUnarchiveUserMutation', () => ({
useUnarchiveUserMutation: () => ({ mutate: mocks.unarchiveUser })
Expand Down Expand Up @@ -95,6 +101,11 @@ describe('Route', () => {
vi.clearAllMocks();
mocks.archiveUser.mockReset();
mocks.currentUser = null;
mocks.groups = [
{ id: 'group-a', name: 'Gamma' },
{ id: 'group-b', name: 'Alpha' },
{ id: 'group-c', name: 'Beta' }
];
});

afterEach(cleanup);
Expand All @@ -117,6 +128,54 @@ describe('Route', () => {
expect(ensureQueryData).toHaveBeenCalledWith({ queryKey: ['users'] });
});

it('should prefetch the groups in the loader, so group names render without a waterfall', async () => {
const queryClient = new QueryClient();
const ensureQueryData = vi.spyOn(queryClient, 'ensureQueryData').mockResolvedValue([]);
await runLoader(queryClient);
expect(ensureQueryData).toHaveBeenCalledWith({ queryKey: ['groups'] });
});

it('should show none for a user who belongs to no group', () => {
renderTable([userFixture({ groupIds: [] })]);
expect(screen.getByTestId('user-groups').textContent).toBe('None');
});

it('should show the name of the only group a user belongs to', () => {
renderTable([userFixture({ groupIds: ['group-c'] })]);
expect(screen.getByTestId('user-groups').textContent).toBe('Beta');
});

it('should leave out a group missing from the groups list, rather than showing its raw id', () => {
renderTable([userFixture({ groupIds: ['group-unknown', 'group-c'] })]);
expect(screen.getByTestId('user-groups').textContent).toBe('Beta');
});

it('should show the first group and a count of the rest, so a long membership fits the cell', () => {
renderTable([userFixture({ groupIds: ['group-c', 'group-a', 'group-b'] })]);
expect(screen.getByTestId('user-groups').textContent).toBe('Alpha +2');
});

it('should keep the full group list hidden until the cell is hovered', () => {
renderTable([userFixture({ groupIds: ['group-c', 'group-a', 'group-b'] })]);
expect(screen.queryByTestId('user-groups-list')).toBeNull();
});

it('should list every group a user belongs to when the cell is hovered', () => {
renderTable([userFixture({ groupIds: ['group-c', 'group-a', 'group-b'] })]);
fireEvent.focus(screen.getByTestId('user-groups'));
const items = within(screen.getAllByTestId('user-groups-list')[0]!).getAllByRole('listitem', { hidden: true });
expect(items.map((item) => item.textContent)).toEqual(['Alpha', 'Beta', 'Gamma']);
});

it('should sort users by their group names', () => {
renderTable([
userFixture({ groupIds: ['group-a'], id: 'b', username: 'bob' }),
userFixture({ groupIds: ['group-c'], id: 'a', username: 'alice' })
]);
fireEvent.click(header('Groups'));
expect(usernames()).toEqual(['alice', 'bob']);
});

it('should mark a user who is not archived as active', () => {
renderTable([userFixture()]);
expect(screen.getByTestId('user-status-active').textContent).toBe('Active');
Expand All @@ -140,7 +199,7 @@ describe('Route', () => {
});

it('should label a user without a base permission level as having none', () => {
renderTable([userFixture({ basePermissionLevel: null })]);
renderTable([userFixture({ basePermissionLevel: null, groupIds: ['group-a'] })]);
expect(within(rows()[0]!).getByText('None')).toBeTruthy();
});

Expand Down
48 changes: 46 additions & 2 deletions apps/web/src/routes/_app/admin/users/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useState } from 'react';

import { snakeToCamelCase, toBasicISOString } from '@douglasneuroinformatics/libjs';
import { Button, DataTable, Dialog, Heading } from '@douglasneuroinformatics/libui/components';
import { Button, DataTable, Dialog, Heading, Tooltip } from '@douglasneuroinformatics/libui/components';
import { useTheme, useTranslation } from '@douglasneuroinformatics/libui/hooks';
import type { User } from '@opendatacapture/schemas/user';
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router';
Expand All @@ -10,6 +10,7 @@ import { ColorTagCell } from '@/components/ColorTagCell';
import { PageHeader } from '@/components/PageHeader';
import { SortableHeader } from '@/components/SortableHeader';
import { useArchiveUserMutation } from '@/hooks/useArchiveUserMutation';
import { groupsQueryOptions, useGroupsQuery } from '@/hooks/useGroupsQuery';
import { useUnarchiveUserMutation } from '@/hooks/useUnarchiveUserMutation';
import { usersQueryOptions, useUsersQuery } from '@/hooks/useUsersQuery';
import { useAppStore } from '@/store';
Expand All @@ -23,6 +24,7 @@ const RouteComponent = () => {
const [theme] = useTheme();
const navigate = useNavigate();
const usersQuery = useUsersQuery();
const groupsQuery = useGroupsQuery();
const archiveUserMutation = useArchiveUserMutation();
const unarchiveUserMutation = useUnarchiveUserMutation();
const currentUser = useAppStore((store) => store.currentUser);
Expand All @@ -34,6 +36,11 @@ const RouteComponent = () => {
void navigate({ params: { userId: user.id }, to: '/admin/users/$userId' });
};

const groupNamesById = new Map(groupsQuery.data.map((group) => [group.id, group.name]));
const getGroupNames = (user: User) => {
return user.groupIds.flatMap((groupId) => groupNamesById.get(groupId) ?? []).sort((a, b) => a.localeCompare(b));
};

return (
<React.Fragment>
<PageHeader>
Expand Down Expand Up @@ -75,6 +82,40 @@ const RouteComponent = () => {
},
header: ({ column }) => <SortableHeader column={column} label={t('common.basePermissionLevel')} />
},
{
accessorFn: (user) => getGroupNames(user).join(', '),
cell: ({ row }) => {
const [firstGroupName, ...otherGroupNames] = getGroupNames(row.original);
if (!firstGroupName) {
return <span data-testid="user-groups">{t({ en: 'None', es: 'Ninguno', fr: 'Aucun' })}</span>;
}
return (
<Tooltip>
<Tooltip.Trigger
className="h-auto max-w-full p-0 font-normal hover:bg-transparent"
data-testid="user-groups"
size="sm"
variant="ghost"
>
<span className="truncate">
{otherGroupNames.length ? `${firstGroupName} +${otherGroupNames.length}` : firstGroupName}
</span>
</Tooltip.Trigger>
<Tooltip.Content>
<ul data-testid="user-groups-list">
{[firstGroupName, ...otherGroupNames].map((groupName) => (
<li key={groupName}>{groupName}</li>
))}
</ul>
</Tooltip.Content>
</Tooltip>
);
},
header: ({ column }) => (
<SortableHeader column={column} label={t({ en: 'Groups', es: 'Grupos', fr: 'Groupes' })} />
),
id: 'groups'
},
{
accessorFn: (user) => Boolean(user.disabled),
cell: ({ row }) => (
Expand Down Expand Up @@ -201,6 +242,9 @@ const RouteComponent = () => {
export const Route = createFileRoute('/_app/admin/users/')({
component: RouteComponent,
loader: async ({ context }) => {
await context.queryClient.ensureQueryData(usersQueryOptions());
await Promise.all([
context.queryClient.ensureQueryData(usersQueryOptions()),
context.queryClient.ensureQueryData(groupsQueryOptions())
]);
}
});
18 changes: 18 additions & 0 deletions testing/src/specs/admin-management.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,24 @@ test.describe('admin management', () => {
await expect(page.getByTestId('user-status-active')).toBeVisible();
});

test('should show the groups of a user in the users list and every one of them on hover', async ({
api,
authenticateAs,
page,
uniqueId
}) => {
const secondGroup = await api.createGroup({ name: `B Group ${uniqueId}` });
const firstGroup = await api.createGroup({ name: `A Group ${uniqueId}` });
const { user } = await api.createUser({ groupIds: [secondGroup.id, firstGroup.id] });
await authenticateAs('ADMIN');
await page.goto('/admin/users');
await page.getByTestId('data-table-search-bar').getByRole('searchbox').fill(user.username);
const groupsCell = page.getByTestId('user-groups');
await expect(groupsCell).toHaveText(`${firstGroup.name} +1`);
await groupsCell.hover();
await expect(page.getByTestId('user-groups-list').first()).toHaveText([firstGroup.name, secondGroup.name].join(''));
});

test('should show a validation error when the group name is missing', async ({ authenticateAs, page }) => {
await authenticateAs('ADMIN');
await page.goto('/admin/groups/create');
Expand Down
Loading