diff --git a/src/app.module.ts b/src/app.module.ts index 6666fa9..62de0a8 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -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: [ @@ -27,6 +28,7 @@ import { QuestionTemplateModule } from './question-template/question-template.mo NotificationModule, AuditModule, QuestionTemplateModule, + EmployeeModule, ], }) export class AppModule {} diff --git a/src/employee/dto/create-employee.dto.spec.ts b/src/employee/dto/create-employee.dto.spec.ts new file mode 100644 index 0000000..71a3a98 --- /dev/null +++ b/src/employee/dto/create-employee.dto.spec.ts @@ -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) { + 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); + }); +}); diff --git a/src/employee/dto/create-employee.dto.ts b/src/employee/dto/create-employee.dto.ts new file mode 100644 index 0000000..10130eb --- /dev/null +++ b/src/employee/dto/create-employee.dto.ts @@ -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; +} diff --git a/src/employee/dto/list-employees-query.dto.ts b/src/employee/dto/list-employees-query.dto.ts new file mode 100644 index 0000000..a3dad26 --- /dev/null +++ b/src/employee/dto/list-employees-query.dto.ts @@ -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; +} diff --git a/src/employee/dto/update-employee.dto.ts b/src/employee/dto/update-employee.dto.ts new file mode 100644 index 0000000..6cddc18 --- /dev/null +++ b/src/employee/dto/update-employee.dto.ts @@ -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; +} diff --git a/src/employee/employee.controller.ts b/src/employee/employee.controller.ts new file mode 100644 index 0000000..d5b7279 --- /dev/null +++ b/src/employee/employee.controller.ts @@ -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 }); + } +} diff --git a/src/employee/employee.module.ts b/src/employee/employee.module.ts new file mode 100644 index 0000000..9962f22 --- /dev/null +++ b/src/employee/employee.module.ts @@ -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 {} diff --git a/src/employee/employee.service.spec.ts b/src/employee/employee.service.spec.ts new file mode 100644 index 0000000..d081198 --- /dev/null +++ b/src/employee/employee.service.spec.ts @@ -0,0 +1,323 @@ +import { + ConflictException, + ForbiddenException, + HttpException, + NotFoundException, +} from '@nestjs/common'; +import { Prisma } from '@prisma/client'; +import { AuditService } from '../audit/audit.service'; +import { PrismaService } from '../prisma/prisma.service'; +import { EmployeeService } from './employee.service'; + +const CEO = { sub: 'comp-1', role: 'COMPANY' as const }; +const META = { ip: '127.0.0.1', userAgent: 'jest' }; + +const storedEmployee = (over: Record = {}) => ({ + id: 'emp-1', + companyId: 'comp-1', + name: '김민준', + email: 'minjun@example.com', + phone: '010-5555-6666', + department: '개발팀', + position: '과장', + employmentStartDate: new Date('2026-05-09T00:00:00.000Z'), + employmentStatus: 'EMPLOYED', + declarationStatus: 'NOT_SENT', + resignationDate: null, + createdAt: new Date('2026-10-01T00:00:00Z'), + updatedAt: new Date('2026-10-01T00:00:00Z'), + ...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('EmployeeService', () => { + let prismaMock: any; + let auditMock: { log: jest.Mock }; + let service: EmployeeService; + + beforeEach(() => { + prismaMock = { + hrManager: { findUnique: jest.fn() }, + employee: { + findUnique: jest.fn(), + create: jest.fn(), + count: jest.fn(), + findMany: jest.fn(), + update: jest.fn(), + }, + $transaction: jest.fn(async (arg: any) => + typeof arg === 'function' ? arg(prismaMock) : Promise.all(arg), + ), + }; + auditMock = { log: jest.fn().mockResolvedValue(undefined) }; + service = new EmployeeService( + prismaMock as unknown as PrismaService, + auditMock as unknown as AuditService, + ); + }); + + describe('create', () => { + const dto = { + name: ' 김민준 ', + email: ' MinJun@Example.COM ', + phone: '010-5555-6666', + department: '', + employmentStartDate: '2026-05-09', + }; + + it('이메일을 정규화해 EMPLOYED/NOT_SENT로 만들고 감사 로그를 같은 트랜잭션에 남긴다', async () => { + prismaMock.employee.findUnique.mockResolvedValue(null); + prismaMock.employee.create.mockResolvedValue(storedEmployee()); + + const result = await service.create(CEO, dto, META); + + expect(result).toEqual({ employeeId: 'emp-1', employmentStatus: 'EMPLOYED', declarationStatus: 'NOT_SENT' }); + expect(prismaMock.employee.findUnique).toHaveBeenCalledWith({ + where: { companyId_email: { companyId: 'comp-1', email: 'minjun@example.com' } }, + select: { id: true }, + }); + expect(prismaMock.employee.create).toHaveBeenCalledWith({ + data: { + companyId: 'comp-1', + name: '김민준', + email: 'minjun@example.com', + phone: '010-5555-6666', + department: null, + position: null, + employmentStartDate: new Date('2026-05-09T00:00:00.000Z'), + employmentStatus: 'EMPLOYED', + declarationStatus: 'NOT_SENT', + }, + }); + expect(auditMock.log).toHaveBeenCalledWith( + expect.objectContaining({ + actorType: 'COMPANY', + actorId: 'comp-1', + action: 'EMPLOYEE_CREATED', + targetType: 'Employee', + targetId: 'emp-1', + ip: '127.0.0.1', + userAgent: 'jest', + }), + prismaMock, + ); + }); + + it('같은 기업에 같은 이메일(대소문자 무시)이 있으면 409 EMPLOYEE_ALREADY_EXISTS', async () => { + prismaMock.employee.findUnique.mockResolvedValue({ id: 'emp-0' }); + + await expectCode(service.create(CEO, dto, META), ConflictException, 'EMPLOYEE_ALREADY_EXISTS'); + expect(prismaMock.employee.create).not.toHaveBeenCalled(); + expect(auditMock.log).not.toHaveBeenCalled(); + }); + + it('동시 등록으로 unique 제약에 걸려도 409 EMPLOYEE_ALREADY_EXISTS', async () => { + prismaMock.employee.findUnique.mockResolvedValue(null); + prismaMock.employee.create.mockRejectedValue( + new Prisma.PrismaClientKnownRequestError('Unique constraint failed', { + code: 'P2002', + clientVersion: '5.22.0', + }), + ); + + await expectCode(service.create(CEO, dto, META), ConflictException, 'EMPLOYEE_ALREADY_EXISTS'); + }); + }); + + describe('list', () => { + it('본인 기업 + 상태·선언상태·검색어 필터와 페이지네이션을 적용한다', async () => { + prismaMock.employee.count.mockResolvedValue(48); + prismaMock.employee.findMany.mockResolvedValue([]); + + const result = await service.list(CEO, { + status: 'RESIGNED', + declarationStatus: 'SUBMITTED', + keyword: ' 개발 ', + page: 3, + size: 10, + }); + + const args = prismaMock.employee.findMany.mock.calls[0][0]; + const expectedWhere = { + companyId: 'comp-1', + employmentStatus: 'RESIGNED', + declarationStatus: 'SUBMITTED', + OR: [ + { name: { contains: '개발', mode: 'insensitive' } }, + { department: { contains: '개발', mode: 'insensitive' } }, + { position: { contains: '개발', mode: 'insensitive' } }, + ], + }; + expect(args.where).toEqual(expectedWhere); + expect(prismaMock.employee.count).toHaveBeenCalledWith({ where: expectedWhere }); + expect(args.skip).toBe(20); + expect(args.take).toBe(10); + expect(result).toEqual({ items: [], page: 3, size: 10, total: 48 }); + }); + + it('page·size 기본값은 1·20이고 필터가 없으면 companyId만 건다', async () => { + prismaMock.employee.count.mockResolvedValue(0); + prismaMock.employee.findMany.mockResolvedValue([]); + + const result = await service.list(CEO, {}); + + expect(prismaMock.employee.findMany.mock.calls[0][0]).toMatchObject({ + where: { companyId: 'comp-1' }, + skip: 0, + take: 20, + }); + expect(result).toMatchObject({ page: 1, size: 20, total: 0 }); + }); + + it('items에 최근 평가의 id·상태·대표 마감을 넣고, 평가가 없으면 null (이메일·점수 미포함)', async () => { + prismaMock.employee.count.mockResolvedValue(2); + prismaMock.employee.findMany.mockResolvedValue([ + { ...storedEmployee(), evaluations: [] }, + { + ...storedEmployee({ id: 'emp-2', employmentStatus: 'RESIGNED', declarationStatus: 'SUBMITTED' }), + evaluations: [{ id: 'ev-9', status: 'CEO_PENDING', ceoEvaluationDueAt: new Date('2026-05-15T14:59:59Z') }], + }, + ]); + + const { items } = await service.list(CEO, {}); + + expect(items).toEqual([ + { + employeeId: 'emp-1', name: '김민준', department: '개발팀', position: '과장', + employmentStatus: 'EMPLOYED', declarationStatus: 'NOT_SENT', + evaluationId: null, evaluationStatus: null, ceoEvaluationDueAt: null, + }, + { + employeeId: 'emp-2', name: '김민준', department: '개발팀', position: '과장', + employmentStatus: 'RESIGNED', declarationStatus: 'SUBMITTED', + evaluationId: 'ev-9', evaluationStatus: 'CEO_PENDING', ceoEvaluationDueAt: new Date('2026-05-15T14:59:59Z'), + }, + ]); + expect(prismaMock.employee.findMany.mock.calls[0][0].include.evaluations).toEqual({ + orderBy: { createdAt: 'desc' }, + take: 1, + select: { id: true, status: true, ceoEvaluationDueAt: true }, + }); + }); + }); + + describe('findOne', () => { + it('기본 정보와 최근 자기선언·평가 요약을 반환한다', async () => { + prismaMock.employee.findUnique.mockResolvedValue({ + ...storedEmployee({ declarationStatus: 'SUBMITTED' }), + declarations: [{ id: 'decl-1', status: 'SUBMITTED', sentAt: new Date('2026-05-10T00:00:00Z'), submittedAt: new Date('2026-05-11T00:00:00Z') }], + evaluations: [], + }); + + const result = await service.findOne(CEO, 'emp-1'); + + expect(result).toMatchObject({ + employeeId: 'emp-1', + email: 'minjun@example.com', + employmentStartDate: '2026-05-09', + resignationDate: null, + declarationStatus: 'SUBMITTED', + evaluationStatus: null, + declaration: { declarationId: 'decl-1', status: 'SUBMITTED' }, + evaluation: null, + }); + }); + + it('없으면 404 EMPLOYEE_NOT_FOUND, 다른 기업 직원이면 403 FORBIDDEN', async () => { + prismaMock.employee.findUnique.mockResolvedValueOnce(null); + await expectCode(service.findOne(CEO, 'nope'), NotFoundException, 'EMPLOYEE_NOT_FOUND'); + + prismaMock.employee.findUnique.mockResolvedValueOnce({ + ...storedEmployee({ companyId: 'comp-other' }), declarations: [], evaluations: [], + }); + await expectCode(service.findOne(CEO, 'emp-1'), ForbiddenException, 'FORBIDDEN'); + }); + }); + + describe('update', () => { + beforeEach(() => { + prismaMock.employee.findUnique.mockResolvedValue(storedEmployee()); + prismaMock.employee.update.mockImplementation(async ({ data }: any) => storedEmployee(data)); + }); + + it('바뀐 필드만 저장하고 변경 전후를 감사 로그에 남긴다', async () => { + const result = await service.update( + CEO, + 'emp-1', + { department: '플랫폼 개발팀', position: '과장', phone: null, employmentStartDate: '2026-05-01' }, + META, + ); + + expect(prismaMock.employee.update).toHaveBeenCalledWith({ + where: { id: 'emp-1' }, + data: { + phone: null, + department: '플랫폼 개발팀', + employmentStartDate: new Date('2026-05-01T00:00:00.000Z'), + }, + }); + expect(auditMock.log).toHaveBeenCalledWith( + expect.objectContaining({ + action: 'EMPLOYEE_UPDATED', + targetId: 'emp-1', + metadata: { + before: { phone: '010-5555-6666', department: '개발팀', employmentStartDate: '2026-05-09' }, + after: { phone: null, department: '플랫폼 개발팀', employmentStartDate: '2026-05-01' }, + }, + }), + prismaMock, + ); + expect(result).toMatchObject({ + employeeId: 'emp-1', + department: '플랫폼 개발팀', + position: '과장', + phone: null, + employmentStartDate: '2026-05-01', + }); + }); + + it('바뀐 값이 없으면 저장·감사 로그를 남기지 않는다', async () => { + await service.update(CEO, 'emp-1', { name: '김민준', department: '개발팀' }, META); + + expect(prismaMock.employee.update).not.toHaveBeenCalled(); + expect(auditMock.log).not.toHaveBeenCalled(); + }); + + it('재직·선언 상태를 바꾸려 하면 409 INVALID_STATUS_CHANGE', async () => { + await expectCode( + service.update(CEO, 'emp-1', { employmentStatus: 'RESIGNED' }, META), + ConflictException, + 'INVALID_STATUS_CHANGE', + ); + await expectCode( + service.update(CEO, 'emp-1', { declarationStatus: 'SUBMITTED' }, META), + ConflictException, + 'INVALID_STATUS_CHANGE', + ); + expect(prismaMock.employee.update).not.toHaveBeenCalled(); + }); + + it('다른 기업 직원은 403, 없는 직원은 404', async () => { + prismaMock.employee.findUnique.mockResolvedValueOnce(storedEmployee({ companyId: 'comp-other' })); + await expectCode(service.update(CEO, 'emp-1', { name: 'x' }, META), ForbiddenException, 'FORBIDDEN'); + + prismaMock.employee.findUnique.mockResolvedValueOnce(null); + await expectCode(service.update(CEO, 'nope', { name: 'x' }, META), NotFoundException, 'EMPLOYEE_NOT_FOUND'); + expect(prismaMock.employee.update).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/src/employee/employee.service.ts b/src/employee/employee.service.ts new file mode 100644 index 0000000..1fa899a --- /dev/null +++ b/src/employee/employee.service.ts @@ -0,0 +1,330 @@ +import { + ConflictException, + ForbiddenException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { Employee, Prisma } from '@prisma/client'; +import { JwtPayload } from '../auth/strategies/jwt.strategy'; +import { AuditService } from '../audit/audit.service'; +import { resolveCompanyId } from '../core/utils/company-scope'; +import { PrismaService } from '../prisma/prisma.service'; +import { CreateEmployeeDto } from './dto/create-employee.dto'; +import { ListEmployeesQueryDto } from './dto/list-employees-query.dto'; +import { UpdateEmployeeDto } from './dto/update-employee.dto'; + +const DEFAULT_PAGE = 1; +const DEFAULT_SIZE = 20; + +export interface RequestMeta { + ip?: string | null; + userAgent?: string | null; +} + +/** 감사 로그에 변경 전후를 남기는 수정 가능 필드 */ +const UPDATABLE_FIELDS = ['name', 'phone', 'department', 'position', 'employmentStartDate'] as const; +type UpdatableField = (typeof UPDATABLE_FIELDS)[number]; + +type Client = PrismaService | Prisma.TransactionClient; + +@Injectable() +export class EmployeeService { + constructor( + private readonly prisma: PrismaService, + private readonly auditService: AuditService, + ) {} + + async create(user: JwtPayload, dto: CreateEmployeeDto, meta: RequestMeta) { + const companyId = await resolveCompanyId(user, this.prisma); + // auth와 같은 규칙: 앞뒤 공백 제거 + 소문자 + const email = normalizeEmail(dto.email); + + const existing = await this.prisma.employee.findUnique({ + where: { companyId_email: { companyId, email } }, + select: { id: true }, + }); + if (existing) { + throw employeeAlreadyExists(); + } + + try { + const employee = await this.prisma.$transaction(async (tx) => { + const created = await tx.employee.create({ + data: { + companyId, + name: dto.name.trim(), + email, + phone: blankToNull(dto.phone), + department: blankToNull(dto.department), + position: blankToNull(dto.position), + employmentStartDate: parseDateOnly(dto.employmentStartDate), + employmentStatus: 'EMPLOYED', + declarationStatus: 'NOT_SENT', + }, + }); + + await this.auditService.log( + { + actorType: 'COMPANY', + actorId: user.sub, + action: 'EMPLOYEE_CREATED', + targetType: 'Employee', + targetId: created.id, + ip: meta.ip, + userAgent: meta.userAgent, + }, + tx, + ); + + return created; + }); + + return { + employeeId: employee.id, + employmentStatus: employee.employmentStatus, + declarationStatus: employee.declarationStatus, + }; + } catch (error) { + // 중복 확인 직후 같은 이메일이 동시에 등록된 경우 (companyId, email) unique 위반 + if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') { + throw employeeAlreadyExists(); + } + throw error; + } + } + + async list(user: JwtPayload, query: ListEmployeesQueryDto) { + 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.EmployeeWhereInput = { + companyId, + ...(query.status && { employmentStatus: query.status }), + ...(query.declarationStatus && { declarationStatus: query.declarationStatus }), + ...(keyword && { + OR: [ + { name: { contains: keyword, mode: 'insensitive' } }, + { department: { contains: keyword, mode: 'insensitive' } }, + { position: { contains: keyword, mode: 'insensitive' } }, + ], + }), + }; + + const [total, employees] = await this.prisma.$transaction([ + this.prisma.employee.count({ where }), + this.prisma.employee.findMany({ + where, + orderBy: [{ createdAt: 'desc' }, { id: 'asc' }], + skip: (page - 1) * size, + take: size, + // 대표 평가 화면 진입용으로 최근 평가 1건의 id·상태·마감만 가져온다 (점수 등 민감 데이터 제외) + include: { + evaluations: { + orderBy: { createdAt: 'desc' }, + take: 1, + select: { id: true, status: true, ceoEvaluationDueAt: true }, + }, + }, + }), + ]); + + return { + items: employees.map((employee) => { + const latestEvaluation = employee.evaluations[0] ?? null; + return { + employeeId: employee.id, + name: employee.name, + department: employee.department, + position: employee.position, + employmentStatus: employee.employmentStatus, + declarationStatus: employee.declarationStatus, + evaluationId: latestEvaluation?.id ?? null, + evaluationStatus: latestEvaluation?.status ?? null, + ceoEvaluationDueAt: latestEvaluation?.ceoEvaluationDueAt ?? null, + }; + }), + page, + size, + total, + }; + } + + async findOne(user: JwtPayload, employeeId: string) { + const companyId = await resolveCompanyId(user, this.prisma); + const employee = await this.prisma.employee.findUnique({ + where: { id: employeeId }, + include: { + declarations: { + orderBy: { sentAt: 'desc' }, + take: 1, + select: { id: true, status: true, sentAt: true, submittedAt: true }, + }, + evaluations: { + orderBy: { createdAt: 'desc' }, + take: 1, + select: { + id: true, + status: true, + selfEvaluationDueAt: true, + ceoEvaluationDueAt: true, + opinionDueAt: true, + }, + }, + }, + }); + assertOwned(employee, companyId); + + const declaration = employee.declarations[0] ?? null; + const evaluation = employee.evaluations[0] ?? null; + + return { + employeeId: employee.id, + name: employee.name, + email: employee.email, + phone: employee.phone, + department: employee.department, + position: employee.position, + employmentStartDate: formatDateOnly(employee.employmentStartDate), + resignationDate: employee.resignationDate ? formatDateOnly(employee.resignationDate) : null, + employmentStatus: employee.employmentStatus, + declarationStatus: employee.declarationStatus, + evaluationStatus: evaluation?.status ?? null, + declaration: declaration && { + declarationId: declaration.id, + status: declaration.status, + sentAt: declaration.sentAt, + submittedAt: declaration.submittedAt, + }, + evaluation: evaluation && { + evaluationId: evaluation.id, + status: evaluation.status, + selfEvaluationDueAt: evaluation.selfEvaluationDueAt, + ceoEvaluationDueAt: evaluation.ceoEvaluationDueAt, + opinionDueAt: evaluation.opinionDueAt, + }, + }; + } + + async update(user: JwtPayload, employeeId: string, dto: UpdateEmployeeDto, meta: RequestMeta) { + // 재직·선언 상태는 이 API로 바꿀 수 없다 (퇴사는 별도 API) + if (dto.employmentStatus !== undefined || dto.declarationStatus !== undefined) { + throw new ConflictException({ + code: 'INVALID_STATUS_CHANGE', + message: '재직·자기선언 상태는 이 API로 변경할 수 없습니다.', + }); + } + + const companyId = await resolveCompanyId(user, this.prisma); + + return this.prisma.$transaction(async (tx) => { + const employee = await findOwnedEmployee(tx, employeeId, companyId); + + const next: Partial> = { + ...(dto.name !== undefined && { name: dto.name.trim() }), + ...(dto.phone !== undefined && { phone: blankToNull(dto.phone) }), + ...(dto.department !== undefined && { department: blankToNull(dto.department) }), + ...(dto.position !== undefined && { position: blankToNull(dto.position) }), + ...(dto.employmentStartDate !== undefined && { + employmentStartDate: parseDateOnly(dto.employmentStartDate), + }), + }; + + // 실제로 값이 바뀐 필드만 저장·기록 + const before: Record = {}; + const after: Record = {}; + for (const field of UPDATABLE_FIELDS) { + if (!(field in next)) continue; + const prev = auditValue(employee[field]); + const value = auditValue(next[field] ?? null); + if (prev !== value) { + before[field] = prev; + after[field] = value; + } + } + + let updated = employee; + if (Object.keys(after).length > 0) { + const changes = Object.fromEntries( + Object.keys(after).map((field) => [field, next[field as UpdatableField]]), + ); + updated = await tx.employee.update({ where: { id: employeeId }, data: changes }); + + await this.auditService.log( + { + actorType: 'COMPANY', + actorId: user.sub, + action: 'EMPLOYEE_UPDATED', + targetType: 'Employee', + targetId: employeeId, + ip: meta.ip, + userAgent: meta.userAgent, + metadata: { before, after } as Prisma.InputJsonValue, + }, + tx, + ); + } + + return { + employeeId: updated.id, + name: updated.name, + phone: updated.phone, + department: updated.department, + position: updated.position, + employmentStartDate: formatDateOnly(updated.employmentStartDate), + updatedAt: updated.updatedAt, + }; + }); + } +} + +async function findOwnedEmployee(client: Client, employeeId: string, companyId: string): Promise { + const employee = await client.employee.findUnique({ where: { id: employeeId } }); + assertOwned(employee, companyId); + return employee; +} + +function assertOwned( + employee: T | null, + companyId: string, +): asserts employee is T { + if (!employee) { + throw new NotFoundException({ code: 'EMPLOYEE_NOT_FOUND', message: '직원을 찾을 수 없습니다.' }); + } + if (employee.companyId !== companyId) { + throw new ForbiddenException({ + code: 'FORBIDDEN', + message: '다른 기업의 직원에는 접근할 수 없습니다.', + }); + } +} + +function employeeAlreadyExists(): ConflictException { + return new ConflictException({ + code: 'EMPLOYEE_ALREADY_EXISTS', + message: '이미 등록된 직원 이메일입니다.', + }); +} + +export function normalizeEmail(email: string): string { + return email.trim().toLowerCase(); +} + +function blankToNull(value: string | null | undefined): string | null { + const trimmed = value?.trim(); + return trimmed ? trimmed : null; +} + +/** 'YYYY-MM-DD'를 UTC 자정 Date로 저장 (KST로도 같은 날짜) */ +function parseDateOnly(value: string): Date { + return new Date(`${value}T00:00:00.000Z`); +} + +function formatDateOnly(date: Date): string { + return date.toISOString().slice(0, 10); +} + +function auditValue(value: string | Date | null): string | null { + return value instanceof Date ? formatDateOnly(value) : value; +}