import type { Payload } from "payload"; import type { Assignment, Award, Profile } from "@/payload-types"; type AssignmentType = Assignment["type"]; type RecipientScope = "same_command" | "whitelist" | "anyone"; const MAX_TREE_DEPTH = 5; /** Extract the numeric id from a relationship reference (raw id or populated doc). */ function refId(ref: number | { id?: unknown } | null | undefined): number | null { if (typeof ref === "number") return ref; if (ref && typeof ref.id === "number") return ref.id; return null; } /** * Assignments where the given user is the leader and whose type is in * `allowedTypes`. An empty `allowedTypes` means no leader may grant. */ export async function getGrantorAssignments( payload: Payload, userId: number, allowedTypes: readonly AssignmentType[], ): Promise { if (allowedTypes.length === 0) return []; const res = await payload.find({ collection: "assignments", where: { and: [{ leader: { equals: userId } }, { type: { in: [...allowedTypes] } }], }, limit: 100, depth: 0, overrideAccess: true, }); return res.docs; } async function collectMembers( payload: Payload, assignmentId: number, depth: number, collected: Set, ): Promise { if (depth > MAX_TREE_DEPTH) return; let assignment: Assignment | null = null; try { assignment = await payload.findByID({ collection: "assignments", id: assignmentId, depth: 0, overrideAccess: true, }); } catch { return; } if (!assignment) return; const leaderId = refId(assignment.leader); if (leaderId !== null) collected.add(leaderId); for (const member of assignment.members ?? []) { const id = refId(member); if (id !== null) collected.add(id); } for (const sub of assignment.subAssignments ?? []) { const id = refId(sub); if (id !== null) await collectMembers(payload, id, depth + 1, collected); } } /** * All member user ids under an assignment: its leader, its direct members, * and (recursively) the members of its sub-assignments. Depth-capped to * prevent infinite loops on circular sub-assignment graphs. */ export async function getAssignmentTreeMembers( payload: Payload, assignmentId: number, depth = 0, ): Promise { const collected = new Set(); await collectMembers(payload, assignmentId, depth, collected); return [...collected]; } /** * Get awards by their IDs in a single batched find operation. */ export async function getAwardsByIds(payload: Payload, ids: number[]): Promise { if (ids.length === 0) return []; const res = await payload.find({ collection: "awards", where: { id: { in: ids, }, }, limit: 1000, depth: 0, overrideAccess: true, }); return res.docs; } /** * Helper to get the held tier of an award in a series. * Returns the advancement.tier if the award's advancement.seriesKey matches the given key, * otherwise returns null. */ export function heldTierOfSeries(award: Award, seriesKey: string): number | null { const normalizedSeriesKey = seriesKey.trim().toLowerCase().replace(/\s+/g, "-"); if (award.advancement?.seriesKey === normalizedSeriesKey) { return award.advancement.tier ?? null; } return null; } /** * How many times `grantorProfileId` has already issued `awardId` across all * profiles. Scans every profile (depth 0) and counts matching grant rows. * Excludes entries where `upgradedFrom` is set (upgrade entries are exempt from grant accounting). */ export async function countGrantsByGrantor( payload: Payload, awardId: number, grantorProfileId: number, ): Promise { const res = await payload.find({ collection: "profiles", limit: 1000, depth: 0, overrideAccess: true, }); let count = 0; for (const profile of res.docs) { for (const entry of profile.progression?.awards ?? []) { // Skip entries that are upgrades (exempt from grant accounting) if (entry.upgradedFrom) continue; if (refId(entry.award) === awardId && refId(entry.awardedBy) === grantorProfileId) { count += 1; } } } return count; } async function isDirectMember( payload: Payload, assignmentId: number, userId: number, ): Promise { let assignment: Assignment | null = null; try { assignment = await payload.findByID({ collection: "assignments", id: assignmentId, depth: 0, overrideAccess: true, }); } catch { return false; } if (!assignment) return false; if (refId(assignment.leader) === userId) return true; return (assignment.members ?? []).some((m) => refId(m) === userId); } /** * Whether `recipientUserId` may receive an award under the given scope. * - anyone: always eligible * - whitelist: a direct member of any assignment in `whitelistIds` * - same_command: a member of the grantor's assignment tree */ export async function isRecipientEligible( payload: Payload, recipientUserId: number, scope: RecipientScope | null | undefined, grantorAssignmentId?: number, whitelistIds?: (number | Assignment)[] | null, ): Promise { if (!scope || scope === "anyone") return true; if (scope === "whitelist") { const ids = (whitelistIds ?? []) .map((ref) => refId(ref)) .filter((id): id is number => id !== null); for (const assignmentId of ids) { if (await isDirectMember(payload, assignmentId, recipientUserId)) return true; } return false; } if (!grantorAssignmentId) return false; const members = await getAssignmentTreeMembers(payload, grantorAssignmentId); return members.includes(recipientUserId); } /** The profile belonging to `userId`, or null if none exists. */ export async function findUserProfile(payload: Payload, userId: number): Promise { const res = await payload.find({ collection: "profiles", where: { user: { equals: userId } }, limit: 1, depth: 0, overrideAccess: true, }); return res.docs[0] ?? null; }