|
| 1 | +import type { PrismaClient } from '@generatedDB/client' |
| 2 | +import type { Guild, GuildMember, TextChannel } from 'discord.js' |
| 3 | +import { getGrindRoles, GRINDER_ROLE } from '@config/discord' |
| 4 | +import { isDateToday, isDateYesterday } from '@utils/date' |
| 5 | +import { sendAsBot } from '@utils/discord' |
| 6 | +import { log } from '@utils/logger' |
| 7 | +import { ResetGrinderRolesMessage } from '../messages/reset-grinder-roles' |
| 8 | + |
| 9 | +interface UserWithLatestCheckin { |
| 10 | + discord_id: string |
| 11 | + checkins: { |
| 12 | + status: string |
| 13 | + created_at: Date |
| 14 | + }[] |
| 15 | +} |
| 16 | + |
| 17 | +export class ResetGrinderRoles extends ResetGrinderRolesMessage { |
| 18 | + static hasValidCheckin(checkin?: { created_at: Date, status: string }): boolean { |
| 19 | + if (!checkin) |
| 20 | + return false |
| 21 | + |
| 22 | + const { created_at, status } = checkin |
| 23 | + if (isDateToday(created_at)) |
| 24 | + return true |
| 25 | + if (isDateYesterday(created_at) && status === 'APPROVED') |
| 26 | + return true |
| 27 | + |
| 28 | + return false |
| 29 | + } |
| 30 | + |
| 31 | + static async removeGrinderRoles(member: GuildMember) { |
| 32 | + await member.roles.remove(GRINDER_ROLE) |
| 33 | + |
| 34 | + const grindRoles = getGrindRoles() |
| 35 | + for (const grindRole of grindRoles) { |
| 36 | + if (member.roles.cache.has(grindRole.id)) { |
| 37 | + await member.roles.remove(grindRole.id) |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + static async validateUsers(guild: Guild, channel: TextChannel, users: UserWithLatestCheckin[]) { |
| 43 | + for (const user of users) { |
| 44 | + const lastCheckin = user.checkins?.[0] |
| 45 | + if (this.hasValidCheckin(lastCheckin)) |
| 46 | + continue |
| 47 | + |
| 48 | + const member = await guild.members.fetch(user.discord_id) |
| 49 | + await this.removeGrinderRoles(member) |
| 50 | + |
| 51 | + await sendAsBot( |
| 52 | + null, |
| 53 | + channel, |
| 54 | + { content: ResetGrinderRoles.MSG.GoodBye(member), allowedMentions: { users: [member.id], roles: [] } }, |
| 55 | + ) |
| 56 | + |
| 57 | + log.info(this.MSG.RemoveGrinderRoleFrom(member)) |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + static async getUsersWithLatestCheckin(prisma: PrismaClient): Promise<UserWithLatestCheckin[]> { |
| 62 | + const users = await prisma.user.findMany({ |
| 63 | + select: { |
| 64 | + discord_id: true, |
| 65 | + checkins: { |
| 66 | + select: { |
| 67 | + status: true, |
| 68 | + created_at: true, |
| 69 | + }, |
| 70 | + orderBy: { created_at: 'desc' }, |
| 71 | + take: 1, |
| 72 | + }, |
| 73 | + }, |
| 74 | + }) as UserWithLatestCheckin[] |
| 75 | + |
| 76 | + return users |
| 77 | + } |
| 78 | +} |
0 commit comments