1
0
Fork 0
polaris-task-force/tests/int/award-automation.int.spec.ts
Z8MB1E db9248244d feat(awards): add award automation platform
- award-rules collection: metric/operator/value threshold rules linked to
  awards, with auto-retire-lower-tiers and once-per-series flags, active
  toggle, and award-rules:* permissions
- src/lib/awards/metrics.ts: pure metric resolvers (years of service from
  dossier.enlistmentDate with account-age fallback, account age, missions
  attended, total XP) plus operator comparison, unit tested
- evaluateAwardRules() sweeper: idempotent, dry-run capable; grants land as
  profile rows with awardedBy null so the existing afterChange hook sends
  award:granted notifications; upgrades replace the lower series tier in
  place preserving the original date; emits award:rule-granted events
- award-tick payload bin for daily evaluation + admin Award Automation
  view with Evaluate now (dry run) preview and Apply grants
- seedYearsOfServiceRules.ts wires the four years-of-service ribbons into
  one advancement series and creates their rules (idempotent, dev seeded)
- migration add_award_rules_automation (table + awards event target enum)
2026-10-12 15:11:38 -04:00

250 lines
7.8 KiB
TypeScript

import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Award, Profile, User } from "@/payload-types";
import { evaluateAwardRules } from "@/lib/awards/automation";
import type { AwardMetric, MetricOperator } from "@/lib/awards/metrics";
const RUN = `awardauto-${Date.now().toString(36)}`;
const YEAR_MS = 365.25 * 24 * 60 * 60 * 1000;
function richText(text: string) {
return {
root: {
type: "root",
format: "" as const,
indent: 0,
version: 1,
children: [
{
type: "paragraph",
format: "" as const,
indent: 0,
version: 1,
children: [
{ type: "text", format: 0, style: "", mode: "normal" as const, text, version: 1 },
],
direction: "ltr" as const,
},
],
direction: "ltr" as const,
},
};
}
describe("Award automation sweeper", () => {
let payload: Payload;
let medalId: number;
let tier1Id: number;
let tier2Id: number;
let tier3Id: number;
let veteranId: number;
let rookieId: number;
let ruleIds: number[] = [];
async function makeAward(name: string, seriesTier?: number): Promise<number> {
const created = (await payload.create({
collection: "awards",
data: {
name,
description: richText(`${RUN} test award`),
type: seriesTier ? "ribbon" : "medal",
...(seriesTier
? { advancement: { seriesKey: `${RUN}-yos`, tier: seriesTier } }
: {}),
},
overrideAccess: true,
depth: 0,
})) as unknown as Award;
return created.id;
}
async function makeUser(username: string): Promise<number> {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${username}`,
discordUsername: `${RUN}-${username}-dc`,
displayName: `${RUN} ${username}`,
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
const profiles = await payload.find({
collection: "profiles",
where: { user: { equals: user.id } },
limit: 1,
depth: 0,
overrideAccess: true,
});
if (!profiles.docs[0]) throw new Error(`profile not auto-created for ${username}`);
return profiles.docs[0].id;
}
async function makeRule(rule: {
label: string;
award: number;
metric: AwardMetric;
operator?: MetricOperator;
value: number;
autoRetireLowerTiers?: boolean;
oncePerSeries?: boolean;
active?: boolean;
}): Promise<number> {
const created = await payload.create({
collection: "award-rules",
data: {
label: rule.label,
award: rule.award,
metric: rule.metric,
operator: rule.operator ?? "gte",
value: rule.value,
autoRetireLowerTiers: rule.autoRetireLowerTiers ?? false,
oncePerSeries: rule.oncePerSeries ?? false,
active: rule.active ?? true,
},
overrideAccess: true,
depth: 0,
});
ruleIds.push(created.id);
return created.id;
}
async function profileAwards(profileId: number) {
const profile = (await payload.findByID({
collection: "profiles",
id: profileId,
depth: 0,
overrideAccess: true,
})) as Profile;
return profile.progression?.awards ?? [];
}
beforeAll(async () => {
const payloadConfig = await config;
payload = await getPayload({ config: payloadConfig });
medalId = await makeAward(`${RUN} Merit Medal`);
tier1Id = await makeAward(`${RUN} YOS Bronze`, 1);
tier2Id = await makeAward(`${RUN} YOS Silver`, 2);
tier3Id = await makeAward(`${RUN} YOS Gold`, 3);
const veteranProfileId = await makeUser("veteran");
veteranId = veteranProfileId;
const rookieProfileId = await makeUser("rookie");
rookieId = rookieProfileId;
// Veteran: enlisted 3 years ago, 150 contribution XP.
await payload.update({
collection: "profiles",
id: veteranProfileId,
data: {
dossier: { enlistmentDate: new Date(Date.now() - 3 * YEAR_MS).toISOString() },
progression: { contributions: { xpEarned: 150 } },
} as unknown as Partial<Profile>,
overrideAccess: true,
depth: 0,
});
// Rookie: enlisted 6 months ago, 10 XP.
await payload.update({
collection: "profiles",
id: rookieProfileId,
data: {
dossier: { enlistmentDate: new Date(Date.now() - 0.5 * YEAR_MS).toISOString() },
progression: { contributions: { xpEarned: 10 } },
} as unknown as Partial<Profile>,
overrideAccess: true,
depth: 0,
});
await makeRule({ label: "100 XP medal", award: medalId, metric: "xpTotal", value: 100 });
await makeRule({ label: "1 year", award: tier1Id, metric: "yearsOfService", value: 1 });
await makeRule({
label: "2 years",
award: tier2Id,
metric: "yearsOfService",
value: 2,
autoRetireLowerTiers: true,
});
await makeRule({
label: "gold once",
award: tier3Id,
metric: "xpTotal",
value: 100,
oncePerSeries: true,
});
await makeRule({
label: "inactive rule",
award: medalId,
metric: "xpTotal",
value: 1,
active: false,
});
});
afterAll(async () => {
for (const id of ruleIds) {
await payload.delete({ collection: "award-rules", id, overrideAccess: true }).catch(() => {});
}
});
it("dry run plans grants and upgrades without writing anything", async () => {
const result = await evaluateAwardRules(payload, { dryRun: true });
expect(result.dryRun).toBe(true);
expect(result.rulesEvaluated).toBe(4); // inactive rule excluded
const veteranPlans = result.plans.filter((p) => p.userId === veteranId);
expect(veteranPlans.map((p) => p.awardId).sort()).toEqual(
[medalId, tier1Id, tier2Id].sort(),
);
const upgradePlan = result.plans.find((p) => p.kind === "upgrade");
expect(upgradePlan?.awardId).toBe(tier2Id);
expect(upgradePlan?.replacesAwardId).toBe(tier1Id);
// oncePerSeries blocks the gold ribbon because the veteran holds the series.
expect(result.skips.some((s) => s.reason === "once-per-series")).toBe(true);
// Nothing written on a dry run.
expect(await profileAwards(veteranId)).toHaveLength(0);
expect(await profileAwards(rookieId)).toHaveLength(0);
});
it("apply writes grants and upgrades, then is idempotent", async () => {
const applied = await evaluateAwardRules(payload);
expect(applied.granted).toBe(2); // medal + tier 1
expect(applied.upgraded).toBe(1); // tier 1 -> tier 2 in place
const veteranAwards = await profileAwards(veteranId);
expect(veteranAwards).toHaveLength(2);
const medalEntry = veteranAwards.find((e) => e.award === medalId);
expect(medalEntry?.awardedBy).toBeNull();
const seriesEntry = veteranAwards.find((e) => e.award === tier2Id);
expect(seriesEntry?.upgradedFrom).toBe(tier1Id);
expect(seriesEntry?.awardedAt).toBeTruthy();
// Rookie never qualifies.
expect(await profileAwards(rookieId)).toHaveLength(0);
// Second run: nothing new to grant.
const rerun = await evaluateAwardRules(payload);
expect(rerun.plans).toHaveLength(0);
expect(rerun.skips.some((s) => s.reason === "already-held")).toBe(true);
expect(await profileAwards(veteranId)).toHaveLength(2);
});
it("emits award:rule-granted game events for applied plans", async () => {
const events = await payload.find({
collection: "game-event-logs",
where: { type: { equals: "award:rule-granted" } },
limit: 50,
depth: 0,
overrideAccess: true,
});
const messages = events.docs.map((doc) => doc.message).join("\n");
expect(messages).toContain("Merit Medal");
expect(messages).toContain("YOS Silver");
});
});