diff --git a/src/evaluations/ceo-evaluation.controller.ts b/src/evaluations/ceo-evaluation.controller.ts new file mode 100644 index 0000000..9d207ea --- /dev/null +++ b/src/evaluations/ceo-evaluation.controller.ts @@ -0,0 +1,57 @@ +import { Body, Controller, Get, Headers, HttpCode, HttpStatus, Ip, Param, Post, UseGuards } from '@nestjs/common'; +import { ApiBearerAuth, ApiOperation, ApiParam, ApiResponse, ApiTags } from '@nestjs/swagger'; +import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; +import { JwtPayload } from '../auth/strategies/jwt.strategy'; +import { ResponseMessage } from '../common/decorators/response-message.decorator'; +import { CurrentUser } from '../core/decorators/current-user.decorator'; +import { Roles } from '../core/decorators/roles.decorator'; +import { RolesGuard } from '../core/guards/roles.guard'; +import { CeoEvaluationService } from './ceo-evaluation.service'; +import { SubmitCeoEvaluationDto } from './dto/submit-ceo-evaluation.dto'; + +/** 대표 검증 API (CEO JWT). 레거시 /evaluation/ceo/:employmentId(단수)와 라우트가 겹치지 않는다. */ +@ApiTags('Evaluations') +@ApiBearerAuth('access-token') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('COMPANY') +@Controller('evaluations') +export class CeoEvaluationController { + constructor(private readonly ceoEvaluationService: CeoEvaluationService) {} + + @Get(':evaluationId/ceo') + @ApiOperation({ summary: '대표: 검증 평가 폼 조회 (자기선언 답변·자기점수 + 공통 역량 6개)' }) + @ApiParam({ name: 'evaluationId', description: '평가 ID' }) + @ApiResponse({ status: 200, description: '조회 성공' }) + @ApiResponse({ status: 401, description: '인증 필요' }) + @ApiResponse({ status: 403, description: 'FORBIDDEN (대표 권한·직원 소속 불일치) / STILL_EMPLOYED (재직 중)' }) + @ApiResponse({ status: 404, description: 'EVALUATION_NOT_FOUND' }) + @ApiResponse({ status: 409, description: 'ALREADY_COMPLETED / INVALID_EVALUATION_STATUS' }) + @ApiResponse({ status: 410, description: 'EVALUATION_EXPIRED (퇴사일 + 15일 대표 검증 기한 초과)' }) + @ResponseMessage('대표 검증 평가 폼 조회 성공') + getForm(@CurrentUser() user: JwtPayload, @Param('evaluationId') evaluationId: string) { + return this.ceoEvaluationService.getForm(user, evaluationId); + } + + @Post(':evaluationId/ceo') + @HttpCode(HttpStatus.CREATED) + @ApiOperation({ summary: '대표: 검증 평가 제출 (항목 점수 + 공통 역량 6개 + 재고용 의사, 제출 후 수정 불가)' }) + @ApiParam({ name: 'evaluationId', description: '평가 ID' }) + @ApiResponse({ status: 201, description: '제출 성공 { evaluationId, status, completedAt, resultNotified, opinionDueAt }' }) + @ApiResponse({ status: 400, description: 'MISSING_EVALUATION_ITEM (항목·역량 누락·중복) 또는 형식 오류(서술형 필드, rehireIntent 비boolean)' }) + @ApiResponse({ status: 401, description: '인증 필요' }) + @ApiResponse({ status: 403, description: 'FORBIDDEN / STILL_EMPLOYED (재직 중)' }) + @ApiResponse({ status: 404, description: 'EVALUATION_NOT_FOUND' }) + @ApiResponse({ status: 409, description: 'ALREADY_COMPLETED / INVALID_EVALUATION_STATUS' }) + @ApiResponse({ status: 410, description: 'EVALUATION_EXPIRED (퇴사일 + 15일 대표 검증 기한 초과)' }) + @ApiResponse({ status: 422, description: 'INVALID_SCORE (점수 범위 1~10 위반)' }) + @ResponseMessage('대표 검증 평가 제출 성공') + submit( + @CurrentUser() user: JwtPayload, + @Param('evaluationId') evaluationId: string, + @Body() dto: SubmitCeoEvaluationDto, + @Ip() ip: string, + @Headers('user-agent') userAgent?: string, + ) { + return this.ceoEvaluationService.submit(user, evaluationId, dto, { ip, userAgent }); + } +} diff --git a/src/evaluations/ceo-evaluation.service.spec.ts b/src/evaluations/ceo-evaluation.service.spec.ts new file mode 100644 index 0000000..4d7695c --- /dev/null +++ b/src/evaluations/ceo-evaluation.service.spec.ts @@ -0,0 +1,402 @@ +import { + BadRequestException, + ConflictException, + ForbiddenException, + GoneException, + HttpException, + NotFoundException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { AccessLinkService } from '../access-link/access-link.service'; +import { AuditService } from '../audit/audit.service'; +import { MailService } from '../notification/mail.service'; +import { PrismaService } from '../prisma/prisma.service'; +import { CeoEvaluationService } from './ceo-evaluation.service'; +import { SubmitCeoEvaluationDto } from './dto/submit-ceo-evaluation.dto'; + +// 법적 로직 테스트 — 시간은 모두 jest fake timers로 고정한다 +const CEO = { sub: 'comp-1', role: 'COMPANY' as const }; +const META = { ip: '127.0.0.1', userAgent: 'jest' }; +const CEO_DUE = new Date('2026-05-15T14:59:59.000Z'); // 퇴사일 2026-04-30 + 15일 KST 23:59:59 +const BEFORE_DUE = new Date('2026-05-10T01:00:00.000Z'); // KST 5/10 10:00 +const ONE_SECOND = 1000; + +type State = Record; + +const snapshot = (id: string, order: number, type: string, response: Record) => ({ + id, declarationId: 'decl-1', order, type, text: `질문 ${order}`, required: true, + scoreMin: 1, scoreMax: 10, options: null, maxLength: 500, evaluationEnabled: true, + response: { id: `r-${id}`, snapshotQuestionId: id, answerScore: null, answerOptionId: null, answerText: null, ...response }, +}); + +const ITEMS_DB = [ + { id: 'it-1', evaluationId: 'ev-1', snapshotQuestionId: 'snap-1', order: 1, selfScore: 8, ceoScore: null, + snapshotQuestion: snapshot('snap-1', 1, 'SCORE', { answerScore: 8 }) }, + { id: 'it-2', evaluationId: 'ev-1', snapshotQuestionId: 'snap-3', order: 3, selfScore: 7, ceoScore: null, + snapshotQuestion: snapshot('snap-3', 3, 'TEXT', { answerText: 'React 성능 개선 경험' }) }, +]; + +const COMPETENCIES = [ + { key: 'TRUST', score: 8 }, + { key: 'DILIGENCE', score: 9 }, + { key: 'RESPONSIBILITY', score: 8 }, + { key: 'COLLABORATION', score: 7 }, + { key: 'COMMUNICATION', score: 7 }, + { key: 'GROWTH_POTENTIAL', score: 9 }, +] as SubmitCeoEvaluationDto['commonCompetencies']; + +const validDto = (over: Partial = {}): SubmitCeoEvaluationDto => ({ + items: [ + { questionId: 'snap-1', ceoScore: 7 }, + { questionId: 'snap-3', ceoScore: 8 }, + ], + commonCompetencies: COMPETENCIES, + rehireIntent: true, + ...over, +}); + +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('CeoEvaluationService (법적 안전 로직)', () => { + let state: State; // DB의 evaluation 한 건 + let prismaMock: any; + let accessLinkMock: { issue: jest.Mock }; + let mailMock: { sendEvaluationResult: jest.Mock }; + let auditMock: { log: jest.Mock }; + let service: CeoEvaluationService; + let committed: boolean; + + const setNow = (date: Date) => jest.setSystemTime(date); + + beforeEach(() => { + jest.useFakeTimers(); + setNow(BEFORE_DUE); + committed = false; + state = { + id: 'ev-1', + companyId: 'comp-1', + employeeId: 'emp-1', + declarationId: 'decl-1', + status: 'CEO_PENDING', + resignationDate: new Date('2026-04-30T00:00:00.000Z'), + selfEvaluationDueAt: new Date('2026-05-03T14:59:59.000Z'), + ceoEvaluationDueAt: CEO_DUE, + completedAt: null, + rehireIntent: null, + opinionDueAt: null, + employee: { + id: 'emp-1', name: '김민준', email: 'minjun@example.com', department: '개발팀', position: '과장', + employmentStatus: 'RESIGNED', + }, + }; + + prismaMock = { + hrManager: { findUnique: jest.fn() }, + evaluation: { + findUnique: jest.fn(async () => ({ ...state, employee: { ...state.employee } })), + // 실제 조건(상태 + 마감 시각)을 그대로 흉내 낸 조건부 갱신 + updateMany: jest.fn(async ({ where, data }: any) => { + const ok = + where.id === state.id && + where.status.in.includes(state.status) && + state.ceoEvaluationDueAt.getTime() >= where.ceoEvaluationDueAt.gte.getTime(); + if (ok) Object.assign(state, data); + return { count: ok ? 1 : 0 }; + }), + }, + evaluationItem: { + findMany: jest.fn(async () => ITEMS_DB.map((i) => ({ ...i }))), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + competencyScore: { createMany: jest.fn().mockResolvedValue({ count: 6 }) }, + company: { findUnique: jest.fn().mockResolvedValue({ companyName: '테크플러스' }) }, + $transaction: jest.fn(async (fn: any) => { + const result = await fn(prismaMock); + committed = true; + return result; + }), + }; + accessLinkMock = { issue: jest.fn().mockResolvedValue('result-token') }; + mailMock = { + sendEvaluationResult: jest.fn(async () => { + expect(committed).toBe(true); // 결과 메일은 커밋 후에만 + return true; + }), + }; + auditMock = { log: jest.fn().mockResolvedValue(undefined) }; + service = new CeoEvaluationService( + prismaMock as unknown as PrismaService, + accessLinkMock as unknown as AccessLinkService, + mailMock as unknown as MailService, + auditMock as unknown as AuditService, + ); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + // 1 + it('재직 중(EMPLOYED) 직원이면 조회·제출 모두 403 STILL_EMPLOYED', async () => { + state.employee.employmentStatus = 'EMPLOYED'; + + await expectCode(service.getForm(CEO, 'ev-1'), ForbiddenException, 'STILL_EMPLOYED'); + await expectCode(service.submit(CEO, 'ev-1', validDto(), META), ForbiddenException, 'STILL_EMPLOYED'); + expect(prismaMock.evaluation.updateMany).not.toHaveBeenCalled(); + }); + + // 2 + it('마감 1초 전 제출은 성공, 1초 후 제출은 410 EVALUATION_EXPIRED', async () => { + setNow(new Date(CEO_DUE.getTime() + ONE_SECOND)); + await expectCode(service.submit(CEO, 'ev-1', validDto(), META), GoneException, 'EVALUATION_EXPIRED'); + expect(state.status).toBe('CEO_PENDING'); + + setNow(new Date(CEO_DUE.getTime() - ONE_SECOND)); + await expect(service.submit(CEO, 'ev-1', validDto(), META)).resolves.toMatchObject({ status: 'COMPLETED' }); + expect(state.status).toBe('COMPLETED'); + }); + + // 3 + it('마감 시각 정각(KST 23:59:59.000) 제출은 성공', async () => { + setNow(CEO_DUE); + await expect(service.submit(CEO, 'ev-1', validDto(), META)).resolves.toMatchObject({ status: 'COMPLETED' }); + }); + + // 4 + it('마감 1초 후에는 폼 조회도 410 EVALUATION_EXPIRED (스케줄러가 상태를 바꾸기 전이어도)', async () => { + setNow(new Date(CEO_DUE.getTime() + ONE_SECOND)); + expect(state.status).toBe('CEO_PENDING'); + await expectCode(service.getForm(CEO, 'ev-1'), GoneException, 'EVALUATION_EXPIRED'); + }); + + // 5 + it('CEO_EXPIRED 상태면 마감 전 시각이어도 조회·제출 410 EVALUATION_EXPIRED', async () => { + state.status = 'CEO_EXPIRED'; + await expectCode(service.getForm(CEO, 'ev-1'), GoneException, 'EVALUATION_EXPIRED'); + await expectCode(service.submit(CEO, 'ev-1', validDto(), META), GoneException, 'EVALUATION_EXPIRED'); + }); + + // 6 + it('재제출은 409 ALREADY_COMPLETED', async () => { + await service.submit(CEO, 'ev-1', validDto(), META); + await expectCode(service.submit(CEO, 'ev-1', validDto(), META), ConflictException, 'ALREADY_COMPLETED'); + await expectCode(service.getForm(CEO, 'ev-1'), ConflictException, 'ALREADY_COMPLETED'); + expect(prismaMock.competencyScore.createMany).toHaveBeenCalledTimes(1); + }); + + it('동시 제출로 조회 직후 다른 요청이 먼저 완료했으면(갱신 0건) 409 ALREADY_COMPLETED, 점수·역량을 저장하지 않는다', async () => { + prismaMock.evaluation.findUnique + .mockResolvedValueOnce({ ...state, employee: { ...state.employee } }) // 트랜잭션 시작 시 CEO_PENDING + .mockResolvedValueOnce({ ...state, status: 'COMPLETED', employee: { ...state.employee } }); // 재판정 시 COMPLETED + prismaMock.evaluation.updateMany.mockResolvedValueOnce({ count: 0 }); + + await expectCode(service.submit(CEO, 'ev-1', validDto(), META), ConflictException, 'ALREADY_COMPLETED'); + expect(prismaMock.evaluationItem.updateMany).not.toHaveBeenCalled(); + expect(prismaMock.competencyScore.createMany).not.toHaveBeenCalled(); + expect(accessLinkMock.issue).not.toHaveBeenCalled(); + expect(mailMock.sendEvaluationResult).not.toHaveBeenCalled(); + }); + + // 7 + it('다른 기업 평가는 403 FORBIDDEN, 없는 평가는 404 EVALUATION_NOT_FOUND', async () => { + state.companyId = 'comp-other'; + await expectCode(service.getForm(CEO, 'ev-1'), ForbiddenException, 'FORBIDDEN'); + await expectCode(service.submit(CEO, 'ev-1', validDto(), META), ForbiddenException, 'FORBIDDEN'); + + prismaMock.evaluation.findUnique.mockResolvedValue(null); + await expectCode(service.getForm(CEO, 'nope'), NotFoundException, 'EVALUATION_NOT_FOUND'); + await expectCode(service.submit(CEO, 'nope', validDto(), META), NotFoundException, 'EVALUATION_NOT_FOUND'); + }); + + // 8 + it('자기평가 진행 중(SELF_PENDING)이면 409 INVALID_EVALUATION_STATUS', async () => { + state.status = 'SELF_PENDING'; + await expectCode(service.getForm(CEO, 'ev-1'), ConflictException, 'INVALID_EVALUATION_STATUS'); + await expectCode(service.submit(CEO, 'ev-1', validDto(), META), ConflictException, 'INVALID_EVALUATION_STATUS'); + }); + + // 9 + describe('400 MISSING_EVALUATION_ITEM', () => { + it('공통 역량 누락·중복·없는 키', async () => { + await expectCode( + service.submit(CEO, 'ev-1', validDto({ commonCompetencies: COMPETENCIES.slice(0, 5) }), META), + BadRequestException, + 'MISSING_EVALUATION_ITEM', + ); + await expectCode( + service.submit(CEO, 'ev-1', validDto({ commonCompetencies: [...COMPETENCIES.slice(0, 5), COMPETENCIES[0]] }), META), + BadRequestException, + 'MISSING_EVALUATION_ITEM', + ); + await expectCode( + service.submit(CEO, 'ev-1', validDto({ commonCompetencies: [...COMPETENCIES, { key: 'LEADERSHIP' as any, score: 5 }] }), META), + BadRequestException, + 'MISSING_EVALUATION_ITEM', + ); + }); + + it('평가 항목 누락·중복·없는 항목', async () => { + await expectCode( + service.submit(CEO, 'ev-1', validDto({ items: [{ questionId: 'snap-1', ceoScore: 7 }] }), META), + BadRequestException, + 'MISSING_EVALUATION_ITEM', + ); + await expectCode( + service.submit(CEO, 'ev-1', validDto({ items: [...validDto().items, { questionId: 'snap-1', ceoScore: 7 }] }), META), + BadRequestException, + 'MISSING_EVALUATION_ITEM', + ); + await expectCode( + service.submit(CEO, 'ev-1', validDto({ items: [...validDto().items, { questionId: 'snap-x', ceoScore: 7 }] }), META), + BadRequestException, + 'MISSING_EVALUATION_ITEM', + ); + expect(state.status).toBe('CEO_PENDING'); + }); + }); + + // 10 + it.each([0, 11, 7.5])('항목 점수 %s는 422 INVALID_SCORE', async (score) => { + await expectCode( + service.submit(CEO, 'ev-1', validDto({ items: [{ questionId: 'snap-1', ceoScore: score }, { questionId: 'snap-3', ceoScore: 8 }] }), META), + UnprocessableEntityException, + 'INVALID_SCORE', + ); + expect(state.status).toBe('CEO_PENDING'); + }); + + it.each([0, 11, 7.5])('공통 역량 점수 %s는 422 INVALID_SCORE', async (score) => { + const competencies = COMPETENCIES.map((c, i) => (i === 2 ? { ...c, score } : c)); + await expectCode( + service.submit(CEO, 'ev-1', validDto({ commonCompetencies: competencies }), META), + UnprocessableEntityException, + 'INVALID_SCORE', + ); + }); + + // 13 + it('SELF_EXPIRED면 폼의 selfScore는 null이고 대표 검증 제출은 성공한다', async () => { + state.status = 'SELF_EXPIRED'; + + const form = await service.getForm(CEO, 'ev-1'); + expect(form.items.map((i) => i.selfScore)).toEqual([null, null]); + + await expect(service.submit(CEO, 'ev-1', validDto(), META)).resolves.toMatchObject({ status: 'COMPLETED' }); + }); + + // 14 + it('결과 메일 발송이 실패해도 COMPLETED는 유지되고 resultNotified=false', async () => { + mailMock.sendEvaluationResult.mockResolvedValue(false); + + const result = await service.submit(CEO, 'ev-1', validDto(), META); + + expect(result.resultNotified).toBe(false); + expect(result.status).toBe('COMPLETED'); + expect(state.status).toBe('COMPLETED'); + expect(committed).toBe(true); + }); + + // 15 + it('정상 제출: COMPLETED·대표 점수·역량 6개·의견 마감(+7일)·결과 링크(+30일)·감사 로그·커밋 후 메일', async () => { + setNow(new Date('2026-05-05T01:00:00.000Z')); // KST 5/5 10:00 완료 + + const result = await service.submit(CEO, 'ev-1', validDto({ rehireIntent: false }), META); + + const completedAt = new Date('2026-05-05T01:00:00.000Z'); + const opinionDueAt = new Date('2026-05-12T14:59:59.000Z'); // KST 5/12 23:59:59 (명세 예시) + expect(result).toEqual({ evaluationId: 'ev-1', status: 'COMPLETED', completedAt, resultNotified: true, opinionDueAt }); + expect(state).toMatchObject({ status: 'COMPLETED', completedAt, rehireIntent: false, opinionDueAt }); + + expect(prismaMock.evaluationItem.updateMany).toHaveBeenCalledWith({ + where: { evaluationId: 'ev-1', snapshotQuestionId: 'snap-1' }, + data: { ceoScore: 7 }, + }); + expect(prismaMock.evaluationItem.updateMany).toHaveBeenCalledWith({ + where: { evaluationId: 'ev-1', snapshotQuestionId: 'snap-3' }, + data: { ceoScore: 8 }, + }); + expect(prismaMock.competencyScore.createMany).toHaveBeenCalledWith({ + data: COMPETENCIES.map((c) => ({ evaluationId: 'ev-1', key: c.key, score: c.score })), + }); + + const linkExpiresAt = new Date(opinionDueAt.getTime() + 30 * 24 * 60 * 60 * 1000); + expect(accessLinkMock.issue).toHaveBeenCalledWith('EVALUATION_RESULT', 'ev-1', linkExpiresAt, prismaMock); + expect(auditMock.log).toHaveBeenCalledWith( + expect.objectContaining({ actorType: 'COMPANY', action: 'EVALUATION_COMPLETED', targetType: 'Evaluation', targetId: 'ev-1' }), + prismaMock, + ); + expect(mailMock.sendEvaluationResult).toHaveBeenCalledWith({ + to: 'minjun@example.com', + token: 'result-token', + employeeName: '김민준', + companyName: '테크플러스', + expiresAt: linkExpiresAt, + }); + }); + + // 16 + describe('검사 우선순위 (프롬프트 순서)', () => { + it('재직 중 + COMPLETED → 403 STILL_EMPLOYED가 먼저', async () => { + state.employee.employmentStatus = 'EMPLOYED'; + state.status = 'COMPLETED'; + await expectCode(service.getForm(CEO, 'ev-1'), ForbiddenException, 'STILL_EMPLOYED'); + }); + + it('COMPLETED + 마감 지남 → 409 ALREADY_COMPLETED가 먼저', async () => { + state.status = 'COMPLETED'; + setNow(new Date(CEO_DUE.getTime() + ONE_SECOND)); + await expectCode(service.getForm(CEO, 'ev-1'), ConflictException, 'ALREADY_COMPLETED'); + }); + + it('SELF_PENDING + 마감 지남 → 410 EVALUATION_EXPIRED가 먼저', async () => { + state.status = 'SELF_PENDING'; + setNow(new Date(CEO_DUE.getTime() + ONE_SECOND)); + await expectCode(service.getForm(CEO, 'ev-1'), GoneException, 'EVALUATION_EXPIRED'); + }); + + it('타사 + 재직 중 → 403 FORBIDDEN이 먼저', async () => { + state.companyId = 'comp-other'; + state.employee.employmentStatus = 'EMPLOYED'; + await expectCode(service.getForm(CEO, 'ev-1'), ForbiddenException, 'FORBIDDEN'); + }); + }); + + // 17 + it('폼 조회: 자기선언 답변·자기점수, ceoScore null, 공통 역량 6개(이름·순서)', async () => { + const form = await service.getForm(CEO, 'ev-1'); + + expect(form).toEqual({ + evaluationId: 'ev-1', + employee: { employeeId: 'emp-1', name: '김민준', department: '개발팀', position: '과장' }, + status: 'CEO_PENDING', + ceoEvaluationDueAt: CEO_DUE, + scoreMin: 1, + scoreMax: 10, + items: [ + { questionId: 'snap-1', order: 1, question: '질문 1', declarationAnswer: { type: 'SCORE', score: 8 }, selfScore: 8, ceoScore: null }, + { questionId: 'snap-3', order: 3, question: '질문 3', declarationAnswer: { type: 'TEXT', text: 'React 성능 개선 경험' }, selfScore: 7, ceoScore: null }, + ], + commonCompetencies: [ + { key: 'TRUST', name: '신뢰', ceoScore: null }, + { key: 'DILIGENCE', name: '성실성', ceoScore: null }, + { key: 'RESPONSIBILITY', name: '책임감', ceoScore: null }, + { key: 'COLLABORATION', name: '협업', ceoScore: null }, + { key: 'COMMUNICATION', name: '의사소통', ceoScore: null }, + { key: 'GROWTH_POTENTIAL', name: '성장 가능성', ceoScore: null }, + ], + }); + }); +}); diff --git a/src/evaluations/ceo-evaluation.service.ts b/src/evaluations/ceo-evaluation.service.ts new file mode 100644 index 0000000..3030a1d --- /dev/null +++ b/src/evaluations/ceo-evaluation.service.ts @@ -0,0 +1,300 @@ +import { + BadRequestException, + ConflictException, + ForbiddenException, + GoneException, + Injectable, + NotFoundException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { Evaluation, Prisma } from '@prisma/client'; +import { AccessLinkService } from '../access-link/access-link.service'; +import { AuditService } from '../audit/audit.service'; +import { JwtPayload } from '../auth/strategies/jwt.strategy'; +import { resolveCompanyId } from '../core/utils/company-scope'; +import { endOfDayKstAfter } from '../core/utils/kst-date'; +import { MailService } from '../notification/mail.service'; +import { PrismaService } from '../prisma/prisma.service'; +import { + COMMON_COMPETENCIES, + OPINION_DUE_DAYS, + RESULT_LINK_EXTRA_DAYS, +} from './competency.constants'; +import { SubmitCeoEvaluationDto } from './dto/submit-ceo-evaluation.dto'; +import { SCORE_MAX, SCORE_MIN, isValidScore } from './evaluation.constants'; +import { RequestMeta, toDeclarationAnswer } from './self-evaluation.service'; + +const DAY_MS = 24 * 60 * 60 * 1000; + +/** 대표 검증이 가능한 상태. 자기평가 만료(SELF_EXPIRED)여도 대표 검증은 진행할 수 있다 */ +const CEO_EVALUABLE_STATUSES = ['CEO_PENDING', 'SELF_EXPIRED'] as const; + +type Client = PrismaService | Prisma.TransactionClient; +type EvaluationWithEmployee = Evaluation & { + employee: { id: string; name: string; email: string; department: string | null; position: string | null; employmentStatus: string }; +}; + +/** + * 대표 검증 (법적 안전 로직) + * - 퇴사 처리된 직원만 평가할 수 있다 (재직 중 403 STILL_EMPLOYED) + * - 대표 검증 마감(퇴사일 + 15일 KST 23:59:59)이 지나면 조회·제출 모두 막는다 (410 EVALUATION_EXPIRED). + * 스케줄러는 매시간 돌기 때문에 상태값만 믿지 않고 요청 시각을 마감과 직접 비교한다. + * - 점수와 재고용 의사(boolean)만 받고 서술형은 받지 않는다. 제출 후 점수 수정 API는 없다. + */ +@Injectable() +export class CeoEvaluationService { + constructor( + private readonly prisma: PrismaService, + private readonly accessLinkService: AccessLinkService, + private readonly mailService: MailService, + private readonly auditService: AuditService, + ) {} + + async getForm(user: JwtPayload, evaluationId: string) { + const companyId = await resolveCompanyId(user, this.prisma); + const evaluation = await this.findEvaluation(this.prisma, evaluationId); + assertCeoEvaluable(evaluation, companyId, new Date()); + + const items = await this.prisma.evaluationItem.findMany({ + where: { evaluationId }, + orderBy: { order: 'asc' }, + include: { snapshotQuestion: { include: { response: true } } }, + }); + const selfExpired = evaluation.status === 'SELF_EXPIRED'; + + return { + evaluationId: evaluation.id, + employee: { + employeeId: evaluation.employee.id, + name: evaluation.employee.name, + department: evaluation.employee.department, + position: evaluation.employee.position, + }, + status: evaluation.status, + ceoEvaluationDueAt: evaluation.ceoEvaluationDueAt, + scoreMin: SCORE_MIN, + scoreMax: SCORE_MAX, + items: items.map((item) => ({ + questionId: item.snapshotQuestionId, + order: item.order, + question: item.snapshotQuestion.text, + declarationAnswer: toDeclarationAnswer(item.snapshotQuestion), + // 자기평가 기한이 지나 제출되지 않았으면 자기점수는 없다 + selfScore: selfExpired ? null : item.selfScore, + ceoScore: null, + })), + commonCompetencies: COMMON_COMPETENCIES.map(({ key, name }) => ({ key, name, ceoScore: null })), + }; + } + + async submit(user: JwtPayload, evaluationId: string, dto: SubmitCeoEvaluationDto, meta: RequestMeta) { + const companyId = await resolveCompanyId(user, this.prisma); + + // 트랜잭션 안에서는 데이터와 링크 저장만 한다. 메일은 커밋 후. + const { evaluation, completedAt, opinionDueAt, linkExpiresAt, token } = await this.prisma.$transaction(async (tx) => { + const now = new Date(); + const current = await this.findEvaluation(tx, evaluationId); + assertCeoEvaluable(current, companyId, now); + + const items = await tx.evaluationItem.findMany({ + where: { evaluationId }, + select: { snapshotQuestionId: true }, + }); + assertExactlyOnce( + 'items', + items.map((item) => item.snapshotQuestionId), + dto.items.map((item) => item.questionId), + ); + assertExactlyOnce( + 'commonCompetencies', + COMMON_COMPETENCIES.map((c) => c.key), + dto.commonCompetencies.map((c) => c.key), + ); + + const invalidItems = dto.items.filter((item) => !isValidScore(item.ceoScore)).map((item) => item.questionId); + const invalidCompetencies = dto.commonCompetencies.filter((c) => !isValidScore(c.score)).map((c) => c.key); + if (invalidItems.length > 0 || invalidCompetencies.length > 0) { + throw new UnprocessableEntityException({ + code: 'INVALID_SCORE', + message: `점수는 ${SCORE_MIN}~${SCORE_MAX} 사이의 정수여야 합니다.`, + details: { items: invalidItems, commonCompetencies: invalidCompetencies }, + }); + } + + const opinionDue = endOfDayKstAfter(now, OPINION_DUE_DAYS); + + // 동시 제출·마감 경합 방지: 검증 가능 상태이고 마감 전일 때만 COMPLETED로 전환 + const { count } = await tx.evaluation.updateMany({ + where: { + id: evaluationId, + status: { in: [...CEO_EVALUABLE_STATUSES] }, + ceoEvaluationDueAt: { gte: now }, + }, + data: { + status: 'COMPLETED', + completedAt: now, + rehireIntent: dto.rehireIntent, + opinionDueAt: opinionDue, + }, + }); + if (count === 0) { + // 그 사이 상태가 바뀌었다 → 바뀐 상태 기준으로 409/410을 다시 판정 + const latest = await this.findEvaluation(tx, evaluationId); + assertCeoEvaluable(latest, companyId, now); + throw alreadyCompleted(); + } + + for (const item of dto.items) { + await tx.evaluationItem.updateMany({ + where: { evaluationId, snapshotQuestionId: item.questionId }, + data: { ceoScore: item.ceoScore }, + }); + } + + await tx.competencyScore.createMany({ + data: dto.commonCompetencies.map((c) => ({ evaluationId, key: c.key, score: c.score })), + }); + + // 결과 링크는 의견 마감 후에도 결과 열람용으로 30일 더 유지 + const resultLinkExpiresAt = new Date(opinionDue.getTime() + RESULT_LINK_EXTRA_DAYS * DAY_MS); + const resultToken = await this.accessLinkService.issue( + 'EVALUATION_RESULT', + evaluationId, + resultLinkExpiresAt, + tx, + ); + + await this.auditService.log( + { + actorType: 'COMPANY', + actorId: user.sub, + action: 'EVALUATION_COMPLETED', + targetType: 'Evaluation', + targetId: evaluationId, + ip: meta.ip, + userAgent: meta.userAgent, + metadata: { + employeeId: current.employeeId, + itemCount: dto.items.length, + rehireIntent: dto.rehireIntent, + }, + }, + tx, + ); + + return { + evaluation: current, + completedAt: now, + opinionDueAt: opinionDue, + linkExpiresAt: resultLinkExpiresAt, + token: resultToken, + }; + }); + + // 커밋 후 결과 통보. 실패해도 COMPLETED는 유지되고 resultNotified=false로 알린다. + const company = await this.prisma.company.findUnique({ + where: { id: companyId }, + select: { companyName: true }, + }); + const resultNotified = await this.mailService.sendEvaluationResult({ + to: evaluation.employee.email, + token, + employeeName: evaluation.employee.name, + companyName: company?.companyName, + expiresAt: linkExpiresAt, + }); + + return { + evaluationId, + status: 'COMPLETED' as const, + completedAt, + resultNotified, + opinionDueAt, + }; + } + + private async findEvaluation(client: Client, evaluationId: string): Promise { + return client.evaluation.findUnique({ + where: { id: evaluationId }, + include: { + employee: { + select: { id: true, name: true, email: true, department: true, position: true, employmentStatus: true }, + }, + }, + }); + } +} + +/** + * 대표 검증 가능 여부를 정해진 순서로 판정한다 (GET·POST 공통). + * 1. 없음 404 / 타사 403 2. 재직 중 403 3. 완료 409 4. 마감 초과·CEO_EXPIRED 410 5. 그 외 상태 409 + */ +export function assertCeoEvaluable( + evaluation: EvaluationWithEmployee | null, + companyId: string, + now: Date, +): asserts evaluation is EvaluationWithEmployee { + if (!evaluation) { + throw new NotFoundException({ code: 'EVALUATION_NOT_FOUND', message: '평가를 찾을 수 없습니다.' }); + } + if (evaluation.companyId !== companyId) { + throw new ForbiddenException({ code: 'FORBIDDEN', message: '다른 기업의 평가에는 접근할 수 없습니다.' }); + } + if (evaluation.employee.employmentStatus === 'EMPLOYED') { + throw new ForbiddenException({ + code: 'STILL_EMPLOYED', + message: '재직 중인 직원은 평가할 수 없습니다.', + }); + } + if (evaluation.status === 'COMPLETED') { + throw alreadyCompleted(); + } + // 마감 시각(23:59:59.000)까지는 허용, 그 이후는 상태값과 무관하게 차단 + if (evaluation.status === 'CEO_EXPIRED' || now.getTime() > evaluation.ceoEvaluationDueAt.getTime()) { + throw new GoneException({ + code: 'EVALUATION_EXPIRED', + message: '대표 검증 기한(퇴사일 + 15일)이 지났습니다.', + details: { ceoEvaluationDueAt: evaluation.ceoEvaluationDueAt }, + }); + } + if (!(CEO_EVALUABLE_STATUSES as readonly string[]).includes(evaluation.status)) { + throw new ConflictException({ + code: 'INVALID_EVALUATION_STATUS', + message: '대표 검증을 진행할 수 있는 상태가 아닙니다.', + details: { status: evaluation.status }, + }); + } +} + +/** 기대한 키가 빠짐없이 한 번씩 들어왔는지 확인 (누락·중복·없는 키 → 400) */ +function assertExactlyOnce(field: string, expected: string[], received: string[]): void { + const expectedSet = new Set(expected); + const seen = new Set(); + const duplicated = new Set(); + const unknown: string[] = []; + + for (const key of received) { + if (seen.has(key)) duplicated.add(key); + seen.add(key); + if (!expectedSet.has(key)) unknown.push(key); + } + const missing = expected.filter((key) => !seen.has(key)); + + if (missing.length > 0 || duplicated.size > 0 || unknown.length > 0) { + throw new BadRequestException({ + code: 'MISSING_EVALUATION_ITEM', + message: + field === 'commonCompetencies' + ? '공통 역량 6개에 한 번씩 점수를 입력해야 합니다.' + : '모든 평가 항목에 한 번씩 점수를 입력해야 합니다.', + details: { field, missing, duplicated: [...duplicated], unknown }, + }); + } +} + +function alreadyCompleted(): ConflictException { + return new ConflictException({ + code: 'ALREADY_COMPLETED', + message: '이미 대표 검증이 완료된 평가입니다.', + }); +} diff --git a/src/evaluations/competency.constants.ts b/src/evaluations/competency.constants.ts new file mode 100644 index 0000000..2f4b5f8 --- /dev/null +++ b/src/evaluations/competency.constants.ts @@ -0,0 +1,17 @@ +import { CompetencyKey } from '@prisma/client'; + +/** 대표가 입력하는 공통 역량 6개 (응답 순서 = 이 배열 순서) */ +export const COMMON_COMPETENCIES: { key: CompetencyKey; name: string }[] = [ + { key: 'TRUST', name: '신뢰' }, + { key: 'DILIGENCE', name: '성실성' }, + { key: 'RESPONSIBILITY', name: '책임감' }, + { key: 'COLLABORATION', name: '협업' }, + { key: 'COMMUNICATION', name: '의사소통' }, + { key: 'GROWTH_POTENTIAL', name: '성장 가능성' }, +]; + +/** 대표 검증 완료 후 직원 의견 마감: 완료일 기준 KST 7일 뒤 23:59:59 */ +export const OPINION_DUE_DAYS = 7; + +/** 결과 확인 링크는 의견 마감 후에도 30일간 결과 열람용으로 유지 */ +export const RESULT_LINK_EXTRA_DAYS = 30; diff --git a/src/evaluations/dto/submit-ceo-evaluation.dto.spec.ts b/src/evaluations/dto/submit-ceo-evaluation.dto.spec.ts new file mode 100644 index 0000000..2dc4195 --- /dev/null +++ b/src/evaluations/dto/submit-ceo-evaluation.dto.spec.ts @@ -0,0 +1,73 @@ +import { BadRequestException, ValidationPipe } from '@nestjs/common'; +import { SubmitCeoEvaluationDto } from './submit-ceo-evaluation.dto'; + +// src/main.ts의 전역 ValidationPipe와 같은 설정으로 검증한다 +const pipe = new ValidationPipe({ + whitelist: true, + forbidNonWhitelisted: true, + transform: true, + transformOptions: { enableImplicitConversion: true }, +}); + +const transform = (body: unknown) => + pipe.transform(body, { type: 'body', metatype: SubmitCeoEvaluationDto }) as Promise; + +const valid = () => ({ + items: [{ questionId: 'snap-1', ceoScore: 7 }], + commonCompetencies: [ + { key: 'TRUST', score: 8 }, + { key: 'DILIGENCE', score: 9 }, + { key: 'RESPONSIBILITY', score: 8 }, + { key: 'COLLABORATION', score: 7 }, + { key: 'COMMUNICATION', score: 7 }, + { key: 'GROWTH_POTENTIAL', score: 9 }, + ], + rehireIntent: true, +}); + +describe('SubmitCeoEvaluationDto (법적 안전: 서술형·비boolean 차단)', () => { + it('정상 body는 통과하고 rehireIntent는 boolean 그대로', async () => { + await expect(transform(valid())).resolves.toMatchObject({ rehireIntent: true }); + await expect(transform({ ...valid(), rehireIntent: false })).resolves.toMatchObject({ rehireIntent: false }); + }); + + // 11 + describe('DTO에 없는 필드(서술형)는 400', () => { + it('최상위 comment', async () => { + await expect(transform({ ...valid(), comment: '성실했음' })).rejects.toBeInstanceOf(BadRequestException); + }); + it('재고용 사유 rehireReason', async () => { + await expect(transform({ ...valid(), rehireReason: '다시 함께하고 싶음' })).rejects.toBeInstanceOf(BadRequestException); + }); + it('항목 안의 comment', async () => { + const body = valid(); + (body.items[0] as any).comment = '구체적 근거'; + await expect(transform(body)).rejects.toBeInstanceOf(BadRequestException); + }); + it('역량 안의 comment', async () => { + const body = valid(); + (body.commonCompetencies[0] as any).comment = '신뢰할 만함'; + await expect(transform(body)).rejects.toBeInstanceOf(BadRequestException); + }); + }); + + // 12 + it.each(['YES', 'HOLD', 'NO', 'true', 'false', 1, 0, null])( + 'rehireIntent %p는 400 (true/false만 허용)', + async (value) => { + await expect(transform({ ...valid(), rehireIntent: value })).rejects.toBeInstanceOf(BadRequestException); + }, + ); + + it('rehireIntent 누락은 400', async () => { + const { rehireIntent: _omit, ...body } = valid(); + await expect(transform(body)).rejects.toBeInstanceOf(BadRequestException); + }); + + it('점수가 숫자가 아니면 400, 역량 키가 enum이 아니면 400', async () => { + await expect(transform({ ...valid(), items: [{ questionId: 'snap-1', ceoScore: 'abc' }] })).rejects.toBeInstanceOf(BadRequestException); + const body = valid(); + (body.commonCompetencies[0] as any).key = 'LEADERSHIP'; + await expect(transform(body)).rejects.toBeInstanceOf(BadRequestException); + }); +}); diff --git a/src/evaluations/dto/submit-ceo-evaluation.dto.ts b/src/evaluations/dto/submit-ceo-evaluation.dto.ts new file mode 100644 index 0000000..28934cb --- /dev/null +++ b/src/evaluations/dto/submit-ceo-evaluation.dto.ts @@ -0,0 +1,49 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { CompetencyKey } from '@prisma/client'; +import { Type } from 'class-transformer'; +import { IsArray, IsEnum, IsNotEmpty, IsNumber, IsString, ValidateNested } from 'class-validator'; +import { StrictBoolean } from '../../core/decorators/strict-boolean.decorator'; + +/** + * 대표 검증은 점수와 재고용 의사(boolean)만 받는다. + * 서술형(평가 코멘트·재고용 사유 등) 필드는 DTO에 없으므로 보내면 400(forbidNonWhitelisted). + */ +export class CeoEvaluationItemDto { + @ApiProperty({ example: 'uuid', description: '대표 검증 폼 조회 응답의 questionId' }) + @IsString() + @IsNotEmpty() + questionId!: string; + + @ApiProperty({ example: 7, minimum: 1, maximum: 10, description: '1~10 정수' }) + @IsNumber() + ceoScore!: number; +} + +export class CompetencyScoreDto { + @ApiProperty({ enum: CompetencyKey, example: 'TRUST' }) + @IsEnum(CompetencyKey) + key!: CompetencyKey; + + @ApiProperty({ example: 8, minimum: 1, maximum: 10, description: '1~10 정수' }) + @IsNumber() + score!: number; +} + +export class SubmitCeoEvaluationDto { + @ApiProperty({ type: [CeoEvaluationItemDto], description: '모든 평가 항목의 대표 점수 (누락·중복 불가)' }) + @IsArray() + @ValidateNested({ each: true }) + @Type(() => CeoEvaluationItemDto) + items!: CeoEvaluationItemDto[]; + + @ApiProperty({ type: [CompetencyScoreDto], description: '공통 역량 6개 점수 (누락·중복 불가)' }) + @IsArray() + @ValidateNested({ each: true }) + @Type(() => CompetencyScoreDto) + commonCompetencies!: CompetencyScoreDto[]; + + // 레거시의 YES/HOLD/NO 문자열이나 "true" 같은 문자열은 거부하고 진짜 boolean만 허용 + @ApiProperty({ example: true, description: '재고용 의사 (true/false만)' }) + @StrictBoolean() + rehireIntent!: boolean; +} diff --git a/src/evaluations/evaluations.module.ts b/src/evaluations/evaluations.module.ts index 1aecfbd..6af1b93 100644 --- a/src/evaluations/evaluations.module.ts +++ b/src/evaluations/evaluations.module.ts @@ -1,14 +1,20 @@ import { Module } from '@nestjs/common'; import { AccessLinkModule } from '../access-link/access-link.module'; import { AuditModule } from '../audit/audit.module'; +import { AuthModule } from '../auth/auth.module'; +import { NotificationModule } from '../notification/notification.module'; +import { CeoEvaluationController } from './ceo-evaluation.controller'; +import { CeoEvaluationService } from './ceo-evaluation.service'; 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], + // AuthModule: 대표 API의 JwtAuthGuard가 RedisService(토큰 블랙리스트)를 사용 + imports: [AuthModule, AccessLinkModule, NotificationModule, AuditModule], + // 직원용 라우트(evaluations/self/:token)를 대표용(evaluations/:evaluationId/ceo)보다 먼저 등록 + controllers: [SelfEvaluationController, CeoEvaluationController], + providers: [SelfEvaluationService, CeoEvaluationService, EvaluationExpiryScheduler], }) export class EvaluationsModule {} diff --git a/src/evaluations/self-evaluation.service.ts b/src/evaluations/self-evaluation.service.ts index a9f3c79..d5f6221 100644 --- a/src/evaluations/self-evaluation.service.ts +++ b/src/evaluations/self-evaluation.service.ts @@ -170,8 +170,8 @@ function assertAllItemsOnce(expectedIds: string[], receivedIds: string[]): void } } -/** 자기선언 때 직원이 한 답변. 미응답이면 값은 null */ -function toDeclarationAnswer( +/** 자기선언 때 직원이 한 답변. 미응답이면 값은 null (자기평가·대표 검증 폼 공용) */ +export function toDeclarationAnswer( snapshot: DeclarationQuestionSnapshot & { response: DeclarationResponse | null }, ) { const response = snapshot.response;