From 24983aeb092ed1a776e4046076402742e765eda1 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Tue, 16 Jun 2026 06:39:50 -0700 Subject: [PATCH] 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}