Files
upstream-rocketchat/apps/meteor/client/lib/omnichannel/queueManager.ts
upstream-mirror 30810eecd7
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 2s
snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
2026-09-16 01:21:02 +05:00

175 lines
6.1 KiB
TypeScript

import {
LivechatInquiryStatus,
type ILivechatDepartment,
type ILivechatInquiryRecord,
type IOmnichannelAgent,
type Serialized,
} from '@rocket.chat/core-typings';
import { useLivechatInquiryStore } from '../../hooks/useLivechatInquiryStore';
import { sdk } from '../SDKClient';
import { queryClient } from '../queryClient';
import { roomsQueryKeys } from '../queryKeys';
import { settings } from '../settings';
import { dispatchToastMessage } from '../toast';
import { mapMessageFromApi } from '../utils/mapMessageFromApi';
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 !== LivechatInquiryStatus.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);
}
};
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 INQUIRY_COUNT_SETTING = 'Livechat_guest_pool_max_number_incoming_livechats_displayed';
const getInquiriesFromAPI = async () => {
const count = settings.peek<number>(INQUIRY_COUNT_SETTING) ?? 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']) => {
try {
const { config } = await sdk.rest.get('/v1/livechat/config/routing');
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 refetchInquiries = async () => updateInquiries(await getInquiriesFromAPI());
await refetchInquiries();
const unobserveInquiryCount = settings.observe(INQUIRY_COUNT_SETTING, () => {
void refetchInquiries();
});
return () => {
useLivechatInquiryStore.getState().discardAll();
removeGlobalListener();
cleanAgentListener?.();
cleanDepartmentListeners?.();
globalCleanup?.();
unobserveInquiryCount();
departments.clear();
};
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
throw error;
}
};
export const initializeLivechatInquiryStream = (() => {
let cleanUp: (() => void) | undefined;
return async (...args: Parameters<typeof subscribe>) => {
cleanUp?.();
cleanUp = await subscribe(...args);
};
})();