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( run: (page: number) => Promise<{ docs: T[]; hasNextPage: boolean }>, ): Promise { 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 { 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(); 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(); 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(); const dirtyProfiles = new Map(); 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, 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, }; }