From a83c0588cad0906026d0f775480d1d53ab8044de Mon Sep 17 00:00:00 2001 From: ChaeYeon Lee Date: Fri, 9 Oct 2026 21:46:17 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=9D=B8=EC=9E=AC=20=EC=B6=94=EC=B2=9C?= =?UTF-8?q?=20=EA=B2=8C=EC=8B=9C=20=EB=8F=99=EC=9D=98=20=EC=9A=94=EC=B2=AD?= =?UTF-8?q?=C2=B7=EC=A1=B0=ED=9A=8C=C2=B7=EB=8F=99=EC=9D=98=C2=B7=EC=B2=A0?= =?UTF-8?q?=ED=9A=8C=20API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - POST /referral/consents (대표): 퇴사 직원에게 동의 요청 링크 발송 (기본 7일, 1~30일) - 422 EMPLOYEE_NOT_RESIGNED, 409 ACTIVE_CONSENT_EXISTS, 429 LINK_RATE_LIMITED(24시간 3회) - GET /referral/consents/:token (직원): 목적·공개 항목·게시 기간·현재 상태 - PATCH /referral/consents/:token/agree: PENDING → AGREED (시각·IP·UA), 링크는 철회용으로 유지 - PATCH /referral/consents/:token/withdraw: PENDING·AGREED → WITHDRAWN, 연결된 공개 게시물 HIDDEN - 동의 후 링크 만료를 1년으로 연장 (AccessLinkService.extend 추가) — 동의 요청 기한 후에도 철회 가능 - ReferralExpiryScheduler(매시간): 기한 지난 PENDING → EXPIRED Co-Authored-By: Claude Opus 5.5 --- src/access-link/access-link.service.spec.ts | 25 +- src/access-link/access-link.service.ts | 11 + src/app.module.ts | 2 + .../dto/create-referral-consent.dto.ts | 50 +++ .../dto/referral-consent-decision.dto.ts | 24 ++ src/referral/referral-consent.controller.ts | 93 +++++ src/referral/referral-consent.service.spec.ts | 329 +++++++++++++++++ src/referral/referral-consent.service.ts | 347 ++++++++++++++++++ .../referral-expiry.scheduler.spec.ts | 51 +++ src/referral/referral-expiry.scheduler.ts | 35 ++ src/referral/referral.constants.ts | 22 ++ src/referral/referral.module.ts | 17 + 12 files changed, 1005 insertions(+), 1 deletion(-) create mode 100644 src/referral/dto/create-referral-consent.dto.ts create mode 100644 src/referral/dto/referral-consent-decision.dto.ts create mode 100644 src/referral/referral-consent.controller.ts create mode 100644 src/referral/referral-consent.service.spec.ts create mode 100644 src/referral/referral-consent.service.ts create mode 100644 src/referral/referral-expiry.scheduler.spec.ts create mode 100644 src/referral/referral-expiry.scheduler.ts create mode 100644 src/referral/referral.constants.ts create mode 100644 src/referral/referral.module.ts diff --git a/src/access-link/access-link.service.spec.ts b/src/access-link/access-link.service.spec.ts index 5a98061..0136d70 100644 --- a/src/access-link/access-link.service.spec.ts +++ b/src/access-link/access-link.service.spec.ts @@ -11,7 +11,11 @@ import { PrismaService } from '../prisma/prisma.service'; function createFakeDb() { const links: any[] = []; const matches = (link: any, where: Record) => - Object.entries(where).every(([key, value]) => link[key] === value); + Object.entries(where).every(([key, value]) => + value && typeof value === 'object' && 'lt' in value + ? link[key] < (value as { lt: Date }).lt + : link[key] === value, + ); const accessLink = { create: jest.fn(async ({ data }: any) => { @@ -161,4 +165,23 @@ describe('AccessLinkService', () => { }); expect(db.client.accessLink.findUnique).not.toHaveBeenCalled(); }); + + it('extend는 미사용·미폐기 링크의 만료만 늦추고, 앞당기지는 않는다', async () => { + const base = future(); + const later = new Date(base.getTime() + 24 * 60 * 60 * 1000); + const earlier = new Date(base.getTime() - 60 * 1000); + await service.issue('REFERRAL_CONSENT', 'c-1', base, tx); + await service.issue('REFERRAL_CONSENT', 'c-2', base, tx); + await service.issue('REFERRAL_CONSENT', 'c-3', base, tx); + db.links[1].usedAt = new Date(); + db.links[2].revokedAt = new Date(); + + await service.extend('link-1', later, tx); + await service.extend('link-2', later, tx); + await service.extend('link-3', later, tx); + expect(db.links.map((l) => l.expiresAt)).toEqual([later, base, base]); + + await service.extend('link-1', earlier, tx); + expect(db.links[0].expiresAt).toEqual(later); + }); }); diff --git a/src/access-link/access-link.service.ts b/src/access-link/access-link.service.ts index 4d3759b..d88b78f 100644 --- a/src/access-link/access-link.service.ts +++ b/src/access-link/access-link.service.ts @@ -108,6 +108,17 @@ export class AccessLinkService { return count; } + + /** + * 사용·폐기되지 않은 링크의 만료 시각을 늦춘다(앞당기지는 않는다). + * 예: 추천 동의 후 같은 링크로 나중에 철회할 수 있도록 유효 기간 연장. + */ + async extend(linkId: string, expiresAt: Date, tx: Tx): Promise { + await tx.accessLink.updateMany({ + where: { id: linkId, usedAt: null, revokedAt: null, expiresAt: { lt: expiresAt } }, + data: { expiresAt }, + }); + } } function linkExpired(): GoneException { diff --git a/src/app.module.ts b/src/app.module.ts index 1dea193..b67758b 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -13,6 +13,7 @@ import { QuestionTemplateModule } from './question-template/question-template.mo import { EmployeeModule } from './employee/employee.module'; import { DeclarationModule } from './declaration/declaration.module'; import { EvaluationsModule } from './evaluations/evaluations.module'; +import { ReferralModule } from './referral/referral.module'; @Module({ imports: [ @@ -33,6 +34,7 @@ import { EvaluationsModule } from './evaluations/evaluations.module'; EmployeeModule, DeclarationModule, EvaluationsModule, + ReferralModule, ], }) export class AppModule {} diff --git a/src/referral/dto/create-referral-consent.dto.ts b/src/referral/dto/create-referral-consent.dto.ts new file mode 100644 index 0000000..403fe8a --- /dev/null +++ b/src/referral/dto/create-referral-consent.dto.ts @@ -0,0 +1,50 @@ +import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; +import { DisplayNameMode } from '@prisma/client'; +import { Type } from 'class-transformer'; +import { + ArrayNotEmpty, + ArrayUnique, + IsArray, + IsEnum, + IsIn, + IsInt, + IsNotEmpty, + IsOptional, + IsString, + Max, + Min, +} from 'class-validator'; +import { CONSENT_EXPIRES_IN_DAYS } from '../referral.constants'; + +export const CONSENT_CHANNELS = ['EMAIL'] as const; + +export class CreateReferralConsentDto { + @ApiProperty({ example: 'uuid', description: '추천할 퇴사 직원 ID' }) + @IsString() + @IsNotEmpty() + employeeId!: string; + + @ApiProperty({ enum: CONSENT_CHANNELS, isArray: true, example: ['EMAIL'], description: '발송 채널 (MVP는 EMAIL만)' }) + @IsArray() + @ArrayNotEmpty() + @ArrayUnique() + @IsIn(CONSENT_CHANNELS, { each: true }) + channels!: (typeof CONSENT_CHANNELS)[number][]; + + @ApiProperty({ enum: DisplayNameMode, example: 'REAL_NAME', description: '게시물에 이름을 실명/익명으로 표시' }) + @IsEnum(DisplayNameMode) + displayNameMode!: DisplayNameMode; + + @ApiPropertyOptional({ + example: CONSENT_EXPIRES_IN_DAYS.default, + minimum: CONSENT_EXPIRES_IN_DAYS.min, + maximum: CONSENT_EXPIRES_IN_DAYS.max, + description: '동의 요청 유효 기간(일), 기본 7', + }) + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(CONSENT_EXPIRES_IN_DAYS.min) + @Max(CONSENT_EXPIRES_IN_DAYS.max) + expiresInDays?: number; +} diff --git a/src/referral/dto/referral-consent-decision.dto.ts b/src/referral/dto/referral-consent-decision.dto.ts new file mode 100644 index 0000000..bdd904c --- /dev/null +++ b/src/referral/dto/referral-consent-decision.dto.ts @@ -0,0 +1,24 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { StrictBoolean } from '../../core/decorators/strict-boolean.decorator'; + +/** 직원 동의. 동의 여부는 진짜 boolean만 허용 ("false" 문자열이 동의로 바뀌지 않도록) */ +export class AgreeReferralConsentDto { + @ApiProperty({ example: true, description: '추천 게시물 공개 동의 (false면 403 CONSENT_NOT_GIVEN)' }) + @StrictBoolean() + recommendationAgreed!: boolean; + + @ApiProperty({ example: true, description: '이력서 공개 동의 (false면 403 CONSENT_NOT_GIVEN)' }) + @StrictBoolean() + resumeDisclosureAgreed!: boolean; + + @ApiProperty({ example: true, description: '최종 확인 (false면 422 INVALID_CONSENT)' }) + @StrictBoolean() + finalConfirmation!: boolean; +} + +/** 직원 동의 철회 */ +export class WithdrawReferralConsentDto { + @ApiProperty({ example: true, description: '철회 최종 확인 (false면 422 INVALID_CONSENT)' }) + @StrictBoolean() + finalConfirmation!: boolean; +} diff --git a/src/referral/referral-consent.controller.ts b/src/referral/referral-consent.controller.ts new file mode 100644 index 0000000..1701b2c --- /dev/null +++ b/src/referral/referral-consent.controller.ts @@ -0,0 +1,93 @@ +import { Body, Controller, Get, Headers, HttpCode, HttpStatus, Ip, Param, Patch, Post, 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 { CreateReferralConsentDto } from './dto/create-referral-consent.dto'; +import { AgreeReferralConsentDto, WithdrawReferralConsentDto } from './dto/referral-consent-decision.dto'; +import { ReferralConsentService } from './referral-consent.service'; + +/** + * 인재 추천 게시 동의. + * 요청(POST)은 대표 JWT, 조회·동의·철회는 직원이 메일로 받은 링크 토큰으로 인증한다. + */ +@ApiTags('Referral') +@Controller('referral/consents') +export class ReferralConsentController { + constructor(private readonly referralConsentService: ReferralConsentService) {} + + @Post() + @HttpCode(HttpStatus.CREATED) + @ApiBearerAuth('access-token') + @UseGuards(JwtAuthGuard, RolesGuard) + @Roles('COMPANY') + @ApiOperation({ summary: '대표: 퇴사 직원에게 인재 추천 게시 동의 요청 (동의 링크 메일 발송)' }) + @ApiResponse({ status: 201, description: '요청 성공 { consentId, status, sentAt, expiresAt, linkSent }' }) + @ApiResponse({ status: 400, description: '필수값 누락 또는 형식 오류 (expiresInDays 1~30)' }) + @ApiResponse({ status: 401, description: '인증 필요' }) + @ApiResponse({ status: 403, description: 'FORBIDDEN (대표 권한 또는 직원 소속 불일치)' }) + @ApiResponse({ status: 404, description: 'EMPLOYEE_NOT_FOUND' }) + @ApiResponse({ status: 409, description: 'ACTIVE_CONSENT_EXISTS (진행 중·동의된 요청 존재)' }) + @ApiResponse({ status: 422, description: 'EMPLOYEE_NOT_RESIGNED (퇴사 직원 아님)' }) + @ApiResponse({ status: 429, description: 'LINK_RATE_LIMITED (같은 직원 24시간 3회 초과)' }) + @ResponseMessage('인재 추천 게시 동의 요청 성공') + request(@CurrentUser() user: JwtPayload, @Body() dto: CreateReferralConsentDto) { + return this.referralConsentService.request(user, dto); + } + + @Get(':token') + @ApiOperation({ summary: '직원: 추천 게시 동의 내용 조회 (목적·공개 항목·게시 기간·현재 상태)' }) + @ApiParam({ name: 'token', description: '메일로 받은 추천 동의 링크 토큰' }) + @ApiResponse({ status: 200, description: '조회 성공' }) + @ApiResponse({ status: 403, description: 'INVALID_LINK_PURPOSE (추천 동의용 토큰 아님)' }) + @ApiResponse({ status: 404, description: 'CONSENT_NOT_FOUND' }) + @ApiResponse({ status: 409, description: 'ALREADY_PROCESSED (철회된 동의)' }) + @ApiResponse({ status: 410, description: 'LINK_EXPIRED (동의 링크 만료)' }) + @ResponseMessage('인재 추천 게시 동의 내용 조회 성공') + getByToken(@Param('token') token: string) { + return this.referralConsentService.getByToken(token); + } + + @Patch(':token/agree') + @ApiOperation({ summary: '직원: 추천 게시·이력서 공개 동의 (링크는 철회용으로 유지)' }) + @ApiParam({ name: 'token', description: '메일로 받은 추천 동의 링크 토큰' }) + @ApiResponse({ status: 200, description: '동의 성공 { consentId, status, agreedAt }' }) + @ApiResponse({ status: 400, description: '형식 오류 (동의 값은 true/false만)' }) + @ApiResponse({ status: 403, description: 'CONSENT_NOT_GIVEN (필수 동의 누락) / INVALID_LINK_PURPOSE' }) + @ApiResponse({ status: 404, description: 'CONSENT_NOT_FOUND' }) + @ApiResponse({ status: 409, description: 'ALREADY_PROCESSED (이미 처리된 동의)' }) + @ApiResponse({ status: 410, description: 'LINK_EXPIRED (동의 링크 만료)' }) + @ApiResponse({ status: 422, description: 'INVALID_CONSENT (최종 확인 누락)' }) + @ResponseMessage('인재 추천 게시 동의 성공') + agree( + @Param('token') token: string, + @Body() dto: AgreeReferralConsentDto, + @Ip() ip: string, + @Headers('user-agent') userAgent?: string, + ) { + return this.referralConsentService.agree(token, dto, { ip, userAgent }); + } + + @Patch(':token/withdraw') + @ApiOperation({ summary: '직원: 추천 게시 동의 철회 (공개 중인 게시물 즉시 비공개)' }) + @ApiParam({ name: 'token', description: '메일로 받은 추천 동의 링크 토큰' }) + @ApiResponse({ status: 200, description: '철회 성공 { consentId, status, postVisibility, withdrawnAt }' }) + @ApiResponse({ status: 400, description: '형식 오류' }) + @ApiResponse({ status: 403, description: 'INVALID_LINK_PURPOSE (철회 가능한 토큰 아님)' }) + @ApiResponse({ status: 404, description: 'CONSENT_NOT_FOUND (동의 기록 없음)' }) + @ApiResponse({ status: 409, description: 'ALREADY_WITHDRAWN (이미 철회) / ALREADY_PROCESSED (만료된 요청)' }) + @ApiResponse({ status: 410, description: 'LINK_EXPIRED (철회 링크 만료)' }) + @ApiResponse({ status: 422, description: 'INVALID_CONSENT (최종 확인 누락)' }) + @ResponseMessage('인재 추천 게시 동의 철회 성공') + withdraw( + @Param('token') token: string, + @Body() dto: WithdrawReferralConsentDto, + @Ip() ip: string, + @Headers('user-agent') userAgent?: string, + ) { + return this.referralConsentService.withdraw(token, dto, { ip, userAgent }); + } +} diff --git a/src/referral/referral-consent.service.spec.ts b/src/referral/referral-consent.service.spec.ts new file mode 100644 index 0000000..0acc494 --- /dev/null +++ b/src/referral/referral-consent.service.spec.ts @@ -0,0 +1,329 @@ +import { + BadRequestException, + ConflictException, + ForbiddenException, + GoneException, + HttpException, + NotFoundException, + UnprocessableEntityException, + ValidationPipe, +} 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 { AgreeReferralConsentDto } from './dto/referral-consent-decision.dto'; +import { ReferralConsentService } from './referral-consent.service'; +import { CONSENT_REQUEST_LIMIT, DAY_MS, WITHDRAWAL_LINK_VALID_DAYS } from './referral.constants'; + +// --------------------------------------------------------------------------- +// 테스트용 인메모리 DB (이 서비스가 쓰는 Prisma 호출 형태만) +// --------------------------------------------------------------------------- +type Row = Record; + +function matchValue(actual: any, expected: any): boolean { + if (expected && typeof expected === 'object' && !(expected instanceof Date)) { + if ('in' in expected) return expected.in.includes(actual); + if ('gte' in expected) return actual >= expected.gte; + if ('lt' in expected) return actual < expected.lt; + if ('not' in expected) return actual !== expected.not; + } + return actual === expected; +} +const matches = (row: Row, where: Row) => Object.entries(where).every(([k, v]) => matchValue(row[k], v)); +const pick = (row: Row | undefined, select?: Row) => + !row ? null : select ? Object.fromEntries(Object.keys(select).map((k) => [k, row[k]])) : { ...row }; + +function createFakeDb() { + let seq = 0; + const id = (p: string) => `${p}-${++seq}`; + const db = { + companies: [] as Row[], + employees: [] as Row[], + consents: [] as Row[], + posts: [] as Row[], + links: [] as Row[], + audits: [] as Row[], + }; + const updateMany = (rows: Row[]) => async ({ where, data }: any) => { + const targets = rows.filter((r) => matches(r, where)); + targets.forEach((r) => Object.assign(r, data)); + return { count: targets.length }; + }; + const client: any = { + hrManager: { findUnique: async () => null }, + company: { findUnique: async ({ where, select }: any) => pick(db.companies.find((c) => c.id === where.id), select) }, + employee: { findUnique: async ({ where, select }: any) => pick(db.employees.find((e) => e.id === where.id), select) }, + referralConsent: { + findFirst: async ({ where, select }: any) => pick(db.consents.find((c) => matches(c, where)), select), + findUnique: async ({ where }: any) => pick(db.consents.find((c) => c.id === where.id)), + count: async ({ where }: any) => db.consents.filter((c) => matches(c, where)).length, + create: async ({ data }: any) => { + const row = { id: id('consent'), agreedAt: null, withdrawnAt: null, agreedIp: null, agreedUserAgent: null, ...data }; + db.consents.push(row); + return { ...row }; + }, + updateMany: updateMany(db.consents), + }, + referralPost: { updateMany: updateMany(db.posts) }, + accessLink: { + create: async ({ data }: any) => { + const row = { id: id('link'), usedAt: null, revokedAt: null, createdAt: new Date(), ...data }; + db.links.push(row); + return { ...row }; + }, + findUnique: async ({ where }: any) => pick(db.links.find((l) => l.tokenHash === where.tokenHash)), + updateMany: updateMany(db.links), + }, + auditLog: { create: async ({ data }: any) => (db.audits.push(data), data) }, + }; + client.$transaction = async (fn: any) => fn(client); + return { db, client }; +} + +// --------------------------------------------------------------------------- + +const CEO = { sub: 'comp-1', role: 'COMPANY' as const }; +const META = { ip: '203.0.113.7', userAgent: 'jest-browser' }; +const NOW = new Date('2026-05-03T01:00:00.000Z'); +const AGREE: AgreeReferralConsentDto = { recommendationAgreed: true, resumeDisclosureAgreed: true, finalConfirmation: true }; + +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 }); + return error as HttpException; +} + +describe('ReferralConsentService', () => { + let fake: ReturnType; + let mailMock: { sendReferralConsentLink: jest.Mock }; + let accessLink: AccessLinkService; + let service: ReferralConsentService; + + beforeEach(() => { + jest.useFakeTimers().setSystemTime(NOW); + fake = createFakeDb(); + fake.db.companies.push({ id: 'comp-1', companyName: '테크플러스' }, { id: 'comp-2', companyName: '다른기업' }); + fake.db.employees.push( + { id: 'emp-1', companyId: 'comp-1', name: '김민준', email: 'minjun@example.com', position: '과장', employmentStatus: 'RESIGNED' }, + { id: 'emp-working', companyId: 'comp-1', name: '재직자', email: 'w@example.com', position: null, employmentStatus: 'EMPLOYED' }, + { id: 'emp-other', companyId: 'comp-2', name: '타사', email: 'o@example.com', position: null, employmentStatus: 'RESIGNED' }, + ); + const prisma = fake.client as unknown as PrismaService; + accessLink = new AccessLinkService(prisma); + mailMock = { sendReferralConsentLink: jest.fn().mockResolvedValue(true) }; + service = new ReferralConsentService(prisma, accessLink, mailMock as unknown as MailService, new AuditService(prisma)); + }); + + afterEach(() => jest.useRealTimers()); + + const request = (over: Record = {}) => + service.request(CEO, { employeeId: 'emp-1', channels: ['EMAIL'], displayNameMode: 'ANONYMOUS', ...over } as any); + const lastToken = (): string => mailMock.sendReferralConsentLink.mock.calls.at(-1)[0].token; + + describe('요청', () => { + it('PENDING 동의를 만들고 링크 발급 + 커밋 후 메일 발송 (기본 7일)', async () => { + mailMock.sendReferralConsentLink.mockImplementation(async () => { + expect(fake.db.consents).toHaveLength(1); // 메일은 커밋 후 + return true; + }); + + const result = await request(); + + const expiresAt = new Date(NOW.getTime() + 7 * DAY_MS); + expect(result).toEqual({ consentId: 'consent-1', status: 'PENDING', sentAt: NOW, expiresAt, linkSent: true }); + expect(fake.db.links[0]).toMatchObject({ purpose: 'REFERRAL_CONSENT', targetId: 'consent-1', expiresAt }); + expect(fake.db.audits.map((a) => a.action)).toEqual(['REFERRAL_CONSENT_REQUESTED']); + expect(mailMock.sendReferralConsentLink).toHaveBeenCalledWith( + expect.objectContaining({ to: 'minjun@example.com', employeeName: '김민준', companyName: '테크플러스', expiresAt }), + ); + }); + + it('expiresInDays를 지정하면 그 기간으로 만료', async () => { + const result = await request({ expiresInDays: 30 }); + expect(result.expiresAt).toEqual(new Date(NOW.getTime() + 30 * DAY_MS)); + }); + + it('메일이 실패해도 동의 요청은 남고 linkSent=false', async () => { + mailMock.sendReferralConsentLink.mockResolvedValue(false); + const result = await request(); + expect(result.linkSent).toBe(false); + expect(fake.db.consents).toHaveLength(1); + }); + + it('퇴사하지 않은 직원이면 422 EMPLOYEE_NOT_RESIGNED', async () => { + await expectCode(request({ employeeId: 'emp-working' }), UnprocessableEntityException, 'EMPLOYEE_NOT_RESIGNED'); + }); + + it('다른 기업 직원 403 FORBIDDEN, 없는 직원 404', async () => { + await expectCode(request({ employeeId: 'emp-other' }), ForbiddenException, 'FORBIDDEN'); + await expectCode(request({ employeeId: 'nope' }), NotFoundException, 'EMPLOYEE_NOT_FOUND'); + }); + + it.each(['PENDING', 'AGREED'])('%s 동의가 있으면 409 ACTIVE_CONSENT_EXISTS', async (status) => { + await request(); + fake.db.consents[0].status = status; + await expectCode(request(), ConflictException, 'ACTIVE_CONSENT_EXISTS'); + }); + + it('같은 직원 24시간 안에 3회까지 허용하고 4번째는 429 LINK_RATE_LIMITED', async () => { + for (let i = 0; i < CONSENT_REQUEST_LIMIT.count; i++) { + await request(); + fake.db.consents.at(-1)!.status = 'WITHDRAWN'; // 진행 중 요청이 없도록 정리 + } + const error = await expectCode(request(), HttpException, 'LINK_RATE_LIMITED'); + expect(error.getStatus()).toBe(429); + }); + + it('24시간이 지난 요청은 횟수에서 빠진다', async () => { + for (let i = 0; i < CONSENT_REQUEST_LIMIT.count; i++) { + await request(); + fake.db.consents.at(-1)!.status = 'WITHDRAWN'; + } + jest.setSystemTime(new Date(NOW.getTime() + CONSENT_REQUEST_LIMIT.windowMs + 1000)); + await expect(request()).resolves.toMatchObject({ status: 'PENDING' }); + }); + }); + + describe('조회 → 동의 → 철회 (상태 전환)', () => { + it('PENDING 조회 → AGREED(동의 시각·IP·UA, 링크 유지·연장) → AGREED 조회 → WITHDRAWN', async () => { + await request(); + const token = lastToken(); + + // 조회 + const view = await service.getByToken(token); + expect(view).toMatchObject({ + consentId: 'consent-1', + status: 'PENDING', + employee: { name: '김민준', position: '과장', companyName: '테크플러스' }, + disclosure: { recommendation: true, resume: true, position: true, displayNameMode: 'ANONYMOUS', publishMonths: 6, publishMonthsOptions: [3, 6] }, + }); + expect(view.purpose).toEqual(expect.any(String)); + + // 동의 + const agreed = await service.agree(token, AGREE, META); + expect(agreed).toEqual({ consentId: 'consent-1', status: 'AGREED', agreedAt: NOW }); + expect(fake.db.consents[0]).toMatchObject({ status: 'AGREED', agreedAt: NOW, agreedIp: META.ip, agreedUserAgent: META.userAgent }); + // 철회에도 쓰므로 소비하지 않고, 유효 기간을 철회 가능 기간으로 연장 + expect(fake.db.links[0].usedAt).toBeNull(); + expect(fake.db.links[0].expiresAt).toEqual(new Date(NOW.getTime() + WITHDRAWAL_LINK_VALID_DAYS * DAY_MS)); + + // 동의 요청 기한(7일)이 한참 지나도 동의 후에는 조회·철회 가능 + jest.setSystemTime(new Date(NOW.getTime() + 60 * DAY_MS)); + await expect(service.getByToken(token)).resolves.toMatchObject({ status: 'AGREED', agreedAt: NOW }); + + // 철회 + const withdrawn = await service.withdraw(token, { finalConfirmation: true }, META); + expect(withdrawn).toMatchObject({ consentId: 'consent-1', status: 'WITHDRAWN', postVisibility: 'HIDDEN' }); + expect(fake.db.consents[0].status).toBe('WITHDRAWN'); + expect(fake.db.audits.map((a) => a.action)).toEqual([ + 'REFERRAL_CONSENT_REQUESTED', + 'REFERRAL_CONSENT_AGREED', + 'REFERRAL_CONSENT_WITHDRAWN', + ]); + }); + + it('PENDING 상태에서도 바로 철회할 수 있다', async () => { + await request(); + await expect(service.withdraw(lastToken(), { finalConfirmation: true }, META)).resolves.toMatchObject({ status: 'WITHDRAWN' }); + }); + + it('철회하면 같은 동의로 공개 중인 게시물만 모두 HIDDEN이 된다', async () => { + await request(); + const token = lastToken(); + await service.agree(token, AGREE, META); + fake.db.posts.push( + { id: 'post-1', referralConsentId: 'consent-1', status: 'PUBLISHED' }, + { id: 'post-2', referralConsentId: 'consent-1', status: 'PUBLISHED' }, + { id: 'post-expired', referralConsentId: 'consent-1', status: 'EXPIRED' }, + { id: 'post-deleted', referralConsentId: 'consent-1', status: 'DELETED' }, + { id: 'post-other', referralConsentId: 'consent-other', status: 'PUBLISHED' }, + ); + + await service.withdraw(token, { finalConfirmation: true }, META); + + expect(Object.fromEntries(fake.db.posts.map((p) => [p.id, p.status]))).toEqual({ + 'post-1': 'HIDDEN', + 'post-2': 'HIDDEN', + 'post-expired': 'EXPIRED', + 'post-deleted': 'DELETED', + 'post-other': 'PUBLISHED', + }); + expect(fake.db.audits.at(-1)!.metadata).toMatchObject({ previousStatus: 'AGREED', hiddenPostCount: 2 }); + }); + }); + + describe('동의·철회 오류', () => { + beforeEach(async () => { + await request(); + }); + + it.each([ + ['recommendationAgreed', { ...AGREE, recommendationAgreed: false }], + ['resumeDisclosureAgreed', { ...AGREE, resumeDisclosureAgreed: false }], + ])('%s=false면 403 CONSENT_NOT_GIVEN이고 상태는 그대로', async (_label, dto) => { + await expectCode(service.agree(lastToken(), dto, META), ForbiddenException, 'CONSENT_NOT_GIVEN'); + expect(fake.db.consents[0].status).toBe('PENDING'); + }); + + it('finalConfirmation=false면 동의·철회 모두 422 INVALID_CONSENT', async () => { + await expectCode(service.agree(lastToken(), { ...AGREE, finalConfirmation: false }, META), UnprocessableEntityException, 'INVALID_CONSENT'); + await expectCode(service.withdraw(lastToken(), { finalConfirmation: false }, META), UnprocessableEntityException, 'INVALID_CONSENT'); + }); + + it('이미 동의했으면 다시 동의 시 409 ALREADY_PROCESSED', async () => { + await service.agree(lastToken(), AGREE, META); + await expectCode(service.agree(lastToken(), AGREE, META), ConflictException, 'ALREADY_PROCESSED'); + }); + + it('이미 철회했으면 철회 409 ALREADY_WITHDRAWN, 동의·조회 409 ALREADY_PROCESSED', async () => { + await service.withdraw(lastToken(), { finalConfirmation: true }, META); + await expectCode(service.withdraw(lastToken(), { finalConfirmation: true }, META), ConflictException, 'ALREADY_WITHDRAWN'); + await expectCode(service.agree(lastToken(), AGREE, META), ConflictException, 'ALREADY_PROCESSED'); + await expectCode(service.getByToken(lastToken()), ConflictException, 'ALREADY_PROCESSED'); + }); + + it('동의 요청 기한이 지나면(스케줄러 전이라도) 조회·동의 410 LINK_EXPIRED', async () => { + const token = lastToken(); + // 링크 자체도 요청 기한에 만료되므로 링크 검증 단계에서 410 + jest.setSystemTime(new Date(NOW.getTime() + 7 * DAY_MS + 1000)); + await expectCode(service.getByToken(token), GoneException, 'LINK_EXPIRED'); + await expectCode(service.agree(token, AGREE, META), GoneException, 'LINK_EXPIRED'); + expect(fake.db.consents[0].status).toBe('PENDING'); + }); + + it('스케줄러가 EXPIRED로 바꾼 요청은 조회 410, 철회 409 ALREADY_PROCESSED', async () => { + fake.db.consents[0].status = 'EXPIRED'; + await expectCode(service.getByToken(lastToken()), GoneException, 'LINK_EXPIRED'); + await expectCode(service.withdraw(lastToken(), { finalConfirmation: true }, META), ConflictException, 'ALREADY_PROCESSED'); + }); + + it('다른 목적 링크면 403 INVALID_LINK_PURPOSE, 동의 기록이 없으면 404 CONSENT_NOT_FOUND', async () => { + const otherToken = await accessLink.issue('DECLARATION', 'consent-1', new Date(NOW.getTime() + DAY_MS), fake.client); + await expectCode(service.getByToken(otherToken), ForbiddenException, 'INVALID_LINK_PURPOSE'); + + const orphan = await accessLink.issue('REFERRAL_CONSENT', 'consent-missing', new Date(NOW.getTime() + DAY_MS), fake.client); + await expectCode(service.withdraw(orphan, { finalConfirmation: true }, META), NotFoundException, 'CONSENT_NOT_FOUND'); + }); + }); + + describe('DTO (전역 ValidationPipe와 같은 설정)', () => { + const pipe = new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true, transformOptions: { enableImplicitConversion: true } }); + + it.each(['true', 'false', 1, 'YES'])('동의 값 %p는 400 (진짜 boolean만)', async (value) => { + await expect( + pipe.transform({ ...AGREE, recommendationAgreed: value }, { type: 'body', metatype: AgreeReferralConsentDto }), + ).rejects.toBeInstanceOf(BadRequestException); + }); + }); +}); diff --git a/src/referral/referral-consent.service.ts b/src/referral/referral-consent.service.ts new file mode 100644 index 0000000..8cb87ca --- /dev/null +++ b/src/referral/referral-consent.service.ts @@ -0,0 +1,347 @@ +import { + ConflictException, + ForbiddenException, + GoneException, + HttpException, + HttpStatus, + Injectable, + NotFoundException, + UnprocessableEntityException, +} from '@nestjs/common'; +import { ReferralConsent } from '@prisma/client'; +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 { MailService } from '../notification/mail.service'; +import { PrismaService } from '../prisma/prisma.service'; +import { CreateReferralConsentDto } from './dto/create-referral-consent.dto'; +import { AgreeReferralConsentDto, WithdrawReferralConsentDto } from './dto/referral-consent-decision.dto'; +import { + CONSENT_EXPIRES_IN_DAYS, + CONSENT_REQUEST_LIMIT, + DAY_MS, + PUBLISH_MONTHS_OPTIONS, + REFERRAL_PURPOSE, + WITHDRAWAL_LINK_VALID_DAYS, +} from './referral.constants'; + +export interface RequestMeta { + ip?: string | null; + userAgent?: string | null; +} + +/** + * 인재 추천 게시 동의 (신규 흐름). 레거시 src/consent와 무관하다. + * 동의 링크 하나로 조회·동의·철회를 모두 처리하므로 링크를 소비하지 않는다. + */ +@Injectable() +export class ReferralConsentService { + constructor( + private readonly prisma: PrismaService, + private readonly accessLinkService: AccessLinkService, + private readonly mailService: MailService, + private readonly auditService: AuditService, + ) {} + + /** 대표: 퇴사 직원에게 추천 게시 동의 요청 링크 발송 */ + async request(user: JwtPayload, dto: CreateReferralConsentDto) { + 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 new UnprocessableEntityException({ + code: 'EMPLOYEE_NOT_RESIGNED', + message: '퇴사한 직원에게만 추천 게시 동의를 요청할 수 있습니다.', + }); + } + + const now = new Date(); + const active = await this.prisma.referralConsent.findFirst({ + where: { employeeId: employee.id, status: { in: ['PENDING', 'AGREED'] } }, + select: { id: true, status: true }, + }); + if (active) { + throw new ConflictException({ + code: 'ACTIVE_CONSENT_EXISTS', + message: '진행 중이거나 동의된 추천 게시 동의가 이미 있습니다.', + details: { consentId: active.id, status: active.status }, + }); + } + + const recentCount = await this.prisma.referralConsent.count({ + where: { employeeId: employee.id, sentAt: { gte: new Date(now.getTime() - CONSENT_REQUEST_LIMIT.windowMs) } }, + }); + if (recentCount >= CONSENT_REQUEST_LIMIT.count) { + throw new HttpException( + { + code: 'LINK_RATE_LIMITED', + message: `같은 직원에게는 24시간 동안 ${CONSENT_REQUEST_LIMIT.count}회까지만 요청할 수 있습니다.`, + }, + HttpStatus.TOO_MANY_REQUESTS, + ); + } + + const expiresInDays = dto.expiresInDays ?? CONSENT_EXPIRES_IN_DAYS.default; + const expiresAt = new Date(now.getTime() + expiresInDays * DAY_MS); + + // 트랜잭션 안에서는 데이터와 링크 저장만 한다. 메일은 커밋 후. + const { consent, token } = await this.prisma.$transaction(async (tx) => { + const created = await tx.referralConsent.create({ + data: { + companyId, + employeeId: employee.id, + status: 'PENDING', + displayNameMode: dto.displayNameMode, + sentAt: now, + expiresAt, + }, + }); + + const issuedToken = await this.accessLinkService.issue('REFERRAL_CONSENT', created.id, expiresAt, tx); + + await this.auditService.log( + { + actorType: 'COMPANY', + actorId: user.sub, + action: 'REFERRAL_CONSENT_REQUESTED', + targetType: 'ReferralConsent', + targetId: created.id, + metadata: { + employeeId: employee.id, + channels: dto.channels, + displayNameMode: dto.displayNameMode, + expiresInDays, + }, + }, + tx, + ); + + return { consent: created, token: issuedToken }; + }); + + // 커밋 후 발송. 실패해도 동의 요청은 유지되고 linkSent=false로 알린다. + const company = await this.prisma.company.findUnique({ + where: { id: companyId }, + select: { companyName: true }, + }); + const linkSent = await this.mailService.sendReferralConsentLink({ + to: employee.email, + token, + employeeName: employee.name, + companyName: company?.companyName, + expiresAt, + }); + + return { + consentId: consent.id, + status: consent.status, + sentAt: consent.sentAt, + expiresAt: consent.expiresAt, + linkSent, + }; + } + + /** 직원: 동의 내용 조회 (동의 전 확인, 동의 후 철회 화면 모두 사용) */ + async getByToken(token: string) { + const consent = await this.findByToken(token); + + if (consent.status === 'WITHDRAWN') { + throw alreadyProcessed(consent.status); + } + if (isRequestExpired(consent, new Date())) { + throw linkExpired(); + } + + const [employee, company] = await Promise.all([ + this.prisma.employee.findUnique({ where: { id: consent.employeeId }, select: { name: true, position: true } }), + this.prisma.company.findUnique({ where: { id: consent.companyId }, select: { companyName: true } }), + ]); + + return { + consentId: consent.id, + status: consent.status, + purpose: REFERRAL_PURPOSE, + employee: { + name: employee?.name ?? null, + position: employee?.position ?? null, + companyName: company?.companyName ?? null, + }, + disclosure: { + recommendation: true, + resume: true, + position: true, + displayNameMode: consent.displayNameMode, + // 게시 기간은 대표가 게시물 작성 시 선택 (최대 6개월) + publishMonths: Math.max(...PUBLISH_MONTHS_OPTIONS), + publishMonthsOptions: [...PUBLISH_MONTHS_OPTIONS], + }, + expiresAt: consent.expiresAt, + agreedAt: consent.agreedAt, + }; + } + + /** 직원: 추천 게시·이력서 공개 동의. 링크는 이후 철회에도 쓰므로 소비하지 않고 유효 기간을 늘린다. */ + async agree(token: string, dto: AgreeReferralConsentDto, meta: RequestMeta) { + if (!dto.recommendationAgreed || !dto.resumeDisclosureAgreed) { + throw new ForbiddenException({ + code: 'CONSENT_NOT_GIVEN', + message: '추천 게시와 이력서 공개에 모두 동의해야 합니다.', + }); + } + if (!dto.finalConfirmation) { + throw invalidConsent(); + } + + return this.prisma.$transaction(async (tx) => { + const link = await this.accessLinkService.verify(token, 'REFERRAL_CONSENT', tx); + const consent = await tx.referralConsent.findUnique({ where: { id: link.targetId } }); + if (!consent) { + throw consentNotFound(); + } + const now = new Date(); + if (consent.status !== 'PENDING') { + throw alreadyProcessed(consent.status); + } + if (isRequestExpired(consent, now)) { + throw linkExpired(); + } + + // 동시에 두 번 눌러도 한 번만 AGREED로 전환 + const { count } = await tx.referralConsent.updateMany({ + where: { id: consent.id, status: 'PENDING' }, + data: { + status: 'AGREED', + agreedAt: now, + agreedIp: meta.ip ?? null, + agreedUserAgent: meta.userAgent ?? null, + }, + }); + if (count === 0) { + throw alreadyProcessed('AGREED'); + } + + await this.accessLinkService.extend( + link.id, + new Date(now.getTime() + WITHDRAWAL_LINK_VALID_DAYS * DAY_MS), + tx, + ); + + await this.auditService.log( + { + actorType: 'EMPLOYEE', + actorId: consent.employeeId, + action: 'REFERRAL_CONSENT_AGREED', + targetType: 'ReferralConsent', + targetId: consent.id, + ip: meta.ip, + userAgent: meta.userAgent, + metadata: { recommendationAgreed: true, resumeDisclosureAgreed: true }, + }, + tx, + ); + + return { consentId: consent.id, status: 'AGREED' as const, agreedAt: now }; + }); + } + + /** 직원: 동의 철회. 같은 트랜잭션에서 연결된 공개 게시물을 모두 비공개(HIDDEN) 처리한다. */ + async withdraw(token: string, dto: WithdrawReferralConsentDto, meta: RequestMeta) { + if (!dto.finalConfirmation) { + throw invalidConsent(); + } + + return this.prisma.$transaction(async (tx) => { + const link = await this.accessLinkService.verify(token, 'REFERRAL_CONSENT', tx); + const consent = await tx.referralConsent.findUnique({ where: { id: link.targetId } }); + if (!consent) { + throw consentNotFound(); + } + if (consent.status === 'WITHDRAWN') { + throw new ConflictException({ code: 'ALREADY_WITHDRAWN', message: '이미 철회된 동의입니다.' }); + } + if (consent.status === 'EXPIRED') { + throw alreadyProcessed(consent.status); + } + + const now = new Date(); + const { count } = await tx.referralConsent.updateMany({ + where: { id: consent.id, status: { in: ['PENDING', 'AGREED'] } }, + data: { status: 'WITHDRAWN', withdrawnAt: now }, + }); + if (count === 0) { + throw new ConflictException({ code: 'ALREADY_WITHDRAWN', message: '이미 철회된 동의입니다.' }); + } + + // 공개 중인 추천 게시물은 즉시 비공개 (이력서는 공개 게시물에서만 내려받을 수 있으므로 함께 차단됨) + const hidden = await tx.referralPost.updateMany({ + where: { referralConsentId: consent.id, status: 'PUBLISHED' }, + data: { status: 'HIDDEN' }, + }); + + await this.auditService.log( + { + actorType: 'EMPLOYEE', + actorId: consent.employeeId, + action: 'REFERRAL_CONSENT_WITHDRAWN', + targetType: 'ReferralConsent', + targetId: consent.id, + ip: meta.ip, + userAgent: meta.userAgent, + metadata: { previousStatus: consent.status, hiddenPostCount: hidden.count }, + }, + tx, + ); + + return { + consentId: consent.id, + status: 'WITHDRAWN' as const, + postVisibility: 'HIDDEN' as const, + withdrawnAt: now, + }; + }); + } + + private async findByToken(token: string): Promise { + const link = await this.accessLinkService.verify(token, 'REFERRAL_CONSENT'); + const consent = await this.prisma.referralConsent.findUnique({ where: { id: link.targetId } }); + if (!consent) { + throw consentNotFound(); + } + return consent; + } +} + +/** 동의 전(PENDING) 요청이 만료됐는지. 동의 후(AGREED)에는 요청 만료와 무관하게 철회할 수 있다 */ +function isRequestExpired(consent: ReferralConsent, now: Date): boolean { + return consent.status === 'EXPIRED' || (consent.status === 'PENDING' && now > consent.expiresAt); +} + +function alreadyProcessed(status: string): ConflictException { + return new ConflictException({ + code: 'ALREADY_PROCESSED', + message: '이미 처리된 동의입니다.', + details: { status }, + }); +} + +function invalidConsent(): UnprocessableEntityException { + return new UnprocessableEntityException({ + code: 'INVALID_CONSENT', + message: '최종 확인에 체크해야 합니다.', + }); +} + +function consentNotFound(): NotFoundException { + return new NotFoundException({ code: 'CONSENT_NOT_FOUND', message: '동의 기록을 찾을 수 없습니다.' }); +} + +function linkExpired(): GoneException { + return new GoneException({ code: 'LINK_EXPIRED', message: '동의 링크가 만료되었습니다.' }); +} diff --git a/src/referral/referral-expiry.scheduler.spec.ts b/src/referral/referral-expiry.scheduler.spec.ts new file mode 100644 index 0000000..21591ec --- /dev/null +++ b/src/referral/referral-expiry.scheduler.spec.ts @@ -0,0 +1,51 @@ +import { Logger } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; +import { ReferralExpiryScheduler } from './referral-expiry.scheduler'; + +describe('ReferralExpiryScheduler', () => { + const NOW = new Date('2026-05-10T01:00:00.000Z'); + let consents: Record[]; + let scheduler: ReferralExpiryScheduler; + + beforeEach(() => { + consents = [ + { id: 'c-expired', status: 'PENDING', expiresAt: new Date(NOW.getTime() - 1000) }, + { id: 'c-just-due', status: 'PENDING', expiresAt: NOW }, + { id: 'c-pending', status: 'PENDING', expiresAt: new Date(NOW.getTime() + 1000) }, + { id: 'c-agreed', status: 'AGREED', expiresAt: new Date(NOW.getTime() - 1000) }, + { id: 'c-withdrawn', status: 'WITHDRAWN', expiresAt: new Date(NOW.getTime() - 1000) }, + ]; + const prisma: any = { + referralConsent: { + updateMany: jest.fn(async ({ where, data }: any) => { + const targets = consents.filter((c) => c.status === where.status && c.expiresAt <= where.expiresAt.lte); + targets.forEach((c) => Object.assign(c, data)); + return { count: targets.length }; + }), + }, + }; + scheduler = new ReferralExpiryScheduler(prisma as PrismaService); + }); + + const statusOf = (id: string) => consents.find((c) => c.id === id)!.status; + + it('응답 기한이 지난 PENDING만 EXPIRED, 동의·철회된 건은 그대로', async () => { + const count = await scheduler.expirePendingConsents(NOW); + + expect(count).toBe(2); + expect(statusOf('c-expired')).toBe('EXPIRED'); + expect(statusOf('c-just-due')).toBe('EXPIRED'); + expect(statusOf('c-pending')).toBe('PENDING'); + expect(statusOf('c-agreed')).toBe('AGREED'); + expect(statusOf('c-withdrawn')).toBe('WITHDRAWN'); + }); + + it('처리 중 오류가 나도 예외를 던지지 않고 로그만 남긴다', async () => { + const errorSpy = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined); + jest.spyOn(scheduler, 'expirePendingConsents').mockRejectedValue(new Error('DB down')); + + await expect(scheduler.run()).resolves.toBeUndefined(); + expect(errorSpy).toHaveBeenCalled(); + errorSpy.mockRestore(); + }); +}); diff --git a/src/referral/referral-expiry.scheduler.ts b/src/referral/referral-expiry.scheduler.ts new file mode 100644 index 0000000..0a83dce --- /dev/null +++ b/src/referral/referral-expiry.scheduler.ts @@ -0,0 +1,35 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { Cron, CronExpression } from '@nestjs/schedule'; +import { PrismaService } from '../prisma/prisma.service'; + +/** + * 인재 추천 만료 처리 (매시간). + * ScheduleModule.forRoot()는 이미 등록돼 있어 @Cron만 사용한다. + */ +@Injectable() +export class ReferralExpiryScheduler { + private readonly logger = new Logger(ReferralExpiryScheduler.name); + + constructor(private readonly prisma: PrismaService) {} + + @Cron(CronExpression.EVERY_HOUR) + async run(): Promise { + try { + const expired = await this.expirePendingConsents(); + if (expired > 0) { + this.logger.log(`추천 동의 요청 만료 처리: ${expired}건`); + } + } catch (error) { + this.logger.error('추천 만료 처리 실패', error instanceof Error ? error.stack : String(error)); + } + } + + /** 응답 기한이 지난 PENDING 동의 요청 → EXPIRED. 동의(AGREED)된 건은 건드리지 않는다. 처리 건수 반환 */ + async expirePendingConsents(now: Date = new Date()): Promise { + const { count } = await this.prisma.referralConsent.updateMany({ + where: { status: 'PENDING', expiresAt: { lte: now } }, + data: { status: 'EXPIRED' }, + }); + return count; + } +} diff --git a/src/referral/referral.constants.ts b/src/referral/referral.constants.ts new file mode 100644 index 0000000..4e1b6b2 --- /dev/null +++ b/src/referral/referral.constants.ts @@ -0,0 +1,22 @@ +/** 동의 요청 링크 유효 기간 (일) */ +export const CONSENT_EXPIRES_IN_DAYS = { min: 1, max: 30, default: 7 } as const; + +/** 같은 직원에게 24시간 안에 보낼 수 있는 동의 요청 횟수 */ +export const CONSENT_REQUEST_LIMIT = { count: 3, windowMs: 24 * 60 * 60 * 1000 } as const; + +/** + * 동의 후 철회 링크 유효 기간 (일). + * 동의 요청 링크는 기본 7일이지만, 동의 후에도 같은 링크로 언제든 철회할 수 있어야 하므로 + * 동의 시점에 링크 만료를 이 기간으로 늘린다. 게시물 최대 공개 기간(6개월)보다 충분히 길게 둔다. + * TODO(법무): 철회 가능 기간 확정 후 조정 + */ +export const WITHDRAWAL_LINK_VALID_DAYS = 365; + +/** 게시물 공개 기간 선택지 (개월) */ +export const PUBLISH_MONTHS_OPTIONS = [3, 6] as const; + +/** 동의 화면에 보여 줄 추천 게시 목적 */ +export const REFERRAL_PURPOSE = + '퇴사 후 재취업을 돕기 위해 GeniCheck 가입 기업들이 볼 수 있는 인재 추천 게시판에 추천 게시물을 올립니다.'; + +export const DAY_MS = 24 * 60 * 60 * 1000; diff --git a/src/referral/referral.module.ts b/src/referral/referral.module.ts new file mode 100644 index 0000000..6f9b34a --- /dev/null +++ b/src/referral/referral.module.ts @@ -0,0 +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 { ReferralConsentController } from './referral-consent.controller'; +import { ReferralConsentService } from './referral-consent.service'; +import { ReferralExpiryScheduler } from './referral-expiry.scheduler'; + +/** 인재 추천 (신규 흐름). 레거시 src/consent와 무관 */ +@Module({ + // AuthModule: 대표 API의 JwtAuthGuard가 RedisService(토큰 블랙리스트)를 사용 + imports: [AuthModule, AccessLinkModule, NotificationModule, AuditModule], + controllers: [ReferralConsentController], + providers: [ReferralConsentService, ReferralExpiryScheduler], +}) +export class ReferralModule {}