-
Notifications
You must be signed in to change notification settings - Fork 13.5k
Expand file tree
/
Copy pathuseAgentsList.ts
More file actions
92 lines (82 loc) · 2.24 KB
/
useAgentsList.ts
File metadata and controls
92 lines (82 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import type { ILivechatAgent, Serialized } from '@rocket.chat/core-typings';
import { useEndpoint } from '@rocket.chat/ui-contexts';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
type AgentsListOptions = {
filter: string;
haveAll?: boolean;
haveNoAgentsSelectedOption?: boolean;
excludeId?: string;
showIdleAgents?: boolean;
onlyAvailable?: boolean;
limit?: number;
};
type AgentOption = {
_id: string;
value: string;
label: string;
};
const DEFAULT_QUERY_LIMIT = 25;
export const useAgentsList = (options: AgentsListOptions) => {
const { t } = useTranslation();
const getAgents = useEndpoint('GET', '/v1/livechat/users/:type', { type: 'agent' });
const {
filter,
onlyAvailable = false,
showIdleAgents = true,
excludeId,
haveAll,
haveNoAgentsSelectedOption,
limit = DEFAULT_QUERY_LIMIT,
} = options;
const formatAgentItem = (agent: Serialized<ILivechatAgent>) => ({
_id: agent._id,
label: `${agent.name || agent._id} (@${agent.username})`,
value: agent._id,
});
return useInfiniteQuery({
queryKey: ['/v1/livechat/users/:type', { type: 'agent', filter, onlyAvailable, showIdleAgents, excludeId, haveAll, haveNoAgentsSelectedOption }],
queryFn: async ({ pageParam: offset = 0 }) => {
const { users, ...data } = await getAgents({
...(filter && { text: filter }),
...(excludeId && { excludeId }),
showIdleAgents,
onlyAvailable,
offset,
count: limit,
sort: `{ "name": 1 }`,
});
return {
...data,
users: users.map(formatAgentItem),
};
},
select: (data) => {
const items = data.pages.flatMap<AgentOption>((page) => page.users);
if (haveAll) {
items.unshift({
label: t('All'),
value: 'all',
_id: 'all',
});
}
if (haveNoAgentsSelectedOption) {
items.unshift({
label: t('Empty_no_agent_selected'),
value: 'no-agent-selected',
_id: 'no-agent-selected',
});
}
return items;
},
initialPageParam: 0,
getNextPageParam: (lastPage) => {
const offset = lastPage.offset + lastPage.count;
return offset < lastPage.total ? offset : undefined;
},
initialData: () => ({
pages: [{ users: [], offset: 0, count: 0, total: Infinity }],
pageParams: [0],
}),
});
};