Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/access-link/access-link.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ import { PrismaService } from '../prisma/prisma.service';
function createFakeDb() {
const links: any[] = [];
const matches = (link: any, where: Record<string, unknown>) =>
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) => {
Expand Down Expand Up @@ -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);
});
});
11 changes: 11 additions & 0 deletions src/access-link/access-link.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,17 @@ export class AccessLinkService {

return count;
}

/**
* 사용·폐기되지 않은 링크의 만료 시각을 늦춘다(앞당기지는 않는다).
* 예: 추천 동의 후 같은 링크로 나중에 철회할 수 있도록 유효 기간 연장.
*/
async extend(linkId: string, expiresAt: Date, tx: Tx): Promise<void> {
await tx.accessLink.updateMany({
where: { id: linkId, usedAt: null, revokedAt: null, expiresAt: { lt: expiresAt } },
data: { expiresAt },
});
}
}

function linkExpired(): GoneException {
Expand Down
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
Expand All @@ -33,6 +34,7 @@ import { EvaluationsModule } from './evaluations/evaluations.module';
EmployeeModule,
DeclarationModule,
EvaluationsModule,
ReferralModule,
],
})
export class AppModule {}
50 changes: 50 additions & 0 deletions src/referral/dto/create-referral-consent.dto.ts
Original file line number Diff line number Diff line change
@@ -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;
}
24 changes: 24 additions & 0 deletions src/referral/dto/referral-consent-decision.dto.ts
Original file line number Diff line number Diff line change
@@ -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;
}
93 changes: 93 additions & 0 deletions src/referral/referral-consent.controller.ts
Original file line number Diff line number Diff line change
@@ -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 });
}
}
Loading
Loading