From 6420da15881efaf150ecda5d6318dc9b2876e928 Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Wed, 11 Nov 2026 10:13:57 -0500 Subject: [PATCH 01/13] MSPCA-56: add pets table and household details to volunteers Co-Authored-By: Claude Opus 5.5 --- apps/backend/src/config/migrations.ts | 2 + ...794408338094-AddPetsAndHouseholdDetails.ts | 60 +++++++++++++++++++ apps/backend/src/pets/pets.entity.ts | 41 +++++++++++++ .../src/volunteers/volunteers.entity.ts | 29 ++++++++- .../src/volunteers/volunteers.module.ts | 3 +- 5 files changed, 132 insertions(+), 3 deletions(-) create mode 100644 apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts create mode 100644 apps/backend/src/pets/pets.entity.ts diff --git a/apps/backend/src/config/migrations.ts b/apps/backend/src/config/migrations.ts index badf1ad7e..fb475cc18 100644 --- a/apps/backend/src/config/migrations.ts +++ b/apps/backend/src/config/migrations.ts @@ -11,6 +11,7 @@ import { ReplaceCanineTrainingWithCompletedTrainings1793150103842 } from '../mig import { AddAnimalUpdatesAndFosterTypeArray1793163582751 } from '../migrations/1793163582751-AddAnimalUpdatesAndFosterTypeArray'; import { AddFarmAnimalsToFosterType1793476100199 } from '../migrations/1793476100199-AddFarmAnimalsToFosterType'; import { RenameAdminUsersToOwners1793485161630 } from '../migrations/1793485161630-RenameAdminUsersToOwners'; +import { AddPetsAndHouseholdDetails1794408338094 } from '../migrations/1794408338094-AddPetsAndHouseholdDetails'; const schemaMigrations = [ InitialSchemas1789354568323, @@ -26,6 +27,7 @@ const schemaMigrations = [ AddAnimalUpdatesAndFosterTypeArray1793163582751, AddFarmAnimalsToFosterType1793476100199, RenameAdminUsersToOwners1793485161630, + AddPetsAndHouseholdDetails1794408338094, ]; export default schemaMigrations; diff --git a/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts b/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts new file mode 100644 index 000000000..5ebf4f5b9 --- /dev/null +++ b/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts @@ -0,0 +1,60 @@ +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, + DROP COLUMN "resident_animals" + `); + + // The defaults only let rows in local dev databases migrate; the API requires both booleans. + await queryRunner.query(` + ALTER TABLE "foster_volunteers" + ALTER COLUMN "has_children" DROP DEFAULT, + ALTER COLUMN "has_separate_foster_room" 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 "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/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/volunteers/volunteers.entity.ts b/apps/backend/src/volunteers/volunteers.entity.ts index 98518df93..5a0298350 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,22 @@ 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; + + @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), From a53201a14351caf8b23074f2a9a848bedd5b46ec Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Wed, 11 Nov 2026 10:16:36 -0500 Subject: [PATCH 02/13] MSPCA-56: accept pets and household details in volunteer DTOs Co-Authored-By: Claude Opus 5.5 --- .../volunteers/dtos/create-volunteer.dto.ts | 26 +++- apps/backend/src/volunteers/dtos/pet.dto.ts | 21 +++ .../volunteers/dtos/update-volunteer.dto.ts | 25 +++- .../volunteers/volunteers.controller.spec.ts | 141 +++++++++++++++++- .../src/volunteers/volunteers.service.spec.ts | 3 +- 5 files changed, 209 insertions(+), 7 deletions(-) create mode 100644 apps/backend/src/volunteers/dtos/pet.dto.ts diff --git a/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts b/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts index ae9f547ce..cb95641d5 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 './pet.dto'; export class CreateVolunteerDto { @IsNonEmptyString() @@ -70,8 +75,23 @@ 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; + + @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/pet.dto.ts b/apps/backend/src/volunteers/dtos/pet.dto.ts new file mode 100644 index 000000000..71e13fe23 --- /dev/null +++ b/apps/backend/src/volunteers/dtos/pet.dto.ts @@ -0,0 +1,21 @@ +import { IsEnum, IsInt, Max, MaxLength, Min } from 'class-validator'; +import { FosterType } from '../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/volunteers/dtos/update-volunteer.dto.ts b/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts index a9e5b8cec..2d1a05b47 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 './pet.dto'; export class UpdateVolunteerDto { @ValidateIf((_, value) => value !== undefined) @@ -56,8 +61,24 @@ 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) + @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 c9fd0b6ce..3dcebee91 100644 --- a/apps/backend/src/volunteers/volunteers.controller.spec.ts +++ b/apps/backend/src/volunteers/volunteers.controller.spec.ts @@ -171,7 +171,8 @@ describe('VolunteersController', () => { city: 'Boston', zipcode: '02130', homebase: Homebase.BOSTON, - residentAnimals: 'One cat', + hasChildren: false, + hasSeparateFosterRoom: true, fosterType: [FosterType.CAT], password: 'Str0ng!Password', } as CreateVolunteerDto; @@ -232,6 +233,144 @@ describe('VolunteersController', () => { expect(result).not.toHaveProperty('completedTrainings'); }); + + const pet = { + ageYear: 3, + ageMonth: 11, + species: FosterType.CAT, + breed: 'Tabby', + }; + + 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]); + }); + + it('accepts a volunteer with no pets and no children', async () => { + const result = await validationPipe.transform(dto, { + type: 'body', + metatype: CreateVolunteerDto, + }); + + expect(result.hasChildren).toBe(false); + expect(result.hasSeparateFosterRoom).toBe(true); + expect(result).not.toHaveProperty('pets'); + }); + + it.each(['hasChildren', 'hasSeparateFosterRoom'])( + 'rejects a missing %s', + async (field) => { + const body: Record = { ...dto }; + delete body[field]; + + await expect( + validationPipe.transform(body, { + type: 'body', + metatype: CreateVolunteerDto, + }), + ).rejects.toThrow(BadRequestException); + }, + ); + + it.each([[[-1]], [[2.5]], [['4']], [null]])( + 'rejects childrenAges %j', + async (childrenAges) => { + await expect( + validationPipe.transform( + { ...dto, hasChildren: true, childrenAges }, + { type: 'body', metatype: CreateVolunteerDto }, + ), + ).rejects.toThrow(BadRequestException); + }, + ); + + it.each([ + ['ageMonth 12', { ...pet, ageMonth: 12 }], + ['a negative ageMonth', { ...pet, ageMonth: -1 }], + ['a negative ageYear', { ...pet, ageYear: -1 }], + ['a non-integer ageYear', { ...pet, ageYear: 1.5 }], + ['a species outside FosterType', { ...pet, species: 'Horse' }], + ['an empty breed', { ...pet, breed: ' ' }], + ['a breed over 255 characters', { ...pet, breed: 'a'.repeat(256) }], + [ + 'a missing ageMonth', + { ageYear: 3, species: FosterType.CAT, breed: 'Tabby' }, + ], + ])('rejects a pet with %s', async (_, invalidPet) => { + await expect( + validationPipe.transform( + { ...dto, pets: [invalidPet] }, + { type: 'body', metatype: CreateVolunteerDto }, + ), + ).rejects.toThrow(BadRequestException); + }); + }); + + describe('UpdateVolunteerDto validation', () => { + it('accepts an empty body', async () => { + const result = await validationPipe.transform( + {}, + { type: 'body', metatype: UpdateVolunteerDto }, + ); + + expect(result).toEqual({}); + }); + + it('accepts an empty pets list', async () => { + const result = await validationPipe.transform( + { pets: [] }, + { type: 'body', metatype: UpdateVolunteerDto }, + ); + + expect(result.pets).toEqual([]); + }); + + it('keeps the pets in the body', async () => { + const pet = { + ageYear: 0, + ageMonth: 0, + species: FosterType.DOG, + breed: 'Beagle', + }; + + const result = await validationPipe.transform( + { pets: [pet] }, + { type: 'body', metatype: UpdateVolunteerDto }, + ); + + expect(result.pets).toEqual([pet]); + }); + + it.each([ + ['pets', null], + ['pets', [{ ageYear: 1, ageMonth: 12, species: 'Dog', breed: 'Lab' }]], + ['hasChildren', null], + ['hasSeparateFosterRoom', null], + ['childrenAges', null], + ['childrenAges', [-3]], + ])('rejects %s %j', async (field, value) => { + await expect( + validationPipe.transform( + { [field]: value }, + { type: 'body', metatype: UpdateVolunteerDto }, + ), + ).rejects.toThrow(BadRequestException); + }); + + it('applies to the coordinator update DTO too', async () => { + await expect( + validationPipe.transform( + { pets: null }, + { type: 'body', metatype: CoordinatorUpdateVolunteerDto }, + ), + ).rejects.toThrow(BadRequestException); + }); }); describe('confirm', () => { diff --git a/apps/backend/src/volunteers/volunteers.service.spec.ts b/apps/backend/src/volunteers/volunteers.service.spec.ts index ba9d05594..73b581070 100644 --- a/apps/backend/src/volunteers/volunteers.service.spec.ts +++ b/apps/backend/src/volunteers/volunteers.service.spec.ts @@ -184,7 +184,8 @@ describe('VolunteersService', () => { city: 'Boston', zipcode: '02130', homebase: Homebase.BOSTON, - residentAnimals: 'One cat', + hasChildren: false, + hasSeparateFosterRoom: true, notes: 'Prefers kittens', fosterType: [FosterType.CAT], password: 'Str0ng!Password', From 254315930272d42a119573a1a4466b26c49a9f47 Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Wed, 11 Nov 2026 10:19:18 -0500 Subject: [PATCH 03/13] MSPCA-56: enforce children rule and replace pets on volunteer updates Co-Authored-By: Claude Opus 5.5 --- .../src/volunteers/volunteers.service.spec.ts | 225 +++++++++++++++++- .../src/volunteers/volunteers.service.ts | 51 +++- 2 files changed, 264 insertions(+), 12 deletions(-) diff --git a/apps/backend/src/volunteers/volunteers.service.spec.ts b/apps/backend/src/volunteers/volunteers.service.spec.ts index 73b581070..c6b82bec7 100644 --- a/apps/backend/src/volunteers/volunteers.service.spec.ts +++ b/apps/backend/src/volunteers/volunteers.service.spec.ts @@ -24,6 +24,7 @@ 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'; describe('VolunteersService', () => { let service: VolunteersService; @@ -33,6 +34,9 @@ describe('VolunteersService', () => { firstName: 'Jane', lastName: 'Doe', notes: 'likes cats', + hasChildren: false, + childrenAges: [] as number[], + pets: [] as Pet[], assignedCoordinators: [] as FosterCoordinator[], } as FosterVolunteer; @@ -106,7 +110,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 +123,7 @@ describe('VolunteersService', () => { ); expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 7 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); }); @@ -241,6 +245,8 @@ describe('VolunteersService', () => { expect(mockRepo.save).toHaveBeenCalledTimes(1); expect(mockRepo.save).toHaveBeenCalledWith({ ...profile, + childrenAges: [], + pets: [], status: VolunteerStatus.PENDING, mostRecentWaiverSigned: true, cognitoSub: 'cognito-sub-123', @@ -249,6 +255,8 @@ describe('VolunteersService', () => { expect(result).toEqual({ volunteerId: 1, ...profile, + childrenAges: [], + pets: [], status: VolunteerStatus.PENDING, mostRecentWaiverSigned: true, cognitoSub: 'cognito-sub-123', @@ -257,6 +265,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, @@ -541,7 +594,7 @@ describe('VolunteersService', () => { expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.save).toHaveBeenCalledWith({ ...volunteer, @@ -617,7 +670,7 @@ describe('VolunteersService', () => { expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.save).toHaveBeenCalledWith({ ...volunteer, @@ -680,7 +733,7 @@ describe('VolunteersService', () => { expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); }); @@ -812,9 +865,165 @@ 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, { hasChildren: false }), + ).rejects.toThrow( + new BadRequestException( + 'childrenAges must be empty when hasChildren is false', + ), + ); + expect(mockRepo.findOne).toHaveBeenCalledTimes(1); + expect(mockRepo.save).not.toHaveBeenCalled(); + }); }); 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', + }; + + beforeEach(() => { + mockRepo.save.mockImplementation(async (v) => v); + }); + + it('replaces the pets list when pets is provided', async () => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + pets: [existingPet], + }); + + 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], + }); + + 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], + }); + + 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 }); + + 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('removes children when both fields are sent', async () => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + hasChildren: true, + childrenAges: [6], + }); + + const result = await service.updateVolunteerById(1, { + hasChildren: false, + childrenAges: [], + }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(result.hasChildren).toBe(false); + expect(result.childrenAges).toEqual([]); + }); + + it.each([ + [ + 'hasChildren false while the saved row still has ages', + { hasChildren: true, childrenAges: [6] }, + { hasChildren: false }, + '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)); @@ -826,7 +1035,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, @@ -858,7 +1067,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, @@ -1046,7 +1255,7 @@ describe('VolunteersService', () => { expect(result).toEqual(mockVolunteers); expect(mockRepo.find).toHaveBeenCalledWith({ - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); }); diff --git a/apps/backend/src/volunteers/volunteers.service.ts b/apps/backend/src/volunteers/volunteers.service.ts index d8d28d76b..ae5cb5c65 100644 --- a/apps/backend/src/volunteers/volunteers.service.ts +++ b/apps/backend/src/volunteers/volunteers.service.ts @@ -67,7 +67,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) { @@ -89,7 +89,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) { @@ -111,6 +111,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. @@ -122,6 +123,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) { @@ -142,6 +147,8 @@ export class VolunteersService { const saved = await this.repo.save({ ...profile, email, + childrenAges, + pets, status: VolunteerStatus.PENDING, mostRecentWaiverSigned: true, cognitoSub, @@ -370,14 +377,21 @@ export class VolunteersService { * also reassigns coordinators and emails them. * @param id - ID of the volunteer to update * @param dto - The fields to update + * Pets, when included, replace the whole list; pets left out are deleted. * @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); + this.checkChildrenConsistent( + dto.hasChildren ?? volunteer.hasChildren, + dto.childrenAges ?? volunteer.childrenAges, + ); Object.assign(volunteer, dto); return this.withoutPrivateFields(await this.repo.save(volunteer)); } @@ -387,22 +401,51 @@ 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. * * @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); + this.checkChildrenConsistent( + dto.hasChildren ?? volunteer.hasChildren, + dto.childrenAges ?? volunteer.childrenAges, + ); Object.assign(volunteer, dto); return this.repo.save(volunteer); } + /** + * 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. + * + * @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', + ); + } + } + /** * Approves a pending Volunteer, setting their status to Active and emailing * them that they can now log in. @@ -483,7 +526,7 @@ export class VolunteersService { */ async getAllVolunteers(): Promise { const volunteers = await this.repo.find({ - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); return volunteers.map((volunteer) => this.withoutPrivateFields(volunteer)); } From 285635c8b97ec33798c42b586de2bfa89a4b4a04 Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Wed, 11 Nov 2026 11:10:16 -0500 Subject: [PATCH 04/13] MSPCA-56: cap pets and children, load pets only where used, clear ages when hasChildren is turned off Co-Authored-By: Claude Opus 5.5 --- .../volunteers/dtos/create-volunteer.dto.ts | 5 + apps/backend/src/volunteers/dtos/pet.dto.ts | 1 + .../volunteers/dtos/update-volunteer.dto.ts | 5 + .../volunteers/volunteers.controller.spec.ts | 42 +++++++- .../src/volunteers/volunteers.controller.ts | 4 +- .../src/volunteers/volunteers.service.spec.ts | 95 ++++++++++++++++--- .../src/volunteers/volunteers.service.ts | 49 +++++++--- 7 files changed, 171 insertions(+), 30 deletions(-) diff --git a/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts b/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts index cb95641d5..8424b2db9 100644 --- a/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts +++ b/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts @@ -1,4 +1,5 @@ import { + ArrayMaxSize, ArrayNotEmpty, ArrayUnique, IsArray, @@ -10,6 +11,7 @@ import { IsPhoneNumber, IsString, IsStrongPassword, + Max, MaxLength, Min, ValidateIf, @@ -80,8 +82,10 @@ export class CreateVolunteerDto { @ValidateIf((_, value) => value !== undefined) @IsArray() + @ArrayMaxSize(20) @IsInt({ each: true }) @Min(0, { each: true }) + @Max(25, { each: true }) childrenAges?: number[]; @IsBoolean() @@ -89,6 +93,7 @@ export class CreateVolunteerDto { @ValidateIf((_, value) => value !== undefined) @IsArray() + @ArrayMaxSize(20) @ValidateNested({ each: true }) @Type(() => PetDto) pets?: PetDto[]; diff --git a/apps/backend/src/volunteers/dtos/pet.dto.ts b/apps/backend/src/volunteers/dtos/pet.dto.ts index 71e13fe23..5577cf104 100644 --- a/apps/backend/src/volunteers/dtos/pet.dto.ts +++ b/apps/backend/src/volunteers/dtos/pet.dto.ts @@ -5,6 +5,7 @@ import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.dec export class PetDto { @IsInt() @Min(0) + @Max(50) ageYear!: number; @IsInt() diff --git a/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts b/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts index 2d1a05b47..a8cad1323 100644 --- a/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts +++ b/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts @@ -1,11 +1,13 @@ import { FosterType } from '../volunteers.types'; import { + ArrayMaxSize, ArrayNotEmpty, IsArray, IsBoolean, IsEnum, IsInt, IsNotEmpty, + Max, MaxLength, Min, IsPhoneNumber, @@ -66,8 +68,10 @@ export class UpdateVolunteerDto { @ValidateIf((_, value) => value !== undefined) @IsArray() + @ArrayMaxSize(20) @IsInt({ each: true }) @Min(0, { each: true }) + @Max(25, { each: true }) childrenAges?: number[]; @ValidateIf((_, value) => value !== undefined) @@ -76,6 +80,7 @@ export class UpdateVolunteerDto { @ValidateIf((_, value) => value !== undefined) @IsArray() + @ArrayMaxSize(20) @ValidateNested({ each: true }) @Type(() => PetDto) pets?: PetDto[]; diff --git a/apps/backend/src/volunteers/volunteers.controller.spec.ts b/apps/backend/src/volunteers/volunteers.controller.spec.ts index 3dcebee91..de5c36494 100644 --- a/apps/backend/src/volunteers/volunteers.controller.spec.ts +++ b/apps/backend/src/volunteers/volunteers.controller.spec.ts @@ -278,7 +278,29 @@ describe('VolunteersController', () => { }, ); - it.each([[[-1]], [[2.5]], [['4']], [null]])( + it('accepts the largest allowed pets and children lists and ages', async () => { + const pets = Array.from({ length: 20 }, () => ({ ...pet, ageYear: 50 })); + const childrenAges = Array.from({ length: 20 }, () => 25); + + const result = await validationPipe.transform( + { ...dto, hasChildren: true, childrenAges, pets }, + { type: 'body', metatype: CreateVolunteerDto }, + ); + + expect(result.pets).toHaveLength(20); + expect(result.childrenAges).toEqual(childrenAges); + }); + + it('rejects more than 20 pets', async () => { + await expect( + validationPipe.transform( + { ...dto, pets: Array.from({ length: 21 }, () => pet) }, + { type: 'body', metatype: CreateVolunteerDto }, + ), + ).rejects.toThrow(BadRequestException); + }); + + it.each([[[-1]], [[2.5]], [['4']], [null], [[26]], [Array(21).fill(5)]])( 'rejects childrenAges %j', async (childrenAges) => { await expect( @@ -294,6 +316,8 @@ describe('VolunteersController', () => { ['ageMonth 12', { ...pet, ageMonth: 12 }], ['a negative ageMonth', { ...pet, ageMonth: -1 }], ['a negative ageYear', { ...pet, ageYear: -1 }], + ['ageYear 51', { ...pet, ageYear: 51 }], + ['ageYear past the Postgres int range', { ...pet, ageYear: 3000000000 }], ['a non-integer ageYear', { ...pet, ageYear: 1.5 }], ['a species outside FosterType', { ...pet, species: 'Horse' }], ['an empty breed', { ...pet, breed: ' ' }], @@ -354,6 +378,17 @@ describe('VolunteersController', () => { ['hasSeparateFosterRoom', null], ['childrenAges', null], ['childrenAges', [-3]], + ['childrenAges', [26]], + ['childrenAges', Array(21).fill(5)], + [ + 'pets', + Array(21).fill({ + ageYear: 1, + ageMonth: 1, + species: 'Dog', + breed: 'Lab', + }), + ], ])('rejects %s %j', async (field, value) => { await expect( validationPipe.transform( @@ -448,7 +483,10 @@ describe('VolunteersController', () => { const result = await controller.getVolunteerById(1); expect(result).toEqual(mockVolunteer); - expect(mockVolunteersService.findByIdOrFail).toHaveBeenCalledWith(1); + expect(mockVolunteersService.findByIdOrFail).toHaveBeenCalledTimes(1); + expect(mockVolunteersService.findByIdOrFail).toHaveBeenCalledWith(1, { + withPets: true, + }); }); it('should throw NotFoundException when volunteer does not exist', async () => { diff --git a/apps/backend/src/volunteers/volunteers.controller.ts b/apps/backend/src/volunteers/volunteers.controller.ts index 79d874f8a..070849c4d 100644 --- a/apps/backend/src/volunteers/volunteers.controller.ts +++ b/apps/backend/src/volunteers/volunteers.controller.ts @@ -164,7 +164,9 @@ export class VolunteersController { @Param('volunteerId', ParseIntPipe) volunteerId: number, ): Promise { validateId(volunteerId, 'Volunteer'); - return this.volunteersService.findByIdOrFail(volunteerId); + return this.volunteersService.findByIdOrFail(volunteerId, { + withPets: true, + }); } // TODO: restrict to coordinators once role guarding is added diff --git a/apps/backend/src/volunteers/volunteers.service.spec.ts b/apps/backend/src/volunteers/volunteers.service.spec.ts index c6b82bec7..3c3130adf 100644 --- a/apps/backend/src/volunteers/volunteers.service.spec.ts +++ b/apps/backend/src/volunteers/volunteers.service.spec.ts @@ -110,11 +110,28 @@ describe('VolunteersService', () => { expect(result).toBe(volunteer); expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 7 }, - relations: ['assignedCoordinators', 'pets'], + relations: ['assignedCoordinators'], }); expect(mockRepo.findOne).toHaveBeenCalledTimes(1); }); + it('also loads the pets when asked to', async () => { + const volunteer = { + volunteerId: 7, + pets: [] as Pet[], + } as FosterVolunteer; + mockRepo.findOne.mockResolvedValue(volunteer); + + const result = await service.findByIdOrFail(7, { withPets: true }); + + expect(result).toBe(volunteer); + expect(mockRepo.findOne).toHaveBeenCalledTimes(1); + expect(mockRepo.findOne).toHaveBeenCalledWith({ + where: { volunteerId: 7 }, + relations: ['assignedCoordinators', 'pets'], + }); + }); + it('throws NotFoundException when no volunteer with the id exists', async () => { mockRepo.findOne.mockResolvedValue(null); @@ -123,7 +140,7 @@ describe('VolunteersService', () => { ); expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 7 }, - relations: ['assignedCoordinators', 'pets'], + relations: ['assignedCoordinators'], }); }); @@ -594,7 +611,7 @@ describe('VolunteersService', () => { expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators', 'pets'], + relations: ['assignedCoordinators'], }); expect(mockRepo.save).toHaveBeenCalledWith({ ...volunteer, @@ -670,7 +687,7 @@ describe('VolunteersService', () => { expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators', 'pets'], + relations: ['assignedCoordinators'], }); expect(mockRepo.save).toHaveBeenCalledWith({ ...volunteer, @@ -874,15 +891,61 @@ describe('VolunteersService', () => { }); await expect( - service.coordinatorUpdateVolunteerById(1, { hasChildren: false }), + service.coordinatorUpdateVolunteerById(1, { childrenAges: [] }), ).rejects.toThrow( new BadRequestException( - 'childrenAges must be empty when hasChildren is false', + '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 pet = { + ageYear: 1, + ageMonth: 6, + species: FosterType.CAT, + breed: 'Siamese', + }; + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + pets: [{ petId: 5, breed: 'Lab' } as Pet], + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.coordinatorUpdateVolunteerById(1, { + pets: [pet], + }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + pets: [pet], + }); + expect(result.pets).toEqual([pet]); + }); }); describe('updateVolunteerById', () => { @@ -972,28 +1035,36 @@ describe('VolunteersService', () => { expect(result.childrenAges).toEqual([6]); }); - it('removes children when both fields are sent', async () => { + 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], }); - const result = await service.updateVolunteerById(1, { + const result = await service.updateVolunteerById(1, dto); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, hasChildren: false, childrenAges: [], }); - - expect(mockRepo.save).toHaveBeenCalledTimes(1); expect(result.hasChildren).toBe(false); expect(result.childrenAges).toEqual([]); }); it.each([ [ - 'hasChildren false while the saved row still has ages', + 'hasChildren false sent with ages', { hasChildren: true, childrenAges: [6] }, - { hasChildren: false }, + { hasChildren: false, childrenAges: [6] }, 'childrenAges must be empty when hasChildren is false', ], [ diff --git a/apps/backend/src/volunteers/volunteers.service.ts b/apps/backend/src/volunteers/volunteers.service.ts index ae5cb5c65..c21acf010 100644 --- a/apps/backend/src/volunteers/volunteers.service.ts +++ b/apps/backend/src/volunteers/volunteers.service.ts @@ -81,15 +81,22 @@ export class VolunteersService { * Fetches a Volunteer by ID, with their assigned Foster Coordinator. * * Returns the Volunteer so callers can reuse it instead of fetching again. + * Pets are only loaded when asked for, since most callers don't need them. * * @param id - The Volunteer's ID. + * @param options.withPets - Also load the Volunteer's pets. * @returns The Volunteer. * @throws {NotFoundException} If no Volunteer with the ID exists. */ - async findByIdOrFail(id: number): Promise { + async findByIdOrFail( + id: number, + { withPets = false }: { withPets?: boolean } = {}, + ): Promise { const volunteer = await this.repo.findOne({ where: { volunteerId: id }, - relations: ['assignedCoordinators', 'pets'], + relations: withPets + ? ['assignedCoordinators', 'pets'] + : ['assignedCoordinators'], }); if (!volunteer) { @@ -373,11 +380,12 @@ 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 - * Pets, when included, replace the whole list; pets left out are deleted. * @returns The updated volunteer * @throws NotFoundException if no volunteer exists with the given ID * @throws BadRequestException if the saved and updated fields together leave @@ -387,12 +395,8 @@ export class VolunteersService { id: number, dto: UpdateVolunteerDto, ): Promise { - const volunteer = await this.findByIdOrFail(id); - this.checkChildrenConsistent( - dto.hasChildren ?? volunteer.hasChildren, - dto.childrenAges ?? volunteer.childrenAges, - ); - Object.assign(volunteer, dto); + const volunteer = await this.findByIdOrFail(id, { withPets: true }); + this.applyProfileUpdate(volunteer, dto); return this.withoutPrivateFields(await this.repo.save(volunteer)); } @@ -401,7 +405,8 @@ 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 - * and pets are replaced as whole lists. + * 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. @@ -415,14 +420,28 @@ export class VolunteersService { dto: CoordinatorUpdateVolunteerDto, ): Promise { const volunteer = await this.coordinatorFindByIdOrFail(id); - this.checkChildrenConsistent( - dto.hasChildren ?? volunteer.hasChildren, - dto.childrenAges ?? volunteer.childrenAges, - ); - 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. + * + * @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, From e510398a575ff97e82599b74f435d728458e7134 Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Sat, 14 Nov 2026 12:44:30 -0500 Subject: [PATCH 05/13] MSPCA-56: address review conventions in tests, docs and Swagger Co-Authored-By: Claude Opus 5.5 --- ...794408338094-AddPetsAndHouseholdDetails.ts | 2 + .../volunteers/volunteers.controller.spec.ts | 155 ------------------ .../src/volunteers/volunteers.controller.ts | 12 +- .../src/volunteers/volunteers.service.spec.ts | 9 +- .../src/volunteers/volunteers.service.ts | 4 +- 5 files changed, 20 insertions(+), 162 deletions(-) diff --git a/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts b/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts index 5ebf4f5b9..601ca7df2 100644 --- a/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts +++ b/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts @@ -27,6 +27,7 @@ export class AddPetsAndHouseholdDetails1794408338094 `); // The defaults only let rows in local dev databases migrate; the API requires both booleans. + // Separate statement: Postgres can't alter a column added in the same ALTER TABLE. await queryRunner.query(` ALTER TABLE "foster_volunteers" ALTER COLUMN "has_children" DROP DEFAULT, @@ -51,6 +52,7 @@ export class AddPetsAndHouseholdDetails1794408338094 ADD COLUMN "resident_animals" text NOT NULL DEFAULT '' `); + // Separate statement for the same reason as in up. await queryRunner.query(` ALTER TABLE "foster_volunteers" ALTER COLUMN "resident_animals" DROP DEFAULT `); diff --git a/apps/backend/src/volunteers/volunteers.controller.spec.ts b/apps/backend/src/volunteers/volunteers.controller.spec.ts index de5c36494..ebd2f0e9b 100644 --- a/apps/backend/src/volunteers/volunteers.controller.spec.ts +++ b/apps/backend/src/volunteers/volunteers.controller.spec.ts @@ -251,161 +251,6 @@ describe('VolunteersController', () => { expect(result.childrenAges).toEqual([4, 9]); expect(result.pets).toEqual([pet]); }); - - it('accepts a volunteer with no pets and no children', async () => { - const result = await validationPipe.transform(dto, { - type: 'body', - metatype: CreateVolunteerDto, - }); - - expect(result.hasChildren).toBe(false); - expect(result.hasSeparateFosterRoom).toBe(true); - expect(result).not.toHaveProperty('pets'); - }); - - it.each(['hasChildren', 'hasSeparateFosterRoom'])( - 'rejects a missing %s', - async (field) => { - const body: Record = { ...dto }; - delete body[field]; - - await expect( - validationPipe.transform(body, { - type: 'body', - metatype: CreateVolunteerDto, - }), - ).rejects.toThrow(BadRequestException); - }, - ); - - it('accepts the largest allowed pets and children lists and ages', async () => { - const pets = Array.from({ length: 20 }, () => ({ ...pet, ageYear: 50 })); - const childrenAges = Array.from({ length: 20 }, () => 25); - - const result = await validationPipe.transform( - { ...dto, hasChildren: true, childrenAges, pets }, - { type: 'body', metatype: CreateVolunteerDto }, - ); - - expect(result.pets).toHaveLength(20); - expect(result.childrenAges).toEqual(childrenAges); - }); - - it('rejects more than 20 pets', async () => { - await expect( - validationPipe.transform( - { ...dto, pets: Array.from({ length: 21 }, () => pet) }, - { type: 'body', metatype: CreateVolunteerDto }, - ), - ).rejects.toThrow(BadRequestException); - }); - - it.each([[[-1]], [[2.5]], [['4']], [null], [[26]], [Array(21).fill(5)]])( - 'rejects childrenAges %j', - async (childrenAges) => { - await expect( - validationPipe.transform( - { ...dto, hasChildren: true, childrenAges }, - { type: 'body', metatype: CreateVolunteerDto }, - ), - ).rejects.toThrow(BadRequestException); - }, - ); - - it.each([ - ['ageMonth 12', { ...pet, ageMonth: 12 }], - ['a negative ageMonth', { ...pet, ageMonth: -1 }], - ['a negative ageYear', { ...pet, ageYear: -1 }], - ['ageYear 51', { ...pet, ageYear: 51 }], - ['ageYear past the Postgres int range', { ...pet, ageYear: 3000000000 }], - ['a non-integer ageYear', { ...pet, ageYear: 1.5 }], - ['a species outside FosterType', { ...pet, species: 'Horse' }], - ['an empty breed', { ...pet, breed: ' ' }], - ['a breed over 255 characters', { ...pet, breed: 'a'.repeat(256) }], - [ - 'a missing ageMonth', - { ageYear: 3, species: FosterType.CAT, breed: 'Tabby' }, - ], - ])('rejects a pet with %s', async (_, invalidPet) => { - await expect( - validationPipe.transform( - { ...dto, pets: [invalidPet] }, - { type: 'body', metatype: CreateVolunteerDto }, - ), - ).rejects.toThrow(BadRequestException); - }); - }); - - describe('UpdateVolunteerDto validation', () => { - it('accepts an empty body', async () => { - const result = await validationPipe.transform( - {}, - { type: 'body', metatype: UpdateVolunteerDto }, - ); - - expect(result).toEqual({}); - }); - - it('accepts an empty pets list', async () => { - const result = await validationPipe.transform( - { pets: [] }, - { type: 'body', metatype: UpdateVolunteerDto }, - ); - - expect(result.pets).toEqual([]); - }); - - it('keeps the pets in the body', async () => { - const pet = { - ageYear: 0, - ageMonth: 0, - species: FosterType.DOG, - breed: 'Beagle', - }; - - const result = await validationPipe.transform( - { pets: [pet] }, - { type: 'body', metatype: UpdateVolunteerDto }, - ); - - expect(result.pets).toEqual([pet]); - }); - - it.each([ - ['pets', null], - ['pets', [{ ageYear: 1, ageMonth: 12, species: 'Dog', breed: 'Lab' }]], - ['hasChildren', null], - ['hasSeparateFosterRoom', null], - ['childrenAges', null], - ['childrenAges', [-3]], - ['childrenAges', [26]], - ['childrenAges', Array(21).fill(5)], - [ - 'pets', - Array(21).fill({ - ageYear: 1, - ageMonth: 1, - species: 'Dog', - breed: 'Lab', - }), - ], - ])('rejects %s %j', async (field, value) => { - await expect( - validationPipe.transform( - { [field]: value }, - { type: 'body', metatype: UpdateVolunteerDto }, - ), - ).rejects.toThrow(BadRequestException); - }); - - it('applies to the coordinator update DTO too', async () => { - await expect( - validationPipe.transform( - { pets: null }, - { type: 'body', metatype: CoordinatorUpdateVolunteerDto }, - ), - ).rejects.toThrow(BadRequestException); - }); }); describe('confirm', () => { diff --git a/apps/backend/src/volunteers/volunteers.controller.ts b/apps/backend/src/volunteers/volunteers.controller.ts index 070849c4d..1bfdd2af2 100644 --- a/apps/backend/src/volunteers/volunteers.controller.ts +++ b/apps/backend/src/volunteers/volunteers.controller.ts @@ -188,7 +188,8 @@ export class VolunteersController { }) @ApiResponse({ status: HttpStatus.BAD_REQUEST, - description: 'Invalid ID, invalid field, or no fields provided', + description: + 'Invalid ID, invalid field, no fields provided, or childrenAges does not match hasChildren', }) @ApiResponse({ status: HttpStatus.NOT_FOUND, @@ -220,6 +221,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.service.spec.ts b/apps/backend/src/volunteers/volunteers.service.spec.ts index 3c3130adf..1b7578b4c 100644 --- a/apps/backend/src/volunteers/volunteers.service.spec.ts +++ b/apps/backend/src/volunteers/volunteers.service.spec.ts @@ -964,15 +964,12 @@ describe('VolunteersService', () => { breed: 'Siamese', }; - beforeEach(() => { - mockRepo.save.mockImplementation(async (v) => v); - }); - 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] }); @@ -989,6 +986,7 @@ describe('VolunteersService', () => { ...mockVolunteer, pets: [existingPet], }); + mockRepo.save.mockImplementation(async (v) => v); const result = await service.updateVolunteerById(1, { pets: [] }); @@ -1005,6 +1003,7 @@ describe('VolunteersService', () => { ...mockVolunteer, pets: [existingPet], }); + mockRepo.save.mockImplementation(async (v) => v); const result = await service.updateVolunteerById(1, { notes: 'x' }); @@ -1019,6 +1018,7 @@ describe('VolunteersService', () => { 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, @@ -1047,6 +1047,7 @@ describe('VolunteersService', () => { hasChildren: true, childrenAges: [6], }); + mockRepo.save.mockImplementation(async (v) => v); const result = await service.updateVolunteerById(1, dto); diff --git a/apps/backend/src/volunteers/volunteers.service.ts b/apps/backend/src/volunteers/volunteers.service.ts index c21acf010..414fe3fff 100644 --- a/apps/backend/src/volunteers/volunteers.service.ts +++ b/apps/backend/src/volunteers/volunteers.service.ts @@ -388,8 +388,8 @@ export class VolunteersService { * @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 + * @throws {BadRequestException} If the saved and updated fields together + * leave childrenAges not matching hasChildren. */ async updateVolunteerById( id: number, From 8a46338b090f2b0a99fa996dc013291d2a8a4f71 Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Sat, 14 Nov 2026 13:30:30 -0500 Subject: [PATCH 06/13] MSPCA-56: always load pets with the volunteer so every endpoint returns them Co-Authored-By: Claude Opus 5.5 --- .../volunteers/volunteers.controller.spec.ts | 4 +-- .../src/volunteers/volunteers.controller.ts | 4 +-- .../src/volunteers/volunteers.service.spec.ts | 26 +++++-------------- .../src/volunteers/volunteers.service.ts | 15 +++-------- 4 files changed, 12 insertions(+), 37 deletions(-) diff --git a/apps/backend/src/volunteers/volunteers.controller.spec.ts b/apps/backend/src/volunteers/volunteers.controller.spec.ts index ebd2f0e9b..e80faadb4 100644 --- a/apps/backend/src/volunteers/volunteers.controller.spec.ts +++ b/apps/backend/src/volunteers/volunteers.controller.spec.ts @@ -329,9 +329,7 @@ describe('VolunteersController', () => { expect(result).toEqual(mockVolunteer); expect(mockVolunteersService.findByIdOrFail).toHaveBeenCalledTimes(1); - expect(mockVolunteersService.findByIdOrFail).toHaveBeenCalledWith(1, { - withPets: true, - }); + expect(mockVolunteersService.findByIdOrFail).toHaveBeenCalledWith(1); }); it('should throw NotFoundException when volunteer does not exist', async () => { diff --git a/apps/backend/src/volunteers/volunteers.controller.ts b/apps/backend/src/volunteers/volunteers.controller.ts index 1bfdd2af2..bde4fb833 100644 --- a/apps/backend/src/volunteers/volunteers.controller.ts +++ b/apps/backend/src/volunteers/volunteers.controller.ts @@ -164,9 +164,7 @@ export class VolunteersController { @Param('volunteerId', ParseIntPipe) volunteerId: number, ): Promise { validateId(volunteerId, 'Volunteer'); - return this.volunteersService.findByIdOrFail(volunteerId, { - withPets: true, - }); + return this.volunteersService.findByIdOrFail(volunteerId); } // TODO: restrict to coordinators once role guarding is added diff --git a/apps/backend/src/volunteers/volunteers.service.spec.ts b/apps/backend/src/volunteers/volunteers.service.spec.ts index 1b7578b4c..d9547325f 100644 --- a/apps/backend/src/volunteers/volunteers.service.spec.ts +++ b/apps/backend/src/volunteers/volunteers.service.spec.ts @@ -101,35 +101,21 @@ describe('VolunteersService', () => { }); describe('findByIdOrFail', () => { - it('returns the volunteer when one with the id exists', async () => { - const volunteer = { volunteerId: 7 } as FosterVolunteer; - mockRepo.findOne.mockResolvedValue(volunteer); - - const result = await service.findByIdOrFail(7); - - expect(result).toBe(volunteer); - expect(mockRepo.findOne).toHaveBeenCalledWith({ - where: { volunteerId: 7 }, - relations: ['assignedCoordinators'], - }); - expect(mockRepo.findOne).toHaveBeenCalledTimes(1); - }); - - it('also loads the pets when asked to', async () => { + it('returns the volunteer with their coordinators and pets', async () => { const volunteer = { volunteerId: 7, pets: [] as Pet[], } as FosterVolunteer; mockRepo.findOne.mockResolvedValue(volunteer); - const result = await service.findByIdOrFail(7, { withPets: true }); + const result = await service.findByIdOrFail(7); expect(result).toBe(volunteer); - expect(mockRepo.findOne).toHaveBeenCalledTimes(1); expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 7 }, relations: ['assignedCoordinators', 'pets'], }); + expect(mockRepo.findOne).toHaveBeenCalledTimes(1); }); it('throws NotFoundException when no volunteer with the id exists', async () => { @@ -140,7 +126,7 @@ describe('VolunteersService', () => { ); expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 7 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); }); @@ -611,7 +597,7 @@ describe('VolunteersService', () => { expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.save).toHaveBeenCalledWith({ ...volunteer, @@ -687,7 +673,7 @@ describe('VolunteersService', () => { expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.save).toHaveBeenCalledWith({ ...volunteer, diff --git a/apps/backend/src/volunteers/volunteers.service.ts b/apps/backend/src/volunteers/volunteers.service.ts index 414fe3fff..80cf96c34 100644 --- a/apps/backend/src/volunteers/volunteers.service.ts +++ b/apps/backend/src/volunteers/volunteers.service.ts @@ -78,25 +78,18 @@ 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. - * Pets are only loaded when asked for, since most callers don't need them. * * @param id - The Volunteer's ID. - * @param options.withPets - Also load the Volunteer's pets. * @returns The Volunteer. * @throws {NotFoundException} If no Volunteer with the ID exists. */ - async findByIdOrFail( - id: number, - { withPets = false }: { withPets?: boolean } = {}, - ): Promise { + async findByIdOrFail(id: number): Promise { const volunteer = await this.repo.findOne({ where: { volunteerId: id }, - relations: withPets - ? ['assignedCoordinators', 'pets'] - : ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); if (!volunteer) { @@ -395,7 +388,7 @@ export class VolunteersService { id: number, dto: UpdateVolunteerDto, ): Promise { - const volunteer = await this.findByIdOrFail(id, { withPets: true }); + const volunteer = await this.findByIdOrFail(id); this.applyProfileUpdate(volunteer, dto); return this.withoutPrivateFields(await this.repo.save(volunteer)); } From 7401ba6a236b278420321c6689416f7db854eab7 Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Sat, 14 Nov 2026 13:40:37 -0500 Subject: [PATCH 07/13] MSPCA-56: drop caps on pet and children counts and ages, remove migration comments Co-Authored-By: Claude Opus 5.5 --- .../migrations/1794408338094-AddPetsAndHouseholdDetails.ts | 3 --- apps/backend/src/volunteers/dtos/create-volunteer.dto.ts | 5 ----- apps/backend/src/volunteers/dtos/pet.dto.ts | 1 - apps/backend/src/volunteers/dtos/update-volunteer.dto.ts | 5 ----- 4 files changed, 14 deletions(-) diff --git a/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts b/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts index 601ca7df2..dd66eec80 100644 --- a/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts +++ b/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts @@ -26,8 +26,6 @@ export class AddPetsAndHouseholdDetails1794408338094 DROP COLUMN "resident_animals" `); - // The defaults only let rows in local dev databases migrate; the API requires both booleans. - // Separate statement: Postgres can't alter a column added in the same ALTER TABLE. await queryRunner.query(` ALTER TABLE "foster_volunteers" ALTER COLUMN "has_children" DROP DEFAULT, @@ -52,7 +50,6 @@ export class AddPetsAndHouseholdDetails1794408338094 ADD COLUMN "resident_animals" text NOT NULL DEFAULT '' `); - // Separate statement for the same reason as in up. await queryRunner.query(` ALTER TABLE "foster_volunteers" ALTER COLUMN "resident_animals" DROP DEFAULT `); diff --git a/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts b/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts index 8424b2db9..cb95641d5 100644 --- a/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts +++ b/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts @@ -1,5 +1,4 @@ import { - ArrayMaxSize, ArrayNotEmpty, ArrayUnique, IsArray, @@ -11,7 +10,6 @@ import { IsPhoneNumber, IsString, IsStrongPassword, - Max, MaxLength, Min, ValidateIf, @@ -82,10 +80,8 @@ export class CreateVolunteerDto { @ValidateIf((_, value) => value !== undefined) @IsArray() - @ArrayMaxSize(20) @IsInt({ each: true }) @Min(0, { each: true }) - @Max(25, { each: true }) childrenAges?: number[]; @IsBoolean() @@ -93,7 +89,6 @@ export class CreateVolunteerDto { @ValidateIf((_, value) => value !== undefined) @IsArray() - @ArrayMaxSize(20) @ValidateNested({ each: true }) @Type(() => PetDto) pets?: PetDto[]; diff --git a/apps/backend/src/volunteers/dtos/pet.dto.ts b/apps/backend/src/volunteers/dtos/pet.dto.ts index 5577cf104..71e13fe23 100644 --- a/apps/backend/src/volunteers/dtos/pet.dto.ts +++ b/apps/backend/src/volunteers/dtos/pet.dto.ts @@ -5,7 +5,6 @@ import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.dec export class PetDto { @IsInt() @Min(0) - @Max(50) ageYear!: number; @IsInt() diff --git a/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts b/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts index a8cad1323..2d1a05b47 100644 --- a/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts +++ b/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts @@ -1,13 +1,11 @@ import { FosterType } from '../volunteers.types'; import { - ArrayMaxSize, ArrayNotEmpty, IsArray, IsBoolean, IsEnum, IsInt, IsNotEmpty, - Max, MaxLength, Min, IsPhoneNumber, @@ -68,10 +66,8 @@ export class UpdateVolunteerDto { @ValidateIf((_, value) => value !== undefined) @IsArray() - @ArrayMaxSize(20) @IsInt({ each: true }) @Min(0, { each: true }) - @Max(25, { each: true }) childrenAges?: number[]; @ValidateIf((_, value) => value !== undefined) @@ -80,7 +76,6 @@ export class UpdateVolunteerDto { @ValidateIf((_, value) => value !== undefined) @IsArray() - @ArrayMaxSize(20) @ValidateNested({ each: true }) @Type(() => PetDto) pets?: PetDto[]; From 62313a8c0a4212acdea20af9a364f60aeb950447 Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Tue, 17 Nov 2026 18:59:41 -0500 Subject: [PATCH 08/13] MSPCA-56: add livelyNeighborhood and address review feedback Move PetDto to pets/dtos, document params on the children-rule helpers, and type the pet fixtures in specs. Co-Authored-By: Claude Sonnet 5.5 --- ...794408338094-AddPetsAndHouseholdDetails.ts | 3 ++ .../src/{volunteers => pets}/dtos/pet.dto.ts | 2 +- .../volunteers/dtos/create-volunteer.dto.ts | 5 ++- .../volunteers/dtos/update-volunteer.dto.ts | 7 ++- .../volunteers/volunteers.controller.spec.ts | 4 +- .../src/volunteers/volunteers.entity.ts | 3 ++ .../src/volunteers/volunteers.service.spec.ts | 45 ++++++++++++++----- .../src/volunteers/volunteers.service.ts | 4 ++ 8 files changed, 58 insertions(+), 15 deletions(-) rename apps/backend/src/{volunteers => pets}/dtos/pet.dto.ts (85%) diff --git a/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts b/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts index dd66eec80..aeed39aa7 100644 --- a/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts +++ b/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts @@ -23,6 +23,7 @@ export class AddPetsAndHouseholdDetails1794408338094 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" `); @@ -30,6 +31,7 @@ export class AddPetsAndHouseholdDetails1794408338094 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) @@ -44,6 +46,7 @@ export class AddPetsAndHouseholdDetails1794408338094 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", diff --git a/apps/backend/src/volunteers/dtos/pet.dto.ts b/apps/backend/src/pets/dtos/pet.dto.ts similarity index 85% rename from apps/backend/src/volunteers/dtos/pet.dto.ts rename to apps/backend/src/pets/dtos/pet.dto.ts index 71e13fe23..120663f89 100644 --- a/apps/backend/src/volunteers/dtos/pet.dto.ts +++ b/apps/backend/src/pets/dtos/pet.dto.ts @@ -1,5 +1,5 @@ import { IsEnum, IsInt, Max, MaxLength, Min } from 'class-validator'; -import { FosterType } from '../volunteers.types'; +import { FosterType } from '../../volunteers/volunteers.types'; import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.decorator'; export class PetDto { diff --git a/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts b/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts index cb95641d5..a720d8380 100644 --- a/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts +++ b/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts @@ -19,7 +19,7 @@ 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 './pet.dto'; +import { PetDto } from '../../pets/dtos/pet.dto'; export class CreateVolunteerDto { @IsNonEmptyString() @@ -87,6 +87,9 @@ export class CreateVolunteerDto { @IsBoolean() hasSeparateFosterRoom!: boolean; + @IsBoolean() + livelyNeighborhood!: boolean; + @ValidateIf((_, value) => value !== undefined) @IsArray() @ValidateNested({ each: true }) diff --git a/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts b/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts index 524c55d4e..048b0e87d 100644 --- a/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts +++ b/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts @@ -16,7 +16,7 @@ import { } from 'class-validator'; import { Type } from 'class-transformer'; import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.decorator'; -import { PetDto } from './pet.dto'; +import { PetDto } from '../../pets/dtos/pet.dto'; import { AtLeastOneValue } from './validators/at-least-one-value.validator'; @AtLeastOneValue([ @@ -31,6 +31,7 @@ import { AtLeastOneValue } from './validators/at-least-one-value.validator'; 'hasChildren', 'childrenAges', 'hasSeparateFosterRoom', + 'livelyNeighborhood', 'pets', 'notes', 'fosterType', @@ -92,6 +93,10 @@ export class UpdateVolunteerDto { @IsBoolean() hasSeparateFosterRoom?: boolean; + @ValidateIf((_, value) => value !== undefined) + @IsBoolean() + livelyNeighborhood?: boolean; + @ValidateIf((_, value) => value !== undefined) @IsArray() @ValidateNested({ each: true }) diff --git a/apps/backend/src/volunteers/volunteers.controller.spec.ts b/apps/backend/src/volunteers/volunteers.controller.spec.ts index b069284e9..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; @@ -165,6 +166,7 @@ describe('VolunteersController', () => { homebase: Homebase.BOSTON, hasChildren: false, hasSeparateFosterRoom: true, + livelyNeighborhood: false, fosterType: [FosterType.CAT], password: 'Str0ng!Password', } as CreateVolunteerDto; @@ -231,7 +233,7 @@ describe('VolunteersController', () => { ageMonth: 11, species: FosterType.CAT, breed: 'Tabby', - }; + } as PetDto; it('accepts a volunteer with pets and children', async () => { const result = await validationPipe.transform( diff --git a/apps/backend/src/volunteers/volunteers.entity.ts b/apps/backend/src/volunteers/volunteers.entity.ts index a194a3a10..e7ed33da0 100644 --- a/apps/backend/src/volunteers/volunteers.entity.ts +++ b/apps/backend/src/volunteers/volunteers.entity.ts @@ -77,6 +77,9 @@ export class FosterVolunteer { @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[]; diff --git a/apps/backend/src/volunteers/volunteers.service.spec.ts b/apps/backend/src/volunteers/volunteers.service.spec.ts index c9efda36e..04d6634fd 100644 --- a/apps/backend/src/volunteers/volunteers.service.spec.ts +++ b/apps/backend/src/volunteers/volunteers.service.spec.ts @@ -25,6 +25,7 @@ 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; @@ -104,6 +105,7 @@ describe('VolunteersService', () => { 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); @@ -193,6 +195,7 @@ describe('VolunteersService', () => { homebase: Homebase.BOSTON, hasChildren: false, hasSeparateFosterRoom: true, + livelyNeighborhood: false, notes: 'Prefers kittens', fosterType: [FosterType.CAT], password: 'Str0ng!Password', @@ -909,28 +912,29 @@ describe('VolunteersService', () => { }); it('replaces the pets list when pets is provided', async () => { - const pet = { - ageYear: 1, - ageMonth: 6, - species: FosterType.CAT, - breed: 'Siamese', - }; + 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], + 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: [pet], + pets: newPets, }); expect(mockRepo.save).toHaveBeenCalledTimes(1); expect(mockRepo.save).toHaveBeenCalledWith({ ...mockVolunteer, - pets: [pet], + pets: newPets, }); - expect(result.pets).toEqual([pet]); + expect(result.pets).toEqual(newPets); }); }); @@ -948,7 +952,26 @@ describe('VolunteersService', () => { 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({ diff --git a/apps/backend/src/volunteers/volunteers.service.ts b/apps/backend/src/volunteers/volunteers.service.ts index 9bd92e909..b2dc1c576 100644 --- a/apps/backend/src/volunteers/volunteers.service.ts +++ b/apps/backend/src/volunteers/volunteers.service.ts @@ -422,6 +422,8 @@ export class VolunteersService { * 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( @@ -441,6 +443,8 @@ export class VolunteersService { * 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( From 29aafbdc1c1b67ad6a5b172b94eb82de26046cc1 Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Sat, 21 Nov 2026 15:49:58 -0500 Subject: [PATCH 09/13] MSPCA-67: add monthly pet age increment service Co-Authored-By: Claude Sonnet 5.5 --- apps/backend/src/pets/pets.module.ts | 11 ++++ apps/backend/src/pets/pets.service.spec.ts | 72 ++++++++++++++++++++++ apps/backend/src/pets/pets.service.ts | 32 ++++++++++ 3 files changed, 115 insertions(+) create mode 100644 apps/backend/src/pets/pets.module.ts create mode 100644 apps/backend/src/pets/pets.service.spec.ts create mode 100644 apps/backend/src/pets/pets.service.ts 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..5bdbd9701 --- /dev/null +++ b/apps/backend/src/pets/pets.service.spec.ts @@ -0,0 +1,72 @@ +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 }), + ]); + }); + + 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 }), + ]); + }); + + 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 }), + ]); + }); + + 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; + } +} From 8d15dd0eb4da33aab86a7a30b751ac66784577b2 Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Sat, 21 Nov 2026 15:50:43 -0500 Subject: [PATCH 10/13] MSPCA-67: add yearly children age increment service Co-Authored-By: Claude Sonnet 5.5 --- .../src/volunteers/volunteers.service.spec.ts | 59 +++++++++++++++++++ .../src/volunteers/volunteers.service.ts | 20 +++++++ 2 files changed, 79 insertions(+) diff --git a/apps/backend/src/volunteers/volunteers.service.spec.ts b/apps/backend/src/volunteers/volunteers.service.spec.ts index 04d6634fd..30b125aab 100644 --- a/apps/backend/src/volunteers/volunteers.service.spec.ts +++ b/apps/backend/src/volunteers/volunteers.service.spec.ts @@ -1962,4 +1962,63 @@ 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 }, + }); + }); + + 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] }), + ]); + }); + + 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] }), + ]); + }); + + 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 b2dc1c576..2e4ba7c73 100644 --- a/apps/backend/src/volunteers/volunteers.service.ts +++ b/apps/backend/src/volunteers/volunteers.service.ts @@ -606,6 +606,26 @@ export class VolunteersService { }); 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. * From 2cdec4e9b95a48f5e175f5632498f712973d980b Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Sat, 21 Nov 2026 15:52:20 -0500 Subject: [PATCH 11/13] MSPCA-67: schedule monthly pet and yearly children age jobs Co-Authored-By: Claude Sonnet 5.5 --- apps/backend/src/app.module.ts | 4 ++ .../backend/src/jobs/age-jobs.service.spec.ts | 69 +++++++++++++++++++ apps/backend/src/jobs/age-jobs.service.ts | 48 +++++++++++++ apps/backend/src/jobs/jobs.module.ts | 10 +++ package.json | 1 + yarn.lock | 31 +++++++++ 6 files changed, 163 insertions(+) create mode 100644 apps/backend/src/jobs/age-jobs.service.spec.ts create mode 100644 apps/backend/src/jobs/age-jobs.service.ts create mode 100644 apps/backend/src/jobs/jobs.module.ts 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/jobs/age-jobs.service.spec.ts b/apps/backend/src/jobs/age-jobs.service.spec.ts new file mode 100644 index 000000000..4a9551914 --- /dev/null +++ b/apps/backend/src/jobs/age-jobs.service.spec.ts @@ -0,0 +1,69 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { Logger } from '@nestjs/common'; +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().mockResolvedValue(0) }; + mockVolunteersService = { + incrementAllChildrenAges: jest.fn().mockResolvedValue(0), + }; + 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 () => { + 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 () => { + 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(); + }); + }); +}); 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/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" From 9c4e1c28afcdc65b03bbc43b4eb62de1424ca043 Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Sun, 22 Nov 2026 11:48:07 -0500 Subject: [PATCH 12/13] MSPCA-67: assert cron expressions and time zone for age jobs Co-Authored-By: Claude Sonnet 5.5 --- .../backend/src/jobs/age-jobs.service.spec.ts | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/apps/backend/src/jobs/age-jobs.service.spec.ts b/apps/backend/src/jobs/age-jobs.service.spec.ts index 4a9551914..49f4a6866 100644 --- a/apps/backend/src/jobs/age-jobs.service.spec.ts +++ b/apps/backend/src/jobs/age-jobs.service.spec.ts @@ -1,5 +1,6 @@ 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'; @@ -66,4 +67,26 @@ describe('AgeJobsService', () => { 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', + }); + }); + }); }); From bdbf65cd672b6a359b8212959bdad946f9417bcd Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Sun, 22 Nov 2026 12:25:55 -0500 Subject: [PATCH 13/13] MSPCA-67: follow repo test conventions in age job specs Co-Authored-By: Claude Sonnet 5.5 --- apps/backend/src/jobs/age-jobs.service.spec.ts | 8 ++++---- apps/backend/src/pets/pets.service.spec.ts | 3 +++ apps/backend/src/volunteers/volunteers.service.spec.ts | 3 +++ 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/apps/backend/src/jobs/age-jobs.service.spec.ts b/apps/backend/src/jobs/age-jobs.service.spec.ts index 49f4a6866..fd4ad5dfb 100644 --- a/apps/backend/src/jobs/age-jobs.service.spec.ts +++ b/apps/backend/src/jobs/age-jobs.service.spec.ts @@ -12,10 +12,8 @@ describe('AgeJobsService', () => { let errorSpy: jest.SpyInstance; beforeEach(async () => { - mockPetsService = { incrementAllAges: jest.fn().mockResolvedValue(0) }; - mockVolunteersService = { - incrementAllChildrenAges: jest.fn().mockResolvedValue(0), - }; + mockPetsService = { incrementAllAges: jest.fn() }; + mockVolunteersService = { incrementAllChildrenAges: jest.fn() }; jest.spyOn(Logger.prototype, 'log').mockImplementation(); errorSpy = jest.spyOn(Logger.prototype, 'error').mockImplementation(); @@ -36,6 +34,7 @@ describe('AgeJobsService', () => { describe('incrementPetAges', () => { it('calls PetsService.incrementAllAges once', async () => { + mockPetsService.incrementAllAges.mockResolvedValue(3); await service.incrementPetAges(); expect(mockPetsService.incrementAllAges).toHaveBeenCalledTimes(1); @@ -51,6 +50,7 @@ describe('AgeJobsService', () => { describe('incrementChildrenAges', () => { it('calls VolunteersService.incrementAllChildrenAges once', async () => { + mockVolunteersService.incrementAllChildrenAges.mockResolvedValue(2); await service.incrementChildrenAges(); expect( diff --git a/apps/backend/src/pets/pets.service.spec.ts b/apps/backend/src/pets/pets.service.spec.ts index 5bdbd9701..5d4879d22 100644 --- a/apps/backend/src/pets/pets.service.spec.ts +++ b/apps/backend/src/pets/pets.service.spec.ts @@ -32,6 +32,7 @@ describe('PetsService', () => { expect(mockRepo.save).toHaveBeenCalledWith([ expect.objectContaining({ ageYear: 1, ageMonth: 6 }), ]); + expect(mockRepo.save).toHaveBeenCalledTimes(1); }); it('rolls 11 months into the next year', async () => { @@ -42,6 +43,7 @@ describe('PetsService', () => { expect(mockRepo.save).toHaveBeenCalledWith([ expect.objectContaining({ ageYear: 3, ageMonth: 0 }), ]); + expect(mockRepo.save).toHaveBeenCalledTimes(1); }); it('increments every pet independently', async () => { @@ -54,6 +56,7 @@ describe('PetsService', () => { 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 () => { diff --git a/apps/backend/src/volunteers/volunteers.service.spec.ts b/apps/backend/src/volunteers/volunteers.service.spec.ts index 30b125aab..63d36bec7 100644 --- a/apps/backend/src/volunteers/volunteers.service.spec.ts +++ b/apps/backend/src/volunteers/volunteers.service.spec.ts @@ -1979,6 +1979,7 @@ describe('VolunteersService', () => { expect(mockRepo.find).toHaveBeenCalledWith({ where: { hasChildren: true }, }); + expect(mockRepo.find).toHaveBeenCalledTimes(1); }); it('adds one year to every child', async () => { @@ -1989,6 +1990,7 @@ describe('VolunteersService', () => { expect(mockRepo.save).toHaveBeenCalledWith([ expect.objectContaining({ volunteerId: 1, childrenAges: [1, 8, 16] }), ]); + expect(mockRepo.save).toHaveBeenCalledTimes(1); }); it('updates each volunteer independently', async () => { @@ -2003,6 +2005,7 @@ describe('VolunteersService', () => { 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 () => {