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 @@ -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: [
Expand All @@ -25,6 +26,7 @@ import { AuditModule } from './audit/audit.module';
AccessLinkModule,
NotificationModule,
AuditModule,
QuestionTemplateModule,
],
})
export class AppModule {}
31 changes: 31 additions & 0 deletions src/question-template/dto/create-question-template.dto.ts
Original file line number Diff line number Diff line change
@@ -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[];
}
32 changes: 32 additions & 0 deletions src/question-template/dto/list-question-templates-query.dto.ts
Original file line number Diff line number Diff line change
@@ -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;
}
64 changes: 64 additions & 0 deletions src/question-template/dto/question.dto.ts
Original file line number Diff line number Diff line change
@@ -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;
}
47 changes: 47 additions & 0 deletions src/question-template/dto/update-question-template.dto.ts
Original file line number Diff line number Diff line change
@@ -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;
}
121 changes: 121 additions & 0 deletions src/question-template/question-set.validator.spec.ts
Original file line number Diff line number Diff line change
@@ -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> = {}): QuestionDto => ({
order: 1,
type: 'SCORE',
text: '업무 책임감을 평가해 주세요.',
required: true,
scoreMin: 1,
scoreMax: 10,
evaluationEnabled: true,
...over,
});
const choice = (over: Partial<QuestionDto> = {}): QuestionDto => ({
order: 2,
type: 'SINGLE_CHOICE',
text: '선호 업무 방식은 무엇인가요?',
required: true,
options: ['개인 집중', '팀 협업'],
evaluationEnabled: false,
...over,
});
const text = (over: Partial<QuestionDto> = {}): 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);
}
});
});
Loading
Loading