import moment from 'moment' import * as UserController from '../../controllers/user' import { logger } from '../../utils/logger' import { prismaClient as prisma } from '../../prismaClient' export default async function verifyIfWeShouldSendSecondInvite() { try { if (moment().hours() >= 21 || moment().hours() <= 7) { return logger.info('Will not process app second invite because it\'s in the night') } logger.info('Start verify if we should send second invite') const users = await prisma.user.findMany({ where: { AND: [ { active: true }, // Only some at the time { createdAt: { lte: moment().subtract(3, 'months').toDate(), }, }, // Resident only for sure { role: 'RESIDENT' }, // ONlY send if user has received first invitation 3 days ago { hasReceivedInvitationAt: { lt: moment().subtract(3, 'days').toDate(), }, }, // Only send if user received first invitation { hasReceivedInvitation: true, }, // Make sure he haven't downloaded the app { OR: [ { hasInstalledApp: null, }, { hasInstalledApp: false, }, ], }, // And make sure he haven't already received second invitation { OR: [ { hasReceivedSecondInvitation: null, }, { hasReceivedSecondInvitation: false, }, ], }, ], }, }) logger.info(`Number of users to process to send second invite ${users.length}`) for await (const user of users) { try { await UserController.sendEmailAppInvitationToResident({ userId: user.id, emailTemplateName: 'RESIDENT_SECOND_INVITE', }).then(() => prisma.user.update({ where: { id: user.id, }, data: { hasReceivedSecondInvitation: true, hasReceivedSecondInvitationAt: new Date(), hasReceivedSecondInvitationByEmail: true, hasReceivedSecondInvitationByEmailAt: new Date(), }, }) ) await UserController.sendSMSAppInvitationToResident({ userId: user.id, type: 'SECOND_APP_INVITATION', }).then(() => prisma.user.update({ where: { id: user.id, }, data: { hasReceivedSecondInvitation: true, hasReceivedSecondInvitationAt: new Date(), hasReceivedSecondInvitationBySMS: true, hasReceivedSecondInvitationBySMSAt: new Date(), }, }) ) } catch (error) { logger.error(error) } await new Promise((resolve) => setTimeout(resolve, 200)) } logger.info('Finish processing app second invite') } catch (e) { logger.error(e) } }