From 06bf7793abb6aaf4e01ff446b0560bd0fd1b1c40 Mon Sep 17 00:00:00 2001 From: Kevin Aleman Date: Fri, 29 Sep 2023 11:44:22 -0600 Subject: [PATCH] refactor: Omni logs (#30322) --- .../app/api/server/v1/voip/omnichannel.ts | 2 - .../business-hour/BusinessHourManager.ts | 2 - .../livechat/server/business-hour/Helper.ts | 1 - .../livechat/server/business-hour/Single.ts | 2 - .../livechat/server/hooks/afterUserActions.ts | 6 --- .../server/hooks/saveAnalyticsData.ts | 4 -- .../app/livechat/server/lib/Analytics.js | 6 --- .../app/livechat/server/lib/Departments.ts | 5 -- .../app/livechat/server/lib/QueueManager.ts | 9 ---- .../app/livechat/server/lib/RoutingManager.ts | 8 +--- .../app/livechat/server/sendMessageBySMS.ts | 13 ++--- apps/meteor/app/livechat/server/startup.ts | 4 +- .../server/business-hour/Multiple.ts | 38 +-------------- .../hooks/afterForwardChatToDepartment.ts | 3 -- .../server/hooks/afterInquiryQueued.ts | 2 - .../server/hooks/afterOnHold.ts | 2 - .../server/hooks/afterOnHoldChatResumed.ts | 1 - .../server/hooks/afterRemoveDepartment.ts | 1 - .../server/hooks/afterReturnRoomAsInquiry.ts | 2 - .../server/hooks/afterTakeInquiry.ts | 2 - .../hooks/applyDepartmentRestrictions.ts | 1 - .../server/hooks/applyRoomRestrictions.ts | 2 - .../applySimultaneousChatsRestrictions.ts | 4 -- .../hooks/beforeForwardRoomToDepartment.ts | 5 -- .../server/hooks/beforeNewInquiry.ts | 3 -- .../server/hooks/beforeRoutingChat.ts | 12 +---- .../hooks/checkAgentBeforeTakeInquiry.ts | 11 ++--- .../server/hooks/onAgentAssignmentFailed.ts | 5 -- .../server/hooks/onCloseLivechat.ts | 6 --- .../onLoadForwardDepartmentRestrictions.ts | 6 +-- .../server/hooks/onSaveVisitorInfo.ts | 7 --- .../server/hooks/onTransferFailure.ts | 5 +- .../server/hooks/scheduleAutoTransfer.ts | 6 +-- .../server/lib/AutoCloseOnHoldScheduler.ts | 4 +- .../server/lib/AutoTransferChatScheduler.ts | 4 +- .../livechat-enterprise/server/lib/Helper.ts | 5 +- .../server/lib/QueueInactivityMonitor.ts | 8 ++-- .../server/lib/VisitorInactivityMonitor.ts | 24 +++------- .../services/omnichannel.internalService.ts | 13 +---- .../ee/server/models/raw/LivechatRooms.ts | 47 ++++++++++++------- .../ee/server/models/raw/LivechatUnit.ts | 12 +++-- .../EmailInbox/EmailInbox_Incoming.ts | 30 ++---------- .../EmailInbox/EmailInbox_Outgoing.ts | 4 +- .../services/omnichannel-voip/service.ts | 21 ++------- .../server/services/omnichannel/queue.ts | 9 ++-- .../src/OmnichannelTranscript.ts | 4 +- 46 files changed, 80 insertions(+), 291 deletions(-) diff --git a/apps/meteor/app/api/server/v1/voip/omnichannel.ts b/apps/meteor/app/api/server/v1/voip/omnichannel.ts index 6ffd0005c764d..e1ee82d724789 100644 --- a/apps/meteor/app/api/server/v1/voip/omnichannel.ts +++ b/apps/meteor/app/api/server/v1/voip/omnichannel.ts @@ -78,7 +78,6 @@ API.v1.addRoute( } try { - logger.debug(`Setting extension ${extension} for agent with id ${user._id}`); await Users.setExtension(user._id, extension); return API.v1.success(); } catch (e) { @@ -146,7 +145,6 @@ API.v1.addRoute( return API.v1.notFound(); } if (!user.extension) { - logger.debug(`User ${user._id} is not associated with any extension. Skipping`); return API.v1.success(); } diff --git a/apps/meteor/app/livechat/server/business-hour/BusinessHourManager.ts b/apps/meteor/app/livechat/server/business-hour/BusinessHourManager.ts index 52ccd0441e24e..c541e5f7b2c36 100644 --- a/apps/meteor/app/livechat/server/business-hour/BusinessHourManager.ts +++ b/apps/meteor/app/livechat/server/business-hour/BusinessHourManager.ts @@ -7,7 +7,6 @@ import moment from 'moment'; import { closeBusinessHour } from '../../../../ee/app/livechat-enterprise/server/business-hour/Helper'; import { callbacks } from '../../../../lib/callbacks'; import { settings } from '../../../settings/server'; -import { businessHourLogger } from '../lib/logger'; import type { IBusinessHourBehavior, IBusinessHourType } from './AbstractBusinessHour'; export class BusinessHourManager { @@ -27,7 +26,6 @@ export class BusinessHourManager { async startManager(): Promise { await this.createCronJobsForWorkHours(); - businessHourLogger.debug('Cron jobs created, setting up callbacks'); this.setupCallbacks(); await this.cleanupDisabledDepartmentReferences(); await this.behavior.onStartBusinessHours(); diff --git a/apps/meteor/app/livechat/server/business-hour/Helper.ts b/apps/meteor/app/livechat/server/business-hour/Helper.ts index e61bb1621765c..e96ccb4c7b89a 100644 --- a/apps/meteor/app/livechat/server/business-hour/Helper.ts +++ b/apps/meteor/app/livechat/server/business-hour/Helper.ts @@ -59,7 +59,6 @@ export const openBusinessHourDefault = async (): Promise => { await Users.makeAgentsWithinBusinessHourAvailable(); } await Users.updateLivechatStatusBasedOnBusinessHours(); - businessHourLogger.debug('Done opening default business hours'); }; export const createDefaultBusinessHourIfNotExists = async (): Promise => { diff --git a/apps/meteor/app/livechat/server/business-hour/Single.ts b/apps/meteor/app/livechat/server/business-hour/Single.ts index d899f27173766..5d2730dba9a14 100644 --- a/apps/meteor/app/livechat/server/business-hour/Single.ts +++ b/apps/meteor/app/livechat/server/business-hour/Single.ts @@ -8,7 +8,6 @@ import { filterBusinessHoursThatMustBeOpened, openBusinessHourDefault } from './ export class SingleBusinessHourBehavior extends AbstractBusinessHourBehavior implements IBusinessHourBehavior { async openBusinessHoursByDayAndHour(): Promise { - businessHourLogger.debug('opening single business hour'); return openBusinessHourDefault(); } @@ -23,7 +22,6 @@ export class SingleBusinessHourBehavior extends AbstractBusinessHourBehavior imp } async onStartBusinessHours(): Promise { - businessHourLogger.debug('Starting Single Business Hours'); return openBusinessHourDefault(); } diff --git a/apps/meteor/app/livechat/server/hooks/afterUserActions.ts b/apps/meteor/app/livechat/server/hooks/afterUserActions.ts index 30900481c4e2c..0419f1d02a1d9 100644 --- a/apps/meteor/app/livechat/server/hooks/afterUserActions.ts +++ b/apps/meteor/app/livechat/server/hooks/afterUserActions.ts @@ -3,7 +3,6 @@ import { Users } from '@rocket.chat/models'; import { callbacks } from '../../../../lib/callbacks'; import { Livechat } from '../lib/Livechat'; -import { callbackLogger } from '../lib/logger'; type IAfterSaveUserProps = { user: IUser; @@ -34,17 +33,12 @@ const handleAgentCreated = async (user: IUser) => { const handleDeactivateUser = async (user: IUser) => { if (wasAgent(user)) { - callbackLogger.debug({ - msg: 'Removing agent extension & making agent unavailable', - userId: user._id, - }); await Users.makeAgentUnavailableAndUnsetExtension(user._id); } }; const handleActivateUser = async (user: IUser) => { if (isAgent(user)) { - callbackLogger.debug('Adding agent', user._id); await Livechat.addAgent(user.username); } }; diff --git a/apps/meteor/app/livechat/server/hooks/saveAnalyticsData.ts b/apps/meteor/app/livechat/server/hooks/saveAnalyticsData.ts index ec584ec001d67..e92e6b4d940b3 100644 --- a/apps/meteor/app/livechat/server/hooks/saveAnalyticsData.ts +++ b/apps/meteor/app/livechat/server/hooks/saveAnalyticsData.ts @@ -3,7 +3,6 @@ import { LivechatRooms } from '@rocket.chat/models'; import { callbacks } from '../../../../lib/callbacks'; import { normalizeMessageFileUpload } from '../../../utils/server/functions/normalizeMessageFileUpload'; -import { callbackLogger } from '../lib/logger'; callbacks.add( 'afterSaveMessage', @@ -13,7 +12,6 @@ callbacks.add( return message; } - callbackLogger.debug(`Calculating Omnichannel metrics for room ${room._id}`); // skips this callback if the message was edited if (!message || isEditedMessage(message)) { return message; @@ -43,7 +41,6 @@ callbacks.add( const isResponseTotal = room.metrics?.response?.total; if (agentLastReply === room.ts) { - callbackLogger.debug('Calculating: first message from agent'); // first response const firstResponseDate = now; const firstResponseTime = (now.getTime() - new Date(visitorLastQuery).getTime()) / 1000; @@ -66,7 +63,6 @@ callbacks.add( reactionTime, }; } else if (visitorLastQuery > agentLastReply) { - callbackLogger.debug('Calculating: visitor sent a message after agent'); // response, not first const responseTime = (now.getTime() - new Date(visitorLastQuery).getTime()) / 1000; const avgResponseTime = diff --git a/apps/meteor/app/livechat/server/lib/Analytics.js b/apps/meteor/app/livechat/server/lib/Analytics.js index 5f6e3469501e2..28bed221afbf0 100644 --- a/apps/meteor/app/livechat/server/lib/Analytics.js +++ b/apps/meteor/app/livechat/server/lib/Analytics.js @@ -43,8 +43,6 @@ export const Analytics = { const from = moment.tz(fDate, 'YYYY-MM-DD', timezone).startOf('day').utc(); const to = moment.tz(tDate, 'YYYY-MM-DD', timezone).endOf('day').utc(); - logger.debug(`getAgentOverviewData[${name}] -> Using timezone ${timezone} with date range ${from} - ${to}`); - if (!(moment(from).isValid() && moment(to).isValid())) { logger.error('livechat:getAgentOverviewData => Invalid dates'); return; @@ -79,8 +77,6 @@ export const Analytics = { const to = moment.tz(tDate, 'YYYY-MM-DD', timezone).endOf('day').utc(); const isSameDay = from.diff(to, 'days') === 0; - logger.debug(`getAnalyticsChartData[${name}] -> Using timezone ${timezone} with date range ${from} - ${to}`); - if (!(moment(from).isValid() && moment(to).isValid())) { logger.error('livechat:getAnalyticsChartData => Invalid dates'); return; @@ -133,8 +129,6 @@ export const Analytics = { const from = moment.tz(fDate, 'YYYY-MM-DD', timezone).startOf('day').utc(); const to = moment.tz(tDate, 'YYYY-MM-DD', timezone).endOf('day').utc(); - logger.debug(`getAnalyticsOverviewData[${name}] -> Using timezone ${timezone} with date range ${from} - ${to}`); - if (!(moment(from).isValid() && moment(to).isValid())) { logger.error('livechat:getAnalyticsOverviewData => Invalid dates'); return; diff --git a/apps/meteor/app/livechat/server/lib/Departments.ts b/apps/meteor/app/livechat/server/lib/Departments.ts index 0dd48a328fd13..f17015e52e795 100644 --- a/apps/meteor/app/livechat/server/lib/Departments.ts +++ b/apps/meteor/app/livechat/server/lib/Departments.ts @@ -12,7 +12,6 @@ class DepartmentHelperClass { const department = await LivechatDepartment.findOneById(departmentId); if (!department) { - this.logger.debug(`Department not found: ${departmentId}`); throw new Error('error-department-not-found'); } @@ -20,10 +19,8 @@ class DepartmentHelperClass { const ret = await LivechatDepartment.removeById(_id); if (ret.acknowledged !== true) { - this.logger.error(`Department record not removed: ${_id}. Result from db: ${ret}`); throw new Error('error-failed-to-delete-department'); } - this.logger.debug(`Department record removed: ${_id}`); const agentsIds: string[] = await LivechatDepartmentAgents.findAgentsByDepartmentId>( department._id, @@ -47,8 +44,6 @@ class DepartmentHelperClass { } }); - this.logger.debug(`Post-department-removal actions completed: ${_id}. Notifying callbacks with department and agentsIds`); - setImmediate(() => { void callbacks.run('livechat.afterRemoveDepartment', { department, agentsIds }); }); diff --git a/apps/meteor/app/livechat/server/lib/QueueManager.ts b/apps/meteor/app/livechat/server/lib/QueueManager.ts index 597f38b71ec07..aed0061e808ef 100644 --- a/apps/meteor/app/livechat/server/lib/QueueManager.ts +++ b/apps/meteor/app/livechat/server/lib/QueueManager.ts @@ -23,7 +23,6 @@ export const queueInquiry = async (inquiry: ILivechatInquiryRecord, defaultAgent const dbInquiry = await LivechatInquiry.findOneById(inquiry._id); if (!dbInquiry) { - logger.error(`Inquiry with id ${inquiry._id} not found`); throw new Error('inquiry-not-found'); } @@ -68,7 +67,6 @@ export const QueueManager: queueManager = { ); if (!(await checkServiceStatus({ guest, agent }))) { - logger.debug(`Cannot create room for visitor ${guest._id}. No online agents`); throw new Meteor.Error('no-agent-online', 'Sorry, no online agents'); } @@ -96,8 +94,6 @@ export const QueueManager: queueManager = { throw new Error('inquiry-not-found'); } - logger.debug(`Generated inquiry for visitor ${guest._id} with id ${inquiry._id} [Not queued]`); - await LivechatRooms.updateRoomCount(); await queueInquiry(inquiry, agent); @@ -114,7 +110,6 @@ export const QueueManager: queueManager = { async unarchiveRoom(archivedRoom) { if (!archivedRoom) { - logger.error('No room to unarchive'); throw new Error('no-room-to-unarchive'); } @@ -145,17 +140,13 @@ export const QueueManager: queueManager = { await LivechatRooms.unarchiveOneById(rid); const room = await LivechatRooms.findOneById(rid); if (!room) { - logger.debug(`Room with id ${rid} not found`); throw new Error('room-not-found'); } const inquiry = await LivechatInquiry.findOneById(await createLivechatInquiry({ rid, name, guest, message, extraData: { source } })); if (!inquiry) { - logger.error(`Inquiry for visitor ${guest._id} not found`); throw new Error('inquiry-not-found'); } - logger.debug(`Generated inquiry for visitor ${v._id} with id ${inquiry._id} [Not queued]`); - await queueInquiry(inquiry, defaultAgent); logger.debug(`Inquiry ${inquiry._id} queued`); diff --git a/apps/meteor/app/livechat/server/lib/RoutingManager.ts b/apps/meteor/app/livechat/server/lib/RoutingManager.ts index 0e975ca067636..f2fd7010eb12e 100644 --- a/apps/meteor/app/livechat/server/lib/RoutingManager.ts +++ b/apps/meteor/app/livechat/server/lib/RoutingManager.ts @@ -74,7 +74,7 @@ export const RoutingManager: Routing = { }, async setMethodNameAndStartQueue(name) { - logger.debug(`Changing default routing method from ${this.methodName} to ${name}`); + logger.info(`Changing default routing method from ${this.methodName} to ${name}`); if (!this.methods[name]) { logger.warn(`Cannot change routing method to ${name}. Selected Routing method does not exists. Defaulting to Manual_Selection`); this.methodName = 'Manual_Selection'; @@ -87,7 +87,6 @@ export const RoutingManager: Routing = { // eslint-disable-next-line @typescript-eslint/naming-convention registerMethod(name, Method) { - logger.debug(`Registering new routing method with name ${name}`); this.methods[name] = new Method(); }, @@ -188,7 +187,6 @@ export const RoutingManager: Routing = { const { servedBy } = room; if (servedBy) { - logger.debug(`Unassigning current agent for inquiry ${inquiry._id}`); await LivechatRooms.removeAgentByRoomId(rid); await this.removeAllRoomSubscriptions(room); await dispatchAgentDelegated(rid); @@ -254,7 +252,7 @@ export const RoutingManager: Routing = { await LivechatInquiry.takeInquiry(_id); const inq = await this.assignAgent(inquiry as InquiryWithAgentInfo, agent); - logger.debug(`Inquiry ${inquiry._id} taken by agent ${agent.agentId}`); + logger.info(`Inquiry ${inquiry._id} taken by agent ${agent.agentId}`); callbacks.runAsync('livechat.afterTakeInquiry', inq, agent); @@ -262,7 +260,6 @@ export const RoutingManager: Routing = { }, async transferRoom(room, guest, transferData) { - logger.debug(`Transfering room ${room._id} by ${transferData.transferredBy._id}`); if (transferData.departmentId) { logger.debug(`Transfering room ${room._id} to department ${transferData.departmentId}`); return forwardRoomToDepartment(room, guest, transferData); @@ -278,7 +275,6 @@ export const RoutingManager: Routing = { }, async delegateAgent(agent, inquiry) { - logger.debug(`Delegating Inquiry ${inquiry._id}`); const defaultAgent = await callbacks.run('livechat.beforeDelegateAgent', agent, { department: inquiry?.department, }); diff --git a/apps/meteor/app/livechat/server/sendMessageBySMS.ts b/apps/meteor/app/livechat/server/sendMessageBySMS.ts index ea220b24d1491..2557fcdeb83d0 100644 --- a/apps/meteor/app/livechat/server/sendMessageBySMS.ts +++ b/apps/meteor/app/livechat/server/sendMessageBySMS.ts @@ -10,33 +10,27 @@ import { callbackLogger } from './lib/logger'; callbacks.add( 'afterSaveMessage', async (message, room) => { - callbackLogger.debug('Attempting to send SMS message'); // skips this callback if the message was edited if (isEditedMessage(message)) { - callbackLogger.debug('Message was edited, skipping SMS send'); return message; } if (!settings.get('SMS_Enabled')) { - callbackLogger.debug('SMS is not enabled, skipping SMS send'); return message; } // only send the sms by SMS if it is a livechat room with SMS set to true if (!(isOmnichannelRoom(room) && room.sms && room.v && room.v.token)) { - callbackLogger.debug('Room is not a livechat room, skipping SMS send'); return message; } // if the message has a token, it was sent from the visitor, so ignore it if (message.token) { - callbackLogger.debug('Message was sent from the visitor, skipping SMS send'); return message; } // if the message has a type means it is a special message (like the closing comment), so skips if (message.t) { - callbackLogger.debug('Message is a special message, skipping SMS send'); return message; } @@ -52,8 +46,9 @@ callbacks.add( const { location } = message; extraData = Object.assign({}, extraData, { location }); } + const service = settings.get('SMS_Service'); - const SMSService = await OmnichannelIntegration.getSmsService(settings.get('SMS_Service')); + const SMSService = await OmnichannelIntegration.getSmsService(service); if (!SMSService) { callbackLogger.debug('SMS Service is not configured, skipping SMS send'); @@ -63,14 +58,12 @@ callbacks.add( const visitor = await LivechatVisitors.getVisitorByToken(room.v.token, { projection: { phone: 1 } }); if (!visitor?.phone || visitor.phone.length === 0) { - callbackLogger.debug('Visitor does not have a phone number, skipping SMS send'); return message; } try { - callbackLogger.debug(`Message will be sent to ${visitor.phone[0].phoneNumber} through service ${settings.get('SMS_Service')}`); await SMSService.send(room.sms.from, visitor.phone[0].phoneNumber, message.msg, extraData); - callbackLogger.debug(`SMS message sent to ${visitor.phone[0].phoneNumber}`); + callbackLogger.debug(`SMS message sent to ${visitor.phone[0].phoneNumber} via ${service}`); } catch (e) { callbackLogger.error(e); } diff --git a/apps/meteor/app/livechat/server/startup.ts b/apps/meteor/app/livechat/server/startup.ts index f24f88975b227..f9fce509e39ad 100644 --- a/apps/meteor/app/livechat/server/startup.ts +++ b/apps/meteor/app/livechat/server/startup.ts @@ -62,14 +62,12 @@ Meteor.startup(async () => { await createDefaultBusinessHourIfNotExists(); settings.watch('Livechat_enable_business_hours', async (value) => { - Livechat.logger.debug(`Changing business hour type to ${value}`); + Livechat.logger.info(`Changing business hour type to ${value}`); if (value) { await businessHourManager.startManager(); - Livechat.logger.debug(`Business hour manager started`); return; } await businessHourManager.stopManager(); - Livechat.logger.debug(`Business hour manager stopped`); }); settings.watch('Livechat_Routing_Method', (value) => { diff --git a/apps/meteor/ee/app/livechat-enterprise/server/business-hour/Multiple.ts b/apps/meteor/ee/app/livechat-enterprise/server/business-hour/Multiple.ts index 22379e27698d5..6c4aac024ab09 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/business-hour/Multiple.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/business-hour/Multiple.ts @@ -44,7 +44,7 @@ export class MultipleBusinessHoursBehavior extends AbstractBusinessHourBehavior }, }); const businessHoursToOpen = await filterBusinessHoursThatMustBeOpened(activeBusinessHours); - bhLogger.debug({ + bhLogger.info({ msg: 'Starting Multiple Business Hours', totalBusinessHoursToOpen: businessHoursToOpen.length, top10BusinessHoursToOpen: businessHoursToOpen.slice(0, 10), @@ -153,7 +153,6 @@ export class MultipleBusinessHoursBehavior extends AbstractBusinessHourBehavior } async onRemoveDepartment(options: { department: ILivechatDepartment; agentsIds: string[] }): Promise { - bhLogger.debug(`onRemoveDepartment: department ${options.department._id} removed`); const { department, agentsIds } = options; if (!department || !agentsIds?.length) { return options; @@ -163,10 +162,6 @@ export class MultipleBusinessHoursBehavior extends AbstractBusinessHourBehavior async onDepartmentDisabled(department: ILivechatDepartment): Promise { if (!department.businessHourId) { - bhLogger.debug({ - msg: 'onDepartmentDisabled: department has no business hour', - departmentId: department._id, - }); return; } @@ -186,7 +181,6 @@ export class MultipleBusinessHoursBehavior extends AbstractBusinessHourBehavior // cleanup user's cache for default business hour and this business hour const defaultBH = await this.BusinessHourRepository.findOneDefaultBusinessHour(); if (!defaultBH) { - bhLogger.error('onDepartmentDisabled: default business hour not found'); throw new Error('Default business hour not found'); } await this.UsersRepository.closeAgentsBusinessHoursByBusinessHourIds([businessHour._id, defaultBH._id]); @@ -203,37 +197,22 @@ export class MultipleBusinessHoursBehavior extends AbstractBusinessHourBehavior businessHour = await this.BusinessHourRepository.findOneById(department.businessHourId); if (!businessHour) { - bhLogger.error({ - msg: 'onDepartmentDisabled: business hour not found', - businessHourId: department.businessHourId, - }); - throw new Error(`Business hour ${department.businessHourId} not found`); } } // start default business hour and this BH if needed if (!settings.get('Livechat_enable_business_hours')) { - bhLogger.debug(`onDepartmentDisabled: business hours are disabled. skipping`); return; } const businessHourToOpen = await filterBusinessHoursThatMustBeOpened([businessHour, defaultBH]); for await (const bh of businessHourToOpen) { - bhLogger.debug({ - msg: 'onDepartmentDisabled: opening business hour', - businessHourId: bh._id, - }); await openBusinessHour(bh, false); } await Users.updateLivechatStatusBasedOnBusinessHours(); await businessHourManager.restartCronJobsIfNecessary(); - - bhLogger.debug({ - msg: 'onDepartmentDisabled: successfully processed department disabled event', - departmentId: department._id, - }); } async onDepartmentArchived(department: Pick): Promise { @@ -253,11 +232,6 @@ export class MultipleBusinessHoursBehavior extends AbstractBusinessHourBehavior } async onNewAgentCreated(agentId: string): Promise { - bhLogger.debug({ - msg: 'Executing onNewAgentCreated for agent', - agentId, - }); - await this.applyAnyOpenBusinessHourToAgent(agentId); await Users.updateLivechatStatusBasedOnBusinessHours([agentId]); @@ -293,11 +267,6 @@ export class MultipleBusinessHoursBehavior extends AbstractBusinessHourBehavior const isDefaultBHActive = openedBusinessHours.find(({ type }) => type === LivechatBusinessHourTypes.DEFAULT); if (isDefaultBHActive?._id) { await Users.openAgentBusinessHoursByBusinessHourIdsAndAgentId([isDefaultBHActive._id], agentId); - - bhLogger.debug({ - msg: 'Business hour status check passed for agent. Found default business hour to be active', - agentId, - }); return; } @@ -330,11 +299,6 @@ export class MultipleBusinessHoursBehavior extends AbstractBusinessHourBehavior const isDefaultBHActive = openedBusinessHours.find(({ type }) => type === LivechatBusinessHourTypes.DEFAULT); if (isDefaultBHActive?._id) { await Users.openAgentBusinessHoursByBusinessHourIdsAndAgentId([isDefaultBHActive._id], agentId); - - bhLogger.debug({ - msg: 'Business hour status check passed for agentId. Found default business hour to be active and agent has no departments with non-default business hours', - agentId, - }); return; } } diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterForwardChatToDepartment.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterForwardChatToDepartment.ts index 8babfec041c7f..903fb8fd6928d 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterForwardChatToDepartment.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterForwardChatToDepartment.ts @@ -13,7 +13,6 @@ callbacks.add( projection: { departmentAncestors: 1 }, }); if (!room) { - cbLogger.debug('Skipping callback. No room found'); return options; } await LivechatRooms.unsetPredictedVisitorAbandonmentByRoomId(room._id); @@ -22,14 +21,12 @@ callbacks.add( projection: { ancestors: 1 }, }); if (!department) { - cbLogger.debug('Skipping callback. No department found'); return options; } const { departmentAncestors } = room; const { ancestors } = department; if (!ancestors && !departmentAncestors) { - cbLogger.debug('Skipping callback. No ancestors found for department'); return options; } diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterInquiryQueued.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterInquiryQueued.ts index d8f5878f01bb4..cb6993b38aec1 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterInquiryQueued.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterInquiryQueued.ts @@ -9,12 +9,10 @@ let timer = 0; const scheduleInquiry = async (inquiry: any): Promise => { if (!inquiry?._id) { - cbLogger.debug('Skipping callback. No inquiry provided'); return; } if (!inquiry?._updatedAt || !inquiry?._createdAt) { - cbLogger.debug('Skipping callback. Inquiry doesnt have timestamps'); return; } diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterOnHold.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterOnHold.ts index 99e69acd8ffe5..11a9593b0c374 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterOnHold.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterOnHold.ts @@ -11,12 +11,10 @@ let autoCloseOnHoldChatTimeout = 0; const handleAfterOnHold = async (room: Pick): Promise => { const { _id: rid } = room; if (!rid) { - cbLogger.debug('Skipping callback. No room provided'); return; } if (!autoCloseOnHoldChatTimeout || autoCloseOnHoldChatTimeout <= 0) { - cbLogger.debug('Skipping callback. Autoclose on hold disabled by setting'); return; } diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterOnHoldChatResumed.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterOnHoldChatResumed.ts index c631656a2a07a..0263efa5fe391 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterOnHoldChatResumed.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterOnHoldChatResumed.ts @@ -8,7 +8,6 @@ type IRoom = Pick; const handleAfterOnHoldChatResumed = async (room: IRoom): Promise => { if (!room?._id) { - cbLogger.debug('Skipping callback. No room provided'); return room; } diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterRemoveDepartment.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterRemoveDepartment.ts index be732be662972..26e176b03eb5b 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterRemoveDepartment.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterRemoveDepartment.ts @@ -5,7 +5,6 @@ import { callbacks } from '../../../../../lib/callbacks'; import { cbLogger } from '../lib/logger'; const afterRemoveDepartment = async (options: { department: ILivechatDepartmentRecord; agentsId: ILivechatAgent['_id'][] }) => { - cbLogger.debug(`Performing post-department-removal actions in EE: ${options?.department?._id}. Removing department from forward list`); if (!options?.department) { cbLogger.warn('No department found in options', options); return options; diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterReturnRoomAsInquiry.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterReturnRoomAsInquiry.ts index 1035a2f03286a..cecf6b5e7f4ae 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterReturnRoomAsInquiry.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterReturnRoomAsInquiry.ts @@ -3,7 +3,6 @@ import { LivechatRooms } from '@rocket.chat/models'; import { settings } from '../../../../../app/settings/server'; import { callbacks } from '../../../../../lib/callbacks'; -import { cbLogger } from '../lib/logger'; settings.watch('Livechat_abandoned_rooms_action', (value) => { if (!value || value === 'none') { @@ -14,7 +13,6 @@ settings.watch('Livechat_abandoned_rooms_action', (value) => { 'livechat:afterReturnRoomAsInquiry', ({ room }: { room: IOmnichannelRoom }) => { if (!room?._id || !room?.omnichannel?.predictedVisitorAbandonmentAt) { - cbLogger.debug('Skipping callback. No room or no visitor abandonment info'); return; } diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterTakeInquiry.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterTakeInquiry.ts index ee83facae6d4c..c5e55e030b65a 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterTakeInquiry.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/afterTakeInquiry.ts @@ -7,12 +7,10 @@ callbacks.add( 'livechat.afterTakeInquiry', async (inquiry) => { if (!settings.get('Livechat_waiting_queue')) { - cbLogger.debug('Skipping callback. Waiting queue disabled by setting'); return inquiry; } if (!inquiry) { - cbLogger.debug('Skipping callback. No inquiry provided'); return null; } diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/applyDepartmentRestrictions.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/applyDepartmentRestrictions.ts index 3c3b1aae61353..d609d8464b043 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/applyDepartmentRestrictions.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/applyDepartmentRestrictions.ts @@ -22,7 +22,6 @@ callbacks.add( 'livechat.applyDepartmentRestrictions', async (originalQuery: FilterOperators = {}, { userId }: { userId?: string | null } = { userId: null }) => { if (!userId || !(await hasRoleAsync(userId, 'livechat-monitor'))) { - cbLogger.debug('Skipping callback. No user id provided or user is not a monitor'); return originalQuery; } diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/applyRoomRestrictions.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/applyRoomRestrictions.ts index cacbd550ef04b..46df5cf210d54 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/applyRoomRestrictions.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/applyRoomRestrictions.ts @@ -3,7 +3,6 @@ import { LivechatDepartment } from '@rocket.chat/models'; import type { FilterOperators } from 'mongodb'; import { callbacks } from '../../../../../lib/callbacks'; -import { cbLogger } from '../lib/logger'; import { getUnitsFromUser } from '../lib/units'; export const restrictQuery = async (originalQuery: FilterOperators = {}) => { @@ -28,7 +27,6 @@ export const restrictQuery = async (originalQuery: FilterOperators = {}) => { - cbLogger.debug('Applying room query restrictions'); return restrictQuery(originalQuery); }, callbacks.priority.HIGH, diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/applySimultaneousChatsRestrictions.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/applySimultaneousChatsRestrictions.ts index 4dd7a032e7171..6d0c05fd39edb 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/applySimultaneousChatsRestrictions.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/applySimultaneousChatsRestrictions.ts @@ -3,7 +3,6 @@ import { LivechatDepartment } from '@rocket.chat/models'; import { settings } from '../../../../../app/settings/server'; import { callbacks } from '../../../../../lib/callbacks'; -import { cbLogger } from '../lib/logger'; callbacks.add( 'livechat.applySimultaneousChatRestrictions', @@ -16,7 +15,6 @@ callbacks.add( }) )?.maxNumberSimultaneousChat || 0; if (departmentLimit > 0) { - cbLogger.debug(`Applying department filters. Max chats per department ${departmentLimit}`); return { $match: { 'queueInfo.chats': { $gte: Number(departmentLimit) } } }; } } @@ -49,8 +47,6 @@ callbacks.add( : // dummy filter meaning: don't match anything { _id: '' }; - cbLogger.debug(`Applying agent & global filters. Max number of chats allowed to all agents by setting: ${maxChatsPerSetting}`); - return { $match: { $or: [agentFilter, globalFilter] } }; }, callbacks.priority.HIGH, diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/beforeForwardRoomToDepartment.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/beforeForwardRoomToDepartment.ts index 2503411d46c4f..5a16b7014bd6b 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/beforeForwardRoomToDepartment.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/beforeForwardRoomToDepartment.ts @@ -3,19 +3,16 @@ import { LivechatDepartment } from '@rocket.chat/models'; import { Meteor } from 'meteor/meteor'; import { callbacks } from '../../../../../lib/callbacks'; -import { cbLogger } from '../lib/logger'; callbacks.add( 'livechat.beforeForwardRoomToDepartment', async (options) => { const { room, transferData } = options; if (!room || !transferData) { - cbLogger.debug('Skipping callback. No room provided'); return options; } const { departmentId } = room; if (!departmentId) { - cbLogger.debug('Skipping callback. No department provided'); return options; } const { department: departmentToTransfer } = transferData; @@ -23,7 +20,6 @@ callbacks.add( projection: { departmentsAllowedToForward: 1 }, }); if (!currentDepartment) { - cbLogger.debug('Skipping callback. Current department does not exists'); return options; } const { departmentsAllowedToForward } = currentDepartment; @@ -31,7 +27,6 @@ callbacks.add( !departmentsAllowedToForward?.length || (Array.isArray(departmentsAllowedToForward) && departmentsAllowedToForward.includes(departmentToTransfer._id)); if (isAllowedToTransfer) { - cbLogger.debug(`Callback success. Room ${room._id} can be forwarded to department ${departmentToTransfer._id}`); return options; } throw new Meteor.Error('error-forwarding-department-target-not-allowed', 'The forwarding to the target department is not allowed.'); diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/beforeNewInquiry.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/beforeNewInquiry.ts index 21c38793734cf..e6d68df1aa965 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/beforeNewInquiry.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/beforeNewInquiry.ts @@ -3,7 +3,6 @@ import { LivechatPriority, OmnichannelServiceLevelAgreements } from '@rocket.cha import { Meteor } from 'meteor/meteor'; import { callbacks } from '../../../../../lib/callbacks'; -import { cbLogger } from '../lib/logger'; type Props = { sla?: string; @@ -14,7 +13,6 @@ type Props = { const beforeNewInquiry = async (extraData: Props) => { const { sla: slaSearchTerm, priority: prioritySearchTerm, ...props } = extraData; if (!slaSearchTerm && !prioritySearchTerm) { - cbLogger.debug('Skipping callback. No sla or priority provided'); return extraData; } @@ -54,7 +52,6 @@ const beforeNewInquiry = async (extraData: Props) => { changes.priorityId = priority._id; changes.priorityWeight = priority.sortItem; } - cbLogger.debug('Callback success. Queue timing properties added to inquiry', changes); return { ...props, ...changes }; }; diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/beforeRoutingChat.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/beforeRoutingChat.ts index 6d2071406260d..69c3914cb4d8f 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/beforeRoutingChat.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/beforeRoutingChat.ts @@ -16,7 +16,6 @@ callbacks.add( async (inquiry, agent) => { // check here if department has fallback before queueing if (inquiry?.department && !(await online(inquiry.department, true, true))) { - cbLogger.debug('No agents online on selected department. Inquiry will use fallback department'); const department = await LivechatDepartment.findOneById>( inquiry.department, { @@ -25,11 +24,10 @@ callbacks.add( ); if (!department) { - cbLogger.debug('No department found. Skipping'); return inquiry; } if (department.fallbackForwardDepartment) { - cbLogger.debug( + cbLogger.info( `Inquiry ${inquiry._id} will be moved from department ${department._id} to fallback department ${department.fallbackForwardDepartment}`, ); // update visitor @@ -41,31 +39,24 @@ callbacks.add( inquiry = (await LivechatInquiry.setDepartmentByInquiryId(inquiry._id, department.fallbackForwardDepartment)) ?? inquiry; // update room await LivechatRooms.setDepartmentByRoomId(inquiry.rid, department.fallbackForwardDepartment); - cbLogger.debug(`Inquiry ${inquiry._id} moved. Continue normal queue process`); - } else { - cbLogger.debug('No fallback department configured. Skipping'); } } if (!settings.get('Livechat_waiting_queue')) { - cbLogger.debug('Skipping callback. Waiting queue disabled by setting'); return inquiry; } if (!inquiry) { - cbLogger.debug('Skipping callback. No inquiry provided'); return inquiry; } const { _id, status, department } = inquiry; if (status !== 'ready') { - cbLogger.debug(`Skipping callback. Inquiry ${_id} is not ready`); return inquiry; } if (agent && (await allowAgentSkipQueue(agent))) { - cbLogger.debug(`Skipping callback. Agent ${agent.agentId} can skip queue`); return inquiry; } @@ -79,7 +70,6 @@ callbacks.add( }); if (inq) { await dispatchInquiryPosition(inq); - cbLogger.debug(`Callback success. Inquiry ${_id} position has been notified`); } } diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/checkAgentBeforeTakeInquiry.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/checkAgentBeforeTakeInquiry.ts index 7f566260cf047..55adb05cbd1cb 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/checkAgentBeforeTakeInquiry.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/checkAgentBeforeTakeInquiry.ts @@ -27,23 +27,20 @@ const validateMaxChats = async ({ }; }) => { if (!inquiry?._id || !agent?.agentId) { - cbLogger.debug('Callback with error. No inquiry or agent provided'); throw new Error('No inquiry or agent provided'); } const { agentId } = agent; if (!(await Livechat.checkOnlineAgents(undefined, agent))) { - cbLogger.debug('Callback with error. provided agent is not online'); throw new Error('Provided agent is not online'); } if (!settings.get('Livechat_waiting_queue')) { - cbLogger.debug('Skipping callback. Disabled by setting'); return agent; } if (await allowAgentSkipQueue(agent)) { - cbLogger.debug(`Callback success. Agent ${agent.agentId} can skip queue`); + cbLogger.info(`Chat can be taken by Agent ${agentId}: agent can skip queue`); return agent; } @@ -55,25 +52,23 @@ const validateMaxChats = async ({ }); if (maxNumberSimultaneousChat === 0) { - cbLogger.debug(`Callback success. Agent ${agentId} max number simultaneous chats on range`); + cbLogger.debug(`Chat can be taken by Agent ${agentId}: max number simultaneous chats on range`); return agent; } const user = await Users.getAgentAndAmountOngoingChats(agentId); if (!user) { - cbLogger.debug('Callback with error. No valid agent found'); throw new Error('No valid agent found'); } const { queueInfo: { chats = 0 } = {} } = user; const maxChats = typeof maxNumberSimultaneousChat === 'number' ? maxNumberSimultaneousChat : parseInt(maxNumberSimultaneousChat, 10); if (maxChats <= chats) { - cbLogger.debug('Callback with error. Agent reached max amount of simultaneous chats'); await callbacks.run('livechat.onMaxNumberSimultaneousChatsReached', inquiry); throw new Error('error-max-number-simultaneous-chats-reached'); } - cbLogger.debug(`Callback success. Agent ${agentId} can take inquiry ${inquiry._id}`); + cbLogger.debug(`Agent ${agentId} can take inquiry ${inquiry._id}`); return agent; }; diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/onAgentAssignmentFailed.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/onAgentAssignmentFailed.ts index f11d3b9514d61..d27f317d3b18e 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/onAgentAssignmentFailed.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/onAgentAssignmentFailed.ts @@ -2,7 +2,6 @@ import type { IOmnichannelRoom } from '@rocket.chat/core-typings'; import { settings } from '../../../../../app/settings/server'; import { callbacks } from '../../../../../lib/callbacks'; -import { cbLogger } from '../lib/logger'; const handleOnAgentAssignmentFailed = async ( room: IOmnichannelRoom, @@ -18,25 +17,21 @@ const handleOnAgentAssignmentFailed = async ( }, ) => { if (!inquiry || !room) { - cbLogger.debug('Skipping callback. No inquiry or room provided'); return; } if (!settings.get('Livechat_waiting_queue')) { - cbLogger.debug('Skipping callback. Queue disabled by setting'); return; } const { forwardingToDepartment: { oldDepartmentId } = {}, forwardingToDepartment } = options; if (!forwardingToDepartment) { - cbLogger.debug('Skipping callback. Room not being forwarded to department'); return; } const { department: newDepartmentId } = inquiry; if (!newDepartmentId || !oldDepartmentId || newDepartmentId === oldDepartmentId) { - cbLogger.debug('Skipping callback. New and old departments are the same'); return; } diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/onCloseLivechat.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/onCloseLivechat.ts index e68148ee825d9..4e76f396617bb 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/onCloseLivechat.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/onCloseLivechat.ts @@ -1,7 +1,6 @@ import type { IOmnichannelRoom } from '@rocket.chat/core-typings'; import { LivechatRooms, Subscriptions } from '@rocket.chat/models'; -import { callbackLogger } from '../../../../../app/livechat/server/lib/logger'; import { settings } from '../../../../../app/settings/server'; import { callbacks } from '../../../../../lib/callbacks'; import { AutoCloseOnHoldScheduler } from '../lib/AutoCloseOnHoldScheduler'; @@ -17,22 +16,17 @@ const onCloseLivechat = async (params: LivechatCloseCallbackParams) => { room: { _id: roomId }, } = params; - callbackLogger.debug(`[onCloseLivechat] clearing onHold related data for room ${roomId}`); - await Promise.all([ LivechatRooms.unsetOnHoldByRoomId(roomId), Subscriptions.unsetOnHoldByRoomId(roomId), AutoCloseOnHoldScheduler.unscheduleRoom(roomId), ]); - callbackLogger.debug(`[onCloseLivechat] clearing onHold related data for room ${roomId} completed`); - if (!settings.get('Livechat_waiting_queue')) { return params; } const { departmentId } = room || {}; - callbackLogger.debug(`[onCloseLivechat] dispatching waiting queue status for department ${departmentId}`); debouncedDispatchWaitingQueueStatus(departmentId); return params; diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/onLoadForwardDepartmentRestrictions.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/onLoadForwardDepartmentRestrictions.ts index 2d4dc52f9a32e..ef252c820ee4a 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/onLoadForwardDepartmentRestrictions.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/onLoadForwardDepartmentRestrictions.ts @@ -1,26 +1,22 @@ import { LivechatDepartment } from '@rocket.chat/models'; import { callbacks } from '../../../../../lib/callbacks'; -import { cbLogger } from '../lib/logger'; callbacks.add( 'livechat.onLoadForwardDepartmentRestrictions', async (options) => { const { departmentId } = options; if (!departmentId) { - cbLogger.debug('Skipping callback. No departmentId provided'); return options; } const department = await LivechatDepartment.findOneById(departmentId, { projection: { departmentsAllowedToForward: 1 }, }); if (!department) { - cbLogger.debug('Skipping callback. Invalid department provided'); return options; } - const { departmentsAllowedToForward, _id } = department; + const { departmentsAllowedToForward } = department; if (!departmentsAllowedToForward) { - cbLogger.debug(`Skipping callback. Department ${_id} doesnt allow forwarding to other departments`); return options; } return Object.assign({ restrictions: { _id: { $in: departmentsAllowedToForward } } }, options); diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/onSaveVisitorInfo.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/onSaveVisitorInfo.ts index 2e1b879458f83..9b3f79f6ce3f5 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/onSaveVisitorInfo.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/onSaveVisitorInfo.ts @@ -4,7 +4,6 @@ import { OmnichannelServiceLevelAgreements } from '@rocket.chat/models'; import { callbacks } from '../../../../../lib/callbacks'; import { removePriorityFromRoom, updateRoomPriority } from '../api/lib/priorities'; import { removeRoomSLA, updateRoomSLA } from '../api/lib/sla'; -import { cbLogger } from '../lib/logger'; const updateSLA = async (room: IOmnichannelRoom, user: Required>, slaId?: string) => { if (!slaId) { @@ -37,19 +36,13 @@ callbacks.add( const { slaId: newSlaId, priorityId: newPriorityId } = room; if (oldSlaId === newSlaId && oldPriorityId === newPriorityId) { - cbLogger.debug('No changes in SLA or Priority'); return room; } if (oldSlaId === newSlaId && oldPriorityId !== newPriorityId) { - cbLogger.debug(`Updating Priority for room ${room._id}, from ${oldPriorityId} to ${newPriorityId}`); await updatePriority(room, user, newPriorityId); } else if (oldSlaId !== newSlaId && oldPriorityId === newPriorityId) { - cbLogger.debug(`Updating SLA for room ${room._id}, from ${oldSlaId} to ${newSlaId}`); await updateSLA(room, user, newSlaId); } else { - cbLogger.debug( - `Updating SLA and Priority for room ${room._id}, from ${oldSlaId} to ${newSlaId} and from ${oldPriorityId} to ${newPriorityId}`, - ); await Promise.all([updateSLA(room, user, newSlaId), updatePriority(room, user, newPriorityId)]); } diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/onTransferFailure.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/onTransferFailure.ts index bd33cfe12bbd5..a667d45249261 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/onTransferFailure.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/onTransferFailure.ts @@ -21,10 +21,8 @@ const onTransferFailure = async ( return false; } - cbLogger.debug(`Attempting to transfer room ${room._id} using fallback departments`); const { departmentId } = transferData; if (!departmentId) { - cbLogger.debug(`No departmentId found in transferData`); return false; } @@ -39,14 +37,12 @@ const onTransferFailure = async ( return false; } - cbLogger.debug(`Fallback department ${department.fallbackForwardDepartment} found for department ${department._id}. Redirecting`); // TODO: find enabled not archived here const fallbackDepartment = await LivechatDepartment.findOneById(department.fallbackForwardDepartment, { projection: { name: 1, _id: 1 }, }); if (!fallbackDepartment) { - cbLogger.debug(`Fallback department ${department.fallbackForwardDepartment} not found`); return false; } @@ -80,6 +76,7 @@ const onTransferFailure = async ( ); } + cbLogger.info(`Fallback department ${department.fallbackForwardDepartment} found for department ${department._id}. Chat transfered`); return forwardSuccess; }; diff --git a/apps/meteor/ee/app/livechat-enterprise/server/hooks/scheduleAutoTransfer.ts b/apps/meteor/ee/app/livechat-enterprise/server/hooks/scheduleAutoTransfer.ts index 4a16316cb93e1..4039754a609ca 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/hooks/scheduleAutoTransfer.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/hooks/scheduleAutoTransfer.ts @@ -18,27 +18,23 @@ let autoTransferTimeout = 0; const handleAfterTakeInquiryCallback = async (inquiry: any = {}): Promise => { const { rid } = inquiry; if (!rid?.trim()) { - cbLogger.debug('Skipping callback. Invalid room id'); return; } if (!autoTransferTimeout || autoTransferTimeout <= 0) { - cbLogger.debug('Skipping callback. No auto transfer timeout or invalid value from setting'); return inquiry; } const room = await LivechatRooms.findOneById(rid, { projection: { _id: 1, autoTransferredAt: 1, autoTransferOngoing: 1 } }); if (!room) { - cbLogger.debug(`Skipping callback. Room ${rid} not found`); return inquiry; } if (room.autoTransferredAt || room.autoTransferOngoing) { - cbLogger.debug(`Skipping callback. Room ${room._id} already being transfered or not found`); return inquiry; } - cbLogger.debug(`Callback success. Room ${room._id} will be scheduled to be auto transfered after ${autoTransferTimeout} seconds`); + cbLogger.info(`Room ${room._id} will be scheduled to be auto transfered after ${autoTransferTimeout} seconds`); await AutoTransferChatScheduler.scheduleRoom(rid, autoTransferTimeout as number); return inquiry; diff --git a/apps/meteor/ee/app/livechat-enterprise/server/lib/AutoCloseOnHoldScheduler.ts b/apps/meteor/ee/app/livechat-enterprise/server/lib/AutoCloseOnHoldScheduler.ts index 0efda85e25a4e..c59c272825011 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/lib/AutoCloseOnHoldScheduler.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/lib/AutoCloseOnHoldScheduler.ts @@ -26,7 +26,6 @@ class AutoCloseOnHoldSchedulerClass { public async init(): Promise { if (this.running) { - this.logger.debug('Already running'); return; } @@ -38,7 +37,7 @@ class AutoCloseOnHoldSchedulerClass { await this.scheduler.start(); this.running = true; - this.logger.debug('Started'); + this.logger.info('Service started'); } public async scheduleRoom(roomId: string, timeout: number, comment: string): Promise { @@ -75,7 +74,6 @@ class AutoCloseOnHoldSchedulerClass { comment, }; - this.logger.debug(`Closing room ${roomId}`); await Livechat.closeRoom(payload); } diff --git a/apps/meteor/ee/app/livechat-enterprise/server/lib/AutoTransferChatScheduler.ts b/apps/meteor/ee/app/livechat-enterprise/server/lib/AutoTransferChatScheduler.ts index 7e52cc266c043..9d4590836ac96 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/lib/AutoTransferChatScheduler.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/lib/AutoTransferChatScheduler.ts @@ -28,7 +28,6 @@ class AutoTransferChatSchedulerClass { public async init(): Promise { if (this.running) { - this.logger.debug('Already running'); return; } @@ -40,7 +39,7 @@ class AutoTransferChatSchedulerClass { await this.scheduler.start(); this.running = true; - this.logger.debug('Started'); + this.logger.info('Service started'); } private async getSchedulerUser(): Promise { @@ -58,7 +57,6 @@ class AutoTransferChatSchedulerClass { this.scheduler.define(jobName, this.executeJob.bind(this)); await this.scheduler.schedule(when, jobName, { roomId }); await LivechatRooms.setAutoTransferOngoingById(roomId); - this.logger.debug(`Scheduled room ${roomId} to be transferred in ${timeout} seconds`); } public async unscheduleRoom(roomId: string): Promise { diff --git a/apps/meteor/ee/app/livechat-enterprise/server/lib/Helper.ts b/apps/meteor/ee/app/livechat-enterprise/server/lib/Helper.ts index af517312348da..08ea48910f020 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/lib/Helper.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/lib/Helper.ts @@ -17,7 +17,7 @@ import { callbacks } from '../../../../../lib/callbacks'; import { OmnichannelQueueInactivityMonitor } from './QueueInactivityMonitor'; import { updateInquiryQueueSla } from './SlaHelper'; import { memoizeDebounce } from './debounceByParams'; -import { logger, helperLogger } from './logger'; +import { logger } from './logger'; type QueueInfo = { message: { @@ -124,7 +124,6 @@ const dispatchWaitingQueueStatus = async (department?: string) => { return; } - helperLogger.debug(`Updating statuses for queue ${department || 'Public'}`); const queue = await LivechatInquiry.getCurrentSortedQueueAsync({ department, queueSortBy: getInquirySortMechanismSetting(), @@ -186,12 +185,10 @@ export const updatePredictedVisitorAbandonment = async () => { export const updateQueueInactivityTimeout = async () => { const queueTimeout = settings.get('Livechat_max_queue_wait_time'); if (queueTimeout <= 0) { - logger.debug('QueueInactivityTimer: Disabling scheduled closing'); await OmnichannelQueueInactivityMonitor.stop(); return; } - logger.debug('QueueInactivityTimer: Updating estimated inactivity time for queued items'); await LivechatInquiry.getQueuedInquiries({ projection: { _updatedAt: 1 } }).forEach((inq) => { const aggregatedDate = moment(inq._updatedAt).add(queueTimeout, 'minutes'); try { diff --git a/apps/meteor/ee/app/livechat-enterprise/server/lib/QueueInactivityMonitor.ts b/apps/meteor/ee/app/livechat-enterprise/server/lib/QueueInactivityMonitor.ts index d7ad14251d3f7..df975a3690be1 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/lib/QueueInactivityMonitor.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/lib/QueueInactivityMonitor.ts @@ -69,6 +69,7 @@ class OmnichannelQueueInactivityMonitorClass { } await this.scheduler.start(); + this.logger.info('Service started'); this.running = true; } @@ -108,21 +109,18 @@ class OmnichannelQueueInactivityMonitorClass { async closeRoom({ attrs: { data } }: any = {}): Promise { const { inquiryId } = data; const inquiry = await LivechatInquiryRaw.findOneById(inquiryId); - this.logger.debug(`Processing inquiry item ${inquiryId}`); if (!inquiry || inquiry.status !== 'queued') { - this.logger.debug(`Skipping inquiry ${inquiryId}. Invalid or not queued anymore`); return; } const room = await LivechatRooms.findOneById(inquiry.rid); if (!room) { - this.logger.error(`Error: unable to find room ${inquiry.rid} for inquiry ${inquiryId} to close in queue inactivity monitor`); + this.logger.error(`Unable to find room ${inquiry.rid} for inquiry ${inquiryId} to close in queue inactivity monitor`); return; } await Promise.all([this.closeRoomAction(room), this.stopInquiry(inquiryId)]); - - this.logger.debug(`Running successful. Closed inquiry ${inquiry._id} because of inactivity`); + this.logger.info(`Closed room ${inquiry.rid} for inquiry ${inquiryId} due to inactivity`); } } diff --git a/apps/meteor/ee/app/livechat-enterprise/server/lib/VisitorInactivityMonitor.ts b/apps/meteor/ee/app/livechat-enterprise/server/lib/VisitorInactivityMonitor.ts index 8947ecf62081b..824296d1e6733 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/lib/VisitorInactivityMonitor.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/lib/VisitorInactivityMonitor.ts @@ -33,7 +33,6 @@ export class VisitorInactivityMonitor { } async start() { - this.logger.debug('Starting'); await this._startMonitoring(); this._initializeMessageCache(); const cat = await Users.findOneById('rocket.cat'); @@ -50,18 +49,17 @@ export class VisitorInactivityMonitor { const everyMinute = '* * * * *'; await this.scheduler.add(this._name, everyMinute, async () => this.handleAbandonedRooms()); this._started = true; - this.logger.debug('Started'); + this.logger.info('Service started'); } async stop() { if (!this.isRunning()) { - this.logger.debug('Not running'); return; } await this.scheduler.remove(this._name); this._started = false; - this.logger.debug('Stopped'); + this.logger.info('Service stopped'); } isRunning() { @@ -73,9 +71,7 @@ export class VisitorInactivityMonitor { } async _getDepartmentAbandonedCustomMessage(departmentId: string) { - this.logger.debug(`Getting department abandoned custom message for department ${departmentId}`); if (this.messageCache.has(departmentId)) { - this.logger.debug(`Using cached department abandoned custom message for department ${departmentId}`); return this.messageCache.get(departmentId); } const department = await LivechatDepartment.findOneById>( @@ -83,16 +79,14 @@ export class VisitorInactivityMonitor { { projection: { _id: 1, abandonedRoomsCloseCustomMessage: 1 } }, ); if (!department) { - this.logger.debug(`Department ${departmentId} not found`); + this.logger.error(`Department ${departmentId} not found`); return; } - this.logger.debug(`Setting department abandoned custom message for department ${departmentId}`); this.messageCache.set(department._id, department.abandonedRoomsCloseCustomMessage); return department.abandonedRoomsCloseCustomMessage; } async closeRooms(room: IOmnichannelRoom) { - this.logger.debug(`Closing room ${room._id}`); let comment = await this.getDefaultAbandonedCustomMessage('close', room.v._id); if (room.departmentId) { comment = (await this._getDepartmentAbandonedCustomMessage(room.departmentId)) || comment; @@ -102,29 +96,24 @@ export class VisitorInactivityMonitor { room, user: this.user, }); - this.logger.debug(`Room ${room._id} closed`); + this.logger.info(`Room ${room._id} closed`); } async placeRoomOnHold(room: IOmnichannelRoom) { - this.logger.debug(`Placing room ${room._id} on hold`); - const comment = await this.getDefaultAbandonedCustomMessage('on-hold', room.v._id); const result = await Promise.allSettled([ OmnichannelEEService.placeRoomOnHold(room, comment, this.user), LivechatRooms.unsetPredictedVisitorAbandonmentByRoomId(room._id), ]); - this.logger.debug(`Room ${room._id} placed on hold`); const rejected = result.filter(isPromiseRejectedResult).map((r) => r.reason); if (rejected.length) { this.logger.error({ msg: 'Error placing room on hold', error: rejected }); - throw new Error('Error placing room on hold. Please check logs for more details.'); } } async handleAbandonedRooms() { - this.logger.debug('Handling abandoned rooms'); const action = settings.get('Livechat_abandoned_rooms_action'); if (!action || action === 'none') { return; @@ -135,12 +124,12 @@ export class VisitorInactivityMonitor { await LivechatRooms.findAbandonedOpenRooms(new Date(), extraQuery).forEach((room) => { switch (action) { case 'close': { - this.logger.debug(`Closing room ${room._id}`); + this.logger.info(`Closing room ${room._id}`); promises.push(this.closeRooms(room)); break; } case 'on-hold': { - this.logger.debug(`Placing room ${room._id} on hold`); + this.logger.info(`Placing room ${room._id} on hold`); promises.push(this.placeRoomOnHold(room)); break; } @@ -153,7 +142,6 @@ export class VisitorInactivityMonitor { if (errors.length) { this.logger.error({ msg: `Error while removing priority from ${errors.length} rooms`, reason: errors[0] }); - this.logger.debug({ msg: 'Rejection results', errors }); } this._initializeMessageCache(); diff --git a/apps/meteor/ee/app/livechat-enterprise/server/services/omnichannel.internalService.ts b/apps/meteor/ee/app/livechat-enterprise/server/services/omnichannel.internalService.ts index e9911ffe246ca..3ef9633267c89 100644 --- a/apps/meteor/ee/app/livechat-enterprise/server/services/omnichannel.internalService.ts +++ b/apps/meteor/ee/app/livechat-enterprise/server/services/omnichannel.internalService.ts @@ -54,8 +54,6 @@ export class OmnichannelEE extends ServiceClassInternal implements IOmnichannelE ]); await callbacks.run('livechat:afterOnHold', room); - - this.logger.debug(`Room ${room._id} set on hold successfully`); } async resumeRoomOnHold( @@ -105,8 +103,6 @@ export class OmnichannelEE extends ServiceClassInternal implements IOmnichannelE ]); await callbacks.run('livechat:afterOnHoldChatResumed', room); - - this.logger.debug(`Room ${room._id} resumed successfully`); } private async attemptToAssignRoomToServingAgentElseQueueIt({ @@ -134,7 +130,7 @@ export class OmnichannelEE extends ServiceClassInternal implements IOmnichannelE return; } catch (e) { - this.logger.debug(`Agent ${servingAgent._id} is not available to take the inquiry ${inquiry._id}`, e); + this.logger.error(`Agent ${servingAgent._id} is not available to take the inquiry ${inquiry._id}`, e); if (clientAction) { // if the action was triggered by the client, we should throw the error // so the client can handle it and show the error message to the user @@ -142,20 +138,15 @@ export class OmnichannelEE extends ServiceClassInternal implements IOmnichannelE } } - this.logger.debug(`Attempting to queue inquiry ${inquiry._id}`); - await this.removeCurrentAgentFromRoom({ room, inquiry }); const { _id: inquiryId } = inquiry; const newInquiry = await LivechatInquiry.findOneById(inquiryId); if (!newInquiry) { - this.logger.error(`No inquiry found for id ${inquiryId}`); throw new Error('error-invalid-inquiry'); } await queueInquiry(newInquiry); - - this.logger.debug('Room queued successfully'); } private async removeCurrentAgentFromRoom({ @@ -178,7 +169,5 @@ export class OmnichannelEE extends ServiceClassInternal implements IOmnichannelE ]); await dispatchAgentDelegated(roomId); - - this.logger.debug(`Current agent removed from room ${room._id} successfully`); } } diff --git a/apps/meteor/ee/server/models/raw/LivechatRooms.ts b/apps/meteor/ee/server/models/raw/LivechatRooms.ts index 3fc8dd84954b3..b39e3d9eacfa1 100644 --- a/apps/meteor/ee/server/models/raw/LivechatRooms.ts +++ b/apps/meteor/ee/server/models/raw/LivechatRooms.ts @@ -11,7 +11,7 @@ import type { FindCursor, UpdateResult, Document, FindOptions, Db, Collection, F import { readSecondaryPreferred } from '../../../../server/database/readSecondaryPreferred'; import { LivechatRoomsRaw } from '../../../../server/models/raw/LivechatRooms'; -import { queriesLogger } from '../../../app/livechat-enterprise/server/lib/logger'; +import { addQueryRestrictionsToRoomsModel } from '../../../app/livechat-enterprise/server/lib/query.helper'; declare module '@rocket.chat/model-typings' { interface ILivechatRoomsModel { @@ -270,25 +270,14 @@ export class LivechatRoomsRawEE extends LivechatRoomsRaw implements ILivechatRoo ], }; const update = { $set: { departmentAncestors: [unitId] } }; - queriesLogger.debug({ msg: `LivechatRoomsRawEE.associateRoomsWithDepartmentToUnit - association step`, query, update }); - const associationResult = await this.updateMany(query, update); - queriesLogger.debug({ msg: `LivechatRoomsRawEE.associateRoomsWithDepartmentToUnit - association step`, result: associationResult }); + await this.updateMany(query, update); const queryToDisassociateOldRoomsConnectedToUnit = { departmentAncestors: unitId, departmentId: { $nin: departments }, }; const updateToDisassociateRooms = { $unset: { departmentAncestors: 1 } }; - queriesLogger.debug({ - msg: `LivechatRoomsRawEE.associateRoomsWithDepartmentToUnit - disassociation step`, - query: queryToDisassociateOldRoomsConnectedToUnit, - update: updateToDisassociateRooms, - }); - const disassociationResult = await this.updateMany(queryToDisassociateOldRoomsConnectedToUnit, updateToDisassociateRooms); - queriesLogger.debug({ - msg: `LivechatRoomsRawEE.associateRoomsWithDepartmentToUnit - disassociation step`, - result: disassociationResult, - }); + await this.updateMany(queryToDisassociateOldRoomsConnectedToUnit, updateToDisassociateRooms); } async removeUnitAssociationFromRooms(unitId: string): Promise { @@ -296,9 +285,7 @@ export class LivechatRoomsRawEE extends LivechatRoomsRaw implements ILivechatRoo departmentAncestors: unitId, }; const update = { $unset: { departmentAncestors: 1 } }; - queriesLogger.debug({ msg: `LivechatRoomsRawEE.removeUnitAssociationFromRooms`, query, update }); - const result = await this.updateMany(query, update); - queriesLogger.debug({ msg: `LivechatRoomsRawEE.removeUnitAssociationFromRooms`, result }); + await this.updateMany(query, update); } async updateDepartmentAncestorsById(rid: string, departmentAncestors?: string[]) { @@ -309,6 +296,32 @@ export class LivechatRoomsRawEE extends LivechatRoomsRaw implements ILivechatRoo return this.updateOne(query, update); } + /** @deprecated Use updateOne or updateMany instead */ + async update(...args: Parameters) { + const [query, ...restArgs] = args; + const restrictedQuery = await addQueryRestrictionsToRoomsModel(query); + return super.update(restrictedQuery, ...restArgs); + } + + async updateOne(...args: [...Parameters, { bypassUnits?: boolean }?]) { + const [query, update, opts, extraOpts] = args; + if (extraOpts?.bypassUnits) { + // When calling updateOne from a service, we cannot call the meteor code inside the query restrictions + // So the solution now is to pass a bypassUnits flag to the updateOne method which prevents checking + // units restrictions on the query, but just for the query the service is actually using + // We need to find a way of remove the meteor dependency when fetching units, and then, we can remove this flag + return super.updateOne(query, update, opts); + } + const restrictedQuery = await addQueryRestrictionsToRoomsModel(query); + return super.updateOne(restrictedQuery, update, opts); + } + + async updateMany(...args: Parameters) { + const [query, ...restArgs] = args; + const restrictedQuery = await addQueryRestrictionsToRoomsModel(query); + return super.updateMany(restrictedQuery, ...restArgs); + } + getConversationsBySource(start: Date, end: Date, extraQuery: Filter): AggregationCursor { return this.col.aggregate( [ diff --git a/apps/meteor/ee/server/models/raw/LivechatUnit.ts b/apps/meteor/ee/server/models/raw/LivechatUnit.ts index aaceb4437699f..180b145e43520 100644 --- a/apps/meteor/ee/server/models/raw/LivechatUnit.ts +++ b/apps/meteor/ee/server/models/raw/LivechatUnit.ts @@ -4,7 +4,6 @@ import { LivechatUnitMonitors, LivechatDepartment, LivechatRooms } from '@rocket import type { FindOptions, Filter, FindCursor, Db, FilterOperators, UpdateResult, DeleteResult, Document, UpdateFilter } from 'mongodb'; import { BaseRaw } from '../../../../server/models/raw/BaseRaw'; -import { queriesLogger } from '../../../app/livechat-enterprise/server/lib/logger'; import { getUnitsFromUser } from '../../../app/livechat-enterprise/server/lib/units'; const addQueryRestrictions = async (originalQuery: Filter = {}) => { @@ -40,7 +39,6 @@ export class LivechatUnitRaw extends BaseRaw implement options: FindOptions, ): Promise> { const query = await addQueryRestrictions(originalQuery); - queriesLogger.debug({ msg: 'LivechatUnit.find', query }); return this.col.find(query, options) as FindCursor; } @@ -50,10 +48,18 @@ export class LivechatUnitRaw extends BaseRaw implement options: FindOptions, ): Promise { const query = await addQueryRestrictions(originalQuery); - queriesLogger.debug({ msg: 'LivechatUnit.findOne', query }); return this.col.findOne(query, options); } + async update( + originalQuery: Filter, + update: Filter, + options: FindOptions, + ): Promise { + const query = await addQueryRestrictions(originalQuery); + return this.col.updateOne(query, update, options); + } + remove(query: Filter): Promise { return this.deleteMany(query); } diff --git a/apps/meteor/server/features/EmailInbox/EmailInbox_Incoming.ts b/apps/meteor/server/features/EmailInbox/EmailInbox_Incoming.ts index 44302ae9ff91a..d71190cb0b6d2 100644 --- a/apps/meteor/server/features/EmailInbox/EmailInbox_Incoming.ts +++ b/apps/meteor/server/features/EmailInbox/EmailInbox_Incoming.ts @@ -25,18 +25,10 @@ const language = settings.get('Language') || 'en'; const t = (s: string): string => i18n.t(s, { lng: language }); async function getGuestByEmail(email: string, name: string, department = ''): Promise { - logger.debug(`Attempt to register a guest for ${email} on department: ${department}`); const guest = await LivechatVisitors.findOneGuestByEmailAddress(email); if (guest) { - logger.debug(`Guest with email ${email} found with id ${guest._id}`); if (guest.department !== department) { - logger.debug({ - msg: 'Switching departments for guest', - guest, - previousDepartment: guest.department, - newDepartment: department, - }); if (!department) { await LivechatVisitors.removeDepartmentById(guest._id); delete guest.department; @@ -48,10 +40,6 @@ async function getGuestByEmail(email: string, name: string, department = ''): Pr return guest; } - logger.debug({ - msg: 'Creating a new Omnichannel guest for visitor with email', - email, - }); const userId = await LivechatTyped.registerGuest({ token: Random.id(), name: name || email, @@ -60,7 +48,6 @@ async function getGuestByEmail(email: string, name: string, department = ''): Pr }); const newGuest = await LivechatVisitors.findOneById(userId); - logger.debug(`Guest ${userId} for visitor ${email} created`); if (newGuest) { return newGuest; } @@ -111,7 +98,7 @@ async function uploadAttachment(attachmentParam: Attachment, rid: string, visito } export async function onEmailReceived(email: ParsedMail, inbox: string, department = ''): Promise { - logger.debug(`New email conversation received on inbox ${inbox}. Will be assigned to department ${department}`); + logger.info(`New email conversation received on inbox ${inbox}. Will be assigned to department ${department}`); if (!email.from?.value?.[0]?.address) { return; } @@ -119,19 +106,13 @@ export async function onEmailReceived(email: ParsedMail, inbox: string, departme const references = typeof email.references === 'string' ? [email.references] : email.references; const initialRef = [email.messageId, email.inReplyTo].filter(Boolean) as string[]; const thread = (references?.length ? references : []).flatMap((t: string) => t.split(',')).concat(initialRef); - - logger.debug(`Received new email conversation with thread ${thread} on inbox ${inbox} from ${email.from.value[0].address}`); - - logger.debug(`Fetching guest for visitor ${email.from.value[0].address}`); const guest = await getGuestByEmail(email.from.value[0].address, email.from.value[0].name, department); if (!guest) { - logger.debug(`No visitor found for ${email.from.value[0].address}`); + logger.error(`No visitor found for ${email.from.value[0].address}`); return; } - logger.debug(`Guest ${guest._id} obtained. Attempting to find or create a room on department ${department}`); - let room: IOmnichannelRoom | null = await LivechatRooms.findOneByVisitorTokenAndEmailThreadAndDepartment( guest.token, thread, @@ -146,7 +127,6 @@ export async function onEmailReceived(email: ParsedMail, inbox: string, departme }); if (room?.closedAt) { - logger.debug(`Room ${room?._id} is closed. Reopening`); room = await QueueManager.unarchiveRoom(room); } @@ -166,8 +146,6 @@ export async function onEmailReceived(email: ParsedMail, inbox: string, departme const rid = room?._id ?? Random.id(); const msgId = Random.id(); - logger.debug(`Sending email message to room ${rid} for visitor ${guest._id}. Conversation assigned to department ${department}`); - Livechat.sendMessage({ guest, message: { @@ -242,7 +220,7 @@ export async function onEmailReceived(email: ParsedMail, inbox: string, departme try { attachments.push(await uploadAttachment(attachment, rid, guest.token)); } catch (err) { - Livechat.logger.error({ msg: 'Error uploading attachment from email', err }); + logger.error({ msg: 'Error uploading attachment from email', err }); } } @@ -259,7 +237,7 @@ export async function onEmailReceived(email: ParsedMail, inbox: string, departme room && (await LivechatRooms.updateEmailThreadByRoomId(room._id, thread)); }) .catch((err) => { - Livechat.logger.error({ + logger.error({ msg: 'Error receiving email', err, }); diff --git a/apps/meteor/server/features/EmailInbox/EmailInbox_Outgoing.ts b/apps/meteor/server/features/EmailInbox/EmailInbox_Outgoing.ts index dccf8315acd33..61ca75aa65d44 100644 --- a/apps/meteor/server/features/EmailInbox/EmailInbox_Outgoing.ts +++ b/apps/meteor/server/features/EmailInbox/EmailInbox_Outgoing.ts @@ -75,7 +75,7 @@ async function sendEmail(inbox: Inbox, mail: Mail.Options, options?: any): Promi ...mail, }) .then((info) => { - logger.info('Message sent: %s', info.messageId); + logger.info({ msg: 'Message sent', info }); return info; }) .catch(async (err) => { @@ -92,7 +92,6 @@ async function sendEmail(inbox: Inbox, mail: Mail.Options, options?: any): Promi slashCommands.add({ command: 'sendEmailAttachment', callback: async ({ command, params }: SlashCommandCallbackParams<'sendEmailAttachment'>) => { - logger.debug('sendEmailAttachment command: ', command, params); if (command !== 'sendEmailAttachment' || !Match.test(params, String)) { return; } @@ -318,7 +317,6 @@ export async function sendTestEmailToInbox(emailInboxRecord: IEmailInbox, user: throw new Error('user-without-verified-email'); } - logger.info(`Sending testing email to ${address}`); void sendEmail(inbox, { to: address, subject: 'Test of inbox configuration', diff --git a/apps/meteor/server/services/omnichannel-voip/service.ts b/apps/meteor/server/services/omnichannel-voip/service.ts index 532bb5d245e98..3e492a4d6514d 100644 --- a/apps/meteor/server/services/omnichannel-voip/service.ts +++ b/apps/meteor/server/services/omnichannel-voip/service.ts @@ -32,10 +32,8 @@ export class OmnichannelVoipService extends ServiceClassInternal implements IOmn // handle agent disconnections this.onEvent('watch.pbxevents', async ({ data }) => { - this.logger.debug(`Get event watch.pbxevents on service`); const extension = data.agentExtension; if (!extension) { - this.logger.debug(`No agent extension associated with the event. Skipping`); return; } switch (data.event) { @@ -53,12 +51,12 @@ export class OmnichannelVoipService extends ServiceClassInternal implements IOmn this.logger.info(`Processing hangup event for call with agent on extension ${extension}`); const agent = await Users.findOneByExtension(extension); if (!agent) { - this.logger.debug(`No agent found with extension ${extension}. Event won't proceed`); + this.logger.error(`No agent found with extension ${extension}. Event won't proceed`); return; } const currentRoom = await VoipRoom.findOneByAgentId(agent._id); if (!currentRoom) { - this.logger.debug(`No active call found for agent ${agent._id}`); + this.logger.error(`No active call found for agent ${agent._id}`); return; } this.logger.debug(`Notifying agent ${agent._id} of hangup on room ${currentRoom._id}`); @@ -69,7 +67,7 @@ export class OmnichannelVoipService extends ServiceClassInternal implements IOmn this.logger.info(`Processing disconnection event for agent with extension ${extension}`); const agent = await Users.findOneByExtension(extension); if (!agent) { - this.logger.debug(`No agent found with extension ${extension}. Event won't proceed`); + this.logger.error(`No agent found with extension ${extension}. Event won't proceed`); // this should not even be possible, but just in case return; } @@ -96,8 +94,6 @@ export class OmnichannelVoipService extends ServiceClassInternal implements IOmn const { _id, department: departmentId } = guest; const newRoomAt = new Date(); - this.logger.debug(`Creating Voip room for visitor ${_id}`); - /** * This is a peculiar case for outbound. In case of outbound, * the room is created as soon as the remote use accepts a call. @@ -182,7 +178,6 @@ export class OmnichannelVoipService extends ServiceClassInternal implements IOmn _updatedAt: newRoomAt, }; - this.logger.debug(`Room created for visitor ${_id}`); return (await VoipRoom.insertOne(room)).insertedId; } @@ -234,11 +229,9 @@ export class OmnichannelVoipService extends ServiceClassInternal implements IOmn direction: IVoipRoom['direction'], options: FindOptions = {}, ): Promise { - this.logger.debug(`Attempting to find or create a room for visitor ${guest._id}`); let room = await VoipRoom.findOneById(rid, options); let newRoom = false; if (room && !room.open) { - this.logger.debug(`Last room for visitor ${guest._id} closed. Creating new one`); room = null; } if (room == null) { @@ -246,10 +239,8 @@ export class OmnichannelVoipService extends ServiceClassInternal implements IOmn const roomId = await this.createVoipRoom(rid, name, agent, guest, direction); room = await VoipRoom.findOneVoipRoomById(roomId); newRoom = true; - this.logger.debug(`Room obtained for visitor ${guest._id} -> ${room?._id}`); } if (!room) { - this.logger.debug(`Visitor ${guest._id} trying to access another visitor's room`); throw new Error('cannot-access-room'); } return { @@ -281,7 +272,6 @@ export class OmnichannelVoipService extends ServiceClassInternal implements IOmn sysMessageId: 'voip-call-wrapup' | 'voip-call-ended-unexpectedly' = 'voip-call-wrapup', options?: { comment?: string; tags?: string[] }, ): Promise { - this.logger.debug(`Attempting to close room ${room._id}`); if (!room || room.t !== 'v' || !room.open) { return false; } @@ -298,8 +288,6 @@ export class OmnichannelVoipService extends ServiceClassInternal implements IOmn // For now, this data will be appended as a metric on room closing await this.setCallWaitingQueueTimers(room); - this.logger.debug(`Room ${room._id} closed and timers set`); - this.logger.debug(`Room ${room._id} was closed at ${closeInfo.closedAt} (duration ${closeInfo.callDuration})`); await VoipRoom.closeByRoomId(room._id, closeInfo); return true; @@ -452,8 +440,6 @@ export class OmnichannelVoipService extends ServiceClassInternal implements IOmn }, }; - this.logger.debug(`Handling event ${event} on room ${room._id}`); - if ( isVoipRoom(room) && room.open && @@ -461,7 +447,6 @@ export class OmnichannelVoipService extends ServiceClassInternal implements IOmn // Check if call exists by looking if we have pbx events of it (await PbxEvents.findOneByUniqueId(room.callUniqueId)) ) { - this.logger.debug(`Room is valid. Sending event ${event}`); await sendMessage(user, message, room); } else { this.logger.warn({ msg: 'Invalid room type or event type', type: room.t, event }); diff --git a/apps/meteor/server/services/omnichannel/queue.ts b/apps/meteor/server/services/omnichannel/queue.ts index 684c10161a94a..cbedf1cdcdec4 100644 --- a/apps/meteor/server/services/omnichannel/queue.ts +++ b/apps/meteor/server/services/omnichannel/queue.ts @@ -20,24 +20,23 @@ export class OmnichannelQueue implements IOmnichannelQueue { } async start() { - queueLogger.debug('Starting queue'); if (this.running) { - queueLogger.debug('Queue already running'); return; } const activeQueues = await this.getActiveQueues(); queueLogger.debug(`Active queues: ${activeQueues.length}`); - this.running = true; + + queueLogger.info('Service started'); return this.execute(); } async stop() { - queueLogger.debug('Stopping queue'); await LivechatInquiry.unlockAll(); this.running = false; + queueLogger.info('Service stopped'); } private async getActiveQueues() { @@ -62,7 +61,7 @@ export class OmnichannelQueue implements IOmnichannelQueue { const queue = await this.nextQueue(); const queueDelayTimeout = this.delay(); - queueLogger.debug(`Executing queue ${queue || 'Public'} with timeout of ${queueDelayTimeout}`); + queueLogger.info(`Executing queue ${queue || 'Public'} with timeout of ${queueDelayTimeout}`); setTimeout(this.checkQueue.bind(this, queue), queueDelayTimeout); } diff --git a/ee/packages/omnichannel-services/src/OmnichannelTranscript.ts b/ee/packages/omnichannel-services/src/OmnichannelTranscript.ts index 899d298fb4451..ce21e963911b3 100644 --- a/ee/packages/omnichannel-services/src/OmnichannelTranscript.ts +++ b/ee/packages/omnichannel-services/src/OmnichannelTranscript.ts @@ -222,7 +222,7 @@ export class OmnichannelTranscript extends ServiceClass implements IOmnichannelT } let file = message.files?.map((v) => ({ _id: v._id, name: v.name })).find((file) => file.name === attachment.title); if (!file) { - this.log.debug(`File ${attachment.title} not found in room ${message.rid}!`); + this.log.warn(`File ${attachment.title} not found in room ${message.rid}!`); // For some reason, when an image is uploaded from clipboard, it doesn't have a file :( // So, we'll try to get the FILE_ID from the `title_link` prop which has the format `/file-upload/FILE_ID/FILE_NAME` using a regex const fileId = attachment.title_link?.match(/\/file-upload\/(.*)\/.*/)?.[1]; @@ -236,7 +236,7 @@ export class OmnichannelTranscript extends ServiceClass implements IOmnichannelT } if (!file) { - this.log.error(`File ${attachment.title} not found in room ${message.rid}!`); + this.log.warn(`File ${attachment.title} not found in room ${message.rid}!`); // ignore attachments without file files.push({ name: attachment.title, buffer: null }); continue;