From 15c85686c61e90d4cc4001d58f480a7f855eae78 Mon Sep 17 00:00:00 2001 From: paritosh18 Date: Sat, 22 Nov 2025 11:33:55 +0530 Subject: [PATCH] Refactor getAllCoadminAndAM to include active user filtering and host count aggregation --- .../minglaradmin/services/minglar.service.ts | 83 +++++++++++-------- 1 file changed, 50 insertions(+), 33 deletions(-) diff --git a/src/modules/minglaradmin/services/minglar.service.ts b/src/modules/minglaradmin/services/minglar.service.ts index a6bfaf6..6d766be 100644 --- a/src/modules/minglaradmin/services/minglar.service.ts +++ b/src/modules/minglaradmin/services/minglar.service.ts @@ -529,42 +529,59 @@ export class MinglarService { } async getAllCoadminAndAM() { - return await this.prisma.user.findMany({ - where: { - roleXid: { - in: [ROLE.CO_ADMIN, ROLE.ACCOUNT_MANAGER, ROLE.MINGLAR_ADMIN] - }, - isActive: true, - userStatus: USER_STATUS.ACTIVE, + // 1. Fetch all required users (Admin, Co-Admin, AM) + const users = await this.prisma.user.findMany({ + where: { + roleXid: { + in: [ + ROLE.MINGLAR_ADMIN, // Admin + ROLE.CO_ADMIN, // Co-Admin + ROLE.ACCOUNT_MANAGER // AM + ] }, - - include: { - role: { - select: { - id: true, - roleName: true, - }, + isActive: true, + userStatus: USER_STATUS.ACTIVE, + }, + include: { + role: { + select: { + id: true, + roleName: true, }, + }, + }, + }); + + if (!users.length) return []; + + const userIds = users.map((u) => u.id); + + // 2. Count assigned hosts for ANY user (Admin / Co-Admin / AM) + const groupedHosts = await this.prisma.hostHeader.groupBy({ + by: ["accountManagerXid"], + where: { + accountManagerXid: { in: userIds }, // assigned user + isActive: true, + }, + _count: { + id: true, + }, + }); + + // 3. Build quick lookup map: userId -> hostCount + const hostCountMap: Record = {}; + groupedHosts.forEach((g) => { + const uid = Number(g.accountManagerXid); + hostCountMap[uid] = g._count.id; + }); + + // 4. Attach host counts to each user + return users.map((user) => ({ + ...user, + assignedHostCount: hostCountMap[user.id] ?? 0, + })); +} - // (Optional) to return only the accepted invitations - // inviteDetails: { - // where: { - // isMinglarInvitation: true, - // is_accepted: true, - // invitation_status: MINGLAR_INVITATION_STATUS.ACCEPTED, - // isActive: true - // }, - // select: { - // id: true, - // invitedBy: true, - // invited_on: true, - // invitation_status: true, - // is_accepted: true - // } - // } - } - }); - } async assignAMToHost(userId: number, hostXid: number, accountManagerXid: number) { const hostDetails = await this.prisma.hostHeader.findFirst({