Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { AuditModule } from './audit/audit.module';
import { QuestionTemplateModule } from './question-template/question-template.module';
import { EmployeeModule } from './employee/employee.module';
import { DeclarationModule } from './declaration/declaration.module';
import { EvaluationsModule } from './evaluations/evaluations.module';

@Module({
imports: [
Expand All @@ -31,6 +32,7 @@ import { DeclarationModule } from './declaration/declaration.module';
QuestionTemplateModule,
EmployeeModule,
DeclarationModule,
EvaluationsModule,
],
})
export class AppModule {}
26 changes: 26 additions & 0 deletions src/evaluations/dto/submit-self-evaluation.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsArray, IsNotEmpty, IsNumber, IsString, ValidateNested } from 'class-validator';

/**
* 자기평가는 점수만 받는다. 서술형 필드는 DTO에 없으므로 보내면 400(forbidNonWhitelisted).
* 숫자가 아니면 400, 1~10 정수가 아니면 서비스에서 422 INVALID_SCORE.
*/
export class SelfEvaluationItemDto {
@ApiProperty({ example: 'uuid', description: '자기평가 조회 응답의 questionId' })
@IsString()
@IsNotEmpty()
questionId!: string;

@ApiProperty({ example: 8, minimum: 1, maximum: 10, description: '1~10 정수' })
@IsNumber()
selfScore!: number;
}

export class SubmitSelfEvaluationDto {
@ApiProperty({ type: [SelfEvaluationItemDto], description: '모든 평가 항목의 자기점수 (누락·중복 불가)' })
@IsArray()
@ValidateNested({ each: true })
@Type(() => SelfEvaluationItemDto)
items!: SelfEvaluationItemDto[];
}
131 changes: 131 additions & 0 deletions src/evaluations/evaluation-expiry.scheduler.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { Logger } from '@nestjs/common';
import { AccessLinkService } from '../access-link/access-link.service';
import { PrismaService } from '../prisma/prisma.service';
import { EvaluationExpiryScheduler } from './evaluation-expiry.scheduler';

type Row = Record<string, any>;

// evaluations·access_links를 메모리로 흉내 낸 가짜 DB (상태 전환 결과를 직접 확인하기 위함)
function createFakeDb(evaluations: Row[], links: Row[]) {
const matchValue = (actual: any, expected: any) => {
if (expected && typeof expected === 'object' && !(expected instanceof Date)) {
if ('lte' in expected) return actual <= expected.lte;
if ('in' in expected) return expected.in.includes(actual);
}
return actual === expected;
};
const matches = (row: Row, where: Row) => Object.entries(where).every(([k, v]) => matchValue(row[k], v));
const updateMany = (rows: Row[]) => async ({ where, data }: any) => {
const targets = rows.filter((r) => matches(r, where));
targets.forEach((r) => Object.assign(r, data));
return { count: targets.length };
};

const client: any = {
evaluation: {
findMany: async ({ where }: any) => evaluations.filter((e) => matches(e, where)).map((e) => ({ id: e.id })),
updateMany: updateMany(evaluations),
},
accessLink: { updateMany: updateMany(links) },
};
client.$transaction = async (fn: any) => fn(client);
return client;
}

