1
0
Fork 0

feat(minigames): notify winners and announce achievements on Discord

Phase 6 of the minigame periods feature:

- Muteable `minigame:achievement` notification type; the close pipeline now
  notifies each winner in-app, but only when the achievement row is newly
  written, so a re-run or a concurrent closer never double-sends.
- New bot service `achievementAnnouncements` polls achievements with no
  announcedAt, groups them by window, posts ONE embed per window to
  DISCORD_ANNOUNCE_CHANNEL_ID, then stamps announcedAt + discordMessageId.
  A failed post leaves the rows unannounced so the next tick retries them.
- Pure, testable renderer (bot/lib/achievementRender.ts) for grouping and the
  embed shape; window labels reuse the period/calendar helpers.
- Register the service in the bot registry and add
  DISCORD_ACHIEVEMENT_POLL_MS (default 60s).
- Tests: renderer grouping/ordering/fallbacks and the in-app notification
  path (including idempotency).
This commit is contained in:
Jason Fraley 2026-10-11 16:42:55 -04:00
parent 316797d27d
commit a1ab247b7b
9 changed files with 476 additions and 3 deletions

View file

@ -15,6 +15,7 @@ export interface BotConfig {
readyReminderPollMs: number;
imminentReminderPollMs: number;
sideOpsNoticePollMs: number;
achievementPollMs: number;
}
const required = (name: string): string => {
@ -62,4 +63,5 @@ export const botConfig: BotConfig = {
readyReminderPollMs: pollMs("DISCORD_READY_REMINDER_POLL_MS", 60_000),
imminentReminderPollMs: pollMs("DISCORD_IMMINENT_POLL_MS", 60_000),
sideOpsNoticePollMs: pollMs("DISCORD_SIDE_OPS_POLL_MS", 1_800_000),
achievementPollMs: pollMs("DISCORD_ACHIEVEMENT_POLL_MS", 60_000),
};

View file

@ -0,0 +1,116 @@
import { formatPeriodLabel } from "@/lib/minigames/periods/derive";
import { formatMonthLabel, formatYearLabel } from "@/lib/minigames/periods/calendar";
import { MINIGAME_ACHIEVEMENT_TYPE_LABELS } from "@/lib/minigames/registry";
/**
* Pure helpers that turn achievement rows into Discord announcement content.
* No Discord or Payload dependencies, so grouping and rendering are testable in
* isolation. The service layer converts the rendered shape into an EmbedBuilder.
*/
export interface AchievementAnnouncementRow {
id: number;
type: string;
window: string;
windowStart: string;
windowEnd: string;
user:
| number
| {
id: number;
displayName?: string | null;
payloadDisplayName?: string | null;
username?: string | null;
}
| null;
value: number;
detail?: string | null;
}
export interface AchievementAnnouncementGroup {
window: string;
windowStart: string;
windowEnd: string;
label: string;
achievements: AchievementAnnouncementRow[];
}
export interface RenderedAchievementAnnouncement {
title: string;
description: string;
color: number;
fields: { name: string; value: string }[];
}
/** Display order for awards inside one announcement. */
const AWARD_ORDER = [
"period-champion",
"player-of-year",
"player-of-month",
"most-improved",
"diligence",
"dedication",
"precision",
];
const GOLD = 0xf59e0b;
const nameOf = (user: AchievementAnnouncementRow["user"]): string => {
if (!user || typeof user !== "object") return "Unknown";
return user.displayName || user.payloadDisplayName || user.username || `Operator #${user.id}`;
};
/** Human label for a window, e.g. "Oct 12 to Oct 25, 2026", "October 2026", "2026". */
export function achievementWindowLabel(window: string, windowStart: string, windowEnd: string): string {
const start = new Date(windowStart);
if (window === "month") return formatMonthLabel(start);
if (window === "year") return formatYearLabel(start);
return formatPeriodLabel(start.getTime(), new Date(windowEnd).getTime());
}
/** Group achievement rows by window (one Discord message per window). */
export function groupAchievementsForAnnouncement(
rows: AchievementAnnouncementRow[],
): AchievementAnnouncementGroup[] {
const byKey = new Map<string, AchievementAnnouncementGroup>();
for (const row of rows) {
const key = `${row.window}|${row.windowStart}`;
const group =
byKey.get(key) ??
({
window: row.window,
windowStart: row.windowStart,
windowEnd: row.windowEnd,
label: achievementWindowLabel(row.window, row.windowStart, row.windowEnd),
achievements: [],
} satisfies AchievementAnnouncementGroup);
group.achievements.push(row);
byKey.set(key, group);
}
const groups = [...byKey.values()];
for (const group of groups) {
group.achievements.sort(
(a, b) => AWARD_ORDER.indexOf(a.type) - AWARD_ORDER.indexOf(b.type) || a.id - b.id,
);
}
return groups.sort((a, b) => new Date(a.windowStart).getTime() - new Date(b.windowStart).getTime());
}
/** Render one window group into embed-ready content (one message per close). */
export function renderAchievementAnnouncement(
group: AchievementAnnouncementGroup,
): RenderedAchievementAnnouncement {
return {
title: `Minigame results: ${group.label}`,
description:
group.window === "period"
? "Anchored period closed. Placement points across the five Core boards."
: `Calendar ${group.window} closed.`,
color: GOLD,
fields: group.achievements.map((achievement) => ({
name: MINIGAME_ACHIEVEMENT_TYPE_LABELS[achievement.type as keyof typeof MINIGAME_ACHIEVEMENT_TYPE_LABELS] ?? achievement.type,
value: `${nameOf(achievement.user)} · ${achievement.detail ?? `${achievement.value}`}`,
})),
};
}

View file

@ -0,0 +1,111 @@
import { type Client, EmbedBuilder } from "discord.js";
import type { Payload } from "payload";
import { botConfig } from "@/bot/config";
import {
groupAchievementsForAnnouncement,
renderAchievementAnnouncement,
type AchievementAnnouncementRow,
} from "@/bot/lib/achievementRender";
/**
* Achievement announcements: poll unannounced achievements, post ONE embed per
* window to the announce channel, then stamp `announcedAt` + `discordMessageId`.
*
* One message per window keeps a close readable: a period close produces a single
* embed listing the five awards. Windows that fail to post stay unannounced and
* are retried on the next tick.
*
* The Next app never talks to Discord; this service owns the bot side.
*/
const MAX_GROUPS_PER_TICK = 3;
const BATCH_LIMIT = 100;
/** Minimal text-channel shape we rely on (mirrors fridayOpsNotice). */
type AnnounceChannel = {
send(payload: { embeds: EmbedBuilder[] }): Promise<{ id: string }>;
};
let running = false;
const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error";
const poll = async (client: Client, payload: Payload): Promise<void> => {
if (running) return;
running = true;
try {
const channelId = botConfig.announceChannelId;
if (!channelId) return;
const res = await payload.find({
collection: "achievements",
where: { announcedAt: { exists: false } },
sort: "windowStart",
limit: BATCH_LIMIT,
depth: 1,
overrideAccess: true,
});
if (res.docs.length === 0) return;
const groups = groupAchievementsForAnnouncement(
res.docs as unknown as AchievementAnnouncementRow[],
);
const channel = await client.channels.fetch(channelId);
if (!channel || !("send" in channel)) {
throw new Error(`[Bot] Announce channel ${channelId} is not a text channel.`);
}
const textChannel = channel as unknown as AnnounceChannel;
let posted = 0;
for (const group of groups.slice(0, MAX_GROUPS_PER_TICK)) {
try {
const rendered = renderAchievementAnnouncement(group);
const message = await textChannel.send({
embeds: [
new EmbedBuilder()
.setTitle(rendered.title)
.setDescription(rendered.description)
.setColor(rendered.color)
.addFields(rendered.fields),
],
});
const announcedAt = new Date().toISOString();
for (const achievement of group.achievements) {
await payload.update({
collection: "achievements",
id: achievement.id,
data: { announcedAt, discordMessageId: message.id },
overrideAccess: true,
depth: 0,
});
}
posted += 1;
} catch (error) {
// Leave the rows unannounced so the next tick retries this window.
payload.logger.error(
`[Bot] Achievement announcement for "${group.label}" failed: ${errorMessage(error)}`,
);
}
}
if (posted > 0) {
payload.logger.info(`[Bot] Achievement announcements posted: ${posted}`);
}
} catch (error) {
payload.logger.error(`[Bot] Achievement announcement poll failed: ${errorMessage(error)}`);
} finally {
running = false;
}
};
export const start = (client: Client, payload: Payload): void => {
payload.logger.info("[Bot] Achievement announcement service started");
void poll(client, payload);
setInterval(() => {
void poll(client, payload);
}, botConfig.achievementPollMs);
};

View file

@ -7,6 +7,7 @@ import { start as startEvaluationReminders } from "./evaluationReminders";
import { start as startReadyReminders } from "./readyReminders";
import { start as startImminentReminders } from "./imminentReminders";
import { start as startFridayOpsNotice } from "./fridayOpsNotice";
import { start as startAchievementAnnouncements } from "./achievementAnnouncements";
export type ServiceStarter = (client: Client, payload: Payload) => Promise<void> | void;
@ -18,4 +19,5 @@ export const services: ServiceStarter[] = [
startReadyReminders,
startImminentReminders,
startFridayOpsNotice,
startAchievementAnnouncements,
];

View file

@ -1,6 +1,11 @@
import type { Payload } from "payload";
import { CORE_MINIGAME_KEYS, type MinigameAchievementType } from "@/lib/minigames/registry";
import {
CORE_MINIGAME_KEYS,
MINIGAME_ACHIEVEMENT_TYPE_LABELS,
type MinigameAchievementType,
} from "@/lib/minigames/registry";
import { loadMinigameRegistry, periodScoringGameKeys } from "@/lib/minigames/loadRegistry";
import { notifyUser } from "@/lib/notifications";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
import { derivePeriodForInstant, periodStartForIndex } from "./derive";
@ -118,6 +123,25 @@ const previousPointsFor = async (
return pointsForPeriod(entries, games, rules);
};
/**
* Notify a winner in-app. Fire-and-forget (notifyUser swallows errors) but
* awaited so the ordering after the achievement write is deterministic. Muteable
* through the `minigame:achievement` notification preference.
*/
const notifyAchievement = async (
payload: PayloadType,
input: { userId: number; type: MinigameAchievementType; windowLabel: string; detail: string },
): Promise<void> => {
const label = MINIGAME_ACHIEVEMENT_TYPE_LABELS[input.type] ?? input.type;
await notifyUser(payload, {
userId: input.userId,
type: "minigame:achievement",
title: `${label} earned for ${input.windowLabel}`,
message: `${input.detail}. See the honor roll on the minigame leaderboards.`,
link: "/minigames/leaderboards",
});
};
/** Insert one achievement unless its `type:windowStart:user` key already exists. */
const writeAchievement = async (
payload: PayloadType,
@ -200,7 +224,7 @@ export async function closePeriodById(
});
for (const award of awards) {
await writeAchievement(payload, {
const wrote = await writeAchievement(payload, {
window: "period",
windowStart: period.startDate,
windowEnd: period.endDate,
@ -209,6 +233,14 @@ export async function closePeriodById(
value: award.value,
detail: award.detail,
});
if (wrote) {
await notifyAchievement(payload, {
userId: award.userId,
type: award.type,
windowLabel: period.label,
detail: award.detail,
});
}
}
// Re-check before committing: a concurrent closer may have won the race.
@ -289,6 +321,7 @@ export async function closeCalendarWindows(
});
if (!champion) continue;
const detail = `${champion.points} placement point${champion.points === 1 ? "" : "s"} across ${champion.boards} board${champion.boards === 1 ? "" : "s"}`;
const wrote = await writeAchievement(payload, {
window: plan.unit,
windowStart,
@ -296,7 +329,7 @@ export async function closeCalendarWindows(
type: plan.type,
user: champion.userId,
value: champion.points,
detail: `${champion.points} placement point${champion.points === 1 ? "" : "s"} across ${champion.boards} board${champion.boards === 1 ? "" : "s"}`,
detail,
});
if (wrote) {
await emitGameEvent(payload, {
@ -304,6 +337,12 @@ export async function closeCalendarWindows(
message: `Minigame ${plan.unit} "${window.label}" closed with 1 achievement.`,
data: { unit: plan.unit, label: window.label, windowStart },
});
await notifyAchievement(payload, {
userId: champion.userId,
type: plan.type,
windowLabel: window.label,
detail,
});
summaries.push({ unit: plan.unit, label: window.label, windowStart, windowEnd, achievements: 1 });
}
}

View file

@ -24,6 +24,7 @@ export const MUTEABLE_NOTIFICATION_TYPES = [
{ label: "Role slot promotions", value: "mission:role-promoted" },
{ label: "Contribution XP granted", value: "contribution:xp-granted" },
{ label: "Contribution XP revoked", value: "contribution:xp-revoked" },
{ label: "Minigame achievements", value: "minigame:achievement" },
] as const;
export type MuteableNotificationType = (typeof MUTEABLE_NOTIFICATION_TYPES)[number]["value"];
export const MUTEABLE_NOTIFICATION_VALUES = MUTEABLE_NOTIFICATION_TYPES.map((t) => t.value);

View file

@ -492,6 +492,7 @@ export interface User {
| 'mission:role-promoted'
| 'contribution:xp-granted'
| 'contribution:xp-revoked'
| 'minigame:achievement'
)[]
| null;
};
@ -531,6 +532,7 @@ export interface User {
| 'mission:role-promoted'
| 'contribution:xp-granted'
| 'contribution:xp-revoked'
| 'minigame:achievement'
)[]
| null;
};

View file

@ -0,0 +1,80 @@
import { describe, expect, it } from "vitest";
import {
achievementWindowLabel,
groupAchievementsForAnnouncement,
renderAchievementAnnouncement,
type AchievementAnnouncementRow,
} from "@/bot/lib/achievementRender";
const row = (over: Partial<AchievementAnnouncementRow>): AchievementAnnouncementRow => ({
id: 1,
type: "period-champion",
window: "period",
windowStart: "2026-10-12T00:00:00.000Z",
windowEnd: "2026-10-26T00:00:00.000Z",
user: { id: 7, displayName: "Alpha" },
value: 42,
detail: "42 placement points across 5 boards",
...over,
});
describe("Achievement announcement rendering", () => {
it("labels period, month and year windows", () => {
expect(
achievementWindowLabel("period", "2026-10-12T00:00:00.000Z", "2026-10-26T00:00:00.000Z"),
).toBe("Oct 12 to Oct 25, 2026");
expect(
achievementWindowLabel("month", "2026-10-01T00:00:00.000Z", "2026-11-01T00:00:00.000Z"),
).toBe("October 2026");
expect(
achievementWindowLabel("year", "2026-01-01T00:00:00.000Z", "2027-01-01T00:00:00.000Z"),
).toBe("2026");
});
it("groups by window and orders awards canonically", () => {
const groups = groupAchievementsForAnnouncement([
row({ id: 3, type: "precision", user: { id: 9, username: "charlie" } }),
row({ id: 1, type: "period-champion" }),
row({ id: 2, type: "diligence", user: { id: 8, displayName: "Bravo" } }),
row({
id: 4,
type: "player-of-month",
window: "month",
windowStart: "2026-10-01T00:00:00.000Z",
windowEnd: "2026-11-01T00:00:00.000Z",
}),
]);
expect(groups).toHaveLength(2);
expect(groups.map((group) => group.label)).toEqual(["October 2026", "Oct 12 to Oct 25, 2026"]);
expect(groups[0].achievements.map((a) => a.type)).toEqual(["player-of-month"]);
expect(groups[1].achievements.map((a) => a.type)).toEqual([
"period-champion",
"diligence",
"precision",
]);
});
it("renders one embed shape per group with the winner and detail", () => {
const [group] = groupAchievementsForAnnouncement([
row({ id: 1, type: "period-champion" }),
row({ id: 2, type: "dedication", detail: "1h 12m played", user: { id: 8, displayName: "Bravo" } }),
]);
const rendered = renderAchievementAnnouncement(group);
expect(rendered.title).toBe("Minigame results: Oct 12 to Oct 25, 2026");
expect(rendered.fields).toEqual([
{ name: "Period Champion", value: "Alpha · 42 placement points across 5 boards" },
{ name: "Dedication (Most Time)", value: "Bravo · 1h 12m played" },
]);
});
it("falls back for an unknown award type and an unpopulated user", () => {
const [group] = groupAchievementsForAnnouncement([
row({ type: "mystery-award", user: 5, detail: null }),
]);
const rendered = renderAchievementAnnouncement(group);
expect(rendered.fields[0].name).toBe("mystery-award");
expect(rendered.fields[0].value).toBe("Unknown · 42");
});
});

View file

@ -0,0 +1,120 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { User } from "@/payload-types";
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
import { closeDuePeriods } from "@/lib/minigames/periods/lifecycle";
const ANCHOR = "2026-08-03T00:00:00.000Z";
const RUN = `mgnotif-${Date.now().toString(36)}`;
let payload: Payload;
let userA: number;
let originalRules: Record<string, unknown> | null = null;
const notificationsFor = async (userId: number) => {
const res = await payload.find({
collection: "user-notifications",
where: { and: [{ user: { equals: userId } }, { type: { equals: "minigame:achievement" } }] },
limit: 50,
depth: 0,
overrideAccess: true,
});
return res.docs;
};
describe("Minigame achievement notifications", () => {
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
await clearMinigameData();
originalRules = (await payload.findGlobal({
slug: "minigame-rules",
depth: 0,
overrideAccess: true,
})) as unknown as Record<string, unknown> | null;
await payload.updateGlobal({
slug: "minigame-rules",
data: {
enabled: true,
anchorDate: ANCHOR,
periodLengthDays: 14,
placementLadderTopN: 10,
precisionMinAttempts: 1,
},
overrideAccess: true,
});
userA = (
(await payload.create({
collection: "users",
data: {
username: `${RUN}-a`,
discordUsername: `${RUN}-a`,
displayName: "Notified Operator",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User
).id;
await recordMinigameEntry({
payload,
userId: userA,
game: "flappy",
score: 7,
durationMs: 1_000,
now: new Date("2026-08-04T12:00:00.000Z"),
});
});
afterAll(async () => {
await clearMinigameData();
if (!originalRules) return;
await payload
.updateGlobal({
slug: "minigame-rules",
data: {
enabled: Boolean(originalRules.enabled),
anchorDate: originalRules.anchorDate as string,
periodLengthDays: (originalRules.periodLengthDays as number) ?? 14,
placementLadderTopN: (originalRules.placementLadderTopN as number) ?? 10,
precisionMinAttempts: (originalRules.precisionMinAttempts as number) ?? 5,
},
overrideAccess: true,
})
.catch(() => undefined);
});
it("notifies winners in-app on close, and does not repeat on a re-run", async () => {
const summary = await closeDuePeriods(payload, new Date("2026-08-18T00:00:00.000Z"));
expect(summary.closed).toHaveLength(1);
const afterFirst = await notificationsFor(userA);
expect(afterFirst.length).toBeGreaterThan(0);
expect(afterFirst[0].title).toContain("earned for");
expect(afterFirst[0].link).toBe("/minigames/leaderboards");
// Idempotent close: nothing new is granted, so nothing new is sent.
await closeDuePeriods(payload, new Date("2026-08-18T00:00:00.000Z"));
const afterSecond = await notificationsFor(userA);
expect(afterSecond.length).toBe(afterFirst.length);
});
async function clearMinigameData() {
for (const collection of [
"achievements",
"minigame-entries",
"minigame-periods",
"minigames",
] as const) {
await payload.delete({ collection, where: { id: { greater_than: 0 } }, overrideAccess: true });
}
}
});