diff --git a/apps/backend/src/config/migrations.ts b/apps/backend/src/config/migrations.ts index 9316b2a32..af863eb36 100644 --- a/apps/backend/src/config/migrations.ts +++ b/apps/backend/src/config/migrations.ts @@ -12,6 +12,7 @@ import { AddAnimalUpdatesAndFosterTypeArray1793163582751 } from '../migrations/1 import { AddFarmAnimalsToFosterType1793476100199 } from '../migrations/1793476100199-AddFarmAnimalsToFosterType'; import { RenameAdminUsersToOwners1793485161630 } from '../migrations/1793485161630-RenameAdminUsersToOwners'; import { AddFosterTypePreferences1793600000000 } from '../migrations/1793600000000-AddFosterTypePreferences'; +import { AddPetsAndHouseholdDetails1794408338094 } from '../migrations/1794408338094-AddPetsAndHouseholdDetails'; import { AddMatchAdditionalComments1794784721012 } from '../migrations/1794784721012-AddMatchAdditionalComments'; const schemaMigrations = [ @@ -29,6 +30,7 @@ const schemaMigrations = [ AddFarmAnimalsToFosterType1793476100199, RenameAdminUsersToOwners1793485161630, AddFosterTypePreferences1793600000000, + AddPetsAndHouseholdDetails1794408338094, AddMatchAdditionalComments1794784721012, ]; diff --git a/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts b/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts new file mode 100644 index 000000000..aeed39aa7 --- /dev/null +++ b/apps/backend/src/migrations/1794408338094-AddPetsAndHouseholdDetails.ts @@ -0,0 +1,62 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddPetsAndHouseholdDetails1794408338094 + implements MigrationInterface +{ + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + CREATE TABLE "pets" ( + "pet_id" SERIAL PRIMARY KEY, + "volunteer_id" int NOT NULL + REFERENCES "foster_volunteers" ("volunteer_id") ON DELETE CASCADE, + "age_year" int NOT NULL, + "age_month" int NOT NULL, + "species" "foster_type_enum" NOT NULL, + "breed" varchar(255) NOT NULL, + CONSTRAINT "CHK_pets_age_year" CHECK ("age_year" >= 0), + CONSTRAINT "CHK_pets_age_month" CHECK ("age_month" BETWEEN 0 AND 11) + ) + `); + + await queryRunner.query(` + ALTER TABLE "foster_volunteers" + ADD COLUMN "has_children" boolean NOT NULL DEFAULT false, + ADD COLUMN "children_ages" int[] NOT NULL DEFAULT '{}', + ADD COLUMN "has_separate_foster_room" boolean NOT NULL DEFAULT false, + ADD COLUMN "lively_neighborhood" boolean NOT NULL DEFAULT false, + DROP COLUMN "resident_animals" + `); + + await queryRunner.query(` + ALTER TABLE "foster_volunteers" + ALTER COLUMN "has_children" DROP DEFAULT, + ALTER COLUMN "has_separate_foster_room" DROP DEFAULT, + ALTER COLUMN "lively_neighborhood" DROP DEFAULT, + ADD CONSTRAINT "CHK_foster_volunteers_children_ages" CHECK ( + ("has_children" AND cardinality("children_ages") > 0) + OR (NOT "has_children" AND cardinality("children_ages") = 0) + ), + ADD CONSTRAINT "CHK_foster_volunteers_children_ages_nonnegative" + CHECK (0 <= ALL ("children_ages")) + `); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + ALTER TABLE "foster_volunteers" + DROP CONSTRAINT "CHK_foster_volunteers_children_ages_nonnegative", + DROP CONSTRAINT "CHK_foster_volunteers_children_ages", + DROP COLUMN "lively_neighborhood", + DROP COLUMN "has_separate_foster_room", + DROP COLUMN "children_ages", + DROP COLUMN "has_children", + ADD COLUMN "resident_animals" text NOT NULL DEFAULT '' + `); + + await queryRunner.query(` + ALTER TABLE "foster_volunteers" ALTER COLUMN "resident_animals" DROP DEFAULT + `); + + await queryRunner.query(`DROP TABLE "pets"`); + } +} diff --git a/apps/backend/src/pets/dtos/pet.dto.ts b/apps/backend/src/pets/dtos/pet.dto.ts new file mode 100644 index 000000000..120663f89 --- /dev/null +++ b/apps/backend/src/pets/dtos/pet.dto.ts @@ -0,0 +1,21 @@ +import { IsEnum, IsInt, Max, MaxLength, Min } from 'class-validator'; +import { FosterType } from '../../volunteers/volunteers.types'; +import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.decorator'; + +export class PetDto { + @IsInt() + @Min(0) + ageYear!: number; + + @IsInt() + @Min(0) + @Max(11) + ageMonth!: number; + + @IsEnum(FosterType) + species!: FosterType; + + @IsNonEmptyString() + @MaxLength(255) + breed!: string; +} diff --git a/apps/backend/src/pets/pets.entity.ts b/apps/backend/src/pets/pets.entity.ts new file mode 100644 index 000000000..eb3997b02 --- /dev/null +++ b/apps/backend/src/pets/pets.entity.ts @@ -0,0 +1,41 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + ManyToOne, + JoinColumn, + Check, +} from 'typeorm'; +import { FosterVolunteer } from '../volunteers/volunteers.entity'; +import { FosterType } from '../volunteers/volunteers.types'; + +@Entity('pets') +@Check('CHK_pets_age_year', '"age_year" >= 0') +@Check('CHK_pets_age_month', '"age_month" BETWEEN 0 AND 11') +export class Pet { + @PrimaryGeneratedColumn({ name: 'pet_id' }) + petId!: number; + + @ManyToOne(() => FosterVolunteer, (volunteer) => volunteer.pets, { + nullable: false, + onDelete: 'CASCADE', + orphanedRowAction: 'delete', + }) + @JoinColumn({ name: 'volunteer_id' }) + volunteer!: FosterVolunteer; + + @Column({ name: 'volunteer_id' }) + volunteerId!: number; + + @Column({ name: 'age_year', type: 'int' }) + ageYear!: number; + + @Column({ name: 'age_month', type: 'int' }) + ageMonth!: number; + + @Column({ type: 'enum', enum: FosterType, enumName: 'foster_type_enum' }) + species!: FosterType; + + @Column({ type: 'varchar', length: 255 }) + breed!: string; +} diff --git a/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts b/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts index ae9f547ce..a720d8380 100644 --- a/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts +++ b/apps/backend/src/volunteers/dtos/create-volunteer.dto.ts @@ -2,19 +2,24 @@ import { ArrayNotEmpty, ArrayUnique, IsArray, + IsBoolean, IsEmail, IsEnum, + IsInt, IsNotEmpty, IsPhoneNumber, IsString, IsStrongPassword, MaxLength, + Min, ValidateIf, + ValidateNested, } from 'class-validator'; -import { Transform } from 'class-transformer'; +import { Transform, Type } from 'class-transformer'; import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.decorator'; import { Homebase } from '../../types'; import { FosterTraining, FosterType } from '../volunteers.types'; +import { PetDto } from '../../pets/dtos/pet.dto'; export class CreateVolunteerDto { @IsNonEmptyString() @@ -70,8 +75,26 @@ export class CreateVolunteerDto { @IsEnum(Homebase) homebase!: Homebase; - @IsNonEmptyString() - residentAnimals!: string; + @IsBoolean() + hasChildren!: boolean; + + @ValidateIf((_, value) => value !== undefined) + @IsArray() + @IsInt({ each: true }) + @Min(0, { each: true }) + childrenAges?: number[]; + + @IsBoolean() + hasSeparateFosterRoom!: boolean; + + @IsBoolean() + livelyNeighborhood!: boolean; + + @ValidateIf((_, value) => value !== undefined) + @IsArray() + @ValidateNested({ each: true }) + @Type(() => PetDto) + pets?: PetDto[]; @ValidateIf((_, value) => value !== undefined && value !== null) @IsNonEmptyString() diff --git a/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts b/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts index 95acb7610..048b0e87d 100644 --- a/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts +++ b/apps/backend/src/volunteers/dtos/update-volunteer.dto.ts @@ -4,14 +4,19 @@ import { IsArray, IsBoolean, IsEnum, + IsInt, IsNotEmpty, MaxLength, + Min, IsPhoneNumber, IsEmail, ArrayUnique, ValidateIf, + ValidateNested, } from 'class-validator'; +import { Type } from 'class-transformer'; import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.decorator'; +import { PetDto } from '../../pets/dtos/pet.dto'; import { AtLeastOneValue } from './validators/at-least-one-value.validator'; @AtLeastOneValue([ @@ -23,7 +28,11 @@ import { AtLeastOneValue } from './validators/at-least-one-value.validator'; 'address', 'city', 'zipcode', - 'residentAnimals', + 'hasChildren', + 'childrenAges', + 'hasSeparateFosterRoom', + 'livelyNeighborhood', + 'pets', 'notes', 'fosterType', 'animalUpdates', @@ -71,8 +80,28 @@ export class UpdateVolunteerDto { zipcode?: string; @ValidateIf((_, value) => value !== undefined) - @IsNonEmptyString() - residentAnimals?: string; + @IsBoolean() + hasChildren?: boolean; + + @ValidateIf((_, value) => value !== undefined) + @IsArray() + @IsInt({ each: true }) + @Min(0, { each: true }) + childrenAges?: number[]; + + @ValidateIf((_, value) => value !== undefined) + @IsBoolean() + hasSeparateFosterRoom?: boolean; + + @ValidateIf((_, value) => value !== undefined) + @IsBoolean() + livelyNeighborhood?: boolean; + + @ValidateIf((_, value) => value !== undefined) + @IsArray() + @ValidateNested({ each: true }) + @Type(() => PetDto) + pets?: PetDto[]; @ValidateIf((_, value) => value !== undefined && value !== null) @IsNonEmptyString() diff --git a/apps/backend/src/volunteers/volunteers.controller.spec.ts b/apps/backend/src/volunteers/volunteers.controller.spec.ts index 332b741aa..a990caa8a 100644 --- a/apps/backend/src/volunteers/volunteers.controller.spec.ts +++ b/apps/backend/src/volunteers/volunteers.controller.spec.ts @@ -24,6 +24,7 @@ import { UpdateSpeciesPreferencesDto } from './dtos/update-species-preferences.d import { CoordinatorUpdateVolunteerDto } from './dtos/coordinator-update-volunteer.dto'; import { Homebase } from '../types'; import { UpdateHomebaseDto } from './dtos/update-homebase.dto'; +import { PetDto } from '../pets/dtos/pet.dto'; describe('VolunteersController', () => { let controller: VolunteersController; @@ -163,7 +164,9 @@ describe('VolunteersController', () => { city: 'Boston', zipcode: '02130', homebase: Homebase.BOSTON, - residentAnimals: 'One cat', + hasChildren: false, + hasSeparateFosterRoom: true, + livelyNeighborhood: false, fosterType: [FosterType.CAT], password: 'Str0ng!Password', } as CreateVolunteerDto; @@ -224,6 +227,24 @@ describe('VolunteersController', () => { expect(result).not.toHaveProperty('completedTrainings'); }); + + const pet = { + ageYear: 3, + ageMonth: 11, + species: FosterType.CAT, + breed: 'Tabby', + } as PetDto; + + it('accepts a volunteer with pets and children', async () => { + const result = await validationPipe.transform( + { ...dto, hasChildren: true, childrenAges: [4, 9], pets: [pet] }, + { type: 'body', metatype: CreateVolunteerDto }, + ); + + expect(result.hasChildren).toBe(true); + expect(result.childrenAges).toEqual([4, 9]); + expect(result.pets).toEqual([pet]); + }); }); describe('confirm', () => { @@ -301,6 +322,7 @@ describe('VolunteersController', () => { const result = await controller.getVolunteerById(1); expect(result).toEqual(mockVolunteer); + expect(mockVolunteersService.findByIdOrFail).toHaveBeenCalledTimes(1); expect(mockVolunteersService.findByIdOrFail).toHaveBeenCalledWith(1); }); diff --git a/apps/backend/src/volunteers/volunteers.controller.ts b/apps/backend/src/volunteers/volunteers.controller.ts index c43c02e47..233572723 100644 --- a/apps/backend/src/volunteers/volunteers.controller.ts +++ b/apps/backend/src/volunteers/volunteers.controller.ts @@ -187,7 +187,8 @@ export class VolunteersController { }) @ApiResponse({ status: HttpStatus.BAD_REQUEST, - description: 'Invalid ID or invalid field', + description: + 'Invalid ID, invalid field, no fields provided, or childrenAges does not match hasChildren', }) @ApiResponse({ status: HttpStatus.NOT_FOUND, @@ -216,6 +217,15 @@ export class VolunteersController { description: 'The volunteer was updated', type: VolunteerWithoutPrivateFields, }) + @ApiResponse({ + status: HttpStatus.BAD_REQUEST, + description: + 'Invalid ID, invalid field, no fields provided, or childrenAges does not match hasChildren', + }) + @ApiResponse({ + status: HttpStatus.NOT_FOUND, + description: 'The volunteer does not exist', + }) async updateVolunteerById( @Param('volunteerId', ParseIntPipe) volunteerId: number, @Body() dto: UpdateVolunteerDto, diff --git a/apps/backend/src/volunteers/volunteers.entity.ts b/apps/backend/src/volunteers/volunteers.entity.ts index 879d868a5..3bd6ea268 100644 --- a/apps/backend/src/volunteers/volunteers.entity.ts +++ b/apps/backend/src/volunteers/volunteers.entity.ts @@ -6,6 +6,7 @@ import { ManyToMany, JoinTable, Unique, + Check, } from 'typeorm'; import { Homebase } from '../types'; import { @@ -14,10 +15,19 @@ import { VolunteerStatus, } from './volunteers.types'; import { FosterCoordinator } from '../coordinators/coordinators.entity'; +import { Pet } from '../pets/pets.entity'; import { Match } from '../matches/matches.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; @@ -54,8 +64,25 @@ export class FosterVolunteer { @Column({ type: 'enum', enum: Homebase }) homebase!: Homebase; - @Column({ name: 'resident_animals', type: 'text' }) - residentAnimals!: string; + @Column({ name: 'has_children', type: 'boolean' }) + hasChildren!: boolean; + + @Column({ + name: 'children_ages', + type: 'int', + array: true, + default: () => "'{}'", + }) + childrenAges!: number[]; + + @Column({ name: 'has_separate_foster_room', type: 'boolean' }) + hasSeparateFosterRoom!: boolean; + + @Column({ name: 'lively_neighborhood', type: 'boolean' }) + livelyNeighborhood!: boolean; + + @OneToMany(() => Pet, (pet) => pet.volunteer, { cascade: true }) + pets!: Pet[]; @Column({ type: 'text', nullable: true }) notes!: string | null; diff --git a/apps/backend/src/volunteers/volunteers.module.ts b/apps/backend/src/volunteers/volunteers.module.ts index 22bff765f..a9c16f5c4 100644 --- a/apps/backend/src/volunteers/volunteers.module.ts +++ b/apps/backend/src/volunteers/volunteers.module.ts @@ -1,6 +1,7 @@ import { Module, forwardRef } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { FosterVolunteer } from './volunteers.entity'; +import { Pet } from '../pets/pets.entity'; import { VolunteersController } from './volunteers.controller'; import { VolunteersService } from './volunteers.service'; import { CoordinatorsModule } from '../coordinators/coordinators.module'; @@ -10,7 +11,7 @@ import { AnimalsModule } from '../animals/animals.module'; @Module({ imports: [ - TypeOrmModule.forFeature([FosterVolunteer]), + TypeOrmModule.forFeature([FosterVolunteer, Pet]), CoordinatorsModule, AWSSESModule, forwardRef(() => MatchesModule), diff --git a/apps/backend/src/volunteers/volunteers.service.spec.ts b/apps/backend/src/volunteers/volunteers.service.spec.ts index 0e7e6be45..7ac78af94 100644 --- a/apps/backend/src/volunteers/volunteers.service.spec.ts +++ b/apps/backend/src/volunteers/volunteers.service.spec.ts @@ -26,6 +26,8 @@ import { AnimalsService } from '../animals/animals.service'; import { CoordinatorsService } from '../coordinators/coordinators.service'; import { FosterCoordinator } from '../coordinators/coordinators.entity'; import { Homebase } from '../types'; +import { Pet } from '../pets/pets.entity'; +import { PetDto } from '../pets/dtos/pet.dto'; describe('VolunteersService', () => { let service: VolunteersService; @@ -35,6 +37,9 @@ describe('VolunteersService', () => { firstName: 'Jane', lastName: 'Doe', notes: 'likes cats', + hasChildren: false, + childrenAges: [] as number[], + pets: [] as Pet[], assignedCoordinators: [] as FosterCoordinator[], } as FosterVolunteer; @@ -109,8 +114,28 @@ describe('VolunteersService', () => { }); describe('findByIdOrFail', () => { - it('returns the volunteer when one with the id exists', async () => { - const volunteer = { volunteerId: 7 } as FosterVolunteer; + it('returns the volunteer with their coordinators and pets', async () => { + const volunteer = { + volunteerId: 7, + assignedCoordinators: [ + { + 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); const result = await service.findByIdOrFail(7); @@ -118,7 +143,7 @@ describe('VolunteersService', () => { expect(result).toBe(volunteer); expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 7 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.findOne).toHaveBeenCalledTimes(1); }); @@ -131,7 +156,7 @@ describe('VolunteersService', () => { ); expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 7 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); }); @@ -235,7 +260,9 @@ describe('VolunteersService', () => { city: 'Boston', zipcode: '02130', homebase: Homebase.BOSTON, - residentAnimals: 'One cat', + hasChildren: false, + hasSeparateFosterRoom: true, + livelyNeighborhood: false, notes: 'Prefers kittens', fosterType: [FosterType.CAT], password: 'Str0ng!Password', @@ -291,6 +318,8 @@ describe('VolunteersService', () => { expect(mockRepo.save).toHaveBeenCalledTimes(1); expect(mockRepo.save).toHaveBeenCalledWith({ ...profile, + childrenAges: [], + pets: [], status: VolunteerStatus.PENDING, mostRecentWaiverSigned: true, cognitoSub: 'cognito-sub-123', @@ -299,6 +328,8 @@ describe('VolunteersService', () => { expect(result).toEqual({ volunteerId: 1, ...profile, + childrenAges: [], + pets: [], status: VolunteerStatus.PENDING, mostRecentWaiverSigned: true, cognitoSub: 'cognito-sub-123', @@ -307,6 +338,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' }, + ] as PetDto[]; + + 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, @@ -591,7 +667,7 @@ describe('VolunteersService', () => { expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.save).toHaveBeenCalledWith({ ...volunteer, @@ -667,7 +743,7 @@ describe('VolunteersService', () => { expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.save).toHaveBeenCalledWith({ ...volunteer, @@ -730,7 +806,7 @@ describe('VolunteersService', () => { expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); }); @@ -862,9 +938,223 @@ describe('VolunteersService', () => { ); expect(mockRepo.save).not.toHaveBeenCalled(); }); + + it('rejects an update that breaks the children rule and saves nothing', async () => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + hasChildren: true, + childrenAges: [6], + }); + + await expect( + service.coordinatorUpdateVolunteerById(1, { childrenAges: [] }), + ).rejects.toThrow( + new BadRequestException( + 'childrenAges must not be empty when hasChildren is true', + ), + ); + expect(mockRepo.findOne).toHaveBeenCalledTimes(1); + expect(mockRepo.save).not.toHaveBeenCalled(); + }); + + it('clears the saved children ages when hasChildren is set to false', async () => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + hasChildren: true, + childrenAges: [6], + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.coordinatorUpdateVolunteerById(1, { + hasChildren: false, + }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + hasChildren: false, + childrenAges: [], + }); + expect(result.childrenAges).toEqual([]); + }); + + it('replaces the pets list when pets is provided', async () => { + const newPets = [ + { ageYear: 1, ageMonth: 6, species: FosterType.CAT, breed: 'Siamese' }, + { ageYear: 8, ageMonth: 0, species: FosterType.DOG, breed: 'Beagle' }, + ] as PetDto[]; + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + pets: [ + { petId: 5, breed: 'Lab' } as Pet, + { petId: 6, breed: 'Tabby' } as Pet, + ], + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.coordinatorUpdateVolunteerById(1, { + pets: newPets, + }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + pets: newPets, + }); + expect(result.pets).toEqual(newPets); + }); }); describe('updateVolunteerById', () => { + const existingPet = { + petId: 5, + volunteerId: 1, + ageYear: 4, + ageMonth: 2, + species: FosterType.DOG, + breed: 'Lab', + } as Pet; + const newPet = { + ageYear: 1, + ageMonth: 6, + species: FosterType.CAT, + breed: 'Siamese', + } as PetDto; + + it('replaces the pets list when pets is provided', async () => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + pets: [existingPet], + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.updateVolunteerById(1, { pets: [newPet] }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + pets: [newPet], + }); + const [saved] = mockRepo.save.mock.calls[0]; + expect(saved.pets).not.toContainEqual(existingPet); + expect(result.pets).toEqual([newPet]); + }); + + it('clears the pets with an empty list', async () => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + pets: [existingPet], + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.updateVolunteerById(1, { pets: [] }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + pets: [], + }); + expect(result.pets).toEqual([]); + }); + + it('leaves the pets unchanged when pets is omitted', async () => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + pets: [existingPet], + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.updateVolunteerById(1, { notes: 'x' }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + notes: 'x', + pets: [existingPet], + }); + expect(result.pets).toEqual([existingPet]); + }); + + it('adds children with their ages', async () => { + mockRepo.findOne.mockResolvedValue({ ...mockVolunteer }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.updateVolunteerById(1, { + hasChildren: true, + childrenAges: [6], + }); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + hasChildren: true, + childrenAges: [6], + }); + expect(result.hasChildren).toBe(true); + expect(result.childrenAges).toEqual([6]); + }); + + it.each([ + ['hasChildren false alone', { hasChildren: false }], + [ + 'hasChildren false with empty ages', + { hasChildren: false, childrenAges: [] }, + ], + ])('removes children and clears the saved ages with %s', async (_, dto) => { + mockRepo.findOne.mockResolvedValue({ + ...mockVolunteer, + hasChildren: true, + childrenAges: [6], + }); + mockRepo.save.mockImplementation(async (v) => v); + + const result = await service.updateVolunteerById(1, dto); + + expect(mockRepo.save).toHaveBeenCalledTimes(1); + expect(mockRepo.save).toHaveBeenCalledWith({ + ...mockVolunteer, + hasChildren: false, + childrenAges: [], + }); + expect(result.hasChildren).toBe(false); + expect(result.childrenAges).toEqual([]); + }); + + it.each([ + [ + 'hasChildren false sent with ages', + { hasChildren: true, childrenAges: [6] }, + { hasChildren: false, childrenAges: [6] }, + 'childrenAges must be empty when hasChildren is false', + ], + [ + 'clearing ages while hasChildren stays true', + { hasChildren: true, childrenAges: [6] }, + { childrenAges: [] }, + 'childrenAges must not be empty when hasChildren is true', + ], + [ + 'hasChildren true with no ages saved or sent', + { hasChildren: false, childrenAges: [] }, + { hasChildren: true }, + 'childrenAges must not be empty when hasChildren is true', + ], + [ + 'ages while hasChildren stays false', + { hasChildren: false, childrenAges: [] }, + { childrenAges: [3] }, + 'childrenAges must be empty when hasChildren is false', + ], + ])('rejects %s and saves nothing', async (_, saved, dto, message) => { + mockRepo.findOne.mockResolvedValue({ ...mockVolunteer, ...saved }); + + await expect(service.updateVolunteerById(1, dto)).rejects.toThrow( + new BadRequestException(message), + ); + expect(mockRepo.findOne).toHaveBeenCalledTimes(1); + expect(mockRepo.save).not.toHaveBeenCalled(); + }); + it('should update and return the volunteer with only the given fields changed', async () => { mockRepo.findOne.mockResolvedValue({ ...mockVolunteer }); mockRepo.save.mockImplementation((v) => Promise.resolve(v)); @@ -876,7 +1166,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, @@ -908,7 +1198,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, @@ -961,7 +1251,7 @@ describe('VolunteersService', () => { ]); expect(mockRepo.findOne).toHaveBeenCalledWith({ where: { volunteerId: 1 }, - relations: ['assignedCoordinators'], + relations: ['assignedCoordinators', 'pets'], }); expect(mockRepo.save).toHaveBeenCalledWith( expect.objectContaining({ fosterTypePreferences: result }), @@ -1274,12 +1564,17 @@ describe('VolunteersService', () => { 'volunteer.assignedCoordinators', 'coordinator', ); + expect(mockQueryBuilder.leftJoinAndSelect).toHaveBeenCalledWith( + 'volunteer.pets', + 'pet', + ); expect(mockQueryBuilder.leftJoinAndSelect).toHaveBeenCalledWith( 'volunteer.matches', 'match', 'match.status = :status', { status: MatchStatus.ACTIVE }, ); + expect(mockQueryBuilder.leftJoinAndSelect).toHaveBeenCalledTimes(3); expect(mockQueryBuilder.getMany).toHaveBeenCalledTimes(1); }); diff --git a/apps/backend/src/volunteers/volunteers.service.ts b/apps/backend/src/volunteers/volunteers.service.ts index e44c726e2..adaa13bf5 100644 --- a/apps/backend/src/volunteers/volunteers.service.ts +++ b/apps/backend/src/volunteers/volunteers.service.ts @@ -69,7 +69,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) { @@ -80,7 +80,7 @@ export class VolunteersService { } /** - * Fetches a Volunteer by ID, with their assigned Foster Coordinator. + * Fetches a Volunteer by ID, with their assigned Foster Coordinator and pets. * * Returns the Volunteer so callers can reuse it instead of fetching again. * @@ -91,7 +91,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) { @@ -113,10 +113,11 @@ 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. - * @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, @@ -124,6 +125,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) { @@ -144,6 +149,8 @@ export class VolunteersService { const saved = await this.repo.save({ ...profile, email, + childrenAges, + pets, status: VolunteerStatus.PENDING, mostRecentWaiverSigned: true, cognitoSub, @@ -397,19 +404,23 @@ export class VolunteersService { /** * Updates a foster volunteer by ID. * Only the fields included in the DTO are changed; all other fields keep their current values. + * Pets, when included, replace the whole list; pets left out are deleted. + * Setting hasChildren to false without sending childrenAges clears the saved ages. * The homebase is changed through changeHomebase instead, since changing it * also reassigns coordinators and emails them. * @param id - ID of the volunteer to update * @param dto - The fields to update * @returns The updated volunteer * @throws NotFoundException if no volunteer exists with the given ID + * @throws {BadRequestException} If the saved and updated fields together + * leave childrenAges not matching hasChildren. */ async updateVolunteerById( id: number, dto: UpdateVolunteerDto, ): Promise { const volunteer = await this.findByIdOrFail(id); - Object.assign(volunteer, dto); + this.applyProfileUpdate(volunteer, dto); return this.withoutPrivateFields(await this.repo.save(volunteer)); } @@ -418,22 +429,70 @@ export class VolunteersService { * Volunteer can edit themselves, plus coordinator-only fields * (coordinator notes and completed trainings). * Only the fields included in the DTO are changed; completed trainings - * are replaced as a whole list. + * and pets are replaced as whole lists. Setting hasChildren to false + * without sending childrenAges clears the saved ages. * * @param id - The Volunteer's ID. * @param dto - The fields to update. * @returns The updated Volunteer, including private fields. * @throws {NotFoundException} If no Volunteer with the ID exists. + * @throws {BadRequestException} If the saved and updated fields together + * leave childrenAges not matching hasChildren. */ async coordinatorUpdateVolunteerById( id: number, dto: CoordinatorUpdateVolunteerDto, ): Promise { const volunteer = await this.coordinatorFindByIdOrFail(id); - Object.assign(volunteer, dto); + this.applyProfileUpdate(volunteer, dto); return this.repo.save(volunteer); } + /** + * Copies an update onto a loaded Volunteer, after checking that the saved + * and updated fields together still satisfy the children rule. + * + * @param volunteer - The loaded Volunteer to update. + * @param dto - The fields to copy onto the Volunteer. + * @throws {BadRequestException} If childrenAges doesn't match hasChildren. + */ + private applyProfileUpdate( + volunteer: VolunteerWithoutPrivateFields, + dto: UpdateVolunteerDto, + ): void { + const hasChildren = dto.hasChildren ?? volunteer.hasChildren; + const childrenAges = + dto.childrenAges ?? + (dto.hasChildren === false ? [] : volunteer.childrenAges); + this.checkChildrenConsistent(hasChildren, childrenAges); + Object.assign(volunteer, dto, { childrenAges }); + } + + /** + * Ensures childrenAges lists at least one age when hasChildren is true, + * and none when it is false. Mirrors CHK_foster_volunteers_children_ages, + * so a bad request is a 400 instead of a database error. + * + * @param hasChildren - Whether the Volunteer has children. + * @param childrenAges - The children's ages. + * @throws {BadRequestException} If childrenAges doesn't match hasChildren. + */ + private checkChildrenConsistent( + hasChildren: boolean, + childrenAges: number[], + ): void { + if (hasChildren && childrenAges.length === 0) { + throw new BadRequestException( + 'childrenAges must not be empty when hasChildren is true', + ); + } + if (!hasChildren && childrenAges.length > 0) { + throw new BadRequestException( + 'childrenAges must be empty when hasChildren is false', + ); + } + } + /** * Updates an active Volunteer's foster type preferences. * Validates all changes before mutating the Volunteer or saving. @@ -567,7 +626,7 @@ export class VolunteersService { } /** - * Gets all foster volunteers. + * Gets all foster volunteers, with their assigned coordinators and pets. * Each volunteer includes only their matches with status ACTIVE, or an empty array if there are no volunteers. * @returns A list of all volunteers */ @@ -575,6 +634,7 @@ export class VolunteersService { const volunteers = await this.repo .createQueryBuilder('volunteer') .leftJoinAndSelect('volunteer.assignedCoordinators', 'coordinator') + .leftJoinAndSelect('volunteer.pets', 'pet') .leftJoinAndSelect( 'volunteer.matches', 'match',