describe('EvaluationExpiryScheduler', () => {
const NOW = new Date('2026-05-04T00:00:00.000Z'); // KST 5/4 09:00
const PAST_SELF_DUE = new Date('2026-05-03T14:59:59.000Z');
const FUTURE_SELF_DUE = new Date('2026-05-10T14:59:59.000Z');
const PAST_CEO_DUE = new Date('2026-05-03T14:59:59.000Z');
const FUTURE_CEO_DUE = new Date('2026-05-15T14:59:59.000Z');

let evaluations: Row[];
let links: Row[];
let scheduler: EvaluationExpiryScheduler;

const link = (id: string, targetId: string, over: Row = {}) => ({
id, purpose: 'SELF_EVALUATION', targetId, usedAt: null, revokedAt: null, ...over,
});

beforeEach(() => {
evaluations = [
{ id: 'ev-self-expired', status: 'SELF_PENDING', selfEvaluationDueAt: PAST_SELF_DUE, ceoEvaluationDueAt: FUTURE_CEO_DUE },
{ id: 'ev-self-pending', status: 'SELF_PENDING', selfEvaluationDueAt: FUTURE_SELF_DUE, ceoEvaluationDueAt: FUTURE_CEO_DUE },
{ id: 'ev-ceo-expired', status: 'CEO_PENDING', selfEvaluationDueAt: PAST_SELF_DUE, ceoEvaluationDueAt: PAST_CEO_DUE },
{ id: 'ev-ceo-pending', status: 'CEO_PENDING', selfEvaluationDueAt: PAST_SELF_DUE, ceoEvaluationDueAt: FUTURE_CEO_DUE },
{ id: 'ev-self-exp-ceo-past', status: 'SELF_EXPIRED', selfEvaluationDueAt: PAST_SELF_DUE, ceoEvaluationDueAt: PAST_CEO_DUE },
{ id: 'ev-completed', status: 'COMPLETED', selfEvaluationDueAt: PAST_SELF_DUE, ceoEvaluationDueAt: PAST_CEO_DUE },
];
links = [
link('l-1', 'ev-self-expired'),
link('l-2', 'ev-self-pending'),
link('l-3', 'ev-self-expired', { purpose: 'EVALUATION_RESULT' }),
];
const prisma = createFakeDb(evaluations, links) as unknown as PrismaService;
scheduler = new EvaluationExpiryScheduler(prisma, new AccessLinkService(prisma));
});

const statusOf = (id: string) => evaluations.find((e) => e.id === id)!.status;

it('자기평가 마감이 지난 SELF_PENDING만 SELF_EXPIRED로 바꾸고 그 평가의 자기평가 링크만 폐기한다', async () => {
const count = await scheduler.expireSelfEvaluations(NOW);

expect(count).toBe(1);
expect(statusOf('ev-self-expired')).toBe('SELF_EXPIRED');
expect(statusOf('ev-self-pending')).toBe('SELF_PENDING');
expect(links.find((l) => l.id === 'l-1')!.revokedAt).toBeInstanceOf(Date);
expect(links.find((l) => l.id === 'l-2')!.revokedAt).toBeNull(); // 마감 전 평가의 링크
expect(links.find((l) => l.id === 'l-3')!.revokedAt).toBeNull(); // 다른 목적 링크
});

it('대표 검증 마감이 지난 CEO_PENDING·SELF_EXPIRED만 CEO_EXPIRED로 바꾼다', async () => {
const count = await scheduler.expireCeoEvaluations(NOW);

expect(count).toBe(2);
expect(statusOf('ev-ceo-expired')).toBe('CEO_EXPIRED');
expect(statusOf('ev-self-exp-ceo-past')).toBe('CEO_EXPIRED');
expect(statusOf('ev-ceo-pending')).toBe('CEO_PENDING');
expect(statusOf('ev-completed')).toBe('COMPLETED'); // 완료된 평가는 건드리지 않음
expect(statusOf('ev-self-expired')).toBe('SELF_PENDING'); // 상태 조건 불일치
});

it('한 회차에서 자기평가 마감 → 대표 검증 마감까지 지난 평가는 CEO_EXPIRED까지 간다', async () => {
evaluations.push({ id: 'ev-both-past', status: 'SELF_PENDING', selfEvaluationDueAt: PAST_SELF_DUE, ceoEvaluationDueAt: PAST_CEO_DUE });
jest.useFakeTimers().setSystemTime(NOW);
const logSpy = jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);

await scheduler.run();

expect(statusOf('ev-both-past')).toBe('CEO_EXPIRED');
expect(statusOf('ev-self-expired')).toBe('SELF_EXPIRED');
expect(logSpy).toHaveBeenCalled();
logSpy.mockRestore();
jest.useRealTimers();
});

it('조회 직후 직원이 제출했으면(상태 변경) 만료 처리하지 않고 링크도 폐기하지 않는다', async () => {
const prisma: any = createFakeDb(evaluations, links);
const originalFindMany = prisma.evaluation.findMany;
prisma.evaluation.findMany = async (args: any) => {
const result = await originalFindMany(args);
evaluations.find((e) => e.id === 'ev-self-expired')!.status = 'CEO_PENDING'; // 그 사이 제출
return result;
};
const racing = new EvaluationExpiryScheduler(prisma, new AccessLinkService(prisma));

const count = await racing.expireSelfEvaluations(NOW);

expect(count).toBe(0);
expect(statusOf('ev-self-expired')).toBe('CEO_PENDING');
expect(links.find((l) => l.id === 'l-1')!.revokedAt).toBeNull();
});

it('처리 중 오류가 나도 예외를 밖으로 던지지 않고 로그만 남긴다', async () => {
const errorSpy = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
jest.spyOn(scheduler, 'expireSelfEvaluations').mockRejectedValue(new Error('DB down'));

await expect(scheduler.run()).resolves.toBeUndefined();
expect(errorSpy).toHaveBeenCalled();
errorSpy.mockRestore();
});
});
71 changes: 71 additions & 0 deletions src/evaluations/evaluation-expiry.scheduler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { AccessLinkService } from '../access-link/access-link.service';
import { PrismaService } from '../prisma/prisma.service';

