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 @@ -10,6 +10,7 @@ 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';
import { EmployeeModule } from './employee/employee.module';

@Module({
imports: [
Expand All @@ -27,6 +28,7 @@ import { QuestionTemplateModule } from './question-template/question-template.mo
NotificationModule,
AuditModule,
QuestionTemplateModule,
EmployeeModule,
],
})
export class AppModule {}
30 changes: 30 additions & 0 deletions src/employee/dto/create-employee.dto.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { plainToInstance } from 'class-transformer';
import { validateSync } from 'class-validator';
import { CreateEmployeeDto } from './create-employee.dto';

// 전역 ValidationPipe(transform + whitelist + forbidNonWhitelisted)와 같은 순서로 변환 후 검증
function validate(body: Record<string, unknown>) {
const dto = plainToInstance(CreateEmployeeDto, body);
return { dto, errors: validateSync(dto, { whitelist: true, forbidNonWhitelisted: true }) };
}

describe('CreateEmployeeDto', () => {
const base = { name: '김민준', employmentStartDate: '2026-05-09' };

it('앞뒤 공백·대문자가 있는 이메일도 형식 검사 전에 정규화되어 통과한다', () => {
const { dto, errors } = validate({ ...base, email: ' MinJun@Example.COM ' });

expect(errors).toHaveLength(0);
expect(dto.email).toBe('minjun@example.com');
});

it('이메일 형식이 아니면 실패한다', () => {
expect(validate({ ...base, email: 'not-an-email' }).errors).toHaveLength(1);
});

it('입사일은 YYYY-MM-DD 형식만 허용한다', () => {
expect(validate({ ...base, email: 'a@b.com', employmentStartDate: '2026/05/09' }).errors).toHaveLength(1);
expect(validate({ ...base, email: 'a@b.com', employmentStartDate: '2026-05-09T00:00:00Z' }).errors).toHaveLength(1);
expect(validate({ ...base, email: 'a@b.com', employmentStartDate: '2026-02-30' }).errors).toHaveLength(1);
});
});
51 changes: 51 additions & 0 deletions src/employee/dto/create-employee.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import {
IsDateString,
IsEmail,
IsNotEmpty,
IsOptional,
IsString,
Matches,
MaxLength,
} from 'class-validator';

export const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;

export class CreateEmployeeDto {
@ApiProperty({ example: '김민준' })
@IsString()
@IsNotEmpty()
@MaxLength(50)
name!: string;

@ApiProperty({ example: 'minjun@example.com', description: '소문자·공백 제거 후 저장, 기업 내 중복 불가' })
// 형식 검사 전에 정규화해야 앞뒤 공백이 있는 이메일도 통과한다
@Transform(({ value }) => (typeof value === 'string' ? value.trim().toLowerCase() : value))
@IsEmail()
@MaxLength(100)
email!: string;

@ApiPropertyOptional({ example: '010-5555-6666' })
@IsOptional()
@IsString()
@MaxLength(20)
phone?: string;

@ApiPropertyOptional({ example: '프론트엔드 개발팀' })
@IsOptional()
@IsString()
@MaxLength(50)
department?: string;

@ApiPropertyOptional({ example: '과장' })
@IsOptional()
@IsString()
@MaxLength(50)
position?: string;

@ApiProperty({ example: '2026-05-09', description: '입사일 (YYYY-MM-DD)' })
@IsDateString({ strict: true })
@Matches(DATE_ONLY_PATTERN, { message: 'employmentStartDate는 YYYY-MM-DD 형식이어야 합니다.' })
employmentStartDate!: string;
}
37 changes: 37 additions & 0 deletions src/employee/dto/list-employees-query.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { DeclarationStatus, EmploymentStatus } from '@prisma/client';
import { Type } from 'class-transformer';
import { IsEnum, IsInt, IsOptional, IsString, Max, MaxLength, Min } from 'class-validator';

export class ListEmployeesQueryDto {
@ApiPropertyOptional({ enum: EmploymentStatus, description: '재직 상태' })
@IsOptional()
@IsEnum(EmploymentStatus)
status?: EmploymentStatus;

@ApiPropertyOptional({ enum: DeclarationStatus, description: '자기선언 진행 상태' })
@IsOptional()
@IsEnum(DeclarationStatus)
declarationStatus?: DeclarationStatus;

@ApiPropertyOptional({ description: '이름·부서·직급 검색어' })
@IsOptional()
@IsString()
@MaxLength(50)
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;
}
59 changes: 59 additions & 0 deletions src/employee/dto/update-employee.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { ApiHideProperty, ApiPropertyOptional } from '@nestjs/swagger';
import {
IsDateString,
IsNotEmpty,
IsOptional,
IsString,
Matches,
MaxLength,
} from 'class-validator';
import { DATE_ONLY_PATTERN } from './create-employee.dto';

