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
92 changes: 92 additions & 0 deletions src/referral/dto/referral-post.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { DisplayNameMode } from '@prisma/client';
import { Type } from 'class-transformer';
import { IsEnum, IsIn, IsInt, IsNotEmpty, IsOptional, IsString, Max, MaxLength, Min } from 'class-validator';
import { PUBLISH_MONTHS_OPTIONS } from '../referral.constants';

// 추천 사유의 글자 수(200자)·금지 표현은 서비스에서 422 INVALID_RECOMMENDATION_CONTENT로 판정
export class CreateReferralPostDto {
@ApiProperty({ example: 'uuid', description: '추천할 퇴사 직원 ID (추천 게시 동의 AGREED 필요)' })
@IsString()
@IsNotEmpty()
employeeId!: string;

@ApiProperty({ example: '함께 일하고 싶은 프론트엔드 개발자', description: '제목 (100자 이내)' })
@IsString()
@IsNotEmpty()
@MaxLength(100)
title!: string;

@ApiProperty({ example: '협업과 일정 준수가 뛰어난 인재입니다.', description: '추천 사유 (200자 이내, 금지 표현 불가)' })
@IsString()
recommendationReason!: string;

@ApiPropertyOptional({ example: 'uuid', description: '업로드가 끝난 이력서 ID (presigned-url 발급 → 업로드 후)' })
@IsOptional()
@IsString()
@IsNotEmpty()
resumeFileId?: string;

@ApiProperty({ enum: DisplayNameMode, example: 'REAL_NAME', description: '직원이 익명 공개에만 동의했다면 ANONYMOUS만 가능' })
@IsEnum(DisplayNameMode)
displayNameMode!: DisplayNameMode;

@ApiProperty({ enum: PUBLISH_MONTHS_OPTIONS, example: 3, description: '게시 기간 (3 또는 6개월)' })
@Type(() => Number)
@IsIn(PUBLISH_MONTHS_OPTIONS)
publishMonths!: (typeof PUBLISH_MONTHS_OPTIONS)[number];
}

export class UpdateReferralPostDto {
@ApiPropertyOptional({ example: '함께 일하고 싶은 프론트엔드 개발자' })
@IsOptional()
@IsString()
@IsNotEmpty()
@MaxLength(100)
title?: string;

@ApiPropertyOptional({ example: '협업과 일정 준수가 뛰어나며 인수인계가 성실한 인재입니다.' })
@IsOptional()
@IsString()
recommendationReason?: string;

@ApiPropertyOptional({ enum: DisplayNameMode })
@IsOptional()
@IsEnum(DisplayNameMode)
displayNameMode?: DisplayNameMode;

@ApiPropertyOptional({ enum: PUBLISH_MONTHS_OPTIONS, example: 6, description: '3 → 6개월 연장만 가능 (게시 시작일 기준)' })
@IsOptional()
@Type(() => Number)
@IsIn(PUBLISH_MONTHS_OPTIONS)
publishMonths?: (typeof PUBLISH_MONTHS_OPTIONS)[number];
}

export class ListReferralPostsQueryDto {
@ApiPropertyOptional({ description: '제목·추천 사유 검색어' })
@IsOptional()
@IsString()
@MaxLength(100)
keyword?: string;

@ApiPropertyOptional({ description: '직급 검색어 (예: 과장)' })
@IsOptional()
@IsString()
@MaxLength(50)
position?: 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;
}
41 changes: 41 additions & 0 deletions src/referral/referral-expiry.scheduler.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,47 @@ describe('ReferralExpiryScheduler', () => {
expect(statusOf('c-withdrawn')).toBe('WITHDRAWN');
});

it('게시 기간이 지난 PUBLISHED 게시물만 EXPIRED, 비공개·삭제 게시물은 그대로', async () => {
const posts = [
{ id: 'p-expired', status: 'PUBLISHED', expiresAt: new Date(NOW.getTime() - 1000) },
{ id: 'p-live', status: 'PUBLISHED', expiresAt: new Date(NOW.getTime() + 1000) },
{ id: 'p-hidden', status: 'HIDDEN', expiresAt: new Date(NOW.getTime() - 1000) },
{ id: 'p-deleted', status: 'DELETED', expiresAt: new Date(NOW.getTime() - 1000) },
];
const prisma: any = {
referralPost: {
updateMany: jest.fn(async ({ where, data }: any) => {
const targets = posts.filter((p) => p.status === where.status && p.expiresAt <= where.expiresAt.lte);
targets.forEach((p) => Object.assign(p, data));
return { count: targets.length };
}),
},
};

const count = await new ReferralExpiryScheduler(prisma as PrismaService).expirePublishedPosts(NOW);

expect(count).toBe(1);
expect(Object.fromEntries(posts.map((p) => [p.id, p.status]))).toEqual({
'p-expired': 'EXPIRED',
'p-live': 'PUBLISHED',
'p-hidden': 'HIDDEN',
'p-deleted': 'DELETED',
});
});

