feat: add double elimination match mode

This commit is contained in:
dahyeon committed 2026-06-26 05:00:08 -07:00
1 parent b9aaf55193
commit e12f182e7f
19 files changed
+3415 -58

No files matched your search

+10 -6
View File
@@ -4,7 +4,7 @@ LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(
<p align="center"> <p align="center">
<video <video
src="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/83/docs/screenshots/lolympus-demo.mp4" src="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/84/docs/screenshots/lolympus-demo.mp4"
poster="docs/screenshots/lolympus-auction.png" poster="docs/screenshots/lolympus-auction.png"
width="960" width="960"
autoplay="autoplay" autoplay="autoplay"
@@ -13,20 +13,20 @@ LOLYMPUS는 리그 오브 레전드 커뮤니티의 여러 이벤트 중 내전(
playsinline="playsinline" playsinline="playsinline"
controls controls
> >
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/83/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a> <a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/84/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
</video> </video>
</p> </p>
<p align="center"> <p align="center">
<a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/83/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a> <a href="https://git.dahyeon.us/dahyeon/lolympus-tournament-support/raw/branch/release/84/docs/screenshots/lolympus-demo.mp4">3초 간격 데모 영상 보기</a>
</p> </p>
## 배포 주소 ## 배포 주소
| Environment | Version | URL | | Environment | Version | URL |
| ----------- | ------- | -------------------------------------- | | ----------- | ------- | -------------------------------------- |
| Production | v83 | <https://lolympus.dahyeon.us/> | | Production | v84 | <https://lolympus.dahyeon.us/> |
| Staging | v83 | <https://release-83.lolympus.pages.dev/> | | Staging | v84 | <https://release-84.lolympus.pages.dev/> |
## 개요 ## 개요
@@ -48,7 +48,10 @@ LOLYMPUS는 이 반복 작업을 줄이는 데 초점을 맞췄습니다. 운영
4. **팀별 진행 페이지** 4. **팀별 진행 페이지**
각 팀은 예정 경기, 상대 팀, 라인업, 토너먼트 코드를 한 화면에서 확인하고 복사할 수 있습니다. 각 팀은 예정 경기, 상대 팀, 라인업, 토너먼트 코드를 한 화면에서 확인하고 복사할 수 있습니다.
5. **결과 수집과 통계** 5. **더블 엘리미네이션 운영**
4팀/8팀 더블 엘리미네이션 대진표를 생성하고, 시드 교체, 부전승, 제한적 결과 취소, 그랜드 파이널 리셋을 관리합니다.
6. **결과 수집과 통계**
Riot Match-V5 데이터를 이용해 경기 결과를 수집하고, 소환사별 전적과 커뮤니티 리더보드를 제공합니다. Riot Match-V5 데이터를 이용해 경기 결과를 수집하고, 소환사별 전적과 커뮤니티 리더보드를 제공합니다.
## 스크린샷 ## 스크린샷
@@ -78,6 +81,7 @@ LOLYMPUS는 이 반복 작업을 줄이는 데 초점을 맞췄습니다. 운영
- Riot 계정 기반 참가자 프로필, 티어, 포지션 확인 - Riot 계정 기반 참가자 프로필, 티어, 포지션 확인
- 팀장 지정, 포지션 기반 팀 구성, 다팀 내전 지원 - 팀장 지정, 포지션 기반 팀 구성, 다팀 내전 지원
- 팀장 경매 방식의 참가자 낙찰과 입찰 기록 관리 - 팀장 경매 방식의 참가자 낙찰과 입찰 기록 관리
- 4팀/8팀 더블 엘리미네이션 대진표, 시드 관리, 부전승, 제한적 취소, 그랜드 파이널 리셋 지원
- 경기별 토너먼트 코드 배정과 팀별 복사 UI - 경기별 토너먼트 코드 배정과 팀별 복사 UI
- 팀별 경기 일정, 상대 팀, 라인업, 결과 확인 - 팀별 경기 일정, 상대 팀, 라인업, 결과 확인
- Riot Match-V5 기반 결과 수집, 개인 전적, 리더보드 제공 - Riot Match-V5 기반 결과 수집, 개인 전적, 리더보드 제공
@@ -0,0 +1,158 @@
import {
buildDoubleEliminationBracket,
cancelDoubleEliminationBracketMatch,
completeDoubleEliminationBracketMatch,
reshuffleDoubleEliminationSeeds,
swapDoubleEliminationSeeds,
} from './double-elimination.util';
describe('double-elimination util', () => {
it('builds a 4-team bracket with winner, loser, and grand final matches', () => {
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: true,
});
expect(bracket.bracketMatches.map((match) => match.bracketMatchId)).toEqual(
['WB_R1_M1', 'WB_R1_M2', 'WB_FINAL', 'LB_R1_M1', 'LB_FINAL', 'GF'],
);
expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'WB_R1_M1'))
.toMatchObject({
teamAIndex: 1,
teamBIndex: 4,
winnerAdvancesTo: { bracketMatchId: 'WB_FINAL', position: 'A' },
loserAdvancesTo: { bracketMatchId: 'LB_R1_M1', position: 'A' },
state: 'ready',
});
});
it('moves winners and losers through a 4-team bracket and records top 3', () => {
let bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: false,
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_R1_M1',
winnerTeamIndex: 1,
completedBy: 'riot-result',
completedAt: new Date('2026-06-01T10:00:00.000Z'),
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_R1_M2',
winnerTeamIndex: 2,
completedBy: 'riot-result',
completedAt: new Date('2026-06-01T10:30:00.000Z'),
});
expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'WB_FINAL'))
.toMatchObject({ teamAIndex: 1, teamBIndex: 2, state: 'ready' });
expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'LB_R1_M1'))
.toMatchObject({ teamAIndex: 4, teamBIndex: 3, state: 'ready' });
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_FINAL',
winnerTeamIndex: 1,
completedBy: 'riot-result',
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'LB_R1_M1',
winnerTeamIndex: 3,
completedBy: 'riot-result',
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'LB_FINAL',
winnerTeamIndex: 2,
completedBy: 'riot-result',
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'GF',
winnerTeamIndex: 1,
completedBy: 'riot-result',
});
expect(bracket.placements).toEqual({
firstTeamIndex: 1,
secondTeamIndex: 2,
thirdTeamIndex: 3,
});
});
it('creates reset final only when the loser bracket finalist wins grand final', () => {
let bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: true,
});
for (const [bracketMatchId, winnerTeamIndex] of [
['WB_R1_M1', 1],
['WB_R1_M2', 2],
['WB_FINAL', 1],
['LB_R1_M1', 3],
['LB_FINAL', 2],
['GF', 2],
] as const) {
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId,
winnerTeamIndex,
completedBy: 'riot-result',
});
}
expect(bracket.resetFinalCreated).toBe(true);
expect(bracket.placements).toEqual({ thirdTeamIndex: 3 });
expect(bracket.bracketMatches.find((match) => match.bracketMatchId === 'GF_RESET'))
.toMatchObject({
gameNumber: 7,
bracketSide: 'reset-final',
teamAIndex: 1,
teamBIndex: 2,
state: 'ready',
});
});
it('rejects completion cancellation when downstream matches are already completed', () => {
let bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: false,
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_R1_M1',
winnerTeamIndex: 1,
completedBy: 'riot-result',
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_R1_M2',
winnerTeamIndex: 2,
completedBy: 'riot-result',
});
bracket = completeDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_FINAL',
winnerTeamIndex: 1,
completedBy: 'riot-result',
});
expect(() =>
cancelDoubleEliminationBracketMatch(bracket, {
bracketMatchId: 'WB_R1_M1',
}),
).toThrow('downstream');
});
it('allows changing seeds before the bracket has completed matches', () => {
const bracket = buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: false,
});
const swapped = swapDoubleEliminationSeeds(bracket, {
leftSeedNumber: 1,
rightSeedNumber: 4,
});
expect(swapped.seeds).toEqual([
{ seedNumber: 1, teamIndex: 4 },
{ seedNumber: 2, teamIndex: 2 },
{ seedNumber: 3, teamIndex: 3 },
{ seedNumber: 4, teamIndex: 1 },
]);
expect(
reshuffleDoubleEliminationSeeds(bracket, () => 0).seeds.map(
(seed) => seed.teamIndex,
),
).toEqual([2, 3, 4, 1]);
});
});
@@ -0,0 +1,672 @@
import type mongoose from 'mongoose';
export type DoubleEliminationBracketSide =
| 'winner'
| 'loser'
| 'grand-final'
| 'reset-final';
export type DoubleEliminationBracketMatchState =
| 'pending'
| 'ready'
| 'completed';
export type DoubleEliminationCompletionType = 'riot-result' | 'walkover';
export interface DoubleEliminationSeed {
seedNumber: number;
teamIndex: number;
}
export interface DoubleEliminationBracketMatchSource {
type: 'seed' | 'winner' | 'loser';
seedNumber?: number;
bracketMatchId?: string;
}
export interface DoubleEliminationBracketMatchDestination {
bracketMatchId: string;
position: 'A' | 'B';
}
export interface DoubleEliminationWalkover {
winnerTeamIndex: number;
reason?: string;
awardedBy?: mongoose.Types.ObjectId;
awardedAt: Date;
cancelledBy?: mongoose.Types.ObjectId;
cancelledAt?: Date;
cancelReason?: string;
active: boolean;
}
export interface DoubleEliminationBracketMatch {
bracketMatchId: string;
gameNumber: number;
bracketSide: DoubleEliminationBracketSide;
roundNumber: number;
matchNumber: number;
state: DoubleEliminationBracketMatchState;
teamAIndex?: number;
teamBIndex?: number;
teamASource?: DoubleEliminationBracketMatchSource;
teamBSource?: DoubleEliminationBracketMatchSource;
winnerAdvancesTo?: DoubleEliminationBracketMatchDestination;
loserAdvancesTo?: DoubleEliminationBracketMatchDestination;
winnerTeamIndex?: number;
loserTeamIndex?: number;
completedBy?: DoubleEliminationCompletionType;
completedAt?: Date;
walkover?: DoubleEliminationWalkover;
}
export interface DoubleEliminationPlacements {
firstTeamIndex?: number;
secondTeamIndex?: number;
thirdTeamIndex?: number;
}
export interface DoubleEliminationEvent {
type:
| 'bracket-created'
| 'seeds-reshuffled'
| 'seeds-swapped'
| 'bracket-match-completed'
| 'bracket-match-cancelled'
| 'walkover-awarded'
| 'walkover-cancelled'
| 'reset-final-created'
| 'riot-result-cancelled';
bracketMatchId?: string;
actorUserId?: mongoose.Types.ObjectId;
reason?: string;
createdAt: Date;
}
export interface DoubleEliminationBracket {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
resetFinalCreated: boolean;
seeds: DoubleEliminationSeed[];
bracketMatches: DoubleEliminationBracketMatch[];
placements: DoubleEliminationPlacements;
events: DoubleEliminationEvent[];
}
export interface BuildDoubleEliminationBracketOptions {
resetFinalEnabled: boolean;
}
export interface CompleteDoubleEliminationBracketMatchParams {
bracketMatchId: string;
winnerTeamIndex: number;
completedBy: DoubleEliminationCompletionType;
completedAt?: Date;
walkover?: DoubleEliminationWalkover;
}
export interface CancelDoubleEliminationBracketMatchParams {
bracketMatchId: string;
cancelledBy?: mongoose.Types.ObjectId;
cancelReason?: string;
}
export function buildDoubleEliminationBracket(
seededTeamIndexes: number[],
options: BuildDoubleEliminationBracketOptions,
): DoubleEliminationBracket {
assertSupportedTeamCount(seededTeamIndexes.length);
const seeds = seededTeamIndexes.map((teamIndex, index) => ({
seedNumber: index + 1,
teamIndex,
}));
const bracket: DoubleEliminationBracket = {
teamCount: seededTeamIndexes.length as 4 | 8,
resetFinalEnabled: options.resetFinalEnabled,
resetFinalCreated: false,
seeds,
bracketMatches:
seededTeamIndexes.length === 4
? buildFourTeamBracketMatches()
: buildEightTeamBracketMatches(),
placements: {},
events: [
{
type: 'bracket-created',
createdAt: new Date(),
},
],
};
applySeedTeams(bracket);
refreshBracketMatchStates(bracket);
return bracket;
}
export function reshuffleDoubleEliminationSeeds(
bracket: DoubleEliminationBracket,
rng: () => number = Math.random,
): DoubleEliminationBracket {
assertSeedChangeAllowed(bracket);
const teamIndexes = shuffleInPlace(
bracket.seeds.map((seed) => seed.teamIndex),
rng,
);
return rebuildWithSeeds(bracket, teamIndexes, 'seeds-reshuffled');
}
export function swapDoubleEliminationSeeds(
bracket: DoubleEliminationBracket,
params: { leftSeedNumber: number; rightSeedNumber: number },
): DoubleEliminationBracket {
assertSeedChangeAllowed(bracket);
const teamIndexes = [...bracket.seeds]
.sort((left, right) => left.seedNumber - right.seedNumber)
.map((seed) => seed.teamIndex);
const leftIndex = params.leftSeedNumber - 1;
const rightIndex = params.rightSeedNumber - 1;
if (!teamIndexes[leftIndex] || !teamIndexes[rightIndex]) {
throw new Error('Invalid seed number.');
}
[teamIndexes[leftIndex], teamIndexes[rightIndex]] = [
teamIndexes[rightIndex],
teamIndexes[leftIndex],
];
return rebuildWithSeeds(bracket, teamIndexes, 'seeds-swapped');
}
export function completeDoubleEliminationBracketMatch(
bracket: DoubleEliminationBracket,
params: CompleteDoubleEliminationBracketMatchParams,
): DoubleEliminationBracket {
const next = cloneBracket(bracket);
const bracketMatch = requireBracketMatch(next, params.bracketMatchId);
if (bracketMatch.state !== 'ready') {
throw new Error('Bracket match is not ready.');
}
if (
bracketMatch.teamAIndex !== params.winnerTeamIndex &&
bracketMatch.teamBIndex !== params.winnerTeamIndex
) {
throw new Error('Winner team is not assigned to this bracket match.');
}
const loserTeamIndex =
bracketMatch.teamAIndex === params.winnerTeamIndex
? bracketMatch.teamBIndex
: bracketMatch.teamAIndex;
if (!loserTeamIndex) throw new Error('Loser team is missing.');
bracketMatch.state = 'completed';
bracketMatch.winnerTeamIndex = params.winnerTeamIndex;
bracketMatch.loserTeamIndex = loserTeamIndex;
bracketMatch.completedBy = params.completedBy;
bracketMatch.completedAt = params.completedAt ?? new Date();
if (params.walkover) {
bracketMatch.walkover = params.walkover;
}
advanceTeam(next, bracketMatch.winnerAdvancesTo, params.winnerTeamIndex);
advanceTeam(next, bracketMatch.loserAdvancesTo, loserTeamIndex);
if (bracketMatch.bracketMatchId === 'LB_FINAL') {
next.placements.thirdTeamIndex = loserTeamIndex;
}
if (bracketMatch.bracketMatchId === 'GF') {
completeGrandFinal(next, bracketMatch);
}
if (bracketMatch.bracketMatchId === 'GF_RESET') {
next.placements.firstTeamIndex = params.winnerTeamIndex;
next.placements.secondTeamIndex = loserTeamIndex;
}
refreshBracketMatchStates(next);
next.events.push({
type:
params.completedBy === 'walkover'
? 'walkover-awarded'
: 'bracket-match-completed',
bracketMatchId: bracketMatch.bracketMatchId,
createdAt: bracketMatch.completedAt,
});
return next;
}
export function cancelDoubleEliminationBracketMatch(
bracket: DoubleEliminationBracket,
params: CancelDoubleEliminationBracketMatchParams,
): DoubleEliminationBracket {
const next = cloneBracket(bracket);
const bracketMatch = requireBracketMatch(next, params.bracketMatchId);
if (bracketMatch.state !== 'completed') {
throw new Error('Bracket match is not completed.');
}
const descendants = collectDescendantBracketMatchIds(
next,
bracketMatch.bracketMatchId,
);
const completedDescendant = next.bracketMatches.find(
(match) => descendants.has(match.bracketMatchId) && match.state === 'completed',
);
if (completedDescendant) {
throw new Error('Cannot cancel because a downstream bracket match is completed.');
}
if (bracketMatch.bracketMatchId === 'GF') {
next.bracketMatches = next.bracketMatches.filter(
(match) => match.bracketMatchId !== 'GF_RESET',
);
next.resetFinalCreated = false;
}
for (const descendantId of descendants) {
const descendant = next.bracketMatches.find(
(match) => match.bracketMatchId === descendantId,
);
if (!descendant) continue;
if (referencesBracketMatch(descendant.teamASource, bracketMatch.bracketMatchId)) {
descendant.teamAIndex = undefined;
}
if (referencesBracketMatch(descendant.teamBSource, bracketMatch.bracketMatchId)) {
descendant.teamBIndex = undefined;
}
descendant.winnerTeamIndex = undefined;
descendant.loserTeamIndex = undefined;
descendant.completedBy = undefined;
descendant.completedAt = undefined;
}
bracketMatch.winnerTeamIndex = undefined;
bracketMatch.loserTeamIndex = undefined;
bracketMatch.completedBy = undefined;
bracketMatch.completedAt = undefined;
if (bracketMatch.walkover?.active) {
bracketMatch.walkover = {
...bracketMatch.walkover,
active: false,
cancelledBy: params.cancelledBy,
cancelledAt: new Date(),
cancelReason: params.cancelReason,
};
}
next.placements = {};
refreshBracketMatchStates(next);
next.events.push({
type:
bracketMatch.walkover && !bracketMatch.walkover.active
? 'walkover-cancelled'
: 'bracket-match-cancelled',
bracketMatchId: bracketMatch.bracketMatchId,
actorUserId: params.cancelledBy,
reason: params.cancelReason,
createdAt: new Date(),
});
return next;
}
export function findNextReadyDoubleEliminationBracketMatches(
bracket: DoubleEliminationBracket | undefined,
): DoubleEliminationBracketMatch[] {
return (bracket?.bracketMatches ?? []).filter(
(bracketMatch) => bracketMatch.state === 'ready',
);
}
export function hasCompletedDoubleEliminationBracketMatches(
bracket: DoubleEliminationBracket | undefined,
): boolean {
return Boolean(
bracket?.bracketMatches.some(
(bracketMatch) => bracketMatch.state === 'completed',
),
);
}
function rebuildWithSeeds(
bracket: DoubleEliminationBracket,
teamIndexes: number[],
eventType: DoubleEliminationEvent['type'],
): DoubleEliminationBracket {
const next = buildDoubleEliminationBracket(teamIndexes, {
resetFinalEnabled: bracket.resetFinalEnabled,
});
next.events = [
...bracket.events,
{
type: eventType,
createdAt: new Date(),
},
];
return next;
}
function completeGrandFinal(
bracket: DoubleEliminationBracket,
grandFinal: DoubleEliminationBracketMatch,
): void {
if (!grandFinal.winnerTeamIndex || !grandFinal.loserTeamIndex) return;
const winnerBracketTeamIndex = grandFinal.teamAIndex;
if (
bracket.resetFinalEnabled &&
!bracket.resetFinalCreated &&
grandFinal.winnerTeamIndex !== winnerBracketTeamIndex
) {
bracket.resetFinalCreated = true;
bracket.bracketMatches.push({
bracketMatchId: 'GF_RESET',
gameNumber: nextGameNumber(bracket),
bracketSide: 'reset-final',
roundNumber: 1,
matchNumber: 1,
state: 'ready',
teamAIndex: grandFinal.teamAIndex,
teamBIndex: grandFinal.teamBIndex,
teamASource: { type: 'winner', bracketMatchId: 'GF' },
teamBSource: { type: 'loser', bracketMatchId: 'GF' },
});
bracket.events.push({
type: 'reset-final-created',
bracketMatchId: 'GF_RESET',
createdAt: new Date(),
});
return;
}
bracket.placements.firstTeamIndex = grandFinal.winnerTeamIndex;
bracket.placements.secondTeamIndex = grandFinal.loserTeamIndex;
}
function advanceTeam(
bracket: DoubleEliminationBracket,
destination: DoubleEliminationBracketMatchDestination | undefined,
teamIndex: number,
): void {
if (!destination) return;
const target = requireBracketMatch(bracket, destination.bracketMatchId);
if (destination.position === 'A') {
target.teamAIndex = teamIndex;
} else {
target.teamBIndex = teamIndex;
}
}
function refreshBracketMatchStates(bracket: DoubleEliminationBracket): void {
for (const bracketMatch of bracket.bracketMatches) {
if (bracketMatch.winnerTeamIndex) {
bracketMatch.state = 'completed';
continue;
}
bracketMatch.state =
bracketMatch.teamAIndex && bracketMatch.teamBIndex ? 'ready' : 'pending';
}
}
function applySeedTeams(bracket: DoubleEliminationBracket): void {
const bySeedNumber = new Map(
bracket.seeds.map((seed) => [seed.seedNumber, seed.teamIndex]),
);
for (const bracketMatch of bracket.bracketMatches) {
if (bracketMatch.teamASource?.type === 'seed') {
bracketMatch.teamAIndex = bySeedNumber.get(
bracketMatch.teamASource.seedNumber ?? 0,
);
}
if (bracketMatch.teamBSource?.type === 'seed') {
bracketMatch.teamBIndex = bySeedNumber.get(
bracketMatch.teamBSource.seedNumber ?? 0,
);
}
}
}
function buildFourTeamBracketMatches(): DoubleEliminationBracketMatch[] {
return [
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, {
teamASource: seedSource(1),
teamBSource: seedSource(4),
winnerAdvancesTo: destination('WB_FINAL', 'A'),
loserAdvancesTo: destination('LB_R1_M1', 'A'),
}),
bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, {
teamASource: seedSource(2),
teamBSource: seedSource(3),
winnerAdvancesTo: destination('WB_FINAL', 'B'),
loserAdvancesTo: destination('LB_R1_M1', 'B'),
}),
bracketMatch('WB_FINAL', 3, 'winner', 2, 1, {
teamASource: winnerSource('WB_R1_M1'),
teamBSource: winnerSource('WB_R1_M2'),
winnerAdvancesTo: destination('GF', 'A'),
loserAdvancesTo: destination('LB_FINAL', 'B'),
}),
bracketMatch('LB_R1_M1', 4, 'loser', 1, 1, {
teamASource: loserSource('WB_R1_M1'),
teamBSource: loserSource('WB_R1_M2'),
winnerAdvancesTo: destination('LB_FINAL', 'A'),
}),
bracketMatch('LB_FINAL', 5, 'loser', 2, 1, {
teamASource: winnerSource('LB_R1_M1'),
teamBSource: loserSource('WB_FINAL'),
winnerAdvancesTo: destination('GF', 'B'),
}),
bracketMatch('GF', 6, 'grand-final', 1, 1, {
teamASource: winnerSource('WB_FINAL'),
teamBSource: winnerSource('LB_FINAL'),
}),
];
}
function buildEightTeamBracketMatches(): DoubleEliminationBracketMatch[] {
return [
bracketMatch('WB_R1_M1', 1, 'winner', 1, 1, {
teamASource: seedSource(1),
teamBSource: seedSource(8),
winnerAdvancesTo: destination('WB_R2_M1', 'A'),
loserAdvancesTo: destination('LB_R1_M1', 'A'),
}),
bracketMatch('WB_R1_M2', 2, 'winner', 1, 2, {
teamASource: seedSource(4),
teamBSource: seedSource(5),
winnerAdvancesTo: destination('WB_R2_M1', 'B'),
loserAdvancesTo: destination('LB_R1_M1', 'B'),
}),
bracketMatch('WB_R1_M3', 3, 'winner', 1, 3, {
teamASource: seedSource(2),
teamBSource: seedSource(7),
winnerAdvancesTo: destination('WB_R2_M2', 'A'),
loserAdvancesTo: destination('LB_R1_M2', 'A'),
}),
bracketMatch('WB_R1_M4', 4, 'winner', 1, 4, {
teamASource: seedSource(3),
teamBSource: seedSource(6),
winnerAdvancesTo: destination('WB_R2_M2', 'B'),
loserAdvancesTo: destination('LB_R1_M2', 'B'),
}),
bracketMatch('WB_R2_M1', 5, 'winner', 2, 1, {
teamASource: winnerSource('WB_R1_M1'),
teamBSource: winnerSource('WB_R1_M2'),
winnerAdvancesTo: destination('WB_FINAL', 'A'),
loserAdvancesTo: destination('LB_R2_M2', 'B'),
}),
bracketMatch('WB_R2_M2', 6, 'winner', 2, 2, {
teamASource: winnerSource('WB_R1_M3'),
teamBSource: winnerSource('WB_R1_M4'),
winnerAdvancesTo: destination('WB_FINAL', 'B'),
loserAdvancesTo: destination('LB_R2_M1', 'B'),
}),
bracketMatch('WB_FINAL', 7, 'winner', 3, 1, {
teamASource: winnerSource('WB_R2_M1'),
teamBSource: winnerSource('WB_R2_M2'),
winnerAdvancesTo: destination('GF', 'A'),
loserAdvancesTo: destination('LB_FINAL', 'B'),
}),
bracketMatch('LB_R1_M1', 8, 'loser', 1, 1, {
teamASource: loserSource('WB_R1_M1'),
teamBSource: loserSource('WB_R1_M2'),
winnerAdvancesTo: destination('LB_R2_M1', 'A'),
}),
bracketMatch('LB_R1_M2', 9, 'loser', 1, 2, {
teamASource: loserSource('WB_R1_M3'),
teamBSource: loserSource('WB_R1_M4'),
winnerAdvancesTo: destination('LB_R2_M2', 'A'),
}),
bracketMatch('LB_R2_M1', 10, 'loser', 2, 1, {
teamASource: winnerSource('LB_R1_M1'),
teamBSource: loserSource('WB_R2_M2'),
winnerAdvancesTo: destination('LB_R3_M1', 'A'),
}),
bracketMatch('LB_R2_M2', 11, 'loser', 2, 2, {
teamASource: winnerSource('LB_R1_M2'),
teamBSource: loserSource('WB_R2_M1'),
winnerAdvancesTo: destination('LB_R3_M1', 'B'),
}),
bracketMatch('LB_R3_M1', 12, 'loser', 3, 1, {
teamASource: winnerSource('LB_R2_M1'),
teamBSource: winnerSource('LB_R2_M2'),
winnerAdvancesTo: destination('LB_FINAL', 'A'),
}),
bracketMatch('LB_FINAL', 13, 'loser', 4, 1, {
teamASource: winnerSource('LB_R3_M1'),
teamBSource: loserSource('WB_FINAL'),
winnerAdvancesTo: destination('GF', 'B'),
}),
bracketMatch('GF', 14, 'grand-final', 1, 1, {
teamASource: winnerSource('WB_FINAL'),
teamBSource: winnerSource('LB_FINAL'),
}),
];
}
function bracketMatch(
bracketMatchId: string,
gameNumber: number,
bracketSide: DoubleEliminationBracketSide,
roundNumber: number,
matchNumber: number,
params: Partial<DoubleEliminationBracketMatch>,
): DoubleEliminationBracketMatch {
return {
bracketMatchId,
gameNumber,
bracketSide,
roundNumber,
matchNumber,
state: 'pending',
...params,
};
}
function seedSource(seedNumber: number): DoubleEliminationBracketMatchSource {
return { type: 'seed', seedNumber };
}
function winnerSource(
bracketMatchId: string,
): DoubleEliminationBracketMatchSource {
return { type: 'winner', bracketMatchId };
}
function loserSource(
bracketMatchId: string,
): DoubleEliminationBracketMatchSource {
return { type: 'loser', bracketMatchId };
}
function destination(
bracketMatchId: string,
position: 'A' | 'B',
): DoubleEliminationBracketMatchDestination {
return { bracketMatchId, position };
}
function collectDescendantBracketMatchIds(
bracket: DoubleEliminationBracket,
bracketMatchId: string,
): Set<string> {
const descendants = new Set<string>();
let changed = true;
while (changed) {
changed = false;
for (const match of bracket.bracketMatches) {
const sourceIds = [
match.teamASource?.bracketMatchId,
match.teamBSource?.bracketMatchId,
].filter((id): id is string => Boolean(id));
if (
sourceIds.some((id) => id === bracketMatchId || descendants.has(id)) &&
!descendants.has(match.bracketMatchId)
) {
descendants.add(match.bracketMatchId);
changed = true;
}
}
}
return descendants;
}
function referencesBracketMatch(
source: DoubleEliminationBracketMatchSource | undefined,
bracketMatchId: string,
): boolean {
return source?.bracketMatchId === bracketMatchId;
}
function requireBracketMatch(
bracket: DoubleEliminationBracket,
bracketMatchId: string,
): DoubleEliminationBracketMatch {
const bracketMatch = bracket.bracketMatches.find(
(match) => match.bracketMatchId === bracketMatchId,
);
if (!bracketMatch) throw new Error('Bracket match not found.');
return bracketMatch;
}
function assertSeedChangeAllowed(bracket: DoubleEliminationBracket): void {
if (hasCompletedDoubleEliminationBracketMatches(bracket)) {
throw new Error('Cannot change seeds after a bracket match is completed.');
}
}
function assertSupportedTeamCount(teamCount: number): asserts teamCount is 4 | 8 {
if (teamCount !== 4 && teamCount !== 8) {
throw new Error('Double elimination supports only 4 or 8 teams.');
}
}
function nextGameNumber(bracket: DoubleEliminationBracket): number {
return Math.max(...bracket.bracketMatches.map((match) => match.gameNumber)) + 1;
}
function cloneBracket(
bracket: DoubleEliminationBracket,
): DoubleEliminationBracket {
return {
...bracket,
seeds: bracket.seeds.map((seed) => ({ ...seed })),
bracketMatches: bracket.bracketMatches.map((match) => ({
...match,
teamASource: match.teamASource ? { ...match.teamASource } : undefined,
teamBSource: match.teamBSource ? { ...match.teamBSource } : undefined,
winnerAdvancesTo: match.winnerAdvancesTo
? { ...match.winnerAdvancesTo }
: undefined,
loserAdvancesTo: match.loserAdvancesTo
? { ...match.loserAdvancesTo }
: undefined,
walkover: match.walkover ? { ...match.walkover } : undefined,
})),
placements: { ...bracket.placements },
events: bracket.events.map((event) => ({ ...event })),
};
}
function shuffleInPlace<T>(
items: T[],
rng: () => number = Math.random,
): T[] {
for (let index = items.length - 1; index > 0; index -= 1) {
const swapIndex = Math.floor(rng() * (index + 1));
[items[index], items[swapIndex]] = [items[swapIndex], items[index]];
}
return items;
}
+285 -2
View File
@@ -32,11 +32,16 @@ export const MATCH_STATUSES: MatchStatus[] = [
export type TeamSide = 'blue' | 'red'; export type TeamSide = 'blue' | 'red';
export const TEAM_SIDES: TeamSide[] = ['blue', 'red']; export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
export type MatchGameMode = 'pair' | 'bracket' | 'round-robin'; export type MatchGameMode =
| 'pair'
| 'bracket'
| 'round-robin'
| 'double-elimination';
export const MATCH_GAME_MODES: MatchGameMode[] = [ export const MATCH_GAME_MODES: MatchGameMode[] = [
'pair', 'pair',
'bracket', 'bracket',
'round-robin', 'round-robin',
'double-elimination',
]; ];
export type CommunityRole = 'owner' | 'admin' | 'member'; export type CommunityRole = 'owner' | 'admin' | 'member';
@@ -47,13 +52,15 @@ export type TournamentCodeState =
| 'reserved' | 'reserved'
| 'used' | 'used'
| 'expired' | 'expired'
| 'released'; | 'released'
| 'voided';
export const TOURNAMENT_CODE_STATES: TournamentCodeState[] = [ export const TOURNAMENT_CODE_STATES: TournamentCodeState[] = [
'available', 'available',
'reserved', 'reserved',
'used', 'used',
'expired', 'expired',
'released', 'released',
'voided',
]; ];
export type TournamentMapType = 'SUMMONERS_RIFT'; export type TournamentMapType = 'SUMMONERS_RIFT';
export const TOURNAMENT_MAP_TYPES: TournamentMapType[] = ['SUMMONERS_RIFT']; export const TOURNAMENT_MAP_TYPES: TournamentMapType[] = ['SUMMONERS_RIFT'];
@@ -445,6 +452,7 @@ export interface TournamentCode extends MongooseTimestamps {
state: TournamentCodeState; state: TournamentCodeState;
matchId?: mongoose.Types.ObjectId; matchId?: mongoose.Types.ObjectId;
gameNumber?: number; gameNumber?: number;
bracketMatchId?: string;
reservedAt?: Date; reservedAt?: Date;
usedAt?: Date; usedAt?: Date;
releasedAt?: Date; releasedAt?: Date;
@@ -497,6 +505,7 @@ export interface MatchGameResultParticipant {
export interface MatchGameResult { export interface MatchGameResult {
gameNumber: number; gameNumber: number;
bracketMatchId?: string;
riotMatchId: string; riotMatchId: string;
blueTeamIndex: number; blueTeamIndex: number;
redTeamIndex: number; redTeamIndex: number;
@@ -508,6 +517,7 @@ export interface MatchGameResult {
} }
export interface MatchSeriesResult { export interface MatchSeriesResult {
bracketMatchId?: string;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
teamAWins: number; teamAWins: number;
@@ -515,6 +525,118 @@ export interface MatchSeriesResult {
winnerTeamIndex?: number; winnerTeamIndex?: number;
} }
export type DoubleEliminationBracketSide =
| 'winner'
| 'loser'
| 'grand-final'
| 'reset-final';
export const DOUBLE_ELIMINATION_BRACKET_SIDES: DoubleEliminationBracketSide[] =
['winner', 'loser', 'grand-final', 'reset-final'];
export type DoubleEliminationBracketMatchState =
| 'pending'
| 'ready'
| 'completed';
export const DOUBLE_ELIMINATION_BRACKET_MATCH_STATES: DoubleEliminationBracketMatchState[] =
['pending', 'ready', 'completed'];
export type DoubleEliminationCompletionType = 'riot-result' | 'walkover';
export const DOUBLE_ELIMINATION_COMPLETION_TYPES: DoubleEliminationCompletionType[] =
['riot-result', 'walkover'];
export type DoubleEliminationEventType =
| 'bracket-created'
| 'seeds-reshuffled'
| 'seeds-swapped'
| 'bracket-match-completed'
| 'bracket-match-cancelled'
| 'walkover-awarded'
| 'walkover-cancelled'
| 'reset-final-created'
| 'riot-result-cancelled';
export const DOUBLE_ELIMINATION_EVENT_TYPES: DoubleEliminationEventType[] = [
'bracket-created',
'seeds-reshuffled',
'seeds-swapped',
'bracket-match-completed',
'bracket-match-cancelled',
'walkover-awarded',
'walkover-cancelled',
'reset-final-created',
'riot-result-cancelled',
];
export interface DoubleEliminationSeed {
seedNumber: number;
teamIndex: number;
}
export interface DoubleEliminationBracketMatchSource {
type: 'seed' | 'winner' | 'loser';
seedNumber?: number;
bracketMatchId?: string;
}
export interface DoubleEliminationBracketMatchDestination {
bracketMatchId: string;
position: 'A' | 'B';
}
export interface DoubleEliminationWalkover {
winnerTeamIndex: number;
reason?: string;
awardedBy?: mongoose.Types.ObjectId;
awardedAt: Date;
cancelledBy?: mongoose.Types.ObjectId;
cancelledAt?: Date;
cancelReason?: string;
active: boolean;
}
export interface DoubleEliminationBracketMatch {
bracketMatchId: string;
gameNumber: number;
bracketSide: DoubleEliminationBracketSide;
roundNumber: number;
matchNumber: number;
state: DoubleEliminationBracketMatchState;
teamAIndex?: number;
teamBIndex?: number;
teamASource?: DoubleEliminationBracketMatchSource;
teamBSource?: DoubleEliminationBracketMatchSource;
winnerAdvancesTo?: DoubleEliminationBracketMatchDestination;
loserAdvancesTo?: DoubleEliminationBracketMatchDestination;
winnerTeamIndex?: number;
loserTeamIndex?: number;
completedBy?: DoubleEliminationCompletionType;
completedAt?: Date;
walkover?: DoubleEliminationWalkover;
}
export interface DoubleEliminationPlacements {
firstTeamIndex?: number;
secondTeamIndex?: number;
thirdTeamIndex?: number;
}
export interface DoubleEliminationEvent {
type: DoubleEliminationEventType;
bracketMatchId?: string;
actorUserId?: mongoose.Types.ObjectId;
reason?: string;
createdAt: Date;
}
export interface DoubleEliminationBracket {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
resetFinalCreated: boolean;
seeds: DoubleEliminationSeed[];
bracketMatches: DoubleEliminationBracketMatch[];
placements: DoubleEliminationPlacements;
events: DoubleEliminationEvent[];
}
export interface MatchGameAssignment { export interface MatchGameAssignment {
gameNumber: number; gameNumber: number;
roundNumber?: number; roundNumber?: number;
@@ -564,6 +686,7 @@ export interface Match extends MongooseTimestamps {
teams: MatchTeam[]; teams: MatchTeam[];
result?: MatchResult; result?: MatchResult;
resultPollState?: MatchResultPollState; resultPollState?: MatchResultPollState;
doubleElimination?: DoubleEliminationBracket;
legacyImported?: boolean; legacyImported?: boolean;
legacyImportSource?: { legacyImportSource?: {
importedAt: Date; importedAt: Date;
@@ -1351,6 +1474,7 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
}, },
matchId: { type: Schema.Types.ObjectId, ref: 'match' }, matchId: { type: Schema.Types.ObjectId, ref: 'match' },
gameNumber: { type: Number }, gameNumber: { type: Number },
bracketMatchId: { type: String },
reservedAt: { type: Date }, reservedAt: { type: Date },
usedAt: { type: Date }, usedAt: { type: Date },
releasedAt: { type: Date }, releasedAt: { type: Date },
@@ -1369,6 +1493,7 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
TournamentCodeSchema.index({ code: 1 }, { unique: true }); TournamentCodeSchema.index({ code: 1 }, { unique: true });
TournamentCodeSchema.index({ state: 1, expiresAt: 1 }); TournamentCodeSchema.index({ state: 1, expiresAt: 1 });
TournamentCodeSchema.index({ matchId: 1, gameNumber: 1 }); TournamentCodeSchema.index({ matchId: 1, gameNumber: 1 });
TournamentCodeSchema.index({ matchId: 1, bracketMatchId: 1 }, { sparse: true });
TournamentCodeSchema.index({ state: 1, uploadedAt: -1 }); TournamentCodeSchema.index({ state: 1, uploadedAt: -1 });
TournamentCodeSchema.index({ riotMatchId: 1 }, { sparse: true }); TournamentCodeSchema.index({ riotMatchId: 1 }, { sparse: true });
@@ -1428,6 +1553,7 @@ const MatchGameResultParticipantSubSchema =
const MatchGameResultSubSchema = new Schema<MatchGameResult>( const MatchGameResultSubSchema = new Schema<MatchGameResult>(
{ {
gameNumber: { type: Number, required: true }, gameNumber: { type: Number, required: true },
bracketMatchId: { type: String, required: false },
riotMatchId: { type: String, required: true }, riotMatchId: { type: String, required: true },
blueTeamIndex: { type: Number, required: true, min: 1 }, blueTeamIndex: { type: Number, required: true, min: 1 },
redTeamIndex: { type: Number, required: true, min: 1 }, redTeamIndex: { type: Number, required: true, min: 1 },
@@ -1446,6 +1572,7 @@ const MatchGameResultSubSchema = new Schema<MatchGameResult>(
const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>( const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>(
{ {
bracketMatchId: { type: String, required: false },
teamAIndex: { type: Number, required: true, min: 1 }, teamAIndex: { type: Number, required: true, min: 1 },
teamBIndex: { type: Number, required: true, min: 1 }, teamBIndex: { type: Number, required: true, min: 1 },
teamAWins: { type: Number, required: true, default: 0 }, teamAWins: { type: Number, required: true, default: 0 },
@@ -1465,6 +1592,158 @@ const MatchGameAssignmentSubSchema = new Schema<MatchGameAssignment>(
{ _id: false }, { _id: false },
); );
const DoubleEliminationSeedSubSchema = new Schema<DoubleEliminationSeed>(
{
seedNumber: { type: Number, required: true, min: 1 },
teamIndex: { type: Number, required: true, min: 1 },
},
{ _id: false },
);
const DoubleEliminationBracketMatchSourceSubSchema =
new Schema<DoubleEliminationBracketMatchSource>(
{
type: {
type: String,
enum: ['seed', 'winner', 'loser'],
required: true,
},
seedNumber: { type: Number, required: false, min: 1 },
bracketMatchId: { type: String, required: false },
},
{ _id: false },
);
const DoubleEliminationBracketMatchDestinationSubSchema =
new Schema<DoubleEliminationBracketMatchDestination>(
{
bracketMatchId: { type: String, required: true },
position: { type: String, enum: ['A', 'B'], required: true },
},
{ _id: false },
);
const DoubleEliminationWalkoverSubSchema =
new Schema<DoubleEliminationWalkover>(
{
winnerTeamIndex: { type: Number, required: true, min: 1 },
reason: { type: String, required: false },
awardedBy: { type: Schema.Types.ObjectId, ref: 'user' },
awardedAt: { type: Date, required: true },
cancelledBy: { type: Schema.Types.ObjectId, ref: 'user' },
cancelledAt: { type: Date },
cancelReason: { type: String },
active: { type: Boolean, required: true, default: true },
},
{ _id: false },
);
const DoubleEliminationBracketMatchSubSchema =
new Schema<DoubleEliminationBracketMatch>(
{
bracketMatchId: { type: String, required: true },
gameNumber: { type: Number, required: true, min: 1 },
bracketSide: {
type: String,
enum: DOUBLE_ELIMINATION_BRACKET_SIDES,
required: true,
},
roundNumber: { type: Number, required: true, min: 1 },
matchNumber: { type: Number, required: true, min: 1 },
state: {
type: String,
enum: DOUBLE_ELIMINATION_BRACKET_MATCH_STATES,
required: true,
},
teamAIndex: { type: Number, required: false, min: 1 },
teamBIndex: { type: Number, required: false, min: 1 },
teamASource: {
type: DoubleEliminationBracketMatchSourceSubSchema,
required: false,
},
teamBSource: {
type: DoubleEliminationBracketMatchSourceSubSchema,
required: false,
},
winnerAdvancesTo: {
type: DoubleEliminationBracketMatchDestinationSubSchema,
required: false,
},
loserAdvancesTo: {
type: DoubleEliminationBracketMatchDestinationSubSchema,
required: false,
},
winnerTeamIndex: { type: Number, required: false, min: 1 },
loserTeamIndex: { type: Number, required: false, min: 1 },
completedBy: {
type: String,
enum: DOUBLE_ELIMINATION_COMPLETION_TYPES,
required: false,
},
completedAt: { type: Date, required: false },
walkover: {
type: DoubleEliminationWalkoverSubSchema,
required: false,
},
},
{ _id: false },
);
const DoubleEliminationPlacementsSubSchema =
new Schema<DoubleEliminationPlacements>(
{
firstTeamIndex: { type: Number, required: false, min: 1 },
secondTeamIndex: { type: Number, required: false, min: 1 },
thirdTeamIndex: { type: Number, required: false, min: 1 },
},
{ _id: false },
);
const DoubleEliminationEventSubSchema = new Schema<DoubleEliminationEvent>(
{
type: {
type: String,
enum: DOUBLE_ELIMINATION_EVENT_TYPES,
required: true,
},
bracketMatchId: { type: String, required: false },
actorUserId: { type: Schema.Types.ObjectId, ref: 'user' },
reason: { type: String, required: false },
createdAt: { type: Date, required: true },
},
{ _id: false },
);
const DoubleEliminationBracketSubSchema =
new Schema<DoubleEliminationBracket>(
{
teamCount: { type: Number, enum: [4, 8], required: true },
resetFinalEnabled: { type: Boolean, required: true, default: false },
resetFinalCreated: { type: Boolean, required: true, default: false },
seeds: {
type: [DoubleEliminationSeedSubSchema],
required: true,
default: [],
},
bracketMatches: {
type: [DoubleEliminationBracketMatchSubSchema],
required: true,
default: [],
},
placements: {
type: DoubleEliminationPlacementsSubSchema,
required: true,
default: () => ({}),
},
events: {
type: [DoubleEliminationEventSubSchema],
required: true,
default: [],
},
},
{ _id: false },
);
const MatchResultSubSchema = new Schema<MatchResult>( const MatchResultSubSchema = new Schema<MatchResult>(
{ {
winnerTeamIndex: { type: Number, required: false, min: 1 }, winnerTeamIndex: { type: Number, required: false, min: 1 },
@@ -1595,6 +1874,10 @@ export const MatchSchema = new Schema<Match>(
type: MatchResultPollStateSubSchema, type: MatchResultPollStateSubSchema,
required: false, required: false,
}, },
doubleElimination: {
type: DoubleEliminationBracketSubSchema,
required: false,
},
legacyImported: { type: Boolean, required: false, default: false }, legacyImported: { type: Boolean, required: false, default: false },
legacyImportSource: { legacyImportSource: {
type: MatchLegacyImportSourceSubSchema, type: MatchLegacyImportSourceSubSchema,
@@ -4,6 +4,7 @@ import {
ArrayMinSize, ArrayMinSize,
registerDecorator, registerDecorator,
IsArray, IsArray,
IsBoolean,
IsDate, IsDate,
IsEnum, IsEnum,
IsInt, IsInt,
@@ -106,6 +107,10 @@ export class CreateMatchDto {
@Min(1) @Min(1)
roundRobinMaxRounds?: number; roundRobinMaxRounds?: number;
@IsOptional()
@IsBoolean()
doubleEliminationResetFinalEnabled?: boolean;
@IsOptional() @IsOptional()
@IsArray() @IsArray()
@IsString({ each: true }) @IsString({ each: true })
@@ -166,6 +171,10 @@ export class UpdateMatchDto {
@Min(1) @Min(1)
roundRobinMaxRounds?: number; roundRobinMaxRounds?: number;
@IsOptional()
@IsBoolean()
doubleEliminationResetFinalEnabled?: boolean;
@IsOptional() @IsOptional()
@IsArray() @IsArray()
@IsString({ each: true }) @IsString({ each: true })
@@ -217,3 +226,31 @@ export class AddParticipantDto {
@IsString() @IsString()
riotPuuid?: string; riotPuuid?: string;
} }
export class SwapDoubleEliminationSeedsDto {
@IsInt()
@Min(1)
leftSeedNumber!: number;
@IsInt()
@Min(1)
rightSeedNumber!: number;
}
export class ApplyDoubleEliminationWalkoverDto {
@IsInt()
@Min(1)
winnerTeamIndex!: number;
@IsOptional()
@IsString()
@MaxLength(512)
reason?: string;
}
export class CancelDoubleEliminationActionDto {
@IsOptional()
@IsString()
@MaxLength(512)
reason?: string;
}
@@ -25,8 +25,11 @@ import type {
} from '../global/database/schema'; } from '../global/database/schema';
import { import {
AddParticipantDto, AddParticipantDto,
ApplyDoubleEliminationWalkoverDto,
CancelDoubleEliminationActionDto,
CreateMatchDto, CreateMatchDto,
JoinMatchDto, JoinMatchDto,
SwapDoubleEliminationSeedsDto,
UpdateMatchDto, UpdateMatchDto,
UpdateParticipantDto, UpdateParticipantDto,
} from './dto/create-match.dto'; } from './dto/create-match.dto';
@@ -58,6 +61,8 @@ export class MatchController {
gameCount: body.gameCount, gameCount: body.gameCount,
gameMode: body.gameMode ?? 'pair', gameMode: body.gameMode ?? 'pair',
roundRobinMaxRounds: body.roundRobinMaxRounds, roundRobinMaxRounds: body.roundRobinMaxRounds,
doubleEliminationResetFinalEnabled:
body.doubleEliminationResetFinalEnabled,
prizes: body.prizes ?? [], prizes: body.prizes ?? [],
notices: body.notices ?? [], notices: body.notices ?? [],
schedule: body.schedule ?? [], schedule: body.schedule ?? [],
@@ -121,6 +126,116 @@ export class MatchController {
return this.matchService.update({ matchId, communityId, patch: body }); return this.matchService.update({ matchId, communityId, patch: body });
} }
@Post(':matchId/double-elimination/seeds/reshuffle')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async reshuffleDoubleEliminationSeeds(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.reshuffleDoubleEliminationSeeds({
matchId,
communityId,
actorUserId: currentUser._id,
});
return this.matchService.serialize(match);
}
@Post(':matchId/double-elimination/seeds/swap')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async swapDoubleEliminationSeeds(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: SwapDoubleEliminationSeedsDto,
) {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.swapDoubleEliminationSeeds({
matchId,
communityId,
actorUserId: currentUser._id,
leftSeedNumber: body.leftSeedNumber,
rightSeedNumber: body.rightSeedNumber,
});
return this.matchService.serialize(match);
}
@Post(':matchId/double-elimination/bracket-matches/:bracketMatchId/walkover')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async applyDoubleEliminationWalkover(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('bracketMatchId') bracketMatchId: string,
@Body() body: ApplyDoubleEliminationWalkoverDto,
) {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.applyDoubleEliminationWalkover({
matchId,
communityId,
actorUserId: currentUser._id,
bracketMatchId,
winnerTeamIndex: body.winnerTeamIndex,
reason: body.reason,
});
return this.matchService.serialize(match);
}
@Post(
':matchId/double-elimination/bracket-matches/:bracketMatchId/walkover/cancel',
)
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async cancelDoubleEliminationWalkover(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('bracketMatchId') bracketMatchId: string,
@Body() body: CancelDoubleEliminationActionDto,
) {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.cancelDoubleEliminationWalkover({
matchId,
communityId,
actorUserId: currentUser._id,
bracketMatchId,
reason: body.reason,
});
return this.matchService.serialize(match);
}
@Post(
':matchId/double-elimination/bracket-matches/:bracketMatchId/result/cancel',
)
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async cancelDoubleEliminationRiotResult(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('bracketMatchId') bracketMatchId: string,
@Body() body: CancelDoubleEliminationActionDto,
) {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.cancelDoubleEliminationRiotResult({
matchId,
communityId,
actorUserId: currentUser._id,
bracketMatchId,
reason: body.reason,
});
return this.matchService.serialize(match);
}
@Delete(':matchId') @Delete(':matchId')
@Roles('admin', 'owner') @Roles('admin', 'owner')
@UseGuards(RolesGuard) @UseGuards(RolesGuard)
@@ -2,6 +2,55 @@ import mongoose from 'mongoose';
import { MatchService } from './match.service'; import { MatchService } from './match.service';
describe('MatchService', () => { describe('MatchService', () => {
function createServiceWithCreateModels() {
const createdPayloads: Record<string, unknown>[] = [];
const MatchModel = {
create: jest.fn().mockImplementation(async (payload) => {
createdPayloads.push(payload);
return payload;
}),
exists: jest.fn().mockResolvedValue(null),
};
const CommunityModel = {
findById: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ matchGameCount: 3 }),
}),
}),
}),
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return MatchModel;
if (name === 'community') return CommunityModel;
return {};
}),
};
const tournamentCodeService = {
buildSlots: jest.fn().mockResolvedValue([]),
releaseFromMatch: jest.fn().mockResolvedValue(undefined),
};
const communityStatsService = {
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
};
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
removeByMatch: jest.fn().mockResolvedValue(undefined),
};
return {
service: new MatchService(
connectionService as never,
tournamentCodeService as never,
communityStatsService as never,
matchStatsService as never,
),
MatchModel,
createdPayloads,
};
}
function createService(match: Record<string, unknown>) { function createService(match: Record<string, unknown>) {
const MatchModel = { const MatchModel = {
findById: jest.fn().mockResolvedValue(match), findById: jest.fn().mockResolvedValue(match),
@@ -254,6 +303,57 @@ describe('MatchService', () => {
expect(match.save).toHaveBeenCalledTimes(1); expect(match.save).toHaveBeenCalledTimes(1);
}); });
it('normalizes double-elimination match creation', async () => {
const { service, createdPayloads } = createServiceWithCreateModels();
const communityId = new mongoose.Types.ObjectId();
await service.create({
communityId,
data: {
title: 'Double elimination',
scheduledAt: new Date('2026-06-01T10:00:00.000Z'),
maxParticipants: 20,
gameCount: 5,
gameMode: 'double-elimination',
doubleEliminationResetFinalEnabled: true,
},
});
expect(createdPayloads[0]).toMatchObject({
communityId,
maxParticipants: 20,
gameCount: 1,
gameMode: 'double-elimination',
roundRobinMaxRounds: undefined,
doubleElimination: {
teamCount: 4,
resetFinalEnabled: true,
resetFinalCreated: false,
seeds: [],
bracketMatches: [],
placements: {},
events: [],
},
});
});
it('rejects unsupported double-elimination participant counts', async () => {
const { service, MatchModel } = createServiceWithCreateModels();
await expect(
service.create({
communityId: new mongoose.Types.ObjectId(),
data: {
title: 'Invalid double elimination',
scheduledAt: new Date('2026-06-01T10:00:00.000Z'),
maxParticipants: 30,
gameMode: 'double-elimination',
},
}),
).rejects.toThrow('Double elimination supports only 20 or 40 participants.');
expect(MatchModel.create).not.toHaveBeenCalled();
});
it('clears game schedule when a built match returns to recruiting', async () => { it('clears game schedule when a built match returns to recruiting', async () => {
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
const match = { const match = {
@@ -310,7 +410,7 @@ describe('MatchService', () => {
patch: { roundRobinMaxRounds: 3 }, patch: { roundRobinMaxRounds: 3 },
}), }),
).rejects.toThrow( ).rejects.toThrow(
'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.', 'maxParticipants, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
); );
expect(match.set).not.toHaveBeenCalled(); expect(match.set).not.toHaveBeenCalled();
}); });
+424 -10
View File
@@ -5,12 +5,19 @@ import {
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import {
cancelDoubleEliminationBracketMatch,
completeDoubleEliminationBracketMatch,
reshuffleDoubleEliminationSeeds,
swapDoubleEliminationSeeds,
} from '../double-elimination/double-elimination.util';
import { MatchStatsService } from '../community-stats/match-stats.service'; import { MatchStatsService } from '../community-stats/match-stats.service';
import { CommunityStatsService } from '../community-stats/community-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import { import {
Match, Match,
MatchDocument, MatchDocument,
MatchGameMode,
MatchSeriesResult, MatchSeriesResult,
MatchStatus, MatchStatus,
POSITIONS, POSITIONS,
@@ -26,17 +33,24 @@ const MATCH_SHORT_CODE_LENGTH = 4;
const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20; const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20;
const DEFAULT_MATCH_LIST_LIMIT = 50; const DEFAULT_MATCH_LIST_LIMIT = 50;
const MAX_MATCH_LIST_LIMIT = 200; const MAX_MATCH_LIST_LIMIT = 200;
const DOUBLE_ELIMINATION_PARTICIPANT_COUNTS = [20, 40] as const;
interface DoubleEliminationConfigInput {
doubleEliminationResetFinalEnabled?: boolean;
}
interface CreateMatchParams { interface CreateMatchParams {
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
hostUserId?: mongoose.Types.ObjectId; hostUserId?: mongoose.Types.ObjectId;
data: Partial<Match> & Pick<Match, 'title' | 'scheduledAt'>; data: Partial<Match> &
Pick<Match, 'title' | 'scheduledAt'> &
DoubleEliminationConfigInput;
} }
interface UpdateMatchParams { interface UpdateMatchParams {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId;
patch: Partial<Match>; patch: Partial<Match> & DoubleEliminationConfigInput;
} }
interface ListMatchesQuery { interface ListMatchesQuery {
@@ -89,6 +103,31 @@ interface UpdateParticipantPositionsParams {
subPosition: Position; subPosition: Position;
} }
interface DoubleEliminationAdminParams {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
actorUserId: mongoose.Types.ObjectId;
}
interface SwapDoubleEliminationSeedsParams
extends DoubleEliminationAdminParams {
leftSeedNumber: number;
rightSeedNumber: number;
}
interface ApplyDoubleEliminationWalkoverParams
extends DoubleEliminationAdminParams {
bracketMatchId: string;
winnerTeamIndex: number;
reason?: string;
}
interface CancelDoubleEliminationActionParams
extends DoubleEliminationAdminParams {
bracketMatchId: string;
reason?: string;
}
@Injectable() @Injectable()
export class MatchService { export class MatchService {
constructor( constructor(
@@ -105,15 +144,18 @@ export class MatchService {
.select({ matchGameCount: 1 }) .select({ matchGameCount: 1 })
.lean() .lean()
.exec(); .exec();
return MatchModel.create({ const normalizedData = this.normalizeMatchConfig({
...params.data, ...params.data,
shortCode:
params.data.shortCode ??
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
gameCount: gameCount:
params.data.gameCount ?? params.data.gameCount ??
community?.matchGameCount ?? community?.matchGameCount ??
DEFAULT_TOURNAMENT_GAME_COUNT, DEFAULT_TOURNAMENT_GAME_COUNT,
});
return MatchModel.create({
...normalizedData,
shortCode:
normalizedData.shortCode ??
(await this.generateUniqueShortCode(MatchModel, params.communityId)),
communityId: params.communityId, communityId: params.communityId,
hostUserId: params.hostUserId, hostUserId: params.hostUserId,
}); });
@@ -216,13 +258,30 @@ export class MatchService {
previousStatus !== 'recruiting' && previousStatus !== 'recruiting' &&
('maxParticipants' in params.patch || ('maxParticipants' in params.patch ||
'gameMode' in params.patch || 'gameMode' in params.patch ||
'roundRobinMaxRounds' in params.patch) 'roundRobinMaxRounds' in params.patch ||
'doubleEliminationResetFinalEnabled' in params.patch)
) { ) {
throw new BadRequestException( throw new BadRequestException(
'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.', 'maxParticipants, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
); );
} }
match.set(params.patch); const patchToSet =
previousStatus === 'recruiting'
? this.normalizeMatchConfig({
...params.patch,
gameMode: params.patch.gameMode ?? match.gameMode,
maxParticipants:
params.patch.maxParticipants ?? match.maxParticipants,
gameCount: params.patch.gameCount ?? match.gameCount,
roundRobinMaxRounds:
params.patch.roundRobinMaxRounds ?? match.roundRobinMaxRounds,
doubleEliminationResetFinalEnabled:
params.patch.doubleEliminationResetFinalEnabled ??
params.patch.doubleElimination?.resetFinalEnabled ??
match.doubleElimination?.resetFinalEnabled,
})
: this.stripMatchConfigInput(params.patch);
match.set(patchToSet);
if (previousStatus !== 'recruiting' && match.status === 'recruiting') { if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
if (match.tournamentCodeIds.length > 0) { if (match.tournamentCodeIds.length > 0) {
await this.tournamentCodeService.releaseFromMatch(match); await this.tournamentCodeService.releaseFromMatch(match);
@@ -260,6 +319,174 @@ export class MatchService {
await this.communityStatsService.invalidateCommunity(params.communityId); await this.communityStatsService.invalidateCommunity(params.communityId);
} }
public async reshuffleDoubleEliminationSeeds(
params: DoubleEliminationAdminParams,
): Promise<MatchDocument> {
const match = await this.loadDoubleEliminationMatch(params);
await this.assertDoubleEliminationSeedsCanChange(match);
await this.releaseReservedDoubleEliminationCodes(match);
match.doubleElimination = reshuffleDoubleEliminationSeeds(
match.doubleElimination as NonNullable<Match['doubleElimination']>,
);
match.doubleElimination!.events.push({
type: 'seeds-reshuffled',
actorUserId: params.actorUserId,
createdAt: new Date(),
});
match.markModified('doubleElimination');
await match.save();
await this.tournamentCodeService.reserveForMatch(match);
return match;
}
public async swapDoubleEliminationSeeds(
params: SwapDoubleEliminationSeedsParams,
): Promise<MatchDocument> {
const match = await this.loadDoubleEliminationMatch(params);
await this.assertDoubleEliminationSeedsCanChange(match);
await this.releaseReservedDoubleEliminationCodes(match);
match.doubleElimination = swapDoubleEliminationSeeds(
match.doubleElimination as NonNullable<Match['doubleElimination']>,
{
leftSeedNumber: params.leftSeedNumber,
rightSeedNumber: params.rightSeedNumber,
},
);
match.doubleElimination!.events.push({
type: 'seeds-swapped',
actorUserId: params.actorUserId,
createdAt: new Date(),
});
match.markModified('doubleElimination');
await match.save();
await this.tournamentCodeService.reserveForMatch(match);
return match;
}
public async applyDoubleEliminationWalkover(
params: ApplyDoubleEliminationWalkoverParams,
): Promise<MatchDocument> {
const match = await this.loadDoubleEliminationMatch(params);
const bracketMatch = this.requireDoubleEliminationBracketMatch(
match,
params.bracketMatchId,
);
if (bracketMatch.state !== 'ready') {
throw new BadRequestException('Bracket match is not ready.');
}
if (
bracketMatch.teamAIndex !== params.winnerTeamIndex &&
bracketMatch.teamBIndex !== params.winnerTeamIndex
) {
throw new BadRequestException(
'Winner team is not assigned to this bracket match.',
);
}
await this.releaseReservedDoubleEliminationCodes(match, [
params.bracketMatchId,
]);
match.doubleElimination = completeDoubleEliminationBracketMatch(
match.doubleElimination as NonNullable<Match['doubleElimination']>,
{
bracketMatchId: params.bracketMatchId,
winnerTeamIndex: params.winnerTeamIndex,
completedBy: 'walkover',
completedAt: new Date(),
walkover: {
winnerTeamIndex: params.winnerTeamIndex,
reason: params.reason,
awardedBy: params.actorUserId,
awardedAt: new Date(),
active: true,
},
},
);
match.markModified('doubleElimination');
this.syncDoubleEliminationWinner(match);
await match.save();
await this.tournamentCodeService.reserveForMatch(match);
await this.communityStatsService.invalidateCommunity(params.communityId);
return match;
}
public async cancelDoubleEliminationWalkover(
params: CancelDoubleEliminationActionParams,
): Promise<MatchDocument> {
const match = await this.loadDoubleEliminationMatch(params);
const bracketMatch = this.requireDoubleEliminationBracketMatch(
match,
params.bracketMatchId,
);
if (
bracketMatch.completedBy !== 'walkover' ||
!bracketMatch.walkover?.active
) {
throw new BadRequestException('Active walkover was not found.');
}
await this.releaseReservedDoubleEliminationCodes(match);
match.doubleElimination = cancelDoubleEliminationBracketMatch(
match.doubleElimination as NonNullable<Match['doubleElimination']>,
{
bracketMatchId: params.bracketMatchId,
cancelledBy: params.actorUserId,
cancelReason: params.reason,
},
);
match.markModified('doubleElimination');
this.syncDoubleEliminationWinner(match);
await match.save();
await this.tournamentCodeService.reserveForMatch(match);
await this.communityStatsService.invalidateCommunity(params.communityId);
return match;
}
public async cancelDoubleEliminationRiotResult(
params: CancelDoubleEliminationActionParams,
): Promise<MatchDocument> {
const match = await this.loadDoubleEliminationMatch(params);
const game = match.result?.games?.find(
(entry) => entry.bracketMatchId === params.bracketMatchId,
);
if (!game) throw new NotFoundException('Collected result not found.');
await this.releaseReservedDoubleEliminationCodes(match);
match.doubleElimination = cancelDoubleEliminationBracketMatch(
match.doubleElimination as NonNullable<Match['doubleElimination']>,
{
bracketMatchId: params.bracketMatchId,
cancelledBy: params.actorUserId,
cancelReason: params.reason,
},
);
match.doubleElimination!.events.push({
type: 'riot-result-cancelled',
bracketMatchId: params.bracketMatchId,
actorUserId: params.actorUserId,
reason: params.reason,
createdAt: new Date(),
});
const games = (match.result?.games ?? []).filter(
(entry) => entry.bracketMatchId !== params.bracketMatchId,
);
match.result = {
winnerTeamIndex: undefined,
mvpUserId: match.result?.mvpUserId,
riotMatchIds: (match.result?.riotMatchIds ?? []).filter(
(riotMatchId) => riotMatchId !== game.riotMatchId,
),
games,
seriesResults: this.buildSeriesResults(games),
};
await this.voidDoubleEliminationCode(match, params.bracketMatchId);
if (match.status === 'finished') match.status = 'in-progress';
match.markModified('doubleElimination');
await match.save();
await this.tournamentCodeService.reserveForMatch(match);
await this.matchStatsService.buildAndUpsert(match._id);
await this.communityStatsService.invalidateCommunity(params.communityId);
return match;
}
public async join(params: JoinMatchParams): Promise<MatchDocument> { public async join(params: JoinMatchParams): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match'); const MatchModel = await this.connectionService.getModel('match');
const UserModel = await this.connectionService.getModel('user'); const UserModel = await this.connectionService.getModel('user');
@@ -307,6 +534,192 @@ export class MatchService {
return match; return match;
} }
private normalizeMatchConfig<T extends Partial<Match> & DoubleEliminationConfigInput>(
input: T,
): Partial<Match> {
const patch = this.stripMatchConfigInput(input);
const gameMode = (patch.gameMode ?? 'pair') as MatchGameMode;
const maxParticipants = patch.maxParticipants ?? 10;
if (gameMode === 'double-elimination') {
if (
!DOUBLE_ELIMINATION_PARTICIPANT_COUNTS.includes(
maxParticipants as (typeof DOUBLE_ELIMINATION_PARTICIPANT_COUNTS)[number],
)
) {
throw new BadRequestException(
'Double elimination supports only 20 or 40 participants.',
);
}
return {
...patch,
gameMode,
maxParticipants,
gameCount: 1,
roundRobinMaxRounds: undefined,
gameSchedule: [],
doubleElimination: {
teamCount: (maxParticipants / 5) as 4 | 8,
resetFinalEnabled:
input.doubleEliminationResetFinalEnabled ??
input.doubleElimination?.resetFinalEnabled ??
false,
resetFinalCreated: false,
seeds: [],
bracketMatches: [],
placements: {},
events: [],
},
};
}
return {
...patch,
gameMode,
doubleElimination: undefined,
};
}
private stripMatchConfigInput<T extends Partial<Match> & DoubleEliminationConfigInput>(
input: T,
): Partial<Match> {
const { doubleEliminationResetFinalEnabled: _ignored, ...patch } = input;
return patch;
}
private async loadDoubleEliminationMatch(params: {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
}): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
let match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Match does not belong to this community.');
}
if ((match.gameMode ?? 'pair') !== 'double-elimination') {
throw new BadRequestException('Match is not double elimination.');
}
if (!match.doubleElimination?.bracketMatches?.length) {
match = await this.tournamentCodeService.reserveForMatch(match);
}
if (!match.doubleElimination?.bracketMatches?.length) {
throw new BadRequestException('Double elimination bracket is not ready.');
}
return match;
}
private async assertDoubleEliminationSeedsCanChange(
match: MatchDocument,
): Promise<void> {
if (
match.doubleElimination?.bracketMatches.some(
(bracketMatch) => bracketMatch.state === 'completed',
)
) {
throw new BadRequestException(
'Seeds cannot be changed after a bracket match is completed.',
);
}
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const usedCode = await TournamentCodeModel.exists({
_id: { $in: match.tournamentCodeIds ?? [] },
$or: [{ state: 'used' }, { riotMatchId: { $exists: true } }],
});
if (usedCode) {
throw new BadRequestException(
'Seeds cannot be changed after a tournament code is used.',
);
}
}
private requireDoubleEliminationBracketMatch(
match: MatchDocument,
bracketMatchId: string,
) {
const bracketMatch = match.doubleElimination?.bracketMatches.find(
(entry) => entry.bracketMatchId === bracketMatchId,
);
if (!bracketMatch) throw new NotFoundException('Bracket match not found.');
return bracketMatch;
}
private async releaseReservedDoubleEliminationCodes(
match: MatchDocument,
bracketMatchIds?: string[],
): Promise<void> {
const ids = match.tournamentCodeIds ?? [];
if (ids.length === 0) return;
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const codes = await TournamentCodeModel.find({
_id: { $in: ids },
matchId: match._id,
state: 'reserved',
...(bracketMatchIds
? { bracketMatchId: { $in: bracketMatchIds } }
: { bracketMatchId: { $exists: true } }),
}).exec();
if (codes.length === 0) return;
const releasedIds = codes.map((code) => code._id.toString());
await TournamentCodeModel.updateMany(
{ _id: { $in: codes.map((code) => code._id) } },
{
$set: { state: 'released', releasedAt: new Date() },
$unset: {
matchId: 1,
gameNumber: 1,
bracketMatchId: 1,
reservedAt: 1,
},
},
).exec();
match.tournamentCodeIds = ids.filter(
(id) => !releasedIds.includes(id.toString()),
);
}
private async voidDoubleEliminationCode(
match: MatchDocument,
bracketMatchId: string,
): Promise<void> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
await TournamentCodeModel.updateOne(
{
_id: { $in: match.tournamentCodeIds ?? [] },
matchId: match._id,
bracketMatchId,
state: 'used',
},
{
$set: { state: 'voided' },
},
).exec();
}
private syncDoubleEliminationWinner(match: MatchDocument): void {
if ((match.gameMode ?? 'pair') !== 'double-elimination') return;
const firstTeamIndex = match.doubleElimination?.placements.firstTeamIndex;
if (firstTeamIndex) {
match.status = 'finished';
match.result = match.result ?? {
riotMatchIds: [],
games: [],
seriesResults: [],
};
match.result.winnerTeamIndex = firstTeamIndex;
return;
}
if (match.status === 'finished') {
match.status = 'in-progress';
}
if (match.result) {
match.result.winnerTeamIndex = undefined;
}
}
public async cancelJoin( public async cancelJoin(
params: CancelMatchJoinParams, params: CancelMatchJoinParams,
): Promise<MatchDocument> { ): Promise<MatchDocument> {
@@ -539,10 +952,11 @@ export class MatchService {
for (const game of games) { for (const game of games) {
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
const key = `${teamAIndex}:${teamBIndex}`; const key = game.bracketMatchId ?? `${teamAIndex}:${teamBIndex}`;
const current = const current =
bySeries.get(key) ?? bySeries.get(key) ??
({ ({
bracketMatchId: game.bracketMatchId,
teamAIndex, teamAIndex,
teamBIndex, teamBIndex,
teamAWins: 0, teamAWins: 0,
@@ -28,10 +28,11 @@ function createService() {
interface MatchOverrides { interface MatchOverrides {
gameCount?: number; gameCount?: number;
gameMode?: 'pair' | 'bracket' | 'round-robin'; gameMode?: 'pair' | 'bracket' | 'round-robin' | 'double-elimination';
roundRobinMaxRounds?: number; roundRobinMaxRounds?: number;
participants?: Array<{ excluded?: boolean }>; participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>; teams?: Array<{ teamIndex: number }>;
doubleElimination?: MatchDocument['doubleElimination'];
gameSchedule?: Array<{ gameSchedule?: Array<{
gameNumber: number; gameNumber: number;
roundNumber?: number; roundNumber?: number;
@@ -51,6 +52,7 @@ function createMatch(overrides: MatchOverrides): MatchDocument {
tournamentCodeIds: [], tournamentCodeIds: [],
gameSchedule: [], gameSchedule: [],
save: jest.fn().mockResolvedValue(undefined), save: jest.fn().mockResolvedValue(undefined),
markModified: jest.fn(),
...overrides, ...overrides,
} as unknown as MatchDocument; } as unknown as MatchDocument;
} }
@@ -206,6 +208,35 @@ describe('TournamentCodeService round-robin scheduling', () => {
expect(pair.gameSchedule).toEqual([]); expect(pair.gameSchedule).toEqual([]);
}); });
it('creates a double-elimination bracket from built teams', () => {
const service = createService();
const match = createMatch({
gameMode: 'double-elimination',
teams: Array.from({ length: 4 }, (_, index) => ({
teamIndex: index + 1,
})),
doubleElimination: {
teamCount: 4,
resetFinalEnabled: true,
resetFinalCreated: false,
seeds: [],
bracketMatches: [],
placements: {},
events: [],
},
});
service.ensureGameSchedule(match);
expect(match.doubleElimination?.seeds).toHaveLength(4);
expect(match.doubleElimination?.bracketMatches).toHaveLength(6);
expect(
match.doubleElimination?.bracketMatches.filter(
(bracketMatch) => bracketMatch.state === 'ready',
),
).toHaveLength(2);
});
it('creates a limited round-robin schedule grouped by playable rounds', () => { it('creates a limited round-robin schedule grouped by playable rounds', () => {
const service = createService(); const service = createService();
const roundRobin = createMatch({ const roundRobin = createMatch({
@@ -4,8 +4,13 @@ import {
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import {
buildDoubleEliminationBracket,
findNextReadyDoubleEliminationBracketMatches,
} from '../double-elimination/double-elimination.util';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import type { import type {
DoubleEliminationBracketMatch,
MatchGameAssignment, MatchGameAssignment,
MatchDocument, MatchDocument,
TournamentCode, TournamentCode,
@@ -239,8 +244,12 @@ export class TournamentCodeService {
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
match.tournamentCodeIds = match.tournamentCodeIds ?? []; match.tournamentCodeIds = match.tournamentCodeIds ?? [];
this.ensureGameSchedule(match); this.ensureGameSchedule(match);
if ((match.gameMode ?? 'pair') === 'double-elimination') {
return this.reserveForDoubleEliminationMatch(match, TournamentCodeModel);
}
const shouldSaveMetadata = const shouldSaveMetadata =
match.isModified('gameCount') || match.isModified('gameSchedule'); this.isMatchModified(match, 'gameCount') ||
this.isMatchModified(match, 'gameSchedule');
const requiredSlots = this.resolveRequiredSlots(match); const requiredSlots = this.resolveRequiredSlots(match);
const need = requiredSlots - match.tournamentCodeIds.length; const need = requiredSlots - match.tournamentCodeIds.length;
if (need <= 0) { if (need <= 0) {
@@ -309,6 +318,13 @@ export class TournamentCodeService {
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
match.tournamentCodeIds = match.tournamentCodeIds ?? []; match.tournamentCodeIds = match.tournamentCodeIds ?? [];
this.ensureGameSchedule(match); this.ensureGameSchedule(match);
const doubleEliminationBracketMatch =
(match.gameMode ?? 'pair') === 'double-elimination'
? this.resolveDoubleEliminationBracketMatchByGameNumber(
match,
params.gameNumber,
)
: undefined;
const requiredSlots = this.resolveRequiredSlots(match); const requiredSlots = this.resolveRequiredSlots(match);
if ( if (
@@ -320,7 +336,11 @@ export class TournamentCodeService {
} }
if ( if (
(match.result?.games ?? []).some( (match.result?.games ?? []).some(
(game) => game.gameNumber === params.gameNumber, (game) =>
game.gameNumber === params.gameNumber ||
(doubleEliminationBracketMatch?.bracketMatchId &&
game.bracketMatchId ===
doubleEliminationBracketMatch.bracketMatchId),
) )
) { ) {
throw new BadRequestException( throw new BadRequestException(
@@ -331,7 +351,9 @@ export class TournamentCodeService {
const currentCode = await TournamentCodeModel.findOne({ const currentCode = await TournamentCodeModel.findOne({
_id: { $in: match.tournamentCodeIds }, _id: { $in: match.tournamentCodeIds },
matchId: match._id, matchId: match._id,
gameNumber: params.gameNumber, ...(doubleEliminationBracketMatch
? { bracketMatchId: doubleEliminationBracketMatch.bracketMatchId }
: { gameNumber: params.gameNumber }),
}).exec(); }).exec();
if (!currentCode) { if (!currentCode) {
throw new NotFoundException('Assigned tournament code not found.'); throw new NotFoundException('Assigned tournament code not found.');
@@ -358,6 +380,11 @@ export class TournamentCodeService {
state: 'reserved', state: 'reserved',
matchId: match._id, matchId: match._id,
gameNumber: params.gameNumber, gameNumber: params.gameNumber,
...(doubleEliminationBracketMatch
? {
bracketMatchId: doubleEliminationBracketMatch.bracketMatchId,
}
: {}),
reservedAt: new Date(), reservedAt: new Date(),
}, },
$unset: { releasedAt: 1 }, $unset: { releasedAt: 1 },
@@ -373,6 +400,7 @@ export class TournamentCodeService {
currentCode.state = 'released'; currentCode.state = 'released';
currentCode.matchId = undefined; currentCode.matchId = undefined;
currentCode.gameNumber = undefined; currentCode.gameNumber = undefined;
currentCode.bracketMatchId = undefined;
currentCode.reservedAt = undefined; currentCode.reservedAt = undefined;
currentCode.releasedAt = new Date(); currentCode.releasedAt = new Date();
currentCode.riotMatchId = undefined; currentCode.riotMatchId = undefined;
@@ -386,6 +414,9 @@ export class TournamentCodeService {
return { return {
gameNumber: params.gameNumber, gameNumber: params.gameNumber,
...(doubleEliminationBracketMatch
? this.toDoubleEliminationSlotBase(doubleEliminationBracketMatch)
: {}),
roundNumber: this.resolveRoundNumberForGameNumber( roundNumber: this.resolveRoundNumberForGameNumber(
match, match,
params.gameNumber, params.gameNumber,
@@ -415,7 +446,12 @@ export class TournamentCodeService {
{ _id: { $in: match.tournamentCodeIds }, state: 'reserved' }, { _id: { $in: match.tournamentCodeIds }, state: 'reserved' },
{ {
$set: { state: 'released', releasedAt: new Date() }, $set: { state: 'released', releasedAt: new Date() },
$unset: { matchId: 1, gameNumber: 1, reservedAt: 1 }, $unset: {
matchId: 1,
gameNumber: 1,
bracketMatchId: 1,
reservedAt: 1,
},
}, },
).exec(); ).exec();
@@ -483,6 +519,9 @@ export class TournamentCodeService {
public async buildSlots( public async buildSlots(
match: MatchDocument, match: MatchDocument,
): Promise<TournamentCodeSlotView[]> { ): Promise<TournamentCodeSlotView[]> {
if ((match.gameMode ?? 'pair') === 'double-elimination') {
return this.buildDoubleEliminationSlots(match);
}
if ( if (
(match.gameMode ?? 'pair') === 'round-robin' && (match.gameMode ?? 'pair') === 'round-robin' &&
(match.gameSchedule?.length ?? 0) === 0 && (match.gameSchedule?.length ?? 0) === 0 &&
@@ -550,10 +589,130 @@ export class TournamentCodeService {
return next; return next;
} }
private async reserveForDoubleEliminationMatch(
match: MatchDocument,
TournamentCodeModel: mongoose.Model<TournamentCode>,
): Promise<MatchDocument> {
const readyBracketMatches = findNextReadyDoubleEliminationBracketMatches(
match.doubleElimination,
);
const existingCodes =
match.tournamentCodeIds.length > 0
? await TournamentCodeModel.find({
_id: { $in: match.tournamentCodeIds },
}).exec()
: [];
const byBracketMatchId = new Map(
existingCodes
.filter(
(code) =>
code.bracketMatchId &&
(code.state === 'reserved' || code.state === 'used'),
)
.map((code) => [code.bracketMatchId as string, code]),
);
const expiresAfter = new Date(
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
);
const reservedIds: mongoose.Types.ObjectId[] = [];
for (const bracketMatch of readyBracketMatches) {
if (byBracketMatchId.has(bracketMatch.bracketMatchId)) continue;
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: bracketMatch.gameNumber,
bracketMatchId: bracketMatch.bracketMatchId,
reservedAt: new Date(),
},
$unset: { releasedAt: 1 },
},
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
).exec();
if (!code) break;
reservedIds.push(code._id);
byBracketMatchId.set(bracketMatch.bracketMatchId, code);
}
if (reservedIds.length > 0) {
match.tournamentCodeIds.push(...reservedIds);
}
if (
reservedIds.length > 0 ||
this.isMatchModified(match, 'doubleElimination')
) {
await match.save();
}
return match;
}
private async buildDoubleEliminationSlots(
match: MatchDocument,
): Promise<TournamentCodeSlotView[]> {
this.ensureGameSchedule(match);
const bracketMatches = match.doubleElimination?.bracketMatches ?? [];
if (bracketMatches.length === 0) return [];
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const ids = match.tournamentCodeIds ?? [];
const codes =
ids.length > 0
? await TournamentCodeModel.find({ _id: { $in: ids } }).exec()
: [];
const byBracketMatchId = new Map(
codes
.filter(
(code) =>
code.bracketMatchId &&
code.state !== 'released' &&
code.state !== 'voided',
)
.map((code) => [code.bracketMatchId as string, code]),
);
return bracketMatches.map((bracketMatch) => {
const code = byBracketMatchId.get(bracketMatch.bracketMatchId);
return {
...this.toDoubleEliminationSlotBase(bracketMatch),
code: code?.code ?? null,
expiresAt: code?.expiresAt.toISOString() ?? null,
state: code?.state ?? 'pending',
riotMatchId: code?.riotMatchId ?? null,
};
});
}
private toDoubleEliminationSlotBase(
bracketMatch: DoubleEliminationBracketMatch,
): Omit<TournamentCodeSlotView, 'code' | 'expiresAt' | 'state' | 'riotMatchId'> {
return {
gameNumber: bracketMatch.gameNumber,
bracketMatchId: bracketMatch.bracketMatchId,
bracketSide: bracketMatch.bracketSide,
roundNumber: bracketMatch.roundNumber,
matchNumber: bracketMatch.matchNumber,
teamAIndex: bracketMatch.teamAIndex,
teamBIndex: bracketMatch.teamBIndex,
};
}
private resolveRequiredSlots(match: MatchDocument): number { private resolveRequiredSlots(match: MatchDocument): number {
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
const gameMode = match.gameMode ?? 'pair'; const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'double-elimination') {
return match.doubleElimination?.bracketMatches.length ?? 0;
}
if (gameMode === 'round-robin') { if (gameMode === 'round-robin') {
if ((match.gameSchedule?.length ?? 0) > 0) { if ((match.gameSchedule?.length ?? 0) > 0) {
return match.gameSchedule.length; return match.gameSchedule.length;
@@ -577,6 +736,17 @@ export class TournamentCodeService {
): { teamAIndex: number; teamBIndex: number } { ): { teamAIndex: number; teamBIndex: number } {
const gameMode = match.gameMode ?? 'pair'; const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'double-elimination') {
const bracketMatch = this.resolveDoubleEliminationBracketMatchByGameNumber(
match,
gameNumber,
);
return {
teamAIndex: bracketMatch?.teamAIndex ?? 1,
teamBIndex: bracketMatch?.teamBIndex ?? 2,
};
}
if (gameMode === 'round-robin') { if (gameMode === 'round-robin') {
const persisted = match.gameSchedule?.find( const persisted = match.gameSchedule?.find(
(entry) => entry.gameNumber === gameNumber, (entry) => entry.gameNumber === gameNumber,
@@ -611,6 +781,10 @@ export class TournamentCodeService {
} }
private ensureGameSchedule(match: MatchDocument): void { private ensureGameSchedule(match: MatchDocument): void {
if ((match.gameMode ?? 'pair') === 'double-elimination') {
this.ensureDoubleEliminationBracket(match);
return;
}
if ((match.gameMode ?? 'pair') !== 'round-robin') return; if ((match.gameMode ?? 'pair') !== 'round-robin') return;
if ((match.gameSchedule?.length ?? 0) > 0) return; if ((match.gameSchedule?.length ?? 0) > 0) return;
@@ -620,6 +794,48 @@ export class TournamentCodeService {
match.gameSchedule = this.buildRoundRobinGameSchedule(match); match.gameSchedule = this.buildRoundRobinGameSchedule(match);
} }
private ensureDoubleEliminationBracket(match: MatchDocument): void {
if ((match.doubleElimination?.bracketMatches.length ?? 0) > 0) return;
const teamIndexes = [...(match.teams ?? [])]
.map((team) => team.teamIndex)
.sort((left, right) => left - right);
if (teamIndexes.length !== 4 && teamIndexes.length !== 8) return;
const shuffledTeamIndexes = this.shuffleTeamIndexes(teamIndexes);
match.doubleElimination = buildDoubleEliminationBracket(
shuffledTeamIndexes,
{
resetFinalEnabled:
match.doubleElimination?.resetFinalEnabled ?? false,
},
);
match.markModified?.('doubleElimination');
}
private resolveDoubleEliminationBracketMatchByGameNumber(
match: MatchDocument,
gameNumber: number,
): DoubleEliminationBracketMatch | undefined {
return match.doubleElimination?.bracketMatches.find(
(bracketMatch) => bracketMatch.gameNumber === gameNumber,
);
}
private shuffleTeamIndexes(teamIndexes: number[]): number[] {
const shuffled = [...teamIndexes];
for (let index = shuffled.length - 1; index > 0; index -= 1) {
const swapIndex = Math.floor(Math.random() * (index + 1));
[shuffled[index], shuffled[swapIndex]] = [
shuffled[swapIndex],
shuffled[index],
];
}
return shuffled;
}
private isMatchModified(match: MatchDocument, path: string): boolean {
return typeof match.isModified === 'function' && match.isModified(path);
}
private resolveRoundNumberForGameNumber( private resolveRoundNumberForGameNumber(
match: MatchDocument, match: MatchDocument,
gameNumber: number, gameNumber: number,
@@ -24,9 +24,12 @@ export interface BulkUploadTournamentCodesResponse {
export interface TournamentCodeSlotView { export interface TournamentCodeSlotView {
gameNumber: number; gameNumber: number;
bracketMatchId?: string;
bracketSide?: string;
roundNumber?: number; roundNumber?: number;
teamAIndex: number; matchNumber?: number;
teamBIndex: number; teamAIndex?: number;
teamBIndex?: number;
code: string | null; code: string | null;
expiresAt: string | null; expiresAt: string | null;
state: TournamentCodeState | 'pending'; state: TournamentCodeState | 'pending';
@@ -10,6 +10,9 @@ type TournamentResultServiceInternals = TournamentResultService & {
match: MatchDocument, match: MatchDocument,
gameNumber: number, gameNumber: number,
): { teamAIndex: number; teamBIndex: number }; ): { teamAIndex: number; teamBIndex: number };
buildSeriesResults(
games: NonNullable<MatchDocument['result']>['games'],
): NonNullable<MatchDocument['result']>['seriesResults'];
}; };
function createService() { function createService() {
@@ -100,6 +103,56 @@ describe('TournamentResultService round-robin scheduling', () => {
teamBIndex: 4, teamBIndex: 4,
}); });
}); });
it('keeps double-elimination rematches separated by bracket match id', () => {
const service = createService();
expect(
service.buildSeriesResults([
{
gameNumber: 1,
bracketMatchId: 'WB_FINAL',
riotMatchId: 'KR_1',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 1,
winnerSide: 'blue',
gameCreation: 1,
gameDuration: 1800,
participants: [],
},
{
gameNumber: 2,
bracketMatchId: 'GF',
riotMatchId: 'KR_2',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 2,
winnerSide: 'red',
gameCreation: 2,
gameDuration: 1800,
participants: [],
},
]),
).toEqual([
{
bracketMatchId: 'GF',
teamAIndex: 1,
teamBIndex: 2,
teamAWins: 0,
teamBWins: 1,
winnerTeamIndex: 2,
},
{
bracketMatchId: 'WB_FINAL',
teamAIndex: 1,
teamBIndex: 2,
teamAWins: 1,
teamBWins: 0,
winnerTeamIndex: 1,
},
]);
});
}); });
describe('TournamentResultService tournament code polling', () => { describe('TournamentResultService tournament code polling', () => {
@@ -5,12 +5,16 @@ import {
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import {
completeDoubleEliminationBracketMatch,
} from '../double-elimination/double-elimination.util';
import { MatchStatsService } from '../community-stats/match-stats.service'; import { MatchStatsService } from '../community-stats/match-stats.service';
import { CommunityStatsService } from '../community-stats/community-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import type { import type {
MatchDocument, MatchDocument,
MatchGameResult, MatchGameResult,
MatchSeriesResult,
RiotMatch as StoredRiotMatch, RiotMatch as StoredRiotMatch,
TournamentCodeDocument, TournamentCodeDocument,
} from '../global/database/schema'; } from '../global/database/schema';
@@ -22,6 +26,7 @@ import {
roundRobinGameSchedule, roundRobinGameSchedule,
resolveRoundRobinTeamCount, resolveRoundRobinTeamCount,
} from '../tournament-code/round-robin.util'; } from '../tournament-code/round-robin.util';
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../tournament-code/tournament-code.constants';
import { import {
collectCaptainAndLimitedTeamMemberUserIds, collectCaptainAndLimitedTeamMemberUserIds,
collectCaptainUserIds, collectCaptainUserIds,
@@ -44,6 +49,7 @@ const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60;
interface ManualGameAssignment { interface ManualGameAssignment {
gameNumber: number; gameNumber: number;
bracketMatchId?: string;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
} }
@@ -207,7 +213,11 @@ export class TournamentResultService {
(code) => code.state === 'reserved' && !code.riotMatchId, (code) => code.state === 'reserved' && !code.riotMatchId,
); );
if (unmatched.length === 0) { if (unmatched.length === 0) {
await this.advanceMatchIfReady(match, codes); const completed = await this.advanceMatchIfReady(match, codes);
if (!completed) {
await this.reserveReadyDoubleEliminationCodes(match);
await this.scheduleNextPoll(match, job);
}
return; return;
} }
@@ -324,6 +334,7 @@ export class TournamentResultService {
return false; return false;
} }
gameResult.bracketMatchId = code.bracketMatchId;
code.state = 'used'; code.state = 'used';
code.usedAt = new Date( code.usedAt = new Date(
detail.info.gameEndTimestamp ?? detail.info.gameCreation, detail.info.gameEndTimestamp ?? detail.info.gameCreation,
@@ -332,10 +343,12 @@ export class TournamentResultService {
await code.save(); await code.save();
this.upsertGameResult(match, gameResult); this.upsertGameResult(match, gameResult);
this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result');
if (match.status === 'team-built') { if (match.status === 'team-built') {
match.status = 'in-progress'; match.status = 'in-progress';
} }
await match.save(); await match.save();
await this.reserveReadyDoubleEliminationCodes(match);
await this.rebuildMatchStatsSafe(match); await this.rebuildMatchStatsSafe(match);
return true; return true;
} }
@@ -365,6 +378,7 @@ export class TournamentResultService {
} }
this.upsertGameResult(match, gameResult); this.upsertGameResult(match, gameResult);
this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result');
await this.markTournamentCodeUsedForManualResult( await this.markTournamentCodeUsedForManualResult(
match, match,
gameResult, gameResult,
@@ -379,6 +393,9 @@ export class TournamentResultService {
} }
this.updateManualCollectionState(match, appliedRiotMatchIds.length); this.updateManualCollectionState(match, appliedRiotMatchIds.length);
await match.save(); await match.save();
if (appliedRiotMatchIds.length > 0) {
await this.reserveReadyDoubleEliminationCodes(match);
}
if (appliedRiotMatchIds.length > 0) { if (appliedRiotMatchIds.length > 0) {
await this.rebuildMatchStatsSafe(match); await this.rebuildMatchStatsSafe(match);
} }
@@ -399,6 +416,36 @@ export class TournamentResultService {
match: MatchDocument, match: MatchDocument,
codes: TournamentCodeDocument[], codes: TournamentCodeDocument[],
): Promise<boolean> { ): Promise<boolean> {
if ((match.gameMode ?? 'pair') === 'double-elimination') {
if (!this.isDoubleEliminationComplete(match)) return false;
match.status = 'finished';
if (match.result) {
match.result.winnerTeamIndex =
match.doubleElimination?.placements.firstTeamIndex;
}
match.resultPollState = {
startedAt: match.resultPollState?.startedAt ?? new Date(),
lastPolledAt: match.resultPollState?.lastPolledAt,
lastPollOutcome: match.resultPollState?.lastPollOutcome,
matchedCount: match.result?.games?.length ?? 0,
expandedToAllPuuids:
match.resultPollState?.expandedToAllPuuids ?? false,
state: 'complete',
};
await match.save();
await this.rebuildMatchStatsSafe(match);
void this.communityStatsService
.invalidateCommunity(match.communityId)
.catch((error) => {
this.logger.warn(
`Failed to invalidate community stats cache for ${match.communityId.toString()}: ${
error instanceof Error ? error.message : error
}`,
);
});
return true;
}
if (codes.length < this.resolveRequiredGameSlots(match)) return false; if (codes.length < this.resolveRequiredGameSlots(match)) return false;
if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) { if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) {
return false; return false;
@@ -585,7 +632,10 @@ export class TournamentResultService {
const seriesResults = this.buildSeriesResults(games); const seriesResults = this.buildSeriesResults(games);
match.result = { match.result = {
winnerTeamIndex: this.resolveMatchWinnerTeamIndex(seriesResults), winnerTeamIndex:
(match.gameMode ?? 'pair') === 'double-elimination'
? match.doubleElimination?.placements.firstTeamIndex
: this.resolveMatchWinnerTeamIndex(seriesResults),
mvpUserId: match.result?.mvpUserId, mvpUserId: match.result?.mvpUserId,
riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))], riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))],
games, games,
@@ -607,7 +657,10 @@ export class TournamentResultService {
teamAIndex: assignment.teamAIndex, teamAIndex: assignment.teamAIndex,
teamBIndex: assignment.teamBIndex, teamBIndex: assignment.teamBIndex,
}); });
if (gameResult) return gameResult; if (gameResult) {
gameResult.bracketMatchId = assignment.bracketMatchId;
return gameResult;
}
} }
return null; return null;
} }
@@ -618,7 +671,26 @@ export class TournamentResultService {
const usedGameNumbers = new Set( const usedGameNumbers = new Set(
(match.result?.games ?? []).map((game) => game.gameNumber), (match.result?.games ?? []).map((game) => game.gameNumber),
); );
const usedBracketMatchIds = new Set(
(match.result?.games ?? [])
.map((game) => game.bracketMatchId)
.filter((id): id is string => Boolean(id)),
);
const assignments: ManualGameAssignment[] = []; const assignments: ManualGameAssignment[] = [];
if ((match.gameMode ?? 'pair') === 'double-elimination') {
for (const bracketMatch of match.doubleElimination?.bracketMatches ?? []) {
if (bracketMatch.state !== 'ready') continue;
if (usedBracketMatchIds.has(bracketMatch.bracketMatchId)) continue;
if (!bracketMatch.teamAIndex || !bracketMatch.teamBIndex) continue;
assignments.push({
gameNumber: bracketMatch.gameNumber,
bracketMatchId: bracketMatch.bracketMatchId,
teamAIndex: bracketMatch.teamAIndex,
teamBIndex: bracketMatch.teamBIndex,
});
}
return assignments;
}
const requiredSlots = this.resolveRequiredGameSlots(match); const requiredSlots = this.resolveRequiredGameSlots(match);
for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) { for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) {
@@ -641,6 +713,9 @@ export class TournamentResultService {
} }
private hasAllRequiredGameResults(match: MatchDocument): boolean { private hasAllRequiredGameResults(match: MatchDocument): boolean {
if ((match.gameMode ?? 'pair') === 'double-elimination') {
return this.isDoubleEliminationComplete(match);
}
const requiredSlots = this.resolveRequiredGameSlots(match); const requiredSlots = this.resolveRequiredGameSlots(match);
if (requiredSlots <= 0) return false; if (requiredSlots <= 0) return false;
const resultGameNumbers = new Set( const resultGameNumbers = new Set(
@@ -671,9 +746,10 @@ export class TournamentResultService {
): Promise<void> { ): Promise<void> {
match.status = 'finished'; match.status = 'finished';
if (match.result) { if (match.result) {
match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex( match.result.winnerTeamIndex =
match.result.seriesResults ?? [], (match.gameMode ?? 'pair') === 'double-elimination'
); ? match.doubleElimination?.placements.firstTeamIndex
: this.resolveMatchWinnerTeamIndex(match.result.seriesResults ?? []);
} }
match.resultPollState = { match.resultPollState = {
startedAt: match.resultPollState?.startedAt ?? new Date(), startedAt: match.resultPollState?.startedAt ?? new Date(),
@@ -708,6 +784,97 @@ export class TournamentResultService {
} }
} }
private advanceDoubleEliminationIfNeeded(
match: MatchDocument,
gameResult: MatchGameResult,
completedBy: 'riot-result' | 'walkover',
): void {
if ((match.gameMode ?? 'pair') !== 'double-elimination') return;
if (!match.doubleElimination || !gameResult.bracketMatchId) return;
match.doubleElimination = completeDoubleEliminationBracketMatch(
match.doubleElimination,
{
bracketMatchId: gameResult.bracketMatchId,
winnerTeamIndex: gameResult.winnerTeamIndex,
completedBy,
completedAt: new Date(gameResult.gameCreation),
},
);
if (match.result && this.isDoubleEliminationComplete(match)) {
match.result.winnerTeamIndex =
match.doubleElimination!.placements.firstTeamIndex;
}
match.markModified?.('doubleElimination');
}
private isDoubleEliminationComplete(match: MatchDocument): boolean {
const placements = match.doubleElimination?.placements;
return Boolean(
placements?.firstTeamIndex &&
placements.secondTeamIndex &&
placements.thirdTeamIndex,
);
}
private async reserveReadyDoubleEliminationCodes(
match: MatchDocument,
): Promise<void> {
if ((match.gameMode ?? 'pair') !== 'double-elimination') return;
const readyBracketMatches = (match.doubleElimination?.bracketMatches ?? [])
.filter((bracketMatch) => bracketMatch.state === 'ready');
if (readyBracketMatches.length === 0) return;
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const existingCodes =
match.tournamentCodeIds.length > 0
? await TournamentCodeModel.find({
_id: { $in: match.tournamentCodeIds },
}).exec()
: [];
const existingByBracketMatchId = new Map(
existingCodes
.filter(
(code) =>
code.bracketMatchId &&
(code.state === 'reserved' || code.state === 'used'),
)
.map((code) => [code.bracketMatchId as string, code]),
);
const reservedIds: mongoose.Types.ObjectId[] = [];
const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
for (const bracketMatch of readyBracketMatches) {
if (existingByBracketMatchId.has(bracketMatch.bracketMatchId)) continue;
const code = await TournamentCodeModel.findOneAndUpdate(
{
state: 'available',
region: 'kr',
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
expiresAt: { $gt: expiresAfter },
},
{
$set: {
state: 'reserved',
matchId: match._id,
gameNumber: bracketMatch.gameNumber,
bracketMatchId: bracketMatch.bracketMatchId,
reservedAt: new Date(),
},
$unset: { releasedAt: 1 },
},
{ sort: { expiresAt: 1 }, returnDocument: 'after' },
).exec();
if (!code) break;
reservedIds.push(code._id);
}
if (reservedIds.length === 0) return;
match.tournamentCodeIds.push(...reservedIds);
await match.save();
}
private async markTournamentCodeUsedForManualResult( private async markTournamentCodeUsedForManualResult(
match: MatchDocument, match: MatchDocument,
gameResult: MatchGameResult, gameResult: MatchGameResult,
@@ -718,7 +885,9 @@ export class TournamentResultService {
await TournamentCodeModel.updateOne( await TournamentCodeModel.updateOne(
{ {
matchId: match._id, matchId: match._id,
gameNumber: gameResult.gameNumber, ...(gameResult.bracketMatchId
? { bracketMatchId: gameResult.bracketMatchId }
: { gameNumber: gameResult.gameNumber }),
state: { $in: ['reserved', 'released'] }, state: { $in: ['reserved', 'released'] },
}, },
{ {
@@ -728,6 +897,9 @@ export class TournamentResultService {
detail.info.gameEndTimestamp ?? detail.info.gameCreation, detail.info.gameEndTimestamp ?? detail.info.gameCreation,
), ),
riotMatchId: detail.metadata.matchId, riotMatchId: detail.metadata.matchId,
...(gameResult.bracketMatchId
? { bracketMatchId: gameResult.bracketMatchId }
: {}),
}, },
}, },
).exec(); ).exec();
@@ -736,22 +908,14 @@ export class TournamentResultService {
private buildSeriesResults( private buildSeriesResults(
games: MatchGameResult[], games: MatchGameResult[],
): NonNullable<MatchDocument['result']>['seriesResults'] { ): NonNullable<MatchDocument['result']>['seriesResults'] {
const bySeries = new Map< const bySeries = new Map<string, MatchSeriesResult>();
string,
{
teamAIndex: number;
teamBIndex: number;
teamAWins: number;
teamBWins: number;
winnerTeamIndex?: number;
}
>();
for (const game of games) { for (const game of games) {
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
const key = `${teamAIndex}:${teamBIndex}`; const key = game.bracketMatchId ?? `${teamAIndex}:${teamBIndex}`;
const current = bySeries.get(key) ?? { const current = bySeries.get(key) ?? {
bracketMatchId: game.bracketMatchId,
teamAIndex, teamAIndex,
teamBIndex, teamBIndex,
teamAWins: 0, teamAWins: 0,
@@ -770,6 +934,9 @@ export class TournamentResultService {
return [...bySeries.values()].sort( return [...bySeries.values()].sort(
(left, right) => (left, right) =>
(left.bracketMatchId ?? '').localeCompare(
right.bracketMatchId ?? '',
) ||
left.teamAIndex - right.teamAIndex || left.teamAIndex - right.teamAIndex ||
left.teamBIndex - right.teamBIndex, left.teamBIndex - right.teamBIndex,
); );
@@ -781,6 +948,21 @@ export class TournamentResultService {
): { teamAIndex: number; teamBIndex: number } { ): { teamAIndex: number; teamBIndex: number } {
const gameMode = match.gameMode ?? 'pair'; const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'double-elimination') {
const bracketMatch = match.doubleElimination?.bracketMatches.find(
(entry) => entry.gameNumber === gameNumber,
);
return bracketMatch
? {
teamAIndex: bracketMatch.teamAIndex ?? 1,
teamBIndex: bracketMatch.teamBIndex ?? 2,
}
: {
teamAIndex: 1,
teamBIndex: 2,
};
}
if (gameMode === 'round-robin') { if (gameMode === 'round-robin') {
const persisted = match.gameSchedule?.find( const persisted = match.gameSchedule?.find(
(entry) => entry.gameNumber === gameNumber, (entry) => entry.gameNumber === gameNumber,
@@ -816,6 +998,9 @@ export class TournamentResultService {
private resolveRequiredGameSlots(match: MatchDocument): number { private resolveRequiredGameSlots(match: MatchDocument): number {
const gameMode = match.gameMode ?? 'pair'; const gameMode = match.gameMode ?? 'pair';
if (gameMode === 'double-elimination') {
return match.doubleElimination?.bracketMatches.length ?? 0;
}
if (gameMode === 'round-robin') { if (gameMode === 'round-robin') {
if ((match.gameSchedule?.length ?? 0) > 0) { if ((match.gameSchedule?.length ?? 0) > 0) {
return match.gameSchedule.length; return match.gameSchedule.length;
+95
View File
@@ -310,6 +310,101 @@ export function useUpdateMatch(communityId = DEFAULT_COMMUNITY_ID) {
}); });
} }
export function useReshuffleDoubleEliminationSeeds(
communityId = DEFAULT_COMMUNITY_ID,
) {
return useMutation({
mutationFn: (matchId: string) =>
apiFetch<ApiMatch>(
`/communities/${communityId}/matches/${matchId}/double-elimination/seeds/reshuffle`,
{ method: 'POST' },
),
});
}
export function useSwapDoubleEliminationSeeds(
communityId = DEFAULT_COMMUNITY_ID,
) {
return useMutation({
mutationFn: (params: {
matchId: string;
leftSeedNumber: number;
rightSeedNumber: number;
}) =>
apiFetch<ApiMatch>(
`/communities/${communityId}/matches/${params.matchId}/double-elimination/seeds/swap`,
{
method: 'POST',
body: JSON.stringify({
leftSeedNumber: params.leftSeedNumber,
rightSeedNumber: params.rightSeedNumber,
}),
},
),
});
}
export function useApplyDoubleEliminationWalkover(
communityId = DEFAULT_COMMUNITY_ID,
) {
return useMutation({
mutationFn: (params: {
matchId: string;
bracketMatchId: string;
winnerTeamIndex: number;
reason?: string;
}) =>
apiFetch<ApiMatch>(
`/communities/${communityId}/matches/${params.matchId}/double-elimination/bracket-matches/${params.bracketMatchId}/walkover`,
{
method: 'POST',
body: JSON.stringify({
winnerTeamIndex: params.winnerTeamIndex,
reason: params.reason,
}),
},
),
});
}
export function useCancelDoubleEliminationWalkover(
communityId = DEFAULT_COMMUNITY_ID,
) {
return useMutation({
mutationFn: (params: {
matchId: string;
bracketMatchId: string;
reason?: string;
}) =>
apiFetch<ApiMatch>(
`/communities/${communityId}/matches/${params.matchId}/double-elimination/bracket-matches/${params.bracketMatchId}/walkover/cancel`,
{
method: 'POST',
body: JSON.stringify({ reason: params.reason }),
},
),
});
}
export function useCancelDoubleEliminationRiotResult(
communityId = DEFAULT_COMMUNITY_ID,
) {
return useMutation({
mutationFn: (params: {
matchId: string;
bracketMatchId: string;
reason?: string;
}) =>
apiFetch<ApiMatch>(
`/communities/${communityId}/matches/${params.matchId}/double-elimination/bracket-matches/${params.bracketMatchId}/result/cancel`,
{
method: 'POST',
body: JSON.stringify({ reason: params.reason }),
},
),
});
}
function createUserHistoryPath( function createUserHistoryPath(
communityId: string, communityId: string,
userId: string, userId: string,
+4
View File
@@ -9,6 +9,7 @@ import type {
ApiRiotRecentStatsSummary, ApiRiotRecentStatsSummary,
ApiTierHistoryEntry, ApiTierHistoryEntry,
ApiTierInfo, ApiTierInfo,
ApiDoubleEliminationBracket,
MatchStatus, MatchStatus,
Position, Position,
RiotLane, RiotLane,
@@ -53,6 +54,7 @@ export interface MatchDetailView {
maxParticipants: number; maxParticipants: number;
gameCount: number; gameCount: number;
gameMode: ApiMatch["gameMode"]; gameMode: ApiMatch["gameMode"];
doubleElimination?: ApiDoubleEliminationBracket;
tournamentCodes: TournamentCodeSlotView[]; tournamentCodes: TournamentCodeSlotView[];
joined: boolean; joined: boolean;
participants: ParticipantView[]; participants: ParticipantView[];
@@ -63,6 +65,7 @@ export interface MatchDetailView {
riotMatchIds: string[]; riotMatchIds: string[];
games: Array<{ games: Array<{
gameNumber: number; gameNumber: number;
bracketMatchId?: string;
riotMatchId: string; riotMatchId: string;
blueTeamIndex: number; blueTeamIndex: number;
redTeamIndex: number; redTeamIndex: number;
@@ -462,6 +465,7 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
maxParticipants: match.maxParticipants, maxParticipants: match.maxParticipants,
gameCount: match.gameCount ?? 3, gameCount: match.gameCount ?? 3,
gameMode: match.gameMode ?? "pair", gameMode: match.gameMode ?? "pair",
doubleElimination: match.doubleElimination,
tournamentCodes: match.tournamentCodes ?? [], tournamentCodes: match.tournamentCodes ?? [],
joined: Boolean(match.joined), joined: Boolean(match.joined),
participants, participants,
+66 -4
View File
@@ -1,7 +1,11 @@
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY'; export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
export type TeamSide = 'blue' | 'red'; export type TeamSide = 'blue' | 'red';
export type MatchGameMode = 'pair' | 'bracket' | 'round-robin'; export type MatchGameMode =
| 'pair'
| 'bracket'
| 'round-robin'
| 'double-elimination';
export type MatchStatus = export type MatchStatus =
| 'recruiting' | 'recruiting'
| 'team-built' | 'team-built'
@@ -136,15 +140,19 @@ export type TournamentCodeState =
| 'reserved' | 'reserved'
| 'used' | 'used'
| 'expired' | 'expired'
| 'released'; | 'released'
| 'voided';
export type TournamentCodeSlotState = TournamentCodeState | 'pending'; export type TournamentCodeSlotState = TournamentCodeState | 'pending';
export interface TournamentCodeSlotView { export interface TournamentCodeSlotView {
gameNumber: number; gameNumber: number;
bracketMatchId?: string;
bracketSide?: string;
roundNumber?: number; roundNumber?: number;
teamAIndex: number; matchNumber?: number;
teamBIndex: number; teamAIndex?: number;
teamBIndex?: number;
code: string | null; code: string | null;
expiresAt: string | null; expiresAt: string | null;
state: TournamentCodeSlotState; state: TournamentCodeSlotState;
@@ -189,6 +197,7 @@ export interface ApiMatchGameResultParticipant {
export interface ApiMatchGameResult { export interface ApiMatchGameResult {
gameNumber: number; gameNumber: number;
bracketMatchId?: string;
riotMatchId: string; riotMatchId: string;
blueTeamIndex: number; blueTeamIndex: number;
redTeamIndex: number; redTeamIndex: number;
@@ -205,6 +214,7 @@ export interface ApiMatchResult {
riotMatchIds: string[]; riotMatchIds: string[];
games: ApiMatchGameResult[]; games: ApiMatchGameResult[];
seriesResults?: Array<{ seriesResults?: Array<{
bracketMatchId?: string;
teamAIndex: number; teamAIndex: number;
teamBIndex: number; teamBIndex: number;
teamAWins: number; teamAWins: number;
@@ -225,6 +235,56 @@ export interface ApiMatchGameAssignment {
teamBIndex: number; teamBIndex: number;
} }
export interface ApiDoubleEliminationSeed {
seedNumber: number;
teamIndex: number;
}
export interface ApiDoubleEliminationBracketDestination {
bracketMatchId: string;
position: 'A' | 'B';
}
export interface ApiDoubleEliminationWalkover {
winnerTeamIndex: number;
reason?: string;
awardedAt: string;
cancelledAt?: string;
cancelReason?: string;
active: boolean;
}
export interface ApiDoubleEliminationBracketMatch {
bracketMatchId: string;
gameNumber: number;
bracketSide: 'winner' | 'loser' | 'grand-final' | 'reset-final';
roundNumber: number;
matchNumber: number;
state: 'pending' | 'ready' | 'completed';
teamAIndex?: number;
teamBIndex?: number;
winnerAdvancesTo?: ApiDoubleEliminationBracketDestination;
loserAdvancesTo?: ApiDoubleEliminationBracketDestination;
winnerTeamIndex?: number;
loserTeamIndex?: number;
completedBy?: 'riot-result' | 'walkover';
completedAt?: string;
walkover?: ApiDoubleEliminationWalkover;
}
export interface ApiDoubleEliminationBracket {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
resetFinalCreated: boolean;
seeds: ApiDoubleEliminationSeed[];
bracketMatches: ApiDoubleEliminationBracketMatch[];
placements: {
firstTeamIndex?: number;
secondTeamIndex?: number;
thirdTeamIndex?: number;
};
}
export interface ManualTournamentResultCollectResponse { export interface ManualTournamentResultCollectResponse {
scanned: number; scanned: number;
matched: number; matched: number;
@@ -247,6 +307,7 @@ export interface ApiMatch {
gameMode: MatchGameMode; gameMode: MatchGameMode;
roundRobinMaxRounds?: number; roundRobinMaxRounds?: number;
gameSchedule?: ApiMatchGameAssignment[]; gameSchedule?: ApiMatchGameAssignment[];
doubleElimination?: ApiDoubleEliminationBracket;
tournamentCodes?: TournamentCodeSlotView[]; tournamentCodes?: TournamentCodeSlotView[];
hostUserId?: string; hostUserId?: string;
participants: ApiMatchParticipant[]; participants: ApiMatchParticipant[];
@@ -407,6 +468,7 @@ export interface MatchMutationRequest {
gameCount?: number; gameCount?: number;
gameMode?: MatchGameMode; gameMode?: MatchGameMode;
roundRobinMaxRounds?: number; roundRobinMaxRounds?: number;
doubleEliminationResetFinalEnabled?: boolean;
prizes?: string[]; prizes?: string[];
notices?: string[]; notices?: string[];
schedule?: ApiMatchScheduleItem[]; schedule?: ApiMatchScheduleItem[];
+872 -5
View File
@@ -1,9 +1,19 @@
import { useEffect, useState } from "react"; import { useEffect, useState, type CSSProperties } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, ChevronRight, Search, X } from "lucide-react"; import {
AlertTriangle,
ArrowLeftRight,
ChevronRight,
Search,
Shuffle,
X,
} from "lucide-react";
import { Link, useLocation, useNavigate, useParams } from "react-router"; import { Link, useLocation, useNavigate, useParams } from "react-router";
import { import {
useAuction, useAuction,
useApplyDoubleEliminationWalkover,
useCancelDoubleEliminationRiotResult,
useCancelDoubleEliminationWalkover,
useCollectTournamentResultByRiotMatch, useCollectTournamentResultByRiotMatch,
useCollectTournamentResultByWindow, useCollectTournamentResultByWindow,
useCommunityUserSearch, useCommunityUserSearch,
@@ -12,6 +22,8 @@ import {
useMe, useMe,
usePollTournamentResult, usePollTournamentResult,
useReplaceTournamentCode, useReplaceTournamentCode,
useReshuffleDoubleEliminationSeeds,
useSwapDoubleEliminationSeeds,
useTournamentCodeStats, useTournamentCodeStats,
useUserHistoryProfile, useUserHistoryProfile,
} from "../api/hooks"; } from "../api/hooks";
@@ -36,6 +48,7 @@ import type {
AuctionTopTierThreshold, AuctionTopTierThreshold,
ApiCommunityUserSearchCandidate, ApiCommunityUserSearchCandidate,
ApiCommunityUserSearchRiotAccount, ApiCommunityUserSearchRiotAccount,
ApiDoubleEliminationBracketMatch,
ApiMatch, ApiMatch,
ApiMatchParticipant, ApiMatchParticipant,
ApiPositionPreference, ApiPositionPreference,
@@ -1520,7 +1533,10 @@ function TournamentCodeList({
function renderSlot(slot: TournamentCodeSlotView) { function renderSlot(slot: TournamentCodeSlotView) {
const shouldShowTeamLabel = const shouldShowTeamLabel =
gameMode === "round-robin" || slot.teamAIndex > 1 || slot.teamBIndex > 2; gameMode === "round-robin" ||
gameMode === "double-elimination" ||
(slot.teamAIndex ?? 0) > 1 ||
(slot.teamBIndex ?? 0) > 2;
return ( return (
<div <div
@@ -1533,8 +1549,9 @@ function TournamentCodeList({
</span> </span>
{shouldShowTeamLabel && ( {shouldShowTeamLabel && (
<span className="min-w-0 truncate text-xs text-base-content/30"> <span className="min-w-0 truncate text-xs text-base-content/30">
{teamIndexLabel(slot.teamAIndex)} vs{" "} {slot.bracketMatchId ? `${slot.bracketMatchId} · ` : ""}
{teamIndexLabel(slot.teamBIndex)} {slot.teamAIndex ? teamIndexLabel(slot.teamAIndex) : "미정"} vs{" "}
{slot.teamBIndex ? teamIndexLabel(slot.teamBIndex) : "미정"}
</span> </span>
)} )}
</div> </div>
@@ -2249,6 +2266,768 @@ function MatchGameListSection({ match }: { match: MatchDetailView }) {
); );
} }
const DOUBLE_ELIMINATION_MATCH_CARD_WIDTH = 208;
const DOUBLE_ELIMINATION_MATCH_CARD_HEIGHT = 112;
const DOUBLE_ELIMINATION_TEAM_A_CENTER_Y = 52;
const DOUBLE_ELIMINATION_TEAM_B_CENTER_Y = 80;
const DOUBLE_ELIMINATION_MATCH_CENTER_Y = 66;
type DoubleEliminationSeriesResult = NonNullable<
NonNullable<ApiMatch["result"]>["seriesResults"]
>[number];
type DoubleEliminationBracketNodeLayout = {
bracketMatchId: string;
x: number;
y: number;
};
type DoubleEliminationRoundLabelLayout = {
label: string;
x: number;
y: number;
};
type DoubleEliminationBracketLayout = {
width: number;
height: number;
nodes: DoubleEliminationBracketNodeLayout[];
labels: DoubleEliminationRoundLabelLayout[];
};
type DoubleEliminationConnectorTone = "winner" | "loser" | "reset";
type DoubleEliminationConnector = {
fromBracketMatchId: string;
toBracketMatchId: string;
toPosition: "A" | "B";
tone: DoubleEliminationConnectorTone;
};
const DOUBLE_ELIMINATION_BRACKET_SIDE_LABEL: Record<
ApiDoubleEliminationBracketMatch["bracketSide"],
string
> = {
winner: "승자조",
loser: "패자조",
"grand-final": "그랜드 파이널",
"reset-final": "리셋 파이널",
};
function buildDoubleEliminationBracketLayout(
teamCount: 4 | 8,
hasResetFinal: boolean,
): DoubleEliminationBracketLayout {
if (teamCount === 4) {
const nodes: DoubleEliminationBracketNodeLayout[] = [
{ bracketMatchId: "WB_R1_M1", x: 0, y: 92 },
{ bracketMatchId: "WB_R1_M2", x: 0, y: 252 },
{ bracketMatchId: "WB_FINAL", x: 260, y: 172 },
{ bracketMatchId: "LB_R1_M1", x: 260, y: 430 },
{ bracketMatchId: "LB_FINAL", x: 520, y: 430 },
{ bracketMatchId: "GF", x: 780, y: 172 },
...(hasResetFinal
? [{ bracketMatchId: "GF_RESET", x: 1040, y: 172 }]
: []),
];
return {
width:
(hasResetFinal ? 1040 : 780) +
DOUBLE_ELIMINATION_MATCH_CARD_WIDTH +
28,
height: 578,
nodes,
labels: [
{ label: "승자조 1라운드", x: 0, y: 44 },
{ label: "승자조 결승", x: 260, y: 44 },
{ label: "패자조 1라운드", x: 260, y: 382 },
{ label: "패자조 결승", x: 520, y: 382 },
{ label: "그랜드 파이널", x: 780, y: 44 },
...(hasResetFinal
? [{ label: "리셋 파이널", x: 1040, y: 44 }]
: []),
],
};
}
const nodes: DoubleEliminationBracketNodeLayout[] = [
{ bracketMatchId: "WB_R1_M1", x: 0, y: 58 },
{ bracketMatchId: "WB_R1_M2", x: 0, y: 162 },
{ bracketMatchId: "WB_R1_M3", x: 0, y: 266 },
{ bracketMatchId: "WB_R1_M4", x: 0, y: 370 },
{ bracketMatchId: "WB_R2_M1", x: 235, y: 110 },
{ bracketMatchId: "WB_R2_M2", x: 235, y: 318 },
{ bracketMatchId: "WB_FINAL", x: 705, y: 214 },
{ bracketMatchId: "LB_R1_M1", x: 235, y: 550 },
{ bracketMatchId: "LB_R1_M2", x: 235, y: 654 },
{ bracketMatchId: "LB_R2_M1", x: 470, y: 550 },
{ bracketMatchId: "LB_R2_M2", x: 470, y: 654 },
{ bracketMatchId: "LB_R3_M1", x: 705, y: 602 },
{ bracketMatchId: "LB_FINAL", x: 940, y: 602 },
{ bracketMatchId: "GF", x: 1175, y: 214 },
...(hasResetFinal
? [{ bracketMatchId: "GF_RESET", x: 1410, y: 214 }]
: []),
];
return {
width:
(hasResetFinal ? 1410 : 1175) +
DOUBLE_ELIMINATION_MATCH_CARD_WIDTH +
28,
height: 790,
nodes,
labels: [
{ label: "승자조 1라운드", x: 0, y: 20 },
{ label: "승자조 2라운드", x: 235, y: 20 },
{ label: "승자조 결승", x: 705, y: 20 },
{ label: "그랜드 파이널", x: 1175, y: 20 },
...(hasResetFinal
? [{ label: "리셋 파이널", x: 1410, y: 20 }]
: []),
{ label: "패자조 1라운드", x: 235, y: 512 },
{ label: "패자조 2라운드", x: 470, y: 512 },
{ label: "패자조 3라운드", x: 705, y: 512 },
{ label: "패자조 결승", x: 940, y: 512 },
],
};
}
function buildDoubleEliminationConnectors(
bracketMatches: ApiDoubleEliminationBracketMatch[],
): DoubleEliminationConnector[] {
const connectors = bracketMatches.flatMap((bracketMatch) => {
const next: DoubleEliminationConnector[] = [];
if (bracketMatch.winnerAdvancesTo) {
next.push({
fromBracketMatchId: bracketMatch.bracketMatchId,
toBracketMatchId: bracketMatch.winnerAdvancesTo.bracketMatchId,
toPosition: bracketMatch.winnerAdvancesTo.position,
tone: "winner",
});
}
if (bracketMatch.loserAdvancesTo) {
next.push({
fromBracketMatchId: bracketMatch.bracketMatchId,
toBracketMatchId: bracketMatch.loserAdvancesTo.bracketMatchId,
toPosition: bracketMatch.loserAdvancesTo.position,
tone: "loser",
});
}
return next;
});
if (
bracketMatches.some(
(bracketMatch) => bracketMatch.bracketMatchId === "GF_RESET",
)
) {
connectors.push(
{
fromBracketMatchId: "GF",
toBracketMatchId: "GF_RESET",
toPosition: "A",
tone: "reset",
},
{
fromBracketMatchId: "GF",
toBracketMatchId: "GF_RESET",
toPosition: "B",
tone: "reset",
},
);
}
return connectors;
}
function formatDoubleEliminationMatchState(
state: ApiDoubleEliminationBracketMatch["state"],
) {
if (state === "ready") return "진행 가능";
if (state === "completed") return "완료";
return "대기";
}
function formatDoubleEliminationCodeState(state?: string) {
if (!state) return null;
const labels: Record<string, string> = {
reserved: "코드 발급",
used: "코드 사용",
released: "코드 해제",
expired: "코드 만료",
voided: "코드 폐기",
};
return labels[state] ?? state;
}
function formatDoubleEliminationCompletionType(
completedBy?: ApiDoubleEliminationBracketMatch["completedBy"],
) {
if (completedBy === "walkover") return "부전승";
if (completedBy === "riot-result") return "결과 반영";
return null;
}
function DoubleEliminationBracketSection({
match,
canManage,
busy,
onReshuffleSeeds,
onSwapSeeds,
onWalkover,
onCancelWalkover,
onCancelResult,
}: {
match: MatchDetailView;
canManage: boolean;
busy: boolean;
onReshuffleSeeds: () => void;
onSwapSeeds: () => void;
onWalkover: (bracketMatchId: string, winnerTeamIndex: number) => void;
onCancelWalkover: (bracketMatchId: string) => void;
onCancelResult: (bracketMatchId: string) => void;
}) {
const bracket = match.doubleElimination;
if (!bracket) return null;
const hasResetFinal = bracket.bracketMatches.some(
(bracketMatch) => bracketMatch.bracketMatchId === "GF_RESET",
);
const layout = buildDoubleEliminationBracketLayout(
bracket.teamCount,
hasResetFinal,
);
const layoutNodeById = new Map(
layout.nodes.map((node) => [node.bracketMatchId, node]),
);
const connectors = buildDoubleEliminationConnectors(
bracket.bracketMatches,
).filter(
(connector) =>
layoutNodeById.has(connector.fromBracketMatchId) &&
layoutNodeById.has(connector.toBracketMatchId),
);
const codeByBracketMatchId = new Map(
match.tournamentCodes
.filter((slot) => slot.bracketMatchId)
.map((slot) => [slot.bracketMatchId as string, slot]),
);
const seriesByBracketMatchId = new Map(
(match.result?.seriesResults ?? [])
.filter((series) => series.bracketMatchId)
.map((series) => [series.bracketMatchId as string, series]),
);
const seedNumberByTeamIndex = new Map(
bracket.seeds.map((seed) => [seed.teamIndex, seed.seedNumber]),
);
const canChangeSeeds =
canManage &&
!bracket.bracketMatches.some(
(bracketMatch) => bracketMatch.state === "completed",
);
const placedBracketMatchIds = new Set(
layout.nodes.map((node) => node.bracketMatchId),
);
const unplacedBracketMatches = bracket.bracketMatches.filter(
(bracketMatch) => !placedBracketMatchIds.has(bracketMatch.bracketMatchId),
);
const placementItems = [
{ label: "우승", teamIndex: bracket.placements.firstTeamIndex },
{ label: "준우승", teamIndex: bracket.placements.secondTeamIndex },
{ label: "3위", teamIndex: bracket.placements.thirdTeamIndex },
].filter((item) => item.teamIndex);
return (
<section className="mb-6 border border-base-content/10 bg-base-100">
<div className="flex flex-col gap-3 border-b border-base-content/10 bg-base-200/35 px-4 py-3 lg:flex-row lg:items-center lg:justify-between">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<h2 className="text-sm font-black text-base-content">
더블 엘리미네이션
</h2>
<span className="border border-info/20 bg-info/8 px-1.5 py-0.5 text-[11px] font-bold text-info">
{bracket.teamCount}팀
</span>
<span className="border border-base-content/10 px-1.5 py-0.5 text-[11px] font-bold text-base-content/45">
GF 리셋 {bracket.resetFinalEnabled ? "허용" : "미사용"}
</span>
</div>
<div className="mt-2 flex flex-wrap gap-1.5 text-xs text-base-content/40">
{bracket.seeds.map((seed) => (
<span
key={seed.seedNumber}
className="inline-flex max-w-[12rem] items-center gap-1 border border-base-content/10 bg-base-100 px-1.5 py-0.5"
>
<span className="font-mono text-[11px] font-black text-primary">
S{seed.seedNumber}
</span>
<span className="truncate">
{resolveMatchTeamName(match, seed.teamIndex)}
</span>
</span>
))}
{placementItems.map((item) => (
<span
key={item.label}
className="inline-flex max-w-[12rem] items-center gap-1 border border-accent/20 bg-accent/10 px-1.5 py-0.5 text-accent-content"
>
<span className="font-bold">{item.label}</span>
<span className="truncate">
{resolveMatchTeamName(match, item.teamIndex as number)}
</span>
</span>
))}
</div>
</div>
{canManage && (
<div className="flex shrink-0 flex-wrap gap-2">
<button
type="button"
className="inline-flex h-8 items-center gap-1.5 border border-base-content/10 bg-base-100 px-2.5 text-xs font-bold text-base-content/50 hover:border-primary/25 hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-40"
disabled={!canChangeSeeds || busy}
onClick={onReshuffleSeeds}
>
<Shuffle className="h-3.5 w-3.5" aria-hidden="true" />
시드 재추첨
</button>
<button
type="button"
className="inline-flex h-8 items-center gap-1.5 border border-base-content/10 bg-base-100 px-2.5 text-xs font-bold text-base-content/50 hover:border-primary/25 hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-40"
disabled={!canChangeSeeds || busy}
onClick={onSwapSeeds}
>
<ArrowLeftRight className="h-3.5 w-3.5" aria-hidden="true" />
시드 교체
</button>
</div>
)}
</div>
<div className="border-t border-base-content/8 bg-base-content/[0.015] p-3 sm:p-4">
<div
className="overflow-x-auto border border-base-content/10 bg-base-100"
role="region"
aria-label="더블 엘리미네이션 대진표"
>
<div
className="relative shrink-0"
style={{ width: layout.width, height: layout.height }}
>
<div className="pointer-events-none absolute inset-0 bg-base-200/25" />
{layout.labels.map((label) => (
<div
key={`${label.label}-${label.x}-${label.y}`}
className="absolute z-10"
style={{
left: label.x,
top: label.y,
width: DOUBLE_ELIMINATION_MATCH_CARD_WIDTH,
}}
>
<div className="flex items-center gap-2">
<span className="text-[11px] font-black uppercase tracking-wider text-base-content/40">
{label.label}
</span>
<span className="h-px min-w-8 flex-1 bg-base-content/10" />
</div>
</div>
))}
{connectors.map((connector, index) => (
<DoubleEliminationBracketConnector
key={`${connector.fromBracketMatchId}-${connector.toBracketMatchId}-${connector.toPosition}-${index}`}
connector={connector}
layoutNodeById={layoutNodeById}
/>
))}
{bracket.bracketMatches
.filter((bracketMatch) =>
layoutNodeById.has(bracketMatch.bracketMatchId),
)
.map((bracketMatch) => {
const node = layoutNodeById.get(bracketMatch.bracketMatchId);
if (!node) return null;
return (
<DoubleEliminationBracketCard
key={bracketMatch.bracketMatchId}
match={match}
bracketMatch={bracketMatch}
seedNumberByTeamIndex={seedNumberByTeamIndex}
seriesResult={seriesByBracketMatchId.get(
bracketMatch.bracketMatchId,
)}
codeState={
codeByBracketMatchId.get(bracketMatch.bracketMatchId)
?.state
}
canManage={canManage}
busy={busy}
onWalkover={onWalkover}
onCancelWalkover={onCancelWalkover}
onCancelResult={onCancelResult}
style={{
left: node.x,
top: node.y,
width: DOUBLE_ELIMINATION_MATCH_CARD_WIDTH,
height: DOUBLE_ELIMINATION_MATCH_CARD_HEIGHT,
}}
/>
);
})}
</div>
</div>
{unplacedBracketMatches.length > 0 && (
<div className="mt-3 border border-base-content/10 bg-base-200/45 px-3 py-2 text-xs text-base-content/55">
표시되지 않은 대진:{" "}
{unplacedBracketMatches
.map((bracketMatch) => bracketMatch.bracketMatchId)
.join(", ")}
</div>
)}
</div>
</section>
);
}
function DoubleEliminationBracketConnector({
connector,
layoutNodeById,
}: {
connector: DoubleEliminationConnector;
layoutNodeById: Map<string, DoubleEliminationBracketNodeLayout>;
}) {
const from = layoutNodeById.get(connector.fromBracketMatchId);
const to = layoutNodeById.get(connector.toBracketMatchId);
if (!from || !to) return null;
const startX = from.x + DOUBLE_ELIMINATION_MATCH_CARD_WIDTH;
const startY = from.y + DOUBLE_ELIMINATION_MATCH_CENTER_Y;
const endX = to.x;
const endY =
to.y +
(connector.toPosition === "A"
? DOUBLE_ELIMINATION_TEAM_A_CENTER_Y
: DOUBLE_ELIMINATION_TEAM_B_CENTER_Y);
const horizontalDistance = Math.max(10, endX - startX);
const elbowX = startX + horizontalDistance / 2;
const topY = Math.min(startY, endY);
const connectorClass =
connector.tone === "winner"
? "bg-info/35"
: connector.tone === "loser"
? "bg-primary/25"
: "bg-accent/35";
return (
<div className="pointer-events-none absolute inset-0 z-0">
<div
className={`absolute h-[2px] ${connectorClass}`}
style={{
left: startX,
top: startY,
width: Math.max(0, elbowX - startX),
}}
/>
<div
className={`absolute w-[2px] ${connectorClass}`}
style={{
left: elbowX,
top: topY,
height: Math.max(2, Math.abs(endY - startY)),
}}
/>
<div
className={`absolute h-[2px] ${connectorClass}`}
style={{
left: elbowX,
top: endY,
width: Math.max(0, endX - elbowX),
}}
/>
</div>
);
}
function DoubleEliminationBracketCard({
match,
bracketMatch,
seedNumberByTeamIndex,
seriesResult,
codeState,
canManage,
busy,
onWalkover,
onCancelWalkover,
onCancelResult,
style,
}: {
match: MatchDetailView;
bracketMatch: ApiDoubleEliminationBracketMatch;
seedNumberByTeamIndex: Map<number, number>;
seriesResult?: DoubleEliminationSeriesResult;
codeState?: string;
canManage: boolean;
busy: boolean;
onWalkover: (bracketMatchId: string, winnerTeamIndex: number) => void;
onCancelWalkover: (bracketMatchId: string) => void;
onCancelResult: (bracketMatchId: string) => void;
style: CSSProperties;
}) {
const canApplyWalkover =
canManage &&
bracketMatch.state === "ready" &&
Boolean(bracketMatch.teamAIndex && bracketMatch.teamBIndex);
const codeStateLabel = formatDoubleEliminationCodeState(codeState);
const completionTypeLabel = formatDoubleEliminationCompletionType(
bracketMatch.completedBy,
);
return (
<div
className={`absolute z-20 border bg-base-100 p-1.5 shadow-[0_1px_0_rgba(0,0,0,0.03)] ${
bracketMatch.state === "ready"
? "border-info/25"
: bracketMatch.state === "completed"
? "border-accent/25"
: "border-base-content/10"
}`}
style={style}
>
<div className="flex h-full min-w-0 flex-col gap-1">
<div className="flex min-w-0 items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-1.5">
<span className="truncate font-mono text-[10px] font-black text-base-content/55">
{bracketMatch.bracketMatchId}
</span>
<span className="shrink-0 text-[10px] font-bold text-base-content/30">
G{bracketMatch.gameNumber}
</span>
</div>
<span
className={`shrink-0 text-[10px] font-black ${
bracketMatch.state === "ready"
? "text-info"
: bracketMatch.state === "completed"
? "text-accent"
: "text-base-content/35"
}`}
>
{formatDoubleEliminationMatchState(bracketMatch.state)}
</span>
</div>
<DoubleEliminationBracketTeamRow
match={match}
teamIndex={bracketMatch.teamAIndex}
seedNumber={
bracketMatch.teamAIndex
? seedNumberByTeamIndex.get(bracketMatch.teamAIndex)
: undefined
}
isWinner={bracketMatch.winnerTeamIndex === bracketMatch.teamAIndex}
isLoser={
bracketMatch.state === "completed" &&
bracketMatch.teamAIndex !== bracketMatch.winnerTeamIndex
}
score={resolveDoubleEliminationTeamScore(
seriesResult,
bracketMatch.teamAIndex,
)}
/>
<DoubleEliminationBracketTeamRow
match={match}
teamIndex={bracketMatch.teamBIndex}
seedNumber={
bracketMatch.teamBIndex
? seedNumberByTeamIndex.get(bracketMatch.teamBIndex)
: undefined
}
isWinner={bracketMatch.winnerTeamIndex === bracketMatch.teamBIndex}
isLoser={
bracketMatch.state === "completed" &&
bracketMatch.teamBIndex !== bracketMatch.winnerTeamIndex
}
score={resolveDoubleEliminationTeamScore(
seriesResult,
bracketMatch.teamBIndex,
)}
/>
<div className="mt-auto flex min-w-0 items-center justify-between gap-1">
<div className="flex min-w-0 items-center gap-1">
<span className="truncate text-[10px] font-bold text-base-content/30">
{DOUBLE_ELIMINATION_BRACKET_SIDE_LABEL[
bracketMatch.bracketSide
] ?? bracketMatch.bracketSide}
</span>
{codeStateLabel && (
<span className="shrink-0 border border-base-content/10 px-1 text-[10px] font-bold text-base-content/45">
{codeStateLabel}
</span>
)}
{completionTypeLabel && (
<span className="shrink-0 border border-accent/25 bg-accent/10 px-1 text-[10px] font-black text-accent">
{completionTypeLabel}
</span>
)}
</div>
{canManage && (
<DoubleEliminationBracketCardActions
bracketMatch={bracketMatch}
canApplyWalkover={canApplyWalkover}
busy={busy}
onWalkover={onWalkover}
onCancelWalkover={onCancelWalkover}
onCancelResult={onCancelResult}
/>
)}
</div>
</div>
</div>
);
}
function resolveDoubleEliminationTeamScore(
seriesResult: DoubleEliminationSeriesResult | undefined,
teamIndex: number | undefined,
) {
if (!seriesResult || !teamIndex) return undefined;
if (teamIndex === seriesResult.teamAIndex) return seriesResult.teamAWins;
if (teamIndex === seriesResult.teamBIndex) return seriesResult.teamBWins;
return undefined;
}
function DoubleEliminationBracketTeamRow({
match,
teamIndex,
seedNumber,
isWinner,
isLoser,
score,
}: {
match: MatchDetailView;
teamIndex?: number;
seedNumber?: number;
isWinner: boolean;
isLoser: boolean;
score?: number;
}) {
const teamName = teamIndex ? resolveMatchTeamName(match, teamIndex) : "미정";
const teamTone = teamIndex ? teamIndexColorClasses(teamIndex) : null;
return (
<div
className={`grid h-7 grid-cols-[2.25rem_minmax(0,1fr)_1.25rem] items-center gap-1 border px-1.5 text-xs ${
isWinner
? "border-primary/30 bg-primary/5 text-base-content"
: isLoser
? "border-base-content/8 bg-base-200/50 text-base-content/35"
: teamIndex
? "border-info/20 bg-info/5 text-base-content/75"
: "border-base-content/8 bg-base-200/40 text-base-content/35"
}`}
>
<span className="flex min-w-0 items-center gap-1">
<span
className={`h-1.5 w-1.5 shrink-0 ${
teamTone?.bar ?? "bg-base-content/20"
}`}
/>
<span className="font-mono text-[10px] font-black text-base-content/45">
{seedNumber ? `S${seedNumber}` : teamIndex ? `T${teamIndex}` : "-"}
</span>
</span>
<span className="min-w-0 truncate font-bold leading-none">
{teamName}
</span>
<span
className={`text-right font-mono text-[11px] font-black ${
isWinner ? "text-primary" : "text-base-content/45"
}`}
>
{score ?? ""}
</span>
</div>
);
}
function DoubleEliminationBracketCardActions({
bracketMatch,
canApplyWalkover,
busy,
onWalkover,
onCancelWalkover,
onCancelResult,
}: {
bracketMatch: ApiDoubleEliminationBracketMatch;
canApplyWalkover: boolean;
busy: boolean;
onWalkover: (bracketMatchId: string, winnerTeamIndex: number) => void;
onCancelWalkover: (bracketMatchId: string) => void;
onCancelResult: (bracketMatchId: string) => void;
}) {
return (
<div className="flex shrink-0 items-center gap-1">
{canApplyWalkover && bracketMatch.teamAIndex && (
<button
type="button"
className="border border-base-content/10 px-1 text-[10px] font-bold text-base-content/45 hover:border-primary/30 hover:text-primary focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-40"
disabled={busy}
onClick={() =>
onWalkover(
bracketMatch.bracketMatchId,
bracketMatch.teamAIndex as number,
)
}
>
A 부전승
</button>
)}
{canApplyWalkover && bracketMatch.teamBIndex && (
<button
type="button"
className="border border-base-content/10 px-1 text-[10px] font-bold text-base-content/45 hover:border-primary/30 hover:text-primary focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-40"
disabled={busy}
onClick={() =>
onWalkover(
bracketMatch.bracketMatchId,
bracketMatch.teamBIndex as number,
)
}
>
B 부전승
</button>
)}
{bracketMatch.completedBy === "walkover" &&
bracketMatch.walkover?.active && (
<button
type="button"
className="border border-amber-400/25 px-1 text-[10px] font-bold text-amber-300 hover:bg-amber-400/10 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-amber-300 disabled:cursor-not-allowed disabled:opacity-40"
disabled={busy}
onClick={() => onCancelWalkover(bracketMatch.bracketMatchId)}
>
취소
</button>
)}
{bracketMatch.completedBy === "riot-result" && (
<button
type="button"
className="border border-red-400/25 px-1 text-[10px] font-bold text-red-300 hover:bg-red-400/10 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-red-300 disabled:cursor-not-allowed disabled:opacity-40"
disabled={busy}
onClick={() => onCancelResult(bracketMatch.bracketMatchId)}
>
결과 취소
</button>
)}
</div>
);
}
function TeamNameChip({ function TeamNameChip({
match, match,
teamIndex, teamIndex,
@@ -2419,6 +3198,15 @@ export default function MatchDetailPage() {
useCollectTournamentResultByWindow(DEFAULT_COMMUNITY_ID); useCollectTournamentResultByWindow(DEFAULT_COMMUNITY_ID);
const collectResultByRiotMatchMutation = const collectResultByRiotMatchMutation =
useCollectTournamentResultByRiotMatch(DEFAULT_COMMUNITY_ID); useCollectTournamentResultByRiotMatch(DEFAULT_COMMUNITY_ID);
const reshuffleSeedsMutation =
useReshuffleDoubleEliminationSeeds(DEFAULT_COMMUNITY_ID);
const swapSeedsMutation = useSwapDoubleEliminationSeeds(DEFAULT_COMMUNITY_ID);
const applyWalkoverMutation =
useApplyDoubleEliminationWalkover(DEFAULT_COMMUNITY_ID);
const cancelWalkoverMutation =
useCancelDoubleEliminationWalkover(DEFAULT_COMMUNITY_ID);
const cancelRiotResultMutation =
useCancelDoubleEliminationRiotResult(DEFAULT_COMMUNITY_ID);
const joinMatchMutation = useMutation({ const joinMatchMutation = useMutation({
mutationFn: () => mutationFn: () =>
@@ -2663,6 +3451,56 @@ export default function MatchDetailPage() {
); );
} }
function handleReshuffleDoubleEliminationSeeds() {
if (!id) return;
if (!window.confirm("시드를 다시 추첨할까요?")) return;
reshuffleSeedsMutation.mutate(id, { onSuccess: invalidateCurrentMatch });
}
function handleSwapDoubleEliminationSeeds() {
if (!id) return;
const leftSeedNumber = Number(window.prompt("교체할 첫 번째 시드 번호"));
const rightSeedNumber = Number(window.prompt("교체할 두 번째 시드 번호"));
if (!Number.isInteger(leftSeedNumber) || !Number.isInteger(rightSeedNumber)) {
return;
}
swapSeedsMutation.mutate(
{ matchId: id, leftSeedNumber, rightSeedNumber },
{ onSuccess: invalidateCurrentMatch },
);
}
function handleApplyDoubleEliminationWalkover(
bracketMatchId: string,
winnerTeamIndex: number,
) {
if (!id) return;
const reason = window.prompt("부전승 사유") ?? undefined;
applyWalkoverMutation.mutate(
{ matchId: id, bracketMatchId, winnerTeamIndex, reason },
{ onSuccess: invalidateCurrentMatch },
);
}
function handleCancelDoubleEliminationWalkover(bracketMatchId: string) {
if (!id) return;
const reason = window.prompt("부전승 취소 사유") ?? undefined;
cancelWalkoverMutation.mutate(
{ matchId: id, bracketMatchId, reason },
{ onSuccess: invalidateCurrentMatch },
);
}
function handleCancelDoubleEliminationRiotResult(bracketMatchId: string) {
if (!id) return;
if (!window.confirm("이 대진의 수집 결과를 취소할까요?")) return;
const reason = window.prompt("결과 취소 사유") ?? undefined;
cancelRiotResultMutation.mutate(
{ matchId: id, bracketMatchId, reason },
{ onSuccess: invalidateCurrentMatch },
);
}
useEffect(() => { useEffect(() => {
const participants = buildAuctionParticipantPool( const participants = buildAuctionParticipantPool(
matchQuery.data?.participants ?? [], matchQuery.data?.participants ?? [],
@@ -2802,6 +3640,18 @@ export default function MatchDetailPage() {
hasUniqueCaptainSelections && hasUniqueCaptainSelections &&
hasValidCaptainInitialPoints && hasValidCaptainInitialPoints &&
hasValidAuctionTimerSettings; hasValidAuctionTimerSettings;
const doubleEliminationActionBusy =
reshuffleSeedsMutation.isPending ||
swapSeedsMutation.isPending ||
applyWalkoverMutation.isPending ||
cancelWalkoverMutation.isPending ||
cancelRiotResultMutation.isPending;
const doubleEliminationActionError =
reshuffleSeedsMutation.error ||
swapSeedsMutation.error ||
applyWalkoverMutation.error ||
cancelWalkoverMutation.error ||
cancelRiotResultMutation.error;
return ( return (
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-6"> <main className="max-w-5xl mx-auto px-4 sm:px-6 py-6">
@@ -2897,6 +3747,23 @@ export default function MatchDetailPage() {
</div> </div>
)} )}
{doubleEliminationActionError instanceof Error && (
<div className="mb-4 border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-500">
{doubleEliminationActionError.message}
</div>
)}
<DoubleEliminationBracketSection
match={match}
canManage={canManageAuction}
busy={doubleEliminationActionBusy}
onReshuffleSeeds={handleReshuffleDoubleEliminationSeeds}
onSwapSeeds={handleSwapDoubleEliminationSeeds}
onWalkover={handleApplyDoubleEliminationWalkover}
onCancelWalkover={handleCancelDoubleEliminationWalkover}
onCancelResult={handleCancelDoubleEliminationRiotResult}
/>
{match.status === "finished" ? ( {match.status === "finished" ? (
<FinishedMatchTabs match={match} /> <FinishedMatchTabs match={match} />
) : ( ) : (
+5 -2
View File
@@ -28,6 +28,7 @@ const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
pair: "페어 매치", pair: "페어 매치",
bracket: "토너먼트", bracket: "토너먼트",
"round-robin": "리그전", "round-robin": "리그전",
"double-elimination": "더블 엘리미네이션",
}; };
function resultBadgeClass(won: boolean) { function resultBadgeClass(won: boolean) {
@@ -191,9 +192,11 @@ function UpcomingGameCard({
const opponentIndex = const opponentIndex =
slot.teamAIndex === parsedTeamIndex ? slot.teamBIndex : slot.teamAIndex; slot.teamAIndex === parsedTeamIndex ? slot.teamBIndex : slot.teamAIndex;
const ourTeam = teamByIndex.get(parsedTeamIndex); const ourTeam = teamByIndex.get(parsedTeamIndex);
const opponentTeam = teamByIndex.get(opponentIndex); const opponentTeam = opponentIndex ? teamByIndex.get(opponentIndex) : undefined;
const ourTeamName = teamIndexLabel(parsedTeamIndex, ourTeam?.name); const ourTeamName = teamIndexLabel(parsedTeamIndex, ourTeam?.name);
const opponentTeamName = teamIndexLabel(opponentIndex, opponentTeam?.name); const opponentTeamName = opponentIndex
? teamIndexLabel(opponentIndex, opponentTeam?.name)
: "상대 미정";
const ourCaptainName = captainName(ourTeam, participantByUserId); const ourCaptainName = captainName(ourTeam, participantByUserId);
const opponentCaptainName = captainName(opponentTeam, participantByUserId); const opponentCaptainName = captainName(opponentTeam, participantByUserId);
const opponentMembers = opponentTeam?.members ?? []; const opponentMembers = opponentTeam?.members ?? [];
+58 -3
View File
@@ -24,6 +24,7 @@ const DEFAULT_FORM: MatchMutationRequest = {
maxParticipants: 10, maxParticipants: 10,
gameCount: 3, gameCount: 3,
gameMode: 'pair', gameMode: 'pair',
doubleEliminationResetFinalEnabled: true,
prizes: [], prizes: [],
notices: [], notices: [],
schedule: [], schedule: [],
@@ -33,6 +34,7 @@ const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
pair: '페어', pair: '페어',
bracket: '브래킷', bracket: '브래킷',
'round-robin': '라운드 로빈', 'round-robin': '라운드 로빈',
'double-elimination': '더블 엘리미네이션',
}; };
function resolveRoundRobinFullRoundCount(maxParticipants?: number) { function resolveRoundRobinFullRoundCount(maxParticipants?: number) {
@@ -122,6 +124,8 @@ function makeForm(match?: ApiMatch): MatchMutationRequest & {
gameCount: match.gameCount, gameCount: match.gameCount,
gameMode: match.gameMode ?? 'pair', gameMode: match.gameMode ?? 'pair',
roundRobinMaxRounds: match.roundRobinMaxRounds, roundRobinMaxRounds: match.roundRobinMaxRounds,
doubleEliminationResetFinalEnabled:
match.doubleElimination?.resetFinalEnabled ?? true,
prizes: match.prizes, prizes: match.prizes,
notices: match.notices, notices: match.notices,
schedule: match.schedule, schedule: match.schedule,
@@ -188,6 +192,10 @@ export default function MatchAdminPage() {
maxParticipants: Number(form.maxParticipants ?? 10), maxParticipants: Number(form.maxParticipants ?? 10),
gameCount: Number(form.gameCount ?? 3), gameCount: Number(form.gameCount ?? 3),
gameMode: form.gameMode, gameMode: form.gameMode,
doubleEliminationResetFinalEnabled:
form.gameMode === 'double-elimination'
? Boolean(form.doubleEliminationResetFinalEnabled)
: undefined,
roundRobinMaxRounds: roundRobinMaxRounds:
form.gameMode === 'round-robin' form.gameMode === 'round-robin'
? normalizeRoundRobinMaxRounds( ? normalizeRoundRobinMaxRounds(
@@ -329,7 +337,10 @@ export default function MatchAdminPage() {
}} }}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm" className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
> >
{[10, 20, 30, 40, 50, 60].map((value) => ( {(form.gameMode === 'double-elimination'
? [20, 40]
: [10, 20, 30, 40, 50, 60]
).map((value) => (
<option key={value} value={value}>{value}명</option> <option key={value} value={value}>{value}명</option>
))} ))}
</select> </select>
@@ -339,16 +350,36 @@ export default function MatchAdminPage() {
<input <input
type="number" type="number"
min={1} min={1}
value={form.gameCount} disabled={form.gameMode === 'double-elimination'}
value={form.gameMode === 'double-elimination' ? 1 : form.gameCount}
onChange={(event) => setForm((current) => ({ ...current, gameCount: Number(event.target.value) }))} onChange={(event) => setForm((current) => ({ ...current, gameCount: Number(event.target.value) }))}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm" className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/> />
{form.gameMode === 'double-elimination' && (
<span className="mt-1 block text-xs text-base-content/30">
더블 엘리미네이션은 단판으로 진행됩니다.
</span>
)}
</label> </label>
<label className="text-xs text-base-content/45"> <label className="text-xs text-base-content/45">
게임 모드 게임 모드
<select <select
value={form.gameMode} value={form.gameMode}
onChange={(event) => setForm((current) => ({ ...current, gameMode: event.target.value as MatchGameMode }))} onChange={(event) => {
const gameMode = event.target.value as MatchGameMode;
setForm((current) => ({
...current,
gameMode,
maxParticipants:
gameMode === 'double-elimination' &&
current.maxParticipants !== 20 &&
current.maxParticipants !== 40
? 20
: current.maxParticipants,
gameCount:
gameMode === 'double-elimination' ? 1 : current.gameCount,
}));
}}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm" className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
> >
{Object.entries(GAME_MODE_LABEL).map(([value, label]) => ( {Object.entries(GAME_MODE_LABEL).map(([value, label]) => (
@@ -385,6 +416,22 @@ export default function MatchAdminPage() {
</span> </span>
</label> </label>
)} )}
{form.gameMode === 'double-elimination' && (
<label className="flex items-center gap-2 border border-base-content/10 px-3 py-2 text-xs text-base-content/55">
<input
type="checkbox"
checked={Boolean(form.doubleEliminationResetFinalEnabled)}
onChange={(event) =>
setForm((current) => ({
...current,
doubleEliminationResetFinalEnabled:
event.target.checked,
}))
}
/>
그랜드 파이널 리셋 허용
</label>
)}
<label className="text-xs text-base-content/45"> <label className="text-xs text-base-content/45">
상품 (줄바꿈 구분) 상품 (줄바꿈 구분)
<textarea <textarea
@@ -474,6 +521,14 @@ export default function MatchAdminPage() {
최대 {match.roundRobinMaxRounds}R 최대 {match.roundRobinMaxRounds}R
</span> </span>
)} )}
{match.gameMode === 'double-elimination' && (
<span className="block text-xs text-base-content/30">
GF 리셋{' '}
{match.doubleElimination?.resetFinalEnabled
? '허용'
: '없음'}
</span>
)}
</td> </td>
<td className="px-3 py-2 text-right"> <td className="px-3 py-2 text-right">
<div className="inline-flex gap-2"> <div className="inline-flex gap-2">