import { ManagingCompany } from 'nexus-plugin-prisma/client' import * as SendBirdController from '../../controllers/sendbird' import { prismaClient as prisma } from '../../prismaClient' prisma.managingCompany.findMany().then(async (managingCompanies: ManagingCompany[]) => { for await (const managingCompany of managingCompanies) { console.log(`Start processing ${managingCompany.shortName}`) try { const usersForManagingCompany = await prisma.user.findMany({ where: { managingCompany: { id: managingCompany.id } }, }) // All channels for current managing company const channels = await SendBirdController.getChannelsForUserId({ all: true, userId: managingCompany.id, show_member: true, }) // Only the new channels const v2Channels = channels.filter((c) => !c.name.startsWith('chat')) console.log('v2Channels.length', v2Channels.length) for await (const channel of v2Channels) { // Make sure that only residents and managing company are in the channel const managingCompanyUsersInPublicChannel = channel.members.filter(({ user_id: userId }) => usersForManagingCompany.some(({ id }) => id === userId) ) if (managingCompanyUsersInPublicChannel.length) { console.log( `${managingCompanyUsersInPublicChannel.length} users shouldn't be in the public channel...` ) await SendBirdController.removeUsersFromChannel({ userIds: managingCompanyUsersInPublicChannel.map(({ user_id: userId }) => userId), channelUrl: channel.channel_url, }) console.log('Done removing them') } // Check if the private channel exists const privateChannel = await SendBirdController.getChannelByName({ name: `${channel.name}-private`, show_member: true, }) // If not exists, create it if (!privateChannel) { console.log('Creating missing private channel') const [projectId, propertyId] = channel.name.split('-') await SendBirdController.createOrGetManagerChannel({ projectId, propertyId, }) } // Check who we didn't add const usersToAdd = usersForManagingCompany.filter( (user) => !privateChannel.members.some((member) => member.user_id === user.id) ) // Add them to the channel if (usersToAdd.length) { console.log(`Adding ${usersToAdd.length} users in channel`) await SendBirdController.addUsersToChannel({ channelUrl: privateChannel.channel_url, userIds: usersForManagingCompany.map((u) => u.id), }) } console.log('Done processing channel channel') } } catch (error) { console.error(error) } } })