From 8aff1be2251c00230c87b30f94858b9a4543bd6b Mon Sep 17 00:00:00 2001 From: dahyeon Date: Tue, 9 Jun 2026 19:13:34 -0700 Subject: [PATCH 001/108] fix: align home page loading states --- apps/web/src/pages/HomePage.tsx | 217 +++++++++++++++++++++++--------- 1 file changed, 156 insertions(+), 61 deletions(-) diff --git a/apps/web/src/pages/HomePage.tsx b/apps/web/src/pages/HomePage.tsx index c59ee301..345a6bcb 100644 --- a/apps/web/src/pages/HomePage.tsx +++ b/apps/web/src/pages/HomePage.tsx @@ -11,15 +11,33 @@ const HISTORY_MATCH_PAGE_SIZE = 10; const EMPTY_SCHEDULE_TEXT = '예정된 매치가 없습니다.'; const HISTORY_TABLE_ROW_CLASS = 'h-10 border-b border-base-content/5 last:border-b-0'; - -function SkeletonBlock({ className }: { className: string }) { - return ( - @@ -181,58 +231,103 @@ function HomePageSkeleton() {
- +

+ 다음 내전 +

- - + + 내전 전적 보기 +
-
+
-
+
- - + + 롤림푸스 경매 테스트 매치 + + + 모집중 +
-
- - +
+ + Socket.IO 경매 페이지 검증용으로 생성된 매치입니다. +
-
- - - +
+ + 6월 11일 21:00 + + | + + 10/10명 + + | + + 소환사의 협곡 +
- +
+ + 상세 보기 + +
- +

+ 예정된 내전 +

{upcomingSkeletons.map((_, index) => ( -
-
- - +
+
+ + 정기 내전 + + + 모집중 +
-
- - +
+ + 6월 11일 21:00 + + + 10/10명 + +
+
+ + 소환사의 협곡 +
-
))}
- +

+ 지난 내전 기록 +

@@ -249,7 +344,7 @@ function StatusBadge({ status }: { status: string }) { return ( {status} @@ -258,7 +353,7 @@ function StatusBadge({ status }: { status: string }) { function MapBadge({ map }: { map: string }) { return ( - + {map} ); @@ -302,7 +397,7 @@ function HistoryMetaText({ result?: string; }) { return ( -
+
{map} · {participants}명 @@ -448,21 +543,21 @@ export default function HomePage() {
-

+

다음 내전

{canManage && ( 내전 관리 )} 내전 전적 보기 @@ -476,18 +571,18 @@ export default function HomePage() {
-

+

{nextMatch.title}

-

+

{nextMatch.description}

-
+
{nextMatch.date} {nextMatch.time} | - + {nextMatch.participants.length}/{nextMatch.maxParticipants}명 | @@ -495,7 +590,7 @@ export default function HomePage() {
- + 상세 보기
@@ -513,21 +608,21 @@ export default function HomePage() {
-

+

예정된 내전

{upcomingCards.length > 0 ? ( upcomingCards.map((match) => ( -
+
-

+

{match.title}

-
+
{match.date} {match.time}
{match.participants.length}/{match.maxParticipants}명 @@ -540,7 +635,7 @@ export default function HomePage() { )) ) : ( -
+
{EMPTY_SCHEDULE_TEXT}
)} @@ -552,7 +647,7 @@ export default function HomePage() { aria-busy={isHistoryPageLoading} aria-live="polite" > -

+

지난 내전 기록

{isHistoryPageLoading ? ( @@ -634,11 +729,11 @@ export default function HomePage() { >
-
+
{match.compactDateTime || `${match.date} ${match.time}`}
-
+
{match.title}
From 24983aeb092ed1a776e4046076402742e765eda1 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Tue, 16 Jun 2026 06:39:50 -0700 Subject: [PATCH 002/108] feat: allow admins to add match participants --- .../src/modules/match/dto/create-match.dto.ts | 14 + .../api/src/modules/match/match.controller.ts | 23 + .../src/modules/match/match.service.spec.ts | 89 ++++ apps/api/src/modules/match/match.service.ts | 30 +- .../modules/user/community-user.controller.ts | 61 +++ .../modules/user/user-search.service.spec.ts | 143 ++++++ .../src/modules/user/user-search.service.ts | 164 ++++++ apps/api/src/modules/user/user.module.ts | 5 +- apps/web/src/api/hooks.ts | 20 + apps/web/src/api/types.ts | 18 + apps/web/src/pages/MatchDetailPage.tsx | 471 +++++++++++++++++- 11 files changed, 1019 insertions(+), 19 deletions(-) create mode 100644 apps/api/src/modules/user/community-user.controller.ts create mode 100644 apps/api/src/modules/user/user-search.service.spec.ts create mode 100644 apps/api/src/modules/user/user-search.service.ts diff --git a/apps/api/src/modules/match/dto/create-match.dto.ts b/apps/api/src/modules/match/dto/create-match.dto.ts index 7fe6ee55..d2dcb85d 100644 --- a/apps/api/src/modules/match/dto/create-match.dto.ts +++ b/apps/api/src/modules/match/dto/create-match.dto.ts @@ -193,3 +193,17 @@ export class JoinMatchDto { @IsString() userId?: string; } + +export class AddParticipantDto { + @IsOptional() + @IsArray() + @ArrayMinSize(1) + @ArrayMaxSize(5) + @ValidateNested({ each: true }) + @Type(() => PositionPreferenceDto) + preferredPositions?: PositionPreferenceDto[]; + + @IsOptional() + @IsString() + riotPuuid?: string; +} diff --git a/apps/api/src/modules/match/match.controller.ts b/apps/api/src/modules/match/match.controller.ts index 81e2a985..1e383b0c 100644 --- a/apps/api/src/modules/match/match.controller.ts +++ b/apps/api/src/modules/match/match.controller.ts @@ -24,6 +24,7 @@ import type { UserDocument, } from '../global/database/schema'; import { + AddParticipantDto, CreateMatchDto, JoinMatchDto, UpdateMatchDto, @@ -149,6 +150,28 @@ export class MatchController { }); } + // 관리자 전용 — 커뮤니티 유저를 모집중 매치에 직접 추가한다. + @Post(':matchId/participants/:userId') + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + public async addParticipant( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + @Body() body: AddParticipantDto | undefined, + ) { + this.assertSameCommunity(currentUser, communityId); + const match = await this.matchService.join({ + matchId, + userId, + preferredPositions: body?.preferredPositions, + riotPuuid: body?.riotPuuid, + }); + return this.matchService.serialize(match); + } + // 관리자 전용 — 참가자 주/부 포지션 변경. @Patch(':matchId/participants/:userId') @Roles('admin', 'owner') diff --git a/apps/api/src/modules/match/match.service.spec.ts b/apps/api/src/modules/match/match.service.spec.ts index 337f8599..31a2e22b 100644 --- a/apps/api/src/modules/match/match.service.spec.ts +++ b/apps/api/src/modules/match/match.service.spec.ts @@ -80,6 +80,47 @@ describe('MatchService', () => { }; } + function createServiceWithJoinModels(params: { + user: Record | null; + match: Record | null; + }) { + const UserModel = { + findById: jest.fn().mockResolvedValue(params.user), + }; + const MatchModel = { + findById: jest.fn().mockResolvedValue(params.match), + }; + const connectionService = { + getModel: jest.fn().mockImplementation(async (name: string) => { + if (name === 'user') return UserModel; + if (name === 'match') return MatchModel; + return {}; + }), + }; + const tournamentCodeService = { + buildSlots: jest.fn().mockResolvedValue([]), + releaseFromMatch: jest.fn().mockResolvedValue(undefined), + }; + const communityStatsService = { + invalidateCommunity: jest.fn().mockResolvedValue(undefined), + }; + const matchStatsService = { + buildAndUpsert: jest.fn().mockResolvedValue(undefined), + removeByMatch: jest.fn().mockResolvedValue(undefined), + }; + + return { + service: new MatchService( + connectionService as never, + tournamentCodeService as never, + communityStatsService as never, + matchStatsService as never, + ), + UserModel, + MatchModel, + }; + } + it('returns a paginated match list with total count', async () => { const communityId = new mongoose.Types.ObjectId(); const { service, MatchModel, sort, skip, limit } = @@ -165,6 +206,54 @@ describe('MatchService', () => { expect(sort).toHaveBeenCalledWith({ scheduledAt: -1 }); }); + it('uses saved user preferences when joining without explicit positions', async () => { + const communityId = new mongoose.Types.ObjectId(); + const userId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const user = { + _id: userId, + communityId, + preferredPositions: [{ position: 'MID', priority: 1 }], + riotAccounts: [ + { + puuid: 'puuid-1', + gameName: 'Dahyeon', + tagLine: 'KR1', + profileIconId: 7, + isPrimary: true, + tiers: [], + }, + ], + }; + const match = { + _id: matchId, + communityId, + status: 'recruiting', + maxParticipants: 10, + participants: [], + save: jest.fn().mockResolvedValue(undefined), + }; + const { service } = createServiceWithJoinModels({ user, match }); + + await service.join({ + matchId, + userId, + }); + + expect(match.participants).toEqual([ + expect.objectContaining({ + userId, + puuid: 'puuid-1', + gameName: 'Dahyeon', + tagLine: 'KR1', + profileIconId: 7, + preferredPositions: [{ position: 'MID', priority: 1 }], + excluded: false, + }), + ]); + expect(match.save).toHaveBeenCalledTimes(1); + }); + it('clears game schedule when a built match returns to recruiting', async () => { const communityId = new mongoose.Types.ObjectId(); const match = { diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index a3db4a51..ca7014c5 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -13,6 +13,7 @@ import { MatchDocument, MatchSeriesResult, MatchStatus, + POSITIONS, Position, PositionPreference, TierInfo, @@ -64,7 +65,7 @@ interface MatchListFilter { interface JoinMatchParams { matchId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId; - preferredPositions: PositionPreference[]; + preferredPositions?: PositionPreference[]; // 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용. riotPuuid?: string; } @@ -293,7 +294,10 @@ export class MatchService { tagLine: selectedRiot?.tagLine, profileIconId: selectedRiot?.profileIconId, tier: selectedTier, - preferredPositions: params.preferredPositions, + preferredPositions: this.resolveJoinPreferredPositions( + params.preferredPositions, + user.preferredPositions, + ), joinedAt: new Date(), excluded: false, }); @@ -436,6 +440,28 @@ export class MatchService { }; } + private resolveJoinPreferredPositions( + requested: PositionPreference[] | undefined, + saved: PositionPreference[] | undefined, + ): PositionPreference[] { + const source = requested?.length + ? requested + : saved?.length + ? saved + : POSITIONS.map((position, index) => ({ + position, + priority: index + 1, + })); + + return [...source] + .sort((left, right) => left.priority - right.priority) + .slice(0, 5) + .map((preference, index) => ({ + position: preference.position, + priority: index + 1, + })); + } + private buildListFilter(query: ListMatchesQuery): MatchListFilter { const filter: MatchListFilter = { communityId: query.communityId, diff --git a/apps/api/src/modules/user/community-user.controller.ts b/apps/api/src/modules/user/community-user.controller.ts new file mode 100644 index 00000000..e078b6d2 --- /dev/null +++ b/apps/api/src/modules/user/community-user.controller.ts @@ -0,0 +1,61 @@ +import { + BadRequestException, + Controller, + Get, + Param, + Query, + UseGuards, +} from '@nestjs/common'; +import { Type } from 'class-transformer'; +import { + IsInt, + IsOptional, + IsString, + Max, + MaxLength, + Min, +} from 'class-validator'; +import mongoose from 'mongoose'; +import { CurrentUser } from '../auth/current-user.decorator'; +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 { UserSearchService } from './user-search.service'; + +class SearchCommunityUsersQueryDto { + @IsString() + @MaxLength(80) + query!: string; + + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + @Max(20) + limit?: number; +} + +@Controller('communities/:communityId/users') +@Roles('admin', 'owner') +@UseGuards(RolesGuard) +export class CommunityUserController { + constructor(private readonly userSearchService: UserSearchService) {} + + @Get('search') + public async searchUsers( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Query() query: SearchCommunityUsersQueryDto, + ) { + if (!currentUser.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + return this.userSearchService.search({ + communityId, + query: query.query, + limit: query.limit, + }); + } +} diff --git a/apps/api/src/modules/user/user-search.service.spec.ts b/apps/api/src/modules/user/user-search.service.spec.ts new file mode 100644 index 00000000..be8b8753 --- /dev/null +++ b/apps/api/src/modules/user/user-search.service.spec.ts @@ -0,0 +1,143 @@ +import mongoose from 'mongoose'; +import { UserSearchService } from './user-search.service'; + +describe('UserSearchService', () => { + function createService(users: Record[] = []) { + const exec = jest.fn().mockResolvedValue(users); + const limit = jest.fn().mockReturnValue({ exec }); + const find = jest.fn().mockReturnValue({ limit }); + const UserModel = { find }; + const connectionService = { + getModel: jest.fn().mockImplementation(async (name: string) => { + if (name === 'user') return UserModel; + return {}; + }), + }; + + return { + service: new UserSearchService(connectionService as never), + UserModel, + limit, + }; + } + + it('returns no results for short queries', async () => { + const communityId = new mongoose.Types.ObjectId(); + const { service, UserModel } = createService(); + + const results = await service.search({ communityId, query: 'a' }); + + expect(results).toEqual([]); + expect(UserModel.find).not.toHaveBeenCalled(); + }); + + it('searches by kakao nickname and Riot ID parts', async () => { + const communityId = new mongoose.Types.ObjectId(); + const { service, UserModel, limit } = createService(); + + await service.search({ communityId, query: 'Hide on bush#KR1', limit: 50 }); + + expect(UserModel.find).toHaveBeenCalledWith({ + communityId, + $or: expect.arrayContaining([ + { kakaoTalkNickname: expect.any(RegExp) }, + { + riotAccounts: { + $elemMatch: { + gameName: expect.any(RegExp), + tagLine: expect.any(RegExp), + }, + }, + }, + ]), + }); + expect(limit).toHaveBeenCalledWith(20); + }); + + it('serializes limited candidate fields', async () => { + const communityId = new mongoose.Types.ObjectId(); + const userId = new mongoose.Types.ObjectId(); + const { service } = createService([ + { + _id: userId, + kakaoTalkNickname: '다혜', + isActivated: true, + preferredPositions: [{ position: 'MID', priority: 1 }], + riotAccounts: [ + { + puuid: 'puuid-1', + gameName: 'Dahyeon', + tagLine: 'KR1', + profileIconId: 7, + isPrimary: true, + tiers: [{ queueType: 'RANKED_SOLO_5x5', tier: 'GOLD' }], + matchIds: ['private-extra-field'], + }, + ], + }, + ]); + + const results = await service.search({ communityId, query: '다혜' }); + + expect(results).toEqual([ + { + userId: userId.toString(), + kakaoTalkNickname: '다혜', + isActivated: true, + preferredPositions: [{ position: 'MID', priority: 1 }], + matchedRiotPuuid: undefined, + riotAccounts: [ + { + puuid: 'puuid-1', + gameName: 'Dahyeon', + tagLine: 'KR1', + profileIconId: 7, + isPrimary: true, + tiers: [{ queueType: 'RANKED_SOLO_5x5', tier: 'GOLD' }], + }, + ], + }, + ]); + }); + + it('returns the matching secondary Riot account as a selection hint', async () => { + const communityId = new mongoose.Types.ObjectId(); + const userId = new mongoose.Types.ObjectId(); + const { service } = createService([ + { + _id: userId, + kakaoTalkNickname: '다혜', + isActivated: true, + preferredPositions: [], + riotAccounts: [ + { + puuid: 'main-puuid', + gameName: 'MainDahyeon', + tagLine: 'KR1', + profileIconId: 7, + isPrimary: true, + tiers: [], + }, + { + puuid: 'smurf-puuid', + gameName: 'PracticeDahyeon', + tagLine: 'KR2', + profileIconId: 8, + isPrimary: false, + tiers: [], + }, + ], + }, + ]); + + const results = await service.search({ + communityId, + query: 'Practice#KR2', + }); + + expect(results[0]).toMatchObject({ + userId: userId.toString(), + matchedRiotPuuid: 'smurf-puuid', + }); + }); +}); diff --git a/apps/api/src/modules/user/user-search.service.ts b/apps/api/src/modules/user/user-search.service.ts new file mode 100644 index 00000000..0b927f67 --- /dev/null +++ b/apps/api/src/modules/user/user-search.service.ts @@ -0,0 +1,164 @@ +import { Injectable } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + PositionPreference, + RiotAccount, + TierInfo, + UserDocument, +} from '../global/database/schema'; + +const DEFAULT_SEARCH_LIMIT = 10; +const MAX_SEARCH_LIMIT = 20; +const MIN_QUERY_LENGTH = 2; + +export interface UserSearchRiotAccountResult { + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + isPrimary: boolean; + tiers: TierInfo[]; +} + +export interface UserSearchResult { + userId: string; + kakaoTalkNickname?: string; + isActivated: boolean; + preferredPositions: PositionPreference[]; + matchedRiotPuuid?: string; + riotAccounts: UserSearchRiotAccountResult[]; +} + +export interface SearchCommunityUsersParams { + communityId: mongoose.Types.ObjectId; + query: string; + limit?: number; +} + +@Injectable() +export class UserSearchService { + constructor(private readonly connectionService: ConnectionService) {} + + public async search( + params: SearchCommunityUsersParams, + ): Promise { + const query = params.query.trim(); + if (query.length < MIN_QUERY_LENGTH) return []; + + const UserModel = await this.connectionService.getModel('user'); + const users = await UserModel.find( + this.buildFilter(params.communityId, query), + ) + .limit(this.resolveLimit(params.limit)) + .exec(); + + return users.map((user) => this.serializeUser(user, query)); + } + + private buildFilter(communityId: mongoose.Types.ObjectId, query: string) { + const [gameName, tagLine] = this.splitRiotId(query); + const generalRegex = this.toContainsRegex(query); + const filters: Record[] = [ + { kakaoTalkNickname: generalRegex }, + { 'riotAccounts.gameName': generalRegex }, + { 'riotAccounts.tagLine': generalRegex }, + ]; + + if (gameName && tagLine) { + filters.push({ + riotAccounts: { + $elemMatch: { + gameName: this.toContainsRegex(gameName), + tagLine: this.toContainsRegex(tagLine), + }, + }, + }); + } + + return { communityId, $or: filters }; + } + + private splitRiotId(query: string): [string | null, string | null] { + const hashIndex = query.lastIndexOf('#'); + if (hashIndex <= 0 || hashIndex === query.length - 1) { + return [null, null]; + } + return [ + query.slice(0, hashIndex).trim(), + query.slice(hashIndex + 1).trim(), + ]; + } + + private toContainsRegex(value: string): RegExp { + return new RegExp(escapeRegex(value.trim()), 'i'); + } + + private resolveLimit(limit: number | undefined): number { + if (typeof limit !== 'number' || !Number.isFinite(limit)) { + return DEFAULT_SEARCH_LIMIT; + } + return Math.min(MAX_SEARCH_LIMIT, Math.max(1, Math.trunc(limit))); + } + + private serializeUser(user: UserDocument, query: string): UserSearchResult { + return { + userId: user._id.toString(), + kakaoTalkNickname: user.kakaoTalkNickname, + isActivated: user.isActivated, + preferredPositions: user.preferredPositions ?? [], + matchedRiotPuuid: this.findMatchingRiotAccount( + user.riotAccounts ?? [], + query, + )?.puuid, + riotAccounts: (user.riotAccounts ?? []).map((account) => + this.serializeRiotAccount(account), + ), + }; + } + + private serializeRiotAccount( + account: RiotAccount, + ): UserSearchRiotAccountResult { + return { + puuid: account.puuid, + gameName: account.gameName, + tagLine: account.tagLine, + profileIconId: account.profileIconId, + isPrimary: account.isPrimary, + tiers: account.tiers ?? [], + }; + } + + private findMatchingRiotAccount( + accounts: RiotAccount[], + query: string, + ): RiotAccount | undefined { + const [gameName, tagLine] = this.splitRiotId(query); + if (gameName && tagLine) { + return accounts.find( + (account) => + includesNormalized(account.gameName, gameName) && + includesNormalized(account.tagLine, tagLine), + ); + } + + return accounts.find( + (account) => + includesNormalized(account.gameName, query) || + includesNormalized(account.tagLine, query), + ); + } +} + +function escapeRegex(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function includesNormalized(value: string | undefined, query: string): boolean { + return normalizeForSearch(value).includes(normalizeForSearch(query)); +} + +function normalizeForSearch(value: string | undefined): string { + return (value ?? '').trim().toLowerCase(); +} diff --git a/apps/api/src/modules/user/user.module.ts b/apps/api/src/modules/user/user.module.ts index 66ca9ce0..5b559c3b 100644 --- a/apps/api/src/modules/user/user.module.ts +++ b/apps/api/src/modules/user/user.module.ts @@ -1,9 +1,12 @@ import { Module } from '@nestjs/common'; import { RiotModule } from '../riot/riot.module'; +import { CommunityUserController } from './community-user.controller'; import { UserController } from './user.controller'; +import { UserSearchService } from './user-search.service'; @Module({ imports: [RiotModule], - controllers: [UserController], + controllers: [UserController, CommunityUserController], + providers: [UserSearchService], }) export class UserModule {} diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index 6857fd41..35f35a56 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -13,6 +13,7 @@ import type { ApiAuctionHistoryEntry, ApiChampionStatsResponse, ApiCommunity, + ApiCommunityUserSearchCandidate, ApiEnqueueRefreshResult, ApiInternalMatchDetailResponse, ApiInternalMatchListResponse, @@ -162,6 +163,25 @@ export function useMatch(matchId: string | undefined, communityId = DEFAULT_COMM }); } +export function useCommunityUserSearch( + query: string, + communityId = DEFAULT_COMMUNITY_ID, + enabled = true, +) { + return useQuery({ + queryKey: ['community-user-search', communityId, query], + queryFn: () => { + const searchParams = new URLSearchParams(); + searchParams.set('query', query); + searchParams.set('limit', '10'); + return apiFetch( + `/communities/${communityId}/users/search?${searchParams.toString()}`, + ); + }, + enabled: Boolean(communityId && enabled && query.trim().length >= 2), + }); +} + export function useAuction( matchId: string | undefined, communityId = DEFAULT_COMMUNITY_ID, diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index d65f0211..5f6d1597 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -103,6 +103,24 @@ export interface ApiUser { updatedAt: string; } +export interface ApiCommunityUserSearchRiotAccount { + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + isPrimary: boolean; + tiers: ApiTierInfo[]; +} + +export interface ApiCommunityUserSearchCandidate { + userId: string; + kakaoTalkNickname?: string; + isActivated: boolean; + preferredPositions: ApiPositionPreference[]; + matchedRiotPuuid?: string; + riotAccounts: ApiCommunityUserSearchRiotAccount[]; +} + export interface ApiCommunity { _id: string; name: string; diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index cdd00b8b..3e9829cd 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -1,10 +1,12 @@ import { useEffect, useState } from "react"; import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { Search, X } from "lucide-react"; import { Link, useLocation, useNavigate, useParams } from "react-router"; import { useAuction, useCollectTournamentResultByRiotMatch, useCollectTournamentResultByWindow, + useCommunityUserSearch, useDdragonManifest, useMatch, useMe, @@ -32,6 +34,8 @@ import { } from "../lib/league"; import type { AuctionTopTierThreshold, + ApiCommunityUserSearchCandidate, + ApiCommunityUserSearchRiotAccount, ApiMatch, ApiMatchParticipant, ApiPositionPreference, @@ -155,6 +159,62 @@ function buildCaptainSlots( })); } +function getDefaultSearchAccount(candidate: ApiCommunityUserSearchCandidate) { + return ( + candidate.riotAccounts.find( + (account) => account.puuid === candidate.matchedRiotPuuid, + ) ?? + candidate.riotAccounts.find((account) => account.isPrimary) ?? + candidate.riotAccounts[0] + ); +} + +function getSelectedSearchAccount( + candidate: ApiCommunityUserSearchCandidate, + selectedPuuid: string | undefined, +) { + return ( + candidate.riotAccounts.find((account) => account.puuid === selectedPuuid) ?? + getDefaultSearchAccount(candidate) + ); +} + +function getCandidateTier(account?: ApiCommunityUserSearchRiotAccount) { + return ( + account?.tiers.find((tier) => tier.queueType === "RANKED_SOLO_5x5") ?? + account?.tiers[0] + ); +} + +function resolveCandidateMainSub( + candidate: ApiCommunityUserSearchCandidate, +): [Position, Position] { + const ordered = [...candidate.preferredPositions].sort( + (left, right) => left.priority - right.priority, + ); + const main = ordered[0]?.position ?? POSITION_ORDER[0]; + const sub = + ordered.find((preference) => preference.position !== main)?.position ?? + POSITION_ORDER.find((position) => position !== main) ?? + POSITION_ORDER[1]; + return [main, sub]; +} + +function buildPreferredPositionsFromMainSub( + mainPosition: Position, + subPosition: Position, +) { + const ordered: Position[] = [mainPosition]; + if (subPosition !== mainPosition) ordered.push(subPosition); + for (const position of POSITION_ORDER) { + if (!ordered.includes(position)) ordered.push(position); + } + return ordered.map((position, index) => ({ + position, + priority: index + 1, + })); +} + function tierByQueue(tiers: ApiTierInfo[], queueType: string) { return tiers.find((tier) => tier.queueType === queueType); } @@ -168,9 +228,7 @@ function QueueRankCell({ }) { return ( - - {label} - + {label} ); @@ -617,6 +675,327 @@ function ParticipantMobileRow({ ); } +function AdminAddParticipantModal({ + open, + participants, + maxParticipants, + onClose, + onAddParticipant, + addingUserId, + error, +}: { + open: boolean; + participants: ParticipantView[]; + maxParticipants: number; + onClose: () => void; + onAddParticipant: (params: { + userId: string; + riotPuuid?: string; + preferredPositions: ApiPositionPreference[]; + }) => void; + addingUserId: string | null; + error?: Error | null; +}) { + const { data: ddragon } = useDdragonManifest(); + const [searchText, setSearchText] = useState(""); + const [debouncedSearchText, setDebouncedSearchText] = useState(""); + const [selectedRiotPuuidByUserId, setSelectedRiotPuuidByUserId] = useState< + Record + >({}); + const [positionOverrides, setPositionOverrides] = useState< + Record + >({}); + const participantUserIds = new Set( + participants.map((participant) => participant.userId), + ); + const isFull = participants.length >= maxParticipants; + + useEffect(() => { + const timer = window.setTimeout(() => { + setDebouncedSearchText(searchText.trim()); + }, 250); + return () => window.clearTimeout(timer); + }, [searchText]); + + useEffect(() => { + if (!open) { + setSearchText(""); + setDebouncedSearchText(""); + setSelectedRiotPuuidByUserId({}); + setPositionOverrides({}); + } + }, [open]); + + useEffect(() => { + setSelectedRiotPuuidByUserId({}); + }, [debouncedSearchText]); + + const searchQuery = useCommunityUserSearch( + debouncedSearchText, + DEFAULT_COMMUNITY_ID, + open && debouncedSearchText.length >= 2, + ); + + if (!open) return null; + + function positionsFor(candidate: ApiCommunityUserSearchCandidate) { + const override = positionOverrides[candidate.userId]; + if (override) return override; + const [mainPosition, subPosition] = resolveCandidateMainSub(candidate); + return { mainPosition, subPosition }; + } + + function setCandidatePosition( + candidate: ApiCommunityUserSearchCandidate, + key: "mainPosition" | "subPosition", + position: Position, + ) { + const current = positionsFor(candidate); + setPositionOverrides((previous) => ({ + ...previous, + [candidate.userId]: { + ...current, + [key]: position, + }, + })); + } + + return ( +
+
+
+
+

+ 참여자 추가 +

+

+ 카카오 닉네임 또는 Riot ID로 커뮤니티 유저를 찾습니다. +

+
+ +
+ +
+ + + {error && ( +
+ {error.message} +
+ )} + +
+ {debouncedSearchText.length < 2 ? ( +
+ 두 글자 이상 입력하면 검색합니다. +
+ ) : searchQuery.isLoading ? ( +
+ 검색 중... +
+ ) : searchQuery.error instanceof Error ? ( +
+ {searchQuery.error.message} +
+ ) : searchQuery.data && searchQuery.data.length > 0 ? ( +
+ {searchQuery.data.map((candidate) => { + const selectedRiotPuuid = + selectedRiotPuuidByUserId[candidate.userId]; + const account = getSelectedSearchAccount( + candidate, + selectedRiotPuuid, + ); + const tier = getCandidateTier(account); + const positions = positionsFor(candidate); + const disabledReason = participantUserIds.has( + candidate.userId, + ) + ? "이미 참가중" + : !candidate.isActivated + ? "비활성" + : !account + ? "Riot 계정 없음" + : isFull + ? "정원 초과" + : null; + const isAdding = addingUserId === candidate.userId; + + return ( +
+
+ +
+
+ + {candidate.kakaoTalkNickname ?? "닉네임 없음"} + + + {disabledReason ?? "추가 가능"} + +
+
+ {candidate.riotAccounts.length > 1 ? ( + + ) : ( + + {account + ? `${account.gameName}#${account.tagLine}` + : "Riot 계정 없음"} + + )} + +
+
+
+ +
+ + +
+ + +
+ ); + })} +
+ ) : ( +
+ 검색 결과가 없습니다. +
+ )} +
+
+
+
+ ); +} + function ParticipantTable({ participants, maxParticipants, @@ -625,6 +1004,7 @@ function ParticipantTable({ onJoin, isJoining, canManage, + onOpenAddParticipant, onRemoveParticipant, onUpdatePositions, removingUserId, @@ -637,6 +1017,7 @@ function ParticipantTable({ onJoin: () => void; isJoining: boolean; canManage: boolean; + onOpenAddParticipant: () => void; onRemoveParticipant: (userId: string) => void; onUpdatePositions: ( userId: string, @@ -697,18 +1078,30 @@ function ParticipantTable({ return (
-
+

참가자 ({participants.length}/{maxParticipants})

- +
+ + {canManage && ( + + )} +
@@ -1547,6 +1940,7 @@ export default function MatchDetailPage() { const [manualResultStartTime, setManualResultStartTime] = useState(""); const [manualResultEndTime, setManualResultEndTime] = useState(""); const [manualRiotMatchId, setManualRiotMatchId] = useState(""); + const [addParticipantOpen, setAddParticipantOpen] = useState(false); const pollTournamentResultMutation = usePollTournamentResult(DEFAULT_COMMUNITY_ID); const collectResultByWindowMutation = @@ -1581,6 +1975,33 @@ export default function MatchDetailPage() { const matchQueryKey = ["match", DEFAULT_COMMUNITY_ID, id ?? null]; + const addParticipantMutation = useMutation({ + mutationFn: ({ + userId, + preferredPositions, + riotPuuid, + }: { + userId: string; + preferredPositions: ApiPositionPreference[]; + riotPuuid?: string; + }) => + apiFetch( + `/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`, + { + method: "POST", + body: JSON.stringify({ preferredPositions, riotPuuid }), + }, + ), + onSuccess: async () => { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: matchQueryKey }), + queryClient.invalidateQueries({ + queryKey: ["matches", DEFAULT_COMMUNITY_ID], + }), + ]); + }, + }); + const removeParticipantMutation = useMutation({ mutationFn: (userId: string) => apiFetch( @@ -1976,6 +2397,7 @@ export default function MatchDetailPage() { onJoin={() => joinMatchMutation.mutate()} isJoining={joinMatchMutation.isPending} canManage={canManageAuction} + onOpenAddParticipant={() => setAddParticipantOpen(true)} onRemoveParticipant={(userId) => removeParticipantMutation.mutate(userId) } @@ -1998,6 +2420,26 @@ export default function MatchDetailPage() { } /> + setAddParticipantOpen(false)} + onAddParticipant={(params) => + addParticipantMutation.mutate(params) + } + addingUserId={ + addParticipantMutation.isPending + ? (addParticipantMutation.variables?.userId ?? null) + : null + } + error={ + addParticipantMutation.error instanceof Error + ? addParticipantMutation.error + : null + } + /> + {isCheckingPermissions ? (

@@ -2335,10 +2777,7 @@ export default function MatchDetailPage() {
    {match.schedule.map((item, index) => ( -
  • +
  • {item.time} From 658592973eeb732f36f22f41d63ac3ab94a7f26e Mon Sep 17 00:00:00 2001 From: dahyeon Date: Fri, 19 Jun 2026 01:13:50 -0700 Subject: [PATCH 003/108] feat: add limited round-robin scheduling --- .../api/src/modules/global/database/schema.ts | 4 + .../src/modules/match/dto/create-match.dto.ts | 10 +++ .../api/src/modules/match/match.controller.ts | 1 + .../src/modules/match/match.service.spec.ts | 23 ++++++ apps/api/src/modules/match/match.service.ts | 6 +- .../tournament-code/round-robin.util.spec.ts | 25 ++++++ .../tournament-code/round-robin.util.ts | 76 +++++++++++++++++++ .../tournament-code.service.spec.ts | 50 +++++++++++- .../tournament-code.service.ts | 71 ++++++++++------- .../tournament-code/tournament-code.types.ts | 1 + .../tournament-result.service.spec.ts | 16 ++++ .../tournament-result.service.ts | 34 ++++++--- apps/web/src/api/types.ts | 4 + apps/web/src/pages/MatchDetailPage.tsx | 75 +++++++++++++----- apps/web/src/pages/admin/MatchAdminPage.tsx | 70 ++++++++++++++++- 15 files changed, 403 insertions(+), 63 deletions(-) diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index e7a0807b..d8826947 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -487,6 +487,7 @@ export interface MatchSeriesResult { export interface MatchGameAssignment { gameNumber: number; + roundNumber?: number; teamAIndex: number; teamBIndex: number; } @@ -524,6 +525,7 @@ export interface Match extends MongooseTimestamps { maxParticipants: number; gameCount: number; gameMode: MatchGameMode; + roundRobinMaxRounds?: number; tournamentCodeIds: mongoose.Types.ObjectId[]; gameSchedule: MatchGameAssignment[]; teamBuiltAt?: Date; @@ -1284,6 +1286,7 @@ const MatchSeriesResultSubSchema = new Schema( const MatchGameAssignmentSubSchema = new Schema( { gameNumber: { type: Number, required: true, min: 1 }, + roundNumber: { type: Number, required: false, min: 1 }, teamAIndex: { type: Number, required: true, min: 1 }, teamBIndex: { type: Number, required: true, min: 1 }, }, @@ -1389,6 +1392,7 @@ export const MatchSchema = new Schema( required: true, default: 'pair', }, + roundRobinMaxRounds: { type: Number, required: false, min: 1 }, tournamentCodeIds: { type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }], required: true, diff --git a/apps/api/src/modules/match/dto/create-match.dto.ts b/apps/api/src/modules/match/dto/create-match.dto.ts index d2dcb85d..605c70b4 100644 --- a/apps/api/src/modules/match/dto/create-match.dto.ts +++ b/apps/api/src/modules/match/dto/create-match.dto.ts @@ -101,6 +101,11 @@ export class CreateMatchDto { @IsEnum(MATCH_GAME_MODES) gameMode?: MatchGameMode; + @IsOptional() + @IsInt() + @Min(1) + roundRobinMaxRounds?: number; + @IsOptional() @IsArray() @IsString({ each: true }) @@ -156,6 +161,11 @@ export class UpdateMatchDto { @IsEnum(MATCH_GAME_MODES) gameMode?: MatchGameMode; + @IsOptional() + @IsInt() + @Min(1) + roundRobinMaxRounds?: number; + @IsOptional() @IsArray() @IsString({ each: true }) diff --git a/apps/api/src/modules/match/match.controller.ts b/apps/api/src/modules/match/match.controller.ts index 1e383b0c..8895d43b 100644 --- a/apps/api/src/modules/match/match.controller.ts +++ b/apps/api/src/modules/match/match.controller.ts @@ -57,6 +57,7 @@ export class MatchController { maxParticipants: body.maxParticipants ?? 10, gameCount: body.gameCount, gameMode: body.gameMode ?? 'pair', + roundRobinMaxRounds: body.roundRobinMaxRounds, prizes: body.prizes ?? [], notices: body.notices ?? [], schedule: body.schedule ?? [], diff --git a/apps/api/src/modules/match/match.service.spec.ts b/apps/api/src/modules/match/match.service.spec.ts index 31a2e22b..7557318f 100644 --- a/apps/api/src/modules/match/match.service.spec.ts +++ b/apps/api/src/modules/match/match.service.spec.ts @@ -292,6 +292,29 @@ describe('MatchService', () => { expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id); }); + it('rejects round-robin max round changes after recruiting', async () => { + const communityId = new mongoose.Types.ObjectId(); + const match = { + communityId, + status: 'team-built', + tournamentCodeIds: [], + set: jest.fn(), + save: jest.fn().mockResolvedValue(undefined), + }; + const { service } = createService(match); + + await expect( + service.update({ + matchId: new mongoose.Types.ObjectId(), + communityId, + patch: { roundRobinMaxRounds: 3 }, + }), + ).rejects.toThrow( + 'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.', + ); + expect(match.set).not.toHaveBeenCalled(); + }); + it('releases reserved codes when returning a built match to recruiting', async () => { const communityId = new mongoose.Types.ObjectId(); const codeId = new mongoose.Types.ObjectId(); diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index ca7014c5..b700ab13 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -214,10 +214,12 @@ export class MatchService { const previousStatus = match.status; if ( previousStatus !== 'recruiting' && - ('maxParticipants' in params.patch || 'gameMode' in params.patch) + ('maxParticipants' in params.patch || + 'gameMode' in params.patch || + 'roundRobinMaxRounds' in params.patch) ) { throw new BadRequestException( - 'maxParticipants and gameMode can only be changed while recruiting.', + 'maxParticipants, gameMode, and roundRobinMaxRounds can only be changed while recruiting.', ); } match.set(params.patch); diff --git a/apps/api/src/modules/tournament-code/round-robin.util.spec.ts b/apps/api/src/modules/tournament-code/round-robin.util.spec.ts index 77691089..50705065 100644 --- a/apps/api/src/modules/tournament-code/round-robin.util.spec.ts +++ b/apps/api/src/modules/tournament-code/round-robin.util.spec.ts @@ -1,5 +1,6 @@ import { resolveRoundRobinTeamCount, + roundRobinGameSchedule, roundRobinPairCount, roundRobinPairs, shuffleInPlace, @@ -25,6 +26,30 @@ describe('round-robin util', () => { expect(roundRobinPairCount(6)).toBe(15); }); + it('builds round-robin games grouped into simultaneously playable rounds', () => { + const schedule = roundRobinGameSchedule(6, { gamesPerPair: 1 }); + + expect(schedule).toHaveLength(15); + for (const roundNumber of [1, 2, 3, 4, 5]) { + const round = schedule.filter((game) => game.roundNumber === roundNumber); + expect(round).toHaveLength(3); + expect(new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex]))) + .toHaveProperty('size', 6); + } + }); + + it('limits round-robin games by max rounds', () => { + const schedule = roundRobinGameSchedule(8, { + gamesPerPair: 1, + maxRounds: 3, + }); + + expect(schedule).toHaveLength(12); + expect(new Set(schedule.map((game) => game.roundNumber))).toEqual( + new Set([1, 2, 3]), + ); + }); + it('resolves team count from teams first, then active participants', () => { expect( resolveRoundRobinTeamCount({ diff --git a/apps/api/src/modules/tournament-code/round-robin.util.ts b/apps/api/src/modules/tournament-code/round-robin.util.ts index 4d928f50..3068fd7a 100644 --- a/apps/api/src/modules/tournament-code/round-robin.util.ts +++ b/apps/api/src/modules/tournament-code/round-robin.util.ts @@ -3,11 +3,23 @@ export interface RoundRobinPair { teamBIndex: number; } +export interface RoundRobinGameAssignment extends RoundRobinPair { + gameNumber: number; + roundNumber: number; +} + export interface RoundRobinTeamCountInput { teams?: Array<{ teamIndex: number }>; participants: Array<{ excluded?: boolean }>; } +export interface RoundRobinGameScheduleOptions { + gamesPerPair?: number; + maxRounds?: number; + rng?: () => number; + shuffleTeams?: boolean; +} + export function roundRobinPairs(teamCount: number): RoundRobinPair[] { const pairs: RoundRobinPair[] = []; for (let teamAIndex = 1; teamAIndex <= teamCount; teamAIndex += 1) { @@ -27,6 +39,70 @@ export function roundRobinPairCount(teamCount: number): number { return (teamCount * (teamCount - 1)) / 2; } +export function roundRobinRoundCount(teamCount: number): number { + if (teamCount < 2) return 0; + return teamCount % 2 === 0 ? teamCount - 1 : teamCount; +} + +export function roundRobinGameSchedule( + teamCount: number, + options: RoundRobinGameScheduleOptions = {}, +): RoundRobinGameAssignment[] { + if (teamCount < 2) return []; + + const rawGamesPerPair = options.gamesPerPair ?? 1; + const gamesPerPair = Number.isFinite(rawGamesPerPair) + ? Math.max(1, Math.floor(rawGamesPerPair)) + : 1; + const fullRoundCount = roundRobinRoundCount(teamCount); + const requestedRoundCount = + typeof options.maxRounds === 'number' && Number.isFinite(options.maxRounds) + ? Math.floor(options.maxRounds) + : fullRoundCount; + const roundLimit = Math.max( + 0, + Math.min(fullRoundCount, requestedRoundCount), + ); + if (roundLimit === 0) return []; + + const bye = 0; + const teams = Array.from({ length: teamCount }, (_, index) => index + 1); + if (options.shuffleTeams) shuffleInPlace(teams, options.rng); + if (teams.length % 2 === 1) teams.push(bye); + + const rotating = [...teams]; + const schedule: RoundRobinGameAssignment[] = []; + let gameNumber = 1; + + for (let roundIndex = 0; roundIndex < roundLimit; roundIndex += 1) { + const roundNumber = roundIndex + 1; + for (let index = 0; index < rotating.length / 2; index += 1) { + const left = rotating[index]; + const right = rotating[rotating.length - 1 - index]; + if (left === bye || right === bye) continue; + + const teamAIndex = Math.min(left, right); + const teamBIndex = Math.max(left, right); + for (let gameIndex = 0; gameIndex < gamesPerPair; gameIndex += 1) { + schedule.push({ + gameNumber, + roundNumber, + teamAIndex, + teamBIndex, + }); + gameNumber += 1; + } + } + + const fixed = rotating[0]; + const tail = rotating.slice(1); + tail.unshift(tail.pop() as number); + rotating.splice(0, rotating.length, fixed, ...tail); + } + + return schedule; +} + export function resolveRoundRobinTeamCount( match: RoundRobinTeamCountInput, ): number { 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 0e2c03e2..8aaf7f73 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 @@ -19,10 +19,12 @@ function createService() { interface MatchOverrides { gameCount?: number; gameMode?: 'pair' | 'bracket' | 'round-robin'; + roundRobinMaxRounds?: number; participants?: Array<{ excluded?: boolean }>; teams?: Array<{ teamIndex: number }>; gameSchedule?: Array<{ gameNumber: number; + roundNumber?: number; teamAIndex: number; teamBIndex: number; }>; @@ -102,6 +104,23 @@ describe('TournamentCodeService round-robin scheduling', () => { ).toBe(15); }); + it('calculates limited round-robin slots from max rounds', () => { + const service = createService(); + + expect( + service.resolveRequiredSlots( + createMatch({ + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: 3, + teams: Array.from({ length: 8 }, (_, index) => ({ + teamIndex: index + 1, + })), + }), + ), + ).toBe(12); + }); + it('uses persisted round-robin game schedule for game refs', () => { const service = createService(); const match = createMatch({ @@ -124,7 +143,7 @@ describe('TournamentCodeService round-robin scheduling', () => { }); }); - it('falls back to lexicographic round-robin pairs before schedule is persisted', () => { + it('falls back to round-based pairs before schedule is persisted', () => { const service = createService(); const match = createMatch({ gameMode: 'round-robin', @@ -137,10 +156,10 @@ describe('TournamentCodeService round-robin scheduling', () => { expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({ teamAIndex: 1, - teamBIndex: 2, + teamBIndex: 4, }); expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({ - teamAIndex: 1, + teamAIndex: 2, teamBIndex: 3, }); }); @@ -173,6 +192,31 @@ describe('TournamentCodeService round-robin scheduling', () => { expect(pair.gameSchedule).toEqual([]); }); + it('creates a limited round-robin schedule grouped by playable rounds', () => { + const service = createService(); + const roundRobin = createMatch({ + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: 3, + teams: Array.from({ length: 8 }, (_, index) => ({ + teamIndex: index + 1, + })), + gameSchedule: [], + }); + + service.ensureGameSchedule(roundRobin); + + expect(roundRobin.gameSchedule).toHaveLength(12); + for (const roundNumber of [1, 2, 3]) { + const round = roundRobin.gameSchedule.filter( + (game) => game.roundNumber === roundNumber, + ); + expect(round).toHaveLength(4); + expect(new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])).size) + .toBe(8); + } + }); + it('does not expose fallback round-robin slots before the schedule is persisted', async () => { const service = createService(); const slots = await service.buildSlots( 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 8801f7df..dec64afb 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.service.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.service.ts @@ -25,10 +25,8 @@ import type { TournamentCodeUploadItem, } from './tournament-code.types'; import { + roundRobinGameSchedule, resolveRoundRobinTeamCount, - roundRobinPairCount, - roundRobinPairs, - shuffleInPlace, } from './round-robin.util'; const DEFAULT_REGION = 'kr'; @@ -368,6 +366,7 @@ export class TournamentCodeService { const seriesRef = this.resolveSeriesRefForGameNumber(match, gameNumber); return { gameNumber, + roundNumber: this.resolveRoundNumberForGameNumber(match, gameNumber), ...seriesRef, code: null, expiresAt: null, @@ -377,6 +376,7 @@ export class TournamentCodeService { } return { gameNumber, + roundNumber: this.resolveRoundNumberForGameNumber(match, gameNumber), ...this.resolveSeriesRefForGameNumber(match, gameNumber), code: code.code, expiresAt: code.expiresAt.toISOString(), @@ -395,8 +395,10 @@ export class TournamentCodeService { const gameMode = match.gameMode ?? 'pair'; if (gameMode === 'round-robin') { - const teamCount = resolveRoundRobinTeamCount(match); - return roundRobinPairCount(teamCount) * gameCount; + if ((match.gameSchedule?.length ?? 0) > 0) { + return match.gameSchedule.length; + } + return this.buildRoundRobinGameSchedule(match).length; } const teamCount = (match.teams ?? []).length; @@ -426,13 +428,18 @@ export class TournamentCodeService { }; } - const teamCount = resolveRoundRobinTeamCount(match); - const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; - const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1); - return roundRobinPairs(teamCount)[pairIndex] ?? { - teamAIndex: 1, - teamBIndex: 2, - }; + const fallback = this.buildRoundRobinGameSchedule(match).find( + (entry) => entry.gameNumber === gameNumber, + ); + return fallback + ? { + teamAIndex: fallback.teamAIndex, + teamBIndex: fallback.teamBIndex, + } + : { + teamAIndex: 1, + teamBIndex: 2, + }; } const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; @@ -450,21 +457,33 @@ export class TournamentCodeService { const teamCount = resolveRoundRobinTeamCount(match); if (teamCount < 2) return; - const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; - const pairs = shuffleInPlace([...roundRobinPairs(teamCount)]); - const schedule: MatchGameAssignment[] = []; + match.gameSchedule = this.buildRoundRobinGameSchedule(match, true); + } - for (let pairIndex = 0; pairIndex < pairs.length; pairIndex += 1) { - const pair = pairs[pairIndex]; - for (let gameIndex = 0; gameIndex < gameCount; gameIndex += 1) { - schedule.push({ - gameNumber: pairIndex * gameCount + gameIndex + 1, - teamAIndex: pair.teamAIndex, - teamBIndex: pair.teamBIndex, - }); - } - } + private resolveRoundNumberForGameNumber( + match: MatchDocument, + gameNumber: number, + ): number | undefined { + if ((match.gameMode ?? 'pair') !== 'round-robin') return undefined; - match.gameSchedule = schedule; + const persisted = match.gameSchedule?.find( + (entry) => entry.gameNumber === gameNumber, + ); + if (persisted?.roundNumber) return persisted.roundNumber; + + return this.buildRoundRobinGameSchedule(match).find( + (entry) => entry.gameNumber === gameNumber, + )?.roundNumber; + } + + private buildRoundRobinGameSchedule( + match: MatchDocument, + shuffleTeams = false, + ): MatchGameAssignment[] { + return roundRobinGameSchedule(resolveRoundRobinTeamCount(match), { + gamesPerPair: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT, + maxRounds: match.roundRobinMaxRounds, + shuffleTeams, + }); } } diff --git a/apps/api/src/modules/tournament-code/tournament-code.types.ts b/apps/api/src/modules/tournament-code/tournament-code.types.ts index 207f5b0c..ceeaed40 100644 --- a/apps/api/src/modules/tournament-code/tournament-code.types.ts +++ b/apps/api/src/modules/tournament-code/tournament-code.types.ts @@ -24,6 +24,7 @@ export interface BulkUploadTournamentCodesResponse { export interface TournamentCodeSlotView { gameNumber: number; + roundNumber?: number; teamAIndex: number; teamBIndex: number; code: string | null; 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 7c181090..04f574f3 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 @@ -24,10 +24,12 @@ function createService() { interface MatchOverrides { gameCount?: number; gameMode?: 'pair' | 'bracket' | 'round-robin'; + roundRobinMaxRounds?: number; participants?: Array<{ excluded?: boolean }>; teams?: Array<{ teamIndex: number }>; gameSchedule?: Array<{ gameNumber: number; + roundNumber?: number; teamAIndex: number; teamBIndex: number; }>; @@ -58,6 +60,20 @@ describe('TournamentResultService round-robin scheduling', () => { expect(service.resolveRequiredGameSlots(match)).toBe(15); }); + it('calculates limited round-robin slots for polling', () => { + const service = createService(); + const match = createMatch({ + gameMode: 'round-robin', + gameCount: 1, + roundRobinMaxRounds: 3, + teams: Array.from({ length: 8 }, (_, index) => ({ + teamIndex: index + 1, + })), + }); + + expect(service.resolveRequiredGameSlots(match)).toBe(12); + }); + it('uses persisted round-robin schedule when mapping a game number', () => { const service = createService(); const match = createMatch({ 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 c6f8bb7a..1ef064bb 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -19,9 +19,8 @@ import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types'; import { RiotMatchService } from '../riot/riot-match.service'; import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types'; import { + roundRobinGameSchedule, resolveRoundRobinTeamCount, - roundRobinPairCount, - roundRobinPairs, } from '../tournament-code/round-robin.util'; import { collectCaptainUserIds, @@ -785,14 +784,18 @@ export class TournamentResultService { }; } - const perSeries = match.gameCount || 1; - const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1); - return ( - roundRobinPairs(resolveRoundRobinTeamCount(match))[pairIndex] ?? { - teamAIndex: 1, - teamBIndex: 2, - } + const fallback = this.buildRoundRobinGameSchedule(match).find( + (entry) => entry.gameNumber === gameNumber, ); + return fallback + ? { + teamAIndex: fallback.teamAIndex, + teamBIndex: fallback.teamBIndex, + } + : { + teamAIndex: 1, + teamBIndex: 2, + }; } const perSeries = match.gameCount || 1; @@ -806,8 +809,10 @@ export class TournamentResultService { private resolveRequiredGameSlots(match: MatchDocument): number { const gameMode = match.gameMode ?? 'pair'; if (gameMode === 'round-robin') { - const teamCount = resolveRoundRobinTeamCount(match); - return roundRobinPairCount(teamCount) * (match.gameCount || 1); + if ((match.gameSchedule?.length ?? 0) > 0) { + return match.gameSchedule.length; + } + return this.buildRoundRobinGameSchedule(match).length; } const activeParticipantCount = match.participants.filter( @@ -819,6 +824,13 @@ export class TournamentResultService { return seriesCount * (match.gameCount || 1); } + private buildRoundRobinGameSchedule(match: MatchDocument) { + return roundRobinGameSchedule(resolveRoundRobinTeamCount(match), { + gamesPerPair: match.gameCount || 1, + maxRounds: match.roundRobinMaxRounds, + }); + } + private resolveMatchWinnerTeamIndex( seriesResults: NonNullable['seriesResults'], ): number | undefined { diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 5f6d1597..68e0ec40 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -142,6 +142,7 @@ export type TournamentCodeSlotState = TournamentCodeState | 'pending'; export interface TournamentCodeSlotView { gameNumber: number; + roundNumber?: number; teamAIndex: number; teamBIndex: number; code: string | null; @@ -219,6 +220,7 @@ export interface ApiMatchScheduleItem { export interface ApiMatchGameAssignment { gameNumber: number; + roundNumber?: number; teamAIndex: number; teamBIndex: number; } @@ -243,6 +245,7 @@ export interface ApiMatch { maxParticipants: number; gameCount: number; gameMode: MatchGameMode; + roundRobinMaxRounds?: number; gameSchedule?: ApiMatchGameAssignment[]; tournamentCodes?: TournamentCodeSlotView[]; hostUserId?: string; @@ -371,6 +374,7 @@ export interface MatchMutationRequest { maxParticipants?: number; gameCount?: number; gameMode?: MatchGameMode; + roundRobinMaxRounds?: number; prizes?: string[]; notices?: string[]; schedule?: ApiMatchScheduleItem[]; diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index 3e9829cd..3e5d6ac9 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -1467,28 +1467,63 @@ function TournamentCodeList({ slots }: { slots: TournamentCodeSlotView[] }) { ); } - return ( -
    - {slots.map((slot) => ( -
    - - {slot.gameNumber}경기 - {(slot.teamAIndex > 1 || slot.teamBIndex > 2) && ( - - {teamIndexLabel(slot.teamAIndex)} vs{" "} - {teamIndexLabel(slot.teamBIndex)} - - )} - - {slot.code ? ( - - ) : ( - - 발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다. + function renderSlot(slot: TournamentCodeSlotView) { + return ( +
    + + {slot.gameNumber}경기 + {(slot.teamAIndex > 1 || slot.teamBIndex > 2) && ( + + {teamIndexLabel(slot.teamAIndex)} vs{" "} + {teamIndexLabel(slot.teamBIndex)} )} -
    - ))} +
    + {slot.code ? ( + + ) : ( + + 발급 대기 중... 운영자가 코드를 채우면 자동으로 붙습니다. + + )} +
    + ); + } + + if (slots.some((slot) => slot.roundNumber)) { + const slotsByRound = slots.reduce< + Map + >((map, slot) => { + const roundNumber = slot.roundNumber ?? 0; + const roundSlots = map.get(roundNumber) ?? []; + roundSlots.push(slot); + map.set(roundNumber, roundSlots); + return map; + }, new Map()); + + return ( +
    + {[...slotsByRound.entries()] + .sort(([left], [right]) => left - right) + .map(([roundNumber, roundSlots]) => ( +
    +
    + {roundNumber}라운드 +
    +
    + {roundSlots + .sort((left, right) => left.gameNumber - right.gameNumber) + .map(renderSlot)} +
    +
    + ))} +
    + ); + } + + return ( +
    + {slots.map(renderSlot)}
    ); } diff --git a/apps/web/src/pages/admin/MatchAdminPage.tsx b/apps/web/src/pages/admin/MatchAdminPage.tsx index 827ff6a4..0e3c6541 100644 --- a/apps/web/src/pages/admin/MatchAdminPage.tsx +++ b/apps/web/src/pages/admin/MatchAdminPage.tsx @@ -35,6 +35,21 @@ const GAME_MODE_LABEL: Record = { 'round-robin': '라운드 로빈', }; +function resolveRoundRobinFullRoundCount(maxParticipants?: number) { + const teamCount = Math.floor(Number(maxParticipants ?? 10) / 5); + if (teamCount < 2) return 0; + return teamCount % 2 === 0 ? teamCount - 1 : teamCount; +} + +function normalizeRoundRobinMaxRounds( + value: number | undefined, + maxParticipants?: number, +) { + if (!value || !Number.isFinite(value)) return undefined; + const fullRoundCount = resolveRoundRobinFullRoundCount(maxParticipants); + return Math.max(1, Math.min(fullRoundCount, Math.floor(value))); +} + function RequiredBadge() { return ( @@ -106,6 +121,7 @@ function makeForm(match?: ApiMatch): MatchMutationRequest & { maxParticipants: match.maxParticipants, gameCount: match.gameCount, gameMode: match.gameMode ?? 'pair', + roundRobinMaxRounds: match.roundRobinMaxRounds, prizes: match.prizes, notices: match.notices, schedule: match.schedule, @@ -138,6 +154,9 @@ export default function MatchAdminPage() { () => [...(matchesQuery.data ?? [])].sort((a, b) => new Date(b.scheduledAt).getTime() - new Date(a.scheduledAt).getTime()), [matchesQuery.data], ); + const roundRobinFullRoundCount = resolveRoundRobinFullRoundCount( + form.maxParticipants, + ); async function invalidate() { await Promise.all([ @@ -169,6 +188,13 @@ export default function MatchAdminPage() { maxParticipants: Number(form.maxParticipants ?? 10), gameCount: Number(form.gameCount ?? 3), gameMode: form.gameMode, + roundRobinMaxRounds: + form.gameMode === 'round-robin' + ? normalizeRoundRobinMaxRounds( + form.roundRobinMaxRounds, + form.maxParticipants, + ) + : undefined, prizes: parseLines(form.prizesText), notices: parseLines(form.noticesText), schedule: parseSchedule(form.scheduleText), @@ -290,7 +316,17 @@ export default function MatchAdminPage() { 정원 + setForm((current) => ({ + ...current, + roundRobinMaxRounds: + event.target.value === '' + ? undefined + : Number(event.target.value), + })) + } + className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-sm" + /> + + 비워두면 전체 {roundRobinFullRoundCount}라운드로 생성됩니다. + + + )}