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, mapApiMatchToMatchDetail, type MatchDetailView, type ParticipantView, type TeamView, } from "../api/mappers"; import { RankBadge } from "../components/RankBadge"; import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config"; import { apiFetch, ApiError } from "../lib/api"; import { profileIconUrl } from "../lib/ddragon"; import { POSITION_ORDER, positionLabel, sideShortLabel, teamIndexColorClasses, teamIndexLabel, } from "../lib/league"; import type { AuctionTopTierThreshold, ApiMatch, ApiMatchParticipant, ApiPositionPreference, 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; const ALL_PARTICIPANT_FILTER = "all"; type ParticipantPositionFilter = Position | typeof ALL_PARTICIPANT_FILTER; type ParticipantTierFilter = string | typeof ALL_PARTICIPANT_FILTER; const PARTICIPANT_TIER_FILTERS = [ "CHALLENGER", "GRANDMASTER", "MASTER", "DIAMOND", "EMERALD", "PLATINUM", "GOLD", "SILVER", "BRONZE", "IRON", "UNRANKED", ] as const; const PARTICIPANT_TIER_LABELS: Record = { CHALLENGER: "챌린저", GRANDMASTER: "그랜드마스터", MASTER: "마스터", DIAMOND: "다이아몬드", EMERALD: "에메랄드", PLATINUM: "플래티넘", GOLD: "골드", SILVER: "실버", BRONZE: "브론즈", IRON: "아이언", UNRANKED: "언랭크", }; const PARTICIPANT_TABLE_ROW_CLASS = "h-12 border-b border-base-content/5 last:border-b-0"; function captainSlotKey(slot: CaptainSelectionSlot) { return String(slot.teamIndex); } // 백엔드 reorderPreferredPositions와 동일 규칙. 낙관적 업데이트에서 // 캐시된 preferredPositions를 즉시 갱신하는 데 사용한다. function reorderPreferredPositions( mainPosition: Position, subPosition: Position, current: ApiPositionPreference[], ): ApiPositionPreference[] { const ordered: Position[] = [mainPosition]; if (subPosition !== mainPosition) ordered.push(subPosition); for (const preference of [...current].sort( (left, right) => left.priority - right.priority, )) { if (!ordered.includes(preference.position)) { ordered.push(preference.position); } } return ordered.map((position, index) => ({ position, priority: index + 1 })); } 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 tierByQueue(tiers: ApiTierInfo[], queueType: string) { return tiers.find((tier) => tier.queueType === queueType); } function QueueRankCell({ label, tier, }: { label: "SOLO" | "FLEX"; tier?: ApiTierInfo; }) { return ( {label} ); } function PreferredPositionText({ mainPosition, subPosition, }: { mainPosition: Position; subPosition: Position; }) { return ( {positionLabel[mainPosition]} / {positionLabel[subPosition]} ); } 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 participantTierFilterValue(participant: ParticipantView) { return participant.tier?.tier ?? "UNRANKED"; } // PARTICIPANT_TIER_FILTERS는 높은 티어 → 낮은 티어 순서이므로 // 인덱스가 작을수록 상위 티어. (없는 값은 최하위로 취급) function tierRank(tier: string) { const index = PARTICIPANT_TIER_FILTERS.indexOf( tier as (typeof PARTICIPANT_TIER_FILTERS)[number], ); return index === -1 ? PARTICIPANT_TIER_FILTERS.length : index; } type ParticipantRowAdmin = { onRemove: (userId: string) => void; onChangePositions: ( userId: string, mainPosition: Position, subPosition: Position, ) => void; isRemoving: boolean; isUpdating: boolean; }; function PositionSelect({ value, sub, disabled, onChange, }: { value: Position; sub?: boolean; disabled?: boolean; onChange: (next: Position) => void; }) { return ( ); } function ParticipantRow({ participant, index, assignedPos, admin, }: { participant: ParticipantView; index: number; assignedPos?: Position; admin?: ParticipantRowAdmin; }) { const { data: ddragon } = useDdragonManifest(); const location = useLocation(); const historyBackTo = `${location.pathname}${location.search}${location.hash}`; const [confirmingRemove, setConfirmingRemove] = useState(false); // 주/부 포지션이 겹치면 두 값을 맞바꿔 항상 서로 다르게 유지한다. const handleMainChange = (next: Position) => { if (!admin) return; const sub = next === participant.subPosition ? participant.mainPosition : participant.subPosition; admin.onChangePositions(participant.userId, next, sub); }; const handleSubChange = (next: Position) => { if (!admin) return; const main = next === participant.mainPosition ? participant.subPosition : participant.mainPosition; admin.onChangePositions(participant.userId, main, next); }; return ( {index + 1}
{participant.summonerName} #{participant.tag} {participant.excluded && ( 제외 )}
{assignedPos ? ( ) : admin ? ( <> / {confirmingRemove ? ( ) : ( )} ) : ( )} ); } function TeamParticipantMobileRow({ participant, }: { participant: ParticipantView; }) { const { data: ddragon } = useDdragonManifest(); const location = useLocation(); const historyBackTo = `${location.pathname}${location.search}${location.hash}`; return (
{participant.summonerName} #{participant.tag} {participant.excluded && ( 제외 )}
); } function ParticipantMobileRow({ participant, admin, }: { participant: ParticipantView; admin?: ParticipantRowAdmin; }) { const { data: ddragon } = useDdragonManifest(); const location = useLocation(); const historyBackTo = `${location.pathname}${location.search}${location.hash}`; const [confirmingRemove, setConfirmingRemove] = useState(false); const handleMainChange = (next: Position) => { if (!admin) return; const sub = next === participant.subPosition ? participant.mainPosition : participant.subPosition; admin.onChangePositions(participant.userId, next, sub); }; const handleSubChange = (next: Position) => { if (!admin) return; const main = next === participant.mainPosition ? participant.subPosition : participant.mainPosition; admin.onChangePositions(participant.userId, main, next); }; return (
{participant.summonerName} #{participant.tag} {participant.excluded && ( 제외 )}
{admin && (
/ {confirmingRemove ? ( ) : ( )}
)}
); } function ParticipantTable({ participants, maxParticipants, joined, canJoin, onJoin, isJoining, canManage, onRemoveParticipant, onUpdatePositions, removingUserId, updatingUserId, }: { participants: ParticipantView[]; maxParticipants: number; joined: boolean; canJoin: boolean; onJoin: () => void; isJoining: boolean; canManage: boolean; onRemoveParticipant: (userId: string) => void; onUpdatePositions: ( userId: string, mainPosition: Position, subPosition: Position, ) => void; removingUserId: string | null; updatingUserId: string | null; }) { const [positionFilter, setPositionFilter] = useState(ALL_PARTICIPANT_FILTER); const [tierFilter, setTierFilter] = useState( ALL_PARTICIPANT_FILTER, ); const filteredParticipants = participants.filter((participant) => { const matchesPosition = positionFilter === ALL_PARTICIPANT_FILTER || participant.mainPosition === positionFilter; const matchesTier = tierFilter === ALL_PARTICIPANT_FILTER || tierRank(participantTierFilterValue(participant)) <= tierRank(tierFilter); return matchesPosition && matchesTier; }); const isFiltered = positionFilter !== ALL_PARTICIPANT_FILTER || tierFilter !== ALL_PARTICIPANT_FILTER; const positionFilteredParticipants = participants.filter( (participant) => positionFilter === ALL_PARTICIPANT_FILTER || participant.mainPosition === positionFilter, ); // "이상" 임계값으로 쓸 수 있는 티어 = 참가자 중 실제 존재하는 티어. // 언랭크는 "이상" 기준으로 전체와 동일하므로 임계값 후보에서 제외한다. const presentTiers = new Set( positionFilteredParticipants.map(participantTierFilterValue), ); const availableTiers = PARTICIPANT_TIER_FILTERS.filter( (tier) => tier !== "UNRANKED" && presentTiers.has(tier), ); const tierAtOrAboveCounts = new Map( availableTiers.map((tier) => [ tier, positionFilteredParticipants.filter( (participant) => tierRank(participantTierFilterValue(participant)) <= tierRank(tier), ).length, ]), ); const positionCounts = new Map( POSITION_ORDER.map((position) => [ position, participants.filter( (participant) => participant.mainPosition === position, ).length, ]), ); return (

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

{POSITION_ORDER.map((position) => { const active = positionFilter === position; const count = positionCounts.get(position) ?? 0; return ( ); })}
{isFiltered && ( )} {filteredParticipants.length}/{participants.length}명
소환사 현재 티어 포지션
{filteredParticipants.length > 0 ? ( filteredParticipants.map((participant) => ( )) ) : (
조건에 맞는 참가자가 없습니다.
)}
{canManage && } {canManage && ( )} {filteredParticipants.length > 0 ? ( filteredParticipants.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) => ( ))}
{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 matchQueryKey = ["match", DEFAULT_COMMUNITY_ID, id ?? null]; const removeParticipantMutation = useMutation({ mutationFn: (userId: string) => apiFetch( `/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`, { method: "DELETE" }, ), onMutate: async (userId: string) => { await queryClient.cancelQueries({ queryKey: matchQueryKey }); const previous = queryClient.getQueryData(matchQueryKey); if (previous) { queryClient.setQueryData(matchQueryKey, { ...previous, participants: previous.participants.filter( (participant) => participant.userId !== userId, ), }); } return { previous }; }, onError: (_error, _userId, context) => { if (context?.previous) { queryClient.setQueryData(matchQueryKey, context.previous); } }, onSettled: () => { void queryClient.invalidateQueries({ queryKey: matchQueryKey }); void queryClient.invalidateQueries({ queryKey: ["matches", DEFAULT_COMMUNITY_ID], }); }, }); const updateParticipantMutation = useMutation({ mutationFn: ({ userId, mainPosition, subPosition, }: { userId: string; mainPosition: Position; subPosition: Position; }) => apiFetch( `/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`, { method: "PATCH", body: JSON.stringify({ mainPosition, subPosition }), }, ), onMutate: async ({ userId, mainPosition, subPosition }) => { await queryClient.cancelQueries({ queryKey: matchQueryKey }); const previous = queryClient.getQueryData(matchQueryKey); if (previous) { queryClient.setQueryData(matchQueryKey, { ...previous, participants: previous.participants.map((participant) => participant.userId === userId ? { ...participant, preferredPositions: reorderPreferredPositions( mainPosition, subPosition, participant.preferredPositions, ), } : participant, ), }); } return { previous }; }, onError: (_error, _variables, context) => { if (context?.previous) { queryClient.setQueryData(matchQueryKey, context.previous); } }, onSettled: () => { void queryClient.invalidateQueries({ queryKey: matchQueryKey }); }, }); 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}
)} {removeParticipantMutation.error instanceof Error && (
{removeParticipantMutation.error.message}
)} {updateParticipantMutation.error instanceof Error && (
{updateParticipantMutation.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} canManage={canManageAuction} onRemoveParticipant={(userId) => removeParticipantMutation.mutate(userId) } onUpdatePositions={(userId, mainPosition, subPosition) => updateParticipantMutation.mutate({ userId, mainPosition, subPosition, }) } removingUserId={ removeParticipantMutation.isPending ? (removeParticipantMutation.variables ?? null) : null } updatingUserId={ updateParticipantMutation.isPending ? (updateParticipantMutation.variables?.userId ?? null) : null } /> {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-xs 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}
  • ))}
)}
); }