1
0
Fork 0
polaris-task-force/src/app/(frontend)/minigames/flappy/actions.ts
Z8MB1E 997ae39a59 feat(minigames): record completed runs in the period ledger
Phase 1 of the minigame periods feature:

- Shared server-side recorder (lib/minigames/periods/record.ts) writes one
  minigame-entries row per completed scored run, lazily creating the
  anchored period it belongs to (unique startDate makes it race-safe).
  Failures are swallowed so a ledger hiccup can never break a submission.
- Pure anchored-period math (lib/minigames/periods/derive.ts).
- Wire the recorder into all five Core submit actions after their profile
  update: flappy (passes > 0), EOD (win), radio (>= 1 correct message),
  aim trainer and OPORD (any completed round).
- Server-validated durations for every game: flappy and radio watch now
  report durationMs (with bounds), aim trainer reports its run duration
  (clamped to the 30s course), EOD derives it from seconds, OPORD from
  timeMs.
- Integration test covering derivation, lazy period creation, pre-anchor
  null period and the never-throw guarantee.
2026-10-11 17:06:52 -04:00

157 lines
4.5 KiB
TypeScript

"use server";
import config from "@payload-config";
import { getPayload } from "payload";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { broadcastToUser } from "@/lib/realtime/bus";
import { chipsForXp } from "@/lib/minigames/chips";
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
interface ActionResult<T = undefined> {
success: boolean;
error?: string;
data?: T;
}
export interface FlappyStats {
gamesPlayed: number;
totalPasses: number;
bestScore: number;
flappyXp: number;
xpEarned: number;
}
const PASSES_PER_XP = 15;
const MAX_PASSES_PER_GAME = 5000;
// A maximal run (5000 passes) is a few hours at most; reject absurd durations.
const MAX_FLAPPY_DURATION_MS = 6 * 60 * 60 * 1000;
async function authenticate() {
const payloadConfig = await config;
const payload = await getPayload({ config: payloadConfig });
const { headers } = await import("next/headers");
const hdrs = await headers();
const { user } = await payload.auth({
headers: hdrs,
canSetHeaders: false,
});
if (!user) {
throw new Error("Unauthorized");
}
return { payload, user };
}
export async function submitFlappyScore(input: {
passes: number;
durationMs: number;
}): Promise<ActionResult<FlappyStats>> {
try {
const { payload, user } = await authenticate();
const passes = Math.floor(input.passes);
if (!Number.isFinite(passes) || passes < 0) {
return { success: false, error: "Invalid score." };
}
if (passes > MAX_PASSES_PER_GAME) {
return { success: false, error: "Score too large." };
}
if (
typeof input.durationMs !== "number" ||
!Number.isFinite(input.durationMs) ||
input.durationMs <= 0 ||
input.durationMs > MAX_FLAPPY_DURATION_MS
) {
return { success: false, error: "Invalid run duration." };
}
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: user.id as number } },
limit: 1,
depth: 0,
overrideAccess: true,
});
const profile = profileRes.docs[0];
if (!profile) {
return { success: false, error: "No profile found for this user." };
}
const progression = (profile.progression ?? {}) as {
xp?: unknown;
chipBank?: number | null;
minigames?: {
flappyBird?: {
gamesPlayed?: number;
totalPasses?: number;
bestScore?: number;
xpEarned?: number;
};
};
};
const current = progression.minigames?.flappyBird ?? {};
const gamesPlayed = (current.gamesPlayed ?? 0) + 1;
const totalPasses = (current.totalPasses ?? 0) + passes;
const bestScore = Math.max(current.bestScore ?? 0, passes);
const runXp = Math.floor(passes / PASSES_PER_XP);
const flappyXp = (current.xpEarned ?? 0) + runXp;
const { xp: _xp, ...progressionRest } = progression;
const chipBank = Math.max(0, (progression.chipBank ?? 0) + chipsForXp(runXp));
await payload.update({
collection: "profiles",
id: profile.id,
data: {
progression: {
...progressionRest,
chipBank,
minigames: {
...(progressionRest.minigames ?? {}),
flappyBird: { gamesPlayed, totalPasses, bestScore, xpEarned: flappyXp },
},
},
},
overrideAccess: true,
depth: 0,
});
broadcastToUser("profile-update", Number(user.id), {
reason: "xp",
xpGained: runXp,
chipBank,
profileId: profile.id,
});
if (passes > 0) {
await emitGameEvent(payload, {
type: EventTypes.MinigameFlappy,
message: `Completed a flight simulator run passing ${passes} obstacle${passes === 1 ? "" : "s"} (+${runXp} XP)`,
actor: user.id as number,
targetCollection: "users",
targetId: user.id as number,
data: { passes, xpEarned: runXp, bestScore, totalPasses, flappyXp },
});
await recordMinigameEntry({
payload,
userId: Number(user.id),
game: "flappy",
score: passes,
durationMs: input.durationMs,
meta: { xpEarned: runXp },
});
}
return {
success: true,
data: { gamesPlayed, totalPasses, bestScore, flappyXp, xpEarned: runXp },
};
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
return { success: false, error: "You must be logged in." };
}
return { success: false, error: message };
}
}