/* eslint-disable no-unused-vars */ import moment from 'moment' import '../../config' import GeneralUtils from '../../utils/general' import * as Notification from '../../utils/notification' import { prismaClient as prisma } from '../../prismaClient' import { sendPost } from '../../queues' prisma.post .findMany({ where: { postSentAt: { not: null }, createdAt: { gte: moment().subtract(2, 'days').toDate() }, }, }) .then(async (posts) => { console.log('posts.length', posts.length) for await (const { id } of posts) { const post = await prisma.post.findOne({ where: { id }, include: { attachments: true, segments: true, audience: true }, }) const projectUsers = await prisma.user.findMany({ where: { projects: { some: { id: { equals: post.projectId } } } }, }) console.log('Processing post:', post.title) const postNotifications = await prisma.post .findOne({ where: { id: post.id } }) .notifications({ include: { user: true } }) const usersThatWillReceiveThePost = // No audience WITH a segment means the user WANTS to send it to 0 users post.audience.length === 0 && post.segments.length > 0 ? [] : // No audience means all residents post.audience.length === 0 ? projectUsers : // Else we take the audience post.audience console.log('Number of users in audience:', usersThatWillReceiveThePost.length) await prisma.post.update({ where: { id: post.id }, data: { audience: { connect: usersThatWillReceiveThePost.map(({ id }) => ({ id })), }, }, }) const usersThatDontHaveDeliveredNotifications = usersThatWillReceiveThePost.filter((u) => { const existingNotification = postNotifications.find((n) => n.user.id === u.id) return !existingNotification }) const usersToSendTo = GeneralUtils.uniq([...usersThatDontHaveDeliveredNotifications], 'id') console.log('Number of notifications for last post', postNotifications.length) console.log('Users that dont have notification created:', usersToSendTo.length) // Don't add this because we might send notification to users and it's been a long time // const notificationThatCouldntBeSent = postNotifications.filter(n => !n.sent && n.user) // console.log('notificationThatCouldntBeSent', notificationThatCouldntBeSent) if (usersToSendTo.length > 0) { await sendPost(post.id) } console.log('Finish processing post:', post.title || `No title`) } console.log('JOB DONE') }) .catch(console.error)