it('run은 동의 요청과 게시물 만료를 모두 처리한다', async () => {
const consentSpy = jest.spyOn(scheduler, 'expirePendingConsents').mockResolvedValue(1);
const postSpy = jest.spyOn(scheduler, 'expirePublishedPosts').mockResolvedValue(2);
const logSpy = jest.spyOn(Logger.prototype, 'log').mockImplementation(() => undefined);

await scheduler.run();

expect(consentSpy).toHaveBeenCalled();
expect(postSpy).toHaveBeenCalled();
expect(logSpy).toHaveBeenCalledWith('추천 만료 처리: 동의 요청 1건, 게시물 2건');
logSpy.mockRestore();
});

it('처리 중 오류가 나도 예외를 던지지 않고 로그만 남긴다', async () => {
const errorSpy = jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
jest.spyOn(scheduler, 'expirePendingConsents').mockRejectedValue(new Error('DB down'));
Expand Down
18 changes: 15 additions & 3 deletions src/referral/referral-expiry.scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { PrismaService } from '../prisma/prisma.service';
/**
* 인재 추천 만료 처리 (매시간).
* ScheduleModule.forRoot()는 이미 등록돼 있어 @Cron만 사용한다.
* 게시물 목록·상세는 만료 시각을 직접 비교하므로, 스케줄러가 돌기 전에도 만료된 게시물은 보이지 않는다.
*/
@Injectable()
export class ReferralExpiryScheduler {
Expand All @@ -15,9 +16,11 @@ export class ReferralExpiryScheduler {
@Cron(CronExpression.EVERY_HOUR)
async run(): Promise<void> {
try {
const expired = await this.expirePendingConsents();
if (expired > 0) {
this.logger.log(`추천 동의 요청 만료 처리: ${expired}건`);
const now = new Date();
const consents = await this.expirePendingConsents(now);
const posts = await this.expirePublishedPosts(now);
if (consents + posts > 0) {
this.logger.log(`추천 만료 처리: 동의 요청 ${consents}건, 게시물 ${posts}건`);
}
} catch (error) {
this.logger.error('추천 만료 처리 실패', error instanceof Error ? error.stack : String(error));
Expand All @@ -32,4 +35,13 @@ export class ReferralExpiryScheduler {
});
return count;
}

/** 게시 기간이 지난 PUBLISHED 게시물 → EXPIRED. 비공개·삭제된 게시물은 건드리지 않는다. 처리 건수 반환 */
async expirePublishedPosts(now: Date = new Date()): Promise<number> {
const { count } = await this.prisma.referralPost.updateMany({
where: { status: 'PUBLISHED', expiresAt: { lte: now } },
data: { status: 'EXPIRED' },
});
return count;
}
}
91 changes: 91 additions & 0 deletions src/referral/referral-post.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { Body, Controller, Delete, Get, HttpCode, HttpStatus, 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 { CreateReferralPostDto, ListReferralPostsQueryDto, UpdateReferralPostDto } from './dto/referral-post.dto';
import { ReferralPostService } from './referral-post.service';

/**
* 인재 추천 게시물.
* 작성·수정·삭제: 작성 기업 대표만 / 목록·상세: 모든 가입 기업의 대표·인사팀장
*/
@ApiTags('Referral')
@ApiBearerAuth('access-token')
@UseGuards(JwtAuthGuard, RolesGuard)
@Controller('referral/posts')
export class ReferralPostController {
constructor(private readonly referralPostService: ReferralPostService) {}

@Post()
@Roles('COMPANY')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: '대표: 인재 추천 게시물 작성 (동의 AGREED 직원, 이력서는 업로드 확인 후 첨부)' })
@ApiResponse({ status: 201, description: '작성 성공 { postId, status, publishedAt, expiresAt }' })
@ApiResponse({ status: 400, description: '필수값 누락 또는 형식 오류 (publishMonths 3·6)' })
@ApiResponse({ status: 401, description: '인증 필요' })
@ApiResponse({ status: 403, description: 'FORBIDDEN (대표 권한·직원 소속 불일치) / CONSENT_NOT_GIVEN (동의 없음·익명 동의인데 실명 게시)' })
@ApiResponse({ status: 404, description: 'EMPLOYEE_NOT_FOUND / RESUME_NOT_FOUND' })
@ApiResponse({ status: 409, description: 'ACTIVE_POST_EXISTS (공개 중인 게시물 존재)' })
@ApiResponse({ status: 422, description: 'INVALID_RECOMMENDATION_CONTENT (200자 초과·금지 표현) / RESUME_NOT_UPLOADED / RESUME_MISMATCH' })
@ResponseMessage('인재 추천 게시물 작성 성공')
create(@CurrentUser() user: JwtPayload, @Body() dto: CreateReferralPostDto) {
return this.referralPostService.create(user, dto);
}

@Get()
@Roles('COMPANY', 'HR_MANAGER')
@ApiOperation({ summary: '대표·인사팀장: 공개 중인 인재 추천 게시물 목록 (모든 기업, 익명은 이름 마스킹)' })
@ApiResponse({ status: 200, description: '조회 성공 { items, page, size, total }' })
@ApiResponse({ status: 400, description: '쿼리 형식 오류' })
@ApiResponse({ status: 401, description: '인증 필요' })
@ApiResponse({ status: 403, description: 'FORBIDDEN (대표·인사팀장 권한 아님)' })
@ResponseMessage('인재 추천 게시물 목록 조회 성공')
list(@CurrentUser() user: JwtPayload, @Query() query: ListReferralPostsQueryDto) {
return this.referralPostService.list(user, query);
}

@Get(':postId')
@Roles('COMPANY', 'HR_MANAGER')
@ApiOperation({ summary: '대표·인사팀장: 인재 추천 게시물 상세 (업로드 확인된 이력서는 5분 다운로드 URL)' })
@ApiParam({ name: 'postId', description: '게시물 ID' })
@ApiResponse({ status: 200, description: '조회 성공' })
@ApiResponse({ status: 401, description: '인증 필요' })
@ApiResponse({ status: 403, description: 'FORBIDDEN (대표·인사팀장 권한 아님)' })
@ApiResponse({ status: 404, description: 'REFERRAL_POST_NOT_FOUND (없음·비공개·동의 철회)' })
@ApiResponse({ status: 410, description: 'REFERRAL_POST_EXPIRED (게시 기간 만료)' })
@ResponseMessage('인재 추천 게시물 상세 조회 성공')
findOne(@CurrentUser() user: JwtPayload, @Param('postId') postId: string) {
return this.referralPostService.findOne(user, postId);
}

@Patch(':postId')
@Roles('COMPANY')
@ApiOperation({ summary: '작성 기업 대표: 추천 게시물 수정 (제목·추천 사유·이름 표시, 게시 기간 3 → 6개월 연장)' })
@ApiParam({ name: 'postId', description: '게시물 ID' })
@ApiResponse({ status: 200, description: '수정 성공 { postId, status, updatedAt, expiresAt }' })
@ApiResponse({ status: 403, description: 'FORBIDDEN (작성 기업 아님) / CONSENT_WITHDRAWN (동의 철회) / CONSENT_NOT_GIVEN (익명 동의인데 실명)' })
@ApiResponse({ status: 404, description: 'REFERRAL_POST_NOT_FOUND' })
@ApiResponse({ status: 410, description: 'REFERRAL_POST_EXPIRED' })
@ApiResponse({ status: 422, description: 'INVALID_RECOMMENDATION_CONTENT / INVALID_PUBLISH_PERIOD (기간 단축)' })
@ResponseMessage('인재 추천 게시물 수정 성공')
update(@CurrentUser() user: JwtPayload, @Param('postId') postId: string, @Body() dto: UpdateReferralPostDto) {
return this.referralPostService.update(user, postId, dto);
}

@Delete(':postId')
@Roles('COMPANY')
@ApiOperation({ summary: '작성 기업 대표: 추천 게시물 삭제 (소프트 삭제 DELETED)' })
@ApiParam({ name: 'postId', description: '게시물 ID' })
@ApiResponse({ status: 200, description: '삭제 성공 { postId, status, deletedAt }' })
@ApiResponse({ status: 403, description: 'FORBIDDEN (대표 권한 또는 작성 기업 불일치)' })
@ApiResponse({ status: 404, description: 'REFERRAL_POST_NOT_FOUND' })
@ApiResponse({ status: 409, description: 'ALREADY_HIDDEN (이미 삭제됨)' })
@ResponseMessage('인재 추천 게시물 삭제 성공')
remove(@CurrentUser() user: JwtPayload, @Param('postId') postId: string) {
return this.referralPostService.remove(user, postId);
}
}
Loading
Loading