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, resolveMongoDbName } from '../connection.service'; import type { Community, MatchGameResult, MatchParticipant, MatchSeriesResult, MatchTeam, Position, PositionPreference, TeamSide, TierInfo, } from '../schema'; import { SecretModule } from '../../secret/secret.module'; const TEMP_JOB_ID = 'temp-finished-30-players-6-teams'; const TEAM_COUNT = 6; const TEAM_SIZE = 5; const TOTAL_PLAYERS = TEAM_COUNT * TEAM_SIZE; const GAME_COUNT_PER_SERIES_GROUP = 5; const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; const CHAMPION_IDS = [ 266, 64, 103, 222, 412, 24, 421, 134, 145, 497, 58, 121, 777, 202, 111, 39, 120, 7, 81, 89, 114, 104, 157, 51, 432, 92, 234, 61, 21, 53, ]; interface CliOptions { communityId?: string; dryRun: boolean; nodeEnv: string; replace: boolean; scheduledAt: Date; title: string; } interface TempPlayer { userId: mongoose.Types.ObjectId; puuid: string; gameName: string; tagLine: string; profileIconId: number; tier: TierInfo; preferredPositions: PositionPreference[]; } interface CommunityLean { _id: mongoose.Types.ObjectId; name?: string; } @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, envFilePath: [ resolve(__dirname, '../../../../../../project.env'), resolve(process.cwd(), '../project.env'), resolve(process.cwd(), 'apps/project.env'), resolve(process.cwd(), 'project.env'), ], }), SecretModule, ], providers: [ConnectionService], }) class TempSeedModule {} 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; process.env[key] = rawValue.replace(/^["']|["']$/g, ''); } } catch { // 로컬 machine env 파일이 없으면 그냥 지나간다. } } function parseArgs(argv: string[]): CliOptions { let communityId = process.env.VITE_DEFAULT_COMMUNITY_ID ?? process.env.DEFAULT_COMMUNITY_ID; let dryRun = false; let nodeEnv = process.env.NODE_ENV ?? 'dev'; let replace = false; let scheduledAt = new Date(Date.now() - 24 * 60 * 60 * 1000); let title = `결과 검증 임시 내전 30인 6팀 ${formatStamp(new Date())}`; for (let index = 0; index < argv.length; index += 1) { const arg = argv[index]; if (arg === '--community-id') { const value = argv[index + 1]; if (!value) throw new Error('--community-id requires an ObjectId.'); communityId = value; index += 1; continue; } if (arg.startsWith('--community-id=')) { communityId = arg.slice('--community-id='.length); continue; } if (arg === '--dry-run') { dryRun = true; continue; } if (arg === '--env') { const value = argv[index + 1]; if (!value) throw new Error('--env requires dev, staging, or prod.'); nodeEnv = value; index += 1; continue; } if (arg.startsWith('--env=')) { nodeEnv = arg.slice('--env='.length); continue; } if (arg === '--replace') { replace = true; continue; } if (arg === '--scheduled-at') { scheduledAt = parseDateArg(argv[index + 1], '--scheduled-at'); index += 1; continue; } if (arg.startsWith('--scheduled-at=')) { scheduledAt = parseDateArg( arg.slice('--scheduled-at='.length), '--scheduled-at', ); continue; } if (arg === '--title') { const value = argv[index + 1]; if (!value) throw new Error('--title requires a value.'); title = value; index += 1; continue; } if (arg.startsWith('--title=')) { title = arg.slice('--title='.length); continue; } if (arg === '--help' || arg === '-h') { printHelp(); process.exit(0); } throw new Error(`Unknown argument: ${arg}`); } if (!['dev', 'staging', 'prod'].includes(nodeEnv)) { throw new Error('--env must be dev, staging, or prod.'); } if (communityId && !mongoose.isValidObjectId(communityId)) { throw new Error('--community-id must be a valid ObjectId.'); } return { communityId: communityId?.trim() || undefined, dryRun, nodeEnv, replace, scheduledAt, title, }; } function parseDateArg(value: string | undefined, label: string): Date { if (!value) throw new Error(`${label} requires an ISO date value.`); const parsed = new Date(value); if (Number.isNaN(parsed.getTime())) { throw new Error(`${label} must be a valid ISO date value.`); } return parsed; } function printHelp() { console.log(`Usage: pnpm --filter api exec ts-node src/modules/global/database/dev-seeds/create-temp-finished-match.ts pnpm --filter api exec ts-node src/modules/global/database/dev-seeds/create-temp-finished-match.ts --replace Options: --community-id Community ObjectId. Defaults to env or first community. --dry-run Print the payload summary without writing. --env dev | staging | prod. Default: NODE_ENV or dev. --replace Delete previous temp matches created by this script first. --scheduled-at Scheduled date. Default: yesterday. --title Match title. Default: timestamped temp title. `); } async function main() { const options = parseArgs(process.argv.slice(2)); process.env.NODE_ENV = options.nodeEnv; await loadMachineEnvFile(); const app = await NestFactory.createApplicationContext(TempSeedModule, { logger: ['log', 'warn', 'error'], }); try { const connectionService = app.get(ConnectionService); const CommunityModel = await connectionService.getModel('community'); const MatchModel = await connectionService.getModel('match'); const community = await resolveCommunity( CommunityModel, options.communityId, ); const payload = buildMatchPayload(community._id, options); console.log( `[temp result seed] mode=${options.dryRun ? 'dry-run' : 'apply'} env=${options.nodeEnv} db=${resolveMongoDbName(options.nodeEnv)}`, ); console.log( `[temp result seed] community=${community.name ?? '(unnamed)'} (${community._id.toString()})`, ); console.log( `[temp result seed] title="${options.title}" participants=${payload.participants.length} teams=${payload.teams.length} games=${payload.result.games.length}`, ); if (options.dryRun) { console.log('[temp result seed] No writes were made.'); return; } if (options.replace) { const deleteResult = await MatchModel.deleteMany({ communityId: community._id, 'legacyImportSource.jobId': TEMP_JOB_ID, }).exec(); console.log( `[temp result seed] deleted=${deleteResult.deletedCount ?? 0}`, ); } const matchId = new mongoose.Types.ObjectId(); await MatchModel.create({ ...payload, _id: matchId }); console.log(`[temp result seed] created=${matchId.toString()}`); console.log(`[temp result seed] route=/match/${matchId.toString()}`); } finally { await app.close(); } } async function resolveCommunity( CommunityModel: mongoose.Model<Community>, communityId?: string, ): Promise<CommunityLean> { const community = communityId ? await CommunityModel.findById(communityId) .select({ name: 1 }) .lean<CommunityLean>() .exec() : await CommunityModel.findOne() .sort({ createdAt: 1 }) .select({ name: 1 }) .lean<CommunityLean>() .exec(); if (!community) { throw new Error( communityId ? `Community not found: ${communityId}` : 'No community found. Pass --community-id.', ); } return community; } function buildMatchPayload( communityId: mongoose.Types.ObjectId, options: CliOptions, ) { const now = new Date(); const players = buildPlayers(now); const participants = players.map( (player, index): MatchParticipant => ({ userId: player.userId, puuid: player.puuid, gameName: player.gameName, tagLine: player.tagLine, profileIconId: player.profileIconId, tier: player.tier, preferredPositions: player.preferredPositions, joinedAt: new Date( options.scheduledAt.getTime() - (TOTAL_PLAYERS - index) * 60000, ), excluded: false, }), ); const teams = buildTeams(players); const games = buildGames(players, options.scheduledAt); const seriesResults = buildSeriesResults(games); const winnerTeamIndex = resolveOverallWinner(seriesResults); return { communityId, title: options.title, description: '결과 페이지 검증용으로 생성된 30명, 6팀, 15경기 완료 임시 데이터입니다.', mapId: 11, status: 'finished' as const, scheduledAt: options.scheduledAt, maxParticipants: TOTAL_PLAYERS, gameCount: GAME_COUNT_PER_SERIES_GROUP, gameMode: 'round-robin' as const, tournamentCodeIds: [], teamBuiltAt: new Date(options.scheduledAt.getTime() - 30 * 60000), participants, teams, result: { winnerTeamIndex, mvpUserId: players[0].userId, riotMatchIds: games.map((game) => game.riotMatchId), games, seriesResults, }, resultPollState: { startedAt: new Date(options.scheduledAt.getTime() + 2 * 60 * 60 * 1000), lastPolledAt: now, lastPollOutcome: 'matched' as const, matchedCount: games.length, expandedToAllPuuids: true, state: 'complete' as const, }, legacyImported: true, legacyImportSource: { importedAt: now, importedBy: players[0].userId, triggeringPuuid: players[0].puuid, jobId: TEMP_JOB_ID, }, prizes: ['1등 팀: 결과 화면 검증용 임시 상품', 'MVP: Temp01'], notices: ['이 매치는 UI 검증용 임시 데이터입니다.'], schedule: [ { time: '20:00', label: '로비 오픈' }, { time: '20:10', label: '1경기 시작' }, { time: '23:30', label: '풀리그 종료' }, ], }; } function buildPlayers(now: Date): TempPlayer[] { return Array.from({ length: TOTAL_PLAYERS }, (_, index) => { const playerNumber = index + 1; const primaryPosition = POSITIONS[index % POSITIONS.length]; return { userId: new mongoose.Types.ObjectId(), puuid: `temp-result-puuid-${playerNumber.toString().padStart(2, '0')}`, gameName: `Temp${playerNumber.toString().padStart(2, '0')}`, tagLine: `T${playerNumber.toString().padStart(3, '0')}`, profileIconId: 20 + playerNumber, tier: buildTier(playerNumber, now), preferredPositions: buildPreferredPositions(primaryPosition), }; }); } function buildPreferredPositions( primaryPosition: Position, ): PositionPreference[] { const ordered = [ primaryPosition, ...POSITIONS.filter((position) => position !== primaryPosition), ]; return ordered.map((position, index) => ({ position, priority: index + 1, })); } function buildTier(playerNumber: number, fetchedAt: Date): TierInfo { const tiers = [ ['CHALLENGER', 'I'], ['GRANDMASTER', 'I'], ['MASTER', 'I'], ['DIAMOND', 'I'], ['DIAMOND', 'II'], ['EMERALD', 'I'], ['EMERALD', 'II'], ['PLATINUM', 'I'], ['PLATINUM', 'II'], ['GOLD', 'I'], ] as const; const [tier, rank] = tiers[(playerNumber - 1) % tiers.length]; return { queueType: 'RANKED_SOLO_5x5', tier, rank, leaguePoints: (playerNumber * 17) % 100, wins: 40 + playerNumber, losses: 22 + (playerNumber % 13), fetchedAt, }; } function buildTeams(players: TempPlayer[]): MatchTeam[] { return Array.from({ length: TEAM_COUNT }, (_, teamOffset) => { const teamIndex = teamOffset + 1; const members = players .slice(teamOffset * TEAM_SIZE, (teamOffset + 1) * TEAM_SIZE) .map((player, memberOffset) => ({ userId: player.userId, assignedPosition: POSITIONS[memberOffset], cost: memberOffset === 0 ? 0 : 80 + teamIndex * 15 + memberOffset * 20, })); return { teamIndex, name: `${teamIndex}팀`, captainUserId: members[0]?.userId, members, }; }); } function buildGames( players: TempPlayer[], scheduledAt: Date, ): MatchGameResult[] { const games: MatchGameResult[] = []; const playersByTeam = new Map<number, TempPlayer[]>(); for (let teamIndex = 1; teamIndex <= TEAM_COUNT; teamIndex += 1) { playersByTeam.set( teamIndex, players.slice((teamIndex - 1) * TEAM_SIZE, teamIndex * TEAM_SIZE), ); } for (let teamAIndex = 1; teamAIndex <= TEAM_COUNT; teamAIndex += 1) { for ( let teamBIndex = teamAIndex + 1; teamBIndex <= TEAM_COUNT; teamBIndex += 1 ) { const gameNumber = games.length + 1; const lowerTeamStartsBlue = gameNumber % 2 === 1; const blueTeamIndex = lowerTeamStartsBlue ? teamAIndex : teamBIndex; const redTeamIndex = lowerTeamStartsBlue ? teamBIndex : teamAIndex; const winnerTeamIndex = teamAIndex; const winnerSide: TeamSide = winnerTeamIndex === blueTeamIndex ? 'blue' : 'red'; const gameCreation = scheduledAt.getTime() + gameNumber * 20 * 60 * 1000; const riotMatchId = `KR_TEMP_30X6_${formatStamp(scheduledAt)}_${gameNumber .toString() .padStart(2, '0')}`; games.push({ gameNumber, riotMatchId, blueTeamIndex, redTeamIndex, winnerTeamIndex, winnerSide, gameCreation, gameDuration: 1650 + gameNumber * 23, participants: [ ...buildGameParticipants({ players: playersByTeam.get(blueTeamIndex) ?? [], teamIndex: blueTeamIndex, side: 'blue', winnerTeamIndex, gameNumber, }), ...buildGameParticipants({ players: playersByTeam.get(redTeamIndex) ?? [], teamIndex: redTeamIndex, side: 'red', winnerTeamIndex, gameNumber, }), ], }); } } return games; } function buildGameParticipants(params: { players: TempPlayer[]; teamIndex: number; side: TeamSide; winnerTeamIndex: number; gameNumber: number; }): MatchGameResult['participants'] { const didWin = params.teamIndex === params.winnerTeamIndex; return params.players.map((player, index) => { const championIndex = (params.gameNumber + params.teamIndex + index) % CHAMPION_IDS.length; return { userId: player.userId, teamIndex: params.teamIndex, side: params.side, championId: CHAMPION_IDS[championIndex], kills: didWin ? 4 + ((params.gameNumber + index) % 8) : 1 + ((params.gameNumber + index) % 5), deaths: didWin ? 1 + (index % 4) : 4 + ((params.gameNumber + index) % 7), assists: didWin ? 7 + ((params.gameNumber + index) % 12) : 3 + ((params.gameNumber + index) % 8), win: didWin, }; }); } function buildSeriesResults(games: MatchGameResult[]): MatchSeriesResult[] { return games.map((game) => { const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); return { teamAIndex, teamBIndex, teamAWins: game.winnerTeamIndex === teamAIndex ? 1 : 0, teamBWins: game.winnerTeamIndex === teamBIndex ? 1 : 0, winnerTeamIndex: game.winnerTeamIndex, }; }); } function resolveOverallWinner( seriesResults: MatchSeriesResult[], ): number | undefined { const winsByTeam = new Map<number, number>(); for (const series of seriesResults) { if (!series.winnerTeamIndex) continue; winsByTeam.set( series.winnerTeamIndex, (winsByTeam.get(series.winnerTeamIndex) ?? 0) + 1, ); } return [...winsByTeam.entries()].sort( (left, right) => right[1] - left[1], )[0]?.[0]; } function formatStamp(date: Date): string { const year = date.getFullYear(); const month = `${date.getMonth() + 1}`.padStart(2, '0'); const day = `${date.getDate()}`.padStart(2, '0'); const hours = `${date.getHours()}`.padStart(2, '0'); const minutes = `${date.getMinutes()}`.padStart(2, '0'); const seconds = `${date.getSeconds()}`.padStart(2, '0'); return `${year}${month}${day}-${hours}${minutes}${seconds}`; } void main().catch((error: unknown) => { console.error(error instanceof Error ? error.message : error); process.exitCode = 1; });