refactor(structure): promote app to repo root + remove redundant workspace cruft
Standard production layout: the OKR app (was nested under AINative_OKR_CASAN5/) is now
the repository root. No more wrapper directory.
- Promote AINative_OKR_CASAN5/* -> repo root (backend/ frontend/ packages/ apps/
.specify/ docs/ infra/ nginx/ scripts/ + configs). Merge tool dirs: .gitea (kept the
active deploy ci.yml, added harness-ci.yml + runbooks), .claude (agents/commands +
launch.json), .github moved up.
- Remove redundant: 00_SUBMISSION_PACKAGE, scattered root notes (FPT_CASAN_Full.md,
tu-tuong-casan.md, casan-tu-sinh..., casan_harness_assessment.md, source-review...,
README_CASAN5_REFINED.md), casan-next-plans/ and optimize-docs/ (competition/planning
artifacts — roadmap + design history preserved in git log / commit messages).
- Update all references to the old layout:
- .gitea/workflows/{ci,harness-ci}.yml, .github/workflows/{ci,deploy}.yml:
working-directory .; drop AINative_OKR_CASAN5/ prefix; .specify/{tests,scripts}
-> packages/casan-harness/... (.specify/logs state kept)
- .claude/launch.json, .gitea/*-runbook.md: path prefixes
- CLAUDE.md, README.md: docs/input -> apps/okr/domain/input
- policy-bundle.yaml: 8 policy paths -> packages/casan-harness/...; manifest re-signed
- secrets-scan.sh: fixture excludes -> new package/domain paths.
Full gate from the new root: PASS=64 FAIL=0 SKIP=3.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
7101af9fd4
commit
36a4812ef3
@@ -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"]
|
||||
}
|
||||
Reference in New Issue
Block a user