diff --git a/.gitignore b/.gitignore index 96db833e..c48451e3 100644 --- a/.gitignore +++ b/.gitignore @@ -24,14 +24,9 @@ website/LICENSE *.md !README.md !design-qa.md -!docs/specs/internal-match-game-analysis.md -!docs/plans/internal-match-game-analysis-p0-p1.md -!docs/specs/double-elimination-connector-routing.md !docs/specs/match-status-and-result-presentation.md !docs/ux-audit-2026-11-10/06-ui-improvement-review.md !docs/ux-audit-2026-11-10/07-visual-design-review.md -!docs/plans/double-elimination-connector-routing.md -!docs/plans/redis-8.10-optimization.md /tmp/ /user-game-history/ /*.txt diff --git a/README.md b/README.md index 0f9d574e..b3f855e5 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,9 @@ pnpm --filter api build `test:redis`는 PATH의 `redis-server` 또는 `REDIS_TEST_SERVER`에 지정한 실행 파일로 Redis 8.10.x를 직접 실행합니다. 임의의 로컬 포트와 일회용 암호를 사용하고, 저장을 비활성화하며, 종료 후 프로세스와 임시 디렉터리를 정리합니다. 애플리케이션 Redis 연결 설정은 사용하지 않습니다. Windows에서는 PowerShell에서 `$env:REDIS_TEST_SERVER = 'C:\tools\redis\redis-server.exe'`처럼 지정할 수 있습니다. -커뮤니티 통계 캐시는 `riot:communitystats:v2:{communityId}:scope` Hash로 전환됩니다. 항목별 TTL은 일반 5분, 완성된 상세 24시간, 미완성 상세 60초를 유지합니다. 이전 String 캐시는 기존 TTL로 만료되며 새 캐시는 첫 조회에 생성됩니다. 구버전과 신버전은 무효화 대상이 다르므로 API 인스턴스를 같은 버전으로 함께 전환해야 합니다. 구현 범위와 검증 기록은 [Redis 변경 계획](docs/plans/redis-8.10-optimization.md)을 참고하세요. +커뮤니티 통계 캐시는 `riot:communitystats:v2:{communityId}:scope` Hash를 사용합니다. 항목별 TTL은 일반 5분, 완성된 상세 24시간, 미완성 상세 60초입니다. 이전 String 캐시는 기존 TTL로 만료되며 새 캐시는 첫 조회에 생성됩니다. 구버전과 신버전은 무효화 대상이 다르므로 배포와 롤백 모두 API 인스턴스를 같은 버전으로 함께 전환해야 합니다. + +스트림이 계속 커지면 소비자 그룹별 미처리 항목을 확인합니다. 사용이 중단된 그룹도 미처리 항목을 계속 보존할 수 있습니다. ### API New Relic APM @@ -171,6 +173,8 @@ API 성능 계측은 기본 비활성화이며 필요할 때 `API_PERF_OBSERVABI 카카오톡 기반 명령어 기능은 Dakao(커스텀 카카오톡 게이트웨이) 연동이 필요합니다. Dakao가 실행 중이 아니거나 NATS를 통해 API 서버와 연결되어 있지 않으면 일정 조회, 내전 참가, 참가 취소, 계정 등록 같은 카카오톡 명령어는 사용할 수 없습니다. +카카오톡 방을 옮긴 뒤에는 새 방에서 `!내전 데이터이관 예전 닉네임`을 실행합니다. 같은 커뮤니티에서 Riot 계정이 등록된 기존 사용자의 카카오톡 ID만 바뀝니다. 기존 사용자 ID, 권한, 참가 기록은 유지됩니다. 닉네임이 중복되거나 새 ID가 이미 다른 사용자에 연결돼 있으면 운영자가 확인합니다. 계정 소유권 확인은 운영 절차에서 담당합니다. + ## 커맨드 | Command | Description | diff --git a/apps/api/src/modules/match/match-history-result.spec.ts b/apps/api/src/modules/match/match-history-result.spec.ts new file mode 100644 index 00000000..f7e91177 --- /dev/null +++ b/apps/api/src/modules/match/match-history-result.spec.ts @@ -0,0 +1,161 @@ +import mongoose from 'mongoose'; +import { + summarizeMatchHistoryResult, + type HistoryCompetition, +} from './match-history-result'; + +const firstId = new mongoose.Types.ObjectId(); +const secondId = new mongoose.Types.ObjectId(); +const thirdId = new mongoose.Types.ObjectId(); +const teams = [ + { + teamId: firstId, + name: '첫 팀', + displayOrder: 1, + seedNumber: 1, + members: [], + }, + { + teamId: secondId, + name: '둘째 팀', + displayOrder: 2, + seedNumber: 2, + members: [], + }, + { + teamId: thirdId, + name: '셋째 팀', + displayOrder: 3, + seedNumber: 3, + members: [], + }, +]; +const finishedMatch = { + status: 'finished' as const, + competitionId: new mongoose.Types.ObjectId(), + teams: [], +}; +const singleSeries = { + status: 'completed', + entries: [{ gameWins: 2 }, { gameWins: 1 }], + outcome: { type: 'played', winnerTeamId: firstId.toString() }, +}; + +describe('summarizeMatchHistoryResult', () => { + it('shows played scores only for one completed series between two teams', () => { + const competition: HistoryCompetition = { + teams: teams.slice(0, 2), + projection: { + series: [singleSeries], + outcome: { type: 'paired-series' }, + }, + }; + + expect(summarizeMatchHistoryResult(finishedMatch, competition)).toEqual({ + type: 'score', + teamAWins: 2, + teamBWins: 1, + winnerTeamName: '첫 팀', + }); + expect( + summarizeMatchHistoryResult( + { ...finishedMatch, status: 'in-progress' }, + competition, + ), + ).toBeUndefined(); + expect( + summarizeMatchHistoryResult(finishedMatch, { + ...competition, + projection: { + ...competition.projection, + series: [singleSeries, singleSeries], + }, + }), + ).toBeUndefined(); + }); + + it('shows adjudication without a score even if some games were played', () => { + expect( + summarizeMatchHistoryResult(finishedMatch, { + teams: teams.slice(0, 2), + projection: { + series: [ + { + ...singleSeries, + outcome: { ...singleSeries.outcome, type: 'forfeit' }, + }, + ], + outcome: { type: 'paired-series' }, + }, + }), + ).toEqual({ + type: 'decision', + decision: 'forfeit', + winnerTeamName: '첫 팀', + }); + }); + + it('uses the tournament winner or joint leaders instead of a series score', () => { + expect( + summarizeMatchHistoryResult(finishedMatch, { + teams, + projection: { + series: [singleSeries], + outcome: { + type: 'double-elimination', + championTeamId: thirdId.toString(), + }, + }, + }), + ).toEqual({ type: 'winners', teamNames: ['셋째 팀'] }); + expect( + summarizeMatchHistoryResult(finishedMatch, { + teams, + projection: { + series: [singleSeries], + outcome: { + type: 'round-robin', + leaderTeamIds: [firstId.toString(), secondId.toString()], + }, + }, + }), + ).toEqual({ type: 'winners', teamNames: ['첫 팀', '둘째 팀'] }); + }); + + it('uses collected games for legacy two-team records without a Competition', () => { + const match = { + status: 'finished' as const, + teams: [ + { teamIndex: 1, name: '첫 팀', members: [] }, + { teamIndex: 2, name: '둘째 팀', members: [] }, + ], + result: { + winnerTeamIndex: 2, + riotMatchIds: ['KR_1'], + games: [ + { + gameNumber: 1, + riotMatchId: 'KR_1', + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 2, + winnerSide: 'red' as const, + gameCreation: 0, + gameDuration: 1800, + participants: [], + }, + ], + }, + }; + + expect(summarizeMatchHistoryResult(match)).toEqual({ + type: 'score', + teamAWins: 0, + teamBWins: 1, + winnerTeamName: '둘째 팀', + }); + expect( + summarizeMatchHistoryResult({ ...match, competitionId: firstId }), + ).toBeUndefined(); + }); +}); diff --git a/apps/api/src/modules/match/match-history-result.ts b/apps/api/src/modules/match/match-history-result.ts new file mode 100644 index 00000000..97336e4c --- /dev/null +++ b/apps/api/src/modules/match/match-history-result.ts @@ -0,0 +1,117 @@ +import type { MatchHistoryResult } from '@lolympus/contracts'; +import type { Competition } from '../competition/competition.schema'; +import type { CompetitionProjection } from '../competition/domain/competition-projector'; +import type { Match } from '../global/database/schema'; + +type HistoryMatch = Pick< + Match, + 'status' | 'competitionId' | 'teams' | 'result' | 'doubleElimination' +>; +export type HistoryCompetition = Pick; + +export function summarizeMatchHistoryResult( + match: HistoryMatch, + competition?: HistoryCompetition, +): MatchHistoryResult | undefined { + if (match.status !== 'finished') return; + if (!match.competitionId) return summarizeLegacyResult(match); + if (!competition) return; + + const { series, outcome } = competition.projection as Pick< + CompetitionProjection, + 'series' | 'outcome' + >; + if (!outcome) return; + + const teamName = (teamId: string) => { + const team = competition.teams.find( + (item) => String(item.teamId) === teamId, + ); + return team && (team.name.trim() || `${team.displayOrder}팀`); + }; + + const singleSeries = series?.length === 1 ? series[0] : undefined; + if (competition.teams.length === 2 && singleSeries?.status === 'completed') { + const decision = singleSeries.outcome; + const winnerTeamName = + decision.type === 'draw' ? undefined : teamName(decision.winnerTeamId); + if ( + decision.type === 'played' || + (decision.type === 'draw' && decision.basis.type === 'played') + ) { + const [teamA, teamB] = singleSeries.entries; + return { + type: 'score', + teamAWins: teamA.gameWins, + teamBWins: teamB.gameWins, + winnerTeamName, + }; + } + return { type: 'decision', decision: decision.type, winnerTeamName }; + } + + const winnerIds = + outcome.type === 'double-elimination' + ? [outcome.championTeamId] + : outcome.type === 'round-robin' + ? outcome.leaderTeamIds + : []; + const teamNames = winnerIds.map(teamName); + if (teamNames.length > 0 && teamNames.every((name) => name !== undefined)) { + return { type: 'winners', teamNames }; + } +} + +function summarizeLegacyResult( + match: HistoryMatch, +): MatchHistoryResult | undefined { + const placement = match.doubleElimination?.placements.firstTeamIndex; + if (placement !== undefined) { + const champion = match.teams.find((team) => team.teamIndex === placement); + if (champion) { + return { + type: 'winners', + teamNames: [champion.name.trim() || `${placement}팀`], + }; + } + } + + if (match.teams.length !== 2 || !match.result?.games.length) return; + const [teamA, teamB] = [...match.teams].sort( + (a, b) => a.teamIndex - b.teamIndex, + ); + const { games } = match.result; + const teamIndices = new Set([teamA.teamIndex, teamB.teamIndex]); + if ( + games.some( + ({ blueTeamIndex, redTeamIndex }) => + blueTeamIndex === redTeamIndex || + !teamIndices.has(blueTeamIndex) || + !teamIndices.has(redTeamIndex), + ) + ) + return; + const teamAWins = games.filter( + (game) => game.winnerTeamIndex === teamA.teamIndex, + ).length; + const teamBWins = games.filter( + (game) => game.winnerTeamIndex === teamB.teamIndex, + ).length; + if (teamAWins + teamBWins !== games.length) return; + const winner = match.teams.find( + (team) => team.teamIndex === match.result?.winnerTeamIndex, + ); + if ( + winner && + (teamAWins === teamBWins || + winner.teamIndex !== + (teamAWins > teamBWins ? teamA.teamIndex : teamB.teamIndex)) + ) + return; + return { + type: 'score', + teamAWins, + teamBWins, + winnerTeamName: winner && (winner.name.trim() || `${winner.teamIndex}팀`), + }; +} diff --git a/apps/api/src/modules/match/match.controller.spec.ts b/apps/api/src/modules/match/match.controller.spec.ts index 55e9a76c..9f33969d 100644 --- a/apps/api/src/modules/match/match.controller.spec.ts +++ b/apps/api/src/modules/match/match.controller.spec.ts @@ -7,6 +7,50 @@ import { RolesGuard } from '../auth/roles.guard'; import type { UserDocument } from '../global/database/schema'; import { MatchController } from './match.controller'; +describe('MatchController history summaries', () => { + it('only attaches the page results when requested', async () => { + const communityId = new mongoose.Types.ObjectId(); + const match = { _id: new mongoose.Types.ObjectId() }; + const summary = { _id: match._id.toString() }; + const historyResult = { type: 'score', teamAWins: 2, teamBWins: 1 }; + const matchService = { + listPage: jest + .fn() + .mockResolvedValue({ matches: [match], total: 1, page: 1, limit: 10 }), + serialize: jest.fn().mockReturnValue(summary), + getHistoryResults: jest + .fn() + .mockResolvedValue(new Map([[summary._id, historyResult]])), + }; + const controller = new MatchController(matchService as never); + + await expect( + controller.listMatches(undefined, communityId), + ).resolves.toMatchObject({ + matches: [summary], + }); + expect(matchService.getHistoryResults).not.toHaveBeenCalled(); + + await expect( + controller.listMatches( + undefined, + communityId, + undefined, + '10', + '1', + undefined, + undefined, + undefined, + 'desc', + 'true', + ), + ).resolves.toMatchObject({ matches: [{ ...summary, historyResult }] }); + expect(matchService.getHistoryResults).toHaveBeenCalledWith(communityId, [ + match, + ]); + }); +}); + describe('MatchController participant access', () => { function createController() { const joinedMatch = { _id: new mongoose.Types.ObjectId() }; diff --git a/apps/api/src/modules/match/match.controller.ts b/apps/api/src/modules/match/match.controller.ts index aa13b292..3e76c4c6 100644 --- a/apps/api/src/modules/match/match.controller.ts +++ b/apps/api/src/modules/match/match.controller.ts @@ -82,6 +82,7 @@ export class MatchController { @Query('scheduledFrom') scheduledFrom?: string, @Query('scheduledTo') scheduledTo?: string, @Query('sort') sort?: 'asc' | 'desc', + @Query('includeResults') includeResults?: string, ): Promise { const result = await this.matchService.listPage({ communityId, @@ -93,10 +94,14 @@ export class MatchController { scheduledTo: this.toOptionalDate(scheduledTo), sort, }); + const historyResults = + includeResults === 'true' + ? await this.matchService.getHistoryResults(communityId, result.matches) + : undefined; return { ...result, - matches: result.matches.map((match) => - this.matchService.serialize(match, { + matches: result.matches.map((match) => { + const summary = this.matchService.serialize(match, { ...(currentUser ? { joined: match.participants.some((participant) => @@ -104,8 +109,10 @@ export class MatchController { ), } : {}), - }), - ), + }); + const historyResult = historyResults?.get(summary._id); + return historyResult ? { ...summary, historyResult } : summary; + }), }; } diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index 37037459..eba7184c 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -1,3 +1,4 @@ +import type { MatchHistoryResult } from '@lolympus/contracts'; import { BadRequestException, ConflictException, @@ -20,6 +21,10 @@ import { } from '../global/database/schema'; import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants'; import { TournamentCodeService } from '../tournament-code/tournament-code.service'; +import { + summarizeMatchHistoryResult, + type HistoryCompetition, +} from './match-history-result'; import { presentPublicMatch } from './match-public.presenter'; const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; @@ -170,6 +175,47 @@ export class MatchService { }; } + public async getHistoryResults( + communityId: mongoose.Types.ObjectId, + matches: readonly MatchDocument[], + ): Promise> { + const finished = matches.filter((match) => match.status === 'finished'); + const competitionIds = finished.flatMap((match) => + match.competitionId ? [match.competitionId] : [], + ); + const competitions = new Map(); + if (competitionIds.length > 0) { + const CompetitionModel = + await this.connectionService.getModel('competition'); + const completed = await CompetitionModel.find({ + _id: { $in: competitionIds }, + communityId, + phase: 'completed', + }) + .select({ + matchId: 1, + 'teams.teamId': 1, + 'teams.name': 1, + 'teams.displayOrder': 1, + 'projection.outcome': 1, + 'projection.series': 1, + }) + .lean() + .exec(); + for (const competition of completed) { + competitions.set(competition.matchId.toString(), competition); + } + } + + const results = new Map(); + for (const match of finished) { + const id = match._id.toString(); + const result = summarizeMatchHistoryResult(match, competitions.get(id)); + if (result) results.set(id, result); + } + return results; + } + public async ensureShortCode(match: MatchDocument): Promise { if (match.shortCode) return match; diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index d415ef94..fc1cbca2 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -1,5 +1,5 @@ import { BrowserRouter, Link, NavLink, Route, Routes } from "react-router"; -import type { ReactNode } from "react"; +import { lazy, Suspense, type ReactNode } from "react"; import { useMsal } from "@azure/msal-react"; import { LogOut, Moon, Sun } from "lucide-react"; import DevAuthSwitcher from "./components/DevAuthSwitcher"; @@ -22,22 +22,15 @@ import MatchAdminPage from "./pages/admin/MatchAdminPage"; import TournamentCodesPage from "./pages/admin/TournamentCodesPage"; import { PlainPage, Tooltip, pageWidthClass } from "./ui"; -const NAV_ICON_BUTTON_CLASS = - "grid size-9 place-items-center rounded-field text-on-ink-muted transition-colors hover:bg-white/10 hover:text-on-ink"; +const InternalStatsPreview = import.meta.env.DEV + ? lazy(() => import("./preview/InternalStatsPreview")) + : null; +const MatchFlowsPreview = import.meta.env.DEV + ? lazy(() => import("./preview/MatchFlowsPreview")) + : null; -function BrandMark() { - return ( - - ); -} +const NAV_ICON_BUTTON_CLASS = + "grid size-9 shrink-0 place-items-center rounded-field text-content-muted transition-colors hover:bg-sunken-strong hover:text-content"; function MsalHeaderActions() { const { accounts, instance } = useMsal(); @@ -46,7 +39,7 @@ function MsalHeaderActions() { if (!account) { return ( 로그인 @@ -58,7 +51,7 @@ function MsalHeaderActions() { return (
- + {name} @@ -110,10 +103,10 @@ function PrimaryNavLink({ to={to} end={end} className={({ isActive }) => - `relative inline-flex h-14 items-center px-3 text-sm font-semibold transition-colors ${ + `relative inline-flex h-full items-center whitespace-nowrap px-3 text-sm font-semibold transition-colors ${ isActive - ? "text-on-ink after:absolute after:inset-x-3 after:bottom-0 after:h-[3px] after:rounded-t-full after:bg-brand-coral" - : "text-on-ink-muted hover:text-on-ink" + ? "text-content after:absolute after:inset-x-3 after:bottom-0 after:h-0.5 after:rounded-t-full after:bg-content" + : "text-content-muted hover:text-content" }` } > @@ -132,45 +125,51 @@ function AppHeader() { const canManage = role === "owner" || role === "admin"; return ( -
+
-
- + + {communityLabel} + + + {DEFAULT_COMMUNITY_ID && ( + + )} +
+
+ +
+ {isMsalConfigured && ( +
+ +
)}
-
- - {isMsalConfigured && } -
); @@ -247,7 +246,9 @@ function NotFoundPage() { function App() { return ( -
+
@@ -270,6 +271,26 @@ function App() { path="/communities/:cid/internal-stats" element={} /> + {InternalStatsPreview && ( + 전적 목업을 불러오는 중}> + + + } + /> + )} + {MatchFlowsPreview && ( + 내전 목업을 불러오는 중}> + + + } + /> + )} } diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index d434d5cf..fa8fe7ab 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -72,6 +72,10 @@ interface MatchesQueryOptions { sort?: 'asc' | 'desc'; } +interface MatchesPageQueryOptions extends MatchesQueryOptions { + includeResults?: boolean; +} + export interface UserHistoryFilters { queueGroup?: RiotQueueGroup; rank?: RiotRankFilter; @@ -89,7 +93,7 @@ export interface CommunityInternalStatsFilters { function createMatchesPath( communityId: string, - options: MatchesQueryOptions = {}, + options: MatchesPageQueryOptions = {}, ) { const searchParams = new URLSearchParams(); if (options.status) searchParams.set('status', options.status); @@ -100,6 +104,7 @@ function createMatchesPath( searchParams.set('scheduledFrom', options.scheduledFrom); if (options.scheduledTo) searchParams.set('scheduledTo', options.scheduledTo); if (options.sort) searchParams.set('sort', options.sort); + if (options.includeResults) searchParams.set('includeResults', 'true'); const queryString = searchParams.toString(); return `/communities/${communityId}/matches${queryString ? `?${queryString}` : ''}`; @@ -183,7 +188,7 @@ export function useMatches( } export function useMatchesPage( - options: MatchesQueryOptions, + options: MatchesPageQueryOptions, communityId = DEFAULT_COMMUNITY_ID, ) { const authScope = useOptionalAuthQueryScope(); @@ -200,6 +205,7 @@ export function useMatchesPage( options.scheduledFrom ?? null, options.scheduledTo ?? null, options.sort ?? null, + options.includeResults ?? false, ], queryFn: () => authScope.fetch( diff --git a/apps/web/src/components/AdminPage.tsx b/apps/web/src/components/AdminPage.tsx index 664ca528..9877133c 100644 --- a/apps/web/src/components/AdminPage.tsx +++ b/apps/web/src/components/AdminPage.tsx @@ -37,14 +37,14 @@ export function AdminPage({
{historyPanel}
- )} + ))} + ); } @@ -1624,7 +1635,7 @@ function PlayerBidStatus({
- {isSold ? "낙찰가" : "현재 입찰가"} + {isSold ? "낙찰가" : "현재 최고가"} - 관전자 모드입니다. 우측 상단에서 조작자 역할을 선택하면 입찰할 수 - 있습니다. -
- ); - } + if (!activeTeam) return null; // 경매는 "현재가보다 얼마 더?"로 생각하므로 절대값이 아니라 증분 프리셋으로 제공한다. const bidIncrements = [10, 50, 100, 200]; - const teamTone = teamIndexColorClasses(activeTeam.teamIndex); const handlePlaceBid = () => onBid(activeTeam.teamIndex, effectiveBidAmount); const isBidDisabled = isBidPending || @@ -1751,15 +1754,14 @@ function BidControls({ ? "입찰 마감 확인 중" : !canAffordNextBid ? `입찰 불가 (다음 ${formatPoints(minBid)}P · 최대 ${formatPoints(maxBid)}P)` - : `${teamIndexLabel(activeTeam.teamIndex, activeTeam.name)} 입찰 (${formatPoints(effectiveBidAmount)}P)`; - const bidButtonToneClassName = `${teamTone.border} ${teamTone.bg} ${teamTone.text} hover:bg-base-content/5`; + : `${formatPoints(effectiveBidAmount)}P 입찰`; return ( <> -
+
-
보유
+
잔여 포인트
{formatPoints(activeTeam.points)}P
@@ -1816,6 +1818,7 @@ function BidControls({ {/* 타이핑 중에는 클램프하지 않고(자릿수 입력 방해 방지) blur 시점에만 보정한다. */} setBidAmount(Number(event.target.value))} onBlur={(event) => @@ -1832,24 +1835,26 @@ function BidControls({ className="lts-input w-24 tabular-nums text-right" />
- +
{/* 모바일 sticky 입찰 바: 스크롤 위치와 무관하게 항상 입찰 가능하게 한다. */}
- +
); @@ -1867,12 +1872,13 @@ function BidLog({ bids }: { bids: AuctionStateView["bids"] }) { if (bids.length === 0) return null; return ( -
-
- - 입찰 기록 - -
+
{ + const list = scrollRef.current; + if (event.currentTarget.open && list) list.scrollTop = list.scrollHeight; + }}> + + 입찰 기록 · {bids.length}건 +
{bids.map((bid, index) => (
))}
-
+
); } @@ -2401,15 +2407,6 @@ export default function AuctionPage() { visualPreview={visualPreview} /> - {auctionState.phase === "sold" && auctionState.currentBidder && ( -
- {teamIndexLabel(auctionState.currentBidder.teamIndex)} 낙찰 —{" "} - {formatPoints(auctionState.currentBid)}P -
- )} - +
+

팀 포인트

+
    + {auctionState.teams.map((team) => ( +
  • + {teamIndexLabel(team.teamIndex, team.name)} + {formatPoints(team.points)}P + {getAuctionTeamSize(team)}/{AUCTION_MAX_TEAM_SIZE}명 +
  • + ))} +
+
{canManageAuction && ( diff --git a/apps/web/src/pages/CommunityInternalStatsPage.tsx b/apps/web/src/pages/CommunityInternalStatsPage.tsx index 24a469cb..fed13401 100644 --- a/apps/web/src/pages/CommunityInternalStatsPage.tsx +++ b/apps/web/src/pages/CommunityInternalStatsPage.tsx @@ -1,7 +1,10 @@ -import { ChevronRight } from 'lucide-react'; -import { Link, useLocation, useSearchParams } from 'react-router'; +import { useState } from 'react'; +import type { CompetitionDetailResponse } from '@lolympus/contracts'; +import { ChevronDown, Search, X } from 'lucide-react'; +import { Link, useLocation, useParams, useSearchParams } from 'react-router'; import { useCommunity, + useCompetition, useCommunityInternalStatsMatches, useCommunityLeaderboard, useDdragonManifest, @@ -13,36 +16,37 @@ import type { ApiLeaderboardRow, } from '../api/types'; import { DEFAULT_COMMUNITY_ID } from '../config'; -import { championDisplayName, championIconUrl, profileIconUrl } from '../lib/ddragon'; -import { teamIndexColorClasses, teamIndexLabel } from '../lib/league'; +import { + championDisplayName, + championIconUrl, + profileIconUrl, +} from '../lib/ddragon'; +import { + internalMatchDetailPath, + internalMatchGamePath, +} from '../lib/internal-match-routes'; +import { + getHistoryMatchTitle, + getHomeMatchSchedule, +} from './home-match-presentation'; +import { + getSeriesHistoryResultLabel, + shouldDisplaySeriesHistoryScore, +} from '../components/competition/competition-series-history'; import { Btn, Chip, EmptyNote, ErrorNote, LoadingNote, - MetaDot, - PageBody, - PageHero, Panel, PanelHeader, - Pill, PlainPage, Skeleton, } from '../ui'; type Manifest = ReturnType['data']; -function formatDateTime(value: string) { - return new Intl.DateTimeFormat('ko-KR', { - month: 'long', - day: 'numeric', - weekday: 'short', - hour: '2-digit', - minute: '2-digit', - }).format(new Date(value)); -} - function ratioClass(value: number) { if (value >= 60) return 'text-loss'; if (value >= 50) return 'text-win'; @@ -81,172 +85,138 @@ function ChampionChip({ ); } -function AvatarStack({ - members, - manifest, +function OfficialMatchResult({ + competition, }: { - members: ApiInternalMatchCard['teams'][number]['members']; - manifest: Manifest; + competition: CompetitionDetailResponse; }) { - return ( - - {members.slice(0, 5).map((member) => ( - - ))} - - ); + const { projection, teams } = competition; + const teamName = (id: string) => + teams.find(({ teamId }) => teamId === id)?.name ?? '팀 미확인'; + const outcome = projection.outcome; + if (projection.phase === 'cancelled') return '취소'; + if (projection.phase !== 'completed' || !outcome) return '결과 확정 전'; + + switch (outcome.type) { + case 'double-elimination': + return `우승 · ${teamName(outcome.championTeamId)}`; + case 'round-robin': + return outcome.leaderTeamIds.length > 0 + ? `${outcome.leaderTeamIds.length > 1 ? '공동 1위' : '우승'} · ${outcome.leaderTeamIds.map(teamName).join(', ')}` + : '대회 종료'; + case 'paired-series': { + if (projection.series.length !== 1) return '시리즈 종료'; + const series = projection.series[0]; + if (!shouldDisplaySeriesHistoryScore(series)) + return getSeriesHistoryResultLabel(series) ?? '시리즈 종료'; + const [left, right] = series.entries; + return `${teamName(left.teamId ?? '')} ${left.gameWins} : ${right.gameWins} ${teamName(right.teamId ?? '')}`; + } + } } -/** - * 내전 한 건. 두 팀 내전이면 시리즈 점수를, 여러 팀 대회면 우승 팀과 - * 규모를 보여 준다. 대회의 첫 시리즈 점수를 대회 점수처럼 보이게 하지 않는다. - */ function MatchCard({ match, - manifest, + communityId, }: { match: ApiInternalMatchCard; - manifest: Manifest; + communityId: string; }) { - const isHeadToHead = match.teams.length === 2; - const series = isHeadToHead ? match.seriesResults[0] : undefined; - const winnerTeam = match.teams.find( - (team) => team.teamIndex === match.winnerTeamIndex, + const [open, setOpen] = useState(false); + const competition = useCompetition(match.matchId, communityId, open); + const location = useLocation(); + const backTo = `${location.pathname}${location.search}`; + const recordedGames = match.games.filter( + ({ winnerTeamIndex }) => winnerTeamIndex !== null, ); - const teamName = (teamIndex: number) => - teamIndexLabel( - teamIndex, - match.teams.find((team) => team.teamIndex === teamIndex)?.name, - ); - const finishedGames = match.games.filter( - (game) => game.winnerTeamIndex !== null, - ).length; + const schedule = getHomeMatchSchedule(match.scheduledAt); return (
  • - setOpen(event.currentTarget.open)} > -
    -
    - {formatDateTime(match.scheduledAt)} - {match.status === 'in-progress' && ( - - 진행중 - - )} -
    -

    - {match.title} -

    -

    - {match.teams.length}팀 - - - {finishedGames === match.gameCount - ? `${match.gameCount}경기` - : `${finishedGames}/${match.gameCount}경기 완료`} +

    + + + {' '} + · {match.teams.length}팀 -

    -
    - - {series ? ( -
    - {[series.teamAIndex, series.teamBIndex].map((teamIndex, side) => { - const team = match.teams.find( - (candidate) => candidate.teamIndex === teamIndex, - ); - const won = series.winnerTeamIndex === teamIndex; - return ( -
    - {team && ( - - )} - - {teamName(teamIndex)} - -
    - ); - })} -
    - - {series.teamAWins} - - : - - {series.teamBWins} - -
    -
    - ) : ( -
    - {winnerTeam ? ( -
    - 우승 - - - {winnerTeam.name} - -
    + + {getHistoryMatchTitle(match.title, schedule)} + + + + {competition.data ? ( + + + ) : ( - - 우승 팀 미정 - + `${recordedGames.length}세트 수집` )} -
    - {match.teams - .filter((team) => team.teamIndex !== winnerTeam?.teamIndex) - .slice(0, 7) - .map((team) => ( - - {team.name} - - ))} + +
  • ); } @@ -255,25 +225,19 @@ function HighlightCell({ title, highlight, suffix = '', - isLoading, }: { title: string; highlight: ApiLeaderHighlight | null | undefined; suffix?: string; - isLoading: boolean; }) { const location = useLocation(); return (
    {title}
    - {isLoading ? ( - - ) : ( -
    - {highlight ? `${highlight.metric}${suffix}` : '—'} -
    - )} +
    + {highlight ? `${highlight.metric}${suffix}` : '—'} +
    {highlight ? ( ) : ( -
    - {isLoading ? ' ' : '기록 없음'} -
    +
    기록 없음
    )}
    ); @@ -293,171 +255,253 @@ function HighlightCell({ function LeaderboardTable({ rows, + ranks, manifest, + onSelectPlayer, }: { rows: ApiLeaderboardRow[]; + ranks: ReadonlyMap; manifest: Manifest; + onSelectPlayer: (id: string) => void; }) { const location = useLocation(); + const [showMetrics, setShowMetrics] = useState(false); + const metricClass = showMetrics ? '' : 'hidden 2xl:table-cell'; const historyBackTo = `${location.pathname}${location.search}${location.hash}`; return ( -
    - - - - - - - - - - - - - - - - {rows.map((row, index) => ( - - - - - - - - - - + <> +
    + setShowMetrics(!showMetrics)} + > + 상세 지표 + +
    +
    +
    - 순위 - 소환사 - 승률 - - 전적 - - KDA - - GPM - - 킬관여 - - 분당 CS - 주 챔피언
    - {index < 3 ? ( - - {index + 1} - - ) : ( - - {index + 1} - - )} - - - - - {row.summonerName} - - - - {row.winRate}% - - {row.games}전 {row.wins}승 {row.losses}패 - - {row.kda} - - {row.avgGoldPerMin} - - {row.avgKillParticipation}% - - {row.avgCsPerMin} - -
    - {row.topChampions.map((champion) => ( - - ))} -
    -
    + + + + + + + + + + + - ))} - -
    + 순위 + 소환사 + 승률 + + 전적 + + KDA + + GPM + + 킬관여 + + 분당 CS + + 주 챔피언 +
    -
    + + + {rows.map((row) => { + const rank = ranks.get(row.userId) ?? 0; + return ( + + + {rank <= 3 ? ( + + {rank} + + ) : ( + + {rank} + + )} + + + + + + {row.summonerName} + + + + + + {row.winRate}% + + + {row.games}전 {row.wins}승 {row.losses}패 + + + {row.kda} + + + {row.avgGoldPerMin} + + + {row.avgKillParticipation}% + + + {row.avgCsPerMin} + + +
    + {row.topChampions.map((champion) => ( + + ))} +
    + + + ); + })} + + +
    + ); } -function SideWinRate({ blue, red }: { blue: number; red: number }) { - const total = blue + red; - const blueShare = total > 0 ? (blue / total) * 100 : 50; +function SideWinRate({ + blue, + red, + sampleSize, +}: { + blue: number; + red: number; + sampleSize: number; +}) { + if (sampleSize === 0 || blue + red === 0) { + return

    진영 승률 집계 없음

    ; + } return ( -
    -
    - 블루 {blue}% - 레드 {red}% +
    +

    진영 승률

    +
    + 블루 {blue}% + 레드 {red}%
    +

    + {sampleSize}세트 집계 +

    ); } export default function CommunityInternalStatsPage() { + const { cid } = useParams(); + const communityId = cid ?? DEFAULT_COMMUNITY_ID; const [searchParams, setSearchParams] = useSearchParams(); - const view = searchParams.get('view') === 'ranking' ? 'ranking' : 'matches'; - const championIdParam = Number(searchParams.get('championId')); - const championId = - Number.isFinite(championIdParam) && championIdParam > 0 - ? championIdParam - : undefined; + const isRanking = searchParams.get('view') === 'ranking'; + const seasonId = searchParams.get('seasonId') || 'current'; + const query = searchParams.get('q') ?? ''; + const keyword = query.trim().toLocaleLowerCase('ko-KR'); + const format = searchParams.get('format'); + const playerId = searchParams.get('player'); + const championId = Number(searchParams.get('championId')); const filters = { - seasonId: searchParams.get('seasonId') ?? undefined, - championId, + seasonId, + championId: + Number.isFinite(championId) && championId > 0 ? championId : undefined, limit: 12, }; - const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID); - const matchesQuery = useCommunityInternalStatsMatches(filters); - const leaderboardQuery = useCommunityLeaderboard(filters); - const insightsQuery = useTeamInsights(filters); + const communityQuery = useCommunity(communityId); + const matchesQuery = useCommunityInternalStatsMatches( + filters, + communityId, + !isRanking, + ); + const leaderboardQuery = useCommunityLeaderboard(filters, communityId); + const insightsQuery = useTeamInsights(filters, communityId); const { data: ddragon } = useDdragonManifest(); - const matches = matchesQuery.data?.pages.flatMap((page) => page.matches) ?? []; + const matches = + matchesQuery.data?.pages.flatMap((page) => page.matches) ?? []; const season = - leaderboardQuery.data?.season ?? matchesQuery.data?.pages[0]?.season ?? null; + insightsQuery.data?.season ?? + leaderboardQuery.data?.season ?? + matchesQuery.data?.pages[0]?.season; const insights = insightsQuery.data; const leaderboardRows = leaderboardQuery.data?.rows ?? []; - - if (!DEFAULT_COMMUNITY_ID) { + const player = leaderboardRows.find((row) => row.userId === playerId); + const visibleMatches = matches.filter((match) => { + const matchType = match.teams.length === 2 ? 'pair' : 'tournament'; return ( - + ((format !== 'pair' && format !== 'tournament') || + matchType === format) && + (!playerId || + match.teams.some((team) => + team.members.some((member) => member.userId === playerId), + )) && + match.title.toLocaleLowerCase('ko-KR').includes(keyword) + ); + }); + const visiblePlayers = leaderboardRows.filter((row) => + row.summonerName.toLocaleLowerCase('ko-KR').includes(keyword), + ); + const hasMatchFilters = Boolean( + keyword || format === 'pair' || format === 'tournament' || playerId, + ); + const title = isRanking ? '선수 순위' : '최근 내전'; + + if (!communityId) { + return ( + - - ) : undefined - } - /> - - - - {insightsQuery.error ? ( -
    - void insightsQuery.refetch()}> - 다시 시도 - +
    + +
    +
    +

    + {communityQuery.data?.name ?? '커뮤니티'} +

    +

    + 내전 전적 +

    +
    +
    + + 전체 일정 기록 + + +
    +
    -
    - setView('matches')} - > - 최근 내전 - - setView('ranking')} - > - 선수 순위 - {leaderboardRows.length > 0 && ( - - {leaderboardRows.length} - - )} - -
    - - {view === 'matches' ? ( - - {matchesQuery.isLoading ? ( - - ) : matchesQuery.error ? ( -
    - void matchesQuery.refetch()}> - 다시 시도 - - } - /> -
    - ) : matches.length === 0 ? ( - - ) : ( -
      - {matches.map((match) => ( - - ))} -
    - )} - {matchesQuery.hasNextPage && ( -
    - void matchesQuery.fetchNextPage()} +
    +
    +
    +
    + updateParam('view', '')} > - 더 보기 - + 최근 내전 + + updateParam('view', 'ranking')} + > + 선수 순위 +
    - )} - - ) : ( - - - {leaderboardQuery.isLoading ? ( - - ) : leaderboardQuery.error ? ( -
    - void leaderboardQuery.refetch()} - > - 다시 시도 - - } + +
    + + +
    +

    + {title}{' '} + + {isRanking ? visiblePlayers.length : visibleMatches.length} + +

    + {isRanking ? ( + 승률 순 + ) : ( +
    + updateParam('format', '')} + > + 전체 + + updateParam('format', 'pair')} + > + 두 팀 내전 + + updateParam('format', 'tournament')} + > + 대회 + +
    + )}
    - ) : leaderboardRows.length === 0 ? ( - - ) : ( - + {!isRanking && playerId && ( +
    + updateParam('player', '')} + aria-label="선수 필터 해제" + > + {player?.summonerName ?? '선택한 선수'} 참가 내전{' '} + +
    + )} + + {isRanking ? ( + leaderboardQuery.isLoading ? ( + + ) : leaderboardQuery.isError && !leaderboardQuery.data ? ( +
    + void leaderboardQuery.refetch()} + > + 다시 시도 + + } + /> +
    + ) : visiblePlayers.length === 0 ? ( + + ) : ( + [ + row.userId, + index + 1, + ]), + ) + } + manifest={ddragon} + onSelectPlayer={(id) => updateParam('player', id)} + /> + ) + ) : ( + <> + {matchesQuery.isLoading ? ( + + ) : matchesQuery.isError && !matchesQuery.data ? ( +
    + void matchesQuery.refetch()} + > + 다시 시도 + + } + /> +
    + ) : visibleMatches.length === 0 ? ( + + ) : ( +
      + {visibleMatches.map((match) => ( + + ))} +
    + )} + {matchesQuery.hasNextPage && ( +
    + {hasMatchFilters && ( +

    + 필터는 불러온 {matches.length}건에 적용됩니다. +

    + )} + {matchesQuery.isFetchNextPageError && ( +

    + 이전 기록을 불러오지 못했습니다. +

    + )} + void matchesQuery.fetchNextPage()} + > + {matchesQuery.isFetchNextPageError + ? '다시 시도' + : '이전 기록 더 보기'} + +
    + )} + + )} +
    +
    + + +
    + +
    ); } diff --git a/apps/web/src/pages/HomePage.tsx b/apps/web/src/pages/HomePage.tsx index b6af8da2..6d750c89 100644 --- a/apps/web/src/pages/HomePage.tsx +++ b/apps/web/src/pages/HomePage.tsx @@ -1,149 +1,252 @@ import { useState } from 'react'; -import { - CalendarDays, - ChevronLeft, - ChevronRight, - Map as MapIcon, - Users, -} from 'lucide-react'; -import { Link } from 'react-router'; -import { mapApiMatchToMatchDetail } from '../api/mappers'; -import { useCommunity, useMatches, useMatchesPage } from '../api/hooks'; +import type { + MatchDetailResponse, + MatchSummaryResponse, +} from '@lolympus/contracts'; +import { ChevronLeft, ChevronRight } from 'lucide-react'; +import { Link, useSearchParams } from 'react-router'; +import { useMatches, useMatchesPage } from '../api/hooks'; +import { mapIdToLabel } from '../api/mappers'; import { DEFAULT_COMMUNITY_ID } from '../config'; import { Button, EmptyNote, ErrorNote, - MetaDot, - PageBody, - PageHero, Panel, PanelHeader, Pill, PlainPage, Skeleton, - type PillTone, } from '../ui'; +import { + getHistoryMatchTitle, + getHomeMatchEnrollment, + getHomeMatchSchedule, + HOME_MATCH_STATUS, +} from './home-match-presentation'; -const UPCOMING_GRID_MATCH_LIMIT = 3; -const UPCOMING_MATCH_LIST_LIMIT = UPCOMING_GRID_MATCH_LIMIT + 1; +const UPCOMING_MATCH_LIST_LIMIT = 4; const HISTORY_MATCH_PAGE_SIZE = 10; +const HOME_HISTORY_LIMIT = 5; +const DEFAULT_MAP_ID = 11; -const STATUS_PRESENTATION: Record< - string, - { label: string; tone: PillTone; live?: boolean } -> = { - recruiting: { label: '모집중', tone: 'live', live: true }, - 'team-built': { label: '팀빌딩', tone: 'gold' }, - 'in-progress': { label: '진행중', tone: 'accent', live: true }, - finished: { label: '종료', tone: 'neutral' }, -}; +const DECISION_LABELS = { + walkover: '부전승', + forfeit: '기권승', + administrative: '판정승', + draw: '무승부', +} as const; -function StatusPill({ status, onInk }: { status: string; onInk?: boolean }) { - const presentation = STATUS_PRESENTATION[status] ?? { - label: status, - tone: 'neutral' as const, - }; - const tone = - onInk && presentation.tone === 'neutral' ? 'ink' : presentation.tone; +function NextMatch({ match }: { match?: MatchDetailResponse }) { + if (!match) { + return ( +

    + 예정된 내전이 없습니다 +

    + ); + } + + const schedule = getHomeMatchSchedule(match.scheduledAt); + const enrollment = getHomeMatchEnrollment(match); + const href = `/match/${match._id}`; return ( - - {presentation.label} - +
    +
    +

    + 다음 내전 + {schedule && ( + + )} +

    +

    + {match.title} +

    +

    + {match.status !== 'recruiting' && ( + {HOME_MATCH_STATUS[match.status]} · + )} + {enrollment.capacity} · + + {enrollment.label} + + {match.mapId !== DEFAULT_MAP_ID && ( + · {mapIdToLabel(match.mapId)} + )} +

    +
    + {enrollment.canApply ? ( +
    +
    + ) : ( + + 내전 보기 +
    ); } -function formatCompactDateTime(dateLike: string) { - const date = new Date(dateLike); - if (Number.isNaN(date.getTime())) return ''; - - const weekday = new Intl.DateTimeFormat('ko-KR', { - weekday: 'short', - }).format(date); - const hours = String(date.getHours()).padStart(2, '0'); - const minutes = String(date.getMinutes()).padStart(2, '0'); - - return `${date.getMonth() + 1}/${date.getDate()} (${weekday}) ${hours}:${minutes}`; +function UpcomingMatches({ matches }: { matches: MatchDetailResponse[] }) { + return ( + + +
      + {matches.map((match) => { + const schedule = getHomeMatchSchedule(match.scheduledAt); + const { capacity, label } = getHomeMatchEnrollment(match); + return ( +
    • + + +

      + {match.title} +

      +

      + {match.status === 'recruiting' + ? label + : HOME_MATCH_STATUS[match.status]}{' '} + · {capacity} +

      +
    • + ); + })} +
    +
    + ); } -/** 정원 대비 신청 인원. 숫자와 막대를 함께 보여 남은 자리를 바로 읽게 한다. */ -function CapacityMeter({ - current, - max, - onInk = false, -}: { - current: number; - max: number; - onInk?: boolean; -}) { - const ratio = max > 0 ? Math.min(1, current / max) : 0; - const isFull = max > 0 && current >= max; - - return ( - - - - {current} - - /{max}명 - - + ); + } + case 'winners': { + const label = result.teamNames.join(', '); + return ( + + + {result.teamNames.length > 1 ? '공동 1위' : '우승'} + + + {label} + + + ); + } + case 'decision': { + return ( + + + {DECISION_LABELS[result.decision]} + + {result.winnerTeamName && ( + + {result.winnerTeamName} + + )} + + ); + } + } + } + if (match.status === 'team-built' || match.status === 'in-progress') { + return ( + - - + {HOME_MATCH_STATUS[match.status]} + + ); + } + return ( + + {HOME_MATCH_STATUS[match.status]} ); } -function HistoryTableColGroup() { - return ( - - - - - - - - ); -} - -function HistoryTableHeader() { - return ( - - - 날짜 - 내전 - 상태 - 맵 - - 참가 - - - - ); -} - -function HistoryRecordsSkeleton({ - rows = HISTORY_MATCH_PAGE_SIZE, -}: { - rows?: number; -}) { - const historySkeletons = Array.from({ length: rows }); - +function HistoryTableColumns() { return ( <> -
    - - - + + + + + + + + + + + + + + + + ); +} + +function HistoryRecordsSkeleton({ limit }: { limit: number }) { + const rows = Array.from({ length: limit }); + return ( + <> +
    +
    일정내전결과 + 참가 +
    + - {historySkeletons.map((_, index) => ( + {rows.map((_, index) => ( -
    -
    - {historySkeletons.map((_, index) => ( +