From 6a192276e8f28f1df27e0ef0bbcd8658c985a4d1 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 7 Jun 2026 06:51:35 -0700 Subject: [PATCH] feat(admin): manage match participants --- .../src/modules/match/dto/create-match.dto.ts | 8 + .../api/src/modules/match/match.controller.ts | 44 +++ apps/api/src/modules/match/match.service.ts | 95 ++++++ apps/web/src/pages/MatchDetailPage.tsx | 291 +++++++++++++++++- 4 files changed, 437 insertions(+), 1 deletion(-) 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 a2757c73..7fe6ee55 100644 --- a/apps/api/src/modules/match/dto/create-match.dto.ts +++ b/apps/api/src/modules/match/dto/create-match.dto.ts @@ -173,6 +173,14 @@ export class UpdateMatchDto { schedule?: MatchScheduleItemDto[]; } +export class UpdateParticipantDto { + @IsEnum(POSITIONS) + mainPosition!: Position; + + @IsEnum(POSITIONS) + subPosition!: Position; +} + export class JoinMatchDto { @IsArray() @ArrayMinSize(1) diff --git a/apps/api/src/modules/match/match.controller.ts b/apps/api/src/modules/match/match.controller.ts index c581dbdc..74b448a2 100644 --- a/apps/api/src/modules/match/match.controller.ts +++ b/apps/api/src/modules/match/match.controller.ts @@ -27,6 +27,7 @@ import { CreateMatchDto, JoinMatchDto, UpdateMatchDto, + UpdateParticipantDto, } from './dto/create-match.dto'; import { MatchService } from './match.service'; @@ -137,6 +138,49 @@ export class MatchController { }); } + // 관리자 전용 — 참가자 주/부 포지션 변경. + @Patch(':matchId/participants/:userId') + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + public async updateParticipant( + @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: UpdateParticipantDto, + ) { + this.assertSameCommunity(currentUser, communityId); + const match = await this.matchService.updateParticipantPositions({ + matchId, + communityId, + targetUserId: userId, + mainPosition: body.mainPosition, + subPosition: body.subPosition, + }); + return this.matchService.serialize(match); + } + + // 관리자 전용 — 참가자 강제 제외. + @Delete(':matchId/participants/:userId') + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + @HttpCode(HttpStatus.NO_CONTENT) + public async removeParticipant( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + await this.matchService.removeParticipant({ + matchId, + communityId, + targetUserId: userId, + }); + } + private resolveJoinerUserId( currentUser: UserDocument | undefined, bodyUserId?: string, diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index 1bf6b3b6..d1a1f184 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, + Position, PositionPreference, TierInfo, } from '../global/database/schema'; @@ -54,6 +55,20 @@ interface CancelMatchJoinParams { userId: mongoose.Types.ObjectId; } +interface RemoveParticipantParams { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + targetUserId: mongoose.Types.ObjectId; +} + +interface UpdateParticipantPositionsParams { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + targetUserId: mongoose.Types.ObjectId; + mainPosition: Position; + subPosition: Position; +} + @Injectable() export class MatchService { constructor( @@ -276,6 +291,86 @@ export class MatchService { return match; } + // 관리자 전용 — 특정 참가자를 강제로 제외한다. + public async removeParticipant( + params: RemoveParticipantParams, + ): Promise { + const match = await this.loadRecruitingMatch( + params.matchId, + params.communityId, + ); + const participantIndex = match.participants.findIndex((participant) => + participant.userId.equals(params.targetUserId), + ); + if (participantIndex === -1) { + throw new NotFoundException('Participant not found.'); + } + match.participants.splice(participantIndex, 1); + await match.save(); + return match; + } + + // 관리자 전용 — 참가자의 주/부 포지션(선호 우선순위 1·2)을 교체한다. + public async updateParticipantPositions( + params: UpdateParticipantPositionsParams, + ): Promise { + const match = await this.loadRecruitingMatch( + params.matchId, + params.communityId, + ); + const participant = match.participants.find((entry) => + entry.userId.equals(params.targetUserId), + ); + if (!participant) { + throw new NotFoundException('Participant not found.'); + } + participant.preferredPositions = this.reorderPreferredPositions( + params.mainPosition, + params.subPosition, + participant.preferredPositions, + ); + match.markModified('participants'); + await match.save(); + return match; + } + + private async loadRecruitingMatch( + matchId: mongoose.Types.ObjectId, + communityId: mongoose.Types.ObjectId, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findById(matchId); + if (!match) throw new NotFoundException('Match not found.'); + if (!match.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + if (match.status !== 'recruiting') { + throw new BadRequestException('Match is not recruiting.'); + } + return match; + } + + // 주/부 포지션을 priority 1·2로 올리고 기존 나머지 선호는 뒤로 보존한다. + private reorderPreferredPositions( + mainPosition: Position, + subPosition: Position, + current: PositionPreference[], + ): PositionPreference[] { + const ordered: Position[] = [mainPosition]; + if (subPosition !== mainPosition) ordered.push(subPosition); + for (const preference of [...current].sort( + (left, right) => left.priority - right.priority, + )) { + if (!ordered.includes(preference.position)) { + ordered.push(preference.position); + } + } + return ordered.map((position, index) => ({ + position, + priority: index + 1, + })); + } + private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined { const tier = tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0]; diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index 9d76a0c2..e5caf73f 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -33,7 +33,9 @@ import { } from "../lib/league"; import type { AuctionTopTierThreshold, + ApiMatch, ApiMatchParticipant, + ApiPositionPreference, ApiTierInfo, ManualTournamentResultCollectResponse, Position, @@ -90,6 +92,25 @@ function captainSlotKey(slot: CaptainSelectionSlot) { return String(slot.teamIndex); } +// 백엔드 reorderPreferredPositions와 동일 규칙. 낙관적 업데이트에서 +// 캐시된 preferredPositions를 즉시 갱신하는 데 사용한다. +function reorderPreferredPositions( + mainPosition: Position, + subPosition: Position, + current: ApiPositionPreference[], +): ApiPositionPreference[] { + const ordered: Position[] = [mainPosition]; + if (subPosition !== mainPosition) ordered.push(subPosition); + for (const preference of [...current].sort( + (left, right) => left.priority - right.priority, + )) { + if (!ordered.includes(preference.position)) { + ordered.push(preference.position); + } + } + return ordered.map((position, index) => ({ position, priority: index + 1 })); +} + function parseInitialPointsInput(value: string) { if (!value.trim()) return null; const points = Number(value); @@ -316,18 +337,81 @@ function tierRank(tier: string) { return index === -1 ? PARTICIPANT_TIER_FILTERS.length : index; } +type ParticipantRowAdmin = { + onRemove: (userId: string) => void; + onChangePositions: ( + userId: string, + mainPosition: Position, + subPosition: Position, + ) => void; + isRemoving: boolean; + isUpdating: boolean; +}; + +function PositionSelect({ + value, + sub, + disabled, + onChange, +}: { + value: Position; + sub?: boolean; + disabled?: boolean; + onChange: (next: Position) => void; +}) { + return ( + + ); +} + function ParticipantRow({ participant, index, assignedPos, + admin, }: { participant: ParticipantView; index: number; assignedPos?: Position; + admin?: ParticipantRowAdmin; }) { const { data: ddragon } = useDdragonManifest(); const location = useLocation(); const historyBackTo = `${location.pathname}${location.search}${location.hash}`; + const [confirmingRemove, setConfirmingRemove] = useState(false); + + // 주/부 포지션이 겹치면 두 값을 맞바꿔 항상 서로 다르게 유지한다. + const handleMainChange = (next: Position) => { + if (!admin) return; + const sub = + next === participant.subPosition + ? participant.mainPosition + : participant.subPosition; + admin.onChangePositions(participant.userId, next, sub); + }; + const handleSubChange = (next: Position) => { + if (!admin) return; + const main = + next === participant.mainPosition + ? participant.subPosition + : participant.mainPosition; + admin.onChangePositions(participant.userId, main, next); + }; return ( @@ -370,6 +454,68 @@ function ParticipantRow({ + ) : admin ? ( + <> + + + + + + + + {confirmingRemove ? ( + + + + + ) : ( + + )} + + ) : ( <> @@ -391,6 +537,11 @@ function ParticipantTable({ canJoin, onJoin, isJoining, + canManage, + onRemoveParticipant, + onUpdatePositions, + removingUserId, + updatingUserId, }: { participants: ParticipantView[]; maxParticipants: number; @@ -398,6 +549,15 @@ function ParticipantTable({ canJoin: boolean; onJoin: () => void; isJoining: boolean; + canManage: boolean; + onRemoveParticipant: (userId: string) => void; + onUpdatePositions: ( + userId: string, + mainPosition: Position, + subPosition: Position, + ) => void; + removingUserId: string | null; + updatingUserId: string | null; }) { const [positionFilter, setPositionFilter] = useState(ALL_PARTICIPANT_FILTER); @@ -542,6 +702,9 @@ function ParticipantTable({ 현재 티어 주 포지션 부 포지션 + {canManage && ( + 관리 + )} @@ -551,12 +714,22 @@ function ParticipantTable({ key={participant.id} participant={participant} index={index} + admin={ + canManage + ? { + onRemove: onRemoveParticipant, + onChangePositions: onUpdatePositions, + isRemoving: removingUserId === participant.userId, + isUpdating: updatingUserId === participant.userId, + } + : undefined + } /> )) ) : ( 조건에 맞는 참가자가 없습니다. @@ -1241,6 +1414,89 @@ export default function MatchDetailPage() { }, }); + const matchQueryKey = ["match", DEFAULT_COMMUNITY_ID, id ?? null]; + + const removeParticipantMutation = useMutation({ + mutationFn: (userId: string) => + apiFetch( + `/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`, + { method: "DELETE" }, + ), + onMutate: async (userId: string) => { + await queryClient.cancelQueries({ queryKey: matchQueryKey }); + const previous = queryClient.getQueryData(matchQueryKey); + if (previous) { + queryClient.setQueryData(matchQueryKey, { + ...previous, + participants: previous.participants.filter( + (participant) => participant.userId !== userId, + ), + }); + } + return { previous }; + }, + onError: (_error, _userId, context) => { + if (context?.previous) { + queryClient.setQueryData(matchQueryKey, context.previous); + } + }, + onSettled: () => { + void queryClient.invalidateQueries({ queryKey: matchQueryKey }); + void queryClient.invalidateQueries({ + queryKey: ["matches", DEFAULT_COMMUNITY_ID], + }); + }, + }); + + const updateParticipantMutation = useMutation({ + mutationFn: ({ + userId, + mainPosition, + subPosition, + }: { + userId: string; + mainPosition: Position; + subPosition: Position; + }) => + apiFetch( + `/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`, + { + method: "PATCH", + body: JSON.stringify({ mainPosition, subPosition }), + }, + ), + onMutate: async ({ userId, mainPosition, subPosition }) => { + await queryClient.cancelQueries({ queryKey: matchQueryKey }); + const previous = queryClient.getQueryData(matchQueryKey); + if (previous) { + queryClient.setQueryData(matchQueryKey, { + ...previous, + participants: previous.participants.map((participant) => + participant.userId === userId + ? { + ...participant, + preferredPositions: reorderPreferredPositions( + mainPosition, + subPosition, + participant.preferredPositions, + ), + } + : participant, + ), + }); + } + return { previous }; + }, + onError: (_error, _variables, context) => { + if (context?.previous) { + queryClient.setQueryData(matchQueryKey, context.previous); + } + }, + onSettled: () => { + void queryClient.invalidateQueries({ queryKey: matchQueryKey }); + }, + }); + const startAuctionMutation = useMutation({ mutationFn: () => apiFetch(`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/auction`, { @@ -1511,6 +1767,18 @@ export default function MatchDetailPage() { )} + {removeParticipantMutation.error instanceof Error && ( +
+ {removeParticipantMutation.error.message} +
+ )} + + {updateParticipantMutation.error instanceof Error && ( +
+ {updateParticipantMutation.error.message} +
+ )} + {pollTournamentResultMutation.error instanceof Error && (
{pollTournamentResultMutation.error.message} @@ -1542,6 +1810,27 @@ export default function MatchDetailPage() { canJoin={canUseMemberActions} onJoin={() => joinMatchMutation.mutate()} isJoining={joinMatchMutation.isPending} + canManage={canManageAuction} + onRemoveParticipant={(userId) => + removeParticipantMutation.mutate(userId) + } + onUpdatePositions={(userId, mainPosition, subPosition) => + updateParticipantMutation.mutate({ + userId, + mainPosition, + subPosition, + }) + } + removingUserId={ + removeParticipantMutation.isPending + ? (removeParticipantMutation.variables ?? null) + : null + } + updatingUserId={ + updateParticipantMutation.isPending + ? (updateParticipantMutation.variables?.userId ?? null) + : null + } /> {isCheckingPermissions ? (