diff --git a/apps/api/src/modules/dakao/handlers/account-register.handler.spec.ts b/apps/api/src/modules/dakao/handlers/account-register.handler.spec.ts new file mode 100644 index 00000000..133b49b4 --- /dev/null +++ b/apps/api/src/modules/dakao/handlers/account-register.handler.spec.ts @@ -0,0 +1,73 @@ +import mongoose from 'mongoose'; +import { DakaoUserError, DakaoUserService } from '../dakao-user.service'; +import { AccountRegisterHandler } from './account-register.handler'; + +const objectId = (hex: string) => new mongoose.Types.ObjectId(hex); + +function makeHandler(dakaoUserService?: Partial) { + return new AccountRegisterHandler({ + registerRiotAccount: jest.fn(), + ...dakaoUserService, + } as unknown as DakaoUserService); +} + +const baseParams = { + communityId: objectId('111111111111111111111111'), + senderUserId: 'kakao-user-1', + senderNickname: '프리리', + gameName: '프리리', + tagLine: 'KR1', +}; + +describe('AccountRegisterHandler', () => { + it('registers a Riot account through DakaoUserService', async () => { + const registerRiotAccount = jest.fn().mockResolvedValue({ + user: { _id: objectId('222222222222222222222222') }, + riotAccount: { gameName: '프리리', tagLine: 'KR1' }, + }); + const handler = makeHandler({ + registerRiotAccount, + }); + + const segments = await handler.handle(baseParams); + + expect(registerRiotAccount).toHaveBeenCalledWith({ + communityId: baseParams.communityId, + kakaoTalkId: 'kakao-user-1', + kakaoTalkNickname: '프리리', + gameName: '프리리', + tagLine: 'KR1', + }); + expect(segments).toEqual([ + expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }), + expect.objectContaining({ + kind: 'text', + text: expect.stringContaining('등록 계정: 프리리#KR1'), + }), + ]); + }); + + it('translates Riot account conflict errors', async () => { + const handler = makeHandler({ + registerRiotAccount: jest + .fn() + .mockRejectedValue( + new DakaoUserError('riot_account_conflict', '기존소환사#KR1'), + ), + }); + + const segments = await handler.handle(baseParams); + + expect(segments).toEqual([ + expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }), + expect.objectContaining({ + kind: 'text', + text: expect.stringContaining('이미 다른 사용자가 등록한 라이엇 계정'), + }), + ]); + expect(segments[1]).toMatchObject({ + kind: 'text', + text: expect.stringContaining('기존소환사#KR1'), + }); + }); +}); diff --git a/apps/api/src/modules/dakao/handlers/account-register.handler.ts b/apps/api/src/modules/dakao/handlers/account-register.handler.ts new file mode 100644 index 00000000..4250ba64 --- /dev/null +++ b/apps/api/src/modules/dakao/handlers/account-register.handler.ts @@ -0,0 +1,81 @@ +import { Injectable } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { DakaoSegment } from '../dakao.types'; +import { DakaoUserError, DakaoUserService } from '../dakao-user.service'; + +interface AccountRegisterHandlerParams { + communityId: mongoose.Types.ObjectId; + senderUserId: string; + senderNickname: string; + gameName: string; + tagLine: string; +} + +@Injectable() +export class AccountRegisterHandler { + constructor(private readonly dakaoUserService: DakaoUserService) {} + + public async handle( + params: AccountRegisterHandlerParams, + ): Promise { + try { + const resolved = await this.dakaoUserService.registerRiotAccount({ + communityId: params.communityId, + kakaoTalkId: params.senderUserId, + kakaoTalkNickname: params.senderNickname, + gameName: params.gameName, + tagLine: params.tagLine, + }); + + return [ + { + kind: 'mention', + userId: params.senderUserId, + displayText: params.senderNickname, + }, + { + kind: 'text', + text: + ` 계정 등록 완료` + + `\n등록 계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`, + }, + ]; + } catch (err) { + if (err instanceof DakaoUserError) { + return this.errorReply(params, this.translateUserError(err)); + } + throw err; + } + } + + private errorReply( + params: AccountRegisterHandlerParams, + message: string, + ): DakaoSegment[] { + return [ + { + kind: 'mention', + userId: params.senderUserId, + displayText: params.senderNickname, + }, + { kind: 'text', text: ` ${message}` }, + ]; + } + + private translateUserError(err: DakaoUserError): string { + switch (err.code) { + case 'invalid_project_id': + return '커뮤니티 식별자가 올바르지 않습니다.'; + case 'community_not_found': + return '연결된 커뮤니티를 찾을 수 없습니다.'; + case 'riot_account_not_found': + return `라이엇 계정을 찾을 수 없습니다 (${err.detail ?? ''}).`; + case 'riot_account_already_registered': + return `이미 등록된 라이엇 계정이 있습니다 (${err.detail ?? ''}). 변경이 필요하면 운영자에게 문의해주세요.`; + case 'riot_account_conflict': + return `이미 다른 사용자가 등록한 라이엇 계정입니다 (${err.detail ?? ''}).`; + case 'riot_account_lookup_failed': + return '라이엇 계정 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.'; + } + } +} diff --git a/apps/api/src/modules/dakao/handlers/preferred-position-register.handler.spec.ts b/apps/api/src/modules/dakao/handlers/preferred-position-register.handler.spec.ts new file mode 100644 index 00000000..d069f981 --- /dev/null +++ b/apps/api/src/modules/dakao/handlers/preferred-position-register.handler.spec.ts @@ -0,0 +1,41 @@ +import mongoose from 'mongoose'; +import { DakaoUserService } from '../dakao-user.service'; +import { PreferredPositionRegisterHandler } from './preferred-position-register.handler'; + +const objectId = (hex: string) => new mongoose.Types.ObjectId(hex); + +describe('PreferredPositionRegisterHandler', () => { + it('registers preferred positions for abbreviated joins', async () => { + const registerPreferredPositions = jest.fn().mockResolvedValue({ + preferredPositions: [ + { position: 'MID', priority: 1 }, + { position: 'JGL', priority: 2 }, + ], + }); + const handler = new PreferredPositionRegisterHandler({ + registerPreferredPositions, + } as unknown as DakaoUserService); + + const segments = await handler.handle({ + communityId: objectId('111111111111111111111111'), + senderUserId: 'kakao-user-1', + senderNickname: '프리리', + positions: ['MID', 'JGL'], + }); + + expect(registerPreferredPositions).toHaveBeenCalledWith({ + communityId: objectId('111111111111111111111111'), + kakaoTalkId: 'kakao-user-1', + kakaoTalkNickname: '프리리', + positions: ['MID', 'JGL'], + }); + expect(segments[1]).toMatchObject({ + kind: 'text', + text: expect.stringContaining('선호 포지션 등록 완료'), + }); + expect(segments[1]).toMatchObject({ + kind: 'text', + text: expect.stringContaining('!내전 신청 <내전코드>'), + }); + }); +}); diff --git a/apps/api/src/modules/dakao/handlers/preferred-position-register.handler.ts b/apps/api/src/modules/dakao/handlers/preferred-position-register.handler.ts new file mode 100644 index 00000000..5c2d67ed --- /dev/null +++ b/apps/api/src/modules/dakao/handlers/preferred-position-register.handler.ts @@ -0,0 +1,54 @@ +import { Injectable } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { Position } from '../../global/database/schema'; +import { DakaoSegment } from '../dakao.types'; +import { DakaoUserService } from '../dakao-user.service'; + +const POSITION_LABELS: Record = { + TOP: '탑', + JGL: '정글', + MID: '미드', + ADC: '원딜', + SUP: '서포터', +}; + +interface PreferredPositionRegisterHandlerParams { + communityId: mongoose.Types.ObjectId; + senderUserId: string; + senderNickname: string; + positions: Position[]; +} + +@Injectable() +export class PreferredPositionRegisterHandler { + constructor(private readonly dakaoUserService: DakaoUserService) {} + + public async handle( + params: PreferredPositionRegisterHandlerParams, + ): Promise { + const user = await this.dakaoUserService.registerPreferredPositions({ + communityId: params.communityId, + kakaoTalkId: params.senderUserId, + kakaoTalkNickname: params.senderNickname, + positions: params.positions, + }); + + return [ + { + kind: 'mention', + userId: params.senderUserId, + displayText: params.senderNickname, + }, + { + kind: 'text', + text: + ` 선호 포지션 등록 완료` + + `\n포지션: ${user.preferredPositions + .sort((left, right) => left.priority - right.priority) + .map((entry) => POSITION_LABELS[entry.position]) + .join(', ')}` + + `\n이제 !내전 신청 <내전코드> 로 간단히 신청할 수 있습니다.`, + }, + ]; + } +} diff --git a/apps/api/src/seed-dakao-participant.ts b/apps/api/src/seed-dakao-participant.ts new file mode 100644 index 00000000..fe0d669e --- /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 { + // 로컬 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/scripts/add-manual-dakao-riot-user.js b/scripts/add-manual-dakao-riot-user.js new file mode 100644 index 00000000..df6c916a --- /dev/null +++ b/scripts/add-manual-dakao-riot-user.js @@ -0,0 +1,406 @@ +/** + * Add or update one lolympus user manually from Kakao + Riot identity. + * + * This is for the last few users that need manual handling. + * + * Install: + * npm install mongodb + * + * Dry-run with Riot API enrichment: + * MONGODB_URI="mongodb://..." \ + * RIOT_API_KEY="RGAPI-..." \ + * KAKAO_TALK_ID="7448687768283723562" \ + * KAKAO_TALK_NICKNAME="탑은죄악이다/95/남/G" \ + * RIOT_ID="탑은죄악이다#망나니" \ + * PREFERRED_POSITIONS="TOP,JGL" \ + * node add-manual-dakao-riot-user.js + * + * Write: + * DRY_RUN=false MONGODB_URI="..." RIOT_API_KEY="..." ... node add-manual-dakao-riot-user.js + * + * Fallback without Riot API: + * PUUID="..." RIOT_ID="..." node add-manual-dakao-riot-user.js + */ + +"use strict"; + +const { MongoClient, ObjectId } = require("mongodb"); + +const CONFIG = { + MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017", + LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-test", + COMMUNITY_ID: new ObjectId( + process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1", + ), + RIOT_API_KEY: process.env.RIOT_API_KEY ?? "", + RIOT_REGION: process.env.RIOT_REGION ?? "asia", + RIOT_PLATFORM: process.env.RIOT_PLATFORM ?? "kr", + MASTERY_COUNT: Number(process.env.MASTERY_COUNT ?? 10), + RECENT_MATCH_COUNT: Number(process.env.RECENT_MATCH_COUNT ?? 20), + FETCH_RECENT_MATCH_IDS: process.env.FETCH_RECENT_MATCH_IDS !== "false", + DRY_RUN: process.env.DRY_RUN !== "false", + FAIL_ON_CONFLICT: process.env.FAIL_ON_CONFLICT !== "false", +}; + +const INPUT = { + kakaoTalkId: process.env.KAKAO_TALK_ID ?? "", + kakaoTalkNickname: process.env.KAKAO_TALK_NICKNAME ?? "", + riotId: process.env.RIOT_ID ?? "", + puuid: process.env.PUUID ?? "", + preferredPositions: process.env.PREFERRED_POSITIONS ?? "", + role: process.env.ROLE ?? "member", + isActivated: process.env.IS_ACTIVATED !== "false", +}; + +function normalizeString(value) { + return typeof value === "string" ? value.trim() : ""; +} + +function splitRiotId(riotId) { + const value = normalizeString(riotId); + const hashIndex = value.lastIndexOf("#"); + if (hashIndex <= 0 || hashIndex === value.length - 1) { + throw new Error(`Invalid RIOT_ID. Expected "gameName#tagLine": ${riotId}`); + } + return { + gameName: value.slice(0, hashIndex).trim(), + tagLine: value.slice(hashIndex + 1).trim(), + }; +} + +function normalizePositions(value) { + const allowed = new Set(["TOP", "JGL", "MID", "ADC", "SUP"]); + return normalizeString(value) + .split(",") + .map((position) => normalizeString(position).toUpperCase()) + .filter((position) => allowed.has(position)) + .map((position, index) => ({ position, priority: index + 1 })); +} + +function removeUndefined(value) { + if (Array.isArray(value)) return value.map(removeUndefined); + if ( + value && + typeof value === "object" && + !(value instanceof Date) && + !(value instanceof ObjectId) + ) { + return Object.fromEntries( + Object.entries(value) + .filter(([, entryValue]) => entryValue !== undefined) + .map(([key, entryValue]) => [key, removeUndefined(entryValue)]), + ); + } + return value; +} + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function maskConfig() { + return { + ...CONFIG, + MONGODB_URI: CONFIG.MONGODB_URI.replace(/\/\/.*@/u, "//***@"), + RIOT_API_KEY: CONFIG.RIOT_API_KEY ? "***" : "", + }; +} + +function requireInput() { + const missing = []; + if (!normalizeString(INPUT.kakaoTalkId)) missing.push("KAKAO_TALK_ID"); + if (!normalizeString(INPUT.kakaoTalkNickname)) { + missing.push("KAKAO_TALK_NICKNAME"); + } + if (!normalizeString(INPUT.riotId)) missing.push("RIOT_ID"); + if (!CONFIG.RIOT_API_KEY && !normalizeString(INPUT.puuid)) { + missing.push("RIOT_API_KEY or PUUID"); + } + if (missing.length > 0) { + throw new Error(`Missing required env: ${missing.join(", ")}`); + } +} + +async function fetchRiotJson({ host, path, query }) { + if (!CONFIG.RIOT_API_KEY) return null; + + const url = new URL(`https://${host}${path}`); + for (const [key, value] of Object.entries(query ?? {})) { + if (value !== undefined && value !== null) { + url.searchParams.set(key, String(value)); + } + } + + for (;;) { + const response = await fetch(url, { + headers: { "X-Riot-Token": CONFIG.RIOT_API_KEY }, + }); + + if (response.status === 429) { + const retryAfterSeconds = Number(response.headers.get("retry-after") ?? 1); + await sleep(Math.max(1, retryAfterSeconds) * 1000); + continue; + } + if (response.status === 404) return null; + if (!response.ok) { + const body = await response.text().catch(() => ""); + throw new Error(`Riot API failed ${response.status} ${url.pathname}: ${body}`); + } + return response.json(); + } +} + +async function fetchAccountByRiotId({ gameName, tagLine }) { + return fetchRiotJson({ + host: `${CONFIG.RIOT_REGION}.api.riotgames.com`, + path: `/riot/account/v1/accounts/by-riot-id/${encodeURIComponent(gameName)}/${encodeURIComponent(tagLine)}`, + }); +} + +async function fetchSummonerByPuuid(puuid) { + return fetchRiotJson({ + host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`, + path: `/lol/summoner/v4/summoners/by-puuid/${encodeURIComponent(puuid)}`, + }); +} + +async function fetchLeagueEntriesByPuuid(puuid) { + return fetchRiotJson({ + host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`, + path: `/lol/league/v4/entries/by-puuid/${encodeURIComponent(puuid)}`, + }); +} + +async function fetchChampionMasteriesByPuuid(puuid) { + return fetchRiotJson({ + host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`, + path: `/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}/top`, + query: { count: CONFIG.MASTERY_COUNT }, + }); +} + +async function fetchRecentMatchIdsByPuuid(puuid) { + if (!CONFIG.FETCH_RECENT_MATCH_IDS) return []; + return fetchRiotJson({ + host: `${CONFIG.RIOT_REGION}.api.riotgames.com`, + path: `/lol/match/v5/matches/by-puuid/${encodeURIComponent(puuid)}/ids`, + query: { start: 0, count: CONFIG.RECENT_MATCH_COUNT }, + }); +} + +async function fetchRiotData({ riotId }) { + const fallback = splitRiotId(riotId); + const account = + (await fetchAccountByRiotId(fallback)) ?? { + ...fallback, + puuid: normalizeString(INPUT.puuid), + }; + if (!account?.puuid) { + throw new Error(`Riot account not found and PUUID was not provided: ${riotId}`); + } + + const [summoner, leagueEntries, championMasteries, matchIds] = + await Promise.all([ + fetchSummonerByPuuid(account.puuid).catch(() => null), + fetchLeagueEntriesByPuuid(account.puuid).catch(() => []), + fetchChampionMasteriesByPuuid(account.puuid).catch(() => []), + fetchRecentMatchIdsByPuuid(account.puuid).catch(() => []), + ]); + + return { + account: { + puuid: account.puuid, + gameName: normalizeString(account.gameName) || fallback.gameName, + tagLine: normalizeString(account.tagLine) || fallback.tagLine, + }, + summoner, + leagueEntries: Array.isArray(leagueEntries) ? leagueEntries : [], + championMasteries: Array.isArray(championMasteries) + ? championMasteries + : [], + matchIds: Array.isArray(matchIds) ? matchIds : [], + }; +} + +function toTierInfo(entry, fetchedAt) { + return { + leagueId: entry.leagueId, + queueType: entry.queueType, + tier: entry.tier, + rank: entry.rank, + puuid: entry.puuid, + leaguePoints: entry.leaguePoints ?? 0, + wins: entry.wins ?? 0, + losses: entry.losses ?? 0, + veteran: entry.veteran, + inactive: entry.inactive, + freshBlood: entry.freshBlood, + hotStreak: entry.hotStreak, + miniSeries: entry.miniSeries, + fetchedAt, + }; +} + +function toTierHistory(entry, recordedAt) { + return { + queueType: entry.queueType, + tier: entry.tier, + rank: entry.rank, + leaguePoints: entry.leaguePoints ?? 0, + wins: entry.wins ?? 0, + losses: entry.losses ?? 0, + recordedAt, + }; +} + +function toChampionMastery(entry) { + return { + puuid: entry.puuid, + championId: entry.championId, + championLevel: entry.championLevel, + championPoints: entry.championPoints, + lastPlayTime: entry.lastPlayTime, + championPointsSinceLastLevel: entry.championPointsSinceLastLevel, + championPointsUntilNextLevel: entry.championPointsUntilNextLevel, + markRequiredForNextLevel: entry.markRequiredForNextLevel, + tokensEarned: entry.tokensEarned, + championSeasonMilestone: entry.championSeasonMilestone, + milestoneGrades: entry.milestoneGrades, + nextSeasonMilestone: entry.nextSeasonMilestone, + }; +} + +function buildRiotAccount(riotData, now) { + return removeUndefined({ + puuid: riotData.account.puuid, + gameName: riotData.account.gameName, + tagLine: riotData.account.tagLine, + profileIconId: riotData.summoner?.profileIconId ?? 0, + revisionDate: riotData.summoner?.revisionDate ?? 0, + summonerLevel: riotData.summoner?.summonerLevel ?? 0, + isPrimary: true, + tiers: riotData.leagueEntries.map((entry) => toTierInfo(entry, now)), + tierHistory: riotData.leagueEntries.map((entry) => toTierHistory(entry, now)), + matchIds: riotData.matchIds, + matchIdsFetchedAt: riotData.matchIds.length > 0 ? now : undefined, + championMasteries: riotData.championMasteries + .slice(0, CONFIG.MASTERY_COUNT) + .map(toChampionMastery), + championMasteriesFetchedAt: + riotData.championMasteries.length > 0 ? now : undefined, + championRecords: {}, + createdAt: now, + updatedAt: now, + }); +} + +function mergeRiotAccount(existingAccounts, nextAccount) { + const merged = (existingAccounts ?? []) + .filter( + (account) => + account.puuid !== nextAccount.puuid && + !( + normalizeString(account.gameName).toLowerCase() === + normalizeString(nextAccount.gameName).toLowerCase() && + normalizeString(account.tagLine).toLowerCase() === + normalizeString(nextAccount.tagLine).toLowerCase() + ), + ) + .map((account) => ({ ...account, isPrimary: false })); + return [nextAccount, ...merged]; +} + +async function buildPlan(User) { + const now = new Date(); + const riotData = await fetchRiotData({ riotId: INPUT.riotId }); + const account = buildRiotAccount(riotData, now); + + const conflict = await User.findOne({ + communityId: CONFIG.COMMUNITY_ID, + kakaoTalkId: { $ne: INPUT.kakaoTalkId }, + "riotAccounts.puuid": account.puuid, + }); + if (conflict && CONFIG.FAIL_ON_CONFLICT) { + throw new Error( + `Riot puuid conflict. existingUserId=${conflict._id.toString()} existingKakaoTalkId=${conflict.kakaoTalkId}`, + ); + } + + const filter = { + communityId: CONFIG.COMMUNITY_ID, + kakaoTalkId: INPUT.kakaoTalkId, + }; + const existing = await User.findOne(filter); + const doc = removeUndefined({ + _id: existing?._id ?? new ObjectId(), + communityId: CONFIG.COMMUNITY_ID, + role: INPUT.role, + kakaoTalkId: INPUT.kakaoTalkId, + kakaoTalkNickname: INPUT.kakaoTalkNickname, + riotAccounts: mergeRiotAccount(existing?.riotAccounts, account), + preferredPositions: normalizePositions(INPUT.preferredPositions), + isActivated: INPUT.isActivated, + createdAt: existing?.createdAt ?? now, + updatedAt: now, + }); + + return { + mode: existing ? "update" : "insert", + filter, + doc, + conflict: conflict + ? { + existingUserId: conflict._id, + existingKakaoTalkId: conflict.kakaoTalkId, + } + : null, + }; +} + +async function applyPlan(User, plan) { + if (CONFIG.DRY_RUN) return { dryRun: true, plan }; + + if (plan.mode === "update") { + const { _id, createdAt, ...setDoc } = plan.doc; + await User.updateOne({ _id: plan.doc._id }, { $set: setDoc }); + return { updated: 1, inserted: 0, userId: plan.doc._id }; + } + + await User.insertOne(plan.doc); + return { updated: 0, inserted: 1, userId: plan.doc._id }; +} + +async function run() { + requireInput(); + const client = new MongoClient(CONFIG.MONGODB_URI); + await client.connect(); + + try { + const db = client.db(CONFIG.LOLYMPUS_DB_NAME); + const User = db.collection("user"); + const plan = await buildPlan(User); + const result = await applyPlan(User, plan); + + return { + config: maskConfig(), + input: { + ...INPUT, + puuid: INPUT.puuid ? "***provided***" : "", + }, + result, + }; + } finally { + await client.close(); + } +} + +if (require.main === module) { + run() + .then((result) => { + console.log(JSON.stringify(result, null, 2)); + }) + .catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/scripts/apply-saved-dakao-riot-users.js b/scripts/apply-saved-dakao-riot-users.js new file mode 100644 index 00000000..a9a4d4c5 --- /dev/null +++ b/scripts/apply-saved-dakao-riot-users.js @@ -0,0 +1,424 @@ +/** + * Apply already-saved Dakao user bootstrap data into lolympus-test.user. + * + * This script does NOT call Riot API. + * + * It reads saved documents from one of: + * 1. lolympus-test.DakaoUserBootstrapRun + * 2. lolympus-test.DakaoUserBootstrapCandidate + * + * It only applies users that already have a valid Riot identity: + * - dryRunUsers[].doc.riotAccounts[0].puuid, or + * - candidate.riotApiResult.puuid, or + * - candidate.matchedRiotAccount.puuid + * + * Install: + * npm install mongodb + * + * Dry-run latest saved run: + * MONGODB_URI="mongodb://..." node apply-saved-dakao-riot-users.js + * + * Dry-run specific saved run: + * MONGODB_URI="mongodb://..." SOURCE=run RUN_ID="..." node apply-saved-dakao-riot-users.js + * + * Dry-run from candidate collection: + * MONGODB_URI="mongodb://..." SOURCE=candidate node apply-saved-dakao-riot-users.js + * + * Write: + * DRY_RUN=false MONGODB_URI="mongodb://..." node apply-saved-dakao-riot-users.js + */ + +"use strict"; + +const { MongoClient, ObjectId } = require("mongodb"); + +const CONFIG = { + MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017", + LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-test", + COMMUNITY_ID: new ObjectId( + process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1", + ), + RUNS_COLLECTION_NAME: + process.env.RUNS_COLLECTION_NAME ?? "DakaoUserBootstrapRun", + CANDIDATES_COLLECTION_NAME: + process.env.CANDIDATES_COLLECTION_NAME ?? "DakaoUserBootstrapCandidate", + SOURCE: process.env.SOURCE ?? "run", // run | candidate + RUN_ID: process.env.RUN_ID ?? "", + DRY_RUN: process.env.DRY_RUN !== "false", + FORCE_REAPPLY_RUN: process.env.FORCE_REAPPLY_RUN === "true", +}; + +function normalizeString(value) { + return typeof value === "string" ? value.trim() : ""; +} + +function toObjectId(value, fieldName) { + if (value instanceof ObjectId) return value; + if (typeof value === "string" && ObjectId.isValid(value)) { + return new ObjectId(value); + } + throw new Error(`Invalid ObjectId for ${fieldName}: ${value}`); +} + +function removeUndefined(value) { + if (Array.isArray(value)) { + return value.map(removeUndefined); + } + if ( + value && + typeof value === "object" && + !(value instanceof Date) && + !(value instanceof ObjectId) + ) { + return Object.fromEntries( + Object.entries(value) + .filter(([, entryValue]) => entryValue !== undefined) + .map(([key, entryValue]) => [key, removeUndefined(entryValue)]), + ); + } + return value; +} + +function maskConfig() { + return { + ...CONFIG, + MONGODB_URI: CONFIG.MONGODB_URI.replace(/\/\/.*@/u, "//***@"), + }; +} + +function hasValidRiotAccount(account) { + return Boolean( + normalizeString(account?.puuid) && + normalizeString(account?.gameName) && + normalizeString(account?.tagLine), + ); +} + +function ensureRiotAccountShape(account, now) { + return removeUndefined({ + puuid: normalizeString(account.puuid), + gameName: normalizeString(account.gameName), + tagLine: normalizeString(account.tagLine), + profileIconId: account.profileIconId ?? 0, + revisionDate: account.revisionDate ?? 0, + summonerLevel: account.summonerLevel ?? 0, + isPrimary: true, + tiers: Array.isArray(account.tiers) ? account.tiers : [], + tierHistory: Array.isArray(account.tierHistory) ? account.tierHistory : [], + matchIds: Array.isArray(account.matchIds) ? account.matchIds : [], + matchIdsFetchedAt: account.matchIdsFetchedAt, + lastRefreshRequestedAt: account.lastRefreshRequestedAt, + recentStatsSummary: account.recentStatsSummary, + recentStatsFetchedAt: account.recentStatsFetchedAt, + championMasteries: Array.isArray(account.championMasteries) + ? account.championMasteries + : [], + championMasteriesFetchedAt: account.championMasteriesFetchedAt, + championRecords: account.championRecords ?? {}, + championRecordsFetchedAt: account.championRecordsFetchedAt, + createdAt: account.createdAt ?? now, + updatedAt: now, + }); +} + +function mergeRiotAccount(existingAccounts, nextAccount) { + const merged = (existingAccounts ?? []) + .filter( + (account) => + account.puuid !== nextAccount.puuid && + !( + normalizeString(account.gameName).toLowerCase() === + normalizeString(nextAccount.gameName).toLowerCase() && + normalizeString(account.tagLine).toLowerCase() === + normalizeString(nextAccount.tagLine).toLowerCase() + ), + ) + .map((account) => ({ ...account, isPrimary: false })); + + return [nextAccount, ...merged]; +} + +function buildPlanFromDryRunUser(planned, now) { + const doc = planned.doc ?? {}; + const primary = doc.riotAccounts?.[0]; + if (!hasValidRiotAccount(primary)) return null; + + return { + source: "dryRunUsers", + originalMode: planned.mode, + filter: { + communityId: toObjectId( + planned.filter?.communityId ?? doc.communityId ?? CONFIG.COMMUNITY_ID, + "planned.communityId", + ), + kakaoTalkId: normalizeString(planned.filter?.kakaoTalkId ?? doc.kakaoTalkId), + }, + doc: removeUndefined({ + _id: + doc._id && ObjectId.isValid(String(doc._id)) + ? toObjectId(doc._id, "planned.doc._id") + : new ObjectId(), + communityId: toObjectId(doc.communityId ?? CONFIG.COMMUNITY_ID, "doc.communityId"), + role: doc.role ?? "member", + kakaoTalkId: normalizeString(doc.kakaoTalkId), + kakaoTalkNickname: normalizeString(doc.kakaoTalkNickname), + riotAccounts: [ensureRiotAccountShape(primary, now)], + preferredPositions: Array.isArray(doc.preferredPositions) + ? doc.preferredPositions + : [], + isActivated: doc.isActivated ?? true, + createdAt: doc.createdAt ?? now, + updatedAt: now, + }), + }; +} + +function buildPlanFromCandidate(candidate, now) { + const api = candidate.riotApiResult; + const matched = candidate.matchedRiotAccount; + const accountSource = hasValidRiotAccount(api) ? api : matched; + if (!hasValidRiotAccount(accountSource)) return null; + + const account = ensureRiotAccountShape( + { + ...matched, + ...api, + profileIconId: candidate.riotEnrichment?.summoner?.profileIconId ?? 0, + revisionDate: candidate.riotEnrichment?.summoner?.revisionDate ?? 0, + summonerLevel: candidate.riotEnrichment?.summoner?.summonerLevel ?? 0, + tiers: (candidate.riotEnrichment?.leagueEntries ?? []).map((entry) => ({ + leagueId: entry.leagueId, + queueType: entry.queueType, + tier: entry.tier, + rank: entry.rank, + puuid: entry.puuid, + leaguePoints: entry.leaguePoints ?? 0, + wins: entry.wins ?? 0, + losses: entry.losses ?? 0, + veteran: entry.veteran, + inactive: entry.inactive, + freshBlood: entry.freshBlood, + hotStreak: entry.hotStreak, + miniSeries: entry.miniSeries, + fetchedAt: now, + })), + tierHistory: (candidate.riotEnrichment?.leagueEntries ?? []).map( + (entry) => ({ + queueType: entry.queueType, + tier: entry.tier, + rank: entry.rank, + leaguePoints: entry.leaguePoints ?? 0, + wins: entry.wins ?? 0, + losses: entry.losses ?? 0, + recordedAt: now, + }), + ), + matchIds: candidate.riotEnrichment?.matchIds ?? [], + matchIdsFetchedAt: + candidate.riotEnrichment?.matchIds?.length > 0 ? now : undefined, + championMasteries: candidate.riotEnrichment?.championMasteries ?? [], + championMasteriesFetchedAt: + candidate.riotEnrichment?.championMasteries?.length > 0 + ? now + : undefined, + }, + now, + ); + + return { + source: "candidate", + filter: { + communityId: toObjectId(candidate.communityId ?? CONFIG.COMMUNITY_ID, "candidate.communityId"), + kakaoTalkId: normalizeString(candidate.kakaoTalkId), + }, + doc: removeUndefined({ + _id: new ObjectId(), + communityId: toObjectId(candidate.communityId ?? CONFIG.COMMUNITY_ID, "candidate.communityId"), + role: candidate.role ?? "member", + kakaoTalkId: normalizeString(candidate.kakaoTalkId), + kakaoTalkNickname: normalizeString( + candidate.targetKakaoTalkNickname || candidate.kakaoTalkNickname, + ), + riotAccounts: [account], + preferredPositions: Array.isArray(candidate.preferredPositions) + ? candidate.preferredPositions + : [], + isActivated: candidate.isActivated ?? true, + createdAt: now, + updatedAt: now, + }), + }; +} + +function dedupePlans(plans) { + const byKakaoTalkId = new Map(); + for (const plan of plans) { + if (!plan?.filter?.kakaoTalkId) continue; + byKakaoTalkId.set(plan.filter.kakaoTalkId, plan); + } + return [...byKakaoTalkId.values()]; +} + +async function loadLatestRun(Runs) { + if (CONFIG.RUN_ID) { + return Runs.findOne({ _id: toObjectId(CONFIG.RUN_ID, "RUN_ID") }); + } + return Runs.findOne( + { communityId: CONFIG.COMMUNITY_ID }, + { sort: { createdAt: -1 } }, + ); +} + +async function loadPlansFromRun(lolympusDb, now) { + const Runs = lolympusDb.collection(CONFIG.RUNS_COLLECTION_NAME); + const run = await loadLatestRun(Runs); + if (!run) { + throw new Error("No saved DakaoUserBootstrapRun found."); + } + if (run.state === "applied" && !CONFIG.FORCE_REAPPLY_RUN) { + throw new Error( + `Run ${run._id.toString()} is already applied. Set FORCE_REAPPLY_RUN=true to re-apply.`, + ); + } + + const fromDryRunUsers = (run.upsertResult?.dryRunUsers ?? []) + .map((planned) => buildPlanFromDryRunUser(planned, now)) + .filter(Boolean); + const fromCandidates = (run.candidates ?? []) + .map((candidate) => buildPlanFromCandidate(candidate, now)) + .filter(Boolean); + const plans = dedupePlans( + fromDryRunUsers.length > 0 ? fromDryRunUsers : fromCandidates, + ); + + return { sourceRun: run, plans }; +} + +async function loadPlansFromCandidates(lolympusDb, now) { + const Candidate = lolympusDb.collection(CONFIG.CANDIDATES_COLLECTION_NAME); + const candidates = await Candidate.find({ + communityId: CONFIG.COMMUNITY_ID, + }).toArray(); + const plans = dedupePlans( + candidates.map((candidate) => buildPlanFromCandidate(candidate, now)).filter(Boolean), + ); + return { sourceRun: null, plans }; +} + +async function applyPlans(lolympusDb, plans) { + const User = lolympusDb.collection("user"); + const result = { + inserted: 0, + updated: 0, + skippedConflict: [], + errors: [], + dryRunUsers: [], + }; + + for (const plan of plans) { + try { + const primary = plan.doc.riotAccounts?.[0]; + const conflict = await User.findOne({ + communityId: plan.doc.communityId, + kakaoTalkId: { $ne: plan.doc.kakaoTalkId }, + "riotAccounts.puuid": primary.puuid, + }); + if (conflict) { + result.skippedConflict.push({ + kakaoTalkId: plan.doc.kakaoTalkId, + riotId: `${primary.gameName}#${primary.tagLine}`, + puuid: primary.puuid, + existingUserId: conflict._id, + existingKakaoTalkId: conflict.kakaoTalkId, + }); + continue; + } + + const existing = await User.findOne(plan.filter); + const nextDoc = removeUndefined({ + ...plan.doc, + _id: existing?._id ?? plan.doc._id, + createdAt: existing?.createdAt ?? plan.doc.createdAt, + riotAccounts: mergeRiotAccount(existing?.riotAccounts, primary), + }); + + if (CONFIG.DRY_RUN) { + result.dryRunUsers.push({ + mode: existing ? "update" : "insert", + filter: plan.filter, + doc: nextDoc, + }); + continue; + } + + if (existing) { + const { _id, createdAt, ...setDoc } = nextDoc; + await User.updateOne({ _id: existing._id }, { $set: setDoc }); + result.updated += 1; + } else { + await User.insertOne(nextDoc); + result.inserted += 1; + } + } catch (error) { + result.errors.push({ + kakaoTalkId: plan?.doc?.kakaoTalkId, + message: error instanceof Error ? error.message : String(error), + }); + } + } + + return result; +} + +async function markRunApplied(lolympusDb, sourceRun, applyResult) { + if (!sourceRun || CONFIG.DRY_RUN) return; + const Runs = lolympusDb.collection(CONFIG.RUNS_COLLECTION_NAME); + await Runs.updateOne( + { _id: sourceRun._id }, + { + $set: { + state: applyResult.errors.length > 0 ? "apply-partial" : "applied", + appliedAt: new Date(), + updatedAt: new Date(), + applyResult, + }, + }, + ); +} + +async function run() { + const client = new MongoClient(CONFIG.MONGODB_URI); + await client.connect(); + + try { + const lolympusDb = client.db(CONFIG.LOLYMPUS_DB_NAME); + const now = new Date(); + const { sourceRun, plans } = + CONFIG.SOURCE === "candidate" + ? await loadPlansFromCandidates(lolympusDb, now) + : await loadPlansFromRun(lolympusDb, now); + const applyResult = await applyPlans(lolympusDb, plans); + await markRunApplied(lolympusDb, sourceRun, applyResult); + + return { + config: maskConfig(), + source: CONFIG.SOURCE, + sourceRunId: sourceRun?._id ?? null, + planCount: plans.length, + applyResult, + }; + } finally { + await client.close(); + } +} + +if (require.main === module) { + run() + .then((result) => { + console.log(JSON.stringify(result, null, 2)); + }) + .catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} diff --git a/scripts/dakao-user-bootstrap.nodeshell.js b/scripts/dakao-user-bootstrap.nodeshell.js new file mode 100644 index 00000000..41b74942 --- /dev/null +++ b/scripts/dakao-user-bootstrap.nodeshell.js @@ -0,0 +1,1063 @@ +/** + * Standalone Node.js script using the official MongoDB driver. + * + * Install: + * npm install mongodb + * + * Run dry-run: + * MONGODB_URI="mongodb://..." RIOT_API_KEY="RGAPI-..." node dakao-user-bootstrap.nodeshell.js + * + * Run write: + * DRY_RUN=false MONGODB_URI="mongodb://..." RIOT_API_KEY="RGAPI-..." node dakao-user-bootstrap.nodeshell.js + * + * Apply saved dry-run without re-calling Riot API: + * APPLY_RUN_ID="" MONGODB_URI="mongodb://..." node dakao-user-bootstrap.nodeshell.js + * + * Flow: + * dakao.OpenChatMemberProfile + dakao.LOCOEvent + * -> extract Kakao userId/nickname + * -> join nickname base with RiotAccount.gameName + * -> verify/fetch puuid from Riot Account API + * -> fetch summoner / league / mastery / recent match ids from Riot API + * -> upsert lolympus-test.user + */ + +"use strict"; + +const { MongoClient, ObjectId } = require("mongodb"); + +const CONFIG = { + // Do not hardcode credentials/API keys in source. Pass them by env. + MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017", + RIOT_API_KEY: process.env.RIOT_API_KEY ?? "", + + DAKAO_DB_NAME: "dakao", + LOLYMPUS_DB_NAME: "lolympus-test", + RIOT_ACCOUNT_DB_NAME: process.env.RIOT_ACCOUNT_DB_NAME ?? "dakao", + RIOT_ACCOUNT_COLLECTION_NAME: + process.env.RIOT_ACCOUNT_COLLECTION_NAME ?? "RiotAccount", + RUNS_COLLECTION_NAME: + process.env.RUNS_COLLECTION_NAME ?? "DakaoUserBootstrapRun", + + DAKAO_PROJECT_ID: new ObjectId("69985467365c75936c355318"), + CHATROOM_ID: "18449690440646330", + COMMUNITY_ID: new ObjectId("69ebe0adf627c11be2f020a1"), + + RECENT_DAYS: Number(process.env.RECENT_DAYS ?? 31), + RIOT_REGION: process.env.RIOT_REGION ?? "asia", + RIOT_PLATFORM: process.env.RIOT_PLATFORM ?? "kr", + MASTERY_COUNT: Number(process.env.MASTERY_COUNT ?? 10), + RECENT_MATCH_COUNT: Number(process.env.RECENT_MATCH_COUNT ?? 20), + FETCH_RECENT_MATCH_IDS: process.env.FETCH_RECENT_MATCH_IDS !== "false", + + // Safe default. Set DRY_RUN=false to write into lolympus-test.user. + DRY_RUN: process.env.DRY_RUN !== "false", + SAVE_DRY_RUN_RESULT: process.env.SAVE_DRY_RUN_RESULT !== "false", + OUTPUT_ONLY_RIOT_MATCHED: process.env.OUTPUT_ONLY_RIOT_MATCHED !== "false", + APPLY_RUN_ID: process.env.APPLY_RUN_ID ?? "", + FORCE_APPLY_SAVED_RUN: process.env.FORCE_APPLY_SAVED_RUN === "true", + RUN_LABEL: process.env.RUN_LABEL ?? "", + WRITE_CANDIDATES_COLLECTION: + process.env.WRITE_CANDIDATES_COLLECTION !== "false", + + // Optional comma-separated Kakao user ids to ignore. + EXCLUDE_KAKAO_IDS: (process.env.EXCLUDE_KAKAO_IDS ?? "") + .split(",") + .map((value) => value.trim()) + .filter(Boolean), + + // Small delay between Riot API requests. 0 is usually okay, but this keeps + // one-off migration scripts polite. + RIOT_REQUEST_DELAY_MS: Number(process.env.RIOT_REQUEST_DELAY_MS ?? 250), +}; + +/** + * Optional corrections for weird Kakao nicknames or Riot IDs. + * + * Key: Kakao userId / LOCOEvent senderId + * + * Use this only when nickname -> RiotAccount.gameName matching is impossible + * or ambiguous. + */ +const MANUAL_OVERRIDES = { + /* + "5004764920338338307": { + riotId: "도구왕#KR1", + nickname: "도구왕/86/남/E", + preferredPositions: ["SUP"], + role: "member", + isActivated: true + }, + */ +}; + +function normalizeString(value) { + return typeof value === "string" ? value.trim() : ""; +} + +function normalizeJoinKey(value) { + return normalizeString(value).toLocaleLowerCase("ko-KR"); +} + +function normalizeCompactJoinKey(value) { + return normalizeJoinKey(value).replace(/\s+/gu, ""); +} + +function extractNicknameBase(nickname) { + const value = normalizeString(nickname); + if (!value) return ""; + return normalizeString(value.split("/")[0]); +} + +function splitRiotId(riotId) { + const value = normalizeString(riotId); + const hashIndex = value.lastIndexOf("#"); + if (hashIndex <= 0 || hashIndex === value.length - 1) { + throw new Error(`Invalid riotId: ${riotId}`); + } + return { + gameName: value.slice(0, hashIndex).trim(), + tagLine: value.slice(hashIndex + 1).trim(), + }; +} + +function normalizePositions(values) { + const allowed = new Set(["TOP", "JGL", "MID", "ADC", "SUP"]); + return (values ?? []) + .map((position) => normalizeString(position).toUpperCase()) + .filter((position) => allowed.has(position)) + .map((position, index) => ({ position, priority: index + 1 })); +} + +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function removeUndefined(value) { + if (Array.isArray(value)) { + return value.map(removeUndefined); + } + if ( + value && + typeof value === "object" && + !(value instanceof Date) && + !(value instanceof ObjectId) + ) { + return Object.fromEntries( + Object.entries(value) + .filter(([, entryValue]) => entryValue !== undefined) + .map(([key, entryValue]) => [key, removeUndefined(entryValue)]), + ); + } + return value; +} + +function maskConfigForStorage() { + return { + ...CONFIG, + MONGODB_URI: CONFIG.MONGODB_URI.replace(/\/\/.*@/u, "//***@"), + RIOT_API_KEY: CONFIG.RIOT_API_KEY ? "***" : "", + }; +} + +function isRiotMatchedCandidate(candidate) { + return Boolean( + candidate.matchedRiotAccount && + candidate.ambiguousRiotAccounts?.length === 0 && + candidate.riotApiResult && + !candidate.riotApiError && + !candidate.riotEnrichmentError, + ); +} + +function filterOutputCandidates(candidates) { + if (!CONFIG.OUTPUT_ONLY_RIOT_MATCHED) return candidates; + return candidates.filter(isRiotMatchedCandidate); +} + +function filterOutputUpsertResult(result) { + if (!CONFIG.OUTPUT_ONLY_RIOT_MATCHED) return result; + return { + ...result, + skippedNoRiotMatchCount: result.skippedNoRiotMatch?.length ?? 0, + skippedAmbiguousCount: result.skippedAmbiguous?.length ?? 0, + skippedRiotApiErrorCount: result.skippedRiotApiError?.length ?? 0, + skippedRiotEnrichmentErrorCount: + result.skippedRiotEnrichmentError?.length ?? 0, + skippedRiotApiNotFoundCount: result.skippedRiotApiNotFound?.length ?? 0, + skippedNoRiotMatch: [], + skippedAmbiguous: [], + skippedRiotApiError: [], + skippedRiotEnrichmentError: [], + skippedRiotApiNotFound: [], + }; +} + +function remember(map, kakaoTalkId, patch) { + if (!kakaoTalkId) return; + + const current = map.get(kakaoTalkId) ?? { + kakaoTalkId, + kakaoTalkNickname: "", + nicknameBase: "", + isPresent: false, + sources: [], + firstJoinedAt: null, + lastSeenAt: null, + joinCount: 0, + leaveCount: 0, + profileImageUrl: null, + fullProfileImageUrl: null, + recentMessageCount: 0, + }; + + const nickname = + normalizeString(patch.kakaoTalkNickname) || + normalizeString(current.kakaoTalkNickname); + const sources = new Set([...(current.sources ?? []), ...(patch.sources ?? [])]); + const lastSeenCandidates = [current.lastSeenAt, patch.lastSeenAt] + .filter(Boolean) + .map((value) => new Date(value)); + + map.set(kakaoTalkId, { + ...current, + ...patch, + kakaoTalkId, + kakaoTalkNickname: nickname, + nicknameBase: extractNicknameBase(nickname), + isPresent: Boolean(current.isPresent || patch.isPresent), + sources: [...sources], + lastSeenAt: + lastSeenCandidates.length > 0 + ? new Date(Math.max(...lastSeenCandidates.map((date) => date.getTime()))) + : null, + recentMessageCount: + (current.recentMessageCount ?? 0) + (patch.recentMessageCount ?? 0), + }); +} + +async function collectCandidates({ dakaoDb }) { + const OpenChatMemberProfile = dakaoDb.collection("OpenChatMemberProfile"); + const LOCOEvent = dakaoDb.collection("LOCOEvent"); + const since = new Date(Date.now() - CONFIG.RECENT_DAYS * 24 * 60 * 60 * 1000); + const excluded = CONFIG.EXCLUDE_KAKAO_IDS; + const map = new Map(); + + const presentProfiles = await OpenChatMemberProfile.find({ + chatroomId: CONFIG.CHATROOM_ID, + isPresent: true, + userId: { $nin: excluded }, + }) + .project({ + userId: 1, + nickname: 1, + firstJoinedAt: 1, + lastSeenAt: 1, + joinCount: 1, + leaveCount: 1, + profileImageUrl: 1, + fullProfileImageUrl: 1, + }) + .toArray(); + + for (const profile of presentProfiles) { + remember(map, normalizeString(profile.userId), { + kakaoTalkNickname: profile.nickname, + isPresent: true, + sources: ["present-profile"], + firstJoinedAt: profile.firstJoinedAt ?? null, + lastSeenAt: profile.lastSeenAt ?? null, + joinCount: profile.joinCount ?? 0, + leaveCount: profile.leaveCount ?? 0, + profileImageUrl: profile.profileImageUrl ?? null, + fullProfileImageUrl: profile.fullProfileImageUrl ?? null, + }); + } + + const recentSenders = await LOCOEvent.aggregate([ + { + $match: { + projectId: CONFIG.DAKAO_PROJECT_ID, + chatroomId: CONFIG.CHATROOM_ID, + eventType: "message.received", + direction: "inbound", + timestamp: { $gte: since }, + senderId: { $nin: excluded }, + }, + }, + { $sort: { timestamp: -1 } }, + { + $group: { + _id: "$senderId", + lastSeenAt: { $first: "$timestamp" }, + kakaoTalkNickname: { $first: "$data.body.authorNickname" }, + recentMessageCount: { $sum: 1 }, + }, + }, + ]).toArray(); + + for (const sender of recentSenders) { + remember(map, normalizeString(sender._id), { + kakaoTalkNickname: sender.kakaoTalkNickname, + sources: ["recent-loco-message"], + lastSeenAt: sender.lastSeenAt ?? null, + recentMessageCount: sender.recentMessageCount ?? 0, + }); + } + + return [...map.values()].sort((left, right) => + normalizeString(left.kakaoTalkNickname).localeCompare( + normalizeString(right.kakaoTalkNickname), + ), + ); +} + +async function loadRiotAccountIndex({ riotAccountDb }) { + const RiotAccount = riotAccountDb.collection( + CONFIG.RIOT_ACCOUNT_COLLECTION_NAME, + ); + const accounts = await RiotAccount.find({}) + .project({ + puuid: 1, + gameName: 1, + tagLine: 1, + region: 1, + updatedAt: 1, + createdAt: 1, + }) + .toArray(); + + const exact = new Map(); + const compact = new Map(); + + for (const account of accounts) { + const exactKey = normalizeJoinKey(account.gameName); + const compactKey = normalizeCompactJoinKey(account.gameName); + if (!exact.has(exactKey)) exact.set(exactKey, []); + if (!compact.has(compactKey)) compact.set(compactKey, []); + exact.get(exactKey).push(account); + compact.get(compactKey).push(account); + } + + return { accounts, exact, compact }; +} + +function pickRiotAccountForCandidate(candidate, index) { + const override = MANUAL_OVERRIDES[candidate.kakaoTalkId]; + if (override?.riotId) { + const { gameName, tagLine } = splitRiotId(override.riotId); + return { + source: "manual-override", + account: { + gameName, + tagLine, + puuid: override.puuid, + region: CONFIG.RIOT_REGION, + }, + override, + ambiguous: [], + }; + } + + const nicknameBase = candidate.nicknameBase; + if (!nicknameBase) { + return { source: "no-nickname-base", account: null, override, ambiguous: [] }; + } + + const exactMatches = index.exact.get(normalizeJoinKey(nicknameBase)) ?? []; + if (exactMatches.length === 1) { + return { + source: "riot-account-exact-gameName", + account: exactMatches[0], + override, + ambiguous: [], + }; + } + if (exactMatches.length > 1) { + return { + source: "ambiguous-exact-gameName", + account: null, + override, + ambiguous: exactMatches, + }; + } + + const compactMatches = + index.compact.get(normalizeCompactJoinKey(nicknameBase)) ?? []; + if (compactMatches.length === 1) { + return { + source: "riot-account-compact-gameName", + account: compactMatches[0], + override, + ambiguous: [], + }; + } + if (compactMatches.length > 1) { + return { + source: "ambiguous-compact-gameName", + account: null, + override, + ambiguous: compactMatches, + }; + } + + return { source: "not-matched", account: null, override, ambiguous: [] }; +} + +async function fetchRiotJson({ host, path, query }) { + if (!CONFIG.RIOT_API_KEY) { + throw new Error("Set RIOT_API_KEY env before calling Riot API."); + } + + const url = new URL(`https://${host}${path}`); + for (const [key, value] of Object.entries(query ?? {})) { + if (value !== undefined && value !== null) { + url.searchParams.set(key, String(value)); + } + } + + for (;;) { + const response = await fetch(url, { + headers: { "X-Riot-Token": CONFIG.RIOT_API_KEY }, + }); + + if (response.status === 429) { + const retryAfterSeconds = Number(response.headers.get("retry-after") ?? 1); + await sleep(Math.max(1, retryAfterSeconds) * 1000); + continue; + } + + if (response.status === 404) return null; + + if (!response.ok) { + const body = await response.text().catch(() => ""); + throw new Error(`Riot API failed ${response.status} ${url.pathname}: ${body}`); + } + + return response.json(); + } +} + +async function fetchRiotAccountByRiotId({ gameName, tagLine }) { + const encodedGameName = encodeURIComponent(gameName); + const encodedTagLine = encodeURIComponent(tagLine); + return fetchRiotJson({ + host: `${CONFIG.RIOT_REGION}.api.riotgames.com`, + path: `/riot/account/v1/accounts/by-riot-id/${encodedGameName}/${encodedTagLine}`, + }); +} + +async function fetchSummonerByPuuid(puuid) { + return fetchRiotJson({ + host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`, + path: `/lol/summoner/v4/summoners/by-puuid/${encodeURIComponent(puuid)}`, + }); +} + +async function fetchLeagueEntriesByPuuid(puuid) { + return fetchRiotJson({ + host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`, + path: `/lol/league/v4/entries/by-puuid/${encodeURIComponent(puuid)}`, + }); +} + +async function fetchChampionMasteriesByPuuid(puuid) { + return fetchRiotJson({ + host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`, + path: `/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}/top`, + query: { count: CONFIG.MASTERY_COUNT }, + }); +} + +async function fetchRecentMatchIdsByPuuid(puuid) { + if (!CONFIG.FETCH_RECENT_MATCH_IDS) return []; + return fetchRiotJson({ + host: `${CONFIG.RIOT_REGION}.api.riotgames.com`, + path: `/lol/match/v5/matches/by-puuid/${encodeURIComponent(puuid)}/ids`, + query: { start: 0, count: CONFIG.RECENT_MATCH_COUNT }, + }); +} + +async function fetchRiotEnrichment(puuid) { + const errors = {}; + + const summoner = await fetchSummonerByPuuid(puuid); + if (!summoner) { + throw new Error(`Summoner not found by puuid: ${puuid}`); + } + + const [leagueEntries, championMasteries, matchIds] = await Promise.all([ + fetchLeagueEntriesByPuuid(puuid).catch((error) => { + errors.league = error instanceof Error ? error.message : String(error); + return []; + }), + fetchChampionMasteriesByPuuid(puuid).catch((error) => { + errors.masteries = error instanceof Error ? error.message : String(error); + return []; + }), + fetchRecentMatchIdsByPuuid(puuid).catch((error) => { + errors.matchIds = error instanceof Error ? error.message : String(error); + return []; + }), + ]); + + return { + summoner, + leagueEntries: Array.isArray(leagueEntries) ? leagueEntries : [], + championMasteries: Array.isArray(championMasteries) + ? championMasteries + : [], + matchIds: Array.isArray(matchIds) ? matchIds : [], + errors, + }; +} + +function toTierInfo(entry, fetchedAt) { + return { + leagueId: entry.leagueId, + queueType: entry.queueType, + tier: entry.tier, + rank: entry.rank, + puuid: entry.puuid, + leaguePoints: entry.leaguePoints ?? 0, + wins: entry.wins ?? 0, + losses: entry.losses ?? 0, + veteran: entry.veteran, + inactive: entry.inactive, + freshBlood: entry.freshBlood, + hotStreak: entry.hotStreak, + miniSeries: entry.miniSeries, + fetchedAt, + }; +} + +function toTierHistory(entry, recordedAt) { + return { + queueType: entry.queueType, + tier: entry.tier, + rank: entry.rank, + leaguePoints: entry.leaguePoints ?? 0, + wins: entry.wins ?? 0, + losses: entry.losses ?? 0, + recordedAt, + }; +} + +function toChampionMastery(entry) { + return { + puuid: entry.puuid, + championId: entry.championId, + championLevel: entry.championLevel, + championPoints: entry.championPoints, + lastPlayTime: entry.lastPlayTime, + championPointsSinceLastLevel: entry.championPointsSinceLastLevel, + championPointsUntilNextLevel: entry.championPointsUntilNextLevel, + markRequiredForNextLevel: entry.markRequiredForNextLevel, + tokensEarned: entry.tokensEarned, + championSeasonMilestone: entry.championSeasonMilestone, + milestoneGrades: entry.milestoneGrades, + nextSeasonMilestone: entry.nextSeasonMilestone, + }; +} + +function buildUserRiotAccount({ + riotAccountApiResult, + riotEnrichment, + fallbackAccount, + now, +}) { + const gameName = + normalizeString(riotAccountApiResult?.gameName) || + normalizeString(fallbackAccount.gameName); + const tagLine = + normalizeString(riotAccountApiResult?.tagLine) || + normalizeString(fallbackAccount.tagLine); + const puuid = + normalizeString(riotAccountApiResult?.puuid) || + normalizeString(fallbackAccount.puuid); + + if (!puuid || !gameName || !tagLine) return null; + const summoner = riotEnrichment?.summoner ?? {}; + const leagueEntries = riotEnrichment?.leagueEntries ?? []; + const championMasteries = riotEnrichment?.championMasteries ?? []; + const matchIds = riotEnrichment?.matchIds ?? []; + + return { + puuid, + gameName, + tagLine, + profileIconId: summoner.profileIconId ?? 0, + revisionDate: summoner.revisionDate ?? 0, + summonerLevel: summoner.summonerLevel ?? 0, + isPrimary: true, + tiers: leagueEntries.map((entry) => toTierInfo(entry, now)), + tierHistory: leagueEntries.map((entry) => toTierHistory(entry, now)), + matchIds, + matchIdsFetchedAt: matchIds.length > 0 ? now : undefined, + championMasteries: championMasteries + .slice(0, CONFIG.MASTERY_COUNT) + .map(toChampionMastery), + championMasteriesFetchedAt: championMasteries.length > 0 ? now : undefined, + championRecords: {}, + createdAt: now, + updatedAt: now, + }; +} + +function mergeRiotAccount(existingAccounts, nextAccount) { + if (!nextAccount) return existingAccounts ?? []; + + const merged = (existingAccounts ?? []) + .filter( + (account) => + account.puuid !== nextAccount.puuid && + !( + normalizeString(account.gameName).toLowerCase() === + normalizeString(nextAccount.gameName).toLowerCase() && + normalizeString(account.tagLine).toLowerCase() === + normalizeString(nextAccount.tagLine).toLowerCase() + ), + ) + .map((account) => ({ ...account, isPrimary: false })); + + return [nextAccount, ...merged]; +} + +async function enrichCandidatesWithRiot({ candidates, riotAccountIndex }) { + const enriched = []; + + for (const candidate of candidates) { + const match = pickRiotAccountForCandidate(candidate, riotAccountIndex); + const fallbackAccount = match.account; + let riotApiResult = null; + let riotApiError = null; + let riotEnrichment = null; + let riotEnrichmentError = null; + + if (fallbackAccount?.gameName && fallbackAccount?.tagLine) { + try { + riotApiResult = await fetchRiotAccountByRiotId({ + gameName: fallbackAccount.gameName, + tagLine: fallbackAccount.tagLine, + }); + if (CONFIG.RIOT_REQUEST_DELAY_MS > 0) { + await sleep(CONFIG.RIOT_REQUEST_DELAY_MS); + } + } catch (error) { + riotApiError = error instanceof Error ? error.message : String(error); + } + + if (riotApiResult?.puuid) { + try { + riotEnrichment = await fetchRiotEnrichment(riotApiResult.puuid); + if (CONFIG.RIOT_REQUEST_DELAY_MS > 0) { + await sleep(CONFIG.RIOT_REQUEST_DELAY_MS); + } + } catch (error) { + riotEnrichmentError = + error instanceof Error ? error.message : String(error); + } + } + } + + enriched.push({ + ...candidate, + manualOverride: match.override ?? null, + riotMatchSource: match.source, + matchedRiotAccount: fallbackAccount ?? null, + ambiguousRiotAccounts: match.ambiguous ?? [], + riotApiResult, + riotApiError, + riotEnrichment, + riotEnrichmentError, + preferredPositions: normalizePositions(match.override?.preferredPositions), + role: match.override?.role ?? "member", + isActivated: match.override?.isActivated ?? true, + targetKakaoTalkNickname: + normalizeString(match.override?.nickname) || candidate.kakaoTalkNickname, + }); + } + + return enriched; +} + +async function writeCandidates({ lolympusDb, candidates }) { + if (!CONFIG.WRITE_CANDIDATES_COLLECTION) return; + + const Candidate = lolympusDb.collection("DakaoUserBootstrapCandidate"); + const now = new Date(); + const outputCandidates = filterOutputCandidates(candidates); + const operations = outputCandidates.map((candidate) => ({ + updateOne: { + filter: { + communityId: CONFIG.COMMUNITY_ID, + kakaoTalkId: candidate.kakaoTalkId, + }, + update: { + $set: { + ...candidate, + communityId: CONFIG.COMMUNITY_ID, + updatedAt: now, + }, + $setOnInsert: { createdAt: now }, + }, + upsert: true, + }, + })); + + if (operations.length > 0) { + await Candidate.bulkWrite(operations, { ordered: false }); + } +} + +async function findRiotPuuidConflict({ User, candidate, account }) { + if (!account?.puuid) return null; + return User.findOne({ + communityId: CONFIG.COMMUNITY_ID, + kakaoTalkId: { $ne: candidate.kakaoTalkId }, + "riotAccounts.puuid": account.puuid, + }); +} + +async function upsertUsers({ lolympusDb, candidates }) { + const User = lolympusDb.collection("user"); + const now = new Date(); + const result = { + inserted: 0, + updated: 0, + skippedNoRiotMatch: [], + skippedAmbiguous: [], + skippedRiotApiError: [], + skippedRiotEnrichmentError: [], + skippedRiotApiNotFound: [], + conflicts: [], + dryRunUsers: [], + }; + + for (const candidate of candidates) { + if (candidate.ambiguousRiotAccounts?.length > 0) { + result.skippedAmbiguous.push(candidate); + continue; + } + if (!candidate.matchedRiotAccount) { + result.skippedNoRiotMatch.push(candidate); + continue; + } + if (candidate.riotApiError) { + result.skippedRiotApiError.push(candidate); + continue; + } + if (candidate.riotEnrichmentError) { + result.skippedRiotEnrichmentError.push(candidate); + continue; + } + if (!candidate.riotApiResult) { + result.skippedRiotApiNotFound.push(candidate); + continue; + } + + const account = buildUserRiotAccount({ + riotAccountApiResult: candidate.riotApiResult, + riotEnrichment: candidate.riotEnrichment, + fallbackAccount: candidate.matchedRiotAccount, + now, + }); + if (!account) { + result.skippedRiotApiNotFound.push(candidate); + continue; + } + + const conflict = await findRiotPuuidConflict({ + User, + candidate, + account, + }); + if (conflict) { + result.conflicts.push({ + kakaoTalkId: candidate.kakaoTalkId, + kakaoTalkNickname: candidate.kakaoTalkNickname, + riotId: `${account.gameName}#${account.tagLine}`, + puuid: account.puuid, + existingUserId: conflict._id, + existingKakaoTalkId: conflict.kakaoTalkId, + }); + continue; + } + + const existing = await User.findOne({ + communityId: CONFIG.COMMUNITY_ID, + kakaoTalkId: candidate.kakaoTalkId, + }); + + const userDoc = { + communityId: CONFIG.COMMUNITY_ID, + role: candidate.role ?? existing?.role ?? "member", + kakaoTalkId: candidate.kakaoTalkId, + kakaoTalkNickname: candidate.targetKakaoTalkNickname, + riotAccounts: mergeRiotAccount(existing?.riotAccounts, account), + preferredPositions: + candidate.preferredPositions?.length > 0 + ? candidate.preferredPositions + : existing?.preferredPositions ?? [], + isActivated: candidate.isActivated ?? true, + updatedAt: now, + }; + + if (CONFIG.DRY_RUN) { + result.dryRunUsers.push({ + mode: existing ? "update" : "insert", + filter: { + communityId: CONFIG.COMMUNITY_ID, + kakaoTalkId: candidate.kakaoTalkId, + }, + doc: { + ...userDoc, + _id: existing?._id ?? new ObjectId(), + createdAt: existing?.createdAt ?? now, + }, + }); + continue; + } + + if (existing) { + await User.updateOne({ _id: existing._id }, { $set: userDoc }); + result.updated += 1; + } else { + await User.insertOne({ + _id: new ObjectId(), + ...userDoc, + createdAt: now, + }); + result.inserted += 1; + } + } + + return result; +} + +function objectIdFromMaybeString(value, fieldName) { + if (value instanceof ObjectId) return value; + if (typeof value === "string" && ObjectId.isValid(value)) { + return new ObjectId(value); + } + throw new Error(`Invalid ObjectId for ${fieldName}: ${value}`); +} + +function buildSetDocFromPlannedDoc(plannedDoc, existing) { + const { _id, createdAt, ...rest } = plannedDoc; + return removeUndefined({ + ...rest, + // Preserve existing createdAt on update. Insert uses the planned createdAt. + updatedAt: new Date(), + }); +} + +async function applyPlannedUsers({ lolympusDb, dryRunUsers }) { + const User = lolympusDb.collection("user"); + const result = { + inserted: 0, + updated: 0, + skippedConflict: [], + errors: [], + }; + + for (const planned of dryRunUsers) { + try { + const filter = removeUndefined({ + ...planned.filter, + communityId: objectIdFromMaybeString( + planned.filter.communityId, + "planned.filter.communityId", + ), + }); + const plannedDoc = removeUndefined({ + ...planned.doc, + _id: objectIdFromMaybeString(planned.doc._id, "planned.doc._id"), + communityId: objectIdFromMaybeString( + planned.doc.communityId, + "planned.doc.communityId", + ), + }); + const primaryPuuid = plannedDoc.riotAccounts?.[0]?.puuid; + + if (primaryPuuid) { + const conflict = await User.findOne({ + communityId: plannedDoc.communityId, + kakaoTalkId: { $ne: plannedDoc.kakaoTalkId }, + "riotAccounts.puuid": primaryPuuid, + }); + if (conflict) { + result.skippedConflict.push({ + kakaoTalkId: plannedDoc.kakaoTalkId, + riotId: `${plannedDoc.riotAccounts[0].gameName}#${plannedDoc.riotAccounts[0].tagLine}`, + puuid: primaryPuuid, + existingUserId: conflict._id, + existingKakaoTalkId: conflict.kakaoTalkId, + }); + continue; + } + } + + const existing = await User.findOne(filter); + if (existing) { + await User.updateOne( + { _id: existing._id }, + { $set: buildSetDocFromPlannedDoc(plannedDoc, existing) }, + ); + result.updated += 1; + } else { + await User.insertOne(plannedDoc); + result.inserted += 1; + } + } catch (error) { + result.errors.push({ + planned, + message: error instanceof Error ? error.message : String(error), + }); + } + } + + return result; +} + +async function saveDryRunResult({ lolympusDb, payload }) { + if (!CONFIG.DRY_RUN || !CONFIG.SAVE_DRY_RUN_RESULT) return null; + + const Runs = lolympusDb.collection(CONFIG.RUNS_COLLECTION_NAME); + const now = new Date(); + const doc = removeUndefined({ + label: CONFIG.RUN_LABEL || null, + state: "planned", + communityId: CONFIG.COMMUNITY_ID, + createdAt: now, + updatedAt: now, + config: maskConfigForStorage(), + summary: { + riotAccountCount: payload.riotAccountCount, + candidateCount: payload.candidateCount, + matchedCandidateCount: payload.matchedCandidateCount, + ambiguousCount: payload.ambiguousCount, + dryRunUserCount: payload.upsertResult?.dryRunUsers?.length ?? 0, + }, + candidates: filterOutputCandidates(payload.candidates), + upsertResult: payload.upsertResult, + }); + + const inserted = await Runs.insertOne(doc); + return inserted.insertedId; +} + +async function applySavedRun({ lolympusDb, runId }) { + const Runs = lolympusDb.collection(CONFIG.RUNS_COLLECTION_NAME); + const _id = objectIdFromMaybeString(runId, "APPLY_RUN_ID"); + const saved = await Runs.findOne({ _id }); + if (!saved) { + throw new Error(`Saved dry-run not found: ${runId}`); + } + if (saved.state === "applied" && !CONFIG.FORCE_APPLY_SAVED_RUN) { + throw new Error( + `Saved dry-run ${runId} is already applied. Set FORCE_APPLY_SAVED_RUN=true to re-apply.`, + ); + } + + const dryRunUsers = saved.upsertResult?.dryRunUsers ?? []; + if (!Array.isArray(dryRunUsers) || dryRunUsers.length === 0) { + throw new Error(`Saved dry-run ${runId} has no dryRunUsers to apply.`); + } + + const applyResult = await applyPlannedUsers({ lolympusDb, dryRunUsers }); + await Runs.updateOne( + { _id }, + { + $set: { + state: applyResult.errors.length > 0 ? "apply-partial" : "applied", + appliedAt: new Date(), + updatedAt: new Date(), + applyResult, + }, + }, + ); + + return { + appliedRunId: _id, + savedSummary: saved.summary, + applyResult, + }; +} + +async function run() { + const client = new MongoClient(CONFIG.MONGODB_URI); + await client.connect(); + + try { + const lolympusDb = client.db(CONFIG.LOLYMPUS_DB_NAME); + if (CONFIG.APPLY_RUN_ID) { + return applySavedRun({ + lolympusDb, + runId: CONFIG.APPLY_RUN_ID, + }); + } + + if (!CONFIG.RIOT_API_KEY) { + throw new Error("Set RIOT_API_KEY env before running this script."); + } + + const dakaoDb = client.db(CONFIG.DAKAO_DB_NAME); + const riotAccountDb = client.db(CONFIG.RIOT_ACCOUNT_DB_NAME); + + const candidates = await collectCandidates({ dakaoDb }); + const riotAccountIndex = await loadRiotAccountIndex({ riotAccountDb }); + const enrichedCandidates = await enrichCandidatesWithRiot({ + candidates, + riotAccountIndex, + }); + + await writeCandidates({ + lolympusDb, + candidates: enrichedCandidates, + }); + + const upsertResult = await upsertUsers({ + lolympusDb, + candidates: enrichedCandidates, + }); + + const outputCandidates = filterOutputCandidates(enrichedCandidates); + const outputUpsertResult = filterOutputUpsertResult(upsertResult); + const payload = { + config: maskConfigForStorage(), + riotAccountCount: riotAccountIndex.accounts.length, + candidateCount: candidates.length, + matchedCandidateCount: enrichedCandidates.filter( + (candidate) => candidate.matchedRiotAccount && candidate.riotApiResult, + ).length, + ambiguousCount: enrichedCandidates.filter( + (candidate) => candidate.ambiguousRiotAccounts?.length > 0, + ).length, + outputCandidateCount: outputCandidates.length, + candidates: outputCandidates, + upsertResult: outputUpsertResult, + }; + + const savedRunId = await saveDryRunResult({ lolympusDb, payload }); + return { + ...payload, + savedRunId, + }; + } finally { + await client.close(); + } +} + +if (require.main === module) { + run() + .then((result) => { + console.log(JSON.stringify(result, null, 2)); + }) + .catch((error) => { + console.error(error); + process.exitCode = 1; + }); +} + +module.exports = { run, CONFIG, MANUAL_OVERRIDES };