eletrotupi / tcc/ api/src/services/dailyReminder.sync.ts95b0a7d7b379540440909110b748904954048374
1.3 KB | 41 lines Raw
1
import { User } from "@prisma/client";
2
import { getQueue } from "@app/lib/queue/QueueRegistry";
3
import { DailyReminderJobName } from "@app/lib/queue/types";
4

5
// XXX: Might be moved to the utilities?
6
function timeToCron(time: string): string {
7
  const [hour, minute] = time.split(":").map(Number);
8
  return `${minute} ${hour} * * *`;
9
}
10

11
export async function syncDailyReminderJob(user: User): Promise<void> {
12
  console.log(`[daily-sync] syncing user ${user.id}`);
13

14
  const queue = getQueue("daily-reminders");
15

16
  const existing = await queue.getRepeatableJobs();
17
  for (const job of existing) {
18
    if (job.id?.includes(`daily-reminder-user-${user.id}`)) {
19
      await queue.removeRepeatableByKey(job.key);
20
    }
21
  }
22

23
  if (!user.notificationsEnabled || !user.dailyReminderTime) {
24
    console.log(`[daily-sync] user ${user.id} skipped (enabled=${user.notificationsEnabled}, time=${user.dailyReminderTime})`);
25

26
    return;
27
  }
28

29
  const cron = timeToCron(user.dailyReminderTime);
30

31
  await queue.add(
32
    DailyReminderJobName.Send,
33
    { userId: user.id },
34
    {
35
      repeat: { pattern: cron, tz: "America/Sao_Paulo" },
36
      jobId: `daily-reminder-user-${user.id}`,
37
    }
38
  );
39

40
  console.log(`[daily-sync] scheduled daily reminder for user ${user.id} at ${user.dailyReminderTime} => cron ${cron}`);
41
}