diff --git a/src/employee/dto/resign-employee.dto.ts b/src/employee/dto/resign-employee.dto.ts new file mode 100644 index 0000000..d986ac1 --- /dev/null +++ b/src/employee/dto/resign-employee.dto.ts @@ -0,0 +1,22 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsIn, IsNotEmpty, IsString, Matches } from 'class-validator'; +import { DATE_ONLY_PATTERN } from './create-employee.dto'; + +export const SELF_EVALUATION_SEND_CHANNELS = ['EMAIL'] as const; + +export class ResignEmployeeDto { + @ApiProperty({ example: 'uuid', description: '퇴사 처리할 직원 ID' }) + @IsString() + @IsNotEmpty() + employeeId!: string; + + // 형식(YYYY-MM-DD)만 여기서 400으로 거르고, 달력에 없는 날짜·입사일 이전은 서비스에서 422로 판정 + @ApiProperty({ example: '2026-04-30', description: '퇴사일 (YYYY-MM-DD, 입사일 이후)' }) + @IsString() + @Matches(DATE_ONLY_PATTERN, { message: 'resignationDate는 YYYY-MM-DD 형식이어야 합니다.' }) + resignationDate!: string; + + @ApiProperty({ enum: SELF_EVALUATION_SEND_CHANNELS, example: 'EMAIL', description: '자기평가 링크 발송 채널 (MVP는 EMAIL만)' }) + @IsIn(SELF_EVALUATION_SEND_CHANNELS) + selfEvaluationSendChannel!: (typeof SELF_EVALUATION_SEND_CHANNELS)[number]; +} diff --git a/src/employee/employee-resign.controller.ts b/src/employee/employee-resign.controller.ts new file mode 100644 index 0000000..1ceb574 --- /dev/null +++ b/src/employee/employee-resign.controller.ts @@ -0,0 +1,47 @@ +import { Body, Controller, Headers, HttpCode, HttpStatus, Ip, Post, UseGuards } from '@nestjs/common'; +import { ApiBearerAuth, ApiOperation, 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 { ResignEmployeeDto } from './dto/resign-employee.dto'; +import { EmployeeResignService } from './employee-resign.service'; + +/** + * 신규 흐름의 퇴사 등록. 레거시 src/employment의 같은 라우트(POST /employment/resign)는 이 이슈에서 제거했다. + * 레거시 EmploymentController(@Controller('employment'))의 applicant-confirm은 그대로 남아 있다. + */ +@ApiTags('Employment') +@ApiBearerAuth('access-token') +@UseGuards(JwtAuthGuard, RolesGuard) +@Roles('COMPANY') +@Controller('employment') +export class EmployeeResignController { + constructor(private readonly employeeResignService: EmployeeResignService) {} + + @Post('resign') + @HttpCode(HttpStatus.CREATED) + @ApiOperation({ summary: '대표: 직원 퇴사 등록 및 자기평가 시작 (평가 생성 + 자기평가 링크 메일)' }) + @ApiResponse({ + status: 201, + description: + '등록 성공 { employmentId(=employeeId), evaluationId, employmentStatus, evaluationStatus, selfEvaluationDueAt, ceoEvaluationDueAt, linkSent }', + }) + @ApiResponse({ status: 400, description: '필수값 누락 또는 형식 오류' }) + @ApiResponse({ status: 401, description: '인증 필요' }) + @ApiResponse({ status: 403, description: 'FORBIDDEN (대표 권한 또는 직원 소속 불일치)' }) + @ApiResponse({ status: 404, description: 'EMPLOYEE_NOT_FOUND' }) + @ApiResponse({ status: 409, description: 'ALREADY_RESIGNED / DECLARATION_NOT_SUBMITTED' }) + @ApiResponse({ status: 422, description: 'INVALID_RESIGNATION_DATE (입사일 이전 또는 유효하지 않은 퇴사일)' }) + @ResponseMessage('직원 퇴사 등록 및 자기평가 시작 성공') + resign( + @CurrentUser() user: JwtPayload, + @Body() dto: ResignEmployeeDto, + @Ip() ip: string, + @Headers('user-agent') userAgent?: string, + ) { + return this.employeeResignService.resign(user, dto, { ip, userAgent }); + } +} diff --git a/src/employee/employee-resign.service.spec.ts b/src/employee/employee-resign.service.spec.ts new file mode 100644 index 0000000..4d753b6 --- /dev/null +++ b/src/employee/employee-resign.service.spec.ts @@ -0,0 +1,236 @@ +import { + ConflictException, + ForbiddenException, + HttpException, + NotFoundException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { AccessLinkService } from '../access-link/access-link.service'; +import { AuditService } from '../audit/audit.service'; +import { MailService } from '../notification/mail.service'; +import { PrismaService } from '../prisma/prisma.service'; +import { EmployeeResignService } from './employee-resign.service'; + +const CEO = { sub: 'comp-1', role: 'COMPANY' as const }; +const META = { ip: '127.0.0.1', userAgent: 'jest' }; +const DTO = { employeeId: 'emp-1', resignationDate: '2026-04-30', selfEvaluationSendChannel: 'EMAIL' as const }; + +const employee = (over: Record = {}) => ({ + id: 'emp-1', + companyId: 'comp-1', + name: '김민준', + email: 'minjun@example.com', + employmentStartDate: new Date('2025-01-02T00:00:00.000Z'), + employmentStatus: 'EMPLOYED', + declarationStatus: 'SUBMITTED', + ...over, +}); + +const snapshot = (id: string, order: number, evaluationEnabled: boolean) => ({ + id, declarationId: 'decl-1', order, type: 'SCORE', text: `질문 ${order}`, required: true, + scoreMin: 1, scoreMax: 10, options: null, maxLength: null, evaluationEnabled, +}); + +const submittedDeclaration = (over: Record = {}) => ({ + id: 'decl-1', + employeeId: 'emp-1', + status: 'SUBMITTED', + questions: [snapshot('snap-1', 1, true), snapshot('snap-2', 2, false), snapshot('snap-3', 3, true)], + ...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('EmployeeResignService', () => { + let prismaMock: any; + let accessLinkMock: { issue: jest.Mock }; + let mailMock: { sendSelfEvaluationLink: jest.Mock }; + let auditMock: { log: jest.Mock }; + let service: EmployeeResignService; + let committed: boolean; + + beforeEach(() => { + committed = false; + prismaMock = { + hrManager: { findUnique: jest.fn() }, + employee: { + findUnique: jest.fn().mockResolvedValue(employee()), + updateMany: jest.fn().mockResolvedValue({ count: 1 }), + }, + declaration: { findFirst: jest.fn().mockResolvedValue(submittedDeclaration()) }, + evaluation: { + create: jest.fn(async ({ data }: any) => ({ id: 'ev-1', ...data })), + }, + company: { findUnique: jest.fn().mockResolvedValue({ companyName: '테크플러스' }) }, + $transaction: jest.fn(async (fn: any) => { + const result = await fn(prismaMock); + committed = true; + return result; + }), + }; + accessLinkMock = { issue: jest.fn().mockResolvedValue('raw-token') }; + mailMock = { + sendSelfEvaluationLink: jest.fn(async () => { + // 메일은 트랜잭션 커밋 후에만 나가야 한다 + expect(committed).toBe(true); + return true; + }), + }; + auditMock = { log: jest.fn().mockResolvedValue(undefined) }; + service = new EmployeeResignService( + prismaMock as unknown as PrismaService, + accessLinkMock as unknown as AccessLinkService, + mailMock as unknown as MailService, + auditMock as unknown as AuditService, + ); + }); + + it('퇴사 처리 + SELF_PENDING 평가 생성 + 마감일(+3, +15일 KST 23:59:59) + 자기평가 링크 발급', async () => { + const result = await service.resign(CEO, DTO, META); + + // 2026-04-30 퇴사 → 자기평가 2026-05-03 23:59:59 KST, 대표 검증 2026-05-15 23:59:59 KST + expect(result).toEqual({ + employmentId: 'emp-1', + evaluationId: 'ev-1', + employmentStatus: 'RESIGNED', + evaluationStatus: 'SELF_PENDING', + selfEvaluationDueAt: new Date('2026-05-03T14:59:59.000Z'), + ceoEvaluationDueAt: new Date('2026-05-15T14:59:59.000Z'), + linkSent: true, + }); + + expect(prismaMock.employee.updateMany).toHaveBeenCalledWith({ + where: { id: 'emp-1', employmentStatus: 'EMPLOYED' }, + data: { employmentStatus: 'RESIGNED', resignationDate: new Date('2026-04-30T00:00:00.000Z') }, + }); + + const { data } = prismaMock.evaluation.create.mock.calls[0][0]; + expect(data).toMatchObject({ + companyId: 'comp-1', + employeeId: 'emp-1', + declarationId: 'decl-1', + status: 'SELF_PENDING', + resignationDate: new Date('2026-04-30T00:00:00.000Z'), + selfEvaluationDueAt: new Date('2026-05-03T14:59:59.000Z'), + ceoEvaluationDueAt: new Date('2026-05-15T14:59:59.000Z'), + }); + + expect(accessLinkMock.issue).toHaveBeenCalledWith( + 'SELF_EVALUATION', + 'ev-1', + new Date('2026-05-03T14:59:59.000Z'), + prismaMock, + ); + expect(auditMock.log).toHaveBeenCalledWith( + expect.objectContaining({ action: 'EMPLOYEE_RESIGNED', targetType: 'Employee', targetId: 'emp-1' }), + prismaMock, + ); + expect(mailMock.sendSelfEvaluationLink).toHaveBeenCalledWith({ + to: 'minjun@example.com', + token: 'raw-token', + employeeName: '김민준', + companyName: '테크플러스', + expiresAt: new Date('2026-05-03T14:59:59.000Z'), + }); + }); + + it('evaluationEnabled=false 질문은 평가 항목에서 빼고, 자기선언 순서를 유지하며 점수는 비워 둔다', async () => { + await service.resign(CEO, DTO, META); + + const { data } = prismaMock.evaluation.create.mock.calls[0][0]; + expect(data.items.create).toEqual([ + { snapshotQuestionId: 'snap-1', order: 1 }, + { snapshotQuestionId: 'snap-3', order: 3 }, + ]); + }); + + it('마감일은 월말·연말을 넘겨도 KST 기준으로 계산한다', async () => { + const result = await service.resign(CEO, { ...DTO, resignationDate: '2026-12-30' }, META); + + expect(result.selfEvaluationDueAt).toEqual(new Date('2027-01-02T14:59:59.000Z')); + expect(result.ceoEvaluationDueAt).toEqual(new Date('2027-01-14T14:59:59.000Z')); + }); + + it('메일 발송이 실패해도 커밋된 퇴사·평가 데이터는 유지되고 linkSent=false', async () => { + mailMock.sendSelfEvaluationLink.mockResolvedValue(false); + + const result = await service.resign(CEO, DTO, META); + + expect(result.linkSent).toBe(false); + expect(committed).toBe(true); + expect(prismaMock.evaluation.create).toHaveBeenCalled(); + expect(accessLinkMock.issue).toHaveBeenCalled(); + }); + + describe('에러', () => { + it('다른 기업 직원이면 403 FORBIDDEN', async () => { + prismaMock.employee.findUnique.mockResolvedValue(employee({ companyId: 'comp-other' })); + await expectCode(service.resign(CEO, DTO, META), ForbiddenException, 'FORBIDDEN'); + }); + + it('이미 퇴사한 직원이면 409 ALREADY_RESIGNED', async () => { + prismaMock.employee.findUnique.mockResolvedValue(employee({ employmentStatus: 'RESIGNED' })); + await expectCode(service.resign(CEO, DTO, META), ConflictException, 'ALREADY_RESIGNED'); + }); + + it('동시 요청으로 먼저 퇴사 처리됐으면(갱신 0건) 409 ALREADY_RESIGNED이고 평가를 만들지 않는다', async () => { + prismaMock.employee.updateMany.mockResolvedValue({ count: 0 }); + await expectCode(service.resign(CEO, DTO, META), ConflictException, 'ALREADY_RESIGNED'); + expect(prismaMock.evaluation.create).not.toHaveBeenCalled(); + expect(mailMock.sendSelfEvaluationLink).not.toHaveBeenCalled(); + }); + + it('최근 자기선언이 없거나 미제출(SENT)이면 409 DECLARATION_NOT_SUBMITTED', async () => { + prismaMock.declaration.findFirst.mockResolvedValueOnce(null); + await expectCode(service.resign(CEO, DTO, META), ConflictException, 'DECLARATION_NOT_SUBMITTED'); + + prismaMock.declaration.findFirst.mockResolvedValueOnce(submittedDeclaration({ status: 'SENT' })); + await expectCode(service.resign(CEO, DTO, META), ConflictException, 'DECLARATION_NOT_SUBMITTED'); + + expect(prismaMock.declaration.findFirst).toHaveBeenCalledWith({ + where: { employeeId: 'emp-1' }, + orderBy: { sentAt: 'desc' }, + include: { questions: { orderBy: { order: 'asc' } } }, + }); + expect(prismaMock.$transaction).not.toHaveBeenCalled(); + }); + + it('입사일 이전이거나 달력에 없는 날짜면 422 INVALID_RESIGNATION_DATE', async () => { + await expectCode( + service.resign(CEO, { ...DTO, resignationDate: '2025-01-01' }, META), + UnprocessableEntityException, + 'INVALID_RESIGNATION_DATE', + ); + await expectCode( + service.resign(CEO, { ...DTO, resignationDate: '2026-02-30' }, META), + UnprocessableEntityException, + 'INVALID_RESIGNATION_DATE', + ); + expect(prismaMock.$transaction).not.toHaveBeenCalled(); + }); + + it('입사일 당일 퇴사는 허용한다', async () => { + await expect(service.resign(CEO, { ...DTO, resignationDate: '2025-01-02' }, META)).resolves.toMatchObject({ + employmentStatus: 'RESIGNED', + }); + }); + + it('없는 직원이면 404 EMPLOYEE_NOT_FOUND', async () => { + prismaMock.employee.findUnique.mockResolvedValue(null); + await expectCode(service.resign(CEO, DTO, META), NotFoundException, 'EMPLOYEE_NOT_FOUND'); + }); + }); +}); diff --git a/src/employee/employee-resign.service.ts b/src/employee/employee-resign.service.ts new file mode 100644 index 0000000..8eee69e --- /dev/null +++ b/src/employee/employee-resign.service.ts @@ -0,0 +1,169 @@ +import { + ConflictException, + ForbiddenException, + Injectable, + NotFoundException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { AccessLinkService } from '../access-link/access-link.service'; +import { AuditService } from '../audit/audit.service'; +import { JwtPayload } from '../auth/strategies/jwt.strategy'; +import { resolveCompanyId } from '../core/utils/company-scope'; +import { endOfDayKstAfter } from '../core/utils/kst-date'; +import { MailService } from '../notification/mail.service'; +import { PrismaService } from '../prisma/prisma.service'; +import { ResignEmployeeDto } from './dto/resign-employee.dto'; +import { RequestMeta } from './employee.service'; + +/** 자기평가 마감 = 퇴사일 + 3일, 대표 검증 마감 = 퇴사일 + 15일 (KST 23:59:59) */ +export const SELF_EVALUATION_DUE_DAYS = 3; +export const CEO_EVALUATION_DUE_DAYS = 15; + +/** + * 신규 흐름의 퇴사 등록 (Employee 기준). + * 레거시 EmploymentService.resign(Applicant/Employment 기준)을 대체한다. + */ +@Injectable() +export class EmployeeResignService { + constructor( + private readonly prisma: PrismaService, + private readonly accessLinkService: AccessLinkService, + private readonly mailService: MailService, + private readonly auditService: AuditService, + ) {} + + async resign(user: JwtPayload, dto: ResignEmployeeDto, meta: RequestMeta) { + const companyId = await resolveCompanyId(user, this.prisma); + + const employee = await this.prisma.employee.findUnique({ where: { id: dto.employeeId } }); + if (!employee) { + throw new NotFoundException({ code: 'EMPLOYEE_NOT_FOUND', message: '직원을 찾을 수 없습니다.' }); + } + if (employee.companyId !== companyId) { + throw new ForbiddenException({ + code: 'FORBIDDEN', + message: '다른 기업의 직원은 퇴사 처리할 수 없습니다.', + }); + } + if (employee.employmentStatus === 'RESIGNED') { + throw alreadyResigned(); + } + + // 평가 항목은 가장 최근 자기선언의 질문 스냅샷으로 만든다 + const declaration = await this.prisma.declaration.findFirst({ + where: { employeeId: employee.id }, + orderBy: { sentAt: 'desc' }, + include: { questions: { orderBy: { order: 'asc' } } }, + }); + if (!declaration || declaration.status !== 'SUBMITTED') { + throw new ConflictException({ + code: 'DECLARATION_NOT_SUBMITTED', + message: '입사 자기선언을 제출한 직원만 퇴사 평가를 시작할 수 있습니다.', + }); + } + + const resignationDate = parseResignationDate(dto.resignationDate); + if (!resignationDate || resignationDate < employee.employmentStartDate) { + throw new UnprocessableEntityException({ + code: 'INVALID_RESIGNATION_DATE', + message: '퇴사일이 유효하지 않거나 입사일보다 이릅니다.', + }); + } + + const selfEvaluationDueAt = endOfDayKstAfter(resignationDate, SELF_EVALUATION_DUE_DAYS); + const ceoEvaluationDueAt = endOfDayKstAfter(resignationDate, CEO_EVALUATION_DUE_DAYS); + const evaluationQuestions = declaration.questions.filter((q) => q.evaluationEnabled); + + // 트랜잭션 안에서는 데이터와 링크 저장만 한다. 메일은 커밋 후. + const { evaluation, token } = await this.prisma.$transaction(async (tx) => { + // 동시에 두 번 요청해도 한 번만 퇴사 처리되도록 재직 중일 때만 갱신 + const { count } = await tx.employee.updateMany({ + where: { id: employee.id, employmentStatus: 'EMPLOYED' }, + data: { employmentStatus: 'RESIGNED', resignationDate }, + }); + if (count === 0) { + throw alreadyResigned(); + } + + const created = await tx.evaluation.create({ + data: { + companyId, + employeeId: employee.id, + declarationId: declaration.id, + status: 'SELF_PENDING', + resignationDate, + selfEvaluationDueAt, + ceoEvaluationDueAt, + // evaluationEnabled=true 질문만 평가 항목으로, 자기선언 순서 유지, 점수는 비워 둔다 + items: { + create: evaluationQuestions.map((q) => ({ snapshotQuestionId: q.id, order: q.order })), + }, + }, + }); + + const issuedToken = await this.accessLinkService.issue( + 'SELF_EVALUATION', + created.id, + selfEvaluationDueAt, + tx, + ); + + await this.auditService.log( + { + actorType: 'COMPANY', + actorId: user.sub, + action: 'EMPLOYEE_RESIGNED', + targetType: 'Employee', + targetId: employee.id, + ip: meta.ip, + userAgent: meta.userAgent, + metadata: { + evaluationId: created.id, + resignationDate: dto.resignationDate, + evaluationItemCount: evaluationQuestions.length, + }, + }, + tx, + ); + + return { evaluation: created, token: issuedToken }; + }); + + // 커밋 후 발송. 실패해도 퇴사·평가 데이터는 유지되고 linkSent=false로 알린다. + const company = await this.prisma.company.findUnique({ + where: { id: companyId }, + select: { companyName: true }, + }); + const linkSent = await this.mailService.sendSelfEvaluationLink({ + to: employee.email, + token, + employeeName: employee.name, + companyName: company?.companyName, + expiresAt: selfEvaluationDueAt, + }); + + return { + // 명세 필드명은 employmentId지만 신규 흐름에는 Employment가 없으므로 employeeId를 담는다 + employmentId: employee.id, + evaluationId: evaluation.id, + employmentStatus: 'RESIGNED' as const, + evaluationStatus: evaluation.status, + selfEvaluationDueAt, + ceoEvaluationDueAt, + linkSent, + }; + } +} + +function alreadyResigned(): ConflictException { + return new ConflictException({ code: 'ALREADY_RESIGNED', message: '이미 퇴사 처리된 직원입니다.' }); +} + +/** 'YYYY-MM-DD' → UTC 자정 Date. 달력에 없는 날짜(2026-02-30 등)는 null */ +function parseResignationDate(value: string): Date | null { + const date = new Date(`${value}T00:00:00.000Z`); + if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value) { + return null; + } + return date; +} diff --git a/src/employee/employee.module.ts b/src/employee/employee.module.ts index 9962f22..1b8b80f 100644 --- a/src/employee/employee.module.ts +++ b/src/employee/employee.module.ts @@ -1,13 +1,17 @@ import { Module } from '@nestjs/common'; +import { AccessLinkModule } from '../access-link/access-link.module'; import { AuditModule } from '../audit/audit.module'; import { AuthModule } from '../auth/auth.module'; +import { NotificationModule } from '../notification/notification.module'; +import { EmployeeResignController } from './employee-resign.controller'; +import { EmployeeResignService } from './employee-resign.service'; import { EmployeeController } from './employee.controller'; import { EmployeeService } from './employee.service'; @Module({ // JwtAuthGuard가 AuthModule의 RedisService(토큰 블랙리스트)를 사용 - imports: [AuthModule, AuditModule], - controllers: [EmployeeController], - providers: [EmployeeService], + imports: [AuthModule, AuditModule, AccessLinkModule, NotificationModule], + controllers: [EmployeeController, EmployeeResignController], + providers: [EmployeeService, EmployeeResignService], }) export class EmployeeModule {} diff --git a/src/employment/dto/resign.dto.ts b/src/employment/dto/resign.dto.ts deleted file mode 100644 index 166999b..0000000 --- a/src/employment/dto/resign.dto.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; -import { IsDateString, IsOptional, IsString, IsUUID } from 'class-validator'; - -export class ResignDto { - @ApiProperty({ description: '퇴사 처리할 지원자 ID' }) - @IsUUID() - applicantId: string; - - @ApiProperty({ description: '퇴사일 (ISO 8601)', example: '2026-05-26' }) - @IsDateString() - resignationDate: string; - - @ApiPropertyOptional({ description: '퇴사 사유' }) - @IsOptional() - @IsString() - reason?: string; -} diff --git a/src/employment/employment.controller.ts b/src/employment/employment.controller.ts index f3c6967..8a38add 100644 --- a/src/employment/employment.controller.ts +++ b/src/employment/employment.controller.ts @@ -5,7 +5,6 @@ import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { JwtPayload } from '../auth/strategies/jwt.strategy'; import { ResponseMessage } from '../common/decorators/response-message.decorator'; import { EmploymentService } from './employment.service'; -import { ResignDto } from './dto/resign.dto'; import { ApplicantConfirmDto } from './dto/applicant-confirm.dto'; @ApiTags('Employment') @@ -15,22 +14,6 @@ import { ApplicantConfirmDto } from './dto/applicant-confirm.dto'; export class EmploymentController { constructor(private readonly employmentService: EmploymentService) {} - @Post('resign') - @HttpCode(HttpStatus.CREATED) - @ApiOperation({ summary: '대표: 직원 퇴사 등록 및 평가 링크 자동 발송' }) - @ApiResponse({ status: 201, description: '퇴사 등록 완료, 평가 링크 발송됨' }) - @ApiResponse({ status: 400, description: '이미 퇴사 등록된 직원' }) - @ApiResponse({ status: 403, description: '권한 없음' }) - @ApiResponse({ status: 404, description: '지원자를 찾을 수 없음' }) - @ResponseMessage('퇴사 등록이 완료되었습니다. 평가 링크가 발송되었습니다.') - async resign(@Body() dto: ResignDto, @Req() req: Request) { - const user = req.user as JwtPayload; - if (user.role !== 'COMPANY') { - throw new ForbiddenException('대표만 퇴사 등록이 가능합니다.'); - } - return this.employmentService.resign(dto, user.sub); - } - @Post(':id/applicant-confirm') @HttpCode(HttpStatus.OK) @ApiOperation({ summary: '지원자: 퇴직 사실 확인 및 2단계 동의 트리거' }) diff --git a/src/employment/employment.service.ts b/src/employment/employment.service.ts index 69eff34..e878220 100644 --- a/src/employment/employment.service.ts +++ b/src/employment/employment.service.ts @@ -7,7 +7,6 @@ import { import { PrismaService } from '../prisma/prisma.service'; import { LinkService } from '../link/link.service'; import { EmailService } from '../auth/email/email.service'; -import { ResignDto } from './dto/resign.dto'; @Injectable() export class EmploymentService { @@ -17,59 +16,6 @@ export class EmploymentService { private readonly emailService: EmailService, ) {} - async resign(dto: ResignDto, companyId: string): Promise { - const applicant = await this.prisma.applicant.findUnique({ - where: { id: dto.applicantId }, - }); - if (!applicant) { - throw new NotFoundException('지원자를 찾을 수 없습니다.'); - } - - const existing = await this.prisma.employment.findFirst({ - where: { applicantId: dto.applicantId, companyId }, - }); - if (existing) { - throw new BadRequestException('이미 퇴사 등록된 직원입니다.'); - } - - const employment = await this.prisma.employment.create({ - data: { - applicantId: dto.applicantId, - companyId, - resignationDate: new Date(dto.resignationDate), - reason: dto.reason, - status: 'resigned', - }, - }); - - const expiresAt = new Date(); - expiresAt.setDate(expiresAt.getDate() + 7); - - const token = await this.linkService.generateToken(employment.id); - - await this.prisma.evaluationLink.create({ - data: { - employmentId: employment.id, - token, - expiresAt, - }, - }); - - // 직원 이메일로 평가 링크 발송 - try { - await this.emailService.sendEvaluationLinkEmail(applicant.email, token); - } catch { - // 이메일 발송 실패 시 로그는 EmailService 내부에서 처리 - } - - return { - employmentId: employment.id, - status: employment.status, - resignationDate: employment.resignationDate, - linkExpiredAt: expiresAt, - }; - } - async applicantConfirm(id: string, confirmed: boolean, applicantId: string): Promise { const employment = await this.prisma.employment.findUnique({ where: { id },