All files / src/application/vaccine mark-vaccine-as-applied.use-case.ts

100% Statements 14/14
100% Branches 8/8
100% Functions 2/2
100% Lines 14/14

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                                                28x 28x 28x 28x       13x   11x   11x 2x     9x 2x     7x         7x                       13x   7x      
import { randomUUID } from 'node:crypto';
import { BabyRepository } from '../baby/baby-repository';
import { BabyGuardianRepository } from '../baby/baby-guardian-repository';
import { ensureBabyAccess } from '../baby/ensure-baby-access';
import { BabyVaccineRecord } from '../../domain/vaccine/baby-vaccine-record';
import { BabyVaccineRecordRepository } from './baby-vaccine-record-repository';
import { VaccineRepository } from './vaccine-repository';
import { VaccineNotFoundError } from './errors/vaccine-not-found.error';
import { RecurringVaccineRequiresAdhocRecordError } from './errors/recurring-vaccine-requires-adhoc-record.error';
 
export interface MarkVaccineAsAppliedInput {
  babyId: string;
  vaccineId: string;
  requestingUserId: string;
  applicationDate?: Date;
  notes?: string | null;
  batchNumber?: string | null;
  location?: string | null;
  professional?: string | null;
  photoUrl?: string | null;
}
 
export class MarkVaccineAsAppliedUseCase {
  constructor(
    private readonly babyRepository: BabyRepository,
    private readonly babyGuardianRepository: BabyGuardianRepository,
    private readonly vaccineRepository: VaccineRepository,
    private readonly babyVaccineRecordRepository: BabyVaccineRecordRepository,
  ) {}
 
  async execute(input: MarkVaccineAsAppliedInput): Promise<BabyVaccineRecord> {
    await ensureBabyAccess(this.babyRepository, this.babyGuardianRepository, input.babyId, input.requestingUserId);
 
    const vaccine = await this.vaccineRepository.findById(input.vaccineId);
 
    if (!vaccine) {
      throw new VaccineNotFoundError();
    }
 
    if (vaccine.recommendationKind === 'RECURRING') {
      throw new RecurringVaccineRequiresAdhocRecordError();
    }
 
    const existingRecord = await this.babyVaccineRecordRepository.findByBabyAndVaccine(
      input.babyId,
      input.vaccineId,
    );
 
    const record = BabyVaccineRecord.markApplied({
      id: existingRecord?.id ?? randomUUID(),
      babyId: input.babyId,
      vaccineId: input.vaccineId,
      applicationDate: input.applicationDate ?? new Date(),
      notes: input.notes,
      batchNumber: input.batchNumber,
      location: input.location,
      professional: input.professional,
      photoUrl: input.photoUrl,
    });
 
    await this.babyVaccineRecordRepository.save(record);
 
    return record;
  }
}