Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Jest run
name: Backend tests

on:
push:
Expand All @@ -7,7 +7,7 @@ on:
branches: ['**']

jobs:
jest-tests:
backend-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
Expand Down
19 changes: 19 additions & 0 deletions .github/workflows/frontend_tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: Frontend tests

on:
push:
branches: ['**']
pull_request:
branches: ['**']

jobs:
frontend-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24.x
cache: 'yarn'
- run: yarn install --frozen-lockfile
- run: npx vitest run --root apps/frontend
46 changes: 46 additions & 0 deletions apps/backend/src/animals/animals.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AnimalsController } from './animals.controller';
import { AnimalsService } from './animals.service';
import { Animal } from './animals.entity';

describe('AnimalsController', () => {
let controller: AnimalsController;
let service: { findAll: jest.Mock };

beforeEach(async () => {
service = { findAll: jest.fn() };

const module: TestingModule = await Test.createTestingModule({
controllers: [AnimalsController],
providers: [{ provide: AnimalsService, useValue: service }],
}).compile();

controller = module.get<AnimalsController>(AnimalsController);
});

it('should be defined', () => {
expect(controller).toBeDefined();
});

describe('getAnimals', () => {
it('returns the animals from the service', async () => {
const animals = [{ animalId: 1 }, { animalId: 2 }] as Animal[];
service.findAll.mockResolvedValue(animals);

await expect(controller.getAnimals()).resolves.toBe(animals);
expect(service.findAll).toHaveBeenCalledTimes(1);
});

it('returns an empty array when there are no animals', async () => {
service.findAll.mockResolvedValue([]);

await expect(controller.getAnimals()).resolves.toEqual([]);
});

it('propagates service errors', async () => {
service.findAll.mockRejectedValue(new Error('db down'));

await expect(controller.getAnimals()).rejects.toThrow('db down');
});
});
});
25 changes: 25 additions & 0 deletions apps/backend/src/animals/animals.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Controller, Get, HttpStatus } from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { AnimalsService } from './animals.service';
import { Animal } from './animals.entity';

@ApiTags('Animals')
@Controller('animals')
export class AnimalsController {
constructor(private animalsService: AnimalsService) {}

@Get()
@ApiOperation({
summary: 'Get all available animals',
description:
'Returns every animal. All animals in the database are currently treated as available.',
})
@ApiResponse({
status: HttpStatus.OK,
description: 'The animals, or an empty array when none are available.',
type: [Animal],
})
async getAnimals(): Promise<Animal[]> {
return this.animalsService.findAll();
}
}
2 changes: 2 additions & 0 deletions apps/backend/src/animals/animals.module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Animal } from './animals.entity';
import { AnimalsController } from './animals.controller';
import { AnimalsService } from './animals.service';

@Module({
imports: [TypeOrmModule.forFeature([Animal])],
controllers: [AnimalsController],
providers: [AnimalsService],
exports: [AnimalsService],
})
Expand Down
17 changes: 17 additions & 0 deletions apps/backend/src/animals/animals.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,23 @@ describe('AnimalsService', () => {
expect(service).toBeDefined();
});

describe('findAll', () => {
it('returns every animal', async () => {
mockRepo.find.mockResolvedValue([mockAnimal]);

const result = await service.findAll();

expect(result).toEqual([mockAnimal]);
expect(mockRepo.find).toHaveBeenCalledWith();
});

it('returns an empty array when there are no animals', async () => {
mockRepo.find.mockResolvedValue([]);

await expect(service.findAll()).resolves.toEqual([]);
});
});

