diff --git a/apps/api/package.json b/apps/api/package.json index 4f579fa5..a5a271ab 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -9,6 +9,7 @@ "build": "nest build", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "seed:dev": "ts-node src/seed.ts", + "seed:dakao-participant": "ts-node src/seed-dakao-participant.ts", "start:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); \"./start.ps1\"\"", "start:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); \"./start.ps1\"\"", "start:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); \"./start.ps1\"\"", diff --git a/apps/api/src/modules/dakao/handlers/match-join.handler.ts b/apps/api/src/modules/dakao/handlers/match-join.handler.ts index 73f47a31..8e6bcab2 100644 --- a/apps/api/src/modules/dakao/handlers/match-join.handler.ts +++ b/apps/api/src/modules/dakao/handlers/match-join.handler.ts @@ -1,4 +1,8 @@ -import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; +import { + BadRequestException, + Injectable, + NotFoundException, +} from '@nestjs/common'; import mongoose from 'mongoose'; import { MatchService } from '../../match/match.service'; import { Position, PositionPreference } from '../../global/database/schema'; @@ -24,7 +28,7 @@ export class MatchJoinHandler { public async handle(params: JoinHandlerParams): Promise { if (!mongoose.isValidObjectId(params.matchId)) { - return this.errorReply(params, '유효하지 않은 매치 ID 입니다.'); + return this.errorReply(params, '유효하지 않은 내전 ID 입니다.'); } const matchObjectId = new mongoose.Types.ObjectId(params.matchId); @@ -66,14 +70,14 @@ export class MatchJoinHandler { kind: 'text', text: ` 신청 완료 (${match.participants.length}/${match.maxParticipants})` + - `\n매치: ${match.title}` + + `\n내전: ${match.title}` + `\n계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}` + `\n포지션: ${params.positions.join(', ')}`, }, ]; } catch (err) { if (err instanceof NotFoundException) { - return this.errorReply(params, '매치를 찾을 수 없습니다.'); + return this.errorReply(params, '내전을 찾을 수 없습니다.'); } if (err instanceof BadRequestException) { return this.errorReply(params, this.translateBadRequest(err.message)); @@ -113,10 +117,10 @@ export class MatchJoinHandler { private translateBadRequest(raw: string): string { if (raw.includes('different communities')) - return '이 매치는 현재 채팅방의 커뮤니티 소속이 아닙니다.'; - if (raw.includes('not recruiting')) return '모집 중인 매치가 아닙니다.'; + return '이 내전은 현재 채팅방의 커뮤니티 소속이 아닙니다.'; + if (raw.includes('not recruiting')) return '모집 중인 내전이 아닙니다.'; if (raw.includes('full')) return '정원이 가득 찼습니다.'; - if (raw.includes('already joined')) return '이미 신청한 매치입니다.'; + if (raw.includes('already joined')) return '이미 신청한 내전입니다.'; return raw; } } diff --git a/apps/api/src/modules/dakao/handlers/match-list.handler.ts b/apps/api/src/modules/dakao/handlers/match-list.handler.ts index 57a3bb23..6bf6ad9b 100644 --- a/apps/api/src/modules/dakao/handlers/match-list.handler.ts +++ b/apps/api/src/modules/dakao/handlers/match-list.handler.ts @@ -45,7 +45,7 @@ export class MatchListHandler { }, { kind: 'text', - text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n신청: !내전 신청 <게임명>#<태그> <포지션1>,<포지션2>`, + text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n신청: !내전 신청 <닉네임>#<태그> <포지션1>,<포지션2>`, }, ]; } diff --git a/apps/api/src/seed-dakao-participant.ts b/apps/api/src/seed-dakao-participant.ts new file mode 100644 index 00000000..f66befa7 --- /dev/null +++ b/apps/api/src/seed-dakao-participant.ts @@ -0,0 +1,241 @@ +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 { SecretModule } from './modules/global/secret/secret.module'; +import { MatchService } from './modules/match/match.service'; +import { DakaoUserService } from './modules/dakao/dakao-user.service'; +import { parsePositionList } from './modules/dakao/parsers/position.parser'; +import { normalizeRiotIdPart } from './modules/dakao/riot-id.util'; +import { RiotAccountEnrichmentService } from './modules/riot/riot-account-enrichment.service'; +import { RiotAccountService } from './modules/riot/riot-account.service'; +import { RiotChampionMasteryService } from './modules/riot/riot-champion-mastery.service'; +import { RiotClientService } from './modules/riot/riot.client.service'; +import { RiotLeagueService } from './modules/riot/riot-league.service'; +import { RiotSummonerService } from './modules/riot/riot-summoner.service'; + +process.env.NODE_ENV ??= 'dev'; + +const DEFAULT_INPUT = { + projectId: '69985467365c75936c355318', + matchId: '69ebe0adf627c11be2f020bb', + senderId: '6657856481076543434', + nickname: '집밖은 위험해/92/여/P', + riotId: '집밖은 위험해#SOS', + positions: 'SUP,MID', +}; + +@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, + RiotClientService, + RiotAccountService, + RiotSummonerService, + RiotLeagueService, + RiotChampionMasteryService, + RiotAccountEnrichmentService, + DakaoUserService, + MatchService, + ], +}) +class SeedDakaoParticipantModule {} + +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 { + // start.ps1과 동일하게 로컬 machine env 파일이 없으면 무시한다. + } +} + +function readInput() { + const riotId = process.env.DAKAO_SEED_RIOT_ID ?? DEFAULT_INPUT.riotId; + const hashIndex = riotId.lastIndexOf('#'); + if (hashIndex <= 0 || hashIndex === riotId.length - 1) { + throw new Error(`Invalid Riot ID: ${riotId}`); + } + + return { + projectId: process.env.DAKAO_SEED_PROJECT_ID ?? DEFAULT_INPUT.projectId, + matchId: process.env.DAKAO_SEED_MATCH_ID ?? DEFAULT_INPUT.matchId, + senderId: process.env.DAKAO_SEED_SENDER_ID ?? DEFAULT_INPUT.senderId, + nickname: process.env.DAKAO_SEED_NICKNAME ?? DEFAULT_INPUT.nickname, + gameName: normalizeRiotIdPart(riotId.slice(0, hashIndex)), + tagLine: normalizeRiotIdPart(riotId.slice(hashIndex + 1)), + positions: parsePositionList( + process.env.DAKAO_SEED_POSITIONS ?? DEFAULT_INPUT.positions, + ).positions, + }; +} + +async function ensureCommunityDakaoProjectId(params: { + connectionService: ConnectionService; + matchId: mongoose.Types.ObjectId; + projectId: mongoose.Types.ObjectId; +}): Promise { + const MatchModel = await params.connectionService.getModel('match'); + const CommunityModel = await params.connectionService.getModel('community'); + const match = await MatchModel.findById(params.matchId).exec(); + if (!match) { + throw new Error(`Match not found: ${params.matchId.toString()}`); + } + + const community = await CommunityModel.findById(match.communityId).exec(); + if (!community) { + throw new Error(`Community not found: ${match.communityId.toString()}`); + } + + if (community.dakaoProjectId?.equals(params.projectId)) { + return community._id; + } + if (community.dakaoProjectId) { + throw new Error( + `Community already has a different dakaoProjectId: ${community.dakaoProjectId.toString()}`, + ); + } + + const conflictingCommunity = await CommunityModel.findOne({ + _id: { $ne: community._id }, + dakaoProjectId: params.projectId, + }).exec(); + if (conflictingCommunity) { + throw new Error( + `dakaoProjectId already belongs to another community: ${conflictingCommunity._id.toString()}`, + ); + } + + community.dakaoProjectId = params.projectId; + await community.save(); + return community._id; +} + +async function main() { + await loadMachineEnvFile(); + + const input = readInput(); + if (!mongoose.isValidObjectId(input.projectId)) { + throw new Error(`Invalid projectId: ${input.projectId}`); + } + if (!mongoose.isValidObjectId(input.matchId)) { + throw new Error(`Invalid matchId: ${input.matchId}`); + } + + const app = await NestFactory.createApplicationContext( + SeedDakaoParticipantModule, + { logger: ['error', 'warn', 'log'] }, + ); + + try { + const connectionService = app.get(ConnectionService); + const dakaoUserService = app.get(DakaoUserService); + const matchService = app.get(MatchService); + const MatchModel = await connectionService.getModel('match'); + + const matchId = new mongoose.Types.ObjectId(input.matchId); + const projectId = new mongoose.Types.ObjectId(input.projectId); + const communityId = await ensureCommunityDakaoProjectId({ + connectionService, + matchId, + projectId, + }); + + const resolved = await dakaoUserService.resolveRiotAccount({ + communityId, + kakaoTalkId: input.senderId, + kakaoTalkNickname: input.nickname, + gameName: input.gameName, + tagLine: input.tagLine, + }); + + const existing = await MatchModel.findOne({ + _id: matchId, + 'participants.userId': resolved.user._id, + }).exec(); + if (existing) { + console.log('[seed:dakao-participant] Participant already exists.'); + console.log( + JSON.stringify( + { + communityId: communityId.toString(), + matchId: matchId.toString(), + userId: resolved.user._id.toString(), + puuid: resolved.riotAccount.puuid, + riotId: `${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`, + }, + null, + 2, + ), + ); + return; + } + + const preferredPositions = input.positions.map((position, index) => ({ + position, + priority: index + 1, + })); + + const match = await matchService.join({ + matchId, + userId: resolved.user._id, + riotPuuid: resolved.riotAccount.puuid, + preferredPositions, + }); + + console.log('[seed:dakao-participant] Participant added.'); + console.log( + JSON.stringify( + { + communityId: communityId.toString(), + matchId: match._id.toString(), + userId: resolved.user._id.toString(), + kakaoTalkId: input.senderId, + kakaoTalkNickname: input.nickname, + puuid: resolved.riotAccount.puuid, + riotId: `${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`, + preferredPositions, + participantCount: match.participants.length, + }, + null, + 2, + ), + ); + } finally { + await app.close(); + } +} + +void main().catch((error: unknown) => { + console.error('\n[seed:dakao-participant] Failed.\n'); + console.error(error); + process.exitCode = 1; +}); diff --git a/apps/web/.env.production b/apps/web/.env.production index c35c549b..b25a5200 100644 --- a/apps/web/.env.production +++ b/apps/web/.env.production @@ -3,5 +3,5 @@ VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1 VITE_MSAL_CLIENT_ID=15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3 VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863 VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev -VITE_MSAL_REDIRECT_URI=http://localhost:5173/auth/callback +VITE_MSAL_REDIRECT_URI=https://lolympus.dahyeon.us/auth/callback diff --git a/apps/web/src/pages/Login.tsx b/apps/web/src/pages/Login.tsx index 9ff01c8c..7f7e639c 100644 --- a/apps/web/src/pages/Login.tsx +++ b/apps/web/src/pages/Login.tsx @@ -1,9 +1,9 @@ -import { useMsal } from '@azure/msal-react'; +import { useMsal } from "@azure/msal-react"; import { isMsalConfigured, MSAL_API_SCOPE, msalInstance, -} from '../lib/auth/msal.config'; +} from "../lib/auth/msal.config"; function LoginButton() { const { instance } = useMsal(); @@ -12,7 +12,12 @@ function LoginButton() {