425 lines
13 KiB
JavaScript
425 lines
13 KiB
JavaScript
/**
|
|
* 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;
|
|
});
|
|
}
|