From 6bddb666fce96857eb732f5c529c037967cb772e Mon Sep 17 00:00:00 2001 From: Park Dahyeon Date: Sun, 12 Jul 2026 20:11:24 +0000 Subject: [PATCH] refactor: cut web results over to competition projections --- apps/web/src/App.tsx | 23 +- apps/web/src/api/hooks.ts | 336 +- apps/web/src/api/mappers.ts | 81 +- apps/web/src/api/types.ts | 123 +- .../competition/CompetitionAdminControls.tsx | 763 ++++ .../competition/CompetitionResults.tsx | 185 + .../competition/RoundRobinTable.tsx | 63 + .../competition/SeriesScoreCard.tsx | 75 + apps/web/src/lib/api.ts | 9 +- apps/web/src/pages/HomePage.tsx | 24 +- apps/web/src/pages/MatchDetailPage.tsx | 3428 +++-------------- apps/web/src/pages/MatchTeamProgressPage.tsx | 923 +---- apps/web/src/pages/admin/MatchAdminPage.tsx | 5 +- 13 files changed, 2153 insertions(+), 3885 deletions(-) create mode 100644 apps/web/src/components/competition/CompetitionAdminControls.tsx create mode 100644 apps/web/src/components/competition/CompetitionResults.tsx create mode 100644 apps/web/src/components/competition/RoundRobinTable.tsx create mode 100644 apps/web/src/components/competition/SeriesScoreCard.tsx diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 172c4221..b1fb1527 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -51,7 +51,8 @@ function MsalHeaderActions() { function ThemeToggle() { const theme = useTheme(); const nextTheme = theme === "light" ? "dark" : "light"; - const label = nextTheme === "dark" ? "다크 테마로 전환" : "라이트 테마로 전환"; + const label = + nextTheme === "dark" ? "다크 테마로 전환" : "라이트 테마로 전환"; const Icon = nextTheme === "dark" ? Moon : Sun; return ( @@ -81,11 +82,11 @@ function AppFooter() {

- © 2026 LOLYMPUS. LOLYMPUS is not endorsed by Riot Games and - does not reflect the views or opinions of Riot Games or anyone - officially involved in producing or managing League of Legends. - League of Legends and Riot Games are trademarks or registered - trademarks of Riot Games, Inc. League of Legends © Riot Games, Inc. + © 2026 LOLYMPUS. LOLYMPUS is not endorsed by Riot Games and does not + reflect the views or opinions of Riot Games or anyone officially + involved in producing or managing League of Legends. League of Legends + and Riot Games are trademarks or registered trademarks of Riot Games, + Inc. League of Legends © Riot Games, Inc.

@@ -156,12 +157,12 @@ function App() { path="/match/:id/game/:gameNumber" element={} /> - } - /> + } /> } /> - } /> + } + /> } diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index e15d8082..1c7d515a 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -1,6 +1,16 @@ import { InteractionStatus } from '@azure/msal-browser'; import { useMsal } from '@azure/msal-react'; import { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query'; +import type { + CompetitionCommandResponse, + CompetitionDetailResponse, + CreateSeriesAdjudicationRequest, + ReverseSeriesResultRequest, + SeriesId, + SeriesReversalPreviewRequest, + SeriesReversalPreviewResponse, + TeamCompetitionViewResponse, +} from '@lolympus/contracts'; import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config'; import { apiFetch } from '../lib/api'; import { @@ -41,7 +51,6 @@ import type { RebuildLegacyMatchesResponse, TournamentCodeBulkUploadResponse, TournamentCodeListResponse, - TournamentCodeSlotView, TournamentCodeState, TournamentCodeStatsResponse, TournamentCodeUploadItem, @@ -83,7 +92,8 @@ function createMatchesPath( if (options.limit) searchParams.set('limit', String(options.limit)); if (options.page) searchParams.set('page', String(options.page)); if (options.offset) searchParams.set('offset', String(options.offset)); - if (options.scheduledFrom) searchParams.set('scheduledFrom', options.scheduledFrom); + if (options.scheduledFrom) + searchParams.set('scheduledFrom', options.scheduledFrom); if (options.scheduledTo) searchParams.set('scheduledTo', options.scheduledTo); if (options.sort) searchParams.set('sort', options.sort); @@ -152,7 +162,10 @@ export function useMatchesPage( }); } -export function useMatch(matchId: string | undefined, communityId = DEFAULT_COMMUNITY_ID) { +export function useMatch( + matchId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, +) { return useQuery({ queryKey: ['match', communityId, matchId ?? null], queryFn: () => @@ -164,6 +177,126 @@ export function useMatch(matchId: string | undefined, communityId = DEFAULT_COMM }); } +export function useCompetition( + matchId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: ['competition', communityId, matchId ?? null], + queryFn: () => + apiFetch( + `/communities/${communityId}/matches/${matchId}/competition`, + { + auth: 'none', + }, + ), + enabled: enabled && Boolean(communityId && matchId), + retry: false, + }); +} + +export function useTeamCompetition( + matchId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, +) { + return useQuery({ + queryKey: ['competition-team', communityId, matchId ?? null], + queryFn: () => + apiFetch( + `/communities/${communityId}/matches/${matchId}/competition/team`, + ), + enabled: Boolean(communityId && matchId), + retry: false, + }); +} + +type CompetitionMutationScope = { + matchId: string; + seriesId: SeriesId; + revision: number; +}; + +type IdempotentCompetitionMutationScope = CompetitionMutationScope & { + idempotencyKey: string; +}; + +function competitionCommandHeaders(revision: number, idempotencyKey?: string) { + return { + 'If-Match': `"${revision}"`, + ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}), + }; +} + +export function useAdjudicateCompetitionSeries( + communityId = DEFAULT_COMMUNITY_ID, +) { + return useMutation({ + mutationFn: ( + params: IdempotentCompetitionMutationScope & { + request: CreateSeriesAdjudicationRequest; + }, + ) => + apiFetch( + `/communities/${communityId}/matches/${params.matchId}/competition/series/${params.seriesId}/adjudications`, + { + method: 'POST', + headers: competitionCommandHeaders( + params.revision, + params.idempotencyKey, + ), + body: JSON.stringify(params.request), + }, + ), + retry: false, + }); +} + +export function usePreviewCompetitionSeriesReversal( + communityId = DEFAULT_COMMUNITY_ID, +) { + return useMutation({ + mutationFn: ( + params: CompetitionMutationScope & { + request: SeriesReversalPreviewRequest; + }, + ) => + apiFetch( + `/communities/${communityId}/matches/${params.matchId}/competition/series/${params.seriesId}/reversal-preview`, + { + method: 'POST', + headers: competitionCommandHeaders(params.revision), + body: JSON.stringify(params.request), + }, + ), + retry: false, + }); +} + +export function useReverseCompetitionSeries( + communityId = DEFAULT_COMMUNITY_ID, +) { + return useMutation({ + mutationFn: ( + params: IdempotentCompetitionMutationScope & { + request: ReverseSeriesResultRequest; + }, + ) => + apiFetch( + `/communities/${communityId}/matches/${params.matchId}/competition/series/${params.seriesId}/reverse`, + { + method: 'POST', + headers: competitionCommandHeaders( + params.revision, + params.idempotencyKey, + ), + body: JSON.stringify(params.request), + }, + ), + retry: false, + }); +} + export function useCommunityUserSearch( query: string, communityId = DEFAULT_COMMUNITY_ID, @@ -302,7 +435,13 @@ export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) { export function useUpdateMatch(communityId = DEFAULT_COMMUNITY_ID) { return useMutation({ - mutationFn: ({ matchId, body }: { matchId: string; body: Partial }) => + mutationFn: ({ + matchId, + body, + }: { + matchId: string; + body: Partial; + }) => apiFetch(`/communities/${communityId}/matches/${matchId}`, { method: 'PATCH', body: JSON.stringify(body), @@ -310,101 +449,6 @@ export function useUpdateMatch(communityId = DEFAULT_COMMUNITY_ID) { }); } -export function useReshuffleDoubleEliminationSeeds( - communityId = DEFAULT_COMMUNITY_ID, -) { - return useMutation({ - mutationFn: (matchId: string) => - apiFetch( - `/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( - `/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( - `/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( - `/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( - `/communities/${communityId}/matches/${params.matchId}/double-elimination/bracket-matches/${params.bracketMatchId}/result/cancel`, - { - method: 'POST', - body: JSON.stringify({ reason: params.reason }), - }, - ), - }); -} - function createUserHistoryPath( communityId: string, userId: string, @@ -416,7 +460,8 @@ function createUserHistoryPath( if (filters.queueGroup) searchParams.set('queueGroup', filters.queueGroup); if (filters.rank) searchParams.set('rank', filters.rank); if (filters.seasonId) searchParams.set('seasonId', filters.seasonId); - if (filters.championId) searchParams.set('championId', String(filters.championId)); + if (filters.championId) + searchParams.set('championId', String(filters.championId)); for (const [key, value] of Object.entries(extra)) { if (value !== null && value !== undefined && value !== '') { searchParams.set(key, String(value)); @@ -461,8 +506,15 @@ export function useChampionStats( ], queryFn: () => apiFetch( - createUserHistoryPath(communityId, userId ?? '', 'champion-stats', filters), - { auth: 'none' }, + createUserHistoryPath( + communityId, + userId ?? '', + 'champion-stats', + filters, + ), + { + auth: 'none', + }, ), enabled: Boolean(communityId && userId && enabled), }); @@ -486,8 +538,15 @@ export function useRecentSummary( ], queryFn: () => apiFetch( - createUserHistoryPath(communityId, userId ?? '', 'recent-summary', filters), - { auth: 'none' }, + createUserHistoryPath( + communityId, + userId ?? '', + 'recent-summary', + filters, + ), + { + auth: 'none', + }, ), enabled: Boolean(communityId && userId && enabled), }); @@ -511,10 +570,16 @@ export function useRecentMatches( ], queryFn: ({ pageParam }) => apiFetch( - createUserHistoryPath(communityId, userId ?? '', 'recent-matches', filters, { - cursor: pageParam, - limit: 10, - }), + createUserHistoryPath( + communityId, + userId ?? '', + 'recent-matches', + filters, + { + cursor: pageParam, + limit: 10, + }, + ), { auth: 'none' }, ), initialPageParam: null as number | null, @@ -533,7 +598,8 @@ function createCommunityInternalStatsPath( if (filters.seasonId) searchParams.set('seasonId', filters.seasonId); if (filters.from) searchParams.set('from', filters.from); if (filters.to) searchParams.set('to', filters.to); - if (filters.championId) searchParams.set('championId', String(filters.championId)); + if (filters.championId) + searchParams.set('championId', String(filters.championId)); if (filters.limit) searchParams.set('limit', String(filters.limit)); for (const [key, value] of Object.entries(extra)) { if (value !== null && value !== undefined && value !== '') { @@ -590,7 +656,9 @@ export function useCommunityLeaderboard( queryFn: () => apiFetch( createCommunityInternalStatsPath(communityId, 'leaderboard', filters), - { auth: 'none' }, + { + auth: 'none', + }, ), enabled: Boolean(communityId && enabled), }); @@ -613,7 +681,9 @@ export function useTeamInsights( queryFn: () => apiFetch( createCommunityInternalStatsPath(communityId, 'team-insights', filters), - { auth: 'none' }, + { + auth: 'none', + }, ), enabled: Boolean(communityId && enabled), }); @@ -628,7 +698,9 @@ export function useInternalMatchDetail( queryFn: () => apiFetch( `/communities/${communityId}/internal-stats/match/${matchId}`, - { auth: 'none' }, + { + auth: 'none', + }, ), enabled: Boolean(communityId && matchId), retry: false, @@ -651,10 +723,16 @@ export function useUserInternalHistory( ], queryFn: ({ pageParam }) => apiFetch( - createUserHistoryPath(communityId, userId ?? '', 'internal-history', filters, { - cursor: pageParam, - limit: 10, - }), + createUserHistoryPath( + communityId, + userId ?? '', + 'internal-history', + filters, + { + cursor: pageParam, + limit: 10, + }, + ), { auth: 'none' }, ), initialPageParam: null as number | null, @@ -740,7 +818,9 @@ export function useTournamentCodes( }); } -export function useBulkUploadTournamentCodes(communityId = DEFAULT_COMMUNITY_ID) { +export function useBulkUploadTournamentCodes( + communityId = DEFAULT_COMMUNITY_ID, +) { return useMutation({ mutationFn: (codes: TournamentCodeUploadItem[]) => apiFetch( @@ -772,16 +852,6 @@ export function useDeleteTournamentCode(communityId = DEFAULT_COMMUNITY_ID) { }); } -export function useReplaceTournamentCode(communityId = DEFAULT_COMMUNITY_ID) { - return useMutation({ - mutationFn: (params: { matchId: string; gameNumber: number }) => - apiFetch( - `/communities/${communityId}/tournament-codes/matches/${params.matchId}/games/${params.gameNumber}/replace`, - { method: 'POST' }, - ), - }); -} - export function usePollTournamentResult(communityId = DEFAULT_COMMUNITY_ID) { return useMutation({ mutationFn: (matchId: string) => @@ -791,9 +861,12 @@ export function usePollTournamentResult(communityId = DEFAULT_COMMUNITY_ID) { priority: 'high' | 'low'; attempt: number; expandedToAllPuuids: boolean; - }>(`/communities/${communityId}/matches/${matchId}/poll-tournament-result`, { - method: 'POST', - }), + }>( + `/communities/${communityId}/matches/${matchId}/poll-tournament-result`, + { + method: 'POST', + }, + ), }); } @@ -848,7 +921,8 @@ export function useLegacyImportMembers( ], queryFn: () => { const searchParams = new URLSearchParams(); - if (options.windowStart) searchParams.set('windowStart', options.windowStart); + if (options.windowStart) + searchParams.set('windowStart', options.windowStart); if (options.windowEnd) searchParams.set('windowEnd', options.windowEnd); const queryString = searchParams.toString(); return apiFetch( diff --git a/apps/web/src/api/mappers.ts b/apps/web/src/api/mappers.ts index 4cddcb3f..91e9acc3 100644 --- a/apps/web/src/api/mappers.ts +++ b/apps/web/src/api/mappers.ts @@ -9,11 +9,9 @@ import type { ApiRiotRecentStatsSummary, ApiTierHistoryEntry, ApiTierInfo, - ApiDoubleEliminationBracket, MatchStatus, Position, RiotLane, - TournamentCodeSlotView, } from "./types"; import { POSITION_ORDER, teamIndexLabel } from "../lib/league"; @@ -52,40 +50,9 @@ export interface MatchDetailView { description: string; map: string; maxParticipants: number; - gameCount: number; - gameMode: ApiMatch["gameMode"]; - doubleElimination?: ApiDoubleEliminationBracket; - tournamentCodes: TournamentCodeSlotView[]; joined: boolean; participants: ParticipantView[]; teams: TeamView[]; - result?: { - winner?: string; - winnerTeamIndex?: number; - riotMatchIds: string[]; - games: Array<{ - gameNumber: number; - bracketMatchId?: string; - riotMatchId: string; - blueTeamIndex: number; - redTeamIndex: number; - winnerTeamIndex: number; - winnerSide: "blue" | "red"; - gameCreation: number; - gameDuration: number; - participants: Array<{ - userId: string; - teamIndex: number; - side: "blue" | "red"; - championId: number; - kills: number; - deaths: number; - assists: number; - win: boolean; - }>; - }>; - seriesResults: NonNullable["seriesResults"]; - }; prizes: string[]; notices: string[]; schedule: { time: string; label: string }[]; @@ -434,7 +401,9 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { captainUserId: team.captainUserId, captainName: captain?.summonerName ?? - (team.captainUserId ? `User ${team.captainUserId.slice(-4)}` : undefined), + (team.captainUserId + ? `User ${team.captainUserId.slice(-4)}` + : undefined), captainTag: captain?.tag, participants: team.members.map((member) => { const participant = @@ -450,10 +419,6 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { }; }); - const winnerTeam = match.result?.winnerTeamIndex - ? teams.find((team) => team.teamIndex === match.result?.winnerTeamIndex) - : undefined; - return { id: match._id, title: match.title, @@ -463,24 +428,9 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { description: match.description, map: mapIdToLabel(match.mapId), maxParticipants: match.maxParticipants, - gameCount: match.gameCount ?? 3, - gameMode: match.gameMode ?? "pair", - doubleElimination: match.doubleElimination, - tournamentCodes: match.tournamentCodes ?? [], joined: Boolean(match.joined), participants, teams, - result: match.result - ? { - winner: match.result.winnerTeamIndex ? winnerTeam?.name : undefined, - winnerTeamIndex: match.result.winnerTeamIndex, - riotMatchIds: match.result.riotMatchIds, - games: [...(match.result.games ?? [])].sort( - (left, right) => left.gameNumber - right.gameNumber, - ), - seriesResults: match.result.seriesResults ?? [], - } - : undefined, prizes: match.prizes, notices: match.notices, schedule: match.schedule, @@ -523,9 +473,9 @@ export function mapApiAuctionToAuctionState( const auctionPlayerLookup = new Map( auctionOrder.map((player) => [player.userId, player]), ); - const teams = rawAuctionTeams.map(normalizeApiAuctionTeam).sort( - (left, right) => left.teamIndex - right.teamIndex, - ); + const teams = rawAuctionTeams + .map(normalizeApiAuctionTeam) + .sort((left, right) => left.teamIndex - right.teamIndex); const totalPlayers = auctionOrder.length; const currentPlayer = @@ -535,7 +485,9 @@ export function mapApiAuctionToAuctionState( rawAuctionOrder[currentAuctionPlayerOrderIndex]?.userId ?? "", ) ?? null); const currentPlayerIndex = - auction.phase === "complete" ? totalPlayers : currentAuctionPlayerOrderIndex; + auction.phase === "complete" + ? totalPlayers + : currentAuctionPlayerOrderIndex; const remainingMs = currentBidRoundDeadlineTimestampMS ? Math.max(0, currentBidRoundDeadlineTimestampMS - now.getTime()) : 0; @@ -557,11 +509,12 @@ export function mapApiAuctionToAuctionState( auctionRound: auction.currentAuctionRound ?? auction.auctionRound ?? 1, bids: normalizeApiAuctionBids(auction), currentBid, - currentBidder: currentBidderTeamIndex !== undefined - ? { - teamIndex: currentBidderTeamIndex, - } - : null, + currentBidder: + currentBidderTeamIndex !== undefined + ? { + teamIndex: currentBidderTeamIndex, + } + : null, remainingMs, timer, maxTimer: maximumBidRoundDurationSeconds, @@ -574,7 +527,9 @@ export function mapApiAuctionToAuctionState( type NormalizedApiAuctionTeam = ApiAuctionTeam & { points: number }; -function normalizeApiAuctionTeam(team: ApiAuctionTeam): NormalizedApiAuctionTeam { +function normalizeApiAuctionTeam( + team: ApiAuctionTeam, +): NormalizedApiAuctionTeam { return { ...team, points: team.points ?? team.remainingBidPointAmount ?? 0, diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index b5f72041..f453045f 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -3,7 +3,6 @@ export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY'; export type TeamSide = 'blue' | 'red'; export type MatchGameMode = | 'pair' - | 'bracket' | 'round-robin' | 'double-elimination'; export type MatchStatus = @@ -143,25 +142,6 @@ export type TournamentCodeState = | 'released' | 'voided'; -export type TournamentCodeSlotState = TournamentCodeState | 'pending'; - -export interface TournamentCodeSlotView { - gameNumber: number; - seriesGameNumber?: number; - seriesGameCount?: number; - seriesRequiredWins?: number; - bracketMatchId?: string; - bracketSide?: string; - roundNumber?: number; - matchNumber?: number; - teamAIndex?: number; - teamBIndex?: number; - code: string | null; - expiresAt: string | null; - state: TournamentCodeSlotState; - riotMatchId: string | null; -} - export interface ApiMatchParticipant { userId: string; puuid?: string; @@ -187,109 +167,11 @@ export interface ApiMatchTeam { members: ApiMatchTeamMember[]; } -export interface ApiMatchGameResultParticipant { - userId: string; - teamIndex: number; - side: TeamSide; - championId: number; - kills: number; - deaths: number; - assists: number; - win: boolean; -} - -export interface ApiMatchGameResult { - gameNumber: number; - bracketMatchId?: string; - riotMatchId: string; - blueTeamIndex: number; - redTeamIndex: number; - winnerTeamIndex: number; - winnerSide: TeamSide; - gameCreation: number; - gameDuration: number; - participants: ApiMatchGameResultParticipant[]; -} - -export interface ApiMatchResult { - winnerTeamIndex?: number; - mvpUserId?: string; - riotMatchIds: string[]; - games: ApiMatchGameResult[]; - seriesResults?: Array<{ - bracketMatchId?: string; - teamAIndex: number; - teamBIndex: number; - teamAWins: number; - teamBWins: number; - winnerTeamIndex?: number; - }>; -} - export interface ApiMatchScheduleItem { time: string; label: string; } -export interface ApiMatchGameAssignment { - gameNumber: number; - roundNumber?: number; - teamAIndex: 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; - gameCount: number; - requiredWins: 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 { scanned: number; matched: number; @@ -311,13 +193,10 @@ export interface ApiMatch { gameCount: number; gameMode: MatchGameMode; roundRobinMaxRounds?: number; - gameSchedule?: ApiMatchGameAssignment[]; - doubleElimination?: ApiDoubleEliminationBracket; - tournamentCodes?: TournamentCodeSlotView[]; + doubleEliminationResetFinalEnabled?: boolean; hostUserId?: string; participants: ApiMatchParticipant[]; teams: ApiMatchTeam[]; - result?: ApiMatchResult; prizes: string[]; notices: string[]; schedule: ApiMatchScheduleItem[]; diff --git a/apps/web/src/components/competition/CompetitionAdminControls.tsx b/apps/web/src/components/competition/CompetitionAdminControls.tsx new file mode 100644 index 00000000..607a0779 --- /dev/null +++ b/apps/web/src/components/competition/CompetitionAdminControls.tsx @@ -0,0 +1,763 @@ +import { useMemo, useRef, useState } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import type { + CompetitionCommandResponse, + CompetitionDetailResponse, + SeriesAdjudicationDecision, + SeriesProjection, + SeriesReversalMode, + SeriesReversalPreviewResponse, + TeamId, +} from "@lolympus/contracts"; +import { + useAdjudicateCompetitionSeries, + usePreviewCompetitionSeriesReversal, + useReverseCompetitionSeries, +} from "../../api/hooks"; +import { ApiError } from "../../lib/api"; + +type AdjudicationType = SeriesAdjudicationDecision["type"]; + +const ADJUDICATION_LABELS: Record = { + walkover: "부전승", + forfeit: "몰수패", + administrative: "운영자 판정", + "administrative-draw": "운영자 무승부", +}; + +export function CompetitionAdminControls({ + competition, + communityId, + canManage, +}: { + competition: CompetitionDetailResponse; + communityId: string; + canManage: boolean; +}) { + const queryClient = useQueryClient(); + const series = competition.projection.series; + const defaultSeries = + series.find( + (item) => item.status === "ready" || item.status === "in-progress", + ) ?? + series.find((item) => item.status === "completed") ?? + series[0]; + const [selectedSeriesId, setSelectedSeriesId] = useState( + defaultSeries?.seriesId ?? "", + ); + const [adjudicationType, setAdjudicationType] = + useState("walkover"); + const [winnerTeamId, setWinnerTeamId] = useState(""); + const [adjudicationReason, setAdjudicationReason] = useState(""); + const [reversalMode, setReversalMode] = + useState("strict"); + const [reversalReason, setReversalReason] = useState(""); + const [reversalPreview, setReversalPreview] = + useState(null); + const [impactConfirmed, setImpactConfirmed] = useState(false); + const [notice, setNotice] = useState(null); + const adjudicationIdempotencyKeyRef = useRef(null); + const reversalIdempotencyKeyRef = useRef(null); + const adjudicationMutation = useAdjudicateCompetitionSeries(communityId); + const previewMutation = usePreviewCompetitionSeriesReversal(communityId); + const reversalMutation = useReverseCompetitionSeries(communityId); + + const selectedSeries = + series.find((item) => item.seriesId === selectedSeriesId) ?? defaultSeries; + const teamById = useMemo( + () => new Map(competition.teams.map((team) => [team.teamId, team])), + [competition.teams], + ); + const eligibleTeams = selectedSeries + ? selectedSeries.entries.flatMap((entry) => + entry.teamId ? [teamById.get(entry.teamId)] : [], + ) + : []; + const selectedSeriesGames = selectedSeries + ? competition.projection.games.filter( + (game) => game.seriesId === selectedSeries.seriesId, + ) + : []; + const drawAllowed = Boolean( + selectedSeries?.rule.type === "fixed-games" && + selectedSeries.rule.drawPolicy === "allow", + ); + const canAdjudicate = Boolean( + selectedSeries && + (selectedSeries.status === "ready" || + selectedSeries.status === "in-progress"), + ); + const canReverse = selectedSeries?.status === "completed"; + const previewIsCurrent = Boolean( + reversalPreview && reversalPreview.sourceRevision === competition.revision, + ); + const effectiveSelectedSeriesId = selectedSeries?.seriesId ?? ""; + const effectiveWinnerTeamId = eligibleTeams.some( + (team) => team?.teamId === winnerTeamId, + ) + ? winnerTeamId + : (eligibleTeams.find(Boolean)?.teamId ?? ""); + const effectiveAdjudicationType = + adjudicationType === "administrative-draw" && !drawAllowed + ? "administrative" + : adjudicationType === "walkover" && selectedSeriesGames.length > 0 + ? "forfeit" + : adjudicationType; + + if (!canManage || series.length === 0) return null; + + async function invalidateCompetitionCaches( + response?: CompetitionCommandResponse, + ) { + const matchId = String(competition.matchId); + if (response) { + queryClient.setQueryData( + ["competition", communityId, matchId], + response.competition, + ); + } + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ["competition", communityId, matchId], + }), + queryClient.invalidateQueries({ + queryKey: ["competition-team", communityId, matchId], + }), + queryClient.invalidateQueries({ + queryKey: ["match", communityId, matchId], + }), + queryClient.invalidateQueries({ + queryKey: ["matches", communityId], + }), + queryClient.invalidateQueries({ + queryKey: ["matches-page", communityId], + }), + ]); + } + + function resetCommandFeedback() { + setNotice(null); + adjudicationMutation.reset(); + previewMutation.reset(); + reversalMutation.reset(); + } + + function handleSelectedSeriesChange(nextSeriesId: string) { + const nextSeries = series.find((item) => item.seriesId === nextSeriesId); + const nextHasGames = competition.projection.games.some( + (game) => game.seriesId === nextSeries?.seriesId, + ); + setSelectedSeriesId(nextSeriesId); + setWinnerTeamId(""); + setAdjudicationType(nextHasGames ? "forfeit" : "walkover"); + setAdjudicationReason(""); + setReversalMode("strict"); + setReversalReason(""); + setReversalPreview(null); + setImpactConfirmed(false); + adjudicationIdempotencyKeyRef.current = null; + reversalIdempotencyKeyRef.current = null; + resetCommandFeedback(); + } + + function handleAdjudicationSubmit(event: React.FormEvent) { + event.preventDefault(); + if (!selectedSeries || !canAdjudicate || !adjudicationReason.trim()) { + return; + } + if ( + effectiveAdjudicationType !== "administrative-draw" && + !effectiveWinnerTeamId + ) { + return; + } + + const decision: SeriesAdjudicationDecision = + effectiveAdjudicationType === "administrative-draw" + ? { type: "administrative-draw" } + : { + type: effectiveAdjudicationType, + winnerTeamId: effectiveWinnerTeamId as TeamId, + }; + const idempotencyKey = + adjudicationIdempotencyKeyRef.current ?? + `adjudicate:${selectedSeries.seriesId}:${crypto.randomUUID()}`; + adjudicationIdempotencyKeyRef.current = idempotencyKey; + resetCommandFeedback(); + adjudicationMutation.mutate( + { + matchId: String(competition.matchId), + seriesId: selectedSeries.seriesId, + revision: competition.revision, + idempotencyKey, + request: { + decision, + reason: adjudicationReason.trim(), + }, + }, + { + onSuccess: async (response) => { + adjudicationIdempotencyKeyRef.current = null; + setNotice("Series 판정을 기록했습니다."); + setAdjudicationReason(""); + await invalidateCompetitionCaches(response); + }, + }, + ); + } + + function handlePreviewSubmit(event: React.FormEvent) { + event.preventDefault(); + if (!selectedSeries || !canReverse || !reversalReason.trim()) return; + + resetCommandFeedback(); + setReversalPreview(null); + setImpactConfirmed(false); + previewMutation.mutate( + { + matchId: String(competition.matchId), + seriesId: selectedSeries.seriesId, + revision: competition.revision, + request: { + mode: reversalMode, + reason: reversalReason.trim(), + }, + }, + { + onSuccess: (preview) => { + reversalIdempotencyKeyRef.current = null; + setReversalPreview(preview); + setImpactConfirmed(false); + }, + }, + ); + } + + function handleReverse() { + if ( + !selectedSeries || + !reversalPreview || + !previewIsCurrent || + !impactConfirmed || + !reversalReason.trim() + ) { + return; + } + + const idempotencyKey = + reversalIdempotencyKeyRef.current ?? + `reverse:${selectedSeries.seriesId}:${crypto.randomUUID()}`; + reversalIdempotencyKeyRef.current = idempotencyKey; + resetCommandFeedback(); + reversalMutation.mutate( + { + matchId: String(competition.matchId), + seriesId: selectedSeries.seriesId, + revision: reversalPreview.sourceRevision, + idempotencyKey, + request: { + mode: reversalMode, + reason: reversalReason.trim(), + impactHash: reversalPreview.impactHash, + }, + }, + { + onSuccess: async (response) => { + reversalIdempotencyKeyRef.current = null; + setNotice("Series 결과를 되돌렸습니다."); + setReversalPreview(null); + setImpactConfirmed(false); + setReversalReason(""); + await invalidateCompetitionCaches(response); + }, + }, + ); + } + + const commandError = + adjudicationMutation.error ?? + previewMutation.error ?? + reversalMutation.error; + const commandErrorCode = competitionCommandErrorCode(commandError); + const staleCommand = + (commandError instanceof ApiError && commandError.status === 412) || + commandErrorCode === "REVERSAL_PREVIEW_STALE"; + const commandPending = + adjudicationMutation.isPending || + previewMutation.isPending || + reversalMutation.isPending; + + return ( +
+
+
+

+ Owner / Admin +

+

+ 공식 결과 관리 +

+
+ + revision {competition.revision} + +
+ + + + {notice && ( +

+ {notice} +

+ )} + + {commandError && ( +
+

{competitionCommandErrorMessage(commandError)}

+ {staleCommand && ( + + )} +
+ )} + + {canAdjudicate ? ( +
+

Series 판정

+
+ + + {effectiveAdjudicationType !== "administrative-draw" && ( + + )} +
+ +