feat: allow admins to add match participants

This commit is contained in:
dahyeon committed 2026-06-16 06:39:50 -07:00
1 parent 8aff1be225
commit 24983aeb09
11 files changed
+1019 -19

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 = {
+28 -2
View File
@@ -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();
}
+4 -1
View File
@@ -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 {}