From bcccb920da43e2c0946a02118595477728ae7abb Mon Sep 17 00:00:00 2001 From: ChaeYeon Lee Date: Fri, 9 Oct 2026 21:30:40 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=ED=8F=89=EA=B0=80=20=EA=B2=B0=EA=B3=BC?= =?UTF-8?q?=20=EC=A1=B0=ED=9A=8C=C2=B7=EC=9D=98=EA=B2=AC=20=EC=A0=9C?= =?UTF-8?q?=EC=B6=9C=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GET /evaluations/:evaluationId/result (대표): 자기선언·자기점수·대표점수·scoreGap·역량·재고용 의사·결과 통보·직원 의견 - GET /evaluations/result/:token (직원): 점수 비교·역량·의견 가능 여부, 최초 조회 시각 기록, 링크 소비 안 함 - POST /evaluations/result/:token/opinion (직원): 1회, 완료 + 7일 이내, 1~1000자, 점수 불변 - 409 OPINION_ALREADY_SUBMITTED, 410 OPINION_PERIOD_EXPIRED, 422 INVALID_OPINION, 미완료 409 EVALUATION_NOT_COMPLETED - 토큰 라우트를 별도 컨트롤러로 분리해 먼저 등록, 라우트 매칭 테스트 추가 - 대표 검증 제출 후 결과 메일 발송 여부를 감사 로그로 기록 (대표 결과의 notification.sent) - docs/evaluation-flow.md: 직원 등록부터 의견 제출까지 Postman 실행 순서·예시 body Co-Authored-By: Claude Opus 5.5 --- docs/evaluation-flow.md | 313 ++++++++++++++++++ .../ceo-evaluation.service.spec.ts | 28 ++ src/evaluations/ceo-evaluation.service.ts | 23 ++ src/evaluations/competency.constants.ts | 11 + src/evaluations/dto/submit-opinion.dto.ts | 12 + .../evaluation-result.controller.ts | 35 ++ .../evaluation-result.service.spec.ts | 288 ++++++++++++++++ src/evaluations/evaluation-result.service.ts | 253 ++++++++++++++ src/evaluations/evaluations.module.ts | 15 +- src/evaluations/evaluations.routes.spec.ts | 102 ++++++ src/evaluations/result-link.controller.ts | 47 +++ 11 files changed, 1124 insertions(+), 3 deletions(-) create mode 100644 docs/evaluation-flow.md create mode 100644 src/evaluations/dto/submit-opinion.dto.ts create mode 100644 src/evaluations/evaluation-result.controller.ts create mode 100644 src/evaluations/evaluation-result.service.spec.ts create mode 100644 src/evaluations/evaluation-result.service.ts create mode 100644 src/evaluations/evaluations.routes.spec.ts create mode 100644 src/evaluations/result-link.controller.ts diff --git a/docs/evaluation-flow.md b/docs/evaluation-flow.md new file mode 100644 index 0000000..41f6090 --- /dev/null +++ b/docs/evaluation-flow.md @@ -0,0 +1,313 @@ +# 신규 평가 흐름 전체 실행 가이드 (Postman) + +직원 등록부터 직원 의견 제출까지, Employee 기반 신규 흐름을 처음부터 끝까지 따라 하는 순서입니다. +요청은 위에서부터 차례대로 실행하면 되고, 각 단계의 응답 값을 다음 단계에서 사용합니다. + +> 레거시 흐름(`/evaluation/*` 단수, Applicant·Employment)과는 별개입니다. 이 문서는 신규 API만 다룹니다. + +--- + +## 0. 준비 + +### Postman 변수 + +| 변수 | 값 | 채우는 시점 | +|---|---|---| +| `baseUrl` | 로컬 `http://localhost:3000/api/v1` / 서버 `https://api.genicheck.com/api/v1` | 처음 | +| `ceoToken` | 대표 accessToken | 1단계 | +| `templateId` | 질문 템플릿 ID | 2단계 | +| `employeeId` | 직원 ID | 3단계 | +| `declarationToken` | 자기선언 링크 토큰 | 4단계 | +| `evaluationId` | 평가 ID | 6단계 | +| `selfToken` | 자기평가 링크 토큰 | 6단계 | +| `resultToken` | 평가 결과 링크 토큰 | 8단계 | + +- 대표 API는 Headers에 `Authorization: Bearer {{ceoToken}}`를 넣습니다. +- 직원 API(토큰 URL)는 인증 헤더가 필요 없습니다. + +### 직원 링크 토큰을 얻는 방법 + +직원용 링크 토큰은 **메일로만** 전달되고, DB에는 해시만 저장되어 조회할 수 없습니다. + +- **SMTP 설정됨(서버):** 직원 이메일로 받은 링크의 마지막 경로(64자리)가 토큰입니다. +- **SMTP 미설정(로컬, `SMTP_USER` 비움):** 메일 대신 서버 로그에 링크가 찍힙니다. + ``` + [MailService] [SMTP 미설정] [GeniCheck] 입사 자기선언 작성 요청 → minjun@example.com: http://localhost:5180/verification/self-declare/<토큰> + ``` + +| 메일 | 링크 경로 | 사용하는 API | +|---|---|---| +| 입사 자기선언 작성 요청 | `/verification/self-declare/<토큰>` | 4·5단계 | +| 퇴사 자기평가 작성 요청 | `/evaluation/self/<토큰>` | 6·7단계 | +| 평가 결과 안내 | `/evaluation/result/<토큰>` | 8·9단계 | + +### 응답 형식 + +- 성공: `{ "success": true, "message": "...", "data": { ... } }` → 아래 응답 예시는 `data`만 적었습니다. +- 실패: `{ "success": false, "code": "ERROR_CODE", "message": "...", "details": { ... } }` +- 날짜는 UTC(ISO 8601)로 응답합니다. 마감 `...T14:59:59.000Z`는 KST `23:59:59`입니다. + +--- + +## 1. 대표 로그인 (CEO JWT 발급) + +가입된 대표 계정이 필요합니다(기존 회원가입 흐름). + +**1-1. 로그인 1단계** +``` +POST {{baseUrl}}/auth/company/login +``` +```json +{ "email": "ceo@company.com", "password": "Password1!" } +``` +→ `data.tempToken`. 대표 이메일로 OTP 6자리가 발송됩니다. + +> 로컬에서 SMTP가 없으면 OTP는 DB에서 확인합니다. +> `SELECT code FROM otp_verifications WHERE email = 'ceo@company.com' AND purpose = 'ceo_login' ORDER BY "createdAt" DESC LIMIT 1;` + +**1-2. OTP 인증** +``` +POST {{baseUrl}}/auth/company/otp/verify +``` +```json +{ "tempToken": "<1-1의 tempToken>", "otpCode": "123456" } +``` +→ `data.accessToken`을 `ceoToken`에 저장합니다. + +--- + +## 2. 질문 템플릿 만들기 (대표) + +``` +POST {{baseUrl}}/question-templates +``` +```json +{ + "name": "개발직군 입사 자기선언", + "description": "개발직군 공통 질문", + "questions": [ + { "order": 1, "type": "SCORE", "text": "업무 책임감을 평가해 주세요.", "required": true, "scoreMin": 1, "scoreMax": 10, "evaluationEnabled": true }, + { "order": 2, "type": "SINGLE_CHOICE", "text": "선호 업무 방식은 무엇인가요?", "required": true, "options": ["개인 집중", "팀 협업"], "evaluationEnabled": false }, + { "order": 3, "type": "TEXT", "text": "주요 성과를 작성해 주세요.", "required": true, "maxLength": 500, "evaluationEnabled": true } + ] +} +``` +→ `{ templateId, version: 1, questionCount: 3, status: "ACTIVE" }` · `templateId` 저장 + +- `evaluationEnabled: true`인 질문만 퇴사 평가 항목이 됩니다(위 예시에서는 1·3번). +- 확인: `GET {{baseUrl}}/question-templates`, `GET {{baseUrl}}/question-templates/{{templateId}}` + +--- + +## 3. 직원 등록 (대표) + +``` +POST {{baseUrl}}/employees +``` +```json +{ + "name": "김민준", + "email": "minjun@example.com", + "phone": "010-5555-6666", + "department": "프론트엔드 개발팀", + "position": "과장", + "employmentStartDate": "2025-01-02" +} +``` +→ `{ employeeId, employmentStatus: "EMPLOYED", declarationStatus: "NOT_SENT" }` · `employeeId` 저장 + +- 이메일은 소문자·공백 제거 후 저장되며, 같은 기업에 같은 이메일이 있으면 409 `EMPLOYEE_ALREADY_EXISTS`입니다. +- 확인: `GET {{baseUrl}}/employees`, `GET {{baseUrl}}/employees/{{employeeId}}` + +--- + +## 4. 자기선언 질문지 발송 → 직원 조회 + +**4-1. 발송 (대표)** +``` +POST {{baseUrl}}/employees/{{employeeId}}/declarations +``` +```json +{ "templateId": "{{templateId}}", "sendChannel": "EMAIL" } +``` +→ `{ declarationId, templateVersion, questionCount, status: "SENT", linkExpiresAt, linkSent }` + +- 메일(또는 서버 로그)의 `/verification/self-declare/<토큰>`에서 토큰을 `declarationToken`에 저장합니다. +- 링크는 발송일 + 7일 KST 23:59:59까지 유효합니다. + +**4-2. 질문지 조회 (직원, 인증 없음)** +``` +GET {{baseUrl}}/declarations/forms/{{declarationToken}} +``` +→ `questions[]`(각 `questionId`), 선택형의 `options[{ optionId, label }]`, `consentVersion` + +- 조회만으로는 링크가 소비되지 않습니다. + +--- + +## 5. 자기선언 제출 (직원) + +``` +POST {{baseUrl}}/declarations/forms/{{declarationToken}}/submit +``` +```json +{ + "answers": [ + { "questionId": "<1번 questionId>", "answerScore": 8 }, + { "questionId": "<2번 questionId>", "answerOptionId": "<2번 options[1].optionId>" }, + { "questionId": "<3번 questionId>", "answerText": "React 성능 개선을 진행했습니다." } + ], + "consents": { + "evaluationAgreed": true, + "dataAccessAgreed": true, + "evidenceRetentionAgreed": true, + "consentVersion": "<4-2의 consentVersion>" + } +} +``` +→ `{ declarationId, status: "SUBMITTED", submittedAt, linkConsumed: true }` + +- 동의 값은 `true`/`false` boolean만 허용합니다(문자열 `"true"`는 400). +- 확인 (대표): `GET {{baseUrl}}/declarations/{{employeeId}}` + +--- + +## 6. 퇴사 등록 (대표) → 자기평가 링크 + +``` +POST {{baseUrl}}/employment/resign +``` +```json +{ "employeeId": "{{employeeId}}", "resignationDate": "2026-10-09", "selfEvaluationSendChannel": "EMAIL" } +``` +→ `{ employmentId, evaluationId, employmentStatus: "RESIGNED", evaluationStatus: "SELF_PENDING", selfEvaluationDueAt, ceoEvaluationDueAt, linkSent }` + +- `evaluationId` 저장. 메일(또는 로그)의 `/evaluation/self/<토큰>`을 `selfToken`에 저장합니다. +- 마감: 자기평가 = 퇴사일 + 3일, 대표 검증 = 퇴사일 + 15일 (KST 23:59:59) +- **시연 팁:** 퇴사일을 오늘로 두세요. 과거 날짜면 마감이 이미 지나 링크가 만료(410)됩니다. + +--- + +## 7. 자기평가 (직원) + +**7-1. 폼 조회** +``` +GET {{baseUrl}}/evaluations/self/{{selfToken}} +``` +→ `items[{ questionId, question, declarationAnswer, selfScore: null }]` (평가 대상 질문만) + +**7-2. 제출** +``` +POST {{baseUrl}}/evaluations/self/{{selfToken}}/submit +``` +```json +{ + "items": [ + { "questionId": "", "selfScore": 8 }, + { "questionId": "", "selfScore": 7 } + ] +} +``` +→ `{ evaluationId, status: "CEO_PENDING", submittedAt, ceoEvaluationDueAt }` + +- 모든 항목을 한 번씩, 1~10 정수로 보냅니다. 서술형 필드는 없습니다. +- 자기평가 기한이 지나면 평가는 `SELF_EXPIRED`가 되고, 대표 검증은 자기점수 없이 진행할 수 있습니다. + +--- + +## 8. 대표 검증 (대표) → 결과 링크 + +**8-1. 검증 폼 조회** +``` +GET {{baseUrl}}/evaluations/{{evaluationId}}/ceo +``` +→ `items[{ questionId, question, declarationAnswer, selfScore, ceoScore: null }]`, `commonCompetencies[6]` + +**8-2. 검증 제출** +``` +POST {{baseUrl}}/evaluations/{{evaluationId}}/ceo +``` +```json +{ + "items": [ + { "questionId": "", "ceoScore": 7 }, + { "questionId": "", "ceoScore": 8 } + ], + "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 +} +``` +→ `{ evaluationId, status: "COMPLETED", completedAt, resultNotified, opinionDueAt }` + +- 메일(또는 로그)의 `/evaluation/result/<토큰>`을 `resultToken`에 저장합니다. +- `rehireIntent`는 `true`/`false`만, 코멘트 등 서술형 필드는 400입니다. 제출 후 점수는 수정할 수 없습니다. +- 대표 검증 기한(퇴사일 + 15일)이 지나면 410 `EVALUATION_EXPIRED`, 직원이 재직 중이면 403 `STILL_EMPLOYED`입니다. + +--- + +## 9. 결과 확인 → 의견 제출 + +**9-1. 결과 조회 (직원)** +``` +GET {{baseUrl}}/evaluations/result/{{resultToken}} +``` +→ `items[{ question, selfScore, ceoScore, scoreGap }]`, `commonCompetencies`, `rehireIntent`, `opinion{ allowed, submitted, dueAt }` + +- `scoreGap = ceoScore - selfScore` (자기점수가 없으면 null) +- 처음 열면 결과 확인 시각이 기록됩니다. 링크는 소비되지 않아 여러 번 볼 수 있습니다. + +**9-2. 의견 제출 (직원)** +``` +POST {{baseUrl}}/evaluations/result/{{resultToken}}/opinion +``` +```json +{ "content": "대표 검증 결과 중 협업 점수에 대해 보완 설명을 제출합니다." } +``` +→ `{ evaluationId, opinionId, submittedAt }` + +- 1회만 제출할 수 있고, 대표 검증 완료 + 7일 KST 23:59:59까지 가능합니다. +- 앞뒤 공백 제거 후 1~1000자. 의견을 내도 점수는 바뀌지 않습니다. + +**9-3. 결과 조회 (대표)** +``` +GET {{baseUrl}}/evaluations/{{evaluationId}}/result +``` +→ 자기선언 답변·자기점수·대표점수·`scoreGap`·역량·`rehireIntent`, `notification{ sent, viewedAt }`, `employeeOpinion{ submitted, content, submittedAt, dueAt }` + +- 9-1에서 직원이 결과를 열었으면 `notification.viewedAt`, 9-2에서 의견을 냈으면 `employeeOpinion.content`가 채워집니다. + +--- + +## 상태 변화 요약 + +| 단계 | Employee | Declaration | Evaluation | +|---|---|---|---| +| 3. 직원 등록 | `EMPLOYED` / `NOT_SENT` | — | — | +| 4. 질문지 발송 | 선언 `SENT` | `SENT` | — | +| 5. 자기선언 제출 | 선언 `SUBMITTED` | `SUBMITTED` | — | +| 6. 퇴사 등록 | `RESIGNED` | — | `SELF_PENDING` | +| 7. 자기평가 제출 | — | — | `CEO_PENDING` | +| (자기평가 기한 초과) | — | — | `SELF_EXPIRED` | +| 8. 대표 검증 제출 | — | — | `COMPLETED` | +| (대표 검증 기한 초과) | — | — | `CEO_EXPIRED` | + +- 기한 초과 상태는 매시간 도는 스케줄러가 바꿉니다. 다만 API는 마감 시각을 직접 확인하므로, 스케줄러가 돌기 전에도 기한이 지나면 바로 막힙니다. + +## 자주 만나는 오류 + +| 코드 | 상황 | 해결 | +|---|---|---| +| 401 `UNAUTHORIZED` | `ceoToken` 없음·만료(기본 1시간) | 1단계 다시 로그인 | +| 410 `LINK_EXPIRED` | 직원 링크 만료·폐기, 토큰 오타 | 메일·로그의 최신 링크 확인 | +| 409 `ALREADY_SUBMITTED` | 같은 링크로 이미 제출 | 다음 단계로 진행 | +| 409 `ACTIVE_DECLARATION_EXISTS` | 제출 전 질문지가 이미 있음 | 기존 질문지 링크로 제출 | +| 409 `DECLARATION_NOT_SUBMITTED` | 자기선언 제출 전 퇴사 등록 | 5단계 먼저 | +| 409 `INVALID_EVALUATION_STATUS` | 자기평가 진행 중에 대표 검증 시도 | 7단계 먼저(또는 자기평가 기한 경과 대기) | +| 409 `EVALUATION_NOT_COMPLETED` | 대표 검증 전 결과 조회 | 8단계 먼저 | diff --git a/src/evaluations/ceo-evaluation.service.spec.ts b/src/evaluations/ceo-evaluation.service.spec.ts index 4d7695c..20dfe43 100644 --- a/src/evaluations/ceo-evaluation.service.spec.ts +++ b/src/evaluations/ceo-evaluation.service.spec.ts @@ -347,6 +347,34 @@ describe('CeoEvaluationService (법적 안전 로직)', () => { }); }); + describe('결과 메일 발송 여부 기록 (대표 결과 화면 notification.sent)', () => { + it('발송 결과를 커밋 후 감사 로그 EVALUATION_RESULT_NOTIFIED로 남긴다 (성공·실패 모두)', async () => { + await service.submit(CEO, 'ev-1', validDto(), META); + expect(auditMock.log).toHaveBeenCalledWith({ + actorType: 'SYSTEM', + action: 'EVALUATION_RESULT_NOTIFIED', + targetType: 'Evaluation', + targetId: 'ev-1', + metadata: { sent: true }, + }); + + state.status = 'CEO_PENDING'; + mailMock.sendEvaluationResult.mockResolvedValue(false); + await service.submit(CEO, 'ev-1', validDto(), META); + expect(auditMock.log).toHaveBeenLastCalledWith(expect.objectContaining({ metadata: { sent: false } })); + }); + + it('발송 기록이 실패해도 제출 응답은 성공한다 (이미 커밋됨)', async () => { + auditMock.log.mockImplementation(async (params: any) => { + if (params.action === 'EVALUATION_RESULT_NOTIFIED') throw new Error('DB down'); + }); + const errorSpy = jest.spyOn((service as any).logger, 'error').mockImplementation(() => undefined); + + await expect(service.submit(CEO, 'ev-1', validDto(), META)).resolves.toMatchObject({ status: 'COMPLETED' }); + expect(errorSpy).toHaveBeenCalled(); + }); + }); + // 16 describe('검사 우선순위 (프롬프트 순서)', () => { it('재직 중 + COMPLETED → 403 STILL_EMPLOYED가 먼저', async () => { diff --git a/src/evaluations/ceo-evaluation.service.ts b/src/evaluations/ceo-evaluation.service.ts index 3030a1d..b38c356 100644 --- a/src/evaluations/ceo-evaluation.service.ts +++ b/src/evaluations/ceo-evaluation.service.ts @@ -4,6 +4,7 @@ import { ForbiddenException, GoneException, Injectable, + Logger, NotFoundException, UnprocessableEntityException, } from '@nestjs/common'; @@ -19,6 +20,7 @@ import { COMMON_COMPETENCIES, OPINION_DUE_DAYS, RESULT_LINK_EXTRA_DAYS, + RESULT_NOTIFIED_ACTION, } from './competency.constants'; import { SubmitCeoEvaluationDto } from './dto/submit-ceo-evaluation.dto'; import { SCORE_MAX, SCORE_MIN, isValidScore } from './evaluation.constants'; @@ -43,6 +45,8 @@ type EvaluationWithEmployee = Evaluation & { */ @Injectable() export class CeoEvaluationService { + private readonly logger = new Logger(CeoEvaluationService.name); + constructor( private readonly prisma: PrismaService, private readonly accessLinkService: AccessLinkService, @@ -203,6 +207,7 @@ export class CeoEvaluationService { companyName: company?.companyName, expiresAt: linkExpiresAt, }); + await this.recordResultNotification(evaluationId, resultNotified); return { evaluationId, @@ -213,6 +218,24 @@ export class CeoEvaluationService { }; } + /** + * 결과 메일 발송 여부를 감사 로그로 남긴다 (대표 결과 화면의 notification.sent에 사용). + * 이미 커밋된 뒤라 기록 실패가 제출 응답을 실패로 만들지 않도록 예외를 삼킨다. + */ + private async recordResultNotification(evaluationId: string, sent: boolean): Promise { + try { + await this.auditService.log({ + actorType: 'SYSTEM', + action: RESULT_NOTIFIED_ACTION, + targetType: 'Evaluation', + targetId: evaluationId, + metadata: { sent }, + }); + } catch (error) { + this.logger.error(`결과 통보 기록 실패: ${evaluationId}`, error instanceof Error ? error.stack : String(error)); + } + } + private async findEvaluation(client: Client, evaluationId: string): Promise { return client.evaluation.findUnique({ where: { id: evaluationId }, diff --git a/src/evaluations/competency.constants.ts b/src/evaluations/competency.constants.ts index 2f4b5f8..69adcfa 100644 --- a/src/evaluations/competency.constants.ts +++ b/src/evaluations/competency.constants.ts @@ -15,3 +15,14 @@ export const OPINION_DUE_DAYS = 7; /** 결과 확인 링크는 의견 마감 후에도 30일간 결과 열람용으로 유지 */ export const RESULT_LINK_EXTRA_DAYS = 30; + +/** 결과 메일 발송 여부를 남기는 감사 로그 action (metadata.sent: boolean) */ +export const RESULT_NOTIFIED_ACTION = 'EVALUATION_RESULT_NOTIFIED'; + +/** 직원 의견 최대 글자 수 */ +export const OPINION_MAX_LENGTH = 1000; + +/** 점수 차이 = 대표 점수 - 자기 점수. 둘 중 하나라도 없으면 null */ +export function scoreGap(selfScore: number | null, ceoScore: number | null): number | null { + return selfScore == null || ceoScore == null ? null : ceoScore - selfScore; +} diff --git a/src/evaluations/dto/submit-opinion.dto.ts b/src/evaluations/dto/submit-opinion.dto.ts new file mode 100644 index 0000000..4dbd2aa --- /dev/null +++ b/src/evaluations/dto/submit-opinion.dto.ts @@ -0,0 +1,12 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsString } from 'class-validator'; + +export class SubmitOpinionDto { + // 빈 값·1000자 초과는 서비스에서 trim 후 422 INVALID_OPINION으로 판정 + @ApiProperty({ + example: '대표 검증 결과 중 협업 점수에 대해 보완 설명을 제출합니다.', + description: '평가 결과에 대한 의견 (앞뒤 공백 제거 후 1~1000자, 1회만 제출)', + }) + @IsString() + content!: string; +} diff --git a/src/evaluations/evaluation-result.controller.ts b/src/evaluations/evaluation-result.controller.ts new file mode 100644 index 0000000..5f5e042 --- /dev/null +++ b/src/evaluations/evaluation-result.controller.ts @@ -0,0 +1,35 @@ +import { Controller, Get, Param, 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 { EvaluationResultService } from './evaluation-result.service'; + +/** + * 대표용 평가 비교 결과 (CEO JWT). + * 직원용 결과 라우트(evaluations/result/:token)는 ResultLinkController로 분리해 먼저 등록한다. + */ +@ApiTags('Evaluations') +@ApiBearerAuth('access-token') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('COMPANY') +@Controller('evaluations') +export class EvaluationResultController { + constructor(private readonly evaluationResultService: EvaluationResultService) {} + + @Get(':evaluationId/result') + @ApiOperation({ summary: '대표: 평가 비교 결과 조회 (자기선언·자기점수·대표점수·점수 차이·역량·결과 통보·직원 의견)' }) + @ApiParam({ name: 'evaluationId', description: '평가 ID' }) + @ApiResponse({ status: 200, description: '조회 성공' }) + @ApiResponse({ status: 401, description: '인증 필요' }) + @ApiResponse({ status: 403, description: 'FORBIDDEN (대표 권한 또는 직원 소속 불일치)' }) + @ApiResponse({ status: 404, description: 'EVALUATION_NOT_FOUND' }) + @ApiResponse({ status: 409, description: 'EVALUATION_NOT_COMPLETED (대표 검증 미완료)' }) + @ResponseMessage('대표 평가 비교 결과 조회 성공') + getResult(@CurrentUser() user: JwtPayload, @Param('evaluationId') evaluationId: string) { + return this.evaluationResultService.getCompanyResult(user, evaluationId); + } +} diff --git a/src/evaluations/evaluation-result.service.spec.ts b/src/evaluations/evaluation-result.service.spec.ts new file mode 100644 index 0000000..43f8819 --- /dev/null +++ b/src/evaluations/evaluation-result.service.spec.ts @@ -0,0 +1,288 @@ +import { + ConflictException, + ForbiddenException, + GoneException, + HttpException, + NotFoundException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { Prisma } from '@prisma/client'; +import { AccessLinkService } from '../access-link/access-link.service'; +import { AuditService } from '../audit/audit.service'; +import { PrismaService } from '../prisma/prisma.service'; +import { EvaluationResultService } from './evaluation-result.service'; + +const CEO = { sub: 'comp-1', role: 'COMPANY' as const }; +const META = { ip: '127.0.0.1', userAgent: 'jest' }; +const COMPLETED_AT = new Date('2026-05-05T01:00:00.000Z'); // KST 5/5 10:00 +const OPINION_DUE = new Date('2026-05-12T14:59:59.000Z'); // KST 5/12 23:59:59 + +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 completedEvaluation = (over: Record = {}) => ({ + id: 'ev-1', + companyId: 'comp-1', + employeeId: 'emp-1', + status: 'COMPLETED', + completedAt: COMPLETED_AT, + opinionDueAt: OPINION_DUE, + rehireIntent: true, + resultViewedAt: null, + employee: { id: 'emp-1', name: '김민준' }, + items: [ + { id: 'it-1', snapshotQuestionId: 'snap-1', order: 1, selfScore: 8, ceoScore: 7, snapshotQuestion: snapshot('snap-1', 1, 'SCORE', { answerScore: 8 }) }, + { id: 'it-2', snapshotQuestionId: 'snap-3', order: 3, selfScore: null, ceoScore: 8, snapshotQuestion: snapshot('snap-3', 3, 'TEXT', { answerText: 'React' }) }, + ], + competencyScores: [ + { key: 'GROWTH_POTENTIAL', score: 9 }, { key: 'TRUST', score: 8 }, { key: 'DILIGENCE', score: 9 }, + { key: 'RESPONSIBILITY', score: 8 }, { key: 'COLLABORATION', score: 7 }, { key: 'COMMUNICATION', score: 7 }, + ], + opinion: null, + ...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('EvaluationResultService', () => { + let prismaMock: any; + let accessLinkMock: { verify: jest.Mock; consume: jest.Mock }; + let auditMock: { log: jest.Mock }; + let service: EvaluationResultService; + + beforeEach(() => { + jest.useFakeTimers().setSystemTime(new Date('2026-05-06T00:00:00.000Z')); + prismaMock = { + hrManager: { findUnique: jest.fn() }, + evaluation: { + findUnique: jest.fn().mockResolvedValue(completedEvaluation()), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + evaluationItem: { update: jest.fn(), updateMany: jest.fn() }, + competencyScore: { update: jest.fn(), updateMany: jest.fn(), createMany: jest.fn() }, + evaluationOpinion: { + create: jest.fn(async ({ data }: any) => ({ id: 'op-1', ...data })), + }, + auditLog: { findFirst: jest.fn().mockResolvedValue({ metadata: { sent: true } }) }, + company: { findUnique: jest.fn().mockResolvedValue({ companyName: '테크플러스 주식회사' }) }, + $transaction: jest.fn(async (fn: any) => fn(prismaMock)), + }; + accessLinkMock = { + verify: jest.fn().mockResolvedValue({ id: 'link-1', purpose: 'EVALUATION_RESULT', targetId: 'ev-1' }), + consume: jest.fn(), + }; + auditMock = { log: jest.fn().mockResolvedValue(undefined) }; + service = new EvaluationResultService( + prismaMock as unknown as PrismaService, + accessLinkMock as unknown as AccessLinkService, + auditMock as unknown as AuditService, + ); + }); + + afterEach(() => jest.useRealTimers()); + + describe('대표 결과 조회', () => { + it('자기선언·자기점수·대표점수·점수 차이(대표-자기)·역량(정해진 순서)·통보·의견을 반환한다', async () => { + prismaMock.evaluation.findUnique.mockResolvedValue(completedEvaluation({ + resultViewedAt: new Date('2026-05-06T00:00:00.000Z'), + opinion: { id: 'op-1', content: '보완 설명', submittedAt: new Date('2026-05-07T01:00:00.000Z') }, + })); + + const result = await service.getCompanyResult(CEO, 'ev-1'); + + expect(result).toEqual({ + evaluationId: 'ev-1', + employeeId: 'emp-1', + status: 'COMPLETED', + completedAt: COMPLETED_AT, + items: [ + { questionId: 'snap-1', order: 1, question: '질문 1', declarationAnswer: { type: 'SCORE', score: 8 }, selfScore: 8, ceoScore: 7, scoreGap: -1 }, + // 자기평가 만료로 자기점수가 없으면 점수 차이도 null + { questionId: 'snap-3', order: 3, question: '질문 3', declarationAnswer: { type: 'TEXT', text: 'React' }, selfScore: null, ceoScore: 8, scoreGap: null }, + ], + commonCompetencies: [ + { key: 'TRUST', name: '신뢰', ceoScore: 8 }, + { key: 'DILIGENCE', name: '성실성', ceoScore: 9 }, + { key: 'RESPONSIBILITY', name: '책임감', ceoScore: 8 }, + { key: 'COLLABORATION', name: '협업', ceoScore: 7 }, + { key: 'COMMUNICATION', name: '의사소통', ceoScore: 7 }, + { key: 'GROWTH_POTENTIAL', name: '성장 가능성', ceoScore: 9 }, + ], + rehireIntent: true, + notification: { sent: true, viewedAt: new Date('2026-05-06T00:00:00.000Z') }, + employeeOpinion: { + submitted: true, + content: '보완 설명', + submittedAt: new Date('2026-05-07T01:00:00.000Z'), + dueAt: OPINION_DUE, + }, + }); + expect(prismaMock.auditLog.findFirst).toHaveBeenCalledWith({ + where: { action: 'EVALUATION_RESULT_NOTIFIED', targetType: 'Evaluation', targetId: 'ev-1' }, + orderBy: { createdAt: 'desc' }, + select: { metadata: true }, + }); + }); + + it('결과 메일 실패 기록이거나 기록이 없으면 notification.sent=false, 의견 미제출이면 submitted=false', async () => { + prismaMock.auditLog.findFirst.mockResolvedValueOnce({ metadata: { sent: false } }); + const failed = await service.getCompanyResult(CEO, 'ev-1'); + expect(failed.notification).toEqual({ sent: false, viewedAt: null }); + expect(failed.employeeOpinion).toEqual({ submitted: false, content: null, submittedAt: null, dueAt: OPINION_DUE }); + + prismaMock.auditLog.findFirst.mockResolvedValueOnce(null); + expect((await service.getCompanyResult(CEO, 'ev-1')).notification.sent).toBe(false); + }); + + it('대표 검증 전이면 409 EVALUATION_NOT_COMPLETED', async () => { + prismaMock.evaluation.findUnique.mockResolvedValue(completedEvaluation({ status: 'CEO_PENDING' })); + await expectCode(service.getCompanyResult(CEO, 'ev-1'), ConflictException, 'EVALUATION_NOT_COMPLETED'); + }); + + it('다른 기업 403 FORBIDDEN, 없는 평가 404 EVALUATION_NOT_FOUND', async () => { + prismaMock.evaluation.findUnique.mockResolvedValueOnce(completedEvaluation({ companyId: 'comp-other' })); + await expectCode(service.getCompanyResult(CEO, 'ev-1'), ForbiddenException, 'FORBIDDEN'); + prismaMock.evaluation.findUnique.mockResolvedValueOnce(null); + await expectCode(service.getCompanyResult(CEO, 'nope'), NotFoundException, 'EVALUATION_NOT_FOUND'); + }); + }); + + describe('직원 결과 조회', () => { + it('점수 비교·역량·의견 가능 여부를 반환하고, 링크는 소비하지 않으며 최초 조회 시각을 기록한다', async () => { + const result = await service.getEmployeeResult('tok'); + + expect(accessLinkMock.verify).toHaveBeenCalledWith('tok', 'EVALUATION_RESULT'); + expect(accessLinkMock.consume).not.toHaveBeenCalled(); + expect(result).toEqual({ + evaluationId: 'ev-1', + employee: { name: '김민준', companyName: '테크플러스 주식회사' }, + completedAt: COMPLETED_AT, + items: [ + { questionId: 'snap-1', question: '질문 1', selfScore: 8, ceoScore: 7, scoreGap: -1 }, + { questionId: 'snap-3', question: '질문 3', selfScore: null, ceoScore: 8, scoreGap: null }, + ], + commonCompetencies: expect.arrayContaining([{ key: 'TRUST', name: '신뢰', ceoScore: 8 }]), + rehireIntent: true, + opinion: { allowed: true, submitted: false, dueAt: OPINION_DUE }, + }); + expect(prismaMock.evaluation.updateMany).toHaveBeenCalledWith({ + where: { id: 'ev-1', resultViewedAt: null }, + data: { resultViewedAt: new Date('2026-05-06T00:00:00.000Z') }, + }); + }); + + it('이미 조회한 적 있으면 조회 시각을 다시 쓰지 않는다', async () => { + prismaMock.evaluation.findUnique.mockResolvedValue(completedEvaluation({ resultViewedAt: new Date('2026-05-05T12:00:00Z') })); + await service.getEmployeeResult('tok'); + expect(prismaMock.evaluation.updateMany).not.toHaveBeenCalled(); + }); + + it('의견을 이미 냈거나 기한이 지나면 opinion.allowed=false', async () => { + prismaMock.evaluation.findUnique.mockResolvedValueOnce(completedEvaluation({ opinion: { id: 'op-1' } })); + expect((await service.getEmployeeResult('tok')).opinion).toEqual({ allowed: false, submitted: true, dueAt: OPINION_DUE }); + + jest.setSystemTime(new Date(OPINION_DUE.getTime() + 1000)); + expect((await service.getEmployeeResult('tok')).opinion).toEqual({ allowed: false, submitted: false, dueAt: OPINION_DUE }); + }); + + it('대표 검증 전이면 409 EVALUATION_NOT_COMPLETED, 링크 오류(410·403)는 그대로', async () => { + prismaMock.evaluation.findUnique.mockResolvedValueOnce(completedEvaluation({ status: 'CEO_PENDING' })); + await expectCode(service.getEmployeeResult('tok'), ConflictException, 'EVALUATION_NOT_COMPLETED'); + + accessLinkMock.verify.mockRejectedValueOnce(new GoneException({ code: 'LINK_EXPIRED' })); + await expectCode(service.getEmployeeResult('tok'), GoneException, 'LINK_EXPIRED'); + accessLinkMock.verify.mockRejectedValueOnce(new ForbiddenException({ code: 'INVALID_LINK_PURPOSE' })); + await expectCode(service.getEmployeeResult('tok'), ForbiddenException, 'INVALID_LINK_PURPOSE'); + }); + }); + + describe('의견 제출', () => { + it('trim한 의견만 저장하고 점수는 건드리지 않으며 링크도 소비하지 않는다', async () => { + const result = await service.submitOpinion('tok', { content: ' 협업 점수 보완 설명 ' }, META); + + expect(result).toEqual({ evaluationId: 'ev-1', opinionId: 'op-1', submittedAt: new Date('2026-05-06T00:00:00.000Z') }); + expect(prismaMock.evaluationOpinion.create).toHaveBeenCalledWith({ + data: { evaluationId: 'ev-1', content: '협업 점수 보완 설명', submittedAt: new Date('2026-05-06T00:00:00.000Z') }, + }); + // 점수 불변: 자기점수·대표점수·역량 점수와 평가 본문에 대한 쓰기가 전혀 없다 + expect(prismaMock.evaluationItem.update).not.toHaveBeenCalled(); + expect(prismaMock.evaluationItem.updateMany).not.toHaveBeenCalled(); + expect(prismaMock.competencyScore.update).not.toHaveBeenCalled(); + expect(prismaMock.competencyScore.updateMany).not.toHaveBeenCalled(); + expect(prismaMock.competencyScore.createMany).not.toHaveBeenCalled(); + expect(prismaMock.evaluation.updateMany).not.toHaveBeenCalled(); + expect(accessLinkMock.consume).not.toHaveBeenCalled(); + expect(auditMock.log).toHaveBeenCalledWith( + expect.objectContaining({ actorType: 'EMPLOYEE', action: 'OPINION_SUBMITTED', targetId: 'ev-1' }), + prismaMock, + ); + }); + + it('이미 제출했으면 409 OPINION_ALREADY_SUBMITTED', async () => { + prismaMock.evaluation.findUnique.mockResolvedValue(completedEvaluation({ opinion: { id: 'op-0' } })); + await expectCode(service.submitOpinion('tok', { content: '또 제출' }, META), ConflictException, 'OPINION_ALREADY_SUBMITTED'); + expect(prismaMock.evaluationOpinion.create).not.toHaveBeenCalled(); + }); + + it('동시 제출로 unique 제약에 걸려도 409 OPINION_ALREADY_SUBMITTED', async () => { + prismaMock.evaluationOpinion.create.mockRejectedValue( + new Prisma.PrismaClientKnownRequestError('Unique constraint failed', { code: 'P2002', clientVersion: '5.22.0' }), + ); + await expectCode(service.submitOpinion('tok', { content: '의견' }, META), ConflictException, 'OPINION_ALREADY_SUBMITTED'); + }); + + it('의견 마감 1초 후 410 OPINION_PERIOD_EXPIRED, 마감 정각은 허용', async () => { + jest.setSystemTime(new Date(OPINION_DUE.getTime() + 1000)); + await expectCode(service.submitOpinion('tok', { content: '늦은 의견' }, META), GoneException, 'OPINION_PERIOD_EXPIRED'); + expect(prismaMock.evaluationOpinion.create).not.toHaveBeenCalled(); + + jest.setSystemTime(OPINION_DUE); + await expect(service.submitOpinion('tok', { content: '정각 의견' }, META)).resolves.toMatchObject({ opinionId: 'op-1' }); + }); + + it.each([ + ['빈 문자열', ''], + ['공백만', ' \n\t '], + ['1001자', '가'.repeat(1001)], + ])('%s이면 422 INVALID_OPINION', async (_label, content) => { + await expectCode(service.submitOpinion('tok', { content }, META), UnprocessableEntityException, 'INVALID_OPINION'); + expect(prismaMock.evaluationOpinion.create).not.toHaveBeenCalled(); + }); + + it('정확히 1000자는 허용 (앞뒤 공백은 글자 수에서 제외)', async () => { + await expect(service.submitOpinion('tok', { content: ` ${'가'.repeat(1000)} ` }, META)).resolves.toMatchObject({ opinionId: 'op-1' }); + }); + + it('대표 검증 전이면 409 EVALUATION_NOT_COMPLETED', async () => { + prismaMock.evaluation.findUnique.mockResolvedValue(completedEvaluation({ status: 'CEO_PENDING' })); + await expectCode(service.submitOpinion('tok', { content: '의견' }, META), ConflictException, 'EVALUATION_NOT_COMPLETED'); + }); + + it('이미 제출 + 기한 지남이면 409가 410보다 먼저', async () => { + prismaMock.evaluation.findUnique.mockResolvedValue(completedEvaluation({ opinion: { id: 'op-0' } })); + jest.setSystemTime(new Date(OPINION_DUE.getTime() + 1000)); + await expectCode(service.submitOpinion('tok', { content: '의견' }, META), ConflictException, 'OPINION_ALREADY_SUBMITTED'); + }); + + it('만료·폐기 링크는 410 LINK_EXPIRED', async () => { + accessLinkMock.verify.mockRejectedValueOnce(new GoneException({ code: 'LINK_EXPIRED' })); + await expectCode(service.submitOpinion('tok', { content: '의견' }, META), GoneException, 'LINK_EXPIRED'); + }); + }); +}); diff --git a/src/evaluations/evaluation-result.service.ts b/src/evaluations/evaluation-result.service.ts new file mode 100644 index 0000000..de985cb --- /dev/null +++ b/src/evaluations/evaluation-result.service.ts @@ -0,0 +1,253 @@ +import { + ConflictException, + ForbiddenException, + GoneException, + Injectable, + NotFoundException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { 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 { PrismaService } from '../prisma/prisma.service'; +import { + COMMON_COMPETENCIES, + OPINION_MAX_LENGTH, + RESULT_NOTIFIED_ACTION, + scoreGap, +} from './competency.constants'; +import { SubmitOpinionDto } from './dto/submit-opinion.dto'; +import { RequestMeta, toDeclarationAnswer } from './self-evaluation.service'; + +const RESULT_INCLUDE = { + items: { + orderBy: { order: 'asc' }, + include: { snapshotQuestion: { include: { response: true } } }, + }, + competencyScores: true, + opinion: true, + employee: { select: { id: true, name: true } }, +} satisfies Prisma.EvaluationInclude; + +type EvaluationWithResult = Prisma.EvaluationGetPayload<{ include: typeof RESULT_INCLUDE }>; + +/** + * 평가 결과 조회(대표·직원)와 직원 의견 제출. + * 의견은 EvaluationOpinion에만 저장하며 자기점수·대표점수는 절대 바꾸지 않는다. + */ +@Injectable() +export class EvaluationResultService { + constructor( + private readonly prisma: PrismaService, + private readonly accessLinkService: AccessLinkService, + private readonly auditService: AuditService, + ) {} + + /** 대표: 자기선언 답변·자기점수·대표점수·점수 차이·역량·결과 통보·직원 의견 */ + async getCompanyResult(user: JwtPayload, evaluationId: string) { + const companyId = await resolveCompanyId(user, this.prisma); + + const evaluation = await this.prisma.evaluation.findUnique({ + where: { id: evaluationId }, + include: RESULT_INCLUDE, + }); + if (!evaluation) { + throw new NotFoundException({ code: 'EVALUATION_NOT_FOUND', message: '평가를 찾을 수 없습니다.' }); + } + if (evaluation.companyId !== companyId) { + throw new ForbiddenException({ code: 'FORBIDDEN', message: '다른 기업의 평가에는 접근할 수 없습니다.' }); + } + assertCompleted(evaluation); + + const notification = await this.prisma.auditLog.findFirst({ + where: { action: RESULT_NOTIFIED_ACTION, targetType: 'Evaluation', targetId: evaluationId }, + orderBy: { createdAt: 'desc' }, + select: { metadata: true }, + }); + + return { + evaluationId: evaluation.id, + employeeId: evaluation.employeeId, + status: evaluation.status, + completedAt: evaluation.completedAt, + items: evaluation.items.map((item) => ({ + questionId: item.snapshotQuestionId, + order: item.order, + question: item.snapshotQuestion.text, + declarationAnswer: toDeclarationAnswer(item.snapshotQuestion), + selfScore: item.selfScore, + ceoScore: item.ceoScore, + scoreGap: scoreGap(item.selfScore, item.ceoScore), + })), + commonCompetencies: toCompetencies(evaluation), + rehireIntent: evaluation.rehireIntent, + notification: { + sent: (notification?.metadata as { sent?: boolean } | null)?.sent === true, + viewedAt: evaluation.resultViewedAt, + }, + employeeOpinion: { + submitted: !!evaluation.opinion, + content: evaluation.opinion?.content ?? null, + submittedAt: evaluation.opinion?.submittedAt ?? null, + dueAt: evaluation.opinionDueAt, + }, + }; + } + + /** 직원: 결과 링크로 비교 결과 조회. 링크는 소비하지 않고, 최초 조회 시각만 기록한다. */ + async getEmployeeResult(token: string) { + const link = await this.accessLinkService.verify(token, 'EVALUATION_RESULT'); + + const evaluation = await this.prisma.evaluation.findUnique({ + where: { id: link.targetId }, + include: RESULT_INCLUDE, + }); + if (!evaluation) { + throw linkExpired(); + } + assertCompleted(evaluation); + + if (!evaluation.resultViewedAt) { + // 조건부 갱신이라 동시에 여러 번 열어도 최초 시각만 남는다 + await this.prisma.evaluation.updateMany({ + where: { id: evaluation.id, resultViewedAt: null }, + data: { resultViewedAt: new Date() }, + }); + } + + const company = await this.prisma.company.findUnique({ + where: { id: evaluation.companyId }, + select: { companyName: true }, + }); + const submitted = !!evaluation.opinion; + + return { + evaluationId: evaluation.id, + employee: { name: evaluation.employee.name, companyName: company?.companyName ?? null }, + completedAt: evaluation.completedAt, + items: evaluation.items.map((item) => ({ + questionId: item.snapshotQuestionId, + question: item.snapshotQuestion.text, + selfScore: item.selfScore, + ceoScore: item.ceoScore, + scoreGap: scoreGap(item.selfScore, item.ceoScore), + })), + commonCompetencies: toCompetencies(evaluation), + rehireIntent: evaluation.rehireIntent, + opinion: { + allowed: !submitted && isWithinOpinionPeriod(evaluation.opinionDueAt, new Date()), + submitted, + dueAt: evaluation.opinionDueAt, + }, + }; + } + + /** + * 직원: 결과에 대한 의견 1회 제출. 링크는 소비하지 않는다(제출 후에도 결과 조회 가능). + * 판정 순서: 링크(410/403) → 미완료 409 → 이미 제출 409 → 기한 초과 410 → 내용 422 + */ + async submitOpinion(token: string, dto: SubmitOpinionDto, meta: RequestMeta) { + return this.prisma.$transaction(async (tx) => { + const link = await this.accessLinkService.verify(token, 'EVALUATION_RESULT', tx); + + const evaluation = await tx.evaluation.findUnique({ + where: { id: link.targetId }, + include: { opinion: { select: { id: true } } }, + }); + if (!evaluation) { + throw linkExpired(); + } + assertCompleted(evaluation); + if (evaluation.opinion) { + throw opinionAlreadySubmitted(); + } + + const now = new Date(); + if (!isWithinOpinionPeriod(evaluation.opinionDueAt, now)) { + throw new GoneException({ + code: 'OPINION_PERIOD_EXPIRED', + message: '의견 제출 기한(대표 검증 완료 + 7일)이 지났습니다.', + details: { opinionDueAt: evaluation.opinionDueAt }, + }); + } + + const content = dto.content.trim(); + if (!content || content.length > OPINION_MAX_LENGTH) { + throw new UnprocessableEntityException({ + code: 'INVALID_OPINION', + message: `의견은 1~${OPINION_MAX_LENGTH}자로 입력해 주세요.`, + details: { length: content.length, maxLength: OPINION_MAX_LENGTH }, + }); + } + + let opinion; + try { + // 점수(EvaluationItem·CompetencyScore)는 건드리지 않고 의견만 저장한다 + opinion = await tx.evaluationOpinion.create({ + data: { evaluationId: evaluation.id, content, submittedAt: now }, + }); + } catch (error) { + // 동시 제출: evaluationId @unique 위반 + if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') { + throw opinionAlreadySubmitted(); + } + throw error; + } + + await this.auditService.log( + { + actorType: 'EMPLOYEE', + actorId: evaluation.employeeId, + action: 'OPINION_SUBMITTED', + targetType: 'Evaluation', + targetId: evaluation.id, + ip: meta.ip, + userAgent: meta.userAgent, + metadata: { opinionId: opinion.id, length: content.length }, + }, + tx, + ); + + return { evaluationId: evaluation.id, opinionId: opinion.id, submittedAt: opinion.submittedAt }; + }); + } +} + +function toCompetencies(evaluation: EvaluationWithResult) { + return COMMON_COMPETENCIES.map(({ key, name }) => ({ + key, + name, + ceoScore: evaluation.competencyScores.find((c) => c.key === key)?.score ?? null, + })); +} + +/** 의견 마감 시각(KST 23:59:59)까지는 허용 */ +function isWithinOpinionPeriod(opinionDueAt: Date | null, now: Date): boolean { + return !!opinionDueAt && now.getTime() <= opinionDueAt.getTime(); +} + +function assertCompleted(evaluation: { status: string }): void { + if (evaluation.status !== 'COMPLETED') { + throw new ConflictException({ + code: 'EVALUATION_NOT_COMPLETED', + message: '대표 검증이 완료되지 않은 평가입니다.', + details: { status: evaluation.status }, + }); + } +} + +function opinionAlreadySubmitted(): ConflictException { + return new ConflictException({ + code: 'OPINION_ALREADY_SUBMITTED', + message: '이미 의견을 제출했습니다.', + }); +} + +function linkExpired(): GoneException { + return new GoneException({ + code: 'LINK_EXPIRED', + message: '만료되었거나 유효하지 않은 링크입니다.', + }); +} diff --git a/src/evaluations/evaluations.module.ts b/src/evaluations/evaluations.module.ts index 6af1b93..8db34b3 100644 --- a/src/evaluations/evaluations.module.ts +++ b/src/evaluations/evaluations.module.ts @@ -6,6 +6,9 @@ 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 { EvaluationResultController } from './evaluation-result.controller'; +import { EvaluationResultService } from './evaluation-result.service'; +import { ResultLinkController } from './result-link.controller'; import { SelfEvaluationController } from './self-evaluation.controller'; import { SelfEvaluationService } from './self-evaluation.service'; @@ -13,8 +16,14 @@ import { SelfEvaluationService } from './self-evaluation.service'; @Module({ // AuthModule: 대표 API의 JwtAuthGuard가 RedisService(토큰 블랙리스트)를 사용 imports: [AuthModule, AccessLinkModule, NotificationModule, AuditModule], - // 직원용 라우트(evaluations/self/:token)를 대표용(evaluations/:evaluationId/ceo)보다 먼저 등록 - controllers: [SelfEvaluationController, CeoEvaluationController], - providers: [SelfEvaluationService, CeoEvaluationService, EvaluationExpiryScheduler], + // 직원용 토큰 라우트(evaluations/self/:token, evaluations/result/:token)를 + // 대표용 라우트(evaluations/:evaluationId/ceo, evaluations/:evaluationId/result)보다 먼저 등록 + controllers: [ + SelfEvaluationController, + ResultLinkController, + CeoEvaluationController, + EvaluationResultController, + ], + providers: [SelfEvaluationService, CeoEvaluationService, EvaluationResultService, EvaluationExpiryScheduler], }) export class EvaluationsModule {} diff --git a/src/evaluations/evaluations.routes.spec.ts b/src/evaluations/evaluations.routes.spec.ts new file mode 100644 index 0000000..e89ba2a --- /dev/null +++ b/src/evaluations/evaluations.routes.spec.ts @@ -0,0 +1,102 @@ +import { INestApplication } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; +import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; +import { RolesGuard } from '../core/guards/roles.guard'; +import { CeoEvaluationController } from './ceo-evaluation.controller'; +import { CeoEvaluationService } from './ceo-evaluation.service'; +import { EvaluationResultController } from './evaluation-result.controller'; +import { EvaluationResultService } from './evaluation-result.service'; +import { ResultLinkController } from './result-link.controller'; +import { SelfEvaluationController } from './self-evaluation.controller'; +import { SelfEvaluationService } from './self-evaluation.service'; + +/** + * 라우트 매칭 테스트: 실제 Nest 앱을 띄워 HTTP로 요청하고 어느 핸들러가 받는지 확인한다. + * 'evaluations/result/:token'(직원)과 'evaluations/:evaluationId/result'(대표)가 섞이지 않아야 한다. + */ +describe('evaluations 라우트 매칭', () => { + let app: INestApplication; + let baseUrl: string; + const result = { getCompanyResult: jest.fn(), getEmployeeResult: jest.fn(), submitOpinion: jest.fn() }; + const self = { getForm: jest.fn(), submit: jest.fn() }; + const ceo = { getForm: jest.fn(), submit: jest.fn() }; + const TOKEN = 'a'.repeat(64); + const EVALUATION_ID = '11111111-2222-3333-4444-555555555555'; + + beforeAll(async () => { + const moduleRef = await Test.createTestingModule({ + // 모듈과 같은 등록 순서 + controllers: [SelfEvaluationController, ResultLinkController, CeoEvaluationController, EvaluationResultController], + providers: [ + { provide: SelfEvaluationService, useValue: self }, + { provide: EvaluationResultService, useValue: result }, + { provide: CeoEvaluationService, useValue: ceo }, + ], + }) + .overrideGuard(JwtAuthGuard) + .useValue({ canActivate: (ctx: any) => ((ctx.switchToHttp().getRequest().user = { sub: 'comp-1', role: 'COMPANY' }), true) }) + .overrideGuard(RolesGuard) + .useValue({ canActivate: () => true }) + .compile(); + + app = moduleRef.createNestApplication(); + app.setGlobalPrefix('api/v1'); + await app.listen(0); + baseUrl = `${await app.getUrl()}/api/v1`.replace('[::1]', 'localhost'); + }); + + afterAll(async () => { + await app.close(); + }); + + beforeEach(() => { + jest.clearAllMocks(); + for (const fn of [...Object.values(result), ...Object.values(self), ...Object.values(ceo)]) { + fn.mockResolvedValue({ ok: true }); + } + }); + + const request = (method: string, path: string, body?: unknown) => + fetch(`${baseUrl}${path}`, { + method, + headers: { 'Content-Type': 'application/json' }, + body: body ? JSON.stringify(body) : undefined, + }); + + it('GET /evaluations/result/:token → 직원 결과 조회', async () => { + const res = await request('GET', `/evaluations/result/${TOKEN}`); + expect(res.status).toBe(200); + expect(result.getEmployeeResult).toHaveBeenCalledWith(TOKEN); + expect(result.getCompanyResult).not.toHaveBeenCalled(); + }); + + it('GET /evaluations/:evaluationId/result → 대표 결과 조회', async () => { + const res = await request('GET', `/evaluations/${EVALUATION_ID}/result`); + expect(res.status).toBe(200); + expect(result.getCompanyResult).toHaveBeenCalledWith({ sub: 'comp-1', role: 'COMPANY' }, EVALUATION_ID); + expect(result.getEmployeeResult).not.toHaveBeenCalled(); + }); + + it('POST /evaluations/result/:token/opinion → 의견 제출', async () => { + const res = await request('POST', `/evaluations/result/${TOKEN}/opinion`, { content: '의견' }); + expect(res.status).toBe(201); + expect(result.submitOpinion).toHaveBeenCalledWith(TOKEN, expect.objectContaining({ content: '의견' }), expect.any(Object)); + }); + + it('토큰이 우연히 "result"여도 직원 라우트로 간다 (등록 순서 확인)', async () => { + await request('GET', '/evaluations/result/result'); + expect(result.getEmployeeResult).toHaveBeenCalledWith('result'); + expect(result.getCompanyResult).not.toHaveBeenCalled(); + }); + + it('기존 자기평가·대표 검증 라우트도 그대로 매칭된다', async () => { + await request('GET', `/evaluations/self/${TOKEN}`); + expect(self.getForm).toHaveBeenCalledWith(TOKEN); + + await request('GET', `/evaluations/${EVALUATION_ID}/ceo`); + expect(ceo.getForm).toHaveBeenCalledWith({ sub: 'comp-1', role: 'COMPANY' }, EVALUATION_ID); + + expect(result.getEmployeeResult).not.toHaveBeenCalled(); + expect(result.getCompanyResult).not.toHaveBeenCalled(); + }); +}); diff --git a/src/evaluations/result-link.controller.ts b/src/evaluations/result-link.controller.ts new file mode 100644 index 0000000..525007b --- /dev/null +++ b/src/evaluations/result-link.controller.ts @@ -0,0 +1,47 @@ +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 { SubmitOpinionDto } from './dto/submit-opinion.dto'; +import { EvaluationResultService } from './evaluation-result.service'; + +/** + * 직원용 평가 결과·의견 API. 메일로 받은 결과 링크 토큰으로만 인증한다. + * 'evaluations/result/:token'이 대표용 'evaluations/:evaluationId/result'와 섞이지 않도록 별도 컨트롤러로 두고 먼저 등록한다. + */ +@ApiTags('Evaluations') +@Controller('evaluations/result') +export class ResultLinkController { + constructor(private readonly evaluationResultService: EvaluationResultService) {} + + @Get(':token') + @ApiOperation({ summary: '직원: 평가 비교 결과 조회 (결과 링크 토큰, 링크 소비 안 함, 최초 조회 시각 기록)' }) + @ApiParam({ name: 'token', description: '메일로 받은 평가 결과 링크 토큰' }) + @ApiResponse({ status: 200, description: '조회 성공 (자기점수·대표점수·점수 차이·역량·의견 제출 가능 여부)' }) + @ApiResponse({ status: 403, description: 'INVALID_LINK_PURPOSE (결과 확인용 토큰 아님)' }) + @ApiResponse({ status: 409, description: 'EVALUATION_NOT_COMPLETED (대표 검증 미완료)' }) + @ApiResponse({ status: 410, description: 'LINK_EXPIRED (링크 만료 또는 폐기)' }) + @ResponseMessage('직원 평가 비교 결과 조회 성공') + getResult(@Param('token') token: string) { + return this.evaluationResultService.getEmployeeResult(token); + } + + @Post(':token/opinion') + @HttpCode(HttpStatus.CREATED) + @ApiOperation({ summary: '직원: 평가 결과 의견 제출 (1회, 완료 + 7일 이내, 점수는 변경되지 않음)' }) + @ApiParam({ name: 'token', description: '메일로 받은 평가 결과 링크 토큰' }) + @ApiResponse({ status: 201, description: '제출 성공 { evaluationId, opinionId, submittedAt }' }) + @ApiResponse({ status: 400, description: '형식 오류 (content 누락·문자열 아님)' }) + @ApiResponse({ status: 403, description: 'INVALID_LINK_PURPOSE' }) + @ApiResponse({ status: 409, description: 'OPINION_ALREADY_SUBMITTED / EVALUATION_NOT_COMPLETED' }) + @ApiResponse({ status: 410, description: 'OPINION_PERIOD_EXPIRED (의견 기한 만료) / LINK_EXPIRED' }) + @ApiResponse({ status: 422, description: 'INVALID_OPINION (빈 내용 또는 1000자 초과)' }) + @ResponseMessage('직원 평가 결과 의견 제출 성공') + submitOpinion( + @Param('token') token: string, + @Body() dto: SubmitOpinionDto, + @Ip() ip: string, + @Headers('user-agent') userAgent?: string, + ) { + return this.evaluationResultService.submitOpinion(token, dto, { ip, userAgent }); + } +}