release/86 #2
No files matched your search
@@ -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;
|
||||
}
|
||||
@@ -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')
|
||||
|
||||
@@ -80,6 +80,47 @@ describe('MatchService', () => {
|
||||
};
|
||||
}
|
||||
|
||||
function createServiceWithJoinModels(params: {
|
||||
user: Record<string, unknown> | null;
|
||||
match: Record<string, unknown> | 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 = {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { UserSearchService } from './user-search.service';
|
||||
|
||||
describe('UserSearchService', () => {
|
||||
function createService(users: Record<string, unknown>[] = []) {
|
||||
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',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<UserSearchResult[]> {
|
||||
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<string, unknown>[] = [
|
||||
{ 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();
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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<ApiCommunityUserSearchCandidate[]>(
|
||||
`/communities/${communityId}/users/search?${searchParams.toString()}`,
|
||||
);
|
||||
},
|
||||
enabled: Boolean(communityId && enabled && query.trim().length >= 2),
|
||||
});
|
||||
}
|
||||
|
||||
export function useAuction(
|
||||
matchId: string | undefined,
|
||||
communityId = DEFAULT_COMMUNITY_ID,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 (
|
||||
<span className="grid grid-cols-[27px_auto] items-center gap-1.5">
|
||||
<span className="text-xs font-medium text-base-content/50">
|
||||
{label}
|
||||
</span>
|
||||
<span className="text-xs font-medium text-base-content/50">{label}</span>
|
||||
<RankBadge tier={tier} size="sm" tooltipPlacement="left" />
|
||||
</span>
|
||||
);
|
||||
@@ -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<string, string>
|
||||
>({});
|
||||
const [positionOverrides, setPositionOverrides] = useState<
|
||||
Record<string, { mainPosition: Position; subPosition: Position }>
|
||||
>({});
|
||||
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 (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-start justify-center bg-black/55 px-3 py-6 sm:items-center"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="admin-add-participant-title"
|
||||
>
|
||||
<div className="w-full max-w-3xl border border-base-content/12 bg-base-100 shadow-xl">
|
||||
<div className="flex items-start justify-between gap-4 border-b border-base-content/10 px-4 py-3">
|
||||
<div>
|
||||
<h3
|
||||
id="admin-add-participant-title"
|
||||
className="text-sm font-black text-base-content"
|
||||
>
|
||||
참여자 추가
|
||||
</h3>
|
||||
<p className="mt-1 text-xs text-base-content/45">
|
||||
카카오 닉네임 또는 Riot ID로 커뮤니티 유저를 찾습니다.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-ghost btn-xs h-8 min-h-8 w-8 p-0"
|
||||
aria-label="참여자 추가 닫기"
|
||||
onClick={onClose}
|
||||
>
|
||||
<X size={15} aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 px-4 py-4">
|
||||
<label className="block">
|
||||
<span className="mb-1.5 block text-xs font-bold text-base-content/45">
|
||||
검색
|
||||
</span>
|
||||
<span className="flex h-10 items-center gap-2 border border-base-content/10 bg-base-200/30 px-3 focus-within:border-primary/40">
|
||||
<Search
|
||||
size={15}
|
||||
className="text-base-content/35"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<input
|
||||
type="search"
|
||||
value={searchText}
|
||||
onChange={(event) => setSearchText(event.target.value)}
|
||||
aria-label="참여자 검색"
|
||||
placeholder="카카오 닉네임 또는 Riot ID (GameName#TagLine)"
|
||||
className="min-w-0 flex-1 bg-transparent text-sm text-base-content outline-none placeholder:text-base-content/25"
|
||||
/>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
{error && (
|
||||
<div className="border border-red-500/20 bg-red-500/10 px-3 py-2 text-xs text-red-500">
|
||||
{error.message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-h-[56vh] overflow-y-auto border border-base-content/10">
|
||||
{debouncedSearchText.length < 2 ? (
|
||||
<div className="px-4 py-8 text-center text-sm text-base-content/35">
|
||||
두 글자 이상 입력하면 검색합니다.
|
||||
</div>
|
||||
) : searchQuery.isLoading ? (
|
||||
<div className="px-4 py-8 text-center text-sm text-base-content/35">
|
||||
검색 중...
|
||||
</div>
|
||||
) : searchQuery.error instanceof Error ? (
|
||||
<div className="px-4 py-8 text-center text-sm text-red-500">
|
||||
{searchQuery.error.message}
|
||||
</div>
|
||||
) : searchQuery.data && searchQuery.data.length > 0 ? (
|
||||
<div className="divide-y divide-base-content/8">
|
||||
{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 (
|
||||
<div
|
||||
key={candidate.userId}
|
||||
className="grid gap-3 px-3 py-3 sm:grid-cols-[minmax(0,1fr)_190px_82px] sm:items-center"
|
||||
>
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<img
|
||||
src={profileIconUrl(
|
||||
ddragon,
|
||||
account?.profileIconId ?? 0,
|
||||
)}
|
||||
alt=""
|
||||
className="h-9 w-9 shrink-0 border border-base-content/10 bg-base-200 object-cover"
|
||||
/>
|
||||
<div className="min-w-0">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<span className="truncate text-sm font-bold text-base-content">
|
||||
{candidate.kakaoTalkNickname ?? "닉네임 없음"}
|
||||
</span>
|
||||
<span
|
||||
className={`shrink-0 border px-1.5 py-0.5 text-[11px] font-bold ${
|
||||
disabledReason
|
||||
? "border-base-content/10 text-base-content/35"
|
||||
: "border-primary/25 bg-primary/5 text-primary"
|
||||
}`}
|
||||
>
|
||||
{disabledReason ?? "추가 가능"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1 flex min-w-0 items-center gap-2 text-xs text-base-content/40">
|
||||
{candidate.riotAccounts.length > 1 ? (
|
||||
<select
|
||||
value={account?.puuid ?? ""}
|
||||
aria-label={`${candidate.kakaoTalkNickname ?? "유저"} Riot ID 선택`}
|
||||
onChange={(event) =>
|
||||
setSelectedRiotPuuidByUserId((previous) => ({
|
||||
...previous,
|
||||
[candidate.userId]: event.target.value,
|
||||
}))
|
||||
}
|
||||
className="h-8 min-w-0 flex-1 border border-base-content/10 bg-base-100 px-2 text-xs text-base-content focus:border-primary/30 focus:outline-none"
|
||||
>
|
||||
{candidate.riotAccounts.map((riotAccount) => (
|
||||
<option
|
||||
key={riotAccount.puuid}
|
||||
value={riotAccount.puuid}
|
||||
>
|
||||
{riotAccount.gameName}#{riotAccount.tagLine}
|
||||
{riotAccount.isPrimary ? " · 대표" : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<span className="truncate">
|
||||
{account
|
||||
? `${account.gameName}#${account.tagLine}`
|
||||
: "Riot 계정 없음"}
|
||||
</span>
|
||||
)}
|
||||
<RankBadge tier={tier} size="sm" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<label className="text-[11px] font-bold text-base-content/35">
|
||||
주
|
||||
<select
|
||||
value={positions.mainPosition}
|
||||
onChange={(event) =>
|
||||
setCandidatePosition(
|
||||
candidate,
|
||||
"mainPosition",
|
||||
event.target.value as Position,
|
||||
)
|
||||
}
|
||||
className="mt-1 h-8 w-full border border-base-content/10 bg-base-100 px-2 text-xs text-base-content focus:border-primary/30 focus:outline-none"
|
||||
>
|
||||
{POSITION_ORDER.map((position) => (
|
||||
<option key={position} value={position}>
|
||||
{positionLabel[position]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="text-[11px] font-bold text-base-content/35">
|
||||
부
|
||||
<select
|
||||
value={positions.subPosition}
|
||||
onChange={(event) =>
|
||||
setCandidatePosition(
|
||||
candidate,
|
||||
"subPosition",
|
||||
event.target.value as Position,
|
||||
)
|
||||
}
|
||||
className="mt-1 h-8 w-full border border-base-content/10 bg-base-100 px-2 text-xs text-base-content focus:border-primary/30 focus:outline-none"
|
||||
>
|
||||
{POSITION_ORDER.map((position) => (
|
||||
<option key={position} value={position}>
|
||||
{positionLabel[position]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
disabled={Boolean(disabledReason) || isAdding}
|
||||
onClick={() =>
|
||||
onAddParticipant({
|
||||
userId: candidate.userId,
|
||||
riotPuuid: account?.puuid,
|
||||
preferredPositions:
|
||||
buildPreferredPositionsFromMainSub(
|
||||
positions.mainPosition,
|
||||
positions.subPosition,
|
||||
),
|
||||
})
|
||||
}
|
||||
className="btn btn-primary btn-sm h-9 min-h-9 w-full text-xs disabled:opacity-40"
|
||||
>
|
||||
{isAdding ? "추가 중..." : "추가"}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="px-4 py-8 text-center text-sm text-base-content/35">
|
||||
검색 결과가 없습니다.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="border border-base-content/10 bg-base-100 overflow-hidden">
|
||||
<div className="px-4 py-2.5 border-b border-base-content/10 bg-base-200/40 flex items-center justify-between gap-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-base-content/10 bg-base-200/40 px-4 py-2.5">
|
||||
<h3 className="text-xs font-bold uppercase tracking-wider text-base-content/40">
|
||||
참가자 ({participants.length}/{maxParticipants})
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onJoin}
|
||||
disabled={!canJoin || joined || isJoining}
|
||||
className="btn btn-primary btn-xs px-4 text-xs font-semibold disabled:opacity-40"
|
||||
>
|
||||
{joined ? "참가 완료" : isJoining ? "신청 중..." : "참가 신청"}
|
||||
</button>
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onJoin}
|
||||
disabled={!canJoin || joined || isJoining}
|
||||
className="btn btn-primary btn-xs px-4 text-xs font-semibold disabled:opacity-40"
|
||||
>
|
||||
{joined ? "참가 완료" : isJoining ? "신청 중..." : "참가 신청"}
|
||||
</button>
|
||||
{canManage && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpenAddParticipant}
|
||||
disabled={participants.length >= maxParticipants}
|
||||
className="btn btn-outline btn-xs px-3 text-xs font-semibold disabled:opacity-40"
|
||||
>
|
||||
참여자 추가
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-b border-base-content/10 bg-base-100 px-4 py-2.5">
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-2">
|
||||
@@ -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<ApiMatch>(
|
||||
`/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() {
|
||||
}
|
||||
/>
|
||||
|
||||
<AdminAddParticipantModal
|
||||
open={addParticipantOpen}
|
||||
participants={match.participants}
|
||||
maxParticipants={match.maxParticipants}
|
||||
onClose={() => setAddParticipantOpen(false)}
|
||||
onAddParticipant={(params) =>
|
||||
addParticipantMutation.mutate(params)
|
||||
}
|
||||
addingUserId={
|
||||
addParticipantMutation.isPending
|
||||
? (addParticipantMutation.variables?.userId ?? null)
|
||||
: null
|
||||
}
|
||||
error={
|
||||
addParticipantMutation.error instanceof Error
|
||||
? addParticipantMutation.error
|
||||
: null
|
||||
}
|
||||
/>
|
||||
|
||||
{isCheckingPermissions ? (
|
||||
<div className="border border-base-content/10 bg-base-100 p-4">
|
||||
<h3 className="text-xs font-bold uppercase tracking-wider text-base-content/40">
|
||||
@@ -2335,10 +2777,7 @@ export default function MatchDetailPage() {
|
||||
<SideCard title="일정">
|
||||
<ul className="space-y-2">
|
||||
{match.schedule.map((item, index) => (
|
||||
<li
|
||||
key={index}
|
||||
className="flex items-start gap-2.5 text-sm"
|
||||
>
|
||||
<li key={index} className="flex items-start gap-2.5 text-sm">
|
||||
<span className="font-mono text-xs text-base-content/30 w-11 shrink-0 pt-px">
|
||||
{item.time}
|
||||
</span>
|
||||
|
||||
Reference in new issue
Block a user