diff --git a/apps/api/src/modules/community/community.controller.ts b/apps/api/src/modules/community/community.controller.ts new file mode 100644 index 00000000..be0f5327 --- /dev/null +++ b/apps/api/src/modules/community/community.controller.ts @@ -0,0 +1,107 @@ +import { + Body, + Controller, + BadRequestException, + ForbiddenException, + Get, + Param, + Patch, + Post, + Req, + UseGuards, +} from '@nestjs/common'; +import type { Request } from 'express'; +import mongoose from 'mongoose'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +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 '../auth/auth-request'; +import { CommunityService } from './community.service'; +import { CreateCommunityDto } from './dto/create-community.dto'; +import { TransferOwnershipDto } from './dto/transfer-ownership.dto'; + +@Controller('communities') +export class CommunityController { + constructor(private readonly communityService: CommunityService) {} + + @Post() + @AllowPublicAccess() + public async createCommunity( + @Body() body: CreateCommunityDto, + @Req() req: Request, + ) { + if (!req.identity && !body.owner) { + throw new BadRequestException( + 'owner is required when not authenticated.', + ); + } + return this.communityService.createCommunityWithOwner({ + ...body, + identityId: req.identity?._id, + }); + } + + @Get(':communityId') + @AllowPublicAccess() + public async getCommunity( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + ) { + return this.communityService.getById(communityId); + } + + @Patch(':communityId/members/:userId/promote') + @Roles('owner') + @UseGuards(RolesGuard) + public async promoteToAdmin( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) targetUserId: mongoose.Types.ObjectId, + ) { + this.assertOwnerOfCommunity(currentUser, communityId); + return this.communityService.promoteToAdmin({ communityId, targetUserId }); + } + + @Patch(':communityId/members/:userId/demote') + @Roles('owner') + @UseGuards(RolesGuard) + public async demoteToMember( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) targetUserId: mongoose.Types.ObjectId, + ) { + this.assertOwnerOfCommunity(currentUser, communityId); + return this.communityService.demoteToMember({ communityId, targetUserId }); + } + + @Patch(':communityId/transfer-ownership') + @Roles('owner') + @UseGuards(RolesGuard) + public async transferOwnership( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Body() body: TransferOwnershipDto, + ) { + this.assertOwnerOfCommunity(currentUser, communityId); + return this.communityService.transferOwnership({ + communityId, + currentOwnerUserId: currentUser._id, + newOwnerUserId: new mongoose.Types.ObjectId(body.newOwnerUserId), + }); + } + + private assertOwnerOfCommunity( + user: UserDocument, + communityId: mongoose.Types.ObjectId, + ): void { + if (!user.communityId.equals(communityId)) { + throw new ForbiddenException('You do not belong to this community.'); + } + } +} diff --git a/apps/api/src/modules/community/community.module.ts b/apps/api/src/modules/community/community.module.ts new file mode 100644 index 00000000..24e60fd7 --- /dev/null +++ b/apps/api/src/modules/community/community.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { CommunityController } from './community.controller'; +import { CommunityService } from './community.service'; + +@Module({ + controllers: [CommunityController], + providers: [CommunityService], + exports: [CommunityService], +}) +export class CommunityModule {} diff --git a/apps/api/src/modules/community/community.service.ts b/apps/api/src/modules/community/community.service.ts new file mode 100644 index 00000000..44a52e42 --- /dev/null +++ b/apps/api/src/modules/community/community.service.ts @@ -0,0 +1,196 @@ +import { + BadRequestException, + Injectable, + InternalServerErrorException, + NotFoundException, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { + CommunityDocument, + UserDocument, +} from '../global/database/schema'; + +export interface CreateCommunityInput { + name: string; + description?: string; + identityId?: mongoose.Types.ObjectId; + owner?: { + kakaoTalkId?: string; + kakaoTalkNickname?: string; + discordId?: string; + discordNickname?: string; + }; +} + +@Injectable() +export class CommunityService { + constructor(private readonly connectionService: ConnectionService) {} + + public async getById( + communityId: mongoose.Types.ObjectId, + ): Promise { + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(communityId).exec(); + if (!community) throw new NotFoundException('Community not found.'); + return community; + } + + public async createCommunityWithOwner(input: CreateCommunityInput): Promise<{ + community: CommunityDocument; + owner: UserDocument; + }> { + const CommunityModel = await this.connectionService.getModel('community'); + const UserModel = await this.connectionService.getModel('user'); + + const communityId = new mongoose.Types.ObjectId(); + const ownerUserId = new mongoose.Types.ObjectId(); + + const session = await this.connectionService.createSession(); + if (!session) { + throw new InternalServerErrorException('Failed to start DB session.'); + } + + try { + session.startTransaction(); + + const [community] = await CommunityModel.create( + [ + { + _id: communityId, + name: input.name, + description: input.description ?? '', + ownerUserId, + }, + ], + { session }, + ); + + const [owner] = await UserModel.create( + [ + { + _id: ownerUserId, + communityId, + identityId: input.identityId, + role: 'owner', + kakaoTalkId: input.owner?.kakaoTalkId, + kakaoTalkNickname: input.owner?.kakaoTalkNickname, + discordId: input.owner?.discordId, + discordNickname: input.owner?.discordNickname, + }, + ], + { session }, + ); + + await session.commitTransaction(); + return { community, owner }; + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + await session.endSession(); + } + } + + public async promoteToAdmin(params: { + communityId: mongoose.Types.ObjectId; + targetUserId: mongoose.Types.ObjectId; + }): Promise { + return this.changeNonOwnerRole({ ...params, nextRole: 'admin' }); + } + + public async demoteToMember(params: { + communityId: mongoose.Types.ObjectId; + targetUserId: mongoose.Types.ObjectId; + }): Promise { + return this.changeNonOwnerRole({ ...params, nextRole: 'member' }); + } + + public async transferOwnership(params: { + communityId: mongoose.Types.ObjectId; + currentOwnerUserId: mongoose.Types.ObjectId; + newOwnerUserId: mongoose.Types.ObjectId; + }): Promise<{ + community: CommunityDocument; + previousOwner: UserDocument; + newOwner: UserDocument; + }> { + if (params.currentOwnerUserId.equals(params.newOwnerUserId)) { + throw new BadRequestException('New owner is already the current owner.'); + } + + const CommunityModel = await this.connectionService.getModel('community'); + const UserModel = await this.connectionService.getModel('user'); + + const session = await this.connectionService.createSession(); + if (!session) { + throw new InternalServerErrorException('Failed to start DB session.'); + } + + try { + session.startTransaction(); + + const community = await CommunityModel.findById( + params.communityId, + ).session(session); + if (!community) throw new NotFoundException('Community not found.'); + if (!community.ownerUserId.equals(params.currentOwnerUserId)) { + throw new BadRequestException('Acting user is not the current owner.'); + } + + const [previousOwner, newOwner] = await Promise.all([ + UserModel.findById(params.currentOwnerUserId).session(session), + UserModel.findById(params.newOwnerUserId).session(session), + ]); + if (!previousOwner) + throw new NotFoundException('Previous owner user not found.'); + if (!newOwner) throw new NotFoundException('New owner user not found.'); + if (!newOwner.communityId.equals(params.communityId)) { + throw new BadRequestException( + 'New owner does not belong to this community.', + ); + } + + community.ownerUserId = newOwner._id; + previousOwner.role = 'admin'; + newOwner.role = 'owner'; + + await Promise.all([ + community.save({ session }), + previousOwner.save({ session }), + newOwner.save({ session }), + ]); + + await session.commitTransaction(); + return { community, previousOwner, newOwner }; + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + await session.endSession(); + } + } + + private async changeNonOwnerRole(params: { + communityId: mongoose.Types.ObjectId; + targetUserId: mongoose.Types.ObjectId; + nextRole: 'admin' | 'member'; + }): Promise { + const UserModel = await this.connectionService.getModel('user'); + const user = await UserModel.findById(params.targetUserId); + if (!user) throw new NotFoundException('Target user not found.'); + if (!user.communityId.equals(params.communityId)) { + throw new BadRequestException( + 'Target user does not belong to this community.', + ); + } + if (user.role === 'owner') { + throw new BadRequestException( + 'Owner role must be changed via transferOwnership.', + ); + } + user.role = params.nextRole; + await user.save(); + return user; + } +} diff --git a/apps/api/src/modules/community/dto/create-community.dto.ts b/apps/api/src/modules/community/dto/create-community.dto.ts new file mode 100644 index 00000000..e175b7fb --- /dev/null +++ b/apps/api/src/modules/community/dto/create-community.dto.ts @@ -0,0 +1,47 @@ +import { Type } from 'class-transformer'; +import { + IsOptional, + IsString, + MaxLength, + MinLength, + ValidateNested, +} from 'class-validator'; + +class CreateCommunityOwnerDto { + @IsOptional() + @IsString() + @MaxLength(64) + kakaoTalkId?: string; + + @IsOptional() + @IsString() + @MaxLength(64) + kakaoTalkNickname?: string; + + @IsOptional() + @IsString() + @MaxLength(64) + discordId?: string; + + @IsOptional() + @IsString() + @MaxLength(64) + discordNickname?: string; +} + +export class CreateCommunityDto { + @IsString() + @MinLength(1) + @MaxLength(64) + name!: string; + + @IsOptional() + @IsString() + @MaxLength(1024) + description?: string; + + @IsOptional() + @ValidateNested() + @Type(() => CreateCommunityOwnerDto) + owner?: CreateCommunityOwnerDto; +} diff --git a/apps/api/src/modules/community/dto/transfer-ownership.dto.ts b/apps/api/src/modules/community/dto/transfer-ownership.dto.ts new file mode 100644 index 00000000..90d472ec --- /dev/null +++ b/apps/api/src/modules/community/dto/transfer-ownership.dto.ts @@ -0,0 +1,6 @@ +import { IsMongoId } from 'class-validator'; + +export class TransferOwnershipDto { + @IsMongoId() + newOwnerUserId!: string; +} diff --git a/apps/api/src/modules/match-history/match-history.controller.ts b/apps/api/src/modules/match-history/match-history.controller.ts new file mode 100644 index 00000000..29d142ca --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.controller.ts @@ -0,0 +1,123 @@ +import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; +import { RiotJobQueueService } from '../riot-job-queue/riot-job-queue.service'; +import type { + RiotJobPriority, +} from '../riot-job-queue/riot-job-queue.types'; +import { MatchHistoryService } from './match-history.service'; + +interface RefreshBody { + queueGroups?: string[]; + priority?: RiotJobPriority; +} + +@Controller('communities/:communityId/users/:userId') +export class MatchHistoryController { + constructor( + private readonly matchHistoryService: MatchHistoryService, + private readonly riotJobQueueService: RiotJobQueueService, + ) {} + + @Get('history-profile') + @AllowPublicAccess() + public getProfile( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + ) { + return this.matchHistoryService.getProfile({ communityId, userId }); + } + + @Get('champion-stats') + @AllowPublicAccess() + public getChampionStats( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + @Query('queueGroup') queueGroup?: string, + @Query('rank') rank?: string, + @Query('seasonId') seasonId?: string, + ) { + return this.matchHistoryService.getChampionStats({ + communityId, + userId, + filters: { queueGroup, rank, seasonId }, + }); + } + + @Get('recent-summary') + @AllowPublicAccess() + public getRecentSummary( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + @Query('queueGroup') queueGroup?: string, + @Query('rank') rank?: string, + @Query('seasonId') seasonId?: string, + @Query('championId') championId?: string, + @Query('limit') limit?: string, + ) { + return this.matchHistoryService.getRecentSummary({ + communityId, + userId, + filters: { + queueGroup, + rank, + seasonId, + championId: this.toNumber(championId), + limit: this.toNumber(limit), + }, + }); + } + + @Get('recent-matches') + @AllowPublicAccess() + public getRecentMatches( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + @Query('queueGroup') queueGroup?: string, + @Query('rank') rank?: string, + @Query('seasonId') seasonId?: string, + @Query('championId') championId?: string, + @Query('limit') limit?: string, + @Query('cursor') cursor?: string, + ) { + return this.matchHistoryService.getRecentMatches({ + communityId, + userId, + filters: { + queueGroup, + rank, + seasonId, + championId: this.toNumber(championId), + limit: this.toNumber(limit), + cursor: this.toNumber(cursor), + }, + }); + } + + @Post('refresh') + @AllowPublicAccess() + public refresh( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + @Body() body: RefreshBody, + ) { + return this.riotJobQueueService.enqueueRefresh({ + communityId, + userId, + queueGroups: body.queueGroups ?? ['summoners-rift'], + priority: body.priority ?? 'high', + }); + } + + private toNumber(value: string | undefined): number | undefined { + if (!value) return undefined; + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : undefined; + } +} diff --git a/apps/api/src/modules/match-history/match-history.module.ts b/apps/api/src/modules/match-history/match-history.module.ts new file mode 100644 index 00000000..062b1286 --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.module.ts @@ -0,0 +1,12 @@ +import { Module } from '@nestjs/common'; +import { RiotJobQueueModule } from '../riot-job-queue/riot-job-queue.module'; +import { MatchHistoryController } from './match-history.controller'; +import { MatchHistoryService } from './match-history.service'; + +@Module({ + imports: [RiotJobQueueModule], + controllers: [MatchHistoryController], + providers: [MatchHistoryService], + exports: [MatchHistoryService], +}) +export class MatchHistoryModule {} diff --git a/apps/api/src/modules/match-history/match-history.service.ts b/apps/api/src/modules/match-history/match-history.service.ts new file mode 100644 index 00000000..2ff34648 --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.service.ts @@ -0,0 +1,782 @@ +import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + CommunityDocument, + RiotAccount, + RiotLane, + RiotMatchDocument, + UserDocument, +} from '../global/database/schema'; +import { + isRiotQueueGroup, + isRiotRankFilter, + RIOT_QUEUE_LABELS, + resolveRiotQueueIds, + type RiotQueueGroup, + type RiotRankFilter, +} from '../riot/riot-queue.constants'; +import type { + RiotMatchDto, + RiotMatchParticipantDto, +} from '../riot/riot.types'; +import type { + ChampionStatsResponse, + ChampionStatsRow, + HistorySeasonDto, + RecentMatchesResponse, + RecentMatchView, + RecentSummaryResponse, + UserHistoryProfileResponse, +} from './match-history.types'; + +const DEFAULT_QUEUE_GROUP: RiotQueueGroup = 'summoners-rift'; +const DEFAULT_RANK: RiotRankFilter = 'all'; +const DEFAULT_RECENT_LIMIT = 10; +const DEFAULT_SUMMARY_LIMIT = 20; +const MAX_AGGREGATE_MATCHES = 500; +const MAX_RECENT_SCAN = 120; + +interface HistoryContext { + community: CommunityDocument; + user: UserDocument; + account: RiotAccount; + season: HistorySeasonDto; + seasonStartedAt: Date | null; +} + +interface MatchFilters { + queueGroup?: string; + rank?: string; + seasonId?: string; + championId?: number; + limit?: number; + cursor?: number; +} + +interface AggregatedChampion { + championId: number; + games: number; + wins: number; + totalKills: number; + totalDeaths: number; + totalAssists: number; + totalCs: number; + totalGameMinutes: number; + doubleKills: number; + tripleKills: number; + quadraKills: number; + pentaKills: number; +} + +@Injectable() +export class MatchHistoryService { + constructor(private readonly connectionService: ConnectionService) {} + + public async getProfile(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + }): Promise { + const context = await this.resolveContext(params); + const lastFetchedAt = + context.account.recentStatsFetchedAt ?? + context.account.matchIdsFetchedAt ?? + null; + + return { + userId: context.user._id.toString(), + puuid: context.account.puuid, + gameName: context.account.gameName, + tagLine: context.account.tagLine, + profileIconId: context.account.profileIconId, + summonerLevel: context.account.summonerLevel, + tiers: context.account.tiers.map((tier) => ({ + queueType: tier.queueType, + tier: tier.tier, + rank: tier.rank, + leaguePoints: tier.leaguePoints, + wins: tier.wins, + losses: tier.losses, + fetchedAt: tier.fetchedAt.toISOString(), + })), + season: context.season, + seasons: this.resolveSeasons(context.community), + lastFetchedAt: lastFetchedAt?.toISOString() ?? null, + }; + } + + public async getChampionStats(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + filters: MatchFilters; + }): Promise { + const context = await this.resolveContext({ + ...params, + seasonId: params.filters.seasonId, + }); + const { queueGroup, rank, queueIds } = this.resolveQueueFilters( + params.filters, + ); + const docs = await this.findStoredMatches({ + context, + queueIds, + limit: MAX_AGGREGATE_MATCHES, + }); + const aggregates = new Map(); + + for (const doc of docs) { + const dto = doc.raw as unknown as RiotMatchDto; + const participant = this.findParticipant(dto, context.account.puuid); + if (!participant) continue; + const aggregate = + aggregates.get(participant.championId) ?? + this.createChampionAggregate(participant.championId); + this.addParticipantToChampionAggregate(aggregate, participant, dto); + aggregates.set(participant.championId, aggregate); + } + + const champions = [...aggregates.values()] + .map((aggregate) => this.toChampionStatsRow(aggregate)) + .sort((a, b) => b.games - a.games || b.winRate - a.winRate); + const totals = this.toChampionStatsRow( + [...aggregates.values()].reduce( + (acc, aggregate) => this.mergeChampionAggregate(acc, aggregate), + this.createChampionAggregate(0), + ), + ); + + return { + queueGroup, + rank, + queueIds, + season: context.season, + lastFetchedAt: this.resolveLastFetchedAt(docs, context), + champions, + totals, + }; + } + + public async getRecentSummary(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + filters: MatchFilters; + }): Promise { + const context = await this.resolveContext({ + ...params, + seasonId: params.filters.seasonId, + }); + const { queueIds } = this.resolveQueueFilters(params.filters); + const limit = this.clampLimit(params.filters.limit, DEFAULT_SUMMARY_LIMIT, 50); + const docs = await this.findStoredMatches({ + context, + queueIds, + championId: params.filters.championId, + limit, + scanLimit: params.filters.championId ? MAX_RECENT_SCAN : undefined, + }); + const views = docs + .map((doc) => this.toRecentMatchView(doc, context.account.puuid)) + .filter((view): view is RecentMatchView => Boolean(view)) + .slice(0, limit); + + return this.createRecentSummary(views, docs, context, limit); + } + + public async getRecentMatches(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + filters: MatchFilters; + }): Promise { + const context = await this.resolveContext({ + ...params, + seasonId: params.filters.seasonId, + }); + const { queueIds } = this.resolveQueueFilters(params.filters); + const limit = this.clampLimit(params.filters.limit, DEFAULT_RECENT_LIMIT, 30); + const docs = await this.findStoredMatches({ + context, + queueIds, + championId: params.filters.championId, + limit: limit + 1, + cursor: params.filters.cursor, + scanLimit: params.filters.championId ? MAX_RECENT_SCAN : undefined, + }); + const views = docs + .map((doc) => this.toRecentMatchView(doc, context.account.puuid)) + .filter((view): view is RecentMatchView => Boolean(view)); + const page = views.slice(0, limit); + + return { + matches: page, + nextCursor: views.length > limit ? page[page.length - 1]?.gameCreation ?? null : null, + lastFetchedAt: this.resolveLastFetchedAt(docs, context), + season: context.season, + }; + } + + private async resolveContext(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + seasonId?: string; + }): Promise { + const UserModel = await this.connectionService.getModel('user'); + const CommunityModel = await this.connectionService.getModel('community'); + const [user, community] = await Promise.all([ + UserModel.findById(params.userId).exec(), + CommunityModel.findById(params.communityId).exec(), + ]); + + if (!community) throw new NotFoundException('Community not found.'); + if (!user || !user.communityId.equals(params.communityId)) { + throw new NotFoundException('User not found.'); + } + + const account = + user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ?? + user.riotAccounts[0]; + if (!account) { + throw new NotFoundException('Riot account not found.'); + } + + const season = this.resolveSeason(community, params.seasonId); + const seasonStartedAt = season.startedAt + ? new Date(season.startedAt) + : (community.seasonStartedAt ?? null); + return { community, user, account, season, seasonStartedAt }; + } + + private resolveSeason( + community: CommunityDocument, + seasonId?: string, + ): HistorySeasonDto { + const seasons = this.resolveSeasons(community); + if (seasonId && seasonId !== 'current') { + const selected = seasons.find((season) => season.id === seasonId); + if (!selected) throw new BadRequestException('Invalid seasonId.'); + return selected; + } + + const configured = + seasons.find((season) => !season.endedAt) ?? + [...seasons].sort((left, right) => + (right.startedAt ?? '').localeCompare(left.startedAt ?? ''), + )[0]; + + if (configured) return configured; + + return { + id: 'current', + label: '현재 시즌', + startedAt: community.seasonStartedAt?.toISOString() ?? null, + endedAt: null, + }; + } + + private resolveSeasons(community: CommunityDocument): HistorySeasonDto[] { + const configured = community.seasons?.map((season) => ({ + id: season.id, + label: season.label, + startedAt: season.startedAt.toISOString(), + endedAt: season.endedAt?.toISOString() ?? null, + })); + + if (configured?.length) return configured; + + return [ + { + id: 'current', + label: '현재 시즌', + startedAt: community.seasonStartedAt?.toISOString() ?? null, + endedAt: null, + }, + ]; + } + + private resolveQueueFilters(filters: MatchFilters): { + queueGroup: RiotQueueGroup; + rank: RiotRankFilter; + queueIds: number[]; + } { + const queueGroup = filters.queueGroup ?? DEFAULT_QUEUE_GROUP; + const rank = filters.rank ?? DEFAULT_RANK; + if (!isRiotQueueGroup(queueGroup)) { + throw new BadRequestException('Invalid queueGroup.'); + } + if (!isRiotRankFilter(rank)) { + throw new BadRequestException('Invalid rank filter.'); + } + return { + queueGroup, + rank, + queueIds: resolveRiotQueueIds(queueGroup, rank), + }; + } + + private async findStoredMatches(params: { + context: HistoryContext; + queueIds: number[]; + limit: number; + cursor?: number; + championId?: number; + scanLimit?: number; + }): Promise { + if (params.queueIds.length === 0) return []; + const RiotMatchModel = await this.connectionService.getModel('riotMatch'); + const gameCreation: Record = {}; + if (params.context.seasonStartedAt) { + gameCreation.$gte = params.context.seasonStartedAt.getTime(); + } + if (params.cursor) gameCreation.$lt = params.cursor; + + const query: Record = { + participantPuuids: params.context.account.puuid, + queueId: { $in: params.queueIds }, + }; + if (Object.keys(gameCreation).length > 0) query.gameCreation = gameCreation; + + const docs = await RiotMatchModel.find(query) + .sort({ gameCreation: -1 }) + .limit(params.scanLimit ?? params.limit) + .exec(); + + if (!params.championId) return docs.slice(0, params.limit); + return docs + .filter((doc) => { + const participant = this.findParticipant( + doc.raw as unknown as RiotMatchDto, + params.context.account.puuid, + ); + return participant?.championId === params.championId; + }) + .slice(0, params.limit); + } + + private findParticipant( + match: RiotMatchDto, + puuid: string, + ): RiotMatchParticipantDto | null { + return ( + match.info.participants.find((participant) => participant.puuid === puuid) ?? + null + ); + } + + private createChampionAggregate(championId: number): AggregatedChampion { + return { + championId, + games: 0, + wins: 0, + totalKills: 0, + totalDeaths: 0, + totalAssists: 0, + totalCs: 0, + totalGameMinutes: 0, + doubleKills: 0, + tripleKills: 0, + quadraKills: 0, + pentaKills: 0, + }; + } + + private addParticipantToChampionAggregate( + aggregate: AggregatedChampion, + participant: RiotMatchParticipantDto, + match: RiotMatchDto, + ): void { + const minutes = this.resolveGameMinutes(match, participant); + aggregate.games += 1; + aggregate.wins += participant.win ? 1 : 0; + aggregate.totalKills += participant.kills; + aggregate.totalDeaths += participant.deaths; + aggregate.totalAssists += participant.assists; + aggregate.totalCs += this.resolveTotalCs(participant); + aggregate.totalGameMinutes += minutes; + aggregate.doubleKills += this.numberField(participant, 'doubleKills'); + aggregate.tripleKills += this.numberField(participant, 'tripleKills'); + aggregate.quadraKills += this.numberField(participant, 'quadraKills'); + aggregate.pentaKills += this.numberField(participant, 'pentaKills'); + } + + private mergeChampionAggregate( + acc: AggregatedChampion, + aggregate: AggregatedChampion, + ): AggregatedChampion { + acc.games += aggregate.games; + acc.wins += aggregate.wins; + acc.totalKills += aggregate.totalKills; + acc.totalDeaths += aggregate.totalDeaths; + acc.totalAssists += aggregate.totalAssists; + acc.totalCs += aggregate.totalCs; + acc.totalGameMinutes += aggregate.totalGameMinutes; + acc.doubleKills += aggregate.doubleKills; + acc.tripleKills += aggregate.tripleKills; + acc.quadraKills += aggregate.quadraKills; + acc.pentaKills += aggregate.pentaKills; + return acc; + } + + private toChampionStatsRow(aggregate: AggregatedChampion): ChampionStatsRow { + const losses = aggregate.games - aggregate.wins; + return { + championId: aggregate.championId, + games: aggregate.games, + wins: aggregate.wins, + losses, + winRate: this.percent(aggregate.wins, aggregate.games), + avgKills: this.average(aggregate.totalKills, aggregate.games), + avgDeaths: this.average(aggregate.totalDeaths, aggregate.games), + avgAssists: this.average(aggregate.totalAssists, aggregate.games), + kda: this.resolveKda( + aggregate.totalKills, + aggregate.totalDeaths, + aggregate.totalAssists, + ), + totalKills: aggregate.totalKills, + totalDeaths: aggregate.totalDeaths, + totalAssists: aggregate.totalAssists, + doubleKills: aggregate.doubleKills, + tripleKills: aggregate.tripleKills, + quadraKills: aggregate.quadraKills, + pentaKills: aggregate.pentaKills, + avgCs: this.average(aggregate.totalCs, aggregate.games), + avgCsPerMin: this.average(aggregate.totalCs, aggregate.totalGameMinutes), + }; + } + + private toRecentMatchView( + doc: RiotMatchDocument, + puuid: string, + ): RecentMatchView | null { + const dto = doc.raw as unknown as RiotMatchDto; + const participant = this.findParticipant(dto, puuid); + if (!participant) return null; + + const teamParticipants = dto.info.participants.filter( + (candidate) => candidate.teamId === participant.teamId, + ); + const teamKills = teamParticipants.reduce( + (sum, candidate) => sum + candidate.kills, + 0, + ); + const minutes = this.resolveGameMinutes(dto, participant); + const totalCs = this.resolveTotalCs(participant); + const damageShare = this.resolveDamageShare(dto, participant); + const rating = this.resolveRating({ + participant, + teamKills, + minutes, + damageShare, + }); + + return { + matchId: dto.metadata.matchId, + queueId: dto.info.queueId, + queueLabel: RIOT_QUEUE_LABELS[dto.info.queueId] ?? `큐 ${dto.info.queueId}`, + gameCreation: dto.info.gameCreation, + gameDuration: dto.info.gameDuration, + win: participant.win, + remake: + this.booleanField(participant, 'gameEndedInEarlySurrender') || + dto.info.gameDuration < 240, + championId: participant.championId, + championLevel: participant.champLevel, + teamPosition: participant.teamPosition || participant.individualPosition, + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + kda: this.resolveKda( + participant.kills, + participant.deaths, + participant.assists, + ), + rating, + totalCs, + csPerMin: this.average(totalCs, minutes), + killParticipation: this.percent( + participant.kills + participant.assists, + teamKills, + ), + visionScore: participant.visionScore, + controlWardsBought: this.numberField( + participant, + 'visionWardsBoughtInGame', + ), + wardsPlaced: participant.wardsPlaced, + wardsKilled: participant.wardsKilled, + damageDealtToChampions: participant.totalDamageDealtToChampions, + damageTaken: participant.totalDamageTaken, + goldEarned: participant.goldEarned, + items: [ + participant.item0, + participant.item1, + participant.item2, + participant.item3, + participant.item4, + participant.item5, + ], + trinket: participant.item6, + summonerSpells: [participant.summoner1Id, participant.summoner2Id], + perks: this.resolvePerks(participant), + teams: this.resolveTeams(dto), + }; + } + + private createRecentSummary( + views: RecentMatchView[], + docs: RiotMatchDocument[], + context: HistoryContext, + requestedLimit: number, + ): RecentSummaryResponse { + const totals = views.reduce( + (acc, view) => { + acc.wins += view.win ? 1 : 0; + acc.kills += view.kills; + acc.deaths += view.deaths; + acc.assists += view.assists; + return acc; + }, + { wins: 0, kills: 0, deaths: 0, assists: 0 }, + ); + const losses = views.length - totals.wins; + const best = views.reduce((acc, view) => { + if (!acc) return view; + return view.deaths === 0 || view.rating > acc.rating ? view : acc; + }, null); + + return { + windowSize: Math.min(views.length, requestedLimit), + winRate: this.percent(totals.wins, views.length), + wins: totals.wins, + losses, + streak: this.resolveStreak(views), + kda: this.resolveKda(totals.kills, totals.deaths, totals.assists), + avgKills: this.average(totals.kills, views.length), + avgDeaths: this.average(totals.deaths, views.length), + avgAssists: this.average(totals.assists, views.length), + bestRating: best + ? { + rating: best.deaths === 0 ? 'Perfect' : best.rating, + kills: best.kills, + deaths: best.deaths, + assists: best.assists, + matchId: best.matchId, + } + : null, + positionRates: this.resolvePositionRates(views), + topChampions: this.resolveTopChampions(views), + lastFetchedAt: this.resolveLastFetchedAt(docs, context), + }; + } + + private resolveTeams(match: RiotMatchDto): RecentMatchView['teams'] { + return match.info.teams.map((team) => ({ + side: team.teamId as 100 | 200, + win: team.win, + objectives: { + baron: team.objectives?.baron?.kills, + dragon: team.objectives?.dragon?.kills, + tower: team.objectives?.tower?.kills, + }, + participants: match.info.participants + .filter((participant) => participant.teamId === team.teamId) + .map((participant) => { + const totalCs = this.resolveTotalCs(participant); + const minutes = this.resolveGameMinutes(match, participant); + + return { + puuid: participant.puuid, + gameName: participant.riotIdGameName || participant.summonerName || 'Unknown', + tagLine: participant.riotIdTagLine || '', + championId: participant.championId, + championLevel: participant.champLevel, + teamPosition: participant.teamPosition || participant.individualPosition, + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + items: [ + participant.item0, + participant.item1, + participant.item2, + participant.item3, + participant.item4, + participant.item5, + ], + trinket: participant.item6, + summonerSpells: [participant.summoner1Id, participant.summoner2Id], + perks: this.resolvePerks(participant), + totalCs, + csPerMin: this.average(totalCs, minutes), + goldEarned: participant.goldEarned, + damageDealtToChampions: participant.totalDamageDealtToChampions, + damageTaken: participant.totalDamageTaken, + visionScore: participant.visionScore, + wardsPlaced: participant.wardsPlaced, + wardsKilled: participant.wardsKilled, + controlWardsBought: this.numberField( + participant, + 'visionWardsBoughtInGame', + ), + }; + }), + })); + } + + private resolvePerks(participant: RiotMatchParticipantDto): RecentMatchView['perks'] { + const primary = participant.perks.styles.find( + (style) => style.description === 'primaryStyle', + ); + const sub = participant.perks.styles.find( + (style) => style.description === 'subStyle', + ); + return { + primaryStyle: primary?.style, + subStyle: sub?.style, + keystone: primary?.selections[0]?.perk, + }; + } + + private resolvePositionRates( + views: RecentMatchView[], + ): Partial> { + const counts = new Map(); + for (const view of views) { + if (!view.teamPosition) continue; + counts.set(view.teamPosition, (counts.get(view.teamPosition) ?? 0) + 1); + } + return Object.fromEntries( + [...counts.entries()].map(([lane, count]) => [ + lane, + this.percent(count, views.length), + ]), + ) as Partial>; + } + + private resolveTopChampions(views: RecentMatchView[]): RecentSummaryResponse['topChampions'] { + const byChampion = new Map(); + for (const view of views) { + const stat = + byChampion.get(view.championId) ?? { games: 0, wins: 0, rating: 0 }; + stat.games += 1; + stat.wins += view.win ? 1 : 0; + stat.rating += view.rating; + byChampion.set(view.championId, stat); + } + return [...byChampion.entries()] + .map(([championId, stat]) => ({ + championId, + games: stat.games, + winRate: this.percent(stat.wins, stat.games), + pickRate: this.percent(stat.games, views.length), + avgRating: this.average(stat.rating, stat.games), + })) + .sort((a, b) => b.games - a.games || b.winRate - a.winRate) + .slice(0, 3); + } + + private resolveStreak( + views: RecentMatchView[], + ): RecentSummaryResponse['streak'] { + if (views.length === 0) return null; + const firstWin = views[0].win; + let count = 0; + for (const view of views) { + if (view.win !== firstWin) break; + count += 1; + } + return { type: firstWin ? 'win' : 'loss', count }; + } + + private resolveRating(params: { + participant: RiotMatchParticipantDto; + teamKills: number; + minutes: number; + damageShare: number; + }): number { + const { participant, teamKills, minutes, damageShare } = params; + const kda = this.resolveKda( + participant.kills, + participant.deaths, + participant.assists, + ); + const kp = teamKills > 0 ? (participant.kills + participant.assists) / teamKills : 0; + const csPerMin = this.resolveTotalCs(participant) / Math.max(minutes, 1); + const visionPerMin = participant.visionScore / Math.max(minutes, 1); + const score = + Math.min(kda / 6, 1) * 4 + + Math.min(kp, 1) * 2 + + Math.min(csPerMin / 9, 1) * 2 + + Math.min(damageShare / 0.35, 1) + + Math.min(visionPerMin / 2, 1); + return this.round(score); + } + + private resolveDamageShare( + match: RiotMatchDto, + participant: RiotMatchParticipantDto, + ): number { + const teamDamage = match.info.participants + .filter((candidate) => candidate.teamId === participant.teamId) + .reduce((sum, candidate) => sum + candidate.totalDamageDealtToChampions, 0); + return teamDamage > 0 ? participant.totalDamageDealtToChampions / teamDamage : 0; + } + + private resolveTotalCs(participant: RiotMatchParticipantDto): number { + return participant.totalMinionsKilled + participant.neutralMinionsKilled; + } + + private resolveGameMinutes( + match: RiotMatchDto, + participant: RiotMatchParticipantDto, + ): number { + return Math.max((participant.timePlayed || match.info.gameDuration) / 60, 1); + } + + private resolveKda(kills: number, deaths: number, assists: number): number { + return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths); + } + + private resolveLastFetchedAt( + docs: RiotMatchDocument[], + context: HistoryContext, + ): string | null { + if (docs.length === 0) { + return context.account.recentStatsFetchedAt?.toISOString() ?? null; + } + const oldest = docs.reduce((acc, doc) => + doc.fetchedAt.getTime() < acc.getTime() ? doc.fetchedAt : acc, + docs[0].fetchedAt); + return oldest.toISOString(); + } + + private clampLimit(value: number | undefined, fallback: number, max: number): number { + if (!value || !Number.isFinite(value)) return fallback; + return Math.max(1, Math.min(Math.floor(value), max)); + } + + private percent(value: number, total: number): number { + return total > 0 ? Math.round((value / total) * 100) : 0; + } + + private average(value: number, total: number): number { + return total > 0 ? this.round(value / total) : 0; + } + + private round(value: number): number { + return Math.round(value * 10) / 10; + } + + private numberField( + value: RiotMatchParticipantDto, + key: string, + ): number { + const field = value[key]; + return typeof field === 'number' && Number.isFinite(field) ? field : 0; + } + + private booleanField( + value: RiotMatchParticipantDto, + key: string, + ): boolean { + return value[key] === true; + } +} diff --git a/apps/api/src/modules/match-history/match-history.types.ts b/apps/api/src/modules/match-history/match-history.types.ts new file mode 100644 index 00000000..e5aeafb8 --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.types.ts @@ -0,0 +1,162 @@ +import type { RiotLane } from '../global/database/schema'; +import type { + RiotQueueGroup, + RiotRankFilter, +} from '../riot/riot-queue.constants'; + +export interface HistorySeasonDto { + id: string; + label: string; + startedAt: string | null; + endedAt: string | null; +} + +export interface UserHistoryProfileResponse { + userId: string; + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + summonerLevel: number; + tiers: Array<{ + queueType: string; + tier: string; + rank: string; + leaguePoints: number; + wins: number; + losses: number; + fetchedAt: string; + }>; + season: HistorySeasonDto; + seasons: HistorySeasonDto[]; + lastFetchedAt: string | null; +} + +export interface ChampionStatsRow { + championId: number; + games: number; + wins: number; + losses: number; + winRate: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + kda: number; + totalKills: number; + totalDeaths: number; + totalAssists: number; + doubleKills: number; + tripleKills: number; + quadraKills: number; + pentaKills: number; + avgCs: number; + avgCsPerMin: number; +} + +export interface ChampionStatsResponse { + queueGroup: RiotQueueGroup; + rank: RiotRankFilter; + queueIds: number[]; + season: HistorySeasonDto; + lastFetchedAt: string | null; + champions: ChampionStatsRow[]; + totals: ChampionStatsRow; +} + +export interface RecentSummaryResponse { + windowSize: number; + winRate: number; + wins: number; + losses: number; + streak: { type: 'win' | 'loss'; count: number } | null; + kda: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + bestRating: { + rating: number | 'Perfect'; + kills: number; + deaths: number; + assists: number; + matchId: string; + } | null; + positionRates: Partial>; + topChampions: Array<{ + championId: number; + games: number; + winRate: number; + pickRate: number; + avgRating: number; + }>; + lastFetchedAt: string | null; +} + +export interface RecentMatchesResponse { + matches: RecentMatchView[]; + nextCursor: number | null; + lastFetchedAt: string | null; + season: HistorySeasonDto; +} + +export interface RecentMatchTeamParticipantView { + puuid: string; + gameName: string; + tagLine: string; + championId: number; + championLevel: number; + teamPosition: string; + kills: number; + deaths: number; + assists: number; + items: number[]; + trinket: number; + summonerSpells: [number, number]; + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + totalCs: number; + csPerMin: number; + goldEarned: number; + damageDealtToChampions: number; + damageTaken: number; + visionScore: number; + wardsPlaced: number; + wardsKilled: number; + controlWardsBought: number; +} + +export interface RecentMatchView { + matchId: string; + queueId: number; + queueLabel: string; + gameCreation: number; + gameDuration: number; + win: boolean; + remake: boolean; + championId: number; + championLevel: number; + teamPosition: string; + kills: number; + deaths: number; + assists: number; + kda: number; + rating: number; + totalCs: number; + csPerMin: number; + killParticipation: number; + visionScore: number; + controlWardsBought: number; + wardsPlaced: number; + wardsKilled: number; + damageDealtToChampions: number; + damageTaken: number; + goldEarned: number; + items: number[]; + trinket: number; + summonerSpells: [number, number]; + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + teams: Array<{ + side: 100 | 200; + win: boolean; + objectives?: { baron?: number; dragon?: number; tower?: number }; + participants: RecentMatchTeamParticipantView[]; + }>; +} diff --git a/apps/api/src/modules/match/dto/create-match.dto.ts b/apps/api/src/modules/match/dto/create-match.dto.ts new file mode 100644 index 00000000..a2757c73 --- /dev/null +++ b/apps/api/src/modules/match/dto/create-match.dto.ts @@ -0,0 +1,187 @@ +import { Type } from 'class-transformer'; +import { + ArrayMaxSize, + ArrayMinSize, + registerDecorator, + IsArray, + IsDate, + IsEnum, + IsInt, + IsOptional, + IsString, + MaxLength, + Min, + MinLength, + ValidateNested, + ValidationArguments, + ValidationOptions, +} from 'class-validator'; +import { MATCH_GAME_MODES, POSITIONS } from '../../global/database/schema'; +import type { MatchGameMode, Position } from '../../global/database/schema'; + +function IsMultipleOf( + multiple: number, + validationOptions?: ValidationOptions, +): PropertyDecorator { + return (object, propertyName) => { + registerDecorator({ + name: 'isMultipleOf', + target: object.constructor, + propertyName: String(propertyName), + constraints: [multiple], + options: validationOptions, + validator: { + validate(value: unknown, args: ValidationArguments) { + const [divisor] = args.constraints as [number]; + return ( + typeof value === 'number' && + Number.isInteger(value) && + value % divisor === 0 + ); + }, + defaultMessage(args: ValidationArguments) { + const [divisor] = args.constraints as [number]; + return `${args.property} must be a multiple of ${divisor}.`; + }, + }, + }); + }; +} + +export class PositionPreferenceDto { + @IsEnum(POSITIONS) + position!: Position; + + @IsInt() + @Min(1) + priority!: number; +} + +class MatchScheduleItemDto { + @IsString() + @MaxLength(32) + time!: string; + + @IsString() + @MaxLength(128) + label!: string; +} + +export class CreateMatchDto { + @IsString() + @MinLength(1) + @MaxLength(128) + title!: string; + + @IsOptional() + @IsString() + @MaxLength(2048) + description?: string; + + @IsOptional() + @IsInt() + mapId?: number; + + @IsDate() + @Type(() => Date) + scheduledAt!: Date; + + @IsOptional() + @IsInt() + @Min(10) + @IsMultipleOf(10) + maxParticipants?: number; + + @IsOptional() + @IsInt() + @Min(1) + gameCount?: number; + + @IsOptional() + @IsEnum(MATCH_GAME_MODES) + gameMode?: MatchGameMode; + + @IsOptional() + @IsArray() + @IsString({ each: true }) + @ArrayMaxSize(32) + prizes?: string[]; + + @IsOptional() + @IsArray() + @IsString({ each: true }) + @ArrayMaxSize(32) + notices?: string[]; + + @IsOptional() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => MatchScheduleItemDto) + @ArrayMaxSize(32) + schedule?: MatchScheduleItemDto[]; +} + +export class UpdateMatchDto { + @IsOptional() + @IsString() + @MaxLength(128) + title?: string; + + @IsOptional() + @IsString() + @MaxLength(2048) + description?: string; + + @IsOptional() + @IsInt() + mapId?: number; + + @IsOptional() + @IsDate() + @Type(() => Date) + scheduledAt?: Date; + + @IsOptional() + @IsInt() + @Min(10) + @IsMultipleOf(10) + maxParticipants?: number; + + @IsOptional() + @IsInt() + @Min(1) + gameCount?: number; + + @IsOptional() + @IsEnum(MATCH_GAME_MODES) + gameMode?: MatchGameMode; + + @IsOptional() + @IsArray() + @IsString({ each: true }) + prizes?: string[]; + + @IsOptional() + @IsArray() + @IsString({ each: true }) + notices?: string[]; + + @IsOptional() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => MatchScheduleItemDto) + schedule?: MatchScheduleItemDto[]; +} + +export class JoinMatchDto { + @IsArray() + @ArrayMinSize(1) + @ArrayMaxSize(5) + @ValidateNested({ each: true }) + @Type(() => PositionPreferenceDto) + preferredPositions!: PositionPreferenceDto[]; + + @IsOptional() + @IsString() + userId?: string; +} diff --git a/apps/api/src/modules/match/match.controller.ts b/apps/api/src/modules/match/match.controller.ts new file mode 100644 index 00000000..c581dbdc --- /dev/null +++ b/apps/api/src/modules/match/match.controller.ts @@ -0,0 +1,170 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Get, + HttpCode, + HttpStatus, + Param, + Patch, + Post, + Query, + UseGuards, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +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 { + MatchDocument, + MatchStatus, + UserDocument, +} from '../global/database/schema'; +import { + CreateMatchDto, + JoinMatchDto, + UpdateMatchDto, +} from './dto/create-match.dto'; +import { MatchService } from './match.service'; + +@Controller('communities/:communityId/matches') +export class MatchController { + constructor(private readonly matchService: MatchService) {} + + @Post() + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + public async createMatch( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Body() body: CreateMatchDto, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.matchService.create({ + communityId, + hostUserId: currentUser._id, + data: { + title: body.title, + description: body.description ?? '', + mapId: body.mapId ?? 11, + scheduledAt: body.scheduledAt, + maxParticipants: body.maxParticipants ?? 10, + gameCount: body.gameCount, + gameMode: body.gameMode ?? 'pair', + prizes: body.prizes ?? [], + notices: body.notices ?? [], + schedule: body.schedule ?? [], + }, + }); + } + + // 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환. + @Get() + @AllowPublicAccess() + public async listMatches( + @CurrentUser() currentUser: UserDocument | undefined, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Query('status') status?: MatchStatus, + @Query('limit') limit?: string, + ) { + const matches = await this.matchService.list({ + communityId, + status, + limit: limit ? Number(limit) : undefined, + }); + if (!currentUser) return { matches }; + const myId = currentUser._id; + return { + matches: matches.map((m) => this.annotateJoined(m, myId)), + }; + } + + @Get(':matchId') + @AllowPublicAccess() + public async getMatch( + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + const match = await this.matchService.getById(matchId); + return this.matchService.serialize(match); + } + + @Patch(':matchId') + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + public async updateMatch( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: UpdateMatchDto, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.matchService.update({ matchId, communityId, patch: body }); + } + + @Delete(':matchId') + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + @HttpCode(HttpStatus.NO_CONTENT) + public async deleteMatch( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + await this.matchService.remove({ matchId, communityId }); + } + + // 공개 — 참여 (로그인된 유저는 자기 자신, 비로그인은 body.userId 사용). + @Post(':matchId/participants') + @AllowPublicAccess() + public async joinMatch( + @CurrentUser() currentUser: UserDocument | undefined, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: JoinMatchDto, + ) { + const userId = this.resolveJoinerUserId(currentUser, body.userId); + return this.matchService.join({ + matchId, + userId, + preferredPositions: body.preferredPositions, + }); + } + + private resolveJoinerUserId( + currentUser: UserDocument | undefined, + bodyUserId?: string, + ): mongoose.Types.ObjectId { + if (currentUser) return currentUser._id; + if (!bodyUserId || !mongoose.isValidObjectId(bodyUserId)) { + throw new BadRequestException( + 'userId is required when not authenticated.', + ); + } + return new mongoose.Types.ObjectId(bodyUserId); + } + + private annotateJoined( + match: MatchDocument, + userId: mongoose.Types.ObjectId, + ) { + const obj = match.toObject(); + const joined = match.participants.some((p) => p.userId.equals(userId)); + return { ...obj, joined }; + } + + private assertSameCommunity( + user: UserDocument, + communityId: mongoose.Types.ObjectId, + ): void { + if (!user.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + } +} diff --git a/apps/api/src/modules/match/match.module.ts b/apps/api/src/modules/match/match.module.ts new file mode 100644 index 00000000..54997369 --- /dev/null +++ b/apps/api/src/modules/match/match.module.ts @@ -0,0 +1,13 @@ +import { Module } from '@nestjs/common'; +import { CommunityStatsModule } from '../community-stats/community-stats.module'; +import { TournamentCodeModule } from '../tournament-code/tournament-code.module'; +import { MatchController } from './match.controller'; +import { MatchService } from './match.service'; + +@Module({ + imports: [TournamentCodeModule, CommunityStatsModule], + controllers: [MatchController], + providers: [MatchService], + exports: [MatchService], +}) +export class MatchModule {} diff --git a/apps/api/src/modules/match/match.service.spec.ts b/apps/api/src/modules/match/match.service.spec.ts new file mode 100644 index 00000000..a846a29f --- /dev/null +++ b/apps/api/src/modules/match/match.service.spec.ts @@ -0,0 +1,105 @@ +import mongoose from 'mongoose'; +import { MatchService } from './match.service'; + +describe('MatchService', () => { + function createService(match: Record) { + const MatchModel = { + findById: jest.fn().mockResolvedValue(match), + }; + const connectionService = { + getModel: jest.fn().mockImplementation(async (name: string) => { + 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, + ), + tournamentCodeService, + matchStatsService, + }; + } + + it('clears game schedule when a built match returns to recruiting', async () => { + const communityId = new mongoose.Types.ObjectId(); + const match = { + communityId, + status: 'team-built', + tournamentCodeIds: [], + gameSchedule: [{ gameNumber: 1, teamAIndex: 2, teamBIndex: 4 }], + teams: [{ teamIndex: 1 }], + teamBuiltAt: new Date(), + result: { games: [] }, + resultPollState: { state: 'polling' }, + set: jest.fn(function ( + this: Record, + patch: Record, + ) { + Object.assign(this, patch); + }), + save: jest.fn().mockResolvedValue(undefined), + }; + const { service, tournamentCodeService, matchStatsService } = + createService(match); + + await service.update({ + matchId: new mongoose.Types.ObjectId(), + communityId, + patch: { status: 'recruiting' }, + }); + + expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled(); + expect(match.tournamentCodeIds).toEqual([]); + expect(match.gameSchedule).toEqual([]); + expect(match.teamBuiltAt).toBeUndefined(); + expect(match.result).toBeUndefined(); + expect(match.resultPollState).toBeUndefined(); + expect(match.save).toHaveBeenCalledTimes(1); + expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id); + }); + + it('releases reserved codes when returning a built match to recruiting', async () => { + const communityId = new mongoose.Types.ObjectId(); + const codeId = new mongoose.Types.ObjectId(); + const match = { + communityId, + status: 'in-progress', + tournamentCodeIds: [codeId], + gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 3 }], + set: jest.fn(function ( + this: Record, + patch: Record, + ) { + Object.assign(this, patch); + }), + save: jest.fn().mockResolvedValue(undefined), + }; + const { service, tournamentCodeService } = createService(match); + + await service.update({ + matchId: new mongoose.Types.ObjectId(), + communityId, + patch: { status: 'recruiting' }, + }); + + expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match); + expect(match.tournamentCodeIds).toEqual([]); + expect(match.gameSchedule).toEqual([]); + }); +}); diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts new file mode 100644 index 00000000..1bf6b3b6 --- /dev/null +++ b/apps/api/src/modules/match/match.service.ts @@ -0,0 +1,360 @@ +import { + BadRequestException, + Injectable, + InternalServerErrorException, + NotFoundException, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { MatchStatsService } from '../community-stats/match-stats.service'; +import { CommunityStatsService } from '../community-stats/community-stats.service'; +import { ConnectionService } from '../global/database/connection.service'; +import { + Match, + MatchDocument, + MatchSeriesResult, + MatchStatus, + PositionPreference, + TierInfo, +} from '../global/database/schema'; +import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants'; +import { TournamentCodeService } from '../tournament-code/tournament-code.service'; + +const MATCH_SHORT_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; +const MATCH_SHORT_CODE_LENGTH = 4; +const MATCH_SHORT_CODE_GENERATION_ATTEMPTS = 20; + +interface CreateMatchParams { + communityId: mongoose.Types.ObjectId; + hostUserId?: mongoose.Types.ObjectId; + data: Partial & Pick; +} + +interface UpdateMatchParams { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + patch: Partial; +} + +interface ListMatchesQuery { + communityId: mongoose.Types.ObjectId; + status?: MatchStatus; + limit?: number; +} + +interface JoinMatchParams { + matchId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + preferredPositions: PositionPreference[]; + // 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용. + riotPuuid?: string; +} + +interface CancelMatchJoinParams { + matchId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; +} + +@Injectable() +export class MatchService { + constructor( + private readonly connectionService: ConnectionService, + private readonly tournamentCodeService: TournamentCodeService, + private readonly communityStatsService: CommunityStatsService, + private readonly matchStatsService: MatchStatsService, + ) {} + + public async create(params: CreateMatchParams): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(params.communityId) + .select({ matchGameCount: 1 }) + .lean() + .exec(); + return MatchModel.create({ + ...params.data, + shortCode: + params.data.shortCode ?? + (await this.generateUniqueShortCode(MatchModel, params.communityId)), + gameCount: + params.data.gameCount ?? + community?.matchGameCount ?? + DEFAULT_TOURNAMENT_GAME_COUNT, + communityId: params.communityId, + hostUserId: params.hostUserId, + }); + } + + public async list(query: ListMatchesQuery): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const filter: { + communityId: mongoose.Types.ObjectId; + status?: MatchStatus; + } = { + communityId: query.communityId, + }; + if (query.status) filter.status = query.status; + return MatchModel.find(filter) + .sort({ scheduledAt: -1 }) + .limit(Math.min(query.limit ?? 50, 200)) + .exec(); + } + + public async ensureShortCode(match: MatchDocument): Promise { + if (match.shortCode) return match; + + const MatchModel = await this.connectionService.getModel('match'); + match.shortCode = await this.generateUniqueShortCode( + MatchModel, + match.communityId, + ); + await match.save(); + return match; + } + + public async getById( + matchId: 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.'); + return match; + } + + public async serialize(match: MatchDocument) { + const obj = match.toObject(); + if (obj.result?.games) { + obj.result.games = [...obj.result.games].sort( + (left, right) => left.gameNumber - right.gameNumber, + ); + if (!obj.result.seriesResults?.length) { + obj.result.seriesResults = this.buildSeriesResults(obj.result.games); + } + } + return { + ...obj, + gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT, + gameMode: match.gameMode ?? 'pair', + participants: (obj.participants ?? []).map((participant) => ({ + ...participant, + excluded: participant.excluded ?? false, + })), + teams: (obj.teams ?? []).map((team) => ({ + ...team, + })), + gameSchedule: obj.gameSchedule ?? [], + tournamentCodes: await this.tournamentCodeService.buildSlots(match), + }; + } + + public async update(params: UpdateMatchParams): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findById(params.matchId); + if (!match) throw new NotFoundException('Match not found.'); + if (!match.communityId.equals(params.communityId)) { + throw new BadRequestException('Match does not belong to this community.'); + } + const previousStatus = match.status; + if ( + previousStatus !== 'recruiting' && + ('maxParticipants' in params.patch || 'gameMode' in params.patch) + ) { + throw new BadRequestException( + 'maxParticipants and gameMode can only be changed while recruiting.', + ); + } + match.set(params.patch); + if (previousStatus !== 'recruiting' && match.status === 'recruiting') { + if (match.tournamentCodeIds.length > 0) { + await this.tournamentCodeService.releaseFromMatch(match); + } + match.tournamentCodeIds = []; + match.gameSchedule = []; + match.teamBuiltAt = undefined; + match.result = undefined; + match.resultPollState = undefined; + } + await match.save(); + if (previousStatus !== 'recruiting' && match.status === 'recruiting') { + await this.matchStatsService.removeByMatch(match._id); + await this.communityStatsService.invalidateCommunity(params.communityId); + } else if (match.result?.games?.length) { + await this.matchStatsService.buildAndUpsert(match._id); + await this.communityStatsService.invalidateCommunity(params.communityId); + } + return match; + } + + public async remove(params: { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + }): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findById(params.matchId); + if (!match) throw new NotFoundException('Match not found.'); + if (!match.communityId.equals(params.communityId)) { + throw new BadRequestException('Match does not belong to this community.'); + } + await this.tournamentCodeService.releaseFromMatch(match); + await this.matchStatsService.removeByMatch(match._id); + await match.deleteOne(); + await this.communityStatsService.invalidateCommunity(params.communityId); + } + + public async join(params: JoinMatchParams): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const UserModel = await this.connectionService.getModel('user'); + + const user = await UserModel.findById(params.userId); + if (!user) throw new NotFoundException('User not found.'); + + const match = await MatchModel.findById(params.matchId); + if (!match) throw new NotFoundException('Match not found.'); + if (!match.communityId.equals(user.communityId)) { + throw new BadRequestException( + 'User and match belong to different communities.', + ); + } + if (match.status !== 'recruiting') { + throw new BadRequestException('Match is not recruiting.'); + } + if (match.participants.length >= match.maxParticipants) { + throw new BadRequestException('Match is full.'); + } + const alreadyIn = match.participants.some((p) => p.userId.equals(user._id)); + if (alreadyIn) { + throw new BadRequestException('User already joined this match.'); + } + + const selectedRiot = params.riotPuuid + ? user.riotAccounts.find((a) => a.puuid === params.riotPuuid) + : user.riotAccounts.find((a) => a.isPrimary); + const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []); + match.participants.push({ + userId: user._id, + puuid: selectedRiot?.puuid, + gameName: selectedRiot?.gameName, + tagLine: selectedRiot?.tagLine, + profileIconId: selectedRiot?.profileIconId, + tier: selectedTier, + preferredPositions: params.preferredPositions, + joinedAt: new Date(), + excluded: false, + }); + await match.save(); + return match; + } + + public async cancelJoin( + params: CancelMatchJoinParams, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const UserModel = await this.connectionService.getModel('user'); + + const user = await UserModel.findById(params.userId); + if (!user) throw new NotFoundException('User not found.'); + + const match = await MatchModel.findById(params.matchId); + if (!match) throw new NotFoundException('Match not found.'); + if (!match.communityId.equals(user.communityId)) { + throw new BadRequestException( + 'User and match belong to different communities.', + ); + } + if (match.status !== 'recruiting') { + throw new BadRequestException('Match is not recruiting.'); + } + + const participantIndex = match.participants.findIndex((participant) => + participant.userId.equals(user._id), + ); + if (participantIndex === -1) { + throw new BadRequestException('User has not joined this match.'); + } + + match.participants.splice(participantIndex, 1); + await match.save(); + return match; + } + + private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined { + const tier = + tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0]; + if (!tier) return undefined; + + return { + leagueId: tier.leagueId, + queueType: tier.queueType, + tier: tier.tier, + rank: tier.rank, + puuid: tier.puuid, + leaguePoints: tier.leaguePoints, + wins: tier.wins, + losses: tier.losses, + veteran: tier.veteran, + inactive: tier.inactive, + freshBlood: tier.freshBlood, + hotStreak: tier.hotStreak, + miniSeries: tier.miniSeries, + fetchedAt: tier.fetchedAt, + }; + } + + private async generateUniqueShortCode( + MatchModel: mongoose.Model, + communityId: mongoose.Types.ObjectId, + ): Promise { + for ( + let attempt = 0; + attempt < MATCH_SHORT_CODE_GENERATION_ATTEMPTS; + attempt += 1 + ) { + const shortCode = this.generateShortCode(); + const exists = await MatchModel.exists({ communityId, shortCode }); + if (!exists) return shortCode; + } + + throw new InternalServerErrorException( + 'Failed to generate unique match short code.', + ); + } + + private generateShortCode(): string { + let code = ''; + for (let index = 0; index < MATCH_SHORT_CODE_LENGTH; index += 1) { + const alphabetIndex = Math.floor( + Math.random() * MATCH_SHORT_CODE_ALPHABET.length, + ); + code += MATCH_SHORT_CODE_ALPHABET[alphabetIndex]; + } + return code; + } + + private buildSeriesResults( + games: NonNullable['games'], + ): MatchSeriesResult[] { + const bySeries = new Map(); + for (const game of games) { + const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); + const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); + const key = `${teamAIndex}:${teamBIndex}`; + const current = + bySeries.get(key) ?? + ({ + teamAIndex, + teamBIndex, + teamAWins: 0, + teamBWins: 0, + } satisfies MatchSeriesResult); + if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1; + if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1; + current.winnerTeamIndex = + current.teamAWins > current.teamBWins + ? teamAIndex + : current.teamBWins > current.teamAWins + ? teamBIndex + : undefined; + bySeries.set(key, current); + } + return [...bySeries.values()]; + } +} diff --git a/apps/api/src/seed.ts b/apps/api/src/seed.ts new file mode 100644 index 00000000..458e8cf6 --- /dev/null +++ b/apps/api/src/seed.ts @@ -0,0 +1,1094 @@ +import 'reflect-metadata'; +import { Module } from '@nestjs/common'; +import { ConfigModule } from '@nestjs/config'; +import { NestFactory } from '@nestjs/core'; +import mongoose from 'mongoose'; +import { readFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { ConnectionService } from './modules/global/database/connection.service'; +import type { + ChampionMasteryEntry, + MatchParticipant, + MatchTeam, + Position, + PositionPreference, + RiotLane, + RiotRecentStatsSummary, + TierInfo, +} from './modules/global/database/schema'; +import { SecretModule } from './modules/global/secret/secret.module'; + +process.env.NODE_ENV ??= 'dev'; + +async function loadMachineEnvFile() { + const homeDir = process.env.HOME ?? process.env.USERPROFILE; + if (!homeDir) return; + + const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt'); + + try { + const file = await readFile(machineEnvFile, 'utf8'); + for (const rawLine of file.split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line || line.startsWith('#')) continue; + + const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/); + if (!matched) continue; + + const [, key, rawValue] = matched; + const value = rawValue.replace(/^["']|["']$/g, ''); + process.env[key] = value; + } + } catch { + // 로컬 machine env 파일이 없으면 그냥 지나간다. + } +} + +@Module({ + imports: [ + ConfigModule.forRoot({ + isGlobal: true, + envFilePath: [ + resolve(__dirname, '../../project.env'), + resolve(process.cwd(), 'apps/project.env'), + resolve(process.cwd(), 'project.env'), + ], + }), + SecretModule, + ], + providers: [ConnectionService], +}) +class SeedModule {} + +type SeedPlayer = { + key: string; + gameName: string; + tagLine: string; + kakaoTalkNickname: string; + profileIconId: number; + main: Position; + sub: Position; + tier: { + tier: string; + rank: string; + leaguePoints: number; + wins: number; + losses: number; + }; + flex?: { + tier: string; + rank: string; + leaguePoints: number; + wins: number; + losses: number; + }; + masteries: SeedChampionMastery[]; + recentStatsSummary: SeedRecentStatsSummary; +}; + +type SeedChampionMastery = { + championId: string; + championName?: string; + level: number; + points: number; +}; + +type SeedRecentStatsSummary = { + games: number; + wins: number; + losses: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + avgCs: number; + avgCsPerMin?: number; + mostPlayedChampionIds: string[]; +}; + +const DEV_COMMUNITY_NAME = '[DEV] Lolympus Test Community'; +const DEV_COMMUNITY_DESCRIPTION = + 'Frontend/Backend 통합 검증용으로 생성된 개발 커뮤니티입니다.'; + +const NOW = new Date(); + +const CHAMPION_IDS: Record = { + Ahri: 103, + Ashe: 22, + Camille: 164, + Ezreal: 81, + Gwen: 887, + Hwei: 910, + JarvanIV: 59, + Jax: 24, + Jinx: 222, + KaiSa: 145, + LeeSin: 64, + Nami: 267, + Nasus: 75, + Nautilus: 111, + Nidalee: 76, + Orianna: 61, + Rakan: 497, + Rengar: 107, + Sona: 37, + Syndra: 134, + Taliyah: 163, + Thresh: 412, + Viego: 234, + Viktor: 112, + Xayah: 498, + Yorick: 83, + Yuumi: 350, + Zeri: 221, +}; + +const POSITION_TO_RIOT_LANE: Record = { + TOP: 'TOP', + JGL: 'JUNGLE', + MID: 'MIDDLE', + ADC: 'BOTTOM', + SUP: 'UTILITY', +}; + +const PLAYER_SEEDS: SeedPlayer[] = [ + { + key: 'priri', + gameName: '프리리', + tagLine: 'KR1', + kakaoTalkNickname: '프리리', + profileIconId: 588, + main: 'MID', + sub: 'ADC', + tier: { + tier: 'DIAMOND', + rank: 'IV', + leaguePoints: 37, + wins: 66, + losses: 58, + }, + flex: { + tier: 'EMERALD', + rank: 'I', + leaguePoints: 54, + wins: 31, + losses: 22, + }, + masteries: [ + { + championId: 'Syndra', + championName: '신드라', + level: 7, + points: 124300, + }, + { championId: 'Ahri', championName: '아리', level: 7, points: 98200 }, + { + championId: 'Orianna', + championName: '오리아나', + level: 6, + points: 63400, + }, + ], + recentStatsSummary: { + games: 24, + wins: 14, + losses: 10, + avgKills: 7.8, + avgDeaths: 4.2, + avgAssists: 6.7, + avgCs: 188, + mostPlayedChampionIds: ['Syndra', 'Ahri', 'Orianna'], + }, + }, + { + key: 'hobul', + gameName: '호호불어먹어요', + tagLine: '0000', + kakaoTalkNickname: '호호불', + profileIconId: 7015, + main: 'JGL', + sub: 'TOP', + tier: { + tier: 'PLATINUM', + rank: 'II', + leaguePoints: 73, + wins: 54, + losses: 49, + }, + flex: { + tier: 'EMERALD', + rank: 'III', + leaguePoints: 22, + wins: 14, + losses: 10, + }, + masteries: [ + { championId: 'Viego', championName: '비에고', level: 7, points: 138200 }, + { championId: 'LeeSin', championName: '리신', level: 6, points: 88700 }, + { + championId: 'Nidalee', + championName: '니달리', + level: 6, + points: 64100, + }, + ], + recentStatsSummary: { + games: 28, + wins: 15, + losses: 13, + avgKills: 5.9, + avgDeaths: 4.9, + avgAssists: 9.1, + avgCs: 151, + mostPlayedChampionIds: ['Viego', 'LeeSin', 'Nidalee'], + }, + }, + { + key: 'soda', + gameName: '소다', + tagLine: 'KR1', + kakaoTalkNickname: '소다', + profileIconId: 5186, + main: 'TOP', + sub: 'MID', + tier: { + tier: 'EMERALD', + rank: 'I', + leaguePoints: 18, + wins: 49, + losses: 41, + }, + flex: { + tier: 'PLATINUM', + rank: 'I', + leaguePoints: 64, + wins: 20, + losses: 14, + }, + masteries: [ + { championId: 'Jax', championName: '잭스', level: 7, points: 112400 }, + { championId: 'Camille', championName: '카밀', level: 6, points: 76500 }, + { championId: 'Gwen', championName: '그웬', level: 6, points: 58700 }, + ], + recentStatsSummary: { + games: 21, + wins: 11, + losses: 10, + avgKills: 5.4, + avgDeaths: 4.6, + avgAssists: 5.2, + avgCs: 201, + mostPlayedChampionIds: ['Jax', 'Camille', 'Gwen'], + }, + }, + { + key: 'inghoba', + gameName: '잉호바', + tagLine: 'KR1', + kakaoTalkNickname: '잉호바', + profileIconId: 7050, + main: 'SUP', + sub: 'MID', + tier: { + tier: 'DIAMOND', + rank: 'III', + leaguePoints: 41, + wins: 72, + losses: 60, + }, + flex: { + tier: 'MASTER', + rank: '', + leaguePoints: 121, + wins: 19, + losses: 11, + }, + masteries: [ + { + championId: 'Thresh', + championName: '쓰레쉬', + level: 7, + points: 187300, + }, + { + championId: 'Nautilus', + championName: '노틸러스', + level: 7, + points: 144800, + }, + { championId: 'Rakan', championName: '라칸', level: 6, points: 65300 }, + ], + recentStatsSummary: { + games: 32, + wins: 19, + losses: 13, + avgKills: 2.5, + avgDeaths: 4.3, + avgAssists: 14.8, + avgCs: 34, + mostPlayedChampionIds: ['Thresh', 'Nautilus', 'Rakan'], + }, + }, + { + key: 'tabkey', + gameName: '잉호바탭키도둑', + tagLine: 'Tab', + kakaoTalkNickname: '탭키도둑', + profileIconId: 5231, + main: 'ADC', + sub: 'SUP', + tier: { + tier: 'PLATINUM', + rank: 'I', + leaguePoints: 47, + wins: 61, + losses: 56, + }, + flex: { + tier: 'EMERALD', + rank: 'IV', + leaguePoints: 28, + wins: 22, + losses: 20, + }, + masteries: [ + { championId: 'Jinx', championName: '징크스', level: 7, points: 166100 }, + { championId: 'KaiSa', championName: '카이사', level: 7, points: 139400 }, + { + championId: 'Ezreal', + championName: '이즈리얼', + level: 6, + points: 90100, + }, + ], + recentStatsSummary: { + games: 29, + wins: 16, + losses: 13, + avgKills: 8.4, + avgDeaths: 4.8, + avgAssists: 6.1, + avgCs: 213, + mostPlayedChampionIds: ['Jinx', 'KaiSa', 'Ezreal'], + }, + }, + { + key: 'osu', + gameName: 'osu', + tagLine: 'KR1', + kakaoTalkNickname: 'osu', + profileIconId: 7091, + main: 'MID', + sub: 'JGL', + tier: { + tier: 'EMERALD', + rank: 'III', + leaguePoints: 59, + wins: 58, + losses: 50, + }, + flex: { + tier: 'MASTER', + rank: '', + leaguePoints: 74, + wins: 12, + losses: 8, + }, + masteries: [ + { + championId: 'Viktor', + championName: '빅토르', + level: 7, + points: 172900, + }, + { championId: 'Hwei', championName: '흐웨이', level: 6, points: 94400 }, + { + championId: 'Taliyah', + championName: '탈리야', + level: 6, + points: 55300, + }, + ], + recentStatsSummary: { + games: 25, + wins: 13, + losses: 12, + avgKills: 6.3, + avgDeaths: 5.2, + avgAssists: 7.7, + avgCs: 198, + mostPlayedChampionIds: ['Viktor', 'Hwei', 'Taliyah'], + }, + }, + { + key: 'icequeen', + gameName: 'IceQueen', + tagLine: 'KR1', + kakaoTalkNickname: '아이스퀸', + profileIconId: 5102, + main: 'ADC', + sub: 'MID', + tier: { + tier: 'DIAMOND', + rank: 'II', + leaguePoints: 63, + wins: 67, + losses: 52, + }, + flex: { + tier: 'MASTER', + rank: '', + leaguePoints: 34, + wins: 11, + losses: 9, + }, + masteries: [ + { championId: 'Xayah', championName: '자야', level: 7, points: 154800 }, + { championId: 'Zeri', championName: '제리', level: 7, points: 141900 }, + { championId: 'Ashe', championName: '애쉬', level: 6, points: 59800 }, + ], + recentStatsSummary: { + games: 31, + wins: 18, + losses: 13, + avgKills: 7.7, + avgDeaths: 4.4, + avgAssists: 7.2, + avgCs: 226, + mostPlayedChampionIds: ['Xayah', 'Zeri', 'Ashe'], + }, + }, + { + key: 'jungler123', + gameName: '정글러123', + tagLine: 'KR3', + kakaoTalkNickname: '정글러123', + profileIconId: 4789, + main: 'JGL', + sub: 'SUP', + tier: { + tier: 'PLATINUM', + rank: 'III', + leaguePoints: 15, + wins: 43, + losses: 42, + }, + flex: { + tier: 'GOLD', + rank: 'I', + leaguePoints: 87, + wins: 18, + losses: 16, + }, + masteries: [ + { championId: 'LeeSin', championName: '리신', level: 7, points: 201300 }, + { championId: 'Viego', championName: '비에고', level: 6, points: 87600 }, + { championId: 'Rengar', championName: '렝가', level: 6, points: 65400 }, + ], + recentStatsSummary: { + games: 38, + wins: 18, + losses: 20, + avgKills: 5.4, + avgDeaths: 5.8, + avgAssists: 8.1, + avgCs: 142, + mostPlayedChampionIds: ['LeeSin', 'Viego', 'Rengar'], + }, + }, + { + key: 'topsol', + gameName: '탑솔장인', + tagLine: 'KR1', + kakaoTalkNickname: '탑솔장인', + profileIconId: 5450, + main: 'TOP', + sub: 'JGL', + tier: { + tier: 'EMERALD', + rank: 'II', + leaguePoints: 46, + wins: 57, + losses: 44, + }, + flex: { + tier: 'PLATINUM', + rank: 'II', + leaguePoints: 34, + wins: 21, + losses: 19, + }, + masteries: [ + { championId: 'Jax', championName: '잭스', level: 7, points: 145600 }, + { championId: 'Yorick', championName: '요릭', level: 7, points: 112400 }, + { championId: 'Nasus', championName: '나서스', level: 6, points: 89300 }, + ], + recentStatsSummary: { + games: 47, + wins: 27, + losses: 20, + avgKills: 5.6, + avgDeaths: 3.9, + avgAssists: 4.1, + avgCs: 201, + mostPlayedChampionIds: ['Jax', 'Yorick', 'Nasus'], + }, + }, + { + key: 'supporter', + gameName: '서폿장인', + tagLine: '0001', + kakaoTalkNickname: '서폿장인', + profileIconId: 4900, + main: 'SUP', + sub: 'ADC', + tier: { + tier: 'DIAMOND', + rank: 'IV', + leaguePoints: 9, + wins: 64, + losses: 61, + }, + flex: { + tier: 'DIAMOND', + rank: 'III', + leaguePoints: 25, + wins: 17, + losses: 14, + }, + masteries: [ + { championId: 'Yuumi', championName: '유미', level: 7, points: 198700 }, + { championId: 'Sona', championName: '소나', level: 7, points: 145200 }, + { championId: 'Nami', championName: '나미', level: 6, points: 92100 }, + ], + recentStatsSummary: { + games: 52, + wins: 30, + losses: 22, + avgKills: 1.8, + avgDeaths: 4.2, + avgAssists: 16.3, + avgCs: 25, + mostPlayedChampionIds: ['Yuumi', 'Sona', 'Nami'], + }, + }, +]; + +function createPreferences( + main: Position, + sub: Position, +): PositionPreference[] { + const rest = (['TOP', 'JGL', 'MID', 'ADC', 'SUP'] as Position[]).filter( + (position) => position !== main && position !== sub, + ); + + return [ + { position: main, priority: 1 }, + { position: sub, priority: 2 }, + ...rest.map((position, index) => ({ + position, + priority: index + 3, + })), + ]; +} + +function createTier( + puuid: string, + queueType: string, + tier: string, + rank: string, + leaguePoints: number, + wins: number, + losses: number, +): TierInfo { + return { + leagueId: `dev-${puuid}-${queueType}`, + queueType, + tier, + rank: rank || 'I', + puuid, + leaguePoints, + wins, + losses, + fetchedAt: NOW, + }; +} + +function selectPrimaryTier(tiers: TierInfo[]) { + return tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ?? tiers[0]; +} + +function createRiotAccount(player: SeedPlayer) { + const puuid = `dev-seed-${player.key}-puuid`; + const tiers = [ + createTier( + puuid, + 'RANKED_SOLO_5x5', + player.tier.tier, + player.tier.rank, + player.tier.leaguePoints, + player.tier.wins, + player.tier.losses, + ), + ]; + + if (player.flex) { + tiers.push( + createTier( + puuid, + 'RANKED_FLEX_SR', + player.flex.tier, + player.flex.rank, + player.flex.leaguePoints, + player.flex.wins, + player.flex.losses, + ), + ); + } + + return { + puuid, + gameName: player.gameName, + tagLine: player.tagLine, + profileIconId: player.profileIconId, + revisionDate: Date.now(), + summonerLevel: 200, + isPrimary: true, + tiers, + tierHistory: [], + matchIds: [], + recentStatsSummary: createRecentStatsSummary( + player.recentStatsSummary, + player.main, + ), + recentStatsFetchedAt: NOW, + championMasteries: createChampionMasteries(puuid, player.masteries), + championMasteriesFetchedAt: NOW, + championRecords: {}, + championRecordsFetchedAt: NOW, + createdAt: NOW, + updatedAt: NOW, + }; +} + +function createStaffRiotAccount( + key: string, + gameName: string, + tagLine: string, +) { + const puuid = `dev-seed-${key}-puuid`; + return { + puuid, + gameName, + tagLine, + profileIconId: 29, + revisionDate: Date.now(), + summonerLevel: 120, + isPrimary: true, + tiers: [createTier(puuid, 'RANKED_SOLO_5x5', 'GOLD', 'I', 75, 24, 19)], + tierHistory: [], + matchIds: [], + recentStatsSummary: createRecentStatsSummary( + { + games: 12, + wins: 7, + losses: 5, + avgKills: 5.1, + avgDeaths: 4.3, + avgAssists: 7.4, + avgCs: 167, + mostPlayedChampionIds: ['Orianna', 'JarvanIV'], + }, + 'MID', + ), + recentStatsFetchedAt: NOW, + championMasteries: createChampionMasteries(puuid, [ + { + championId: 'Orianna', + championName: '오리아나', + level: 5, + points: 18300, + }, + { + championId: 'JarvanIV', + championName: '자르반 4세', + level: 5, + points: 12600, + }, + ]), + championMasteriesFetchedAt: NOW, + championRecords: {}, + championRecordsFetchedAt: NOW, + createdAt: NOW, + updatedAt: NOW, + }; +} + +function createChampionMasteries( + puuid: string, + masteries: SeedChampionMastery[], +): ChampionMasteryEntry[] { + return masteries.map((mastery) => ({ + puuid, + championId: CHAMPION_IDS[mastery.championId] ?? 0, + championLevel: mastery.level, + championPoints: mastery.points, + })); +} + +function createRecentStatsSummary( + input: SeedRecentStatsSummary, + mainPosition: Position, +): RiotRecentStatsSummary { + const lane = POSITION_TO_RIOT_LANE[mainPosition]; + const championIds = input.mostPlayedChampionIds.map( + (championId) => CHAMPION_IDS[championId] ?? 0, + ); + const laneStats = { + games: input.games, + wins: input.wins, + losses: input.losses, + avgKills: input.avgKills, + avgDeaths: input.avgDeaths, + avgAssists: input.avgAssists, + avgCs: input.avgCs, + avgCsPerMin: + input.avgCsPerMin ?? Math.round((input.avgCs / 28) * 10) / 10, + mostPlayedChampionIds: championIds, + }; + + return { + overall: laneStats, + byLane: { + [lane]: laneStats, + }, + }; +} + +function toMatchParticipant(user: { + _id: mongoose.Types.ObjectId; + riotAccounts: Array<{ + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + tiers: TierInfo[]; + }>; + preferredPositions: PositionPreference[]; +}): MatchParticipant { + const primary = user.riotAccounts[0]; + + return { + userId: user._id, + puuid: primary?.puuid, + gameName: primary?.gameName, + tagLine: primary?.tagLine, + profileIconId: primary?.profileIconId, + tier: primary ? selectPrimaryTier(primary.tiers) : undefined, + preferredPositions: user.preferredPositions, + joinedAt: NOW, + }; +} + +async function main() { + await loadMachineEnvFile(); + + const app = await NestFactory.createApplicationContext(SeedModule, { + logger: ['error', 'warn', 'log'], + }); + + try { + const connectionService = app.get(ConnectionService); + const CommunityModel = await connectionService.getModel('community'); + const UserModel = await connectionService.getModel('user'); + const MatchModel = await connectionService.getModel('match'); + const AuctionModel = await connectionService.getModel('auction'); + + const existingCommunity = await CommunityModel.findOne({ + name: DEV_COMMUNITY_NAME, + }).exec(); + + if (existingCommunity) { + const existingMatches = await MatchModel.find({ + communityId: existingCommunity._id, + }) + .select('_id') + .lean() + .exec(); + + const matchIds = existingMatches.map((match) => match._id); + if (matchIds.length > 0) { + await AuctionModel.deleteMany({ matchId: { $in: matchIds } }).exec(); + } + + await MatchModel.deleteMany({ + communityId: existingCommunity._id, + }).exec(); + await UserModel.deleteMany({ communityId: existingCommunity._id }).exec(); + await CommunityModel.deleteOne({ _id: existingCommunity._id }).exec(); + } + + const communityId = new mongoose.Types.ObjectId(); + const ownerUserId = new mongoose.Types.ObjectId(); + const adminUserId = new mongoose.Types.ObjectId(); + + await CommunityModel.create({ + _id: communityId, + name: DEV_COMMUNITY_NAME, + description: DEV_COMMUNITY_DESCRIPTION, + ownerUserId, + riotPlatform: 'kr', + riotRegion: 'asia', + }); + + const owner = { + _id: ownerUserId, + communityId, + role: 'owner' as const, + kakaoTalkId: 'dev-owner', + kakaoTalkNickname: 'DevOwner', + discordId: 'dev-owner-discord', + discordNickname: 'DevOwner', + riotAccounts: [createStaffRiotAccount('owner', 'DevOwner', 'KR1')], + preferredPositions: createPreferences('MID', 'SUP'), + isActivated: true, + }; + + const admin = { + _id: adminUserId, + communityId, + role: 'admin' as const, + kakaoTalkId: 'dev-admin', + kakaoTalkNickname: 'DevAdmin', + discordId: 'dev-admin-discord', + discordNickname: 'DevAdmin', + riotAccounts: [createStaffRiotAccount('admin', 'DevAdmin', 'KR1')], + preferredPositions: createPreferences('JGL', 'MID'), + isActivated: true, + }; + + const players = PLAYER_SEEDS.map((player) => ({ + _id: new mongoose.Types.ObjectId(), + communityId, + role: 'member' as const, + kakaoTalkId: `seed-${player.key}`, + kakaoTalkNickname: player.kakaoTalkNickname, + discordId: `seed-${player.key}-discord`, + discordNickname: player.gameName, + riotAccounts: [createRiotAccount(player)], + preferredPositions: createPreferences(player.main, player.sub), + isActivated: true, + })); + + await UserModel.insertMany([owner, admin, ...players], { ordered: true }); + + const recruitingPlayers = players.slice(0, 6); + const auctionPlayers = players; + const finishedBlue = [ + { user: players[0], assignedPosition: 'MID' as const, cost: 0 }, + { user: players[2], assignedPosition: 'TOP' as const, cost: 320 }, + { user: players[4], assignedPosition: 'ADC' as const, cost: 280 }, + { user: players[7], assignedPosition: 'JGL' as const, cost: 190 }, + { user: players[9], assignedPosition: 'SUP' as const, cost: 210 }, + ]; + const finishedRed = [ + { user: players[1], assignedPosition: 'JGL' as const, cost: 0 }, + { user: players[3], assignedPosition: 'SUP' as const, cost: 240 }, + { user: players[5], assignedPosition: 'MID' as const, cost: 250 }, + { user: players[6], assignedPosition: 'ADC' as const, cost: 300 }, + { user: players[8], assignedPosition: 'TOP' as const, cost: 220 }, + ]; + + const recruitingMatchId = new mongoose.Types.ObjectId(); + const auctionMatchId = new mongoose.Types.ObjectId(); + const finishedMatchId = new mongoose.Types.ObjectId(); + + await MatchModel.insertMany([ + { + _id: recruitingMatchId, + communityId, + hostUserId: ownerUserId, + title: '쌀먹 내전', + description: '통합 테스트용 모집 중 매치입니다.', + mapId: 11, + status: 'recruiting', + scheduledAt: new Date('2026-04-27T12:00:00.000Z'), + maxParticipants: 10, + participants: recruitingPlayers.map(toMatchParticipant), + teams: [], + prizes: ['5명 추첨 커피', 'MVP: 스킨 선물'], + notices: [ + '시작 10분 전까지 커스텀 방에 입장해주세요.', + '개발용 시드 데이터입니다.', + ], + schedule: [ + { time: '20:50', label: '로비 오픈' }, + { time: '21:00', label: '내전 시작' }, + ], + }, + { + _id: auctionMatchId, + communityId, + hostUserId: ownerUserId, + title: '롤림푸스 경매 테스트 매치', + description: 'Socket.IO 경매 페이지 검증용으로 생성된 매치입니다.', + mapId: 11, + status: 'team-built', + scheduledAt: new Date('2026-04-26T11:00:00.000Z'), + maxParticipants: 10, + participants: auctionPlayers.map(toMatchParticipant), + teams: [ + { + teamIndex: 1, + name: '1팀', + captainUserId: players[0]._id, + members: [ + { + userId: players[0]._id, + assignedPosition: 'MID', + cost: 0, + }, + ], + }, + { + teamIndex: 2, + name: '2팀', + captainUserId: players[1]._id, + members: [ + { + userId: players[1]._id, + assignedPosition: 'JGL', + cost: 0, + }, + ], + }, + ], + prizes: ['우승팀 햄버거 세트'], + notices: ['현재 경매 진행 중인 테스트 매치입니다.'], + schedule: [ + { time: '19:30', label: '디스코드 집합' }, + { time: '19:45', label: '경매 시작' }, + ], + }, + { + _id: finishedMatchId, + communityId, + hostUserId: ownerUserId, + title: '시즌 4 준결승', + description: '완료된 매치 UI 확인용 더미 경기 결과입니다.', + mapId: 11, + status: 'finished', + scheduledAt: new Date('2026-04-20T11:00:00.000Z'), + maxParticipants: 10, + participants: players.map(toMatchParticipant), + teams: [ + { + teamIndex: 1, + name: '1팀', + captainUserId: players[0]._id, + members: finishedBlue.map((member) => ({ + userId: member.user._id, + assignedPosition: member.assignedPosition, + cost: member.cost, + })), + }, + { + teamIndex: 2, + name: '2팀', + captainUserId: players[1]._id, + members: finishedRed.map((member) => ({ + userId: member.user._id, + assignedPosition: member.assignedPosition, + cost: member.cost, + })), + }, + ], + result: { + winnerTeamIndex: 1, + mvpUserId: players[0]._id, + riotMatchIds: ['KR_DEV_0001', 'KR_DEV_0002', 'KR_DEV_0003'], + seriesResults: [ + { + teamAIndex: 1, + teamBIndex: 2, + teamAWins: 2, + teamBWins: 1, + winnerTeamIndex: 1, + }, + ], + }, + prizes: ['1등 팀: RP 10,000 지급', 'MVP: 프리리'], + notices: [], + schedule: [], + }, + ]); + + const auctionOrder = auctionPlayers.slice(2).map((player) => { + const primary = player.riotAccounts[0]; + + return { + userId: player._id, + puuid: primary.puuid, + gameName: primary.gameName, + tagLine: primary.tagLine, + profileIconId: primary.profileIconId, + preferredPositions: player.preferredPositions, + tiers: primary.tiers, + masteries: primary.championMasteries, + recentStatsSummary: primary.recentStatsSummary, + }; + }); + + await AuctionModel.create({ + matchId: auctionMatchId, + phase: 'presenting', + teams: [ + { + teamIndex: 1, + captainUserId: players[0]._id, + points: 1000, + members: [], + }, + { + teamIndex: 2, + captainUserId: players[1]._id, + points: 1000, + members: [], + }, + ], + order: auctionOrder, + currentIndex: 0, + bids: [], + currentBid: 0, + maxTimerSeconds: 30, + initialPoints: 1000, + startedAt: NOW, + }); + + const summary = { + communityId: communityId.toString(), + ownerUserId: ownerUserId.toString(), + adminUserId: adminUserId.toString(), + recruitingMatchId: recruitingMatchId.toString(), + auctionMatchId: auctionMatchId.toString(), + finishedMatchId: finishedMatchId.toString(), + playerUserIds: players.map((player) => ({ + userId: player._id.toString(), + gameName: player.riotAccounts[0].gameName, + })), + }; + + console.log('\n[seed:dev] Dev seed completed.\n'); + console.log(JSON.stringify(summary, null, 2)); + console.log( + `\napps/web/.env.development 에 아래 값을 넣으면 됩니다:\nVITE_DEFAULT_COMMUNITY_ID=${summary.communityId}\n`, + ); + } finally { + await app.close(); + } +} + +void main().catch((error: unknown) => { + console.error('\n[seed:dev] Failed to seed database.\n'); + console.error(error); + process.exitCode = 1; +});