From 486dad154f9ca6dac2cdf520a93cd0b6454ef7c4 Mon Sep 17 00:00:00 2001 From: ChaeYeon Lee Date: Fri, 9 Oct 2026 20:25:21 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=A7=81=EC=9B=90=20=EC=9E=90=EA=B8=B0?= =?UTF-8?q?=ED=8F=89=EA=B0=80=20=ED=8F=BC=C2=B7=EC=A0=9C=EC=B6=9C=20API=20?= =?UTF-8?q?=EB=B0=8F=20=ED=8F=89=EA=B0=80=20=EB=A7=8C=EB=A3=8C=20=EC=8A=A4?= =?UTF-8?q?=EC=BC=80=EC=A4=84=EB=9F=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 신규 src/evaluations(복수) 모듈, 레거시 src/evaluation(단수)은 변경 없음 - GET /evaluations/self/:token: 자기선언 답변 + 평가 항목 조회 (링크 소비 안 함), SELF_PENDING 아니면 409 INVALID_EVALUATION_STATUS - POST /evaluations/self/:token/submit: 항목별 1~10점 제출 → CEO_PENDING, 링크 소비 - 항목 누락·중복 400 MISSING_EVALUATION_ITEM, 점수 위반 422 INVALID_SCORE, 재제출 409 ALREADY_SUBMITTED - EvaluationExpiryScheduler(매시간): 자기평가 마감 → SELF_EXPIRED + 링크 폐기, 대표 검증 마감 → CEO_EXPIRED Co-Authored-By: Claude Opus 5.5 --- src/app.module.ts | 2 + .../dto/submit-self-evaluation.dto.ts | 26 +++ .../evaluation-expiry.scheduler.spec.ts | 131 +++++++++++ .../evaluation-expiry.scheduler.ts | 71 ++++++ src/evaluations/evaluation.constants.ts | 7 + src/evaluations/evaluations.module.ts | 14 ++ src/evaluations/self-evaluation.controller.ts | 46 ++++ .../self-evaluation.service.spec.ts | 214 ++++++++++++++++++ src/evaluations/self-evaluation.service.ts | 203 +++++++++++++++++ 9 files changed, 714 insertions(+) create mode 100644 src/evaluations/dto/submit-self-evaluation.dto.ts create mode 100644 src/evaluations/evaluation-expiry.scheduler.spec.ts create mode 100644 src/evaluations/evaluation-expiry.scheduler.ts create mode 100644 src/evaluations/evaluation.constants.ts create mode 100644 src/evaluations/evaluations.module.ts create mode 100644 src/evaluations/self-evaluation.controller.ts create mode 100644 src/evaluations/self-evaluation.service.spec.ts create mode 100644 src/evaluations/self-evaluation.service.ts diff --git a/src/app.module.ts b/src/app.module.ts index 99b01b8..1dea193 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -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: [ @@ -31,6 +32,7 @@ import { DeclarationModule } from './declaration/declaration.module'; QuestionTemplateModule, EmployeeModule, DeclarationModule, + EvaluationsModule, ], }) export class AppModule {} diff --git a/src/evaluations/dto/submit-self-evaluation.dto.ts b/src/evaluations/dto/submit-self-evaluation.dto.ts new file mode 100644 index 0000000..a27885c --- /dev/null +++ b/src/evaluations/dto/submit-self-evaluation.dto.ts @@ -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[]; +} diff --git a/src/evaluations/evaluation-expiry.scheduler.spec.ts b/src/evaluations/evaluation-expiry.scheduler.spec.ts new file mode 100644 index 0000000..47f5090 --- /dev/null +++ b/src/evaluations/evaluation-expiry.scheduler.spec.ts @@ -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; + +// 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(); + }); +}); diff --git a/src/evaluations/evaluation-expiry.scheduler.ts b/src/evaluations/evaluation-expiry.scheduler.ts new file mode 100644 index 0000000..25532e5 --- /dev/null +++ b/src/evaluations/evaluation-expiry.scheduler.ts @@ -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 { + 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 { + 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 { + const { count } = await this.prisma.evaluation.updateMany({ + where: { + status: { in: ['CEO_PENDING', 'SELF_EXPIRED'] }, + ceoEvaluationDueAt: { lte: now }, + }, + data: { status: 'CEO_EXPIRED' }, + }); + return count; + } +} diff --git a/src/evaluations/evaluation.constants.ts b/src/evaluations/evaluation.constants.ts new file mode 100644 index 0000000..0ed210f --- /dev/null +++ b/src/evaluations/evaluation.constants.ts @@ -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; +} diff --git a/src/evaluations/evaluations.module.ts b/src/evaluations/evaluations.module.ts new file mode 100644 index 0000000..1aecfbd --- /dev/null +++ b/src/evaluations/evaluations.module.ts @@ -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 {} diff --git a/src/evaluations/self-evaluation.controller.ts b/src/evaluations/self-evaluation.controller.ts new file mode 100644 index 0000000..b96a6b5 --- /dev/null +++ b/src/evaluations/self-evaluation.controller.ts @@ -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 }); + } +} diff --git a/src/evaluations/self-evaluation.service.spec.ts b/src/evaluations/self-evaluation.service.spec.ts new file mode 100644 index 0000000..c4fdabd --- /dev/null +++ b/src/evaluations/self-evaluation.service.spec.ts @@ -0,0 +1,214 @@ +import { + BadRequestException, + ConflictException, + ForbiddenException, + GoneException, + HttpException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { AccessLinkService } from '../access-link/access-link.service'; +import { AuditService } from '../audit/audit.service'; +import { PrismaService } from '../prisma/prisma.service'; +import { SelfEvaluationService } from './self-evaluation.service'; + +const META = { ip: '127.0.0.1', userAgent: 'jest' }; +const CEO_DUE = new Date('2026-05-15T14:59:59.000Z'); + +const snapshot = (id: string, order: number, type: string, extra: Record, response: Record | null) => ({ + id, declarationId: 'decl-1', order, type, text: `질문 ${order}`, required: true, + scoreMin: null, scoreMax: null, options: null, maxLength: null, evaluationEnabled: true, + ...extra, + response: response && { id: `resp-${id}`, snapshotQuestionId: id, answerScore: null, answerOptionId: null, answerText: null, ...response }, +}); + +const evaluationWithItems = (over: Record = {}) => ({ + id: 'ev-1', + companyId: 'comp-1', + employeeId: 'emp-1', + status: 'SELF_PENDING', + selfEvaluationDueAt: new Date('2026-05-03T14:59:59.000Z'), + ceoEvaluationDueAt: CEO_DUE, + employee: { name: '김민준' }, + items: [ + { id: 'it-1', snapshotQuestionId: 'snap-1', order: 1, selfScore: null, ceoScore: null, + snapshotQuestion: snapshot('snap-1', 1, 'SCORE', { scoreMin: 1, scoreMax: 10 }, { answerScore: 8 }) }, + { id: 'it-2', snapshotQuestionId: 'snap-2', order: 2, selfScore: null, ceoScore: null, + snapshotQuestion: snapshot('snap-2', 2, 'SINGLE_CHOICE', { options: [{ optionId: 'opt-a', label: '개인' }, { optionId: 'opt-b', label: '팀' }] }, { answerOptionId: 'opt-b' }) }, + { id: 'it-3', snapshotQuestionId: 'snap-3', order: 3, selfScore: null, ceoScore: null, + snapshotQuestion: snapshot('snap-3', 3, 'TEXT', { maxLength: 500 }, { answerText: 'React 성능 개선' }) }, + ], + ...over, +}); + +const ITEMS = [ + { questionId: 'snap-1', selfScore: 8 }, + { questionId: 'snap-2', selfScore: 7 }, + { questionId: 'snap-3', selfScore: 9 }, +]; + +async function expectCode( + promise: Promise, + type: new (...args: any[]) => HttpException, + code: string, +) { + const error = await promise.then( + () => { + throw new Error('예외가 발생해야 합니다.'); + }, + (e) => e, + ); + expect(error).toBeInstanceOf(type); + expect((error as HttpException).getResponse()).toMatchObject({ code }); +} + +describe('SelfEvaluationService', () => { + let prismaMock: any; + let accessLinkMock: { verify: jest.Mock; consume: jest.Mock }; + let auditMock: { log: jest.Mock }; + let service: SelfEvaluationService; + + beforeEach(() => { + prismaMock = { + evaluation: { + findUnique: jest.fn().mockResolvedValue(evaluationWithItems()), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + evaluationItem: { updateMany: jest.fn().mockResolvedValue({ count: 1 }) }, + company: { findUnique: jest.fn().mockResolvedValue({ companyName: '테크플러스 주식회사' }) }, + $transaction: jest.fn(async (fn: any) => fn(prismaMock)), + }; + accessLinkMock = { + verify: jest.fn().mockResolvedValue({ id: 'link-1', purpose: 'SELF_EVALUATION', targetId: 'ev-1', expiresAt: new Date() }), + consume: jest.fn().mockResolvedValue(undefined), + }; + auditMock = { log: jest.fn().mockResolvedValue(undefined) }; + service = new SelfEvaluationService( + prismaMock as unknown as PrismaService, + accessLinkMock as unknown as AccessLinkService, + auditMock as unknown as AuditService, + ); + }); + + describe('getForm', () => { + it('자기선언 답변과 평가 항목을 order순으로 반환하고 링크는 소비하지 않는다', async () => { + const form = await service.getForm('tok'); + + expect(accessLinkMock.verify).toHaveBeenCalledWith('tok', 'SELF_EVALUATION'); + expect(accessLinkMock.consume).not.toHaveBeenCalled(); + expect(form).toEqual({ + evaluationId: 'ev-1', + employee: { name: '김민준', companyName: '테크플러스 주식회사' }, + status: 'SELF_PENDING', + dueAt: new Date('2026-05-03T14:59:59.000Z'), + scoreMin: 1, + scoreMax: 10, + items: [ + { questionId: 'snap-1', order: 1, question: '질문 1', declarationAnswer: { type: 'SCORE', score: 8 }, selfScore: null }, + { questionId: 'snap-2', order: 2, question: '질문 2', declarationAnswer: { type: 'SINGLE_CHOICE', optionId: 'opt-b', label: '팀' }, selfScore: null }, + { questionId: 'snap-3', order: 3, question: '질문 3', declarationAnswer: { type: 'TEXT', text: 'React 성능 개선' }, selfScore: null }, + ], + }); + }); + + it('자기선언에서 답하지 않은 선택 질문은 답변 값이 null', async () => { + const ev = evaluationWithItems(); + ev.items[2].snapshotQuestion = snapshot('snap-3', 3, 'TEXT', { maxLength: 500, required: false }, null); + prismaMock.evaluation.findUnique.mockResolvedValue(ev); + + const form = await service.getForm('tok'); + + expect(form.items[2].declarationAnswer).toEqual({ type: 'TEXT', text: null }); + }); + + it.each(['CEO_PENDING', 'SELF_EXPIRED', 'COMPLETED', 'CEO_EXPIRED'])( + 'SELF_PENDING이 아니면(%s) 409 INVALID_EVALUATION_STATUS', + async (status) => { + prismaMock.evaluation.findUnique.mockResolvedValue(evaluationWithItems({ status })); + await expectCode(service.getForm('tok'), ConflictException, 'INVALID_EVALUATION_STATUS'); + }, + ); + + it('링크 검증 오류(410 만료, 403 목적 불일치)는 그대로 전달된다', async () => { + accessLinkMock.verify.mockRejectedValueOnce(new GoneException({ code: 'LINK_EXPIRED' })); + await expectCode(service.getForm('tok'), GoneException, 'LINK_EXPIRED'); + + accessLinkMock.verify.mockRejectedValueOnce(new ForbiddenException({ code: 'INVALID_LINK_PURPOSE' })); + await expectCode(service.getForm('tok'), ForbiddenException, 'INVALID_LINK_PURPOSE'); + }); + }); + + describe('submit', () => { + it('자기점수 저장 → CEO_PENDING 전환 → 링크 소비를 한 트랜잭션에서 처리한다', async () => { + const result = await service.submit('tok', { items: ITEMS }, META); + + expect(result).toEqual({ + evaluationId: 'ev-1', + status: 'CEO_PENDING', + submittedAt: expect.any(Date), + ceoEvaluationDueAt: CEO_DUE, + }); + expect(accessLinkMock.verify).toHaveBeenCalledWith('tok', 'SELF_EVALUATION', prismaMock); + expect(prismaMock.evaluation.updateMany).toHaveBeenCalledWith({ + where: { id: 'ev-1', status: 'SELF_PENDING' }, + data: { status: 'CEO_PENDING', selfSubmittedAt: result.submittedAt }, + }); + expect(prismaMock.evaluationItem.updateMany).toHaveBeenCalledTimes(3); + expect(prismaMock.evaluationItem.updateMany).toHaveBeenCalledWith({ + where: { evaluationId: 'ev-1', snapshotQuestionId: 'snap-2' }, + data: { selfScore: 7 }, + }); + expect(accessLinkMock.consume).toHaveBeenCalledWith('link-1', prismaMock); + expect(auditMock.log).toHaveBeenCalledWith( + expect.objectContaining({ actorType: 'EMPLOYEE', action: 'SELF_EVALUATION_SUBMITTED', targetId: 'ev-1' }), + prismaMock, + ); + }); + + it('항목 누락·중복·없는 항목이면 400 MISSING_EVALUATION_ITEM이고 저장하지 않는다', async () => { + await expectCode(service.submit('tok', { items: ITEMS.slice(0, 2) }, META), BadRequestException, 'MISSING_EVALUATION_ITEM'); + await expectCode(service.submit('tok', { items: [...ITEMS, ITEMS[0]] }, META), BadRequestException, 'MISSING_EVALUATION_ITEM'); + await expectCode( + service.submit('tok', { items: [...ITEMS, { questionId: 'snap-x', selfScore: 5 }] }, META), + BadRequestException, + 'MISSING_EVALUATION_ITEM', + ); + expect(prismaMock.evaluation.updateMany).not.toHaveBeenCalled(); + expect(accessLinkMock.consume).not.toHaveBeenCalled(); + }); + + it.each([0, 11, 7.5, -1])('점수가 1~10 정수가 아니면(%s) 422 INVALID_SCORE', async (score) => { + await expectCode( + service.submit('tok', { items: [{ questionId: 'snap-1', selfScore: score }, ITEMS[1], ITEMS[2]] }, META), + UnprocessableEntityException, + 'INVALID_SCORE', + ); + expect(prismaMock.evaluation.updateMany).not.toHaveBeenCalled(); + }); + + it('SELF_PENDING이 아니면 409 ALREADY_SUBMITTED', async () => { + prismaMock.evaluation.findUnique.mockResolvedValue(evaluationWithItems({ status: 'CEO_PENDING' })); + await expectCode(service.submit('tok', { items: ITEMS }, META), ConflictException, 'ALREADY_SUBMITTED'); + }); + + it('동시 제출로 먼저 전환됐으면(갱신 0건) 409 ALREADY_SUBMITTED이고 점수·링크를 건드리지 않는다', async () => { + prismaMock.evaluation.updateMany.mockResolvedValue({ count: 0 }); + await expectCode(service.submit('tok', { items: ITEMS }, META), ConflictException, 'ALREADY_SUBMITTED'); + expect(prismaMock.evaluationItem.updateMany).not.toHaveBeenCalled(); + expect(accessLinkMock.consume).not.toHaveBeenCalled(); + }); + + it('이미 사용된 링크(409)·만료 링크(410)는 링크 검증에서 막힌다', async () => { + accessLinkMock.verify.mockRejectedValueOnce(new ConflictException({ code: 'ALREADY_SUBMITTED' })); + await expectCode(service.submit('tok', { items: ITEMS }, META), ConflictException, 'ALREADY_SUBMITTED'); + + accessLinkMock.verify.mockRejectedValueOnce(new GoneException({ code: 'LINK_EXPIRED' })); + await expectCode(service.submit('tok', { items: ITEMS }, META), GoneException, 'LINK_EXPIRED'); + expect(prismaMock.evaluation.updateMany).not.toHaveBeenCalled(); + }); + + it('평가 항목이 0개면 빈 items로 제출할 수 있다', async () => { + prismaMock.evaluation.findUnique.mockResolvedValue(evaluationWithItems({ items: [] })); + await expect(service.submit('tok', { items: [] }, META)).resolves.toMatchObject({ status: 'CEO_PENDING' }); + }); + }); +}); diff --git a/src/evaluations/self-evaluation.service.ts b/src/evaluations/self-evaluation.service.ts new file mode 100644 index 0000000..a9f3c79 --- /dev/null +++ b/src/evaluations/self-evaluation.service.ts @@ -0,0 +1,203 @@ +import { + BadRequestException, + ConflictException, + GoneException, + Injectable, + UnprocessableEntityException, +} from '@nestjs/common'; +import { DeclarationQuestionSnapshot, DeclarationResponse } from '@prisma/client'; +import { AccessLinkService } from '../access-link/access-link.service'; +import { AuditService } from '../audit/audit.service'; +import { SnapshotOption } from '../declaration/declaration.constants'; +import { PrismaService } from '../prisma/prisma.service'; +import { SubmitSelfEvaluationDto } from './dto/submit-self-evaluation.dto'; +import { SCORE_MAX, SCORE_MIN, isValidScore } from './evaluation.constants'; + +export interface RequestMeta { + ip?: string | null; + userAgent?: string | null; +} + +@Injectable() +export class SelfEvaluationService { + constructor( + private readonly prisma: PrismaService, + private readonly accessLinkService: AccessLinkService, + private readonly auditService: AuditService, + ) {} + + /** 퇴사 직원이 링크로 자기평가 폼을 조회한다. 조회만으로는 링크를 소비하지 않는다. */ + async getForm(token: string) { + const link = await this.accessLinkService.verify(token, 'SELF_EVALUATION'); + + const evaluation = await this.prisma.evaluation.findUnique({ + where: { id: link.targetId }, + include: { + employee: { select: { name: true } }, + items: { + orderBy: { order: 'asc' }, + include: { snapshotQuestion: { include: { response: true } } }, + }, + }, + }); + if (!evaluation) { + throw linkExpired(); + } + if (evaluation.status !== 'SELF_PENDING') { + throw new ConflictException({ + code: 'INVALID_EVALUATION_STATUS', + message: '자기평가를 진행할 수 있는 상태가 아닙니다.', + details: { status: evaluation.status }, + }); + } + + const company = await this.prisma.company.findUnique({ + where: { id: evaluation.companyId }, + select: { companyName: true }, + }); + + return { + evaluationId: evaluation.id, + employee: { name: evaluation.employee.name, companyName: company?.companyName ?? null }, + status: evaluation.status, + dueAt: evaluation.selfEvaluationDueAt, + scoreMin: SCORE_MIN, + scoreMax: SCORE_MAX, + items: evaluation.items.map((item) => ({ + questionId: item.snapshotQuestionId, + order: item.order, + question: item.snapshotQuestion.text, + declarationAnswer: toDeclarationAnswer(item.snapshotQuestion), + selfScore: item.selfScore, + })), + }; + } + + /** 자기점수를 제출하고 대표 검증 단계(CEO_PENDING)로 넘긴다. 이후 수정할 수 없다. */ + async submit(token: string, dto: SubmitSelfEvaluationDto, meta: RequestMeta) { + return this.prisma.$transaction(async (tx) => { + const link = await this.accessLinkService.verify(token, 'SELF_EVALUATION', tx); + + const evaluation = await tx.evaluation.findUnique({ + where: { id: link.targetId }, + include: { items: { select: { snapshotQuestionId: true } } }, + }); + if (!evaluation) { + throw linkExpired(); + } + if (evaluation.status !== 'SELF_PENDING') { + throw alreadySubmitted(); + } + + assertAllItemsOnce( + evaluation.items.map((item) => item.snapshotQuestionId), + dto.items.map((item) => item.questionId), + ); + + const invalid = dto.items.filter((item) => !isValidScore(item.selfScore)); + if (invalid.length > 0) { + throw new UnprocessableEntityException({ + code: 'INVALID_SCORE', + message: `점수는 ${SCORE_MIN}~${SCORE_MAX} 사이의 정수여야 합니다.`, + details: { questionIds: invalid.map((item) => item.questionId) }, + }); + } + + const submittedAt = new Date(); + + // 동시 제출 시 하나만 통과 (SELF_PENDING일 때만 CEO_PENDING으로 전환) + const { count } = await tx.evaluation.updateMany({ + where: { id: evaluation.id, status: 'SELF_PENDING' }, + data: { status: 'CEO_PENDING', selfSubmittedAt: submittedAt }, + }); + if (count === 0) { + throw alreadySubmitted(); + } + + for (const item of dto.items) { + await tx.evaluationItem.updateMany({ + where: { evaluationId: evaluation.id, snapshotQuestionId: item.questionId }, + data: { selfScore: item.selfScore }, + }); + } + + await this.accessLinkService.consume(link.id, tx); + + await this.auditService.log( + { + actorType: 'EMPLOYEE', + actorId: evaluation.employeeId, + action: 'SELF_EVALUATION_SUBMITTED', + targetType: 'Evaluation', + targetId: evaluation.id, + ip: meta.ip, + userAgent: meta.userAgent, + metadata: { itemCount: dto.items.length }, + }, + tx, + ); + + return { + evaluationId: evaluation.id, + status: 'CEO_PENDING' as const, + submittedAt, + ceoEvaluationDueAt: evaluation.ceoEvaluationDueAt, + }; + }); + } +} + +/** 평가 항목이 빠짐없이, 한 번씩만 들어왔는지 확인 (없는 항목 포함 시에도 400) */ +function assertAllItemsOnce(expectedIds: string[], receivedIds: string[]): void { + const expected = new Set(expectedIds); + const seen = new Set(); + const duplicated = new Set(); + const unknown: string[] = []; + + for (const id of receivedIds) { + if (seen.has(id)) duplicated.add(id); + seen.add(id); + if (!expected.has(id)) unknown.push(id); + } + const missing = expectedIds.filter((id) => !seen.has(id)); + + if (missing.length > 0 || duplicated.size > 0 || unknown.length > 0) { + throw new BadRequestException({ + code: 'MISSING_EVALUATION_ITEM', + message: '모든 평가 항목에 한 번씩 점수를 입력해야 합니다.', + details: { missing, duplicated: [...duplicated], unknown }, + }); + } +} + +/** 자기선언 때 직원이 한 답변. 미응답이면 값은 null */ +function toDeclarationAnswer( + snapshot: DeclarationQuestionSnapshot & { response: DeclarationResponse | null }, +) { + const response = snapshot.response; + switch (snapshot.type) { + case 'SCORE': + return { type: 'SCORE' as const, score: response?.answerScore ?? null }; + case 'SINGLE_CHOICE': { + const options = (snapshot.options as SnapshotOption[] | null) ?? []; + const option = options.find((o) => o.optionId === response?.answerOptionId); + return { type: 'SINGLE_CHOICE' as const, optionId: option?.optionId ?? null, label: option?.label ?? null }; + } + case 'TEXT': + return { type: 'TEXT' as const, text: response?.answerText ?? null }; + } +} + +function alreadySubmitted(): ConflictException { + return new ConflictException({ + code: 'ALREADY_SUBMITTED', + message: '이미 자기평가를 제출했습니다.', + }); +} + +function linkExpired(): GoneException { + return new GoneException({ + code: 'LINK_EXPIRED', + message: '만료되었거나 유효하지 않은 링크입니다.', + }); +}