import { CollectionConfig, type CollectionAfterChangeHook, type CollectionBeforeChangeHook, } from "payload"; import type { User, Award, RibbonSubmission } from "@/payload-types"; import hasRoles from "@/utils/access-control/hasRoles"; import { isSuperuser } from "@/utils/access-control/hasPermission"; import { broadcastToUser } from "@/lib/realtime/bus"; import { notifyUser } from "@/lib/notifications"; import { emitGameEvent } from "@/utils/event-log/emit"; import { EventTypes } from "@/utils/event-log/eventTypes"; import { validateRibbonDesign } from "@/lib/awards/ribbonValidation"; type PayloadType = Awaited>; const submitterIdOf = (user: RibbonSubmission["user"]): number => typeof user === "object" && user !== null ? user.id : user; const reviewerName = (reqUser: unknown): string => { const user = reqUser as Pick | null | undefined; return user?.displayName ?? user?.username ?? "A reviewer"; }; /** * Guard review transition and apply review side effects for ribbon submissions. */ const guardReviewTransition: CollectionBeforeChangeHook = async ({ operation, data, originalDoc, req, }) => { if (operation !== "update") return data; const nextStatus = data?.status; if (!nextStatus || nextStatus === originalDoc?.status) return data; if (nextStatus !== "approved" && nextStatus !== "rejected") return data; // Validate design when transitioning to approved or rejected const designToValidate = data.design ?? originalDoc.design; const validation = validateRibbonDesign(designToValidate); if (!validation.ok) { throw new Error(validation.error); } if (nextStatus === "approved") { // Validate XP and grantor types if (data.awardXp === undefined || data.awardXp < 1) { throw new Error("XP must be at least 1."); } if (!data.grantorTypes || !Array.isArray(data.grantorTypes) || data.grantorTypes.length === 0) { throw new Error("Choose at least one grantor type."); } // Check for name collision const existingAwards = await req.payload.count({ collection: "awards", where: { name: { equals: data.name ?? originalDoc.name } }, overrideAccess: true, }); if (existingAwards.totalDocs > 0) { throw new Error(`An award named ${data.name ?? originalDoc.name} already exists. Rename the ribbon and approve again.`); } } return data; }; const applyReviewSideEffects: CollectionAfterChangeHook = async ({ operation, doc, previousDoc, req, }) => { if (operation !== "update") return doc; if (previousDoc?.status !== "pending") return doc; if (doc.status !== "approved" && doc.status !== "rejected") return doc; const submitterId = submitterIdOf(doc.user); if (doc.status === "approved") { // Create the award with a simple description const descriptionRichText: Award["description"] = { root: { type: "root", children: [ { type: "paragraph", children: [ { type: "text", text: doc.description, format: 0, style: "", mode: "normal", detail: 0, version: 1, }, ], direction: "ltr", format: "", indent: 0, textFormat: 0, textStyle: "", version: 1, }, ], direction: "ltr", format: "", indent: 0, version: 1, }, }; let createdAward: Award | null = null; try { // req joins every nested write to the outer update's transaction; // without it the same-doc update below deadlocks on this hook's row lock. const createdAwardResult = await req.payload.create({ collection: "awards", req, data: { name: doc.name, description: descriptionRichText, type: "ribbon", ribbonDesign: doc.design, experiencePoints: doc.awardXp, grantConfig: { allowedGrantorAssignmentTypes: doc.grantorTypes, recipientScope: doc.recipientScope ?? "same_command", maxGrantsPerGrantor: doc.maxGrantsPerGrantor ?? null, }, }, overrideAccess: true, depth: 0, }); createdAward = createdAwardResult; // Update the submission with award info and reviewer details await req.payload.update({ collection: "ribbon-submissions", id: doc.id, req, data: { award: createdAward.id, reviewedBy: req.user?.id, reviewedAt: new Date().toISOString(), }, overrideAccess: true, depth: 0, }); // Notify user of approval await notifyUser(req.payload, { userId: submitterId, type: "award:ribbon-approved", title: "Ribbon approved", message: `Your ribbon design "${doc.name}" has been approved and is now awardable.`, link: "/awards", }); await emitGameEvent(req.payload, { type: EventTypes.AwardRibbonApproved, message: `${reviewerName(req.user)} approved the ribbon design "${doc.name}"`, actor: typeof req.user === "object" && req.user !== null ? req.user.id : undefined, targetCollection: "ribbon-submissions", targetId: doc.id, data: { submissionId: doc.id, submitterId, decision: "approved", reviewNote: doc.reviewNote ?? null, awardId: createdAward.id, awardName: doc.name, }, }); } catch (error) { req.payload.logger.error( `Failed to create award for ribbon submission ${doc.id}: ${ error instanceof Error ? error.message : String(error) }`, ); // Roll back the partial approval so the reviewer can retry. Nested // writes use req for the same-transaction reason noted above. if (createdAward) { try { await req.payload.delete({ collection: "awards", id: createdAward.id, req, overrideAccess: true, depth: 0, }); } catch (cleanupError) { req.payload.logger.error( `Failed to clean up award ${createdAward.id} after failed approval: ${ cleanupError instanceof Error ? cleanupError.message : String(cleanupError) }`, ); } } await req.payload.update({ collection: "ribbon-submissions", id: doc.id, req, data: { status: "pending", }, overrideAccess: true, depth: 0, }); } } else { // Handle rejection await notifyUser(req.payload, { userId: submitterId, type: "award:ribbon-rejected", title: "Ribbon not approved", message: `Your ribbon design "${doc.name}" was not approved${doc.reviewNote ? `. ${doc.reviewNote}` : "."}`, link: "/awards", }); await emitGameEvent(req.payload, { type: EventTypes.AwardRibbonRejected, message: `${reviewerName(req.user)} rejected the ribbon design "${doc.name}"`, actor: typeof req.user === "object" && req.user !== null ? req.user.id : undefined, targetCollection: "ribbon-submissions", targetId: doc.id, data: { submissionId: doc.id, submitterId, decision: "rejected", reviewNote: doc.reviewNote ?? null, }, }); } return doc; }; export const RibbonSubmissions: CollectionConfig = { slug: "ribbon-submissions", admin: { group: "Awards", useAsTitle: "name", defaultColumns: ["name", "user", "status", "createdAt"], }, access: { read: async ({ req }) => { const user = req.user as User | null; if (!user) return false; // Elevation bypasses the owner scope so reviewers see every submission; // regular users only ever see their own. if (await isSuperuser(req.payload, user)) return true; if (hasRoles(["admin", "developer"], user)) return true; return { user: { equals: user.id } }; }, create: ({ req, data }) => { const user = req.user as User | null; if (!user) return false; if (hasRoles(["admin", "developer"], user)) return true; // Submitters may only create their own submissions. Server actions that // write on behalf of users run with overrideAccess and set `user` themselves. const submittedUser = typeof data?.user === "object" && data?.user !== null ? data.user.id : data?.user; return submittedUser === user.id; }, // Status changes are review actions — submitters must not edit their own docs. update: ({ req }) => hasRoles(["admin", "developer"], req.user), delete: ({ req }) => hasRoles(["developer"], req.user), }, fields: [ { name: "name", type: "text", required: true, maxLength: 60, }, { name: "description", type: "textarea", required: true, maxLength: 300, admin: { description: "What this ribbon is awarded for.", }, }, { name: "design", type: "json", required: true, }, { name: "user", type: "relationship", relationTo: "users", required: true, index: true, admin: { description: "Submitter", }, }, { name: "status", type: "select", required: true, defaultValue: "pending", options: [ { label: "Pending", value: "pending" }, { label: "Approved", value: "approved" }, { label: "Rejected", value: "rejected" }, ], }, { name: "reviewNote", type: "textarea", admin: { description: "Reviewer feedback shown to the submitter.", }, }, { name: "reviewedBy", type: "relationship", relationTo: "users", admin: { condition: (data) => data?.status === "approved" || data?.status === "rejected", }, }, { name: "reviewedAt", type: "date", admin: { condition: (data) => data?.status === "approved" || data?.status === "rejected", }, }, { name: "award", type: "relationship", relationTo: "awards", admin: { description: "Award created after approval", }, }, { name: "awardXp", type: "number", min: 1, admin: { description: "XP awarded for this ribbon", condition: (data) => data?.status === "approved", }, }, { name: "grantorTypes", type: "select", hasMany: true, options: [ { label: "Division Leader", value: "division" }, { label: "Squad Leader", value: "squad" }, { label: "Team Leader", value: "team" }, { label: "Special Assignment Leader", value: "special" }, ], admin: { description: "Who can grant this award", condition: (data) => data?.status === "approved", }, }, { name: "recipientScope", type: "select", options: [ { label: "Own Command (grantor's assignment tree)", value: "same_command" }, { label: "Whitelist (specific assignments)", value: "whitelist" }, { label: "Anyone (unit-wide)", value: "anyone" }, ], defaultValue: "same_command", admin: { description: "Who can receive this award", condition: (data) => data?.status === "approved", }, }, { name: "maxGrantsPerGrantor", type: "number", admin: { description: "Maximum grants per leader (empty = unlimited)", condition: (data) => data?.status === "approved", }, }, ], timestamps: true, hooks: { beforeChange: [guardReviewTransition], afterChange: [applyReviewSideEffects], }, };