import type { ILivechatInquiryRecord, SelectedAgent, ILivechatDepartment } from '@rocket.chat/core-typings'; import { LivechatDepartment, LivechatInquiry, LivechatRooms } from '@rocket.chat/models'; import { notifyOnLivechatInquiryChanged, notifyOnRoomChangedById } from '../../../../server/lib/notifyListener'; import { allowAgentSkipQueue } from '../../../../server/lib/omnichannel/Helper'; import { saveQueueInquiry } from '../../../../server/lib/omnichannel/QueueManager'; import { setDepartmentForGuest } from '../../../../server/lib/omnichannel/departmentsLib'; import { beforeRouteChat } from '../../../../server/lib/omnichannel/hooks'; import { online } from '../../../../server/lib/omnichannel/service-status'; import { settings } from '../../../../server/settings'; import { cbLogger } from '../../lib/omnichannel/logger'; beforeRouteChat.patch( async ( originalFn: (inquiry: ILivechatInquiryRecord, _agent?: SelectedAgent | null) => Promise, inquiry: ILivechatInquiryRecord, agent?: SelectedAgent | null, ) => { await originalFn(inquiry, agent); if (!inquiry) { return inquiry; } if (inquiry?.department && !(await online(inquiry.department, true, true))) { const department = await LivechatDepartment.findOneById>( inquiry.department, { projection: { fallbackForwardDepartment: 1 }, }, ); if (!department) { return inquiry; } if (department.fallbackForwardDepartment) { cbLogger.info({ msg: 'Moving inquiry to fallback department', originalDepartment: inquiry.department, fallbackDepartment: department.fallbackForwardDepartment, inquiryId: inquiry._id, }); const [, updatedLivechatInquiry] = await Promise.all([ setDepartmentForGuest({ visitorId: inquiry.v._id, department: department.fallbackForwardDepartment, }), LivechatInquiry.setDepartmentByInquiryId(inquiry._id, department.fallbackForwardDepartment), LivechatRooms.setDepartmentByRoomId(inquiry.rid, department.fallbackForwardDepartment), ]); if (updatedLivechatInquiry) { void notifyOnLivechatInquiryChanged(updatedLivechatInquiry, 'updated', { department: updatedLivechatInquiry.department }); } void notifyOnRoomChangedById(inquiry.rid, 'updated'); inquiry = updatedLivechatInquiry ?? inquiry; } } if (!settings.get('Livechat_waiting_queue')) { return inquiry; } if (agent && (await allowAgentSkipQueue(agent))) { return inquiry; } return saveQueueInquiry(inquiry); }, );