feat(api): add tournament codes
This commit is contained in:
1 parent
705790bdab
commit
45c7fe34ca
10 files changed
+1329
No files matched your search
@@ -0,0 +1,52 @@
|
|||||||
|
import {
|
||||||
|
resolveRoundRobinTeamCount,
|
||||||
|
roundRobinPairCount,
|
||||||
|
roundRobinPairs,
|
||||||
|
shuffleInPlace,
|
||||||
|
} from './round-robin.util';
|
||||||
|
|
||||||
|
describe('round-robin util', () => {
|
||||||
|
it('builds every team pair in lexicographic order', () => {
|
||||||
|
expect(roundRobinPairs(2)).toEqual([
|
||||||
|
{ teamAIndex: 1, teamBIndex: 2 },
|
||||||
|
]);
|
||||||
|
expect(roundRobinPairs(4)).toEqual([
|
||||||
|
{ teamAIndex: 1, teamBIndex: 2 },
|
||||||
|
{ teamAIndex: 1, teamBIndex: 3 },
|
||||||
|
{ teamAIndex: 1, teamBIndex: 4 },
|
||||||
|
{ teamAIndex: 2, teamBIndex: 3 },
|
||||||
|
{ teamAIndex: 2, teamBIndex: 4 },
|
||||||
|
{ teamAIndex: 3, teamBIndex: 4 },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('counts round-robin pairs', () => {
|
||||||
|
expect(roundRobinPairCount(1)).toBe(0);
|
||||||
|
expect(roundRobinPairCount(6)).toBe(15);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves team count from teams first, then active participants', () => {
|
||||||
|
expect(
|
||||||
|
resolveRoundRobinTeamCount({
|
||||||
|
teams: [{ teamIndex: 1 }, { teamIndex: 2 }, { teamIndex: 3 }],
|
||||||
|
participants: Array.from({ length: 30 }, () => ({})),
|
||||||
|
}),
|
||||||
|
).toBe(3);
|
||||||
|
expect(
|
||||||
|
resolveRoundRobinTeamCount({
|
||||||
|
teams: [],
|
||||||
|
participants: [
|
||||||
|
...Array.from({ length: 29 }, () => ({})),
|
||||||
|
{ excluded: true },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shuffles in place with an injectable rng', () => {
|
||||||
|
const items = [1, 2, 3, 4];
|
||||||
|
const result = shuffleInPlace(items, () => 0);
|
||||||
|
expect(result).toBe(items);
|
||||||
|
expect(items).toEqual([2, 3, 4, 1]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
export interface RoundRobinPair {
|
||||||
|
teamAIndex: number;
|
||||||
|
teamBIndex: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RoundRobinTeamCountInput {
|
||||||
|
teams?: Array<{ teamIndex: number }>;
|
||||||
|
participants: Array<{ excluded?: boolean }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function roundRobinPairs(teamCount: number): RoundRobinPair[] {
|
||||||
|
const pairs: RoundRobinPair[] = [];
|
||||||
|
for (let teamAIndex = 1; teamAIndex <= teamCount; teamAIndex += 1) {
|
||||||
|
for (
|
||||||
|
let teamBIndex = teamAIndex + 1;
|
||||||
|
teamBIndex <= teamCount;
|
||||||
|
teamBIndex += 1
|
||||||
|
) {
|
||||||
|
pairs.push({ teamAIndex, teamBIndex });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pairs;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function roundRobinPairCount(teamCount: number): number {
|
||||||
|
if (teamCount < 2) return 0;
|
||||||
|
return (teamCount * (teamCount - 1)) / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveRoundRobinTeamCount(
|
||||||
|
match: RoundRobinTeamCountInput,
|
||||||
|
): number {
|
||||||
|
if (match.teams && match.teams.length > 0) {
|
||||||
|
return match.teams.length;
|
||||||
|
}
|
||||||
|
const activeParticipantCount = match.participants.filter(
|
||||||
|
(participant) => !participant.excluded,
|
||||||
|
).length;
|
||||||
|
return Math.floor(activeParticipantCount / 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shuffleInPlace<T>(
|
||||||
|
items: T[],
|
||||||
|
rng: () => number = Math.random,
|
||||||
|
): T[] {
|
||||||
|
for (let index = items.length - 1; index > 0; index -= 1) {
|
||||||
|
const swapIndex = Math.floor(rng() * (index + 1));
|
||||||
|
[items[index], items[swapIndex]] = [items[swapIndex], items[index]];
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
export const TOURNAMENT_CODE_PATTERN = /^[A-Z0-9-]{8,}$/i;
|
||||||
|
export const TOURNAMENT_CODE_EXPIRY_MARGIN_MS = 24 * 60 * 60 * 1000;
|
||||||
|
export const TOURNAMENT_CODE_EXPIRING_SOON_MS = 7 * 24 * 60 * 60 * 1000;
|
||||||
|
export const DEFAULT_TOURNAMENT_GAME_COUNT = 3;
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
UseGuards,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { CurrentUser } from '../auth/current-user.decorator';
|
||||||
|
import { Roles } from '../auth/roles.decorator';
|
||||||
|
import { RolesGuard } from '../auth/roles.guard';
|
||||||
|
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||||
|
import type {
|
||||||
|
TournamentCodeState,
|
||||||
|
UserDocument,
|
||||||
|
} from '../global/database/schema';
|
||||||
|
import { TournamentCodeService } from './tournament-code.service';
|
||||||
|
import type { BulkUploadTournamentCodesRequest } from './tournament-code.types';
|
||||||
|
|
||||||
|
@Controller('communities/:communityId/tournament-codes')
|
||||||
|
@Roles('owner', 'admin')
|
||||||
|
@UseGuards(RolesGuard)
|
||||||
|
export class TournamentCodeController {
|
||||||
|
constructor(private readonly tournamentCodeService: TournamentCodeService) {}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
public async bulkUpload(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Body() body: BulkUploadTournamentCodesRequest,
|
||||||
|
) {
|
||||||
|
this.assertSameCommunity(currentUser, communityId);
|
||||||
|
return this.tournamentCodeService.bulkUpload({
|
||||||
|
communityId,
|
||||||
|
uploadedBy: currentUser._id,
|
||||||
|
codes: body.codes ?? [],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
public async list(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Query('state') state?: TournamentCodeState,
|
||||||
|
@Query('limit') limit?: string,
|
||||||
|
) {
|
||||||
|
this.assertSameCommunity(currentUser, communityId);
|
||||||
|
return {
|
||||||
|
codes: await this.tournamentCodeService.list({
|
||||||
|
state,
|
||||||
|
limit: limit ? Number(limit) : undefined,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('stats')
|
||||||
|
public async stats(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
) {
|
||||||
|
this.assertSameCommunity(currentUser, communityId);
|
||||||
|
return this.tournamentCodeService.stats();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post(':id/release')
|
||||||
|
public async restore(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Param('id', ParseObjectIdPipe) id: mongoose.Types.ObjectId,
|
||||||
|
) {
|
||||||
|
this.assertSameCommunity(currentUser, communityId);
|
||||||
|
return this.tournamentCodeService.restoreToAvailable(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':id')
|
||||||
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
|
public async discard(
|
||||||
|
@CurrentUser() currentUser: UserDocument,
|
||||||
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
@Param('id', ParseObjectIdPipe) id: mongoose.Types.ObjectId,
|
||||||
|
) {
|
||||||
|
this.assertSameCommunity(currentUser, communityId);
|
||||||
|
await this.tournamentCodeService.discardAvailable(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertSameCommunity(
|
||||||
|
user: UserDocument,
|
||||||
|
communityId: mongoose.Types.ObjectId,
|
||||||
|
): void {
|
||||||
|
if (!user.communityId.equals(communityId)) {
|
||||||
|
throw new BadRequestException('Different community.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { TournamentCodeController } from './tournament-code.controller';
|
||||||
|
import { TournamentCodeScheduler } from './tournament-code.scheduler';
|
||||||
|
import { TournamentCodeService } from './tournament-code.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
controllers: [TournamentCodeController],
|
||||||
|
providers: [TournamentCodeService, TournamentCodeScheduler],
|
||||||
|
exports: [TournamentCodeService],
|
||||||
|
})
|
||||||
|
export class TournamentCodeModule {}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||||
|
import { TournamentCodeService } from './tournament-code.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
|
||||||
|
private readonly logger = new Logger(TournamentCodeScheduler.name);
|
||||||
|
private attachTimer?: NodeJS.Timeout;
|
||||||
|
private expireTimer?: NodeJS.Timeout;
|
||||||
|
|
||||||
|
constructor(private readonly tournamentCodeService: TournamentCodeService) {}
|
||||||
|
|
||||||
|
public onModuleInit() {
|
||||||
|
this.attachTimer = setInterval(() => {
|
||||||
|
void this.attachPending();
|
||||||
|
}, 30_000);
|
||||||
|
this.expireTimer = setInterval(() => {
|
||||||
|
void this.markExpired();
|
||||||
|
}, 60 * 60 * 1000);
|
||||||
|
this.attachTimer.unref?.();
|
||||||
|
this.expireTimer.unref?.();
|
||||||
|
|
||||||
|
void this.attachPending();
|
||||||
|
void this.markExpired();
|
||||||
|
}
|
||||||
|
|
||||||
|
public onModuleDestroy() {
|
||||||
|
if (this.attachTimer) clearInterval(this.attachTimer);
|
||||||
|
if (this.expireTimer) clearInterval(this.expireTimer);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async attachPending() {
|
||||||
|
try {
|
||||||
|
const touched = await this.tournamentCodeService.attachPendingMatches();
|
||||||
|
if (touched > 0) {
|
||||||
|
this.logger.debug(`Attached tournament codes for ${touched} matches.`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.warn(
|
||||||
|
`Failed to attach pending tournament codes: ${
|
||||||
|
error instanceof Error ? error.message : error
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async markExpired() {
|
||||||
|
try {
|
||||||
|
await this.tournamentCodeService.markExpired();
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.warn(
|
||||||
|
`Failed to mark expired tournament codes: ${
|
||||||
|
error instanceof Error ? error.message : error
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
import type { MatchDocument } from '../global/database/schema';
|
||||||
|
import { TournamentCodeService } from './tournament-code.service';
|
||||||
|
|
||||||
|
type TournamentCodeServiceInternals = TournamentCodeService & {
|
||||||
|
resolveRequiredSlots(match: MatchDocument): number;
|
||||||
|
resolveSeriesRefForGameNumber(
|
||||||
|
match: MatchDocument,
|
||||||
|
gameNumber: number,
|
||||||
|
): { teamAIndex: number; teamBIndex: number };
|
||||||
|
ensureGameSchedule(match: MatchDocument): void;
|
||||||
|
};
|
||||||
|
|
||||||
|
function createService() {
|
||||||
|
return new TournamentCodeService(
|
||||||
|
{} as never,
|
||||||
|
) as unknown as TournamentCodeServiceInternals;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MatchOverrides {
|
||||||
|
gameCount?: number;
|
||||||
|
gameMode?: 'pair' | 'bracket' | 'round-robin';
|
||||||
|
participants?: Array<{ excluded?: boolean }>;
|
||||||
|
teams?: Array<{ teamIndex: number }>;
|
||||||
|
gameSchedule?: Array<{
|
||||||
|
gameNumber: number;
|
||||||
|
teamAIndex: number;
|
||||||
|
teamBIndex: number;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createMatch(overrides: MatchOverrides): MatchDocument {
|
||||||
|
return {
|
||||||
|
gameCount: 1,
|
||||||
|
gameMode: 'pair',
|
||||||
|
participants: [],
|
||||||
|
teams: [],
|
||||||
|
gameSchedule: [],
|
||||||
|
...overrides,
|
||||||
|
} as unknown as MatchDocument;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('TournamentCodeService round-robin scheduling', () => {
|
||||||
|
it('keeps pair slot calculation unchanged', () => {
|
||||||
|
const service = createService();
|
||||||
|
const match = createMatch({
|
||||||
|
gameCount: 3,
|
||||||
|
teams: Array.from({ length: 6 }, (_, index) => ({
|
||||||
|
teamIndex: index + 1,
|
||||||
|
})),
|
||||||
|
participants: Array.from({ length: 30 }, () => ({})),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(service.resolveRequiredSlots(match)).toBe(9);
|
||||||
|
expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({
|
||||||
|
teamAIndex: 1,
|
||||||
|
teamBIndex: 2,
|
||||||
|
});
|
||||||
|
expect(service.resolveSeriesRefForGameNumber(match, 4)).toEqual({
|
||||||
|
teamAIndex: 3,
|
||||||
|
teamBIndex: 4,
|
||||||
|
});
|
||||||
|
expect(service.resolveSeriesRefForGameNumber(match, 7)).toEqual({
|
||||||
|
teamAIndex: 5,
|
||||||
|
teamBIndex: 6,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('calculates round-robin slots from team pairs and per-pair game count', () => {
|
||||||
|
const service = createService();
|
||||||
|
|
||||||
|
expect(
|
||||||
|
service.resolveRequiredSlots(
|
||||||
|
createMatch({
|
||||||
|
gameMode: 'round-robin',
|
||||||
|
gameCount: 1,
|
||||||
|
teams: Array.from({ length: 6 }, (_, index) => ({
|
||||||
|
teamIndex: index + 1,
|
||||||
|
})),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).toBe(15);
|
||||||
|
expect(
|
||||||
|
service.resolveRequiredSlots(
|
||||||
|
createMatch({
|
||||||
|
gameMode: 'round-robin',
|
||||||
|
gameCount: 2,
|
||||||
|
teams: Array.from({ length: 6 }, (_, index) => ({
|
||||||
|
teamIndex: index + 1,
|
||||||
|
})),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).toBe(30);
|
||||||
|
expect(
|
||||||
|
service.resolveRequiredSlots(
|
||||||
|
createMatch({
|
||||||
|
gameMode: 'round-robin',
|
||||||
|
gameCount: 1,
|
||||||
|
teams: [],
|
||||||
|
participants: Array.from({ length: 30 }, () => ({})),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
).toBe(15);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses persisted round-robin game schedule for game refs', () => {
|
||||||
|
const service = createService();
|
||||||
|
const match = createMatch({
|
||||||
|
gameMode: 'round-robin',
|
||||||
|
gameCount: 2,
|
||||||
|
gameSchedule: [
|
||||||
|
{ gameNumber: 1, teamAIndex: 2, teamBIndex: 5 },
|
||||||
|
{ gameNumber: 2, teamAIndex: 2, teamBIndex: 5 },
|
||||||
|
{ gameNumber: 3, teamAIndex: 1, teamBIndex: 4 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({
|
||||||
|
teamAIndex: 2,
|
||||||
|
teamBIndex: 5,
|
||||||
|
});
|
||||||
|
expect(service.resolveSeriesRefForGameNumber(match, 3)).toEqual({
|
||||||
|
teamAIndex: 1,
|
||||||
|
teamBIndex: 4,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to lexicographic round-robin pairs before schedule is persisted', () => {
|
||||||
|
const service = createService();
|
||||||
|
const match = createMatch({
|
||||||
|
gameMode: 'round-robin',
|
||||||
|
gameCount: 1,
|
||||||
|
teams: Array.from({ length: 4 }, (_, index) => ({
|
||||||
|
teamIndex: index + 1,
|
||||||
|
})),
|
||||||
|
gameSchedule: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({
|
||||||
|
teamAIndex: 1,
|
||||||
|
teamBIndex: 2,
|
||||||
|
});
|
||||||
|
expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({
|
||||||
|
teamAIndex: 1,
|
||||||
|
teamBIndex: 3,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates a round-robin schedule once and leaves pair matches empty', () => {
|
||||||
|
const service = createService();
|
||||||
|
const roundRobin = createMatch({
|
||||||
|
gameMode: 'round-robin',
|
||||||
|
gameCount: 2,
|
||||||
|
teams: Array.from({ length: 4 }, (_, index) => ({
|
||||||
|
teamIndex: index + 1,
|
||||||
|
})),
|
||||||
|
gameSchedule: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
service.ensureGameSchedule(roundRobin);
|
||||||
|
expect(roundRobin.gameSchedule).toHaveLength(12);
|
||||||
|
const persisted = [...roundRobin.gameSchedule];
|
||||||
|
service.ensureGameSchedule(roundRobin);
|
||||||
|
expect(roundRobin.gameSchedule).toEqual(persisted);
|
||||||
|
|
||||||
|
const pair = createMatch({
|
||||||
|
gameMode: 'pair',
|
||||||
|
teams: Array.from({ length: 4 }, (_, index) => ({
|
||||||
|
teamIndex: index + 1,
|
||||||
|
})),
|
||||||
|
gameSchedule: [],
|
||||||
|
});
|
||||||
|
service.ensureGameSchedule(pair);
|
||||||
|
expect(pair.gameSchedule).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not expose fallback round-robin slots before the schedule is persisted', async () => {
|
||||||
|
const service = createService();
|
||||||
|
const slots = await service.buildSlots(
|
||||||
|
createMatch({
|
||||||
|
gameMode: 'round-robin',
|
||||||
|
gameCount: 1,
|
||||||
|
teams: Array.from({ length: 6 }, (_, index) => ({
|
||||||
|
teamIndex: index + 1,
|
||||||
|
})),
|
||||||
|
gameSchedule: [],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(slots).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,470 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import mongoose from 'mongoose';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type {
|
||||||
|
MatchGameAssignment,
|
||||||
|
MatchDocument,
|
||||||
|
TournamentCode,
|
||||||
|
TournamentCodeDocument,
|
||||||
|
TournamentCodeState,
|
||||||
|
TournamentSpectatorType,
|
||||||
|
} from '../global/database/schema';
|
||||||
|
import {
|
||||||
|
DEFAULT_TOURNAMENT_GAME_COUNT,
|
||||||
|
TOURNAMENT_CODE_EXPIRING_SOON_MS,
|
||||||
|
TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
|
||||||
|
TOURNAMENT_CODE_PATTERN,
|
||||||
|
} from './tournament-code.constants';
|
||||||
|
import type {
|
||||||
|
BulkUploadTournamentCodesResponse,
|
||||||
|
TournamentCodeSlotView,
|
||||||
|
TournamentCodeUploadItem,
|
||||||
|
} from './tournament-code.types';
|
||||||
|
import {
|
||||||
|
resolveRoundRobinTeamCount,
|
||||||
|
roundRobinPairCount,
|
||||||
|
roundRobinPairs,
|
||||||
|
shuffleInPlace,
|
||||||
|
} from './round-robin.util';
|
||||||
|
|
||||||
|
const DEFAULT_REGION = 'kr';
|
||||||
|
const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TournamentCodeService {
|
||||||
|
constructor(private readonly connectionService: ConnectionService) {}
|
||||||
|
|
||||||
|
public async bulkUpload(params: {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
uploadedBy: mongoose.Types.ObjectId;
|
||||||
|
codes: TournamentCodeUploadItem[];
|
||||||
|
}): Promise<BulkUploadTournamentCodesResponse> {
|
||||||
|
const TournamentCodeModel =
|
||||||
|
await this.connectionService.getModel('tournamentCode');
|
||||||
|
const invalid: BulkUploadTournamentCodesResponse['invalid'] = [];
|
||||||
|
const duplicates: string[] = [];
|
||||||
|
const valid: Array<
|
||||||
|
Omit<TournamentCode, 'createdAt' | 'updatedAt'> & {
|
||||||
|
uploadedBy: mongoose.Types.ObjectId;
|
||||||
|
}
|
||||||
|
> = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
|
||||||
|
for (const item of params.codes) {
|
||||||
|
const code = this.normalizeCode(item.code);
|
||||||
|
if (!code) {
|
||||||
|
invalid.push({ code: item.code ?? '', reason: 'empty-code' });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!TOURNAMENT_CODE_PATTERN.test(code)) {
|
||||||
|
invalid.push({ code, reason: 'invalid-format' });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (seen.has(code)) {
|
||||||
|
duplicates.push(code);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seen.add(code);
|
||||||
|
|
||||||
|
const expiresAt = new Date(item.expiresAt);
|
||||||
|
if (Number.isNaN(expiresAt.getTime())) {
|
||||||
|
invalid.push({ code, reason: 'invalid-expiresAt' });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (expiresAt <= new Date()) {
|
||||||
|
invalid.push({ code, reason: 'expired-expiresAt' });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
valid.push({
|
||||||
|
code,
|
||||||
|
region: DEFAULT_REGION,
|
||||||
|
mapType: 'SUMMONERS_RIFT',
|
||||||
|
teamSize: 5,
|
||||||
|
spectatorType: item.spectatorType ?? DEFAULT_SPECTATOR_TYPE,
|
||||||
|
metadata: item.metadata,
|
||||||
|
expiresAt,
|
||||||
|
state: 'available',
|
||||||
|
uploadedBy: params.uploadedBy,
|
||||||
|
uploadedAt: new Date(),
|
||||||
|
source: item.source,
|
||||||
|
notes: item.notes,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (valid.length === 0) {
|
||||||
|
return { inserted: 0, duplicates, invalid };
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await TournamentCodeModel.find({
|
||||||
|
code: { $in: valid.map((item) => item.code) },
|
||||||
|
})
|
||||||
|
.select({ code: 1 })
|
||||||
|
.lean()
|
||||||
|
.exec();
|
||||||
|
const existingCodes = new Set(existing.map((item) => item.code));
|
||||||
|
duplicates.push(...existing.map((item) => item.code));
|
||||||
|
|
||||||
|
const insertable = valid.filter((item) => !existingCodes.has(item.code));
|
||||||
|
if (insertable.length > 0) {
|
||||||
|
await TournamentCodeModel.insertMany(insertable, { ordered: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.attachPendingMatches(params.communityId);
|
||||||
|
|
||||||
|
return {
|
||||||
|
inserted: insertable.length,
|
||||||
|
duplicates: [...new Set(duplicates)],
|
||||||
|
invalid,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public async list(params: {
|
||||||
|
state?: TournamentCodeState;
|
||||||
|
limit?: number;
|
||||||
|
}): Promise<TournamentCodeDocument[]> {
|
||||||
|
const TournamentCodeModel =
|
||||||
|
await this.connectionService.getModel('tournamentCode');
|
||||||
|
const filter: { state?: TournamentCodeState } = {};
|
||||||
|
if (params.state) filter.state = params.state;
|
||||||
|
return TournamentCodeModel.find(filter)
|
||||||
|
.sort({ expiresAt: 1, uploadedAt: -1 })
|
||||||
|
.limit(Math.min(params.limit ?? 100, 300))
|
||||||
|
.exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async stats(): Promise<{
|
||||||
|
byState: Record<TournamentCodeState, number>;
|
||||||
|
expiringSoon: number;
|
||||||
|
available: number;
|
||||||
|
}> {
|
||||||
|
const TournamentCodeModel =
|
||||||
|
await this.connectionService.getModel('tournamentCode');
|
||||||
|
const states: TournamentCodeState[] = [
|
||||||
|
'available',
|
||||||
|
'reserved',
|
||||||
|
'used',
|
||||||
|
'expired',
|
||||||
|
'released',
|
||||||
|
];
|
||||||
|
const counts = await TournamentCodeModel.aggregate<{
|
||||||
|
_id: TournamentCodeState;
|
||||||
|
count: number;
|
||||||
|
}>([{ $group: { _id: '$state', count: { $sum: 1 } } }]).exec();
|
||||||
|
const byState = Object.fromEntries(states.map((state) => [state, 0])) as Record<
|
||||||
|
TournamentCodeState,
|
||||||
|
number
|
||||||
|
>;
|
||||||
|
for (const entry of counts) byState[entry._id] = entry.count;
|
||||||
|
|
||||||
|
const expiringSoon = await TournamentCodeModel.countDocuments({
|
||||||
|
state: 'available',
|
||||||
|
expiresAt: {
|
||||||
|
$gt: new Date(),
|
||||||
|
$lte: new Date(Date.now() + TOURNAMENT_CODE_EXPIRING_SOON_MS),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return { byState, expiringSoon, available: byState.available };
|
||||||
|
}
|
||||||
|
|
||||||
|
public async discardAvailable(id: mongoose.Types.ObjectId): Promise<void> {
|
||||||
|
const TournamentCodeModel =
|
||||||
|
await this.connectionService.getModel('tournamentCode');
|
||||||
|
const result = await TournamentCodeModel.deleteOne({
|
||||||
|
_id: id,
|
||||||
|
state: 'available',
|
||||||
|
}).exec();
|
||||||
|
if (result.deletedCount === 0) {
|
||||||
|
throw new BadRequestException('Only available tournament codes can be deleted.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async restoreToAvailable(
|
||||||
|
id: mongoose.Types.ObjectId,
|
||||||
|
): Promise<TournamentCodeDocument> {
|
||||||
|
const TournamentCodeModel =
|
||||||
|
await this.connectionService.getModel('tournamentCode');
|
||||||
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
|
const code = await TournamentCodeModel.findById(id);
|
||||||
|
if (!code) throw new NotFoundException('Tournament code not found.');
|
||||||
|
if (code.state !== 'released' && code.state !== 'reserved') {
|
||||||
|
throw new BadRequestException(
|
||||||
|
'Only released or reserved tournament codes can be restored.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const previousMatchId = code.matchId;
|
||||||
|
code.state = 'available';
|
||||||
|
code.matchId = undefined;
|
||||||
|
code.gameNumber = undefined;
|
||||||
|
code.reservedAt = undefined;
|
||||||
|
code.releasedAt = undefined;
|
||||||
|
await code.save();
|
||||||
|
if (previousMatchId) {
|
||||||
|
await MatchModel.updateOne(
|
||||||
|
{ _id: previousMatchId },
|
||||||
|
{ $pull: { tournamentCodeIds: code._id } },
|
||||||
|
).exec();
|
||||||
|
await this.attachPendingMatches();
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async reserveForMatch(
|
||||||
|
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
||||||
|
): Promise<MatchDocument> {
|
||||||
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
|
const TournamentCodeModel =
|
||||||
|
await this.connectionService.getModel('tournamentCode');
|
||||||
|
const match =
|
||||||
|
matchOrId instanceof mongoose.Types.ObjectId
|
||||||
|
? await MatchModel.findById(matchOrId)
|
||||||
|
: await MatchModel.findById(matchOrId._id);
|
||||||
|
if (!match) throw new NotFoundException('Match not found.');
|
||||||
|
|
||||||
|
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||||
|
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
||||||
|
this.ensureGameSchedule(match);
|
||||||
|
const shouldSaveMetadata =
|
||||||
|
match.isModified('gameCount') || match.isModified('gameSchedule');
|
||||||
|
const requiredSlots = this.resolveRequiredSlots(match);
|
||||||
|
const need = requiredSlots - match.tournamentCodeIds.length;
|
||||||
|
if (need <= 0) {
|
||||||
|
if (shouldSaveMetadata) await match.save();
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
|
||||||
|
const reservedIds: mongoose.Types.ObjectId[] = [];
|
||||||
|
const startGameNumber = match.tournamentCodeIds.length + 1;
|
||||||
|
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
|
||||||
|
|
||||||
|
for (let index = 0; index < need; index += 1) {
|
||||||
|
const code = await TournamentCodeModel.findOneAndUpdate(
|
||||||
|
{
|
||||||
|
state: 'available',
|
||||||
|
region: DEFAULT_REGION,
|
||||||
|
mapType: 'SUMMONERS_RIFT',
|
||||||
|
teamSize: 5,
|
||||||
|
expiresAt: { $gt: expiresAfter },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
state: 'reserved',
|
||||||
|
matchId: match._id,
|
||||||
|
gameNumber: startGameNumber + index,
|
||||||
|
reservedAt: new Date(),
|
||||||
|
},
|
||||||
|
$unset: { releasedAt: 1 },
|
||||||
|
},
|
||||||
|
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
||||||
|
).exec();
|
||||||
|
if (!code) break;
|
||||||
|
reservedIds.push(code._id);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (reservedIds.length > 0) {
|
||||||
|
match.tournamentCodeIds.push(...reservedIds);
|
||||||
|
}
|
||||||
|
if (reservedIds.length > 0 || shouldSaveMetadata) {
|
||||||
|
await match.save();
|
||||||
|
}
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async releaseFromMatch(
|
||||||
|
matchOrId: MatchDocument | mongoose.Types.ObjectId,
|
||||||
|
): Promise<void> {
|
||||||
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
|
const TournamentCodeModel =
|
||||||
|
await this.connectionService.getModel('tournamentCode');
|
||||||
|
const match =
|
||||||
|
matchOrId instanceof mongoose.Types.ObjectId
|
||||||
|
? await MatchModel.findById(matchOrId)
|
||||||
|
: await MatchModel.findById(matchOrId._id);
|
||||||
|
if (!match) return;
|
||||||
|
if (match.tournamentCodeIds.length === 0) return;
|
||||||
|
|
||||||
|
await TournamentCodeModel.updateMany(
|
||||||
|
{ _id: { $in: match.tournamentCodeIds }, state: 'reserved' },
|
||||||
|
{
|
||||||
|
$set: { state: 'released', releasedAt: new Date() },
|
||||||
|
$unset: { matchId: 1, gameNumber: 1, reservedAt: 1 },
|
||||||
|
},
|
||||||
|
).exec();
|
||||||
|
|
||||||
|
match.tournamentCodeIds = [];
|
||||||
|
await match.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async markExpired(): Promise<number> {
|
||||||
|
const TournamentCodeModel =
|
||||||
|
await this.connectionService.getModel('tournamentCode');
|
||||||
|
const result = await TournamentCodeModel.updateMany(
|
||||||
|
{
|
||||||
|
state: { $in: ['available', 'reserved', 'released'] },
|
||||||
|
expiresAt: { $lte: new Date() },
|
||||||
|
},
|
||||||
|
{ $set: { state: 'expired' } },
|
||||||
|
).exec();
|
||||||
|
return result.modifiedCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async attachPendingMatches(
|
||||||
|
communityId?: mongoose.Types.ObjectId,
|
||||||
|
): Promise<number> {
|
||||||
|
const MatchModel = await this.connectionService.getModel('match');
|
||||||
|
const filter: {
|
||||||
|
status: { $in: string[] };
|
||||||
|
communityId?: mongoose.Types.ObjectId;
|
||||||
|
} = {
|
||||||
|
status: { $in: ['team-built', 'in-progress'] },
|
||||||
|
};
|
||||||
|
if (communityId) filter.communityId = communityId;
|
||||||
|
|
||||||
|
const matches = await MatchModel.find(filter).exec();
|
||||||
|
let touched = 0;
|
||||||
|
for (const match of matches) {
|
||||||
|
if ((match.tournamentCodeIds?.length ?? 0) >= this.resolveRequiredSlots(match)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const before = match.tournamentCodeIds?.length ?? 0;
|
||||||
|
await this.reserveForMatch(match);
|
||||||
|
const after = match.tournamentCodeIds?.length ?? 0;
|
||||||
|
if (after > before) touched += 1;
|
||||||
|
}
|
||||||
|
return touched;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async buildSlots(match: MatchDocument): Promise<TournamentCodeSlotView[]> {
|
||||||
|
if (
|
||||||
|
(match.gameMode ?? 'pair') === 'round-robin' &&
|
||||||
|
(match.gameSchedule?.length ?? 0) === 0 &&
|
||||||
|
(match.tournamentCodeIds?.length ?? 0) === 0
|
||||||
|
) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const TournamentCodeModel =
|
||||||
|
await this.connectionService.getModel('tournamentCode');
|
||||||
|
const gameCount = this.resolveRequiredSlots(match);
|
||||||
|
const ids = match.tournamentCodeIds ?? [];
|
||||||
|
const codes =
|
||||||
|
ids.length > 0
|
||||||
|
? await TournamentCodeModel.find({ _id: { $in: ids } }).exec()
|
||||||
|
: [];
|
||||||
|
const byGameNumber = new Map(
|
||||||
|
codes
|
||||||
|
.filter((code) => typeof code.gameNumber === 'number')
|
||||||
|
.map((code) => [code.gameNumber as number, code]),
|
||||||
|
);
|
||||||
|
|
||||||
|
return Array.from({ length: gameCount }, (_, index) => {
|
||||||
|
const gameNumber = index + 1;
|
||||||
|
const code = byGameNumber.get(gameNumber);
|
||||||
|
if (!code) {
|
||||||
|
const seriesRef = this.resolveSeriesRefForGameNumber(match, gameNumber);
|
||||||
|
return {
|
||||||
|
gameNumber,
|
||||||
|
...seriesRef,
|
||||||
|
code: null,
|
||||||
|
expiresAt: null,
|
||||||
|
state: 'pending',
|
||||||
|
riotMatchId: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
gameNumber,
|
||||||
|
...this.resolveSeriesRefForGameNumber(match, gameNumber),
|
||||||
|
code: code.code,
|
||||||
|
expiresAt: code.expiresAt.toISOString(),
|
||||||
|
state: code.state,
|
||||||
|
riotMatchId: code.riotMatchId ?? null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeCode(code: string | undefined): string {
|
||||||
|
return (code ?? '').trim().toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveRequiredSlots(match: MatchDocument): number {
|
||||||
|
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||||
|
const gameMode = match.gameMode ?? 'pair';
|
||||||
|
|
||||||
|
if (gameMode === 'round-robin') {
|
||||||
|
const teamCount = resolveRoundRobinTeamCount(match);
|
||||||
|
return roundRobinPairCount(teamCount) * gameCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
const teamCount = (match.teams ?? []).length;
|
||||||
|
const activeParticipantCount = (match.participants ?? []).filter(
|
||||||
|
(participant) => !participant.excluded,
|
||||||
|
).length;
|
||||||
|
const participantSeriesCount = Math.floor(activeParticipantCount / 10);
|
||||||
|
const teamSeriesCount = Math.ceil(teamCount / 2);
|
||||||
|
const seriesCount = Math.max(1, teamSeriesCount, participantSeriesCount);
|
||||||
|
return seriesCount * gameCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveSeriesRefForGameNumber(
|
||||||
|
match: MatchDocument,
|
||||||
|
gameNumber: number,
|
||||||
|
): { teamAIndex: number; teamBIndex: number } {
|
||||||
|
const gameMode = match.gameMode ?? 'pair';
|
||||||
|
|
||||||
|
if (gameMode === 'round-robin') {
|
||||||
|
const persisted = match.gameSchedule?.find(
|
||||||
|
(entry) => entry.gameNumber === gameNumber,
|
||||||
|
);
|
||||||
|
if (persisted) {
|
||||||
|
return {
|
||||||
|
teamAIndex: persisted.teamAIndex,
|
||||||
|
teamBIndex: persisted.teamBIndex,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const teamCount = resolveRoundRobinTeamCount(match);
|
||||||
|
const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||||
|
const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1);
|
||||||
|
return roundRobinPairs(teamCount)[pairIndex] ?? {
|
||||||
|
teamAIndex: 1,
|
||||||
|
teamBIndex: 2,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||||
|
const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
|
||||||
|
return {
|
||||||
|
teamAIndex: (seriesIndex - 1) * 2 + 1,
|
||||||
|
teamBIndex: (seriesIndex - 1) * 2 + 2,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureGameSchedule(match: MatchDocument): void {
|
||||||
|
if ((match.gameMode ?? 'pair') !== 'round-robin') return;
|
||||||
|
if ((match.gameSchedule?.length ?? 0) > 0) return;
|
||||||
|
|
||||||
|
const teamCount = resolveRoundRobinTeamCount(match);
|
||||||
|
if (teamCount < 2) return;
|
||||||
|
|
||||||
|
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||||
|
const pairs = shuffleInPlace([...roundRobinPairs(teamCount)]);
|
||||||
|
const schedule: MatchGameAssignment[] = [];
|
||||||
|
|
||||||
|
for (let pairIndex = 0; pairIndex < pairs.length; pairIndex += 1) {
|
||||||
|
const pair = pairs[pairIndex];
|
||||||
|
for (let gameIndex = 0; gameIndex < gameCount; gameIndex += 1) {
|
||||||
|
schedule.push({
|
||||||
|
gameNumber: pairIndex * gameCount + gameIndex + 1,
|
||||||
|
teamAIndex: pair.teamAIndex,
|
||||||
|
teamBIndex: pair.teamBIndex,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match.gameSchedule = schedule;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import type {
|
||||||
|
TournamentCodeState,
|
||||||
|
TournamentSpectatorType,
|
||||||
|
} from '../global/database/schema';
|
||||||
|
|
||||||
|
export interface TournamentCodeUploadItem {
|
||||||
|
code: string;
|
||||||
|
expiresAt: string;
|
||||||
|
spectatorType?: TournamentSpectatorType;
|
||||||
|
metadata?: Record<string, unknown>;
|
||||||
|
source?: string;
|
||||||
|
notes?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BulkUploadTournamentCodesRequest {
|
||||||
|
codes: TournamentCodeUploadItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BulkUploadTournamentCodesResponse {
|
||||||
|
inserted: number;
|
||||||
|
duplicates: string[];
|
||||||
|
invalid: Array<{ code: string; reason: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TournamentCodeSlotView {
|
||||||
|
gameNumber: number;
|
||||||
|
teamAIndex: number;
|
||||||
|
teamBIndex: number;
|
||||||
|
code: string | null;
|
||||||
|
expiresAt: string | null;
|
||||||
|
state: TournamentCodeState | 'pending';
|
||||||
|
riotMatchId: string | null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,355 @@
|
|||||||
|
import { useMemo, useState } from 'react';
|
||||||
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { Link, useParams } from 'react-router';
|
||||||
|
import {
|
||||||
|
useBulkUploadTournamentCodes,
|
||||||
|
useDeleteTournamentCode,
|
||||||
|
useMe,
|
||||||
|
useRestoreTournamentCode,
|
||||||
|
useTournamentCodes,
|
||||||
|
useTournamentCodeStats,
|
||||||
|
} from '../../api/hooks';
|
||||||
|
import type {
|
||||||
|
TournamentCodeState,
|
||||||
|
TournamentCodeUploadItem,
|
||||||
|
} from '../../api/types';
|
||||||
|
import { DEFAULT_COMMUNITY_ID } from '../../config';
|
||||||
|
|
||||||
|
const STATES: TournamentCodeState[] = [
|
||||||
|
'available',
|
||||||
|
'reserved',
|
||||||
|
'released',
|
||||||
|
'used',
|
||||||
|
'expired',
|
||||||
|
];
|
||||||
|
|
||||||
|
function formatDate(value: string | undefined) {
|
||||||
|
if (!value) return '-';
|
||||||
|
return new Intl.DateTimeFormat('ko-KR', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit',
|
||||||
|
}).format(new Date(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseCsv(text: string): TournamentCodeUploadItem[] {
|
||||||
|
return text
|
||||||
|
.split(/\r?\n/u)
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((line) => {
|
||||||
|
const [code, expiresAt, notes] = line.split(',').map((part) => part.trim());
|
||||||
|
return { code, expiresAt, notes };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseJson(text: string): TournamentCodeUploadItem[] {
|
||||||
|
const parsed = JSON.parse(text) as unknown;
|
||||||
|
if (Array.isArray(parsed)) return parsed as TournamentCodeUploadItem[];
|
||||||
|
if (
|
||||||
|
typeof parsed === 'object' &&
|
||||||
|
parsed !== null &&
|
||||||
|
'codes' in parsed &&
|
||||||
|
Array.isArray((parsed as { codes: unknown }).codes)
|
||||||
|
) {
|
||||||
|
return (parsed as { codes: TournamentCodeUploadItem[] }).codes;
|
||||||
|
}
|
||||||
|
throw new Error('JSON은 배열 또는 { codes: [...] } 형태여야 합니다.');
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function TournamentCodesPage() {
|
||||||
|
const { cid } = useParams();
|
||||||
|
const communityId = cid ?? DEFAULT_COMMUNITY_ID;
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const meQuery = useMe();
|
||||||
|
const [stateFilter, setStateFilter] = useState<TournamentCodeState | ''>('');
|
||||||
|
const [mode, setMode] = useState<'csv' | 'json'>('csv');
|
||||||
|
const [text, setText] = useState('');
|
||||||
|
const [message, setMessage] = useState<string | null>(null);
|
||||||
|
const currentUser =
|
||||||
|
meQuery.data?.memberships.find(
|
||||||
|
(membership) => membership.community?._id === communityId,
|
||||||
|
)?.user ?? null;
|
||||||
|
const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin';
|
||||||
|
const manageableMemberships =
|
||||||
|
meQuery.data?.memberships.filter((membership) => {
|
||||||
|
const role = membership.user.role;
|
||||||
|
return Boolean(
|
||||||
|
membership.community && (role === 'owner' || role === 'admin'),
|
||||||
|
);
|
||||||
|
}) ?? [];
|
||||||
|
const statsQuery = useTournamentCodeStats(communityId, canManage);
|
||||||
|
const listQuery = useTournamentCodes(
|
||||||
|
{ state: stateFilter || undefined, limit: 200 },
|
||||||
|
communityId,
|
||||||
|
canManage,
|
||||||
|
);
|
||||||
|
const uploadMutation = useBulkUploadTournamentCodes(communityId);
|
||||||
|
const restoreMutation = useRestoreTournamentCode(communityId);
|
||||||
|
const deleteMutation = useDeleteTournamentCode(communityId);
|
||||||
|
|
||||||
|
const counts = statsQuery.data?.byState;
|
||||||
|
const codes = useMemo(
|
||||||
|
() => listQuery.data?.codes ?? [],
|
||||||
|
[listQuery.data?.codes],
|
||||||
|
);
|
||||||
|
|
||||||
|
async function invalidate() {
|
||||||
|
await Promise.all([
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ['tournament-code-stats', communityId],
|
||||||
|
}),
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ['tournament-codes', communityId],
|
||||||
|
}),
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ['matches', communityId],
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleUpload() {
|
||||||
|
setMessage(null);
|
||||||
|
let payload: TournamentCodeUploadItem[];
|
||||||
|
try {
|
||||||
|
payload = mode === 'csv' ? parseCsv(text) : parseJson(text);
|
||||||
|
} catch (error) {
|
||||||
|
setMessage(error instanceof Error ? error.message : '입력 파싱 실패');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
uploadMutation.mutate(payload, {
|
||||||
|
onSuccess: async (result) => {
|
||||||
|
await invalidate();
|
||||||
|
setMessage(
|
||||||
|
`업로드 완료: ${result.inserted}개 추가, 중복 ${result.duplicates.length}개, invalid ${result.invalid.length}개`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
setMessage(error instanceof Error ? error.message : '업로드 실패');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!communityId) {
|
||||||
|
return (
|
||||||
|
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
|
||||||
|
<h1 className="text-lg font-bold">커뮤니티 설정이 필요합니다</h1>
|
||||||
|
<p className="mt-2 text-sm text-base-content/40">
|
||||||
|
`VITE_DEFAULT_COMMUNITY_ID`를 설정하거나 올바른 커뮤니티 경로로
|
||||||
|
접속해주세요.
|
||||||
|
</p>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (meQuery.isPending) {
|
||||||
|
return (
|
||||||
|
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
|
||||||
|
<h1 className="text-lg font-bold">권한 확인 중...</h1>
|
||||||
|
<p className="mt-2 text-sm text-base-content/40">
|
||||||
|
로그인한 계정의 커뮤니티 권한을 확인하고 있습니다.
|
||||||
|
</p>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!canManage) {
|
||||||
|
return (
|
||||||
|
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
|
||||||
|
<h1 className="text-lg font-bold">권한이 필요합니다</h1>
|
||||||
|
<p className="mt-2 text-sm text-base-content/40">
|
||||||
|
토너먼트 코드 풀은 owner/admin만 관리할 수 있습니다.
|
||||||
|
</p>
|
||||||
|
{manageableMemberships.length > 0 && (
|
||||||
|
<div className="mt-5 flex flex-wrap justify-center gap-2">
|
||||||
|
{manageableMemberships.map((membership) => (
|
||||||
|
<Link
|
||||||
|
key={membership.community?._id ?? membership.user._id}
|
||||||
|
to={`/admin/communities/${membership.community?._id}/tournament-codes`}
|
||||||
|
className="btn btn-primary btn-sm px-4 text-xs"
|
||||||
|
>
|
||||||
|
{membership.community?.name ?? '관리 가능한 커뮤니티'}로 이동
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
|
||||||
|
<Link
|
||||||
|
to="/"
|
||||||
|
className="inline-flex text-xs text-base-content/40 hover:text-base-content mb-5"
|
||||||
|
>
|
||||||
|
← 목록으로
|
||||||
|
</Link>
|
||||||
|
<div className="mb-6">
|
||||||
|
<h1 className="text-2xl font-black text-base-content">
|
||||||
|
토너먼트 코드 풀
|
||||||
|
</h1>
|
||||||
|
<p className="mt-1 text-sm text-base-content/45">
|
||||||
|
외부에서 생성한 코드를 업로드하고, 매치에 자동 할당되는 풀을 관리합니다.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section className="grid sm:grid-cols-5 gap-3 mb-6">
|
||||||
|
{STATES.map((state) => (
|
||||||
|
<div key={state} className="border border-base-content/10 bg-base-100 p-4">
|
||||||
|
<div className="text-[10px] uppercase tracking-wider text-base-content/30">
|
||||||
|
{state}
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 text-2xl font-black tabular-nums">
|
||||||
|
{counts?.[state] ?? 0}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="border border-base-content/10 bg-base-100 p-4 mb-6">
|
||||||
|
<div className="flex items-center justify-between gap-3 mb-3">
|
||||||
|
<h2 className="text-sm font-bold">Bulk 업로드</h2>
|
||||||
|
<div className="flex gap-1">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`px-3 py-1 text-xs border ${mode === 'csv' ? 'border-primary/40 text-primary bg-primary/5' : 'border-base-content/10 text-base-content/40'}`}
|
||||||
|
onClick={() => setMode('csv')}
|
||||||
|
>
|
||||||
|
간단 CSV
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={`px-3 py-1 text-xs border ${mode === 'json' ? 'border-primary/40 text-primary bg-primary/5' : 'border-base-content/10 text-base-content/40'}`}
|
||||||
|
onClick={() => setMode('json')}
|
||||||
|
>
|
||||||
|
확장 JSON
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<textarea
|
||||||
|
value={text}
|
||||||
|
onChange={(event) => setText(event.target.value)}
|
||||||
|
rows={7}
|
||||||
|
placeholder={
|
||||||
|
mode === 'csv'
|
||||||
|
? 'KR-ABCD-1234,2026-05-30T18:00:00Z,메모'
|
||||||
|
: '[{"code":"KR-ABCD-1234","expiresAt":"2026-05-30T18:00:00Z","source":"external"}]'
|
||||||
|
}
|
||||||
|
className="w-full border border-base-content/10 bg-transparent p-3 text-xs font-mono focus:outline-none focus:border-primary/30"
|
||||||
|
/>
|
||||||
|
<div className="mt-3 flex items-center gap-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-primary btn-sm px-5 text-xs"
|
||||||
|
disabled={uploadMutation.isPending || !text.trim()}
|
||||||
|
onClick={handleUpload}
|
||||||
|
>
|
||||||
|
{uploadMutation.isPending ? '업로드 중...' : '업로드'}
|
||||||
|
</button>
|
||||||
|
{message && <span className="text-xs text-base-content/45">{message}</span>}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="border border-base-content/10 bg-base-100 overflow-hidden">
|
||||||
|
<div className="px-4 py-3 border-b border-base-content/10 flex items-center justify-between gap-3">
|
||||||
|
<h2 className="text-sm font-bold">코드 목록</h2>
|
||||||
|
<select
|
||||||
|
value={stateFilter}
|
||||||
|
onChange={(event) => setStateFilter(event.target.value as TournamentCodeState | '')}
|
||||||
|
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
|
||||||
|
>
|
||||||
|
<option value="">전체</option>
|
||||||
|
{STATES.map((state) => (
|
||||||
|
<option key={state} value={state}>
|
||||||
|
{state}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full min-w-[900px] text-left">
|
||||||
|
<thead>
|
||||||
|
<tr className="bg-base-200/40 border-b border-base-content/10 text-[11px] uppercase tracking-wider text-base-content/35">
|
||||||
|
<th className="px-3 py-2">코드</th>
|
||||||
|
<th className="px-3 py-2">상태</th>
|
||||||
|
<th className="px-3 py-2">만료</th>
|
||||||
|
<th className="px-3 py-2">매치</th>
|
||||||
|
<th className="px-3 py-2">소스</th>
|
||||||
|
<th className="px-3 py-2 text-right">작업</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{codes.map((code) => (
|
||||||
|
<tr key={code._id} className="border-b border-base-content/5">
|
||||||
|
<td className="px-3 py-2 font-mono text-xs font-bold">
|
||||||
|
{code.code}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2 text-xs">{code.state}</td>
|
||||||
|
<td className="px-3 py-2 text-xs text-base-content/50">
|
||||||
|
{formatDate(code.expiresAt)}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2 text-xs text-base-content/50">
|
||||||
|
{code.matchId ? (
|
||||||
|
<Link to={`/match/${code.matchId}`} className="text-primary">
|
||||||
|
{code.matchId.slice(-6)} · {code.gameNumber}경기
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
'-'
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2 text-xs text-base-content/50">
|
||||||
|
{code.source ?? '-'}
|
||||||
|
</td>
|
||||||
|
<td className="px-3 py-2">
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
{(code.state === 'released' || code.state === 'reserved') && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="text-[11px] px-2 py-1 border border-base-content/10 text-base-content/50 hover:text-primary"
|
||||||
|
onClick={() =>
|
||||||
|
restoreMutation.mutate(code._id, {
|
||||||
|
onSuccess: invalidate,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
available 환원
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{code.state === 'available' && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="text-[11px] px-2 py-1 border border-red-500/20 text-red-400"
|
||||||
|
onClick={() =>
|
||||||
|
deleteMutation.mutate(code._id, {
|
||||||
|
onSuccess: invalidate,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
폐기
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{codes.length === 0 && (
|
||||||
|
<tr>
|
||||||
|
<td
|
||||||
|
colSpan={6}
|
||||||
|
className="px-4 py-10 text-center text-sm text-base-content/35"
|
||||||
|
>
|
||||||
|
코드가 없습니다.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user