1
0
Fork 0
polaris-task-force/src/lib/awards/metrics.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

112 lines
3.7 KiB
TypeScript

/**
* 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;
}