.
This commit is contained in:
1 parent
7a43a667f1
commit
c00545f281
21 files changed
+1920
-5
No files matched your search
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user