| 1 | import { User } from "@prisma/client";
|
| 2 | import { getQueue } from "@app/lib/queue/QueueRegistry";
|
| 3 | import { DailyReminderJobName } from "@app/lib/queue/types";
|
| 4 | import { logger } from "@app/lib/logger";
|
| 5 |
|
| 6 | // XXX: Might be moved to the utilities?
|
| 7 | function timeToCron(time: string): string {
|
| 8 | const [hour, minute] = time.split(":").map(Number);
|
| 9 | return `${minute} ${hour} * * *`;
|
| 10 | }
|
| 11 |
|
| 12 | export async function syncDailyReminderJob(user: User): Promise<void> {
|
| 13 | logger.info({ userId: user.id }, "[daily-sync] syncing user");
|
| 14 |
|
| 15 | const queue = getQueue("daily-reminders");
|
| 16 |
|
| 17 | const existing = await queue.getRepeatableJobs();
|
| 18 | for (const job of existing) {
|
| 19 | if (job.id?.includes(`daily-reminder-user-${user.id}`)) {
|
| 20 | await queue.removeRepeatableByKey(job.key);
|
| 21 | }
|
| 22 | }
|
| 23 |
|
| 24 | if (!user.dailyReminderTime) {
|
| 25 | logger.info(
|
| 26 | { userId: user.id, time: user.dailyReminderTime },
|
| 27 | "[daily-sync] user skipped",
|
| 28 | );
|
| 29 |
|
| 30 | return;
|
| 31 | }
|
| 32 |
|
| 33 | const cron = timeToCron(user.dailyReminderTime);
|
| 34 |
|
| 35 | await queue.add(
|
| 36 | DailyReminderJobName.Send,
|
| 37 | { userId: user.id, scheduledTime: user.dailyReminderTime },
|
| 38 | {
|
| 39 | repeat: { pattern: cron, tz: "America/Sao_Paulo" },
|
| 40 | jobId: `daily-reminder-user-${user.id}`,
|
| 41 | }
|
| 42 | );
|
| 43 |
|
| 44 | logger.info(
|
| 45 | { userId: user.id, time: user.dailyReminderTime, cron },
|
| 46 | "[daily-sync] scheduled daily reminder",
|
| 47 | );
|
| 48 | }
|