release/86 #2

Merged
dahyeon merged 108 commits from release/86 into main 2026-07-15 08:56:05 +00:00
5 changed files with 537 additions and 37 deletions
Showing only changes of commit 303886ed53 - Show all commits

No files matched your search

@@ -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,
@@ -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<unknown>;
};
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<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function createCode(overrides: Record<string, unknown>) {
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<string, unknown> | null;
replacementCode?: Record<string, unknown> | 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();
});
});
@@ -273,6 +273,107 @@ export class TournamentCodeService {
return match;
}
public async replaceForMatchGame(params: {
matchId: mongoose.Types.ObjectId;
gameNumber: number;
}): Promise<TournamentCodeSlotView> {
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<void> {
@@ -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';
+11
View File
@@ -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<TournamentCodeSlotView>(
`/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) =>
+212 -37
View File
@@ -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 (
<div className="flex-1 min-w-0">
<div className="min-w-0 space-y-1.5">
<div
className={`flex items-center gap-2 border px-2 py-1.5 ${
className={`border px-2 py-2 ${
expired
? "border-red-500/20 bg-red-500/8 text-red-400"
: used
@@ -1431,29 +1443,45 @@ function TournamentCodeDisplay({ slot }: { slot: TournamentCodeSlotView }) {
: "border-primary/20 bg-primary/5 text-base-content"
}`}
>
<code className="font-mono text-xs font-bold truncate">
<code className="block min-w-0 truncate font-mono text-[11px] font-bold leading-4">
{expired ? "코드 만료" : slot.code}
</code>
{slot.code && !expired && (
<button
type="button"
className="ml-auto text-xs px-1.5 py-0.5 border border-base-content/10 text-base-content/45 hover:text-primary"
onClick={copyCode}
>
{copied ? "복사됨" : "복사"}
</button>
)}
</div>
<div
className={`mt-1 text-xs ${
expired || expiringSoon ? "text-amber-500" : "text-base-content/30"
}`}
>
{used
? "사용됨"
: expired
? "운영자에게 새 코드를 요청해주세요."
: `만료: ${formatTournamentCodeExpiry(slot.expiresAt)}`}
<div className="flex items-center justify-between gap-2">
<div
className={`min-w-0 truncate text-xs ${
expired || expiringSoon ? "text-amber-500" : "text-base-content/30"
}`}
>
{used
? "사용됨"
: expired
? "운영자에게 새 코드를 요청해주세요."
: expiryText
? `만료 ${expiryText}`
: "만료 정보 없음"}
</div>
<div className="flex shrink-0 items-center gap-1">
{slot.code && !expired && (
<button
type="button"
className="whitespace-nowrap border border-base-content/10 px-1.5 py-0.5 text-xs text-base-content/45 hover:text-primary"
onClick={copyCode}
>
{copied ? "복사됨" : "복사"}
</button>
)}
{replaceable && (
<button
type="button"
className="whitespace-nowrap border border-base-content/10 px-1.5 py-0.5 text-xs text-base-content/45 hover:text-primary disabled:cursor-not-allowed disabled:opacity-45"
disabled={replacing}
onClick={() => onReplace?.(slot)}
>
{replacing ? "교체 중" : "교체"}
</button>
)}
</div>
</div>
</div>
);
@@ -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 (
<div key={slot.gameNumber} className="flex items-start gap-2">
<span className="text-xs font-bold text-base-content/40 w-20 shrink-0 pt-1.5">
{slot.gameNumber}경기
<div
key={slot.gameNumber}
className="border-b border-base-content/8 pb-2 last:border-b-0 last:pb-0"
>
<div className="mb-1.5 flex items-center justify-between gap-2">
<span className="shrink-0 text-xs font-bold text-base-content/45">
{slot.gameNumber}경기
</span>
{shouldShowTeamLabel && (
<span className="block text-xs font-normal text-base-content/25">
<span className="min-w-0 truncate text-xs text-base-content/30">
{teamIndexLabel(slot.teamAIndex)} vs{" "}
{teamIndexLabel(slot.teamBIndex)}
</span>
)}
</span>
</div>
{slot.code ? (
<TournamentCodeDisplay slot={slot} />
<TournamentCodeDisplay
slot={slot}
canReplace={canReplace}
replacing={replacingGameNumber === slot.gameNumber}
onReplace={onReplace}
/>
) : (
<span className="text-xs text-base-content/30 border border-dashed border-base-content/10 px-2 py-2 flex-1">
<span className="block border border-dashed border-base-content/10 px-2 py-2 text-xs text-base-content/30">
발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다.
</span>
)}
@@ -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<TournamentCodeSlotView | null>(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() {
<TournamentCodeList
slots={match.tournamentCodes}
gameMode={match.gameMode}
canReplace={canManageAuction}
replacingGameNumber={
replaceTournamentCodeMutation.isPending
? replaceTournamentCodeMutation.variables?.gameNumber ?? null
: null
}
onReplace={handleReplaceTournamentCode}
/>
{replaceTournamentCodeMutation.error instanceof Error && (
<div className="mt-3 border border-red-500/20 bg-red-500/8 px-3 py-2 text-xs text-red-300">
{replaceTournamentCodeMutation.error.message}
</div>
)}
<PoolStatsHint enabled={canManageAuction} />
</SideCard>
)}
@@ -2995,6 +3086,90 @@ export default function MatchDetailPage() {
)}
</div>
</div>
{replaceCodeSlot && (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/55 px-4"
role="dialog"
aria-modal="true"
aria-labelledby="tournament-code-replace-title"
>
<div className="w-full max-w-md border border-amber-500/25 bg-base-100 p-5 shadow-2xl">
<div className="flex items-start gap-3">
<span className="inline-flex h-9 w-9 shrink-0 items-center justify-center border border-amber-500/25 bg-amber-500/10 text-amber-400">
<AlertTriangle className="h-4 w-4" />
</span>
<div className="min-w-0">
<h2
id="tournament-code-replace-title"
className="text-base font-bold text-base-content"
>
토너먼트 코드 교체
</h2>
<p className="mt-2 text-sm leading-6 text-base-content/60">
정상적인 경기 진행이 불가한 경우 우리팀과 상대팀에
상황을 알린 뒤 {replaceCodeSlot.gameNumber}경기 코드를
교체하세요.
</p>
</div>
</div>
<label
htmlFor="tournament-code-replace-confirm"
className="mt-5 block text-xs font-bold uppercase tracking-wider text-base-content/40"
>
계속하려면 예 입력
</label>
<input
id="tournament-code-replace-confirm"
value={replaceCodeConfirmText}
onChange={(event) => 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="예"
/>
<div className="mt-5 flex flex-wrap justify-end gap-2">
<button
type="button"
className="btn btn-ghost btn-sm px-4 text-xs"
onClick={() => {
setReplaceCodeSlot(null);
setReplaceCodeConfirmText("");
}}
disabled={replaceTournamentCodeMutation.isPending}
>
닫기
</button>
<button
type="button"
className="btn btn-warning btn-sm px-4 text-xs"
onClick={handleConfirmReplaceTournamentCode}
disabled={
replaceCodeConfirmText.trim() !== "예" ||
replaceTournamentCodeMutation.isPending
}
>
{replaceTournamentCodeMutation.isPending
? "교체 중..."
: "코드 교체 진행"}
</button>
</div>
</div>
</div>
)}
</main>
);
}