diff --git a/src/app.module.ts b/src/app.module.ts index 62de0a8..99b01b8 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -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: [ @@ -29,6 +30,7 @@ import { EmployeeModule } from './employee/employee.module'; AuditModule, QuestionTemplateModule, EmployeeModule, + DeclarationModule, ], }) export class AppModule {} diff --git a/src/declaration/answer.validator.spec.ts b/src/declaration/answer.validator.spec.ts new file mode 100644 index 0000000..3667216 --- /dev/null +++ b/src/declaration/answer.validator.spec.ts @@ -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 => ({ + 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')); + }); +}); diff --git a/src/declaration/answer.validator.ts b/src/declaration/answer.validator.ts new file mode 100644 index 0000000..7135a1f --- /dev/null +++ b/src/declaration/answer.validator.ts @@ -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 = { + 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(); + + 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)); +} diff --git a/src/declaration/declaration-form.controller.ts b/src/declaration/declaration-form.controller.ts new file mode 100644 index 0000000..fe231c3 --- /dev/null +++ b/src/declaration/declaration-form.controller.ts @@ -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 }); + } +} diff --git a/src/declaration/declaration.constants.ts b/src/declaration/declaration.constants.ts new file mode 100644 index 0000000..5d0f9fb --- /dev/null +++ b/src/declaration/declaration.constants.ts @@ -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; +}; diff --git a/src/declaration/declaration.controller.ts b/src/declaration/declaration.controller.ts new file mode 100644 index 0000000..334a6ad --- /dev/null +++ b/src/declaration/declaration.controller.ts @@ -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); + } +} diff --git a/src/declaration/declaration.module.ts b/src/declaration/declaration.module.ts new file mode 100644 index 0000000..47e2676 --- /dev/null +++ b/src/declaration/declaration.module.ts @@ -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 {} diff --git a/src/declaration/declaration.service.spec.ts b/src/declaration/declaration.service.spec.ts new file mode 100644 index 0000000..7ecfd6b --- /dev/null +++ b/src/declaration/declaration.service.spec.ts @@ -0,0 +1,497 @@ +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 { CURRENT_CONSENT_VERSION } from './declaration.constants'; +import { DeclarationService } from './declaration.service'; + +// --------------------------------------------------------------------------- +// 테스트용 인메모리 DB: 이 서비스가 쓰는 Prisma 호출 형태만 흉내 낸다 (prisma·tx 공용) +// --------------------------------------------------------------------------- +type Row = Record; + +function matches(row: Row, where: Row): boolean { + return Object.entries(where).every(([key, value]) => { + if (value && typeof value === 'object' && !(value instanceof Date) && 'not' in value) { + return row[key] !== value.not; + } + return row[key] === value; + }); +} + +function pick(row: Row | undefined, select?: Row) { + if (!row) return null; + if (!select) return { ...row }; + return Object.fromEntries(Object.keys(select).map((key) => [key, row[key]])); +} + +function createFakeDb() { + let seq = 0; + const newId = (prefix: string) => `${prefix}-${++seq}`; + const db = { + companies: [] as Row[], + employees: [] as Row[], + templates: [] as Row[], + templateQuestions: [] as Row[], + declarations: [] as Row[], + snapshots: [] as Row[], + responses: [] as Row[], + accessLinks: [] as Row[], + auditLogs: [] as Row[], + }; + const byOrder = (a: Row, b: Row) => a.order - b.order; + const snapshotsOf = (declarationId: string) => + db.snapshots.filter((s) => s.declarationId === declarationId).sort(byOrder).map((s) => ({ ...s })); + const updateMany = (rows: Row[]) => async ({ where, data }: any) => { + const targets = rows.filter((r) => matches(r, where)); + targets.forEach((r) => Object.assign(r, data)); + return { count: targets.length }; + }; + + const client: any = { + hrManager: { findUnique: async () => null }, + company: { + findUnique: async ({ where, select }: any) => pick(db.companies.find((c) => c.id === where.id), select), + }, + employee: { + findUnique: async ({ where, select }: any) => pick(db.employees.find((e) => e.id === where.id), select), + updateMany: updateMany(db.employees), + update: async ({ where, data }: any) => Object.assign(db.employees.find((e) => e.id === where.id)!, data), + }, + questionTemplate: { + findUnique: async ({ where }: any) => { + const template = db.templates.find((t) => t.id === where.id); + if (!template) return null; + const questions = db.templateQuestions + .filter((q) => q.templateId === template.id) + .sort(byOrder) + .map((q) => ({ ...q })); + return { ...template, questions }; + }, + }, + declaration: { + findFirst: async ({ where }: any) => db.declarations.find((d) => matches(d, where)) ?? null, + create: async ({ data }: any) => { + const { questions, ...rest } = data; + const declaration = { + id: newId('decl'), + submittedAt: null, + consentEvaluation: false, + consentDataAccess: false, + consentEvidenceRetention: false, + consentVersion: null, + consentAgreedAt: null, + consentIp: null, + consentUserAgent: null, + ...rest, + }; + db.declarations.push(declaration); + for (const q of questions.create) { + db.snapshots.push({ + id: newId('snap'), + declarationId: declaration.id, + scoreMin: null, + scoreMax: null, + options: null, + maxLength: null, + ...structuredClone(q), + }); + } + return { ...declaration }; + }, + findUnique: async ({ where, include }: any) => { + const declaration = db.declarations.find((d) => d.id === where.id); + if (!declaration) return null; + return { + ...declaration, + ...(include?.questions && { questions: snapshotsOf(declaration.id) }), + ...(include?.employee && { employee: { ...db.employees.find((e) => e.id === declaration.employeeId) } }), + }; + }, + updateMany: updateMany(db.declarations), + findMany: async ({ where }: any) => + db.declarations + .filter((d) => matches(d, where)) + .sort((a, b) => b.submittedAt - a.submittedAt) + .map((d) => ({ + ...d, + questions: snapshotsOf(d.id).map((s) => ({ + ...s, + response: db.responses.find((r) => r.snapshotQuestionId === s.id) ?? null, + })), + })), + }, + declarationResponse: { + createMany: async ({ data }: any) => { + for (const r of data) { + if (db.responses.some((x) => x.snapshotQuestionId === r.snapshotQuestionId)) { + throw new Error('unique constraint (snapshotQuestionId)'); + } + db.responses.push({ id: newId('resp'), ...r }); + } + return { count: data.length }; + }, + }, + accessLink: { + create: async ({ data }: any) => { + const link = { id: newId('link'), usedAt: null, revokedAt: null, createdAt: new Date(), ...data }; + db.accessLinks.push(link); + return { ...link }; + }, + findUnique: async ({ where }: any) => { + const link = db.accessLinks.find((l) => l.tokenHash === where.tokenHash); + return link ? { ...link } : null; + }, + updateMany: updateMany(db.accessLinks), + }, + auditLog: { + create: async ({ data }: any) => { + db.auditLogs.push(data); + return data; + }, + }, + }; + client.$transaction = async (fn: (tx: any) => unknown) => fn(client); + + return { db, client }; +} + +// --------------------------------------------------------------------------- + +const CEO = { sub: 'comp-1', role: 'COMPANY' as const }; +const OTHER_CEO = { sub: 'comp-2', role: 'COMPANY' as const }; +const META = { ip: '203.0.113.7', userAgent: 'jest-browser' }; + +function seed(db: ReturnType['db']) { + db.companies.push({ id: 'comp-1', companyName: '테크플러스 주식회사' }, { id: 'comp-2', companyName: '다른기업' }); + db.employees.push( + { id: 'emp-1', companyId: 'comp-1', name: '김민준', email: 'minjun@example.com', position: '과장', declarationStatus: 'NOT_SENT' }, + { id: 'emp-other', companyId: 'comp-2', name: '타사직원', email: 'x@other.com', position: null, declarationStatus: 'NOT_SENT' }, + ); + db.templates.push( + { id: 'tpl-1', companyId: 'comp-1', name: '개발직군 입사 자기선언', version: 2, status: 'ACTIVE' }, + { id: 'tpl-archived', companyId: 'comp-1', name: '보관됨', version: 1, status: 'ARCHIVED' }, + { id: 'tpl-other', companyId: 'comp-2', name: '타사 템플릿', version: 1, status: 'ACTIVE' }, + ); + db.templateQuestions.push( + { id: 'tq-1', templateId: 'tpl-1', order: 1, type: 'SCORE', text: '업무 책임감을 평가해 주세요.', required: true, scoreMin: 1, scoreMax: 10, options: null, maxLength: null, evaluationEnabled: true }, + { id: 'tq-2', templateId: 'tpl-1', order: 2, type: 'SINGLE_CHOICE', text: '선호 업무 방식은 무엇인가요?', required: true, scoreMin: null, scoreMax: null, options: ['개인 집중', '팀 협업'], maxLength: null, evaluationEnabled: false }, + { id: 'tq-3', templateId: 'tpl-1', order: 3, type: 'TEXT', text: '주요 성과를 작성해 주세요.', required: true, scoreMin: null, scoreMax: null, options: null, maxLength: 500, evaluationEnabled: true }, + ); +} + +const AGREED = { + evaluationAgreed: true, + dataAccessAgreed: true, + evidenceRetentionAgreed: true, + consentVersion: CURRENT_CONSENT_VERSION, +}; + +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('DeclarationService', () => { + let fake: ReturnType; + let accessLinkService: AccessLinkService; + let mailMock: { sendDeclarationLink: jest.Mock }; + let service: DeclarationService; + + beforeEach(() => { + fake = createFakeDb(); + seed(fake.db); + const prisma = fake.client as unknown as PrismaService; + accessLinkService = new AccessLinkService(prisma); + mailMock = { sendDeclarationLink: jest.fn().mockResolvedValue(true) }; + service = new DeclarationService( + prisma, + accessLinkService, + mailMock as unknown as MailService, + new AuditService(prisma), + ); + }); + + /** 발송 후 메일로 나간 토큰을 돌려준다 */ + async function assignAndGetToken() { + const result = await service.assign(CEO, 'emp-1', { templateId: 'tpl-1', sendChannel: 'EMAIL' }); + const token: string = mailMock.sendDeclarationLink.mock.calls.at(-1)[0].token; + return { result, token }; + } + + /** 질문지 조회 결과로 유효한 답변을 만든다 */ + function validAnswers(form: Awaited>) { + const [score, choice, text] = form.questions as any[]; + return [ + { questionId: score.questionId, answerScore: 8 }, + { questionId: choice.questionId, answerOptionId: choice.options[1].optionId }, + { questionId: text.questionId, answerText: 'React 성능 개선을 진행했습니다.' }, + ]; + } + + describe('발송 → 질문지 조회 → 제출 → 대표 조회 (전체 흐름)', () => { + it('끝까지 정상 동작한다', async () => { + // 메일은 트랜잭션 커밋 후에 나가야 한다: 메일 호출 시점에 데이터가 이미 저장돼 있는지 확인 + mailMock.sendDeclarationLink.mockImplementation(async () => { + expect(fake.db.declarations).toHaveLength(1); + expect(fake.db.accessLinks).toHaveLength(1); + return true; + }); + + // 1) 발송 + const { result, token } = await assignAndGetToken(); + expect(result).toMatchObject({ + templateId: 'tpl-1', + templateVersion: 2, + questionCount: 3, + status: 'SENT', + linkSent: true, + }); + expect(result.linkExpiresAt.toISOString()).toMatch(/T14:59:59\.000Z$/); // KST 23:59:59 + expect(fake.db.employees[0].declarationStatus).toBe('SENT'); + expect(mailMock.sendDeclarationLink).toHaveBeenCalledWith( + expect.objectContaining({ to: 'minjun@example.com', employeeName: '김민준', companyName: '테크플러스 주식회사' }), + ); + // 링크에는 원문 토큰이 아니라 해시만 저장 + expect(fake.db.accessLinks[0]).toMatchObject({ purpose: 'DECLARATION', targetId: result.declarationId }); + expect(fake.db.accessLinks[0].tokenHash).not.toBe(token); + + // 2) 직원 질문지 조회 (링크 소비 안 함) + const form = await service.getForm(token); + expect(form).toMatchObject({ + declarationId: result.declarationId, + templateName: '개발직군 입사 자기선언', + templateVersion: 2, + employee: { name: '김민준', companyName: '테크플러스 주식회사', position: '과장' }, + status: 'SENT', + requiredConsents: ['EVALUATION', 'DATA_ACCESS', 'EVIDENCE_RETENTION'], + consentVersion: CURRENT_CONSENT_VERSION, + }); + const choice = form.questions[1] as any; + expect(choice.options).toEqual([ + { optionId: expect.stringMatching(/^[0-9a-f-]{36}$/), label: '개인 집중' }, + { optionId: expect.stringMatching(/^[0-9a-f-]{36}$/), label: '팀 협업' }, + ]); + expect(fake.db.accessLinks[0].usedAt).toBeNull(); + + // 3) 제출 + const submitted = await service.submit(token, { answers: validAnswers(form), consents: AGREED }, META); + expect(submitted).toMatchObject({ declarationId: result.declarationId, status: 'SUBMITTED', linkConsumed: true }); + + const declaration = fake.db.declarations[0]; + expect(declaration).toMatchObject({ + status: 'SUBMITTED', + consentEvaluation: true, + consentDataAccess: true, + consentEvidenceRetention: true, + consentVersion: CURRENT_CONSENT_VERSION, + consentIp: META.ip, + consentUserAgent: META.userAgent, + }); + expect(declaration.consentAgreedAt).toBeInstanceOf(Date); + expect(fake.db.responses).toHaveLength(3); + expect(fake.db.employees[0].declarationStatus).toBe('SUBMITTED'); + expect(fake.db.accessLinks[0].usedAt).toBeInstanceOf(Date); + expect(fake.db.auditLogs.map((log) => log.action)).toEqual(['DECLARATION_SENT', 'DECLARATION_SUBMITTED']); + + // 4) 대표 조회 + const view = await service.getEmployeeDeclarations(CEO, 'emp-1'); + expect(view.employeeId).toBe('emp-1'); + expect(view.declarations).toHaveLength(1); + expect(view.declarations[0].items).toEqual([ + expect.objectContaining({ type: 'SCORE', question: '업무 책임감을 평가해 주세요.', answerScore: 8, evaluationEnabled: true }), + expect.objectContaining({ type: 'SINGLE_CHOICE', answerOption: { optionId: choice.options[1].optionId, label: '팀 협업' } }), + expect.objectContaining({ type: 'TEXT', answerText: 'React 성능 개선을 진행했습니다.' }), + ]); + expect(view.declarations[0].consents).toMatchObject({ + evaluationAgreed: true, + dataAccessAgreed: true, + evidenceRetentionAgreed: true, + consentVersion: CURRENT_CONSENT_VERSION, + agreedAt: expect.any(Date), + }); + }); + + it('제출 후 재제출과 재조회는 409 ALREADY_SUBMITTED', async () => { + const { token } = await assignAndGetToken(); + const form = await service.getForm(token); + await service.submit(token, { answers: validAnswers(form), consents: AGREED }, META); + + await expectCode( + service.submit(token, { answers: validAnswers(form), consents: AGREED }, META), + ConflictException, + 'ALREADY_SUBMITTED', + ); + await expectCode(service.getForm(token), ConflictException, 'ALREADY_SUBMITTED'); + expect(fake.db.responses).toHaveLength(3); + }); + + it('만료된 링크는 조회·제출 모두 410 LINK_EXPIRED', async () => { + const { token } = await assignAndGetToken(); + const form = await service.getForm(token); + fake.db.accessLinks[0].expiresAt = new Date(Date.now() - 1000); + + await expectCode(service.getForm(token), GoneException, 'LINK_EXPIRED'); + await expectCode( + service.submit(token, { answers: validAnswers(form), consents: AGREED }, META), + GoneException, + 'LINK_EXPIRED', + ); + expect(fake.db.declarations[0].status).toBe('SENT'); + }); + + it('자기선언용이 아닌 토큰은 403 INVALID_LINK_PURPOSE', async () => { + const { result } = await assignAndGetToken(); + const otherToken = await accessLinkService.issue( + 'SELF_EVALUATION', + result.declarationId, + new Date(Date.now() + 60_000), + fake.client, + ); + + await expectCode(service.getForm(otherToken), ForbiddenException, 'INVALID_LINK_PURPOSE'); + }); + + it.each([ + ['evaluationAgreed', { ...AGREED, evaluationAgreed: false }], + ['dataAccessAgreed', { ...AGREED, dataAccessAgreed: false }], + ['evidenceRetentionAgreed', { ...AGREED, evidenceRetentionAgreed: false }], + ['consentVersion 불일치', { ...AGREED, consentVersion: '2025-01-01' }], + ])('동의 누락(%s)이면 403 CONSENT_NOT_GIVEN이고 아무것도 저장하지 않는다', async (_label, consents) => { + const { token } = await assignAndGetToken(); + const form = await service.getForm(token); + + await expectCode( + service.submit(token, { answers: validAnswers(form), consents }, META), + ForbiddenException, + 'CONSENT_NOT_GIVEN', + ); + expect(fake.db.declarations[0].status).toBe('SENT'); + expect(fake.db.responses).toHaveLength(0); + expect(fake.db.accessLinks[0].usedAt).toBeNull(); + }); + + it('답변 오류(400·422)면 저장하지 않고 링크도 그대로 쓸 수 있다', async () => { + const { token } = await assignAndGetToken(); + const form = await service.getForm(token); + const answers = validAnswers(form); + + await expectCode( + service.submit(token, { answers: [{ ...answers[0], answerScore: undefined, answerText: '8' }, ...answers.slice(1)], consents: AGREED }, META), + BadRequestException, + 'INVALID_ANSWER_TYPE', + ); + await expectCode( + service.submit(token, { answers: [{ ...answers[0], answerScore: 11 }, ...answers.slice(1)], consents: AGREED }, META), + UnprocessableEntityException, + 'ANSWER_VALIDATION_FAILED', + ); + expect(fake.db.responses).toHaveLength(0); + + await expect(service.submit(token, { answers, consents: AGREED }, META)).resolves.toMatchObject({ status: 'SUBMITTED' }); + }); + + it('발송 후 템플릿을 수정해도 발송된 질문지(스냅샷)는 그대로다', async () => { + const { token } = await assignAndGetToken(); + + // 템플릿 수정: 질문 문구 변경 + 질문 삭제 + 선택지 변경 + version 증가 + fake.db.templates[0].version = 3; + fake.db.templateQuestions[0].text = '바뀐 질문'; + fake.db.templateQuestions[1].options = ['완전히 다른 선택지', '또 다른 선택지']; + fake.db.templateQuestions.splice(2, 1); + + const form = await service.getForm(token); + expect(form.templateVersion).toBe(2); + expect(form.questions).toHaveLength(3); + expect(form.questions.map((q) => q.text)).toEqual([ + '업무 책임감을 평가해 주세요.', + '선호 업무 방식은 무엇인가요?', + '주요 성과를 작성해 주세요.', + ]); + expect((form.questions[1] as any).options.map((o: any) => o.label)).toEqual(['개인 집중', '팀 협업']); + + await expect(service.submit(token, { answers: validAnswers(form), consents: AGREED }, META)).resolves.toMatchObject({ + status: 'SUBMITTED', + }); + }); + + it('메일 발송이 실패해도 질문지·링크 데이터는 유지되고 linkSent=false로 알린다', async () => { + mailMock.sendDeclarationLink.mockResolvedValue(false); + + const { result, token } = await assignAndGetToken(); + + expect(result.linkSent).toBe(false); + expect(fake.db.declarations).toHaveLength(1); + expect(fake.db.snapshots).toHaveLength(3); + expect(fake.db.accessLinks).toHaveLength(1); + expect(fake.db.employees[0].declarationStatus).toBe('SENT'); + // 링크 자체는 유효하므로 재발송 기능이 생기기 전에도 토큰으로 조회 가능 + await expect(service.getForm(token)).resolves.toMatchObject({ status: 'SENT' }); + }); + }); + + describe('assign 오류', () => { + const dto = (templateId: string) => ({ templateId, sendChannel: 'EMAIL' as const }); + + it('직원 또는 템플릿이 없으면 404 EMPLOYEE_OR_TEMPLATE_NOT_FOUND', async () => { + await expectCode(service.assign(CEO, 'nope', dto('tpl-1')), NotFoundException, 'EMPLOYEE_OR_TEMPLATE_NOT_FOUND'); + await expectCode(service.assign(CEO, 'emp-1', dto('nope')), NotFoundException, 'EMPLOYEE_OR_TEMPLATE_NOT_FOUND'); + }); + + it('다른 기업의 직원·템플릿이면 403 FORBIDDEN', async () => { + await expectCode(service.assign(CEO, 'emp-other', dto('tpl-1')), ForbiddenException, 'FORBIDDEN'); + await expectCode(service.assign(CEO, 'emp-1', dto('tpl-other')), ForbiddenException, 'FORBIDDEN'); + await expectCode(service.assign(OTHER_CEO, 'emp-1', dto('tpl-1')), ForbiddenException, 'FORBIDDEN'); + }); + + it('보관된 템플릿이면 422 TEMPLATE_NOT_ACTIVE', async () => { + await expectCode(service.assign(CEO, 'emp-1', dto('tpl-archived')), UnprocessableEntityException, 'TEMPLATE_NOT_ACTIVE'); + }); + + it('제출 전 질문지가 있으면 409 ACTIVE_DECLARATION_EXISTS', async () => { + await service.assign(CEO, 'emp-1', dto('tpl-1')); + await expectCode(service.assign(CEO, 'emp-1', dto('tpl-1')), ConflictException, 'ACTIVE_DECLARATION_EXISTS'); + expect(fake.db.declarations).toHaveLength(1); + }); + + it('동시 발송으로 직원 상태가 먼저 SENT가 되면 409이고 질문지를 만들지 않는다', async () => { + fake.db.employees[0].declarationStatus = 'SENT'; + + await expectCode(service.assign(CEO, 'emp-1', dto('tpl-1')), ConflictException, 'ACTIVE_DECLARATION_EXISTS'); + expect(fake.db.declarations).toHaveLength(0); + expect(mailMock.sendDeclarationLink).not.toHaveBeenCalled(); + }); + }); + + describe('getEmployeeDeclarations 오류', () => { + it('제출된 자기선언이 없으면 404 DECLARATION_NOT_FOUND (발송만 된 상태 포함)', async () => { + await expectCode(service.getEmployeeDeclarations(CEO, 'emp-1'), NotFoundException, 'DECLARATION_NOT_FOUND'); + await service.assign(CEO, 'emp-1', { templateId: 'tpl-1', sendChannel: 'EMAIL' }); + await expectCode(service.getEmployeeDeclarations(CEO, 'emp-1'), NotFoundException, 'DECLARATION_NOT_FOUND'); + }); + + it('다른 기업 직원은 403, 없는 직원은 404 EMPLOYEE_NOT_FOUND', async () => { + await expectCode(service.getEmployeeDeclarations(CEO, 'emp-other'), ForbiddenException, 'FORBIDDEN'); + await expectCode(service.getEmployeeDeclarations(CEO, 'nope'), NotFoundException, 'EMPLOYEE_NOT_FOUND'); + }); + }); +}); diff --git a/src/declaration/declaration.service.ts b/src/declaration/declaration.service.ts new file mode 100644 index 0000000..40b83b3 --- /dev/null +++ b/src/declaration/declaration.service.ts @@ -0,0 +1,418 @@ +import { + ConflictException, + ForbiddenException, + GoneException, + Injectable, + NotFoundException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { DeclarationQuestionSnapshot, DeclarationResponse, Prisma } from '@prisma/client'; +import { randomUUID } from 'crypto'; +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 { validateAnswers } from './answer.validator'; +import { + CURRENT_CONSENT_VERSION, + DECLARATION_LINK_VALID_DAYS, + REQUIRED_CONSENTS, + SnapshotOption, +} from './declaration.constants'; +import { AssignDeclarationDto } from './dto/assign-declaration.dto'; +import { SubmitDeclarationDto } from './dto/submit-declaration.dto'; + +export interface RequestMeta { + ip?: string | null; + userAgent?: string | null; +} + +@Injectable() +export class DeclarationService { + constructor( + private readonly prisma: PrismaService, + private readonly accessLinkService: AccessLinkService, + private readonly mailService: MailService, + private readonly auditService: AuditService, + ) {} + + /** + * 대표가 직원에게 질문 템플릿을 할당하고 자기선언 링크를 발송한다. + * 발송 시점의 템플릿 질문을 DeclarationQuestionSnapshot으로 복사하므로 + * 이후 템플릿을 수정해도 이 질문지와 답변은 바뀌지 않는다. + */ + async assign(user: JwtPayload, employeeId: string, dto: AssignDeclarationDto) { + const companyId = await resolveCompanyId(user, this.prisma); + + const [employee, template] = await Promise.all([ + this.prisma.employee.findUnique({ where: { id: employeeId } }), + this.prisma.questionTemplate.findUnique({ + where: { id: dto.templateId }, + include: { questions: { orderBy: { order: 'asc' } } }, + }), + ]); + + if (!employee || !template) { + throw new NotFoundException({ + code: 'EMPLOYEE_OR_TEMPLATE_NOT_FOUND', + message: '직원 또는 질문 템플릿을 찾을 수 없습니다.', + }); + } + if (employee.companyId !== companyId || template.companyId !== companyId) { + throw forbidden(); + } + if (template.status !== 'ACTIVE') { + throw new UnprocessableEntityException({ + code: 'TEMPLATE_NOT_ACTIVE', + message: '사용할 수 없는 질문 템플릿입니다.', + }); + } + + const activeDeclaration = await this.prisma.declaration.findFirst({ + where: { employeeId, status: 'SENT' }, + select: { id: true }, + }); + if (activeDeclaration) { + throw activeDeclarationExists(); + } + + const now = new Date(); + const linkExpiresAt = endOfDayKstAfter(now, DECLARATION_LINK_VALID_DAYS); + + // 트랜잭션 안에서는 데이터와 링크 저장만 한다. 메일은 커밋 후. + const { declaration, token } = await this.prisma.$transaction(async (tx) => { + // 동시에 두 번 발송해도 하나만 통과하도록 조건부 갱신으로 선점 + const { count } = await tx.employee.updateMany({ + where: { id: employeeId, declarationStatus: { not: 'SENT' } }, + data: { declarationStatus: 'SENT' }, + }); + if (count === 0) { + throw activeDeclarationExists(); + } + + const created = await tx.declaration.create({ + data: { + companyId, + employeeId, + templateId: template.id, + templateName: template.name, + templateVersion: template.version, + status: 'SENT', + sentAt: now, + questions: { + create: template.questions.map((q) => ({ + order: q.order, + type: q.type, + text: q.text, + required: q.required, + scoreMin: q.scoreMin, + scoreMax: q.scoreMax, + options: toSnapshotOptions(q.options), + maxLength: q.maxLength, + evaluationEnabled: q.evaluationEnabled, + })), + }, + }, + }); + + const issuedToken = await this.accessLinkService.issue('DECLARATION', created.id, linkExpiresAt, tx); + + await this.auditService.log( + { + actorType: 'COMPANY', + actorId: user.sub, + action: 'DECLARATION_SENT', + targetType: 'Declaration', + targetId: created.id, + metadata: { employeeId, templateId: template.id, templateVersion: template.version }, + }, + tx, + ); + + return { declaration: created, token: issuedToken }; + }); + + // 커밋 후 발송. 실패해도 데이터는 유지되고 linkSent=false로 알린다. + const company = await this.prisma.company.findUnique({ + where: { id: companyId }, + select: { companyName: true }, + }); + const linkSent = await this.mailService.sendDeclarationLink({ + to: employee.email, + token, + employeeName: employee.name, + companyName: company?.companyName, + expiresAt: linkExpiresAt, + }); + + return { + declarationId: declaration.id, + templateId: template.id, + templateVersion: template.version, + questionCount: template.questions.length, + status: declaration.status, + linkExpiresAt, + linkSent, + }; + } + + /** 직원이 링크로 질문지를 조회한다. 조회만으로는 링크를 소비하지 않는다. */ + async getForm(token: string) { + const link = await this.accessLinkService.verify(token, 'DECLARATION'); + + const declaration = await this.prisma.declaration.findUnique({ + where: { id: link.targetId }, + include: { + questions: { orderBy: { order: 'asc' } }, + employee: { select: { name: true, position: true } }, + }, + }); + if (!declaration) { + throw linkExpired(); + } + if (declaration.status === 'SUBMITTED') { + throw alreadySubmitted(); + } + + const company = await this.prisma.company.findUnique({ + where: { id: declaration.companyId }, + select: { companyName: true }, + }); + + return { + declarationId: declaration.id, + templateName: declaration.templateName, + templateVersion: declaration.templateVersion, + employee: { + name: declaration.employee.name, + companyName: company?.companyName ?? null, + position: declaration.employee.position, + }, + status: declaration.status, + expiresAt: link.expiresAt, + questions: declaration.questions.map(toFormQuestion), + requiredConsents: [...REQUIRED_CONSENTS], + consentVersion: CURRENT_CONSENT_VERSION, + }; + } + + /** 직원이 답변과 필수 동의를 제출한다. 성공 시 링크를 소비하고 이후 수정할 수 없다. */ + async submit(token: string, dto: SubmitDeclarationDto, meta: RequestMeta) { + return this.prisma.$transaction(async (tx) => { + const link = await this.accessLinkService.verify(token, 'DECLARATION', tx); + + const declaration = await tx.declaration.findUnique({ + where: { id: link.targetId }, + include: { questions: { orderBy: { order: 'asc' } } }, + }); + if (!declaration) { + throw linkExpired(); + } + if (declaration.status === 'SUBMITTED') { + throw alreadySubmitted(); + } + + assertConsentsGiven(dto.consents); + const answers = validateAnswers(declaration.questions, dto.answers); + + const submittedAt = new Date(); + + // 동시 제출 시 하나만 통과 (SENT일 때만 SUBMITTED로 전환) + const { count } = await tx.declaration.updateMany({ + where: { id: declaration.id, status: 'SENT' }, + data: { + status: 'SUBMITTED', + submittedAt, + consentEvaluation: true, + consentDataAccess: true, + consentEvidenceRetention: true, + consentVersion: dto.consents.consentVersion, + consentAgreedAt: submittedAt, + consentIp: meta.ip ?? null, + consentUserAgent: meta.userAgent ?? null, + }, + }); + if (count === 0) { + throw alreadySubmitted(); + } + + if (answers.length > 0) { + await tx.declarationResponse.createMany({ data: answers }); + } + + await tx.employee.update({ + where: { id: declaration.employeeId }, + data: { declarationStatus: 'SUBMITTED' }, + }); + + await this.accessLinkService.consume(link.id, tx); + + await this.auditService.log( + { + actorType: 'EMPLOYEE', + actorId: declaration.employeeId, + action: 'DECLARATION_SUBMITTED', + targetType: 'Declaration', + targetId: declaration.id, + ip: meta.ip, + userAgent: meta.userAgent, + metadata: { consentVersion: dto.consents.consentVersion, answerCount: answers.length }, + }, + tx, + ); + + return { + declarationId: declaration.id, + status: 'SUBMITTED' as const, + submittedAt, + linkConsumed: true, + }; + }); + } + + /** 대표가 직원의 제출된 자기선언(질문·답변·동의 이력)을 최신순으로 조회한다. */ + async getEmployeeDeclarations(user: JwtPayload, employeeId: string) { + const companyId = await resolveCompanyId(user, this.prisma); + + const employee = await this.prisma.employee.findUnique({ + where: { id: employeeId }, + select: { id: true, companyId: true }, + }); + if (!employee) { + throw new NotFoundException({ code: 'EMPLOYEE_NOT_FOUND', message: '직원을 찾을 수 없습니다.' }); + } + if (employee.companyId !== companyId) { + throw forbidden(); + } + + const declarations = await this.prisma.declaration.findMany({ + where: { employeeId, status: 'SUBMITTED' }, + orderBy: { submittedAt: 'desc' }, + include: { + questions: { orderBy: { order: 'asc' }, include: { response: true } }, + }, + }); + if (declarations.length === 0) { + throw new NotFoundException({ + code: 'DECLARATION_NOT_FOUND', + message: '제출된 자기선언이 없습니다.', + }); + } + + return { + employeeId, + declarations: declarations.map((declaration) => ({ + declarationId: declaration.id, + templateId: declaration.templateId, + templateName: declaration.templateName, + templateVersion: declaration.templateVersion, + status: declaration.status, + submittedAt: declaration.submittedAt, + items: declaration.questions.map(toDeclarationItem), + consents: { + evaluationAgreed: declaration.consentEvaluation, + dataAccessAgreed: declaration.consentDataAccess, + evidenceRetentionAgreed: declaration.consentEvidenceRetention, + consentVersion: declaration.consentVersion, + agreedAt: declaration.consentAgreedAt, + }, + })), + }; + } +} + +/** 템플릿 선택지(string[])를 스냅샷 선택지([{optionId, label}])로 변환. 선택형이 아니면 저장하지 않음 */ +function toSnapshotOptions(options: Prisma.JsonValue | null): SnapshotOption[] | undefined { + if (!Array.isArray(options)) { + return undefined; + } + return options.map((label) => ({ optionId: randomUUID(), label: String(label) })); +} + +function toFormQuestion(q: DeclarationQuestionSnapshot) { + return { + questionId: q.id, + order: q.order, + type: q.type, + text: q.text, + required: q.required, + ...(q.type === 'SCORE' && { scoreMin: q.scoreMin, scoreMax: q.scoreMax }), + ...(q.type === 'SINGLE_CHOICE' && { options: (q.options as SnapshotOption[] | null) ?? [] }), + ...(q.type === 'TEXT' && { maxLength: q.maxLength }), + evaluationEnabled: q.evaluationEnabled, + }; +} + +function toDeclarationItem(q: DeclarationQuestionSnapshot & { response: DeclarationResponse | null }) { + const base = { + questionId: q.id, + order: q.order, + type: q.type, + question: q.text, + required: q.required, + evaluationEnabled: q.evaluationEnabled, + }; + + switch (q.type) { + case 'SCORE': + return { ...base, answerScore: q.response?.answerScore ?? null }; + case 'SINGLE_CHOICE': { + const options = (q.options as SnapshotOption[] | null) ?? []; + const option = options.find((o) => o.optionId === q.response?.answerOptionId); + return { ...base, answerOption: option ?? null }; + } + case 'TEXT': + return { ...base, answerText: q.response?.answerText ?? null }; + } +} + +function assertConsentsGiven(consents: SubmitDeclarationDto['consents']): void { + const allAgreed = + consents.evaluationAgreed && consents.dataAccessAgreed && consents.evidenceRetentionAgreed; + + if (!allAgreed) { + throw new ForbiddenException({ + code: 'CONSENT_NOT_GIVEN', + message: '필수 동의 항목에 모두 동의해야 제출할 수 있습니다.', + }); + } + // 직원이 본 동의서와 현재 동의서 버전이 다르면 유효한 동의로 보지 않는다 + if (consents.consentVersion !== CURRENT_CONSENT_VERSION) { + throw new ForbiddenException({ + code: 'CONSENT_NOT_GIVEN', + message: '동의서가 변경되었습니다. 질문지를 다시 불러와 최신 동의서에 동의해 주세요.', + details: { currentConsentVersion: CURRENT_CONSENT_VERSION }, + }); + } +} + +function forbidden(): ForbiddenException { + return new ForbiddenException({ + code: 'FORBIDDEN', + message: '다른 기업의 직원 또는 템플릿에는 접근할 수 없습니다.', + }); +} + +function activeDeclarationExists(): ConflictException { + return new ConflictException({ + code: 'ACTIVE_DECLARATION_EXISTS', + message: '제출 전인 자기선언 질문지가 이미 있습니다.', + }); +} + +function alreadySubmitted(): ConflictException { + return new ConflictException({ + code: 'ALREADY_SUBMITTED', + message: '이미 제출이 완료된 자기선언입니다.', + }); +} + +function linkExpired(): GoneException { + return new GoneException({ + code: 'LINK_EXPIRED', + message: '만료되었거나 유효하지 않은 링크입니다.', + }); +} diff --git a/src/declaration/dto/assign-declaration.dto.ts b/src/declaration/dto/assign-declaration.dto.ts new file mode 100644 index 0000000..300435d --- /dev/null +++ b/src/declaration/dto/assign-declaration.dto.ts @@ -0,0 +1,15 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsIn, IsNotEmpty, IsString } from 'class-validator'; + +export const SEND_CHANNELS = ['EMAIL'] as const; + +export class AssignDeclarationDto { + @ApiProperty({ example: 'uuid', description: '할당할 질문 템플릿 ID (ACTIVE만 가능)' }) + @IsString() + @IsNotEmpty() + templateId!: string; + + @ApiProperty({ enum: SEND_CHANNELS, example: 'EMAIL', description: '발송 채널 (MVP는 EMAIL만)' }) + @IsIn(SEND_CHANNELS) + sendChannel!: (typeof SEND_CHANNELS)[number]; +} diff --git a/src/declaration/dto/submit-declaration.dto.ts b/src/declaration/dto/submit-declaration.dto.ts new file mode 100644 index 0000000..d8ffc45 --- /dev/null +++ b/src/declaration/dto/submit-declaration.dto.ts @@ -0,0 +1,69 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { Type } from 'class-transformer'; +import { + IsArray, + IsBoolean, + IsNotEmpty, + IsNumber, + IsOptional, + IsString, + ValidateNested, +} from 'class-validator'; + +/** + * 질문 유형에 맞는 필드 하나만 보낸다. SCORE → answerScore, SINGLE_CHOICE → answerOptionId, TEXT → answerText + * 유형과 다른 필드는 400 INVALID_ANSWER_TYPE, 범위·선택지·글자 수 위반은 422 ANSWER_VALIDATION_FAILED (서비스에서 판정) + */ +export class AnswerDto { + @ApiProperty({ example: 'uuid', description: '질문지 조회 응답의 questionId' }) + @IsString() + @IsNotEmpty() + questionId!: string; + + @ApiPropertyOptional({ example: 8, description: 'SCORE: scoreMin~scoreMax 정수' }) + @IsOptional() + @IsNumber() + answerScore?: number; + + @ApiPropertyOptional({ example: 'uuid', description: 'SINGLE_CHOICE: 선택지의 optionId' }) + @IsOptional() + @IsString() + answerOptionId?: string; + + @ApiPropertyOptional({ example: 'React 성능 개선을 진행했습니다.', description: 'TEXT: maxLength 이내' }) + @IsOptional() + @IsString() + answerText?: string; +} + +export class DeclarationConsentsDto { + @ApiProperty({ example: true, description: '평가 활용 동의' }) + @IsBoolean() + evaluationAgreed!: boolean; + + @ApiProperty({ example: true, description: '정보 열람 동의' }) + @IsBoolean() + dataAccessAgreed!: boolean; + + @ApiProperty({ example: true, description: '증빙 보관 동의' }) + @IsBoolean() + evidenceRetentionAgreed!: boolean; + + @ApiProperty({ example: '2026-10-01', description: '질문지 조회 응답의 consentVersion' }) + @IsString() + @IsNotEmpty() + consentVersion!: string; +} + +export class SubmitDeclarationDto { + @ApiProperty({ type: [AnswerDto] }) + @IsArray() + @ValidateNested({ each: true }) + @Type(() => AnswerDto) + answers!: AnswerDto[]; + + @ApiProperty({ type: DeclarationConsentsDto }) + @ValidateNested() + @Type(() => DeclarationConsentsDto) + consents!: DeclarationConsentsDto; +}