-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Expand file tree
/
Copy pathqueueManager.ts
More file actions
159 lines (132 loc) · 5.95 KB
/
queueManager.ts
File metadata and controls
159 lines (132 loc) · 5.95 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import type { ILivechatDepartment, ILivechatInquiryRecord, IOmnichannelAgent, Serialized } from '@rocket.chat/core-typings';
import { useLivechatInquiryStore } from '../../../../../client/hooks/useLivechatInquiryStore';
import { queryClient } from '../../../../../client/lib/queryClient';
import { roomsQueryKeys } from '../../../../../client/lib/queryKeys';
import { callWithErrorHandling } from '../../../../../client/lib/utils/callWithErrorHandling';
import { mapMessageFromApi } from '../../../../../client/lib/utils/mapMessageFromApi';
import { settings } from '../../../../settings/client';
import { sdk } from '../../../../utils/client/lib/SDKClient';
const departments = new Set();
const events = {
added: async (inquiry: ILivechatInquiryRecord) => {
if (!departments.has(inquiry.department)) {
return;
}
useLivechatInquiryStore.getState().add({ ...inquiry, alert: true });
await invalidateRoomQueries(inquiry.rid);
},
changed: async (inquiry: ILivechatInquiryRecord) => {
if (inquiry.status !== 'queued' || (inquiry.department && !departments.has(inquiry.department))) {
return removeInquiry(inquiry);
}
useLivechatInquiryStore.getState().merge({ ...inquiry, alert: true });
await invalidateRoomQueries(inquiry.rid);
},
removed: (inquiry: ILivechatInquiryRecord) => removeInquiry(inquiry),
};
type InquiryEventType = keyof typeof events;
type InquiryEventArgs = { type: InquiryEventType } & Omit<ILivechatInquiryRecord, 'type'>;
const processInquiryEvent = async (args: unknown): Promise<void> => {
if (!args || typeof args !== 'object' || !('type' in args)) {
return;
}
const { type, ...inquiry } = args as InquiryEventArgs;
if (type in events) {
await events[type](inquiry as ILivechatInquiryRecord);
}
};
const invalidateRoomQueries = async (rid: string) => {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['rooms', { reference: rid, type: 'l' }] }),
queryClient.invalidateQueries({ queryKey: roomsQueryKeys.room(rid) }),
queryClient.invalidateQueries({ queryKey: roomsQueryKeys.info(rid) }),
]);
};
const removeInquiry = async (inquiry: ILivechatInquiryRecord) => {
useLivechatInquiryStore.getState().discard(inquiry._id);
return queryClient.invalidateQueries({ queryKey: ['rooms', { reference: inquiry.rid, type: 'l' }] });
};
const getInquiriesFromAPI = async () => {
const count = settings.get('Livechat_guest_pool_max_number_incoming_livechats_displayed') ?? 0;
const { inquiries } = await sdk.rest.get('/v1/livechat/inquiries.queuedForUser', { count });
return inquiries;
};
const removeListenerOfDepartment = (departmentId: ILivechatDepartment['_id']) => {
sdk.stop('livechat-inquiry-queue-observer', `department/${departmentId}`);
departments.delete(departmentId);
};
const appendListenerToDepartment = (departmentId: ILivechatDepartment['_id']) => {
departments.add(departmentId);
sdk.stream('livechat-inquiry-queue-observer', [`department/${departmentId}`], async (args) => {
await processInquiryEvent(args);
});
return () => removeListenerOfDepartment(departmentId);
};
const addListenerForeachDepartment = (departments: ILivechatDepartment['_id'][] = []) => {
const cleanupFunctions = departments.map((department) => appendListenerToDepartment(department));
return () => cleanupFunctions.forEach((cleanup) => cleanup());
};
const updateInquiries = async (inquiries: Serialized<ILivechatInquiryRecord>[] = []) =>
inquiries.forEach((inquiry) => {
useLivechatInquiryStore.getState().merge({
...inquiry,
alert: true,
ts: new Date(inquiry.ts),
v: { ...inquiry.v, lastMessageTs: inquiry.v.lastMessageTs ? new Date(inquiry.v.lastMessageTs) : undefined },
estimatedInactivityCloseTimeAt: inquiry.estimatedInactivityCloseTimeAt ? new Date(inquiry.estimatedInactivityCloseTimeAt) : undefined,
lockedAt: inquiry.lockedAt ? new Date(inquiry.lockedAt) : undefined,
lastMessage: inquiry.lastMessage ? mapMessageFromApi(inquiry.lastMessage) : undefined,
_updatedAt: new Date(inquiry._updatedAt),
});
});
const getAgentsDepartments = async (userId: IOmnichannelAgent['_id']) => {
const { departments } = await sdk.rest.get(`/v1/livechat/agents/${userId}/departments`, { enabledDepartmentsOnly: 'true' });
return departments;
};
const removeGlobalListener = () => sdk.stop('livechat-inquiry-queue-observer', 'public');
const addGlobalListener = () => {
sdk.stream('livechat-inquiry-queue-observer', ['public'], async (args) => {
await processInquiryEvent(args);
});
return removeGlobalListener;
};
const removeAgentListener = (userId: IOmnichannelAgent['_id']) => {
sdk.stop('livechat-inquiry-queue-observer', `agent/${userId}`);
};
const addAgentListener = (userId: IOmnichannelAgent['_id']) => {
sdk.stream('livechat-inquiry-queue-observer', [`agent/${userId}`], async (args) => {
await processInquiryEvent(args);
});
return () => removeAgentListener(userId);
};
const subscribe = async (userId: IOmnichannelAgent['_id']) => {
const config = await callWithErrorHandling('livechat:getRoutingConfig');
if (config?.autoAssignAgent) {
return;
}
const agentDepartments = (await getAgentsDepartments(userId)).map((department) => department.departmentId);
// Register to agent-specific queue, all depts + public queue to match the inquiry list returned by backend
const cleanAgentListener = addAgentListener(userId);
const cleanDepartmentListeners = addListenerForeachDepartment(agentDepartments);
const globalCleanup = addGlobalListener();
const computation = Tracker.autorun(async () => {
const inquiriesFromAPI = await getInquiriesFromAPI();
await updateInquiries(inquiriesFromAPI);
});
return () => {
useLivechatInquiryStore.getState().discardAll();
removeGlobalListener();
cleanAgentListener?.();
cleanDepartmentListeners?.();
globalCleanup?.();
departments.clear();
computation.stop();
};
};
export const initializeLivechatInquiryStream = (() => {
let cleanUp: (() => void) | undefined;
return async (...args: Parameters<typeof subscribe>) => {
cleanUp?.();
cleanUp = await subscribe(...args);
};
})();