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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { NotificationModule } from './notification/notification.module';
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';

@Module({
imports: [
Expand All @@ -29,6 +30,7 @@ import { EmployeeModule } from './employee/employee.module';
AuditModule,
QuestionTemplateModule,
EmployeeModule,
DeclarationModule,
],
})
export class AppModule {}
95 changes: 95 additions & 0 deletions src/declaration/answer.validator.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { BadRequestException, UnprocessableEntityException } from '@nestjs/common';
import { DeclarationQuestionSnapshot } from '@prisma/client';
import { validateAnswers } from './answer.validator';
import { AnswerDto } from './dto/submit-declaration.dto';

const snapshot = (over: Partial<DeclarationQuestionSnapshot>): DeclarationQuestionSnapshot => ({
id: 'q',
declarationId: 'decl-1',
order: 1,
type: 'SCORE',
text: '질문',
required: true,
scoreMin: null,
scoreMax: null,
options: null,
maxLength: null,
evaluationEnabled: true,
...over,
});

const SCORE = snapshot({ id: 'q-score', order: 1, type: 'SCORE', scoreMin: 1, scoreMax: 10 });
const CHOICE = snapshot({
id: 'q-choice',
order: 2,
type: 'SINGLE_CHOICE',
options: [
{ optionId: 'opt-a', label: '개인 집중' },
{ optionId: 'opt-b', label: '팀 협업' },
],
});
const TEXT = snapshot({ id: 'q-text', order: 3, type: 'TEXT', maxLength: 10 });
const OPTIONAL_TEXT = snapshot({ id: 'q-opt', order: 4, type: 'TEXT', maxLength: 10, required: false });
const ALL = [SCORE, CHOICE, TEXT, OPTIONAL_TEXT];

const valid: AnswerDto[] = [
{ questionId: 'q-score', answerScore: 8 },
{ questionId: 'q-choice', answerOptionId: 'opt-b' },
{ questionId: 'q-text', answerText: ' 성과입니다 ' },
];

function expectError(answers: AnswerDto[], type: any, code: string, questionId?: string) {
try {
validateAnswers(ALL, answers);
throw new Error('예외가 발생해야 합니다.');
} catch (error) {
expect(error).toBeInstanceOf(type);
const body = (error as any).getResponse();
expect(body.code).toBe(code);
if (questionId) {
expect(body.details.errors.map((e: any) => e.questionId)).toContain(questionId);
}
}
}

describe('validateAnswers', () => {
it('유형별로 맞는 답변을 저장 형태로 정리하고, 선택 질문 미응답은 저장하지 않는다', () => {
expect(validateAnswers(ALL, valid)).toEqual([
{ snapshotQuestionId: 'q-score', answerScore: 8, answerOptionId: null, answerText: null },
{ snapshotQuestionId: 'q-choice', answerScore: null, answerOptionId: 'opt-b', answerText: null },
{ snapshotQuestionId: 'q-text', answerScore: null, answerOptionId: null, answerText: '성과입니다' },
]);
});

describe('400 INVALID_ANSWER_TYPE (유형과 답변 필드 불일치)', () => {
it('SCORE 질문에 answerText', () =>
expectError([{ questionId: 'q-score', answerText: '8점' }, ...valid.slice(1)], BadRequestException, 'INVALID_ANSWER_TYPE', 'q-score'));
it('SINGLE_CHOICE 질문에 answerScore', () =>
expectError([valid[0], { questionId: 'q-choice', answerScore: 1 }, valid[2]], BadRequestException, 'INVALID_ANSWER_TYPE', 'q-choice'));
it('TEXT 질문에 answerOptionId', () =>
expectError([valid[0], valid[1], { questionId: 'q-text', answerOptionId: 'opt-a' }], BadRequestException, 'INVALID_ANSWER_TYPE', 'q-text'));
it('유형 불일치는 다른 422 위반보다 먼저 판정한다', () =>
expectError([{ questionId: 'q-score', answerText: 'x' }, { questionId: 'q-choice', answerOptionId: 'nope' }], BadRequestException, 'INVALID_ANSWER_TYPE'));
});

describe('422 ANSWER_VALIDATION_FAILED', () => {
it('필수 질문 누락', () =>
expectError([valid[0], valid[1]], UnprocessableEntityException, 'ANSWER_VALIDATION_FAILED', 'q-text'));
it('필수 TEXT에 공백만 입력하면 누락으로 본다', () =>
expectError([valid[0], valid[1], { questionId: 'q-text', answerText: ' ' }], UnprocessableEntityException, 'ANSWER_VALIDATION_FAILED', 'q-text'));
it('점수 범위 밖 (0, 11)', () => {
expectError([{ questionId: 'q-score', answerScore: 0 }, valid[1], valid[2]], UnprocessableEntityException, 'ANSWER_VALIDATION_FAILED', 'q-score');
expectError([{ questionId: 'q-score', answerScore: 11 }, valid[1], valid[2]], UnprocessableEntityException, 'ANSWER_VALIDATION_FAILED', 'q-score');
});
it('정수가 아닌 점수', () =>
expectError([{ questionId: 'q-score', answerScore: 7.5 }, valid[1], valid[2]], UnprocessableEntityException, 'ANSWER_VALIDATION_FAILED', 'q-score'));
it('없는 optionId', () =>
expectError([valid[0], { questionId: 'q-choice', answerOptionId: 'opt-x' }, valid[2]], UnprocessableEntityException, 'ANSWER_VALIDATION_FAILED', 'q-choice'));
it('maxLength 초과', () =>
expectError([valid[0], valid[1], { questionId: 'q-text', answerText: '가'.repeat(11) }], UnprocessableEntityException, 'ANSWER_VALIDATION_FAILED', 'q-text'));
it('질문지에 없는 questionId', () =>
expectError([...valid, { questionId: 'q-unknown', answerText: 'x' }], UnprocessableEntityException, 'ANSWER_VALIDATION_FAILED', 'q-unknown'));
it('같은 질문에 중복 답변', () =>
expectError([...valid, { questionId: 'q-score', answerScore: 5 }], UnprocessableEntityException, 'ANSWER_VALIDATION_FAILED', 'q-score'));
});
});
141 changes: 141 additions & 0 deletions src/declaration/answer.validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { BadRequestException, UnprocessableEntityException } from '@nestjs/common';
import { DeclarationQuestionSnapshot, QuestionType } from '@prisma/client';
import { SnapshotOption } from './declaration.constants';
import { AnswerDto } from './dto/submit-declaration.dto';

