import type { ILivechatBusinessHour } from '@rocket.chat/core-typings'; import { LivechatBusinessHourTypes } from '@rocket.chat/core-typings'; import { LivechatDepartment, LivechatDepartmentAgents, Users } from '@rocket.chat/models'; import { makeAgentsUnavailableBasedOnBusinessHour, makeOnlineAgentsAvailable, } from '../../../../../server/lib/omnichannel/business-hour/Helper'; import { getAgentIdsForBusinessHour } from '../../../../../server/lib/omnichannel/business-hour/getAgentIdsForBusinessHour'; import { businessHourLogger } from '../../../../../server/lib/omnichannel/logger'; export const getAgentIdsToHandle = async (businessHour: Pick): Promise => { if (businessHour.type === LivechatBusinessHourTypes.DEFAULT) { return getAgentIdsForBusinessHour(); } const departmentIds = ( await LivechatDepartment.findEnabledByBusinessHourId(businessHour._id, { projection: { _id: 1 }, }).toArray() ).map((dept) => dept._id); return ( await LivechatDepartmentAgents.findByDepartmentIds(departmentIds, { projection: { agentId: 1 }, }).toArray() ).map((dept) => dept.agentId); }; export const openBusinessHour = async ( businessHour: Pick, updateLivechatStatus = true, ): Promise => { const agentIds = await getAgentIdsToHandle(businessHour); businessHourLogger.debug({ msg: 'Opening business hour', businessHour: businessHour._id, totalAgents: agentIds.length, top10AgentIds: agentIds.slice(0, 10), }); await Users.addBusinessHourByAgentIds(agentIds, businessHour._id); await makeOnlineAgentsAvailable(agentIds); if (updateLivechatStatus) { await makeAgentsUnavailableBasedOnBusinessHour(); } }; export const removeBusinessHourByAgentIds = async (agentIds: string[], businessHourId: string): Promise => { if (!agentIds.length) { return; } await Users.removeBusinessHourByAgentIds(agentIds, businessHourId); await makeAgentsUnavailableBasedOnBusinessHour(); };