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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
ALTER TABLE "tournament_entries"
ADD COLUMN "disqualified" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "disqualify_note" VARCHAR(200);
2 changes: 2 additions & 0 deletions fishing/apps/api/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,8 @@ model TournamentEntry {
bestLengthCm Decimal? @map("best_length_cm") @db.Decimal(5, 1)
bestCatchId String? @map("best_catch_id")
rank Int?
disqualified Boolean @default(false)
disqualifyNote String? @map("disqualify_note") @db.VarChar(200)
joinedAt DateTime @default(now()) @map("joined_at")

tournament Tournament @relation(fields: [tournamentId], references: [id])
Expand Down
11 changes: 11 additions & 0 deletions fishing/apps/api/src/tournaments/dto/set-participant.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { IsBoolean, IsOptional, IsString, MaxLength } from 'class-validator';

export class SetParticipantDto {
@IsBoolean()
disqualified: boolean;

@IsOptional()
@IsString()
@MaxLength(200)
note?: string;
}
64 changes: 64 additions & 0 deletions fishing/apps/api/src/tournaments/leaderboard.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { TournamentsService } from './tournaments.service';

describe('TournamentsService 실시간 순위', () => {
const prisma = {
user: { findUnique: jest.fn() },
tournament: { findUnique: jest.fn() },
tournamentEntry: { findMany: jest.fn(), findUnique: jest.fn(), update: jest.fn() },
catch: { findMany: jest.fn() },
};
const service = new TournamentsService(prisma as never);

beforeEach(() => {
jest.clearAllMocks();
prisma.tournament.findUnique.mockResolvedValue({
id: 'tour-1',
organizerId: 'org-1',
fishSpeciesId: null,
minLengthCm: null,
maxLengthCm: null,
startAt: new Date('2026-11-01T00:00:00.000Z'),
endAt: new Date('2026-11-02T00:00:00.000Z'),
});
});

it('저장된 최고 체장 대신 승인된 인증 기록으로 순위를 만든다', async () => {
prisma.tournamentEntry.findMany.mockResolvedValue([
{
id: 'entry-1',
userId: 'user-1',
disqualified: false,
paymentStatus: 'free',
bestLengthCm: 99,
user: { id: 'user-1', nickname: '하나', profileImage: null },
},
]);
prisma.catch.findMany.mockResolvedValue([
{
id: 'catch-1',
userId: 'user-1',
lengthCm: 32.5,
createdAt: new Date('2026-11-01T03:00:00.000Z'),
fishSpeciesId: 1,
},
]);

const rows = await service.getRanking('tour-1');
expect(rows).toEqual([
expect.objectContaining({ userId: 'user-1', bestLengthCm: 32.5, bestCatchId: 'catch-1', rank: 1 }),
]);
});

it('실격은 참가 행을 지우지 않고 표시만 바꾼다', async () => {
prisma.user.findUnique.mockResolvedValue({ id: 'org-1', role: 'organizer' });
prisma.tournamentEntry.findUnique.mockResolvedValue({ id: 'entry-1' });
prisma.tournamentEntry.update.mockResolvedValue({ id: 'entry-1', disqualified: true });

await service.setDisqualified('org-1', 'tour-1', 'user-1', true, '사진 재사용');

expect(prisma.tournamentEntry.update).toHaveBeenCalledWith({
where: { id: 'entry-1' },
data: { disqualified: true, disqualifyNote: '사진 재사용' },
});
});
});
69 changes: 69 additions & 0 deletions fishing/apps/api/src/tournaments/live-leaderboard.util.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { buildLiveLeaderboard, leaderboardCsv } from './live-leaderboard.util';

const tournament = {
fishSpeciesId: 7,
minLengthCm: 20,
maxLengthCm: 60,
startAt: new Date('2026-11-01T00:00:00.000Z'),
endAt: new Date('2026-11-03T00:00:00.000Z'),
};

function entry(userId: string, extra: Partial<{ disqualified: boolean; paymentStatus: string }> = {}) {
return {
id: `entry-${userId}`,
userId,
disqualified: extra.disqualified ?? false,
paymentStatus: extra.paymentStatus ?? 'free',
user: { id: userId, nickname: userId },
};
}

function fish(userId: string, lengthCm: number, at: string, extra: Partial<{ fishSpeciesId: number; status: string }> = {}) {
return {
id: `${userId}-${lengthCm}`,
userId,
lengthCm,
createdAt: new Date(at),
fishSpeciesId: extra.fishSpeciesId ?? 7,
status: extra.status ?? 'approved',
recordType: 'certified',
};
}

describe('실시간 대회 순위', () => {
it('기간·어종·체장에 맞는 가장 긴 기록으로 순위를 매긴다', () => {
const rows = buildLiveLeaderboard(
tournament,
[entry('a'), entry('b'), entry('c', { disqualified: true }), entry('d', { paymentStatus: 'pending' })],
[
fish('a', 30, '2026-11-01T01:00:00.000Z'),
fish('a', 41, '2026-11-01T02:00:00.000Z'),
fish('b', 41, '2026-11-01T00:30:00.000Z'),
fish('a', 70, '2026-11-01T03:00:00.000Z'),
fish('a', 50, '2026-10-31T00:00:00.000Z'),
fish('b', 55, '2026-11-02T00:00:00.000Z', { fishSpeciesId: 8 }),
fish('c', 59, '2026-11-01T04:00:00.000Z'),
fish('d', 58, '2026-11-01T04:00:00.000Z'),
],
);

expect(rows.map((row) => [row.userId, row.bestLengthCm, row.rank])).toEqual([
['b', 41, 1],
['a', 41, 2],
]);
});

it('결과 CSV는 순위와 닉네임을 담는다', () => {
const csv = leaderboardCsv([
{
id: 'e1',
userId: 'a',
user: { id: 'a', nickname: '홍,길동' },
bestLengthCm: 41,
bestCatchId: 'catch-1',
rank: 1,
},
]);
expect(csv).toBe('rank,nickname,length_cm,catch_id\n1,"홍,길동",41,catch-1');
});
});
94 changes: 94 additions & 0 deletions fishing/apps/api/src/tournaments/live-leaderboard.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
export type LeaderboardCatch = {
id: string;
userId: string;
lengthCm: number;
createdAt: Date;
fishSpeciesId?: number | null;
status?: string;
recordType?: string;
deletedAt?: Date | null;
};

export type LeaderboardEntry = {
id: string;
userId: string;
disqualified: boolean;
paymentStatus: string;
user: { id: string; nickname: string; profileImage?: string | null };
};

export type LeaderboardTournament = {
fishSpeciesId?: number | null;
minLengthCm?: number | null;
maxLengthCm?: number | null;
startAt: Date;
endAt: Date;
};

export type LeaderboardRow = {
id: string;
userId: string;
user: LeaderboardEntry['user'];
bestLengthCm: number;
bestCatchId: string;
rank: number;
};

export function buildLiveLeaderboard(
tournament: LeaderboardTournament,
entries: LeaderboardEntry[],
catches: LeaderboardCatch[],
): LeaderboardRow[] {
const eligible = new Map(
entries
.filter((entry) => !entry.disqualified && (entry.paymentStatus === 'free' || entry.paymentStatus === 'paid'))
.map((entry) => [entry.userId, entry]),
);
const best = new Map<string, LeaderboardCatch>();

for (const catch_ of catches) {
if (!eligible.has(catch_.userId) || !Number.isFinite(catch_.lengthCm)) continue;
if (catch_.deletedAt) continue;
if (catch_.status && catch_.status !== 'approved') continue;
if (catch_.recordType && catch_.recordType !== 'certified') continue;
if (catch_.createdAt < tournament.startAt || catch_.createdAt > tournament.endAt) continue;
if (tournament.fishSpeciesId && catch_.fishSpeciesId !== tournament.fishSpeciesId) continue;
if (tournament.minLengthCm != null && catch_.lengthCm < Number(tournament.minLengthCm)) continue;
if (tournament.maxLengthCm != null && catch_.lengthCm > Number(tournament.maxLengthCm)) continue;

const current = best.get(catch_.userId);
const better =
!current ||
catch_.lengthCm > current.lengthCm ||
(catch_.lengthCm === current.lengthCm && catch_.createdAt < current.createdAt);
if (better) best.set(catch_.userId, catch_);
}

return [...best.entries()]
.map(([userId, catch_]) => ({ entry: eligible.get(userId)!, catch_ }))
.sort((left, right) => {
if (right.catch_.lengthCm !== left.catch_.lengthCm) return right.catch_.lengthCm - left.catch_.lengthCm;
return left.catch_.createdAt.getTime() - right.catch_.createdAt.getTime();
})
.map((row, index) => ({
id: row.entry.id,
userId: row.entry.userId,
user: row.entry.user,
bestLengthCm: row.catch_.lengthCm,
bestCatchId: row.catch_.id,
rank: index + 1,
}));
}

export function leaderboardCsv(rows: LeaderboardRow[]): string {
const lines = ['rank,nickname,length_cm,catch_id'];
for (const row of rows) {
lines.push([row.rank, csvCell(row.user.nickname), row.bestLengthCm, row.bestCatchId].join(','));
}
return lines.join('\n');
}

function csvCell(value: string): string {
if (/[",\n]/.test(value)) return `"${value.replace(/"/g, '""')}"`;
return value;
}
38 changes: 37 additions & 1 deletion fishing/apps/api/src/tournaments/tournaments.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Controller, Get, Post, Patch, Delete, Param, Body, Query, UseGuards, UseInterceptors, UploadedFile } from '@nestjs/common';
import { Controller, Get, Post, Patch, Delete, Param, Body, Query, UseGuards, UseInterceptors, UploadedFile, Res } from '@nestjs/common';
import type { Response } from 'express';

import { ApiTags, ApiOperation, ApiBearerAuth, ApiConsumes } from '@nestjs/swagger';

Expand All @@ -9,6 +10,7 @@ import { CurrentUser } from '../common/decorators/current-user.decorator';
import { TournamentsService } from './tournaments.service';
import { SetDayCodeDto } from './dto/set-day-code.dto';
import { OrganizerTournamentDto } from './dto/organizer-tournament.dto';
import { SetParticipantDto } from './dto/set-participant.dto';

import { createImageUploadInterceptor, saveUploadedFile } from '../common/upload/upload.config';
import { ImageMagicInterceptor } from '../common/upload/image-magic.interceptor';
Expand Down Expand Up @@ -100,6 +102,40 @@ export class TournamentsController {
return { success: true, data: result };
}

@Get('organized/:id/participants')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: '대회 참가자. 실격은 삭제하지 않음' })
async listParticipants(@Param('id') id: string, @CurrentUser() user: any) {
const result = await this.tournamentsService.listParticipants(user.id, id);
return { success: true, data: result };
}

@Patch('organized/:id/participants/:userId')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: '참가자 실격 또는 복귀' })
async setParticipant(
@Param('id') id: string,
@Param('userId') userId: string,
@CurrentUser() user: any,
@Body() body: SetParticipantDto,
) {
const result = await this.tournamentsService.setDisqualified(user.id, id, userId, body.disqualified, body.note);
return { success: true, data: result };
}

@Get('organized/:id/export')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: '실시간 순위 CSV' })
async exportLeaderboard(@Param('id') id: string, @CurrentUser() user: any, @Res({ passthrough: true }) res: Response) {
const csv = await this.tournamentsService.exportLeaderboard(user.id, id);
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="tournament-${id}.csv"`);
return `\uFEFF${csv}`;
}

@Get(':id')

@ApiOperation({ summary: '대회 상세' })
Expand Down
Loading
Loading