/** 저장할 답변 (DeclarationResponse) */
export interface NormalizedAnswer {
snapshotQuestionId: string;
answerScore: number | null;
answerOptionId: string | null;
answerText: string | null;
}

interface AnswerError {
questionId: string;
message: string;
}

type AnswerField = 'answerScore' | 'answerOptionId' | 'answerText';

const FIELD_BY_TYPE: Record<QuestionType, AnswerField> = {
SCORE: 'answerScore',
SINGLE_CHOICE: 'answerOptionId',
TEXT: 'answerText',
};

const ANSWER_FIELDS: AnswerField[] = ['answerScore', 'answerOptionId', 'answerText'];

/**
* 발송 시점의 질문 스냅샷을 기준으로 답변을 검증한다.
* - 유형과 다른 답변 필드 → 400 INVALID_ANSWER_TYPE (가장 먼저 판정)
* - 없는 질문·중복 답변·필수 누락·점수 범위·없는 선택지·글자 수 초과 → 422 ANSWER_VALIDATION_FAILED
* 위반은 모두 모아 details.errors로 돌려준다.
*/
export function validateAnswers(
snapshots: DeclarationQuestionSnapshot[],
answers: AnswerDto[],
): NormalizedAnswer[] {
const snapshotById = new Map(snapshots.map((s) => [s.id, s]));
const typeErrors: AnswerError[] = [];
const errors: AnswerError[] = [];
const answered = new Map<string, NormalizedAnswer>();

for (const answer of answers) {
const snapshot = snapshotById.get(answer.questionId);
if (!snapshot) {
errors.push({ questionId: answer.questionId, message: '질문지에 없는 질문입니다.' });
continue;
}
if (answered.has(snapshot.id)) {
errors.push({ questionId: snapshot.id, message: '같은 질문에 답변이 중복됩니다.' });
continue;
}

const expected = FIELD_BY_TYPE[snapshot.type];
const provided = ANSWER_FIELDS.filter((field) => answer[field] != null);
const wrong = provided.filter((field) => field !== expected);
if (wrong.length > 0) {
typeErrors.push({
questionId: snapshot.id,
message: `${snapshot.type} 질문에는 ${expected}만 보낼 수 있습니다. (받은 필드: ${wrong.join(', ')})`,
});
continue;
}

const normalized = normalizeAnswer(snapshot, answer, errors);
if (normalized) {
answered.set(snapshot.id, normalized);
}
}

for (const snapshot of snapshots) {
if (snapshot.required && !answered.has(snapshot.id) && !hasErrorFor(snapshot.id, errors, typeErrors)) {
errors.push({ questionId: snapshot.id, message: '필수 질문에 답변하지 않았습니다.' });
}
}

if (typeErrors.length > 0) {
throw new BadRequestException({
code: 'INVALID_ANSWER_TYPE',
message: '질문 유형과 답변 필드가 맞지 않습니다.',
details: { errors: typeErrors },
});
}
if (errors.length > 0) {
throw new UnprocessableEntityException({
code: 'ANSWER_VALIDATION_FAILED',
message: '답변이 질문 조건을 만족하지 않습니다.',
details: { errors },
});
}

return [...answered.values()];
}

