generated from nhcarrigan/template
1195b657a0
Working through open issues — fixes, balance changes, and features. ## Closed - Closes #161 - Closes #181 - Closes #191 - Closes #199 - Closes #201 - Closes #202 - Closes #203 - Closes #204 - Closes #205 - Closes #206 - Closes #208 - Closes #211 - Closes #212 - Closes #213 - Closes #214 - Closes #216 - Closes #219 - Closes #220 - Closes #221 - Closes #222 - Closes #224 - Closes #225 - Closes #226 - Closes #228 - Closes #229 - Closes #230 - Closes #231 - Closes #232 - Closes #233 - Closes #234 - Closes #235 - Closes #236 ✨ This PR was created with help from Hikari~ 🌸 Reviewed-on: #238 Co-authored-by: Hikari <hikari@nhcarrigan.com> Co-committed-by: Hikari <hikari@nhcarrigan.com>
274 lines
9.3 KiB
TypeScript
274 lines
9.3 KiB
TypeScript
/**
|
|
* @file Prestige routes handling prestige resets and upgrade purchases.
|
|
* @copyright nhcarrigan
|
|
* @license Naomi's Public License
|
|
* @author Naomi Carrigan
|
|
*/
|
|
/* eslint-disable max-lines-per-function -- Route handlers require many steps */
|
|
/* eslint-disable max-statements -- Route handlers require many statements */
|
|
/* eslint-disable complexity -- Route handlers have inherent complexity */
|
|
import { Hono } from "hono";
|
|
import { defaultPrestigeUpgrades } from "../data/prestigeUpgrades.js";
|
|
import { prisma } from "../db/client.js";
|
|
import { authMiddleware } from "../middleware/auth.js";
|
|
import { updateChallengeProgress } from "../services/dailyChallenges.js";
|
|
import { logger } from "../services/logger.js";
|
|
import {
|
|
buildPostPrestigeState,
|
|
calculatePrestigeThreshold,
|
|
computeRunestoneMultipliers,
|
|
isEligibleForPrestige,
|
|
} from "../services/prestige.js";
|
|
import { postMilestoneWebhook } from "../services/webhook.js";
|
|
import type { HonoEnvironment } from "../types/hono.js";
|
|
import type { BuyPrestigeUpgradeRequest, GameState } from "@elysium/types";
|
|
|
|
const prestigeRouter = new Hono<HonoEnvironment>();
|
|
|
|
prestigeRouter.use("*", authMiddleware);
|
|
|
|
prestigeRouter.post("/", async(context) => {
|
|
try {
|
|
const discordId = context.get("discordId");
|
|
|
|
const record = await prisma.gameState.findUnique({ where: { discordId } });
|
|
|
|
if (!record) {
|
|
return context.json({ error: "No save found" }, 404);
|
|
}
|
|
|
|
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma returns JsonValue */
|
|
const state = record.state as unknown as GameState;
|
|
|
|
if (!isEligibleForPrestige(state)) {
|
|
const thresholdMultiplier
|
|
= state.transcendence?.echoPrestigeThresholdMultiplier ?? 1;
|
|
const required = calculatePrestigeThreshold(
|
|
state.prestige.count,
|
|
thresholdMultiplier,
|
|
);
|
|
return context.json(
|
|
{
|
|
error: `Not eligible for prestige — collect ${required.toLocaleString()} total gold first`,
|
|
},
|
|
400,
|
|
);
|
|
}
|
|
|
|
// Update daily prestige challenge progress before resetting the run
|
|
let updatedDailyChallenges = state.dailyChallenges;
|
|
let challengeCrystals = 0;
|
|
if (updatedDailyChallenges) {
|
|
const result = updateChallengeProgress(
|
|
updatedDailyChallenges,
|
|
"prestige",
|
|
1,
|
|
);
|
|
updatedDailyChallenges = result.updatedChallenges;
|
|
challengeCrystals = result.crystalsAwarded;
|
|
}
|
|
|
|
const {
|
|
milestoneRunestones,
|
|
prestigeData,
|
|
prestigeState,
|
|
runestonesEarned,
|
|
} = buildPostPrestigeState(state, state.player.characterName);
|
|
|
|
// Preserve daily challenges across the prestige reset and apply any crystal rewards
|
|
const finalState: GameState = {
|
|
...prestigeState,
|
|
...updatedDailyChallenges === undefined
|
|
? {}
|
|
: { dailyChallenges: updatedDailyChallenges },
|
|
resources: {
|
|
...prestigeState.resources,
|
|
crystals: prestigeState.resources.crystals + challengeCrystals,
|
|
},
|
|
};
|
|
|
|
// Capture current-run stats to accumulate into lifetime totals before resetting
|
|
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
|
/* v8 ignore next 10 -- @preserve */
|
|
const runBossesDefeated = state.bosses.filter((boss) => {
|
|
return boss.status === "defeated";
|
|
}).length;
|
|
const runQuestsCompleted = state.quests.filter((quest) => {
|
|
return quest.status === "completed";
|
|
}).length;
|
|
let runAdventurersRecruited = 0;
|
|
for (const adventurer of state.adventurers) {
|
|
runAdventurersRecruited = runAdventurersRecruited + adventurer.count;
|
|
}
|
|
|
|
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
|
/* v8 ignore next 3 -- @preserve */
|
|
const runAchievementsUnlocked = state.achievements.filter((achievement) => {
|
|
return achievement.unlockedAt !== null;
|
|
}).length;
|
|
|
|
const now = Date.now();
|
|
const { updatedAt } = record;
|
|
|
|
/*
|
|
* Use the record's current updatedAt as an optimistic lock — if another
|
|
* concurrent prestige request already committed, this update will match
|
|
* 0 rows and we can safely reject the duplicate without a double webhook.
|
|
*/
|
|
const updateResult = await prisma.gameState.updateMany({
|
|
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma requires object */
|
|
data: { state: finalState as object, updatedAt: now },
|
|
where: { discordId, updatedAt },
|
|
});
|
|
|
|
if (updateResult.count === 0) {
|
|
return context.json({ error: "Prestige already in progress" }, 409);
|
|
}
|
|
|
|
await prisma.player.update({
|
|
data: {
|
|
characterName: state.player.characterName,
|
|
|
|
lastSavedAt: now,
|
|
|
|
lifetimeAchievementsUnlocked: { increment: runAchievementsUnlocked },
|
|
|
|
lifetimeAdventurersRecruited: { increment: runAdventurersRecruited },
|
|
|
|
lifetimeBossesDefeated: { increment: runBossesDefeated },
|
|
|
|
lifetimeClicks: { increment: state.player.totalClicks },
|
|
|
|
// Accumulate into lifetime totals — never reset
|
|
lifetimeGoldEarned: { increment: state.player.totalGoldEarned },
|
|
|
|
lifetimeQuestsCompleted: { increment: runQuestsCompleted },
|
|
|
|
totalClicks: 0,
|
|
// Reset current-run counters
|
|
totalGoldEarned: 0,
|
|
},
|
|
where: { discordId },
|
|
});
|
|
|
|
const prestigeCount = prestigeData.count;
|
|
void logger.metric("prestige", 1, { discordId, prestigeCount });
|
|
|
|
const playerRecord = await prisma.player.findUnique({
|
|
select: { profileSettings: true },
|
|
where: { discordId },
|
|
});
|
|
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Runtime shape check for JSON field */
|
|
const playerSettings = playerRecord?.profileSettings as
|
|
Record<string, unknown> | null | undefined;
|
|
const announcementsEnabled
|
|
= playerSettings?.enablePrestigeAnnouncements !== false;
|
|
|
|
if (announcementsEnabled) {
|
|
void postMilestoneWebhook(discordId, "prestige", {
|
|
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
|
/* v8 ignore next -- @preserve */
|
|
apotheosis: prestigeState.apotheosis?.count ?? 0,
|
|
|
|
prestige: prestigeData.count,
|
|
|
|
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
|
/* v8 ignore next 2 -- @preserve */
|
|
transcendence: prestigeState.transcendence?.count ?? 0,
|
|
});
|
|
}
|
|
|
|
return context.json({
|
|
milestoneRunestones: milestoneRunestones,
|
|
newPrestigeCount: prestigeData.count, // eslint-disable-line unicorn/no-keyword-prefix -- API response field name required by client
|
|
runestones: runestonesEarned,
|
|
});
|
|
} catch (error) {
|
|
void logger.error(
|
|
"prestige",
|
|
error instanceof Error
|
|
? error
|
|
: new Error(String(error)),
|
|
);
|
|
return context.json({ error: "Internal server error" }, 500);
|
|
}
|
|
});
|
|
|
|
prestigeRouter.post("/buy-upgrade", async(context) => {
|
|
try {
|
|
const discordId = context.get("discordId");
|
|
const body = await context.req.json<BuyPrestigeUpgradeRequest>();
|
|
|
|
const { upgradeId } = body;
|
|
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions -- Runtime body validation
|
|
if (!upgradeId) {
|
|
return context.json({ error: "upgradeId is required" }, 400);
|
|
}
|
|
|
|
const upgrade = defaultPrestigeUpgrades.find((prestigeUpgrade) => {
|
|
return prestigeUpgrade.id === upgradeId;
|
|
});
|
|
if (!upgrade) {
|
|
return context.json({ error: "Unknown prestige upgrade" }, 404);
|
|
}
|
|
|
|
const record = await prisma.gameState.findUnique({ where: { discordId } });
|
|
if (!record) {
|
|
return context.json({ error: "No save found" }, 404);
|
|
}
|
|
|
|
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma returns JsonValue */
|
|
const state = record.state as unknown as GameState;
|
|
const { purchasedUpgradeIds, runestones } = state.prestige;
|
|
|
|
if (purchasedUpgradeIds.includes(upgradeId)) {
|
|
return context.json({ error: "Upgrade already purchased" }, 400);
|
|
}
|
|
|
|
if (runestones < upgrade.runestonesCost) {
|
|
return context.json({ error: "Not enough runestones" }, 400);
|
|
}
|
|
|
|
const updatedRunestones = runestones - upgrade.runestonesCost;
|
|
const updatedPurchasedUpgradeIds = [ ...purchasedUpgradeIds, upgradeId ];
|
|
|
|
const updatedState: GameState = {
|
|
...state,
|
|
prestige: {
|
|
...state.prestige,
|
|
purchasedUpgradeIds: updatedPurchasedUpgradeIds,
|
|
runestones: updatedRunestones,
|
|
...computeRunestoneMultipliers(updatedPurchasedUpgradeIds),
|
|
},
|
|
};
|
|
|
|
await prisma.gameState.update({
|
|
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma requires object */
|
|
data: { state: updatedState as object, updatedAt: Date.now() },
|
|
where: { discordId },
|
|
});
|
|
|
|
const multipliers = computeRunestoneMultipliers(updatedPurchasedUpgradeIds);
|
|
|
|
void logger.metric("prestige_upgrade_purchased", 1, {
|
|
discordId,
|
|
upgradeId,
|
|
});
|
|
return context.json({
|
|
purchasedUpgradeIds: updatedPurchasedUpgradeIds,
|
|
runestonesRemaining: updatedRunestones,
|
|
...multipliers,
|
|
});
|
|
} catch (error) {
|
|
void logger.error(
|
|
"prestige_buy_upgrade",
|
|
error instanceof Error
|
|
? error
|
|
: new Error(String(error)),
|
|
);
|
|
return context.json({ error: "Internal server error" }, 500);
|
|
}
|
|
});
|
|
|
|
export { prestigeRouter };
|