diff --git a/apps/api/src/modules/tournament-code/tournament-code.controller.ts b/apps/api/src/modules/tournament-code/tournament-code.controller.ts index cd28cd47..aac93705 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.controller.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.controller.ts @@ -7,6 +7,7 @@ import { HttpCode, HttpStatus, Param, + ParseIntPipe, Post, Query, UseGuards, @@ -71,6 +72,21 @@ export class TournamentCodeController { return this.tournamentCodeService.stats(); } + @Post('matches/:matchId/games/:gameNumber/replace') + public async replaceForMatchGame( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Param('gameNumber', ParseIntPipe) gameNumber: number, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.tournamentCodeService.replaceForMatchGame({ + matchId, + gameNumber, + }); + } + @Post(':id/release') public async restore( @CurrentUser() currentUser: UserDocument, diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts b/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts index 9c51de74..00415405 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.service.spec.ts @@ -1,4 +1,5 @@ import type { MatchDocument } from '../global/database/schema'; +import mongoose from 'mongoose'; import { TournamentCodeService } from './tournament-code.service'; type TournamentCodeServiceInternals = TournamentCodeService & { @@ -8,6 +9,10 @@ type TournamentCodeServiceInternals = TournamentCodeService & { gameNumber: number, ): { teamAIndex: number; teamBIndex: number }; ensureGameSchedule(match: MatchDocument): void; + replaceForMatchGame(params: { + matchId: mongoose.Types.ObjectId; + gameNumber: number; + }): Promise; }; function createService() { @@ -32,11 +37,15 @@ interface MatchOverrides { function createMatch(overrides: MatchOverrides): MatchDocument { return { + _id: new mongoose.Types.ObjectId(), + status: 'in-progress', gameCount: 1, gameMode: 'pair', participants: [], teams: [], + tournamentCodeIds: [], gameSchedule: [], + save: jest.fn().mockResolvedValue(undefined), ...overrides, } as unknown as MatchDocument; } @@ -307,3 +316,176 @@ describe('TournamentCodeService round-robin scheduling', () => { expect(slots).toEqual([]); }); }); + +describe('TournamentCodeService code replacement', () => { + function queryResult(value: T) { + return { exec: jest.fn().mockResolvedValue(value) }; + } + + function createCode(overrides: Record) { + return { + _id: new mongoose.Types.ObjectId(), + code: 'CODE', + state: 'reserved', + expiresAt: new Date(Date.now() + 60 * 60 * 1000), + matchId: new mongoose.Types.ObjectId(), + gameNumber: 1, + reservedAt: new Date(), + releasedAt: undefined, + riotMatchId: undefined, + save: jest.fn().mockResolvedValue(undefined), + ...overrides, + }; + } + + function createReplacementFixture(params?: { + currentCode?: Record | null; + replacementCode?: Record | null; + match?: MatchDocument; + }) { + const matchId = new mongoose.Types.ObjectId(); + const oldCodeId = new mongoose.Types.ObjectId(); + const newCodeId = new mongoose.Types.ObjectId(); + const match = + params?.match ?? + createMatch({ + _id: matchId, + status: 'in-progress', + gameCount: 1, + participants: Array.from({ length: 10 }, () => ({})), + teams: [{ teamIndex: 1 }, { teamIndex: 2 }], + tournamentCodeIds: [oldCodeId], + } as unknown as MatchOverrides); + const currentCode = + params?.currentCode === null + ? null + : createCode({ + _id: oldCodeId, + code: 'OLD-CODE', + matchId, + gameNumber: 1, + ...(params?.currentCode ?? {}), + }); + const replacementCode = + params?.replacementCode === null + ? null + : createCode({ + _id: newCodeId, + code: 'NEW-CODE', + matchId, + gameNumber: 1, + ...(params?.replacementCode ?? {}), + }); + + const MatchModel = { + findById: jest.fn().mockReturnValue(queryResult(match)), + }; + const TournamentCodeModel = { + findOne: jest.fn().mockReturnValue(queryResult(currentCode)), + findOneAndUpdate: jest.fn().mockReturnValue(queryResult(replacementCode)), + }; + const connectionService = { + getModel: jest.fn().mockImplementation((modelName: string) => { + if (modelName === 'match') return Promise.resolve(MatchModel); + if (modelName === 'tournamentCode') { + return Promise.resolve(TournamentCodeModel); + } + throw new Error(`Unexpected model: ${modelName}`); + }), + }; + const service = new TournamentCodeService( + connectionService as never, + ) as unknown as TournamentCodeServiceInternals; + + return { + match, + matchId, + currentCode, + replacementCode, + MatchModel, + TournamentCodeModel, + service, + }; + } + + it('replaces a reserved code on the same game slot', async () => { + const { match, matchId, currentCode, replacementCode, TournamentCodeModel, service } = + createReplacementFixture(); + + const slot = await service.replaceForMatchGame({ + matchId, + gameNumber: 1, + }); + + expect(slot).toEqual( + expect.objectContaining({ + gameNumber: 1, + teamAIndex: 1, + teamBIndex: 2, + code: 'NEW-CODE', + state: 'reserved', + }), + ); + expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledWith( + expect.objectContaining({ + state: 'available', + region: 'kr', + mapType: 'SUMMONERS_RIFT', + teamSize: 5, + }), + expect.objectContaining({ + $set: expect.objectContaining({ + state: 'reserved', + matchId, + gameNumber: 1, + }), + }), + expect.objectContaining({ returnDocument: 'after' }), + ); + expect(currentCode?.state).toBe('released'); + expect(currentCode?.matchId).toBeUndefined(); + expect(currentCode?.gameNumber).toBeUndefined(); + expect(currentCode?.save).toHaveBeenCalled(); + expect(match.tournamentCodeIds.map((id) => id.toString())).toEqual([ + replacementCode?._id.toString(), + ]); + expect(match.save).toHaveBeenCalled(); + }); + + it('rejects replacement after the game result is collected', async () => { + const matchId = new mongoose.Types.ObjectId(); + const fixture = createReplacementFixture({ + match: createMatch({ + _id: matchId, + status: 'in-progress', + gameCount: 1, + participants: Array.from({ length: 10 }, () => ({})), + teams: [{ teamIndex: 1 }, { teamIndex: 2 }], + tournamentCodeIds: [new mongoose.Types.ObjectId()], + result: { + riotMatchIds: ['KR_1'], + games: [{ gameNumber: 1 }], + seriesResults: [], + }, + } as unknown as MatchOverrides), + }); + + await expect( + fixture.service.replaceForMatchGame({ matchId, gameNumber: 1 }), + ).rejects.toThrow('already has a collected result'); + expect(fixture.TournamentCodeModel.findOne).not.toHaveBeenCalled(); + expect(fixture.TournamentCodeModel.findOneAndUpdate).not.toHaveBeenCalled(); + }); + + it('leaves the current code untouched when no replacement code is available', async () => { + const { match, matchId, currentCode, service } = createReplacementFixture({ + replacementCode: null, + }); + + await expect( + service.replaceForMatchGame({ matchId, gameNumber: 1 }), + ).rejects.toThrow('No available tournament code'); + expect(currentCode?.save).not.toHaveBeenCalled(); + expect(match.save).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.ts b/apps/api/src/modules/tournament-code/tournament-code.service.ts index 613df6c8..f81b3760 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.service.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.service.ts @@ -273,6 +273,107 @@ export class TournamentCodeService { return match; } + public async replaceForMatchGame(params: { + matchId: mongoose.Types.ObjectId; + gameNumber: number; + }): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const match = await MatchModel.findById(params.matchId).exec(); + if (!match) throw new NotFoundException('Match not found.'); + if (match.status !== 'team-built' && match.status !== 'in-progress') { + throw new BadRequestException( + 'Tournament codes can only be replaced while the match is ready or in progress.', + ); + } + + match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; + match.tournamentCodeIds = match.tournamentCodeIds ?? []; + this.ensureGameSchedule(match); + + const requiredSlots = this.resolveRequiredSlots(match); + if ( + !Number.isInteger(params.gameNumber) || + params.gameNumber < 1 || + params.gameNumber > requiredSlots + ) { + throw new BadRequestException('Invalid tournament code game number.'); + } + if ( + (match.result?.games ?? []).some( + (game) => game.gameNumber === params.gameNumber, + ) + ) { + throw new BadRequestException( + 'This game already has a collected result and cannot be replaced.', + ); + } + + const currentCode = await TournamentCodeModel.findOne({ + _id: { $in: match.tournamentCodeIds }, + matchId: match._id, + gameNumber: params.gameNumber, + }).exec(); + if (!currentCode) { + throw new NotFoundException('Assigned tournament code not found.'); + } + if (currentCode.state === 'used' || currentCode.riotMatchId) { + throw new BadRequestException('Used tournament codes cannot be replaced.'); + } + + const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS); + const replacement = await TournamentCodeModel.findOneAndUpdate( + { + state: 'available', + region: DEFAULT_REGION, + mapType: 'SUMMONERS_RIFT', + teamSize: 5, + expiresAt: { $gt: expiresAfter }, + }, + { + $set: { + state: 'reserved', + matchId: match._id, + gameNumber: params.gameNumber, + reservedAt: new Date(), + }, + $unset: { releasedAt: 1 }, + }, + { sort: { expiresAt: 1 }, returnDocument: 'after' }, + ).exec(); + if (!replacement) { + throw new BadRequestException('No available tournament code to replace with.'); + } + + currentCode.state = 'released'; + currentCode.matchId = undefined; + currentCode.gameNumber = undefined; + currentCode.reservedAt = undefined; + currentCode.releasedAt = new Date(); + currentCode.riotMatchId = undefined; + match.tournamentCodeIds = this.replaceTournamentCodeId( + match.tournamentCodeIds, + currentCode._id, + replacement._id, + ); + await currentCode.save(); + await match.save(); + + return { + gameNumber: params.gameNumber, + roundNumber: this.resolveRoundNumberForGameNumber( + match, + params.gameNumber, + ), + ...this.resolveSeriesRefForGameNumber(match, params.gameNumber), + code: replacement.code, + expiresAt: replacement.expiresAt.toISOString(), + state: replacement.state, + riotMatchId: replacement.riotMatchId ?? null, + }; + } + public async releaseFromMatch( matchOrId: MatchDocument | mongoose.Types.ObjectId, ): Promise { @@ -390,6 +491,21 @@ export class TournamentCodeService { return (code ?? '').trim().toUpperCase(); } + private replaceTournamentCodeId( + currentIds: mongoose.Types.ObjectId[], + oldId: mongoose.Types.ObjectId, + newId: mongoose.Types.ObjectId, + ): mongoose.Types.ObjectId[] { + let replaced = false; + const next = currentIds.map((id) => { + if (id.toString() !== oldId.toString()) return id; + replaced = true; + return newId; + }); + if (!replaced) next.push(newId); + return next; + } + private resolveRequiredSlots(match: MatchDocument): number { const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; const gameMode = match.gameMode ?? 'pair'; diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index 35f35a56..27927829 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -41,6 +41,7 @@ import type { RebuildLegacyMatchesResponse, TournamentCodeBulkUploadResponse, TournamentCodeListResponse, + TournamentCodeSlotView, TournamentCodeState, TournamentCodeStatsResponse, TournamentCodeUploadItem, @@ -632,6 +633,16 @@ export function useDeleteTournamentCode(communityId = DEFAULT_COMMUNITY_ID) { }); } +export function useReplaceTournamentCode(communityId = DEFAULT_COMMUNITY_ID) { + return useMutation({ + mutationFn: (params: { matchId: string; gameNumber: number }) => + apiFetch( + `/communities/${communityId}/tournament-codes/matches/${params.matchId}/games/${params.gameNumber}/replace`, + { method: 'POST' }, + ), + }); +} + export function usePollTournamentResult(communityId = DEFAULT_COMMUNITY_ID) { return useMutation({ mutationFn: (matchId: string) => diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index 13c121d9..f8ed58f3 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from "react"; import { useMutation, useQueryClient } from "@tanstack/react-query"; -import { Search, X } from "lucide-react"; +import { AlertTriangle, Search, X } from "lucide-react"; import { Link, useLocation, useNavigate, useParams } from "react-router"; import { useAuction, @@ -11,6 +11,7 @@ import { useMatch, useMe, usePollTournamentResult, + useReplaceTournamentCode, useTournamentCodeStats, useUserHistoryProfile, } from "../api/hooks"; @@ -1393,12 +1394,11 @@ function SideCard({ function formatTournamentCodeExpiry(value: string | null) { if (!value) return null; - return new Intl.DateTimeFormat("ko-KR", { - month: "long", - day: "numeric", - hour: "2-digit", - minute: "2-digit", - }).format(new Date(value)); + const date = new Date(value); + if (Number.isNaN(date.getTime())) return null; + return `${date.getMonth() + 1}/${date.getDate()} ${String( + date.getHours(), + ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`; } function isExpiringSoon(value: string | null) { @@ -1407,11 +1407,23 @@ function isExpiringSoon(value: string | null) { return expiresAt - Date.now() <= 24 * 60 * 60 * 1000; } -function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) { +function TournamentCodeDisplay({ + slot, + canReplace, + replacing, + onReplace, +}: { + slot: TournamentCodeSlotView; + canReplace?: boolean; + replacing?: boolean; + onReplace?: (slot: TournamentCodeSlotView) => void; +}) { const [copied, setCopied] = useState(false); const expired = slot.state === "expired"; const used = slot.state === "used"; const expiringSoon = isExpiringSoon(slot.expiresAt); + const replaceable = Boolean(canReplace && slot.code && !used); + const expiryText = formatTournamentCodeExpiry(slot.expiresAt); async function copyCode() { if (!slot.code) return; @@ -1421,9 +1433,9 @@ function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) { } return ( -
+
- + {expired ? "코드 만료" : slot.code} - {slot.code && !expired && ( - - )}
-
- {used - ? "사용됨" - : expired - ? "운영자에게 새 코드를 요청해주세요." - : `만료: ${formatTournamentCodeExpiry(slot.expiresAt)}`} +
+
+ {used + ? "사용됨" + : expired + ? "운영자에게 새 코드를 요청해주세요." + : expiryText + ? `만료 ${expiryText}` + : "만료 정보 없음"} +
+
+ {slot.code && !expired && ( + + )} + {replaceable && ( + + )} +
); @@ -1462,9 +1490,15 @@ function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) { function TournamentCodeList({ slots, gameMode, + canReplace, + replacingGameNumber, + onReplace, }: { slots: TournamentCodeSlotView[]; gameMode: MatchGameMode; + canReplace?: boolean; + replacingGameNumber?: number | null; + onReplace?: (slot: TournamentCodeSlotView) => void; }) { if (slots.length === 0) { return ( @@ -1479,20 +1513,30 @@ function TournamentCodeList({ gameMode === "round-robin" || slot.teamAIndex > 1 || slot.teamBIndex > 2; return ( -
- - {slot.gameNumber}경기 +
+
+ + {slot.gameNumber}경기 + {shouldShowTeamLabel && ( - + {teamIndexLabel(slot.teamAIndex)} vs{" "} {teamIndexLabel(slot.teamBIndex)} )} - +
{slot.code ? ( - + ) : ( - + 발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다. )} @@ -1986,8 +2030,13 @@ export default function MatchDetailPage() { const [manualResultEndTime, setManualResultEndTime] = useState(""); const [manualRiotMatchId, setManualRiotMatchId] = useState(""); const [addParticipantOpen, setAddParticipantOpen] = useState(false); + const [replaceCodeSlot, setReplaceCodeSlot] = + useState(null); + const [replaceCodeConfirmText, setReplaceCodeConfirmText] = useState(""); const pollTournamentResultMutation = usePollTournamentResult(DEFAULT_COMMUNITY_ID); + const replaceTournamentCodeMutation = + useReplaceTournamentCode(DEFAULT_COMMUNITY_ID); const collectResultByWindowMutation = useCollectTournamentResultByWindow(DEFAULT_COMMUNITY_ID); const collectResultByRiotMatchMutation = @@ -2177,6 +2226,36 @@ export default function MatchDetailPage() { }); } + function handleReplaceTournamentCode(slot: TournamentCodeSlotView) { + if (!slot.code) return; + setReplaceCodeConfirmText(""); + setReplaceCodeSlot(slot); + } + + function handleConfirmReplaceTournamentCode() { + if (!id || !replaceCodeSlot || replaceCodeConfirmText.trim() !== "예") { + return; + } + replaceTournamentCodeMutation.mutate( + { matchId: id, gameNumber: replaceCodeSlot.gameNumber }, + { + onSuccess: async () => { + await Promise.all([ + invalidateCurrentMatch(), + queryClient.invalidateQueries({ + queryKey: ["tournament-code-stats", DEFAULT_COMMUNITY_ID], + }), + queryClient.invalidateQueries({ + queryKey: ["tournament-codes", DEFAULT_COMMUNITY_ID], + }), + ]); + setReplaceCodeSlot(null); + setReplaceCodeConfirmText(""); + }, + }, + ); + } + async function invalidateCurrentMatch() { await queryClient.invalidateQueries({ queryKey: ["match", DEFAULT_COMMUNITY_ID, id ?? null], @@ -2839,7 +2918,19 @@ export default function MatchDetailPage() { + {replaceTournamentCodeMutation.error instanceof Error && ( +
+ {replaceTournamentCodeMutation.error.message} +
+ )} )} @@ -2995,6 +3086,90 @@ export default function MatchDetailPage() { )}
+ + {replaceCodeSlot && ( +
+
+
+ + + +
+

+ 토너먼트 코드 교체 +

+

+ 정상적인 경기 진행이 불가한 경우 우리팀과 상대팀에 + 상황을 알린 뒤 {replaceCodeSlot.gameNumber}경기 코드를 + 교체하세요. +

+
+
+ + + setReplaceCodeConfirmText(event.target.value)} + onKeyDown={(event) => { + if (event.key === "Escape") { + setReplaceCodeSlot(null); + setReplaceCodeConfirmText(""); + } + if ( + event.key === "Enter" && + replaceCodeConfirmText.trim() === "예" && + !replaceTournamentCodeMutation.isPending + ) { + handleConfirmReplaceTournamentCode(); + } + }} + className="mt-2 h-10 w-full border border-base-content/15 bg-base-100 px-3 text-sm text-base-content outline-none transition-colors focus:border-amber-400/60" + placeholder="예" + /> + +
+ + +
+
+
+ )} ); }