All files / src/presentation/http/routes vaccine.routes.ts

98.24% Statements 56/57
80.55% Branches 29/36
100% Functions 11/11
98.24% Lines 56/57

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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371                                                                            325x       15x                                 9x   117x   306x                                         22x 22x 22x 22x 22x           22x           22x         22x         22x           22x                                       12x 12x         9x   3x 2x     1x         22x                                     8x 8x                           4x   4x               4x                                 4x 2x     2x 1x     1x         22x                                         7x 7x           5x   2x 1x     1x         22x                                         12x 12x                           10x               10x   2x 1x     1x       1x         22x                                     5x 5x           1x               1x   4x 3x     1x          
import { z } from 'zod';
import type { App } from '../../../infrastructure/http/build-app';
import { VaccineSchedule } from '../../../application/vaccine/get-baby-vaccine-schedule.use-case';
import { GetBabyVaccineScheduleUseCase } from '../../../application/vaccine/get-baby-vaccine-schedule.use-case';
import { MarkVaccineAsAppliedUseCase } from '../../../application/vaccine/mark-vaccine-as-applied.use-case';
import { RegisterAdhocVaccineUseCase } from '../../../application/vaccine/register-adhoc-vaccine.use-case';
import { ListAdhocVaccineRecordsUseCase } from '../../../application/vaccine/list-adhoc-vaccine-records.use-case';
import { DeleteAdhocVaccineRecordUseCase } from '../../../application/vaccine/delete-adhoc-vaccine-record.use-case';
import { BabyNotFoundError } from '../../../application/baby/errors/baby-not-found.error';
import { VaccineNotFoundError } from '../../../application/vaccine/errors/vaccine-not-found.error';
import { VaccineRecordNotFoundError } from '../../../application/vaccine/errors/vaccine-record-not-found.error';
import { RecurringVaccineRequiresAdhocRecordError } from '../../../application/vaccine/errors/recurring-vaccine-requires-adhoc-record.error';
import { DomainError } from '../../../shared/errors/domain-error';
import { BabyVaccineRecord } from '../../../domain/vaccine/baby-vaccine-record';
import { PrismaBabyRepository } from '../../../infrastructure/database/repositories/prisma-baby.repository';
import { PrismaBabyGuardianRepository } from '../../../infrastructure/database/repositories/prisma-baby-guardian.repository';
import { PrismaVaccineRepository } from '../../../infrastructure/database/repositories/prisma-vaccine.repository';
import { CachedVaccineRepository } from '../../../infrastructure/database/repositories/cached-vaccine.repository';
import { PrismaBabyVaccineRecordRepository } from '../../../infrastructure/database/repositories/prisma-baby-vaccine-record.repository';
import { prisma } from '../../../infrastructure/database/prisma-client';
import { redis } from '../../../infrastructure/cache/redis-client';
import { auditLogger } from '../../../infrastructure/audit/audit-logger.instance';
import { authenticate } from '../plugins/authenticate';
import { authErrorResponseSchema } from '../schemas/auth.schema';
import {
  adhocVaccineListQuerystringSchema,
  adhocVaccineListResponseSchema,
  adhocVaccineRecordParamsSchema,
  adhocVaccineRecordResponseSchema,
  markVaccineAppliedBodySchema,
  markVaccineAppliedParamsSchema,
  registerAdhocVaccineBodySchema,
  vaccineScheduleItemSchema,
  vaccineScheduleParamsSchema,
  vaccineScheduleResponseSchema,
} from '../schemas/vaccine.schema';
 
function toDateOnly(date: Date | null): string | null {
  return date ? date.toISOString().slice(0, 10) : null;
}
 
function toAdhocResponse(record: BabyVaccineRecord) {
  return {
    id: record.id,
    babyId: record.babyId,
    source: record.source as 'CAMPAIGN' | 'CUSTOM',
    customName: record.customName ?? '',
    customDose: record.customDose,
    status: 'APPLIED' as const,
    applicationDate: toDateOnly(record.applicationDate),
    notes: record.notes,
    batchNumber: record.batchNumber,
    location: record.location,
    professional: record.professional,
    photoUrl: record.photoUrl,
  };
}
 
function toScheduleResponse(schedule: VaccineSchedule) {
  return {
    metadata: schedule.metadata,
    groups: schedule.groups.map((group) => ({
      ageInMonths: group.ageInMonths,
      items: group.items.map((item) => ({
        vaccineId: item.vaccineId,
        name: item.name,
        description: item.description,
        guidance: item.guidance,
        doseNumber: item.doseNumber,
        recommendedAgeInMonths: item.recommendedAgeInMonths,
        recommendationKind: item.recommendationKind,
        status: item.status,
        applicationDate: toDateOnly(item.applicationDate),
        notes: item.notes,
        batchNumber: item.batchNumber,
        location: item.location,
        professional: item.professional,
        photoUrl: item.photoUrl,
      })),
    })),
  };
}
 
