diff --git a/apps/backend/src/app.module.ts b/apps/backend/src/app.module.ts index 4a4710ea6..eb84e0453 100644 --- a/apps/backend/src/app.module.ts +++ b/apps/backend/src/app.module.ts @@ -1,4 +1,5 @@ import { Module } from '@nestjs/common'; +import { ScheduleModule } from '@nestjs/schedule'; import { TypeOrmModule } from '@nestjs/typeorm'; import { ConfigModule, ConfigService } from '@nestjs/config'; import typeorm from './config/typeorm'; @@ -9,6 +10,7 @@ import { CoordinatorsModule } from './coordinators/coordinators.module'; import { VolunteersModule } from './volunteers/volunteers.module'; import { OwnersModule } from './owners/owners.module'; import { AnimalsModule } from './animals/animals.module'; +import { JobsModule } from './jobs/jobs.module'; @Module({ imports: [ @@ -21,6 +23,7 @@ import { AnimalsModule } from './animals/animals.module'; useFactory: (configService: ConfigService) => configService.getOrThrow('typeorm'), }), + ScheduleModule.forRoot(), CognitoModule, RecommendationsModule, MatchesModule, @@ -28,6 +31,7 @@ import { AnimalsModule } from './animals/animals.module'; VolunteersModule, OwnersModule, AnimalsModule, + JobsModule, ], }) export class AppModule {} diff --git a/apps/backend/src/config/migrations.ts b/apps/backend/src/config/migrations.ts index f702dcdd8..20c5db75b 100644 --- a/apps/backend/src/config/migrations.ts +++ b/apps/backend/src/config/migrations.ts @@ -12,6 +12,7 @@ import { AddAnimalUpdatesAndFosterTypeArray1793163582751 } from '../migrations/1 import { AddFarmAnimalsToFosterType1793476100199 } from '../migrations/1793476100199-AddFarmAnimalsToFosterType'; import { RenameAdminUsersToOwners1793485161630 } from '../migrations/1793485161630-RenameAdminUsersToOwners'; import { AddFosterTypePreferences1793600000000 } from '../migrations/1793600000000-AddFosterTypePreferences'; +import { AddPetsAndHouseholdDetails1794408338094 } from '../migrations/1794408338094-AddPetsAndHouseholdDetails'; const schemaMigrations = [ InitialSchemas1789354568323, @@ -28,6 +29,7 @@ const schemaMigrations = [ AddFarmAnimalsToFosterType1793476100199, RenameAdminUsersToOwners1793485161630, AddFosterTypePreferences1793600000000, + AddPetsAndHouseholdDetails1794408338094, ]; export default schemaMigrations; diff --git a/apps/backend/src/jobs/age-jobs.service.spec.ts b/apps/backend/src/jobs/age-jobs.service.spec.ts new file mode 100644 index 000000000..fd4ad5dfb --- /dev/null +++ b/apps/backend/src/jobs/age-jobs.service.spec.ts @@ -0,0 +1,92 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { Logger } from '@nestjs/common'; +import { SCHEDULE_CRON_OPTIONS } from '@nestjs/schedule/dist/schedule.constants'; +import { AgeJobsService } from './age-jobs.service'; +import { PetsService } from '../pets/pets.service'; +import { VolunteersService } from '../volunteers/volunteers.service'; + +describe('AgeJobsService', () => { + let service: AgeJobsService; + let mockPetsService: { incrementAllAges: jest.Mock }; + let mockVolunteersService: { incrementAllChildrenAges: jest.Mock }; + let errorSpy: jest.SpyInstance; + + beforeEach(async () => { + mockPetsService = { incrementAllAges: jest.fn() }; + mockVolunteersService = { incrementAllChildrenAges: jest.fn() }; + jest.spyOn(Logger.prototype, 'log').mockImplementation(); + errorSpy = jest.spyOn(Logger.prototype, 'error').mockImplementation(); + + const module: TestingModule = await Test.createTestingModule({ + providers: [ + AgeJobsService, + { provide: PetsService, useValue: mockPetsService }, + { provide: VolunteersService, useValue: mockVolunteersService }, + ], + }).compile(); + + service = module.get(AgeJobsService); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + describe('incrementPetAges', () => { + it('calls PetsService.incrementAllAges once', async () => { + mockPetsService.incrementAllAges.mockResolvedValue(3); + await service.incrementPetAges(); + + expect(mockPetsService.incrementAllAges).toHaveBeenCalledTimes(1); + }); + + it('logs and swallows a failure', async () => { + mockPetsService.incrementAllAges.mockRejectedValue(new Error('db down')); + + await expect(service.incrementPetAges()).resolves.toBeUndefined(); + expect(errorSpy).toHaveBeenCalled(); + }); + }); + + describe('incrementChildrenAges', () => { + it('calls VolunteersService.incrementAllChildrenAges once', async () => { + mockVolunteersService.incrementAllChildrenAges.mockResolvedValue(2); + await service.incrementChildrenAges(); + + expect( + mockVolunteersService.incrementAllChildrenAges, + ).toHaveBeenCalledTimes(1); + }); + + it('logs and swallows a failure', async () => { + mockVolunteersService.incrementAllChildrenAges.mockRejectedValue( + new Error('db down'), + ); + + await expect(service.incrementChildrenAges()).resolves.toBeUndefined(); + expect(errorSpy).toHaveBeenCalled(); + }); + }); + + describe('schedules', () => { + const cronOptions = (method: keyof AgeJobsService) => + Reflect.getMetadata( + SCHEDULE_CRON_OPTIONS, + AgeJobsService.prototype[method], + ); + + it('runs incrementPetAges at midnight on the first of each month, Eastern', () => { + expect(cronOptions('incrementPetAges')).toMatchObject({ + cronTime: '0 0 1 * *', + timeZone: 'America/New_York', + }); + }); + + it('runs incrementChildrenAges at midnight on January 1, Eastern', () => { + expect(cronOptions('incrementChildrenAges')).toMatchObject({ + cronTime: '0 0 1 1 *', + timeZone: 'America/New_York', + }); + }); + }); +}); diff --git a/apps/backend/src/jobs/age-jobs.service.ts b/apps/backend/src/jobs/age-jobs.service.ts new file mode 100644 index 000000000..da54497b7 --- /dev/null +++ b/apps/backend/src/jobs/age-jobs.service.ts @@ -0,0 +1,48 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { Cron } from '@nestjs/schedule'; +import { PetsService } from '../pets/pets.service'; +import { VolunteersService } from '../volunteers/volunteers.service'; + +const SCHEDULE_TIME_ZONE = 'America/New_York'; + +@Injectable() +export class AgeJobsService { + private readonly logger = new Logger(AgeJobsService.name); + + constructor( + private petsService: PetsService, + private volunteersService: VolunteersService, + ) {} + + /** + * Ages every pet by one month. Runs at midnight on the first of each month. + */ + @Cron('0 0 1 * *', { timeZone: SCHEDULE_TIME_ZONE }) + async incrementPetAges(): Promise { + try { + const count = await this.petsService.incrementAllAges(); + this.logger.log(`Incremented age of ${count} pets`); + } catch (err) { + this.logger.error( + 'Failed to increment pet ages', + err instanceof Error ? err.stack : String(err), + ); + } + } + + /** + * Ages every child by one year. Runs at midnight on January 1. + */ + @Cron('0 0 1 1 *', { timeZone: SCHEDULE_TIME_ZONE }) + async incrementChildrenAges(): Promise { + try { + const count = await this.volunteersService.incrementAllChildrenAges(); + this.logger.log(`Incremented children's ages for ${count} volunteers`); + } catch (err) { + this.logger.error( + "Failed to increment children's ages", + err instanceof Error ? err.stack : String(err), + ); + } + } +} diff --git a/apps/backend/src/jobs/jobs.module.ts b/apps/backend/src/jobs/jobs.module.ts new file mode 100644 index 000000000..2072bb325 --- /dev/null +++ b/apps/backend/src/jobs/jobs.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { PetsModule } from '../pets/pets.module'; +import { VolunteersModule } from '../volunteers/volunteers.module'; +import { AgeJobsService } from './age-jobs.service'; + +@Module({ + imports: [PetsModule, VolunteersModule], + providers: [AgeJobsService], +}) +export class JobsModule {} diff --git a/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts b/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts new file mode 100644 index 000000000..aeed39aa7 --- /dev/null +++ b/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts @@ -0,0 +1,62 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddPetsAndHouseholdDetails1794408338094 + implements MigrationInterface +{ + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + CREATE TABLE "pets" ( + "pet_id" SERIAL PRIMARY KEY, + "volunteer_id" int NOT NULL + REFERENCES "foster_volunteers" ("volunteer_id") ON DELETE CASCADE, + "age_year" int NOT NULL, + "age_month" int NOT NULL, + "species" "foster_type_enum" NOT NULL, + "breed" varchar(255) NOT NULL, + CONSTRAINT "CHK_pets_age_year" CHECK ("age_year" >= 0), + CONSTRAINT "CHK_pets_age_month" CHECK ("age_month" BETWEEN 0 AND 11) + ) + `); + + await queryRunner.query(` + ALTER TABLE "foster_volunteers" + ADD COLUMN "has_children" boolean NOT NULL DEFAULT false, + ADD COLUMN "children_ages" int[] NOT NULL DEFAULT '{}', + ADD COLUMN "has_separate_foster_room" boolean NOT NULL DEFAULT false, + ADD COLUMN "lively_neighborhood" boolean NOT NULL DEFAULT false, + DROP COLUMN "resident_animals" + `); + + await queryRunner.query(` + ALTER TABLE "foster_volunteers" + ALTER COLUMN "has_children" DROP DEFAULT, + ALTER COLUMN "has_separate_foster_room" DROP DEFAULT, + ALTER COLUMN "lively_neighborhood" DROP DEFAULT, + ADD CONSTRAINT "CHK_foster_volunteers_children_ages" CHECK ( + ("has_children" AND cardinality("children_ages") > 0) + OR (NOT "has_children" AND cardinality("children_ages") = 0) + ), + ADD CONSTRAINT "CHK_foster_volunteers_children_ages_nonnegative" + CHECK (0 <= ALL ("children_ages")) + `); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + ALTER TABLE "foster_volunteers" + DROP CONSTRAINT "CHK_foster_volunteers_children_ages_nonnegative", + DROP CONSTRAINT "CHK_foster_volunteers_children_ages", + DROP COLUMN "lively_neighborhood", + DROP COLUMN "has_separate_foster_room", + DROP COLUMN "children_ages", + DROP COLUMN "has_children", + ADD COLUMN "resident_animals" text NOT NULL DEFAULT '' + `); + + await queryRunner.query(` + ALTER TABLE "foster_volunteers" ALTER COLUMN "resident_animals" DROP DEFAULT + `); + + await queryRunner.query(`DROP TABLE "pets"`); + } +} diff --git a/apps/backend/src/pets/dtos/pet.dto.ts b/apps/backend/src/pets/dtos/pet.dto.ts new file mode 100644 index 000000000..120663f89 --- /dev/null +++ b/apps/backend/src/pets/dtos/pet.dto.ts @@ -0,0 +1,21 @@ +import { IsEnum, IsInt, Max, MaxLength, Min } from 'class-validator'; +import { FosterType } from '../../volunteers/volunteers.types'; +import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.decorator'; + +export class PetDto { + @IsInt() + @Min(0) + ageYear!: number; + + @IsInt() + @Min(0) + @Max(11) + ageMonth!: number; + + @IsEnum(FosterType) + species!: FosterType; + + @IsNonEmptyString() + @MaxLength(255) + breed!: string; +} diff --git a/apps/backend/src/pets/pets.entity.ts b/apps/backend/src/pets/pets.entity.ts new file mode 100644 index 000000000..eb3997b02 --- /dev/null +++ b/apps/backend/src/pets/pets.entity.ts @@ -0,0 +1,41 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + JoinColumn, + Check, +} from 'typeorm'; +import { FosterVolunteer } from '../volunteers/volunteers.entity'; +import { FosterType } from '../volunteers/volunteers.types'; + +@Entity('pets') +@Check('CHK_pets_age_year', '"age_year" >= 0') +@Check('CHK_pets_age_month', '"age_month" BETWEEN 0 AND 11') +export class Pet { + @PrimaryGeneratedColumn({ name: 'pet_id' }) + petId!: number; + + @ManyToOne(() => FosterVolunteer, (volunteer) => volunteer.pets, { + nullable: false, + onDelete: 'CASCADE', + orphanedRowAction: 'delete', + }) + @JoinColumn({ name: 'volunteer_id' }) + volunteer!: FosterVolunteer; + + @Column({ name: 'volunteer_id' }) + volunteerId!: number; + + @Column({ name: 'age_year', type: 'int' }) + ageYear!: number; + + @Column({ name: 'age_month', type: 'int' }) + ageMonth!: number; + + @Column({ type: 'enum', enum: FosterType, enumName: 'foster_type_enum' }) + species!: FosterType; + + @Column({ type: 'varchar', length: 255 }) + breed!: string; +} diff --git a/apps/backend/src/pets/pets.module.ts b/apps/backend/src/pets/pets.module.ts new file mode 100644 index 000000000..a0a444008 --- /dev/null +++ b/apps/backend/src/pets/pets.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { TypeOrmModule } from '@nestjs/typeorm'; +import { Pet } from './pets.entity'; +import { PetsService } from './pets.service'; + +@Module({ + imports: [TypeOrmModule.forFeature([Pet])], + providers: [PetsService], + exports: [PetsService], +}) +export class PetsModule {} diff --git a/apps/backend/src/pets/pets.service.spec.ts b/apps/backend/src/pets/pets.service.spec.ts new file mode 100644 index 000000000..5d4879d22 --- /dev/null +++ b/apps/backend/src/pets/pets.service.spec.ts @@ -0,0 +1,75 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { getRepositoryToken } from '@nestjs/typeorm'; +import { PetsService } from './pets.service'; +import { Pet } from './pets.entity'; + +describe('PetsService', () => { + let service: PetsService; + let mockRepo: { find: jest.Mock; save: jest.Mock }; + + const pet = (ageYear: number, ageMonth: number) => + ({ ageYear, ageMonth } as Pet); + + beforeEach(async () => { + mockRepo = { find: jest.fn(), save: jest.fn() }; + + const module: TestingModule = await Test.createTestingModule({ + providers: [ + PetsService, + { provide: getRepositoryToken(Pet), useValue: mockRepo }, + ], + }).compile(); + + service = module.get(PetsService); + }); + + describe('incrementAllAges', () => { + it('adds one month to a pet under 11 months', async () => { + mockRepo.find.mockResolvedValue([pet(1, 5)]); + + await service.incrementAllAges(); + + expect(mockRepo.save).toHaveBeenCalledWith([ + expect.objectContaining({ ageYear: 1, ageMonth: 6 }), + ]); + expect(mockRepo.save).toHaveBeenCalledTimes(1); + }); + + it('rolls 11 months into the next year', async () => { + mockRepo.find.mockResolvedValue([pet(2, 11)]); + + await service.incrementAllAges(); + + expect(mockRepo.save).toHaveBeenCalledWith([ + expect.objectContaining({ ageYear: 3, ageMonth: 0 }), + ]); + expect(mockRepo.save).toHaveBeenCalledTimes(1); + }); + + it('increments every pet independently', async () => { + mockRepo.find.mockResolvedValue([pet(0, 0), pet(0, 11), pet(4, 3)]); + + await service.incrementAllAges(); + + expect(mockRepo.save).toHaveBeenCalledWith([ + expect.objectContaining({ ageYear: 0, ageMonth: 1 }), + expect.objectContaining({ ageYear: 1, ageMonth: 0 }), + expect.objectContaining({ ageYear: 4, ageMonth: 4 }), + ]); + expect(mockRepo.save).toHaveBeenCalledTimes(1); + }); + + it('returns the number of pets updated', async () => { + mockRepo.find.mockResolvedValue([pet(1, 1), pet(2, 2)]); + + await expect(service.incrementAllAges()).resolves.toBe(2); + }); + + it('does not save when there are no pets', async () => { + mockRepo.find.mockResolvedValue([]); + + await expect(service.incrementAllAges()).resolves.toBe(0); + expect(mockRepo.save).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/apps/backend/src/pets/pets.service.ts b/apps/backend/src/pets/pets.service.ts new file mode 100644 index 000000000..8065904b7 --- /dev/null +++ b/apps/backend/src/pets/pets.service.ts @@ -0,0 +1,32 @@ +import { Injectable } from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; +import { Pet } from './pets.entity'; + +const MONTHS_PER_YEAR = 12; + +@Injectable() +export class PetsService { + constructor(@InjectRepository(Pet) private repo: Repository) {} + + /** + * Ages every pet by one month, rolling into the next year after month 11. + * + * @returns The number of pets updated. + */ + async incrementAllAges(): Promise { + const pets = await this.repo.find(); + if (pets.length === 0) { + return 0; + } + + for (const pet of pets) { + const totalMonths = pet.ageYear * MONTHS_PER_YEAR + pet.ageMonth + 1; + pet.ageYear = Math.floor(totalMonths / MONTHS_PER_YEAR); + pet.ageMonth = totalMonths % MONTHS_PER_YEAR; + } + + await this.repo.save(pets); + return pets.length; + } +} diff --git a/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts b/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts index ae9f547ce..a720d8380 100644 --- a/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts +++ b/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts @@ -2,19 +2,24 @@ import { ArrayNotEmpty, ArrayUnique, IsArray, + IsBoolean, IsEmail, IsEnum, + IsInt, IsNotEmpty, IsPhoneNumber, IsString, IsStrongPassword, MaxLength, + Min, ValidateIf, + ValidateNested, } from 'class-validator'; -import { Transform } from 'class-transformer'; +import { Transform, Type } from 'class-transformer'; import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.decorator'; import { Homebase } from '../../types'; import { FosterTraining, FosterType } from '../volunteers.types'; +import { PetDto } from '../../pets/dtos/pet.dto'; export class CreateVolunteerDto { @IsNonEmptyString() @@ -70,8 +75,26 @@ export class CreateVolunteerDto { @IsEnum(Homebase) homebase!: Homebase; - @IsNonEmptyString() - residentAnimals!: string; + @IsBoolean() + hasChildren!: boolean; + + @ValidateIf((_, value) => value !== undefined) + @IsArray() + @IsInt({ each: true }) + @Min(0, { each: true }) + childrenAges?: number[]; + + @IsBoolean() + hasSeparateFosterRoom!: boolean; + + @IsBoolean() + livelyNeighborhood!: boolean; + + @ValidateIf((_, value) => value !== undefined) + @IsArray() + @ValidateNested({ each: true }) + @Type(() => PetDto) + pets?: PetDto[]; @ValidateIf((_, value) => value !== undefined && value !== null) @IsNonEmptyString() diff --git a/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts b/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts index 95acb7610..048b0e87d 100644 --- a/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts +++ b/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts @@ -4,14 +4,19 @@ import { IsArray, IsBoolean, IsEnum, + IsInt, IsNotEmpty, MaxLength, + Min, IsPhoneNumber, IsEmail, ArrayUnique, ValidateIf, + ValidateNested, } from 'class-validator'; +import { Type } from 'class-transformer'; import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.decorator'; +import { PetDto } from '../../pets/dtos/pet.dto'; import { AtLeastOneValue } from './validators/at-least-one-value.validator'; @AtLeastOneValue([ @@ -23,7 +28,11 @@ import { AtLeastOneValue } from './validators/at-least-one-value.validator'; 'address', 'city', 'zipcode', - 'residentAnimals', + 'hasChildren', + 'childrenAges', + 'hasSeparateFosterRoom', + 'livelyNeighborhood', + 'pets', 'notes', 'fosterType', 'animalUpdates', @@ -71,8 +80,28 @@ export class UpdateVolunteerDto { zipcode?: string; @ValidateIf((_, value) => value !== undefined) - @IsNonEmptyString() - residentAnimals?: string; + @IsBoolean() + hasChildren?: boolean; + + @ValidateIf((_, value) => value !== undefined) + @IsArray() + @IsInt({ each: true }) + @Min(0, { each: true }) + childrenAges?: number[]; + + @ValidateIf((_, value) => value !== undefined) + @IsBoolean() + hasSeparateFosterRoom?: boolean; + + @ValidateIf((_, value) => value !== undefined) + @IsBoolean() + livelyNeighborhood?: boolean; + + @ValidateIf((_, value) => value !== undefined) + @IsArray() + @ValidateNested({ each: true }) + @Type(() => PetDto) + pets?: PetDto[]; @ValidateIf((_, value) => value !== undefined && value !== null) @IsNonEmptyString() diff --git a/apps/backend/src/volunteers/volunteers.controller.spec.ts b/apps/backend/src/volunteers/volunteers.controller.spec.ts index 332b741aa..a990caa8a 100644 --- a/apps/backend/src/volunteers/volunteers.controller.spec.ts +++ b/apps/backend/src/volunteers/volunteers.controller.spec.ts @@ -24,6 +24,7 @@ import { UpdateSpeciesPreferencesDto } from './dtos/update-species-preferences.d import { CoordinatorUpdateVolunteerDto } from './dtos/coordinator-update-volunteer.dto'; import { Homebase } from '../types'; import { UpdateHomebaseDto } from './dtos/update-homebase.dto'; +import { PetDto } from '../pets/dtos/pet.dto'; describe('VolunteersController', () => { let controller: VolunteersController; @@ -163,7 +164,9 @@ describe('VolunteersController', () => { city: 'Boston', zipcode: '02130', homebase: Homebase.BOSTON, - residentAnimals: 'One cat', + hasChildren: false, + hasSeparateFosterRoom: true, + livelyNeighborhood: false, fosterType: [FosterType.CAT], password: 'Str0ng!Password', } as CreateVolunteerDto; @@ -224,6 +227,24 @@ describe('VolunteersController', () => { expect(result).not.toHaveProperty('completedTrainings'); }); + + const pet = { + ageYear: 3, + ageMonth: 11, + species: FosterType.CAT, + breed: 'Tabby', + } as PetDto; + + it('accepts a volunteer with pets and children', async () => { + const result = await validationPipe.transform( + { ...dto, hasChildren: true, childrenAges: [4, 9], pets: [pet] }, + { type: 'body', metatype: CreateVolunteerDto }, + ); + + expect(result.hasChildren).toBe(true); + expect(result.childrenAges).toEqual([4, 9]); + expect(result.pets).toEqual([pet]); + }); }); describe('confirm', () => { @@ -301,6 +322,7 @@ describe('VolunteersController', () => { const result = await controller.getVolunteerById(1); expect(result).toEqual(mockVolunteer); + expect(mockVolunteersService.findByIdOrFail).toHaveBeenCalledTimes(1); expect(mockVolunteersService.findByIdOrFail).toHaveBeenCalledWith(1); }); diff --git a/apps/backend/src/volunteers/volunteers.controller.ts b/apps/backend/src/volunteers/volunteers.controller.ts index 86f83b8c2..27cfc0c5a 100644 --- a/apps/backend/src/volunteers/volunteers.controller.ts +++ b/apps/backend/src/volunteers/volunteers.controller.ts @@ -187,7 +187,8 @@ export class VolunteersController { }) @ApiResponse({ status: HttpStatus.BAD_REQUEST, - description: 'Invalid ID or invalid field', + description: + 'Invalid ID, invalid field, no fields provided, or childrenAges does not match hasChildren', }) @ApiResponse({ status: HttpStatus.NOT_FOUND, @@ -216,6 +217,15 @@ export class VolunteersController { description: 'The volunteer was updated', type: VolunteerWithoutPrivateFields, }) + @ApiResponse({ + status: HttpStatus.BAD_REQUEST, + description: + 'Invalid ID, invalid field, no fields provided, or childrenAges does not match hasChildren', + }) + @ApiResponse({ + status: HttpStatus.NOT_FOUND, + description: 'The volunteer does not exist', + }) async updateVolunteerById( @Param('volunteerId', ParseIntPipe) volunteerId: number, @Body() dto: UpdateVolunteerDto, diff --git a/apps/backend/src/volunteers/volunteers.entity.ts b/apps/backend/src/volunteers/volunteers.entity.ts index 514475eaa..e7ed33da0 100644 --- a/apps/backend/src/volunteers/volunteers.entity.ts +++ b/apps/backend/src/volunteers/volunteers.entity.ts @@ -3,8 +3,10 @@ import { PrimaryGeneratedColumn, Column, ManyToMany, + OneToMany, JoinTable, Unique, + Check, } from 'typeorm'; import { Homebase } from '../types'; import { @@ -13,9 +15,18 @@ import { VolunteerStatus, } from './volunteers.types'; import { FosterCoordinator } from '../coordinators/coordinators.entity'; +import { Pet } from '../pets/pets.entity'; @Entity('foster_volunteers') @Unique('UQ_foster_volunteers_email', ['email']) +@Check( + 'CHK_foster_volunteers_children_ages', + '("has_children" AND cardinality("children_ages") > 0) OR (NOT "has_children" AND cardinality("children_ages") = 0)', +) +@Check( + 'CHK_foster_volunteers_children_ages_nonnegative', + '0 <= ALL ("children_ages")', +) export class FosterVolunteer { @PrimaryGeneratedColumn({ name: 'volunteer_id' }) volunteerId!: number; @@ -52,8 +63,25 @@ export class FosterVolunteer { @Column({ type: 'enum', enum: Homebase }) homebase!: Homebase; - @Column({ name: 'resident_animals', type: 'text' }) - residentAnimals!: string; + @Column({ name: 'has_children', type: 'boolean' }) + hasChildren!: boolean; + + @Column({ + name: 'children_ages', + type: 'int', + array: true, + default: () => "'{}'", + }) + childrenAges!: number[]; + + @Column({ name: 'has_separate_foster_room', type: 'boolean' }) + hasSeparateFosterRoom!: boolean; + + @Column({ name: 'lively_neighborhood', type: 'boolean' }) + livelyNeighborhood!: boolean; + + @OneToMany(() => Pet, (pet) => pet.volunteer, { cascade: true }) + pets!: Pet[]; @Column({ type: 'text', nullable: true }) notes!: string | null; diff --git a/apps/backend/src/volunteers/volunteers.module.ts b/apps/backend/src/volunteers/volunteers.module.ts index 22bff765f..a9c16f5c4 100644 --- a/apps/backend/src/volunteers/volunteers.module.ts +++ b/apps/backend/src/volunteers/volunteers.module.ts @@ -1,6 +1,7 @@ import { Module, forwardRef } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { FosterVolunteer } from './volunteers.entity'; +import { Pet } from '../pets/pets.entity'; import { VolunteersController } from './volunteers.controller'; import { VolunteersService } from './volunteers.service'; import { CoordinatorsModule } from '../coordinators/coordinators.module'; @@ -10,7 +11,7 @@ import { AnimalsModule } from '../animals/animals.module'; @Module({ imports: [ - TypeOrmModule.forFeature([FosterVolunteer]), + TypeOrmModule.forFeature([FosterVolunteer, Pet]), CoordinatorsModule, AWSSESModule, forwardRef(() => MatchesModule), diff --git a/apps/backend/src/volunteers/volunteers.service.spec.ts b/apps/backend/src/volunteers/volunteers.service.spec.ts index d61193f0b..63d36bec7 100644 --- a/apps/backend/src/volunteers/volunteers.service.spec.ts +++ b/apps/backend/src/volunteers/volunteers.service.spec.ts @@ -24,6 +24,8 @@ import { AnimalsService } from '../animals/animals.service'; import { CoordinatorsService } from '../coordinators/coordinators.service'; import { FosterCoordinator } from '../coordinators/coordinators.entity'; import { Homebase } from '../types'; +import { Pet } from '../pets/pets.entity'; +import { PetDto } from '../pets/dtos/pet.dto'; describe('VolunteersService', () => { let service: VolunteersService; @@ -33,6 +35,9 @@ describe('VolunteersService', () => { firstName: 'Jane', lastName: 'Doe', notes: 'likes cats', + hasChildren: false, + childrenAges: [] as number[], + pets: [] as Pet[], assignedCoordinators: [] as FosterCoordinator[], } as FosterVolunteer; @@ -97,8 +102,12 @@ describe('VolunteersService', () => { }); describe('findByIdOrFail', () => { - it('returns the volunteer when one with the id exists', async () => { - const volunteer = { volunteerId: 7 } as FosterVolunteer; + it('returns the volunteer with their coordinators and pets', async () => { + const volunteer = { + volunteerId: 7, + assignedCoordinators: [] as FosterCoordinator[], + pets: [] as Pet[], + } as FosterVolunteer; mockRepo.findOne.mockResolvedValue(volunteer); const result = await service.findByIdOrFail(7); @@ -106,7 +115,7 @@ describe('VolunteersService', () => { expect(result).toBe(volunteer); expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 7 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.findOne).toHaveBeenCalledTimes(1); }); @@ -119,7 +128,7 @@ describe('VolunteersService', () => { ); expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 7 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); }); @@ -184,7 +193,9 @@ describe('VolunteersService', () => { city: 'Boston', zipcode: '02130', homebase: Homebase.BOSTON, - residentAnimals: 'One cat', + hasChildren: false, + hasSeparateFosterRoom: true, + livelyNeighborhood: false, notes: 'Prefers kittens', fosterType: [FosterType.CAT], password: 'Str0ng!Password', @@ -240,6 +251,8 @@ describe('VolunteersService', () => { expect(mockRepo.save).toHaveBeenCalledTimes(1); expect(mockRepo.save).toHaveBeenCalledWith({ ...profile, + childrenAges: [], + pets: [], status: VolunteerStatus.PENDING, mostRecentWaiverSigned: true, cognitoSub: 'cognito-sub-123', @@ -248,6 +261,8 @@ describe('VolunteersService', () => { expect(result).toEqual({ volunteerId: 1, ...profile, + childrenAges: [], + pets: [], status: VolunteerStatus.PENDING, mostRecentWaiverSigned: true, cognitoSub: 'cognito-sub-123', @@ -256,6 +271,51 @@ describe('VolunteersService', () => { expect(result).not.toHaveProperty('password'); }); + it('saves a volunteer with pets and children', async () => { + const pets = [ + { ageYear: 2, ageMonth: 3, species: FosterType.DOG, breed: 'Beagle' }, + { ageYear: 0, ageMonth: 8, species: FosterType.CAT, breed: 'Tabby' }, + ]; + + const result = await service.create({ + ...dto, + hasChildren: true, + childrenAges: [4, 9], + pets, + }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith( + expect.objectContaining({ + hasChildren: true, + childrenAges: [4, 9], + pets, + }), + ); + expect(result.pets).toEqual(pets); + expect(result.childrenAges).toEqual([4, 9]); + }); + + it.each([ + [ + true, + undefined, + 'childrenAges must not be empty when hasChildren is true', + ], + [true, [], 'childrenAges must not be empty when hasChildren is true'], + [false, [3], 'childrenAges must be empty when hasChildren is false'], + ])( + 'rejects hasChildren %s with childrenAges %j before touching Cognito', + async (hasChildren, childrenAges, message) => { + await expect( + service.create({ ...dto, hasChildren, childrenAges }), + ).rejects.toThrow(new BadRequestException(message)); + expect(mockRepo.findOneBy).not.toHaveBeenCalled(); + expect(mockCognitoService.signUpUser).not.toHaveBeenCalled(); + expect(mockRepo.save).not.toHaveBeenCalled(); + }, + ); + it('saves the completed trainings given at sign-up', async () => { const result = await service.create({ ...dto, @@ -540,7 +600,7 @@ describe('VolunteersService', () => { expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.save).toHaveBeenCalledWith({ ...volunteer, @@ -616,7 +676,7 @@ describe('VolunteersService', () => { expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.save).toHaveBeenCalledWith({ ...volunteer, @@ -679,7 +739,7 @@ describe('VolunteersService', () => { expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); }); @@ -811,9 +871,240 @@ describe('VolunteersService', () => { ); expect(mockRepo.save).not.toHaveBeenCalled(); }); + + it('rejects an update that breaks the children rule and saves nothing', async () => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + hasChildren: true, + childrenAges: [6], + }); + + await expect( + service.coordinatorUpdateVolunteerById(1, { childrenAges: [] }), + ).rejects.toThrow( + new BadRequestException( + 'childrenAges must not be empty when hasChildren is true', + ), + ); + expect(mockRepo.findOne).toHaveBeenCalledTimes(1); + expect(mockRepo.save).not.toHaveBeenCalled(); + }); + + it('clears the saved children ages when hasChildren is set to false', async () => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + hasChildren: true, + childrenAges: [6], + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.coordinatorUpdateVolunteerById(1, { + hasChildren: false, + }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + hasChildren: false, + childrenAges: [], + }); + expect(result.childrenAges).toEqual([]); + }); + + it('replaces the pets list when pets is provided', async () => { + const newPets = [ + { ageYear: 1, ageMonth: 6, species: FosterType.CAT, breed: 'Siamese' }, + { ageYear: 8, ageMonth: 0, species: FosterType.DOG, breed: 'Beagle' }, + ] as PetDto[]; + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + pets: [ + { petId: 5, breed: 'Lab' } as Pet, + { petId: 6, breed: 'Tabby' } as Pet, + ], + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.coordinatorUpdateVolunteerById(1, { + pets: newPets, + }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + pets: newPets, + }); + expect(result.pets).toEqual(newPets); + }); }); describe('updateVolunteerById', () => { + const existingPet = { + petId: 5, + volunteerId: 1, + ageYear: 4, + ageMonth: 2, + species: FosterType.DOG, + breed: 'Lab', + } as Pet; + const newPet = { + ageYear: 1, + ageMonth: 6, + species: FosterType.CAT, + breed: 'Siamese', + } as PetDto; + + it('updates livelyNeighborhood', async () => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + livelyNeighborhood: false, + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.updateVolunteerById(1, { + livelyNeighborhood: true, + }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + livelyNeighborhood: true, + }); + expect(result.livelyNeighborhood).toBe(true); + }); + + it('replaces the pets list when pets is provided', async () => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + pets: [existingPet], + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.updateVolunteerById(1, { pets: [newPet] }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + pets: [newPet], + }); + expect(result.pets).toEqual([newPet]); + }); + + it('clears the pets with an empty list', async () => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + pets: [existingPet], + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.updateVolunteerById(1, { pets: [] }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + pets: [], + }); + expect(result.pets).toEqual([]); + }); + + it('leaves the pets unchanged when pets is omitted', async () => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + pets: [existingPet], + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.updateVolunteerById(1, { notes: 'x' }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + notes: 'x', + pets: [existingPet], + }); + expect(result.pets).toEqual([existingPet]); + }); + + it('adds children with their ages', async () => { + mockRepo.findOne.mockResolvedValue({ ...mockVolunteer }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.updateVolunteerById(1, { + hasChildren: true, + childrenAges: [6], + }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + hasChildren: true, + childrenAges: [6], + }); + expect(result.hasChildren).toBe(true); + expect(result.childrenAges).toEqual([6]); + }); + + it.each([ + ['hasChildren false alone', { hasChildren: false }], + [ + 'hasChildren false with empty ages', + { hasChildren: false, childrenAges: [] }, + ], + ])('removes children and clears the saved ages with %s', async (_, dto) => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + hasChildren: true, + childrenAges: [6], + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.updateVolunteerById(1, dto); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + hasChildren: false, + childrenAges: [], + }); + expect(result.hasChildren).toBe(false); + expect(result.childrenAges).toEqual([]); + }); + + it.each([ + [ + 'hasChildren false sent with ages', + { hasChildren: true, childrenAges: [6] }, + { hasChildren: false, childrenAges: [6] }, + 'childrenAges must be empty when hasChildren is false', + ], + [ + 'clearing ages while hasChildren stays true', + { hasChildren: true, childrenAges: [6] }, + { childrenAges: [] }, + 'childrenAges must not be empty when hasChildren is true', + ], + [ + 'hasChildren true with no ages saved or sent', + { hasChildren: false, childrenAges: [] }, + { hasChildren: true }, + 'childrenAges must not be empty when hasChildren is true', + ], + [ + 'ages while hasChildren stays false', + { hasChildren: false, childrenAges: [] }, + { childrenAges: [3] }, + 'childrenAges must be empty when hasChildren is false', + ], + ])('rejects %s and saves nothing', async (_, saved, dto, message) => { + mockRepo.findOne.mockResolvedValue({ ...mockVolunteer, ...saved }); + + await expect(service.updateVolunteerById(1, dto)).rejects.toThrow( + new BadRequestException(message), + ); + expect(mockRepo.findOne).toHaveBeenCalledTimes(1); + expect(mockRepo.save).not.toHaveBeenCalled(); + }); + it('should update and return the volunteer with only the given fields changed', async () => { mockRepo.findOne.mockResolvedValue({ ...mockVolunteer }); mockRepo.save.mockImplementation((v) => Promise.resolve(v)); @@ -825,7 +1116,7 @@ describe('VolunteersService', () => { expect(result.firstName).toBe('Jane'); expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.save).toHaveBeenCalledWith({ ...mockVolunteer, @@ -857,7 +1148,7 @@ describe('VolunteersService', () => { expect(result.notes).toBe('likes cats'); expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.save).toHaveBeenCalledWith({ ...mockVolunteer, @@ -910,7 +1201,7 @@ describe('VolunteersService', () => { ]); expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.save).toHaveBeenCalledWith( expect.objectContaining({ fosterTypePreferences: result }), @@ -1170,7 +1461,7 @@ describe('VolunteersService', () => { expect(result).toEqual(mockVolunteers); expect(mockRepo.find).toHaveBeenCalledWith({ - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); }); @@ -1671,4 +1962,66 @@ describe('VolunteersService', () => { expect(mockRepo.save).not.toHaveBeenCalled(); }); }); + + describe('incrementAllChildrenAges', () => { + const volunteerWithChildren = (volunteerId: number, ages: number[]) => + ({ + volunteerId, + hasChildren: true, + childrenAges: ages, + } as FosterVolunteer); + + it('loads only volunteers that have children', async () => { + mockRepo.find.mockResolvedValue([]); + + await service.incrementAllChildrenAges(); + + expect(mockRepo.find).toHaveBeenCalledWith({ + where: { hasChildren: true }, + }); + expect(mockRepo.find).toHaveBeenCalledTimes(1); + }); + + it('adds one year to every child', async () => { + mockRepo.find.mockResolvedValue([volunteerWithChildren(1, [0, 7, 15])]); + + await service.incrementAllChildrenAges(); + + expect(mockRepo.save).toHaveBeenCalledWith([ + expect.objectContaining({ volunteerId: 1, childrenAges: [1, 8, 16] }), + ]); + expect(mockRepo.save).toHaveBeenCalledTimes(1); + }); + + it('updates each volunteer independently', async () => { + mockRepo.find.mockResolvedValue([ + volunteerWithChildren(1, [2]), + volunteerWithChildren(2, [5, 9]), + ]); + + await service.incrementAllChildrenAges(); + + expect(mockRepo.save).toHaveBeenCalledWith([ + expect.objectContaining({ volunteerId: 1, childrenAges: [3] }), + expect.objectContaining({ volunteerId: 2, childrenAges: [6, 10] }), + ]); + expect(mockRepo.save).toHaveBeenCalledTimes(1); + }); + + it('returns the number of volunteers updated', async () => { + mockRepo.find.mockResolvedValue([ + volunteerWithChildren(1, [2]), + volunteerWithChildren(2, [5]), + ]); + + await expect(service.incrementAllChildrenAges()).resolves.toBe(2); + }); + + it('does not save when no volunteer has children', async () => { + mockRepo.find.mockResolvedValue([]); + + await expect(service.incrementAllChildrenAges()).resolves.toBe(0); + expect(mockRepo.save).not.toHaveBeenCalled(); + }); + }); }); diff --git a/apps/backend/src/volunteers/volunteers.service.ts b/apps/backend/src/volunteers/volunteers.service.ts index e55c108a1..2e4ba7c73 100644 --- a/apps/backend/src/volunteers/volunteers.service.ts +++ b/apps/backend/src/volunteers/volunteers.service.ts @@ -68,7 +68,7 @@ export class VolunteersService { async coordinatorFindByIdOrFail(id: number): Promise { const volunteer = await this.repo.findOne({ where: { volunteerId: id }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); if (!volunteer) { @@ -79,7 +79,7 @@ export class VolunteersService { } /** - * Fetches a Volunteer by ID, with their assigned Foster Coordinator. + * Fetches a Volunteer by ID, with their assigned Foster Coordinator and pets. * * Returns the Volunteer so callers can reuse it instead of fetching again. * @@ -90,7 +90,7 @@ export class VolunteersService { async findByIdOrFail(id: number): Promise { const volunteer = await this.repo.findOne({ where: { volunteerId: id }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); if (!volunteer) { @@ -112,6 +112,7 @@ export class VolunteersService { * * @param dto - The Volunteer's profile fields and chosen password. * @returns The saved Volunteer. + * @throws {BadRequestException} If childrenAges doesn't match hasChildren (checked before Cognito is called). * @throws {ConflictException} If a Volunteer or Cognito user with the email already exists. * @throws {BadRequestException} If Cognito rejects the password. * @throws {InternalServerErrorException} If the Cognito user could not be registered. @@ -123,6 +124,10 @@ export class VolunteersService { // The password only goes to Cognito; keep it out of the saved and returned Volunteer. const { password, ...profile } = dto; const email = profile.email.toLowerCase(); + const childrenAges = profile.childrenAges ?? []; + const pets = profile.pets ?? []; + + this.checkChildrenConsistent(profile.hasChildren, childrenAges); const existing = await this.repo.findOneBy({ email }); if (existing) { @@ -143,6 +148,8 @@ export class VolunteersService { const saved = await this.repo.save({ ...profile, email, + childrenAges, + pets, status: VolunteerStatus.PENDING, mostRecentWaiverSigned: true, cognitoSub, @@ -367,19 +374,23 @@ export class VolunteersService { /** * Updates a foster volunteer by ID. * Only the fields included in the DTO are changed; all other fields keep their current values. + * Pets, when included, replace the whole list; pets left out are deleted. + * Setting hasChildren to false without sending childrenAges clears the saved ages. * The homebase is changed through changeHomebase instead, since changing it * also reassigns coordinators and emails them. * @param id - ID of the volunteer to update * @param dto - The fields to update * @returns The updated volunteer * @throws NotFoundException if no volunteer exists with the given ID + * @throws {BadRequestException} If the saved and updated fields together + * leave childrenAges not matching hasChildren. */ async updateVolunteerById( id: number, dto: UpdateVolunteerDto, ): Promise { const volunteer = await this.findByIdOrFail(id); - Object.assign(volunteer, dto); + this.applyProfileUpdate(volunteer, dto); return this.withoutPrivateFields(await this.repo.save(volunteer)); } @@ -388,22 +399,70 @@ export class VolunteersService { * Volunteer can edit themselves, plus coordinator-only fields * (coordinator notes and completed trainings). * Only the fields included in the DTO are changed; completed trainings - * are replaced as a whole list. + * and pets are replaced as whole lists. Setting hasChildren to false + * without sending childrenAges clears the saved ages. * * @param id - The Volunteer's ID. * @param dto - The fields to update. * @returns The updated Volunteer, including private fields. * @throws {NotFoundException} If no Volunteer with the ID exists. + * @throws {BadRequestException} If the saved and updated fields together + * leave childrenAges not matching hasChildren. */ async coordinatorUpdateVolunteerById( id: number, dto: CoordinatorUpdateVolunteerDto, ): Promise { const volunteer = await this.coordinatorFindByIdOrFail(id); - Object.assign(volunteer, dto); + this.applyProfileUpdate(volunteer, dto); return this.repo.save(volunteer); } + /** + * Copies an update onto a loaded Volunteer, after checking that the saved + * and updated fields together still satisfy the children rule. + * + * @param volunteer - The loaded Volunteer to update. + * @param dto - The fields to copy onto the Volunteer. + * @throws {BadRequestException} If childrenAges doesn't match hasChildren. + */ + private applyProfileUpdate( + volunteer: VolunteerWithoutPrivateFields, + dto: UpdateVolunteerDto, + ): void { + const hasChildren = dto.hasChildren ?? volunteer.hasChildren; + const childrenAges = + dto.childrenAges ?? + (dto.hasChildren === false ? [] : volunteer.childrenAges); + this.checkChildrenConsistent(hasChildren, childrenAges); + Object.assign(volunteer, dto, { childrenAges }); + } + + /** + * Ensures childrenAges lists at least one age when hasChildren is true, + * and none when it is false. Mirrors CHK_foster_volunteers_children_ages, + * so a bad request is a 400 instead of a database error. + * + * @param hasChildren - Whether the Volunteer has children. + * @param childrenAges - The children's ages. + * @throws {BadRequestException} If childrenAges doesn't match hasChildren. + */ + private checkChildrenConsistent( + hasChildren: boolean, + childrenAges: number[], + ): void { + if (hasChildren && childrenAges.length === 0) { + throw new BadRequestException( + 'childrenAges must not be empty when hasChildren is true', + ); + } + if (!hasChildren && childrenAges.length > 0) { + throw new BadRequestException( + 'childrenAges must be empty when hasChildren is false', + ); + } + } + /** * Updates an active Volunteer's foster type preferences. * Validates all changes before mutating the Volunteer or saving. @@ -543,10 +602,30 @@ export class VolunteersService { */ async getAllVolunteers(): Promise { const volunteers = await this.repo.find({ - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); return volunteers.map((volunteer) => this.withoutPrivateFields(volunteer)); } + + /** + * Ages every child of every volunteer who has children by one year. + * + * @returns The number of volunteers updated. + */ + async incrementAllChildrenAges(): Promise { + const volunteers = await this.repo.find({ where: { hasChildren: true } }); + if (volunteers.length === 0) { + return 0; + } + + for (const volunteer of volunteers) { + volunteer.childrenAges = volunteer.childrenAges.map((age) => age + 1); + } + + await this.repo.save(volunteers); + return volunteers.length; + } + /** * Updates a Volunteer's animal preferences by adding and removing Chameleon animal IDs. * diff --git a/package.json b/package.json index 74e48863b..f9edba6c1 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ "@nestjs/core": "^10.0.2", "@nestjs/passport": "^11.0.5", "@nestjs/platform-express": "^11.2.1", + "@nestjs/schedule": "^4.1.2", "@nestjs/swagger": "^7.1.12", "@nestjs/typeorm": "^11.0.3", "@nx/eslint": "22.7.5", diff --git a/yarn.lock b/yarn.lock index 9c67a1e6c..c8fdfff39 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3059,6 +3059,14 @@ path-to-regexp "8.4.2" tslib "2.8.1" +"@nestjs/schedule@^4.1.2": + version "4.1.2" + resolved "https://registry.yarnpkg.com/@nestjs/schedule/-/schedule-4.1.2.tgz#1b289d8270463bdf26c0152e4b426105c5730f49" + integrity sha512-hCTQ1lNjIA5EHxeu8VvQu2Ed2DBLS1GSC6uKPYlBiQe6LL9a7zfE9iVSK+zuK8E2odsApteEBmfAQchc8Hx0Gg== + dependencies: + cron "3.2.1" + uuid "11.0.3" + "@nestjs/schematics@^11.0.1", "@nestjs/schematics@^11.1.0": version "11.1.0" resolved "https://registry.yarnpkg.com/@nestjs/schematics/-/schematics-11.1.0.tgz#aa9bc77218e04696031db6efc4510c8eacb0a20c" @@ -4936,6 +4944,11 @@ "@types/ms" "*" "@types/node" "*" +"@types/luxon@~3.4.0": + version "3.4.2" + resolved "https://registry.yarnpkg.com/@types/luxon/-/luxon-3.4.2.tgz#e4fc7214a420173cea47739c33cdf10874694db7" + integrity sha512-TifLZlFudklWlMBfhubvgqTXRzLDI5pCbGa4P8a3wPyUQSW+1xQ5eDsreP9DWHX3tjq1ke96uYG/nwundroWcA== + "@types/ms@*": version "2.1.0" resolved "https://registry.yarnpkg.com/@types/ms/-/ms-2.1.0.tgz#052aa67a48eccc4309d7f0191b7e41434b90bb78" @@ -7804,6 +7817,14 @@ create-require@^1.1.0: resolved "https://registry.yarnpkg.com/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333" integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ== +cron@3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/cron/-/cron-3.2.1.tgz#f319b9e46f8f4108eaa08639980f982dc22dd5f6" + integrity sha512-w2n5l49GMmmkBFEsH9FIDhjZ1n1QgTMOCMGuQtOXs5veNiosZmso6bQGuqOJSYAXXrG84WQFVneNk+Yt0Ua9iw== + dependencies: + "@types/luxon" "~3.4.0" + luxon "~3.5.0" + cross-spawn@^7.0.0, cross-spawn@^7.0.2, cross-spawn@^7.0.3, cross-spawn@^7.0.6: version "7.0.6" resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.6.tgz#8a58fe78f00dcd70c370451759dfbfaf03e8ee9f" @@ -11225,6 +11246,11 @@ lru-memoizer@^3.0.0: lodash.clonedeep "^4.5.0" lru-cache "^11.0.1" +luxon@~3.5.0: + version "3.5.0" + resolved "https://registry.yarnpkg.com/luxon/-/luxon-3.5.0.tgz#6b6f65c5cd1d61d1fd19dbf07ee87a50bf4b8e20" + integrity sha512-rh+Zjr6DNfUYR3bPwJEnuwDdqMbxZW7LOQfUN4B54+Cl+0o5zaU9RJ6bcidfDtC1cWCZXQ+nvX8bf6bAji37QQ== + lz-string@^1.5.0: version "1.5.0" resolved "https://registry.yarnpkg.com/lz-string/-/lz-string-1.5.0.tgz#c1ab50f77887b712621201ba9fd4e3a6ed099941" @@ -15006,6 +15032,11 @@ utils-merge@1.0.1, utils-merge@^1.0.1: resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713" integrity sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA== +uuid@11.0.3: + version "11.0.3" + resolved "https://registry.yarnpkg.com/uuid/-/uuid-11.0.3.tgz#248451cac9d1a4a4128033e765d137e2b2c49a3d" + integrity sha512-d0z310fCWv5dJwnX1Y/MncBAqGMKEzlBb1AOf7z9K8ALnd0utBX/msg/fA0+sbyN1ihbMsLhrBlnl1ak7Wa0rg== + uuid@^11.1.1: version "11.1.1" resolved "https://registry.yarnpkg.com/uuid/-/uuid-11.1.1.tgz#f6d81d2e1c65d00762e5e29b16c5d2d995e208ad"