feat: improve tournament workflows and prune outdated docs

This commit is contained in:
dahyeon committed 2026-11-10 15:31:19 +09:00
1 parent da7b502936
commit 38a89b5374
53 files changed
+3308 -3276

No files matched your search

@@ -0,0 +1,161 @@
import mongoose from 'mongoose';
import {
summarizeMatchHistoryResult,
type HistoryCompetition,
} from './match-history-result';
const firstId = new mongoose.Types.ObjectId();
const secondId = new mongoose.Types.ObjectId();
const thirdId = new mongoose.Types.ObjectId();
const teams = [
{
teamId: firstId,
name: '첫 팀',
displayOrder: 1,
seedNumber: 1,
members: [],
},
{
teamId: secondId,
name: '둘째 팀',
displayOrder: 2,
seedNumber: 2,
members: [],
},
{
teamId: thirdId,
name: '셋째 팀',
displayOrder: 3,
seedNumber: 3,
members: [],
},
];
const finishedMatch = {
status: 'finished' as const,
competitionId: new mongoose.Types.ObjectId(),
teams: [],
};
const singleSeries = {
status: 'completed',
entries: [{ gameWins: 2 }, { gameWins: 1 }],
outcome: { type: 'played', winnerTeamId: firstId.toString() },
};
describe('summarizeMatchHistoryResult', () => {
it('shows played scores only for one completed series between two teams', () => {
const competition: HistoryCompetition = {
teams: teams.slice(0, 2),
projection: {
series: [singleSeries],
outcome: { type: 'paired-series' },
},
};
expect(summarizeMatchHistoryResult(finishedMatch, competition)).toEqual({
type: 'score',
teamAWins: 2,
teamBWins: 1,
winnerTeamName: '첫 팀',
});
expect(
summarizeMatchHistoryResult(
{ ...finishedMatch, status: 'in-progress' },
competition,
),
).toBeUndefined();
expect(
summarizeMatchHistoryResult(finishedMatch, {
...competition,
projection: {
...competition.projection,
series: [singleSeries, singleSeries],
},
}),
).toBeUndefined();
});
it('shows adjudication without a score even if some games were played', () => {
expect(
summarizeMatchHistoryResult(finishedMatch, {
teams: teams.slice(0, 2),
projection: {
series: [
{
...singleSeries,
outcome: { ...singleSeries.outcome, type: 'forfeit' },
},
],
outcome: { type: 'paired-series' },
},
}),
).toEqual({
type: 'decision',
decision: 'forfeit',
winnerTeamName: '첫 팀',
});
});
it('uses the tournament winner or joint leaders instead of a series score', () => {
expect(
summarizeMatchHistoryResult(finishedMatch, {
teams,
projection: {
series: [singleSeries],
outcome: {
type: 'double-elimination',
championTeamId: thirdId.toString(),
},
},
}),
).toEqual({ type: 'winners', teamNames: ['셋째 팀'] });
expect(
summarizeMatchHistoryResult(finishedMatch, {
teams,
projection: {
series: [singleSeries],
outcome: {
type: 'round-robin',
leaderTeamIds: [firstId.toString(), secondId.toString()],
},
},
}),
).toEqual({ type: 'winners', teamNames: ['첫 팀', '둘째 팀'] });
});
it('uses collected games for legacy two-team records without a Competition', () => {
const match = {
status: 'finished' as const,
teams: [
{ teamIndex: 1, name: '첫 팀', members: [] },
{ teamIndex: 2, name: '둘째 팀', members: [] },
],
result: {
winnerTeamIndex: 2,
riotMatchIds: ['KR_1'],
games: [
{
gameNumber: 1,
riotMatchId: 'KR_1',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 2,
winnerSide: 'red' as const,
gameCreation: 0,
gameDuration: 1800,
participants: [],
},
],
},
};
expect(summarizeMatchHistoryResult(match)).toEqual({
type: 'score',
teamAWins: 0,
teamBWins: 1,
winnerTeamName: '둘째 팀',
});
expect(
summarizeMatchHistoryResult({ ...match, competitionId: firstId }),
).toBeUndefined();
});
});
@@ -0,0 +1,117 @@
import type { MatchHistoryResult } from '@lolympus/contracts';
import type { Competition } from '../competition/competition.schema';
import type { CompetitionProjection } from '../competition/domain/competition-projector';
import type { Match } from '../global/database/schema';
type HistoryMatch = Pick<
Match,
'status' | 'competitionId' | 'teams' | 'result' | 'doubleElimination'
>;
export type HistoryCompetition = Pick<Competition, 'projection' | 'teams'>;
export function summarizeMatchHistoryResult(
match: HistoryMatch,
competition?: HistoryCompetition,
): MatchHistoryResult | undefined {
if (match.status !== 'finished') return;
if (!match.competitionId) return summarizeLegacyResult(match);
if (!competition) return;
const { series, outcome } = competition.projection as Pick<
CompetitionProjection,
'series' | 'outcome'
>;
if (!outcome) return;
const teamName = (teamId: string) => {
const team = competition.teams.find(
(item) => String(item.teamId) === teamId,
);
return team && (team.name.trim() || `${team.displayOrder}팀`);
};
const singleSeries = series?.length === 1 ? series[0] : undefined;
if (competition.teams.length === 2 && singleSeries?.status === 'completed') {
const decision = singleSeries.outcome;
const winnerTeamName =
decision.type === 'draw' ? undefined : teamName(decision.winnerTeamId);
if (
decision.type === 'played' ||
(decision.type === 'draw' && decision.basis.type === 'played')
) {
const [teamA, teamB] = singleSeries.entries;
return {
type: 'score',
teamAWins: teamA.gameWins,
teamBWins: teamB.gameWins,
winnerTeamName,
};
}
return { type: 'decision', decision: decision.type, winnerTeamName };
}
const winnerIds =
outcome.type === 'double-elimination'
? [outcome.championTeamId]
: outcome.type === 'round-robin'
? outcome.leaderTeamIds
: [];
const teamNames = winnerIds.map(teamName);
if (teamNames.length > 0 && teamNames.every((name) => name !== undefined)) {
return { type: 'winners', teamNames };
}
}
function summarizeLegacyResult(
match: HistoryMatch,
): MatchHistoryResult | undefined {
const placement = match.doubleElimination?.placements.firstTeamIndex;
if (placement !== undefined) {
const champion = match.teams.find((team) => team.teamIndex === placement);
if (champion) {
return {
type: 'winners',
teamNames: [champion.name.trim() || `${placement}팀`],
};
}
}
if (match.teams.length !== 2 || !match.result?.games.length) return;
const [teamA, teamB] = [...match.teams].sort(
(a, b) => a.teamIndex - b.teamIndex,
);
const { games } = match.result;
const teamIndices = new Set([teamA.teamIndex, teamB.teamIndex]);
if (
games.some(
({ blueTeamIndex, redTeamIndex }) =>
blueTeamIndex === redTeamIndex ||
!teamIndices.has(blueTeamIndex) ||
!teamIndices.has(redTeamIndex),
)
)
return;
const teamAWins = games.filter(
(game) => game.winnerTeamIndex === teamA.teamIndex,
).length;
const teamBWins = games.filter(
(game) => game.winnerTeamIndex === teamB.teamIndex,
).length;
if (teamAWins + teamBWins !== games.length) return;
const winner = match.teams.find(
(team) => team.teamIndex === match.result?.winnerTeamIndex,
);
if (
winner &&
(teamAWins === teamBWins ||
winner.teamIndex !==
(teamAWins > teamBWins ? teamA.teamIndex : teamB.teamIndex))
)
return;
return {
type: 'score',
teamAWins,
teamBWins,
winnerTeamName: winner && (winner.name.trim() || `${winner.teamIndex}팀`),
};
}
@@ -7,6 +7,50 @@ import { RolesGuard } from '../auth/roles.guard';
import type { UserDocument } from '../global/database/schema';
import { MatchController } from './match.controller';
describe('MatchController history summaries', () => {
it('only attaches the page results when requested', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = { _id: new mongoose.Types.ObjectId() };
const summary = { _id: match._id.toString() };
const historyResult = { type: 'score', teamAWins: 2, teamBWins: 1 };
const matchService = {
listPage: jest
.fn()
.mockResolvedValue({ matches: [match], total: 1, page: 1, limit: 10 }),
serialize: jest.fn().mockReturnValue(summary),
getHistoryResults: jest
.fn()
.mockResolvedValue(new Map([[summary._id, historyResult]])),
};
const controller = new MatchController(matchService as never);
await expect(
controller.listMatches(undefined, communityId),
).resolves.toMatchObject({
matches: [summary],
});
expect(matchService.getHistoryResults).not.toHaveBeenCalled();
await expect(
controller.listMatches(
undefined,
communityId,
undefined,
'10',
'1',
undefined,
undefined,
undefined,
'desc',
'true',
),
).resolves.toMatchObject({ matches: [{ ...summary, historyResult }] });
expect(matchService.getHistoryResults).toHaveBeenCalledWith(communityId, [
match,
]);
});
});
describe('MatchController participant access', () => {
function createController() {
const joinedMatch = { _id: new mongoose.Types.ObjectId() };
+11 -4
View File
@@ -82,6 +82,7 @@ export class MatchController {
@Query('scheduledFrom') scheduledFrom?: string,
@Query('scheduledTo') scheduledTo?: string,
@Query('sort') sort?: 'asc' | 'desc',
@Query('includeResults') includeResults?: string,
): Promise<MatchListResponse> {
const result = await this.matchService.listPage({
communityId,
@@ -93,10 +94,14 @@ export class MatchController {
scheduledTo: this.toOptionalDate(scheduledTo),
sort,
});
const historyResults =
includeResults === 'true'
? await this.matchService.getHistoryResults(communityId, result.matches)
: undefined;
return {
...result,
matches: result.matches.map((match) =>
this.matchService.serialize(match, {
matches: result.matches.map((match) => {
const summary = this.matchService.serialize(match, {
...(currentUser
? {
joined: match.participants.some((participant) =>
@@ -104,8 +109,10 @@ export class MatchController {
),
}
: {}),
}),
),
});
const historyResult = historyResults?.get(summary._id);
return historyResult ? { ...summary, historyResult } : summary;
}),
};
}
@@ -1,3 +1,4 @@
import type { MatchHistoryResult } from '@lolympus/contracts';
import {
BadRequestException,
ConflictException,
@@ -20,6 +21,10 @@ import {
} from '../global/database/schema';
import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants';
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
import {
summarizeMatchHistoryResult,
type HistoryCompetition,
} from './match-history-result';
import { presentPublicMatch } from './match-public.presenter';
const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
@@ -170,6 +175,47 @@ export class MatchService {
};
}
public async getHistoryResults(
communityId: mongoose.Types.ObjectId,
matches: readonly MatchDocument[],
): Promise<Map<string, MatchHistoryResult>> {
const finished = matches.filter((match) => match.status === 'finished');
const competitionIds = finished.flatMap((match) =>
match.competitionId ? [match.competitionId] : [],
);
const competitions = new Map<string, HistoryCompetition>();
if (competitionIds.length > 0) {
const CompetitionModel =
await this.connectionService.getModel('competition');
const completed = await CompetitionModel.find({
_id: { $in: competitionIds },
communityId,
phase: 'completed',
})
.select({
matchId: 1,
'teams.teamId': 1,
'teams.name': 1,
'teams.displayOrder': 1,
'projection.outcome': 1,
'projection.series': 1,
})
.lean()
.exec();
for (const competition of completed) {
competitions.set(competition.matchId.toString(), competition);
}
}
const results = new Map<string, MatchHistoryResult>();
for (const match of finished) {
const id = match._id.toString();
const result = summarizeMatchHistoryResult(match, competitions.get(id));
if (result) results.set(id, result);
}
return results;
}
public async ensureShortCode(match: MatchDocument): Promise<MatchDocument> {
if (match.shortCode) return match;