diff --git a/apps/backend/src/app.module.ts b/apps/backend/src/app.module.ts index 9219e513a..6d59fb0ba 100644 --- a/apps/backend/src/app.module.ts +++ b/apps/backend/src/app.module.ts @@ -9,6 +9,7 @@ import { CoordinatorsModule } from './coordinators/coordinators.module'; import { VolunteersModule } from './volunteers/volunteers.module'; import { OwnersModule } from './owners/owners.module'; import { AnimalsModule } from './animals/animals.module'; +import { StaffModule } from './staff/staff.module'; import { AuthModule } from './auth/auth.module'; @Module({ @@ -29,6 +30,7 @@ import { AuthModule } from './auth/auth.module'; VolunteersModule, OwnersModule, AnimalsModule, + StaffModule, AuthModule, ], }) diff --git a/apps/backend/src/auth/auth.controller.spec.ts b/apps/backend/src/auth/auth.controller.spec.ts index 2da90565d..832504096 100644 --- a/apps/backend/src/auth/auth.controller.spec.ts +++ b/apps/backend/src/auth/auth.controller.spec.ts @@ -10,9 +10,11 @@ import { AuthController } from './auth.controller'; import { CognitoService } from '../aws/cognito/cognito.service'; import { AccessTokenPayload, CognitoRole } from '../aws/cognito/cognito.types'; import { VolunteersService } from '../volunteers/volunteers.service'; +import { StaffService } from '../staff/staff.service'; import { CoordinatorsService } from '../coordinators/coordinators.service'; import { OwnersService } from '../owners/owners.service'; import { FosterVolunteer } from '../volunteers/volunteers.entity'; +import { FosterStaff } from '../staff/staff.entity'; import { FosterCoordinator } from '../coordinators/coordinators.entity'; import { Owner } from '../owners/owners.entity'; @@ -20,12 +22,14 @@ describe('AuthController', () => { let controller: AuthController; let cognitoService: { getUser: jest.Mock }; let volunteersService: { findByCognitoSubOrFail: jest.Mock }; + let staffService: { findByCognitoSubOrFail: jest.Mock }; let coordinatorsService: { findByCognitoSubOrFail: jest.Mock }; let ownersService: { findByCognitoSubOrFail: jest.Mock }; let warnSpy: jest.SpyInstance; const request = {} as Request; const volunteer = { volunteerId: 1, firstName: 'Jane' } as FosterVolunteer; + const staffMember = { staffId: 4, firstName: 'Sam' } as FosterStaff; const coordinator = { coordinatorId: 2, firstName: 'Cora', @@ -47,6 +51,7 @@ describe('AuthController', () => { beforeEach(async () => { cognitoService = { getUser: jest.fn() }; volunteersService = { findByCognitoSubOrFail: jest.fn() }; + staffService = { findByCognitoSubOrFail: jest.fn() }; coordinatorsService = { findByCognitoSubOrFail: jest.fn() }; ownersService = { findByCognitoSubOrFail: jest.fn() }; @@ -55,6 +60,7 @@ describe('AuthController', () => { providers: [ { provide: CognitoService, useValue: cognitoService }, { provide: VolunteersService, useValue: volunteersService }, + { provide: StaffService, useValue: staffService }, { provide: CoordinatorsService, useValue: coordinatorsService }, { provide: OwnersService, useValue: ownersService }, ], @@ -88,6 +94,23 @@ describe('AuthController', () => { expect(warnSpy).not.toHaveBeenCalled(); }); + it('returns the staff member for a Staff user', async () => { + cognitoService.getUser.mockReturnValue( + payloadWithGroups([CognitoRole.Staff]), + ); + staffService.findByCognitoSubOrFail.mockResolvedValue(staffMember); + + const result = await controller.getMe(request); + + expect(staffService.findByCognitoSubOrFail).toHaveBeenCalledWith( + 'cognito-sub-123', + ); + expect(result).toEqual({ + role: CognitoRole.Staff, + user: staffMember, + }); + }); + it('returns the coordinator for a FosterCoordinator', async () => { cognitoService.getUser.mockReturnValue( payloadWithGroups([CognitoRole.FosterCoordinator]), @@ -124,6 +147,7 @@ describe('AuthController', () => { payloadWithGroups([ CognitoRole.Owner, CognitoRole.FosterCoordinator, + CognitoRole.Staff, CognitoRole.FosterVolunteer, ]), ); @@ -132,10 +156,11 @@ describe('AuthController', () => { const result = await controller.getMe(request); expect(result.role).toBe(CognitoRole.FosterVolunteer); + expect(staffService.findByCognitoSubOrFail).not.toHaveBeenCalled(); expect(coordinatorsService.findByCognitoSubOrFail).not.toHaveBeenCalled(); expect(ownersService.findByCognitoSubOrFail).not.toHaveBeenCalled(); expect(warnSpy).toHaveBeenCalledWith( - 'User cognito-sub-123 is in multiple groups (FosterVolunteer, FosterCoordinator, Owner); using the least privileged role', + 'User cognito-sub-123 is in multiple groups (FosterVolunteer, Staff, FosterCoordinator, Owner); using the least privileged role', ); }); @@ -146,6 +171,7 @@ describe('AuthController', () => { new UnauthorizedException('No user attached to the request'), ); expect(volunteersService.findByCognitoSubOrFail).not.toHaveBeenCalled(); + expect(staffService.findByCognitoSubOrFail).not.toHaveBeenCalled(); expect(coordinatorsService.findByCognitoSubOrFail).not.toHaveBeenCalled(); expect(ownersService.findByCognitoSubOrFail).not.toHaveBeenCalled(); }); diff --git a/apps/backend/src/auth/auth.controller.ts b/apps/backend/src/auth/auth.controller.ts index e6c792c2b..070fa6a84 100644 --- a/apps/backend/src/auth/auth.controller.ts +++ b/apps/backend/src/auth/auth.controller.ts @@ -12,6 +12,7 @@ import { Request } from 'express'; import { CognitoService } from '../aws/cognito/cognito.service'; import { CognitoRole } from '../aws/cognito/cognito.types'; import { VolunteersService } from '../volunteers/volunteers.service'; +import { StaffService } from '../staff/staff.service'; import { CoordinatorsService } from '../coordinators/coordinators.service'; import { OwnersService } from '../owners/owners.service'; import { AuthenticatedUser } from './auth.types'; @@ -24,6 +25,7 @@ export class AuthController { constructor( private readonly cognitoService: CognitoService, private readonly volunteersService: VolunteersService, + private readonly staffService: StaffService, private readonly coordinatorsService: CoordinatorsService, private readonly ownersService: OwnersService, ) {} @@ -91,6 +93,11 @@ export class AuthController { payload.sub, ), }; + case CognitoRole.Staff: + return { + role: CognitoRole.Staff, + user: await this.staffService.findByCognitoSubOrFail(payload.sub), + }; case CognitoRole.FosterCoordinator: return { role: CognitoRole.FosterCoordinator, diff --git a/apps/backend/src/auth/auth.module.ts b/apps/backend/src/auth/auth.module.ts index 485e56c43..c204e9863 100644 --- a/apps/backend/src/auth/auth.module.ts +++ b/apps/backend/src/auth/auth.module.ts @@ -2,11 +2,18 @@ import { Module } from '@nestjs/common'; import { AuthController } from './auth.controller'; import { CognitoModule } from '../aws/cognito/cognito.module'; import { VolunteersModule } from '../volunteers/volunteers.module'; +import { StaffModule } from '../staff/staff.module'; import { CoordinatorsModule } from '../coordinators/coordinators.module'; import { OwnersModule } from '../owners/owners.module'; @Module({ - imports: [CognitoModule, VolunteersModule, CoordinatorsModule, OwnersModule], + imports: [ + CognitoModule, + VolunteersModule, + StaffModule, + CoordinatorsModule, + OwnersModule, + ], controllers: [AuthController], }) export class AuthModule {} diff --git a/apps/backend/src/auth/auth.types.ts b/apps/backend/src/auth/auth.types.ts index 346a456a7..e702a288f 100644 --- a/apps/backend/src/auth/auth.types.ts +++ b/apps/backend/src/auth/auth.types.ts @@ -1,6 +1,7 @@ import { CognitoRole } from '../aws/cognito/cognito.types'; import { FosterCoordinator } from '../coordinators/coordinators.entity'; import { Owner } from '../owners/owners.entity'; +import { FosterStaff } from '../staff/staff.entity'; import { VolunteerWithoutPrivateFields } from '../volunteers/dtos/volunteer-without-private-fields.dto'; /** @@ -9,5 +10,6 @@ import { VolunteerWithoutPrivateFields } from '../volunteers/dtos/volunteer-with */ export type AuthenticatedUser = | { role: CognitoRole.FosterVolunteer; user: VolunteerWithoutPrivateFields } + | { role: CognitoRole.Staff; user: FosterStaff } | { role: CognitoRole.FosterCoordinator; user: FosterCoordinator } | { role: CognitoRole.Owner; user: Owner }; diff --git a/apps/backend/src/aws/cognito/cognito.types.ts b/apps/backend/src/aws/cognito/cognito.types.ts index 4ef827b31..20913ae06 100644 --- a/apps/backend/src/aws/cognito/cognito.types.ts +++ b/apps/backend/src/aws/cognito/cognito.types.ts @@ -1,6 +1,7 @@ // Cognito user pool group names that map to application roles. export enum CognitoRole { FosterVolunteer = 'FosterVolunteer', + Staff = 'Staff', FosterCoordinator = 'FosterCoordinator', Owner = 'Owner', } diff --git a/apps/backend/src/config/migrations.ts b/apps/backend/src/config/migrations.ts index af863eb36..3d59dd535 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 { AddStaffAndUpdateMatches1795372304908 } from '../migrations/1795372304908-AddStaffAndUpdateMatches'; import { AddPetsAndHouseholdDetails1794408338094 } from '../migrations/1794408338094-AddPetsAndHouseholdDetails'; import { AddMatchAdditionalComments1794784721012 } from '../migrations/1794784721012-AddMatchAdditionalComments'; @@ -32,6 +33,7 @@ const schemaMigrations = [ AddFosterTypePreferences1793600000000, AddPetsAndHouseholdDetails1794408338094, AddMatchAdditionalComments1794784721012, + AddStaffAndUpdateMatches1795372304908, ]; export default schemaMigrations; diff --git a/apps/backend/src/matches/dtos/create-match.dto.ts b/apps/backend/src/matches/dtos/create-match.dto.ts index 236d1262b..d902080ae 100644 --- a/apps/backend/src/matches/dtos/create-match.dto.ts +++ b/apps/backend/src/matches/dtos/create-match.dto.ts @@ -1,10 +1,18 @@ import { IsInt, IsPositive, MaxLength, ValidateIf } from 'class-validator'; import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.decorator'; +import { ExactlyOne } from './validators/exactly-one.validator'; +@ExactlyOne(['volunteerId', 'staffId']) export class CreateMatchDto { + @ValidateIf((o) => o.volunteerId !== undefined) @IsInt() @IsPositive() - volunteerId!: number; + volunteerId?: number; + + @ValidateIf((o) => o.staffId !== undefined) + @IsInt() + @IsPositive() + staffId?: number; @IsNonEmptyString() @MaxLength(255) diff --git a/apps/backend/src/matches/dtos/validators/exactly-one.validator.spec.ts b/apps/backend/src/matches/dtos/validators/exactly-one.validator.spec.ts new file mode 100644 index 000000000..66ecc8cc9 --- /dev/null +++ b/apps/backend/src/matches/dtos/validators/exactly-one.validator.spec.ts @@ -0,0 +1,48 @@ +import { validate } from 'class-validator'; +import { ExactlyOne } from './exactly-one.validator'; + +@ExactlyOne(['a', 'b']) +class TestDto { + a?: number; + b?: number; +} + +describe('ExactlyOne', () => { + it('passes when only the first field is provided', async () => { + const dto = Object.assign(new TestDto(), { a: 1 }); + + expect(await validate(dto)).toHaveLength(0); + }); + + it('passes when only the second field is provided', async () => { + const dto = Object.assign(new TestDto(), { b: 2 }); + + expect(await validate(dto)).toHaveLength(0); + }); + + it('fails when both fields are provided', async () => { + const dto = Object.assign(new TestDto(), { a: 1, b: 2 }); + const errors = await validate(dto); + + expect(errors).toHaveLength(1); + expect(errors[0].constraints).toEqual({ + exactlyOne: 'Exactly one of a, b must be provided', + }); + }); + + it('fails when neither field is provided', async () => { + const errors = await validate(new TestDto()); + + expect(errors).toHaveLength(1); + expect(errors[0].constraints).toEqual({ + exactlyOne: 'Exactly one of a, b must be provided', + }); + }); + + it('fails when both fields are explicitly undefined', async () => { + const dto = Object.assign(new TestDto(), { a: undefined, b: undefined }); + const errors = await validate(dto); + + expect(errors).toHaveLength(1); + }); +}); diff --git a/apps/backend/src/matches/dtos/validators/exactly-one.validator.ts b/apps/backend/src/matches/dtos/validators/exactly-one.validator.ts new file mode 100644 index 000000000..2384f21b3 --- /dev/null +++ b/apps/backend/src/matches/dtos/validators/exactly-one.validator.ts @@ -0,0 +1,29 @@ +import { registerDecorator, ValidationArguments } from 'class-validator'; + +/** + * Class decorator that rejects the DTO unless exactly one of the given fields + * is provided (i.e. not undefined). + * + * It only checks presence. The decorators on each field still validate the + * values themselves. + */ +export function ExactlyOne( + fields: (keyof T & string)[], +): ClassDecorator { + return (target) => { + registerDecorator({ + name: 'exactlyOne', + target, + propertyName: 'exactlyOne', + validator: { + validate(_: unknown, args: ValidationArguments): boolean { + const dto = args.object as Record; + return fields.filter((f) => dto[f] !== undefined).length === 1; + }, + defaultMessage(): string { + return `Exactly one of ${fields.join(', ')} must be provided`; + }, + }, + }); + }; +} diff --git a/apps/backend/src/matches/matches.entity.ts b/apps/backend/src/matches/matches.entity.ts index 096c7e78e..89409f461 100644 --- a/apps/backend/src/matches/matches.entity.ts +++ b/apps/backend/src/matches/matches.entity.ts @@ -6,6 +6,7 @@ import { JoinColumn, } from 'typeorm'; import { FosterVolunteer } from '../volunteers/volunteers.entity'; +import { FosterStaff } from '../staff/staff.entity'; import { Animal } from '../animals/animals.entity'; import { MatchStatus } from './matches.types'; @@ -15,13 +16,22 @@ export class Match { matchId!: number; @ManyToOne(() => FosterVolunteer, (volunteer) => volunteer.matches, { - nullable: false, + nullable: true, }) @JoinColumn({ name: 'volunteer_id' }) - volunteer!: FosterVolunteer; + volunteer!: FosterVolunteer | null; - @Column({ name: 'volunteer_id' }) - volunteerId!: number; + @Column({ name: 'volunteer_id', nullable: true }) + volunteerId!: number | null; + + @ManyToOne(() => FosterStaff, (staff) => staff.matches, { + nullable: true, + }) + @JoinColumn({ name: 'staff_id' }) + staff!: FosterStaff | null; + + @Column({ name: 'staff_id', nullable: true }) + staffId!: number | null; @ManyToOne(() => Animal, { nullable: false }) @JoinColumn({ diff --git a/apps/backend/src/matches/matches.module.ts b/apps/backend/src/matches/matches.module.ts index b6824c708..d3518cd96 100644 --- a/apps/backend/src/matches/matches.module.ts +++ b/apps/backend/src/matches/matches.module.ts @@ -6,6 +6,7 @@ import { MatchesService } from './matches.service'; import { VolunteersModule } from '../volunteers/volunteers.module'; import { AWSSESModule } from '../aws/ses/email.module'; import { AnimalsModule } from '../animals/animals.module'; +import { StaffModule } from '../staff/staff.module'; @Module({ imports: [ @@ -13,6 +14,7 @@ import { AnimalsModule } from '../animals/animals.module'; forwardRef(() => VolunteersModule), AWSSESModule, AnimalsModule, + StaffModule, ], controllers: [MatchesController], providers: [MatchesService], diff --git a/apps/backend/src/matches/matches.service.spec.ts b/apps/backend/src/matches/matches.service.spec.ts index 6c3427e2a..020ff9637 100644 --- a/apps/backend/src/matches/matches.service.spec.ts +++ b/apps/backend/src/matches/matches.service.spec.ts @@ -13,6 +13,7 @@ import { FosterVolunteer } from '../volunteers/volunteers.entity'; import { VolunteerStatus } from '../volunteers/volunteers.types'; import { FosterCoordinator } from '../coordinators/coordinators.entity'; import { VolunteersService } from '../volunteers/volunteers.service'; +import { StaffService } from '../staff/staff.service'; import { AnimalsService } from '../animals/animals.service'; import { EmailsService } from '../aws/ses/email.service'; import { SendEmailDTO } from '../aws/ses/sendEmail.dto'; @@ -71,6 +72,7 @@ describe('MatchesService', () => { getRepository: jest.Mock; }; let volunteersService: { findActiveOrFail: jest.Mock }; + let staffService: { findActiveOrFail: jest.Mock }; let animalsService: { findByChameleonIdOrFail: jest.Mock }; let emailsService: { sendEmail: jest.Mock }; @@ -124,6 +126,7 @@ describe('MatchesService', () => { }; volunteersService = { findActiveOrFail: jest.fn() }; + staffService = { findActiveOrFail: jest.fn() }; animalsService = { findByChameleonIdOrFail: jest.fn() }; emailsService = { sendEmail: jest.fn() }; @@ -132,6 +135,7 @@ describe('MatchesService', () => { MatchesService, { provide: getRepositoryToken(Match), useValue: matchRepo }, { provide: VolunteersService, useValue: volunteersService }, + { provide: StaffService, useValue: staffService }, { provide: AnimalsService, useValue: animalsService }, { provide: EmailsService, useValue: emailsService }, ], @@ -162,6 +166,7 @@ describe('MatchesService', () => { beforeEach(() => { process.env.AWS_SES_SENDER_EMAIL = 'sender@example.com'; + matchRepo.findOneBy.mockResolvedValue(null); }); afterEach(() => { @@ -193,6 +198,7 @@ describe('MatchesService', () => { ); expect(matchRepo.create).toHaveBeenCalledWith({ volunteerId: 1, + staffId: null, chameleonAnimalId: 'A42', status: MatchStatus.PENDING, additionalComments: null, @@ -256,6 +262,27 @@ describe('MatchesService', () => { expect(matchRepo.save).toHaveBeenCalled(); }); + it('throws ConflictException when a staff member already has a PENDING or ACTIVE match for the animal', async () => { + staffService.findActiveOrFail.mockResolvedValue({ staffId: 2 }); + matchRepo.findOneBy.mockResolvedValue({ + matchId: 5, + staffId: 2, + chameleonAnimalId: 'A42', + status: MatchStatus.ACTIVE, + }); + + await expect( + service.create({ staffId: 2, chameleonAnimalId: 'A42' }), + ).rejects.toThrow(ConflictException); + + expect(matchRepo.findOneBy).toHaveBeenCalledWith({ + staffId: 2, + chameleonAnimalId: 'A42', + status: In([MatchStatus.PENDING, MatchStatus.ACTIVE]), + }); + expect(matchRepo.save).not.toHaveBeenCalled(); + }); + it('saves additional comments when provided', async () => { volunteersService.findActiveOrFail.mockResolvedValue( volunteerWithCoordinator, @@ -454,15 +481,14 @@ describe('MatchesService', () => { service.create({ volunteerId: 999, chameleonAnimalId: 'A42' }), ).rejects.toThrow(NotFoundException); - expect(animalsService.findByChameleonIdOrFail).not.toHaveBeenCalled(); + expect(animalsService.findByChameleonIdOrFail).toHaveBeenCalledWith( + 'A42', + ); expect(matchRepo.save).not.toHaveBeenCalled(); expect(emailsService.sendEmail).not.toHaveBeenCalled(); }); - it('throws when the animal does not exist, after checking the volunteer', async () => { - volunteersService.findActiveOrFail.mockResolvedValue( - volunteerWithCoordinator, - ); + it('throws when the animal does not exist, before checking the volunteer', async () => { animalsService.findByChameleonIdOrFail.mockRejectedValue( new NotFoundException('Animal with Chameleon ID A999 not found'), ); @@ -473,10 +499,10 @@ describe('MatchesService', () => { new NotFoundException('Animal with Chameleon ID A999 not found'), ); - expect(volunteersService.findActiveOrFail).toHaveBeenCalledWith(1); expect(animalsService.findByChameleonIdOrFail).toHaveBeenCalledWith( 'A999', ); + expect(volunteersService.findActiveOrFail).not.toHaveBeenCalled(); expect(matchRepo.save).not.toHaveBeenCalled(); expect(emailsService.sendEmail).not.toHaveBeenCalled(); }); @@ -619,7 +645,7 @@ describe('MatchesService', () => { _value: 1, }), }, - relations: ['volunteer'], + relations: ['volunteer', 'staff'], }); }); diff --git a/apps/backend/src/matches/matches.service.ts b/apps/backend/src/matches/matches.service.ts index b22f1fe85..2c75912f2 100644 --- a/apps/backend/src/matches/matches.service.ts +++ b/apps/backend/src/matches/matches.service.ts @@ -13,6 +13,7 @@ import { Match } from './matches.entity'; import { MatchStatus } from './matches.types'; import { CreateMatchDto } from './dtos/create-match.dto'; import { VolunteersService } from '../volunteers/volunteers.service'; +import { StaffService } from '../staff/staff.service'; import { AnimalsService } from '../animals/animals.service'; import { EmailsService } from '../aws/ses/email.service'; import { matchCreatedEmail } from './emails/matchCreated'; @@ -28,54 +29,99 @@ export class MatchesService { private repo: Repository, @Inject(forwardRef(() => VolunteersService)) private volunteersService: VolunteersService, + private staffService: StaffService, private animalsService: AnimalsService, private emailsService: EmailsService, ) {} /** - * Creates a PENDING match between a volunteer and a Chameleon animal, then - * notifies the volunteer's assigned foster coordinators by email. + * Creates a PENDING match between a volunteer or staff member and a Chameleon + * animal, then notifies the applicant's assigned foster coordinators by email. * * The email is best-effort: the match is already committed when it is sent, - * so a send failure is logged rather than surfaced to the caller. Volunteers + * so a send failure is logged rather than surfaced to the caller. Applicants * with no assigned coordinators still get a match; no email goes out. * - * @param dto the volunteer and Chameleon animal to match + * @param dto the volunteer/staff and Chameleon animal to match * @returns the created match * @throws NotFoundException if the volunteer or animal does not exist * @throws BadRequestException if the volunteer is not active * @throws ConflictException if the volunteer already has a PENDING or ACTIVE match for the animal */ async create(dto: CreateMatchDto): Promise { - const volunteer = await this.volunteersService.findActiveOrFail( - dto.volunteerId, - ); await this.animalsService.findByChameleonIdOrFail(dto.chameleonAnimalId); - const existingMatch = await this.repo.findOneBy({ - volunteerId: dto.volunteerId, - chameleonAnimalId: dto.chameleonAnimalId, - status: In([MatchStatus.PENDING, MatchStatus.ACTIVE]), - }); - if (existingMatch) { - throw new ConflictException( - `Volunteer ${dto.volunteerId} already has a ${existingMatch.status} match for animal ${dto.chameleonAnimalId}`, + if (dto.volunteerId) { + const volunteer = await this.volunteersService.findActiveOrFail( + dto.volunteerId, ); - } - const match = await this.repo.save( - this.repo.create({ + const existing = await this.repo.findOneBy({ volunteerId: dto.volunteerId, chameleonAnimalId: dto.chameleonAnimalId, - status: MatchStatus.PENDING, - additionalComments: dto.additionalComments ?? null, - deniedReason: null, - }), - ); + status: In([MatchStatus.PENDING, MatchStatus.ACTIVE]), + }); + + if (existing) { + throw new ConflictException( + `Volunteer ${ + dto.volunteerId + } already has a ${existing.status.toLowerCase()} match for animal ${ + dto.chameleonAnimalId + }`, + ); + } + + const match = await this.repo.save( + this.repo.create({ + volunteerId: dto.volunteerId, + staffId: null, + chameleonAnimalId: dto.chameleonAnimalId, + status: MatchStatus.PENDING, + additionalComments: dto.additionalComments ?? null, + deniedReason: null, + }), + ); + + await this.notifyCoordinators(match, volunteer); + + return match; + } + + if (dto.staffId) { + await this.staffService.findActiveOrFail(dto.staffId); + + const existing = await this.repo.findOneBy({ + staffId: dto.staffId, + chameleonAnimalId: dto.chameleonAnimalId, + status: In([MatchStatus.PENDING, MatchStatus.ACTIVE]), + }); + + if (existing) { + throw new ConflictException( + `Staff member ${ + dto.staffId + } already has a ${existing.status.toLowerCase()} match for animal ${ + dto.chameleonAnimalId + }`, + ); + } - await this.notifyCoordinators(match, volunteer); + return this.repo.save( + this.repo.create({ + volunteerId: null, + staffId: dto.staffId, + chameleonAnimalId: dto.chameleonAnimalId, + status: MatchStatus.PENDING, + additionalComments: dto.additionalComments ?? null, + deniedReason: null, + }), + ); + } - return match; + throw new BadRequestException( + 'Exactly one of volunteerId or staffId must be provided', + ); } /** @@ -164,6 +210,20 @@ export class MatchesService { return this.repo.find({ where: { volunteerId } }); } + /** + * Fetches all Matches for a Staff member. + * + * Returns Matches of every status, not just active ones. + * Does not check that the Staff member exists, so an unknown ID yields an + * empty array; callers that need a 404 should check the Staff member first. + * + * @param staffId - The Staff member's ID. + * @returns The Staff member's Matches, or an empty array if they have none. + */ + findByStaffId(staffId: number): Promise { + return this.repo.find({ where: { staffId } }); + } + /** * Fetches all PENDING Matches for a Chameleon animal, each with its Volunteer * loaded, oldest application first. @@ -215,7 +275,7 @@ export class MatchesService { status: MatchStatus.PENDING, matchId: Not(id), }, - relations: ['volunteer'], + relations: ['volunteer', 'staff'], }); match.status = MatchStatus.ACTIVE; @@ -233,7 +293,11 @@ export class MatchesService { const applicantEmails = [ ...new Set( - otherMatches.map((otherMatch) => otherMatch.volunteer.email), + otherMatches.map((otherMatch) => + otherMatch.volunteer + ? otherMatch.volunteer.email + : otherMatch.staff!.email, + ), ), ]; diff --git a/apps/backend/src/migrations/1795372304908-AddStaffAndUpdateMatches.ts b/apps/backend/src/migrations/1795372304908-AddStaffAndUpdateMatches.ts new file mode 100644 index 000000000..70b4c85b1 --- /dev/null +++ b/apps/backend/src/migrations/1795372304908-AddStaffAndUpdateMatches.ts @@ -0,0 +1,72 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddStaffAndUpdateMatches1795372304908 + implements MigrationInterface +{ + public async up(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + CREATE TYPE "staff_type_enum" AS ENUM ('Hospital', 'Shelter') + `); + + await queryRunner.query(` + CREATE TABLE "foster_staff" ( + "staff_id" SERIAL PRIMARY KEY, + "first_name" varchar(255) NOT NULL, + "last_name" varchar(255) NOT NULL, + "phone" varchar(20) NOT NULL, + "secondary_phone" varchar(20), + "email" varchar(255) NOT NULL, + "address" varchar(255) NOT NULL, + "city" varchar(255) NOT NULL, + "zipcode" varchar(10) NOT NULL, + "homebase" "homebase_enum" NOT NULL, + "notes" text, + "most_recent_waiver_signed" boolean NOT NULL, + "staff_type" "staff_type_enum" NOT NULL, + "active" boolean NOT NULL, + "cognito_sub" varchar(255) NOT NULL DEFAULT '', + CONSTRAINT "UQ_foster_staff_email" UNIQUE ("email") + ) + `); + + await queryRunner.query(` + CREATE TABLE "staff_coordinator_assignments" ( + "staff_id" int NOT NULL, + "coordinator_id" int NOT NULL, + PRIMARY KEY ("staff_id", "coordinator_id"), + CONSTRAINT "fk_staff_coordinator_staff" FOREIGN KEY ("staff_id") + REFERENCES "foster_staff" ("staff_id") ON DELETE CASCADE, + CONSTRAINT "fk_staff_coordinator_coordinator" FOREIGN KEY ("coordinator_id") + REFERENCES "foster_coordinators" ("coordinator_id") ON DELETE RESTRICT + ) + `); + + await queryRunner.query(` + ALTER TABLE "matches" + ALTER COLUMN "volunteer_id" DROP NOT NULL, + ADD COLUMN "staff_id" int, + ADD CONSTRAINT "fk_matches_staff" FOREIGN KEY ("staff_id") + REFERENCES "foster_staff" ("staff_id"), + ADD CONSTRAINT "chk_matches_one_applicant" CHECK ( + ("volunteer_id" IS NOT NULL AND "staff_id" IS NULL) + OR ("volunteer_id" IS NULL AND "staff_id" IS NOT NULL) + ) + `); + } + + public async down(queryRunner: QueryRunner): Promise { + await queryRunner.query(` + ALTER TABLE "matches" + DROP CONSTRAINT "chk_matches_one_applicant", + DROP CONSTRAINT "fk_matches_staff", + DROP COLUMN "staff_id", + ALTER COLUMN "volunteer_id" SET NOT NULL + `); + + await queryRunner.query(`DROP TABLE "staff_coordinator_assignments"`); + + await queryRunner.query(`DROP TABLE "foster_staff"`); + + await queryRunner.query(`DROP TYPE "staff_type_enum"`); + } +} diff --git a/apps/backend/src/staff/dtos/confirm-staff.dto.ts b/apps/backend/src/staff/dtos/confirm-staff.dto.ts new file mode 100644 index 000000000..ae4ceb645 --- /dev/null +++ b/apps/backend/src/staff/dtos/confirm-staff.dto.ts @@ -0,0 +1,19 @@ +import { Transform } from 'class-transformer'; +import { IsEmail, Matches, MaxLength } from 'class-validator'; + +export class ConfirmStaffDto { + @Transform(({ value }) => + typeof value === 'string' ? value.trim().toLowerCase() : value, + ) + @IsEmail() + @MaxLength(255) + @Matches(/^[^\s@]+@mspca\.org$/, { + message: 'Email must end in @mspca.org', + }) + email!: string; + + @Matches(/^\d{6}$/, { + message: 'Verification code must be 6 digits', + }) + code!: string; +} diff --git a/apps/backend/src/staff/dtos/create-staff.dto.ts b/apps/backend/src/staff/dtos/create-staff.dto.ts new file mode 100644 index 000000000..bc805df11 --- /dev/null +++ b/apps/backend/src/staff/dtos/create-staff.dto.ts @@ -0,0 +1,80 @@ +import { + IsEmail, + IsEnum, + IsNotEmpty, + IsPhoneNumber, + IsString, + IsStrongPassword, + Matches, + MaxLength, + ValidateIf, +} from 'class-validator'; +import { Transform } from 'class-transformer'; +import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.decorator'; +import { Homebase } from '../../types'; +import { StaffType } from '../staff.types'; + +export class CreateStaffDto { + @IsNonEmptyString() + @MaxLength(255) + firstName!: string; + + @IsNonEmptyString() + @MaxLength(255) + lastName!: string; + + @IsNonEmptyString() + @IsPhoneNumber('US') + @MaxLength(20) + phone!: string; + + @ValidateIf((_, value) => value !== undefined && value !== null) + @IsNonEmptyString() + @IsPhoneNumber('US') + @MaxLength(20) + secondaryPhone?: string | null; + + @Transform(({ value }) => + typeof value === 'string' ? value.trim().toLowerCase() : value, + ) + @IsEmail() + @MaxLength(255) + @Matches(/^[^\s@]+@mspca\.org$/, { + message: 'Email must end in @mspca.org', + }) + email!: string; + + @IsString() + @IsNotEmpty() + @IsStrongPassword({ + minLength: 8, + minLowercase: 1, + minUppercase: 1, + minNumbers: 1, + minSymbols: 1, + }) + @MaxLength(256) + password!: string; + + @IsNonEmptyString() + @MaxLength(255) + address!: string; + + @IsNonEmptyString() + @MaxLength(255) + city!: string; + + @IsNonEmptyString() + @MaxLength(10) + zipcode!: string; + + @IsEnum(Homebase) + homebase!: Homebase; + + @ValidateIf((_, value) => value !== undefined && value !== null) + @IsNonEmptyString() + notes?: string | null; + + @IsEnum(StaffType) + staffType!: StaffType; +} diff --git a/apps/backend/src/staff/staff.controller.spec.ts b/apps/backend/src/staff/staff.controller.spec.ts new file mode 100644 index 000000000..f1e9a1163 --- /dev/null +++ b/apps/backend/src/staff/staff.controller.spec.ts @@ -0,0 +1,166 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { NotFoundException } from '@nestjs/common'; +import { StaffController } from './staff.controller'; +import { StaffService } from './staff.service'; +import { FosterStaff } from './staff.entity'; +import { Homebase } from '../types'; +import { StaffType } from './staff.types'; +import { CreateStaffDto } from './dtos/create-staff.dto'; +import { ConfirmStaffDto } from './dtos/confirm-staff.dto'; + +describe('StaffController', () => { + let controller: StaffController; + let service: { + create: jest.Mock; + confirm: jest.Mock; + deactivate: jest.Mock; + activate: jest.Mock; + }; + + const dto = { + firstName: 'Jane', + lastName: 'Doe', + phone: '+16175551234', + secondaryPhone: null, + email: 'jane.doe@mspca.org', + password: 'Str0ng!Password', + address: '123 Main St', + city: 'Boston', + zipcode: '02101', + homebase: Homebase.BOSTON, + notes: null, + staffType: StaffType.SHELTER, + } as CreateStaffDto; + + const confirmDto = { + email: 'jane.doe@mspca.org', + code: '123456', + } as ConfirmStaffDto; + + beforeEach(async () => { + service = { + create: jest.fn(), + confirm: jest.fn(), + deactivate: jest.fn(), + activate: jest.fn(), + }; + + const module: TestingModule = await Test.createTestingModule({ + controllers: [StaffController], + providers: [{ provide: StaffService, useValue: service }], + }).compile(); + + controller = module.get(StaffController); + }); + + it('should be defined', () => { + expect(controller).toBeDefined(); + }); + + describe('create', () => { + it('delegates creation to the service', async () => { + const profile = { + firstName: dto.firstName, + lastName: dto.lastName, + phone: dto.phone, + secondaryPhone: dto.secondaryPhone, + email: dto.email, + address: dto.address, + city: dto.city, + zipcode: dto.zipcode, + homebase: dto.homebase, + notes: dto.notes, + staffType: dto.staffType, + }; + + const created = { + staffId: 1, + ...profile, + active: true, + cognitoSub: 'cognito-sub-123', + assignedCoordinators: [], + } as FosterStaff; + + service.create.mockResolvedValue(created); + + const result = await controller.create(dto); + + expect(service.create).toHaveBeenCalledWith(dto); + expect(result).toBe(created); + }); + + it('propagates service errors', async () => { + const error = new Error('Service failure'); + service.create.mockRejectedValue(error); + + await expect(controller.create(dto)).rejects.toBe(error); + }); + }); + + describe('confirm', () => { + it('delegates confirmation to the service', async () => { + service.confirm.mockResolvedValue(undefined); + + await controller.confirm(confirmDto); + + expect(service.confirm).toHaveBeenCalledWith(confirmDto); + }); + + it('propagates service errors', async () => { + const error = new Error('Invalid code'); + service.confirm.mockRejectedValue(error); + + await expect(controller.confirm(confirmDto)).rejects.toBe(error); + }); + }); + + describe('deactivate', () => { + it('should call service.deactivate with the parsed id', async () => { + const staff = { + staffId: 1, + active: false, + } as FosterStaff; + service.deactivate.mockResolvedValue(staff); + + const result = await controller.deactivate(1); + + expect(service.deactivate).toHaveBeenCalledWith(1); + expect(result).toEqual(staff); + }); + + it('propagates NotFoundException thrown by the service', async () => { + service.deactivate.mockRejectedValue( + new NotFoundException('Staff member with ID 999 not found'), + ); + + await expect(controller.deactivate(999)).rejects.toThrow( + new NotFoundException('Staff member with ID 999 not found'), + ); + }); + }); + + describe('activate', () => { + it('should call service.activate with the parsed id', async () => { + const staff = { + staffId: 1, + active: true, + } as FosterStaff; + service.activate.mockResolvedValue(staff); + + const result = await controller.activate(1); + + expect(service.activate).toHaveBeenCalledWith(1); + expect(result).toEqual(staff); + }); + + it('propagates NotFoundException thrown by the service', async () => { + service.activate.mockRejectedValue( + new NotFoundException('Staff member with ID 999 not found'), + ); + + await expect(controller.activate(999)).rejects.toThrow( + new NotFoundException('Staff member with ID 999 not found'), + ); + }); + }); +}); diff --git a/apps/backend/src/staff/staff.controller.ts b/apps/backend/src/staff/staff.controller.ts new file mode 100644 index 000000000..434910d9a --- /dev/null +++ b/apps/backend/src/staff/staff.controller.ts @@ -0,0 +1,137 @@ +import { + Body, + Controller, + HttpCode, + HttpStatus, + Param, + ParseIntPipe, + Patch, + Post, +} from '@nestjs/common'; +import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger'; +import { StaffService } from './staff.service'; +import { FosterStaff } from './staff.entity'; +import { CreateStaffDto } from './dtos/create-staff.dto'; +import { ConfirmStaffDto } from './dtos/confirm-staff.dto'; +import { Public } from '../aws/cognito/cognito.decorator'; +import { validateId } from '../utils/validation.utils'; + +@ApiTags('Staff') +@Controller('staff') +export class StaffController { + constructor(private staffService: StaffService) {} + + @Public() + @Post() + @ApiOperation({ + summary: 'Create a staff member account', + }) + @ApiResponse({ + status: HttpStatus.CREATED, + description: + 'The staff member was created and a verification code was emailed', + type: FosterStaff, + }) + @ApiResponse({ + status: HttpStatus.BAD_REQUEST, + description: 'Invalid profile fields or password', + }) + @ApiResponse({ + status: HttpStatus.CONFLICT, + description: 'An account with this email already exists', + }) + @ApiResponse({ + status: HttpStatus.INTERNAL_SERVER_ERROR, + description: 'Failed to register or save the staff member', + }) + async create(@Body() dto: CreateStaffDto): Promise { + return this.staffService.create(dto); + } + + @Public() + @Post('/confirm') + @HttpCode(HttpStatus.NO_CONTENT) + @ApiOperation({ + summary: 'Confirm a staff member email', + }) + @ApiResponse({ + status: HttpStatus.NO_CONTENT, + description: + 'The email was confirmed and the staff member was assigned their Cognito role', + }) + @ApiResponse({ + status: HttpStatus.BAD_REQUEST, + description: 'Invalid or expired verification code', + }) + @ApiResponse({ + status: HttpStatus.NOT_FOUND, + description: 'No staff member with this email exists', + }) + @ApiResponse({ + status: HttpStatus.TOO_MANY_REQUESTS, + description: 'Too many verification attempts', + }) + @ApiResponse({ + status: HttpStatus.INTERNAL_SERVER_ERROR, + description: 'Failed to confirm the staff member', + }) + async confirm(@Body() dto: ConfirmStaffDto): Promise { + await this.staffService.confirm(dto); + } + + @Patch('/:id/deactivate') + @ApiOperation({ + summary: 'Deactivate an active staff member', + }) + @ApiParam({ + name: 'id', + type: Number, + description: 'Staff member ID', + }) + @ApiResponse({ + status: HttpStatus.OK, + description: 'The staff member was deactivated', + type: FosterStaff, + }) + @ApiResponse({ + status: HttpStatus.BAD_REQUEST, + description: 'Invalid staff member ID or staff member is already inactive', + }) + @ApiResponse({ + status: HttpStatus.NOT_FOUND, + description: 'Staff member with the given ID does not exist', + }) + async deactivate( + @Param('id', ParseIntPipe) id: number, + ): Promise { + validateId(id, 'Staff member'); + return this.staffService.deactivate(id); + } + + @Patch('/:id/activate') + @ApiOperation({ + summary: 'Activate an inactive staff member', + }) + @ApiParam({ + name: 'id', + type: Number, + description: 'Staff member ID', + }) + @ApiResponse({ + status: HttpStatus.OK, + description: 'The staff member was activated', + type: FosterStaff, + }) + @ApiResponse({ + status: HttpStatus.BAD_REQUEST, + description: 'Invalid staff member ID or staff member is already active', + }) + @ApiResponse({ + status: HttpStatus.NOT_FOUND, + description: 'Staff member with the given ID does not exist', + }) + async activate(@Param('id', ParseIntPipe) id: number): Promise { + validateId(id, 'Staff member'); + return this.staffService.activate(id); + } +} diff --git a/apps/backend/src/staff/staff.entity.ts b/apps/backend/src/staff/staff.entity.ts new file mode 100644 index 000000000..05fd6e478 --- /dev/null +++ b/apps/backend/src/staff/staff.entity.ts @@ -0,0 +1,79 @@ +import { + Entity, + PrimaryGeneratedColumn, + Column, + OneToMany, + ManyToMany, + JoinTable, +} from 'typeorm'; +import { Homebase } from '../types'; +import { StaffType } from './staff.types'; +import { FosterCoordinator } from '../coordinators/coordinators.entity'; +import { Match } from '../matches/matches.entity'; + +@Entity('foster_staff') +export class FosterStaff { + @PrimaryGeneratedColumn({ name: 'staff_id' }) + staffId!: number; + + @Column({ name: 'first_name', type: 'varchar', length: 255 }) + firstName!: string; + + @Column({ name: 'last_name', type: 'varchar', length: 255 }) + lastName!: string; + + @Column({ type: 'varchar', length: 20 }) + phone!: string; + + @Column({ + name: 'secondary_phone', + type: 'varchar', + length: 20, + nullable: true, + }) + secondaryPhone!: string | null; + + @Column({ type: 'varchar', length: 255, unique: true }) + email!: string; + + @Column({ type: 'varchar', length: 255 }) + address!: string; + + @Column({ type: 'varchar', length: 255 }) + city!: string; + + @Column({ type: 'varchar', length: 10 }) + zipcode!: string; + + @Column({ type: 'enum', enum: Homebase }) + homebase!: Homebase; + + @Column({ type: 'text', nullable: true }) + notes!: string | null; + + @Column({ name: 'most_recent_waiver_signed', type: 'boolean' }) + mostRecentWaiverSigned!: boolean; + + @Column({ name: 'staff_type', type: 'enum', enum: StaffType }) + staffType!: StaffType; + + @Column({ type: 'boolean' }) + active!: boolean; + + @Column({ name: 'cognito_sub', type: 'varchar', length: 255, default: '' }) + cognitoSub!: string; + + @ManyToMany(() => FosterCoordinator, { onDelete: 'CASCADE' }) + @JoinTable({ + name: 'staff_coordinator_assignments', + joinColumn: { name: 'staff_id', referencedColumnName: 'staffId' }, + inverseJoinColumn: { + name: 'coordinator_id', + referencedColumnName: 'coordinatorId', + }, + }) + assignedCoordinators!: FosterCoordinator[]; + + @OneToMany(() => Match, (match) => match.staff) + matches?: Match[]; +} diff --git a/apps/backend/src/staff/staff.module.ts b/apps/backend/src/staff/staff.module.ts new file mode 100644 index 000000000..5f059228e --- /dev/null +++ b/apps/backend/src/staff/staff.module.ts @@ -0,0 +1,14 @@ +import { Module } from '@nestjs/common'; +import { TypeOrmModule } from '@nestjs/typeorm'; +import { FosterStaff } from './staff.entity'; +import { StaffController } from './staff.controller'; +import { StaffService } from './staff.service'; +import { CognitoModule } from '../aws/cognito/cognito.module'; + +@Module({ + imports: [TypeOrmModule.forFeature([FosterStaff]), CognitoModule], + controllers: [StaffController], + providers: [StaffService], + exports: [StaffService], +}) +export class StaffModule {} diff --git a/apps/backend/src/staff/staff.service.spec.ts b/apps/backend/src/staff/staff.service.spec.ts new file mode 100644 index 000000000..39470fe50 --- /dev/null +++ b/apps/backend/src/staff/staff.service.spec.ts @@ -0,0 +1,329 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { + BadRequestException, + ConflictException, + InternalServerErrorException, + Logger, + NotFoundException, +} from '@nestjs/common'; +import { getRepositoryToken } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; +import { StaffService } from './staff.service'; +import { FosterStaff } from './staff.entity'; +import { CreateStaffDto } from './dtos/create-staff.dto'; +import { ConfirmStaffDto } from './dtos/confirm-staff.dto'; +import { CognitoService } from '../aws/cognito/cognito.service'; +import { CognitoRole } from '../aws/cognito/cognito.types'; +import { Homebase } from '../types'; +import { StaffType } from './staff.types'; + +describe('StaffService', () => { + let service: StaffService; + let repo: jest.Mocked>; + let cognitoService: jest.Mocked; + let loggerSpy: jest.SpyInstance; + + const dto = { + firstName: 'Jane', + lastName: 'Doe', + phone: '+16175551234', + secondaryPhone: null, + email: 'jane.doe@mspca.org', + password: 'Str0ng!Password', + address: '123 Main St', + city: 'Boston', + zipcode: '02101', + homebase: Homebase.BOSTON, + notes: null, + staffType: StaffType.SHELTER, + } as CreateStaffDto; + + const confirmDto = { + email: dto.email, + code: '123456', + } as ConfirmStaffDto; + + const staff = { + staffId: 1, + firstName: dto.firstName, + lastName: dto.lastName, + phone: dto.phone, + secondaryPhone: dto.secondaryPhone, + email: dto.email, + address: dto.address, + city: dto.city, + zipcode: dto.zipcode, + homebase: dto.homebase, + notes: dto.notes, + staffType: dto.staffType, + active: true, + mostRecentWaiverSigned: true, + cognitoSub: 'cognito-sub-123', + assignedCoordinators: [], + } as FosterStaff; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [ + StaffService, + { + provide: getRepositoryToken(FosterStaff), + useValue: { + findOneBy: jest.fn(), + findOne: jest.fn(), + save: jest.fn(), + }, + }, + { + provide: CognitoService, + useValue: { + signUpUser: jest.fn(), + confirmUser: jest.fn(), + deleteUser: jest.fn(), + }, + }, + ], + }).compile(); + + service = module.get(StaffService); + repo = module.get(getRepositoryToken(FosterStaff)); + cognitoService = module.get(CognitoService); + + loggerSpy = jest.spyOn(Logger.prototype, 'error').mockImplementation(); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + describe('create', () => { + it('signs up with Cognito before saving', async () => { + repo.findOneBy.mockResolvedValue(null); + cognitoService.signUpUser.mockResolvedValue('cognito-sub-123'); + repo.save.mockResolvedValue(staff); + + const result = await service.create(dto); + + expect(repo.findOneBy).toHaveBeenCalledWith({ + email: dto.email, + }); + + expect(cognitoService.signUpUser).toHaveBeenCalledWith({ + firstName: dto.firstName, + lastName: dto.lastName, + email: dto.email, + password: dto.password, + }); + + expect(repo.save).toHaveBeenCalledWith( + expect.objectContaining({ + email: dto.email, + active: true, + mostRecentWaiverSigned: true, + cognitoSub: 'cognito-sub-123', + }), + ); + + expect(repo.save.mock.calls[0][0]).not.toHaveProperty('password'); + expect(result).toBe(staff); + }); + + it('saves with an empty coordinator list', async () => { + repo.findOneBy.mockResolvedValue(null); + cognitoService.signUpUser.mockResolvedValue('cognito-sub-123'); + repo.save.mockResolvedValue(staff); + + await service.create(dto); + + expect(repo.save).toHaveBeenCalledWith( + expect.objectContaining({ assignedCoordinators: [] }), + ); + }); + + it('rejects duplicate staff members', async () => { + repo.findOneBy.mockResolvedValue(staff); + + await expect(service.create(dto)).rejects.toThrow(ConflictException); + + expect(cognitoService.signUpUser).not.toHaveBeenCalled(); + expect(repo.save).not.toHaveBeenCalled(); + }); + + it('does not save if Cognito sign-up fails', async () => { + repo.findOneBy.mockResolvedValue(null); + cognitoService.signUpUser.mockRejectedValue( + new ConflictException('Cognito user already exists'), + ); + + await expect(service.create(dto)).rejects.toThrow(ConflictException); + + expect(repo.save).not.toHaveBeenCalled(); + }); + + it('deletes the Cognito user when saving fails and logs the error', async () => { + const databaseError = new Error('Database error'); + + repo.findOneBy.mockResolvedValue(null); + cognitoService.signUpUser.mockResolvedValue('sub-123'); + repo.save.mockRejectedValue(databaseError); + cognitoService.deleteUser.mockResolvedValue(undefined); + + await expect(service.create(dto)).rejects.toThrow( + InternalServerErrorException, + ); + + expect(cognitoService.deleteUser).toHaveBeenCalledWith(dto.email); + + expect(loggerSpy).toHaveBeenCalledWith( + `Failed to save staff member ${dto.email}`, + databaseError, + ); + }); + + it('returns a server error and logs when Cognito cleanup fails', async () => { + const databaseError = new Error('Database error'); + const cleanupError = new Error('Cleanup failed'); + + repo.findOneBy.mockResolvedValue(null); + cognitoService.signUpUser.mockResolvedValue('sub-123'); + repo.save.mockRejectedValue(databaseError); + cognitoService.deleteUser.mockRejectedValue(cleanupError); + + await expect(service.create(dto)).rejects.toThrow( + InternalServerErrorException, + ); + + expect(cognitoService.deleteUser).toHaveBeenCalledWith(dto.email); + + expect(loggerSpy).toHaveBeenCalledWith( + `Failed to save staff member ${dto.email}`, + databaseError, + ); + + expect(loggerSpy).toHaveBeenCalledWith( + `Created Cognito user sub-123 for ${dto.email}, but failed to save the staff member or delete the Cognito user`, + ); + }); + }); + + describe('confirm', () => { + it('confirms an existing staff member', async () => { + repo.findOneBy.mockResolvedValue(staff); + cognitoService.confirmUser.mockResolvedValue(undefined); + + await expect(service.confirm(confirmDto)).resolves.toBeUndefined(); + + expect(repo.findOneBy).toHaveBeenCalledWith({ + email: confirmDto.email, + }); + + expect(cognitoService.confirmUser).toHaveBeenCalledWith( + confirmDto.email, + confirmDto.code, + CognitoRole.Staff, + ); + }); + + it('rejects confirmation when the staff member does not exist', async () => { + repo.findOneBy.mockResolvedValue(null); + + await expect(service.confirm(confirmDto)).rejects.toThrow( + NotFoundException, + ); + + expect(cognitoService.confirmUser).not.toHaveBeenCalled(); + }); + + it('propagates errors from Cognito', async () => { + const error = new BadRequestException('Invalid verification code'); + + repo.findOneBy.mockResolvedValue(staff); + cognitoService.confirmUser.mockRejectedValue(error); + + await expect(service.confirm(confirmDto)).rejects.toBe(error); + + expect(cognitoService.confirmUser).toHaveBeenCalledWith( + confirmDto.email, + confirmDto.code, + CognitoRole.Staff, + ); + }); + }); + + describe('findByCognitoSubOrFail', () => { + it('returns the staff member with the matching Cognito sub', async () => { + repo.findOne.mockResolvedValue(staff); + + const result = await service.findByCognitoSubOrFail('cognito-sub-123'); + + expect(repo.findOne).toHaveBeenCalledWith({ + where: { cognitoSub: 'cognito-sub-123' }, + relations: ['assignedCoordinators'], + }); + expect(result).toBe(staff); + }); + + it('throws NotFoundException when no staff member has the Cognito sub', async () => { + repo.findOne.mockResolvedValue(null); + + await expect( + service.findByCognitoSubOrFail('unknown-sub'), + ).rejects.toThrow(NotFoundException); + }); + + it('throws NotFoundException without querying when the sub is empty', async () => { + await expect(service.findByCognitoSubOrFail('')).rejects.toThrow( + NotFoundException, + ); + + expect(repo.findOne).not.toHaveBeenCalled(); + }); + }); + + describe('deactivate', () => { + it('deactivates an active staff member', async () => { + repo.findOne.mockResolvedValue({ ...staff }); + repo.save.mockImplementation(async (value) => value as FosterStaff); + + const result = await service.deactivate(1); + + expect(result.active).toBe(false); + expect(repo.save).toHaveBeenCalled(); + }); + + it('rejects an already inactive staff member', async () => { + repo.findOne.mockResolvedValue({ + ...staff, + active: false, + }); + + await expect(service.deactivate(1)).rejects.toThrow(BadRequestException); + }); + }); + + describe('activate', () => { + it('activates an inactive staff member', async () => { + repo.findOne.mockResolvedValue({ + ...staff, + active: false, + }); + repo.save.mockImplementation(async (value) => value as FosterStaff); + + const result = await service.activate(1); + + expect(result.active).toBe(true); + }); + + it('rejects an already active staff member', async () => { + repo.findOne.mockResolvedValue({ ...staff }); + + await expect(service.activate(1)).rejects.toThrow(BadRequestException); + }); + + it('rejects a missing staff member', async () => { + repo.findOne.mockResolvedValue(null); + + await expect(service.activate(999)).rejects.toThrow(NotFoundException); + }); + }); +}); diff --git a/apps/backend/src/staff/staff.service.ts b/apps/backend/src/staff/staff.service.ts new file mode 100644 index 000000000..1d692c1d2 --- /dev/null +++ b/apps/backend/src/staff/staff.service.ts @@ -0,0 +1,207 @@ +import { + BadRequestException, + ConflictException, + Injectable, + InternalServerErrorException, + Logger, + NotFoundException, +} from '@nestjs/common'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; +import { FosterStaff } from './staff.entity'; +import { CreateStaffDto } from './dtos/create-staff.dto'; +import { ConfirmStaffDto } from './dtos/confirm-staff.dto'; +import { CognitoService } from '../aws/cognito/cognito.service'; +import { CognitoRole } from '../aws/cognito/cognito.types'; + +@Injectable() +export class StaffService { + private readonly logger = new Logger(StaffService.name); + + constructor( + @InjectRepository(FosterStaff) + private repo: Repository, + private cognitoService: CognitoService, + ) {} + + /** + * Registers a staff member with Cognito and saves their profile. + * Staff are active immediately and do not require approval. + * Coordinator assignments are left empty for now. + * + * @param dto - The staff member's registration information. + * @returns The newly created staff member. + * @throws {ConflictException} If a staff member with the email already exists in the database. + * @throws {BadRequestException} If Cognito rejects the registration request. + * @throws {InternalServerErrorException} If saving the staff member to the database fails (the Cognito user is deleted). + */ + async create(dto: CreateStaffDto): Promise { + const { password, ...profile } = dto; + const { email } = profile; + + const existing = await this.repo.findOneBy({ email }); + + if (existing) { + throw new ConflictException( + 'A staff member with this email already exists', + ); + } + + const cognitoSub = await this.cognitoService.signUpUser({ + firstName: profile.firstName, + lastName: profile.lastName, + email, + password, + }); + + try { + return await this.repo.save({ + ...profile, + active: true, + mostRecentWaiverSigned: true, + cognitoSub, + assignedCoordinators: [], + }); + } catch (error) { + this.logger.error(`Failed to save staff member ${email}`, error); + + try { + await this.cognitoService.deleteUser(email); + } catch { + this.logger.error( + `Created Cognito user ${cognitoSub} for ${email}, but failed to save the staff member or delete the Cognito user`, + ); + } + + throw new InternalServerErrorException('Failed to save the staff member'); + } + } + + /** + * Confirms a staff member's email and assigns the Staff Cognito role. + * + * @param dto - The staff member's email and verification code. + * @returns A promise that resolves when confirmation is complete. + * @throws {NotFoundException} If no staff member exists with the given email in the database. + * @throws {BadRequestException} If Cognito rejects the verification code or confirmation request. + * @throws {InternalServerErrorException} If Cognito fails to complete the confirmation. + */ + async confirm(dto: ConfirmStaffDto): Promise { + const { email } = dto; + + const staff = await this.repo.findOneBy({ email }); + + if (!staff) { + throw new NotFoundException('No staff member with this email exists'); + } + + await this.cognitoService.confirmUser(email, dto.code, CognitoRole.Staff); + } + + /** + * Fetches a staff member by their ID, including their assigned coordinators. + * + * @param id - The ID of the staff member to retrieve. + * @returns The staff member with their assigned coordinators. + * @throws {NotFoundException} If no staff member exists with the given ID. + */ + async findByIdOrFail(id: number): Promise { + const staff = await this.repo.findOne({ + where: { staffId: id }, + relations: ['assignedCoordinators'], + }); + + if (!staff) { + throw new NotFoundException(`Staff member with ID ${id} not found`); + } + + return staff; + } + + /** + * Fetches a staff member by their ID and verifies they are active. + * + * @param id - The ID of the staff member to retrieve. + * @returns The staff member. + * @throws {NotFoundException} If no staff member exists with the given ID. + * @throws {BadRequestException} If the staff member is not active. + */ + async findActiveOrFail(id: number): Promise { + const staff = await this.findByIdOrFail(id); + + if (!staff.active) { + throw new BadRequestException(`Staff member with ID ${id} is not active`); + } + + return staff; + } + + /** + * Fetches a staff member by their Cognito sub, including their assigned + * coordinators. Used to look up the signed-in user from their token. + * + * @param cognitoSub - The `sub` claim from the user's Cognito access token. + * @returns The staff member. + * @throws {NotFoundException} If no staff member has this Cognito sub. + */ + async findByCognitoSubOrFail(cognitoSub: string): Promise { + if (!cognitoSub) { + throw new NotFoundException('Staff member not found'); + } + + const staff = await this.repo.findOne({ + where: { cognitoSub }, + relations: ['assignedCoordinators'], + }); + + if (!staff) { + throw new NotFoundException('Staff member not found'); + } + + return staff; + } + + /** + * Deactivates an active staff member. + * + * @param id - The ID of the staff member to deactivate. + * @returns The updated staff member. + * @throws {NotFoundException} If the staff member does not exist. + * @throws {BadRequestException} If the staff member is already inactive. + */ + async deactivate(id: number): Promise { + const staff = await this.findByIdOrFail(id); + + if (!staff.active) { + throw new BadRequestException( + `Staff member with ID ${id} is already inactive`, + ); + } + + staff.active = false; + + return this.repo.save(staff); + } + + /** + * Reactivates an inactive staff member. + * + * @param id - The ID of the staff member to activate. + * @returns The updated staff member. + * @throws {NotFoundException} If the staff member does not exist. + * @throws {BadRequestException} If the staff member is already active. + */ + async activate(id: number): Promise { + const staff = await this.findByIdOrFail(id); + + if (staff.active) { + throw new BadRequestException( + `Staff member with ID ${id} is already active`, + ); + } + + staff.active = true; + + return this.repo.save(staff); + } +} diff --git a/apps/backend/src/staff/staff.types.ts b/apps/backend/src/staff/staff.types.ts new file mode 100644 index 000000000..2beb0c3c3 --- /dev/null +++ b/apps/backend/src/staff/staff.types.ts @@ -0,0 +1,4 @@ +export enum StaffType { + HOSPITAL = 'Hospital', + SHELTER = 'Shelter', +} diff --git a/apps/backend/src/volunteers/volunteers.controller.ts b/apps/backend/src/volunteers/volunteers.controller.ts index 233572723..0975d160d 100644 --- a/apps/backend/src/volunteers/volunteers.controller.ts +++ b/apps/backend/src/volunteers/volunteers.controller.ts @@ -168,12 +168,12 @@ export class VolunteersController { return this.volunteersService.findByIdOrFail(volunteerId); } - // TODO: restrict to coordinators once role guarding is added + // TODO: restrict to coordinators and staff once role guarding is added @Patch('/:volunteerId/coordinator-update-profile') @ApiOperation({ - summary: "Update a volunteer's profile as a coordinator", + summary: "Update a volunteer's profile as a coordinator or staff member", description: - 'Accepts every field a volunteer can edit, plus coordinator-only fields. Returns the full volunteer, including all fields hidden to them.', + 'Accepts every field a volunteer can edit, plus coordinator-only fields. Returns the full volunteer, including all fields hidden to them. Staff members can also use this endpoint (role guards will be added later).', }) @ApiParam({ name: 'volunteerId', diff --git a/apps/backend/src/volunteers/volunteers.entity.ts b/apps/backend/src/volunteers/volunteers.entity.ts index 3bd6ea268..c23a64fcc 100644 --- a/apps/backend/src/volunteers/volunteers.entity.ts +++ b/apps/backend/src/volunteers/volunteers.entity.ts @@ -5,7 +5,6 @@ import { OneToMany, ManyToMany, JoinTable, - Unique, Check, } from 'typeorm'; import { Homebase } from '../types'; @@ -19,7 +18,6 @@ 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)',