update first - 84
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { AuthModule } from './auth/auth.module.js';
|
||||
import { KeyResultsModule } from './key-results/key-results.module.js';
|
||||
import { ObjectivesModule } from './objectives/objectives.module.js';
|
||||
import { PrismaModule } from './prisma/prisma.module.js';
|
||||
import { UsersModule } from './users/users.module.js';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
JwtModule.register({
|
||||
global: true,
|
||||
secret: process.env.JWT_SECRET ?? 'dev-secret-change-me',
|
||||
signOptions: { expiresIn: '2h' },
|
||||
}),
|
||||
PrismaModule,
|
||||
AuthModule,
|
||||
UsersModule,
|
||||
ObjectivesModule,
|
||||
KeyResultsModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Body, Controller, Inject, Post, Res, ValidationPipe } from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { ok } from '../common/api-response.js';
|
||||
import { AuthService } from './auth.service.js';
|
||||
import { LoginDto } from './dto/login.dto.js';
|
||||
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(@Inject(AuthService) private readonly authService: AuthService) {}
|
||||
|
||||
@Post('login')
|
||||
async login(
|
||||
@Body(new ValidationPipe({ expectedType: LoginDto, whitelist: true, forbidNonWhitelisted: true })) dto: LoginDto,
|
||||
@Res({ passthrough: true }) response: Response,
|
||||
) {
|
||||
const result = await this.authService.login(dto.username, dto.password);
|
||||
response.cookie('okr_token', result.token, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: false,
|
||||
maxAge: 2 * 60 * 60 * 1000,
|
||||
});
|
||||
return ok(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../prisma/prisma.module.js';
|
||||
import { AuthController } from './auth.controller.js';
|
||||
import { AuthService } from './auth.service.js';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import bcrypt from 'bcrypt';
|
||||
import { PrismaService } from '../prisma/prisma.service.js';
|
||||
|
||||
export interface LoginResult {
|
||||
token: string;
|
||||
user: {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
username: string;
|
||||
role: string;
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
@Inject(PrismaService) private readonly prisma: PrismaService,
|
||||
@Inject(JwtService) private readonly jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
async login(usernameOrEmail: string, password: string): Promise<LoginResult> {
|
||||
const user = await this.prisma.user.findFirst({
|
||||
where: {
|
||||
OR: [{ username: usernameOrEmail }, { email: usernameOrEmail }],
|
||||
},
|
||||
});
|
||||
if (user === null) {
|
||||
throw new UnauthorizedException('Invalid credentials');
|
||||
}
|
||||
|
||||
const validPassword = await bcrypt.compare(password, user.passwordHash);
|
||||
if (!validPassword) {
|
||||
throw new UnauthorizedException('Invalid credentials');
|
||||
}
|
||||
|
||||
const token = await this.jwtService.signAsync({
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
name: user.name,
|
||||
});
|
||||
|
||||
return {
|
||||
token,
|
||||
user: {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { IsString, MinLength } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@IsString()
|
||||
username!: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password!: string;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export interface ApiResponse<T> {
|
||||
success: true;
|
||||
data: T;
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function ok<T>(data: T, meta?: Record<string, unknown>): ApiResponse<T> {
|
||||
return meta === undefined ? { success: true, data } : { success: true, data, meta };
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { Request } from 'express';
|
||||
|
||||
export type Role = 'ADMIN' | 'MANAGER' | 'EMPLOYEE';
|
||||
|
||||
export interface JwtUser {
|
||||
sub: number;
|
||||
email: string;
|
||||
role: Role;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface AuthenticatedRequest extends Request {
|
||||
user: JwtUser;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||
import type { AuthenticatedRequest, JwtUser } from './auth.types.js';
|
||||
|
||||
export const CurrentUser = createParamDecorator((_data: unknown, context: ExecutionContext): JwtUser => {
|
||||
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
||||
return request.user;
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import type { Request } from 'express';
|
||||
import type { AuthenticatedRequest, JwtUser } from './auth.types.js';
|
||||
|
||||
function readCookieToken(request: Request): string | undefined {
|
||||
const header = request.headers.cookie;
|
||||
if (header === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const tokenPair = header
|
||||
.split(';')
|
||||
.map((part) => part.trim())
|
||||
.find((part) => part.startsWith('okr_token='));
|
||||
return tokenPair?.slice('okr_token='.length);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(@Inject(JwtService) private readonly jwtService: JwtService) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
||||
const authHeader = request.headers.authorization;
|
||||
const bearer = authHeader?.startsWith('Bearer ') === true ? authHeader.slice(7) : undefined;
|
||||
const token = bearer ?? readCookieToken(request);
|
||||
if (token === undefined || token.length === 0) {
|
||||
throw new UnauthorizedException('Authentication required');
|
||||
}
|
||||
|
||||
try {
|
||||
request.user = this.jwtService.verify<JwtUser>(token);
|
||||
return true;
|
||||
} catch {
|
||||
throw new UnauthorizedException('Invalid or expired token');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
import type { Role } from './auth.types.js';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
export const Roles = (...roles: Role[]): ReturnType<typeof SetMetadata> => SetMetadata(ROLES_KEY, roles);
|
||||
@@ -0,0 +1,25 @@
|
||||
import { CanActivate, ExecutionContext, ForbiddenException, Inject, Injectable } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import type { AuthenticatedRequest, Role } from './auth.types.js';
|
||||
import { ROLES_KEY } from './roles.decorator.js';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
constructor(@Inject(Reflector) private readonly reflector: Reflector) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const roles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (roles === undefined || roles.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
||||
if (!roles.includes(request.user.role)) {
|
||||
throw new ForbiddenException('Insufficient role');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { IsDateString, IsInt, IsNotEmpty, IsPositive, IsString, Max, Min } from 'class-validator';
|
||||
|
||||
export class CreateKeyResultDto {
|
||||
@IsInt()
|
||||
@IsPositive()
|
||||
objectiveId!: number;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
title!: string;
|
||||
|
||||
@IsInt()
|
||||
startValue!: number;
|
||||
|
||||
@IsInt()
|
||||
@IsPositive()
|
||||
targetValue!: number;
|
||||
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
@Max(100)
|
||||
progress!: number;
|
||||
|
||||
@IsDateString()
|
||||
deadline!: string;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { IsInt, IsOptional, IsString, Max, Min } from 'class-validator';
|
||||
|
||||
export class UpdateProgressDto {
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
@Max(100)
|
||||
progress!: number;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
comment?: string;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Body, Controller, Get, Inject, Param, ParseIntPipe, Patch, Post, UseGuards, ValidationPipe } from '@nestjs/common';
|
||||
import { ok } from '../common/api-response.js';
|
||||
import type { JwtUser } from '../common/auth.types.js';
|
||||
import { CurrentUser } from '../common/current-user.decorator.js';
|
||||
import { JwtAuthGuard } from '../common/jwt-auth.guard.js';
|
||||
import { RolesGuard } from '../common/roles.guard.js';
|
||||
import { CreateKeyResultDto } from './dto/create-key-result.dto.js';
|
||||
import { UpdateProgressDto } from './dto/update-progress.dto.js';
|
||||
import { KeyResultsService } from './key-results.service.js';
|
||||
|
||||
@Controller('key-results')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
export class KeyResultsController {
|
||||
constructor(@Inject(KeyResultsService) private readonly keyResultsService: KeyResultsService) {}
|
||||
|
||||
@Get(':id')
|
||||
async get(@Param('id', ParseIntPipe) id: number, @CurrentUser() user: JwtUser) {
|
||||
return ok(await this.keyResultsService.getById(id, user));
|
||||
}
|
||||
|
||||
@Post()
|
||||
async create(
|
||||
@Body(new ValidationPipe({ expectedType: CreateKeyResultDto, whitelist: true, forbidNonWhitelisted: true, transform: true }))
|
||||
dto: CreateKeyResultDto,
|
||||
@CurrentUser() user: JwtUser,
|
||||
) {
|
||||
return ok(await this.keyResultsService.create(dto, user));
|
||||
}
|
||||
|
||||
@Patch(':id/progress')
|
||||
async updateProgress(
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body(new ValidationPipe({ expectedType: UpdateProgressDto, whitelist: true, forbidNonWhitelisted: true, transform: true }))
|
||||
dto: UpdateProgressDto,
|
||||
@CurrentUser() user: JwtUser,
|
||||
) {
|
||||
return ok(await this.keyResultsService.updateProgress(id, dto, user));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../prisma/prisma.module.js';
|
||||
import { KeyResultsController } from './key-results.controller.js';
|
||||
import { KeyResultsService } from './key-results.service.js';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [KeyResultsController],
|
||||
providers: [KeyResultsService],
|
||||
})
|
||||
export class KeyResultsModule {}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { ForbiddenException, Inject, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import type { JwtUser } from '../common/auth.types.js';
|
||||
import { PrismaService } from '../prisma/prisma.service.js';
|
||||
import type { CreateKeyResultDto } from './dto/create-key-result.dto.js';
|
||||
import type { UpdateProgressDto } from './dto/update-progress.dto.js';
|
||||
|
||||
const keyResultInclude = {
|
||||
objective: {
|
||||
include: {
|
||||
owner: { select: { id: true, name: true, username: true, email: true, role: true } },
|
||||
},
|
||||
},
|
||||
} satisfies Prisma.KeyResultInclude;
|
||||
|
||||
export type KeyResultWithObjective = Prisma.KeyResultGetPayload<{ include: typeof keyResultInclude }>;
|
||||
|
||||
@Injectable()
|
||||
export class KeyResultsService {
|
||||
constructor(@Inject(PrismaService) private readonly prisma: PrismaService) {}
|
||||
|
||||
async getById(id: number, user: JwtUser): Promise<KeyResultWithObjective> {
|
||||
const keyResult = await this.prisma.keyResult.findUnique({ where: { id }, include: keyResultInclude });
|
||||
if (keyResult === null) {
|
||||
throw new NotFoundException('Key result not found');
|
||||
}
|
||||
this.assertCanRead(keyResult.objective.ownerId, user);
|
||||
return keyResult;
|
||||
}
|
||||
|
||||
async create(dto: CreateKeyResultDto, user: JwtUser): Promise<KeyResultWithObjective> {
|
||||
const objective = await this.prisma.objective.findUnique({ where: { id: dto.objectiveId } });
|
||||
if (objective === null) {
|
||||
throw new NotFoundException('Objective not found');
|
||||
}
|
||||
this.assertCanWrite(objective.ownerId, user);
|
||||
const keyResult = await this.prisma.keyResult.create({
|
||||
data: {
|
||||
objectiveId: dto.objectiveId,
|
||||
title: dto.title,
|
||||
progress: dto.progress,
|
||||
startValue: dto.startValue,
|
||||
targetValue: dto.targetValue,
|
||||
deadline: new Date(dto.deadline),
|
||||
},
|
||||
include: keyResultInclude,
|
||||
});
|
||||
await this.recalculateObjectiveStatus(dto.objectiveId);
|
||||
return keyResult;
|
||||
}
|
||||
|
||||
async updateProgress(id: number, dto: UpdateProgressDto, user: JwtUser): Promise<KeyResultWithObjective> {
|
||||
const existing = await this.prisma.keyResult.findUnique({ where: { id }, include: keyResultInclude });
|
||||
if (existing === null) {
|
||||
throw new NotFoundException('Key result not found');
|
||||
}
|
||||
this.assertCanWrite(existing.objective.ownerId, user);
|
||||
|
||||
const updated = await this.prisma.$transaction(async (tx) => {
|
||||
const keyResult = await tx.keyResult.update({
|
||||
where: { id },
|
||||
data: { progress: dto.progress },
|
||||
include: keyResultInclude,
|
||||
});
|
||||
await tx.progressUpdate.create({
|
||||
data: {
|
||||
keyResultId: id,
|
||||
progress: dto.progress,
|
||||
comment: dto.comment,
|
||||
createdById: user.sub,
|
||||
},
|
||||
});
|
||||
return keyResult;
|
||||
});
|
||||
await this.recalculateObjectiveStatus(existing.objectiveId);
|
||||
return updated;
|
||||
}
|
||||
|
||||
private assertCanRead(ownerId: number, user: JwtUser): void {
|
||||
if (user.role === 'EMPLOYEE' && ownerId !== user.sub) {
|
||||
throw new ForbiddenException('Key result belongs to another owner');
|
||||
}
|
||||
}
|
||||
|
||||
private assertCanWrite(ownerId: number, user: JwtUser): void {
|
||||
if (user.role === 'EMPLOYEE' && ownerId !== user.sub) {
|
||||
throw new ForbiddenException('Only the owner can update this key result');
|
||||
}
|
||||
}
|
||||
|
||||
private async recalculateObjectiveStatus(objectiveId: number): Promise<void> {
|
||||
const keyResults = await this.prisma.keyResult.findMany({ where: { objectiveId } });
|
||||
const average =
|
||||
keyResults.length === 0
|
||||
? 0
|
||||
: Math.round(keyResults.reduce((total, keyResult) => total + keyResult.progress, 0) / keyResults.length);
|
||||
const status =
|
||||
average === 0 ? 'NOT_STARTED' : average >= 100 ? 'COMPLETED' : 'IN_PROGRESS';
|
||||
await this.prisma.objective.update({ where: { id: objectiveId }, data: { status } });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import 'reflect-metadata';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module.js';
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
app.setGlobalPrefix('api/v1');
|
||||
const allowedOrigins = (process.env.FRONTEND_ORIGIN ?? 'http://localhost:5173,http://127.0.0.1:5173')
|
||||
.split(',')
|
||||
.map((origin) => origin.trim())
|
||||
.filter((origin) => origin.length > 0);
|
||||
app.enableCors({
|
||||
origin: allowedOrigins,
|
||||
credentials: true,
|
||||
});
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
}),
|
||||
);
|
||||
await app.listen(Number(process.env.PORT ?? 3000));
|
||||
}
|
||||
|
||||
void bootstrap();
|
||||
@@ -0,0 +1,19 @@
|
||||
import { IsInt, IsNotEmpty, IsOptional, IsPositive, IsString, Matches } from 'class-validator';
|
||||
|
||||
export class CreateObjectiveDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
title!: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@IsInt()
|
||||
@IsPositive()
|
||||
ownerId!: number;
|
||||
|
||||
@IsString()
|
||||
@Matches(/^Q[1-4]\/\d{4}$/)
|
||||
quarter!: string;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Body, Controller, Get, Inject, Param, ParseIntPipe, Post, Query, UseGuards, ValidationPipe } from '@nestjs/common';
|
||||
import { ok } from '../common/api-response.js';
|
||||
import { CurrentUser } from '../common/current-user.decorator.js';
|
||||
import type { JwtUser } from '../common/auth.types.js';
|
||||
import { JwtAuthGuard } from '../common/jwt-auth.guard.js';
|
||||
import { RolesGuard } from '../common/roles.guard.js';
|
||||
import { CreateObjectiveDto } from './dto/create-objective.dto.js';
|
||||
import { ObjectivesService } from './objectives.service.js';
|
||||
|
||||
@Controller('objectives')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
export class ObjectivesController {
|
||||
constructor(@Inject(ObjectivesService) private readonly objectivesService: ObjectivesService) {}
|
||||
|
||||
@Get()
|
||||
async list(@CurrentUser() user: JwtUser, @Query('quarter') quarter?: string) {
|
||||
const objectives = await this.objectivesService.list(user, quarter);
|
||||
return ok(objectives, { total: objectives.length });
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
async get(@Param('id', ParseIntPipe) id: number, @CurrentUser() user: JwtUser) {
|
||||
return ok(await this.objectivesService.getById(id, user));
|
||||
}
|
||||
|
||||
@Post()
|
||||
async create(
|
||||
@Body(new ValidationPipe({ expectedType: CreateObjectiveDto, whitelist: true, forbidNonWhitelisted: true, transform: true }))
|
||||
dto: CreateObjectiveDto,
|
||||
@CurrentUser() user: JwtUser,
|
||||
) {
|
||||
return ok(await this.objectivesService.create(dto, user));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../prisma/prisma.module.js';
|
||||
import { ObjectivesController } from './objectives.controller.js';
|
||||
import { ObjectivesService } from './objectives.service.js';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [ObjectivesController],
|
||||
providers: [ObjectivesService],
|
||||
exports: [ObjectivesService],
|
||||
})
|
||||
export class ObjectivesModule {}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { ForbiddenException, Inject, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import type { JwtUser } from '../common/auth.types.js';
|
||||
import { PrismaService } from '../prisma/prisma.service.js';
|
||||
import type { CreateObjectiveDto } from './dto/create-objective.dto.js';
|
||||
|
||||
const objectiveInclude = {
|
||||
owner: { select: { id: true, name: true, username: true, email: true, role: true } },
|
||||
keyResults: { orderBy: { id: 'asc' as const } },
|
||||
} satisfies Prisma.ObjectiveInclude;
|
||||
|
||||
export type ObjectiveWithRelations = Prisma.ObjectiveGetPayload<{ include: typeof objectiveInclude }>;
|
||||
|
||||
function averageProgress(keyResults: { progress: number }[]): number {
|
||||
if (keyResults.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
const total = keyResults.reduce((sum, keyResult) => sum + keyResult.progress, 0);
|
||||
return Math.round(total / keyResults.length);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ObjectivesService {
|
||||
constructor(@Inject(PrismaService) private readonly prisma: PrismaService) {}
|
||||
|
||||
async list(user: JwtUser, quarter?: string): Promise<ObjectiveWithRelations[]> {
|
||||
const where: Prisma.ObjectiveWhereInput = {
|
||||
...(quarter === undefined ? {} : { quarter }),
|
||||
...(user.role === 'EMPLOYEE' ? { ownerId: user.sub } : {}),
|
||||
};
|
||||
return this.prisma.objective.findMany({
|
||||
where,
|
||||
include: objectiveInclude,
|
||||
orderBy: { id: 'asc' },
|
||||
});
|
||||
}
|
||||
|
||||
async getById(id: number, user: JwtUser): Promise<ObjectiveWithRelations & { computedProgress: number }> {
|
||||
const objective = await this.prisma.objective.findUnique({ where: { id }, include: objectiveInclude });
|
||||
if (objective === null) {
|
||||
throw new NotFoundException('Objective not found');
|
||||
}
|
||||
if (user.role === 'EMPLOYEE' && objective.ownerId !== user.sub) {
|
||||
throw new ForbiddenException('Objective belongs to another owner');
|
||||
}
|
||||
return { ...objective, computedProgress: averageProgress(objective.keyResults) };
|
||||
}
|
||||
|
||||
async create(dto: CreateObjectiveDto, user: JwtUser): Promise<ObjectiveWithRelations> {
|
||||
if (user.role === 'EMPLOYEE' && dto.ownerId !== user.sub) {
|
||||
throw new ForbiddenException('Employees can create only their own objectives');
|
||||
}
|
||||
const owner = await this.prisma.user.findUnique({ where: { id: dto.ownerId } });
|
||||
if (owner === null) {
|
||||
throw new NotFoundException('Owner not found');
|
||||
}
|
||||
|
||||
return this.prisma.objective.create({
|
||||
data: {
|
||||
title: dto.title,
|
||||
description: dto.description,
|
||||
ownerId: dto.ownerId,
|
||||
quarter: dto.quarter,
|
||||
status: 'NOT_STARTED',
|
||||
},
|
||||
include: objectiveInclude,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaService } from './prisma.service.js';
|
||||
|
||||
@Module({
|
||||
providers: [PrismaService],
|
||||
exports: [PrismaService],
|
||||
})
|
||||
export class PrismaModule {}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
|
||||
async onModuleInit(): Promise<void> {
|
||||
await this.$connect();
|
||||
}
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
await this.$disconnect();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Controller, Get, Inject, UseGuards } from '@nestjs/common';
|
||||
import { ok } from '../common/api-response.js';
|
||||
import { JwtAuthGuard } from '../common/jwt-auth.guard.js';
|
||||
import { Roles } from '../common/roles.decorator.js';
|
||||
import { RolesGuard } from '../common/roles.guard.js';
|
||||
import { UsersService } from './users.service.js';
|
||||
|
||||
@Controller('users')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
export class UsersController {
|
||||
constructor(@Inject(UsersService) private readonly usersService: UsersService) {}
|
||||
|
||||
@Get()
|
||||
@Roles('ADMIN', 'MANAGER')
|
||||
async list() {
|
||||
return ok(await this.usersService.listUsers());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PrismaModule } from '../prisma/prisma.module.js';
|
||||
import { UsersController } from './users.controller.js';
|
||||
import { UsersService } from './users.service.js';
|
||||
|
||||
@Module({
|
||||
imports: [PrismaModule],
|
||||
controllers: [UsersController],
|
||||
providers: [UsersService],
|
||||
exports: [UsersService],
|
||||
})
|
||||
export class UsersModule {}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service.js';
|
||||
|
||||
export interface PublicUser {
|
||||
id: number;
|
||||
name: string;
|
||||
username: string;
|
||||
email: string;
|
||||
role: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
constructor(@Inject(PrismaService) private readonly prisma: PrismaService) {}
|
||||
|
||||
async listUsers(): Promise<PublicUser[]> {
|
||||
return this.prisma.user.findMany({
|
||||
orderBy: { id: 'asc' },
|
||||
select: { id: true, name: true, username: true, email: true, role: true },
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user