Skip to content

Commit

Permalink
regression: Inquiries not showing "over MAC limit" indicator (#30763)
Browse files Browse the repository at this point in the history
  • Loading branch information
aleksandernsilva authored Nov 1, 2023
1 parent 3c19109 commit 589c451
Show file tree
Hide file tree
Showing 15 changed files with 62 additions and 38 deletions.
1 change: 1 addition & 0 deletions apps/meteor/app/livechat/server/api/lib/livechat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export function findGuest(token: string): Promise<ILivechatVisitor | null> {
token: 1,
visitorEmails: 1,
department: 1,
activity: 1,
},
});
}
Expand Down
11 changes: 9 additions & 2 deletions apps/meteor/app/livechat/server/hooks/markRoomResponded.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { IOmnichannelRoom } from '@rocket.chat/core-typings';
import { isOmnichannelRoom, isEditedMessage } from '@rocket.chat/core-typings';
import { LivechatRooms, LivechatVisitors } from '@rocket.chat/models';
import { LivechatRooms, LivechatVisitors, LivechatInquiry } from '@rocket.chat/models';
import moment from 'moment';

import { callbacks } from '../../../../lib/callbacks';
Expand Down Expand Up @@ -30,11 +30,18 @@ callbacks.add(
// Return YYYY-MM from moment
const monthYear = moment().format('YYYY-MM');
const isVisitorActive = await LivechatVisitors.isVisitorActiveOnPeriod(room.v._id, monthYear);

// Case: agent answers & visitor is not active, we mark visitor as active
if (!isVisitorActive) {
await LivechatVisitors.markVisitorActiveForPeriod(room.v._id, monthYear);
}

await LivechatRooms.markVisitorActiveForPeriod(room._id, monthYear);
if (!room.v?.activity?.includes(monthYear)) {
await Promise.all([
LivechatRooms.markVisitorActiveForPeriod(room._id, monthYear),
LivechatInquiry.markInquiryActiveForPeriod(room._id, monthYear),
]);
}

if (room.responseBy) {
await LivechatRooms.setAgentLastMessageTs(room._id);
Expand Down
18 changes: 14 additions & 4 deletions apps/meteor/app/livechat/server/lib/Helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,11 @@ export const createLivechatRoom = async (
const { _id, username, token, department: departmentId, status = 'online' } = guest;
const newRoomAt = new Date();

logger.debug(`Creating livechat room for visitor ${_id}`);
const { activity } = guest;
logger.debug({
msg: `Creating livechat room for visitor ${_id}`,
visitor: { _id, username, departmentId, status, activity },
});

const room: InsertionModel<IOmnichannelRoom> = Object.assign(
{
Expand All @@ -94,6 +98,7 @@ export const createLivechatRoom = async (
username,
token,
status,
...(activity?.length && { activity }),
},
cl: false,
open: true,
Expand Down Expand Up @@ -132,7 +137,7 @@ export const createLivechatInquiry = async ({
}: {
rid: string;
name?: string;
guest?: Pick<ILivechatVisitor, '_id' | 'username' | 'status' | 'department' | 'name' | 'token'>;
guest?: Pick<ILivechatVisitor, '_id' | 'username' | 'status' | 'department' | 'name' | 'token' | 'activity'>;
message?: Pick<IMessage, 'msg'>;
initialStatus?: LivechatInquiryStatus;
extraData?: Pick<ILivechatInquiryRecord, 'source'>;
Expand All @@ -146,6 +151,7 @@ export const createLivechatInquiry = async ({
username: String,
status: Match.Maybe(String),
department: Match.Maybe(String),
activity: Match.Maybe([String]),
}),
);
check(
Expand All @@ -157,11 +163,14 @@ export const createLivechatInquiry = async ({

const extraInquiryInfo = await callbacks.run('livechat.beforeInquiry', extraData);

const { _id, username, token, department, status = UserStatus.ONLINE } = guest;
const { _id, username, token, department, status = UserStatus.ONLINE, activity } = guest;
const { msg } = message;
const ts = new Date();

logger.debug(`Creating livechat inquiry for visitor ${_id}`);
logger.debug({
msg: `Creating livechat inquiry for visitor ${_id}`,
visitor: { _id, username, department, status, activity },
});

const inquiry: InsertionModel<ILivechatInquiryRecord> = {
rid,
Expand All @@ -175,6 +184,7 @@ export const createLivechatInquiry = async ({
username,
token,
status,
...(activity?.length && { activity }),
},
t: 'l',
priorityWeight: LivechatPriorityWeight.NOT_SPECIFIED,
Expand Down
1 change: 1 addition & 0 deletions apps/meteor/app/livechat/server/lib/QueueManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export const QueueManager: queueManager = {
status: Match.Maybe(String),
department: Match.Maybe(String),
name: Match.Maybe(String),
activity: Match.Maybe([String]),
}),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const useIsRoomOverMacLimit = (room: IRoom) => {
return false;
}

if (!room.open) {
if (room.closedAt) {
return false;
}

Expand Down
4 changes: 4 additions & 0 deletions apps/meteor/server/models/raw/LivechatInquiry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -419,4 +419,8 @@ export class LivechatInquiryRaw extends BaseRaw<ILivechatInquiryRecord> implemen

await this.deleteMany(query);
}

async markInquiryActiveForPeriod(rid: string, period: string): Promise<UpdateResult> {
return this.updateOne({ rid }, { $addToSet: { 'v.activity': period } });
}
}
8 changes: 0 additions & 8 deletions apps/meteor/server/modules/listeners/listeners.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -474,13 +474,5 @@ export class ListenersModule {
notifications.streamApps.emitWithoutBroadcast('actions/changed');
notifications.streamApps.emitWithoutBroadcast('apps', ['actions/changed', []]);
});

service.onEvent('mac.limitReached', () => {
notifications.notifyLoggedInThisInstance('mac.limit', { limitReached: true });
});

service.onEvent('mac.limitRestored', () => {
notifications.notifyLoggedInThisInstance('mac.limit', { limitReached: false });
});
}
}
11 changes: 0 additions & 11 deletions apps/meteor/server/services/omnichannel/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ export class OmnichannelService extends ServiceClassInternal implements IOmnicha

private queueWorker: IOmnichannelQueue;

private macLimitReached = false;

constructor() {
super();
this.queueWorker = new OmnichannelQueue();
Expand All @@ -40,19 +38,10 @@ export class OmnichannelService extends ServiceClassInternal implements IOmnicha
});

License.onLimitReached('monthlyActiveContacts', async (): Promise<void> => {
if (this.macLimitReached) {
// Dupe events
return;
}

this.macLimitReached = true;
void this.api?.broadcast('mac.limitReached');
this.queueWorker.isRunning() && (await this.queueWorker.stop());
});

License.onValidateLicense(async (): Promise<void> => {
this.macLimitReached = false;
void this.api?.broadcast('mac.limitRestored');
RoutingManager.isMethodSet() && (await this.queueWorker.shouldStart());
});
}
Expand Down
6 changes: 3 additions & 3 deletions apps/meteor/tests/data/livechat/rooms.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { faker } from '@faker-js/faker';
import type {
IInquiry,
ILivechatInquiryRecord,
ILivechatAgent,
ILivechatDepartment,
ILivechatVisitor,
Expand Down Expand Up @@ -68,12 +68,12 @@ export const takeInquiry = async (inquiryId: string, agentCredentials?: IUserCre
await request.post(api('livechat/inquiries.take')).set(agentCredentials || credentials).send({ userId, inquiryId }).expect(200);
};

export const fetchInquiry = (roomId: string): Promise<IInquiry> => {
export const fetchInquiry = (roomId: string): Promise<ILivechatInquiryRecord> => {
return new Promise((resolve, reject) => {
request
.get(api(`livechat/inquiries.getOne?roomId=${roomId}`))
.set(credentials)
.end((err: Error, res: DummyResponse<IInquiry>) => {
.end((err: Error, res: DummyResponse<ILivechatInquiryRecord>) => {
if (err) {
return reject(err);
}
Expand Down
29 changes: 26 additions & 3 deletions apps/meteor/tests/end-to-end/api/livechat/23-mac.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ import {
makeAgentAvailable,
sendAgentMessage,
getLivechatRoomInfo,
fetchInquiry,
closeOmnichannelRoom,
} from '../../../data/livechat/rooms';
import { IS_EE } from '../../../e2e/config/constants';

(IS_EE ? describe : describe.skip)('MAC', () => {
describe('MAC', () => {
before((done) => getCredentials(done));

before(async () => {
Expand Down Expand Up @@ -43,14 +44,36 @@ import { IS_EE } from '../../../e2e/config/constants';
expect(updatedRoom).to.have.nested.property('v.activity').and.to.be.an('array');
});

it('should mark multiple rooms as active when they come from same visitor', async () => {
it('should mark multiple rooms as active when they come from same visitor after an agent sends a message', async () => {
const room = await createLivechatRoom(visitor.token);

await sendAgentMessage(room._id);

const updatedRoom = await getLivechatRoomInfo(room._id);

expect(updatedRoom).to.have.nested.property('v.activity').and.to.be.an('array');

await closeOmnichannelRoom(room._id);
});

it('should mark room as active when it comes from same visitor on same period, even without agent interaction', async () => {
const room = await createLivechatRoom(visitor.token);

expect(room).to.have.nested.property('v.activity').and.to.be.an('array');
expect(room.v.activity?.includes(moment.utc().format('YYYY-MM'))).to.be.true;

await closeOmnichannelRoom(room._id);
});

it('should mark an inquiry as active when it comes from same visitor on same period, even without agent interaction', async () => {
const room = await createLivechatRoom(visitor.token);
const inquiry = await fetchInquiry(room._id);

expect(inquiry).to.have.nested.property('v.activity').and.to.be.an('array');
expect(inquiry.v.activity?.includes(moment.utc().format('YYYY-MM'))).to.be.true;
expect(room.v.activity?.includes(moment.utc().format('YYYY-MM'))).to.be.true;

await closeOmnichannelRoom(room._id);
});

it('visitor should be marked as active for period', async () => {
Expand Down
1 change: 0 additions & 1 deletion ee/packages/ddp-client/src/types/streams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,6 @@ export interface StreamerEvents {
},

{ key: 'voip.statuschanged'; args: [boolean] },
{ key: 'mac.limit'; args: [{ limitReached: boolean }] },
{ key: 'omnichannel.priority-changed'; args: [{ id: string; clientAction: ClientAction; name?: string }] },
];

Expand Down
2 changes: 0 additions & 2 deletions packages/core-services/src/Events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,4 @@ export type EventSignatures = {
'command.updated'(command: string): void;
'command.removed'(command: string): void;
'actions.changed'(): void;
'mac.limitReached'(): void;
'mac.limitRestored'(): void;
};
2 changes: 1 addition & 1 deletion packages/core-typings/src/IInquiry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export interface ILivechatInquiryRecord extends IRocketChatRecord {
ts: Date;
message: string;
status: LivechatInquiryStatus;
v: Pick<ILivechatVisitor, '_id' | 'username' | 'status' | 'name' | 'token' | 'phone'> & { lastMessageTs?: Date };
v: Pick<ILivechatVisitor, '_id' | 'username' | 'status' | 'name' | 'token' | 'phone' | 'activity'> & { lastMessageTs?: Date };
t: 'l';

department?: string;
Expand Down
3 changes: 1 addition & 2 deletions packages/core-typings/src/IRoom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,9 @@ export enum OmnichannelSourceType {

export interface IOmnichannelGenericRoom extends Omit<IRoom, 'default' | 'featured' | 'broadcast' | ''> {
t: 'l' | 'v';
v: Pick<ILivechatVisitor, '_id' | 'username' | 'status' | 'name' | 'token'> & {
v: Pick<ILivechatVisitor, '_id' | 'username' | 'status' | 'name' | 'token' | 'activity'> & {
lastMessageTs?: Date;
phone?: string;
activity?: string[];
};
email?: {
// Data used when the room is created from an email, via email Integration.
Expand Down
1 change: 1 addition & 0 deletions packages/model-typings/src/models/ILivechatInquiryModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,5 @@ export interface ILivechatInquiryModel extends IBaseModel<ILivechatInquiryRecord
findOneByToken(token: string): Promise<ILivechatInquiryRecord | null>;
removeDefaultAgentById(inquiryId: string): Promise<UpdateResult | Document>;
removeByVisitorToken(token: string): Promise<void>;
markInquiryActiveForPeriod(rid: string, period: string): Promise<UpdateResult>;
}

0 comments on commit 589c451

Please sign in to comment.