import { connectWiseApi, prisma } from "../../../constants"; import { events } from "../../globalEvents"; import { fetchAllCwMembers, findCwIdentifierByEmail } from "./fetchAllMembers"; import { setMemberCache } from "./memberCache"; /** * Refresh CW Identifiers * * Fetches all CW members and all users from the database, then updates * each user's `cwIdentifier` field by matching their email to a CW member's * `officeEmail`. Only users whose identifier has changed (or was previously * null) are updated to avoid unnecessary writes. * * Also refreshes the in-memory member cache used for name resolution. */ export const refreshCwIdentifiers = async () => { events.emit("cw:members:refresh:started"); const allMembers = await fetchAllCwMembers(); await setMemberCache(allMembers); const allUsers = await prisma.user.findMany({ select: { id: true, email: true, cwIdentifier: true }, }); let updatedCount = 0; await Promise.all( allUsers.map(async (user) => { const identifier = await findCwIdentifierByEmail(user.email, allMembers); if (identifier !== user.cwIdentifier) { await prisma.user.update({ where: { id: user.id }, data: { cwIdentifier: identifier }, }); updatedCount++; } }), ); events.emit("cw:members:refresh:completed", { totalMembers: allMembers.size, totalUsers: allUsers.length, usersUpdated: updatedCount, }); };