import * as UserControllers from '../../controllers/user' import { User } from 'nexus-plugin-prisma/client' import { logger } from '../../utils/logger' import { prismaClient as prisma } from '../../prismaClient' /** * We did this script because we don't want 2 users with the same email/phone number */ export default async function mixResidentWithMultipleAccounts() { try { logger.info( 'Start updating users so that if there\'s multiple user for the same account, they are all mixed together' ) await new Promise((resolve, reject) => { try { let totalNumberOfUsersFetched = 0 const fetchAndVerifyUsers = async ({ skip = 0 }) => { try { const users: User[] = await prisma.user.findMany({ where: { AND: [{ role: 'RESIDENT' }, { email: { not: null } }, { email: { not: '' } }], }, skip, take: 1, orderBy: { createdAt: 'desc' }, }) const userToEvaluate = users[0] if (!userToEvaluate) { return resolve() } if (!userToEvaluate.email) { throw new Error('User doesn\'t have any email, carefull') } totalNumberOfUsersFetched += 1 const usersWithSameEmail = await prisma.user.findMany({ where: { role: 'RESIDENT', id: { not: userToEvaluate.id }, email: userToEvaluate.email, }, }) if (usersWithSameEmail.length) { logger.info( `${usersWithSameEmail.length} users with same email: ${userToEvaluate.email}` ) try { await UserControllers.mergeUsersAndGetNewUpdatedOne({ users: [userToEvaluate, ...usersWithSameEmail], }) } catch (error) { logger.error(error) } } logger.info(`Total number of users processed: ${totalNumberOfUsersFetched}`) return fetchAndVerifyUsers({ skip: totalNumberOfUsersFetched }) } catch (error) { console.log('error', error) } } // START fetchAndVerifyUsers({}) } catch (error) { reject(error) } }) logger.info( 'Finish updating users so that if there\'s multiple user for the same account, they are all mixed together' ) } catch (e) { logger.error(e) } } mixResidentWithMultipleAccounts()