Skip to content
Open
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
4 changes: 4 additions & 0 deletions apps/backend/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import typeorm from './config/typeorm';
Expand All @@ -9,6 +10,7 @@ import { CoordinatorsModule } from './coordinators/coordinators.module';
import { VolunteersModule } from './volunteers/volunteers.module';
import { OwnersModule } from './owners/owners.module';
import { AnimalsModule } from './animals/animals.module';
import { JobsModule } from './jobs/jobs.module';

@Module({
imports: [
Expand All @@ -21,13 +23,15 @@ import { AnimalsModule } from './animals/animals.module';
useFactory: (configService: ConfigService) =>
configService.getOrThrow('typeorm'),
}),
ScheduleModule.forRoot(),
CognitoModule,
RecommendationsModule,
MatchesModule,
CoordinatorsModule,
VolunteersModule,
OwnersModule,
AnimalsModule,
JobsModule,
],
})
export class AppModule {}
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 { AddPetsAndHouseholdDetails1794408338094 } from '../migrations/1794408338094-AddPetsAndHouseholdDetails';

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

export default schemaMigrations;
92 changes: 92 additions & 0 deletions apps/backend/src/jobs/age-jobs.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { Test, TestingModule } from '@nestjs/testing';
import { Logger } from '@nestjs/common';
import { SCHEDULE_CRON_OPTIONS } from '@nestjs/schedule/dist/schedule.constants';
import { AgeJobsService } from './age-jobs.service';
import { PetsService } from '../pets/pets.service';
import { VolunteersService } from '../volunteers/volunteers.service';

describe('AgeJobsService', () => {
let service: AgeJobsService;
let mockPetsService: { incrementAllAges: jest.Mock };
let mockVolunteersService: { incrementAllChildrenAges: jest.Mock };
let errorSpy: jest.SpyInstance;

beforeEach(async () => {
mockPetsService = { incrementAllAges: jest.fn() };
mockVolunteersService = { incrementAllChildrenAges: jest.fn() };
jest.spyOn(Logger.prototype, 'log').mockImplementation();
errorSpy = jest.spyOn(Logger.prototype, 'error').mockImplementation();

const module: TestingModule = await Test.createTestingModule({
providers: [
AgeJobsService,
{ provide: PetsService, useValue: mockPetsService },
{ provide: VolunteersService, useValue: mockVolunteersService },
],
}).compile();

service = module.get(AgeJobsService);
});

afterEach(() => {
jest.restoreAllMocks();
});

describe('incrementPetAges', () => {
it('calls PetsService.incrementAllAges once', async () => {
mockPetsService.incrementAllAges.mockResolvedValue(3);
await service.incrementPetAges();

expect(mockPetsService.incrementAllAges).toHaveBeenCalledTimes(1);
});

it('logs and swallows a failure', async () => {
mockPetsService.incrementAllAges.mockRejectedValue(new Error('db down'));

await expect(service.incrementPetAges()).resolves.toBeUndefined();
expect(errorSpy).toHaveBeenCalled();
});
});

describe('incrementChildrenAges', () => {
it('calls VolunteersService.incrementAllChildrenAges once', async () => {
mockVolunteersService.incrementAllChildrenAges.mockResolvedValue(2);
await service.incrementChildrenAges();

expect(
mockVolunteersService.incrementAllChildrenAges,
).toHaveBeenCalledTimes(1);
});

it('logs and swallows a failure', async () => {
mockVolunteersService.incrementAllChildrenAges.mockRejectedValue(
new Error('db down'),
);

await expect(service.incrementChildrenAges()).resolves.toBeUndefined();
expect(errorSpy).toHaveBeenCalled();
});
});

describe('schedules', () => {
const cronOptions = (method: keyof AgeJobsService) =>
Reflect.getMetadata(
SCHEDULE_CRON_OPTIONS,
AgeJobsService.prototype[method],
);

it('runs incrementPetAges at midnight on the first of each month, Eastern', () => {
expect(cronOptions('incrementPetAges')).toMatchObject({
cronTime: '0 0 1 * *',
timeZone: 'America/New_York',
});
});

it('runs incrementChildrenAges at midnight on January 1, Eastern', () => {
expect(cronOptions('incrementChildrenAges')).toMatchObject({
cronTime: '0 0 1 1 *',
timeZone: 'America/New_York',
});
});
});
});
48 changes: 48 additions & 0 deletions apps/backend/src/jobs/age-jobs.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { PetsService } from '../pets/pets.service';
import { VolunteersService } from '../volunteers/volunteers.service';

const SCHEDULE_TIME_ZONE = 'America/New_York';

@Injectable()
export class AgeJobsService {
private readonly logger = new Logger(AgeJobsService.name);

constructor(
private petsService: PetsService,
private volunteersService: VolunteersService,
) {}

/**
* Ages every pet by one month. Runs at midnight on the first of each month.
*/
@Cron('0 0 1 * *', { timeZone: SCHEDULE_TIME_ZONE })
async incrementPetAges(): Promise<void> {
try {
const count = await this.petsService.incrementAllAges();
this.logger.log(`Incremented age of ${count} pets`);
} catch (err) {
this.logger.error(
'Failed to increment pet ages',
err instanceof Error ? err.stack : String(err),
);
}
}

/**
* Ages every child by one year. Runs at midnight on January 1.
*/
@Cron('0 0 1 1 *', { timeZone: SCHEDULE_TIME_ZONE })
async incrementChildrenAges(): Promise<void> {
try {
const count = await this.volunteersService.incrementAllChildrenAges();
this.logger.log(`Incremented children's ages for ${count} volunteers`);
} catch (err) {
this.logger.error(
"Failed to increment children's ages",
err instanceof Error ? err.stack : String(err),
);
}
}
}
10 changes: 10 additions & 0 deletions apps/backend/src/jobs/jobs.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { PetsModule } from '../pets/pets.module';
import { VolunteersModule } from '../volunteers/volunteers.module';
import { AgeJobsService } from './age-jobs.service';

@Module({
imports: [PetsModule, VolunteersModule],
providers: [AgeJobsService],
})
export class JobsModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddPetsAndHouseholdDetails1794408338094
implements MigrationInterface
{
public async up(queryRunner: QueryRunner): Promise<void> {
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<void> {
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"`);
}
}
21 changes: 21 additions & 0 deletions apps/backend/src/pets/dtos/pet.dto.ts
Original file line number Diff line number Diff line change
@@ -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;
}
41 changes: 41 additions & 0 deletions apps/backend/src/pets/pets.entity.ts
Original file line number Diff line number Diff line change
@@ -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;
}
11 changes: 11 additions & 0 deletions apps/backend/src/pets/pets.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Pet } from './pets.entity';
import { PetsService } from './pets.service';

@Module({
imports: [TypeOrmModule.forFeature([Pet])],
providers: [PetsService],
exports: [PetsService],
})
export class PetsModule {}
Loading
Loading