/**
* 수정 가능한 필드는 name, phone, department, position, employmentStartDate뿐이다.
* email은 DTO에 없으므로 보내면 400(forbidNonWhitelisted).
* 재직·선언 상태는 수정 필드가 아니라 차단용으로만 선언한다. 값이 오면 서비스에서
* 명세의 409 INVALID_STATUS_CHANGE로 거절한다(퇴사 전환은 별도 API).
*/
export class UpdateEmployeeDto {
@ApiPropertyOptional({ example: '김민준' })
@IsOptional()
@IsString()
@IsNotEmpty()
@MaxLength(50)
name?: string;

@ApiPropertyOptional({ example: '010-7777-8888', nullable: true, description: 'null이면 삭제' })
@IsOptional()
@IsString()
@MaxLength(20)
phone?: string | null;

@ApiPropertyOptional({ example: '플랫폼 개발팀', nullable: true, description: 'null이면 삭제' })
@IsOptional()
@IsString()
@MaxLength(50)
department?: string | null;

@ApiPropertyOptional({ example: '차장', nullable: true, description: 'null이면 삭제' })
@IsOptional()
@IsString()
@MaxLength(50)
position?: string | null;

@ApiPropertyOptional({ example: '2026-05-09', description: '입사일 (YYYY-MM-DD)' })
@IsOptional()
@IsDateString({ strict: true })
@Matches(DATE_ONLY_PATTERN, { message: 'employmentStartDate는 YYYY-MM-DD 형식이어야 합니다.' })
employmentStartDate?: string;

/** 차단용: 값이 오면 409 INVALID_STATUS_CHANGE */
@ApiHideProperty()
@IsOptional()
employmentStatus?: unknown;

/** 차단용: 값이 오면 409 INVALID_STATUS_CHANGE */
@ApiHideProperty()
@IsOptional()
declarationStatus?: unknown;
}
98 changes: 98 additions & 0 deletions src/employee/employee.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import {
Body,
Controller,
Get,
Headers,
HttpCode,
HttpStatus,
Ip,
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 { CreateEmployeeDto } from './dto/create-employee.dto';
import { ListEmployeesQueryDto } from './dto/list-employees-query.dto';
import { UpdateEmployeeDto } from './dto/update-employee.dto';
import { EmployeeService } from './employee.service';

@ApiTags('Employee')
@ApiBearerAuth('access-token')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('COMPANY')
@Controller('employees')
export class EmployeeController {
constructor(private readonly employeeService: EmployeeService) {}

@Post()
@HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: '대표: 직원 등록 (EMPLOYED / NOT_SENT로 생성)' })
@ApiResponse({ status: 201, description: '등록 성공 { employeeId, employmentStatus, declarationStatus }' })
@ApiResponse({ status: 400, description: '필수값 누락 또는 형식 오류' })
@ApiResponse({ status: 401, description: '인증 필요' })
@ApiResponse({ status: 403, description: 'FORBIDDEN (대표 권한 아님)' })
@ApiResponse({ status: 409, description: 'EMPLOYEE_ALREADY_EXISTS (기업 내 이메일 중복)' })
@ResponseMessage('직원 등록 성공')
create(
@CurrentUser() user: JwtPayload,
@Body() dto: CreateEmployeeDto,
@Ip() ip: string,
@Headers('user-agent') userAgent?: string,
) {
return this.employeeService.create(user, dto, { ip, userAgent });
}

@Get()
@ApiOperation({ summary: '대표: 직원 목록 조회 (재직·선언 상태 필터, 이름·부서·직급 검색, 페이지네이션)' })
@ApiResponse({
status: 200,
description: '조회 성공 { items, page, size, total } — items에 최근 평가의 evaluationId·evaluationStatus·ceoEvaluationDueAt 포함(없으면 null)',
})
@ApiResponse({ status: 400, description: '쿼리 형식 오류' })
@ApiResponse({ status: 401, description: '인증 필요' })
@ApiResponse({ status: 403, description: 'FORBIDDEN (대표 권한 아님)' })
@ResponseMessage('직원 목록 조회 성공')
list(@CurrentUser() user: JwtPayload, @Query() query: ListEmployeesQueryDto) {
return this.employeeService.list(user, query);
}

@Get(':employeeId')
@ApiOperation({ summary: '대표: 직원 상세 조회 (기본 정보 + 최근 자기선언·평가 요약)' })
@ApiParam({ name: 'employeeId', description: '직원 ID' })
@ApiResponse({ status: 200, description: '조회 성공' })
@ApiResponse({ status: 401, description: '인증 필요' })
@ApiResponse({ status: 403, description: 'FORBIDDEN (다른 기업의 직원)' })
@ApiResponse({ status: 404, description: 'EMPLOYEE_NOT_FOUND' })
@ResponseMessage('직원 상세 조회 성공')
findOne(@CurrentUser() user: JwtPayload, @Param('employeeId') employeeId: string) {
return this.employeeService.findOne(user, employeeId);
}

@Patch(':employeeId')
@ApiOperation({ summary: '대표: 직원 정보 수정 (이름·연락처·부서·직급·입사일만, 퇴사 전환은 별도 API)' })
@ApiParam({ name: 'employeeId', description: '직원 ID' })
@ApiResponse({ status: 200, description: '수정 성공' })
@ApiResponse({ status: 400, description: '형식 오류 또는 수정 불가 필드(email 등)' })
@ApiResponse({ status: 401, description: '인증 필요' })
@ApiResponse({ status: 403, description: 'FORBIDDEN (다른 기업의 직원)' })
@ApiResponse({ status: 404, description: 'EMPLOYEE_NOT_FOUND' })
@ApiResponse({ status: 409, description: 'INVALID_STATUS_CHANGE (재직·선언 상태 변경 시도)' })
@ResponseMessage('직원 정보 수정 성공')
update(
@CurrentUser() user: JwtPayload,
@Param('employeeId') employeeId: string,
@Body() dto: UpdateEmployeeDto,
@Ip() ip: string,
@Headers('user-agent') userAgent?: string,
) {
return this.employeeService.update(user, employeeId, dto, { ip, userAgent });
}
}
13 changes: 13 additions & 0 deletions src/employee/employee.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { AuditModule } from '../audit/audit.module';
import { AuthModule } from '../auth/auth.module';
import { EmployeeController } from './employee.controller';
import { EmployeeService } from './employee.service';

@Module({
// JwtAuthGuard가 AuthModule의 RedisService(토큰 블랙리스트)를 사용
imports: [AuthModule, AuditModule],
controllers: [EmployeeController],
providers: [EmployeeService],
})
export class EmployeeModule {}
Loading
Loading