Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(excuses): add excuses model + API end points ✨ #10

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
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
17 changes: 17 additions & 0 deletions prisma/migrations/20240609100553_add_excuses/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
-- CreateTable
CREATE TABLE "excuses" (
"id" SERIAL NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,
"student_id" INTEGER NOT NULL,
"window_id" INTEGER NOT NULL,
"reason" TEXT NOT NULL,

CONSTRAINT "excuses_pkey" PRIMARY KEY ("id")
);

-- AddForeignKey
ALTER TABLE "excuses" ADD CONSTRAINT "excuses_student_id_fkey" FOREIGN KEY ("student_id") REFERENCES "students"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "excuses" ADD CONSTRAINT "excuses_window_id_fkey" FOREIGN KEY ("window_id") REFERENCES "windows"("id") ON DELETE CASCADE ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
Warnings:

- Added the required column `excuse_from` to the `excuses` table without a default value. This is not possible if the table is not empty.

*/
-- CreateEnum
CREATE TYPE "excuse_from" AS ENUM ('INTERVIEW', 'QUESTION', 'INTERVIEW_AND_QUESTION');

-- CreateEnum
CREATE TYPE "excuse_status" AS ENUM ('PENDING', 'ACCEPTED', 'REJECTED');

-- AlterTable
ALTER TABLE "excuses" ADD COLUMN "excuse_from" "excuse_from" NOT NULL;
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:

- Added the required column `excuse_status` to the `excuses` table without a default value. This is not possible if the table is not empty.

