fix: close competition cutover integrity gaps
This commit is contained in:
1 parent
7ea2002975
commit
683d602d63
57 files changed
+4805
-1582
No files matched your search
@@ -0,0 +1,35 @@
|
||||
export interface AuthQueryScopeInput {
|
||||
authUserId: string | null;
|
||||
accountKey: string | null;
|
||||
msalConfigured: boolean;
|
||||
msalReady: boolean;
|
||||
}
|
||||
|
||||
interface ExecuteAuthScopedQueryInput<T> {
|
||||
accountKey: string | null;
|
||||
acquireAccessToken: () => Promise<string>;
|
||||
request: (authorizationHeader: string | null) => Promise<T>;
|
||||
}
|
||||
|
||||
export function resolveAuthQueryScope({
|
||||
authUserId,
|
||||
accountKey,
|
||||
msalConfigured,
|
||||
msalReady,
|
||||
}: AuthQueryScopeInput) {
|
||||
return {
|
||||
cacheKey: [authUserId, accountKey] as const,
|
||||
ready: Boolean(authUserId || !msalConfigured || msalReady),
|
||||
};
|
||||
}
|
||||
|
||||
export async function executeAuthScopedQuery<T>({
|
||||
accountKey,
|
||||
acquireAccessToken,
|
||||
request,
|
||||
}: ExecuteAuthScopedQueryInput<T>): Promise<T> {
|
||||
if (!accountKey) return request(null);
|
||||
|
||||
const accessToken = await acquireAccessToken();
|
||||
return request(`Bearer ${accessToken}`);
|
||||
}
|
||||
+87
-48
@@ -5,6 +5,9 @@ import type {
|
||||
CompetitionCommandResponse,
|
||||
CompetitionDetailResponse,
|
||||
CreateSeriesAdjudicationRequest,
|
||||
MatchDetailResponse,
|
||||
MatchLifecycleStatus,
|
||||
MatchListResponse,
|
||||
ReverseSeriesResultRequest,
|
||||
SeriesId,
|
||||
SeriesReversalPreviewRequest,
|
||||
@@ -18,6 +21,10 @@ import {
|
||||
MSAL_API_SCOPE,
|
||||
MSAL_SILENT_REDIRECT_URI,
|
||||
} from '../lib/auth/msal.config';
|
||||
import {
|
||||
executeAuthScopedQuery,
|
||||
resolveAuthQueryScope,
|
||||
} from './auth-query-scope';
|
||||
import type {
|
||||
ApiAuction,
|
||||
ApiAuctionHistoryEntry,
|
||||
@@ -31,7 +38,6 @@ import type {
|
||||
LegacyImportJobsResponse,
|
||||
LegacyImportMembersResponse,
|
||||
LegacyMatchListResponse,
|
||||
ApiMatch,
|
||||
ApiRecentMatchesResponse,
|
||||
ApiRecentSummaryResponse,
|
||||
ApiTeamInsightsResponse,
|
||||
@@ -41,9 +47,7 @@ import type {
|
||||
DdragonManifest,
|
||||
StartLegacyImportRequest,
|
||||
StartLegacyImportResponse,
|
||||
MatchStatus,
|
||||
MatchMutationRequest,
|
||||
MatchesResponse,
|
||||
ManualTournamentResultCollectResponse,
|
||||
MeResponse,
|
||||
RiotQueueGroup,
|
||||
@@ -59,7 +63,7 @@ import type {
|
||||
const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
interface MatchesQueryOptions {
|
||||
status?: MatchStatus;
|
||||
status?: MatchLifecycleStatus;
|
||||
limit?: number;
|
||||
page?: number;
|
||||
offset?: number;
|
||||
@@ -101,6 +105,45 @@ function createMatchesPath(
|
||||
return `/communities/${communityId}/matches${queryString ? `?${queryString}` : ''}`;
|
||||
}
|
||||
|
||||
function useOptionalAuthQueryScope() {
|
||||
const authUserId = useAuthUserId();
|
||||
const { accounts, inProgress, instance } = useMsal();
|
||||
const account = isMsalConfigured
|
||||
? (instance.getActiveAccount() ?? accounts[0] ?? null)
|
||||
: null;
|
||||
const scope = resolveAuthQueryScope({
|
||||
authUserId,
|
||||
accountKey: account?.homeAccountId ?? null,
|
||||
msalConfigured: isMsalConfigured,
|
||||
msalReady: inProgress === InteractionStatus.None,
|
||||
});
|
||||
|
||||
const fetch = <T>(path: string) =>
|
||||
executeAuthScopedQuery({
|
||||
accountKey: account?.homeAccountId ?? null,
|
||||
acquireAccessToken: async () => {
|
||||
if (!account) {
|
||||
throw new Error('MSAL account is unavailable.');
|
||||
}
|
||||
const response = await instance.acquireTokenSilent({
|
||||
account,
|
||||
scopes: [MSAL_API_SCOPE],
|
||||
redirectUri: MSAL_SILENT_REDIRECT_URI,
|
||||
});
|
||||
return response.accessToken;
|
||||
},
|
||||
request: (authorizationHeader) =>
|
||||
apiFetch<T>(
|
||||
path,
|
||||
authorizationHeader
|
||||
? { headers: { Authorization: authorizationHeader } }
|
||||
: undefined,
|
||||
),
|
||||
});
|
||||
|
||||
return { ...scope, fetch };
|
||||
}
|
||||
|
||||
export function useCommunity(communityId = DEFAULT_COMMUNITY_ID) {
|
||||
return useQuery({
|
||||
queryKey: ['community', communityId],
|
||||
@@ -114,10 +157,13 @@ export function useMatches(
|
||||
options: MatchesQueryOptions,
|
||||
communityId = DEFAULT_COMMUNITY_ID,
|
||||
) {
|
||||
const authScope = useOptionalAuthQueryScope();
|
||||
|
||||
return useQuery({
|
||||
queryKey: [
|
||||
'matches',
|
||||
communityId,
|
||||
...authScope.cacheKey,
|
||||
options.status ?? null,
|
||||
options.limit ?? null,
|
||||
options.page ?? null,
|
||||
@@ -127,13 +173,12 @@ export function useMatches(
|
||||
options.sort ?? null,
|
||||
],
|
||||
queryFn: async () => {
|
||||
const response = await apiFetch<MatchesResponse>(
|
||||
const response = await authScope.fetch<MatchListResponse>(
|
||||
createMatchesPath(communityId, options),
|
||||
{ auth: 'none' },
|
||||
);
|
||||
return response.matches;
|
||||
},
|
||||
enabled: Boolean(communityId),
|
||||
enabled: Boolean(communityId && authScope.ready),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -141,10 +186,13 @@ export function useMatchesPage(
|
||||
options: MatchesQueryOptions,
|
||||
communityId = DEFAULT_COMMUNITY_ID,
|
||||
) {
|
||||
const authScope = useOptionalAuthQueryScope();
|
||||
|
||||
return useQuery({
|
||||
queryKey: [
|
||||
'matches-page',
|
||||
communityId,
|
||||
...authScope.cacheKey,
|
||||
options.status ?? null,
|
||||
options.limit ?? null,
|
||||
options.page ?? null,
|
||||
@@ -154,10 +202,10 @@ export function useMatchesPage(
|
||||
options.sort ?? null,
|
||||
],
|
||||
queryFn: () =>
|
||||
apiFetch<MatchesResponse>(createMatchesPath(communityId, options), {
|
||||
auth: 'none',
|
||||
}),
|
||||
enabled: Boolean(communityId),
|
||||
authScope.fetch<MatchListResponse>(
|
||||
createMatchesPath(communityId, options),
|
||||
),
|
||||
enabled: Boolean(communityId && authScope.ready),
|
||||
placeholderData: (previousData) => previousData,
|
||||
});
|
||||
}
|
||||
@@ -166,15 +214,25 @@ export function useMatch(
|
||||
matchId: string | undefined,
|
||||
communityId = DEFAULT_COMMUNITY_ID,
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ['match', communityId, matchId ?? null],
|
||||
const authScope = useOptionalAuthQueryScope();
|
||||
const queryKey = [
|
||||
'match',
|
||||
communityId,
|
||||
matchId ?? null,
|
||||
...authScope.cacheKey,
|
||||
] as const;
|
||||
|
||||
const query = useQuery({
|
||||
queryKey,
|
||||
queryFn: () =>
|
||||
apiFetch<ApiMatch>(`/communities/${communityId}/matches/${matchId}`, {
|
||||
auth: 'none',
|
||||
}),
|
||||
enabled: Boolean(communityId && matchId),
|
||||
authScope.fetch<MatchDetailResponse>(
|
||||
`/communities/${communityId}/matches/${matchId}`,
|
||||
),
|
||||
enabled: Boolean(communityId && matchId && authScope.ready),
|
||||
retry: false,
|
||||
});
|
||||
|
||||
return { ...query, queryKey };
|
||||
}
|
||||
|
||||
export function useCompetition(
|
||||
@@ -426,7 +484,7 @@ export function useResetAuction(communityId = DEFAULT_COMMUNITY_ID) {
|
||||
export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) {
|
||||
return useMutation({
|
||||
mutationFn: (body: MatchMutationRequest) =>
|
||||
apiFetch<ApiMatch>(`/communities/${communityId}/matches`, {
|
||||
apiFetch<MatchDetailResponse>(`/communities/${communityId}/matches`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
@@ -442,10 +500,13 @@ export function useUpdateMatch(communityId = DEFAULT_COMMUNITY_ID) {
|
||||
matchId: string;
|
||||
body: Partial<MatchMutationRequest>;
|
||||
}) =>
|
||||
apiFetch<ApiMatch>(`/communities/${communityId}/matches/${matchId}`, {
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
apiFetch<MatchDetailResponse>(
|
||||
`/communities/${communityId}/matches/${matchId}`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1028,34 +1089,12 @@ export function useRebuildLegacyMatches(communityId = DEFAULT_COMMUNITY_ID) {
|
||||
}
|
||||
|
||||
export function useMe() {
|
||||
const authUserId = useAuthUserId();
|
||||
const { accounts, inProgress, instance } = useMsal();
|
||||
const account = isMsalConfigured
|
||||
? (instance.getActiveAccount() ?? accounts[0] ?? null)
|
||||
: null;
|
||||
const accountKey = account?.homeAccountId ?? null;
|
||||
const isMsalReady =
|
||||
!isMsalConfigured || inProgress === InteractionStatus.None;
|
||||
const authScope = useOptionalAuthQueryScope();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['me', authUserId, accountKey],
|
||||
queryFn: async () => {
|
||||
if (!account) {
|
||||
return apiFetch<MeResponse>('/me');
|
||||
}
|
||||
|
||||
const response = await instance.acquireTokenSilent({
|
||||
account,
|
||||
scopes: [MSAL_API_SCOPE],
|
||||
redirectUri: MSAL_SILENT_REDIRECT_URI,
|
||||
});
|
||||
return apiFetch<MeResponse>('/me', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${response.accessToken}`,
|
||||
},
|
||||
});
|
||||
},
|
||||
enabled: Boolean(authUserId || isMsalReady),
|
||||
queryKey: ['me', ...authScope.cacheKey],
|
||||
queryFn: () => authScope.fetch<MeResponse>('/me'),
|
||||
enabled: authScope.ready,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
@@ -1,15 +1,17 @@
|
||||
import type {
|
||||
MatchDetailResponse,
|
||||
MatchLifecycleStatus,
|
||||
MatchParticipantView,
|
||||
} from "@lolympus/contracts";
|
||||
import type {
|
||||
ApiAuction,
|
||||
ApiAuctionPlayerSnapshot,
|
||||
ApiAuctionTeam,
|
||||
ApiMatch,
|
||||
ApiMatchParticipant,
|
||||
ApiPositionPreference,
|
||||
ApiRiotLaneStats,
|
||||
ApiRiotRecentStatsSummary,
|
||||
ApiTierHistoryEntry,
|
||||
ApiTierInfo,
|
||||
MatchStatus,
|
||||
Position,
|
||||
RiotLane,
|
||||
} from "./types";
|
||||
@@ -46,7 +48,7 @@ export interface MatchDetailView {
|
||||
title: string;
|
||||
date: string;
|
||||
time: string;
|
||||
status: MatchStatus;
|
||||
status: MatchLifecycleStatus;
|
||||
description: string;
|
||||
map: string;
|
||||
maxParticipants: number;
|
||||
@@ -180,7 +182,7 @@ function resolveMainAndSubPosition(
|
||||
}
|
||||
|
||||
function mapMatchParticipantToView(
|
||||
participant: ApiMatchParticipant,
|
||||
participant: MatchParticipantView,
|
||||
): ParticipantView {
|
||||
const { mainPosition, subPosition } = resolveMainAndSubPosition(
|
||||
participant.preferredPositions,
|
||||
@@ -383,7 +385,9 @@ export function buildDefaultPreferredPositions() {
|
||||
}));
|
||||
}
|
||||
|
||||
export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
|
||||
export function mapApiMatchToMatchDetail(
|
||||
match: MatchDetailResponse,
|
||||
): MatchDetailView {
|
||||
const formattedDate = formatKoreanDate(match.scheduledAt);
|
||||
const participants = match.participants.map(mapMatchParticipantToView);
|
||||
const participantLookup = new Map(
|
||||
@@ -439,7 +443,7 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
|
||||
|
||||
export function mapApiAuctionToAuctionState(
|
||||
auction: ApiAuction,
|
||||
match: ApiMatch,
|
||||
match: MatchDetailResponse,
|
||||
now = new Date(),
|
||||
): AuctionStateView {
|
||||
const participantLookup = new Map(
|
||||
|
||||
+12
-87
@@ -1,15 +1,14 @@
|
||||
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP';
|
||||
import type {
|
||||
MatchGameMode,
|
||||
MatchPosition,
|
||||
MatchPositionPreferenceView,
|
||||
MatchScheduleItemView,
|
||||
MatchTierView,
|
||||
} from '@lolympus/contracts';
|
||||
|
||||
export type Position = MatchPosition;
|
||||
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
|
||||
export type TeamSide = 'blue' | 'red';
|
||||
export type MatchGameMode =
|
||||
| 'pair'
|
||||
| 'round-robin'
|
||||
| 'double-elimination';
|
||||
export type MatchStatus =
|
||||
| 'recruiting'
|
||||
| 'team-built'
|
||||
| 'in-progress'
|
||||
| 'finished';
|
||||
export type AuctionPhase =
|
||||
| 'waiting'
|
||||
| 'presenting'
|
||||
@@ -25,20 +24,8 @@ export type AuctionTopTierThreshold =
|
||||
| 'MANUAL';
|
||||
export type CommunityRole = 'owner' | 'admin' | 'member';
|
||||
|
||||
export interface ApiPositionPreference {
|
||||
position: Position;
|
||||
priority: number;
|
||||
}
|
||||
|
||||
export interface ApiTierInfo {
|
||||
queueType: string;
|
||||
tier: string;
|
||||
rank: string;
|
||||
leaguePoints: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
fetchedAt: string;
|
||||
}
|
||||
export type ApiPositionPreference = MatchPositionPreferenceView;
|
||||
export type ApiTierInfo = MatchTierView;
|
||||
|
||||
export interface ApiChampionMasteryEntry {
|
||||
puuid?: string;
|
||||
@@ -142,36 +129,6 @@ export type TournamentCodeState =
|
||||
| 'released'
|
||||
| 'voided';
|
||||
|
||||
export interface ApiMatchParticipant {
|
||||
userId: string;
|
||||
puuid?: string;
|
||||
gameName?: string;
|
||||
tagLine?: string;
|
||||
profileIconId?: number;
|
||||
tier?: ApiTierInfo;
|
||||
preferredPositions: ApiPositionPreference[];
|
||||
joinedAt: string;
|
||||
excluded?: boolean;
|
||||
}
|
||||
|
||||
export interface ApiMatchTeamMember {
|
||||
userId: string;
|
||||
assignedPosition: Position;
|
||||
cost?: number;
|
||||
}
|
||||
|
||||
export interface ApiMatchTeam {
|
||||
teamIndex: number;
|
||||
name: string;
|
||||
captainUserId?: string;
|
||||
members: ApiMatchTeamMember[];
|
||||
}
|
||||
|
||||
export interface ApiMatchScheduleItem {
|
||||
time: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface ManualTournamentResultCollectResponse {
|
||||
scanned: number;
|
||||
matched: number;
|
||||
@@ -180,31 +137,6 @@ export interface ManualTournamentResultCollectResponse {
|
||||
gameNumbers: number[];
|
||||
}
|
||||
|
||||
export interface ApiMatch {
|
||||
_id: string;
|
||||
communityId: string;
|
||||
shortCode?: string;
|
||||
title: string;
|
||||
description: string;
|
||||
mapId: number;
|
||||
status: MatchStatus;
|
||||
scheduledAt: string;
|
||||
maxParticipants: number;
|
||||
gameCount: number;
|
||||
gameMode: MatchGameMode;
|
||||
roundRobinMaxRounds?: number;
|
||||
doubleEliminationResetFinalEnabled?: boolean;
|
||||
hostUserId?: string;
|
||||
participants: ApiMatchParticipant[];
|
||||
teams: ApiMatchTeam[];
|
||||
prizes: string[];
|
||||
notices: string[];
|
||||
schedule: ApiMatchScheduleItem[];
|
||||
joined?: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface ApiAuctionPlayerSnapshot {
|
||||
userId: string;
|
||||
puuid: string;
|
||||
@@ -336,13 +268,6 @@ export interface MeResponse {
|
||||
memberships: ApiMembership[];
|
||||
}
|
||||
|
||||
export interface MatchesResponse {
|
||||
matches: ApiMatch[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
export interface MatchMutationRequest {
|
||||
title: string;
|
||||
description?: string;
|
||||
@@ -355,7 +280,7 @@ export interface MatchMutationRequest {
|
||||
doubleEliminationResetFinalEnabled?: boolean;
|
||||
prizes?: string[];
|
||||
notices?: string[];
|
||||
schedule?: ApiMatchScheduleItem[];
|
||||
schedule?: MatchScheduleItemView[];
|
||||
}
|
||||
|
||||
export interface DdragonChampionEntry {
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import type {
|
||||
MatchDetailResponse,
|
||||
MatchParticipantView,
|
||||
} from "@lolympus/contracts";
|
||||
import { ChevronLeft, Search, X } from "lucide-react";
|
||||
import { Link, useLocation, useNavigate, useParams } from "react-router";
|
||||
import {
|
||||
@@ -37,8 +41,6 @@ import type {
|
||||
AuctionTopTierThreshold,
|
||||
ApiCommunityUserSearchCandidate,
|
||||
ApiCommunityUserSearchRiotAccount,
|
||||
ApiMatch,
|
||||
ApiMatchParticipant,
|
||||
ApiPositionPreference,
|
||||
ApiTierInfo,
|
||||
ManualTournamentResultCollectResponse,
|
||||
@@ -138,7 +140,7 @@ function parseAuctionSecondsInput(value: string, min: number) {
|
||||
return seconds;
|
||||
}
|
||||
|
||||
function buildAuctionParticipantPool(participants: ApiMatchParticipant[]) {
|
||||
function buildAuctionParticipantPool(participants: MatchParticipantView[]) {
|
||||
const ordered = [...participants].sort(
|
||||
(left, right) =>
|
||||
new Date(left.joinedAt).getTime() - new Date(right.joinedAt).getTime(),
|
||||
@@ -148,7 +150,7 @@ function buildAuctionParticipantPool(participants: ApiMatchParticipant[]) {
|
||||
}
|
||||
|
||||
function buildCaptainSlots(
|
||||
participants: ApiMatchParticipant[],
|
||||
participants: MatchParticipantView[],
|
||||
): CaptainSelectionSlot[] {
|
||||
const teamCount = Math.floor(
|
||||
buildAuctionParticipantPool(participants).length / 5,
|
||||
@@ -1451,7 +1453,7 @@ export default function MatchDetailPage() {
|
||||
},
|
||||
});
|
||||
|
||||
const matchQueryKey = ["match", DEFAULT_COMMUNITY_ID, id ?? null];
|
||||
const matchQueryKey = matchQuery.queryKey;
|
||||
|
||||
const addParticipantMutation = useMutation({
|
||||
mutationFn: ({
|
||||
@@ -1463,7 +1465,7 @@ export default function MatchDetailPage() {
|
||||
preferredPositions: ApiPositionPreference[];
|
||||
riotPuuid?: string;
|
||||
}) =>
|
||||
apiFetch<ApiMatch>(
|
||||
apiFetch<MatchDetailResponse>(
|
||||
`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`,
|
||||
{
|
||||
method: "POST",
|
||||
@@ -1488,9 +1490,10 @@ export default function MatchDetailPage() {
|
||||
),
|
||||
onMutate: async (userId: string) => {
|
||||
await queryClient.cancelQueries({ queryKey: matchQueryKey });
|
||||
const previous = queryClient.getQueryData<ApiMatch>(matchQueryKey);
|
||||
const previous =
|
||||
queryClient.getQueryData<MatchDetailResponse>(matchQueryKey);
|
||||
if (previous) {
|
||||
queryClient.setQueryData<ApiMatch>(matchQueryKey, {
|
||||
queryClient.setQueryData<MatchDetailResponse>(matchQueryKey, {
|
||||
...previous,
|
||||
participants: previous.participants.filter(
|
||||
(participant) => participant.userId !== userId,
|
||||
@@ -1531,9 +1534,10 @@ export default function MatchDetailPage() {
|
||||
),
|
||||
onMutate: async ({ userId, mainPosition, subPosition }) => {
|
||||
await queryClient.cancelQueries({ queryKey: matchQueryKey });
|
||||
const previous = queryClient.getQueryData<ApiMatch>(matchQueryKey);
|
||||
const previous =
|
||||
queryClient.getQueryData<MatchDetailResponse>(matchQueryKey);
|
||||
if (previous) {
|
||||
queryClient.setQueryData<ApiMatch>(matchQueryKey, {
|
||||
queryClient.setQueryData<MatchDetailResponse>(matchQueryKey, {
|
||||
...previous,
|
||||
participants: previous.participants.map((participant) =>
|
||||
participant.userId === userId
|
||||
@@ -1759,7 +1763,7 @@ export default function MatchDetailPage() {
|
||||
const manualPriorityCandidates = auctionParticipantPool.filter(
|
||||
(participant) => !selectedCaptainIds.includes(participant.userId),
|
||||
);
|
||||
const manualPriorityCandidateIds = new Set(
|
||||
const manualPriorityCandidateIds = new Set<string>(
|
||||
manualPriorityCandidates.map((participant) => participant.userId),
|
||||
);
|
||||
const selectedManualTopTierUserIds =
|
||||
|
||||
@@ -1,41 +1,112 @@
|
||||
import { useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Link, useParams } from "react-router";
|
||||
import { useCompetition, useTeamCompetition } from "../api/hooks";
|
||||
import { SeriesScoreCard } from "../components/competition/SeriesScoreCard";
|
||||
import { DEFAULT_COMMUNITY_ID } from "../config";
|
||||
import {
|
||||
getTeamProgressErrorContent,
|
||||
isConsistentTeamProgressSnapshot,
|
||||
type TeamProgressErrorContent,
|
||||
} from "./match-team-progress-state";
|
||||
|
||||
export default function MatchTeamProgressPage() {
|
||||
const { id } = useParams();
|
||||
const competitionQuery = useCompetition(id, DEFAULT_COMMUNITY_ID);
|
||||
const teamQuery = useTeamCompetition(id, DEFAULT_COMMUNITY_ID);
|
||||
const refetchCompetition = competitionQuery.refetch;
|
||||
const refetchTeam = teamQuery.refetch;
|
||||
const [copiedSlotId, setCopiedSlotId] = useState<string | null>(null);
|
||||
const lastAutoRefetchedMismatchRef = useRef<string | null>(null);
|
||||
const competition = competitionQuery.data;
|
||||
const teamView = teamQuery.data;
|
||||
const hasQueryError = Boolean(
|
||||
competitionQuery.error || teamQuery.error,
|
||||
);
|
||||
const isRefetching = competitionQuery.isFetching || teamQuery.isFetching;
|
||||
const revisionsMatch = isConsistentTeamProgressSnapshot(
|
||||
competition,
|
||||
teamView,
|
||||
);
|
||||
const revisionMismatchKey =
|
||||
competition && teamView && !revisionsMatch
|
||||
? `${competition.revision}:${teamView.revision}`
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!revisionMismatchKey) {
|
||||
lastAutoRefetchedMismatchRef.current = null;
|
||||
return;
|
||||
}
|
||||
if (
|
||||
hasQueryError ||
|
||||
isRefetching ||
|
||||
lastAutoRefetchedMismatchRef.current === revisionMismatchKey
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastAutoRefetchedMismatchRef.current = revisionMismatchKey;
|
||||
void Promise.all([refetchCompetition(), refetchTeam()]).catch(
|
||||
() => undefined,
|
||||
);
|
||||
}, [
|
||||
hasQueryError,
|
||||
isRefetching,
|
||||
refetchCompetition,
|
||||
refetchTeam,
|
||||
revisionMismatchKey,
|
||||
]);
|
||||
|
||||
function retryBoth() {
|
||||
void Promise.all([refetchCompetition(), refetchTeam()]).catch(
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
|
||||
if (competitionQuery.isLoading || teamQuery.isLoading) {
|
||||
return <TeamProgressLoadingState />;
|
||||
}
|
||||
|
||||
if (hasQueryError) {
|
||||
return (
|
||||
<main
|
||||
className="mx-auto max-w-5xl space-y-3 px-4 py-12 sm:px-6"
|
||||
aria-busy="true"
|
||||
aria-label="팀 진행 정보를 불러오는 중"
|
||||
>
|
||||
<div className="h-7 w-48 animate-pulse bg-base-200" />
|
||||
<div className="h-32 animate-pulse bg-base-200/70" />
|
||||
</main>
|
||||
<TeamProgressProblemState
|
||||
content={getTeamProgressErrorContent(
|
||||
[competitionQuery.error, teamQuery.error].filter(Boolean),
|
||||
)}
|
||||
isRetrying={isRefetching}
|
||||
matchId={id}
|
||||
onRetry={retryBoth}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const competition = competitionQuery.data;
|
||||
const teamView = teamQuery.data;
|
||||
if (!competition || !teamView) {
|
||||
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/45">
|
||||
이 내전에 참여한 계정으로 로그인했는지 확인해주세요.
|
||||
</p>
|
||||
<Link to={`/match/${id}`} className="btn btn-primary btn-sm mt-5">
|
||||
내전 상세로
|
||||
</Link>
|
||||
</main>
|
||||
<TeamProgressProblemState
|
||||
content={getTeamProgressErrorContent([])}
|
||||
isRetrying={isRefetching}
|
||||
matchId={id}
|
||||
onRetry={retryBoth}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (!revisionsMatch) {
|
||||
return (
|
||||
<TeamProgressProblemState
|
||||
content={{
|
||||
kind: "unknown",
|
||||
title: isRefetching
|
||||
? "최신 경기 정보를 맞추는 중입니다"
|
||||
: "경기 정보의 revision이 일치하지 않습니다",
|
||||
description: isRefetching
|
||||
? "Competition과 팀 정보를 함께 다시 불러오고 있습니다."
|
||||
: "일관된 경기 정보를 표시할 수 없어 두 응답을 다시 확인해야 합니다.",
|
||||
}}
|
||||
isRetrying={isRefetching}
|
||||
matchId={id}
|
||||
onRetry={retryBoth}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -208,6 +279,59 @@ export default function MatchTeamProgressPage() {
|
||||
);
|
||||
}
|
||||
|
||||
function TeamProgressLoadingState() {
|
||||
return (
|
||||
<main
|
||||
className="mx-auto max-w-5xl space-y-3 px-4 py-12 sm:px-6"
|
||||
aria-busy="true"
|
||||
aria-label="팀 진행 정보를 불러오는 중"
|
||||
>
|
||||
<div className="h-7 w-48 animate-pulse bg-base-200" />
|
||||
<div className="h-32 animate-pulse bg-base-200/70" />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function TeamProgressProblemState({
|
||||
content,
|
||||
isRetrying,
|
||||
matchId,
|
||||
onRetry,
|
||||
}: {
|
||||
content: TeamProgressErrorContent;
|
||||
isRetrying: boolean;
|
||||
matchId: string | undefined;
|
||||
onRetry: () => void;
|
||||
}) {
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-20 sm:px-6">
|
||||
<section
|
||||
role="alert"
|
||||
aria-busy={isRetrying}
|
||||
className="border border-base-content/10 bg-base-100 px-5 py-8 text-center"
|
||||
>
|
||||
<h1 className="text-lg font-bold">{content.title}</h1>
|
||||
<p className="mt-2 text-sm text-base-content/45">
|
||||
{content.description}
|
||||
</p>
|
||||
<div className="mt-5 flex flex-wrap justify-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary btn-sm"
|
||||
disabled={isRetrying}
|
||||
onClick={onRetry}
|
||||
>
|
||||
{isRetrying ? "다시 불러오는 중..." : "다시 시도"}
|
||||
</button>
|
||||
<Link to={`/match/${matchId}`} className="btn btn-ghost btn-sm">
|
||||
내전 상세로
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyState({ message }: { message: string }) {
|
||||
return (
|
||||
<p
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import type {
|
||||
MatchDetailResponse,
|
||||
MatchGameMode,
|
||||
MatchScheduleItemView,
|
||||
} from '@lolympus/contracts';
|
||||
import { Link, useParams } from 'react-router';
|
||||
import {
|
||||
useCreateMatch,
|
||||
@@ -8,12 +13,7 @@ import {
|
||||
useMe,
|
||||
useUpdateMatch,
|
||||
} from '../../api/hooks';
|
||||
import type {
|
||||
ApiMatch,
|
||||
ApiMatchScheduleItem,
|
||||
MatchGameMode,
|
||||
MatchMutationRequest,
|
||||
} from '../../api/types';
|
||||
import type { MatchMutationRequest } from '../../api/types';
|
||||
import { DEFAULT_COMMUNITY_ID } from '../../config';
|
||||
|
||||
const DEFAULT_FORM: MatchMutationRequest = {
|
||||
@@ -92,7 +92,7 @@ function parseLines(value: string) {
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function parseSchedule(value: string): ApiMatchScheduleItem[] {
|
||||
function parseSchedule(value: string): MatchScheduleItemView[] {
|
||||
return parseLines(value).map((line) => {
|
||||
const [time, ...labelParts] = line.split('|').map((part) => part.trim());
|
||||
return {
|
||||
@@ -102,11 +102,11 @@ function parseSchedule(value: string): ApiMatchScheduleItem[] {
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleToText(schedule: ApiMatchScheduleItem[] = []) {
|
||||
function scheduleToText(schedule: MatchScheduleItemView[] = []) {
|
||||
return schedule.map((item) => `${item.time}|${item.label}`).join('\n');
|
||||
}
|
||||
|
||||
function makeForm(match?: ApiMatch): MatchMutationRequest & {
|
||||
function makeForm(match?: MatchDetailResponse): MatchMutationRequest & {
|
||||
prizesText: string;
|
||||
noticesText: string;
|
||||
scheduleText: string;
|
||||
@@ -149,7 +149,7 @@ export default function MatchAdminPage() {
|
||||
const createMutation = useCreateMatch(communityId);
|
||||
const updateMutation = useUpdateMatch(communityId);
|
||||
const deleteMutation = useDeleteMatch(communityId);
|
||||
const [editing, setEditing] = useState<ApiMatch | null>(null);
|
||||
const [editing, setEditing] = useState<MatchDetailResponse | null>(null);
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
const [form, setForm] = useState(makeForm());
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
@@ -181,7 +181,7 @@ export default function MatchAdminPage() {
|
||||
setMessage(null);
|
||||
}
|
||||
|
||||
function openEdit(match: ApiMatch) {
|
||||
function openEdit(match: MatchDetailResponse) {
|
||||
setEditing(match);
|
||||
setForm(makeForm(match));
|
||||
setShowForm(true);
|
||||
@@ -550,7 +550,15 @@ export default function MatchAdminPage() {
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs px-2 py-1 border border-red-500/20 text-red-400 hover:bg-red-500/10"
|
||||
disabled={deleteMutation.isPending}
|
||||
disabled={
|
||||
deleteMutation.isPending ||
|
||||
match.status !== 'recruiting'
|
||||
}
|
||||
title={
|
||||
match.status === 'recruiting'
|
||||
? '내전 삭제'
|
||||
: '팀 구성이 확정된 내전 기록은 삭제할 수 없습니다.'
|
||||
}
|
||||
onClick={() => {
|
||||
if (!window.confirm('이 내전을 삭제할까요?')) return;
|
||||
deleteMutation.mutate(match._id, {
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
interface RevisionedSnapshot {
|
||||
revision: number;
|
||||
}
|
||||
|
||||
export type TeamProgressErrorContent = {
|
||||
kind:
|
||||
| "unauthorized"
|
||||
| "forbidden"
|
||||
| "not-found"
|
||||
| "not-ready"
|
||||
| "server"
|
||||
| "network"
|
||||
| "unknown";
|
||||
title: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
export function isConsistentTeamProgressSnapshot(
|
||||
competition: RevisionedSnapshot | null | undefined,
|
||||
teamView: RevisionedSnapshot | null | undefined,
|
||||
): boolean {
|
||||
return Boolean(
|
||||
competition &&
|
||||
teamView &&
|
||||
competition.revision === teamView.revision,
|
||||
);
|
||||
}
|
||||
|
||||
export function getTeamProgressErrorContent(
|
||||
errors: readonly unknown[],
|
||||
): TeamProgressErrorContent {
|
||||
const statuses = errors.flatMap((error) => {
|
||||
if (typeof error !== "object" || error === null || !("status" in error)) {
|
||||
return [];
|
||||
}
|
||||
return typeof error.status === "number" ? [error.status] : [];
|
||||
});
|
||||
|
||||
if (statuses.includes(401)) {
|
||||
return {
|
||||
kind: "unauthorized",
|
||||
title: "로그인이 필요합니다",
|
||||
description: "팀 진행 정보를 보려면 로그인한 뒤 다시 시도해 주세요.",
|
||||
};
|
||||
}
|
||||
if (statuses.includes(403)) {
|
||||
return {
|
||||
kind: "forbidden",
|
||||
title: "팀 진행 정보를 볼 권한이 없습니다",
|
||||
description:
|
||||
"이 내전에 참여한 팀원 계정으로 로그인했는지 확인해 주세요.",
|
||||
};
|
||||
}
|
||||
if (statuses.includes(404)) {
|
||||
return {
|
||||
kind: "not-found",
|
||||
title: "팀 진행 정보를 찾을 수 없습니다",
|
||||
description: "내전이 삭제되었거나 Competition이 아직 준비되지 않았습니다.",
|
||||
};
|
||||
}
|
||||
if (statuses.includes(409)) {
|
||||
return {
|
||||
kind: "not-ready",
|
||||
title: "Competition이 아직 준비되지 않았습니다",
|
||||
description: "팀 구성이 완료된 뒤 다시 시도해 주세요.",
|
||||
};
|
||||
}
|
||||
if (statuses.some((status) => status >= 500 && status <= 599)) {
|
||||
return {
|
||||
kind: "server",
|
||||
title: "서버에서 팀 진행 정보를 불러오지 못했습니다",
|
||||
description: "잠시 후 다시 시도해 주세요.",
|
||||
};
|
||||
}
|
||||
if (errors.some(isNetworkError)) {
|
||||
return {
|
||||
kind: "network",
|
||||
title: "네트워크에 연결할 수 없습니다",
|
||||
description: "인터넷 연결을 확인한 뒤 다시 시도해 주세요.",
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: "unknown",
|
||||
title: "팀 진행 정보를 불러오지 못했습니다",
|
||||
description: "일시적인 오류일 수 있습니다. 다시 시도해 주세요.",
|
||||
};
|
||||
}
|
||||
|
||||
function isNetworkError(error: unknown): boolean {
|
||||
return (
|
||||
error instanceof TypeError ||
|
||||
(error instanceof Error && error.name === "TypeError")
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user