From 5df3ea67e7246b63f3c25f41e58884e8702882a9 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 3 May 2026 04:33:47 -0700 Subject: [PATCH] . --- .../dto/manual-result-collection.dto.ts | 19 ++ .../tournament-result.controller.ts | 42 +++ .../tournament-result.service.spec.ts | 178 ++++++++++ .../tournament-result.service.ts | 307 ++++++++++++++++++ .../tournament-result.types.ts | 8 + apps/web/src/api/hooks.ts | 38 +++ apps/web/src/api/types.ts | 8 + apps/web/src/pages/MatchDetailPage.tsx | 201 +++++++++++- 8 files changed, 785 insertions(+), 16 deletions(-) create mode 100644 apps/api/src/modules/tournament-result/dto/manual-result-collection.dto.ts diff --git a/apps/api/src/modules/tournament-result/dto/manual-result-collection.dto.ts b/apps/api/src/modules/tournament-result/dto/manual-result-collection.dto.ts new file mode 100644 index 00000000..4a6898b1 --- /dev/null +++ b/apps/api/src/modules/tournament-result/dto/manual-result-collection.dto.ts @@ -0,0 +1,19 @@ +import { Type } from 'class-transformer'; +import { IsDate, IsString, MaxLength, MinLength } from 'class-validator'; + +export class CollectTournamentResultWindowDto { + @IsDate() + @Type(() => Date) + startTime!: Date; + + @IsDate() + @Type(() => Date) + endTime!: Date; +} + +export class CollectTournamentResultRiotMatchDto { + @IsString() + @MinLength(1) + @MaxLength(96) + riotMatchId!: string; +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.controller.ts b/apps/api/src/modules/tournament-result/tournament-result.controller.ts index 9f9e627e..b14abcfe 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.controller.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.controller.ts @@ -1,5 +1,6 @@ import { BadRequestException, + Body, Controller, Param, Post, @@ -11,6 +12,10 @@ import { Roles } from '../auth/roles.decorator'; import { RolesGuard } from '../auth/roles.guard'; import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; import type { UserDocument } from '../global/database/schema'; +import { + CollectTournamentResultRiotMatchDto, + CollectTournamentResultWindowDto, +} from './dto/manual-result-collection.dto'; import { TournamentResultService } from './tournament-result.service'; @Controller('communities/:communityId/matches/:matchId/poll-tournament-result') @@ -36,4 +41,41 @@ export class TournamentResultController { communityId, }); } + + @Post('collect-by-window') + public async collectByWindow( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: CollectTournamentResultWindowDto, + ) { + if (!currentUser.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + return this.tournamentResultService.collectManualByWindow({ + matchId, + communityId, + startTime: body.startTime, + endTime: body.endTime, + }); + } + + @Post('collect-by-riot-match') + public async collectByRiotMatch( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: CollectTournamentResultRiotMatchDto, + ) { + if (!currentUser.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + return this.tournamentResultService.collectManualByRiotMatch({ + matchId, + communityId, + riotMatchId: body.riotMatchId, + }); + } } diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts index baf5c0f2..878ec8ce 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts @@ -1,4 +1,6 @@ +import mongoose from 'mongoose'; import type { MatchDocument } from '../global/database/schema'; +import type { RiotMatchDto } from '../riot/riot.types'; import { TournamentResultService } from './tournament-result.service'; type TournamentResultServiceInternals = TournamentResultService & { @@ -81,3 +83,179 @@ describe('TournamentResultService round-robin scheduling', () => { }); }); }); + +describe('TournamentResultService manual result collection', () => { + function createManualFixture() { + const communityId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const users = Array.from({ length: 10 }, (_, index) => ({ + userId: new mongoose.Types.ObjectId(), + puuid: `puuid-${index + 1}`, + })); + const match = { + _id: matchId, + communityId, + gameCount: 1, + gameMode: 'pair', + teamBuiltAt: new Date('2026-05-03T10:00:00.000Z'), + status: 'team-built', + tournamentCodeIds: [], + gameSchedule: [], + participants: users.map((user) => ({ + userId: user.userId, + puuid: user.puuid, + excluded: false, + })), + teams: [ + { + teamIndex: 1, + members: users.slice(0, 5).map((user) => ({ userId: user.userId })), + }, + { + teamIndex: 2, + members: users.slice(5).map((user) => ({ userId: user.userId })), + }, + ], + save: jest.fn().mockResolvedValue(undefined), + } as unknown as MatchDocument & { + save: jest.Mock; + result?: MatchDocument['result']; + }; + const detail = { + metadata: { + matchId: 'KR_1234567890', + participants: users.map((user) => user.puuid), + }, + info: { + gameCreation: Date.parse('2026-05-03T10:30:00.000Z'), + gameDuration: 1800, + participants: users.map((user, index) => ({ + puuid: user.puuid, + teamId: index < 5 ? 100 : 200, + championId: 1, + kills: 1, + deaths: 1, + assists: 1, + win: index < 5, + })), + teams: [ + { teamId: 100, win: true }, + { teamId: 200, win: false }, + ], + }, + } as unknown as RiotMatchDto; + const communityFindById = jest.fn().mockReturnValue({ + select: jest.fn().mockReturnValue({ + lean: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ riotRegion: 'asia' }), + }), + }), + }); + const riotMatchFindOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue(null), + }); + const riotMatchUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue(undefined), + }); + const tournamentCodeUpdateOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue(undefined), + }); + const connectionService = { + getModel: jest.fn().mockImplementation(async (name: string) => { + if (name === 'match') { + return { findById: jest.fn().mockResolvedValue(match) }; + } + if (name === 'community') { + return { findById: communityFindById }; + } + if (name === 'riotMatch') { + return { + findOne: riotMatchFindOne, + updateOne: riotMatchUpdateOne, + }; + } + if (name === 'tournamentCode') { + return { updateOne: tournamentCodeUpdateOne }; + } + return {}; + }), + }; + const riotMatchService = { + getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_1234567890']), + getMatch: jest.fn().mockResolvedValue(detail), + }; + const service = new TournamentResultService( + connectionService as never, + riotMatchService as never, + {} as never, + { invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never, + ); + + return { + service, + match, + communityId, + matchId, + riotMatchService, + tournamentCodeUpdateOne, + }; + } + + it('collects by time window without setting Riot match type', async () => { + const { service, match, communityId, matchId, riotMatchService } = + createManualFixture(); + + const result = await service.collectManualByWindow({ + matchId, + communityId, + startTime: new Date('2026-05-03T10:00:00.000Z'), + endTime: new Date('2026-05-03T11:00:00.000Z'), + }); + + expect(result).toMatchObject({ + scanned: 1, + matched: 1, + gameNumbers: [1], + riotMatchIds: ['KR_1234567890'], + }); + expect(riotMatchService.getMatchIdsByPuuid).toHaveBeenCalledWith( + 'puuid-1', + expect.not.objectContaining({ type: expect.anything() }), + ); + expect(match.result?.games).toHaveLength(1); + expect(match.status).toBe('finished'); + }); + + it('collects directly by Riot match id', async () => { + const { + service, + match, + communityId, + matchId, + riotMatchService, + tournamentCodeUpdateOne, + } = createManualFixture(); + + const result = await service.collectManualByRiotMatch({ + matchId, + communityId, + riotMatchId: ' KR_1234567890 ', + }); + + expect(result.matched).toBe(1); + expect(riotMatchService.getMatchIdsByPuuid).not.toHaveBeenCalled(); + expect(riotMatchService.getMatch).toHaveBeenCalledWith('KR_1234567890', { + region: 'asia', + }); + expect(tournamentCodeUpdateOne).toHaveBeenCalledWith( + expect.objectContaining({ + matchId, + gameNumber: 1, + }), + expect.objectContaining({ + $set: expect.objectContaining({ riotMatchId: 'KR_1234567890' }), + }), + ); + expect(match.result?.games[0].winnerTeamIndex).toBe(1); + }); +}); diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.ts b/apps/api/src/modules/tournament-result/tournament-result.service.ts index 9a4e6765..5033007d 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -30,6 +30,7 @@ import { } from './team-mapping.util'; import type { EnqueueTournamentResultPollResult, + ManualTournamentResultCollectResponse, PollTournamentResultJob, } from './tournament-result.types'; @@ -39,6 +40,12 @@ const POLL_EXPIRY_MS = 24 * 60 * 60_000; const EXPAND_AFTER_MS = 60 * 60_000; const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60; +interface ManualGameAssignment { + gameNumber: number; + teamAIndex: number; + teamBIndex: number; +} + @Injectable() export class TournamentResultService { private readonly logger = new Logger(TournamentResultService.name); @@ -96,6 +103,75 @@ export class TournamentResultService { return result; } + public async collectManualByWindow(params: { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + startTime: Date; + endTime: Date; + }): Promise { + const match = await this.loadMatch(params.matchId); + this.assertManualCollectionAllowed(match, params.communityId); + if (params.startTime.getTime() > params.endTime.getTime()) { + throw new BadRequestException( + 'startTime must be less than or equal to endTime.', + ); + } + + const region = await this.resolveRiotRegion(match); + const lookup = await this.buildPuuidLookup(match); + const puuids = this.collectPollingPuuids(collectMatchUserIds(match), lookup); + const startTime = Math.floor(params.startTime.getTime() / 1000); + const endTime = Math.floor(params.endTime.getTime() / 1000); + const riotMatchIds = new Set(); + + for (const puuid of puuids) { + try { + const ids = await this.riotMatchService.getMatchIdsByPuuid(puuid, { + region, + startTime, + endTime, + count: 100, + }); + ids.forEach((id) => riotMatchIds.add(id)); + } catch (error) { + this.logger.warn( + `Manual result match id lookup failed for ${puuid}: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } + + const details = await this.loadRiotMatchDetails( + [...riotMatchIds], + region, + 'Manual result detail fetch failed', + ); + return this.applyManualRiotMatches(match, details, lookup); + } + + public async collectManualByRiotMatch(params: { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + riotMatchId: string; + }): Promise { + const match = await this.loadMatch(params.matchId); + this.assertManualCollectionAllowed(match, params.communityId); + + const normalizedRiotMatchId = params.riotMatchId.trim(); + if (!normalizedRiotMatchId) { + throw new BadRequestException('riotMatchId is required.'); + } + + const region = await this.resolveRiotRegion(match); + const lookup = await this.buildPuuidLookup(match); + const detail = await this.ensureRiotMatchPersisted( + normalizedRiotMatchId, + region, + ); + return this.applyManualRiotMatches(match, [detail], lookup); + } + public async cancelPolling( matchOrId: MatchDocument | mongoose.Types.ObjectId, ): Promise { @@ -245,6 +321,54 @@ export class TournamentResultService { return true; } + private async applyManualRiotMatches( + match: MatchDocument, + details: RiotMatchDto[], + lookup: MatchPuuidLookup, + ): Promise { + const sortedDetails = [...details].sort( + (left, right) => left.info.gameCreation - right.info.gameCreation, + ); + const appliedRiotMatchIds: string[] = []; + const appliedGameNumbers: number[] = []; + let skipped = 0; + + for (const detail of sortedDetails) { + if (this.hasResultForRiotMatch(match, detail.metadata.matchId)) { + skipped += 1; + continue; + } + + const gameResult = this.computeManualGameResult(match, detail, lookup); + if (!gameResult) { + skipped += 1; + continue; + } + + this.upsertGameResult(match, gameResult); + await this.markTournamentCodeUsedForManualResult(match, gameResult, detail); + appliedRiotMatchIds.push(detail.metadata.matchId); + appliedGameNumbers.push(gameResult.gameNumber); + } + + if (appliedRiotMatchIds.length > 0 && match.status === 'team-built') { + match.status = 'in-progress'; + } + this.updateManualCollectionState(match, appliedRiotMatchIds.length); + await match.save(); + if (this.hasAllRequiredGameResults(match)) { + await this.finishMatchFromManualResults(match); + } + + return { + scanned: sortedDetails.length, + matched: appliedRiotMatchIds.length, + skipped, + riotMatchIds: appliedRiotMatchIds, + gameNumbers: appliedGameNumbers, + }; + } + private async advanceMatchIfReady( match: MatchDocument, codes: TournamentCodeDocument[], @@ -344,6 +468,29 @@ export class TournamentResultService { return dto; } + private async loadRiotMatchDetails( + riotMatchIds: string[], + region: RiotRegionalRoute, + logPrefix: string, + ): Promise { + const details: RiotMatchDto[] = []; + const checked = new Set(); + for (const riotMatchId of riotMatchIds) { + if (checked.has(riotMatchId)) continue; + checked.add(riotMatchId); + try { + details.push(await this.ensureRiotMatchPersisted(riotMatchId, region)); + } catch (error) { + this.logger.warn( + `${logPrefix} ${riotMatchId}: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } + return details; + } + private async buildPuuidLookup(match: MatchDocument): Promise { const puuidByUserId = new Map(); const userIdByPuuid = new Map(); @@ -413,6 +560,133 @@ export class TournamentResultService { }; } + private computeManualGameResult( + match: MatchDocument, + detail: RiotMatchDto, + lookup: MatchPuuidLookup, + ): MatchGameResult | null { + for (const assignment of this.resolveOpenManualGameAssignments(match)) { + const gameResult = computeGameResult({ + match, + detail, + gameNumber: assignment.gameNumber, + lookup, + teamAIndex: assignment.teamAIndex, + teamBIndex: assignment.teamBIndex, + }); + if (gameResult) return gameResult; + } + return null; + } + + private resolveOpenManualGameAssignments( + match: MatchDocument, + ): ManualGameAssignment[] { + const usedGameNumbers = new Set( + (match.result?.games ?? []).map((game) => game.gameNumber), + ); + const assignments: ManualGameAssignment[] = []; + const requiredSlots = this.resolveRequiredGameSlots(match); + + for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) { + if (usedGameNumbers.has(gameNumber)) continue; + assignments.push({ + gameNumber, + ...this.resolveSeriesRefForGameNumber(match, gameNumber), + }); + } + return assignments; + } + + private hasResultForRiotMatch( + match: MatchDocument, + riotMatchId: string, + ): boolean { + return Boolean( + match.result?.games?.some((game) => game.riotMatchId === riotMatchId), + ); + } + + private hasAllRequiredGameResults(match: MatchDocument): boolean { + const requiredSlots = this.resolveRequiredGameSlots(match); + if (requiredSlots <= 0) return false; + const resultGameNumbers = new Set( + (match.result?.games ?? []).map((game) => game.gameNumber), + ); + for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) { + if (!resultGameNumbers.has(gameNumber)) return false; + } + return true; + } + + private updateManualCollectionState( + match: MatchDocument, + matchedCount: number, + ): void { + match.resultPollState = { + startedAt: match.resultPollState?.startedAt ?? new Date(), + lastPolledAt: new Date(), + lastPollOutcome: matchedCount > 0 ? 'matched' : 'not-found', + matchedCount: match.result?.games?.length ?? 0, + expandedToAllPuuids: true, + state: 'polling', + }; + } + + private async finishMatchFromManualResults( + match: MatchDocument, + ): Promise { + match.status = 'finished'; + if (match.result) { + match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex( + match.result.seriesResults ?? [], + ); + } + match.resultPollState = { + startedAt: match.resultPollState?.startedAt ?? new Date(), + lastPolledAt: new Date(), + lastPollOutcome: 'matched', + matchedCount: match.result?.games?.length ?? 0, + expandedToAllPuuids: true, + state: 'complete', + }; + await match.save(); + void this.communityStatsService + .invalidateCommunity(match.communityId) + .catch((error) => { + this.logger.warn( + `Failed to invalidate community stats cache for ${match.communityId.toString()}: ${ + error instanceof Error ? error.message : error + }`, + ); + }); + } + + private async markTournamentCodeUsedForManualResult( + match: MatchDocument, + gameResult: MatchGameResult, + detail: RiotMatchDto, + ): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + await TournamentCodeModel.updateOne( + { + matchId: match._id, + gameNumber: gameResult.gameNumber, + state: { $in: ['reserved', 'released'] }, + }, + { + $set: { + state: 'used', + usedAt: new Date( + detail.info.gameEndTimestamp ?? detail.info.gameCreation, + ), + riotMatchId: detail.metadata.matchId, + }, + }, + ).exec(); + } + private buildSeriesResults( games: MatchGameResult[], ): NonNullable['seriesResults'] { @@ -564,6 +838,39 @@ export class TournamentResultService { ); } + private assertManualCollectionAllowed( + match: MatchDocument, + communityId: mongoose.Types.ObjectId, + ): void { + if (!match.communityId.equals(communityId)) { + throw new BadRequestException('Match does not belong to this community.'); + } + if (!this.hasBuiltTeams(match)) { + throw new BadRequestException( + 'Match needs built teams before manual result collection.', + ); + } + } + + private hasBuiltTeams(match: MatchDocument): boolean { + return Boolean( + match.teamBuiltAt && + match.teams.length >= 2 && + match.teams.every((team) => team.members.length > 0), + ); + } + + private async resolveRiotRegion( + match: MatchDocument, + ): Promise { + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(match.communityId) + .select({ riotRegion: 1 }) + .lean() + .exec(); + return community?.riotRegion ?? 'asia'; + } + private async loadMatch( matchOrId: MatchDocument | mongoose.Types.ObjectId, ): Promise { diff --git a/apps/api/src/modules/tournament-result/tournament-result.types.ts b/apps/api/src/modules/tournament-result/tournament-result.types.ts index cd9fc0d7..687b9910 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.types.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.types.ts @@ -19,6 +19,14 @@ export interface EnqueueTournamentResultPollResult { expandedToAllPuuids: boolean; } +export interface ManualTournamentResultCollectResponse { + scanned: number; + matched: number; + skipped: number; + riotMatchIds: string[]; + gameNumbers: number[]; +} + export interface ComputedGameParticipant { userId: string; teamIndex: number; diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index 5847a73c..8546bf22 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -33,6 +33,7 @@ import type { MatchStatus, MatchMutationRequest, MatchesResponse, + ManualTournamentResultCollectResponse, MeResponse, RiotQueueGroup, RiotRankFilter, @@ -571,6 +572,43 @@ export function usePollTournamentResult(communityId = DEFAULT_COMMUNITY_ID) { }); } +export function useCollectTournamentResultByWindow( + communityId = DEFAULT_COMMUNITY_ID, +) { + return useMutation({ + mutationFn: (params: { + matchId: string; + startTime: string; + endTime: string; + }) => + apiFetch( + `/communities/${communityId}/matches/${params.matchId}/poll-tournament-result/collect-by-window`, + { + method: 'POST', + body: JSON.stringify({ + startTime: params.startTime, + endTime: params.endTime, + }), + }, + ), + }); +} + +export function useCollectTournamentResultByRiotMatch( + communityId = DEFAULT_COMMUNITY_ID, +) { + return useMutation({ + mutationFn: (params: { matchId: string; riotMatchId: string }) => + apiFetch( + `/communities/${communityId}/matches/${params.matchId}/poll-tournament-result/collect-by-riot-match`, + { + method: 'POST', + body: JSON.stringify({ riotMatchId: params.riotMatchId }), + }, + ), + }); +} + export function useLegacyImportMembers( options: { windowStart?: string; windowEnd?: string }, communityId = DEFAULT_COMMUNITY_ID, diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index c10c4d16..e349c1c9 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -205,6 +205,14 @@ export interface ApiMatchGameAssignment { teamBIndex: number; } +export interface ManualTournamentResultCollectResponse { + scanned: number; + matched: number; + skipped: number; + riotMatchIds: string[]; + gameNumbers: number[]; +} + export interface ApiMatch { _id: string; communityId: string; diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index 7b5e5b81..cf330b08 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -3,6 +3,8 @@ import { useMutation, useQueryClient } from "@tanstack/react-query"; import { Link, useLocation, useNavigate, useParams } from "react-router"; import { useAuction, + useCollectTournamentResultByRiotMatch, + useCollectTournamentResultByWindow, useDdragonManifest, useMatch, useMe, @@ -32,6 +34,7 @@ import type { AuctionTopTierThreshold, ApiMatchParticipant, ApiTierInfo, + ManualTournamentResultCollectResponse, Position, TeamSide, TournamentCodeSlotView, @@ -548,6 +551,14 @@ function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) { } function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) { + if (slots.length === 0) { + return ( +
+ 아직 배정된 코드가 없습니다. +
+ ); + } + return (
{slots.map((slot) => ( @@ -574,6 +585,23 @@ function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) { ); } +function toIsoFromLocalDateTime(value: string): string | null { + if (!value) return null; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return null; + return date.toISOString(); +} + +function formatManualCollectSummary( + result: ManualTournamentResultCollectResponse | undefined, +) { + if (!result) return null; + const games = result.gameNumbers.length + ? ` · ${result.gameNumbers.join(", ")}경기` + : ""; + return `${result.matched}/${result.scanned}개 반영${games}`; +} + function PoolStatsHint({ enabled }: { enabled: boolean }) { const statsQuery = useTournamentCodeStats(DEFAULT_COMMUNITY_ID, enabled); if (!enabled) return null; @@ -1001,8 +1029,16 @@ export default function MatchDetailPage() { const [bidExtensionSeconds, setBidExtensionSeconds] = useState( String(DEFAULT_AUCTION_BID_EXTENSION_SECONDS), ); + const [manualResultStartTime, setManualResultStartTime] = useState(""); + const [manualResultEndTime, setManualResultEndTime] = useState(""); + const [manualRiotMatchId, setManualRiotMatchId] = useState(""); const pollTournamentResultMutation = usePollTournamentResult(DEFAULT_COMMUNITY_ID); + const collectResultByWindowMutation = useCollectTournamentResultByWindow( + DEFAULT_COMMUNITY_ID, + ); + const collectResultByRiotMatchMutation = + useCollectTournamentResultByRiotMatch(DEFAULT_COMMUNITY_ID); const joinMatchMutation = useMutation({ mutationFn: () => @@ -1073,13 +1109,36 @@ export default function MatchDetailPage() { if (!id) return; pollTournamentResultMutation.mutate(id, { onSuccess: async () => { - await queryClient.invalidateQueries({ - queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null], - }); + await invalidateCurrentMatch(); }, }); } + async function invalidateCurrentMatch() { + await queryClient.invalidateQueries({ + queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null], + }); + } + + function handleCollectResultByWindow() { + if (!id) return; + const startTime = toIsoFromLocalDateTime(manualResultStartTime); + const endTime = toIsoFromLocalDateTime(manualResultEndTime); + if (!startTime || !endTime) return; + collectResultByWindowMutation.mutate( + { matchId: id, startTime, endTime }, + { onSuccess: invalidateCurrentMatch }, + ); + } + + function handleCollectResultByRiotMatch() { + if (!id || !manualRiotMatchId.trim()) return; + collectResultByRiotMatchMutation.mutate( + { matchId: id, riotMatchId: manualRiotMatchId.trim() }, + { onSuccess: invalidateCurrentMatch }, + ); + } + useEffect(() => { const participants = buildAuctionParticipantPool( matchQuery.data?.participants ?? [], @@ -1282,6 +1341,18 @@ export default function MatchDetailPage() {
)} + {collectResultByWindowMutation.error instanceof Error && ( +
+ {collectResultByWindowMutation.error.message} +
+ )} + + {collectResultByRiotMatchMutation.error instanceof Error && ( +
+ {collectResultByRiotMatchMutation.error.message} +
+ )} +
@@ -1660,19 +1731,117 @@ export default function MatchDetailPage() { (match.status === "team-built" || match.status === "in-progress") && ( -

- Riot match-v5에서 토너먼트 코드가 붙은 경기를 다시 찾습니다. -

- +
+
+
+ 토너먼트 코드 +
+ +
+ +
+
+ 시간 범위 +
+
+ + + + {formatManualCollectSummary( + collectResultByWindowMutation.data, + ) && ( +
+ {formatManualCollectSummary( + collectResultByWindowMutation.data, + )} +
+ )} +
+
+ +
+
+ Riot Match ID +
+
+ + setManualRiotMatchId(event.target.value) + } + placeholder="KR_1234567890" + className="w-full border border-base-content/10 bg-transparent px-2 py-2 text-[11px] text-base-content focus:outline-none focus:border-primary/30" + /> + + {formatManualCollectSummary( + collectResultByRiotMatchMutation.data, + ) && ( +
+ {formatManualCollectSummary( + collectResultByRiotMatchMutation.data, + )} +
+ )} +
+
+
)}