export async function vaccineRoutes(app: App) {
  const babyRepository = new PrismaBabyRepository(prisma);
  const babyGuardianRepository = new PrismaBabyGuardianRepository(prisma);
  const vaccineRepository = new CachedVaccineRepository(new PrismaVaccineRepository(prisma), redis);
  const babyVaccineRecordRepository = new PrismaBabyVaccineRecordRepository(prisma);
  const getBabyVaccineScheduleUseCase = new GetBabyVaccineScheduleUseCase(
    babyRepository,
    babyGuardianRepository,
    vaccineRepository,
    babyVaccineRecordRepository,
  );
  const markVaccineAsAppliedUseCase = new MarkVaccineAsAppliedUseCase(
    babyRepository,
    babyGuardianRepository,
    vaccineRepository,
    babyVaccineRecordRepository,
  );
  const registerAdhocVaccineUseCase = new RegisterAdhocVaccineUseCase(
    babyRepository,
    babyGuardianRepository,
    babyVaccineRecordRepository,
  );
  const listAdhocVaccineRecordsUseCase = new ListAdhocVaccineRecordsUseCase(
    babyRepository,
    babyGuardianRepository,
    babyVaccineRecordRepository,
  );
  const deleteAdhocVaccineRecordUseCase = new DeleteAdhocVaccineRecordUseCase(
    babyRepository,
    babyGuardianRepository,
    babyVaccineRecordRepository,
  );
 
  app.route({
    method: 'GET',
    url: '/babies/:babyId/vaccines',
    preHandler: authenticate,
    schema: {
      tags: ['Vaccines'],
      summary: "Get a baby's vaccination schedule",
      description:
        'Returns the active official vaccination calendar source and version, grouped by recommended age. ' +
        'Routine entries can be PENDING, DELAYED or APPLIED. Conditional and recurring guidance is never ' +
        'automatically labelled overdue.',
      params: vaccineScheduleParamsSchema,
      response: {
        200: vaccineScheduleResponseSchema,
        401: authErrorResponseSchema,
        404: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      try {
        const schedule = await getBabyVaccineScheduleUseCase.execute({
          babyId: request.params.babyId,
          requestingUserId: request.userId,
        });
 
        return reply.status(200).send(toScheduleResponse(schedule));
      } catch (error) {
        if (error instanceof BabyNotFoundError) {
          return reply.status(404).send({ status: 'error', message: error.message });
        }
 
        throw error;
      }
    },
  });
 
  app.route({
    method: 'PATCH',
    url: '/babies/:babyId/vaccines/:vaccineId/apply',
    preHandler: authenticate,
    schema: {
      tags: ['Vaccines'],
      summary: 'Mark a vaccine dose as applied',
      description: "Records that a vaccine dose was applied, updating the baby's vaccination checklist.",
      params: markVaccineAppliedParamsSchema,
      body: markVaccineAppliedBodySchema,
      response: {
        200: vaccineScheduleItemSchema,
        400: authErrorResponseSchema,
        401: authErrorResponseSchema,
        404: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      try {
        const record = await markVaccineAsAppliedUseCase.execute({
          babyId: request.params.babyId,
          vaccineId: request.params.vaccineId,
          requestingUserId: request.userId,
          applicationDate: request.body.applicationDate
            ? new Date(`${request.body.applicationDate}T00:00:00.000Z`)
            : undefined,
          notes: request.body.notes,
          batchNumber: request.body.batchNumber,
          location: request.body.location,
          professional: request.body.professional,
          photoUrl: request.body.photoUrl,
        });
 
        const vaccine = await vaccineRepository.findById(request.params.vaccineId);
 
        auditLogger.log({
          userId: request.userId,
          action: 'vaccine.apply',
          resourceType: 'BabyVaccineRecord',
          resourceId: record.id,
          babyId: record.babyId,
        });
 
        return reply.status(200).send({
          vaccineId: request.params.vaccineId,
          name: vaccine?.name ?? '',
          description: vaccine?.description ?? '',
          guidance: vaccine?.guidance ?? null,
          doseNumber: vaccine?.doseNumber ?? 0,
          recommendedAgeInMonths: vaccine?.recommendedAgeInMonths ?? 0,
          recommendationKind: vaccine?.recommendationKind ?? 'ROUTINE',
          status: record.status,
          applicationDate: toDateOnly(record.applicationDate),
          notes: record.notes,
          batchNumber: record.batchNumber,
          location: record.location,
          professional: record.professional,
          photoUrl: record.photoUrl,
        });
      } catch (error) {
        if (error instanceof BabyNotFoundError || error instanceof VaccineNotFoundError) {
          return reply.status(404).send({ status: 'error', message: error.message });
        }
 
        if (error instanceof RecurringVaccineRequiresAdhocRecordError) {
          return reply.status(400).send({ status: 'error', message: error.message });
        }
 
        throw error;
      }
    },
  });
 
  app.route({
    method: 'GET',
    url: '/babies/:babyId/vaccines/adhoc',
    preHandler: authenticate,
    schema: {
      tags: ['Vaccines'],
      summary: "List a baby's campaign/custom vaccine records",
      description:
        'Returns vaccines logged by hand (a vaccination campaign or a fully custom entry) rather than applied ' +
        'from the catalog schedule, newest application first. Optionally filtered by `search`, matched ' +
        'case-insensitively against the campaign/custom vaccine name.',
      params: vaccineScheduleParamsSchema,
      querystring: adhocVaccineListQuerystringSchema,
      response: {
        200: adhocVaccineListResponseSchema,
        401: authErrorResponseSchema,
        404: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      try {
        const records = await listAdhocVaccineRecordsUseCase.execute({
          babyId: request.params.babyId,
          requestingUserId: request.userId,
          search: request.query.search,
        });
 
        return reply.status(200).send(records.map(toAdhocResponse));
      } catch (error) {
        if (error instanceof BabyNotFoundError) {
          return reply.status(404).send({ status: 'error', message: error.message });
        }
 
        throw error;
      }
    },
  });
 
  app.route({
    method: 'POST',
    url: '/babies/:babyId/vaccines/adhoc',
    preHandler: authenticate,
    schema: {
      tags: ['Vaccines'],
      summary: 'Register a campaign or custom vaccine',
      description:
        'Logs a vaccine that was not applied from the catalog schedule — a vaccination campaign (e.g. a ' +
        'seasonal flu drive) or a fully custom entry. Always recorded as already applied.',
      params: vaccineScheduleParamsSchema,
      body: registerAdhocVaccineBodySchema,
      response: {
        201: adhocVaccineRecordResponseSchema,
        400: authErrorResponseSchema,
        401: authErrorResponseSchema,
        404: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      try {
        const record = await registerAdhocVaccineUseCase.execute({
          babyId: request.params.babyId,
          requestingUserId: request.userId,
          source: request.body.source,
          customName: request.body.customName,
          customDose: request.body.customDose,
          applicationDate: new Date(`${request.body.applicationDate}T00:00:00.000Z`),
          notes: request.body.notes,
          batchNumber: request.body.batchNumber,
          location: request.body.location,
          professional: request.body.professional,
          photoUrl: request.body.photoUrl,
        });
 
        auditLogger.log({
          userId: request.userId,
          action: 'vaccine.adhoc-create',
          resourceType: 'BabyVaccineRecord',
          resourceId: record.id,
          babyId: record.babyId,
        });
 
        return reply.status(201).send(toAdhocResponse(record));
      } catch (error) {
        if (error instanceof BabyNotFoundError) {
          return reply.status(404).send({ status: 'error', message: error.message });
        }
 
        Iif (error instanceof DomainError) {
          return reply.status(400).send({ status: 'error', message: error.message });
        }
 
        throw error;
      }
    },
  });
 
  app.route({
    method: 'DELETE',
    url: '/babies/:babyId/vaccines/adhoc/:recordId',
    preHandler: authenticate,
    schema: {
      tags: ['Vaccines'],
      summary: 'Delete a campaign or custom vaccine record',
      description:
        'Removes a vaccine that was logged by hand (a vaccination campaign or a fully custom entry) — used ' +
        'to undo a wrong custom/campaign entry. Does not apply to vaccines applied from the catalog schedule.',
      params: adhocVaccineRecordParamsSchema,
      response: {
        204: z.null().describe('Vaccine record deleted successfully'),
        401: authErrorResponseSchema,
        404: authErrorResponseSchema,
        500: authErrorResponseSchema,
      },
    },
    handler: async (request, reply) => {
      try {
        await deleteAdhocVaccineRecordUseCase.execute({
          babyId: request.params.babyId,
          recordId: request.params.recordId,
          requestingUserId: request.userId,
        });
 
        auditLogger.log({
          userId: request.userId,
          action: 'vaccine.delete',
          resourceType: 'BabyVaccineRecord',
          resourceId: request.params.recordId,
          babyId: request.params.babyId,
        });
 
        return reply.status(204).send(null);
      } catch (error) {
        if (error instanceof BabyNotFoundError || error instanceof VaccineRecordNotFoundError) {
          return reply.status(404).send({ status: 'error', message: error.message });
        }
 
        throw error;
      }
    },
  });
}