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.
319 lines
11 KiB
TypeScript
319 lines
11 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 RadioStats {
|
|
gamesPlayed: number;
|
|
totalMessages: number;
|
|
incorrectMessages: number;
|
|
bestScore: number;
|
|
bestAccuracy: number;
|
|
bestSprintTimeMs: number;
|
|
sprintGamesPlayed: number;
|
|
sprintTotalMessages: number;
|
|
sprintIncorrectMessages: number;
|
|
sprintBestScore: number;
|
|
sprintBestAccuracy: number;
|
|
watchGamesPlayed: number;
|
|
watchTotalMessages: number;
|
|
watchIncorrectMessages: number;
|
|
watchBestScore: number;
|
|
watchBestAccuracy: number;
|
|
radioTrafficXp: number;
|
|
xpEarned: number;
|
|
}
|
|
|
|
const SPRINT_MESSAGE_COUNT = 10;
|
|
const MAX_WATCH_MESSAGES = 30;
|
|
const MAX_SCORE_PER_GAME = 5000;
|
|
const MAX_SPRINT_TIME_MS = 600_000;
|
|
// Watch rounds run against a 60s clock; allow generous grace for throttled tabs.
|
|
const MAX_WATCH_TIME_MS = 120_000;
|
|
const WATCH_DURATION_FALLBACK_MS = 60_000;
|
|
|
|
type RadioMode = "sprint" | "watch";
|
|
|
|
function isRadioMode(value: string): value is RadioMode {
|
|
return value === "sprint" || value === "watch";
|
|
}
|
|
|
|
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 submitRadioResult(input: {
|
|
score: number;
|
|
messageCount: number;
|
|
correctMessages: number;
|
|
incorrectMessages: number;
|
|
accuracy: number;
|
|
mode: RadioMode;
|
|
timeMs?: number;
|
|
}): Promise<ActionResult<RadioStats>> {
|
|
try {
|
|
const { payload, user } = await authenticate();
|
|
|
|
if (!isRadioMode(input.mode)) {
|
|
return { success: false, error: "Invalid result." };
|
|
}
|
|
const score = Math.floor(input.score);
|
|
if (!Number.isFinite(score) || score < 0 || score > MAX_SCORE_PER_GAME) {
|
|
return { success: false, error: "Invalid score." };
|
|
}
|
|
if (
|
|
!Number.isInteger(input.messageCount) ||
|
|
(input.mode === "sprint"
|
|
? input.messageCount !== SPRINT_MESSAGE_COUNT
|
|
: input.messageCount < 1 || input.messageCount > MAX_WATCH_MESSAGES)
|
|
) {
|
|
return { success: false, error: "Invalid result." };
|
|
}
|
|
if (
|
|
!Number.isInteger(input.correctMessages) ||
|
|
input.correctMessages < 0 ||
|
|
input.correctMessages > input.messageCount
|
|
) {
|
|
return { success: false, error: "Invalid result." };
|
|
}
|
|
if (!Number.isInteger(input.incorrectMessages) || input.incorrectMessages < 0) {
|
|
return { success: false, error: "Invalid result." };
|
|
}
|
|
if (input.mode === "sprint" && input.correctMessages === 0) {
|
|
return { success: false, error: "A Sprint needs at least one correct transmission." };
|
|
}
|
|
if (!Number.isFinite(input.accuracy) || input.accuracy < 0 || input.accuracy > 1) {
|
|
return { success: false, error: "Invalid result." };
|
|
}
|
|
const sprintTime = input.timeMs;
|
|
if (
|
|
input.mode === "sprint" &&
|
|
(typeof sprintTime !== "number" || !Number.isFinite(sprintTime) || sprintTime <= 0 || sprintTime > MAX_SPRINT_TIME_MS)
|
|
) {
|
|
return { success: false, error: "Invalid result." };
|
|
}
|
|
if (
|
|
input.mode === "watch" &&
|
|
sprintTime != null &&
|
|
(typeof sprintTime !== "number" || !Number.isFinite(sprintTime) || sprintTime < 0 || sprintTime > MAX_WATCH_TIME_MS)
|
|
) {
|
|
return { success: false, error: "Invalid result." };
|
|
}
|
|
const runDurationMs =
|
|
input.mode === "sprint"
|
|
? Math.round(sprintTime as number)
|
|
: typeof sprintTime === "number" && Number.isFinite(sprintTime) && sprintTime > 0
|
|
? Math.round(sprintTime)
|
|
: WATCH_DURATION_FALLBACK_MS;
|
|
|
|
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?: {
|
|
radioTraffic?: {
|
|
gamesPlayed?: number;
|
|
totalMessages?: number;
|
|
incorrectMessages?: number;
|
|
bestScore?: number;
|
|
bestAccuracy?: number;
|
|
bestSprintTimeMs?: number;
|
|
sprintGamesPlayed?: number;
|
|
sprintTotalMessages?: number;
|
|
sprintIncorrectMessages?: number;
|
|
sprintBestScore?: number;
|
|
sprintBestAccuracy?: number;
|
|
watchGamesPlayed?: number;
|
|
watchTotalMessages?: number;
|
|
watchIncorrectMessages?: number;
|
|
watchBestScore?: number;
|
|
watchBestAccuracy?: number;
|
|
xpEarned?: number;
|
|
};
|
|
};
|
|
};
|
|
const current = progression.minigames?.radioTraffic ?? {};
|
|
const runXp = Math.round(input.correctMessages * 0.1 * 10) / 10;
|
|
const gamesPlayed = (current.gamesPlayed ?? 0) + 1;
|
|
const totalMessages = (current.totalMessages ?? 0) + input.correctMessages;
|
|
const incorrectMessages = (current.incorrectMessages ?? 0) + input.incorrectMessages;
|
|
const bestScore = Math.max(current.bestScore ?? 0, score);
|
|
const bestAccuracy = Math.round(Math.max(current.bestAccuracy ?? 0, input.accuracy) * 10000) / 10000;
|
|
const sprintGamesPlayed = (current.sprintGamesPlayed ?? 0) + (input.mode === "sprint" ? 1 : 0);
|
|
const sprintTotalMessages =
|
|
(current.sprintTotalMessages ?? 0) + (input.mode === "sprint" ? input.correctMessages : 0);
|
|
const sprintIncorrectMessages =
|
|
(current.sprintIncorrectMessages ?? 0) + (input.mode === "sprint" ? input.incorrectMessages : 0);
|
|
const sprintBestScore =
|
|
input.mode === "sprint" ? Math.max(current.sprintBestScore ?? 0, score) : (current.sprintBestScore ?? 0);
|
|
const sprintBestAccuracy =
|
|
input.mode === "sprint"
|
|
? Math.round(Math.max(current.sprintBestAccuracy ?? 0, input.accuracy) * 10000) / 10000
|
|
: (current.sprintBestAccuracy ?? 0);
|
|
const watchGamesPlayed = (current.watchGamesPlayed ?? 0) + (input.mode === "watch" ? 1 : 0);
|
|
const watchTotalMessages =
|
|
(current.watchTotalMessages ?? 0) + (input.mode === "watch" ? input.correctMessages : 0);
|
|
const watchIncorrectMessages =
|
|
(current.watchIncorrectMessages ?? 0) + (input.mode === "watch" ? input.incorrectMessages : 0);
|
|
const watchBestScore =
|
|
input.mode === "watch" ? Math.max(current.watchBestScore ?? 0, score) : (current.watchBestScore ?? 0);
|
|
const watchBestAccuracy =
|
|
input.mode === "watch"
|
|
? Math.round(Math.max(current.watchBestAccuracy ?? 0, input.accuracy) * 10000) / 10000
|
|
: (current.watchBestAccuracy ?? 0);
|
|
const previousBestSprintTimeMs = current.bestSprintTimeMs ?? 0;
|
|
const bestSprintTimeMs =
|
|
input.mode === "sprint" && typeof sprintTime === "number"
|
|
? Math.min(previousBestSprintTimeMs > 0 ? previousBestSprintTimeMs : Infinity, Math.round(sprintTime))
|
|
: previousBestSprintTimeMs;
|
|
const radioTrafficXp = Math.round(((current.xpEarned ?? 0) + runXp) * 10) / 10;
|
|
|
|
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 ?? {}),
|
|
radioTraffic: {
|
|
gamesPlayed,
|
|
totalMessages,
|
|
incorrectMessages,
|
|
bestScore,
|
|
bestAccuracy,
|
|
bestSprintTimeMs,
|
|
sprintGamesPlayed,
|
|
sprintTotalMessages,
|
|
sprintIncorrectMessages,
|
|
sprintBestScore,
|
|
sprintBestAccuracy,
|
|
watchGamesPlayed,
|
|
watchTotalMessages,
|
|
watchIncorrectMessages,
|
|
watchBestScore,
|
|
watchBestAccuracy,
|
|
xpEarned: radioTrafficXp,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
broadcastToUser("profile-update", Number(user.id), {
|
|
reason: "xp",
|
|
xpGained: runXp,
|
|
chipBank,
|
|
profileId: profile.id,
|
|
});
|
|
|
|
if (score > 0) {
|
|
const modeLabel = input.mode === "sprint" ? "sprint" : "watch";
|
|
await emitGameEvent(payload, {
|
|
type: EventTypes.MinigameRadioTraffic,
|
|
message: `Completed a radio traffic ${modeLabel} run with ${input.correctMessages}/${input.messageCount} messages accurate (+${runXp} XP)`,
|
|
actor: user.id as number,
|
|
targetCollection: "users",
|
|
targetId: user.id as number,
|
|
data: {
|
|
mode: input.mode,
|
|
score,
|
|
messageCount: input.messageCount,
|
|
correctMessages: input.correctMessages,
|
|
accuracy: input.accuracy,
|
|
xpEarned: runXp,
|
|
bestScore,
|
|
bestSprintTimeMs,
|
|
totalMessages,
|
|
radioTrafficXp,
|
|
},
|
|
});
|
|
}
|
|
|
|
if (input.correctMessages >= 1) {
|
|
await recordMinigameEntry({
|
|
payload,
|
|
userId: Number(user.id),
|
|
game: "radio",
|
|
score,
|
|
accuracy: input.accuracy,
|
|
durationMs: runDurationMs,
|
|
mode: input.mode,
|
|
meta: {
|
|
messageCount: input.messageCount,
|
|
correctMessages: input.correctMessages,
|
|
},
|
|
});
|
|
}
|
|
|
|
return {
|
|
success: true,
|
|
data: {
|
|
gamesPlayed,
|
|
totalMessages,
|
|
incorrectMessages,
|
|
bestScore,
|
|
bestAccuracy,
|
|
bestSprintTimeMs,
|
|
sprintGamesPlayed,
|
|
sprintTotalMessages,
|
|
sprintIncorrectMessages,
|
|
sprintBestScore,
|
|
sprintBestAccuracy,
|
|
watchGamesPlayed,
|
|
watchTotalMessages,
|
|
watchIncorrectMessages,
|
|
watchBestScore,
|
|
watchBestAccuracy,
|
|
radioTrafficXp,
|
|
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 };
|
|
}
|
|
}
|