From b2af5c4607f1ca0d906d580c0a086b46eead9fe8 Mon Sep 17 00:00:00 2001 From: ChaeYeon Lee Date: Fri, 9 Oct 2026 18:27:08 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=A7=88=EB=AC=B8=20=ED=85=9C=ED=94=8C?= =?UTF-8?q?=EB=A6=BF=20=EC=83=9D=EC=84=B1=C2=B7=EC=A1=B0=ED=9A=8C=C2=B7?= =?UTF-8?q?=EC=88=98=EC=A0=95=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - POST/GET/GET:id/PATCH /question-templates (대표 전용) - 질문 유형별 제약조건 위반은 422 INVALID_QUESTION_SET - PATCH 시 질문이 바뀌면 질문 교체 + version 1 증가, 요청 버전 불일치는 409 TEMPLATE_VERSION_CONFLICT - 목록은 상태·검색어 필터와 페이지네이션 지원 Co-Authored-By: Claude Opus 5.5 --- src/app.module.ts | 2 + .../dto/create-question-template.dto.ts | 31 ++ .../dto/list-question-templates-query.dto.ts | 32 ++ src/question-template/dto/question.dto.ts | 64 ++++ .../dto/update-question-template.dto.ts | 47 +++ .../question-set.validator.spec.ts | 121 ++++++++ .../question-set.validator.ts | 121 ++++++++ .../question-template.controller.ts | 76 +++++ .../question-template.module.ts | 12 + .../question-template.service.spec.ts | 287 ++++++++++++++++++ .../question-template.service.ts | 250 +++++++++++++++ 11 files changed, 1043 insertions(+) create mode 100644 src/question-template/dto/create-question-template.dto.ts create mode 100644 src/question-template/dto/list-question-templates-query.dto.ts create mode 100644 src/question-template/dto/question.dto.ts create mode 100644 src/question-template/dto/update-question-template.dto.ts create mode 100644 src/question-template/question-set.validator.spec.ts create mode 100644 src/question-template/question-set.validator.ts create mode 100644 src/question-template/question-template.controller.ts create mode 100644 src/question-template/question-template.module.ts create mode 100644 src/question-template/question-template.service.spec.ts create mode 100644 src/question-template/question-template.service.ts diff --git a/src/app.module.ts b/src/app.module.ts index f498071..6666fa9 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -9,6 +9,7 @@ import { EvaluationModule } from './evaluation/evaluation.module'; import { AccessLinkModule } from './access-link/access-link.module'; import { NotificationModule } from './notification/notification.module'; import { AuditModule } from './audit/audit.module'; +import { QuestionTemplateModule } from './question-template/question-template.module'; @Module({ imports: [ @@ -25,6 +26,7 @@ import { AuditModule } from './audit/audit.module'; AccessLinkModule, NotificationModule, AuditModule, + QuestionTemplateModule, ], }) export class AppModule {} diff --git a/src/question-template/dto/create-question-template.dto.ts b/src/question-template/dto/create-question-template.dto.ts new file mode 100644 index 0000000..feb61ca --- /dev/null +++ b/src/question-template/dto/create-question-template.dto.ts @@ -0,0 +1,31 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { Type } from 'class-transformer'; +import { + IsArray, + IsNotEmpty, + IsOptional, + IsString, + MaxLength, + ValidateNested, +} from 'class-validator'; +import { QuestionDto } from './question.dto'; + +export class CreateQuestionTemplateDto { + @ApiProperty({ example: '개발직군 입사 자기선언', description: '템플릿 이름 (100자 이내)' }) + @IsString() + @IsNotEmpty() + @MaxLength(100) + name!: string; + + @ApiPropertyOptional({ example: '개발직군 공통 질문', description: '설명 (500자 이내)' }) + @IsOptional() + @IsString() + @MaxLength(500) + description?: string; + + @ApiProperty({ type: [QuestionDto], description: '질문 목록 (1개 이상)' }) + @IsArray() + @ValidateNested({ each: true }) + @Type(() => QuestionDto) + questions!: QuestionDto[]; +} diff --git a/src/question-template/dto/list-question-templates-query.dto.ts b/src/question-template/dto/list-question-templates-query.dto.ts new file mode 100644 index 0000000..65462dc --- /dev/null +++ b/src/question-template/dto/list-question-templates-query.dto.ts @@ -0,0 +1,32 @@ +import { ApiPropertyOptional } from '@nestjs/swagger'; +import { TemplateStatus } from '@prisma/client'; +import { Type } from 'class-transformer'; +import { IsEnum, IsInt, IsOptional, IsString, Max, MaxLength, Min } from 'class-validator'; + +export class ListQuestionTemplatesQueryDto { + @ApiPropertyOptional({ enum: TemplateStatus }) + @IsOptional() + @IsEnum(TemplateStatus) + status?: TemplateStatus; + + @ApiPropertyOptional({ description: '템플릿 이름·설명 검색어' }) + @IsOptional() + @IsString() + @MaxLength(100) + keyword?: string; + + @ApiPropertyOptional({ default: 1, minimum: 1 }) + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + page?: number; + + @ApiPropertyOptional({ default: 20, minimum: 1, maximum: 100 }) + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + @Max(100) + size?: number; +} diff --git a/src/question-template/dto/question.dto.ts b/src/question-template/dto/question.dto.ts new file mode 100644 index 0000000..a9804ab --- /dev/null +++ b/src/question-template/dto/question.dto.ts @@ -0,0 +1,64 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { QuestionType } from '@prisma/client'; +import { + IsArray, + IsBoolean, + IsEnum, + IsInt, + IsString, + Min, + ValidateIf, +} from 'class-validator'; + +/** + * 템플릿 질문 1개. 여기서는 형식(타입)만 검사하고(400), + * 유형별 제약조건(범위·선택지·글자 수·order 중복)은 validateQuestionSet에서 422로 판정한다. + * 유형과 무관한 필드(예: TEXT 질문의 scoreMin)는 검사하지 않고 저장 시 버린다. + */ +export class QuestionDto { + @ApiProperty({ example: 1, description: '질문 순서 (1부터, 중복 불가)' }) + @IsInt() + @Min(1) + order!: number; + + @ApiProperty({ enum: QuestionType, example: QuestionType.SCORE }) + @IsEnum(QuestionType) + type!: QuestionType; + + @ApiProperty({ example: '업무 책임감을 평가해 주세요.', description: '질문 문구 (100자 이내)' }) + @IsString() + text!: string; + + @ApiProperty({ example: true }) + @IsBoolean() + required!: boolean; + + @ApiPropertyOptional({ example: 1, description: 'SCORE 필수. 1 이상' }) + @ValidateIf((q: QuestionDto) => q.type === QuestionType.SCORE && q.scoreMin != null) + @IsInt() + scoreMin?: number; + + @ApiPropertyOptional({ example: 10, description: 'SCORE 필수. scoreMin보다 크고 10 이하' }) + @ValidateIf((q: QuestionDto) => q.type === QuestionType.SCORE && q.scoreMax != null) + @IsInt() + scoreMax?: number; + + @ApiPropertyOptional({ + example: ['개인 집중', '팀 협업'], + description: 'SINGLE_CHOICE 필수. 2개 이상, 빈값·중복 불가', + type: [String], + }) + @ValidateIf((q: QuestionDto) => q.type === QuestionType.SINGLE_CHOICE && q.options != null) + @IsArray() + @IsString({ each: true }) + options?: string[]; + + @ApiPropertyOptional({ example: 500, description: 'TEXT 필수. 1~1000' }) + @ValidateIf((q: QuestionDto) => q.type === QuestionType.TEXT && q.maxLength != null) + @IsInt() + maxLength?: number; + + @ApiProperty({ example: true, description: '퇴사 평가 항목으로 사용할지 여부' }) + @IsBoolean() + evaluationEnabled!: boolean; +} diff --git a/src/question-template/dto/update-question-template.dto.ts b/src/question-template/dto/update-question-template.dto.ts new file mode 100644 index 0000000..a124b32 --- /dev/null +++ b/src/question-template/dto/update-question-template.dto.ts @@ -0,0 +1,47 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { TemplateStatus } from '@prisma/client'; +import { Type } from 'class-transformer'; +import { + IsArray, + IsEnum, + IsInt, + IsNotEmpty, + IsOptional, + IsString, + MaxLength, + Min, + ValidateNested, +} from 'class-validator'; +import { QuestionDto } from './question.dto'; + +export class UpdateQuestionTemplateDto { + @ApiProperty({ example: 1, description: '수정 기준 버전. 현재 버전과 다르면 409 TEMPLATE_VERSION_CONFLICT' }) + @IsInt() + @Min(1) + version!: number; + + @ApiPropertyOptional({ example: '개발직군 입사 자기선언 v2' }) + @IsOptional() + @IsString() + @IsNotEmpty() + @MaxLength(100) + name?: string; + + @ApiPropertyOptional({ example: '개발직군 공통 질문', nullable: true, description: 'null이면 설명 삭제' }) + @IsOptional() + @IsString() + @MaxLength(500) + description?: string | null; + + @ApiPropertyOptional({ type: [QuestionDto], description: '질문 전체 교체. 내용이 바뀌면 version 1 증가' }) + @IsOptional() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => QuestionDto) + questions?: QuestionDto[]; + + @ApiPropertyOptional({ enum: TemplateStatus, description: 'ARCHIVED로 바꾸면 새 직원에게 할당 불가' }) + @IsOptional() + @IsEnum(TemplateStatus) + status?: TemplateStatus; +} diff --git a/src/question-template/question-set.validator.spec.ts b/src/question-template/question-set.validator.spec.ts new file mode 100644 index 0000000..e2e03ab --- /dev/null +++ b/src/question-template/question-set.validator.spec.ts @@ -0,0 +1,121 @@ +import { UnprocessableEntityException } from '@nestjs/common'; +import { QuestionDto } from './dto/question.dto'; +import { validateQuestionSet } from './question-set.validator'; + +const score = (over: Partial = {}): QuestionDto => ({ + order: 1, + type: 'SCORE', + text: '업무 책임감을 평가해 주세요.', + required: true, + scoreMin: 1, + scoreMax: 10, + evaluationEnabled: true, + ...over, +}); +const choice = (over: Partial = {}): QuestionDto => ({ + order: 2, + type: 'SINGLE_CHOICE', + text: '선호 업무 방식은 무엇인가요?', + required: true, + options: ['개인 집중', '팀 협업'], + evaluationEnabled: false, + ...over, +}); +const text = (over: Partial = {}): QuestionDto => ({ + order: 3, + type: 'TEXT', + text: '주요 성과를 작성해 주세요.', + required: true, + maxLength: 500, + evaluationEnabled: true, + ...over, +}); + +function expectInvalid(questions: QuestionDto[], field: string) { + try { + validateQuestionSet(questions); + throw new Error('예외가 발생해야 합니다.'); + } catch (error) { + expect(error).toBeInstanceOf(UnprocessableEntityException); + const body = (error as UnprocessableEntityException).getResponse() as any; + expect(body.code).toBe('INVALID_QUESTION_SET'); + expect(body.details.errors.map((e: any) => e.field)).toContain(field); + } +} + +describe('validateQuestionSet', () => { + it('세 유형이 모두 유효하면 order순으로 정리하고 유형과 무관한 필드는 버린다', () => { + const result = validateQuestionSet([ + text({ scoreMin: 1, options: ['x', 'y'] }), + score({ maxLength: 10, text: ' 앞뒤 공백 ' }), + choice({ options: [' 개인 집중 ', '팀 협업'], scoreMax: 5 }), + ]); + + expect(result.map((q) => q.order)).toEqual([1, 2, 3]); + expect(result[0]).toEqual({ + order: 1, type: 'SCORE', text: '앞뒤 공백', required: true, + scoreMin: 1, scoreMax: 10, evaluationEnabled: true, + }); + expect(result[1]).toEqual({ + order: 2, type: 'SINGLE_CHOICE', text: '선호 업무 방식은 무엇인가요?', required: true, + options: ['개인 집중', '팀 협업'], evaluationEnabled: false, + }); + expect(result[2]).toEqual({ + order: 3, type: 'TEXT', text: '주요 성과를 작성해 주세요.', required: true, + maxLength: 500, evaluationEnabled: true, + }); + }); + + describe('공통', () => { + it('질문이 없으면 422', () => expectInvalid([], 'questions')); + it('order 중복이면 422', () => expectInvalid([score({ order: 1 }), text({ order: 1 })], 'order')); + it('질문 문구가 비면 422', () => expectInvalid([score({ text: ' ' })], 'text')); + it('질문 문구가 100자를 넘으면 422', () => expectInvalid([score({ text: '가'.repeat(101) })], 'text')); + it('질문 문구 100자는 허용', () => expect(validateQuestionSet([score({ text: '가'.repeat(100) })])).toHaveLength(1)); + }); + + describe('SCORE', () => { + it('scoreMin/scoreMax 누락이면 422', () => { + expectInvalid([score({ scoreMin: undefined })], 'scoreMin/scoreMax'); + expectInvalid([score({ scoreMax: undefined })], 'scoreMin/scoreMax'); + }); + it('scoreMin < 1 이면 422', () => expectInvalid([score({ scoreMin: 0 })], 'scoreMin/scoreMax')); + it('scoreMax > 10 이면 422', () => expectInvalid([score({ scoreMax: 11 })], 'scoreMin/scoreMax')); + it('scoreMin >= scoreMax 이면 422', () => { + expectInvalid([score({ scoreMin: 5, scoreMax: 5 })], 'scoreMin/scoreMax'); + expectInvalid([score({ scoreMin: 7, scoreMax: 3 })], 'scoreMin/scoreMax'); + }); + }); + + describe('SINGLE_CHOICE', () => { + it('선택지가 2개 미만이면 422', () => { + expectInvalid([choice({ options: ['하나'] })], 'options'); + expectInvalid([choice({ options: undefined })], 'options'); + }); + it('빈 선택지가 있으면 422', () => expectInvalid([choice({ options: ['개인 집중', ' '] })], 'options')); + it('선택지가 중복되면 422 (앞뒤 공백 무시)', () => + expectInvalid([choice({ options: ['팀 협업', ' 팀 협업'] })], 'options')); + }); + + describe('TEXT', () => { + it('maxLength 누락이면 422', () => expectInvalid([text({ maxLength: undefined })], 'maxLength')); + it('maxLength가 1~1000을 벗어나면 422', () => { + expectInvalid([text({ maxLength: 0 })], 'maxLength'); + expectInvalid([text({ maxLength: 1001 })], 'maxLength'); + }); + it('maxLength 1과 1000은 허용', () => { + expect(validateQuestionSet([text({ maxLength: 1 })])[0].maxLength).toBe(1); + expect(validateQuestionSet([text({ maxLength: 1000 })])[0].maxLength).toBe(1000); + }); + }); + + it('위반이 여러 개면 모두 details.errors에 담는다', () => { + try { + validateQuestionSet([score({ scoreMin: 0 }), choice({ options: ['하나'] }), text({ maxLength: 0 })]); + throw new Error('예외가 발생해야 합니다.'); + } catch (error) { + const body = (error as UnprocessableEntityException).getResponse() as any; + expect(body.details.errors).toHaveLength(3); + } + }); +}); diff --git a/src/question-template/question-set.validator.ts b/src/question-template/question-set.validator.ts new file mode 100644 index 0000000..a383fd0 --- /dev/null +++ b/src/question-template/question-set.validator.ts @@ -0,0 +1,121 @@ +import { UnprocessableEntityException } from '@nestjs/common'; +import { QuestionType } from '@prisma/client'; +import { QuestionDto } from './dto/question.dto'; + +export const QUESTION_TEXT_MAX_LENGTH = 100; +export const SCORE_RANGE = { min: 1, max: 10 } as const; +export const TEXT_MAX_LENGTH_RANGE = { min: 1, max: 1000 } as const; +export const SINGLE_CHOICE_MIN_OPTIONS = 2; + +/** 검증을 통과해 저장 가능한 형태로 정리된 질문 (유형과 무관한 필드는 제거) */ +export interface NormalizedQuestion { + order: number; + type: QuestionType; + text: string; + required: boolean; + scoreMin?: number; + scoreMax?: number; + options?: string[]; + maxLength?: number; + evaluationEnabled: boolean; +} + +interface QuestionSetError { + order: number | null; + field: string; + message: string; +} + +/** + * 질문 유형별 제약조건을 검사하고 정리된 질문 목록(order순)을 반환한다. + * 위반이 하나라도 있으면 전체 목록을 details.errors에 담아 422 INVALID_QUESTION_SET을 던진다. + */ +export function validateQuestionSet(questions: QuestionDto[]): NormalizedQuestion[] { + const errors: QuestionSetError[] = []; + + if (!questions || questions.length === 0) { + errors.push({ order: null, field: 'questions', message: '질문은 1개 이상이어야 합니다.' }); + } + + const seenOrders = new Set(); + const normalized: NormalizedQuestion[] = []; + + for (const q of questions ?? []) { + const add = (field: string, message: string) => errors.push({ order: q.order, field, message }); + + if (seenOrders.has(q.order)) { + add('order', '질문 순서가 중복됩니다.'); + } + seenOrders.add(q.order); + + const text = q.text.trim(); + if (!text) { + add('text', '질문 문구를 입력해 주세요.'); + } else if (text.length > QUESTION_TEXT_MAX_LENGTH) { + add('text', `질문 문구는 ${QUESTION_TEXT_MAX_LENGTH}자 이내여야 합니다.`); + } + + const base = { + order: q.order, + type: q.type, + text, + required: q.required, + evaluationEnabled: q.evaluationEnabled, + }; + + switch (q.type) { + case QuestionType.SCORE: { + const { scoreMin, scoreMax } = q; + if (scoreMin == null || scoreMax == null) { + add('scoreMin/scoreMax', '점수형 질문은 scoreMin과 scoreMax가 필요합니다.'); + } else if ( + scoreMin < SCORE_RANGE.min || + scoreMax > SCORE_RANGE.max || + scoreMin >= scoreMax + ) { + add( + 'scoreMin/scoreMax', + `점수 범위는 ${SCORE_RANGE.min} ≤ scoreMin < scoreMax ≤ ${SCORE_RANGE.max}여야 합니다.`, + ); + } + normalized.push({ ...base, scoreMin: scoreMin ?? undefined, scoreMax: scoreMax ?? undefined }); + break; + } + case QuestionType.SINGLE_CHOICE: { + const options = (q.options ?? []).map((option) => option.trim()); + if (options.length < SINGLE_CHOICE_MIN_OPTIONS) { + add('options', `선택형 질문은 선택지가 ${SINGLE_CHOICE_MIN_OPTIONS}개 이상이어야 합니다.`); + } else if (options.some((option) => !option)) { + add('options', '빈 선택지는 사용할 수 없습니다.'); + } else if (new Set(options).size !== options.length) { + add('options', '선택지가 중복됩니다.'); + } + normalized.push({ ...base, options }); + break; + } + case QuestionType.TEXT: { + const { maxLength } = q; + if (maxLength == null) { + add('maxLength', '서술형 질문은 maxLength가 필요합니다.'); + } else if (maxLength < TEXT_MAX_LENGTH_RANGE.min || maxLength > TEXT_MAX_LENGTH_RANGE.max) { + add( + 'maxLength', + `maxLength는 ${TEXT_MAX_LENGTH_RANGE.min}~${TEXT_MAX_LENGTH_RANGE.max}여야 합니다.`, + ); + } + normalized.push({ ...base, maxLength: maxLength ?? undefined }); + break; + } + } + } + + if (errors.length > 0) { + throw new UnprocessableEntityException({ + code: 'INVALID_QUESTION_SET', + message: '질문 구성이 유형별 제약조건을 만족하지 않습니다.', + details: { errors }, + }); + } + + return normalized.sort((a, b) => a.order - b.order); +} diff --git a/src/question-template/question-template.controller.ts b/src/question-template/question-template.controller.ts new file mode 100644 index 0000000..6973d55 --- /dev/null +++ b/src/question-template/question-template.controller.ts @@ -0,0 +1,76 @@ +import { Body, Controller, Get, HttpCode, HttpStatus, Param, Patch, Post, Query, 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 { CreateQuestionTemplateDto } from './dto/create-question-template.dto'; +import { ListQuestionTemplatesQueryDto } from './dto/list-question-templates-query.dto'; +import { UpdateQuestionTemplateDto } from './dto/update-question-template.dto'; +import { QuestionTemplateService } from './question-template.service'; + +@ApiTags('QuestionTemplate') +@ApiBearerAuth('access-token') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('COMPANY') +@Controller('question-templates') +export class QuestionTemplateController { + constructor(private readonly questionTemplateService: QuestionTemplateService) {} + + @Post() + @HttpCode(HttpStatus.CREATED) + @ApiOperation({ summary: '대표: 질문 템플릿 생성 (version 1)' }) + @ApiResponse({ status: 201, description: '생성 성공 { templateId, version, questionCount, status }' }) + @ApiResponse({ status: 400, description: '필수값 누락 또는 형식 오류' }) + @ApiResponse({ status: 401, description: '인증 필요' }) + @ApiResponse({ status: 403, description: 'FORBIDDEN (대표 권한 아님)' }) + @ApiResponse({ status: 422, description: 'INVALID_QUESTION_SET (질문 유형별 제약조건 위반)' }) + @ResponseMessage('질문 템플릿 생성 성공') + create(@CurrentUser() user: JwtPayload, @Body() dto: CreateQuestionTemplateDto) { + return this.questionTemplateService.create(user, dto); + } + + @Get() + @ApiOperation({ summary: '대표: 질문 템플릿 목록 조회 (최신 수정순)' }) + @ApiResponse({ status: 200, description: '조회 성공 { items, page, size, totalElements }' }) + @ApiResponse({ status: 400, description: '쿼리 형식 오류' }) + @ApiResponse({ status: 401, description: '인증 필요' }) + @ApiResponse({ status: 403, description: 'FORBIDDEN (대표 권한 아님)' }) + @ResponseMessage('질문 템플릿 목록 조회 성공') + list(@CurrentUser() user: JwtPayload, @Query() query: ListQuestionTemplatesQueryDto) { + return this.questionTemplateService.list(user, query); + } + + @Get(':templateId') + @ApiOperation({ summary: '대표: 질문 템플릿 상세 조회 (질문 order순)' }) + @ApiParam({ name: 'templateId', description: '질문 템플릿 ID' }) + @ApiResponse({ status: 200, description: '조회 성공' }) + @ApiResponse({ status: 401, description: '인증 필요' }) + @ApiResponse({ status: 403, description: 'FORBIDDEN (다른 기업의 템플릿)' }) + @ApiResponse({ status: 404, description: 'QUESTION_TEMPLATE_NOT_FOUND' }) + @ResponseMessage('질문 템플릿 상세 조회 성공') + findOne(@CurrentUser() user: JwtPayload, @Param('templateId') templateId: string) { + return this.questionTemplateService.findOne(user, templateId); + } + + @Patch(':templateId') + @ApiOperation({ summary: '대표: 질문 템플릿 수정 (질문 변경 시 version 증가, 발송된 질문지는 영향 없음)' }) + @ApiParam({ name: 'templateId', description: '질문 템플릿 ID' }) + @ApiResponse({ status: 200, description: '수정 성공 { templateId, version, questionCount, status }' }) + @ApiResponse({ status: 400, description: '필수값 누락 또는 형식 오류' }) + @ApiResponse({ status: 401, description: '인증 필요' }) + @ApiResponse({ status: 403, description: 'FORBIDDEN (다른 기업의 템플릿)' }) + @ApiResponse({ status: 404, description: 'QUESTION_TEMPLATE_NOT_FOUND' }) + @ApiResponse({ status: 409, description: 'TEMPLATE_VERSION_CONFLICT (요청 버전과 최신 버전 불일치)' }) + @ApiResponse({ status: 422, description: 'INVALID_QUESTION_SET (질문 유형별 제약조건 위반)' }) + @ResponseMessage('질문 템플릿 수정 성공') + update( + @CurrentUser() user: JwtPayload, + @Param('templateId') templateId: string, + @Body() dto: UpdateQuestionTemplateDto, + ) { + return this.questionTemplateService.update(user, templateId, dto); + } +} diff --git a/src/question-template/question-template.module.ts b/src/question-template/question-template.module.ts new file mode 100644 index 0000000..9416fbd --- /dev/null +++ b/src/question-template/question-template.module.ts @@ -0,0 +1,12 @@ +import { Module } from '@nestjs/common'; +import { AuthModule } from '../auth/auth.module'; +import { QuestionTemplateController } from './question-template.controller'; +import { QuestionTemplateService } from './question-template.service'; + +@Module({ + // JwtAuthGuard가 AuthModule의 RedisService(토큰 블랙리스트)를 사용 + imports: [AuthModule], + controllers: [QuestionTemplateController], + providers: [QuestionTemplateService], +}) +export class QuestionTemplateModule {} diff --git a/src/question-template/question-template.service.spec.ts b/src/question-template/question-template.service.spec.ts new file mode 100644 index 0000000..f3ed334 --- /dev/null +++ b/src/question-template/question-template.service.spec.ts @@ -0,0 +1,287 @@ +import { + ConflictException, + ForbiddenException, + HttpException, + NotFoundException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; +import { QuestionTemplateService } from './question-template.service'; +import { QuestionDto } from './dto/question.dto'; + +const CEO = { sub: 'comp-1', role: 'COMPANY' as const }; + +const scoreQuestion = (over: Partial = {}): QuestionDto => ({ + order: 1, + type: 'SCORE', + text: '업무 책임감을 평가해 주세요.', + required: true, + scoreMin: 1, + scoreMax: 10, + evaluationEnabled: true, + ...over, +}); + +// DB에 저장된 형태의 템플릿 질문 +const storedScore = { + id: 'q-1', + templateId: 'tpl-1', + order: 1, + type: 'SCORE', + text: '업무 책임감을 평가해 주세요.', + required: true, + scoreMin: 1, + scoreMax: 10, + options: null, + maxLength: null, + evaluationEnabled: true, +}; + +const storedTemplate = (over: Record = {}) => ({ + id: 'tpl-1', + companyId: 'comp-1', + name: '개발직군 입사 자기선언', + description: null, + version: 1, + status: 'ACTIVE', + createdAt: new Date('2026-10-01T00:00:00Z'), + updatedAt: new Date('2026-10-01T00:00:00Z'), + questions: [storedScore], + ...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('QuestionTemplateService', () => { + let prismaMock: any; + let service: QuestionTemplateService; + + beforeEach(() => { + prismaMock = { + hrManager: { findUnique: jest.fn() }, + questionTemplate: { + create: jest.fn(), + count: jest.fn(), + findMany: jest.fn(), + findUnique: jest.fn(), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + templateQuestion: { + deleteMany: jest.fn().mockResolvedValue({ count: 1 }), + createMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + $transaction: jest.fn(async (arg: any) => + typeof arg === 'function' ? arg(prismaMock) : Promise.all(arg), + ), + }; + service = new QuestionTemplateService(prismaMock as unknown as PrismaService); + }); + + describe('create', () => { + it('대표 기업으로 version 1 템플릿을 만들고 요약을 반환한다', async () => { + prismaMock.questionTemplate.create.mockResolvedValue(storedTemplate()); + + const result = await service.create(CEO, { + name: ' 개발직군 입사 자기선언 ', + questions: [scoreQuestion()], + }); + + expect(result).toEqual({ templateId: 'tpl-1', version: 1, questionCount: 1, status: 'ACTIVE' }); + const { data } = prismaMock.questionTemplate.create.mock.calls[0][0]; + expect(data.companyId).toBe('comp-1'); + expect(data.name).toBe('개발직군 입사 자기선언'); + expect(data.questions.create).toEqual([ + expect.objectContaining({ order: 1, type: 'SCORE', scoreMin: 1, scoreMax: 10, maxLength: null }), + ]); + }); + + it('질문 제약조건 위반이면 422 INVALID_QUESTION_SET이고 저장하지 않는다', async () => { + await expectCode( + service.create(CEO, { name: 't', questions: [scoreQuestion({ scoreMax: 11 })] }), + UnprocessableEntityException, + 'INVALID_QUESTION_SET', + ); + expect(prismaMock.questionTemplate.create).not.toHaveBeenCalled(); + }); + + it('대표·인사팀장이 아닌 역할은 403', async () => { + await expectCode( + service.create({ sub: 'app-1', role: 'APPLICANT' }, { name: 't', questions: [scoreQuestion()] }), + ForbiddenException, + 'FORBIDDEN', + ); + }); + }); + + describe('list', () => { + it('본인 기업만 최신 수정순으로 조회하고 페이지 정보를 반환한다', async () => { + prismaMock.questionTemplate.count.mockResolvedValue(21); + prismaMock.questionTemplate.findMany.mockResolvedValue([ + { ...storedTemplate({ version: 2 }), _count: { questions: 3 } }, + ]); + + const result = await service.list(CEO, { status: 'ACTIVE', keyword: ' 개발 ', page: 2, size: 20 }); + + const args = prismaMock.questionTemplate.findMany.mock.calls[0][0]; + expect(args.where).toEqual({ + companyId: 'comp-1', + status: 'ACTIVE', + OR: [ + { name: { contains: '개발', mode: 'insensitive' } }, + { description: { contains: '개발', mode: 'insensitive' } }, + ], + }); + expect(args.orderBy).toEqual([{ updatedAt: 'desc' }, { id: 'asc' }]); + expect(args.skip).toBe(20); + expect(args.take).toBe(20); + expect(result).toEqual({ + items: [{ + templateId: 'tpl-1', name: '개발직군 입사 자기선언', version: 2, questionCount: 3, + status: 'ACTIVE', updatedAt: new Date('2026-10-01T00:00:00Z'), + }], + page: 2, + size: 20, + totalElements: 21, + }); + }); + + it('page·size 기본값은 1·20', async () => { + prismaMock.questionTemplate.count.mockResolvedValue(0); + prismaMock.questionTemplate.findMany.mockResolvedValue([]); + + const result = await service.list(CEO, {}); + + expect(prismaMock.questionTemplate.findMany.mock.calls[0][0]).toMatchObject({ skip: 0, take: 20 }); + expect(result).toMatchObject({ page: 1, size: 20, totalElements: 0 }); + }); + }); + + describe('findOne', () => { + it('질문을 order순으로, 유형에 맞는 필드만 반환한다', async () => { + prismaMock.questionTemplate.findUnique.mockResolvedValue(storedTemplate({ + questions: [ + storedScore, + { ...storedScore, id: 'q-2', order: 2, type: 'SINGLE_CHOICE', scoreMin: null, scoreMax: null, options: ['A', 'B'] }, + { ...storedScore, id: 'q-3', order: 3, type: 'TEXT', scoreMin: null, scoreMax: null, maxLength: 500 }, + ], + })); + + const result = await service.findOne(CEO, 'tpl-1'); + + expect(prismaMock.questionTemplate.findUnique).toHaveBeenCalledWith({ + where: { id: 'tpl-1' }, + include: { questions: { orderBy: { order: 'asc' } } }, + }); + expect(result.questions).toEqual([ + { questionId: 'q-1', order: 1, type: 'SCORE', text: storedScore.text, required: true, scoreMin: 1, scoreMax: 10, evaluationEnabled: true }, + { questionId: 'q-2', order: 2, type: 'SINGLE_CHOICE', text: storedScore.text, required: true, options: ['A', 'B'], evaluationEnabled: true }, + { questionId: 'q-3', order: 3, type: 'TEXT', text: storedScore.text, required: true, maxLength: 500, evaluationEnabled: true }, + ]); + }); + + it('없으면 404 QUESTION_TEMPLATE_NOT_FOUND', async () => { + prismaMock.questionTemplate.findUnique.mockResolvedValue(null); + await expectCode(service.findOne(CEO, 'nope'), NotFoundException, 'QUESTION_TEMPLATE_NOT_FOUND'); + }); + + it('다른 기업 템플릿이면 403 FORBIDDEN', async () => { + prismaMock.questionTemplate.findUnique.mockResolvedValue(storedTemplate({ companyId: 'comp-other' })); + await expectCode(service.findOne(CEO, 'tpl-1'), ForbiddenException, 'FORBIDDEN'); + }); + }); + + describe('update', () => { + beforeEach(() => { + prismaMock.questionTemplate.findUnique.mockResolvedValue(storedTemplate()); + }); + + it('질문이 바뀌면 트랜잭션으로 질문을 교체하고 version을 1 올린다', async () => { + const result = await service.update(CEO, 'tpl-1', { + version: 1, + questions: [scoreQuestion({ scoreMax: 5 }), scoreQuestion({ order: 2, text: '협업 능력' })], + }); + + expect(result).toEqual({ templateId: 'tpl-1', version: 2, questionCount: 2, status: 'ACTIVE' }); + expect(prismaMock.$transaction).toHaveBeenCalled(); + expect(prismaMock.questionTemplate.updateMany).toHaveBeenCalledWith({ + where: { id: 'tpl-1', version: 1 }, + data: { version: { increment: 1 } }, + }); + expect(prismaMock.templateQuestion.deleteMany).toHaveBeenCalledWith({ where: { templateId: 'tpl-1' } }); + expect(prismaMock.templateQuestion.createMany.mock.calls[0][0].data).toHaveLength(2); + }); + + it('이름·상태만 바꾸면 질문은 그대로 두고 version도 유지한다 (ARCHIVED 전환)', async () => { + const result = await service.update(CEO, 'tpl-1', { version: 1, name: '새 이름', status: 'ARCHIVED' }); + + expect(result).toEqual({ templateId: 'tpl-1', version: 1, questionCount: 1, status: 'ARCHIVED' }); + expect(prismaMock.questionTemplate.updateMany).toHaveBeenCalledWith({ + where: { id: 'tpl-1', version: 1 }, + data: { name: '새 이름', status: 'ARCHIVED' }, + }); + expect(prismaMock.templateQuestion.deleteMany).not.toHaveBeenCalled(); + }); + + it('기존과 같은 질문을 보내면 version을 올리지 않는다', async () => { + const result = await service.update(CEO, 'tpl-1', { version: 1, questions: [scoreQuestion()] }); + + expect(result.version).toBe(1); + expect(prismaMock.questionTemplate.updateMany).not.toHaveBeenCalled(); + expect(prismaMock.templateQuestion.deleteMany).not.toHaveBeenCalled(); + }); + + it('요청 버전이 현재 버전과 다르면 409 TEMPLATE_VERSION_CONFLICT', async () => { + await expectCode( + service.update(CEO, 'tpl-1', { version: 2, name: 'x' }), + ConflictException, + 'TEMPLATE_VERSION_CONFLICT', + ); + expect(prismaMock.questionTemplate.updateMany).not.toHaveBeenCalled(); + }); + + it('조회 직후 다른 요청이 먼저 수정했으면(갱신 0건) 409', async () => { + prismaMock.questionTemplate.updateMany.mockResolvedValue({ count: 0 }); + await expectCode( + service.update(CEO, 'tpl-1', { version: 1, questions: [scoreQuestion({ scoreMax: 5 })] }), + ConflictException, + 'TEMPLATE_VERSION_CONFLICT', + ); + expect(prismaMock.templateQuestion.deleteMany).not.toHaveBeenCalled(); + }); + + it('다른 기업 템플릿 수정은 403, 없는 템플릿은 404', async () => { + prismaMock.questionTemplate.findUnique.mockResolvedValueOnce(storedTemplate({ companyId: 'comp-other' })); + await expectCode(service.update(CEO, 'tpl-1', { version: 1, name: 'x' }), ForbiddenException, 'FORBIDDEN'); + + prismaMock.questionTemplate.findUnique.mockResolvedValueOnce(null); + await expectCode( + service.update(CEO, 'nope', { version: 1, name: 'x' }), + NotFoundException, + 'QUESTION_TEMPLATE_NOT_FOUND', + ); + expect(prismaMock.questionTemplate.updateMany).not.toHaveBeenCalled(); + }); + + it('질문 제약조건 위반이면 DB 조회 전에 422', async () => { + await expectCode( + service.update(CEO, 'tpl-1', { version: 1, questions: [scoreQuestion({ scoreMin: 0 })] }), + UnprocessableEntityException, + 'INVALID_QUESTION_SET', + ); + expect(prismaMock.$transaction).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/src/question-template/question-template.service.ts b/src/question-template/question-template.service.ts new file mode 100644 index 0000000..cf5e7a2 --- /dev/null +++ b/src/question-template/question-template.service.ts @@ -0,0 +1,250 @@ +import { + ConflictException, + ForbiddenException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { Prisma, QuestionTemplate, TemplateQuestion } from '@prisma/client'; +import { JwtPayload } from '../auth/strategies/jwt.strategy'; +import { resolveCompanyId } from '../core/utils/company-scope'; +import { PrismaService } from '../prisma/prisma.service'; +import { CreateQuestionTemplateDto } from './dto/create-question-template.dto'; +import { ListQuestionTemplatesQueryDto } from './dto/list-question-templates-query.dto'; +import { UpdateQuestionTemplateDto } from './dto/update-question-template.dto'; +import { NormalizedQuestion, validateQuestionSet } from './question-set.validator'; + +const DEFAULT_PAGE = 1; +const DEFAULT_SIZE = 20; + +type Client = PrismaService | Prisma.TransactionClient; + +@Injectable() +export class QuestionTemplateService { + constructor(private readonly prisma: PrismaService) {} + + async create(user: JwtPayload, dto: CreateQuestionTemplateDto) { + const companyId = await resolveCompanyId(user, this.prisma); + const questions = validateQuestionSet(dto.questions); + + const template = await this.prisma.questionTemplate.create({ + data: { + companyId, + name: dto.name.trim(), + description: dto.description?.trim() || null, + questions: { create: questions.map(toQuestionData) }, + }, + }); + + return { + templateId: template.id, + version: template.version, + questionCount: questions.length, + status: template.status, + }; + } + + async list(user: JwtPayload, query: ListQuestionTemplatesQueryDto) { + const companyId = await resolveCompanyId(user, this.prisma); + const page = query.page ?? DEFAULT_PAGE; + const size = query.size ?? DEFAULT_SIZE; + const keyword = query.keyword?.trim(); + + const where: Prisma.QuestionTemplateWhereInput = { + companyId, + ...(query.status && { status: query.status }), + ...(keyword && { + OR: [ + { name: { contains: keyword, mode: 'insensitive' } }, + { description: { contains: keyword, mode: 'insensitive' } }, + ], + }), + }; + + const [totalElements, templates] = await this.prisma.$transaction([ + this.prisma.questionTemplate.count({ where }), + this.prisma.questionTemplate.findMany({ + where, + orderBy: [{ updatedAt: 'desc' }, { id: 'asc' }], + skip: (page - 1) * size, + take: size, + include: { _count: { select: { questions: true } } }, + }), + ]); + + return { + items: templates.map((template) => ({ + templateId: template.id, + name: template.name, + version: template.version, + questionCount: template._count.questions, + status: template.status, + updatedAt: template.updatedAt, + })), + page, + size, + totalElements, + }; + } + + async findOne(user: JwtPayload, templateId: string) { + const companyId = await resolveCompanyId(user, this.prisma); + const template = await this.findOwnedTemplate(this.prisma, templateId, companyId); + + return { + templateId: template.id, + name: template.name, + description: template.description, + version: template.version, + status: template.status, + questions: template.questions.map(toQuestionResponse), + }; + } + + /** + * 이름·설명·상태 수정과 질문 전체 교체. + * 질문 내용이 바뀌면 TemplateQuestion을 교체하고 version을 1 올린다. + * 이미 직원에게 발송된 질문지는 발송 시점에 DeclarationQuestionSnapshot으로 복사돼 있으므로 + * 여기서 질문을 지우고 다시 만들어도 발송·제출된 질문지와 답변에는 영향이 없다. + */ + async update(user: JwtPayload, templateId: string, dto: UpdateQuestionTemplateDto) { + const companyId = await resolveCompanyId(user, this.prisma); + // 질문 검증은 트랜잭션 밖에서 먼저 (실패 시 DB를 건드리지 않음) + const questions = dto.questions ? validateQuestionSet(dto.questions) : null; + + return this.prisma.$transaction(async (tx) => { + const template = await this.findOwnedTemplate(tx, templateId, companyId); + + if (dto.version !== template.version) { + throw versionConflict(); + } + + const questionsChanged = !!questions && !isSameQuestionSet(questions, template.questions); + + const data: Prisma.QuestionTemplateUpdateManyMutationInput = { + ...(dto.name !== undefined && { name: dto.name.trim() }), + ...(dto.description !== undefined && { description: dto.description?.trim() || null }), + ...(dto.status !== undefined && { status: dto.status }), + ...(questionsChanged && { version: { increment: 1 } }), + }; + + if (Object.keys(data).length > 0) { + // 조회 이후 다른 요청이 먼저 수정했으면 version이 달라져 0건 → 409 + const { count } = await tx.questionTemplate.updateMany({ + where: { id: templateId, version: dto.version }, + data, + }); + if (count === 0) { + throw versionConflict(); + } + } + + if (questionsChanged) { + await tx.templateQuestion.deleteMany({ where: { templateId } }); + await tx.templateQuestion.createMany({ + data: questions.map((q) => ({ ...toQuestionData(q), templateId })), + }); + } + + return { + templateId, + version: questionsChanged ? template.version + 1 : template.version, + questionCount: questions ? questions.length : template.questions.length, + status: dto.status ?? template.status, + }; + }); + } + + private async findOwnedTemplate( + client: Client, + templateId: string, + companyId: string, + ): Promise { + const template = await client.questionTemplate.findUnique({ + where: { id: templateId }, + include: { questions: { orderBy: { order: 'asc' } } }, + }); + + if (!template) { + throw new NotFoundException({ + code: 'QUESTION_TEMPLATE_NOT_FOUND', + message: '질문 템플릿을 찾을 수 없습니다.', + }); + } + if (template.companyId !== companyId) { + throw new ForbiddenException({ + code: 'FORBIDDEN', + message: '다른 기업의 질문 템플릿에는 접근할 수 없습니다.', + }); + } + + return template; + } +} + +function versionConflict(): ConflictException { + return new ConflictException({ + code: 'TEMPLATE_VERSION_CONFLICT', + message: '질문 템플릿이 이미 수정되었습니다. 최신 버전을 다시 불러와 주세요.', + }); +} + +function toQuestionData(q: NormalizedQuestion) { + return { + order: q.order, + type: q.type, + text: q.text, + required: q.required, + scoreMin: q.scoreMin ?? null, + scoreMax: q.scoreMax ?? null, + // Json? 컬럼은 null 대신 생략해야 DB NULL로 저장된다 + options: q.options, + maxLength: q.maxLength ?? null, + evaluationEnabled: q.evaluationEnabled, + }; +} + +/** 질문 유형에 해당하는 필드만 응답에 포함 (노션 명세 형식) */ +function toQuestionResponse(q: TemplateQuestion) { + 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 string[] | null) ?? [] }), + ...(q.type === 'TEXT' && { maxLength: q.maxLength }), + evaluationEnabled: q.evaluationEnabled, + }; +} + +function isSameQuestionSet(next: NormalizedQuestion[], current: TemplateQuestion[]): boolean { + if (next.length !== current.length) { + return false; + } + const comparable = (q: { + order: number; + type: string; + text: string; + required: boolean; + scoreMin?: number | null; + scoreMax?: number | null; + options?: unknown; + maxLength?: number | null; + evaluationEnabled: boolean; + }) => + JSON.stringify([ + q.order, + q.type, + q.text, + q.required, + q.scoreMin ?? null, + q.scoreMax ?? null, + q.options ?? null, + q.maxLength ?? null, + q.evaluationEnabled, + ]); + + const sortedCurrent = [...current].sort((a, b) => a.order - b.order); + return next.every((q, i) => comparable(q) === comparable(sortedCurrent[i])); +}