From 6420da15881efaf150ecda5d6318dc9b2876e928 Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Wed, 11 Nov 2026 10:13:57 -0500 Subject: [PATCH 1/9] 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 2/9] 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 3/9] 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 4/9] 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 5/9] 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 6/9] 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 7/9] 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 8/9] 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 c3dcc088ec0c2e6cdd6f17e2f78698390614bdb5 Mon Sep 17 00:00:00 2001 From: Justin Wang Date: Sun, 22 Nov 2026 10:13:28 -0500 Subject: [PATCH 9/9] MSPCA-56: address second-round review comments Combine the create() InternalServerErrorException @throws, use real coordinator and pet data in the findByIdOrFail test, cast the pet fixtures, drop the livelyNeighborhood update test, and assert the old pet is left out of the saved list. Co-Authored-By: Claude Opus 5.5 --- .../src/volunteers/volunteers.service.spec.ts | 43 +++++++++---------- .../src/volunteers/volunteers.service.ts | 4 +- 2 files changed, 23 insertions(+), 24 deletions(-) diff --git a/apps/backend/src/volunteers/volunteers.service.spec.ts b/apps/backend/src/volunteers/volunteers.service.spec.ts index f44061ca4..274fb8ac6 100644 --- a/apps/backend/src/volunteers/volunteers.service.spec.ts +++ b/apps/backend/src/volunteers/volunteers.service.spec.ts @@ -117,8 +117,24 @@ describe('VolunteersService', () => { it('returns the volunteer with their coordinators and pets', async () => { const volunteer = { volunteerId: 7, - assignedCoordinators: [] as FosterCoordinator[], - pets: [] as Pet[], + assignedCoordinators: [ + { + coordinatorId: 3, + email: 'c3@example.com', + homebase: Homebase.BOSTON, + active: true, + }, + ] as FosterCoordinator[], + pets: [ + { + petId: 5, + volunteerId: 7, + ageYear: 4, + ageMonth: 2, + species: FosterType.DOG, + breed: 'Lab', + }, + ] as Pet[], } as FosterVolunteer; mockRepo.findOne.mockResolvedValue(volunteer); @@ -287,7 +303,7 @@ describe('VolunteersService', () => { const pets = [ { ageYear: 2, ageMonth: 3, species: FosterType.DOG, breed: 'Beagle' }, { ageYear: 0, ageMonth: 8, species: FosterType.CAT, breed: 'Tabby' }, - ]; + ] as PetDto[]; const result = await service.create({ ...dto, @@ -966,25 +982,6 @@ describe('VolunteersService', () => { breed: 'Siamese', } as PetDto; - it('updates livelyNeighborhood', async () => { - mockRepo.findOne.mockResolvedValue({ - ...mockVolunteer, - livelyNeighborhood: false, - }); - mockRepo.save.mockImplementation(async (v) => v); - - const result = await service.updateVolunteerById(1, { - livelyNeighborhood: true, - }); - - expect(mockRepo.save).toHaveBeenCalledTimes(1); - expect(mockRepo.save).toHaveBeenCalledWith({ - ...mockVolunteer, - livelyNeighborhood: true, - }); - expect(result.livelyNeighborhood).toBe(true); - }); - it('replaces the pets list when pets is provided', async () => { mockRepo.findOne.mockResolvedValue({ ...mockVolunteer, @@ -999,6 +996,8 @@ describe('VolunteersService', () => { ...mockVolunteer, pets: [newPet], }); + const [saved] = mockRepo.save.mock.calls[0]; + expect(saved.pets).not.toContainEqual(existingPet); expect(result.pets).toEqual([newPet]); }); diff --git a/apps/backend/src/volunteers/volunteers.service.ts b/apps/backend/src/volunteers/volunteers.service.ts index 053dcbcba..5a43d2eb2 100644 --- a/apps/backend/src/volunteers/volunteers.service.ts +++ b/apps/backend/src/volunteers/volunteers.service.ts @@ -116,8 +116,8 @@ export class VolunteersService { * @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. - * @throws {InternalServerErrorException} If the Volunteer could not be saved (the Cognito user is deleted). + * @throws {InternalServerErrorException} If the Cognito user could not be registered, + * or the Volunteer could not be saved (the Cognito user is then deleted). */ async create( dto: CreateVolunteerDto,