describe('findByChameleonIdOrFail', () => {
it('returns the animal when one with the Chameleon ID exists', async () => {
mockRepo.findOneBy.mockResolvedValue(mockAnimal);
Expand Down
12 changes: 12 additions & 0 deletions apps/backend/src/animals/animals.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ export class AnimalsService {
private repo: Repository<Animal>,
) {}

/**
* Fetches every available Animal.
*
* There is no availability tracking yet, so every Animal in the database is
* treated as available.
*
* @returns All Animals, or an empty array when there are none.
*/
async findAll(): Promise<Animal[]> {
return this.repo.find();
}

/**
* Fetches an Animal by its Chameleon animal ID.
*
Expand Down
2 changes: 2 additions & 0 deletions apps/backend/src/config/migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 { AddMatchAdditionalComments1794784721012 } from '../migrations/1794784721012-AddMatchAdditionalComments';

const schemaMigrations = [
InitialSchemas1789354568323,
Expand All @@ -28,6 +29,7 @@ const schemaMigrations = [
AddFarmAnimalsToFosterType1793476100199,
RenameAdminUsersToOwners1793485161630,
AddFosterTypePreferences1793600000000,
AddMatchAdditionalComments1794784721012,
];

export default schemaMigrations;
6 changes: 5 additions & 1 deletion apps/backend/src/matches/dtos/create-match.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IsInt, IsPositive, MaxLength } from 'class-validator';
import { IsInt, IsPositive, MaxLength, ValidateIf } from 'class-validator';
import { IsNonEmptyString } from '../../utils/decorators/is-non-empty-string.decorator';

export class CreateMatchDto {
Expand All @@ -9,4 +9,8 @@ export class CreateMatchDto {
@IsNonEmptyString()
@MaxLength(255)
chameleonAnimalId!: string;

@ValidateIf((_, value) => value !== undefined && value !== null)
@IsNonEmptyString()
additionalComments?: string;
}
3 changes: 3 additions & 0 deletions apps/backend/src/matches/matches.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ export class Match {
@Column({ type: 'enum', enum: MatchStatus })
status!: MatchStatus;

@Column({ name: 'additional_comments', type: 'text', nullable: true })
additionalComments!: string | null;

@Column({ name: 'denied_reason', type: 'text', nullable: true })
deniedReason!: string | null;
}
88 changes: 87 additions & 1 deletion apps/backend/src/matches/matches.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { BadRequestException, Logger, NotFoundException } from '@nestjs/common';
import {
BadRequestException,
ConflictException,
Logger,
NotFoundException,
} from '@nestjs/common';
import { MatchesService } from './matches.service';
import { Match } from './matches.entity';
import { MatchStatus } from './matches.types';
Expand All @@ -11,6 +16,7 @@ import { VolunteersService } from '../volunteers/volunteers.service';
import { AnimalsService } from '../animals/animals.service';
import { EmailsService } from '../aws/ses/email.service';
import { SendEmailDTO } from '../aws/ses/sendEmail.dto';
import { In } from 'typeorm';

const coordinator = {
coordinatorId: 7,
Expand Down Expand Up @@ -189,11 +195,91 @@ describe('MatchesService', () => {
volunteerId: 1,
chameleonAnimalId: 'A42',
status: MatchStatus.PENDING,
additionalComments: null,
deniedReason: null,
});
expect(match.status).toEqual(MatchStatus.PENDING);
});

it('throws ConflictException when the volunteer already has a PENDING match for the animal', async () => {
volunteersService.findActiveOrFail.mockResolvedValue(
volunteerWithCoordinator,
);
matchRepo.findOneBy.mockResolvedValue({
matchId: 5,
volunteerId: 1,
chameleonAnimalId: 'A42',
status: MatchStatus.PENDING,
});

await expect(
service.create({ volunteerId: 1, chameleonAnimalId: 'A42' }),
).rejects.toThrow(ConflictException);
expect(matchRepo.save).not.toHaveBeenCalled();
expect(emailsService.sendEmail).not.toHaveBeenCalled();
});

it('only treats PENDING and ACTIVE matches as duplicates', async () => {
Comment thread
pujitakalinadhabhotla marked this conversation as resolved.
Resolved
volunteersService.findActiveOrFail.mockResolvedValue(
volunteerWithCoordinator,
);
emailsService.sendEmail.mockResolvedValue(undefined);
const existingMatches = [
{
matchId: 5,
volunteerId: 1,
chameleonAnimalId: 'A42',
status: MatchStatus.WITHDRAWN,
},
];
matchRepo.findOneBy.mockImplementation(
async (where) =>
existingMatches.find(
(m) =>
m.volunteerId === where.volunteerId &&
m.chameleonAnimalId === where.chameleonAnimalId &&
where.status.value.includes(m.status),
) ?? null,
);
matchRepo.create.mockImplementation((attrs) => attrs);
matchRepo.save.mockImplementation((match) =>
Promise.resolve({ matchId: 10, ...match }),
);

await service.create({ volunteerId: 1, chameleonAnimalId: 'A42' });

expect(matchRepo.findOneBy).toHaveBeenCalledWith({
volunteerId: 1,
chameleonAnimalId: 'A42',
status: In([MatchStatus.PENDING, MatchStatus.ACTIVE]),
});
expect(matchRepo.save).toHaveBeenCalled();
});

it('saves additional comments when provided', async () => {
volunteersService.findActiveOrFail.mockResolvedValue(
volunteerWithCoordinator,
);
emailsService.sendEmail.mockResolvedValue(undefined);
matchRepo.create.mockImplementation((attrs) => attrs);
matchRepo.save.mockImplementation((match) =>
Promise.resolve({ matchId: 10, ...match }),
);

const match = await service.create({
volunteerId: 1,
chameleonAnimalId: 'A42',
additionalComments: 'Can pick up on weekends',
});

expect(matchRepo.create).toHaveBeenCalledWith(
expect.objectContaining({
additionalComments: 'Can pick up on weekends',
}),
);
expect(match.additionalComments).toEqual('Can pick up on weekends');
});

it("emails the sender address with the volunteer's assigned coordinator cc'd", async () => {
volunteersService.findActiveOrFail.mockResolvedValue(
volunteerWithCoordinator,
Expand Down
16 changes: 15 additions & 1 deletion apps/backend/src/matches/matches.service.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import {
BadRequestException,
ConflictException,
Inject,
Injectable,
Logger,
NotFoundException,
forwardRef,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Not, Repository } from 'typeorm';
import { In, Not, Repository } from 'typeorm';
import { Match } from './matches.entity';
import { MatchStatus } from './matches.types';
import { CreateMatchDto } from './dtos/create-match.dto';
Expand Down Expand Up @@ -43,18 +44,31 @@ export class MatchesService {
* @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<Match> {
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}`,
);
}

const match = await this.repo.save(
this.repo.create({
volunteerId: dto.volunteerId,
chameleonAnimalId: dto.chameleonAnimalId,
status: MatchStatus.PENDING,
additionalComments: dto.additionalComments ?? null,
deniedReason: null,
}),
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we regenerate this so it sorts last after you merge main?


export class AddMatchAdditionalComments1794784721012
implements MigrationInterface
{
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "matches" ADD COLUMN "additional_comments" text`,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "matches" DROP COLUMN "additional_comments"`,
);
}
}
Loading
Loading