import GeneralUtils from '../../utils/general' import { logger } from '../../utils/logger' import * as SendBirdController from '../../controllers/sendbird' import { prismaClient as prisma } from '../../prismaClient' export async function removePropertyFromUser(userId: string, propertyId: string) { if (!userId || !propertyId) throw new Error('userId and propertyId are mandatory') const property = await prisma.property.findOne({ where: { id: propertyId }, select: { id: true, owners: { select: { id: true, }, }, users: { select: { id: true, }, }, }, }) // Might need to also remove Condo Manager Compte for the removed property const updatedProperty = updateProperty({ where: { id: propertyId, }, data: { ...(property.users.some((u) => u.id === userId) && { users: { disconnect: [ { id: userId, }, ], }, previousUsers: { connect: [ { id: userId, }, ], }, }), ...(property.owners.some((u) => u.id === userId) && { owners: { disconnect: [ { id: userId, }, ], }, previousOwners: { connect: [ { id: userId, }, ], }, }), }, }) return updatedProperty } export async function updateProperty({ where, data }) { const [oldPropertyUsers, oldPropertyOwners] = await Promise.all([ prisma.property.findOne({ where }).owners(), prisma.property.findOne({ where }).users(), ]) const updatedProperty = await prisma.property.update({ where, data, }) // Also need to add it to conversation if exists if (data.owners || data.users) { const [actualPropertyOwners, actualPropertyUsers] = await Promise.all([ prisma.property.findOne({ where }).owners(), prisma.property.findOne({ where }).users(), ]) const actualPropertyResidents = [...actualPropertyOwners, ...actualPropertyUsers] const oldPropertyResidents = [...oldPropertyOwners, ...oldPropertyUsers] const addedUsers = actualPropertyResidents.filter( (user) => !oldPropertyResidents.some((u) => u.id === user.id) ) const removedUsers = oldPropertyResidents.filter( (user) => !actualPropertyResidents.some((u) => u.id === user.id) ) if (addedUsers.length) { const usersToAddToPropertyChannel = GeneralUtils.uniq(addedUsers, 'id') SendBirdController.addUsersToPropertyChannelIfExists({ userIds: usersToAddToPropertyChannel.map(({ id }) => id), propertyId: where?.id, }).catch(logger.error) } if (removedUsers.length) { SendBirdController.removeUsersFromPropertyChannel({ userIds: removedUsers.map(({ id }) => id), propertyId: where?.id, }).catch(logger.error) } } return updatedProperty } export async function deleteProperty(propertyId) { const deletedProperty = await prisma.property.delete({ where: { id: propertyId } }) return deletedProperty }