All files / src/application/notification generate-reminder-notifications.use-case.ts

100% Statements 64/64
100% Branches 23/23
100% Functions 8/8
100% Lines 63/63

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183                                2x               15x 15x 15x 15x 15x 15x 15x 15x       16x 16x 16x   16x 16x 16x     16x               16x 16x 16x   16x 78x 8x     70x 1x     69x 69x 15x     54x               54x 33x     21x           21x 9x     12x                     12x   12x 13x       16x       16x 16x   16x 7x 1x     6x 6x   7x 1x     5x           5x 2x     3x                     3x   3x 3x       16x               15x   15x 18x   18x 2x     16x 16x   1x          
import { randomUUID } from 'node:crypto';
import { BabyRepository } from '../baby/baby-repository';
import { BabyGuardianRepository } from '../baby/baby-guardian-repository';
import { VaccineRepository } from '../vaccine/vaccine-repository';
import { BabyVaccineRecordRepository } from '../vaccine/baby-vaccine-record-repository';
import { AppointmentRepository } from '../appointment/appointment-repository';
import { UserRepository } from '../user/user-repository';
import { NotificationRepository } from './notification-repository';
import { Baby } from '../../domain/baby/baby';
import { Vaccine } from '../../domain/vaccine/vaccine';
import { BabyVaccineRecord } from '../../domain/vaccine/baby-vaccine-record';
import { Notification } from '../../domain/notification/notification';
import { addMonthsClamped } from '../../shared/utils/date';
import { ReminderEmailSender } from '../../infrastructure/email/email-service';
import { logger } from '../../shared/logging/logger';
 
const APPOINTMENT_REMINDER_WINDOW_MS = 3 * 24 * 60 * 60 * 1000;
 
export interface GenerateReminderNotificationsResult {
  createdCount: number;
}
 
export class GenerateReminderNotificationsUseCase {
  constructor(
    private readonly babyRepository: BabyRepository,
    private readonly vaccineRepository: VaccineRepository,
    private readonly babyVaccineRecordRepository: BabyVaccineRecordRepository,
    private readonly appointmentRepository: AppointmentRepository,
    private readonly notificationRepository: NotificationRepository,
    private readonly babyGuardianRepository: BabyGuardianRepository,
    private readonly userRepository: UserRepository,
    private readonly emailService: ReminderEmailSender,
  ) {}
 
  async execute(referenceDate: Date = new Date()): Promise<GenerateReminderNotificationsResult> {
    const babies = await this.babyRepository.findAll();
    const vaccines = await this.vaccineRepository.findAll();
    let createdCount = 0;
 
    for (const baby of babies) {
      createdCount += await this.generateVaccineDelayNotifications(baby, vaccines, referenceDate);
      createdCount += await this.generateAppointmentReminderNotifications(baby, referenceDate);
    }
 
    return { createdCount };
  }
 
  private async generateVaccineDelayNotifications(
    baby: Baby,
    vaccines: Vaccine[],
    referenceDate: Date,
  ): Promise<number> {
    const appliedRecords = await this.babyVaccineRecordRepository.findAllByBabyId(baby.id);
    const appliedVaccineIds = new Set(appliedRecords.map((record) => record.vaccineId));
    let created = 0;
 
    for (const vaccine of vaccines) {
      if (vaccine.recommendationKind !== 'ROUTINE') {
        continue;
      }
 
      if (appliedVaccineIds.has(vaccine.id)) {
        continue;
      }
 
      const dueDate = addMonthsClamped(baby.birthDate, vaccine.recommendedAgeInMonths);
      if (dueDate.getTime() < vaccine.effectiveFrom.getTime()) {
        continue;
      }
 
      const record = BabyVaccineRecord.derive({
        id: `${baby.id}:${vaccine.id}`,
        babyId: baby.id,
        vaccineId: vaccine.id,
        dueDate,
        referenceDate,
      });
 
      if (record.status !== 'DELAYED') {
        continue;
      }
 
      const alreadyNotified = await this.notificationRepository.existsForTrigger(
        baby.id,
        'VACCINE_DELAYED',
        vaccine.id,
      );
 
      if (alreadyNotified) {
        continue;
      }
 
      await this.notificationRepository.save(
        Notification.create({
          id: randomUUID(),
          userId: baby.userId,
          babyId: baby.id,
          type: 'VACCINE_DELAYED',
          referenceId: vaccine.id,
          title: `Vacina atrasada: ${vaccine.name}`,
          message: `A vacina ${vaccine.name} de ${baby.name} está atrasada.`,
        }),
      );
      created += 1;
 
      await this.notifyGuardiansByEmail(baby, (email) =>
        this.emailService.sendVaccineOverdueEmail(email, baby.name, vaccine.name),
      );
    }
 
    return created;
  }
 
  private async generateAppointmentReminderNotifications(baby: Baby, referenceDate: Date): Promise<number> {
    const appointments = await this.appointmentRepository.findAllByBabyId(baby.id);
    let created = 0;
 
    for (const appointment of appointments) {
      if (appointment.status !== 'SCHEDULED') {
        continue;
      }
 
      const millisecondsUntilAppointment = appointment.scheduledAt.getTime() - referenceDate.getTime();
      const isUpcoming = millisecondsUntilAppointment >= 0 && millisecondsUntilAppointment <= APPOINTMENT_REMINDER_WINDOW_MS;
 
      if (!isUpcoming) {
        continue;
      }
 
      const alreadyNotified = await this.notificationRepository.existsForTrigger(
        baby.id,
        'APPOINTMENT_UPCOMING',
        appointment.id,
      );
 
      if (alreadyNotified) {
        continue;
      }
 
      await this.notificationRepository.save(
        Notification.create({
          id: randomUUID(),
          userId: baby.userId,
          babyId: baby.id,
          type: 'APPOINTMENT_UPCOMING',
          referenceId: appointment.id,
          title: `Consulta próxima com ${appointment.doctorName}`,
          message: `${baby.name} tem consulta com ${appointment.doctorName} em ${appointment.scheduledAt.toISOString()}.`,
        }),
      );
      created += 1;
 
      await this.notifyGuardiansByEmail(baby, (email) =>
        this.emailService.sendAppointmentReminderEmail(email, baby.name, appointment.doctorName, appointment.scheduledAt),
      );
    }
 
    return created;
  }
 
  // A baby can have multiple guardians (owner + co-parents added via the sharing feature) — every
  // guardian who opted into email notifications gets reminded, not just the original owner.
  // A failure sending to one guardian (Resend outage, bad address, etc.) is logged and must never
  // stop the sweep from processing the rest of this baby's guardians or the next baby/vaccine.
  private async notifyGuardiansByEmail(baby: Baby, sendToGuardian: (email: string) => Promise<void>): Promise<void> {
    const guardians = await this.babyGuardianRepository.findAllByBaby(baby.id);
 
    for (const guardian of guardians) {
      const user = await this.userRepository.findById(guardian.userId);
 
      if (!user || !user.emailNotificationsEnabled) {
        continue;
      }
 
      try {
        await sendToGuardian(user.email);
      } catch (error) {
        logger.warn({ err: error, babyId: baby.id, userId: user.id }, 'reminders.email_send_failed');
      }
    }
  }
}