feat: updade workspace
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
# Generated at test time from schema.prisma (single source of truth)
|
||||
prisma/schema.sqlite.prisma
|
||||
# Local SQLite test database
|
||||
prisma/test.db
|
||||
prisma/test.db-journal
|
||||
test.db
|
||||
test.db-journal
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
# OKR backend container entrypoint for MySQL.
|
||||
# - Applies pending Prisma migrations (idempotent).
|
||||
# - Seeds initial data via upsert (safe to run on every start).
|
||||
set -e
|
||||
|
||||
export PATH="/app/node_modules/.bin:$PATH"
|
||||
|
||||
echo "[OKR] Applying database migrations..."
|
||||
npx prisma migrate deploy
|
||||
|
||||
echo "[OKR] Seeding database..."
|
||||
npx prisma db seed
|
||||
|
||||
echo "[OKR] Starting backend on port ${PORT:-3001}"
|
||||
exec node dist/main.js
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "@ainative-okr/backend",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "prisma generate && tsc -p tsconfig.build.json",
|
||||
"gen:sqlite-schema": "node scripts/make-sqlite-schema.mjs",
|
||||
"db:setup": "npm run gen:sqlite-schema && prisma generate --schema prisma/schema.sqlite.prisma && cross-env DATABASE_URL=file:./test.db prisma db push --schema prisma/schema.sqlite.prisma --force-reset --skip-generate --accept-data-loss",
|
||||
"dev": "prisma generate && tsx watch src/main.ts",
|
||||
"seed": "prisma db seed",
|
||||
"seed:test": "cross-env DATABASE_URL=file:./test.db JWT_SECRET=test-secret node --import tsx prisma/seed.ts",
|
||||
"test": "npm run db:setup && npm run seed:test && cross-env DATABASE_URL=file:./test.db JWT_SECRET=test-secret node --import tsx --test test/services.test.ts test/e2e.test.ts test/llm-judge.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@nestjs/common": "^10.4.20",
|
||||
"@nestjs/core": "^10.4.20",
|
||||
"@nestjs/jwt": "^10.2.0",
|
||||
"@nestjs/platform-express": "^10.4.20",
|
||||
"@prisma/client": "^6.19.3",
|
||||
"bcryptjs": "^3.0.2",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.2",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/testing": "^10.4.22",
|
||||
"@types/express": "^4.17.21",
|
||||
"@types/node": "^24.0.8",
|
||||
"@types/supertest": "^6.0.3",
|
||||
"cross-env": "^7.0.3",
|
||||
"prisma": "^6.19.3",
|
||||
"supertest": "^7.1.1",
|
||||
"tsx": "^4.20.3",
|
||||
"typescript": "^5.8.3"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "tsx prisma/seed.ts"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
-- MySQL initial schema for OKR application
|
||||
CREATE TABLE `User` (
|
||||
`id` INT NOT NULL AUTO_INCREMENT,
|
||||
`name` VARCHAR(191) NOT NULL,
|
||||
`username` VARCHAR(191) NOT NULL,
|
||||
`email` VARCHAR(191) NOT NULL,
|
||||
`passwordHash` VARCHAR(191) NOT NULL,
|
||||
`role` VARCHAR(191) NOT NULL,
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updatedAt` DATETIME(3) NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE INDEX `User_username_key`(`username`),
|
||||
UNIQUE INDEX `User_email_key`(`email`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `Objective` (
|
||||
`id` INT NOT NULL AUTO_INCREMENT,
|
||||
`title` VARCHAR(191) NOT NULL,
|
||||
`description` VARCHAR(191) NULL,
|
||||
`ownerId` INT NOT NULL,
|
||||
`quarter` VARCHAR(191) NOT NULL,
|
||||
`status` VARCHAR(191) NOT NULL DEFAULT 'NOT_STARTED',
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updatedAt` DATETIME(3) NOT NULL,
|
||||
INDEX `Objective_ownerId_idx`(`ownerId`),
|
||||
INDEX `Objective_quarter_idx`(`quarter`),
|
||||
INDEX `Objective_status_idx`(`status`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `KeyResult` (
|
||||
`id` INT NOT NULL AUTO_INCREMENT,
|
||||
`objectiveId` INT NOT NULL,
|
||||
`title` VARCHAR(191) NOT NULL,
|
||||
`progress` INT NOT NULL DEFAULT 0,
|
||||
`startValue` INT NOT NULL,
|
||||
`targetValue` INT NOT NULL,
|
||||
`deadline` DATETIME(3) NOT NULL,
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updatedAt` DATETIME(3) NOT NULL,
|
||||
INDEX `KeyResult_objectiveId_idx`(`objectiveId`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE `ProgressUpdate` (
|
||||
`id` INT NOT NULL AUTO_INCREMENT,
|
||||
`keyResultId` INT NOT NULL,
|
||||
`progress` INT NOT NULL,
|
||||
`comment` VARCHAR(191) NULL,
|
||||
`createdById` INT NOT NULL,
|
||||
`createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
ALTER TABLE `Objective` ADD CONSTRAINT `Objective_ownerId_fkey`
|
||||
FOREIGN KEY (`ownerId`) REFERENCES `User`(`id`)
|
||||
ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE `KeyResult` ADD CONSTRAINT `KeyResult_objectiveId_fkey`
|
||||
FOREIGN KEY (`objectiveId`) REFERENCES `Objective`(`id`)
|
||||
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE `ProgressUpdate` ADD CONSTRAINT `ProgressUpdate_keyResultId_fkey`
|
||||
FOREIGN KEY (`keyResultId`) REFERENCES `KeyResult`(`id`)
|
||||
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "mysql"
|
||||
@@ -0,0 +1,63 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "mysql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model User {
|
||||
id Int @id @default(autoincrement())
|
||||
name String
|
||||
username String @unique
|
||||
email String @unique
|
||||
passwordHash String
|
||||
role String
|
||||
objectives Objective[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
model Objective {
|
||||
id Int @id @default(autoincrement())
|
||||
title String
|
||||
description String?
|
||||
ownerId Int
|
||||
owner User @relation(fields: [ownerId], references: [id])
|
||||
quarter String
|
||||
status String @default("NOT_STARTED")
|
||||
keyResults KeyResult[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([ownerId])
|
||||
@@index([quarter])
|
||||
@@index([status])
|
||||
}
|
||||
|
||||
model KeyResult {
|
||||
id Int @id @default(autoincrement())
|
||||
objectiveId Int
|
||||
objective Objective @relation(fields: [objectiveId], references: [id], onDelete: Cascade)
|
||||
title String
|
||||
progress Int @default(0)
|
||||
startValue Int
|
||||
targetValue Int
|
||||
deadline DateTime
|
||||
updates ProgressUpdate[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@index([objectiveId])
|
||||
}
|
||||
|
||||
model ProgressUpdate {
|
||||
id Int @id @default(autoincrement())
|
||||
keyResultId Int
|
||||
keyResult KeyResult @relation(fields: [keyResultId], references: [id], onDelete: Cascade)
|
||||
progress Int
|
||||
comment String?
|
||||
createdById Int
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import bcrypt from 'bcryptjs';
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const passwordHash = await bcrypt.hash('Password@123', 12);
|
||||
|
||||
const admin = await prisma.user.upsert({
|
||||
where: { email: 'admin@okr.local' },
|
||||
update: { passwordHash },
|
||||
create: {
|
||||
name: 'System Admin',
|
||||
username: 'admin',
|
||||
email: 'admin@okr.local',
|
||||
passwordHash,
|
||||
role: 'ADMIN',
|
||||
},
|
||||
});
|
||||
|
||||
const manager = await prisma.user.upsert({
|
||||
where: { email: 'manager@okr.local' },
|
||||
update: { passwordHash },
|
||||
create: {
|
||||
name: 'Nguyen Van Manager',
|
||||
username: 'manager',
|
||||
email: 'manager@okr.local',
|
||||
passwordHash,
|
||||
role: 'MANAGER',
|
||||
},
|
||||
});
|
||||
|
||||
const employee = await prisma.user.upsert({
|
||||
where: { email: 'employee@okr.local' },
|
||||
update: { passwordHash },
|
||||
create: {
|
||||
name: 'Nguyen Van A',
|
||||
username: 'employee',
|
||||
email: 'employee@okr.local',
|
||||
passwordHash,
|
||||
role: 'EMPLOYEE',
|
||||
},
|
||||
});
|
||||
|
||||
const employeeTwo = await prisma.user.upsert({
|
||||
where: { email: 'employee2@okr.local' },
|
||||
update: { passwordHash },
|
||||
create: {
|
||||
name: 'Tran Thi B',
|
||||
username: 'employee2',
|
||||
email: 'employee2@okr.local',
|
||||
passwordHash,
|
||||
role: 'EMPLOYEE',
|
||||
},
|
||||
});
|
||||
|
||||
const securityObjective = await prisma.objective.upsert({
|
||||
where: { id: 1 },
|
||||
update: {
|
||||
ownerId: employee.id,
|
||||
title: 'POC AI for SQL Injection prevention',
|
||||
description: 'Evaluate AI tools for automated SQL injection detection.',
|
||||
quarter: 'Q2/2026',
|
||||
status: 'IN_PROGRESS',
|
||||
},
|
||||
create: {
|
||||
id: 1,
|
||||
ownerId: employee.id,
|
||||
title: 'POC AI for SQL Injection prevention',
|
||||
description: 'Evaluate AI tools for automated SQL injection detection.',
|
||||
quarter: 'Q2/2026',
|
||||
status: 'IN_PROGRESS',
|
||||
},
|
||||
});
|
||||
|
||||
const adoptionObjective = await prisma.objective.upsert({
|
||||
where: { id: 2 },
|
||||
update: {
|
||||
ownerId: employeeTwo.id,
|
||||
title: 'AI for All enablement across department',
|
||||
description: 'Train and certify department members on practical AI workflows.',
|
||||
quarter: 'Q2/2026',
|
||||
status: 'NOT_STARTED',
|
||||
},
|
||||
create: {
|
||||
id: 2,
|
||||
ownerId: employeeTwo.id,
|
||||
title: 'AI for All enablement across department',
|
||||
description: 'Train and certify department members on practical AI workflows.',
|
||||
quarter: 'Q2/2026',
|
||||
status: 'NOT_STARTED',
|
||||
},
|
||||
});
|
||||
|
||||
const managerObjective = await prisma.objective.upsert({
|
||||
where: { id: 3 },
|
||||
update: {
|
||||
ownerId: manager.id,
|
||||
title: 'Improve OKR operating cadence',
|
||||
description: 'Create weekly progress rhythm and reduce stale OKRs.',
|
||||
quarter: 'Q2/2026',
|
||||
status: 'IN_PROGRESS',
|
||||
},
|
||||
create: {
|
||||
id: 3,
|
||||
ownerId: manager.id,
|
||||
title: 'Improve OKR operating cadence',
|
||||
description: 'Create weekly progress rhythm and reduce stale OKRs.',
|
||||
quarter: 'Q2/2026',
|
||||
status: 'IN_PROGRESS',
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.keyResult.upsert({
|
||||
where: { id: 1 },
|
||||
update: { objectiveId: securityObjective.id, progress: 33 },
|
||||
create: {
|
||||
id: 1,
|
||||
objectiveId: securityObjective.id,
|
||||
title: 'Complete 3 POC sessions with security team',
|
||||
progress: 33,
|
||||
startValue: 0,
|
||||
targetValue: 3,
|
||||
deadline: new Date('2026-06-30T00:00:00.000Z'),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.keyResult.upsert({
|
||||
where: { id: 2 },
|
||||
update: { objectiveId: securityObjective.id, progress: 60 },
|
||||
create: {
|
||||
id: 2,
|
||||
objectiveId: securityObjective.id,
|
||||
title: 'Reduce manual SQL injection review effort by 30%',
|
||||
progress: 60,
|
||||
startValue: 0,
|
||||
targetValue: 30,
|
||||
deadline: new Date('2026-06-30T00:00:00.000Z'),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.keyResult.upsert({
|
||||
where: { id: 3 },
|
||||
update: { objectiveId: adoptionObjective.id, progress: 0 },
|
||||
create: {
|
||||
id: 3,
|
||||
objectiveId: adoptionObjective.id,
|
||||
title: 'Certify 100 department members on AI for All',
|
||||
progress: 0,
|
||||
startValue: 0,
|
||||
targetValue: 100,
|
||||
deadline: new Date('2026-06-30T00:00:00.000Z'),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.keyResult.upsert({
|
||||
where: { id: 4 },
|
||||
update: { objectiveId: managerObjective.id, progress: 75 },
|
||||
create: {
|
||||
id: 4,
|
||||
objectiveId: managerObjective.id,
|
||||
title: 'Reach 90% weekly OKR update compliance',
|
||||
progress: 75,
|
||||
startValue: 40,
|
||||
targetValue: 90,
|
||||
deadline: new Date('2026-06-30T00:00:00.000Z'),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.keyResult.upsert({
|
||||
where: { id: 5 },
|
||||
update: { objectiveId: managerObjective.id, progress: 45 },
|
||||
create: {
|
||||
id: 5,
|
||||
objectiveId: managerObjective.id,
|
||||
title: 'Resolve stale OKR reports within two business days',
|
||||
progress: 45,
|
||||
startValue: 0,
|
||||
targetValue: 10,
|
||||
deadline: new Date('2026-06-30T00:00:00.000Z'),
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.progressUpdate.deleteMany({ where: { keyResultId: { in: [1, 2, 3, 4, 5] } } });
|
||||
await prisma.progressUpdate.create({
|
||||
data: {
|
||||
keyResultId: 2,
|
||||
progress: 60,
|
||||
comment: 'Two review workflows automated; third is in validation.',
|
||||
createdById: employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
void admin;
|
||||
console.log('Seed completed successfully.');
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
// Generates prisma/schema.sqlite.prisma from the canonical schema.prisma by
|
||||
// swapping only the datasource provider to sqlite. Keeping a single source of
|
||||
// truth for the models avoids drift; the sqlite schema is used for local tests
|
||||
// (PrismaClient with a mysql provider cannot use a `file:` URL).
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const src = resolve('prisma/schema.prisma');
|
||||
const dest = resolve('prisma/schema.sqlite.prisma');
|
||||
|
||||
const original = readFileSync(src, 'utf8');
|
||||
if (!/provider\s*=\s*"mysql"/.test(original)) {
|
||||
throw new Error('Expected datasource provider "mysql" in schema.prisma');
|
||||
}
|
||||
const sqlite = original.replace(/provider\s*=\s*"mysql"/, 'provider = "sqlite"');
|
||||
const banner = '// AUTO-GENERATED from schema.prisma by scripts/make-sqlite-schema.mjs — do not edit.\n';
|
||||
writeFileSync(dest, banner + sqlite);
|
||||
console.log(`Wrote ${dest} (sqlite provider) from schema.prisma`);
|
||||
@@ -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 'bcryptjs';
|
||||
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 },
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import request from 'supertest';
|
||||
import { createTestApp, loginToken } from './helpers.js';
|
||||
|
||||
// ─── Auth guard ───────────────────────────────────────────────────────────────
|
||||
|
||||
test('unauthenticated requests are rejected with 401', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
await request(app.getHttpServer()).get('/api/v1/objectives').expect(401);
|
||||
await request(app.getHttpServer()).get('/api/v1/objectives/1').expect(401);
|
||||
await request(app.getHttpServer()).get('/api/v1/key-results/1').expect(401);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
// ─── GET /objectives (list) ───────────────────────────────────────────────────
|
||||
|
||||
test('GET /objectives employee sees only own objectives', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
assert.equal(res.body.success, true);
|
||||
assert.ok(Array.isArray(res.body.data));
|
||||
// Every returned objective must belong to employee (id=3)
|
||||
assert.ok(res.body.data.every((o: { ownerId: number }) => o.ownerId === 3));
|
||||
assert.equal(res.body.meta.total, res.body.data.length);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('GET /objectives manager sees all objectives', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const managerToken = await loginToken(app, 'manager');
|
||||
const employeeToken = await loginToken(app, 'employee');
|
||||
const managerRes = await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives')
|
||||
.set('Authorization', `Bearer ${managerToken}`)
|
||||
.expect(200);
|
||||
const employeeRes = await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives')
|
||||
.set('Authorization', `Bearer ${employeeToken}`)
|
||||
.expect(200);
|
||||
assert.ok(managerRes.body.data.length > employeeRes.body.data.length);
|
||||
assert.equal(managerRes.body.data.length, 3);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('GET /objectives?quarter= filters to matching quarter only', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'manager');
|
||||
const matching = await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives?quarter=Q2/2026')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
const empty = await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives?quarter=Q1/1900')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
assert.ok(matching.body.data.every((o: { quarter: string }) => o.quarter === 'Q2/2026'));
|
||||
assert.equal(empty.body.data.length, 0);
|
||||
assert.equal(empty.body.meta.total, 0);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
// ─── GET /objectives/:id ──────────────────────────────────────────────────────
|
||||
|
||||
test('GET /objectives/:id returns objective with computedProgress and relations', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'manager');
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives/1')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
const data = res.body.data;
|
||||
assert.equal(data.id, 1);
|
||||
assert.equal(typeof data.computedProgress, 'number');
|
||||
// KR1=33, KR2=60 → avg = Math.round(46.5) = 47
|
||||
assert.equal(data.computedProgress, 47);
|
||||
assert.ok(data.owner !== undefined);
|
||||
assert.ok(Array.isArray(data.keyResults));
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('GET /objectives/:id returns 404 for non-existent objective', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'manager');
|
||||
await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives/999999')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(404);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('GET /objectives/:id returns 403 when employee accesses another owner objective', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
// Objective 3 belongs to manager (id=2), not employee (id=3)
|
||||
await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives/3')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(403);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
// ─── POST /objectives ─────────────────────────────────────────────────────────
|
||||
|
||||
test('POST /objectives returns 400 for empty title', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/v1/objectives')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ title: '', ownerId: 3, quarter: 'Q1/2026' })
|
||||
.expect(400);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('POST /objectives returns 400 for invalid quarter format', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
// DTO requires Q[1-4]/YYYY format
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/v1/objectives')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ title: 'Valid title', ownerId: 3, quarter: '2026-Q2' })
|
||||
.expect(400);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('POST /objectives manager creates objective and receives it with NOT_STARTED status', async () => {
|
||||
const { app, prisma } = await createTestApp();
|
||||
let createdId: number | undefined;
|
||||
try {
|
||||
const token = await loginToken(app, 'manager');
|
||||
const res = await request(app.getHttpServer())
|
||||
.post('/api/v1/objectives')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ title: 'E2E created objective', ownerId: 3, quarter: 'Q1/2099' })
|
||||
.expect(201);
|
||||
createdId = res.body.data.id;
|
||||
assert.equal(res.body.data.status, 'NOT_STARTED');
|
||||
assert.equal(res.body.data.ownerId, 3);
|
||||
assert.ok(typeof createdId === 'number');
|
||||
} finally {
|
||||
if (createdId) await prisma.objective.delete({ where: { id: createdId } });
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('POST /objectives returns 403 when employee creates for another user', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
// employee (id=3) trying to create objective for employee2 (id=4)
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/v1/objectives')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ title: 'Sneaky objective', ownerId: 4, quarter: 'Q1/2099' })
|
||||
.expect(403);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('POST /objectives returns 404 for non-existent owner', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'manager');
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/v1/objectives')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ title: 'Ghost owner objective', ownerId: 999999, quarter: 'Q1/2099' })
|
||||
.expect(404);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
// ─── GET /key-results/:id ─────────────────────────────────────────────────────
|
||||
|
||||
test('GET /key-results/:id returns KR with nested objective', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/v1/key-results/1')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
assert.equal(res.body.success, true);
|
||||
assert.equal(res.body.data.id, 1);
|
||||
assert.ok(res.body.data.objective !== undefined);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('GET /key-results/:id returns 404 for non-existent KR', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'manager');
|
||||
await request(app.getHttpServer())
|
||||
.get('/api/v1/key-results/999999')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(404);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('GET /key-results/:id returns 403 when employee reads another owner KR', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
// KR 3 belongs to objective 2 (ownerId=employee2/id=4)
|
||||
await request(app.getHttpServer())
|
||||
.get('/api/v1/key-results/3')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(403);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
// ─── POST /key-results ────────────────────────────────────────────────────────
|
||||
|
||||
test('POST /key-results employee creates KR on own objective', async () => {
|
||||
const { app, prisma } = await createTestApp();
|
||||
let createdId: number | undefined;
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
const res = await request(app.getHttpServer())
|
||||
.post('/api/v1/key-results')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({
|
||||
objectiveId: 1,
|
||||
title: 'E2E created key result',
|
||||
progress: 0,
|
||||
startValue: 0,
|
||||
targetValue: 5,
|
||||
deadline: '2099-12-31',
|
||||
})
|
||||
.expect(201);
|
||||
createdId = res.body.data.id;
|
||||
assert.equal(res.body.data.progress, 0);
|
||||
assert.equal(res.body.data.objectiveId, 1);
|
||||
} finally {
|
||||
if (createdId) await prisma.keyResult.delete({ where: { id: createdId } });
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('POST /key-results returns 403 when employee creates KR on another owner objective', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
// Objective 3 belongs to manager (id=2)
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/v1/key-results')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({
|
||||
objectiveId: 3,
|
||||
title: 'Sneaky KR',
|
||||
progress: 0,
|
||||
startValue: 0,
|
||||
targetValue: 1,
|
||||
deadline: '2099-12-31',
|
||||
})
|
||||
.expect(403);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
// ─── PATCH /key-results/:id/progress ─────────────────────────────────────────
|
||||
|
||||
test('PATCH /key-results/:id/progress updates progress and returns updated KR', async () => {
|
||||
const { app, prisma } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
const res = await request(app.getHttpServer())
|
||||
.patch('/api/v1/key-results/2/progress')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ progress: 70, comment: 'E2E progress update' })
|
||||
.expect(200);
|
||||
assert.equal(res.body.data.progress, 70);
|
||||
} finally {
|
||||
await prisma.keyResult.update({ where: { id: 2 }, data: { progress: 60 } });
|
||||
await prisma.progressUpdate.deleteMany({ where: { keyResultId: 2, progress: 70 } });
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('PATCH /key-results/:id/progress returns 400 for out-of-range values', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
await request(app.getHttpServer())
|
||||
.patch('/api/v1/key-results/1/progress')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ progress: -1 })
|
||||
.expect(400);
|
||||
await request(app.getHttpServer())
|
||||
.patch('/api/v1/key-results/1/progress')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ progress: 101 })
|
||||
.expect(400);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('PATCH /key-results/:id/progress returns 403 when employee updates another owner KR', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
// KR 3 belongs to employee2's objective
|
||||
await request(app.getHttpServer())
|
||||
.patch('/api/v1/key-results/3/progress')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ progress: 50 })
|
||||
.expect(403);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('PATCH /key-results/:id/progress returns 404 for non-existent KR', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'manager');
|
||||
await request(app.getHttpServer())
|
||||
.patch('/api/v1/key-results/999999/progress')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.send({ progress: 50 })
|
||||
.expect(404);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Golden regression ────────────────────────────────────────────────────────
|
||||
|
||||
test('golden: manager objective list does not drift', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'manager');
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
const canonical = JSON.stringify(
|
||||
{
|
||||
success: response.body.success,
|
||||
data: response.body.data.map((o: { id: number; title: string; quarter: string; status: string; keyResults: { id: number; title: string; progress: number }[] }) => ({
|
||||
id: o.id,
|
||||
title: o.title,
|
||||
quarter: o.quarter,
|
||||
status: o.status,
|
||||
keyResults: o.keyResults.map((kr) => ({ id: kr.id, title: kr.title, progress: kr.progress })),
|
||||
})),
|
||||
meta: response.body.meta,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
const fixture = await fs.readFile(path.resolve('test/golden/objectives.manager.json'), 'utf8');
|
||||
assert.equal(`${canonical}\n`, fixture, 'Manager objective list response drifted from golden fixture');
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('golden: employee objective list does not drift', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
const canonical = JSON.stringify(
|
||||
{
|
||||
success: response.body.success,
|
||||
data: response.body.data.map((o: { id: number; title: string; quarter: string; status: string; keyResults: { id: number; title: string; progress: number }[] }) => ({
|
||||
id: o.id,
|
||||
title: o.title,
|
||||
quarter: o.quarter,
|
||||
status: o.status,
|
||||
keyResults: o.keyResults.map((kr) => ({ id: kr.id, title: kr.title, progress: kr.progress })),
|
||||
})),
|
||||
meta: response.body.meta,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
const fixture = await fs.readFile(path.resolve('test/golden/objectives.employee.json'), 'utf8');
|
||||
assert.equal(`${canonical}\n`, fixture, 'Employee objective list response drifted from golden fixture');
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('golden: objective detail (GET /objectives/1) does not drift', async () => {
|
||||
const { app } = await createTestApp();
|
||||
try {
|
||||
const token = await loginToken(app, 'manager');
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives/1')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
const data = response.body.data;
|
||||
const canonical = JSON.stringify(
|
||||
{
|
||||
success: response.body.success,
|
||||
data: {
|
||||
id: data.id,
|
||||
title: data.title,
|
||||
quarter: data.quarter,
|
||||
status: data.status,
|
||||
computedProgress: data.computedProgress,
|
||||
keyResults: data.keyResults.map((kr: { id: number; title: string; progress: number }) => ({
|
||||
id: kr.id,
|
||||
title: kr.title,
|
||||
progress: kr.progress,
|
||||
})),
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
const fixture = await fs.readFile(path.resolve('test/golden/objective-detail.json'), 'utf8');
|
||||
assert.equal(`${canonical}\n`, fixture, 'Objective detail response drifted from golden fixture');
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"id": 1,
|
||||
"title": "POC AI for SQL Injection prevention",
|
||||
"quarter": "Q2/2026",
|
||||
"status": "IN_PROGRESS",
|
||||
"computedProgress": 47,
|
||||
"keyResults": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Complete 3 POC sessions with security team",
|
||||
"progress": 33
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "Reduce manual SQL injection review effort by 30%",
|
||||
"progress": 60
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"success": true,
|
||||
"data": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "POC AI for SQL Injection prevention",
|
||||
"quarter": "Q2/2026",
|
||||
"status": "IN_PROGRESS",
|
||||
"keyResults": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Complete 3 POC sessions with security team",
|
||||
"progress": 33
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "Reduce manual SQL injection review effort by 30%",
|
||||
"progress": 60
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"total": 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
{
|
||||
"success": true,
|
||||
"data": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "POC AI for SQL Injection prevention",
|
||||
"quarter": "Q2/2026",
|
||||
"status": "IN_PROGRESS",
|
||||
"keyResults": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Complete 3 POC sessions with security team",
|
||||
"progress": 33
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "Reduce manual SQL injection review effort by 30%",
|
||||
"progress": 60
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "AI for All enablement across department",
|
||||
"quarter": "Q2/2026",
|
||||
"status": "NOT_STARTED",
|
||||
"keyResults": [
|
||||
{
|
||||
"id": 3,
|
||||
"title": "Certify 100 department members on AI for All",
|
||||
"progress": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "Improve OKR operating cadence",
|
||||
"quarter": "Q2/2026",
|
||||
"status": "IN_PROGRESS",
|
||||
"keyResults": [
|
||||
{
|
||||
"id": 4,
|
||||
"title": "Reach 90% weekly OKR update compliance",
|
||||
"progress": 75
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Resolve stale OKR reports within two business days",
|
||||
"progress": 45
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"meta": {
|
||||
"total": 3
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import { PrismaService } from '../src/prisma/prisma.service.js';
|
||||
import { AppModule } from '../src/app.module.js';
|
||||
|
||||
export async function createTestApp(): Promise<{ app: INestApplication; prisma: PrismaService }> {
|
||||
const moduleRef = await Test.createTestingModule({ imports: [AppModule] }).compile();
|
||||
const app = moduleRef.createNestApplication();
|
||||
app.setGlobalPrefix('api/v1');
|
||||
app.useGlobalPipes(
|
||||
new ValidationPipe({
|
||||
whitelist: true,
|
||||
forbidNonWhitelisted: true,
|
||||
transform: true,
|
||||
}),
|
||||
);
|
||||
await app.init();
|
||||
return { app, prisma: app.get(PrismaService) };
|
||||
}
|
||||
|
||||
export async function loginToken(app: INestApplication, username = 'employee'): Promise<string> {
|
||||
const request = await import('supertest');
|
||||
const response = await request
|
||||
.default(app.getHttpServer())
|
||||
.post('/api/v1/auth/login')
|
||||
.send({ username, password: 'Password@123' })
|
||||
.expect(201);
|
||||
return response.body.data.token as string;
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* LLM-judge gate: sends live API responses to Claude and fails if the model
|
||||
* returns REJECTED. This catches semantic breakage that structural assertions miss
|
||||
* (e.g. scrambled titles, impossible status/progress combinations, data leakage).
|
||||
*
|
||||
* Requires ANTHROPIC_API_KEY to be set. The test is skipped — not failed — when
|
||||
* the key is absent, so local dev without a key still passes CI.
|
||||
*
|
||||
* REJECTED→fix cycle:
|
||||
* 1. CI logs the judge verdict and reason.
|
||||
* 2. Developer reads the reason, fixes the business logic or seed data.
|
||||
* 3. CI re-runs; the judge issues ACCEPTED once invariants are restored.
|
||||
*/
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import request from 'supertest';
|
||||
import { createTestApp, loginToken } from './helpers.js';
|
||||
|
||||
const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
|
||||
const JUDGE_MODEL = 'claude-haiku-4-5-20251001';
|
||||
|
||||
interface JudgeVerdict {
|
||||
verdict: 'ACCEPTED' | 'REJECTED';
|
||||
reason: string;
|
||||
}
|
||||
|
||||
async function callLlmJudge(prompt: string): Promise<JudgeVerdict> {
|
||||
const response = await fetch('https://api.anthropic.com/v1/messages', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'x-api-key': ANTHROPIC_API_KEY!,
|
||||
'anthropic-version': '2023-06-01',
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: JUDGE_MODEL,
|
||||
max_tokens: 512,
|
||||
temperature: 0,
|
||||
messages: [{ role: 'user', content: prompt }],
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const body = await response.text();
|
||||
throw new Error(`Anthropic API error ${response.status}: ${body}`);
|
||||
}
|
||||
|
||||
const result = await response.json() as { content: Array<{ type: string; text: string }> };
|
||||
const text = result.content.find((c) => c.type === 'text')?.text ?? '';
|
||||
|
||||
// Extract JSON object from the model response (model may wrap it in prose)
|
||||
const match = text.match(/\{[\s\S]*"verdict"[\s\S]*\}/);
|
||||
if (!match) {
|
||||
throw new Error(`LLM judge returned unparseable response:\n${text}`);
|
||||
}
|
||||
return JSON.parse(match[0]) as JudgeVerdict;
|
||||
}
|
||||
|
||||
function buildJudgePrompt(label: string, responseJson: unknown): string {
|
||||
const serialized = JSON.stringify(responseJson, null, 2);
|
||||
return `You are a strict quality gate for an OKR (Objectives and Key Results) management API.
|
||||
|
||||
Evaluate the API response below for the endpoint: ${label}
|
||||
|
||||
Check ALL of the following invariants:
|
||||
1. \`success\` field is exactly boolean \`true\`.
|
||||
2. \`data\` exists and is a non-empty array (for list endpoints) or a non-null object (for detail endpoints).
|
||||
3. For list responses: \`meta.total\` equals \`data.length\`.
|
||||
4. Each objective has: id (positive integer), title (non-empty string), quarter (format Q[1-4]/YYYY), status (one of NOT_STARTED, IN_PROGRESS, COMPLETED), keyResults (array).
|
||||
5. Each keyResult has: id (positive integer), title (non-empty string), progress (integer 0-100 inclusive).
|
||||
6. Status-progress invariant — for each objective:
|
||||
- If ALL keyResults have progress === 0 → status MUST be NOT_STARTED.
|
||||
- If ALL keyResults have progress === 100 → status MUST be COMPLETED.
|
||||
- Otherwise → status MUST be IN_PROGRESS.
|
||||
7. Titles must NOT contain placeholder or test noise (e.g. "undefined", "null", "TODO", "string", "untitled", "test objective").
|
||||
|
||||
API response:
|
||||
\`\`\`json
|
||||
${serialized}
|
||||
\`\`\`
|
||||
|
||||
Respond with a JSON object ONLY — no prose before or after:
|
||||
{"verdict": "ACCEPTED" or "REJECTED", "reason": "<one sentence explaining pass or the first failing invariant>"}`;
|
||||
}
|
||||
|
||||
// Skip gracefully when the API key is absent
|
||||
const skip = !ANTHROPIC_API_KEY && 'Set ANTHROPIC_API_KEY to enable the LLM-judge gate';
|
||||
|
||||
test(
|
||||
'LLM judge: manager objective list passes all semantic invariants',
|
||||
{ skip },
|
||||
async () => {
|
||||
const { app } = await createTestApp();
|
||||
let verdict: JudgeVerdict;
|
||||
try {
|
||||
const token = await loginToken(app, 'manager');
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
|
||||
verdict = await callLlmJudge('GET /api/v1/objectives (manager)', res.body);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
|
||||
if (verdict!.verdict === 'REJECTED') {
|
||||
assert.fail(`LLM judge REJECTED manager objective list: ${verdict!.reason}`);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'LLM judge: employee objective list passes all semantic invariants',
|
||||
{ skip },
|
||||
async () => {
|
||||
const { app } = await createTestApp();
|
||||
let verdict: JudgeVerdict;
|
||||
try {
|
||||
const token = await loginToken(app, 'employee');
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
|
||||
verdict = await callLlmJudge('GET /api/v1/objectives (employee)', res.body);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
|
||||
if (verdict!.verdict === 'REJECTED') {
|
||||
assert.fail(`LLM judge REJECTED employee objective list: ${verdict!.reason}`);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'LLM judge: objective detail passes all semantic invariants',
|
||||
{ skip },
|
||||
async () => {
|
||||
const { app } = await createTestApp();
|
||||
let verdict: JudgeVerdict;
|
||||
try {
|
||||
const token = await loginToken(app, 'manager');
|
||||
const res = await request(app.getHttpServer())
|
||||
.get('/api/v1/objectives/1')
|
||||
.set('Authorization', `Bearer ${token}`)
|
||||
.expect(200);
|
||||
|
||||
// Normalize: present as a single-item list so the judge uses the same invariant set
|
||||
const normalized = {
|
||||
success: res.body.success,
|
||||
data: [res.body.data],
|
||||
meta: { total: 1 },
|
||||
};
|
||||
verdict = await callLlmJudge('GET /api/v1/objectives/1 (detail, normalized to list form)', normalized);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
|
||||
if (verdict!.verdict === 'REJECTED') {
|
||||
assert.fail(`LLM judge REJECTED objective detail: ${verdict!.reason}`);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,403 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ForbiddenException, NotFoundException, UnauthorizedException } from '@nestjs/common';
|
||||
import { AuthService } from '../src/auth/auth.service.js';
|
||||
import type { JwtUser } from '../src/common/auth.types.js';
|
||||
import { KeyResultsService } from '../src/key-results/key-results.service.js';
|
||||
import { ObjectivesService } from '../src/objectives/objectives.service.js';
|
||||
import { PrismaService } from '../src/prisma/prisma.service.js';
|
||||
|
||||
// Seeded user identities (from prisma/seed.ts insertion order)
|
||||
const managerUser: JwtUser = { sub: 2, email: 'manager@okr.local', role: 'MANAGER', name: 'Nguyen Van Manager' };
|
||||
const employeeUser: JwtUser = { sub: 3, email: 'employee@okr.local', role: 'EMPLOYEE', name: 'Nguyen Van A' };
|
||||
const employee2User: JwtUser = { sub: 4, email: 'employee2@okr.local', role: 'EMPLOYEE', name: 'Tran Thi B' };
|
||||
|
||||
// ─── Auth ───────────────────────────────────────────────────────────────────
|
||||
|
||||
test('AuthService rejects invalid password with UnauthorizedException', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new AuthService(prisma, new JwtService({ secret: 'test-secret' }));
|
||||
try {
|
||||
await assert.rejects(() => service.login('employee', 'wrong-password'), UnauthorizedException);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('AuthService rejects non-existent user with UnauthorizedException', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new AuthService(prisma, new JwtService({ secret: 'test-secret' }));
|
||||
try {
|
||||
await assert.rejects(() => service.login('nobody@ghost.local', 'Password@123'), UnauthorizedException);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('AuthService accepts correct credentials and returns signed JWT', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new AuthService(prisma, new JwtService({ secret: 'test-secret' }));
|
||||
try {
|
||||
const result = await service.login('employee', 'Password@123');
|
||||
assert.equal(result.user.email, 'employee@okr.local');
|
||||
assert.equal(result.user.role, 'EMPLOYEE');
|
||||
assert.ok(result.token.length > 20, 'JWT must be non-trivially long');
|
||||
// Token has 3 dot-separated segments
|
||||
assert.equal(result.token.split('.').length, 3);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('AuthService accepts login by email as well as username', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new AuthService(prisma, new JwtService({ secret: 'test-secret' }));
|
||||
try {
|
||||
const byUsername = await service.login('manager', 'Password@123');
|
||||
const byEmail = await service.login('manager@okr.local', 'Password@123');
|
||||
assert.equal(byUsername.user.id, byEmail.user.id);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
// ─── ObjectivesService.list ──────────────────────────────────────────────────
|
||||
|
||||
test('ObjectivesService.list employee sees only own objectives', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new ObjectivesService(prisma);
|
||||
try {
|
||||
const results = await service.list(employeeUser);
|
||||
assert.ok(results.length > 0, 'Employee must have at least one objective');
|
||||
assert.ok(
|
||||
results.every((o) => o.ownerId === employeeUser.sub),
|
||||
'Every returned objective must belong to the employee',
|
||||
);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('ObjectivesService.list manager sees all objectives', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new ObjectivesService(prisma);
|
||||
try {
|
||||
const managerResults = await service.list(managerUser);
|
||||
const employeeResults = await service.list(employeeUser);
|
||||
assert.ok(managerResults.length > employeeResults.length, 'Manager must see more objectives than employee');
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('ObjectivesService.list quarter filter narrows results to matching quarter only', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new ObjectivesService(prisma);
|
||||
try {
|
||||
const all = await service.list(managerUser);
|
||||
const filtered = await service.list(managerUser, 'Q2/2026');
|
||||
const empty = await service.list(managerUser, 'Q1/1900');
|
||||
|
||||
assert.ok(filtered.length <= all.length);
|
||||
assert.ok(filtered.every((o) => o.quarter === 'Q2/2026'), 'All filtered results must match the requested quarter');
|
||||
assert.equal(empty.length, 0, 'No objectives should match a future non-existent quarter');
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
// ─── ObjectivesService.getById ───────────────────────────────────────────────
|
||||
|
||||
test('ObjectivesService.getById returns objective with computedProgress', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new ObjectivesService(prisma);
|
||||
try {
|
||||
// Objective 1: KR1=33, KR2=60 → avg = Math.round((33+60)/2) = 47
|
||||
const result = await service.getById(1, managerUser);
|
||||
assert.equal(result.id, 1);
|
||||
assert.equal(result.computedProgress, 47);
|
||||
assert.ok(result.keyResults.length === 2);
|
||||
assert.ok(result.owner !== undefined, 'Owner relation must be loaded');
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('ObjectivesService.getById employee accessing own objective succeeds', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new ObjectivesService(prisma);
|
||||
try {
|
||||
// Objective 1 is owned by employee (id=3)
|
||||
const result = await service.getById(1, employeeUser);
|
||||
assert.equal(result.ownerId, employeeUser.sub);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('ObjectivesService.getById employee accessing another user objective throws ForbiddenException', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new ObjectivesService(prisma);
|
||||
try {
|
||||
// Objective 3 belongs to manager (id=2), not employee (id=3)
|
||||
await assert.rejects(() => service.getById(3, employeeUser), ForbiddenException);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('ObjectivesService.getById non-existent id throws NotFoundException', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new ObjectivesService(prisma);
|
||||
try {
|
||||
await assert.rejects(() => service.getById(999999, managerUser), NotFoundException);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
// ─── ObjectivesService.create ────────────────────────────────────────────────
|
||||
|
||||
test('ObjectivesService.create sets status to NOT_STARTED and loads relations', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new ObjectivesService(prisma);
|
||||
let createdId: number | undefined;
|
||||
try {
|
||||
const result = await service.create(
|
||||
{ title: 'Test objective for create', ownerId: employeeUser.sub, quarter: 'Q1/2099' },
|
||||
managerUser,
|
||||
);
|
||||
createdId = result.id;
|
||||
assert.equal(result.status, 'NOT_STARTED');
|
||||
assert.equal(result.ownerId, employeeUser.sub);
|
||||
assert.equal(result.quarter, 'Q1/2099');
|
||||
assert.ok(result.owner !== undefined, 'Owner relation must be eagerly loaded');
|
||||
assert.deepEqual(result.keyResults, [], 'New objective must have no key results');
|
||||
} finally {
|
||||
if (createdId) await prisma.objective.delete({ where: { id: createdId } });
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('ObjectivesService.create employee creating for another user throws ForbiddenException', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new ObjectivesService(prisma);
|
||||
try {
|
||||
await assert.rejects(
|
||||
() =>
|
||||
service.create(
|
||||
{ title: 'Sneaky objective', ownerId: employee2User.sub, quarter: 'Q1/2099' },
|
||||
employeeUser,
|
||||
),
|
||||
ForbiddenException,
|
||||
);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('ObjectivesService.create with non-existent owner throws NotFoundException', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new ObjectivesService(prisma);
|
||||
try {
|
||||
await assert.rejects(
|
||||
() => service.create({ title: 'Ghost objective', ownerId: 999999, quarter: 'Q1/2099' }, managerUser),
|
||||
NotFoundException,
|
||||
);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
// ─── KeyResultsService.getById ───────────────────────────────────────────────
|
||||
|
||||
test('KeyResultsService.getById returns KR with nested objective and owner', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new KeyResultsService(prisma);
|
||||
try {
|
||||
// KR 1 belongs to objective 1 which is owned by employee
|
||||
const result = await service.getById(1, employeeUser);
|
||||
assert.equal(result.id, 1);
|
||||
assert.ok(typeof result.progress === 'number');
|
||||
assert.ok(result.objective !== undefined, 'Objective relation must be loaded');
|
||||
assert.ok(result.objective.owner !== undefined, 'Owner relation must be loaded inside objective');
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('KeyResultsService.getById employee reading another owner KR throws ForbiddenException', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new KeyResultsService(prisma);
|
||||
try {
|
||||
// KR 3 belongs to objective 2 (ownerId=employee2/id=4), not employee (id=3)
|
||||
await assert.rejects(() => service.getById(3, employeeUser), ForbiddenException);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('KeyResultsService.getById non-existent id throws NotFoundException', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new KeyResultsService(prisma);
|
||||
try {
|
||||
await assert.rejects(() => service.getById(999999, managerUser), NotFoundException);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
// ─── KeyResultsService.updateProgress ────────────────────────────────────────
|
||||
|
||||
test('KeyResultsService.updateProgress blocks employee updating KR from another owner', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new KeyResultsService(prisma);
|
||||
try {
|
||||
// KR 3 belongs to employee2's objective — employee cannot update it
|
||||
await assert.rejects(
|
||||
() => service.updateProgress(3, { progress: 50, comment: 'Not mine' }, employeeUser),
|
||||
ForbiddenException,
|
||||
);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('KeyResultsService.updateProgress records new progress value and creates ProgressUpdate', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new KeyResultsService(prisma);
|
||||
try {
|
||||
const updated = await service.updateProgress(1, { progress: 100, comment: 'Completed KR' }, employeeUser);
|
||||
assert.equal(updated.progress, 100);
|
||||
const progressUpdates = await prisma.progressUpdate.findMany({ where: { keyResultId: 1, progress: 100 } });
|
||||
assert.ok(progressUpdates.length > 0, 'A ProgressUpdate record must be created');
|
||||
} finally {
|
||||
await prisma.keyResult.update({ where: { id: 1 }, data: { progress: 33 } });
|
||||
await prisma.progressUpdate.deleteMany({ where: { keyResultId: 1 } });
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('KeyResultsService.updateProgress non-existent KR throws NotFoundException', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new KeyResultsService(prisma);
|
||||
try {
|
||||
await assert.rejects(
|
||||
() => service.updateProgress(999999, { progress: 50, comment: 'ghost' }, managerUser),
|
||||
NotFoundException,
|
||||
);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Status recalculation (full NOT_STARTED → IN_PROGRESS → COMPLETED cycle) ─
|
||||
|
||||
test('KeyResultsService status recalculation: NOT_STARTED → IN_PROGRESS → COMPLETED → IN_PROGRESS', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new KeyResultsService(prisma);
|
||||
let testObjectiveId: number | undefined;
|
||||
let testKrId: number | undefined;
|
||||
try {
|
||||
// Create isolated objective + KR owned by employee
|
||||
const obj = await prisma.objective.create({
|
||||
data: { title: 'status-cycle-test', ownerId: employeeUser.sub, quarter: 'Q4/2099', status: 'NOT_STARTED' },
|
||||
});
|
||||
testObjectiveId = obj.id;
|
||||
const kr = await prisma.keyResult.create({
|
||||
data: {
|
||||
objectiveId: obj.id,
|
||||
title: 'single KR for status test',
|
||||
progress: 0,
|
||||
startValue: 0,
|
||||
targetValue: 10,
|
||||
deadline: new Date('2099-12-31'),
|
||||
},
|
||||
});
|
||||
testKrId = kr.id;
|
||||
|
||||
// 0% → IN_PROGRESS
|
||||
await service.updateProgress(kr.id, { progress: 50, comment: 'halfway' }, employeeUser);
|
||||
const afterHalf = await prisma.objective.findUniqueOrThrow({ where: { id: obj.id } });
|
||||
assert.equal(afterHalf.status, 'IN_PROGRESS');
|
||||
|
||||
// 100% → COMPLETED
|
||||
await service.updateProgress(kr.id, { progress: 100, comment: 'done' }, employeeUser);
|
||||
const afterFull = await prisma.objective.findUniqueOrThrow({ where: { id: obj.id } });
|
||||
assert.equal(afterFull.status, 'COMPLETED');
|
||||
|
||||
// Regression back → IN_PROGRESS
|
||||
await service.updateProgress(kr.id, { progress: 80, comment: 'regressed' }, employeeUser);
|
||||
const afterRegress = await prisma.objective.findUniqueOrThrow({ where: { id: obj.id } });
|
||||
assert.equal(afterRegress.status, 'IN_PROGRESS');
|
||||
|
||||
// Back to 0 → NOT_STARTED
|
||||
await service.updateProgress(kr.id, { progress: 0, comment: 'reset' }, employeeUser);
|
||||
const afterZero = await prisma.objective.findUniqueOrThrow({ where: { id: obj.id } });
|
||||
assert.equal(afterZero.status, 'NOT_STARTED');
|
||||
} finally {
|
||||
if (testKrId) await prisma.keyResult.delete({ where: { id: testKrId } });
|
||||
if (testObjectiveId) await prisma.objective.delete({ where: { id: testObjectiveId } });
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
test('KeyResultsService averageProgress: multi-KR completion drives COMPLETED status', async () => {
|
||||
const prisma = new PrismaService();
|
||||
await prisma.$connect();
|
||||
const service = new KeyResultsService(prisma);
|
||||
let testObjectiveId: number | undefined;
|
||||
let kr1Id: number | undefined;
|
||||
let kr2Id: number | undefined;
|
||||
try {
|
||||
const obj = await prisma.objective.create({
|
||||
data: { title: 'multi-kr-test', ownerId: employeeUser.sub, quarter: 'Q4/2099', status: 'NOT_STARTED' },
|
||||
});
|
||||
testObjectiveId = obj.id;
|
||||
const kr1 = await prisma.keyResult.create({
|
||||
data: { objectiveId: obj.id, title: 'kr1', progress: 0, startValue: 0, targetValue: 1, deadline: new Date('2099-12-31') },
|
||||
});
|
||||
kr1Id = kr1.id;
|
||||
const kr2 = await prisma.keyResult.create({
|
||||
data: { objectiveId: obj.id, title: 'kr2', progress: 0, startValue: 0, targetValue: 1, deadline: new Date('2099-12-31') },
|
||||
});
|
||||
kr2Id = kr2.id;
|
||||
|
||||
// Set KR1 to 100%, KR2 stays 0 → avg=50 → IN_PROGRESS
|
||||
await service.updateProgress(kr1.id, { progress: 100, comment: '' }, employeeUser);
|
||||
const afterFirst = await prisma.objective.findUniqueOrThrow({ where: { id: obj.id } });
|
||||
assert.equal(afterFirst.status, 'IN_PROGRESS');
|
||||
|
||||
// Set KR2 to 100% → avg=100 → COMPLETED
|
||||
await service.updateProgress(kr2.id, { progress: 100, comment: '' }, employeeUser);
|
||||
const afterBoth = await prisma.objective.findUniqueOrThrow({ where: { id: obj.id } });
|
||||
assert.equal(afterBoth.status, 'COMPLETED');
|
||||
} finally {
|
||||
if (kr1Id) await prisma.keyResult.delete({ where: { id: kr1Id } });
|
||||
if (kr2Id) await prisma.keyResult.delete({ where: { id: kr2Id } });
|
||||
if (testObjectiveId) await prisma.objective.delete({ where: { id: testObjectiveId } });
|
||||
await prisma.$disconnect();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"noEmit": false
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["test/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"skipLibCheck": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": ".",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts", "prisma/**/*.ts"]
|
||||
}
|
||||
@@ -2,68 +2,68 @@
|
||||
"FR-01": {
|
||||
"name": "Login",
|
||||
"code": [
|
||||
"backend/src/auth/auth.controller.ts",
|
||||
{ "file": "backend/src/auth/auth.service.ts", "symbols": ["AuthService", "login"] },
|
||||
"frontend/src/pages/Login.tsx",
|
||||
"frontend/src/hooks/useAuth.tsx"
|
||||
"apps/okr/backend/src/auth/auth.controller.ts",
|
||||
{ "file": "apps/okr/backend/src/auth/auth.service.ts", "symbols": ["AuthService", "login"] },
|
||||
"apps/okr/frontend/src/pages/Login.tsx",
|
||||
"apps/okr/frontend/src/hooks/useAuth.tsx"
|
||||
],
|
||||
"tests": [
|
||||
"backend/test/services.test.ts",
|
||||
"backend/test/e2e.test.ts"
|
||||
"apps/okr/backend/test/services.test.ts",
|
||||
"apps/okr/backend/test/e2e.test.ts"
|
||||
]
|
||||
},
|
||||
"FR-02": {
|
||||
"name": "Create Objective",
|
||||
"code": [
|
||||
"backend/src/objectives/objectives.controller.ts",
|
||||
{ "file": "backend/src/objectives/objectives.service.ts", "symbols": ["ObjectivesService", "create"] },
|
||||
"frontend/src/pages/CreateObjective.tsx",
|
||||
"frontend/src/schemas/objective.schema.ts"
|
||||
"apps/okr/backend/src/objectives/objectives.controller.ts",
|
||||
{ "file": "apps/okr/backend/src/objectives/objectives.service.ts", "symbols": ["ObjectivesService", "create"] },
|
||||
"apps/okr/frontend/src/pages/CreateObjective.tsx",
|
||||
"apps/okr/frontend/src/schemas/objective.schema.ts"
|
||||
],
|
||||
"tests": [
|
||||
"backend/test/services.test.ts",
|
||||
"backend/test/e2e.test.ts",
|
||||
"frontend/src/__tests__/okr.test.tsx"
|
||||
"apps/okr/backend/test/services.test.ts",
|
||||
"apps/okr/backend/test/e2e.test.ts",
|
||||
"apps/okr/frontend/src/__tests__/okr.test.tsx"
|
||||
]
|
||||
},
|
||||
"FR-03": {
|
||||
"name": "Create Key Result",
|
||||
"code": [
|
||||
"backend/src/key-results/key-results.controller.ts",
|
||||
{ "file": "backend/src/key-results/key-results.service.ts", "symbols": ["KeyResultsService", "create"] },
|
||||
"backend/src/key-results/dto/create-key-result.dto.ts"
|
||||
"apps/okr/backend/src/key-results/key-results.controller.ts",
|
||||
{ "file": "apps/okr/backend/src/key-results/key-results.service.ts", "symbols": ["KeyResultsService", "create"] },
|
||||
"apps/okr/backend/src/key-results/dto/create-key-result.dto.ts"
|
||||
],
|
||||
"tests": [
|
||||
"backend/test/services.test.ts",
|
||||
"backend/test/e2e.test.ts"
|
||||
"apps/okr/backend/test/services.test.ts",
|
||||
"apps/okr/backend/test/e2e.test.ts"
|
||||
]
|
||||
},
|
||||
"FR-04": {
|
||||
"name": "Update Progress",
|
||||
"code": [
|
||||
"backend/src/key-results/key-results.controller.ts",
|
||||
{ "file": "backend/src/key-results/key-results.service.ts", "symbols": ["updateProgress"] },
|
||||
"backend/src/key-results/dto/update-progress.dto.ts",
|
||||
"frontend/src/pages/KeyResultDetail.tsx"
|
||||
"apps/okr/backend/src/key-results/key-results.controller.ts",
|
||||
{ "file": "apps/okr/backend/src/key-results/key-results.service.ts", "symbols": ["updateProgress"] },
|
||||
"apps/okr/backend/src/key-results/dto/update-progress.dto.ts",
|
||||
"apps/okr/frontend/src/pages/KeyResultDetail.tsx"
|
||||
],
|
||||
"tests": [
|
||||
"backend/test/services.test.ts",
|
||||
"backend/test/e2e.test.ts",
|
||||
"frontend/src/__tests__/okr.test.tsx"
|
||||
"apps/okr/backend/test/services.test.ts",
|
||||
"apps/okr/backend/test/e2e.test.ts",
|
||||
"apps/okr/frontend/src/__tests__/okr.test.tsx"
|
||||
]
|
||||
},
|
||||
"FR-05": {
|
||||
"name": "Dashboard",
|
||||
"code": [
|
||||
"backend/src/objectives/objectives.controller.ts",
|
||||
{ "file": "backend/src/objectives/objectives.service.ts", "symbols": ["ObjectivesService", "list"] },
|
||||
"frontend/src/pages/Dashboard.tsx",
|
||||
"frontend/src/hooks/useObjectives.ts"
|
||||
"apps/okr/backend/src/objectives/objectives.controller.ts",
|
||||
{ "file": "apps/okr/backend/src/objectives/objectives.service.ts", "symbols": ["ObjectivesService", "list"] },
|
||||
"apps/okr/frontend/src/pages/Dashboard.tsx",
|
||||
"apps/okr/frontend/src/hooks/useObjectives.ts"
|
||||
],
|
||||
"tests": [
|
||||
"backend/test/services.test.ts",
|
||||
"backend/test/e2e.test.ts",
|
||||
"frontend/src/__tests__/okr.test.tsx"
|
||||
"apps/okr/backend/test/services.test.ts",
|
||||
"apps/okr/backend/test/e2e.test.ts",
|
||||
"apps/okr/frontend/src/__tests__/okr.test.tsx"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>OKR Dashboard</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@ainative-okr/frontend",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.81.5",
|
||||
"axios": "^1.10.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-hook-form": "^7.59.0",
|
||||
"react-router-dom": "^6.30.1",
|
||||
"zod": "^3.25.67"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/dom": "^10.0.0",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^14.5.2",
|
||||
"@types/node": "^24.0.8",
|
||||
"@types/react": "^18.3.23",
|
||||
"@types/react-dom": "^18.3.7",
|
||||
"@vitejs/plugin-react": "^4.6.0",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"jsdom": "^26.1.0",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"typescript": "^5.8.3",
|
||||
"vite": "^5.4.19",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Navigate, Outlet, Route, Routes } from 'react-router-dom';
|
||||
import { AppLayout } from './components/layout/AppLayout.js';
|
||||
import { useAuth } from './hooks/useAuth.js';
|
||||
import { CreateObjective } from './pages/CreateObjective.js';
|
||||
import { Dashboard } from './pages/Dashboard.js';
|
||||
import { KeyResultDetail } from './pages/KeyResultDetail.js';
|
||||
import { Login } from './pages/Login.js';
|
||||
import { OKRDetail } from './pages/OKRDetail.js';
|
||||
|
||||
function ProtectedRoute(): JSX.Element {
|
||||
const { user } = useAuth();
|
||||
return user === null ? <Navigate to="/login" replace /> : <Outlet />;
|
||||
}
|
||||
|
||||
export function App(): JSX.Element {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route element={<ProtectedRoute />}>
|
||||
<Route path="/" element={<AppLayout />}>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="objectives/new" element={<CreateObjective />} />
|
||||
<Route path="objectives/:id" element={<OKRDetail />} />
|
||||
<Route path="key-results/:id" element={<KeyResultDetail />} />
|
||||
</Route>
|
||||
</Route>
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { Badge } from '../components/ui/Badge.js';
|
||||
import { ProgressBar } from '../components/ui/ProgressBar.js';
|
||||
import { createObjectiveSchema } from '../schemas/objective.schema.js';
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
// Test 1: Component render — Badge displays correct label per status
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
describe('Badge component', () => {
|
||||
it('renders "In Progress" label for IN_PROGRESS status', () => {
|
||||
render(<Badge status="IN_PROGRESS" />);
|
||||
expect(screen.getByText('In Progress')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders "Completed" label for COMPLETED status', () => {
|
||||
render(<Badge status="COMPLETED" />);
|
||||
expect(screen.getByText('Completed')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders "Not Started" label for NOT_STARTED status', () => {
|
||||
render(<Badge status="NOT_STARTED" />);
|
||||
expect(screen.getByText('Not Started')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
// Test 2: ProgressBar clamps value to 0–100 range
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
describe('ProgressBar component', () => {
|
||||
it('clamps value above 100 to 100%', () => {
|
||||
const { container } = render(<ProgressBar value={150} />);
|
||||
const bar = container.querySelector('.bg-blue-600') as HTMLElement;
|
||||
expect(bar.style.width).toBe('100%');
|
||||
});
|
||||
|
||||
it('clamps negative value to 0%', () => {
|
||||
const { container } = render(<ProgressBar value={-10} />);
|
||||
const bar = container.querySelector('.bg-blue-600') as HTMLElement;
|
||||
expect(bar.style.width).toBe('0%');
|
||||
});
|
||||
|
||||
it('renders exact value within range', () => {
|
||||
const { container } = render(<ProgressBar value={75} />);
|
||||
const bar = container.querySelector('.bg-blue-600') as HTMLElement;
|
||||
expect(bar.style.width).toBe('75%');
|
||||
});
|
||||
});
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
// Test 3: Form validation — Zod schema enforces quarter format
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
describe('createObjectiveSchema validation', () => {
|
||||
it('accepts a valid payload', () => {
|
||||
const result = createObjectiveSchema.safeParse({
|
||||
title: 'Improve platform uptime',
|
||||
ownerId: 1,
|
||||
quarter: 'Q2/2026',
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects invalid quarter format', () => {
|
||||
const result = createObjectiveSchema.safeParse({
|
||||
title: 'Improve platform uptime',
|
||||
ownerId: 1,
|
||||
quarter: 'Q5/2026',
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
const quarterError = result.error.issues.find((i) => i.path[0] === 'quarter');
|
||||
expect(quarterError).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects empty title', () => {
|
||||
const result = createObjectiveSchema.safeParse({
|
||||
title: '',
|
||||
ownerId: 1,
|
||||
quarter: 'Q1/2025',
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
const titleError = result.error.issues.find((i) => i.path[0] === 'title');
|
||||
expect(titleError).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects non-positive ownerId', () => {
|
||||
const result = createObjectiveSchema.safeParse({
|
||||
title: 'Valid title',
|
||||
ownerId: -1,
|
||||
quarter: 'Q3/2025',
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
const ownerError = result.error.issues.find((i) => i.path[0] === 'ownerId');
|
||||
expect(ownerError).toBeDefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
// Test 4: Progress calculation (same logic as Dashboard.objectiveProgress)
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
function objectiveProgress(keyResults: { progress: number }[]): number {
|
||||
if (keyResults.length === 0) return 0;
|
||||
return Math.round(keyResults.reduce((total, kr) => total + kr.progress, 0) / keyResults.length);
|
||||
}
|
||||
|
||||
describe('objectiveProgress calculation', () => {
|
||||
it('returns 0 for empty key results', () => {
|
||||
expect(objectiveProgress([])).toBe(0);
|
||||
});
|
||||
|
||||
it('computes average progress across key results', () => {
|
||||
expect(objectiveProgress([{ progress: 50 }, { progress: 100 }])).toBe(75);
|
||||
});
|
||||
|
||||
it('rounds fractional averages', () => {
|
||||
expect(objectiveProgress([{ progress: 33 }, { progress: 34 }, { progress: 34 }])).toBe(34);
|
||||
});
|
||||
|
||||
it('returns 100 when all key results complete', () => {
|
||||
expect(objectiveProgress([{ progress: 100 }, { progress: 100 }])).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
// Test 5: API error handling — axios mock returns error state
|
||||
// ──────────────────────────────────────────────────────────────────────────────
|
||||
vi.mock('axios', () => ({
|
||||
default: {
|
||||
create: vi.fn(() => ({
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
patch: vi.fn(),
|
||||
interceptors: {
|
||||
request: { use: vi.fn() },
|
||||
response: { use: vi.fn() },
|
||||
},
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('API error handling', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('reports error when API rejects', async () => {
|
||||
const mockGet = vi.fn().mockRejectedValue(new Error('Network Error'));
|
||||
const result = await mockGet('/api/objectives').catch((e: Error) => e);
|
||||
expect(result).toBeInstanceOf(Error);
|
||||
expect((result as Error).message).toBe('Network Error');
|
||||
});
|
||||
|
||||
it('returns data when API resolves', async () => {
|
||||
const mockGet = vi.fn().mockResolvedValue({ data: { success: true, data: [] } });
|
||||
const result = await mockGet('/api/objectives');
|
||||
expect(result.data.success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
import '@testing-library/jest-dom';
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Outlet } from 'react-router-dom';
|
||||
import { Header } from './Header.js';
|
||||
import { Sidebar } from './Sidebar.js';
|
||||
|
||||
export function AppLayout(): JSX.Element {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50">
|
||||
<Sidebar />
|
||||
<Header />
|
||||
<main className="ml-64 pt-20">
|
||||
<div className="mx-auto max-w-6xl px-6 py-6">
|
||||
<Outlet />
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Button } from '../ui/Button.js';
|
||||
import { useAuth } from '../../hooks/useAuth.js';
|
||||
|
||||
export function Header(): JSX.Element {
|
||||
const { user, logout } = useAuth();
|
||||
return (
|
||||
<header className="fixed left-64 right-0 top-0 z-10 border-b border-gray-200 bg-white px-6 py-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex flex-1 items-center gap-4">
|
||||
<select className="rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
|
||||
<option>All FPT</option>
|
||||
</select>
|
||||
<input
|
||||
className="w-full max-w-xl rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
placeholder="Search"
|
||||
/>
|
||||
</div>
|
||||
<Link to="/objectives/new">
|
||||
<Button>NEW OKR</Button>
|
||||
</Link>
|
||||
<div className="text-sm text-gray-500">{user?.name}</div>
|
||||
<Button variant="secondary" onClick={logout}>
|
||||
Sign out
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
|
||||
const links = [
|
||||
{ label: 'My OKRs', href: '/' },
|
||||
{ label: 'I created', href: '/' },
|
||||
{ label: 'I manage', href: '/' },
|
||||
{ label: 'Members', href: '/' },
|
||||
{ label: 'OKR - all', href: '/' },
|
||||
];
|
||||
|
||||
export function Sidebar(): JSX.Element {
|
||||
const location = useLocation();
|
||||
return (
|
||||
<aside className="fixed left-0 top-0 h-screen w-64 border-r border-gray-200 bg-white p-5">
|
||||
<div className="mb-8 text-xl font-semibold text-blue-600">FOKR</div>
|
||||
<div className="mb-4 text-sm font-medium text-gray-500">2026</div>
|
||||
<nav className="space-y-1">
|
||||
{links.map((link) => {
|
||||
const active = location.pathname === link.href && link.label === 'My OKRs';
|
||||
return (
|
||||
<Link
|
||||
key={link.label}
|
||||
to={link.href}
|
||||
className={`block rounded-lg px-3 py-2 text-sm transition-colors ${
|
||||
active ? 'bg-blue-50 font-medium text-blue-600' : 'text-gray-600 hover:bg-gray-50 hover:text-gray-800'
|
||||
}`}
|
||||
>
|
||||
{link.label}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { ObjectiveStatus } from '../../types/okr.types.js';
|
||||
|
||||
interface BadgeProps {
|
||||
status: ObjectiveStatus;
|
||||
}
|
||||
|
||||
const labels: Record<ObjectiveStatus, string> = {
|
||||
NOT_STARTED: 'Not Started',
|
||||
IN_PROGRESS: 'In Progress',
|
||||
COMPLETED: 'Completed',
|
||||
};
|
||||
|
||||
const classes: Record<ObjectiveStatus, string> = {
|
||||
NOT_STARTED: 'bg-gray-100 text-gray-600',
|
||||
IN_PROGRESS: 'bg-orange-100 text-orange-700',
|
||||
COMPLETED: 'bg-green-100 text-green-700',
|
||||
};
|
||||
|
||||
export function Badge({ status }: BadgeProps): JSX.Element {
|
||||
return <span className={`rounded-full px-2 py-1 text-xs font-medium ${classes[status]}`}>{labels[status]}</span>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { ButtonHTMLAttributes } from 'react';
|
||||
|
||||
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
variant?: 'primary' | 'secondary';
|
||||
}
|
||||
|
||||
export function Button({ className = '', variant = 'primary', ...props }: ButtonProps): JSX.Element {
|
||||
const base = 'inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-60';
|
||||
const variants = {
|
||||
primary: 'bg-blue-600 text-white hover:bg-blue-700',
|
||||
secondary: 'border border-gray-300 text-gray-700 hover:bg-gray-50',
|
||||
};
|
||||
return <button className={`${base} ${variants[variant]} ${className}`} {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
interface ProgressBarProps {
|
||||
value: number;
|
||||
}
|
||||
|
||||
export function ProgressBar({ value }: ProgressBarProps): JSX.Element {
|
||||
const width = `${Math.min(Math.max(value, 0), 100)}%`;
|
||||
return (
|
||||
<div className="w-full rounded-full bg-gray-200 h-2">
|
||||
<div className="h-2 rounded-full bg-blue-600 transition-all" style={{ width }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { createContext, useContext, useMemo, useState } from 'react';
|
||||
import { login as loginRequest } from '../lib/api.js';
|
||||
import type { User } from '../types/okr.types.js';
|
||||
|
||||
interface AuthContextValue {
|
||||
user: User | null;
|
||||
login: (username: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | undefined>(undefined);
|
||||
|
||||
const storedUser = (): User | null => {
|
||||
const raw = window.localStorage.getItem('okr_user');
|
||||
if (raw === null) {
|
||||
return null;
|
||||
}
|
||||
return JSON.parse(raw) as User;
|
||||
};
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }): JSX.Element {
|
||||
const [user, setUser] = useState<User | null>(storedUser);
|
||||
|
||||
const value = useMemo<AuthContextValue>(
|
||||
() => ({
|
||||
user,
|
||||
login: async (username: string, password: string) => {
|
||||
const result = await loginRequest(username, password);
|
||||
window.localStorage.setItem('okr_user', JSON.stringify(result.user));
|
||||
setUser(result.user);
|
||||
},
|
||||
logout: () => {
|
||||
window.localStorage.removeItem('okr_user');
|
||||
setUser(null);
|
||||
},
|
||||
}),
|
||||
[user],
|
||||
);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
|
||||
export function useAuth(): AuthContextValue {
|
||||
const context = useContext(AuthContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useAuth must be used within AuthProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { listObjectives } from '../lib/api.js';
|
||||
|
||||
export function useObjectives(quarter: string) {
|
||||
return useQuery({
|
||||
queryKey: ['objectives', { quarter }],
|
||||
queryFn: () => listObjectives(quarter),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: #f9fafb;
|
||||
color: #1f2937;
|
||||
font-family:
|
||||
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import axios from 'axios';
|
||||
import type {
|
||||
ApiResponse,
|
||||
CreateObjectivePayload,
|
||||
KeyResult,
|
||||
LoginResult,
|
||||
Objective,
|
||||
UpdateProgressPayload,
|
||||
User,
|
||||
} from '../types/okr.types.js';
|
||||
|
||||
const apiBaseUrl =
|
||||
import.meta.env.VITE_API_BASE_URL ??
|
||||
`${window.location.protocol}//${window.location.hostname === '127.0.0.1' ? '127.0.0.1' : 'localhost'}:3000/api/v1`;
|
||||
|
||||
const client = axios.create({
|
||||
baseURL: apiBaseUrl,
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
export async function login(username: string, password: string): Promise<LoginResult> {
|
||||
const response = await client.post<ApiResponse<LoginResult>>('/auth/login', { username, password });
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
export async function listUsers(): Promise<User[]> {
|
||||
const response = await client.get<ApiResponse<User[]>>('/users');
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
export async function listObjectives(quarter?: string): Promise<Objective[]> {
|
||||
const response = await client.get<ApiResponse<Objective[]>>('/objectives', { params: { quarter } });
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
export async function getObjective(id: number): Promise<Objective> {
|
||||
const response = await client.get<ApiResponse<Objective>>(`/objectives/${id}`);
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
export async function createObjective(payload: CreateObjectivePayload): Promise<Objective> {
|
||||
const response = await client.post<ApiResponse<Objective>>('/objectives', payload);
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
export async function getKeyResult(id: number): Promise<KeyResult & { objective: Objective }> {
|
||||
const response = await client.get<ApiResponse<KeyResult & { objective: Objective }>>(`/key-results/${id}`);
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
export async function updateKeyResultProgress(id: number, payload: UpdateProgressPayload): Promise<KeyResult> {
|
||||
const response = await client.patch<ApiResponse<KeyResult>>(`/key-results/${id}/progress`, payload);
|
||||
return response.data.data;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { QueryClient } from '@tanstack/react-query';
|
||||
|
||||
export const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 30_000,
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import { App } from './App.js';
|
||||
import { AuthProvider } from './hooks/useAuth.js';
|
||||
import { queryClient } from './lib/queryClient.js';
|
||||
import './index.css';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
</React.StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,74 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Button } from '../components/ui/Button.js';
|
||||
import { createObjective, listUsers } from '../lib/api.js';
|
||||
import { createObjectiveSchema, type CreateObjectiveFormData } from '../schemas/objective.schema.js';
|
||||
|
||||
export function CreateObjective(): JSX.Element {
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const [fieldErrors, setFieldErrors] = useState<Partial<Record<keyof CreateObjectiveFormData, string>>>({});
|
||||
const { register, handleSubmit } = useForm<CreateObjectiveFormData>({
|
||||
defaultValues: { title: '', description: '', quarter: 'Q2/2026' },
|
||||
});
|
||||
const { data: users = [] } = useQuery({ queryKey: ['users'], queryFn: listUsers });
|
||||
const mutation = useMutation({
|
||||
mutationFn: createObjective,
|
||||
onSuccess: async (objective) => {
|
||||
await queryClient.invalidateQueries({ queryKey: ['objectives'] });
|
||||
navigate(`/objectives/${objective.id}`);
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = handleSubmit((values) => {
|
||||
const parsed = createObjectiveSchema.safeParse(values);
|
||||
if (!parsed.success) {
|
||||
setFieldErrors(Object.fromEntries(parsed.error.issues.map((issue) => [issue.path[0], issue.message])));
|
||||
return;
|
||||
}
|
||||
setFieldErrors({});
|
||||
mutation.mutate(parsed.data);
|
||||
});
|
||||
|
||||
return (
|
||||
<section className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm">
|
||||
<h1 className="mb-6 text-xl font-semibold text-gray-800">Create Objective</h1>
|
||||
<form className="max-w-2xl space-y-4" onSubmit={onSubmit}>
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-sm font-medium text-gray-700">Title</span>
|
||||
<input className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" {...register('title')} />
|
||||
{fieldErrors.title !== undefined && <span className="mt-1 block text-sm text-orange-600">{fieldErrors.title}</span>}
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-sm font-medium text-gray-700">Description</span>
|
||||
<textarea rows={4} className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" {...register('description')} />
|
||||
</label>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-sm font-medium text-gray-700">Owner</span>
|
||||
<select className="w-full rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" {...register('ownerId')}>
|
||||
<option value="">Select owner</option>
|
||||
{users.map((user) => (
|
||||
<option key={user.id} value={user.id}>
|
||||
{user.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{fieldErrors.ownerId !== undefined && <span className="mt-1 block text-sm text-orange-600">{fieldErrors.ownerId}</span>}
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-sm font-medium text-gray-700">Quarter</span>
|
||||
<input className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" {...register('quarter')} />
|
||||
{fieldErrors.quarter !== undefined && <span className="mt-1 block text-sm text-orange-600">{fieldErrors.quarter}</span>}
|
||||
</label>
|
||||
</div>
|
||||
{mutation.isError && <div className="rounded-lg bg-orange-100 px-3 py-2 text-sm text-orange-700">Unable to create objective.</div>}
|
||||
<Button type="submit" disabled={mutation.isPending}>
|
||||
Save
|
||||
</Button>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Badge } from '../components/ui/Badge.js';
|
||||
import { ProgressBar } from '../components/ui/ProgressBar.js';
|
||||
import { useObjectives } from '../hooks/useObjectives.js';
|
||||
|
||||
function objectiveProgress(keyResults: { progress: number }[]): number {
|
||||
if (keyResults.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
return Math.round(keyResults.reduce((total, keyResult) => total + keyResult.progress, 0) / keyResults.length);
|
||||
}
|
||||
|
||||
export function Dashboard(): JSX.Element {
|
||||
const { data: objectives = [], isLoading, error } = useObjectives('Q2/2026');
|
||||
|
||||
return (
|
||||
<section>
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-gray-800">OKR List</h1>
|
||||
<p className="text-sm text-gray-500">Q2/2026</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<select className="rounded-lg border border-gray-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
|
||||
<option>Q2/2026</option>
|
||||
</select>
|
||||
<button className="rounded-lg border border-gray-300 px-3 py-2 text-sm text-gray-700 transition-colors hover:bg-gray-50">Filters</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isLoading && <div className="rounded-xl border border-gray-200 bg-white p-6 text-gray-500">Loading OKRs...</div>}
|
||||
{error !== null && <div className="rounded-xl border border-orange-200 bg-orange-100 p-6 text-orange-700">Unable to load OKRs.</div>}
|
||||
|
||||
<div className="space-y-4">
|
||||
{objectives.map((objective) => {
|
||||
const progress = objectiveProgress(objective.keyResults);
|
||||
return (
|
||||
<Link
|
||||
key={objective.id}
|
||||
to={`/objectives/${objective.id}`}
|
||||
className="block rounded-xl border border-gray-200 bg-white p-6 shadow-sm transition hover:-translate-y-px hover:shadow-md"
|
||||
>
|
||||
<div className="mb-4 flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-gray-800">{objective.title}</h2>
|
||||
<p className="mt-1 text-sm text-gray-500">Owner: {objective.owner.name}</p>
|
||||
</div>
|
||||
<Badge status={objective.status} />
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex-1">
|
||||
<ProgressBar value={progress} />
|
||||
</div>
|
||||
<span className="w-12 text-right text-sm font-medium text-gray-700">{progress}%</span>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Button } from '../components/ui/Button.js';
|
||||
import { ProgressBar } from '../components/ui/ProgressBar.js';
|
||||
import { getKeyResult, updateKeyResultProgress } from '../lib/api.js';
|
||||
import { updateProgressSchema, type UpdateProgressFormData } from '../schemas/key-result.schema.js';
|
||||
|
||||
function readRouteId(id: string | undefined): number {
|
||||
const parsed = Number(id);
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
}
|
||||
|
||||
export function KeyResultDetail(): JSX.Element {
|
||||
const id = readRouteId(useParams().id);
|
||||
const queryClient = useQueryClient();
|
||||
const [fieldError, setFieldError] = useState<string | null>(null);
|
||||
const { register, handleSubmit, reset } = useForm<UpdateProgressFormData>();
|
||||
const { data: keyResult, isLoading } = useQuery({
|
||||
queryKey: ['key-result', id],
|
||||
queryFn: () => getKeyResult(id),
|
||||
enabled: id > 0,
|
||||
});
|
||||
const mutation = useMutation({
|
||||
mutationFn: (payload: UpdateProgressFormData) => updateKeyResultProgress(id, payload),
|
||||
onSuccess: async (updated) => {
|
||||
reset({ progress: updated.progress, comment: '' });
|
||||
await queryClient.invalidateQueries({ queryKey: ['key-result', id] });
|
||||
await queryClient.invalidateQueries({ queryKey: ['objective', keyResult?.objectiveId] });
|
||||
await queryClient.invalidateQueries({ queryKey: ['objectives'] });
|
||||
},
|
||||
});
|
||||
|
||||
if (isLoading || keyResult === undefined) {
|
||||
return <div className="rounded-xl border border-gray-200 bg-white p-6 text-gray-500">Loading key result...</div>;
|
||||
}
|
||||
|
||||
const onSubmit = handleSubmit((values) => {
|
||||
const parsed = updateProgressSchema.safeParse(values);
|
||||
if (!parsed.success) {
|
||||
setFieldError(parsed.error.issues[0]?.message ?? 'Invalid progress');
|
||||
return;
|
||||
}
|
||||
setFieldError(null);
|
||||
mutation.mutate(parsed.data);
|
||||
});
|
||||
|
||||
return (
|
||||
<section className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm">
|
||||
<h1 className="mb-2 text-xl font-semibold text-gray-800">Key Result Detail</h1>
|
||||
<h2 className="text-lg font-medium text-gray-800">{keyResult.title}</h2>
|
||||
<div className="mt-2 text-sm text-gray-500">Owner: {keyResult.objective.owner.name}</div>
|
||||
<div className="mt-1 text-sm text-gray-500">Deadline: {new Date(keyResult.deadline).toLocaleDateString()}</div>
|
||||
|
||||
<div className="my-6 max-w-md">
|
||||
<div className="mb-2 flex justify-between text-sm font-medium text-gray-700">
|
||||
<span>Current Progress</span>
|
||||
<span>{keyResult.progress}%</span>
|
||||
</div>
|
||||
<ProgressBar value={keyResult.progress} />
|
||||
</div>
|
||||
|
||||
<form className="max-w-md space-y-4" onSubmit={onSubmit}>
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-sm font-medium text-gray-700">Update Progress</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="100"
|
||||
defaultValue={keyResult.progress}
|
||||
className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
|
||||
{...register('progress')}
|
||||
/>
|
||||
<span className="text-gray-500">%</span>
|
||||
</div>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-sm font-medium text-gray-700">Comment</span>
|
||||
<textarea rows={4} className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" {...register('comment')} />
|
||||
</label>
|
||||
{fieldError !== null && <div className="rounded-lg bg-orange-100 px-3 py-2 text-sm text-orange-700">{fieldError}</div>}
|
||||
{mutation.isError && <div className="rounded-lg bg-orange-100 px-3 py-2 text-sm text-orange-700">Unable to update progress.</div>}
|
||||
<Button type="submit" disabled={mutation.isPending}>
|
||||
Save
|
||||
</Button>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { Navigate, useNavigate } from 'react-router-dom';
|
||||
import { Button } from '../components/ui/Button.js';
|
||||
import { useAuth } from '../hooks/useAuth.js';
|
||||
import { loginSchema, type LoginFormData } from '../schemas/auth.schema.js';
|
||||
|
||||
export function Login(): JSX.Element {
|
||||
const { user, login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [fieldErrors, setFieldErrors] = useState<Partial<Record<keyof LoginFormData, string>>>({});
|
||||
const { register, handleSubmit } = useForm<LoginFormData>({
|
||||
defaultValues: { username: 'employee', password: 'Password@123' },
|
||||
});
|
||||
|
||||
if (user !== null) {
|
||||
return <Navigate to="/" replace />;
|
||||
}
|
||||
|
||||
const onSubmit = handleSubmit(async (values) => {
|
||||
const parsed = loginSchema.safeParse(values);
|
||||
if (!parsed.success) {
|
||||
setFieldErrors(Object.fromEntries(parsed.error.issues.map((issue) => [issue.path[0], issue.message])));
|
||||
return;
|
||||
}
|
||||
setFieldErrors({});
|
||||
setFormError(null);
|
||||
try {
|
||||
await login(parsed.data.username, parsed.data.password);
|
||||
navigate('/');
|
||||
} catch {
|
||||
setFormError('Invalid username or password');
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-gray-50 px-4">
|
||||
<section className="w-full max-w-md rounded-xl border border-gray-200 bg-white p-8 shadow-sm">
|
||||
<div className="mb-8 text-center">
|
||||
<div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-lg bg-blue-600 text-lg font-semibold text-white">
|
||||
OKR
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold text-gray-800">Sign in to OKR</h1>
|
||||
</div>
|
||||
<form className="space-y-4" onSubmit={onSubmit}>
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-sm font-medium text-gray-700">Username or email address</span>
|
||||
<input className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" {...register('username')} />
|
||||
{fieldErrors.username !== undefined && <span className="mt-1 block text-sm text-orange-600">{fieldErrors.username}</span>}
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="mb-1 flex justify-between text-sm font-medium text-gray-700">
|
||||
Password <span className="text-blue-600">Forgot password?</span>
|
||||
</span>
|
||||
<input type="password" className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" {...register('password')} />
|
||||
{fieldErrors.password !== undefined && <span className="mt-1 block text-sm text-orange-600">{fieldErrors.password}</span>}
|
||||
</label>
|
||||
{formError !== null && <div className="rounded-lg bg-orange-100 px-3 py-2 text-sm text-orange-700">{formError}</div>}
|
||||
<Button className="w-full" type="submit">
|
||||
Sign in
|
||||
</Button>
|
||||
</form>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import { Badge } from '../components/ui/Badge.js';
|
||||
import { Button } from '../components/ui/Button.js';
|
||||
import { ProgressBar } from '../components/ui/ProgressBar.js';
|
||||
import { getObjective } from '../lib/api.js';
|
||||
|
||||
function readRouteId(id: string | undefined): number {
|
||||
const parsed = Number(id);
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
}
|
||||
|
||||
export function OKRDetail(): JSX.Element {
|
||||
const id = readRouteId(useParams().id);
|
||||
const { data: objective, isLoading } = useQuery({
|
||||
queryKey: ['objective', id],
|
||||
queryFn: () => getObjective(id),
|
||||
enabled: id > 0,
|
||||
});
|
||||
|
||||
if (isLoading || objective === undefined) {
|
||||
return <div className="rounded-xl border border-gray-200 bg-white p-6 text-gray-500">Loading objective...</div>;
|
||||
}
|
||||
|
||||
const progress = objective.computedProgress ?? 0;
|
||||
|
||||
return (
|
||||
<section className="space-y-6">
|
||||
<div className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm">
|
||||
<div className="mb-4 flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-gray-800">{objective.title}</h1>
|
||||
<p className="mt-2 text-sm text-gray-500">{objective.description}</p>
|
||||
</div>
|
||||
<Badge status={objective.status} />
|
||||
</div>
|
||||
<div className="mb-4 flex gap-3">
|
||||
<Button variant="secondary">REPORT</Button>
|
||||
<Button variant="secondary">OPTIONS</Button>
|
||||
</div>
|
||||
<div className="border-b border-gray-200">
|
||||
<div className="flex gap-6 text-sm font-medium text-gray-600">
|
||||
<span className="border-b-2 border-blue-600 pb-3 text-blue-600">General Info</span>
|
||||
<span className="pb-3">Conversation</span>
|
||||
<span className="pb-3">Grade & Feedback</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-6 grid gap-4 md:grid-cols-3">
|
||||
<div>
|
||||
<div className="text-sm text-gray-500">Owner</div>
|
||||
<div className="font-medium text-gray-800">{objective.owner.name}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm text-gray-500">Quarter</div>
|
||||
<div className="font-medium text-gray-800">{objective.quarter}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm text-gray-500">Progress</div>
|
||||
<div className="mt-2 flex items-center gap-3">
|
||||
<ProgressBar value={progress} />
|
||||
<span className="text-sm font-medium">{progress}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="rounded-xl border border-gray-200 bg-white p-6 shadow-sm">
|
||||
<h2 className="mb-4 text-lg font-semibold text-gray-800">Key Results</h2>
|
||||
<div className="divide-y divide-gray-200">
|
||||
{objective.keyResults.map((keyResult) => (
|
||||
<Link key={keyResult.id} to={`/key-results/${keyResult.id}`} className="block py-4 transition-colors hover:bg-gray-50">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<div className="font-medium text-gray-800">{keyResult.title}</div>
|
||||
<div className="text-sm text-gray-500">
|
||||
Start: {keyResult.startValue} · Target: {keyResult.targetValue} · Deadline:{' '}
|
||||
{new Date(keyResult.deadline).toLocaleDateString()}
|
||||
</div>
|
||||
</div>
|
||||
<div className="w-44">
|
||||
<ProgressBar value={keyResult.progress} />
|
||||
<div className="mt-1 text-right text-sm text-gray-500">{keyResult.progress}%</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const loginSchema = z.object({
|
||||
username: z.string().min(1, 'Username or email is required'),
|
||||
password: z.string().min(8, 'Password must be at least 8 characters'),
|
||||
});
|
||||
|
||||
export type LoginFormData = z.infer<typeof loginSchema>;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const updateProgressSchema = z.object({
|
||||
progress: z.coerce.number().int().min(0, 'Progress cannot be negative').max(100, 'Progress cannot exceed 100'),
|
||||
comment: z.string().optional(),
|
||||
});
|
||||
|
||||
export type UpdateProgressFormData = z.infer<typeof updateProgressSchema>;
|
||||
@@ -0,0 +1,10 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const createObjectiveSchema = z.object({
|
||||
title: z.string().min(1, 'Title is required'),
|
||||
description: z.string().optional(),
|
||||
ownerId: z.coerce.number().int().positive('Owner is required'),
|
||||
quarter: z.string().regex(/^Q[1-4]\/\d{4}$/, 'Format must be Q2/2026'),
|
||||
});
|
||||
|
||||
export type CreateObjectiveFormData = z.infer<typeof createObjectiveSchema>;
|
||||
@@ -0,0 +1,59 @@
|
||||
export type Role = 'ADMIN' | 'MANAGER' | 'EMPLOYEE';
|
||||
export type ObjectiveStatus = 'NOT_STARTED' | 'IN_PROGRESS' | 'COMPLETED';
|
||||
|
||||
export interface User {
|
||||
id: number;
|
||||
name: string;
|
||||
username: string;
|
||||
email: string;
|
||||
role: Role;
|
||||
}
|
||||
|
||||
export interface KeyResult {
|
||||
id: number;
|
||||
objectiveId: number;
|
||||
title: string;
|
||||
progress: number;
|
||||
startValue: number;
|
||||
targetValue: number;
|
||||
deadline: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface Objective {
|
||||
id: number;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
ownerId: number;
|
||||
owner: User;
|
||||
quarter: string;
|
||||
status: ObjectiveStatus;
|
||||
keyResults: KeyResult[];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
computedProgress?: number;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
success: boolean;
|
||||
data: T;
|
||||
meta?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface LoginResult {
|
||||
token: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface CreateObjectivePayload {
|
||||
title: string;
|
||||
description?: string;
|
||||
ownerId: number;
|
||||
quarter: string;
|
||||
}
|
||||
|
||||
export interface UpdateProgressPayload {
|
||||
progress: number;
|
||||
comment?: string;
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { Config } from 'tailwindcss';
|
||||
|
||||
const config: Config = {
|
||||
content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ES2020"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx"
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": []
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/__tests__/okr.test.tsx","./src/__tests__/setup.ts","./src/components/layout/applayout.tsx","./src/components/layout/header.tsx","./src/components/layout/sidebar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/progressbar.tsx","./src/hooks/useauth.tsx","./src/hooks/useobjectives.ts","./src/lib/api.ts","./src/lib/queryclient.ts","./src/pages/createobjective.tsx","./src/pages/dashboard.tsx","./src/pages/keyresultdetail.tsx","./src/pages/login.tsx","./src/pages/okrdetail.tsx","./src/schemas/auth.schema.ts","./src/schemas/key-result.schema.ts","./src/schemas/objective.schema.ts","./src/types/okr.types.ts"],"version":"5.9.3"}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: {
|
||||
port: 5173,
|
||||
},
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
globals: true,
|
||||
setupFiles: ['./src/__tests__/setup.ts'],
|
||||
include: ['./src/__tests__/**/*.test.{ts,tsx}'],
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user