.
This commit is contained in:
1 parent
7a43a667f1
commit
c00545f281
21 files changed
+1920
-5
No files matched your search
@@ -10,6 +10,7 @@ import { GlobalModule } from './modules/global/global.module';
|
||||
import { MatchHistoryModule } from './modules/match-history/match-history.module';
|
||||
import { MatchModule } from './modules/match/match.module';
|
||||
import { RiotModule } from './modules/riot/riot.module';
|
||||
import { TournamentCodeModule } from './modules/tournament-code/tournament-code.module';
|
||||
import { UserModule } from './modules/user/user.module';
|
||||
|
||||
@Module({
|
||||
@@ -24,6 +25,7 @@ import { UserModule } from './modules/user/user.module';
|
||||
CommunityModule,
|
||||
MatchModule,
|
||||
MatchHistoryModule,
|
||||
TournamentCodeModule,
|
||||
AuctionModule,
|
||||
UserModule,
|
||||
DakaoModule,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import { TournamentCodeModule } from '../tournament-code/tournament-code.module';
|
||||
import { AuctionGateway } from './auction.gateway';
|
||||
import { AuctionController } from './auction.controller';
|
||||
import { AuctionService } from './auction.service';
|
||||
|
||||
@Module({
|
||||
imports: [RiotModule],
|
||||
imports: [RiotModule, TournamentCodeModule],
|
||||
controllers: [AuctionController],
|
||||
providers: [AuctionService, AuctionGateway],
|
||||
exports: [AuctionService],
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
TeamSide,
|
||||
} from '../global/database/schema';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
|
||||
|
||||
const AUCTION_MAX_TEAM_SIZE = 5;
|
||||
|
||||
@@ -43,6 +44,7 @@ export class AuctionService {
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly enrichmentService: RiotAccountEnrichmentService,
|
||||
private readonly tournamentCodeService: TournamentCodeService,
|
||||
) {}
|
||||
|
||||
public async start(params: StartAuctionParams): Promise<AuctionDocument> {
|
||||
@@ -173,7 +175,9 @@ export class AuctionService {
|
||||
});
|
||||
|
||||
match.status = 'team-built';
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
|
||||
return auction;
|
||||
}
|
||||
@@ -312,8 +316,11 @@ export class AuctionService {
|
||||
|
||||
await auction.deleteOne({ session });
|
||||
if (match.status === 'team-built') {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
match.status = 'recruiting';
|
||||
match.teams = [];
|
||||
match.tournamentCodeIds = [];
|
||||
match.teamBuiltAt = undefined;
|
||||
await match.save({ session });
|
||||
}
|
||||
await session.commitTransaction();
|
||||
@@ -393,7 +400,9 @@ export class AuctionService {
|
||||
};
|
||||
});
|
||||
match.status = 'team-built';
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
}
|
||||
|
||||
private resolveTeamName(side: TeamSide): string {
|
||||
|
||||
@@ -35,6 +35,28 @@ export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
|
||||
export type CommunityRole = 'owner' | 'admin' | 'member';
|
||||
export const COMMUNITY_ROLES: CommunityRole[] = ['owner', 'admin', 'member'];
|
||||
|
||||
export type TournamentCodeState =
|
||||
| 'available'
|
||||
| 'reserved'
|
||||
| 'used'
|
||||
| 'expired'
|
||||
| 'released';
|
||||
export const TOURNAMENT_CODE_STATES: TournamentCodeState[] = [
|
||||
'available',
|
||||
'reserved',
|
||||
'used',
|
||||
'expired',
|
||||
'released',
|
||||
];
|
||||
export type TournamentMapType = 'SUMMONERS_RIFT';
|
||||
export const TOURNAMENT_MAP_TYPES: TournamentMapType[] = ['SUMMONERS_RIFT'];
|
||||
export type TournamentSpectatorType = 'NONE' | 'LOBBYONLY' | 'ALL';
|
||||
export const TOURNAMENT_SPECTATOR_TYPES: TournamentSpectatorType[] = [
|
||||
'NONE',
|
||||
'LOBBYONLY',
|
||||
'ALL',
|
||||
];
|
||||
|
||||
export interface PositionPreference {
|
||||
position: Position;
|
||||
priority: number; // 1 = 최우선, 숫자가 작을수록 높은 우선순위
|
||||
@@ -215,6 +237,7 @@ export interface Community extends MongooseTimestamps {
|
||||
riotRegion?: RiotRegionalRoute;
|
||||
seasonStartedAt?: Date;
|
||||
seasons?: CommunitySeason[];
|
||||
matchGameCount?: number;
|
||||
}
|
||||
|
||||
export interface CommunitySeason {
|
||||
@@ -242,6 +265,30 @@ export interface RiotMatch extends MongooseTimestamps {
|
||||
|
||||
export type RiotMatchDocument = HydratedDocument<RiotMatch>;
|
||||
|
||||
// ===== TournamentCode (운영자가 미리 업로드한 토너먼트 코드 풀) =====
|
||||
export interface TournamentCode extends MongooseTimestamps {
|
||||
code: string;
|
||||
region: RiotPlatformRoute;
|
||||
mapType: TournamentMapType;
|
||||
teamSize: number;
|
||||
spectatorType: TournamentSpectatorType;
|
||||
metadata?: Record<string, unknown>;
|
||||
expiresAt: Date;
|
||||
state: TournamentCodeState;
|
||||
matchId?: mongoose.Types.ObjectId;
|
||||
gameNumber?: number;
|
||||
reservedAt?: Date;
|
||||
usedAt?: Date;
|
||||
releasedAt?: Date;
|
||||
riotMatchId?: string;
|
||||
uploadedBy: mongoose.Types.ObjectId;
|
||||
uploadedAt: Date;
|
||||
source?: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export type TournamentCodeDocument = HydratedDocument<TournamentCode>;
|
||||
|
||||
// ===== Match (내전) =====
|
||||
export interface MatchParticipant {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
@@ -289,6 +336,9 @@ export interface Match extends MongooseTimestamps {
|
||||
status: MatchStatus;
|
||||
scheduledAt: Date;
|
||||
maxParticipants: number;
|
||||
gameCount: number;
|
||||
tournamentCodeIds: mongoose.Types.ObjectId[];
|
||||
teamBuiltAt?: Date;
|
||||
hostUserId?: mongoose.Types.ObjectId;
|
||||
participants: MatchParticipant[];
|
||||
teams: MatchTeam[];
|
||||
@@ -530,6 +580,7 @@ export const CommunitySchema = new Schema<Community>(
|
||||
riotPlatform: { type: String },
|
||||
riotRegion: { type: String },
|
||||
seasonStartedAt: { type: Date },
|
||||
matchGameCount: { type: Number, required: false, default: 3 },
|
||||
seasons: {
|
||||
type: [
|
||||
new Schema<CommunitySeason>(
|
||||
@@ -664,6 +715,59 @@ export const RiotMatchSchema = new Schema<RiotMatch>(
|
||||
RiotMatchSchema.index({ participantPuuids: 1, gameCreation: -1 });
|
||||
RiotMatchSchema.index({ participantPuuids: 1, queueId: 1, gameCreation: -1 });
|
||||
|
||||
export const TournamentCodeSchema = new Schema<TournamentCode>(
|
||||
{
|
||||
code: {
|
||||
type: String,
|
||||
required: true,
|
||||
trim: true,
|
||||
uppercase: true,
|
||||
},
|
||||
region: { type: String, required: true, default: 'kr' },
|
||||
mapType: {
|
||||
type: String,
|
||||
enum: TOURNAMENT_MAP_TYPES,
|
||||
required: true,
|
||||
default: 'SUMMONERS_RIFT',
|
||||
},
|
||||
teamSize: { type: Number, required: true, default: 5 },
|
||||
spectatorType: {
|
||||
type: String,
|
||||
enum: TOURNAMENT_SPECTATOR_TYPES,
|
||||
required: true,
|
||||
default: 'ALL',
|
||||
},
|
||||
metadata: { type: Schema.Types.Mixed },
|
||||
expiresAt: { type: Date, required: true },
|
||||
state: {
|
||||
type: String,
|
||||
enum: TOURNAMENT_CODE_STATES,
|
||||
required: true,
|
||||
default: 'available',
|
||||
},
|
||||
matchId: { type: Schema.Types.ObjectId, ref: 'match' },
|
||||
gameNumber: { type: Number },
|
||||
reservedAt: { type: Date },
|
||||
usedAt: { type: Date },
|
||||
releasedAt: { type: Date },
|
||||
riotMatchId: { type: String },
|
||||
uploadedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
uploadedAt: { type: Date, required: true, default: Date.now },
|
||||
source: { type: String },
|
||||
notes: { type: String },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
collection: 'tournament_code',
|
||||
},
|
||||
);
|
||||
|
||||
TournamentCodeSchema.index({ code: 1 }, { unique: true });
|
||||
TournamentCodeSchema.index({ state: 1, expiresAt: 1 });
|
||||
TournamentCodeSchema.index({ matchId: 1, gameNumber: 1 });
|
||||
TournamentCodeSchema.index({ state: 1, uploadedAt: -1 });
|
||||
TournamentCodeSchema.index({ riotMatchId: 1 }, { sparse: true });
|
||||
|
||||
const MatchParticipantSubSchema = new Schema<MatchParticipant>(
|
||||
{
|
||||
userId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
|
||||
@@ -738,6 +842,13 @@ export const MatchSchema = new Schema<Match>(
|
||||
},
|
||||
scheduledAt: { type: Date, required: true },
|
||||
maxParticipants: { type: Number, required: true, default: 10 },
|
||||
gameCount: { type: Number, required: true, default: 3 },
|
||||
tournamentCodeIds: {
|
||||
type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
teamBuiltAt: { type: Date },
|
||||
hostUserId: { type: Schema.Types.ObjectId, ref: 'user' },
|
||||
participants: {
|
||||
type: [MatchParticipantSubSchema],
|
||||
@@ -868,6 +979,11 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
|
||||
{ name: 'community', schema: CommunitySchema, schemaName: 'community' },
|
||||
{ name: 'user', schema: UserSchema, schemaName: 'user' },
|
||||
{ name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' },
|
||||
{
|
||||
name: 'tournamentCode',
|
||||
schema: TournamentCodeSchema,
|
||||
schemaName: 'tournamentCode',
|
||||
},
|
||||
{ name: 'match', schema: MatchSchema, schemaName: 'match' },
|
||||
{ name: 'auction', schema: AuctionSchema, schemaName: 'auction' },
|
||||
];
|
||||
@@ -877,6 +993,7 @@ export interface TournamentModelTypes {
|
||||
community: Community;
|
||||
user: User;
|
||||
riotMatch: RiotMatch;
|
||||
tournamentCode: TournamentCode;
|
||||
match: Match;
|
||||
auction: Auction;
|
||||
}
|
||||
@@ -59,6 +59,11 @@ export class CreateMatchDto {
|
||||
@Min(2)
|
||||
maxParticipants?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
gameCount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@@ -104,6 +109,11 @@ export class UpdateMatchDto {
|
||||
@Min(2)
|
||||
maxParticipants?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
gameCount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
|
||||
@@ -53,6 +53,7 @@ export class MatchController {
|
||||
mapId: body.mapId ?? 11,
|
||||
scheduledAt: body.scheduledAt,
|
||||
maxParticipants: body.maxParticipants ?? 10,
|
||||
gameCount: body.gameCount,
|
||||
prizes: body.prizes ?? [],
|
||||
notices: body.notices ?? [],
|
||||
schedule: body.schedule ?? [],
|
||||
@@ -87,7 +88,8 @@ export class MatchController {
|
||||
public async getMatch(
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
return this.matchService.getById(matchId);
|
||||
const match = await this.matchService.getById(matchId);
|
||||
return this.matchService.serialize(match);
|
||||
}
|
||||
|
||||
@Patch(':matchId')
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TournamentCodeModule } from '../tournament-code/tournament-code.module';
|
||||
import { MatchController } from './match.controller';
|
||||
import { MatchService } from './match.service';
|
||||
|
||||
@Module({
|
||||
imports: [TournamentCodeModule],
|
||||
controllers: [MatchController],
|
||||
providers: [MatchService],
|
||||
exports: [MatchService],
|
||||
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
PositionPreference,
|
||||
TierInfo,
|
||||
} from '../global/database/schema';
|
||||
import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants';
|
||||
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
|
||||
|
||||
interface CreateMatchParams {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
@@ -41,12 +43,24 @@ interface JoinMatchParams {
|
||||
|
||||
@Injectable()
|
||||
export class MatchService {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly tournamentCodeService: TournamentCodeService,
|
||||
) {}
|
||||
|
||||
public async create(params: CreateMatchParams): Promise<MatchDocument> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
const community = await CommunityModel.findById(params.communityId)
|
||||
.select({ matchGameCount: 1 })
|
||||
.lean()
|
||||
.exec();
|
||||
return MatchModel.create({
|
||||
...params.data,
|
||||
gameCount:
|
||||
params.data.gameCount ??
|
||||
community?.matchGameCount ??
|
||||
DEFAULT_TOURNAMENT_GAME_COUNT,
|
||||
communityId: params.communityId,
|
||||
hostUserId: params.hostUserId,
|
||||
});
|
||||
@@ -76,6 +90,15 @@ export class MatchService {
|
||||
return match;
|
||||
}
|
||||
|
||||
public async serialize(match: MatchDocument) {
|
||||
const obj = match.toObject();
|
||||
return {
|
||||
...obj,
|
||||
gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
|
||||
tournamentCodes: await this.tournamentCodeService.buildSlots(match),
|
||||
};
|
||||
}
|
||||
|
||||
public async update(params: UpdateMatchParams): Promise<MatchDocument> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const match = await MatchModel.findById(params.matchId);
|
||||
@@ -83,7 +106,17 @@ export class MatchService {
|
||||
if (!match.communityId.equals(params.communityId)) {
|
||||
throw new BadRequestException('Match does not belong to this community.');
|
||||
}
|
||||
const previousStatus = match.status;
|
||||
match.set(params.patch);
|
||||
if (
|
||||
previousStatus !== 'recruiting' &&
|
||||
match.status === 'recruiting' &&
|
||||
match.tournamentCodeIds.length > 0
|
||||
) {
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
match.tournamentCodeIds = [];
|
||||
match.teamBuiltAt = undefined;
|
||||
}
|
||||
await match.save();
|
||||
return match;
|
||||
}
|
||||
@@ -98,6 +131,7 @@ export class MatchService {
|
||||
if (!match.communityId.equals(params.communityId)) {
|
||||
throw new BadRequestException('Match does not belong to this community.');
|
||||
}
|
||||
await this.tournamentCodeService.releaseFromMatch(match);
|
||||
await match.deleteOne();
|
||||
}
|
||||
|
||||
|
||||
@@ -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,363 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
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';
|
||||
|
||||
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;
|
||||
const need = match.gameCount - match.tournamentCodeIds.length;
|
||||
if (need <= 0) 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 }, new: true },
|
||||
).exec();
|
||||
if (!code) break;
|
||||
reservedIds.push(code._id);
|
||||
}
|
||||
|
||||
if (reservedIds.length > 0) {
|
||||
match.tournamentCodeIds.push(...reservedIds);
|
||||
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) >= (match.gameCount || 0)) {
|
||||
continue;
|
||||
}
|
||||
await this.reserveForMatch(match);
|
||||
touched += 1;
|
||||
}
|
||||
return touched;
|
||||
}
|
||||
|
||||
public async buildSlots(match: MatchDocument): Promise<TournamentCodeSlotView[]> {
|
||||
const TournamentCodeModel =
|
||||
await this.connectionService.getModel('tournamentCode');
|
||||
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
||||
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) {
|
||||
return {
|
||||
gameNumber,
|
||||
code: null,
|
||||
expiresAt: null,
|
||||
state: 'pending',
|
||||
riotMatchId: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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;
|
||||
code: string | null;
|
||||
expiresAt: string | null;
|
||||
state: TournamentCodeState | 'pending';
|
||||
riotMatchId: string | null;
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import LoginPage from './pages/Login';
|
||||
import MatchDetailPage from './pages/MatchDetailPage';
|
||||
import AuctionPage from './pages/AuctionPage';
|
||||
import UserHistoryPage from './pages/UserHistoryPage';
|
||||
import TournamentCodesPage from './pages/admin/TournamentCodesPage';
|
||||
|
||||
function MsalHeaderActions() {
|
||||
const { accounts, instance } = useMsal();
|
||||
@@ -71,6 +72,10 @@ function App() {
|
||||
<Route path="/match/:id" element={<MatchDetailPage />} />
|
||||
<Route path="/match/:id/auction" element={<AuctionPage />} />
|
||||
<Route path="/users/:userId/history" element={<UserHistoryPage />} />
|
||||
<Route
|
||||
path="/admin/communities/:cid/tournament-codes"
|
||||
element={<TournamentCodesPage />}
|
||||
/>
|
||||
</Routes>
|
||||
<DevAuthSwitcher />
|
||||
</div>
|
||||
|
||||
@@ -16,6 +16,7 @@ import type {
|
||||
ApiMatch,
|
||||
ApiRecentMatchesResponse,
|
||||
ApiRecentSummaryResponse,
|
||||
ApiTournamentCode,
|
||||
ApiUserHistoryProfile,
|
||||
DdragonManifest,
|
||||
MatchStatus,
|
||||
@@ -23,6 +24,11 @@ import type {
|
||||
MeResponse,
|
||||
RiotQueueGroup,
|
||||
RiotRankFilter,
|
||||
TournamentCodeBulkUploadResponse,
|
||||
TournamentCodeListResponse,
|
||||
TournamentCodeState,
|
||||
TournamentCodeStatsResponse,
|
||||
TournamentCodeUploadItem,
|
||||
} from './types';
|
||||
|
||||
const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000;
|
||||
@@ -253,6 +259,79 @@ export function useDdragonManifest(locale = 'ko_KR') {
|
||||
});
|
||||
}
|
||||
|
||||
export function useTournamentCodeStats(
|
||||
communityId = DEFAULT_COMMUNITY_ID,
|
||||
enabled = true,
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ['tournament-code-stats', communityId],
|
||||
queryFn: () =>
|
||||
apiFetch<TournamentCodeStatsResponse>(
|
||||
`/communities/${communityId}/tournament-codes/stats`,
|
||||
),
|
||||
enabled: Boolean(communityId && enabled),
|
||||
refetchInterval: enabled ? 30_000 : false,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function useTournamentCodes(
|
||||
options: { state?: TournamentCodeState; limit?: number },
|
||||
communityId = DEFAULT_COMMUNITY_ID,
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: [
|
||||
'tournament-codes',
|
||||
communityId,
|
||||
options.state ?? null,
|
||||
options.limit ?? null,
|
||||
],
|
||||
queryFn: () => {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (options.state) searchParams.set('state', options.state);
|
||||
if (options.limit) searchParams.set('limit', String(options.limit));
|
||||
const queryString = searchParams.toString();
|
||||
return apiFetch<TournamentCodeListResponse>(
|
||||
`/communities/${communityId}/tournament-codes${queryString ? `?${queryString}` : ''}`,
|
||||
);
|
||||
},
|
||||
enabled: Boolean(communityId),
|
||||
refetchInterval: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useBulkUploadTournamentCodes(communityId = DEFAULT_COMMUNITY_ID) {
|
||||
return useMutation({
|
||||
mutationFn: (codes: TournamentCodeUploadItem[]) =>
|
||||
apiFetch<TournamentCodeBulkUploadResponse>(
|
||||
`/communities/${communityId}/tournament-codes`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ codes }),
|
||||
},
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function useRestoreTournamentCode(communityId = DEFAULT_COMMUNITY_ID) {
|
||||
return useMutation({
|
||||
mutationFn: (codeId: string) =>
|
||||
apiFetch<ApiTournamentCode>(
|
||||
`/communities/${communityId}/tournament-codes/${codeId}/release`,
|
||||
{ method: 'POST' },
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteTournamentCode(communityId = DEFAULT_COMMUNITY_ID) {
|
||||
return useMutation({
|
||||
mutationFn: (codeId: string) =>
|
||||
apiFetch<void>(`/communities/${communityId}/tournament-codes/${codeId}`, {
|
||||
method: 'DELETE',
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export function useMe() {
|
||||
const authUserId = useAuthUserId();
|
||||
const { accounts, inProgress, instance } = useMsal();
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
Position,
|
||||
RiotLane,
|
||||
TeamSide,
|
||||
TournamentCodeSlotView,
|
||||
} from "./types";
|
||||
import { POSITION_ORDER, sideLabel } from "../lib/league";
|
||||
|
||||
@@ -46,6 +47,8 @@ export interface MatchDetailView {
|
||||
description: string;
|
||||
map: string;
|
||||
maxParticipants: number;
|
||||
gameCount: number;
|
||||
tournamentCodes: TournamentCodeSlotView[];
|
||||
joined: boolean;
|
||||
participants: ParticipantView[];
|
||||
teams: TeamView[];
|
||||
@@ -402,6 +405,8 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
|
||||
description: match.description,
|
||||
map: mapIdToLabel(match.mapId),
|
||||
maxParticipants: match.maxParticipants,
|
||||
gameCount: match.gameCount ?? 3,
|
||||
tournamentCodes: match.tournamentCodes ?? [],
|
||||
joined: Boolean(match.joined),
|
||||
participants,
|
||||
teams,
|
||||
|
||||
@@ -100,10 +100,28 @@ export interface ApiCommunity {
|
||||
name: string;
|
||||
description: string;
|
||||
ownerUserId: string;
|
||||
matchGameCount?: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export type TournamentCodeState =
|
||||
| 'available'
|
||||
| 'reserved'
|
||||
| 'used'
|
||||
| 'expired'
|
||||
| 'released';
|
||||
|
||||
export type TournamentCodeSlotState = TournamentCodeState | 'pending';
|
||||
|
||||
export interface TournamentCodeSlotView {
|
||||
gameNumber: number;
|
||||
code: string | null;
|
||||
expiresAt: string | null;
|
||||
state: TournamentCodeSlotState;
|
||||
riotMatchId: string | null;
|
||||
}
|
||||
|
||||
export interface ApiMatchParticipant {
|
||||
userId: string;
|
||||
puuid?: string;
|
||||
@@ -150,6 +168,8 @@ export interface ApiMatch {
|
||||
status: MatchStatus;
|
||||
scheduledAt: string;
|
||||
maxParticipants: number;
|
||||
gameCount: number;
|
||||
tournamentCodes?: TournamentCodeSlotView[];
|
||||
hostUserId?: string;
|
||||
participants: ApiMatchParticipant[];
|
||||
teams: ApiMatchTeam[];
|
||||
@@ -248,6 +268,57 @@ export interface DdragonManifest {
|
||||
fetchedAt: string;
|
||||
}
|
||||
|
||||
export type TournamentSpectatorType = 'NONE' | 'LOBBYONLY' | 'ALL';
|
||||
|
||||
export interface ApiTournamentCode {
|
||||
_id: string;
|
||||
code: string;
|
||||
region: string;
|
||||
mapType: 'SUMMONERS_RIFT';
|
||||
teamSize: number;
|
||||
spectatorType: TournamentSpectatorType;
|
||||
metadata?: Record<string, unknown>;
|
||||
expiresAt: string;
|
||||
state: TournamentCodeState;
|
||||
matchId?: string;
|
||||
gameNumber?: number;
|
||||
reservedAt?: string;
|
||||
usedAt?: string;
|
||||
releasedAt?: string;
|
||||
riotMatchId?: string;
|
||||
uploadedBy: string;
|
||||
uploadedAt: string;
|
||||
source?: string;
|
||||
notes?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface TournamentCodeStatsResponse {
|
||||
byState: Record<TournamentCodeState, number>;
|
||||
expiringSoon: number;
|
||||
available: number;
|
||||
}
|
||||
|
||||
export interface TournamentCodeListResponse {
|
||||
codes: ApiTournamentCode[];
|
||||
}
|
||||
|
||||
export interface TournamentCodeUploadItem {
|
||||
code: string;
|
||||
expiresAt: string;
|
||||
spectatorType?: TournamentSpectatorType;
|
||||
metadata?: Record<string, unknown>;
|
||||
source?: string;
|
||||
notes?: string;
|
||||
}
|
||||
|
||||
export interface TournamentCodeBulkUploadResponse {
|
||||
inserted: number;
|
||||
duplicates: string[];
|
||||
invalid: Array<{ code: string; reason: string }>;
|
||||
}
|
||||
|
||||
export type RiotQueueGroup =
|
||||
| 'all'
|
||||
| 'summoners-rift'
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { Link, useNavigate, useParams } from 'react-router';
|
||||
import { useAuction, useDdragonManifest, useMatch, useMe } from '../api/hooks';
|
||||
import {
|
||||
useAuction,
|
||||
useDdragonManifest,
|
||||
useMatch,
|
||||
useMe,
|
||||
useTournamentCodeStats,
|
||||
} from '../api/hooks';
|
||||
import {
|
||||
buildDefaultPreferredPositions,
|
||||
formatTierLabel,
|
||||
@@ -15,7 +21,7 @@ import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config';
|
||||
import { apiFetch, ApiError } from '../lib/api';
|
||||
import { profileIconUrl } from '../lib/ddragon';
|
||||
import { positionIcon, positionLabel } from '../lib/league';
|
||||
import type { Position } from '../api/types';
|
||||
import type { Position, TournamentCodeSlotView } from '../api/types';
|
||||
|
||||
function PosBadge({ pos, sub }: { pos: Position; sub?: boolean }) {
|
||||
return (
|
||||
@@ -279,6 +285,117 @@ function SideCard({
|
||||
);
|
||||
}
|
||||
|
||||
function formatTournamentCodeExpiry(value: string | null) {
|
||||
if (!value) return null;
|
||||
return new Intl.DateTimeFormat('ko-KR', {
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
function isExpiringSoon(value: string | null) {
|
||||
if (!value) return false;
|
||||
const expiresAt = new Date(value).getTime();
|
||||
return expiresAt - Date.now() <= 24 * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const expired = slot.state === 'expired';
|
||||
const used = slot.state === 'used';
|
||||
const expiringSoon = isExpiringSoon(slot.expiresAt);
|
||||
|
||||
async function copyCode() {
|
||||
if (!slot.code) return;
|
||||
await navigator.clipboard.writeText(slot.code);
|
||||
setCopied(true);
|
||||
window.setTimeout(() => setCopied(false), 1600);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex-1 min-w-0">
|
||||
<div
|
||||
className={`flex items-center gap-2 border px-2 py-1.5 ${
|
||||
expired
|
||||
? 'border-red-500/20 bg-red-500/8 text-red-400'
|
||||
: used
|
||||
? 'border-base-content/8 bg-base-content/5 text-base-content/35'
|
||||
: 'border-primary/20 bg-primary/5 text-base-content'
|
||||
}`}
|
||||
>
|
||||
<code className="font-mono text-[12px] font-bold truncate">
|
||||
{expired ? '코드 만료' : slot.code}
|
||||
</code>
|
||||
{slot.code && !expired && (
|
||||
<button
|
||||
type="button"
|
||||
className="ml-auto text-[10px] px-1.5 py-0.5 border border-base-content/10 text-base-content/45 hover:text-primary"
|
||||
onClick={copyCode}
|
||||
>
|
||||
{copied ? '복사됨' : '복사'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={`mt-1 text-[10px] ${
|
||||
expired || expiringSoon ? 'text-amber-500' : 'text-base-content/30'
|
||||
}`}
|
||||
>
|
||||
{used
|
||||
? '사용됨'
|
||||
: expired
|
||||
? '운영자에게 새 코드를 요청해주세요.'
|
||||
: `만료: ${formatTournamentCodeExpiry(slot.expiresAt)}`}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{slots.map((slot) => (
|
||||
<div key={slot.gameNumber} className="flex items-start gap-2">
|
||||
<span className="text-[11px] font-bold text-base-content/40 w-11 shrink-0 pt-1.5">
|
||||
{slot.gameNumber}경기
|
||||
</span>
|
||||
{slot.code ? (
|
||||
<TournamentCodeDisplay slot={slot} />
|
||||
) : (
|
||||
<span className="text-[11px] text-base-content/30 border border-dashed border-base-content/10 px-2 py-2 flex-1">
|
||||
발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다.
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PoolStatsHint({ enabled }: { enabled: boolean }) {
|
||||
const statsQuery = useTournamentCodeStats(DEFAULT_COMMUNITY_ID, enabled);
|
||||
if (!enabled) return null;
|
||||
const available = statsQuery.data?.available ?? 0;
|
||||
const expiringSoon = statsQuery.data?.expiringSoon ?? 0;
|
||||
|
||||
return (
|
||||
<div className="mt-3 border-t border-base-content/8 pt-3 text-[11px]">
|
||||
<div className={available < 5 ? 'text-red-400' : 'text-base-content/35'}>
|
||||
풀 잔여 {available}개
|
||||
{expiringSoon > 0 ? ` · 만료 임박 ${expiringSoon}개` : ''}
|
||||
</div>
|
||||
<Link
|
||||
to={`/admin/communities/${DEFAULT_COMMUNITY_ID}/tournament-codes`}
|
||||
className="mt-1 inline-flex text-primary hover:underline"
|
||||
>
|
||||
코드 풀 관리
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function MatchDetailPage() {
|
||||
const { id } = useParams();
|
||||
const navigate = useNavigate();
|
||||
@@ -623,6 +740,13 @@ export default function MatchDetailPage() {
|
||||
</SideCard>
|
||||
)}
|
||||
|
||||
{(match.status === 'team-built' || match.status === 'in-progress') && (
|
||||
<SideCard title="토너먼트 코드">
|
||||
<TournamentCodeList slots={match.tournamentCodes} />
|
||||
<PoolStatsHint enabled={canManageAuction} />
|
||||
</SideCard>
|
||||
)}
|
||||
|
||||
{match.prizes.length > 0 && (
|
||||
<SideCard title="상품">
|
||||
<ul className="space-y-1.5">
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
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 statsQuery = useTournamentCodeStats(communityId, canManage);
|
||||
const listQuery = useTournamentCodes(
|
||||
{ state: stateFilter || undefined, limit: 200 },
|
||||
communityId,
|
||||
);
|
||||
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 (!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>
|
||||
</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