diff --git a/apps/web/src/routes/_app/admin/users/__tests__/index.test.tsx b/apps/web/src/routes/_app/admin/users/__tests__/index.test.tsx index 70dd79f8b..32e639550 100644 --- a/apps/web/src/routes/_app/admin/users/__tests__/index.test.tsx +++ b/apps/web/src/routes/_app/admin/users/__tests__/index.test.tsx @@ -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[], @@ -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 }) @@ -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); @@ -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'); @@ -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(); }); diff --git a/apps/web/src/routes/_app/admin/users/index.tsx b/apps/web/src/routes/_app/admin/users/index.tsx index 898c163d0..808ee9d12 100644 --- a/apps/web/src/routes/_app/admin/users/index.tsx +++ b/apps/web/src/routes/_app/admin/users/index.tsx @@ -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'; @@ -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'; @@ -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); @@ -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 ( @@ -75,6 +82,40 @@ const RouteComponent = () => { }, header: ({ column }) => }, + { + accessorFn: (user) => getGroupNames(user).join(', '), + cell: ({ row }) => { + const [firstGroupName, ...otherGroupNames] = getGroupNames(row.original); + if (!firstGroupName) { + return {t({ en: 'None', es: 'Ninguno', fr: 'Aucun' })}; + } + return ( + + + + {otherGroupNames.length ? `${firstGroupName} +${otherGroupNames.length}` : firstGroupName} + + + +
    + {[firstGroupName, ...otherGroupNames].map((groupName) => ( +
  • {groupName}
  • + ))} +
+
+
+ ); + }, + header: ({ column }) => ( + + ), + id: 'groups' + }, { accessorFn: (user) => Boolean(user.disabled), cell: ({ row }) => ( @@ -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()) + ]); } }); diff --git a/testing/src/specs/admin-management.spec.ts b/testing/src/specs/admin-management.spec.ts index f3d16a318..3802befbd 100644 --- a/testing/src/specs/admin-management.spec.ts +++ b/testing/src/specs/admin-management.spec.ts @@ -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');