This commit is contained in:
dahyeon committed 2026-05-02 02:59:33 -07:00
1 parent b152a5b0fa
commit 2379051196
32 files changed
+1682 -383

No files matched your search

+10
View File
@@ -8,12 +8,14 @@ import AuthCallbackPage from './pages/AuthCallback';
import HomePage from './pages/HomePage';
import LoginPage from './pages/Login';
import MatchDetailPage from './pages/MatchDetailPage';
import MatchTeamProgressPage from './pages/MatchTeamProgressPage';
import AuctionPage from './pages/AuctionPage';
import UserHistoryPage from './pages/UserHistoryPage';
import CommunityInternalStatsPage from './pages/CommunityInternalStatsPage';
import InternalMatchDetailPage from './pages/InternalMatchDetailPage';
import LegacyImportPage from './pages/admin/LegacyImportPage';
import LegacyMatchesPage from './pages/admin/LegacyMatchesPage';
import MatchAdminPage from './pages/admin/MatchAdminPage';
import TournamentCodesPage from './pages/admin/TournamentCodesPage';
function MsalHeaderActions() {
@@ -74,6 +76,10 @@ function App() {
<Route path="/login" element={<LoginPage />} />
<Route path="/auth/callback" element={<AuthCallbackPage />} />
<Route path="/match/:id" element={<MatchDetailPage />} />
<Route
path="/match/:id/team/:side/:groupIndex"
element={<MatchTeamProgressPage />}
/>
<Route path="/match/:id/auction" element={<AuctionPage />} />
<Route path="/users/:userId/history" element={<UserHistoryPage />} />
<Route
@@ -84,6 +90,10 @@ function App() {
path="/communities/:cid/internal-stats/match/:matchId"
element={<InternalMatchDetailPage />}
/>
<Route
path="/admin/communities/:cid/matches"
element={<MatchAdminPage />}
/>
<Route
path="/admin/communities/:cid/tournament-codes"
element={<TournamentCodesPage />}
+21
View File
@@ -30,6 +30,7 @@ import type {
StartLegacyImportRequest,
StartLegacyImportResponse,
MatchStatus,
MatchMutationRequest,
MatchesResponse,
MeResponse,
RiotQueueGroup,
@@ -130,6 +131,26 @@ export function useAuction(
});
}
export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (body: MatchMutationRequest) =>
apiFetch<ApiMatch>(`/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<MatchMutationRequest> }) =>
apiFetch<ApiMatch>(`/communities/${communityId}/matches/${matchId}`, {
method: 'PATCH',
body: JSON.stringify(body),
}),
});
}
function createUserHistoryPath(
communityId: string,
userId: string,
+31 -24
View File
@@ -25,6 +25,7 @@ export interface ParticipantView {
mainPosition: Position;
subPosition: Position;
profileIconId: number;
excluded?: boolean;
}
export interface TeamParticipantView extends ParticipantView {
@@ -34,6 +35,7 @@ export interface TeamParticipantView extends ParticipantView {
export interface TeamView {
side: TeamSide;
groupIndex: number;
name: string;
participants: TeamParticipantView[];
}
@@ -48,6 +50,7 @@ export interface MatchDetailView {
map: string;
maxParticipants: number;
gameCount: number;
gameMode: ApiMatch["gameMode"];
tournamentCodes: TournamentCodeSlotView[];
joined: boolean;
participants: ParticipantView[];
@@ -62,6 +65,8 @@ export interface MatchDetailView {
gameNumber: number;
riotMatchId: string;
winnerSide: TeamSide;
blueGroupIndex: number;
redGroupIndex: number;
gameCreation: number;
gameDuration: number;
participants: Array<{
@@ -74,6 +79,7 @@ export interface MatchDetailView {
win: boolean;
}>;
}>;
seriesResults: NonNullable<ApiMatch["result"]>["seriesResults"];
};
prizes: string[];
notices: string[];
@@ -96,6 +102,7 @@ export interface AuctionPlayerView extends ParticipantView {
export interface AuctionTeamView {
side: TeamSide;
groupIndex: number;
captainUserId: string;
captainName: string;
points: number;
@@ -108,18 +115,19 @@ export interface AuctionTeamView {
export interface AuctionStateView {
matchId: string;
phase: ApiAuction["phase"];
teams: [AuctionTeamView, AuctionTeamView];
teams: AuctionTeamView[];
currentPlayer: AuctionPlayerView | null;
currentPlayerIndex: number;
totalPlayers: number;
auctionOrder: AuctionPlayerView[];
bids: {
side: TeamSide;
groupIndex: number;
amount: number;
timestamp: string;
}[];
currentBid: number;
currentBidder: TeamSide | null;
currentBidder: { side: TeamSide; groupIndex: number } | null;
timer: number;
maxTimer: number;
deadline?: string;
@@ -208,6 +216,7 @@ function mapMatchParticipantToView(
mainPosition,
subPosition,
profileIconId: participant.profileIconId ?? 0,
excluded: participant.excluded ?? false,
};
}
@@ -262,6 +271,7 @@ function mapAuctionTeamToView(
): AuctionTeamView {
return {
side: team.side,
groupIndex: team.groupIndex ?? 1,
captainUserId: team.captainUserId,
captainName:
participantLookup.get(team.captainUserId)?.summonerName ??
@@ -396,6 +406,7 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
const teams = match.teams.map((team) => ({
side: team.side,
groupIndex: team.groupIndex ?? 1,
name: team.name || sideLabel(team.side),
participants: team.members.map((member) => {
const participant =
@@ -423,7 +434,8 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
description: match.description,
map: mapIdToLabel(match.mapId),
maxParticipants: match.maxParticipants,
gameCount: match.gameCount ?? 3,
gameCount: match.gameCount ?? 3,
gameMode: match.gameMode ?? "pair",
tournamentCodes: match.tournamentCodes ?? [],
joined: Boolean(match.joined),
participants,
@@ -440,6 +452,7 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
games: [...(match.result.games ?? [])].sort(
(left, right) => left.gameNumber - right.gameNumber,
),
seriesResults: match.result.seriesResults ?? [],
}
: undefined,
prizes: match.prizes,
@@ -462,22 +475,11 @@ export function mapApiAuctionToAuctionState(
const auctionPlayerLookup = new Map(
auctionOrder.map((player) => [player.userId, player]),
);
const blueTeam =
auction.teams.find((team) => team.side === "blue") ??
({
side: "blue",
captainUserId: "",
points: 0,
members: [],
} satisfies ApiAuctionTeam);
const redTeam =
auction.teams.find((team) => team.side === "red") ??
({
side: "red",
captainUserId: "",
points: 0,
members: [],
} satisfies ApiAuctionTeam);
const teams = [...auction.teams].sort(
(left, right) =>
(left.groupIndex ?? 1) - (right.groupIndex ?? 1) ||
(left.side === "blue" ? -1 : 1),
);
const totalPlayers = auctionOrder.length;
const currentPlayer =
@@ -500,21 +502,26 @@ export function mapApiAuctionToAuctionState(
return {
matchId: auction.matchId,
phase: auction.phase,
teams: [
mapAuctionTeamToView(blueTeam, auctionPlayerLookup, participantLookup),
mapAuctionTeamToView(redTeam, auctionPlayerLookup, participantLookup),
],
teams: teams.map((team) =>
mapAuctionTeamToView(team, auctionPlayerLookup, participantLookup),
),
currentPlayer,
currentPlayerIndex,
totalPlayers,
auctionOrder,
bids: auction.bids.map((bid) => ({
side: bid.side,
groupIndex: bid.groupIndex ?? 1,
amount: bid.amount,
timestamp: bid.timestamp,
})),
currentBid: auction.currentBid,
currentBidder: auction.currentBidder ?? null,
currentBidder: auction.currentBidder
? {
side: auction.currentBidder,
groupIndex: auction.currentBidderGroupIndex ?? 1,
}
: null,
timer,
maxTimer: auction.maxTimerSeconds,
deadline: auction.currentDeadline,
+31
View File
@@ -1,6 +1,7 @@
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'
@@ -116,6 +117,8 @@ export type TournamentCodeSlotState = TournamentCodeState | 'pending';
export interface TournamentCodeSlotView {
gameNumber: number;
blueGroupIndex: number;
redGroupIndex: number;
code: string | null;
expiresAt: string | null;
state: TournamentCodeSlotState;
@@ -131,6 +134,7 @@ export interface ApiMatchParticipant {
tier?: ApiTierInfo;
preferredPositions: ApiPositionPreference[];
joinedAt: string;
excluded?: boolean;
}
export interface ApiMatchTeamMember {
@@ -141,6 +145,7 @@ export interface ApiMatchTeamMember {
export interface ApiMatchTeam {
side: TeamSide;
groupIndex: number;
name: string;
captainUserId?: string;
members: ApiMatchTeamMember[];
@@ -160,6 +165,8 @@ export interface ApiMatchGameResult {
gameNumber: number;
riotMatchId: string;
winnerSide: TeamSide;
blueGroupIndex: number;
redGroupIndex: number;
gameCreation: number;
gameDuration: number;
participants: ApiMatchGameResultParticipant[];
@@ -172,6 +179,13 @@ export interface ApiMatchResult {
mvpUserId?: string;
riotMatchIds: string[];
games: ApiMatchGameResult[];
seriesResults?: Array<{
blueGroupIndex: number;
redGroupIndex: number;
blueScore: number;
redScore: number;
winnerSide?: TeamSide;
}>;
}
export interface ApiMatchScheduleItem {
@@ -189,6 +203,7 @@ export interface ApiMatch {
scheduledAt: string;
maxParticipants: number;
gameCount: number;
gameMode: MatchGameMode;
tournamentCodes?: TournamentCodeSlotView[];
hostUserId?: string;
participants: ApiMatchParticipant[];
@@ -222,6 +237,7 @@ export interface ApiAuctionTeamMember {
export interface ApiAuctionTeam {
side: TeamSide;
groupIndex: number;
captainUserId: string;
points: number;
members: ApiAuctionTeamMember[];
@@ -229,6 +245,7 @@ export interface ApiAuctionTeam {
export interface ApiAuctionBid {
side: TeamSide;
groupIndex?: number;
amount: number;
bidderUserId: string;
timestamp: string;
@@ -244,6 +261,7 @@ export interface ApiAuction {
bids: ApiAuctionBid[];
currentBid: number;
currentBidder?: TeamSide;
currentBidderGroupIndex?: number;
maxTimerSeconds: number;
currentDeadline?: string;
initialPoints: number;
@@ -275,6 +293,19 @@ 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;
+1
View File
@@ -13,6 +13,7 @@ type ConnectionStatus =
interface BidPayload {
side: TeamSide;
groupIndex?: number;
amount: number;
bidderUserId?: string;
}
+96 -38
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Link, useParams } from 'react-router';
import { useAuction, useDdragonManifest, useMatch, useMe } from '../api/hooks';
import {
@@ -20,12 +20,32 @@ import {
profileIconUrl,
} from '../lib/ddragon';
import { positionIcon, positionLabel } from '../lib/league';
import type { ApiRiotLaneStats, Position } from '../api/types';
import type { ApiRiotLaneStats, Position, TeamSide } from '../api/types';
type CaptainRole = {
side: TeamSide;
groupIndex: number;
};
function formatPoints(value: number) {
return value.toLocaleString();
}
function teamLabel(side: 'blue' | 'red', groupIndex = 1) {
const sideLabel = side === 'blue' ? '블루팀' : '레드팀';
return groupIndex === 1 ? sideLabel : `${groupIndex}조 ${sideLabel}`;
}
function isCurrentBidder(
currentBidder: AuctionStateView['currentBidder'],
team: Pick<AuctionStateView['teams'][number], 'side' | 'groupIndex'>,
) {
return (
currentBidder?.side === team.side &&
currentBidder.groupIndex === team.groupIndex
);
}
const AUCTION_MAX_TEAM_SIZE = 5;
const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
const POSITION_TO_RIOT_LANE = {
@@ -209,7 +229,7 @@ function TeamPanel({
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<span className={`text-[11px] font-bold uppercase tracking-wide ${sideColor}`}>
{team.side === 'blue' ? '블루팀' : '레드팀'}
{teamLabel(team.side, team.groupIndex)}
</span>
<span className="text-[10px] text-base-content/30">
팀장: {team.captainName}
@@ -265,7 +285,7 @@ function TeamPanel({
length: Math.max(0, AUCTION_MAX_TEAM_SIZE - 1 - team.members.length),
}).map((_, index) => (
<div
key={`empty-${team.side}-${index}`}
key={`empty-${team.side}-${team.groupIndex}-${index}`}
className="px-3 py-1.5 h-[34px] flex items-center"
>
<div className="w-6 h-6 border border-dashed border-base-content/8 shrink-0" />
@@ -385,9 +405,12 @@ function PlayerSpotlight({
<div className="flex items-center gap-2">
{state.currentBidder && (
<span
className={`text-[10px] font-bold uppercase ${state.currentBidder === 'blue' ? 'text-blue-400' : 'text-red-400'}`}
className={`text-[10px] font-bold uppercase ${state.currentBidder.side === 'blue' ? 'text-blue-400' : 'text-red-400'}`}
>
{state.currentBidder === 'blue' ? '블루' : '레드'}
{teamLabel(
state.currentBidder.side,
state.currentBidder.groupIndex,
)}
</span>
)}
<span className="text-lg font-black text-amber-400 tabular-nums">
@@ -403,21 +426,22 @@ function PlayerSpotlight({
function BidControls({
state,
captainSide,
captainRole,
onBid,
}: {
state: AuctionStateView;
captainSide: 'spectator' | 'blue' | 'red';
onBid: (side: 'blue' | 'red', amount: number) => void;
captainRole: CaptainRole | null;
onBid: (side: TeamSide, groupIndex: number, amount: number) => void;
}) {
const [bidAmount, setBidAmount] = useState(100);
const minBid = state.currentBid + 10;
const activeTeam =
captainSide === 'blue'
? state.teams[0]
: captainSide === 'red'
? state.teams[1]
: null;
const activeTeam = captainRole
? state.teams.find(
(team) =>
team.side === captainRole.side &&
team.groupIndex === captainRole.groupIndex,
)
: null;
const activeTeamSize = activeTeam ? activeTeam.members.length + 1 : 0;
const isActiveTeamFull = activeTeamSize >= AUCTION_MAX_TEAM_SIZE;
@@ -466,7 +490,7 @@ function BidControls({
/>
</div>
<button
onClick={() => onBid(activeTeam.side, bidAmount)}
onClick={() => onBid(activeTeam.side, activeTeam.groupIndex, bidAmount)}
disabled={
isActiveTeamFull ||
bidAmount > activeTeam.points ||
@@ -479,8 +503,8 @@ function BidControls({
}`}
>
{isActiveTeamFull
? `${activeTeam.side === 'blue' ? '블루팀' : '레드팀'} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})`
: `${activeTeam.side === 'blue' ? '블루팀' : '레드팀'} 입찰 (${formatPoints(bidAmount)}P)`}
? `${teamLabel(activeTeam.side, activeTeam.groupIndex)} 정원 완료 (${activeTeamSize}/${AUCTION_MAX_TEAM_SIZE})`
: `${teamLabel(activeTeam.side, activeTeam.groupIndex)} 입찰 (${formatPoints(bidAmount)}P)`}
</button>
</div>
);
@@ -508,7 +532,7 @@ function BidLog({ bids }: { bids: AuctionStateView['bids'] }) {
<span
className={`font-bold uppercase ${bid.side === 'blue' ? 'text-blue-400' : 'text-red-400'}`}
>
{bid.side === 'blue' ? '블루' : '레드'}
{teamLabel(bid.side, bid.groupIndex)}
</span>
<span className="text-base-content/30">→</span>
<span className="text-amber-400 tabular-nums font-semibold">
@@ -533,6 +557,7 @@ export default function AuctionPage() {
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
const socket = useAuctionSocket(id);
const captainSide = useDevCaptainSide();
const [captainGroupIndex, setCaptainGroupIndex] = useState(1);
const [now, setNow] = useState(() => Date.now());
const [assignedPosition, setAssignedPosition] = useState<Position>('MID');
@@ -546,6 +571,17 @@ export default function AuctionPage() {
liveAuction && matchQuery.data
? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now))
: null;
const availableGroups = useMemo(() => {
const groups = new Set((auctionState?.teams ?? []).map((team) => team.groupIndex));
return [...groups].sort((left, right) => left - right);
}, [auctionState?.teams]);
const captainRole: CaptainRole | null =
captainSide === 'spectator'
? null
: {
side: captainSide,
groupIndex: captainGroupIndex,
};
useEffect(() => {
if (auctionState?.currentPlayer) {
@@ -553,6 +589,13 @@ export default function AuctionPage() {
}
}, [auctionState?.currentPlayer?.id]);
useEffect(() => {
if (availableGroups.length === 0) return;
if (!availableGroups.includes(captainGroupIndex)) {
setCaptainGroupIndex(availableGroups[0]);
}
}, [availableGroups, captainGroupIndex]);
if (!DEFAULT_COMMUNITY_ID) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
@@ -681,6 +724,21 @@ export default function AuctionPage() {
<option value="blue">블루팀장</option>
<option value="red">레드팀장</option>
</select>
{captainSide !== 'spectator' && availableGroups.length > 1 && (
<select
value={captainGroupIndex}
onChange={(event) =>
setCaptainGroupIndex(Number(event.target.value))
}
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
>
{availableGroups.map((groupIndex) => (
<option key={groupIndex} value={groupIndex}>
{groupIndex}조
</option>
))}
</select>
)}
</div>
</div>
</div>
@@ -689,13 +747,16 @@ export default function AuctionPage() {
<TimerBar timer={auctionState.timer} maxTimer={auctionState.maxTimer} />
)}
<div className="flex flex-col lg:flex-row gap-4 mt-4">
<div className="w-full lg:w-56 shrink-0">
<TeamPanel
team={auctionState.teams[0]}
isActive={auctionState.currentBidder === 'blue'}
isLeft
/>
<div className="grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_minmax(340px,440px)] gap-4 mt-4">
<div className="grid sm:grid-cols-2 gap-4 content-start">
{auctionState.teams.map((team) => (
<TeamPanel
key={`${team.side}-${team.groupIndex}`}
team={team}
isActive={isCurrentBidder(auctionState.currentBidder, team)}
isLeft={team.side === 'blue'}
/>
))}
</div>
<div className="flex-1 min-w-0 space-y-4">
@@ -721,20 +782,25 @@ export default function AuctionPage() {
{auctionState.phase === 'sold' && auctionState.currentBidder && (
<div
className={`text-center py-3 border text-sm font-bold ${
auctionState.currentBidder === 'blue'
auctionState.currentBidder.side === 'blue'
? 'border-blue-500/20 bg-blue-500/8 text-blue-400'
: 'border-red-500/20 bg-red-500/8 text-red-400'
}`}
>
{auctionState.currentBidder === 'blue' ? '블루팀' : '레드팀'} 낙찰
{teamLabel(
auctionState.currentBidder.side,
auctionState.currentBidder.groupIndex,
)} 낙찰
{' '}— {formatPoints(auctionState.currentBid)}P
</div>
)}
<BidControls
state={auctionState}
captainSide={captainSide}
onBid={(side, amount) => socket.placeBid({ side, amount })}
captainRole={captainRole}
onBid={(side, groupIndex, amount) =>
socket.placeBid({ side, groupIndex, amount })
}
/>
<BidLog bids={auctionState.bids} />
@@ -788,14 +854,6 @@ export default function AuctionPage() {
</>
)}
</div>
<div className="w-full lg:w-56 shrink-0">
<TeamPanel
team={auctionState.teams[1]}
isActive={auctionState.currentBidder === 'red'}
isLeft={false}
/>
</div>
</div>
</main>
);
+23 -7
View File
@@ -1,6 +1,6 @@
import { Link } from 'react-router';
import { mapApiMatchToMatchDetail } from '../api/mappers';
import { useMatches } from '../api/hooks';
import { useMatches, useMe } from '../api/hooks';
import { DEFAULT_COMMUNITY_ID } from '../config';
function StatusBadge({ status }: { status: string }) {
@@ -49,6 +49,7 @@ export default function HomePage() {
{ status: 'finished', limit: 10 },
DEFAULT_COMMUNITY_ID,
);
const meQuery = useMe();
if (!DEFAULT_COMMUNITY_ID) {
return (
@@ -84,6 +85,11 @@ export default function HomePage() {
finishedMatchesQuery.data?.map(mapApiMatchToMatchDetail) ?? [];
const nextMatch = upcomingMatches[0];
const upcomingCards = nextMatch ? upcomingMatches.slice(1) : upcomingMatches;
const currentUser =
meQuery.data?.memberships.find(
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
)?.user ?? null;
const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin';
return (
<main className="max-w-5xl mx-auto px-4 sm:px-6">
@@ -92,12 +98,22 @@ export default function HomePage() {
<h2 className="text-xs font-bold text-base-content/40 uppercase tracking-widest">
다음 내전
</h2>
<Link
to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`}
className="text-xs font-bold text-primary hover:underline"
>
내전 전적 보기
</Link>
<div className="flex items-center gap-3">
{canManage && (
<Link
to={`/admin/communities/${DEFAULT_COMMUNITY_ID}/matches`}
className="text-xs font-bold text-base-content/35 hover:text-primary"
>
내전 관리
</Link>
)}
<Link
to={`/communities/${DEFAULT_COMMUNITY_ID}/internal-stats`}
className="text-xs font-bold text-primary hover:underline"
>
내전 전적 보기
</Link>
</div>
</div>
{nextMatch ? (
+212 -58
View File
@@ -22,7 +22,47 @@ import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config';
import { apiFetch, ApiError } from '../lib/api';
import { profileIconUrl } from '../lib/ddragon';
import { positionIcon, positionLabel } from '../lib/league';
import type { Position, TournamentCodeSlotView } from '../api/types';
import type {
ApiMatchParticipant,
Position,
TeamSide,
TournamentCodeSlotView,
} from '../api/types';
type CaptainSelectionSlot = {
side: TeamSide;
groupIndex: number;
};
function captainSlotKey(slot: CaptainSelectionSlot) {
return `${slot.side}:${slot.groupIndex}`;
}
function teamLabel(side: TeamSide, groupIndex = 1) {
const sideText = side === 'blue' ? '블루팀' : '레드팀';
return groupIndex === 1 ? sideText : `${groupIndex}조 ${sideText}`;
}
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 groupCount = Math.floor(buildAuctionParticipantPool(participants).length / 10);
return Array.from({ length: groupCount }, (_, index) => index + 1).flatMap(
(groupIndex) => [
{ side: 'blue' as const, groupIndex },
{ side: 'red' as const, groupIndex },
],
);
}
function PosBadge({ pos, sub }: { pos: Position; sub?: boolean }) {
return (
@@ -123,8 +163,13 @@ function ParticipantRow({
<span className="font-medium text-[13px] text-base-content truncate block leading-tight group-hover:text-primary transition-colors">
{participant.summonerName}
</span>
<span className="text-[10px] text-base-content/25 leading-tight">
<span className="inline-flex items-center gap-1 text-[10px] text-base-content/25 leading-tight">
#{participant.tag}
{participant.excluded && (
<span className="border border-amber-500/20 bg-amber-500/10 px-1 text-[9px] font-bold text-amber-500">
제외
</span>
)}
</span>
</div>
</Link>
@@ -215,9 +260,11 @@ function ParticipantTable({
function TeamCard({
team,
matchId,
isWinner,
}: {
team: TeamView;
matchId: string;
isWinner?: boolean;
}) {
const borderColor =
@@ -242,6 +289,12 @@ function TeamCard({
</span>
)}
</div>
<Link
to={`/match/${matchId}/team/${team.side}/${team.groupIndex}`}
className="text-[10px] font-bold text-base-content/35 hover:text-primary"
>
진행 페이지
</Link>
</div>
<table className="w-full text-left">
<thead>
@@ -359,8 +412,13 @@ function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) {
<div className="space-y-2">
{slots.map((slot) => (
<div key={slot.gameNumber} className="flex items-start gap-2">
<span className="text-[11px] font-bold text-base-content/40 w-11 shrink-0 pt-1.5">
<span className="text-[11px] font-bold text-base-content/40 w-20 shrink-0 pt-1.5">
{slot.gameNumber}경기
{(slot.blueGroupIndex > 1 || slot.redGroupIndex > 1) && (
<span className="block text-[10px] font-normal text-base-content/25">
{slot.blueGroupIndex}조
</span>
)}
</span>
{slot.code ? (
<TournamentCodeDisplay slot={slot} />
@@ -403,8 +461,8 @@ function formatGameDuration(seconds: number) {
return `${minutes}:${String(rest).padStart(2, '0')}`;
}
function resultSideLabel(side: 'blue' | 'red') {
return side === 'blue' ? '블루팀' : '레드팀';
function resultSideLabel(side: 'blue' | 'red', groupIndex = 1) {
return teamLabel(side, groupIndex);
}
function resultSideClass(side: 'blue' | 'red') {
@@ -417,10 +475,16 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
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: match.gameCount },
{ length: maxGameNumber },
(_, index) => index + 1,
);
const seriesResults = match.result.seriesResults ?? [];
return (
<div className="mb-6 border border-base-content/10 bg-base-content/[0.02] p-5">
@@ -452,11 +516,34 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
<div className="text-center mt-3 text-[11px] font-bold text-amber-400 uppercase tracking-wide">
{match.result.winner
? `${match.result.winner} 승리`
: `결과 수집 중 · ${match.result.games.length}/${match.gameCount}경기`}
: `결과 수집 중 · ${match.result.games.length}/${maxGameNumber}경기`}
</div>
{seriesResults.length > 1 && (
<div className="mt-4 grid sm:grid-cols-2 gap-2">
{seriesResults.map((series) => (
<div
key={`${series.blueGroupIndex}-${series.redGroupIndex}`}
className="border border-base-content/8 bg-base-100 px-3 py-2 text-xs"
>
<div className="font-bold text-base-content/55">
{series.blueGroupIndex}조
</div>
<div className="mt-1 flex items-center justify-between">
<span className="text-blue-400">블루 {series.blueScore}</span>
<span className="text-base-content/20">:</span>
<span className="text-red-400">레드 {series.redScore}</span>
</div>
</div>
))}
</div>
)}
<div className="mt-5 border border-base-content/8 divide-y divide-base-content/8">
{gameNumbers.map((gameNumber) => {
const game = gamesByNumber.get(gameNumber);
const winnerGroupIndex =
game?.winnerSide === 'blue'
? game.blueGroupIndex
: game?.redGroupIndex;
return (
<div
key={gameNumber}
@@ -468,7 +555,7 @@ function MatchResultPanel({ match }: { match: MatchDetailView }) {
{game ? (
<div>
<span className={`font-black ${resultSideClass(game.winnerSide)}`}>
{resultSideLabel(game.winnerSide)} 승
{resultSideLabel(game.winnerSide, winnerGroupIndex)} 승
</span>
<span className="ml-2 text-base-content/35 font-mono">
{game.riotMatchId}
@@ -501,8 +588,9 @@ export default function MatchDetailPage() {
)?.user ?? null;
const canUseMemberActions = Boolean(currentUser || authUserId);
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
const [blueCaptainUserId, setBlueCaptainUserId] = useState('');
const [redCaptainUserId, setRedCaptainUserId] = useState('');
const [captainSelections, setCaptainSelections] = useState<Record<string, string>>(
{},
);
const pollTournamentResultMutation = usePollTournamentResult(
DEFAULT_COMMUNITY_ID,
);
@@ -535,10 +623,13 @@ export default function MatchDetailPage() {
apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, {
method: 'POST',
body: JSON.stringify({
captains: [
{ side: 'blue', userId: blueCaptainUserId },
{ side: 'red', userId: redCaptainUserId },
],
captains: buildCaptainSlots(matchQuery.data?.participants ?? []).map(
(slot) => ({
side: slot.side,
groupIndex: slot.groupIndex,
userId: captainSelections[captainSlotKey(slot)],
}),
),
initialPoints: 1000,
maxTimerSeconds: 30,
}),
@@ -568,14 +659,43 @@ export default function MatchDetailPage() {
}
useEffect(() => {
const participants = matchQuery.data?.participants ?? [];
if (!blueCaptainUserId && participants[0]) {
setBlueCaptainUserId(participants[0].userId);
const participants = buildAuctionParticipantPool(
matchQuery.data?.participants ?? [],
);
const slots = buildCaptainSlots(matchQuery.data?.participants ?? []);
if (slots.length === 0) {
setCaptainSelections({});
return;
}
if (!redCaptainUserId && participants[1]) {
setRedCaptainUserId(participants[1].userId);
}
}, [blueCaptainUserId, redCaptainUserId, matchQuery.data?.participants]);
setCaptainSelections((current) => {
const next: Record<string, string> = {};
const usedUserIds = new Set<string>();
for (const slot of slots) {
const key = captainSlotKey(slot);
const currentUserId = current[key];
const currentIsValid =
currentUserId &&
participants.some((participant) => participant.userId === currentUserId) &&
!usedUserIds.has(currentUserId);
if (currentIsValid) {
next[key] = currentUserId;
usedUserIds.add(currentUserId);
continue;
}
const fallback = participants.find(
(participant) => !usedUserIds.has(participant.userId),
);
next[key] = fallback?.userId ?? '';
if (fallback) usedUserIds.add(fallback.userId);
}
return next;
});
}, [matchQuery.data?.participants]);
if (!DEFAULT_COMMUNITY_ID) {
return (
@@ -615,14 +735,24 @@ export default function MatchDetailPage() {
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)])
.filter(Boolean);
const hasUniqueCaptainSelections =
selectedCaptainIds.length === captainSlots.length &&
new Set(selectedCaptainIds).size === selectedCaptainIds.length;
const waitingParticipantCount =
matchQuery.data.participants.length - auctionParticipantPool.length;
const canStartAuction =
canManageAuction &&
match.status === 'recruiting' &&
matchQuery.data.participants.length >= 2 &&
auctionParticipantPool.length >= 10 &&
auctionNotStarted &&
blueCaptainUserId &&
redCaptainUserId &&
blueCaptainUserId !== redCaptainUserId;
hasUniqueCaptainSelections;
return (
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-6">
@@ -721,8 +851,13 @@ export default function MatchDetailPage() {
경매 시작
</h3>
<p className="mt-1 text-xs text-base-content/40">
두 팀장을 선택하면 경매를 시작할 수 있습니다.
참가 신청 순서 기준 10명당 1개 조가 만들어지고, 각 조에 블루/레드 팀장을 지정합니다.
</p>
{waitingParticipantCount > 0 && (
<p className="mt-1 text-[11px] text-amber-500">
{waitingParticipantCount}명은 10명 단위에 맞지 않아 이번 경매에서 제외됩니다.
</p>
)}
</div>
{showAuctionLink ? (
@@ -730,37 +865,55 @@ export default function MatchDetailPage() {
경매 페이지 열기
</Link>
) : (
<div className="grid sm:grid-cols-2 gap-3">
<label className="text-xs text-base-content/45">
블루팀 팀장
<select
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm"
value={blueCaptainUserId}
onChange={(event) => setBlueCaptainUserId(event.target.value)}
>
<option value="">선택하세요</option>
{matchQuery.data.participants.map((participant) => (
<option key={`blue-${participant.userId}`} value={participant.userId}>
{participant.gameName ?? participant.userId}
</option>
))}
</select>
</label>
<label className="text-xs text-base-content/45">
레드팀 팀장
<select
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm"
value={redCaptainUserId}
onChange={(event) => setRedCaptainUserId(event.target.value)}
>
<option value="">선택하세요</option>
{matchQuery.data.participants.map((participant) => (
<option key={`red-${participant.userId}`} value={participant.userId}>
{participant.gameName ?? participant.userId}
</option>
))}
</select>
</label>
<div className="space-y-3">
{captainSlots.length > 0 ? (
<div className="grid sm:grid-cols-2 gap-3">
{captainSlots.map((slot) => {
const key = captainSlotKey(slot);
const currentValue = captainSelections[key] ?? '';
return (
<label
key={key}
className="text-xs text-base-content/45"
>
{teamLabel(slot.side, slot.groupIndex)} 팀장
<select
className="mt-1 w-full border border-base-content/10 bg-transparent px-2 py-2 text-sm"
value={currentValue}
onChange={(event) =>
setCaptainSelections((current) => ({
...current,
[key]: event.target.value,
}))
}
>
<option value="">선택하세요</option>
{auctionParticipantPool.map((participant) => {
const selectedByOtherSlot =
selectedCaptainIds.includes(
participant.userId,
) && currentValue !== participant.userId;
return (
<option
key={`${key}-${participant.userId}`}
value={participant.userId}
disabled={selectedByOtherSlot}
>
{participant.gameName ?? participant.userId}
{selectedByOtherSlot ? ' (선택됨)' : ''}
</option>
);
})}
</select>
</label>
);
})}
</div>
) : (
<div className="border border-dashed border-base-content/10 px-3 py-4 text-xs text-base-content/35">
경매를 시작하려면 최소 10명이 필요합니다.
</div>
)}
<div className="sm:col-span-2 flex items-center gap-3">
<button
type="button"
@@ -785,8 +938,9 @@ export default function MatchDetailPage() {
<div className="space-y-4">
{match.teams.map((team) => (
<TeamCard
key={team.side}
key={`${team.side}-${team.groupIndex}`}
team={team}
matchId={match.id}
isWinner={
match.status === 'finished'
? match.result?.winner === team.name
@@ -0,0 +1,245 @@
import { Link, useParams } from 'react-router';
import { useDdragonManifest, useMatch } from '../api/hooks';
import type { ApiMatchParticipant, Position, TeamSide } from '../api/types';
import { DEFAULT_COMMUNITY_ID } from '../config';
import { profileIconUrl } from '../lib/ddragon';
import { positionLabel } from '../lib/league';
function teamLabel(side: TeamSide, groupIndex = 1) {
const sideText = side === 'blue' ? '블루팀' : '레드팀';
return groupIndex === 1 ? sideText : `${groupIndex}조 ${sideText}`;
}
function formatExpiry(value: string | null) {
if (!value) return '-';
return new Intl.DateTimeFormat('ko-KR', {
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(value));
}
function ParticipantLine({
participant,
assignedPosition,
isCaptain,
}: {
participant?: ApiMatchParticipant;
assignedPosition?: Position;
isCaptain?: boolean;
}) {
const { data: ddragon } = useDdragonManifest();
const name = participant?.gameName ?? '알 수 없는 참가자';
const tag = participant?.tagLine ?? '----';
return (
<div className="flex items-center gap-3 border-b border-base-content/5 last:border-b-0 px-3 py-2">
<div className="h-8 w-8 shrink-0 overflow-hidden bg-base-content/10">
<img
src={profileIconUrl(ddragon, participant?.profileIconId ?? 0)}
alt=""
className="h-full w-full object-cover"
loading="lazy"
/>
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-sm font-bold text-base-content">
{name}
</span>
{isCaptain && (
<span className="border border-amber-500/20 bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-bold text-amber-500">
팀장
</span>
)}
</div>
<div className="text-[11px] text-base-content/30">#{tag}</div>
</div>
<div className="text-xs font-semibold text-primary">
{assignedPosition ? positionLabel[assignedPosition] : '-'}
</div>
</div>
);
}
export default function MatchTeamProgressPage() {
const { id, side, groupIndex } = useParams();
const parsedGroupIndex = Number(groupIndex ?? 1);
const teamSide = side === 'blue' || side === 'red' ? side : null;
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
if (!DEFAULT_COMMUNITY_ID) {
return (
<main className="mx-auto max-w-5xl px-4 py-20 text-center text-sm text-amber-600">
`VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다.
</main>
);
}
if (matchQuery.isLoading) {
return (
<main className="mx-auto max-w-5xl px-4 py-20 text-center text-sm text-base-content/40">
팀 진행 정보를 불러오는 중...
</main>
);
}
if (!teamSide || !matchQuery.data) {
return (
<main className="mx-auto max-w-5xl px-4 py-20 text-center">
<h1 className="text-lg font-bold">팀 정보를 찾을 수 없습니다</h1>
<Link to={`/match/${id}`} className="btn btn-primary btn-sm mt-4 px-5 text-xs">
내전 상세로
</Link>
</main>
);
}
const match = matchQuery.data;
const team = match.teams.find(
(item) =>
item.side === teamSide && (item.groupIndex ?? 1) === parsedGroupIndex,
);
const participantByUserId = new Map(
match.participants.map((participant) => [participant.userId, participant]),
);
const codes = (match.tournamentCodes ?? []).filter((slot) =>
teamSide === 'blue'
? slot.blueGroupIndex === parsedGroupIndex
: slot.redGroupIndex === parsedGroupIndex,
);
const games = (match.result?.games ?? []).filter((game) =>
teamSide === 'blue'
? game.blueGroupIndex === parsedGroupIndex
: game.redGroupIndex === parsedGroupIndex,
);
if (!team) {
return (
<main className="mx-auto max-w-5xl px-4 py-20 text-center">
<h1 className="text-lg font-bold">아직 팀이 생성되지 않았습니다</h1>
<p className="mt-2 text-sm text-base-content/40">
경매가 완료되면 팀별 진행 페이지를 사용할 수 있습니다.
</p>
<Link to={`/match/${id}`} className="btn btn-primary btn-sm mt-4 px-5 text-xs">
내전 상세로
</Link>
</main>
);
}
return (
<main className="mx-auto max-w-5xl px-4 py-6 sm:px-6">
<Link
to={`/match/${id}`}
className="mb-5 inline-flex text-xs text-base-content/40 hover:text-base-content"
>
← 내전 상세로
</Link>
<div className="mb-6 border-b border-base-content/8 pb-5">
<h1 className="text-2xl font-black text-base-content">
{team.name || teamLabel(team.side, team.groupIndex)}
</h1>
<p className="mt-1 text-sm text-base-content/45">
이 팀에 연결된 토너먼트 코드와 수집된 결과만 보여줍니다.
</p>
</div>
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_320px]">
<section className="border border-base-content/10 bg-base-100">
<div className="border-b border-base-content/10 bg-base-200/40 px-4 py-2">
<h2 className="text-[11px] font-bold uppercase tracking-wider text-base-content/40">
팀 구성
</h2>
</div>
<ParticipantLine
participant={
team.captainUserId
? participantByUserId.get(team.captainUserId)
: undefined
}
isCaptain
/>
{team.members.map((member) => (
<ParticipantLine
key={member.userId}
participant={participantByUserId.get(member.userId)}
assignedPosition={member.assignedPosition}
/>
))}
</section>
<section className="space-y-4">
<div className="border border-base-content/10 bg-base-100">
<div className="border-b border-base-content/10 bg-base-200/40 px-4 py-2">
<h2 className="text-[11px] font-bold uppercase tracking-wider text-base-content/40">
토너먼트 코드
</h2>
</div>
<div className="divide-y divide-base-content/5">
{codes.length > 0 ? (
codes.map((slot) => (
<div key={slot.gameNumber} className="px-4 py-3 text-xs">
<div className="flex items-center justify-between gap-2">
<span className="font-bold text-base-content/50">
{slot.gameNumber}경기
</span>
<code className="font-mono font-black text-primary">
{slot.code ?? '발급 대기'}
</code>
</div>
<div className="mt-1 text-[11px] text-base-content/30">
만료 {formatExpiry(slot.expiresAt)}
</div>
</div>
))
) : (
<div className="px-4 py-6 text-center text-xs text-base-content/30">
아직 연결된 코드가 없습니다.
</div>
)}
</div>
</div>
<div className="border border-base-content/10 bg-base-100">
<div className="border-b border-base-content/10 bg-base-200/40 px-4 py-2">
<h2 className="text-[11px] font-bold uppercase tracking-wider text-base-content/40">
결과
</h2>
</div>
<div className="divide-y divide-base-content/5">
{games.length > 0 ? (
games.map((game) => {
const won = game.winnerSide === teamSide;
return (
<div key={game.gameNumber} className="px-4 py-3 text-xs">
<div className="flex items-center justify-between gap-2">
<span className="font-bold text-base-content/50">
{game.gameNumber}경기
</span>
<span
className={won ? 'font-black text-blue-400' : 'font-black text-red-400'}
>
{won ? '승리' : '패배'}
</span>
</div>
<div className="mt-1 truncate font-mono text-[11px] text-base-content/30">
{game.riotMatchId}
</div>
</div>
);
})
) : (
<div className="px-4 py-6 text-center text-xs text-base-content/30">
아직 수집된 결과가 없습니다.
</div>
)}
</div>
</div>
</section>
</div>
</main>
);
}
+433
View File
@@ -0,0 +1,433 @@
import { useMemo, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { Link, useParams } from 'react-router';
import {
useCreateMatch,
useDeleteMatch,
useMatches,
useMe,
useUpdateMatch,
} from '../../api/hooks';
import type {
ApiMatch,
ApiMatchScheduleItem,
MatchGameMode,
MatchMutationRequest,
} from '../../api/types';
import { DEFAULT_COMMUNITY_ID } from '../../config';
const DEFAULT_FORM: MatchMutationRequest = {
title: '',
description: '',
mapId: 11,
scheduledAt: toInputValue(new Date(Date.now() + 24 * 60 * 60 * 1000)),
maxParticipants: 10,
gameCount: 3,
gameMode: 'pair',
prizes: [],
notices: [],
schedule: [],
};
const GAME_MODE_LABEL: Record<MatchGameMode, string> = {
pair: '페어',
bracket: '브래킷',
'round-robin': '라운드 로빈',
};
function toInputValue(value: string | Date) {
const date = value instanceof Date ? value : new Date(value);
const offset = date.getTimezoneOffset();
return new Date(date.getTime() - offset * 60_000).toISOString().slice(0, 16);
}
function toIsoFromInput(value: string) {
return new Date(value).toISOString();
}
function formatDate(value: string) {
return new Intl.DateTimeFormat('ko-KR', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(value));
}
function parseLines(value: string) {
return value
.split(/\r?\n/u)
.map((line) => line.trim())
.filter(Boolean);
}
function parseSchedule(value: string): ApiMatchScheduleItem[] {
return parseLines(value).map((line) => {
const [time, ...labelParts] = line.split('|').map((part) => part.trim());
return {
time: time || '00:00',
label: labelParts.join('|') || '일정',
};
});
}
function scheduleToText(schedule: ApiMatchScheduleItem[] = []) {
return schedule.map((item) => `${item.time}|${item.label}`).join('\n');
}
function makeForm(match?: ApiMatch): MatchMutationRequest & {
prizesText: string;
noticesText: string;
scheduleText: string;
} {
if (!match) {
return {
...DEFAULT_FORM,
prizesText: '',
noticesText: '',
scheduleText: '',
};
}
return {
title: match.title,
description: match.description,
mapId: match.mapId,
scheduledAt: toInputValue(match.scheduledAt),
maxParticipants: match.maxParticipants,
gameCount: match.gameCount,
gameMode: match.gameMode ?? 'pair',
prizes: match.prizes,
notices: match.notices,
schedule: match.schedule,
prizesText: match.prizes.join('\n'),
noticesText: match.notices.join('\n'),
scheduleText: scheduleToText(match.schedule),
};
}
export default function MatchAdminPage() {
const { cid } = useParams();
const communityId = cid ?? DEFAULT_COMMUNITY_ID;
const queryClient = useQueryClient();
const meQuery = useMe();
const matchesQuery = useMatches({ limit: 200 }, communityId);
const createMutation = useCreateMatch(communityId);
const updateMutation = useUpdateMatch(communityId);
const deleteMutation = useDeleteMatch(communityId);
const [editing, setEditing] = useState<ApiMatch | null>(null);
const [showForm, setShowForm] = useState(false);
const [form, setForm] = useState(makeForm());
const [message, setMessage] = useState<string | null>(null);
const currentUser =
meQuery.data?.memberships.find(
(membership) => membership.community?._id === communityId,
)?.user ?? null;
const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin';
const matches = useMemo(
() => [...(matchesQuery.data ?? [])].sort((a, b) => new Date(b.scheduledAt).getTime() - new Date(a.scheduledAt).getTime()),
[matchesQuery.data],
);
async function invalidate() {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['matches', communityId] }),
queryClient.invalidateQueries({ queryKey: ['match', communityId] }),
]);
}
function openCreate() {
setEditing(null);
setForm(makeForm());
setShowForm(true);
setMessage(null);
}
function openEdit(match: ApiMatch) {
setEditing(match);
setForm(makeForm(match));
setShowForm(true);
setMessage(null);
}
function buildPayload(): MatchMutationRequest {
return {
title: form.title.trim(),
description: form.description?.trim() ?? '',
mapId: Number(form.mapId ?? 11),
scheduledAt: toIsoFromInput(form.scheduledAt),
maxParticipants: Number(form.maxParticipants ?? 10),
gameCount: Number(form.gameCount ?? 3),
gameMode: form.gameMode,
prizes: parseLines(form.prizesText),
notices: parseLines(form.noticesText),
schedule: parseSchedule(form.scheduleText),
};
}
function submit() {
setMessage(null);
const payload = buildPayload();
if (!payload.title) {
setMessage('제목을 입력해주세요.');
return;
}
const callbacks = {
onSuccess: async () => {
await invalidate();
setShowForm(false);
setEditing(null);
setMessage(editing ? '내전을 수정했습니다.' : '내전을 만들었습니다.');
},
onError: (error: Error) => setMessage(error.message),
};
if (editing) {
updateMutation.mutate({ matchId: editing._id, body: payload }, callbacks);
return;
}
createMutation.mutate(payload, callbacks);
}
if (!canManage && !meQuery.isPending) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">권한이 필요합니다</h1>
<p className="mt-2 text-sm text-base-content/40">
내전 관리는 owner/admin만 사용할 수 있습니다.
</p>
</main>
);
}
return (
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
<Link to="/" className="inline-flex text-xs text-base-content/40 hover:text-base-content mb-5">
← 목록으로
</Link>
<div className="mb-6 flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3">
<div>
<h1 className="text-2xl font-black text-base-content">내전 관리</h1>
<p className="mt-1 text-sm text-base-content/45">
내전 생성, 모집 정원, 게임 모드와 공지 내용을 관리합니다.
</p>
</div>
<button type="button" className="btn btn-primary btn-sm px-5 text-xs" onClick={openCreate}>
새 내전 만들기
</button>
</div>
{message && (
<div className="mb-4 border border-primary/20 bg-primary/5 px-3 py-2 text-xs text-base-content/60">
{message}
</div>
)}
{showForm && (
<section className="mb-6 border border-base-content/10 bg-base-100 p-4">
<div className="mb-4 flex items-center justify-between gap-3">
<h2 className="text-sm font-bold">
{editing ? '내전 수정' : '새 내전'}
</h2>
<button
type="button"
className="text-xs text-base-content/35 hover:text-base-content"
onClick={() => setShowForm(false)}
>
닫기
</button>
</div>
<div className="grid md:grid-cols-2 gap-3">
<label className="text-xs text-base-content/45 md:col-span-2">
제목
<input
value={form.title}
onChange={(event) => setForm((current) => ({ ...current, title: event.target.value }))}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
</label>
<label className="text-xs text-base-content/45 md:col-span-2">
설명
<textarea
value={form.description}
onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))}
rows={3}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
</label>
<label className="text-xs text-base-content/45">
시작 시간
<input
type="datetime-local"
value={form.scheduledAt}
onChange={(event) => setForm((current) => ({ ...current, scheduledAt: event.target.value }))}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
</label>
<label className="text-xs text-base-content/45">
정원
<select
value={form.maxParticipants}
onChange={(event) => setForm((current) => ({ ...current, maxParticipants: Number(event.target.value) }))}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
>
{[10, 20, 30, 40, 50, 60].map((value) => (
<option key={value} value={value}>{value}명</option>
))}
</select>
</label>
<label className="text-xs text-base-content/45">
게임 수
<input
type="number"
min={1}
value={form.gameCount}
onChange={(event) => setForm((current) => ({ ...current, gameCount: Number(event.target.value) }))}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
</label>
<label className="text-xs text-base-content/45">
게임 모드
<select
value={form.gameMode}
onChange={(event) => setForm((current) => ({ ...current, gameMode: event.target.value as MatchGameMode }))}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
>
{Object.entries(GAME_MODE_LABEL).map(([value, label]) => (
<option key={value} value={value}>{label}</option>
))}
</select>
<span className="mt-1 block text-[10px] text-amber-500/80">
현재 경매/코드 연결은 페어 방식 기준으로 동작합니다.
</span>
</label>
<label className="text-xs text-base-content/45">
상품 (줄바꿈 구분)
<textarea
value={form.prizesText}
onChange={(event) => setForm((current) => ({ ...current, prizesText: event.target.value }))}
rows={4}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
</label>
<label className="text-xs text-base-content/45">
공지 (줄바꿈 구분)
<textarea
value={form.noticesText}
onChange={(event) => setForm((current) => ({ ...current, noticesText: event.target.value }))}
rows={4}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm"
/>
</label>
<label className="text-xs text-base-content/45 md:col-span-2">
일정 (`시간|라벨`, 줄바꿈 구분)
<textarea
value={form.scheduleText}
onChange={(event) => setForm((current) => ({ ...current, scheduleText: event.target.value }))}
rows={3}
placeholder="20:50|로비 오픈"
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm font-mono"
/>
</label>
</div>
<div className="mt-4 flex gap-2">
<button
type="button"
className="btn btn-primary btn-sm px-5 text-xs"
disabled={createMutation.isPending || updateMutation.isPending}
onClick={submit}
>
{editing ? '수정 저장' : '생성'}
</button>
<button
type="button"
className="btn btn-ghost btn-sm px-5 text-xs"
onClick={() => setShowForm(false)}
>
취소
</button>
</div>
</section>
)}
<section className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full min-w-[900px] text-left">
<thead>
<tr className="bg-base-200/40 border-b border-base-content/10 text-[11px] uppercase tracking-wider text-base-content/35">
<th className="px-3 py-2">시간</th>
<th className="px-3 py-2">내전</th>
<th className="px-3 py-2">상태</th>
<th className="px-3 py-2">정원</th>
<th className="px-3 py-2">모드</th>
<th className="px-3 py-2 text-right">작업</th>
</tr>
</thead>
<tbody>
{matches.map((match) => (
<tr key={match._id} className="border-b border-base-content/5">
<td className="px-3 py-2 text-xs text-base-content/45">
{formatDate(match.scheduledAt)}
</td>
<td className="px-3 py-2">
<Link to={`/match/${match._id}`} className="text-sm font-bold hover:text-primary">
{match.title}
</Link>
<div className="mt-0.5 text-[11px] text-base-content/30">
{match.description || '-'}
</div>
</td>
<td className="px-3 py-2 text-xs">{match.status}</td>
<td className="px-3 py-2 text-xs tabular-nums">
{match.participants.length}/{match.maxParticipants}
</td>
<td className="px-3 py-2 text-xs">
{GAME_MODE_LABEL[match.gameMode ?? 'pair']}
</td>
<td className="px-3 py-2 text-right">
<div className="inline-flex gap-2">
<button
type="button"
className="text-[11px] px-2 py-1 border border-base-content/10 text-base-content/50 hover:text-primary"
onClick={() => openEdit(match)}
>
수정
</button>
<button
type="button"
className="text-[11px] px-2 py-1 border border-red-500/20 text-red-400 hover:bg-red-500/10"
disabled={deleteMutation.isPending}
onClick={() => {
if (!window.confirm('이 내전을 삭제할까요?')) return;
deleteMutation.mutate(match._id, {
onSuccess: invalidate,
onError: (error) =>
setMessage(error instanceof Error ? error.message : '삭제 실패'),
});
}}
>
삭제
</button>
</div>
</td>
</tr>
))}
{matches.length === 0 && (
<tr>
<td colSpan={6} className="px-4 py-10 text-center text-sm text-base-content/35">
등록된 내전이 없습니다.
</td>
</tr>
)}
</tbody>
</table>
</div>
</section>
</main>
);
}