diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts new file mode 100644 index 00000000..8546bf22 --- /dev/null +++ b/apps/web/src/api/hooks.ts @@ -0,0 +1,762 @@ +import { InteractionStatus } from '@azure/msal-browser'; +import { useMsal } from '@azure/msal-react'; +import { useInfiniteQuery, useMutation, useQuery } from '@tanstack/react-query'; +import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config'; +import { apiFetch } from '../lib/api'; +import { + isMsalConfigured, + MSAL_API_SCOPE, + MSAL_SILENT_REDIRECT_URI, +} from '../lib/auth/msal.config'; +import type { + ApiAuction, + ApiAuctionHistoryEntry, + ApiChampionStatsResponse, + ApiCommunity, + ApiEnqueueRefreshResult, + ApiInternalMatchDetailResponse, + ApiInternalMatchListResponse, + ApiLeaderboardResponse, + LegacyImportJobsResponse, + LegacyImportMembersResponse, + LegacyMatchListResponse, + ApiMatch, + ApiRecentMatchesResponse, + ApiRecentSummaryResponse, + ApiTeamInsightsResponse, + ApiTournamentCode, + ApiUserInternalHistoryResponse, + ApiUserHistoryProfile, + DdragonManifest, + StartLegacyImportRequest, + StartLegacyImportResponse, + MatchStatus, + MatchMutationRequest, + MatchesResponse, + ManualTournamentResultCollectResponse, + MeResponse, + RiotQueueGroup, + RiotRankFilter, + RebuildLegacyMatchesResponse, + TournamentCodeBulkUploadResponse, + TournamentCodeListResponse, + TournamentCodeState, + TournamentCodeStatsResponse, + TournamentCodeUploadItem, +} from './types'; + +const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000; + +interface MatchesQueryOptions { + status?: MatchStatus; + limit?: number; +} + +export interface UserHistoryFilters { + queueGroup?: RiotQueueGroup; + rank?: RiotRankFilter; + seasonId?: string; + championId?: number; +} + +export interface CommunityInternalStatsFilters { + seasonId?: string; + from?: string; + to?: string; + championId?: number; + limit?: number; +} + +function createMatchesPath( + communityId: string, + options: MatchesQueryOptions = {}, +) { + const searchParams = new URLSearchParams(); + if (options.status) searchParams.set('status', options.status); + if (options.limit) searchParams.set('limit', String(options.limit)); + + const queryString = searchParams.toString(); + return `/communities/${communityId}/matches${queryString ? `?${queryString}` : ''}`; +} + +export function useCommunity(communityId = DEFAULT_COMMUNITY_ID) { + return useQuery({ + queryKey: ['community', communityId], + queryFn: () => + apiFetch(`/communities/${communityId}`, { auth: 'none' }), + enabled: Boolean(communityId), + }); +} + +export function useMatches( + options: MatchesQueryOptions, + communityId = DEFAULT_COMMUNITY_ID, +) { + return useQuery({ + queryKey: ['matches', communityId, options.status ?? null, options.limit ?? null], + queryFn: async () => { + const response = await apiFetch( + createMatchesPath(communityId, options), + { auth: 'none' }, + ); + return response.matches; + }, + enabled: Boolean(communityId), + }); +} + +export function useMatch(matchId: string | undefined, communityId = DEFAULT_COMMUNITY_ID) { + return useQuery({ + queryKey: ['match', communityId, matchId ?? null], + queryFn: () => + apiFetch(`/communities/${communityId}/matches/${matchId}`, { + auth: 'none', + }), + enabled: Boolean(communityId && matchId), + retry: false, + }); +} + +export function useAuction( + matchId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, + options: { refetchInterval?: number | false } = {}, +) { + return useQuery({ + queryKey: ['auction', communityId, matchId ?? null], + queryFn: () => + apiFetch( + `/communities/${communityId}/matches/${matchId}/auction`, + { auth: 'none' }, + ), + enabled: Boolean(communityId && matchId), + retry: false, + refetchInterval: options.refetchInterval, + }); +} + +export function useAuctionHistory( + matchId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, + options: { enabled?: boolean; refetchInterval?: number | false } = {}, +) { + return useQuery({ + queryKey: ['auction-history', communityId, matchId ?? null], + queryFn: () => + apiFetch( + `/communities/${communityId}/matches/${matchId}/auction/history`, + ), + enabled: Boolean(communityId && matchId && (options.enabled ?? true)), + retry: false, + refetchInterval: options.refetchInterval, + }); +} + +export function useUndoAuction(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: ({ + matchId, + sequence, + }: { + matchId: string; + sequence: number; + }) => + apiFetch( + `/communities/${communityId}/matches/${matchId}/auction/undo`, + { + method: 'POST', + body: JSON.stringify({ sequence }), + }, + ), + }); +} + +export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (body: MatchMutationRequest) => + apiFetch(`/communities/${communityId}/matches`, { + method: 'POST', + body: JSON.stringify(body), + }), + }); +} + +export function useUpdateMatch(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: ({ matchId, body }: { matchId: string; body: Partial }) => + apiFetch(`/communities/${communityId}/matches/${matchId}`, { + method: 'PATCH', + body: JSON.stringify(body), + }), + }); +} + +function createUserHistoryPath( + communityId: string, + userId: string, + resource: string, + filters: UserHistoryFilters = {}, + extra: Record = {}, +) { + const searchParams = new URLSearchParams(); + 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)); + for (const [key, value] of Object.entries(extra)) { + if (value !== null && value !== undefined && value !== '') { + searchParams.set(key, String(value)); + } + } + + const queryString = searchParams.toString(); + return `/communities/${communityId}/users/${userId}/${resource}${queryString ? `?${queryString}` : ''}`; +} + +export function useUserHistoryProfile( + userId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, +) { + return useQuery({ + queryKey: ['user-history-profile', communityId, userId ?? null], + queryFn: () => + apiFetch( + `/communities/${communityId}/users/${userId}/history-profile`, + { auth: 'none' }, + ), + enabled: Boolean(communityId && userId), + retry: false, + }); +} + +export function useChampionStats( + userId: string | undefined, + filters: UserHistoryFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: [ + 'user-champion-stats', + communityId, + userId ?? null, + filters.queueGroup ?? null, + filters.rank ?? null, + filters.seasonId ?? null, + ], + queryFn: () => + apiFetch( + createUserHistoryPath(communityId, userId ?? '', 'champion-stats', filters), + { auth: 'none' }, + ), + enabled: Boolean(communityId && userId && enabled), + }); +} + +export function useRecentSummary( + userId: string | undefined, + filters: UserHistoryFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: [ + 'user-recent-summary', + communityId, + userId ?? null, + filters.queueGroup ?? null, + filters.rank ?? null, + filters.seasonId ?? null, + filters.championId ?? null, + ], + queryFn: () => + apiFetch( + createUserHistoryPath(communityId, userId ?? '', 'recent-summary', filters), + { auth: 'none' }, + ), + enabled: Boolean(communityId && userId && enabled), + }); +} + +export function useRecentMatches( + userId: string | undefined, + filters: UserHistoryFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useInfiniteQuery({ + queryKey: [ + 'user-recent-matches', + communityId, + userId ?? null, + filters.queueGroup ?? null, + filters.rank ?? null, + filters.seasonId ?? null, + filters.championId ?? null, + ], + queryFn: ({ pageParam }) => + apiFetch( + createUserHistoryPath(communityId, userId ?? '', 'recent-matches', filters, { + cursor: pageParam, + limit: 10, + }), + { auth: 'none' }, + ), + initialPageParam: null as number | null, + getNextPageParam: (lastPage) => lastPage.nextCursor, + enabled: Boolean(communityId && userId && enabled), + }); +} + +function createCommunityInternalStatsPath( + communityId: string, + resource: string, + filters: CommunityInternalStatsFilters = {}, + extra: Record = {}, +) { + const searchParams = new URLSearchParams(); + 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.limit) searchParams.set('limit', String(filters.limit)); + for (const [key, value] of Object.entries(extra)) { + if (value !== null && value !== undefined && value !== '') { + searchParams.set(key, String(value)); + } + } + + const queryString = searchParams.toString(); + return `/communities/${communityId}/internal-stats/${resource}${queryString ? `?${queryString}` : ''}`; +} + +export function useCommunityInternalStatsMatches( + filters: CommunityInternalStatsFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useInfiniteQuery({ + queryKey: [ + 'community-internal-stats-matches', + communityId, + filters.seasonId ?? null, + filters.from ?? null, + filters.to ?? null, + filters.championId ?? null, + filters.limit ?? null, + ], + queryFn: ({ pageParam }) => + apiFetch( + createCommunityInternalStatsPath(communityId, 'matches', filters, { + cursor: pageParam, + }), + { auth: 'none' }, + ), + initialPageParam: null as number | null, + getNextPageParam: (lastPage) => lastPage.nextCursor, + enabled: Boolean(communityId && enabled), + }); +} + +export function useCommunityLeaderboard( + filters: CommunityInternalStatsFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: [ + 'community-internal-stats-leaderboard', + communityId, + filters.seasonId ?? null, + filters.from ?? null, + filters.to ?? null, + filters.championId ?? null, + ], + queryFn: () => + apiFetch( + createCommunityInternalStatsPath(communityId, 'leaderboard', filters), + { auth: 'none' }, + ), + enabled: Boolean(communityId && enabled), + }); +} + +export function useTeamInsights( + filters: CommunityInternalStatsFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: [ + 'community-internal-stats-team-insights', + communityId, + filters.seasonId ?? null, + filters.from ?? null, + filters.to ?? null, + filters.championId ?? null, + ], + queryFn: () => + apiFetch( + createCommunityInternalStatsPath(communityId, 'team-insights', filters), + { auth: 'none' }, + ), + enabled: Boolean(communityId && enabled), + }); +} + +export function useInternalMatchDetail( + matchId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, +) { + return useQuery({ + queryKey: ['community-internal-stats-match', communityId, matchId ?? null], + queryFn: () => + apiFetch( + `/communities/${communityId}/internal-stats/match/${matchId}`, + { auth: 'none' }, + ), + enabled: Boolean(communityId && matchId), + retry: false, + }); +} + +export function useUserInternalHistory( + userId: string | undefined, + filters: UserHistoryFilters, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useInfiniteQuery({ + queryKey: [ + 'user-internal-history', + communityId, + userId ?? null, + filters.seasonId ?? null, + filters.championId ?? null, + ], + queryFn: ({ pageParam }) => + apiFetch( + createUserHistoryPath(communityId, userId ?? '', 'internal-history', filters, { + cursor: pageParam, + limit: 10, + }), + { auth: 'none' }, + ), + initialPageParam: null as number | null, + getNextPageParam: (lastPage) => lastPage.nextCursor, + enabled: Boolean(communityId && userId && enabled), + }); +} + +export function useRefreshUserHistory( + userId: string | undefined, + communityId = DEFAULT_COMMUNITY_ID, +) { + return useMutation({ + mutationFn: (body: { + queueGroups: RiotQueueGroup[]; + priority: 'high' | 'low'; + }) => + apiFetch( + `/communities/${communityId}/users/${userId}/refresh`, + { + method: 'POST', + body: JSON.stringify(body), + }, + ), + }); +} + +export function useDdragonManifest(locale = 'ko_KR') { + return useQuery({ + queryKey: ['ddragon-manifest', locale], + queryFn: () => + apiFetch( + `/riot/ddragon/manifest?locale=${encodeURIComponent(locale)}`, + { auth: 'none' }, + ), + staleTime: DDRAGON_MANIFEST_STALE_MS, + gcTime: DDRAGON_MANIFEST_STALE_MS, + refetchOnMount: false, + refetchOnReconnect: false, + }); +} + +export function useTournamentCodeStats( + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: ['tournament-code-stats', communityId], + queryFn: () => + apiFetch( + `/communities/${communityId}/tournament-codes/stats`, + ), + enabled: Boolean(communityId && enabled), + refetchInterval: enabled ? 30_000 : false, + retry: false, + }); +} + +export function useTournamentCodes( + options: { state?: TournamentCodeState; limit?: number }, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: [ + 'tournament-codes', + communityId, + options.state ?? null, + options.limit ?? null, + ], + queryFn: () => { + const searchParams = new URLSearchParams(); + if (options.state) searchParams.set('state', options.state); + if (options.limit) searchParams.set('limit', String(options.limit)); + const queryString = searchParams.toString(); + return apiFetch( + `/communities/${communityId}/tournament-codes${queryString ? `?${queryString}` : ''}`, + ); + }, + enabled: Boolean(communityId && enabled), + refetchInterval: enabled ? 30_000 : false, + retry: false, + }); +} + +export function useBulkUploadTournamentCodes(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (codes: TournamentCodeUploadItem[]) => + apiFetch( + `/communities/${communityId}/tournament-codes`, + { + method: 'POST', + body: JSON.stringify({ codes }), + }, + ), + }); +} + +export function useRestoreTournamentCode(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (codeId: string) => + apiFetch( + `/communities/${communityId}/tournament-codes/${codeId}/release`, + { method: 'POST' }, + ), + }); +} + +export function useDeleteTournamentCode(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (codeId: string) => + apiFetch(`/communities/${communityId}/tournament-codes/${codeId}`, { + method: 'DELETE', + }), + }); +} + +export function usePollTournamentResult(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (matchId: string) => + apiFetch<{ + jobId: string; + matchId: string; + priority: 'high' | 'low'; + attempt: number; + expandedToAllPuuids: boolean; + }>(`/communities/${communityId}/matches/${matchId}/poll-tournament-result`, { + method: 'POST', + }), + }); +} + +export function useCollectTournamentResultByWindow( + communityId = DEFAULT_COMMUNITY_ID, +) { + return useMutation({ + mutationFn: (params: { + matchId: string; + startTime: string; + endTime: string; + }) => + apiFetch( + `/communities/${communityId}/matches/${params.matchId}/poll-tournament-result/collect-by-window`, + { + method: 'POST', + body: JSON.stringify({ + startTime: params.startTime, + endTime: params.endTime, + }), + }, + ), + }); +} + +export function useCollectTournamentResultByRiotMatch( + communityId = DEFAULT_COMMUNITY_ID, +) { + return useMutation({ + mutationFn: (params: { matchId: string; riotMatchId: string }) => + apiFetch( + `/communities/${communityId}/matches/${params.matchId}/poll-tournament-result/collect-by-riot-match`, + { + method: 'POST', + body: JSON.stringify({ riotMatchId: params.riotMatchId }), + }, + ), + }); +} + +export function useLegacyImportMembers( + options: { windowStart?: string; windowEnd?: string }, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: [ + 'legacy-import-members', + communityId, + options.windowStart ?? null, + options.windowEnd ?? null, + ], + queryFn: () => { + const searchParams = new URLSearchParams(); + if (options.windowStart) searchParams.set('windowStart', options.windowStart); + if (options.windowEnd) searchParams.set('windowEnd', options.windowEnd); + const queryString = searchParams.toString(); + return apiFetch( + `/communities/${communityId}/legacy-import/members${queryString ? `?${queryString}` : ''}`, + ); + }, + enabled: Boolean(communityId && enabled), + }); +} + +export function useLegacyImportJobs( + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: ['legacy-import-jobs', communityId], + queryFn: () => + apiFetch( + `/communities/${communityId}/legacy-import-jobs?limit=10`, + ), + enabled: Boolean(communityId && enabled), + refetchInterval: (query) => + query.state.data?.jobs.some( + (job) => job.state === 'pending' || job.state === 'running', + ) + ? 5_000 + : false, + }); +} + +export function useStartLegacyImport(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (body: StartLegacyImportRequest) => + apiFetch( + `/communities/${communityId}/legacy-import`, + { + method: 'POST', + body: JSON.stringify(body), + }, + ), + }); +} + +export function useCancelLegacyImport(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (jobId: string) => + apiFetch( + `/communities/${communityId}/legacy-import-jobs/${jobId}/cancel`, + { method: 'POST' }, + ), + }); +} + +export function useLegacyMatches( + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useInfiniteQuery({ + queryKey: ['legacy-matches', communityId], + queryFn: ({ pageParam }) => { + const searchParams = new URLSearchParams({ limit: '50' }); + if (pageParam) searchParams.set('cursor', String(pageParam)); + return apiFetch( + `/communities/${communityId}/legacy-matches?${searchParams.toString()}`, + ); + }, + initialPageParam: null as number | null, + getNextPageParam: (lastPage) => lastPage.nextCursor, + enabled: Boolean(communityId && enabled), + }); +} + +export function useDeleteMatch(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (matchId: string) => + apiFetch(`/communities/${communityId}/matches/${matchId}`, { + method: 'DELETE', + }), + }); +} + +export function useBulkDeleteLegacyMatches(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (matchIds: string[]) => + apiFetch<{ deleted: number }>( + `/communities/${communityId}/legacy-matches/bulk-delete`, + { + method: 'POST', + body: JSON.stringify({ matchIds }), + }, + ), + }); +} + +export function useRebuildLegacyMatches(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: () => + apiFetch( + `/communities/${communityId}/legacy-matches/rebuild`, + { method: 'POST' }, + ), + }); +} + +export function useMe() { + const authUserId = useAuthUserId(); + const { accounts, inProgress, instance } = useMsal(); + const account = isMsalConfigured + ? (instance.getActiveAccount() ?? accounts[0] ?? null) + : null; + const accountKey = account?.homeAccountId ?? null; + const isMsalReady = + !isMsalConfigured || inProgress === InteractionStatus.None; + + return useQuery({ + queryKey: ['me', authUserId, accountKey], + queryFn: async () => { + if (!account) { + return apiFetch('/me'); + } + + const response = await instance.acquireTokenSilent({ + account, + scopes: [MSAL_API_SCOPE], + redirectUri: MSAL_SILENT_REDIRECT_URI, + }); + return apiFetch('/me', { + headers: { + Authorization: `Bearer ${response.accessToken}`, + }, + }); + }, + enabled: Boolean(authUserId || isMsalReady), + retry: false, + }); +} diff --git a/apps/web/src/api/mappers.ts b/apps/web/src/api/mappers.ts new file mode 100644 index 00000000..3cb9c491 --- /dev/null +++ b/apps/web/src/api/mappers.ts @@ -0,0 +1,528 @@ +import type { + ApiAuction, + ApiAuctionPlayerSnapshot, + ApiAuctionTeam, + ApiMatch, + ApiMatchParticipant, + ApiPositionPreference, + ApiRiotLaneStats, + ApiRiotRecentStatsSummary, + ApiTierInfo, + MatchStatus, + Position, + RiotLane, + TournamentCodeSlotView, +} from "./types"; +import { POSITION_ORDER, teamIndexLabel } from "../lib/league"; + +export interface ParticipantView { + id: string; + userId: string; + summonerName: string; + tag: string; + tier?: ApiTierInfo; + mainPosition: Position; + subPosition: Position; + profileIconId: number; + excluded?: boolean; +} + +export interface TeamParticipantView extends ParticipantView { + assignedPosition: Position; + cost?: number; +} + +export interface TeamView { + teamIndex: number; + name: string; + participants: TeamParticipantView[]; +} + +export interface MatchDetailView { + id: string; + title: string; + date: string; + time: string; + status: MatchStatus; + description: string; + map: string; + maxParticipants: number; + gameCount: number; + gameMode: ApiMatch["gameMode"]; + tournamentCodes: TournamentCodeSlotView[]; + joined: boolean; + participants: ParticipantView[]; + teams: TeamView[]; + result?: { + winner?: string; + winnerTeamIndex?: number; + riotMatchIds: string[]; + games: Array<{ + gameNumber: number; + 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 }[]; +} + +export interface AuctionPlayerView extends ParticipantView { + passCount: number; + masteries: { + championId: number; + level: number; + points: number; + }[]; + recentStats: { + overall: ApiRiotLaneStats; + byLane: Partial>; + primary: ApiRiotLaneStats | null; + primarySource: "lane" | "overall" | "none"; + }; +} + +export interface AuctionTeamView { + teamIndex: number; + name: string; + captainUserId: string; + captainName: string; + points: number; + members: (AuctionPlayerView & { + assignedPosition: Position; + cost: number; + })[]; +} + +export interface AuctionStateView { + matchId: string; + phase: ApiAuction["phase"]; + teams: AuctionTeamView[]; + currentPlayer: AuctionPlayerView | null; + currentPlayerIndex: number; + totalPlayers: number; + auctionOrder: AuctionPlayerView[]; + passedQueue: AuctionPlayerView[]; + auctionRound: number; + bids: { + teamIndex: number; + amount: number; + timestamp: string; + }[]; + currentBid: number; + currentBidder: { teamIndex: number } | null; + timer: number; + maxTimer: number; + bidExtensionSeconds: number; + deadline?: string; +} + +const MAP_LABELS: Record = { + 11: "소환사의 협곡", + 12: "칼바람 나락", + 21: "소환사의 협곡", + 22: "전략적 팀 전투", +}; + +const TIER_NAMES: Record = { + IRON: "아이언", + BRONZE: "브론즈", + SILVER: "실버", + GOLD: "골드", + PLATINUM: "플래티넘", + EMERALD: "에메랄드", + DIAMOND: "다이아", + MASTER: "마스터", + GRANDMASTER: "그랜드마스터", + CHALLENGER: "챌린저", +}; + +const POSITION_TO_RIOT_LANE: Record = { + TOP: "TOP", + JGL: "JUNGLE", + MID: "MIDDLE", + ADC: "BOTTOM", + SUP: "UTILITY", +}; + +function createEmptyLaneStats(): ApiRiotLaneStats { + return { + games: 0, + wins: 0, + losses: 0, + avgKills: 0, + avgDeaths: 0, + avgAssists: 0, + avgCs: 0, + avgCsPerMin: 0, + mostPlayedChampionIds: [], + }; +} + +function createEmptyRecentStatsView(): AuctionPlayerView["recentStats"] { + return { + overall: createEmptyLaneStats(), + byLane: {}, + primary: null, + primarySource: "none", + }; +} + +function sortPreferredPositions(preferredPositions: ApiPositionPreference[]) { + return [...preferredPositions].sort( + (left, right) => left.priority - right.priority, + ); +} + +function resolveMainAndSubPosition( + preferredPositions: ApiPositionPreference[], +) { + const sorted = sortPreferredPositions(preferredPositions); + return { + mainPosition: sorted[0]?.position ?? "MID", + subPosition: sorted[1]?.position ?? sorted[0]?.position ?? "MID", + }; +} + +function mapMatchParticipantToView( + participant: ApiMatchParticipant, +): ParticipantView { + const { mainPosition, subPosition } = resolveMainAndSubPosition( + participant.preferredPositions, + ); + + return { + id: participant.userId, + userId: participant.userId, + summonerName: participant.gameName ?? "알 수 없음", + tag: participant.tagLine ?? "----", + tier: participant.tier, + mainPosition, + subPosition, + profileIconId: participant.profileIconId ?? 0, + excluded: participant.excluded ?? false, + }; +} + +function mapAuctionPlayerToView( + player: ApiAuctionPlayerSnapshot, +): AuctionPlayerView { + const { mainPosition, subPosition } = resolveMainAndSubPosition( + player.preferredPositions, + ); + const summary = player.recentStatsSummary; + const primary = pickPrimary(summary, mainPosition); + + return { + id: player.userId, + userId: player.userId, + summonerName: player.gameName, + tag: player.tagLine, + tier: selectPrimaryTier(player.tiers), + mainPosition, + subPosition, + profileIconId: player.profileIconId, + passCount: player.passCount ?? 0, + masteries: player.masteries.slice(0, 5).map((mastery) => ({ + championId: mastery.championId, + level: mastery.championLevel, + points: mastery.championPoints, + })), + recentStats: { + overall: summary?.overall ?? createEmptyLaneStats(), + byLane: summary?.byLane ?? {}, + primary: primary.stats, + primarySource: primary.source, + }, + }; +} + +function createFallbackParticipant(userId: string): ParticipantView { + return { + id: userId, + userId, + summonerName: `User ${userId.slice(-4)}`, + tag: "----", + mainPosition: "MID", + subPosition: "MID", + profileIconId: 0, + }; +} + +function mapAuctionTeamToView( + team: ApiAuctionTeam, + playerLookup: Map, + participantLookup: Map, +): AuctionTeamView { + return { + teamIndex: team.teamIndex, + name: teamIndexLabel(team.teamIndex), + captainUserId: team.captainUserId, + captainName: + participantLookup.get(team.captainUserId)?.summonerName ?? + `User ${team.captainUserId.slice(-4)}`, + points: team.points, + members: team.members.map((member) => { + const participant = participantLookup.get(member.userId); + const player = + playerLookup.get(member.userId) ?? + (participant + ? { + ...participant, + passCount: 0, + masteries: [], + recentStats: createEmptyRecentStatsView(), + } + : { + ...createFallbackParticipant(member.userId), + passCount: 0, + masteries: [], + recentStats: createEmptyRecentStatsView(), + }); + + return { + ...player, + assignedPosition: member.assignedPosition, + cost: member.cost, + }; + }), + }; +} + +export function mapIdToLabel(mapId: number) { + return MAP_LABELS[mapId] ?? `맵 #${mapId}`; +} + +export function formatKoreanDate(dateLike: string | Date) { + const date = new Date(dateLike); + + return { + date: new Intl.DateTimeFormat("ko-KR", { + year: "numeric", + month: "long", + day: "numeric", + weekday: "short", + }).format(date), + time: new Intl.DateTimeFormat("ko-KR", { + hour: "numeric", + minute: "2-digit", + }).format(date), + }; +} + +function pickPrimary( + summary: ApiRiotRecentStatsSummary | undefined, + mainPosition: Position, +): { + stats: ApiRiotLaneStats | null; + source: "lane" | "overall" | "none"; +} { + if (!summary) { + return { stats: null, source: "none" }; + } + + const laneStats = summary.byLane[POSITION_TO_RIOT_LANE[mainPosition]]; + if (laneStats && laneStats.games > 0) { + return { stats: laneStats, source: "lane" }; + } + + if (summary.overall.games > 0) { + return { stats: summary.overall, source: "overall" }; + } + + return { stats: null, source: "none" }; +} + +export function selectPrimaryTier(tiers: ApiTierInfo[]) { + return tiers.find((tier) => tier.queueType === "RANKED_SOLO_5x5") ?? tiers[0]; +} + +export function formatTierLabel(tier?: ApiTierInfo) { + if (!tier) return "미등록"; + + const tierName = TIER_NAMES[tier.tier] ?? tier.tier; + const highTier = ["MASTER", "GRANDMASTER", "CHALLENGER"].includes(tier.tier); + + if (highTier && tier.leaguePoints > 0) { + return `${tierName} ${tier.leaguePoints}LP`; + } + + return tier.rank ? `${tierName} ${tier.rank}` : tierName; +} + +export function getTierColorToken(tier?: ApiTierInfo) { + switch (tier?.tier) { + case "CHALLENGER": + return "text-amber-400"; + case "GRANDMASTER": + return "text-red-400"; + case "MASTER": + return "text-fuchsia-400"; + case "DIAMOND": + return "text-cyan-400"; + case "EMERALD": + return "text-emerald-400"; + case "PLATINUM": + return "text-teal-300"; + case "GOLD": + return "text-yellow-400"; + case "SILVER": + return "text-gray-300"; + case "BRONZE": + return "text-amber-700"; + case "IRON": + return "text-stone-400"; + default: + return "text-base-content/50"; + } +} + +export function buildDefaultPreferredPositions() { + return POSITION_ORDER.map((position, index) => ({ + position, + priority: index + 1, + })); +} + +export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { + const formattedDate = formatKoreanDate(match.scheduledAt); + const participants = match.participants.map(mapMatchParticipantToView); + const participantLookup = new Map( + participants.map((participant) => [participant.userId, participant]), + ); + + const teams = match.teams.map((team) => ({ + teamIndex: team.teamIndex, + name: teamIndexLabel(team.teamIndex, team.name), + participants: team.members.map((member) => { + const participant = + participantLookup.get(member.userId) ?? + createFallbackParticipant(member.userId); + + return { + ...participant, + assignedPosition: member.assignedPosition, + cost: member.cost, + }; + }), + })); + + const winnerTeam = match.result?.winnerTeamIndex + ? teams.find((team) => team.teamIndex === match.result?.winnerTeamIndex) + : undefined; + + return { + id: match._id, + title: match.title, + date: formattedDate.date, + time: formattedDate.time, + status: match.status, + description: match.description, + map: mapIdToLabel(match.mapId), + maxParticipants: match.maxParticipants, + gameCount: match.gameCount ?? 3, + gameMode: match.gameMode ?? "pair", + 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, + }; +} + +export function mapApiAuctionToAuctionState( + auction: ApiAuction, + match: ApiMatch, + now = new Date(), +): AuctionStateView { + const participantLookup = new Map( + match.participants + .map(mapMatchParticipantToView) + .map((participant) => [participant.userId, participant]), + ); + const auctionOrder = auction.order.map(mapAuctionPlayerToView); + const passedQueue = (auction.passedQueue ?? []).map(mapAuctionPlayerToView); + const auctionPlayerLookup = new Map( + auctionOrder.map((player) => [player.userId, player]), + ); + const teams = [...auction.teams].sort( + (left, right) => left.teamIndex - right.teamIndex, + ); + + const totalPlayers = auctionOrder.length; + const currentPlayer = + auction.phase === "complete" + ? null + : (auctionPlayerLookup.get( + auction.order[auction.currentIndex]?.userId ?? "", + ) ?? null); + const currentPlayerIndex = + auction.phase === "complete" ? totalPlayers : auction.currentIndex; + const timer = auction.currentDeadline + ? Math.max( + 0, + Math.ceil( + (new Date(auction.currentDeadline).getTime() - now.getTime()) / 1000, + ), + ) + : 0; + + return { + matchId: auction.matchId, + phase: auction.phase, + teams: teams.map((team) => + mapAuctionTeamToView(team, auctionPlayerLookup, participantLookup), + ), + currentPlayer, + currentPlayerIndex, + totalPlayers, + auctionOrder, + passedQueue, + auctionRound: auction.auctionRound ?? 1, + bids: auction.bids.map((bid) => ({ + teamIndex: bid.teamIndex, + amount: bid.amount, + timestamp: bid.timestamp, + })), + currentBid: auction.currentBid, + currentBidder: auction.currentBidderTeamIndex + ? { + teamIndex: auction.currentBidderTeamIndex, + } + : null, + timer, + maxTimer: auction.maxTimerSeconds, + bidExtensionSeconds: auction.bidExtensionSeconds ?? 5, + deadline: auction.currentDeadline, + }; +} diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts new file mode 100644 index 00000000..e349c1c9 --- /dev/null +++ b/apps/web/src/api/types.ts @@ -0,0 +1,853 @@ +export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; +export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY'; +export type TeamSide = 'blue' | 'red'; +export type MatchGameMode = 'pair' | 'bracket' | 'round-robin'; +export type MatchStatus = + | 'recruiting' + | 'team-built' + | 'in-progress' + | 'finished'; +export type AuctionPhase = + | 'waiting' + | 'presenting' + | 'bidding' + | 'sold' + | 'passed' + | 'complete'; +export type AuctionTopTierThreshold = + | 'NONE' + | 'EMERALD' + | 'DIAMOND' + | 'MASTER' + | 'MANUAL'; +export type CommunityRole = 'owner' | 'admin' | 'member'; + +export interface ApiPositionPreference { + position: Position; + priority: number; +} + +export interface ApiTierInfo { + queueType: string; + tier: string; + rank: string; + leaguePoints: number; + wins: number; + losses: number; + fetchedAt: string; +} + +export interface ApiChampionMasteryEntry { + puuid?: string; + championId: number; + championLevel: number; + championPoints: number; + lastPlayTime?: number; + championPointsSinceLastLevel?: number; + championPointsUntilNextLevel?: number; + markRequiredForNextLevel?: number; + tokensEarned?: number; + championSeasonMilestone?: number; + milestoneGrades?: string[]; + nextSeasonMilestone?: Record; +} + +export interface ApiRiotLaneStats { + games: number; + wins: number; + losses: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + avgCs: number; + avgCsPerMin: number; + mostPlayedChampionIds: number[]; +} + +export interface ApiRiotRecentStatsSummary { + overall: ApiRiotLaneStats; + byLane: Partial>; +} + +export interface ApiRiotAccount { + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + revisionDate: number; + summonerLevel: number; + isPrimary: boolean; + tiers: ApiTierInfo[]; + tierHistory: unknown[]; + matchIds: string[]; + championMasteries: ApiChampionMasteryEntry[]; + championRecords: Record>; + recentStatsSummary?: ApiRiotRecentStatsSummary; + createdAt: string; + updatedAt: string; +} + +export interface ApiUser { + _id: string; + communityId: string; + identityId?: string; + role: CommunityRole; + kakaoTalkId?: string; + kakaoTalkNickname?: string; + discordId?: string; + discordNickname?: string; + riotAccounts: ApiRiotAccount[]; + preferredPositions: ApiPositionPreference[]; + isActivated: boolean; + createdAt: string; + updatedAt: string; +} + +export interface ApiCommunity { + _id: string; + name: string; + description: string; + ownerUserId: string; + matchGameCount?: number; + createdAt: string; + updatedAt: string; +} + +export type TournamentCodeState = + | 'available' + | 'reserved' + | 'used' + | 'expired' + | 'released'; + +export type TournamentCodeSlotState = TournamentCodeState | 'pending'; + +export interface TournamentCodeSlotView { + gameNumber: number; + teamAIndex: number; + teamBIndex: number; + code: string | null; + expiresAt: string | null; + state: TournamentCodeSlotState; + riotMatchId: string | null; +} + +export interface ApiMatchParticipant { + userId: string; + puuid?: string; + gameName?: string; + tagLine?: string; + profileIconId?: number; + tier?: ApiTierInfo; + preferredPositions: ApiPositionPreference[]; + joinedAt: string; + excluded?: boolean; +} + +export interface ApiMatchTeamMember { + userId: string; + assignedPosition: Position; + cost?: number; +} + +export interface ApiMatchTeam { + teamIndex: number; + name: string; + captainUserId?: string; + 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; + 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<{ + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; + winnerTeamIndex?: number; + }>; +} + +export interface ApiMatchScheduleItem { + time: string; + label: string; +} + +export interface ApiMatchGameAssignment { + gameNumber: number; + teamAIndex: number; + teamBIndex: number; +} + +export interface ManualTournamentResultCollectResponse { + scanned: number; + matched: number; + skipped: number; + riotMatchIds: string[]; + gameNumbers: number[]; +} + +export interface ApiMatch { + _id: string; + communityId: string; + shortCode?: string; + title: string; + description: string; + mapId: number; + status: MatchStatus; + scheduledAt: string; + maxParticipants: number; + gameCount: number; + gameMode: MatchGameMode; + gameSchedule?: ApiMatchGameAssignment[]; + tournamentCodes?: TournamentCodeSlotView[]; + hostUserId?: string; + participants: ApiMatchParticipant[]; + teams: ApiMatchTeam[]; + result?: ApiMatchResult; + prizes: string[]; + notices: string[]; + schedule: ApiMatchScheduleItem[]; + joined?: boolean; + createdAt: string; + updatedAt: string; +} + +export interface ApiAuctionPlayerSnapshot { + userId: string; + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + preferredPositions: ApiPositionPreference[]; + tiers: ApiTierInfo[]; + masteries: ApiChampionMasteryEntry[]; + recentStatsSummary?: ApiRiotRecentStatsSummary; + passCount: number; +} + +export interface ApiAuctionTeamMember { + userId: string; + assignedPosition: Position; + cost: number; +} + +export interface ApiAuctionTeam { + teamIndex: number; + captainUserId: string; + points: number; + members: ApiAuctionTeamMember[]; +} + +export interface ApiAuctionBid { + teamIndex: number; + amount: number; + bidderUserId: string; + timestamp: string; +} + +export interface ApiAuction { + _id: string; + matchId: string; + phase: AuctionPhase; + teams: ApiAuctionTeam[]; + order: ApiAuctionPlayerSnapshot[]; + passedQueue: ApiAuctionPlayerSnapshot[]; + auctionRound: number; + currentIndex: number; + bids: ApiAuctionBid[]; + currentBid: number; + currentBidderTeamIndex?: number; + maxTimerSeconds: number; + bidExtensionSeconds: number; + currentDeadline?: string; + initialPoints: number; + topTierThreshold: AuctionTopTierThreshold; + manualTopTierUserIds: string[]; + startedAt?: string; + completedAt?: string; + createdAt: string; + updatedAt: string; +} + +export interface ApiAuctionHistoryEntry { + sequence: number; + action: + | 'start' + | 'open-bidding' + | 'bid' + | 'sold' + | 'passed' + | 'next' + | 'complete'; + actionLabel: string; + takenAt: string; +} + +export interface ApiIdentity { + id: string; + entraOid: string; + tenantId?: string; + email?: string; + displayName?: string; +} + +export interface ApiMembership { + user: ApiUser; + community: ApiCommunity | null; +} + +export interface MeResponse { + identity: ApiIdentity | null; + memberships: ApiMembership[]; +} + +export interface MatchesResponse { + matches: ApiMatch[]; +} + +export interface MatchMutationRequest { + title: string; + description?: string; + mapId?: number; + scheduledAt: string; + maxParticipants?: number; + gameCount?: number; + gameMode?: MatchGameMode; + prizes?: string[]; + notices?: string[]; + schedule?: ApiMatchScheduleItem[]; +} + +export interface DdragonChampionEntry { + key: string; + name: string; +} + +export interface DdragonSummonerSpellEntry { + key: string; + name: string; +} + +export interface DdragonRuneEntry { + id: number; + key: string; + icon: string; + name: string; +} + +export interface DdragonRuneStyleEntry extends DdragonRuneEntry { + slots: Array<{ runes: DdragonRuneEntry[] }>; +} + +export interface DdragonManifest { + version: string; + cdn: string; + locale: string; + champions: Record; + summonerSpells: Record; + runesReforged: DdragonRuneStyleEntry[]; + fetchedAt: string; +} + +export type TournamentSpectatorType = 'NONE' | 'LOBBYONLY' | 'ALL'; + +export interface ApiTournamentCode { + _id: string; + code: string; + region: string; + mapType: 'SUMMONERS_RIFT'; + teamSize: number; + spectatorType: TournamentSpectatorType; + metadata?: Record; + expiresAt: string; + state: TournamentCodeState; + matchId?: string; + gameNumber?: number; + reservedAt?: string; + usedAt?: string; + releasedAt?: string; + riotMatchId?: string; + uploadedBy: string; + uploadedAt: string; + source?: string; + notes?: string; + createdAt: string; + updatedAt: string; +} + +export interface TournamentCodeStatsResponse { + byState: Record; + expiringSoon: number; + available: number; +} + +export interface TournamentCodeListResponse { + codes: ApiTournamentCode[]; +} + +export interface TournamentCodeUploadItem { + code: string; + expiresAt: string; + spectatorType?: TournamentSpectatorType; + metadata?: Record; + source?: string; + notes?: string; +} + +export interface TournamentCodeBulkUploadResponse { + inserted: number; + duplicates: string[]; + invalid: Array<{ code: string; reason: string }>; +} + +export type RiotQueueGroup = + | 'all' + | 'summoners-rift' + | 'aram' + | 'urf' + | 'arena' + | 'internal'; +export type RiotRankFilter = 'all' | 'solo' | 'flex' | 'normal'; + +export interface ApiHistorySeason { + id: string; + label: string; + startedAt: string | null; + endedAt: string | null; +} + +export interface ApiUserHistoryProfile { + userId: string; + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + summonerLevel: number; + tiers: ApiTierInfo[]; + season: ApiHistorySeason; + seasons: ApiHistorySeason[]; + lastFetchedAt: string | null; +} + +export interface ApiChampionStatsRow { + championId: number; + games: number; + wins: number; + losses: number; + winRate: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + kda: number; + totalKills: number; + totalDeaths: number; + totalAssists: number; + doubleKills: number; + tripleKills: number; + quadraKills: number; + pentaKills: number; + avgCs: number; + avgCsPerMin: number; +} + +export interface ApiChampionStatsResponse { + queueGroup: RiotQueueGroup; + rank: RiotRankFilter; + queueIds: number[]; + season: ApiHistorySeason; + lastFetchedAt: string | null; + champions: ApiChampionStatsRow[]; + totals: ApiChampionStatsRow; +} + +export interface ApiRecentSummaryResponse { + windowSize: number; + winRate: number; + wins: number; + losses: number; + streak: { type: 'win' | 'loss'; count: number } | null; + kda: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + bestRating: { + rating: number | 'Perfect'; + kills: number; + deaths: number; + assists: number; + matchId: string; + } | null; + positionRates: Partial>; + topChampions: Array<{ + championId: number; + games: number; + winRate: number; + pickRate: number; + avgRating: number; + }>; + lastFetchedAt: string | null; +} + +export interface ApiRecentMatchTeamParticipant { + puuid: string; + gameName: string; + tagLine: string; + championId: number; + championLevel: number; + teamPosition: string; + kills: number; + deaths: number; + assists: number; + items: number[]; + trinket: number; + summonerSpells: [number, number]; + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + totalCs: number; + csPerMin: number; + goldEarned: number; + damageDealtToChampions: number; + damageTaken: number; + visionScore: number; + wardsPlaced: number; + wardsKilled: number; + controlWardsBought: number; +} + +export interface ApiRecentMatchTeam { + side: 100 | 200; + win: boolean; + objectives?: { baron?: number; dragon?: number; tower?: number }; + participants: ApiRecentMatchTeamParticipant[]; +} + +export interface ApiRecentMatchView { + matchId: string; + queueId: number; + queueLabel: string; + gameCreation: number; + gameDuration: number; + win: boolean; + remake: boolean; + championId: number; + championLevel: number; + teamPosition: string; + kills: number; + deaths: number; + assists: number; + kda: number; + rating: number; + totalCs: number; + csPerMin: number; + killParticipation: number; + visionScore: number; + controlWardsBought: number; + wardsPlaced: number; + wardsKilled: number; + damageDealtToChampions: number; + damageTaken: number; + goldEarned: number; + items: number[]; + trinket: number; + summonerSpells: [number, number]; + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + teams: ApiRecentMatchTeam[]; +} + +export interface ApiRecentMatchesResponse { + matches: ApiRecentMatchView[]; + nextCursor: number | null; + lastFetchedAt: string | null; + season: ApiHistorySeason; +} + +export interface ApiInternalMatchCard { + matchId: string; + title: string; + scheduledAt: string; + status: 'finished' | 'in-progress'; + gameCount: number; + winnerTeamIndex?: number; + seriesResults: Array<{ + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; + winnerTeamIndex?: number; + }>; + games: Array<{ + gameNumber: number; + riotMatchId: string | null; + blueTeamIndex: number; + redTeamIndex: number; + winnerTeamIndex: number | null; + winnerSide: TeamSide | null; + gameDuration: number; + }>; + teams: Array<{ + teamIndex: number; + name: string; + members: Array<{ + userId: string; + summonerName: string; + profileIconId: number; + }>; + }>; +} + +export interface ApiInternalMatchListResponse { + matches: ApiInternalMatchCard[]; + nextCursor: number | null; + season: ApiHistorySeason; +} + +export interface ApiLeaderboardRow { + userId: string; + summonerName: string; + profileIconId: number; + games: number; + wins: number; + losses: number; + winRate: number; + totalKills: number; + totalDeaths: number; + totalAssists: number; + kda: number; + avgGoldPerMin: number; + avgKillParticipation: number; + avgCsPerMin: number; + avgDamageShare: number; + avgVisionScore: number; + byLane: Partial>; + topChampions: Array<{ championId: number; games: number; winRate: number }>; +} + +export interface ApiLeaderboardResponse { + rows: ApiLeaderboardRow[]; + season: ApiHistorySeason; +} + +export interface ApiLeaderHighlight { + metric: number; + userId: string; + summonerName: string; + championId?: number; + matchId?: string; + isSingleGame: boolean; +} + +export interface ApiTeamInsightsResponse { + season: ApiHistorySeason; + sideWinRate: { + blue: number; + red: number; + bluePicks: number; + redPicks: number; + }; + topKda: ApiLeaderHighlight | null; + mostKills: ApiLeaderHighlight | null; + topTeamGpm: ApiLeaderHighlight | null; + topKillParticipation: ApiLeaderHighlight | null; + bestFarm: ApiLeaderHighlight | null; + minGamesThreshold: number; +} + +export interface ApiInternalMatchDetailResponse { + match: ApiInternalMatchCard; + games: Array<{ + gameNumber: number; + riotMatchId: string; + gameCreation: number; + gameDuration: number; + teams: Array<{ + teamIndex: number; + side: TeamSide; + win: boolean; + objectives: { baron: number; dragon: number; tower: number }; + participants: Array<{ + userId: string | null; + summonerName: string; + teamIndex: number; + side: TeamSide; + teamPosition: string; + championId: number; + kills: number; + deaths: number; + assists: number; + cs: number; + csPerMin: number; + gold: number; + gpm: number; + damageDealtToChampions: number; + damageShare: number; + killParticipation: number; + visionScore: number; + items: number[]; + trinket: number; + summonerSpells: [number, number]; + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + win: boolean; + }>; + }>; + }>; +} + +export interface ApiUserInternalHistoryResponse { + season: ApiHistorySeason; + championStats: ApiChampionStatsResponse; + summary: ApiRecentSummaryResponse; + matches: ApiRecentMatchView[]; + nextCursor: number | null; + lastFetchedAt: string | null; +} + +export type LegacyImportJobState = + | 'pending' + | 'running' + | 'completed' + | 'failed' + | 'cancelled'; + +export interface LegacyImportMemberWindow { + userId: string; + puuid: string; + displayName: string; + gameName: string; + tagLine: string; + profileIconId: number; + isActivated: boolean; + startTime: string; + endTime: string; +} + +export interface LegacyImportMembersResponse { + members: LegacyImportMemberWindow[]; +} + +export interface StartLegacyImportRequest { + windowStart?: string; + windowEnd?: string; + memberOverrides?: Array<{ + userId: string; + startTime?: string; + endTime?: string; + }>; +} + +export interface StartLegacyImportResponse { + jobId: string; + totalMembers: number; + etaSeconds: number; +} + +export interface LegacyImportJob { + _id: string; + jobId: string; + communityId: string; + triggeredBy: string; + startedAt: string; + completedAt?: string; + state: LegacyImportJobState; + windowStart: string; + windowEnd: string; + memberOverrides: Array<{ + userId: string; + puuid: string; + startTime: string; + endTime: string; + }>; + totalMembers: number; + processedMembers: number; + totalDiscoveredMatchIds: number; + totalImportedMatches: number; + totalSkippedDuplicate: number; + totalErrors: number; + averageMemberSeconds?: number; + errors?: Array<{ + puuid?: string; + matchId?: string; + reason: string; + at: string; + }>; +} + +export interface LegacyImportJobsResponse { + jobs: LegacyImportJob[]; +} + +export interface LegacyMatchListItem { + matchId: string; + title: string; + scheduledAt: string; + riotMatchId: string | null; + memberCount: number; + externalCount: number; + teamAIndex: number; + teamBIndex: number; + teamAWins: number; + teamBWins: number; + winnerTeamIndex?: number; +} + +export interface LegacyMatchListResponse { + matches: LegacyMatchListItem[]; + nextCursor: number | null; +} + +export interface RebuildLegacyMatchesResponse { + scanned: number; + rebuilt: number; + normalizedTitles: number; + skippedMissingRaw: number; + skippedNoKnownParticipants: number; +} + +export type ApiRiotJobPriority = 'high' | 'low'; +export type ApiRiotJobState = 'queued' | 'processing' | 'completed' | 'failed'; + +export interface ApiEnqueueRefreshResult { + parentJobId: string; + subJobs: Array<{ + jobId: string; + queueGroup: RiotQueueGroup; + alreadyQueued: boolean; + etaSeconds: number; + queuePosition: number; + }>; + totalEtaSeconds: number; +} + +export interface ApiRiotRefreshEvent { + parentJobId: string; + jobId: string; + queueGroup: RiotQueueGroup; + puuid: string; + state: ApiRiotJobState; + error?: string; +} diff --git a/apps/web/src/api/useAuctionSocket.ts b/apps/web/src/api/useAuctionSocket.ts new file mode 100644 index 00000000..49cef7ed --- /dev/null +++ b/apps/web/src/api/useAuctionSocket.ts @@ -0,0 +1,121 @@ +import { useEffect, useRef, useState } from 'react'; +import { io, type Socket } from 'socket.io-client'; +import { API_BASE_URL, useAuthUserId } from '../config'; +import { acquireAccessToken } from '../lib/auth/token-provider'; +import type { ApiAuction, Position } from './types'; + +type ConnectionStatus = + | 'idle' + | 'connecting' + | 'connected' + | 'disconnected' + | 'error'; + +interface BidPayload { + teamIndex: number; + amount: number; + bidderUserId?: string; +} + +export function useAuctionSocket(matchId: string | undefined) { + const authUserId = useAuthUserId(); + const socketRef = useRef(null); + const [auction, setAuction] = useState(null); + const [connectionStatus, setConnectionStatus] = + useState('idle'); + const [error, setError] = useState(null); + + useEffect(() => { + if (!matchId) { + setAuction(null); + setConnectionStatus('idle'); + return; + } + + let disposed = false; + setConnectionStatus('connecting'); + setError(null); + + void (async () => { + const accessToken = await acquireAccessToken().catch((error) => { + console.warn('Failed to acquire socket access token:', error); + return null; + }); + if (disposed) return; + + const socket = io(`${API_BASE_URL}/auction`, { + transports: ['websocket'], + auth: accessToken + ? { token: accessToken } + : authUserId + ? { 'x-auth-user-id': authUserId } + : {}, + }); + + socketRef.current = socket; + + socket.on('connect', () => { + setConnectionStatus('connected'); + socket.emit('join', { matchId }); + }); + + socket.on('disconnect', () => { + setConnectionStatus('disconnected'); + }); + + socket.on('state', (nextAuction: ApiAuction) => { + setAuction(nextAuction); + setError(null); + }); + + socket.on('error', (payload: { message?: string }) => { + setConnectionStatus('error'); + setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.'); + }); + })(); + + return () => { + disposed = true; + const socket = socketRef.current; + socket?.removeAllListeners(); + socket?.disconnect(); + socketRef.current = null; + setConnectionStatus('idle'); + }; + }, [authUserId, matchId]); + + function emit(eventName: string, payload?: unknown) { + const socket = socketRef.current; + if (!socket || !socket.connected) { + setError('소켓이 아직 연결되지 않았습니다.'); + return; + } + + setError(null); + + if (payload === undefined) { + socket.emit(eventName); + return; + } + + socket.emit(eventName, payload); + } + + return { + auction, + connectionStatus, + error, + placeBid(payload: BidPayload) { + emit('bid', payload); + }, + openBidding() { + emit('open-bidding', {}); + }, + markSold(assignedPosition?: Position) { + emit('sold', assignedPosition ? { assignedPosition } : {}); + }, + next() { + emit('next', {}); + }, + }; +} diff --git a/apps/web/src/api/useRiotRefreshSocket.ts b/apps/web/src/api/useRiotRefreshSocket.ts new file mode 100644 index 00000000..c53aa443 --- /dev/null +++ b/apps/web/src/api/useRiotRefreshSocket.ts @@ -0,0 +1,73 @@ +import { useEffect, useRef, useState } from 'react'; +import { io, type Socket } from 'socket.io-client'; +import { API_BASE_URL } from '../config'; +import type { ApiRiotRefreshEvent } from './types'; + +type ConnectionStatus = + | 'idle' + | 'connecting' + | 'connected' + | 'disconnected' + | 'error'; + +export function useRiotRefreshSocket({ + puuid, + parentJobId, + onEvent, +}: { + puuid?: string; + parentJobId?: string; + onEvent: (event: ApiRiotRefreshEvent) => void; +}) { + const socketRef = useRef(null); + const onEventRef = useRef(onEvent); + const [connectionStatus, setConnectionStatus] = + useState('idle'); + const [error, setError] = useState(null); + + useEffect(() => { + onEventRef.current = onEvent; + }, [onEvent]); + + useEffect(() => { + if (!puuid && !parentJobId) { + setConnectionStatus('idle'); + return; + } + + setConnectionStatus('connecting'); + setError(null); + + const socket = io(`${API_BASE_URL}/riot-refresh`, { + transports: ['websocket'], + }); + socketRef.current = socket; + + socket.on('connect', () => { + setConnectionStatus('connected'); + socket.emit('subscribe', { puuid, parentJobId }); + }); + + socket.on('disconnect', () => { + setConnectionStatus('disconnected'); + }); + + socket.on('riot-refresh', (event: ApiRiotRefreshEvent) => { + onEventRef.current(event); + }); + + socket.on('error', (payload: { message?: string }) => { + setConnectionStatus('error'); + setError(payload.message ?? '전적 갱신 소켓 연결 중 오류가 발생했습니다.'); + }); + + return () => { + socket.removeAllListeners(); + socket.disconnect(); + socketRef.current = null; + setConnectionStatus('idle'); + }; + }, [parentJobId, puuid]); + + return { connectionStatus, error }; +} diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx new file mode 100644 index 00000000..0478e23f --- /dev/null +++ b/apps/web/src/pages/AuctionPage.tsx @@ -0,0 +1,1072 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { Link, useLocation, useParams } from 'react-router'; +import { + useAuction, + useAuctionHistory, + useDdragonManifest, + useMatch, + useMe, + useUndoAuction, +} from '../api/hooks'; +import { + mapApiAuctionToAuctionState, + type AuctionStateView, +} from '../api/mappers'; +import { useAuctionSocket } from '../api/useAuctionSocket'; +import { + DEFAULT_COMMUNITY_ID, + setDevCaptainTeamIndex, + useDevCaptainTeamIndex, +} from '../config'; +import { ApiError } from '../lib/api'; +import { + championDisplayName, + championIconUrl, + profileIconUrl, +} from '../lib/ddragon'; +import { + positionIcon, + positionLabel, + teamIndexColorClasses, + teamIndexLabel, +} from '../lib/league'; +import type { + ApiAuction, + ApiRiotLaneStats, + ApiTierInfo, + Position, +} from '../api/types'; + +type CaptainRole = { + teamIndex: number; +}; + +const TIER_NAMES: Record = { + IRON: '아이언', + BRONZE: '브론즈', + SILVER: '실버', + GOLD: '골드', + PLATINUM: '플래티넘', + EMERALD: '에메랄드', + DIAMOND: '다이아몬드', + MASTER: '마스터', + GRANDMASTER: '그랜드마스터', + CHALLENGER: '챌린저', +}; + +function formatPoints(value: number) { + return value.toLocaleString(); +} + +function relativeTime(dateLike: string) { + const seconds = Math.max( + 0, + Math.floor((Date.now() - new Date(dateLike).getTime()) / 1000), + ); + if (seconds < 60) return `${seconds}초 전`; + const minutes = Math.floor(seconds / 60); + if (minutes < 60) return `${minutes}분 전`; + const hours = Math.floor(minutes / 60); + if (hours < 24) return `${hours}시간 전`; + return `${Math.floor(hours / 24)}일 전`; +} + +function normalizeRank(rank: string | undefined) { + switch (rank) { + case 'I': + return '1'; + case 'II': + return '2'; + case 'III': + return '3'; + case 'IV': + return '4'; + default: + return rank; + } +} + +function formatRankBadge(tier: ApiTierInfo | undefined) { + if (!tier) return 'U'; + const tierInitial = + tier.tier === 'GRANDMASTER' ? 'GM' : tier.tier.slice(0, 1); + const rank = normalizeRank(tier.rank); + return rank ? `${tierInitial}${rank}` : tierInitial; +} + +function formatRankDetail(tier: ApiTierInfo | undefined) { + if (!tier) return '랭크 정보 없음'; + const tierName = TIER_NAMES[tier.tier] ?? tier.tier; + const rank = normalizeRank(tier.rank); + const label = rank ? `${tierName} ${rank}` : tierName; + return `${label} - ${tier.leaguePoints} LP`; +} + +function rankBadgeClass(tier: ApiTierInfo | undefined) { + switch (tier?.tier) { + case 'CHALLENGER': + return 'border-amber-500/60 bg-amber-100 text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/20 dark:text-amber-200'; + case 'GRANDMASTER': + return 'border-red-500/60 bg-red-100 text-red-800 dark:border-red-400/40 dark:bg-red-400/20 dark:text-red-200'; + case 'MASTER': + return 'border-fuchsia-500/60 bg-fuchsia-100 text-fuchsia-800 dark:border-fuchsia-400/40 dark:bg-fuchsia-400/20 dark:text-fuchsia-200'; + case 'DIAMOND': + return 'border-cyan-500/60 bg-cyan-100 text-cyan-800 dark:border-cyan-400/40 dark:bg-cyan-400/20 dark:text-cyan-200'; + case 'EMERALD': + return 'border-emerald-500/60 bg-emerald-100 text-emerald-800 dark:border-emerald-400/40 dark:bg-emerald-400/20 dark:text-emerald-200'; + case 'PLATINUM': + return 'border-teal-500/60 bg-teal-100 text-teal-800 dark:border-teal-400/40 dark:bg-teal-400/20 dark:text-teal-200'; + case 'GOLD': + return 'border-amber-500/70 bg-amber-100 text-amber-900 dark:border-yellow-400/40 dark:bg-yellow-400/20 dark:text-yellow-200'; + case 'SILVER': + return 'border-slate-400/60 bg-slate-100 text-slate-700 dark:border-slate-300/40 dark:bg-slate-300/15 dark:text-slate-200'; + case 'BRONZE': + return 'border-orange-600/60 bg-orange-100 text-orange-800 dark:border-orange-500/40 dark:bg-orange-500/20 dark:text-orange-200'; + case 'IRON': + return 'border-stone-500/60 bg-stone-100 text-stone-700 dark:border-stone-400/40 dark:bg-stone-400/15 dark:text-stone-300'; + default: + return 'border-base-content/30 bg-transparent text-base-content/50'; + } +} + +function RankBadge({ tier }: { tier?: ApiTierInfo }) { + const tooltip = formatRankDetail(tier); + + return ( + + + {formatRankBadge(tier)} + + + ); +} + +function ResponsiveTierLabel({ tier }: { tier?: ApiTierInfo }) { + return ( + + + + {formatRankDetail(tier)} + + + ); +} + +function isCurrentBidder( + currentBidder: AuctionStateView['currentBidder'], + team: Pick, +) { + return currentBidder?.teamIndex === team.teamIndex; +} + +function getAuctionUpdatedAt(auction: ApiAuction | null | undefined) { + if (!auction) return 0; + return Date.parse(auction.updatedAt ?? auction.createdAt ?? '') || 0; +} + +function pickLatestAuction( + socketAuction: ApiAuction | null, + queryAuction: ApiAuction | undefined, +) { + if (!socketAuction) return queryAuction ?? null; + if (!queryAuction) return socketAuction; + return getAuctionUpdatedAt(queryAuction) > getAuctionUpdatedAt(socketAuction) + ? queryAuction + : socketAuction; +} + +const AUCTION_MAX_TEAM_SIZE = 5; +const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; +const POSITION_TO_RIOT_LANE = { + TOP: 'TOP', + JGL: 'JUNGLE', + MID: 'MIDDLE', + ADC: 'BOTTOM', + SUP: 'UTILITY', +} as const; + +function PosBadge({ pos }: { pos: Position }) { + return ( + + + {positionLabel[pos]} + + ); +} + +function TimerBar({ timer, maxTimer }: { timer: number; maxTimer: number }) { + const pct = maxTimer > 0 ? (timer / maxTimer) * 100 : 0; + const urgent = timer <= 5; + + return ( +
+
+
+ ); +} + +function getWinRate(stats: ApiRiotLaneStats) { + return stats.games > 0 ? Math.round((stats.wins / stats.games) * 100) : 0; +} + +function getWinRateClass(winRate: number) { + if (winRate >= 55) return 'text-blue-400'; + if (winRate >= 50) return 'text-base-content'; + return 'text-red-400'; +} + +function formatKdaRatio(stats: ApiRiotLaneStats) { + if (stats.avgDeaths === 0) return 'Perfect'; + return ((stats.avgKills + stats.avgAssists) / stats.avgDeaths).toFixed(2); +} + +function RecentSoloStats({ + player, +}: { + player: NonNullable; +}) { + const primaryStats = player.recentStats.primary; + + if (!primaryStats) { + return ( +
+

+ 최근 솔로랭크 +

+
+ 최근 솔로랭크 기록이 없습니다 +
+
+ ); + } + + const primaryWinRate = getWinRate(primaryStats); + const primaryKdaRatio = formatKdaRatio(primaryStats); + + return ( +
+
+
+

+ 최근 솔로랭크 +

+
+ + {positionLabel[player.mainPosition]} + + {player.recentStats.primarySource === 'overall' ? ( + + 전체 기준 + + ) : null} +
+
+
+ {primaryWinRate}% +
+
+ +
+
+ 전적 + + {primaryStats.wins}W{' '} + {primaryStats.losses}L + +
+
+ KDA + + {primaryStats.avgKills}/{primaryStats.avgDeaths}/{primaryStats.avgAssists} + = 3 ? 'text-emerald-400' : 'text-base-content/50'}`} + > + ({primaryKdaRatio}) + + +
+
+ 분당 CS + + {primaryStats.avgCsPerMin} + +
+
+ +
+ {LANE_ROWS.map((position) => { + const laneStats = + player.recentStats.byLane[POSITION_TO_RIOT_LANE[position]]; + const isMainLane = position === player.mainPosition; + + return ( +
+ + {positionLabel[position]} + + {laneStats && laneStats.games > 0 ? ( + + {laneStats.wins}W {laneStats.losses}L · {laneStats.avgKills}/ + {laneStats.avgDeaths}/{laneStats.avgAssists} ·{' '} + {laneStats.avgCsPerMin} CS/min + + ) : ( + — + )} +
+ ); + })} +
+
+ ); +} + +function TeamPanel({ + team, + isActive, + isLeft, + historyBackTo, +}: { + team: AuctionStateView['teams'][number]; + isActive: boolean; + isLeft: boolean; + historyBackTo: string; +}) { + const { data: ddragon } = useDdragonManifest(); + const tone = teamIndexColorClasses(team.teamIndex); + const teamSize = team.members.length + 1; + const isFull = teamSize >= AUCTION_MAX_TEAM_SIZE; + + return ( +
+
+
+
+
+ + {teamIndexLabel(team.teamIndex, team.name)} + + + 팀장: {team.captainName} + +
+ + {formatPoints(team.points)}P + +
+
+ + 팀장 포함 {teamSize}/{AUCTION_MAX_TEAM_SIZE} + + {isFull && 정원 완료} +
+
+ +
+ {team.members.length === 0 ? ( +
+ 아직 멤버가 없습니다 +
+ ) : ( + team.members.map((member) => ( +
+ +
+ +
+ +
+ + {member.summonerName} + +
+ + + {positionLabel[member.assignedPosition]} + + + {member.cost} + +
+ )) + )} + + {Array.from({ + length: Math.max(0, AUCTION_MAX_TEAM_SIZE - 1 - team.members.length), + }).map((_, index) => ( +
+
+ — +
+ ))} +
+
+ ); +} + +function PlayerSpotlight({ + state, + historyBackTo, +}: { + state: AuctionStateView; + historyBackTo: string; +}) { + const { data: ddragon } = useDdragonManifest(); + const player = state.currentPlayer; + if (!player) return null; + + return ( +
+
+
+ + + +
+
+ + {player.summonerName} + + + #{player.tag} + +
+
+ +
+
+ + + {' '} + {positionLabel[player.subPosition]} + +
+
+
+
+ +
+
+

+ 숙련도 높은 챔피언 +

+
+ {player.masteries.length > 0 ? ( + player.masteries.map((mastery) => { + const iconUrl = championIconUrl(ddragon, mastery.championId); + const displayName = + championDisplayName(ddragon, mastery.championId) ?? + String(mastery.championId); + return ( +
+
+ {iconUrl ? ( + {displayName} + ) : null} +
+
+
+ {displayName} +
+
+ Lv.{mastery.level} · {(mastery.points / 1000).toFixed(0)}K +
+
+
+ ); + }) + ) : ( +
+ 숙련도 데이터가 없습니다. +
+ )} +
+
+ + +
+ + {(state.phase === 'bidding' || state.phase === 'sold') && ( +
+
+ + {state.phase === 'sold' ? '낙찰가' : '현재 입찰가'} + +
+ {state.currentBidder && ( + + {teamIndexLabel(state.currentBidder.teamIndex)} + + )} + + {state.currentBid > 0 ? formatPoints(state.currentBid) : '—'} + +
+
+
+ )} + {state.phase === 'passed' && ( +
+ + 유찰{' '} + {state.auctionRound === 1 + ? '— 마지막에 다시 등장합니다' + : '— 강제 배정 대상'} + +
+ )} +
+ ); +} + +function BidControls({ + state, + captainRole, + onBid, +}: { + state: AuctionStateView; + captainRole: CaptainRole | null; + onBid: (teamIndex: number, amount: number) => void; +}) { + const [bidAmount, setBidAmount] = useState(100); + const minBid = state.currentBid + 10; + const activeTeam = captainRole + ? state.teams.find((team) => team.teamIndex === captainRole.teamIndex) + : null; + const activeTeamSize = activeTeam ? activeTeam.members.length + 1 : 0; + const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE; + + useEffect(() => { + setBidAmount(Math.max(minBid, Math.ceil(minBid / 10) * 10)); + }, [state.currentBid, minBid]); + + if (state.phase !== 'bidding') return null; + + if (!activeTeam) { + return ( +
+ 관전자 모드입니다. 우측 상단에서 조작자 역할을 선택하면 입찰할 수 있습니다. +
+ ); + } + + const presets = [50, 100, 150, 200, 300, 500]; + + return ( +
+
+ {presets.map((preset) => ( + + ))} + + setBidAmount(Math.max(minBid, Number(event.target.value))) + } + min={minBid} + disabled={isActiveTeamFull} + className="w-24 text-xs px-2 py-1 border border-base-content/10 bg-transparent text-base-content tabular-nums text-right focus:outline-none focus:border-primary/30" + /> +
+ +
+ ); +} + +function BidLog({ bids }: { bids: AuctionStateView['bids'] }) { + const endRef = useRef(null); + + useEffect(() => { + endRef.current?.scrollIntoView({ behavior: 'smooth' }); + }, [bids.length]); + + if (bids.length === 0) return null; + + return ( +
+
+ + 입찰 기록 + +
+
+ {bids.map((bid, index) => ( +
+ + {teamIndexLabel(bid.teamIndex)} + + → + + {formatPoints(bid.amount)}P + +
+ ))} +
+
+
+ ); +} + +export default function AuctionPage() { + const { id } = useParams(); + const location = useLocation(); + const queryClient = useQueryClient(); + const meQuery = useMe(); + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === DEFAULT_COMMUNITY_ID, + )?.user ?? null; + const canManageAuction = + import.meta.env.DEV || + currentUser?.role === 'owner' || + currentUser?.role === 'admin'; + const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); + const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID, { + refetchInterval: 5000, + }); + const historyQuery = useAuctionHistory(id, DEFAULT_COMMUNITY_ID, { + enabled: canManageAuction, + refetchInterval: 3000, + }); + const undoMutation = useUndoAuction(DEFAULT_COMMUNITY_ID); + const socket = useAuctionSocket(id); + const captainTeamIndex = useDevCaptainTeamIndex(); + const [now, setNow] = useState(() => Date.now()); + const [assignedPosition, setAssignedPosition] = useState('MID'); + const historyBackTo = `${location.pathname}${location.search}${location.hash}`; + + useEffect(() => { + const timer = window.setInterval(() => setNow(Date.now()), 1000); + return () => window.clearInterval(timer); + }, []); + + const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data); + const auctionState = + liveAuction && matchQuery.data + ? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now)) + : null; + const availableTeamIndexes = useMemo(() => { + const indexes = new Set((auctionState?.teams ?? []).map((team) => team.teamIndex)); + return [...indexes].sort((left, right) => left - right); + }, [auctionState?.teams]); + const captainRole: CaptainRole | null = + captainTeamIndex === null + ? null + : { + teamIndex: captainTeamIndex, + }; + + useEffect(() => { + if (auctionState?.currentPlayer) { + setAssignedPosition(auctionState.currentPlayer.mainPosition); + } + }, [auctionState?.currentPlayer?.id]); + + useEffect(() => { + if (availableTeamIndexes.length === 0) return; + if (captainTeamIndex !== null && !availableTeamIndexes.includes(captainTeamIndex)) { + setDevCaptainTeamIndex(availableTeamIndexes[0]); + } + }, [availableTeamIndexes, captainTeamIndex]); + + if (!DEFAULT_COMMUNITY_ID) { + return ( +
+ + `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. + +
+ ); + } + + if (matchQuery.isLoading || (auctionQuery.isLoading && !socket.auction)) { + return ( +
+ 경매를 연결하는 중... +
+ ); + } + + if (auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404 && !socket.auction) { + return ( +
+

경매가 아직 시작되지 않았습니다

+ + 내전 상세로 돌아가기 + +
+ ); + } + + if (!auctionState || !matchQuery.data) { + return ( +
+ + 경매 상태를 불러오지 못했습니다. + +
+ ); + } + + const phaseLabel: Record = { + waiting: '경매 준비 중...', + presenting: '다음 선수 등장', + bidding: '입찰 진행 중', + sold: '낙찰!', + passed: '유찰 — 다음 선수로', + complete: '경매 완료', + }; + const errorMessage = + socket.error ?? + (auctionQuery.error instanceof Error ? auctionQuery.error.message : null); + + function handleUndo(sequence: number) { + if (!id) return; + if (!window.confirm(`${sequence}번 액션 직전으로 되돌릴까요?`)) return; + undoMutation.mutate( + { matchId: id, sequence }, + { + onSuccess: async () => { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ['auction', DEFAULT_COMMUNITY_ID, id], + }), + queryClient.invalidateQueries({ + queryKey: ['auction-history', DEFAULT_COMMUNITY_ID, id], + }), + queryClient.invalidateQueries({ + queryKey: ['match', DEFAULT_COMMUNITY_ID, id], + }), + ]); + }, + }, + ); + } + + const undoPanel = canManageAuction ? ( +
+
+ 되돌리기 (Undo) +
+
+ {historyQuery.data?.length ? ( + historyQuery.data.map((entry) => ( + + )) + ) : ( +
+ 기록이 없습니다 +
+ )} +
+
+ ) : null; + + return ( +
+ + + + + 내전 상세로 + + + {errorMessage && ( +
+ {errorMessage} +
+ )} + + {undoMutation.error instanceof Error && ( +
+ {undoMutation.error.message} +
+ )} + +
+
+

+ 경매 팀빌딩 +

+

+ {Math.min(auctionState.currentPlayerIndex + 1, Math.max(auctionState.totalPlayers, 1))} /{' '} + {auctionState.totalPlayers} 선수 +

+
+
+
+ + {phaseLabel[auctionState.phase]} + + {auctionState.phase === 'bidding' && ( + + {auctionState.timer}s + + )} +
+
+ 소켓: {socket.connectionStatus} + {/* 임시 운영용: 로그인/권한 확인 없이 조작자 역할을 선택할 수 있게 열어둔다. */} + +
+
+
+ + {auctionState.phase === 'bidding' && ( + + )} + +
+
+ {auctionState.teams.map((team) => ( + + ))} +
+ +
+ {auctionState.phase === 'complete' ? ( + <> +
+
+ 경매 완료 +
+
+ 모든 선수가 팀에 배정되었습니다. +
+ + 결과 확인 + +
+ {undoPanel} + + ) : ( + <> + + + {auctionState.phase === 'sold' && auctionState.currentBidder && ( +
+ {teamIndexLabel(auctionState.currentBidder.teamIndex)} 낙찰 + {' '}— {formatPoints(auctionState.currentBid)}P +
+ )} + + + socket.placeBid({ teamIndex, amount }) + } + /> + + + {canManageAuction && ( +
+
+ Auction Controls +
+ {auctionState.phase === 'presenting' && ( + + )} + {auctionState.phase === 'bidding' && ( +
+ + +
+ )} + {(auctionState.phase === 'sold' || + auctionState.phase === 'passed') && ( + + )} +
+ )} + {undoPanel} + + )} +
+
+
+ ); +} diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx new file mode 100644 index 00000000..cf330b08 --- /dev/null +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -0,0 +1,1883 @@ +import { useEffect, useState } from "react"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { Link, useLocation, useNavigate, useParams } from "react-router"; +import { + useAuction, + useCollectTournamentResultByRiotMatch, + useCollectTournamentResultByWindow, + useDdragonManifest, + useMatch, + useMe, + usePollTournamentResult, + useTournamentCodeStats, + useUserHistoryProfile, +} from "../api/hooks"; +import { + buildDefaultPreferredPositions, + formatTierLabel, + mapApiMatchToMatchDetail, + type MatchDetailView, + type ParticipantView, + type TeamView, +} from "../api/mappers"; +import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config"; +import { apiFetch, ApiError } from "../lib/api"; +import { profileIconUrl } from "../lib/ddragon"; +import { + positionIcon, + positionLabel, + sideShortLabel, + teamIndexColorClasses, + teamIndexLabel, +} from "../lib/league"; +import type { + AuctionTopTierThreshold, + ApiMatchParticipant, + ApiTierInfo, + ManualTournamentResultCollectResponse, + Position, + TeamSide, + TournamentCodeSlotView, +} from "../api/types"; + +type CaptainSelectionSlot = { + teamIndex: number; +}; + +type CaptainSelection = { + userId: string; + initialPoints: string; +}; + +const DEFAULT_AUCTION_MAX_TIMER_SECONDS = 30; +const DEFAULT_AUCTION_BID_EXTENSION_SECONDS = 5; +const MAX_AUCTION_TIMER_SECONDS = 3600; + +function captainSlotKey(slot: CaptainSelectionSlot) { + return String(slot.teamIndex); +} + +function parseInitialPointsInput(value: string) { + if (!value.trim()) return null; + const points = Number(value); + if (!Number.isInteger(points) || points < 100 || points > 100000) { + return null; + } + return points; +} + +function parseAuctionSecondsInput(value: string, min: number) { + if (!value.trim()) return null; + const seconds = Number(value); + if ( + !Number.isInteger(seconds) || + seconds < min || + seconds > MAX_AUCTION_TIMER_SECONDS + ) { + return null; + } + return seconds; +} + +function buildAuctionParticipantPool(participants: ApiMatchParticipant[]) { + const ordered = [...participants].sort( + (left, right) => + new Date(left.joinedAt).getTime() - new Date(right.joinedAt).getTime(), + ); + const auctionParticipantCount = Math.floor(ordered.length / 10) * 10; + return ordered.slice(0, auctionParticipantCount); +} + +function buildCaptainSlots( + participants: ApiMatchParticipant[], +): CaptainSelectionSlot[] { + const teamCount = Math.floor( + buildAuctionParticipantPool(participants).length / 5, + ); + return Array.from({ length: teamCount }, (_, index) => ({ + teamIndex: index + 1, + })); +} + +function PosBadge({ pos, sub }: { pos: Position; sub?: boolean }) { + return ( + + + {positionLabel[pos]} + + ); +} + +function tierByQueue(tiers: ApiTierInfo[], queueType: string) { + return tiers.find((tier) => tier.queueType === queueType); +} + +function normalizeRank(rank: string | undefined) { + switch (rank) { + case "I": + return "1"; + case "II": + return "2"; + case "III": + return "3"; + case "IV": + return "4"; + default: + return rank; + } +} + +function formatRankTooltip(tier: ApiTierInfo | undefined) { + if (!tier) return "언랭크"; + const highTier = ["MASTER", "GRANDMASTER", "CHALLENGER"].includes(tier.tier); + const normalizedTier = { + ...tier, + rank: normalizeRank(tier.rank) ?? tier.rank, + }; + const label = highTier + ? formatTierLabel({ ...normalizedTier, leaguePoints: 0 }) + : formatTierLabel(normalizedTier); + return `${label} - ${tier.leaguePoints}LP`; +} + +function formatRankBadge(tier: ApiTierInfo | undefined) { + if (!tier) return "U"; + const tierInitial = + tier.tier === "GRANDMASTER" ? "GM" : tier.tier.slice(0, 1); + const rank = normalizeRank(tier.rank); + return rank ? `${tierInitial}${rank}` : tierInitial; +} + +function rankBadgeClass(tier: ApiTierInfo | undefined) { + switch (tier?.tier) { + case "CHALLENGER": + return "border-amber-500/60 bg-amber-100 text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/20 dark:text-amber-200"; + case "GRANDMASTER": + return "border-red-500/60 bg-red-100 text-red-800 dark:border-red-400/40 dark:bg-red-400/20 dark:text-red-200"; + case "MASTER": + return "border-fuchsia-500/60 bg-fuchsia-100 text-fuchsia-800 dark:border-fuchsia-400/40 dark:bg-fuchsia-400/20 dark:text-fuchsia-200"; + case "DIAMOND": + return "border-cyan-500/60 bg-cyan-100 text-cyan-800 dark:border-cyan-400/40 dark:bg-cyan-400/20 dark:text-cyan-200"; + case "EMERALD": + return "border-emerald-500/60 bg-emerald-100 text-emerald-800 dark:border-emerald-400/40 dark:bg-emerald-400/20 dark:text-emerald-200"; + case "PLATINUM": + return "border-teal-500/60 bg-teal-100 text-teal-800 dark:border-teal-400/40 dark:bg-teal-400/20 dark:text-teal-200"; + case "GOLD": + return "border-amber-500/70 bg-amber-100 text-amber-900 dark:border-yellow-400/40 dark:bg-yellow-400/20 dark:text-yellow-200"; + case "SILVER": + return "border-slate-400/60 bg-slate-100 text-slate-700 dark:border-slate-300/40 dark:bg-slate-300/15 dark:text-slate-200"; + case "BRONZE": + return "border-orange-600/60 bg-orange-100 text-orange-800 dark:border-orange-500/40 dark:bg-orange-500/20 dark:text-orange-200"; + case "IRON": + return "border-stone-500/60 bg-stone-100 text-stone-700 dark:border-stone-400/40 dark:bg-stone-400/15 dark:text-stone-300"; + default: + return "border-base-content/30 bg-transparent text-base-content/50"; + } +} + +function RankBadge({ tier }: { tier?: ApiTierInfo }) { + const tooltip = formatRankTooltip(tier); + + return ( + + + {formatRankBadge(tier)} + + + ); +} + +function QueueRankCell({ + label, + tier, +}: { + label: "SOLO" | "FLEX"; + tier?: ApiTierInfo; +}) { + return ( + + {label} + + + ); +} + +function SoloRankPrefix({ tier }: { tier?: ApiTierInfo }) { + return ( + + {/* SOLO */} + + + ); +} + +function TierCell({ participant }: { participant: ParticipantView }) { + const profileQuery = useUserHistoryProfile( + participant.userId, + DEFAULT_COMMUNITY_ID, + ); + const tiers = profileQuery.data?.tiers ?? []; + const soloTier = + tierByQueue(tiers, "RANKED_SOLO_5x5") ?? + (participant.tier?.queueType === "RANKED_SOLO_5x5" + ? participant.tier + : undefined); + const flexTier = tierByQueue(tiers, "RANKED_FLEX_SR"); + + return ( +
+ + +
+ ); +} + +function statusBadge(status: MatchDetailView["status"]) { + switch (status) { + case "recruiting": + return { + label: "모집 중", + cls: "bg-green-500/15 text-green-500 border-green-500/20", + }; + case "team-built": + return { + label: "팀빌딩 완료", + cls: "bg-amber-500/15 text-amber-500 border-amber-500/20", + }; + case "in-progress": + return { + label: "진행 중", + cls: "bg-blue-500/15 text-blue-400 border-blue-500/20", + }; + case "finished": + return { + label: "종료", + cls: "bg-base-content/8 text-base-content/40 border-base-content/10", + }; + } +} + +function ParticipantRow({ + participant, + index, + assignedPos, +}: { + participant: ParticipantView; + index: number; + assignedPos?: Position; +}) { + const { data: ddragon } = useDdragonManifest(); + const location = useLocation(); + const historyBackTo = `${location.pathname}${location.search}${location.hash}`; + + return ( + + + {index + 1} + + + +
+ +
+
+ + {participant.summonerName} + + + #{participant.tag} + {participant.excluded && ( + + 제외 + + )} + +
+ + + + + + {assignedPos ? ( + + + + ) : ( + <> + + + + + + + + )} + + ); +} + +function ParticipantTable({ + participants, + maxParticipants, + joined, + canJoin, + onJoin, + isJoining, +}: { + participants: ParticipantView[]; + maxParticipants: number; + joined: boolean; + canJoin: boolean; + onJoin: () => void; + isJoining: boolean; +}) { + return ( +
+
+

+ 참가자 ({participants.length}/{maxParticipants}) +

+ +
+
+ + + + + + + + + + + + {participants.map((participant, index) => ( + + ))} + +
#소환사현재 티어주 포지션부 포지션
+
+ {participants.length < maxParticipants && ( +
+ + {maxParticipants - participants.length}자리 남음 + +
+ )} +
+ ); +} + +function TeamCard({ + team, + matchId, + isWinner, +}: { + team: TeamView; + matchId: string; + isWinner?: boolean; +}) { + const tone = teamIndexColorClasses(team.teamIndex); + + return ( +
+
+
+
+ + {team.name} + + {isWinner && ( + + WIN + + )} +
+ + 진행 페이지 + +
+ + + + + + + + + + + {team.participants.map((participant, index) => ( + + ))} + +
#소환사현재 티어포지션
+
+ ); +} + +function SideCard({ + title, + children, +}: { + title: string; + children: React.ReactNode; +}) { + return ( +
+
+

+ {title} +

+
+
{children}
+
+ ); +} + +function formatTournamentCodeExpiry(value: string | null) { + if (!value) return null; + return new Intl.DateTimeFormat("ko-KR", { + month: "long", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + }).format(new Date(value)); +} + +function isExpiringSoon(value: string | null) { + if (!value) return false; + const expiresAt = new Date(value).getTime(); + return expiresAt - Date.now() <= 24 * 60 * 60 * 1000; +} + +function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) { + const [copied, setCopied] = useState(false); + const expired = slot.state === "expired"; + const used = slot.state === "used"; + const expiringSoon = isExpiringSoon(slot.expiresAt); + + async function copyCode() { + if (!slot.code) return; + await navigator.clipboard.writeText(slot.code); + setCopied(true); + window.setTimeout(() => setCopied(false), 1600); + } + + return ( +
+
+ + {expired ? "코드 만료" : slot.code} + + {slot.code && !expired && ( + + )} +
+
+ {used + ? "사용됨" + : expired + ? "운영자에게 새 코드를 요청해주세요." + : `만료: ${formatTournamentCodeExpiry(slot.expiresAt)}`} +
+
+ ); +} + +function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) { + if (slots.length === 0) { + return ( +
+ 아직 배정된 코드가 없습니다. +
+ ); + } + + return ( +
+ {slots.map((slot) => ( +
+ + {slot.gameNumber}경기 + {(slot.teamAIndex > 1 || slot.teamBIndex > 2) && ( + + {teamIndexLabel(slot.teamAIndex)} vs{" "} + {teamIndexLabel(slot.teamBIndex)} + + )} + + {slot.code ? ( + + ) : ( + + 발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다. + + )} +
+ ))} +
+ ); +} + +function toIsoFromLocalDateTime(value: string): string | null { + if (!value) return null; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return null; + return date.toISOString(); +} + +function formatManualCollectSummary( + result: ManualTournamentResultCollectResponse | undefined, +) { + if (!result) return null; + const games = result.gameNumbers.length + ? ` · ${result.gameNumbers.join(", ")}경기` + : ""; + return `${result.matched}/${result.scanned}개 반영${games}`; +} + +function PoolStatsHint({ enabled }: { enabled: boolean }) { + const statsQuery = useTournamentCodeStats(DEFAULT_COMMUNITY_ID, enabled); + if (!enabled) return null; + const available = statsQuery.data?.available ?? 0; + const expiringSoon = statsQuery.data?.expiringSoon ?? 0; + + return ( +
+
+ 풀 잔여 {available}개 + {expiringSoon > 0 ? ` · 만료 임박 ${expiringSoon}개` : ""} +
+ + 코드 풀 관리 + +
+ ); +} + +function formatGameDuration(seconds: number) { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, "0")}`; +} + +function resultSideClass(side: "blue" | "red") { + return side === "blue" ? "text-blue-400" : "text-red-400"; +} + +function resultSideLabel(side: TeamSide) { + return sideShortLabel(side); +} + +function resolveMatchTeamName(match: MatchDetailView, teamIndex: number) { + const team = match.teams.find((item) => item.teamIndex === teamIndex); + return teamIndexLabel(teamIndex, team?.name); +} + +type RoundRobinStanding = { + teamIndex: number; + name: string; + seriesWins: number; + seriesLosses: number; + gameWins: number; + gameLosses: number; + gameDiff: number; + kills: number; + deaths: number; + assists: number; + kdaScore: number; + winRate: number; +}; + +function formatRecordRate(value: number) { + if (!Number.isFinite(value)) return "-"; + return value.toFixed(2).replace(/\.?0+$/, ""); +} + +function formatSignedNumber(value: number) { + return String(value); +} + +function formatKda(standing: RoundRobinStanding) { + if (standing.deaths === 0) { + return standing.kills + standing.assists > 0 ? "Perfect" : "-"; + } + return formatRecordRate(standing.kdaScore); +} + +function buildRoundRobinStandings( + match: MatchDetailView, +): RoundRobinStanding[] { + const standings = new Map(); + + const getStanding = (teamIndex: number) => { + const existing = standings.get(teamIndex); + if (existing) return existing; + + const standing: RoundRobinStanding = { + teamIndex, + name: resolveMatchTeamName(match, teamIndex), + seriesWins: 0, + seriesLosses: 0, + gameWins: 0, + gameLosses: 0, + gameDiff: 0, + kills: 0, + deaths: 0, + assists: 0, + kdaScore: 0, + winRate: 0, + }; + standings.set(teamIndex, standing); + return standing; + }; + + match.teams.forEach((team) => getStanding(team.teamIndex)); + + const seriesResults = match.result?.seriesResults ?? []; + seriesResults.forEach((series) => { + const teamA = getStanding(series.teamAIndex); + const teamB = getStanding(series.teamBIndex); + const teamAWins = series.teamAWins ?? 0; + const teamBWins = series.teamBWins ?? 0; + const winnerTeamIndex = + series.winnerTeamIndex ?? + (teamAWins === teamBWins + ? undefined + : teamAWins > teamBWins + ? series.teamAIndex + : series.teamBIndex); + + teamA.gameWins += teamAWins; + teamA.gameLosses += teamBWins; + teamB.gameWins += teamBWins; + teamB.gameLosses += teamAWins; + + if (winnerTeamIndex === series.teamAIndex) { + teamA.seriesWins += 1; + teamB.seriesLosses += 1; + } + if (winnerTeamIndex === series.teamBIndex) { + teamB.seriesWins += 1; + teamA.seriesLosses += 1; + } + }); + + match.result?.games.forEach((game) => { + game.participants.forEach((participant) => { + const standing = getStanding(participant.teamIndex); + standing.kills += participant.kills; + standing.deaths += participant.deaths; + standing.assists += participant.assists; + }); + }); + + standings.forEach((standing) => { + standing.gameDiff = standing.gameWins - standing.gameLosses; + const totalSeries = standing.seriesWins + standing.seriesLosses; + standing.winRate = totalSeries > 0 ? standing.seriesWins / totalSeries : 0; + standing.kdaScore = + standing.deaths > 0 + ? (standing.kills + standing.assists) / standing.deaths + : standing.kills + standing.assists; + }); + + return [...standings.values()].sort((left, right) => { + if (right.seriesWins !== left.seriesWins) { + return right.seriesWins - left.seriesWins; + } + if (left.seriesLosses !== right.seriesLosses) { + return left.seriesLosses - right.seriesLosses; + } + if (right.gameDiff !== left.gameDiff) { + return right.gameDiff - left.gameDiff; + } + if (right.winRate !== left.winRate) { + return right.winRate - left.winRate; + } + if (right.kdaScore !== left.kdaScore) { + return right.kdaScore - left.kdaScore; + } + if (right.kills !== left.kills) { + return right.kills - left.kills; + } + return left.teamIndex - right.teamIndex; + }); +} + +function RoundRobinStandingsTable({ match }: { match: MatchDetailView }) { + const standings = buildRoundRobinStandings(match); + + return ( +
+
+
+

+ 라운드로빈 순위 +

+

+ {standings.length}팀 · {match.result?.games.length ?? 0}경기 완료 +

+
+ {match.result?.winner && ( +
+
+ 1위 +
+
+ {match.result.winner} +
+
+ )} +
+
+ + + + + + + + + + + + + + + + {standings.map((standing, index) => { + const tone = teamIndexColorClasses(standing.teamIndex); + const isWinner = + match.result?.winnerTeamIndex === standing.teamIndex; + + return ( + + + + + + + + + + + + ); + })} + +
팀 순위 + 승 + 패득실차승률KDA킬데스어시스트
+
+ + {index + 1} + +
+
+ {standing.seriesWins} + + {standing.seriesLosses} + + {formatSignedNumber(standing.gameDiff)} + + {formatRecordRate(standing.winRate)} + + {formatKda(standing)} + + {standing.kills} + + {standing.deaths} + + {standing.assists} +
+
+
+ ); +} + +function MatchResultPanel({ match }: { match: MatchDetailView }) { + if (!match.result) return null; + + const gamesByNumber = new Map( + match.result.games.map((game) => [game.gameNumber, game]), + ); + const maxGameNumber = Math.max( + match.gameCount, + match.tournamentCodes.length, + ...match.result.games.map((game) => game.gameNumber), + ); + const gameNumbers = Array.from( + { length: maxGameNumber }, + (_, index) => index + 1, + ); + const seriesResults = match.result.seriesResults ?? []; + const primarySeries = seriesResults[0]; + const showRoundRobinStandings = + match.gameMode === "round-robin" && match.teams.length > 2; + + return ( +
+ {showRoundRobinStandings ? ( + + ) : ( + <> + {primarySeries && ( +
+
+
+ {primarySeries.teamAWins} +
+
+ {resolveMatchTeamName(match, primarySeries.teamAIndex)} +
+
+
+ VS +
+
+
+ {primarySeries.teamBWins} +
+
+ {resolveMatchTeamName(match, primarySeries.teamBIndex)} +
+
+
+ )} +
+ {match.result.winner + ? `${match.result.winner} 승리` + : `결과 수집 중 · ${match.result.games.length}/${maxGameNumber}경기`} +
+ {seriesResults.length > 1 && ( +
+ {seriesResults.map((series) => ( +
+
+ {resolveMatchTeamName(match, series.teamAIndex)} vs{" "} + {resolveMatchTeamName(match, series.teamBIndex)} +
+
+ + {series.teamAWins} + + : + + {series.teamBWins} + +
+
+ ))} +
+ )} + + )} +
+ {gameNumbers.map((gameNumber) => { + const game = gamesByNumber.get(gameNumber); + return ( +
+ + {gameNumber}경기 + + {game ? ( +
+ + {resolveMatchTeamName(match, game.winnerTeamIndex)} 승 + + + ({resultSideLabel(game.winnerSide)} 진영) + + + {game.riotMatchId} + +
+ ) : ( + 대기 중 + )} + + {game ? formatGameDuration(game.gameDuration) : "-"} + +
+ ); + })} +
+
+ ); +} + +export default function MatchDetailPage() { + const { id } = useParams(); + const navigate = useNavigate(); + const queryClient = useQueryClient(); + const authUserId = useAuthUserId(); + const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); + const meQuery = useMe(); + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === DEFAULT_COMMUNITY_ID, + )?.user ?? null; + const canUseMemberActions = Boolean(currentUser || authUserId); + const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID); + const [captainSelections, setCaptainSelections] = useState< + Record + >({}); + const [topTierThreshold, setTopTierThreshold] = + useState("NONE"); + const [manualTopTierUserIds, setManualTopTierUserIds] = useState( + [], + ); + const [maxTimerSeconds, setMaxTimerSeconds] = useState( + String(DEFAULT_AUCTION_MAX_TIMER_SECONDS), + ); + const [bidExtensionSeconds, setBidExtensionSeconds] = useState( + String(DEFAULT_AUCTION_BID_EXTENSION_SECONDS), + ); + const [manualResultStartTime, setManualResultStartTime] = useState(""); + const [manualResultEndTime, setManualResultEndTime] = useState(""); + const [manualRiotMatchId, setManualRiotMatchId] = useState(""); + const pollTournamentResultMutation = + usePollTournamentResult(DEFAULT_COMMUNITY_ID); + const collectResultByWindowMutation = useCollectTournamentResultByWindow( + DEFAULT_COMMUNITY_ID, + ); + const collectResultByRiotMatchMutation = + useCollectTournamentResultByRiotMatch(DEFAULT_COMMUNITY_ID); + + const joinMatchMutation = useMutation({ + mutationFn: () => + apiFetch( + `/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants`, + { + method: "POST", + body: JSON.stringify({ + preferredPositions: currentUser?.preferredPositions.length + ? currentUser.preferredPositions.slice(0, 5) + : buildDefaultPreferredPositions(), + }), + }, + ), + onSuccess: async () => { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null], + }), + queryClient.invalidateQueries({ + queryKey: ["matches", DEFAULT_COMMUNITY_ID], + }), + ]); + }, + }); + + const startAuctionMutation = useMutation({ + mutationFn: () => + apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, { + method: "POST", + body: JSON.stringify({ + captains: buildCaptainSlots(matchQuery.data?.participants ?? []).map( + (slot) => ({ + teamIndex: slot.teamIndex, + userId: captainSelections[captainSlotKey(slot)]?.userId, + initialPoints: + parseInitialPointsInput( + captainSelections[captainSlotKey(slot)]?.initialPoints ?? "", + ) ?? 1000, + }), + ), + initialPoints: 1000, + topTierThreshold, + manualTopTierUserIds: + topTierThreshold === "MANUAL" ? selectedManualTopTierUserIds : [], + maxTimerSeconds: + parseAuctionSecondsInput(maxTimerSeconds, 5) ?? + DEFAULT_AUCTION_MAX_TIMER_SECONDS, + bidExtensionSeconds: + parseAuctionSecondsInput(bidExtensionSeconds, 0) ?? + DEFAULT_AUCTION_BID_EXTENSION_SECONDS, + }), + }), + onSuccess: async () => { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null], + }), + queryClient.invalidateQueries({ + queryKey: ["auction", DEFAULT_COMMUNITY_ID, id ?? null], + }), + ]); + navigate(`/match/${id}/auction`); + }, + }); + + function handlePollTournamentResult() { + if (!id) return; + pollTournamentResultMutation.mutate(id, { + onSuccess: async () => { + await invalidateCurrentMatch(); + }, + }); + } + + async function invalidateCurrentMatch() { + await queryClient.invalidateQueries({ + queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null], + }); + } + + function handleCollectResultByWindow() { + if (!id) return; + const startTime = toIsoFromLocalDateTime(manualResultStartTime); + const endTime = toIsoFromLocalDateTime(manualResultEndTime); + if (!startTime || !endTime) return; + collectResultByWindowMutation.mutate( + { matchId: id, startTime, endTime }, + { onSuccess: invalidateCurrentMatch }, + ); + } + + function handleCollectResultByRiotMatch() { + if (!id || !manualRiotMatchId.trim()) return; + collectResultByRiotMatchMutation.mutate( + { matchId: id, riotMatchId: manualRiotMatchId.trim() }, + { onSuccess: invalidateCurrentMatch }, + ); + } + + useEffect(() => { + const participants = buildAuctionParticipantPool( + matchQuery.data?.participants ?? [], + ); + const slots = buildCaptainSlots(matchQuery.data?.participants ?? []); + if (slots.length === 0) { + setCaptainSelections({}); + return; + } + + setCaptainSelections((current) => { + const next: Record = {}; + const usedUserIds = new Set(); + + for (const slot of slots) { + const key = captainSlotKey(slot); + const currentSelection = current[key]; + const currentUserId = currentSelection?.userId; + const currentIsValid = + currentUserId && + participants.some( + (participant) => participant.userId === currentUserId, + ) && + !usedUserIds.has(currentUserId); + + if (currentIsValid) { + next[key] = { + userId: currentUserId, + initialPoints: currentSelection?.initialPoints ?? "1000", + }; + usedUserIds.add(currentUserId); + continue; + } + + const fallback = participants.find( + (participant) => !usedUserIds.has(participant.userId), + ); + next[key] = { + userId: fallback?.userId ?? "", + initialPoints: currentSelection?.initialPoints ?? "1000", + }; + if (fallback) usedUserIds.add(fallback.userId); + } + + return next; + }); + }, [matchQuery.data?.participants]); + + if (!DEFAULT_COMMUNITY_ID) { + return ( +
+ + `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. + +
+ ); + } + + if (matchQuery.isLoading) { + return ( +
+ + 매치 정보를 불러오는 중... + +
+ ); + } + + if (matchQuery.error || !matchQuery.data) { + return ( +
+

내전을 찾을 수 없습니다

+ + 홈으로 돌아가기 + +
+ ); + } + + const match = mapApiMatchToMatchDetail(matchQuery.data); + const si = statusBadge(match.status); + const canManageAuction = + currentUser?.role === "owner" || currentUser?.role === "admin"; + const isCheckingPermissions = + meQuery.isLoading || (meQuery.isFetching && !meQuery.data); + const auctionNotStarted = + auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404; + const showAuctionLink = Boolean(auctionQuery.data); + const auctionParticipantPool = buildAuctionParticipantPool( + matchQuery.data.participants, + ); + const captainSlots = buildCaptainSlots(matchQuery.data.participants); + const selectedCaptainIds = captainSlots + .map((slot) => captainSelections[captainSlotKey(slot)]?.userId) + .filter((userId): userId is string => Boolean(userId)); + const hasUniqueCaptainSelections = + selectedCaptainIds.length === captainSlots.length && + new Set(selectedCaptainIds).size === selectedCaptainIds.length; + const hasValidCaptainInitialPoints = captainSlots.every((slot) => + Boolean( + parseInitialPointsInput( + captainSelections[captainSlotKey(slot)]?.initialPoints ?? "", + ), + ), + ); + const manualPriorityCandidates = auctionParticipantPool.filter( + (participant) => !selectedCaptainIds.includes(participant.userId), + ); + const manualPriorityCandidateIds = new Set( + manualPriorityCandidates.map((participant) => participant.userId), + ); + const selectedManualTopTierUserIds = manualTopTierUserIds.filter((userId) => + manualPriorityCandidateIds.has(userId), + ); + const parsedMaxTimerSeconds = parseAuctionSecondsInput(maxTimerSeconds, 5); + const parsedBidExtensionSeconds = parseAuctionSecondsInput( + bidExtensionSeconds, + 0, + ); + const hasValidAuctionTimerSettings = + parsedMaxTimerSeconds !== null && parsedBidExtensionSeconds !== null; + const waitingParticipantCount = + matchQuery.data.participants.length - auctionParticipantPool.length; + const canStartAuction = + canManageAuction && + match.status === "recruiting" && + auctionParticipantPool.length >= 10 && + auctionNotStarted && + hasUniqueCaptainSelections && + hasValidCaptainInitialPoints && + hasValidAuctionTimerSettings; + + return ( +
+ + + + + 목록으로 + + +
+
+

+ {match.title} +

+ + {si.label} + +
+

+ {match.description} +

+
+ + {match.date} {match.time} + + | + + {match.participants.length}/{match.maxParticipants}명 + + | + + {match.map} + +
+
+ + {joinMatchMutation.error instanceof Error && ( +
+ {joinMatchMutation.error.message} +
+ )} + + {startAuctionMutation.error instanceof Error && ( +
+ {startAuctionMutation.error.message} +
+ )} + + {pollTournamentResultMutation.error instanceof Error && ( +
+ {pollTournamentResultMutation.error.message} +
+ )} + + {collectResultByWindowMutation.error instanceof Error && ( +
+ {collectResultByWindowMutation.error.message} +
+ )} + + {collectResultByRiotMatchMutation.error instanceof Error && ( +
+ {collectResultByRiotMatchMutation.error.message} +
+ )} + + + +
+
+ {match.status === "recruiting" ? ( + <> + joinMatchMutation.mutate()} + isJoining={joinMatchMutation.isPending} + /> + + {isCheckingPermissions ? ( +
+

+ 권한 확인 중 +

+

+ 관리자 권한을 확인한 뒤 경매 시작 버튼을 표시합니다. +

+
+ ) : canManageAuction ? ( +
+
+

+ 경매 시작 +

+

+ 참가 신청 순서 기준 5명당 1개 팀이 만들어지고, 각 팀의 + 팀장을 지정합니다. +

+ {waitingParticipantCount > 0 && ( +

+ {waitingParticipantCount}명은 10명 단위에 맞지 않아 이번 + 경매에서 제외됩니다. +

+ )} +
+ + {showAuctionLink ? ( + + 경매 페이지 열기 + + ) : ( +
+ {captainSlots.length > 0 ? ( +
+ {captainSlots.map((slot) => { + const key = captainSlotKey(slot); + const currentSelection = captainSelections[key]; + const currentValue = currentSelection?.userId ?? ""; + return ( + + ); + })} +
+ ) : ( +
+ 경매를 시작하려면 최소 10명이 필요합니다. +
+ )} +
+ + + +
+ {topTierThreshold === "MANUAL" && ( +
+
+ 우선 등장 선수 +
+
+ {manualPriorityCandidates.map((participant) => { + const checked = + selectedManualTopTierUserIds.includes( + participant.userId, + ); + const soloTier = + participant.tier?.queueType === + "RANKED_SOLO_5x5" + ? participant.tier + : undefined; + return ( + + ); + })} + {manualPriorityCandidates.length === 0 && ( +
+ 팀장을 제외한 우선 등장 후보가 없습니다. +
+ )} +
+
+ )} +
+ + {!canUseMemberActions && ( + + 로그인 또는 Dev Auth에 owner/admin User ID를 먼저 + 입력해주세요. + + )} +
+
+ )} +
+ ) : null} + + ) : ( +
+ {match.teams.map((team) => ( + + ))} + {showAuctionLink && ( +
+ + 경매 페이지 열기 + +
+ )} +
+ )} +
+ +
+ {match.schedule.length > 0 && ( + +
    + {match.schedule.map((item, index) => ( +
  • + + {item.time} + + {item.label} +
  • + ))} +
+
+ )} + + {(match.status === "team-built" || + match.status === "in-progress") && ( + + + + + )} + + {canManageAuction && + (match.status === "team-built" || + match.status === "in-progress") && ( + +
+
+
+ 토너먼트 코드 +
+ +
+ +
+
+ 시간 범위 +
+
+ + + + {formatManualCollectSummary( + collectResultByWindowMutation.data, + ) && ( +
+ {formatManualCollectSummary( + collectResultByWindowMutation.data, + )} +
+ )} +
+
+ +
+
+ Riot Match ID +
+
+ + setManualRiotMatchId(event.target.value) + } + placeholder="KR_1234567890" + className="w-full border border-base-content/10 bg-transparent px-2 py-2 text-[11px] text-base-content focus:outline-none focus:border-primary/30" + /> + + {formatManualCollectSummary( + collectResultByRiotMatchMutation.data, + ) && ( +
+ {formatManualCollectSummary( + collectResultByRiotMatchMutation.data, + )} +
+ )} +
+
+
+
+ )} + + {match.prizes.length > 0 && ( + +
    + {match.prizes.map((prize, index) => ( +
  • + ▸ + {prize} +
  • + ))} +
+
+ )} + + {match.notices.length > 0 && ( + +
    + {match.notices.map((notice, index) => ( +
  • + • + {notice} +
  • + ))} +
+
+ )} +
+
+
+ ); +} diff --git a/apps/web/src/pages/MatchTeamProgressPage.tsx b/apps/web/src/pages/MatchTeamProgressPage.tsx new file mode 100644 index 00000000..8e122332 --- /dev/null +++ b/apps/web/src/pages/MatchTeamProgressPage.tsx @@ -0,0 +1,710 @@ +import { useState } from "react"; +import { ChevronDown, ChevronUp } from "lucide-react"; +import { Link, useLocation, useParams } from "react-router"; +import { + useDdragonManifest, + useMatch, + useUserHistoryProfile, +} from "../api/hooks"; +import { formatKoreanDate, formatTierLabel } from "../api/mappers"; +import type { + ApiMatch, + ApiMatchGameResult, + ApiMatchParticipant, + ApiTierInfo, + MatchGameMode, + Position, + TeamSide, + TournamentCodeSlotView, +} from "../api/types"; +import { DEFAULT_COMMUNITY_ID } from "../config"; +import { profileIconUrl } from "../lib/ddragon"; +import { positionLabel, sideShortLabel, teamIndexLabel } from "../lib/league"; + +const GAME_MODE_LABEL: Record = { + pair: "페어 매치", + bracket: "토너먼트", + "round-robin": "리그전", +}; + +function resultBadgeClass(won: boolean) { + return won + ? "border-blue-500/20 bg-blue-500/10 text-blue-400" + : "border-red-500/20 bg-red-500/10 text-red-400"; +} + +function captainName( + team: ApiMatch["teams"][number] | undefined, + participantByUserId: Map, +) { + if (!team?.captainUserId) return undefined; + return participantByUserId.get(team.captainUserId)?.gameName; +} + +function tierByQueue(tiers: ApiTierInfo[], queueType: string) { + return tiers.find((tier) => tier.queueType === queueType); +} + +function normalizeRank(rank: string | undefined) { + switch (rank) { + case "I": + return "1"; + case "II": + return "2"; + case "III": + return "3"; + case "IV": + return "4"; + default: + return rank; + } +} + +function formatRankTooltip(tier: ApiTierInfo | undefined) { + if (!tier) return "언랭크"; + const highTier = ["MASTER", "GRANDMASTER", "CHALLENGER"].includes(tier.tier); + const normalizedTier = { + ...tier, + rank: normalizeRank(tier.rank) ?? tier.rank, + }; + const label = highTier + ? formatTierLabel({ ...normalizedTier, leaguePoints: 0 }) + : formatTierLabel(normalizedTier); + return `${label} - ${tier.leaguePoints}LP`; +} + +function formatRankBadge(tier: ApiTierInfo | undefined) { + if (!tier) return "U"; + const tierInitial = + tier.tier === "GRANDMASTER" ? "GM" : tier.tier.slice(0, 1); + const rank = normalizeRank(tier.rank); + return rank ? `${tierInitial}${rank}` : tierInitial; +} + +function rankBadgeClass(tier: ApiTierInfo | undefined) { + switch (tier?.tier) { + case "CHALLENGER": + return "border-amber-500/60 bg-amber-100 text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/20 dark:text-amber-200"; + + case "GRANDMASTER": + return "border-red-500/60 bg-red-100 text-red-800 dark:border-red-400/40 dark:bg-red-400/20 dark:text-red-200"; + + case "MASTER": + return "border-fuchsia-500/60 bg-fuchsia-100 text-fuchsia-800 dark:border-fuchsia-400/40 dark:bg-fuchsia-400/20 dark:text-fuchsia-200"; + + case "DIAMOND": + return "border-cyan-500/60 bg-cyan-100 text-cyan-800 dark:border-cyan-400/40 dark:bg-cyan-400/20 dark:text-cyan-200"; + + case "EMERALD": + return "border-emerald-500/60 bg-emerald-100 text-emerald-800 dark:border-emerald-400/40 dark:bg-emerald-400/20 dark:text-emerald-200"; + + case "PLATINUM": + return "border-teal-500/60 bg-teal-100 text-teal-800 dark:border-teal-400/40 dark:bg-teal-400/20 dark:text-teal-200"; + + case "GOLD": + return "border-amber-500/70 bg-amber-100 text-amber-900 dark:border-yellow-400/40 dark:bg-yellow-400/20 dark:text-yellow-200"; + + case "SILVER": + return "border-slate-400/60 bg-slate-100 text-slate-700 dark:border-slate-300/40 dark:bg-slate-300/15 dark:text-slate-200"; + + case "BRONZE": + return "border-orange-600/60 bg-orange-100 text-orange-800 dark:border-orange-500/40 dark:bg-orange-500/20 dark:text-orange-200"; + + case "IRON": + return "border-stone-500/60 bg-stone-100 text-stone-700 dark:border-stone-400/40 dark:bg-stone-400/15 dark:text-stone-300"; + + default: + return "border-base-content/30 bg-transparent text-base-content/50"; + } +} + +function RankBadge({ tier }: { tier?: ApiTierInfo }) { + const tooltip = formatRankTooltip(tier); + + return ( + + + {formatRankBadge(tier)} + + + ); +} + +function SummonerStatsSummary({ + assignedPosition, + fallbackTier, + userId, +}: { + assignedPosition?: Position; + fallbackTier?: ApiTierInfo; + userId?: string; +}) { + const profileQuery = useUserHistoryProfile(userId, DEFAULT_COMMUNITY_ID); + const tiers = profileQuery.data?.tiers ?? []; + const soloTier = + tierByQueue(tiers, "RANKED_SOLO_5x5") ?? + (fallbackTier?.queueType === "RANKED_SOLO_5x5" ? fallbackTier : undefined); + const flexTier = tierByQueue(tiers, "RANKED_FLEX_SR"); + + return ( +
+
+ {assignedPosition ? positionLabel[assignedPosition] : "-"} +
+
+ + SOLO + + + + FLEX + + +
+
+ ); +} + +function TeamMemberScoutLine({ + isCaptain, + member, + participant, +}: { + isCaptain?: boolean; + member: ApiMatch["teams"][number]["members"][number]; + participant?: ApiMatchParticipant; +}) { + return ( + + ); +} + +function ParticipantLine({ + participant, + assignedPosition, + isCaptain, +}: { + participant?: ApiMatchParticipant; + assignedPosition?: Position; + isCaptain?: boolean; +}) { + const { data: ddragon } = useDdragonManifest(); + const location = useLocation(); + const historyBackTo = `${location.pathname}${location.search}${location.hash}`; + const name = participant?.gameName ?? "알 수 없는 참가자"; + const tag = participant?.tagLine ?? "----"; + const content = ( + <> +
+ +
+
+
+ + {name} + + {isCaptain && ( + + 팀장 + + )} +
+
#{tag}
+
+ + + ); + + const className = + "flex items-center gap-3 border-b border-base-content/5 px-3 py-2 last:border-b-0"; + + if (participant?.userId) { + return ( + + {content} + + ); + } + + return
{content}
; +} + +function UpcomingGameCard({ + expanded, + game, + isNext, + onToggle, + participantByUserId, + parsedTeamIndex, + slot, + teamByIndex, +}: { + expanded: boolean; + game?: ApiMatchGameResult; + isNext?: boolean; + onToggle: () => void; + participantByUserId: Map; + parsedTeamIndex: number; + slot: TournamentCodeSlotView; + teamByIndex: Map; +}) { + const [copied, setCopied] = useState(false); + const opponentIndex = + slot.teamAIndex === parsedTeamIndex ? slot.teamBIndex : slot.teamAIndex; + const ourTeam = teamByIndex.get(parsedTeamIndex); + const opponentTeam = teamByIndex.get(opponentIndex); + const ourTeamName = teamIndexLabel(parsedTeamIndex, ourTeam?.name); + const opponentTeamName = teamIndexLabel(opponentIndex, opponentTeam?.name); + const ourCaptainName = captainName(ourTeam, participantByUserId); + const opponentCaptainName = captainName(opponentTeam, participantByUserId); + const opponentMembers = opponentTeam?.members ?? []; + const finished = Boolean(game?.winnerTeamIndex); + const won = finished && game?.winnerTeamIndex === parsedTeamIndex; + const ourSide: TeamSide = + slot.teamAIndex === parsedTeamIndex ? "blue" : "red"; + + async function handleCopy() { + if (!slot.code) return; + try { + await navigator.clipboard.writeText(slot.code); + setCopied(true); + window.setTimeout(() => setCopied(false), 1500); + } catch { + setCopied(false); + } + } + + return ( +
  • +
    +
    + + {isNext ? "다음 경기" : `${slot.gameNumber}경기`} + + + {sideShortLabel(ourSide)} + +
    + {finished ? ( +
    + + {won ? "승리" : "패배"} + + +
    + ) : ( + + )} +
    + +
    +
    +
    + {ourTeamName} +
    + {ourCaptainName && ( +
    + 팀장 {ourCaptainName} +
    + )} +
    +
    + vs +
    +
    +
    + {opponentTeamName} +
    + {opponentCaptainName && ( +
    + 팀장 {opponentCaptainName} +
    + )} +
    +
    + +
    +
    + 토너먼트 코드 +
    +
    + {slot.code ? ( + <> + + {slot.code} + + + + ) : ( + + 발급 대기 + + )} +
    +
    + + {expanded && ( +
    +
    +
    +
    + 상대팀 멤버 +
    +
    + 라인 · 티어 +
    +
    +
    + {opponentTeamName} +
    +
    + {opponentMembers.length > 0 ? ( +
    + {opponentMembers.map((member) => ( + + ))} +
    + ) : ( +
    + 상대팀 멤버 정보가 아직 없습니다. +
    + )} +
    + )} + + {finished && game?.riotMatchId && ( +
    + {game.riotMatchId} +
    + )} +
  • + ); +} + +function TeamGameCardsSection({ + defaultExpandedGameNumber, + emptyMessage, + gameByNumber, + isPreTeamBuilt, + match, + participantByUserId, + parsedTeamIndex, + teamByIndex, + slots, + title, +}: { + defaultExpandedGameNumber?: number | null; + emptyMessage: string; + gameByNumber: Map; + isPreTeamBuilt?: boolean; + match: ApiMatch; + participantByUserId: Map; + parsedTeamIndex: number; + teamByIndex: Map; + slots: TournamentCodeSlotView[]; + title: string; +}) { + const formatted = formatKoreanDate(match.scheduledAt); + const [expandedGameNumber, setExpandedGameNumber] = useState( + defaultExpandedGameNumber ?? null, + ); + const nextGameNumber = defaultExpandedGameNumber ?? null; + + return ( +
    +
    +

    + {title} +

    +
    +
    + {formatted.date} {formatted.time} +
    +
    + {GAME_MODE_LABEL[match.gameMode]} +
    +
    +
    + +
    + {isPreTeamBuilt ? ( +
    + 팀 빌딩이 끝나면 일정이 표시됩니다. +
    + ) : slots.length === 0 ? ( +
    + {emptyMessage} +
    + ) : ( +
      + {slots.map((slot) => ( + + setExpandedGameNumber((current) => + current === slot.gameNumber ? null : slot.gameNumber, + ) + } + participantByUserId={participantByUserId} + parsedTeamIndex={parsedTeamIndex} + slot={slot} + teamByIndex={teamByIndex} + /> + ))} +
    + )} +
    +
    + ); +} + +function buildFinishedSlot( + game: ApiMatchGameResult, + slotByGameNumber: Map, +): TournamentCodeSlotView { + const slot = slotByGameNumber.get(game.gameNumber); + + return { + gameNumber: game.gameNumber, + teamAIndex: game.blueTeamIndex, + teamBIndex: game.redTeamIndex, + code: slot?.code ?? null, + expiresAt: slot?.expiresAt ?? null, + state: slot?.state ?? "used", + riotMatchId: slot?.riotMatchId ?? game.riotMatchId, + }; +} + +export default function MatchTeamProgressPage() { + const { id, teamIndex } = useParams(); + const parsedTeamIndex = Number(teamIndex); + const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); + + if (!DEFAULT_COMMUNITY_ID) { + return ( +
    + `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. +
    + ); + } + + if (matchQuery.isLoading) { + return ( +
    + 팀 진행 정보를 불러오는 중... +
    + ); + } + + if ( + !Number.isInteger(parsedTeamIndex) || + parsedTeamIndex < 1 || + !matchQuery.data + ) { + return ( +
    +

    팀 정보를 찾을 수 없습니다

    + + 내전 상세로 + +
    + ); + } + + const match = matchQuery.data; + const team = match.teams.find((item) => item.teamIndex === parsedTeamIndex); + const participantByUserId = new Map( + match.participants.map((participant) => [participant.userId, participant]), + ); + const slotByGameNumber = new Map( + (match.tournamentCodes ?? []).map((slot) => [slot.gameNumber, slot]), + ); + const codes = (match.tournamentCodes ?? []).filter( + (slot) => + slot.teamAIndex === parsedTeamIndex || + slot.teamBIndex === parsedTeamIndex, + ); + const upcomingSlots = [...codes].sort( + (left, right) => left.gameNumber - right.gameNumber, + ); + const teamByIndex = new Map( + match.teams.map((team) => [team.teamIndex, team]), + ); + const gameByNumber = new Map( + (match.result?.games ?? []).map((game) => [game.gameNumber, game]), + ); + const isPreTeamBuilt = + match.status === "recruiting" || (match.teams ?? []).length === 0; + const teamGames = (match.result?.games ?? []).filter( + (game) => + game.blueTeamIndex === parsedTeamIndex || + game.redTeamIndex === parsedTeamIndex, + ); + const finishedSlots = teamGames + .filter((game) => Boolean(game.winnerTeamIndex)) + .map((game) => buildFinishedSlot(game, slotByGameNumber)) + .sort((left, right) => left.gameNumber - right.gameNumber); + const activeSlots = upcomingSlots.filter( + (slot) => !gameByNumber.get(slot.gameNumber)?.winnerTeamIndex, + ); + + if (!team) { + return ( +
    +

    아직 팀이 생성되지 않았습니다

    +

    + 경매가 완료되면 팀별 진행 페이지를 사용할 수 있습니다. +

    + + 내전 상세로 + +
    + ); + } + + return ( +
    + + ← 내전 상세로 + + +
    +

    + {teamIndexLabel(team.teamIndex, team.name)} +

    +

    + 이 팀의 다가오는 경기 일정과 결과를 한곳에서 확인합니다. +

    +
    + + + + + +
    +
    +

    + 팀 구성 +

    +
    + + {team.members.map((member) => ( + + ))} +
    +
    + ); +} diff --git a/apps/web/src/pages/UserHistoryPage.tsx b/apps/web/src/pages/UserHistoryPage.tsx new file mode 100644 index 00000000..45c4923e --- /dev/null +++ b/apps/web/src/pages/UserHistoryPage.tsx @@ -0,0 +1,1511 @@ +import { useState } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { ChevronDown, ChevronUp } from "lucide-react"; +import { Link, useLocation, useParams, useSearchParams } from "react-router"; +import { + useChampionStats, + useDdragonManifest, + useRecentMatches, + useRecentSummary, + useRefreshUserHistory, + useUserInternalHistory, + useUserHistoryProfile, + type UserHistoryFilters, +} from "../api/hooks"; +import { useRiotRefreshSocket } from "../api/useRiotRefreshSocket"; +import type { + ApiChampionStatsRow, + ApiEnqueueRefreshResult, + ApiTierInfo, + ApiRiotRefreshEvent, + ApiRecentMatchTeam, + ApiRecentMatchTeamParticipant, + ApiRecentMatchView, + DdragonManifest, + RiotQueueGroup, + RiotRankFilter, +} from "../api/types"; +import { DEFAULT_COMMUNITY_ID } from "../config"; +import { ApiError } from "../lib/api"; +import { + championDisplayName, + championIconUrl, + itemIconUrl, + profileIconUrl, + runeKeystoneIconUrl, + runeStyleIconUrl, + summonerSpellIconUrl, +} from "../lib/ddragon"; +import { + isRiotQueueGroup, + isRiotRankFilter, + LANE_LABELS, + QUEUE_GROUP_TABS, + RANK_FILTER_TABS, +} from "../lib/riot-history"; + +type ChampionSortKey = "games" | "winRate" | "kda" | "avgCsPerMin"; + +type HistoryLocationState = { + backTo?: unknown; +}; + +const SORT_LABELS: Record = { + games: "게임 수", + winRate: "승률", + kda: "KDA", + avgCsPerMin: "분당 CS", +}; + +const TIER_NAMES: Record = { + IRON: "아이언", + BRONZE: "브론즈", + SILVER: "실버", + GOLD: "골드", + PLATINUM: "플래티넘", + EMERALD: "에메랄드", + DIAMOND: "다이아몬드", + MASTER: "마스터", + GRANDMASTER: "그랜드마스터", + CHALLENGER: "챌린저", +}; + +function resolveBackTo(state: unknown) { + if (!state || typeof state !== "object") return "/"; + const backTo = (state as HistoryLocationState).backTo; + if ( + typeof backTo !== "string" || + !backTo.startsWith("/") || + backTo.startsWith("//") + ) { + return "/"; + } + return backTo; +} + +function normalizeRank(rank: string | undefined) { + switch (rank) { + case "I": + return "1"; + case "II": + return "2"; + case "III": + return "3"; + case "IV": + return "4"; + default: + return rank; + } +} + +function formatRankBadge(tier: ApiTierInfo | undefined) { + if (!tier) return "U"; + const tierInitial = + tier.tier === "GRANDMASTER" ? "GM" : tier.tier.slice(0, 1); + const rank = normalizeRank(tier.rank); + return rank ? `${tierInitial}${rank}` : tierInitial; +} + +function formatRankDetail(tier: ApiTierInfo | undefined) { + if (!tier) return "랭크 정보 없음"; + const tierName = TIER_NAMES[tier.tier] ?? tier.tier; + const rank = normalizeRank(tier.rank); + const label = rank ? `${tierName} ${rank}` : tierName; + return `${label} - ${tier.leaguePoints} LP`; +} + +function rankBadgeClass(tier: ApiTierInfo | undefined) { + switch (tier?.tier) { + case "CHALLENGER": + return "border-amber-500/60 bg-amber-100 text-amber-900 dark:border-amber-400/40 dark:bg-amber-400/20 dark:text-amber-200"; + case "GRANDMASTER": + return "border-red-500/60 bg-red-100 text-red-800 dark:border-red-400/40 dark:bg-red-400/20 dark:text-red-200"; + case "MASTER": + return "border-fuchsia-500/60 bg-fuchsia-100 text-fuchsia-800 dark:border-fuchsia-400/40 dark:bg-fuchsia-400/20 dark:text-fuchsia-200"; + case "DIAMOND": + return "border-cyan-500/60 bg-cyan-100 text-cyan-800 dark:border-cyan-400/40 dark:bg-cyan-400/20 dark:text-cyan-200"; + case "EMERALD": + return "border-emerald-500/60 bg-emerald-100 text-emerald-800 dark:border-emerald-400/40 dark:bg-emerald-400/20 dark:text-emerald-200"; + case "PLATINUM": + return "border-teal-500/60 bg-teal-100 text-teal-800 dark:border-teal-400/40 dark:bg-teal-400/20 dark:text-teal-200"; + case "GOLD": + return "border-amber-500/70 bg-amber-100 text-amber-900 dark:border-yellow-400/40 dark:bg-yellow-400/20 dark:text-yellow-200"; + case "SILVER": + return "border-slate-400/60 bg-slate-100 text-slate-700 dark:border-slate-300/40 dark:bg-slate-300/15 dark:text-slate-200"; + case "BRONZE": + return "border-orange-600/60 bg-orange-100 text-orange-800 dark:border-orange-500/40 dark:bg-orange-500/20 dark:text-orange-200"; + case "IRON": + return "border-stone-500/60 bg-stone-100 text-stone-700 dark:border-stone-400/40 dark:bg-stone-400/15 dark:text-stone-300"; + default: + return "border-base-content/30 bg-transparent text-base-content/50"; + } +} + +function RankBadge({ tier }: { tier?: ApiTierInfo }) { + const tooltip = formatRankDetail(tier); + + return ( + + + {formatRankBadge(tier)} + + + ); +} + +function ResponsiveTierLabel({ tier }: { tier?: ApiTierInfo }) { + return ( + + + + {formatRankDetail(tier)} + + + ); +} + +function formatDuration(seconds: number) { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, "0")}`; +} + +function formatDate(ms: number) { + return new Intl.DateTimeFormat("ko-KR", { + month: "long", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + }).format(new Date(ms)); +} + +function formatLastFetched(value: string | null | undefined) { + if (!value) return "저장된 갱신 시각 없음"; + return new Intl.DateTimeFormat("ko-KR", { + month: "long", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + }).format(new Date(value)); +} + +function formatEta(seconds: number) { + if (seconds < 60) return `${Math.max(1, Math.ceil(seconds))}초`; + return `${Math.ceil(seconds / 60)}분`; +} + +function formatRefreshError(error: unknown) { + if (error instanceof ApiError) { + const data = error.data; + if ( + typeof data === "object" && + data !== null && + "retryAfterSeconds" in data && + typeof data.retryAfterSeconds === "number" + ) { + return `잠시 후 다시 시도해 주세요. 약 ${formatEta(data.retryAfterSeconds)} 뒤에 요청할 수 있습니다.`; + } + return error.message; + } + return error instanceof Error ? error.message : "갱신 요청에 실패했습니다."; +} + +function ratioClass(value: number) { + if (value >= 55) return "text-blue-400"; + if (value >= 50) return "text-amber-400"; + return "text-base-content/50"; +} + +function kdaClass(value: number) { + if (value >= 4) return "text-amber-400"; + if (value >= 3) return "text-emerald-400"; + return "text-base-content/60"; +} + +function FilterButton({ + active, + children, + onClick, +}: { + active: boolean; + children: React.ReactNode; + onClick: () => void; +}) { + return ( + + ); +} + +function ChampionIcon({ + championId, + manifest, + size = "md", +}: { + championId: number; + manifest: DdragonManifest | null | undefined; + size?: "sm" | "md" | "lg"; +}) { + const iconUrl = championIconUrl(manifest, championId); + const displayName = + championDisplayName(manifest, championId) ?? String(championId); + const sizeClass = + size === "lg" ? "w-12 h-12" : size === "sm" ? "w-5 h-5" : "w-8 h-8"; + + return ( +
    + {iconUrl ? ( + {displayName} + ) : null} +
    + ); +} + +function SummaryCard({ + label, + value, + sub, +}: { + label: string; + value: React.ReactNode; + sub?: React.ReactNode; +}) { + return ( +
    +
    + {label} +
    +
    + {value} +
    + {sub && ( +
    {sub}
    + )} +
    + ); +} + +function ChampionStatsTable({ + rows, + manifest, + selectedChampionId, + onChampionSelect, +}: { + rows: ApiChampionStatsRow[]; + manifest: DdragonManifest | null | undefined; + selectedChampionId?: number; + onChampionSelect: (championId: number | null) => void; +}) { + if (rows.length === 0) { + return ( +
    + 조건에 맞는 챔피언 통계가 아직 없습니다. +
    + ); + } + + return ( +
    +
    + + + + + + + + + + + + + + + + + + {rows.map((row) => { + const displayName = + championDisplayName(manifest, row.championId) ?? + String(row.championId); + const selected = selectedChampionId === row.championId; + return ( + + + + + + + + + + + + + + ); + })} + +
    챔피언승률게임승/패KDA킬데스어시스트멀티킬CS필터
    +
    + + + {displayName} + +
    +
    + {row.winRate}% + + {row.games} + + {row.wins} /{" "} + {row.losses} + + {row.kda} + + {row.totalKills} + + {row.totalDeaths} + + {row.totalAssists} + + {row.doubleKills}/{row.tripleKills}/{row.quadraKills}/ + {row.pentaKills} + + {row.avgCs} · {row.avgCsPerMin}/m + + +
    +
    +
    + ); +} + +function ItemGrid({ + items, + trinket, + manifest, + itemKey, + variant = "card", +}: { + items: number[]; + trinket: number; + manifest: DdragonManifest | null | undefined; + itemKey: string; + variant?: "card" | "detail"; +}) { + const slots = [...items.slice(0, 6), trinket]; + const layoutClass = + variant === "detail" ? "grid-cols-7 w-[164px]" : "grid-cols-4 w-[92px]"; + + return ( +
    + {slots.map((itemId, index) => { + const url = itemIconUrl(manifest, itemId); + return ( +
    + {url ? ( + + ) : null} +
    + ); + })} +
    + ); +} + +function TeamMini({ + match, + manifest, +}: { + match: ApiRecentMatchView; + manifest: DdragonManifest | null | undefined; +}) { + return ( +
    + {match.teams.map((team) => ( +
    + {team.participants.map((participant) => { + const championName = + championDisplayName(manifest, participant.championId) ?? + String(participant.championId); + return ( +
    + + + {participant.gameName || championName} + +
    + ); + })} +
    + ))} +
    + ); +} + +type MatchDetailScales = { + maxGold: number; + maxDamage: number; + maxTaken: number; +}; + +function formatCompactNumber(value: number) { + const safeValue = Number.isFinite(value) ? value : 0; + const abs = Math.abs(safeValue); + if (abs >= 1000) { + return `${(safeValue / 1000).toFixed(1).replace(/\.0$/, "")}k`; + } + return safeValue.toLocaleString(); +} + +function resolveParticipantKda(participant: ApiRecentMatchTeamParticipant) { + const score = participant.kills + participant.assists; + return participant.deaths === 0 + ? score + : Math.round((score / participant.deaths) * 10) / 10; +} + +function barPercent(value: number, max: number) { + if (!Number.isFinite(value) || !Number.isFinite(max) || max <= 0) return 0; + return Math.max(0, Math.min(100, Math.round((value / max) * 100))); +} + +function AssetIcon({ + url, + label, + className = "w-4 h-4", +}: { + url: string | null; + label: string; + className?: string; +}) { + return ( +
    + {url ? ( + + ) : null} +
    + ); +} + +function LoadoutIcons({ + summonerSpells, + perks, + manifest, +}: { + summonerSpells: [number, number]; + perks: ApiRecentMatchTeamParticipant["perks"]; + manifest: DdragonManifest | null | undefined; +}) { + return ( +
    + + + + +
    + ); +} + +function DetailStatBar({ + label, + value, + max, + fillClass, +}: { + label: string; + value: number; + max: number; + fillClass: string; +}) { + return ( +
    +
    + {label} + + {formatCompactNumber(value)} + +
    +
    +
    +
    +
    + ); +} + +function TeamHeader({ team }: { team: ApiRecentMatchTeam }) { + const sideLabel = team.side === 100 ? "블루팀" : "레드팀"; + const sideClass = team.side === 100 ? "text-sky-400" : "text-rose-400"; + const resultClass = team.win ? "text-blue-400" : "text-red-400"; + + return ( +
    +
    + + {sideLabel} + + + {team.win ? "승리" : "패배"} + +
    +
    + 드래곤 {team.objectives?.dragon ?? 0} + 바론 {team.objectives?.baron ?? 0} + 타워 {team.objectives?.tower ?? 0} +
    +
    + ); +} + +function ParticipantRow({ + participant, + manifest, + ownerParticipantId, + scales, + teamSide, +}: { + participant: ApiRecentMatchTeamParticipant; + manifest: DdragonManifest | null | undefined; + ownerParticipantId: string; + scales: MatchDetailScales; + teamSide: 100 | 200; +}) { + const championName = + championDisplayName(manifest, participant.championId) ?? + String(participant.championId); + const championUrl = championIconUrl(manifest, participant.championId); + const participantName = participant.gameName || championName; + const isOwner = participant.puuid === ownerParticipantId; + const kda = resolveParticipantKda(participant); + const fillClass = teamSide === 100 ? "bg-sky-400/70" : "bg-rose-400/70"; + + return ( +
    +
    +
    + {championUrl ? ( + {championName} + ) : null} + {participant.championLevel > 0 && ( + + {participant.championLevel} + + )} +
    +
    + + + + +
    +
    +
    + {participantName} +
    +
    + {participant.tagLine ? `#${participant.tagLine} · ` : ""} + {(LANE_LABELS[participant.teamPosition] ?? participant.teamPosition) || + "포지션 없음"} +
    +
    +
    + +
    +
    + {participant.kills} + / + {participant.deaths} + / + {participant.assists} +
    +
    + {participant.deaths === 0 ? "Perfect" : `${kda} KDA`} +
    +
    + +
    +
    + CS + + {participant.totalCs} ({participant.csPerMin}/m) + +
    + +
    + +
    +
    + + +
    +
    + 시야 {participant.visionScore} · 와드 {participant.wardsPlaced}/ + {participant.wardsKilled} · 제어 {participant.controlWardsBought} +
    +
    + + +
    + ); +} + +function MatchDetailPanel({ + match, + manifest, + ownerParticipantId, +}: { + match: ApiRecentMatchView; + manifest: DdragonManifest | null | undefined; + ownerParticipantId: string; +}) { + const teams = [...match.teams].sort((left, right) => left.side - right.side); + const participants = teams.flatMap((team) => team.participants); + const scales: MatchDetailScales = { + maxGold: Math.max(1, ...participants.map((participant) => participant.goldEarned)), + maxDamage: Math.max( + 1, + ...participants.map((participant) => participant.damageDealtToChampions), + ), + maxTaken: Math.max(1, ...participants.map((participant) => participant.damageTaken)), + }; + + if (participants.length === 0) { + return ( +
    + 이 경기의 상세 팀 데이터가 아직 없습니다. +
    + ); + } + + return ( +
    + {teams.map((team) => ( +
    + +
    +
    +
    소환사
    +
    KDA
    +
    CS · 골드
    +
    피해량 · 와드
    +
    아이템
    +
    + {team.participants.map((participant) => ( + + ))} +
    +
    + ))} +
    + ); +} + +function RecentMatchCard({ + match, + manifest, + ownerParticipantId, +}: { + match: ApiRecentMatchView; + manifest: DdragonManifest | null | undefined; + ownerParticipantId: string; +}) { + const [expanded, setExpanded] = useState(false); + const championName = + championDisplayName(manifest, match.championId) ?? String(match.championId); + const accent = match.win ? "border-l-blue-500" : "border-l-red-500"; + const resultClass = match.win ? "text-blue-400" : "text-red-400"; + + return ( +
    +
    +
    +
    + {match.remake ? "다시하기" : match.win ? "승리" : "패배"} +
    +
    + {match.queueLabel} +
    +
    + {formatDate(match.gameCreation)} +
    +
    + {formatDuration(match.gameDuration)} +
    +
    + +
    + +
    +
    + {championName} +
    +
    + Lv.{match.championLevel} ·{" "} + {(LANE_LABELS[match.teamPosition] ?? match.teamPosition) || + "포지션 없음"} +
    +
    + +
    +
    +
    + +
    +
    + {match.kills} + / + {match.deaths} + / + {match.assists} +
    +
    + {match.deaths === 0 ? "Perfect" : `${match.kda} 평점`} +
    +
    + 킬 관여 {match.killParticipation}% +
    +
    + +
    +
    +
    + CS{" "} + + {match.totalCs} + {" "} + ({match.csPerMin}/m) +
    +
    + 시야{" "} + + {match.visionScore} + {" "} + 제어와드 {match.controlWardsBought} +
    +
    + 피해량{" "} + + {match.damageDealtToChampions.toLocaleString()} + +
    +
    +
    + + +
    +
    + +
    + +
    +
    + {expanded && ( +
    + +
    + )} +
    + ); +} + +export default function UserHistoryPage() { + const { userId } = useParams(); + const location = useLocation(); + const queryClient = useQueryClient(); + const [searchParams, setSearchParams] = useSearchParams(); + const [backTo] = useState(() => resolveBackTo(location.state)); + const [championSearch, setChampionSearch] = useState(""); + const [sortKey, setSortKey] = useState("games"); + const [refreshResult, setRefreshResult] = + useState(null); + const [refreshNotice, setRefreshNotice] = useState(null); + const queueGroupParam = searchParams.get("queueGroup"); + const rankParam = searchParams.get("rank"); + const queueGroup: RiotQueueGroup = isRiotQueueGroup(queueGroupParam) + ? queueGroupParam + : "summoners-rift"; + const isInternalQueue = queueGroup === "internal"; + const rank: RiotRankFilter = + !isInternalQueue && isRiotRankFilter(rankParam) ? rankParam : "all"; + const championIdParam = Number(searchParams.get("championId")); + const championId = + Number.isFinite(championIdParam) && championIdParam > 0 + ? championIdParam + : undefined; + const filters: UserHistoryFilters = { + queueGroup, + rank, + championId, + seasonId: searchParams.get("seasonId") ?? undefined, + }; + const aggregateFilters: UserHistoryFilters = { + queueGroup, + rank, + seasonId: filters.seasonId, + }; + const { data: ddragon } = useDdragonManifest(); + const profileQuery = useUserHistoryProfile(userId, DEFAULT_COMMUNITY_ID); + const standardHistoryEnabled = !isInternalQueue; + const championStatsQuery = useChampionStats( + userId, + aggregateFilters, + DEFAULT_COMMUNITY_ID, + standardHistoryEnabled, + ); + const summaryQuery = useRecentSummary( + userId, + filters, + DEFAULT_COMMUNITY_ID, + standardHistoryEnabled, + ); + const recentMatchesQuery = useRecentMatches( + userId, + filters, + DEFAULT_COMMUNITY_ID, + standardHistoryEnabled, + ); + const internalHistoryQuery = useUserInternalHistory( + userId, + filters, + DEFAULT_COMMUNITY_ID, + isInternalQueue, + ); + const refreshMutation = useRefreshUserHistory(userId, DEFAULT_COMMUNITY_ID); + + const profile = profileQuery.data; + const primaryTier = + profile?.tiers.find((tier) => tier.queueType === "RANKED_SOLO_5x5") ?? + profile?.tiers[0]; + const internalPages = internalHistoryQuery.data?.pages ?? []; + const internalFirstPage = internalPages[0]; + const summary = isInternalQueue + ? internalFirstPage?.summary + : summaryQuery.data; + const matches = isInternalQueue + ? internalPages.flatMap((page) => page.matches) + : (recentMatchesQuery.data?.pages.flatMap((page) => page.matches) ?? []); + const historyLastFetchedAt = isInternalQueue + ? internalFirstPage?.lastFetchedAt + : recentMatchesQuery.data?.pages[0]?.lastFetchedAt; + const matchesLoading = isInternalQueue + ? internalHistoryQuery.isLoading + : recentMatchesQuery.isLoading; + const hasNextPage = isInternalQueue + ? internalHistoryQuery.hasNextPage + : recentMatchesQuery.hasNextPage; + const isFetchingNextPage = isInternalQueue + ? internalHistoryQuery.isFetchingNextPage + : recentMatchesQuery.isFetchingNextPage; + const selectedChampionName = championId + ? (championDisplayName(ddragon, championId) ?? String(championId)) + : null; + + const visibleChampionRows = (() => { + const rows = isInternalQueue + ? (internalFirstPage?.championStats.champions ?? []) + : (championStatsQuery.data?.champions ?? []); + const keyword = championSearch.trim().toLowerCase(); + return rows + .filter((row) => { + if (!keyword) return true; + const displayName = + championDisplayName(ddragon, row.championId) ?? + String(row.championId); + return displayName.toLowerCase().includes(keyword); + }) + .sort((left, right) => right[sortKey] - left[sortKey]); + })(); + + const refreshSocket = useRiotRefreshSocket({ + puuid: isInternalQueue ? undefined : profile?.puuid, + parentJobId: refreshResult?.parentJobId, + onEvent: (event: ApiRiotRefreshEvent) => { + if (!profile || event.puuid !== profile.puuid) return; + void invalidateHistoryQueries(); + if (event.state === "completed") { + setRefreshNotice("갱신이 완료되어 전적을 다시 불러왔습니다."); + } + if (event.state === "failed") { + setRefreshNotice( + event.error + ? `갱신 실패: ${event.error}` + : "갱신에 실패했습니다. 잠시 후 다시 시도해 주세요.", + ); + } + }, + }); + + function updateSearch(next: Partial>) { + const params = new URLSearchParams(searchParams); + for (const [key, value] of Object.entries(next)) { + if (value === null || value === undefined || value === "") { + params.delete(key); + } else { + params.set(key, String(value)); + } + } + setSearchParams(params, { state: { backTo } }); + } + + async function invalidateHistoryQueries() { + await Promise.all([ + queryClient.invalidateQueries({ + queryKey: [ + "user-history-profile", + DEFAULT_COMMUNITY_ID, + userId ?? null, + ], + }), + queryClient.invalidateQueries({ + queryKey: ["user-champion-stats", DEFAULT_COMMUNITY_ID, userId ?? null], + }), + queryClient.invalidateQueries({ + queryKey: ["user-recent-summary", DEFAULT_COMMUNITY_ID, userId ?? null], + }), + queryClient.invalidateQueries({ + queryKey: ["user-recent-matches", DEFAULT_COMMUNITY_ID, userId ?? null], + }), + queryClient.invalidateQueries({ + queryKey: [ + "user-internal-history", + DEFAULT_COMMUNITY_ID, + userId ?? null, + ], + }), + ]); + } + + function handleRefresh() { + if (!userId) return; + if (isInternalQueue) { + setRefreshResult(null); + setRefreshNotice("과거의 토너먼트 결과 수집 데이터를 다시 조회합니다."); + void queryClient.invalidateQueries({ + queryKey: [ + "user-internal-history", + DEFAULT_COMMUNITY_ID, + userId ?? null, + ], + }); + return; + } + refreshMutation.mutate( + { queueGroups: [queueGroup], priority: "high" }, + { + onSuccess: (result) => { + setRefreshResult(result); + const alreadyQueued = result.subJobs.every( + (job) => job.alreadyQueued, + ); + setRefreshNotice( + alreadyQueued + ? `이미 갱신 작업이 대기 중입니다. 예상 ${formatEta(result.totalEtaSeconds)} 후 반영됩니다.` + : `갱신을 요청했습니다. 예상 ${formatEta(result.totalEtaSeconds)} 후 반영됩니다.`, + ); + }, + onError: (error) => { + setRefreshNotice(formatRefreshError(error)); + }, + }, + ); + } + + if (!DEFAULT_COMMUNITY_ID) { + return ( +
    + + `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. + +
    + ); + } + + if (profileQuery.isLoading) { + return ( +
    + + 소환사 전적을 불러오는 중... + +
    + ); + } + + if (profileQuery.error || !profile) { + return ( +
    +

    소환사를 찾을 수 없습니다

    + + 홈으로 돌아가기 + +
    + ); + } + + return ( +
    + + ← 이전으로 + + +
    +
    +
    + +
    +
    +
    +

    + {profile.gameName} +

    + + #{profile.tagLine} + +
    +
    + Lv.{profile.summonerLevel} + + 시즌: {profile.season.label} + 최근 저장: {formatLastFetched(profile.lastFetchedAt)} +
    +
    +
    +
    + {isInternalQueue ? ( + <> + {/* 내전 탭은 토너먼트 결과 DB를 조회합니다. */} + {/* Riot API 갱신 없이 수집된 내전 결과를 다시 불러옵니다. */} + 내전 기록이 확인되지 않을 경우 버튼을 눌러 갱신 (테스트) + + ) : ( + <> + {/* 이 페이지는 저장된 경기 DB만 조회합니다. */} +
    + {/* Riot API 갱신은 버튼 클릭 시 큐에서 처리합니다. */} + 아래 버튼을 누르면 기록이 갱신됩니다. + + )} +
    + + {!isInternalQueue && ( +
    + 갱신 소켓: {refreshSocket.connectionStatus} +
    + )} +
    +
    + {(refreshNotice || refreshSocket.error) && ( +
    + {refreshNotice ?? refreshSocket.error} +
    + )} +
    + +
    +
    + {QUEUE_GROUP_TABS.map((tab) => ( + + updateSearch({ queueGroup: tab.value, championId: null }) + } + > + {tab.label} + + ))} +
    +
    + {!isInternalQueue ? ( +
    + {RANK_FILTER_TABS.map((tab) => ( + + updateSearch({ rank: tab.value, championId: null }) + } + > + {tab.label} + + ))} +
    + ) : ( +
    + 내전 탭은 토너먼트 코드 결과 수집 데이터를 기준으로 집계합니다. +
    + )} + {selectedChampionName && ( + + )} + {profile.seasons.length > 0 && ( + + )} +
    +
    + +
    +

    + 최근 {summary?.windowSize ?? 20}게임 전적 요약 +

    +
    + + + + +
    +
    + 자주 플레이한 챔피언 +
    +
    + {(summary?.topChampions ?? []).map((champion) => ( + + ))} + {(summary?.topChampions ?? []).length === 0 && ( + + 기록 없음 + + )} +
    +
    +
    +
    + +
    +
    +
    +

    챔피언 통계

    +

    + 저장된 데이터를 기준으로 집계합니다. 최신 데이터가 반영되지 않을 + 수 있습니다. +

    +
    +
    + setChampionSearch(event.target.value)} + placeholder="챔피언 검색" + className="border border-base-content/10 bg-transparent px-3 py-2 text-xs focus:outline-none focus:border-primary/30" + /> + +
    +
    + + updateSearch({ championId: nextChampionId }) + } + /> +
    + +
    +
    +

    매치 히스토리

    + + 최근 저장: {formatLastFetched(historyLastFetchedAt)} + +
    + + {matchesLoading ? ( +
    + 최근 경기를 불러오는 중... +
    + ) : matches.length === 0 ? ( +
    + 조건에 맞는 최근 경기 기록이 없습니다. +
    + ) : ( +
    + {matches.map((match) => ( + + ))} +
    + )} + + {hasNextPage && ( + + )} +
    +
    + ); +}