| 1 | import { MedicineRegimen } from "@prisma/client";
|
| 2 | import { getQueue } from "@app/lib/queue/QueueRegistry";
|
| 3 | import { MedicineReminderJobName } from "@app/lib/queue/types";
|
| 4 |
|
| 5 | function timeToCron(time: string): string {
|
| 6 | const [hour, minute] = time.split(":").map(Number);
|
| 7 | return `${minute} ${hour} * * *`;
|
| 8 | }
|
| 9 |
|
| 10 | export async function syncMedicineReminderJobs(
|
| 11 | regimen: MedicineRegimen
|
| 12 | ): Promise<void> {
|
| 13 | console.log(`[medicine-sync] syncing regimen ${regimen.id} (active=${regimen.active}, times=[${regimen.scheduledAt}])`);
|
| 14 |
|
| 15 | const queue = getQueue("medicine-reminders");
|
| 16 |
|
| 17 | const existing = await queue.getRepeatableJobs();
|
| 18 | let removedCount = 0;
|
| 19 |
|
| 20 | for (const job of existing) {
|
| 21 | if (job.id?.startsWith(`regimen-${regimen.id}-`)) {
|
| 22 | await queue.removeRepeatableByKey(job.key);
|
| 23 | removedCount++;
|
| 24 | }
|
| 25 | }
|
| 26 |
|
| 27 | console.log(`[medicine-sync] removed ${removedCount} existing jobs for regimen ${regimen.id}`);
|
| 28 |
|
| 29 | if (!regimen.active) {
|
| 30 | console.log(`[medicine-sync] regimen ${regimen.id} inactive, no jobs scheduled`);
|
| 31 |
|
| 32 | return;
|
| 33 | }
|
| 34 |
|
| 35 | if (regimen.scheduledAt.length === 0) {
|
| 36 | console.log(`[medicine-sync] regimen ${regimen.id} has no scheduledAt times, skipping`);
|
| 37 |
|
| 38 | return;
|
| 39 | }
|
| 40 |
|
| 41 | for (const time of regimen.scheduledAt) {
|
| 42 | const cron = timeToCron(time);
|
| 43 | await queue.add(
|
| 44 | MedicineReminderJobName.Send,
|
| 45 | {
|
| 46 | userId: regimen.userId,
|
| 47 | regimenId: regimen.id,
|
| 48 | medicineName: regimen.name,
|
| 49 | dosage: regimen.dosage,
|
| 50 | scheduledTime: time,
|
| 51 | },
|
| 52 | {
|
| 53 | repeat: { pattern: cron, tz: "America/Sao_Paulo" },
|
| 54 | jobId: `regimen-${regimen.id}-${time}`,
|
| 55 | }
|
| 56 | );
|
| 57 |
|
| 58 | console.log(`[medicine-sync] scheduled job for regimen ${regimen.id} at ${time} => cron ${cron}`);
|
| 59 | }
|
| 60 | }
|