/**
* 신규 흐름 평가(evaluations 테이블) 마감 처리.
* 레거시 EvaluationSchedulerService(employments 테이블)와는 대상이 다르다.
* ScheduleModule.forRoot()는 이미 등록돼 있어 @Cron만 사용한다.
*/
@Injectable()
export class EvaluationExpiryScheduler {
private readonly logger = new Logger(EvaluationExpiryScheduler.name);

constructor(
private readonly prisma: PrismaService,
private readonly accessLinkService: AccessLinkService,
) {}

@Cron(CronExpression.EVERY_HOUR)
async run(): Promise<void> {
try {
// 자기평가 만료를 먼저 처리해야, 같은 회차에 대표 검증 마감도 지난 건이 CEO_EXPIRED까지 간다
const selfExpired = await this.expireSelfEvaluations();
const ceoExpired = await this.expireCeoEvaluations();
if (selfExpired + ceoExpired > 0) {
this.logger.log(`평가 만료 처리: SELF_EXPIRED ${selfExpired}건, CEO_EXPIRED ${ceoExpired}건`);
}
} catch (error) {
this.logger.error('평가 만료 처리 실패', error instanceof Error ? error.stack : String(error));
}
}

/** 자기평가 마감이 지난 SELF_PENDING → SELF_EXPIRED, 남은 자기평가 링크 폐기. 처리 건수 반환 */
async expireSelfEvaluations(now: Date = new Date()): Promise<number> {
const targets = await this.prisma.evaluation.findMany({
where: { status: 'SELF_PENDING', selfEvaluationDueAt: { lte: now } },
select: { id: true },
});

let expired = 0;
for (const { id } of targets) {
// 건별 트랜잭션: 조회 직후 직원이 제출했다면 상태 조건에 걸려 0건 → 링크도 건드리지 않는다
const changed = await this.prisma.$transaction(async (tx) => {
const { count } = await tx.evaluation.updateMany({
where: { id, status: 'SELF_PENDING', selfEvaluationDueAt: { lte: now } },
data: { status: 'SELF_EXPIRED' },
});
if (count === 0) {
return false;
}
await this.accessLinkService.revokeActive('SELF_EVALUATION', id, tx);
return true;
});
if (changed) expired++;
}
return expired;
}

/** 대표 검증 마감이 지난 CEO_PENDING·SELF_EXPIRED → CEO_EXPIRED. 처리 건수 반환 */
async expireCeoEvaluations(now: Date = new Date()): Promise<number> {
const { count } = await this.prisma.evaluation.updateMany({
where: {
status: { in: ['CEO_PENDING', 'SELF_EXPIRED'] },
ceoEvaluationDueAt: { lte: now },
},
data: { status: 'CEO_EXPIRED' },
});
return count;
}
}
7 changes: 7 additions & 0 deletions src/evaluations/evaluation.constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/** 신규 흐름 평가 점수 범위 (자기평가·대표 검증·공통 역량 공통) */
export const SCORE_MIN = 1;
export const SCORE_MAX = 10;

