Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

regression: no sorting by status in rooms.membersByOrderedByRole #35004

Open
wants to merge 4 commits into
base: release-7.3.0
Choose a base branch
from
Open
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
313 changes: 313 additions & 0 deletions apps/meteor/client/views/hooks/useMemberList.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,313 @@
import { UserStatus } from '@rocket.chat/core-typings';
import { mockAppRoot } from '@rocket.chat/mock-providers';
import { useStream } from '@rocket.chat/ui-contexts';
import { renderHook, act, waitFor } from '@testing-library/react';

import type { RoomMember } from './useMembersList';
import { useMembersList } from './useMembersList';

type MembersPage = {
offset: number;
count: number;
total: number;
members: Array<{
_id: string;
username: string;
roles: string[];
status?: UserStatus;
}>;
};

jest.mock('@rocket.chat/ui-contexts', () => {
const originalModule = jest.requireActual('@rocket.chat/ui-contexts');

return {
__esModule: true,
...originalModule,
useStream: jest.fn(),
};
});

const mockUseStream = useStream as jest.MockedFunction<typeof useStream>;
const mockDMMembersEndpoint = jest.fn();
const mockRoomMembersEndpoint = jest.fn();

describe('useMembersList', () => {
let fakeMembersPage1: MembersPage;
let fakeMembersPage2: MembersPage;

const wrapper = mockAppRoot()
.withJohnDoe()
.withSetting('UI_Use_Real_Name', false)
.withEndpoint('GET', '/v1/im.members', (_params) => {
mockDMMembersEndpoint();
return fakeMembersPage1 as any;
})
.withEndpoint('GET', '/v1/rooms.membersOrderedByRole', (_params) => {
mockRoomMembersEndpoint();
return fakeMembersPage1 as any;
});

beforeEach(() => {
jest.clearAllMocks();

fakeMembersPage1 = {
offset: 0,
count: 20,
total: 40,
members: [
{ _id: 'user1', username: 'alex', roles: ['owner'], status: UserStatus.ONLINE },
{ _id: 'user2', username: 'john', roles: ['moderator'], status: UserStatus.OFFLINE },
],
};

fakeMembersPage2 = {
offset: 20,
count: 20,
total: 40,
members: [
{ _id: 'user3', username: 'chris', roles: [], status: UserStatus.ONLINE },
{ _id: 'user4', username: 'zoe', roles: [], status: UserStatus.OFFLINE },
],
};

mockUseStream.mockReturnValue(() => () => undefined);
});

it('fetches members using the correct endpoint for roomType c', async () => {
const { result } = renderHook(
() =>
useMembersList({
rid: 'room123',
type: 'all',
limit: 20,
debouncedText: '',
roomType: 'c',
}),
{ legacyRoot: true, wrapper: wrapper.build() },
);

await expect(result.current.isLoading).toBe(true);

await waitFor(() => expect(result.current.isLoading).toBe(false));
expect(mockDMMembersEndpoint).not.toHaveBeenCalled();
expect(mockRoomMembersEndpoint).toHaveBeenCalled();

expect(result.current.data?.pages[0].members).toHaveLength(fakeMembersPage1.members.length);
});

it('fetches members using the correct endpoint for roomType p', async () => {
const { result } = renderHook(
() =>
useMembersList({
rid: 'room123',
type: 'all',
limit: 20,
debouncedText: '',
roomType: 'p',
}),
{ legacyRoot: true, wrapper: wrapper.build() },
);

expect(result.current.isLoading).toBe(true);

await waitFor(() => expect(result.current.isLoading).toBe(false));

expect(mockRoomMembersEndpoint).toHaveBeenCalled();
expect(mockDMMembersEndpoint).not.toHaveBeenCalled();

expect(result.current.data?.pages[0].members).toHaveLength(fakeMembersPage1.members.length);
});

it('fetches from /v1/im.members if roomType is d', async () => {
const { result } = renderHook(
() =>
useMembersList({
rid: 'directRoomId',
type: 'all',
limit: 20,
debouncedText: '',
roomType: 'd',
}),
{ legacyRoot: true, wrapper: wrapper.build() },
);

await waitFor(() => expect(result.current.isLoading).toBe(false));

expect(mockDMMembersEndpoint).toHaveBeenCalled();
expect(mockRoomMembersEndpoint).not.toHaveBeenCalled();

expect(result.current.data?.pages[0].members).toHaveLength(fakeMembersPage1.members.length);
});

it('applies pagination with fetchNextPage', async () => {
const { result } = renderHook(
() =>
useMembersList({
rid: 'room123',
type: 'all',
limit: 20,
debouncedText: '',
roomType: 'c',
}),
{
legacyRoot: true,
wrapper: wrapper
.withEndpoint('GET', '/v1/rooms.membersOrderedByRole', ({ offset }) => {
if (offset === 0) {
return fakeMembersPage1 as any;
}
if (offset === 20) {
return fakeMembersPage2 as any;
}
return {
members: [],
offset,
count: 20,
total: 40,
};
})
.build(),
},
);

await waitFor(() => expect(result.current.isLoading).toBe(false));
expect(result.current.data?.pages[0].members).toHaveLength(2);

await act(async () => {
await result.current.fetchNextPage();
});

await waitFor(() => expect(result.current.isFetchingNextPage).toBe(false));
await waitFor(() => expect(result.current.data?.pages).toHaveLength(2));
expect(result.current.data?.pages[1].members).toHaveLength(2);
});

it('subscribes to "roles-change" and unsubscribes on unmount', async () => {
const unsubscribeMock = jest.fn();
const subscribeMock = jest.fn().mockReturnValue(unsubscribeMock);

mockUseStream.mockReturnValue(subscribeMock);

const { unmount } = renderHook(
() =>
useMembersList({
rid: 'room123',
type: 'all',
limit: 20,
debouncedText: '',
roomType: 'c',
}),
{ legacyRoot: true, wrapper: wrapper.build() },
);

await waitFor(() => expect(subscribeMock).toHaveBeenCalledWith('roles-change', expect.any(Function)));

unmount();
expect(unsubscribeMock).toHaveBeenCalled();
});

it('updates member roles in the cache on roles-change', async () => {
const subscribeMock = jest.fn();
let rolesChangeCallback: ((payload: any) => void) | undefined = undefined;

subscribeMock.mockImplementation((eventName, cb) => {
if (eventName === 'roles-change') {
rolesChangeCallback = cb;
}
return () => undefined; // unsubscribe mock
});
mockUseStream.mockReturnValue(subscribeMock);

const { result } = renderHook(
() =>
useMembersList({
rid: 'room123',
type: 'all',
limit: 20,
debouncedText: '',
roomType: 'c',
}),
{ legacyRoot: true, wrapper: wrapper.build() },
);

await waitFor(() => expect(result.current.isLoading).toBe(false));
let user2 = result.current.data?.pages[0].members.find((m) => m._id === 'user2') as RoomMember;
expect(user2?.roles).toEqual(['moderator']);

// Simulate a roles-change event "added" for user2 -> 'owner'
await act(async () => {
rolesChangeCallback?.({
type: 'added',
scope: 'room123',
u: { _id: 'user2' },
_id: 'owner',
});
});

user2 = result.current.data?.pages[0].members.find((m) => m._id === 'user2') as RoomMember;

await waitFor(() => expect(user2?.roles).toContain('owner'));
await waitFor(() => expect(user2?.roles).toContain('moderator'));
});

it('sorts members list cache by "roles > status > username/name" logic on roles-change', async () => {
const customPage = {
offset: 0,
count: 4,
total: 4,
members: [
{ _id: 'u1', username: 'michael', roles: ['owner'], status: UserStatus.OFFLINE },
{ _id: 'u2', username: 'karl', roles: ['moderator'], status: UserStatus.ONLINE },
{ _id: 'u3', username: 'bob', roles: ['moderator'], status: UserStatus.OFFLINE },
{ _id: 'u4', username: 'alex', roles: [], status: UserStatus.OFFLINE },
{ _id: 'u5', username: 'john', roles: [], status: UserStatus.ONLINE },
],
};

let rolesChangeCallback: ((payload: any) => void) | undefined;
mockUseStream.mockReturnValue((eventName, cb) => {
if (eventName === 'roles-change') {
rolesChangeCallback = cb as any;
}
return () => undefined;
});

const { result } = renderHook(
() =>
useMembersList({
rid: 'room123',
type: 'all',
limit: 20,
debouncedText: '',
roomType: 'c',
}),
{
legacyRoot: true,
wrapper: wrapper.withEndpoint('GET', '/v1/rooms.membersOrderedByRole', (_params) => customPage as any).build(),
},
);

await waitFor(() => expect(result.current.isLoading).toBe(false));

let memberIds = result.current.data?.pages[0].members.map((m) => m._id);
expect(memberIds).toEqual(['u1', 'u2', 'u3', 'u4', 'u5']);

// Simulate giving user 'alex/u4' the "moderator" role.
// That should push 'alex/u4' to the third of the sorted list -
// after michael/u1 (since owner), after karl/u2 (since online) and before bob/u3 (since sort by username).
act(() => {
rolesChangeCallback?.({
type: 'added',
scope: 'room123',
u: { _id: 'u4' },
_id: 'moderator',
});
});

await waitFor(() => {
memberIds = result.current.data?.pages[0].members.map((m) => m._id);
expect(memberIds).toEqual(['u1', 'u2', 'u4', 'u3', 'u5']);
});
});
});
6 changes: 3 additions & 3 deletions apps/meteor/client/views/hooks/useMembersList.ts
abhinavkrin marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const endpointsByRoomType = {
c: '/v1/rooms.membersOrderedByRole',
} as const;

type RoomMember = Pick<IUser, 'username' | '_id' | 'name' | 'status' | 'freeSwitchExtension'> & { roles?: IRole['_id'][] };
export type RoomMember = Pick<IUser, 'username' | '_id' | 'name' | 'status' | 'freeSwitchExtension'> & { roles?: IRole['_id'][] };

const getSortedMembers = (members: RoomMember[], useRealName = false) => {
return members.sort((a, b) => {
Expand All @@ -37,8 +37,8 @@ const getSortedMembers = (members: RoomMember[], useRealName = false) => {
return isModeratorA ? -1 : 1;
}

if ((a.status === 'online' || b.status === 'online') && a.status !== b.status) {
return a.status === 'online' ? -1 : 1;
if (a.status !== b.status) {
return ((a.status ?? 'offline')?.localeCompare(b.status ?? 'offline') ?? 0) * -1;
}

if (useRealName && a.name && b.name) {
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/server/lib/findUsersOfRoomOrderedByRole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export async function findUsersOfRoomOrderedByRole({

const sortCriteria = {
rolePriority: rolePrioritySort ?? 1,
statusConnection: -1,
status: -1,
...(usernameSort
? { username: usernameSort }
: {
Expand Down
Loading
Loading