/** 유효하면 저장 형태로 정리해 반환, 답변이 비어 있으면 null(미응답), 위반이면 errors에 추가하고 null */
function normalizeAnswer(
snapshot: DeclarationQuestionSnapshot,
answer: AnswerDto,
errors: AnswerError[],
): NormalizedAnswer | null {
const empty = { snapshotQuestionId: snapshot.id, answerScore: null, answerOptionId: null, answerText: null };
const fail = (message: string) => {
errors.push({ questionId: snapshot.id, message });
return null;
};

switch (snapshot.type) {
case QuestionType.SCORE: {
const score = answer.answerScore;
if (score == null) return null;
const min = snapshot.scoreMin ?? 1;
const max = snapshot.scoreMax ?? 10;
if (!Number.isInteger(score) || score < min || score > max) {
return fail(`점수는 ${min}~${max} 사이의 정수여야 합니다.`);
}
return { ...empty, answerScore: score };
}
case QuestionType.SINGLE_CHOICE: {
const optionId = answer.answerOptionId;
if (optionId == null || optionId === '') return null;
const options = (snapshot.options as SnapshotOption[] | null) ?? [];
if (!options.some((option) => option.optionId === optionId)) {
return fail('존재하지 않는 선택지입니다.');
}
return { ...empty, answerOptionId: optionId };
}
case QuestionType.TEXT: {
const text = answer.answerText?.trim();
if (!text) return null;
if (snapshot.maxLength != null && text.length > snapshot.maxLength) {
return fail(`답변은 ${snapshot.maxLength}자 이내여야 합니다.`);
}
return { ...empty, answerText: text };
}
}
}

function hasErrorFor(questionId: string, ...lists: AnswerError[][]): boolean {
return lists.some((list) => list.some((e) => e.questionId === questionId));
}
44 changes: 44 additions & 0 deletions src/declaration/declaration-form.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
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 { DeclarationService } from './declaration.service';
import { SubmitDeclarationDto } from './dto/submit-declaration.dto';

/** 직원용 자기선언 API. 계정 없이 메일로 받은 1회성 링크 토큰으로만 인증한다. */
@ApiTags('Declaration')
@Controller('declarations/forms')
export class DeclarationFormController {
constructor(private readonly declarationService: DeclarationService) {}

@Get(':token')
@ApiOperation({ summary: '직원: 자기선언 질문지 조회 (링크 토큰, 조회만으로는 링크 소비 안 함)' })
@ApiParam({ name: 'token', description: '메일로 받은 자기선언 링크 토큰' })
@ApiResponse({ status: 200, description: '조회 성공 (질문 스냅샷, 필수 동의 항목, 동의서 버전)' })
@ApiResponse({ status: 403, description: 'INVALID_LINK_PURPOSE (자기선언용 토큰 아님)' })
@ApiResponse({ status: 409, description: 'ALREADY_SUBMITTED (이미 제출 완료)' })
@ApiResponse({ status: 410, description: 'LINK_EXPIRED (링크 만료 또는 폐기)' })
@ResponseMessage('직원 자기선언 질문지 조회 성공')
getForm(@Param('token') token: string) {
return this.declarationService.getForm(token);
}

@Post(':token/submit')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: '직원: 자기선언 답변·필수 동의 제출 (성공 시 링크 소비, 이후 수정 불가)' })
@ApiParam({ name: 'token', description: '메일로 받은 자기선언 링크 토큰' })
@ApiResponse({ status: 201, description: '제출 성공 { declarationId, status, submittedAt, linkConsumed }' })
@ApiResponse({ status: 400, description: 'INVALID_ANSWER_TYPE (질문 유형과 답변 필드 불일치) 또는 형식 오류' })
@ApiResponse({ status: 403, description: 'CONSENT_NOT_GIVEN (필수 동의 누락) / INVALID_LINK_PURPOSE' })
@ApiResponse({ status: 409, description: 'ALREADY_SUBMITTED (이미 제출 완료)' })
@ApiResponse({ status: 410, description: 'LINK_EXPIRED (링크 만료 또는 폐기)' })
@ApiResponse({ status: 422, description: 'ANSWER_VALIDATION_FAILED (필수 누락·점수 범위·선택지·글자 수 위반)' })
@ResponseMessage('직원 자기선언 답변 제출 성공')
submit(
@Param('token') token: string,
@Body() dto: SubmitDeclarationDto,
@Ip() ip: string,
@Headers('user-agent') userAgent?: string,
) {
return this.declarationService.submit(token, dto, { ip, userAgent });
}
}
14 changes: 14 additions & 0 deletions src/declaration/declaration.constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/** 자기선언 링크 유효 기간: 발송일 기준 KST 7일 뒤 23:59:59 */
export const DECLARATION_LINK_VALID_DAYS = 7;