*/
-- AlterTable
ALTER TABLE "excuses" ADD COLUMN "excuse_status" "excuse_status" NOT NULL;
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
-- This is an empty migration.
33 changes: 33 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ model Student {
results StudentResult[]
exclusion Exclusion?
pairingStudents PairingStudent[]
excuses Excuse[]

@@unique([userId, cohortId])
@@map("students")
Expand All @@ -161,10 +162,26 @@ model Window {
studentResults StudentResult[]
exclusions Exclusion[]
pairings Pairing[]
Excuse Excuse[]

@@map("windows")
}

model Excuse {
id Int @id @default(autoincrement())
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
studentId Int @map("student_id")
windowId Int @map("window_id")
excuseFrom ExcuseFrom @map("excuse_from")
status ExcuseStatus @map("excuse_status")
reason String
student Student @relation(fields: [studentId], references: [id], onDelete: Cascade)
window Window @relation(fields: [windowId], references: [id], onDelete: Cascade)

@@map("excuses")
}

// Tracks the student's work done for each window
model StudentResult {
id Int @id @default(autoincrement())
Expand Down Expand Up @@ -395,3 +412,19 @@ enum KeyBinding {

@@map("key_binding")
}

enum ExcuseFrom {
INTERVIEW
QUESTION
INTERVIEW_AND_QUESTION

@@map("excuse_from")
}

enum ExcuseStatus {
PENDING
ACCEPTED
REJECTED

@@map("excuse_status")
}
17 changes: 17 additions & 0 deletions src/product/general/excuses/dtos/create-excuse.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { IsEnum, IsNotEmpty, IsNumber, IsString } from 'class-validator';

import { ExcuseFrom } from '../../../../infra/prisma/generated';

export class CreateExcuseDto {
@IsString()
@IsNotEmpty()
reason: string;

@IsEnum(ExcuseFrom)
@IsNotEmpty()
excuseFrom: ExcuseFrom;

@IsNumber()
@IsNotEmpty()
windowId: number;
}
14 changes: 14 additions & 0 deletions src/product/general/excuses/dtos/update-excuse.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { IsEnum, IsString } from 'class-validator';

import { ExcuseFrom, ExcuseStatus } from '../../../../infra/prisma/generated';

export class UpdateExcuseDto {
@IsString()
reason: string;

@IsEnum(ExcuseFrom)
excuseFrom: ExcuseFrom;

@IsEnum(ExcuseStatus)
status: ExcuseStatus;
}
90 changes: 90 additions & 0 deletions src/product/general/excuses/excuses.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import {
Body,
Controller,
Delete,
Get,
Logger,
Param,
Post,
Put,
Query,
UseFilters,
UseGuards,
} from '@nestjs/common';

import { User } from '../../../infra/prisma/generated';
import { ExcuseBase } from '../../../product/interfaces/excuses';
import { GetUserRest } from '../../../productinfra/decorators';
import {
JwtRestAdminGuard,
JwtRestStudentOrAdminGuard,
} from '../../../productinfra/guards';
import { BadRequestExceptionFilter } from '../../../utils';

import { CreateExcuseDto } from './dtos/create-excuse.dto';
import { UpdateExcuseDto } from './dtos/update-excuse.dto';
import { ExcusesService } from './excuses.service';

@UseGuards(JwtRestStudentOrAdminGuard)
@Controller('excuses')
export class ExcusesController {
constructor(
private readonly logger: Logger,
private readonly excusesService: ExcusesService,
) {}

@UseGuards(JwtRestAdminGuard)
@Get()
@UseFilters(BadRequestExceptionFilter)
findAllExcuses(@Query('cohortId') id: string): Promise<ExcuseBase[]> {
this.logger.log('GET /excuses', ExcusesController.name);
return this.excusesService.findAllExcuses(+id);
}

@Get('/self')
@UseFilters(BadRequestExceptionFilter)
findSelfExcuse(
@GetUserRest() user: User,
@Query('windowId') windowId?: string,
): Promise<ExcuseBase[]> {
this.logger.log('GET /excuses/self', ExcusesController.name);
const windowIdNumber = windowId ? +windowId : undefined;
return this.excusesService.findSelf(user, windowIdNumber);
}

@Get(':id')
@UseFilters(BadRequestExceptionFilter)
findWindow(@Param('id') id: string): Promise<ExcuseBase> {
this.logger.log('GET /excuses/:id', ExcusesController.name);
return this.excusesService.findExcuse(+id);
}

@Delete(':id')
@UseFilters(BadRequestExceptionFilter)
deleteExcuse(@Param('id') id: string): Promise<void> {
this.logger.log('DELETE /excuses/:id', ExcusesController.name);
return this.excusesService.deleteExcuse(+id);
}

@Post('/create')
@UseFilters(BadRequestExceptionFilter)
createExcuse(
@Body() dto: CreateExcuseDto,
@GetUserRest() user: User,
): Promise<number> {
this.logger.log('POST /excuses/create', ExcusesController.name);

return this.excusesService.createExcuse(dto, user);
}

@Put(':id')
@UseFilters(BadRequestExceptionFilter)
updateExcuse(
@Param('id') id: string,
@Body() dto: Partial<UpdateExcuseDto>,
): Promise<number> {
this.logger.log('PUT /excuses/:id', ExcusesController.name);

return this.excusesService.updateExcuse(+id, dto);
}
}
10 changes: 10 additions & 0 deletions src/product/general/excuses/excuses.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Logger, Module } from '@nestjs/common';

import { ExcusesController } from './excuses.controller';
import { ExcusesService } from './excuses.service';

@Module({
controllers: [ExcusesController],
providers: [ExcusesService, Logger],
})
export class ExcusesModule {}
114 changes: 114 additions & 0 deletions src/product/general/excuses/excuses.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { Injectable } from '@nestjs/common';

import { ExcuseStatus, User } from '../../../infra/prisma/generated';
import { PrismaService } from '../../../infra/prisma/prisma.service';
import {
ExcuseBase,
makeExcuseBase,
} from '../../../product/interfaces/excuses';

import { CreateExcuseDto } from './dtos/create-excuse.dto';
import { UpdateExcuseDto } from './dtos/update-excuse.dto';

@Injectable()
export class ExcusesService {
constructor(private readonly prismaService: PrismaService) {}

async findAllExcuses(cohortId: number): Promise<ExcuseBase[]> {
const excuses = await this.prismaService.excuse.findMany({
where: { window: { cohortId } },
include: { student: { include: { user: true } }, window: true },
});

return excuses.map((excuse) => makeExcuseBase(excuse));
}

async findExcuse(id: number): Promise<ExcuseBase> {
const excuse = await this.prismaService.excuse.findUniqueOrThrow({
where: { id },
include: { student: { include: { user: true } }, window: true },
});

return makeExcuseBase(excuse);
}

async findSelf(user: User, windowId?: number): Promise<ExcuseBase[]> {
const student = await this.prismaService.student.findFirst({
where: { userId: user.id },
});

if (!student) {
return [];
}

const excuses = await this.prismaService.excuse.findMany({
where: { studentId: student.id, windowId },
include: { student: { include: { user: true } }, window: true },
});

return excuses.map((excuse) => makeExcuseBase(excuse));
}

async createExcuse(excuse: CreateExcuseDto, user: User): Promise<number> {
const [student, window] = await Promise.all([
this.prismaService.student.findFirst({
where: { userId: user.id },
}),
this.prismaService.window.findUnique({
where: { id: excuse.windowId },
}),
]);

if (!student || !window) {
throw new Error('Student or Window not found');
}

if (window.endAt < new Date()) {
throw new Error('End date must be greater than current date');
}

const createExcuseData = {
...excuse,
studentId: student.id,
status: ExcuseStatus.PENDING,
};

const createdExcuse = await this.prismaService.excuse.create({
data: createExcuseData,
});

return createdExcuse.id;
}

async deleteExcuse(id: number): Promise<void> {
await this.prismaService.excuse.delete({ where: { id } });
}

async updateExcuse(
id: number,
excuse: Partial<UpdateExcuseDto>,
): Promise<number> {
const existingExcuse = await this.prismaService.excuse.findUnique({
where: { id },
});

if (!existingExcuse) {
throw new Error('Excuse not found');
}

const window = await this.prismaService.window.findUnique({
where: { id: existingExcuse.windowId },
});

if (window && window.endAt < new Date()) {
throw new Error('End date must be greater than current date');
}

const res = await this.prismaService.excuse.update({
where: { id },
data: { ...excuse },
});

return res.id;
}
}
2 changes: 2 additions & 0 deletions src/product/general/general.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';

import { AuthModule } from './auth/auth.module';
import { CodeModule } from './code/code.module';
import { ExcusesModule } from './excuses/excuses.module';
import { InterviewsModule } from './interviews/interviews.module';
import { NotesModule } from './notes/notes.module';
import { QuestionsModule } from './questions/questions.module';
Expand All @@ -17,6 +18,7 @@ import { UsersModule } from './users/users.module';
UsersModule,
QuestionsModule,
InterviewsModule,
ExcusesModule,
],
})
export class GeneralModule {}
Loading
Loading