export function isValidScore(score: unknown): score is number {
return Number.isInteger(score) && (score as number) >= SCORE_MIN && (score as number) <= SCORE_MAX;
}
14 changes: 14 additions & 0 deletions src/evaluations/evaluations.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { AccessLinkModule } from '../access-link/access-link.module';
import { AuditModule } from '../audit/audit.module';
import { EvaluationExpiryScheduler } from './evaluation-expiry.scheduler';
import { SelfEvaluationController } from './self-evaluation.controller';
import { SelfEvaluationService } from './self-evaluation.service';

/** 신규 흐름 평가 모듈 (src/evaluations, 복수). 레거시 src/evaluation(단수)과 별개 */
@Module({
imports: [AccessLinkModule, AuditModule],
controllers: [SelfEvaluationController],
providers: [SelfEvaluationService, EvaluationExpiryScheduler],
})
export class EvaluationsModule {}
46 changes: 46 additions & 0 deletions src/evaluations/self-evaluation.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { Body, Controller, Get, Headers, HttpCode, HttpStatus, Ip, Param, Post } from '@nestjs/common';
import { ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger';
import { ResponseMessage } from '../common/decorators/response-message.decorator';
import { SubmitSelfEvaluationDto } from './dto/submit-self-evaluation.dto';
import { SelfEvaluationService } from './self-evaluation.service';

/**
* 직원용 자기평가 API. 메일로 받은 1회성 링크 토큰으로만 인증한다.
* 레거시 /evaluation/*(단수)과 라우트가 겹치지 않는다.
*/
@ApiTags('Evaluations')
@Controller('evaluations/self')
export class SelfEvaluationController {
constructor(private readonly selfEvaluationService: SelfEvaluationService) {}

@Get(':token')
@ApiOperation({ summary: '직원: 자기평가 폼 조회 (링크 토큰, 자기선언 답변 포함, 링크 소비 안 함)' })
@ApiParam({ name: 'token', description: '메일로 받은 자기평가 링크 토큰' })
@ApiResponse({ status: 200, description: '조회 성공 { evaluationId, employee, status, dueAt, scoreMin, scoreMax, items }' })
@ApiResponse({ status: 403, description: 'INVALID_LINK_PURPOSE (자기평가용 토큰 아님)' })
@ApiResponse({ status: 409, description: 'INVALID_EVALUATION_STATUS (자기평가 가능한 상태 아님) / ALREADY_SUBMITTED' })
@ApiResponse({ status: 410, description: 'LINK_EXPIRED (링크 만료 또는 폐기)' })
@ResponseMessage('직원 자기평가 폼 조회 성공')
getForm(@Param('token') token: string) {
return this.selfEvaluationService.getForm(token);
}

@Post(':token/submit')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: '직원: 자기평가 제출 (항목별 1~10점, 제출 후 CEO_PENDING, 수정 불가)' })
@ApiParam({ name: 'token', description: '메일로 받은 자기평가 링크 토큰' })
@ApiResponse({ status: 201, description: '제출 성공 { evaluationId, status, submittedAt, ceoEvaluationDueAt }' })
@ApiResponse({ status: 400, description: 'MISSING_EVALUATION_ITEM (항목 누락·중복) 또는 형식 오류' })
@ApiResponse({ status: 409, description: 'ALREADY_SUBMITTED (이미 제출 완료)' })
@ApiResponse({ status: 410, description: 'LINK_EXPIRED (링크 만료 또는 폐기)' })
@ApiResponse({ status: 422, description: 'INVALID_SCORE (점수 범위 1~10 위반)' })
@ResponseMessage('직원 자기평가 제출 성공')
submit(
@Param('token') token: string,
@Body() dto: SubmitSelfEvaluationDto,
@Ip() ip: string,
@Headers('user-agent') userAgent?: string,
) {
return this.selfEvaluationService.submit(token, dto, { ip, userAgent });
}
}
Loading
Loading