621 lines
19 KiB
TypeScript
621 lines
19 KiB
TypeScript
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 {
|
|
roundRobinGameSchedule,
|
|
resolveRoundRobinTeamCount,
|
|
} 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 countUsableAvailable(): Promise<number> {
|
|
const TournamentCodeModel =
|
|
await this.connectionService.getModel('tournamentCode');
|
|
return TournamentCodeModel.countDocuments({
|
|
state: 'available',
|
|
expiresAt: {
|
|
$gt: new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS),
|
|
},
|
|
}).exec();
|
|
}
|
|
|
|
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 replaceForMatchGame(params: {
|
|
communityId: mongoose.Types.ObjectId;
|
|
matchId: mongoose.Types.ObjectId;
|
|
gameNumber: number;
|
|
}): Promise<TournamentCodeSlotView> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const TournamentCodeModel =
|
|
await this.connectionService.getModel('tournamentCode');
|
|
const match = await MatchModel.findOne({
|
|
_id: params.matchId,
|
|
communityId: params.communityId,
|
|
}).exec();
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
if (match.status !== 'team-built' && match.status !== 'in-progress') {
|
|
throw new BadRequestException(
|
|
'Tournament codes can only be replaced while the match is ready or in progress.',
|
|
);
|
|
}
|
|
|
|
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
|
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
|
|
this.ensureGameSchedule(match);
|
|
|
|
const requiredSlots = this.resolveRequiredSlots(match);
|
|
if (
|
|
!Number.isInteger(params.gameNumber) ||
|
|
params.gameNumber < 1 ||
|
|
params.gameNumber > requiredSlots
|
|
) {
|
|
throw new BadRequestException('Invalid tournament code game number.');
|
|
}
|
|
if (
|
|
(match.result?.games ?? []).some(
|
|
(game) => game.gameNumber === params.gameNumber,
|
|
)
|
|
) {
|
|
throw new BadRequestException(
|
|
'This game already has a collected result and cannot be replaced.',
|
|
);
|
|
}
|
|
|
|
const currentCode = await TournamentCodeModel.findOne({
|
|
_id: { $in: match.tournamentCodeIds },
|
|
matchId: match._id,
|
|
gameNumber: params.gameNumber,
|
|
}).exec();
|
|
if (!currentCode) {
|
|
throw new NotFoundException('Assigned tournament code not found.');
|
|
}
|
|
if (currentCode.state === 'used' || currentCode.riotMatchId) {
|
|
throw new BadRequestException('Used tournament codes cannot be replaced.');
|
|
}
|
|
|
|
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
|
|
const replacement = await TournamentCodeModel.findOneAndUpdate(
|
|
{
|
|
state: 'available',
|
|
region: DEFAULT_REGION,
|
|
mapType: 'SUMMONERS_RIFT',
|
|
teamSize: 5,
|
|
expiresAt: { $gt: expiresAfter },
|
|
},
|
|
{
|
|
$set: {
|
|
state: 'reserved',
|
|
matchId: match._id,
|
|
gameNumber: params.gameNumber,
|
|
reservedAt: new Date(),
|
|
},
|
|
$unset: { releasedAt: 1 },
|
|
},
|
|
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
|
|
).exec();
|
|
if (!replacement) {
|
|
throw new BadRequestException('No available tournament code to replace with.');
|
|
}
|
|
|
|
currentCode.state = 'released';
|
|
currentCode.matchId = undefined;
|
|
currentCode.gameNumber = undefined;
|
|
currentCode.reservedAt = undefined;
|
|
currentCode.releasedAt = new Date();
|
|
currentCode.riotMatchId = undefined;
|
|
match.tournamentCodeIds = this.replaceTournamentCodeId(
|
|
match.tournamentCodeIds,
|
|
currentCode._id,
|
|
replacement._id,
|
|
);
|
|
await currentCode.save();
|
|
await match.save();
|
|
|
|
return {
|
|
gameNumber: params.gameNumber,
|
|
roundNumber: this.resolveRoundNumberForGameNumber(
|
|
match,
|
|
params.gameNumber,
|
|
),
|
|
...this.resolveSeriesRefForGameNumber(match, params.gameNumber),
|
|
code: replacement.code,
|
|
expiresAt: replacement.expiresAt.toISOString(),
|
|
state: replacement.state,
|
|
riotMatchId: replacement.riotMatchId ?? null,
|
|
};
|
|
}
|
|
|
|
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,
|
|
roundNumber: this.resolveRoundNumberForGameNumber(match, gameNumber),
|
|
...seriesRef,
|
|
code: null,
|
|
expiresAt: null,
|
|
state: 'pending',
|
|
riotMatchId: null,
|
|
};
|
|
}
|
|
return {
|
|
gameNumber,
|
|
roundNumber: this.resolveRoundNumberForGameNumber(match, 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();
|
|
}
|
|
|
|
private replaceTournamentCodeId(
|
|
currentIds: mongoose.Types.ObjectId[],
|
|
oldId: mongoose.Types.ObjectId,
|
|
newId: mongoose.Types.ObjectId,
|
|
): mongoose.Types.ObjectId[] {
|
|
let replaced = false;
|
|
const next = currentIds.map((id) => {
|
|
if (id.toString() !== oldId.toString()) return id;
|
|
replaced = true;
|
|
return newId;
|
|
});
|
|
if (!replaced) next.push(newId);
|
|
return next;
|
|
}
|
|
|
|
private resolveRequiredSlots(match: MatchDocument): number {
|
|
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
|
|
const gameMode = match.gameMode ?? 'pair';
|
|
|
|
if (gameMode === 'round-robin') {
|
|
if ((match.gameSchedule?.length ?? 0) > 0) {
|
|
return match.gameSchedule.length;
|
|
}
|
|
return this.buildRoundRobinGameSchedule(match).length;
|
|
}
|
|
|
|
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 fallback = this.buildRoundRobinGameSchedule(match).find(
|
|
(entry) => entry.gameNumber === gameNumber,
|
|
);
|
|
return fallback
|
|
? {
|
|
teamAIndex: fallback.teamAIndex,
|
|
teamBIndex: fallback.teamBIndex,
|
|
}
|
|
: {
|
|
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;
|
|
|
|
match.gameSchedule = this.buildRoundRobinGameSchedule(match);
|
|
}
|
|
|
|
private resolveRoundNumberForGameNumber(
|
|
match: MatchDocument,
|
|
gameNumber: number,
|
|
): number | undefined {
|
|
if ((match.gameMode ?? 'pair') !== 'round-robin') return undefined;
|
|
|
|
const persisted = match.gameSchedule?.find(
|
|
(entry) => entry.gameNumber === gameNumber,
|
|
);
|
|
if (persisted) return persisted.roundNumber;
|
|
|
|
return this.buildRoundRobinGameSchedule(match).find(
|
|
(entry) => entry.gameNumber === gameNumber,
|
|
)?.roundNumber;
|
|
}
|
|
|
|
private buildRoundRobinGameSchedule(
|
|
match: MatchDocument,
|
|
shuffleTeams = false,
|
|
): MatchGameAssignment[] {
|
|
return roundRobinGameSchedule(resolveRoundRobinTeamCount(match), {
|
|
gamesPerPair: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
|
|
maxRounds: match.roundRobinMaxRounds,
|
|
shuffleTeams,
|
|
});
|
|
}
|
|
}
|