// TODO(법무): 동의서 문안 확정 시 버전 갱신. 직원이 제출한 consentVersion이 이 값과 같아야 한다.
export const CURRENT_CONSENT_VERSION = '2026-10-01';

/** 자기선언 제출 시 모두 동의해야 하는 항목 */
export const REQUIRED_CONSENTS = ['EVALUATION', 'DATA_ACCESS', 'EVIDENCE_RETENTION'] as const;

/** 스냅샷에 저장되는 단일 선택형 선택지 형식 (Prisma Json에 넣을 수 있도록 type으로 선언) */
export type SnapshotOption = {
optionId: string;
label: string;
};
55 changes: 55 additions & 0 deletions src/declaration/declaration.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Body, Controller, Get, HttpCode, HttpStatus, 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 { DeclarationService } from './declaration.service';
import { AssignDeclarationDto } from './dto/assign-declaration.dto';

/** 대표용 자기선언 API (CEO JWT) */
@ApiTags('Declaration')
@ApiBearerAuth('access-token')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('COMPANY')
@Controller()
export class DeclarationController {
constructor(private readonly declarationService: DeclarationService) {}

@Post('employees/:employeeId/declarations')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: '대표: 직원에게 자기선언 질문지 할당·발송 (템플릿 스냅샷 저장 + 1회성 링크 메일)' })
@ApiParam({ name: 'employeeId', description: '직원 ID' })
@ApiResponse({
status: 201,
description: '발송 성공 { declarationId, templateId, templateVersion, questionCount, status, linkExpiresAt, linkSent }',
})
@ApiResponse({ status: 400, description: '필수값 누락 또는 형식 오류' })
@ApiResponse({ status: 401, description: '인증 필요' })
@ApiResponse({ status: 403, description: 'FORBIDDEN (대표 권한 또는 직원·템플릿 소속 불일치)' })
@ApiResponse({ status: 404, description: 'EMPLOYEE_OR_TEMPLATE_NOT_FOUND' })
@ApiResponse({ status: 409, description: 'ACTIVE_DECLARATION_EXISTS (제출 전 질문지 존재)' })
@ApiResponse({ status: 422, description: 'TEMPLATE_NOT_ACTIVE (보관된 템플릿)' })
@ResponseMessage('직원 자기선언 질문지 할당·발송 성공')
assign(
@CurrentUser() user: JwtPayload,
@Param('employeeId') employeeId: string,
@Body() dto: AssignDeclarationDto,
) {
return this.declarationService.assign(user, employeeId, dto);
}

@Get('declarations/:employeeId')
@ApiOperation({ summary: '대표: 직원의 제출된 자기선언 조회 (질문·답변·동의 이력, 최신순)' })
@ApiParam({ name: 'employeeId', description: '직원 ID' })
@ApiResponse({ status: 200, description: '조회 성공 { employeeId, declarations[] }' })
@ApiResponse({ status: 401, description: '인증 필요' })
@ApiResponse({ status: 403, description: 'FORBIDDEN (대표 권한 또는 직원 소속 불일치)' })
@ApiResponse({ status: 404, description: 'DECLARATION_NOT_FOUND (제출된 자기선언 없음) / EMPLOYEE_NOT_FOUND' })
@ResponseMessage('직원 자기선언 조회 성공')
getEmployeeDeclarations(@CurrentUser() user: JwtPayload, @Param('employeeId') employeeId: string) {
return this.declarationService.getEmployeeDeclarations(user, employeeId);
}
}
17 changes: 17 additions & 0 deletions src/declaration/declaration.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
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 { DeclarationFormController } from './declaration-form.controller';
import { DeclarationController } from './declaration.controller';
import { DeclarationService } from './declaration.service';

@Module({
// JwtAuthGuard가 AuthModule의 RedisService(토큰 블랙리스트)를 사용
imports: [AuthModule, AccessLinkModule, NotificationModule, AuditModule],
// 직원용 라우트(declarations/forms/:token)를 대표용(declarations/:employeeId)보다 먼저 등록
controllers: [DeclarationFormController, DeclarationController],
providers: [DeclarationService],
})
export class DeclarationModule {}
Loading
Loading