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)
This commit is contained in:
parent
8a7d79c369
commit
db9248244d
20 changed files with 42108 additions and 2 deletions
|
|
@ -30,6 +30,7 @@ import { default as default_513af5ed43d616d133e530d8c94232f8 } from '@/component
|
|||
import { default as default_d9c22b951ac6762f436db59b889da382 } from '@/components/admin/awards/CommendationColorField'
|
||||
import { default as default_c3ea68702b5e5f8f2f98055e01c43c8d } from '@/components/admin/awards/RibbonDesigner'
|
||||
import { default as default_2f2033acccb3be245f1a85f7b4271dac } from '@/components/admin/awards/MedalDesigner'
|
||||
import { default as default_701da9bef3b3cc3d8567adf41fa08aa3 } from '@/components/admin/awards/AwardAutomationView'
|
||||
import { default as default_4b88a624e9f0b376cffcc6814d459adb } from '@/components/admin/assignments/AssignmentMembersField'
|
||||
import { default as default_0edde40a6ccd30c893b1227360f69360 } from '@/components/static/TickDurationDescription'
|
||||
import { default as default_2d468cc5cf0b647ffca3201592c20825 } from '@/components/static/WarningMessage'
|
||||
|
|
@ -84,6 +85,7 @@ export const importMap = {
|
|||
"@/components/admin/awards/CommendationColorField#default": default_d9c22b951ac6762f436db59b889da382,
|
||||
"@/components/admin/awards/RibbonDesigner#default": default_c3ea68702b5e5f8f2f98055e01c43c8d,
|
||||
"@/components/admin/awards/MedalDesigner#default": default_2f2033acccb3be245f1a85f7b4271dac,
|
||||
"@/components/admin/awards/AwardAutomationView#default": default_701da9bef3b3cc3d8567adf41fa08aa3,
|
||||
"@/components/admin/assignments/AssignmentMembersField#default": default_4b88a624e9f0b376cffcc6814d459adb,
|
||||
"@/components/static/TickDurationDescription#default": default_0edde40a6ccd30c893b1227360f69360,
|
||||
"@/components/static/WarningMessage#default": default_2d468cc5cf0b647ffca3201592c20825,
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ const TARGET_COLLECTIONS = [
|
|||
{ label: "Voice Submissions", value: "voice-submissions" },
|
||||
{ label: "Chronicle Entries", value: "story-beats" },
|
||||
{ label: "Journals", value: "journals" },
|
||||
{ label: "Awards", value: "awards" },
|
||||
{ label: "Chronicle Entry States", value: "story-beat-states" },
|
||||
{ label: "Custom Minefields", value: "custom-minefields" },
|
||||
{ label: "Custom Minefield Scores", value: "custom-minefield-scores" },
|
||||
|
|
|
|||
112
src/collections/users/AwardRules.ts
Normal file
112
src/collections/users/AwardRules.ts
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
import type { CollectionConfig } from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
import { AWARD_METRICS, METRIC_LABELS, METRIC_OPERATORS, OPERATOR_LABELS } from "@/lib/awards/metrics";
|
||||
|
||||
/**
|
||||
* Declarative grant rules evaluated by the award automation sweeper
|
||||
* (src/lib/awards/automation.ts). Each rule says: when a member's metric
|
||||
* passes `<operator> <value>`, grant them the linked award automatically.
|
||||
*/
|
||||
export const AwardRules: CollectionConfig = {
|
||||
slug: "award-rules",
|
||||
labels: {
|
||||
singular: "Award Rule",
|
||||
plural: "Award Rules",
|
||||
},
|
||||
admin: {
|
||||
group: "Users",
|
||||
useAsTitle: "label",
|
||||
defaultColumns: ["label", "award", "metric", "operator", "value", "active"],
|
||||
description:
|
||||
"Automation rules that grant awards when a member's metric crosses a threshold. Evaluated by the daily award tick and the Evaluate Now view.",
|
||||
components: {
|
||||
views: {
|
||||
awardAutomation: {
|
||||
Component: "@/components/admin/awards/AwardAutomationView",
|
||||
path: "/award-automation",
|
||||
exact: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
access: {
|
||||
read: requirePermission("award-rules:read"),
|
||||
create: requirePermission("award-rules:create"),
|
||||
update: requirePermission("award-rules:update"),
|
||||
delete: requirePermission("award-rules:delete"),
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "label",
|
||||
type: "text",
|
||||
required: true,
|
||||
admin: {
|
||||
description:
|
||||
'Short rule name shown in previews and feed events (e.g. "2 years of service").',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "award",
|
||||
type: "relationship",
|
||||
relationTo: "awards",
|
||||
required: true,
|
||||
admin: {
|
||||
description: "The award granted when the rule fires.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "metric",
|
||||
type: "select",
|
||||
required: true,
|
||||
options: AWARD_METRICS.map((metric) => ({ label: METRIC_LABELS[metric], value: metric })),
|
||||
},
|
||||
{
|
||||
name: "operator",
|
||||
type: "select",
|
||||
required: true,
|
||||
defaultValue: "gte",
|
||||
options: METRIC_OPERATORS.map((operator) => ({
|
||||
label: OPERATOR_LABELS[operator],
|
||||
value: operator,
|
||||
})),
|
||||
},
|
||||
{
|
||||
name: "value",
|
||||
type: "number",
|
||||
required: true,
|
||||
min: 0,
|
||||
admin: {
|
||||
description:
|
||||
"Threshold compared against the metric (years for time-based metrics, counts otherwise).",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "autoRetireLowerTiers",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
admin: {
|
||||
description:
|
||||
"For awards in an advancement series: replace any lower tier the member already holds with this award, preserving their original award date.",
|
||||
condition: (_, siblingData) => Boolean(siblingData?.award),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "oncePerSeries",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
admin: {
|
||||
description:
|
||||
"Skip members who already hold any award in this award's advancement series (use instead of auto-retire when tiers must not stack or upgrade).",
|
||||
condition: (_, siblingData) => Boolean(siblingData?.award),
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "active",
|
||||
type: "checkbox",
|
||||
defaultValue: true,
|
||||
admin: {
|
||||
description: "Inactive rules are ignored by the sweeper.",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
108
src/components/admin/awards/AwardAutomationView.tsx
Normal file
108
src/components/admin/awards/AwardAutomationView.tsx
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { runAwardEvaluation, applyAwardGrants } from "@/lib/awards/automationActions";
|
||||
import type { EvaluationResult } from "@/lib/awards/automation";
|
||||
|
||||
/**
|
||||
* Admin view (award-rules collection): preview which members currently
|
||||
* qualify under the active rules, then apply the grants. Both actions are
|
||||
* idempotent; the sweeper skips members who already hold the award.
|
||||
*/
|
||||
export default function AwardAutomationView() {
|
||||
const [result, setResult] = React.useState<EvaluationResult | null>(null);
|
||||
const [busy, setBusy] = React.useState<"preview" | "apply" | null>(null);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
|
||||
const runPreview = async () => {
|
||||
setBusy("preview");
|
||||
setError(null);
|
||||
const res = await runAwardEvaluation();
|
||||
setBusy(null);
|
||||
if (!res.success) {
|
||||
setError(res.error);
|
||||
return;
|
||||
}
|
||||
setResult(res.result);
|
||||
};
|
||||
|
||||
const runApply = async () => {
|
||||
setBusy("apply");
|
||||
setError(null);
|
||||
const res = await applyAwardGrants();
|
||||
setBusy(null);
|
||||
if (!res.success) {
|
||||
setError(res.error);
|
||||
return;
|
||||
}
|
||||
setResult(res.result);
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ padding: "var(--spacing-6) var(--base)" }}>
|
||||
<h1>Award Automation</h1>
|
||||
<p className="row-layout" style={{ color: "var(--theme-elevation-600)", maxWidth: 640 }}>
|
||||
Evaluate every active award rule against all members. Preview first: nothing is written
|
||||
until you apply. Applying is safe to repeat, members who already hold an award are skipped.
|
||||
</p>
|
||||
|
||||
<div style={{ display: "flex", gap: "var(--spacing-2)", margin: "var(--spacing-4) 0" }}>
|
||||
<Button onClick={runPreview} disabled={busy !== null}>
|
||||
{busy === "preview" ? "Evaluating..." : "Evaluate now (dry run)"}
|
||||
</Button>
|
||||
<Button onClick={runApply} disabled={busy !== null || !result || result.plans.length === 0}>
|
||||
{busy === "apply" ? "Applying..." : "Apply grants"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p style={{ color: "var(--theme-error-500)" }}>{error}</p>
|
||||
)}
|
||||
|
||||
{result && (
|
||||
<>
|
||||
<p>
|
||||
<Badge variant="secondary">{result.dryRun ? "Dry run" : "Applied"}</Badge>{" "}
|
||||
Rules evaluated: {result.rulesEvaluated}, members checked: {result.membersChecked},{" "}
|
||||
{result.dryRun
|
||||
? `would grant ${result.plans.filter((p) => p.kind === "grant").length}, would upgrade ${result.plans.filter((p) => p.kind === "upgrade").length}`
|
||||
: `granted ${result.granted}, upgraded ${result.upgraded}`}
|
||||
, skipped: {result.skips.length}
|
||||
</p>
|
||||
|
||||
{result.plans.length > 0 && (
|
||||
<table cellPadding={6} style={{ width: "100%", borderCollapse: "collapse" }}>
|
||||
<thead>
|
||||
<tr style={{ textAlign: "left", borderBottom: "1px solid var(--theme-elevation-200)" }}>
|
||||
<th>Member</th>
|
||||
<th>Rule</th>
|
||||
<th>Award</th>
|
||||
<th>Metric value</th>
|
||||
<th>Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{result.plans.map((plan, i) => (
|
||||
<tr key={`${plan.ruleId}-${plan.userId}-${i}`} style={{ borderBottom: "1px solid var(--theme-elevation-100)" }}>
|
||||
<td>{plan.username}</td>
|
||||
<td>{plan.ruleLabel}</td>
|
||||
<td>{plan.awardName}</td>
|
||||
<td>{plan.metricValue.toFixed(2)}</td>
|
||||
<td>
|
||||
{plan.kind === "upgrade"
|
||||
? `Upgrade (retires award #${plan.replacesAwardId})`
|
||||
: "Grant"}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{result.plans.length === 0 && <p>No members currently qualify for anything new.</p>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -208,6 +208,7 @@ export const collectionIcons: Record<string, LucideIcon> = {
|
|||
"story-beat-states": BookmarkCheck,
|
||||
"story-beats": ScrollText,
|
||||
journals: NotebookText,
|
||||
"award-rules": Zap,
|
||||
"story-voiceovers": Mic,
|
||||
|
||||
// Server
|
||||
|
|
|
|||
334
src/lib/awards/automation.ts
Normal file
334
src/lib/awards/automation.ts
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
import type { Payload } from "payload";
|
||||
import type { Award, AwardRule, Profile } from "@/payload-types";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
import type { AwardGrantEntry } from "@/lib/awards";
|
||||
import { getAwardsByIds, heldTierOfSeries } from "@/lib/awards/grant";
|
||||
import {
|
||||
qualifiesForRule,
|
||||
resolveMetricValue,
|
||||
sumProgressionXp,
|
||||
type MemberFacts,
|
||||
} from "@/lib/awards/metrics";
|
||||
|
||||
/** A single row in `profile.progression.awards` plus automation bookkeeping. */
|
||||
type MutableGrantEntry = AwardGrantEntry & {
|
||||
upgradedFrom?: number | null;
|
||||
upgradedAt?: string | null;
|
||||
};
|
||||
|
||||
export interface AutomationPlan {
|
||||
ruleId: number;
|
||||
ruleLabel: string;
|
||||
userId: number;
|
||||
username: string;
|
||||
awardId: number;
|
||||
awardName: string;
|
||||
metricValue: number;
|
||||
/** "upgrade" replaces a lower tier of the same series; "grant" appends. */
|
||||
kind: "grant" | "upgrade";
|
||||
/** For upgrades: the award id being replaced (auto-retire). */
|
||||
replacesAwardId?: number;
|
||||
}
|
||||
|
||||
export interface AutomationSkip {
|
||||
ruleId: number;
|
||||
userId: number;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export interface EvaluationResult {
|
||||
dryRun: boolean;
|
||||
rulesEvaluated: number;
|
||||
membersChecked: number;
|
||||
plans: AutomationPlan[];
|
||||
skips: AutomationSkip[];
|
||||
granted: number;
|
||||
upgraded: number;
|
||||
}
|
||||
|
||||
interface ProgressionShape {
|
||||
awards?: MutableGrantEntry[] | null;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
function refId(ref: number | { id?: number } | null | undefined): number | null {
|
||||
if (typeof ref === "number") return ref;
|
||||
if (ref && typeof ref.id === "number") return ref.id;
|
||||
return null;
|
||||
}
|
||||
|
||||
function entryAwardId(entry: MutableGrantEntry): number | null {
|
||||
return refId(entry.award);
|
||||
}
|
||||
|
||||
async function paginate<T>(
|
||||
run: (page: number) => Promise<{ docs: T[]; hasNextPage: boolean }>,
|
||||
): Promise<T[]> {
|
||||
const all: T[] = [];
|
||||
let page = 1;
|
||||
for (;;) {
|
||||
const res = await run(page);
|
||||
all.push(...res.docs);
|
||||
if (!res.hasNextPage) break;
|
||||
page += 1;
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate every active award rule against every member profile and (unless
|
||||
* dry-run) apply the resulting grants. Idempotent: members who already hold
|
||||
* the award (or a higher series tier, or any series tier under oncePerSeries)
|
||||
* are skipped, so re-running never double-grants. Grants land as ordinary
|
||||
* profile rows with `awardedBy: null`, which the Profiles afterChange hook
|
||||
* turns into award:granted notifications exactly like manual admin grants.
|
||||
*/
|
||||
export async function evaluateAwardRules(
|
||||
payload: Payload,
|
||||
options: { dryRun?: boolean; ruleIds?: number[] } = {},
|
||||
): Promise<EvaluationResult> {
|
||||
const dryRun = options.dryRun ?? false;
|
||||
const now = new Date();
|
||||
|
||||
const rulesResult = await payload.find({
|
||||
collection: "award-rules",
|
||||
where: {
|
||||
...(options.ruleIds?.length ? { id: { in: options.ruleIds } } : {}),
|
||||
active: { equals: true },
|
||||
},
|
||||
depth: 1,
|
||||
limit: 200,
|
||||
overrideAccess: true,
|
||||
});
|
||||
const rules = rulesResult.docs.filter((rule): rule is AwardRule & { award: Award } =>
|
||||
Boolean(rule.award && typeof rule.award !== "number"),
|
||||
);
|
||||
|
||||
const profiles = await paginate((page) =>
|
||||
payload.find({
|
||||
collection: "profiles",
|
||||
depth: 0,
|
||||
limit: 500,
|
||||
page,
|
||||
overrideAccess: true,
|
||||
}),
|
||||
);
|
||||
|
||||
const users = await paginate((page) =>
|
||||
payload.find({
|
||||
collection: "users",
|
||||
select: { username: true, displayName: true, createdAt: true },
|
||||
depth: 0,
|
||||
limit: 500,
|
||||
page,
|
||||
overrideAccess: true,
|
||||
}),
|
||||
);
|
||||
const userById = new Map(users.map((user) => [user.id, user]));
|
||||
|
||||
// Missions attended = mission-attendances rows with response "yes".
|
||||
const attendances = await paginate((page) =>
|
||||
payload.find({
|
||||
collection: "mission-attendances",
|
||||
where: { response: { equals: "yes" } },
|
||||
select: { user: true },
|
||||
depth: 0,
|
||||
limit: 1000,
|
||||
page,
|
||||
overrideAccess: true,
|
||||
}),
|
||||
);
|
||||
const attendanceCounts = new Map<number, number>();
|
||||
for (const row of attendances) {
|
||||
const userId = refId(row.user as number | { id?: number });
|
||||
if (userId !== null) {
|
||||
attendanceCounts.set(userId, (attendanceCounts.get(userId) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Every award referenced by any grant row on any profile, so series/tier
|
||||
// lookups stay in-memory. One batch up front; plans mutate working copies
|
||||
// only, so the set never grows mid-run.
|
||||
const referencedAwardIds = new Set<number>();
|
||||
for (const profile of profiles) {
|
||||
for (const entry of (profile.progression as ProgressionShape | undefined)?.awards ?? []) {
|
||||
const id = entryAwardId(entry);
|
||||
if (id !== null) referencedAwardIds.add(id);
|
||||
}
|
||||
}
|
||||
for (const rule of rules) referencedAwardIds.add((rule.award as Award).id);
|
||||
const allAwards = await getAwardsByIds(payload, [...referencedAwardIds]);
|
||||
const awardById = new Map(allAwards.map((award) => [award.id, award]));
|
||||
|
||||
// Working copies so multiple rules against the same profile compose within
|
||||
// one run (e.g. tier 1 grants, then tier 2 upgrades it) and stay idempotent.
|
||||
const workingAwards = new Map<number, MutableGrantEntry[]>();
|
||||
const dirtyProfiles = new Map<number, Profile>();
|
||||
|
||||
const plans: AutomationPlan[] = [];
|
||||
const skips: AutomationSkip[] = [];
|
||||
|
||||
// Evaluate lower tiers first so an upgrade chain resolves in one pass.
|
||||
const orderedRules = [...rules].sort(
|
||||
(a, b) =>
|
||||
((a.award as Award).advancement?.tier ?? 0) - ((b.award as Award).advancement?.tier ?? 0),
|
||||
);
|
||||
|
||||
for (const rule of orderedRules) {
|
||||
const award = rule.award as Award;
|
||||
for (const profile of profiles) {
|
||||
const userId = refId(profile.user as number | { id?: number });
|
||||
if (userId === null) continue;
|
||||
const user = userById.get(userId);
|
||||
if (!user) continue;
|
||||
|
||||
const facts: MemberFacts = {
|
||||
enlistmentDate: profile.dossier?.enlistmentDate ?? null,
|
||||
accountCreatedAt: user.createdAt,
|
||||
missionsAttended: attendanceCounts.get(userId) ?? 0,
|
||||
xpTotal: sumProgressionXp(profile.progression),
|
||||
};
|
||||
if (!qualifiesForRule(rule, facts, now)) continue;
|
||||
|
||||
let current = workingAwards.get(profile.id);
|
||||
if (!current) {
|
||||
current = [
|
||||
...(((profile.progression as ProgressionShape | undefined)?.awards ?? []) as MutableGrantEntry[]),
|
||||
];
|
||||
workingAwards.set(profile.id, current);
|
||||
}
|
||||
|
||||
const heldIds = current
|
||||
.map(entryAwardId)
|
||||
.filter((id): id is number => id !== null);
|
||||
|
||||
// Already holds this exact award: nothing to do, ever.
|
||||
if (heldIds.includes(award.id)) {
|
||||
skips.push({ ruleId: rule.id, userId, reason: "already-held" });
|
||||
continue;
|
||||
}
|
||||
|
||||
const seriesKey = award.advancement?.seriesKey;
|
||||
const targetTier = award.advancement?.tier ?? null;
|
||||
let heldSeriesTier: { tier: number; entry: MutableGrantEntry; awardId: number } | null =
|
||||
null;
|
||||
if (seriesKey) {
|
||||
for (const entry of current) {
|
||||
const heldAwardId = entryAwardId(entry);
|
||||
if (heldAwardId === null) continue;
|
||||
const heldAward = awardById.get(heldAwardId);
|
||||
if (!heldAward) continue;
|
||||
const tier = heldTierOfSeries(heldAward, seriesKey);
|
||||
if (tier !== null) {
|
||||
heldSeriesTier = { tier, entry, awardId: heldAwardId };
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (heldSeriesTier && targetTier !== null) {
|
||||
if (heldSeriesTier.tier >= targetTier) {
|
||||
skips.push({ ruleId: rule.id, userId, reason: "higher-or-equal-tier-held" });
|
||||
continue;
|
||||
}
|
||||
if (!rule.autoRetireLowerTiers) {
|
||||
skips.push({
|
||||
ruleId: rule.id,
|
||||
userId,
|
||||
reason: rule.oncePerSeries ? "once-per-series" : "series-tier-held",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
// Auto-retire: replace the lower tier in place, preserving the date
|
||||
// the member first earned the series (mirrors the manual upgrade).
|
||||
const index = current.indexOf(heldSeriesTier.entry);
|
||||
current[index] = {
|
||||
...heldSeriesTier.entry,
|
||||
award: award.id,
|
||||
awardedBy: null,
|
||||
awardReason: rule.label,
|
||||
upgradedFrom: heldSeriesTier.awardId,
|
||||
upgradedAt: now.toISOString(),
|
||||
};
|
||||
plans.push({
|
||||
ruleId: rule.id,
|
||||
ruleLabel: rule.label,
|
||||
userId,
|
||||
username: user.displayName || user.username || String(userId),
|
||||
awardId: award.id,
|
||||
awardName: award.name,
|
||||
metricValue: resolveMetricValue(rule.metric, facts, now),
|
||||
kind: "upgrade",
|
||||
replacesAwardId: heldSeriesTier.awardId,
|
||||
});
|
||||
dirtyProfiles.set(profile.id, profile);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (rule.oncePerSeries && heldSeriesTier) {
|
||||
skips.push({ ruleId: rule.id, userId, reason: "once-per-series" });
|
||||
continue;
|
||||
}
|
||||
|
||||
current.push({
|
||||
award: award.id,
|
||||
awardedBy: null,
|
||||
awardedAt: now.toISOString(),
|
||||
awardReason: rule.label,
|
||||
});
|
||||
plans.push({
|
||||
ruleId: rule.id,
|
||||
ruleLabel: rule.label,
|
||||
userId,
|
||||
username: user.displayName || user.username || String(userId),
|
||||
awardId: award.id,
|
||||
awardName: award.name,
|
||||
metricValue: resolveMetricValue(rule.metric, facts, now),
|
||||
kind: "grant",
|
||||
});
|
||||
dirtyProfiles.set(profile.id, profile);
|
||||
}
|
||||
}
|
||||
|
||||
let granted = 0;
|
||||
let upgraded = 0;
|
||||
|
||||
if (!dryRun) {
|
||||
for (const profile of dirtyProfiles.values()) {
|
||||
const awards = workingAwards.get(profile.id) ?? [];
|
||||
await payload.update({
|
||||
collection: "profiles",
|
||||
id: profile.id,
|
||||
data: {
|
||||
progression: {
|
||||
...((profile.progression as ProgressionShape | undefined) ?? {}),
|
||||
awards,
|
||||
},
|
||||
} as unknown as Partial<Profile>,
|
||||
overrideAccess: true,
|
||||
});
|
||||
}
|
||||
for (const plan of plans) {
|
||||
if (plan.kind === "upgrade") upgraded += 1;
|
||||
else granted += 1;
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.AwardRuleGranted,
|
||||
message: `${plan.username} automatically received "${plan.awardName}" (${plan.ruleLabel})`,
|
||||
targetCollection: "awards",
|
||||
targetId: plan.awardId,
|
||||
data: { ruleId: plan.ruleId, kind: plan.kind },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
dryRun,
|
||||
rulesEvaluated: orderedRules.length,
|
||||
membersChecked: profiles.length,
|
||||
plans,
|
||||
skips,
|
||||
granted,
|
||||
upgraded,
|
||||
};
|
||||
}
|
||||
60
src/lib/awards/automationActions.ts
Normal file
60
src/lib/awards/automationActions.ts
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
"use server";
|
||||
|
||||
import config from "@payload-config";
|
||||
import { getPayload } from "payload";
|
||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { evaluateAwardRules, type EvaluationResult } from "@/lib/awards/automation";
|
||||
|
||||
async function authorizeEvaluation() {
|
||||
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 (!isPayloadUser(user)) {
|
||||
return { ok: false as const, error: "You must be logged in." };
|
||||
}
|
||||
if (!(await hasPermission(payload, user, "award-rules:update"))) {
|
||||
return { ok: false as const, error: "Missing award-rules:update permission." };
|
||||
}
|
||||
return { ok: true as const, payload };
|
||||
}
|
||||
|
||||
/**
|
||||
* Server actions behind the admin Award Automation view. Both require
|
||||
* award-rules:update; the dry run is the who-qualifies preview and the apply
|
||||
* run performs the actual grants (idempotent either way).
|
||||
*/
|
||||
export async function runAwardEvaluation(): Promise<
|
||||
{ success: true; result: EvaluationResult } | { success: false; error: string }
|
||||
> {
|
||||
try {
|
||||
const auth = await authorizeEvaluation();
|
||||
if (!auth.ok) return { success: false, error: auth.error };
|
||||
const result = await evaluateAwardRules(auth.payload, { dryRun: true });
|
||||
return { success: true, result };
|
||||
} catch (e) {
|
||||
return {
|
||||
success: false,
|
||||
error: e instanceof Error ? e.message : "Unknown error",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyAwardGrants(): Promise<
|
||||
{ success: true; result: EvaluationResult } | { success: false; error: string }
|
||||
> {
|
||||
try {
|
||||
const auth = await authorizeEvaluation();
|
||||
if (!auth.ok) return { success: false, error: auth.error };
|
||||
const result = await evaluateAwardRules(auth.payload, { dryRun: false });
|
||||
return { success: true, result };
|
||||
} catch (e) {
|
||||
return {
|
||||
success: false,
|
||||
error: e instanceof Error ? e.message : "Unknown error",
|
||||
};
|
||||
}
|
||||
}
|
||||
112
src/lib/awards/metrics.ts
Normal file
112
src/lib/awards/metrics.ts
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
/**
|
||||
* Award automation metric resolvers. Pure module (no Payload import): the
|
||||
* sweeper gathers raw `MemberFacts` per profile, and everything derived from
|
||||
* them (metric values, threshold comparisons) is computed here so it is unit
|
||||
* testable without a database.
|
||||
*/
|
||||
|
||||
export const AWARD_METRICS = [
|
||||
"yearsOfService",
|
||||
"accountAge",
|
||||
"missionsAttended",
|
||||
"xpTotal",
|
||||
] as const;
|
||||
|
||||
export type AwardMetric = (typeof AWARD_METRICS)[number];
|
||||
|
||||
export const METRIC_LABELS: Record<AwardMetric, string> = {
|
||||
yearsOfService: "Years of Service",
|
||||
accountAge: "Account Age (years)",
|
||||
missionsAttended: "Missions Attended",
|
||||
xpTotal: "Total XP",
|
||||
};
|
||||
|
||||
export const METRIC_OPERATORS = ["gte", "gt"] as const;
|
||||
export type MetricOperator = (typeof METRIC_OPERATORS)[number];
|
||||
|
||||
export const OPERATOR_LABELS: Record<MetricOperator, string> = {
|
||||
gte: "at least",
|
||||
gt: "more than",
|
||||
};
|
||||
|
||||
/** Raw facts the sweeper collects per member; all metrics derive from these. */
|
||||
export interface MemberFacts {
|
||||
/** profile.dossier.enlistmentDate when set; account age is the fallback. */
|
||||
enlistmentDate: string | null;
|
||||
/** users.createdAt */
|
||||
accountCreatedAt: string;
|
||||
/** Count of mission-attendances rows with response "yes". */
|
||||
missionsAttended: number;
|
||||
/** Sum of every progression xpEarned bucket (minigames, voiceover, contributions). */
|
||||
xpTotal: number;
|
||||
}
|
||||
|
||||
const MS_PER_YEAR = 365.25 * 24 * 60 * 60 * 1000;
|
||||
|
||||
/** Whole-and-fractional years between a date and `now`, clamped at 0. */
|
||||
export function yearsBetween(from: string | Date | null | undefined, now: Date): number {
|
||||
if (!from) return 0;
|
||||
const t = typeof from === "string" ? Date.parse(from) : from.getTime();
|
||||
if (!Number.isFinite(t)) return 0;
|
||||
return Math.max(0, (now.getTime() - t) / MS_PER_YEAR);
|
||||
}
|
||||
|
||||
export function resolveMetricValue(metric: AwardMetric, facts: MemberFacts, now: Date): number {
|
||||
switch (metric) {
|
||||
case "yearsOfService":
|
||||
// Enlistment date is the service clock; accounts without one age from
|
||||
// registration so long-standing members are never unfairly gated out.
|
||||
return yearsBetween(facts.enlistmentDate ?? facts.accountCreatedAt, now);
|
||||
case "accountAge":
|
||||
return yearsBetween(facts.accountCreatedAt, now);
|
||||
case "missionsAttended":
|
||||
return facts.missionsAttended;
|
||||
case "xpTotal":
|
||||
return facts.xpTotal;
|
||||
}
|
||||
}
|
||||
|
||||
export function applyOperator(operator: MetricOperator, actual: number, threshold: number): boolean {
|
||||
return operator === "gt" ? actual > threshold : actual >= threshold;
|
||||
}
|
||||
|
||||
export interface RuleThreshold {
|
||||
metric: AwardMetric;
|
||||
operator: MetricOperator;
|
||||
value: number;
|
||||
}
|
||||
|
||||
export function qualifiesForRule(rule: RuleThreshold, facts: MemberFacts, now: Date): boolean {
|
||||
const actual = resolveMetricValue(rule.metric, facts, now);
|
||||
return applyOperator(rule.operator, actual, rule.value);
|
||||
}
|
||||
|
||||
interface XpBucketLike {
|
||||
xpEarned?: number | null;
|
||||
}
|
||||
|
||||
interface ProgressionLike {
|
||||
minigames?: Record<string, XpBucketLike | null | undefined> | null;
|
||||
voiceover?: XpBucketLike | null;
|
||||
contributions?: XpBucketLike | null;
|
||||
}
|
||||
|
||||
function bucketXp(bucket: XpBucketLike | null | undefined): number {
|
||||
const value = bucket?.xpEarned;
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Total XP across every progression bucket, mirroring the virtual `xp` field
|
||||
* on Profiles (minigame buckets + voiceover + contributions). Accepts the raw
|
||||
* progression group so it can run depth-0 without the virtual hook.
|
||||
*/
|
||||
export function sumProgressionXp(progression: unknown): number {
|
||||
const p = progression as ProgressionLike | null | undefined;
|
||||
if (!p) return 0;
|
||||
let total = bucketXp(p.voiceover) + bucketXp(p.contributions);
|
||||
for (const bucket of Object.values(p.minigames ?? {})) {
|
||||
total += bucketXp(bucket);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
40658
src/migrations/20261012_185409_add_award_rules_automation.json
Normal file
40658
src/migrations/20261012_185409_add_award_rules_automation.json
Normal file
File diff suppressed because it is too large
Load diff
71
src/migrations/20261012_185409_add_award_rules_automation.ts
Normal file
71
src/migrations/20261012_185409_add_award_rules_automation.ts
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -131,6 +131,7 @@ import * as migration_20261012_134242_add_discord_presence_global from './202610
|
|||
import * as migration_20261012_173511_add_sidebar_order_preference from './20261012_173511_add_sidebar_order_preference';
|
||||
import * as migration_20261012_181310_add_journals_collection from './20261012_181310_add_journals_collection';
|
||||
import * as migration_20261012_182016_add_journals_event_target from './20261012_182016_add_journals_event_target';
|
||||
import * as migration_20261012_185409_add_award_rules_automation from './20261012_185409_add_award_rules_automation';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -796,6 +797,11 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261012_182016_add_journals_event_target.up,
|
||||
down: migration_20261012_182016_add_journals_event_target.down,
|
||||
name: '20261012_182016_add_journals_event_target'
|
||||
name: '20261012_182016_add_journals_event_target',
|
||||
},
|
||||
{
|
||||
up: migration_20261012_185409_add_award_rules_automation.up,
|
||||
down: migration_20261012_185409_add_award_rules_automation.down,
|
||||
name: '20261012_185409_add_award_rules_automation'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -85,6 +85,7 @@ export interface Config {
|
|||
ranks: Rank;
|
||||
profiles: Profile;
|
||||
awards: Award;
|
||||
'award-rules': AwardRule;
|
||||
qualifications: Qualification;
|
||||
assignments: Assignment;
|
||||
'assignment-transfers': AssignmentTransfer;
|
||||
|
|
@ -191,6 +192,7 @@ export interface Config {
|
|||
ranks: RanksSelect<false> | RanksSelect<true>;
|
||||
profiles: ProfilesSelect<false> | ProfilesSelect<true>;
|
||||
awards: AwardsSelect<false> | AwardsSelect<true>;
|
||||
'award-rules': AwardRulesSelect<false> | AwardRulesSelect<true>;
|
||||
qualifications: QualificationsSelect<false> | QualificationsSelect<true>;
|
||||
assignments: AssignmentsSelect<false> | AssignmentsSelect<true>;
|
||||
'assignment-transfers': AssignmentTransfersSelect<false> | AssignmentTransfersSelect<true>;
|
||||
|
|
@ -647,6 +649,11 @@ export interface Role {
|
|||
| 'journals:update'
|
||||
| 'journals:delete'
|
||||
| 'admin:journals:manage'
|
||||
| 'award-rules:create'
|
||||
| 'award-rules:read'
|
||||
| 'award-rules:update'
|
||||
| 'award-rules:delete'
|
||||
| 'admin:award-rules:manage'
|
||||
| 'qualifications:create'
|
||||
| 'qualifications:read'
|
||||
| 'qualifications:update'
|
||||
|
|
@ -2763,6 +2770,11 @@ export interface GameEventLog {
|
|||
| 'journals:update'
|
||||
| 'journals:delete'
|
||||
| 'admin:journals:manage'
|
||||
| 'award-rules:create'
|
||||
| 'award-rules:read'
|
||||
| 'award-rules:update'
|
||||
| 'award-rules:delete'
|
||||
| 'admin:award-rules:manage'
|
||||
| 'qualifications:create'
|
||||
| 'qualifications:read'
|
||||
| 'qualifications:update'
|
||||
|
|
@ -3155,6 +3167,7 @@ export interface GameEventLog {
|
|||
| 'voice-submissions'
|
||||
| 'story-beats'
|
||||
| 'journals'
|
||||
| 'awards'
|
||||
| 'story-beat-states'
|
||||
| 'custom-minefields'
|
||||
| 'custom-minefield-scores'
|
||||
|
|
@ -3530,6 +3543,43 @@ export interface Qualification {
|
|||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* Automation rules that grant awards when a member's metric crosses a threshold. Evaluated by the daily award tick and the Evaluate Now view.
|
||||
*
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "award-rules".
|
||||
*/
|
||||
export interface AwardRule {
|
||||
id: number;
|
||||
/**
|
||||
* Short rule name shown in previews and feed events (e.g. "2 years of service").
|
||||
*/
|
||||
label: string;
|
||||
/**
|
||||
* The award granted when the rule fires.
|
||||
*/
|
||||
award: number | Award;
|
||||
metric: 'yearsOfService' | 'accountAge' | 'missionsAttended' | 'xpTotal';
|
||||
operator: 'gte' | 'gt';
|
||||
/**
|
||||
* Threshold compared against the metric (years for time-based metrics, counts otherwise).
|
||||
*/
|
||||
value: number;
|
||||
/**
|
||||
* For awards in an advancement series: replace any lower tier the member already holds with this award, preserving their original award date.
|
||||
*/
|
||||
autoRetireLowerTiers?: boolean | null;
|
||||
/**
|
||||
* Skip members who already hold any award in this award's advancement series (use instead of auto-retire when tiers must not stack or upgrade).
|
||||
*/
|
||||
oncePerSeries?: boolean | null;
|
||||
/**
|
||||
* Inactive rules are ignored by the sweeper.
|
||||
*/
|
||||
active?: boolean | null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "assignment-transfers".
|
||||
|
|
@ -6796,6 +6846,24 @@ export interface PayloadMcpApiKey {
|
|||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
awardRules?: {
|
||||
/**
|
||||
* Allow clients to find award-rules.
|
||||
*/
|
||||
find?: boolean | null;
|
||||
/**
|
||||
* Allow clients to create award-rules.
|
||||
*/
|
||||
create?: boolean | null;
|
||||
/**
|
||||
* Allow clients to update award-rules.
|
||||
*/
|
||||
update?: boolean | null;
|
||||
/**
|
||||
* Allow clients to delete award-rules.
|
||||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
qualifications?: {
|
||||
/**
|
||||
* Allow clients to find qualifications.
|
||||
|
|
@ -8173,6 +8241,10 @@ export interface PayloadLockedDocument {
|
|||
relationTo: 'awards';
|
||||
value: number | Award;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'award-rules';
|
||||
value: number | AwardRule;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'qualifications';
|
||||
value: number | Qualification;
|
||||
|
|
@ -9172,6 +9244,22 @@ export interface AwardsSelect<T extends boolean = true> {
|
|||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "award-rules_select".
|
||||
*/
|
||||
export interface AwardRulesSelect<T extends boolean = true> {
|
||||
label?: T;
|
||||
award?: T;
|
||||
metric?: T;
|
||||
operator?: T;
|
||||
value?: T;
|
||||
autoRetireLowerTiers?: T;
|
||||
oncePerSeries?: T;
|
||||
active?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "qualifications_select".
|
||||
|
|
@ -11297,6 +11385,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
|
|||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
awardRules?:
|
||||
| T
|
||||
| {
|
||||
find?: T;
|
||||
create?: T;
|
||||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
qualifications?:
|
||||
| T
|
||||
| {
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import nodemailer from "nodemailer";
|
|||
import { Users } from "@/collections/users/Users";
|
||||
import { Roles } from "@/collections/users/Roles";
|
||||
import { Awards } from "@/collections/users/Awards";
|
||||
import { AwardRules } from "@/collections/users/AwardRules";
|
||||
import { Media } from "@/collections/Media";
|
||||
import { Ranks } from "@/collections/users/Ranks";
|
||||
import { Profiles } from "@/collections/users/Profiles";
|
||||
|
|
@ -290,6 +291,7 @@ const collections = [
|
|||
Ranks,
|
||||
Profiles,
|
||||
Awards,
|
||||
AwardRules,
|
||||
Qualifications,
|
||||
Assignments,
|
||||
AssignmentTransfers,
|
||||
|
|
@ -527,6 +529,10 @@ export default buildConfig({
|
|||
scriptPath: path.resolve(dirname, "scripts/periodTick.ts"),
|
||||
key: "period-tick",
|
||||
},
|
||||
{
|
||||
scriptPath: path.resolve(dirname, "scripts/awardTick.ts"),
|
||||
key: "award-tick",
|
||||
},
|
||||
{
|
||||
scriptPath: path.resolve(dirname, "scripts/generateNextMission.ts"),
|
||||
key: "generate-mission",
|
||||
|
|
|
|||
|
|
@ -112,6 +112,16 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
|
|||
{ value: "admin:journals:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Award Rules",
|
||||
permissions: [
|
||||
{ value: "award-rules:create", label: "Create" },
|
||||
{ value: "award-rules:read", label: "Read" },
|
||||
{ value: "award-rules:update", label: "Update (also runs Evaluate Now / Apply)" },
|
||||
{ value: "award-rules:delete", label: "Delete" },
|
||||
{ value: "admin:award-rules:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Qualifications",
|
||||
permissions: [
|
||||
|
|
@ -861,6 +871,11 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
|
|||
"journals:update",
|
||||
"journals:delete",
|
||||
"admin:journals:manage",
|
||||
"award-rules:create",
|
||||
"award-rules:read",
|
||||
"award-rules:update",
|
||||
"award-rules:delete",
|
||||
"admin:award-rules:manage",
|
||||
"qualifications:create",
|
||||
"qualifications:read",
|
||||
"qualifications:update",
|
||||
|
|
|
|||
23
src/scripts/awardTick.ts
Normal file
23
src/scripts/awardTick.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import type { SanitizedConfig } from "payload";
|
||||
import { getPayload } from "payload";
|
||||
import { evaluateAwardRules } from "@/lib/awards/automation";
|
||||
import { createBinLogger, errorMessage } from "./lib/binFileLogger";
|
||||
|
||||
export const script = async (config: SanitizedConfig) => {
|
||||
const payload = await getPayload({ config });
|
||||
const log = createBinLogger("award-tick", payload.logger);
|
||||
|
||||
try {
|
||||
log.info("[Award Tick] Evaluating award rules...");
|
||||
const result = await evaluateAwardRules(payload);
|
||||
log.info(
|
||||
`[Award Tick] Complete. Rules ${result.rulesEvaluated}; members ${result.membersChecked}; granted ${result.granted}; upgraded ${result.upgraded}; skipped ${result.skips.length}.`,
|
||||
);
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
log.error(
|
||||
`[Award Tick] Fatal: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
150
src/tools/seed/seedYearsOfServiceRules.ts
Normal file
150
src/tools/seed/seedYearsOfServiceRules.ts
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
/**
|
||||
* Seeds the years-of-service advancement series and its automation rules.
|
||||
*
|
||||
* - Wires the existing "First/Two/Three/Five Years of Service" ribbons into
|
||||
* one advancement series (seriesKey "years-of-service", tier = years).
|
||||
* - Creates one active award-rule per ribbon: yearsOfService >= <years>,
|
||||
* auto-retiring the lower tier so anniversaries upgrade the member's ribbon
|
||||
* in place instead of stacking.
|
||||
*
|
||||
* Idempotent: re-running updates nothing that already exists. Pass
|
||||
* --create-missing to create the ribbons first (local dev databases only;
|
||||
* production already has them).
|
||||
*
|
||||
* Usage: bun src/tools/seed/seedYearsOfServiceRules.ts [--create-missing]
|
||||
*/
|
||||
import { getPayload } from "payload";
|
||||
import config from "@payload-config";
|
||||
import type { Award } from "@/payload-types";
|
||||
|
||||
const SERIES_KEY = "years-of-service";
|
||||
|
||||
const PLAN: ReadonlyArray<{ name: string; tier: number; threshold: number }> = [
|
||||
{ name: "First Year of Service", tier: 1, threshold: 1 },
|
||||
{ name: "Two Years of Service", tier: 2, threshold: 2 },
|
||||
{ name: "Three Years of Service", tier: 3, threshold: 3 },
|
||||
{ name: "Five Years of Service", tier: 5, threshold: 5 },
|
||||
];
|
||||
|
||||
function richText(text: string) {
|
||||
return {
|
||||
root: {
|
||||
type: "root" as const,
|
||||
format: "" as const,
|
||||
indent: 0,
|
||||
version: 1,
|
||||
children: [
|
||||
{
|
||||
type: "paragraph" as const,
|
||||
format: "" as const,
|
||||
indent: 0,
|
||||
version: 1,
|
||||
direction: "ltr" as const,
|
||||
children: [
|
||||
{
|
||||
type: "text" as const,
|
||||
format: 0,
|
||||
style: "",
|
||||
mode: "normal" as const,
|
||||
text,
|
||||
version: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
direction: "ltr" as const,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const payload = await getPayload({ config });
|
||||
const createMissing = process.argv.includes("--create-missing");
|
||||
|
||||
for (const entry of PLAN) {
|
||||
const found = await payload.find({
|
||||
collection: "awards",
|
||||
where: { name: { equals: entry.name } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
let award = found.docs[0] as Award | undefined;
|
||||
|
||||
if (!award && createMissing) {
|
||||
award = (await payload.create({
|
||||
collection: "awards",
|
||||
data: {
|
||||
name: entry.name,
|
||||
description: richText(`Awarded for ${entry.threshold} full years of service.`),
|
||||
type: "ribbon",
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as Award;
|
||||
payload.logger.info(`Created ribbon "${entry.name}"`);
|
||||
}
|
||||
|
||||
if (!award) {
|
||||
payload.logger.warn(`Ribbon "${entry.name}" not found; skipping.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (award.advancement?.seriesKey !== SERIES_KEY || award.advancement?.tier !== entry.tier) {
|
||||
await payload.update({
|
||||
collection: "awards",
|
||||
id: award.id,
|
||||
data: { advancement: { seriesKey: SERIES_KEY, tier: entry.tier } },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
payload.logger.info(
|
||||
`Wired "${entry.name}" into series ${SERIES_KEY} at tier ${entry.tier}`,
|
||||
);
|
||||
}
|
||||
|
||||
const label = `Auto: ${entry.name.toLowerCase()}`;
|
||||
const existingRule = await payload.find({
|
||||
collection: "award-rules",
|
||||
where: { label: { equals: label } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
if (existingRule.docs.length > 0) {
|
||||
payload.logger.info(`Rule "${label}" already exists; skipping.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await payload.create({
|
||||
collection: "award-rules",
|
||||
data: {
|
||||
label,
|
||||
award: award.id,
|
||||
metric: "yearsOfService",
|
||||
operator: "gte",
|
||||
value: entry.threshold,
|
||||
autoRetireLowerTiers: entry.tier > 1,
|
||||
oncePerSeries: false,
|
||||
active: true,
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
});
|
||||
payload.logger.info(
|
||||
`Created rule "${label}" (yearsOfService >= ${entry.threshold}${
|
||||
entry.tier > 1 ? ", auto-retire lower tiers" : ""
|
||||
})`,
|
||||
);
|
||||
}
|
||||
|
||||
payload.logger.info("Years-of-service rules seed complete.");
|
||||
}
|
||||
|
||||
main()
|
||||
.then(() => process.exit(0))
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
|
|
@ -56,7 +56,8 @@ interface GameEventInput {
|
|||
| "form-submissions"
|
||||
| "mission-map-markers"
|
||||
| "contribution-entries"
|
||||
| "journals";
|
||||
| "journals"
|
||||
| "awards";
|
||||
targetId?: number;
|
||||
data?: Record<string, unknown>;
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -213,6 +213,9 @@ export const EventTypes = {
|
|||
JournalUpdated: "journal:updated",
|
||||
JournalDeleted: "journal:deleted",
|
||||
|
||||
// Award automation
|
||||
AwardRuleGranted: "award:rule-granted",
|
||||
|
||||
// Projects
|
||||
ProjectCreate: "project:create",
|
||||
ProjectUpdate: "project:update",
|
||||
|
|
|
|||
250
tests/int/award-automation.int.spec.ts
Normal file
250
tests/int/award-automation.int.spec.ts
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
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");
|
||||
});
|
||||
});
|
||||
97
tests/int/award-metrics.int.spec.ts
Normal file
97
tests/int/award-metrics.int.spec.ts
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
applyOperator,
|
||||
qualifiesForRule,
|
||||
resolveMetricValue,
|
||||
sumProgressionXp,
|
||||
yearsBetween,
|
||||
type MemberFacts,
|
||||
} from "@/lib/awards/metrics";
|
||||
|
||||
const NOW = new Date("2026-10-12T12:00:00Z");
|
||||
const MS_PER_YEAR = 365.25 * 24 * 60 * 60 * 1000;
|
||||
|
||||
function facts(overrides: Partial<MemberFacts> = {}): MemberFacts {
|
||||
return {
|
||||
enlistmentDate: null,
|
||||
accountCreatedAt: "2024-10-12T12:00:00Z",
|
||||
missionsAttended: 0,
|
||||
xpTotal: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("award metric resolvers (pure)", () => {
|
||||
describe("yearsBetween", () => {
|
||||
it("computes fractional years", () => {
|
||||
const twoYearsAgo = new Date(NOW.getTime() - 2 * MS_PER_YEAR).toISOString();
|
||||
expect(yearsBetween(twoYearsAgo, NOW)).toBeCloseTo(2, 5);
|
||||
});
|
||||
|
||||
it("clamps future and invalid dates to 0", () => {
|
||||
expect(yearsBetween("2030-01-01T00:00:00Z", NOW)).toBe(0);
|
||||
expect(yearsBetween("not-a-date", NOW)).toBe(0);
|
||||
expect(yearsBetween(null, NOW)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveMetricValue", () => {
|
||||
it("falls back to account age when enlistment date is missing", () => {
|
||||
const value = resolveMetricValue("yearsOfService", facts(), NOW);
|
||||
expect(value).toBeCloseTo(2, 1);
|
||||
});
|
||||
|
||||
it("prefers enlistment date over account creation", () => {
|
||||
const value = resolveMetricValue(
|
||||
"yearsOfService",
|
||||
facts({ enlistmentDate: "2026-01-12T12:00:00Z" }),
|
||||
NOW,
|
||||
);
|
||||
expect(value).toBeLessThan(1);
|
||||
});
|
||||
|
||||
it("resolves count metrics directly", () => {
|
||||
const f = facts({ missionsAttended: 7, xpTotal: 1234 });
|
||||
expect(resolveMetricValue("missionsAttended", f, NOW)).toBe(7);
|
||||
expect(resolveMetricValue("xpTotal", f, NOW)).toBe(1234);
|
||||
expect(resolveMetricValue("accountAge", f, NOW)).toBeCloseTo(2, 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyOperator / qualifiesForRule", () => {
|
||||
it("gte includes the boundary, gt excludes it", () => {
|
||||
expect(applyOperator("gte", 5, 5)).toBe(true);
|
||||
expect(applyOperator("gt", 5, 5)).toBe(false);
|
||||
expect(applyOperator("gte", 4.9, 5)).toBe(false);
|
||||
expect(applyOperator("gt", 5.1, 5)).toBe(true);
|
||||
});
|
||||
|
||||
it("qualifies via metric + operator + value", () => {
|
||||
const rule = { metric: "missionsAttended" as const, operator: "gte" as const, value: 5 };
|
||||
expect(qualifiesForRule(rule, facts({ missionsAttended: 5 }), NOW)).toBe(true);
|
||||
expect(qualifiesForRule(rule, facts({ missionsAttended: 4 }), NOW)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sumProgressionXp", () => {
|
||||
it("sums minigame, voiceover, and contributions buckets", () => {
|
||||
const total = sumProgressionXp({
|
||||
minigames: {
|
||||
flappyBird: { xpEarned: 10 },
|
||||
poker: { xpEarned: 5 },
|
||||
blackjack: null,
|
||||
},
|
||||
voiceover: { xpEarned: 3 },
|
||||
contributions: { xpEarned: 100 },
|
||||
});
|
||||
expect(total).toBe(118);
|
||||
});
|
||||
|
||||
it("tolerates missing, null, and non-numeric values", () => {
|
||||
expect(sumProgressionXp(undefined)).toBe(0);
|
||||
expect(sumProgressionXp(null)).toBe(0);
|
||||
expect(sumProgressionXp({ contributions: { xpEarned: null } })).toBe(0);
|
||||
expect(sumProgressionXp({ minigames: { poker: { xpEarned: "nope" as never } } })).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
Loading…
Reference in a new issue