diff --git a/src/app/(frontend)/contributions/page.tsx b/src/app/(frontend)/contributions/page.tsx index ec588dd1..199f5481 100644 --- a/src/app/(frontend)/contributions/page.tsx +++ b/src/app/(frontend)/contributions/page.tsx @@ -3,6 +3,7 @@ import { getPayload } from "payload"; import { headers as nextHeaders } from "next/headers"; import { TrophyIcon } from "lucide-react"; import { isPayloadUser } from "@/utils/access-control/isPayloadUser"; +import { hasPermission } from "@/utils/access-control/hasPermission"; import { getContributionLeaderboard, getContributionSummary, @@ -12,21 +13,25 @@ import { ContributionLeaderboard, type LeaderboardDisplayRow, } from "@/components/frontend/contributions/ContributionLeaderboard"; +import { + ContributionModeration, + type ModerationEntry, +} from "@/components/frontend/contributions/ContributionModeration"; type Payload = Awaited>; -async function resolveNames( +async function resolveUserNames( payload: Payload, - rows: LeaderboardRow[], + ids: number[], ): Promise> { - const ids = [...new Set(rows.map((row) => row.userId))]; + const unique = [...new Set(ids)]; const nameById = new Map(); - if (ids.length === 0) return nameById; + if (unique.length === 0) return nameById; const res = await payload.find({ collection: "users", - where: { id: { in: ids } }, - limit: ids.length, + where: { id: { in: unique } }, + limit: unique.length, depth: 0, overrideAccess: true, select: { displayName: true, username: true }, @@ -40,6 +45,16 @@ async function resolveNames( return nameById; } +async function resolveNames( + payload: Payload, + rows: LeaderboardRow[], +): Promise> { + return resolveUserNames( + payload, + rows.map((row) => row.userId), + ); +} + function toDisplayRows( rows: LeaderboardRow[], nameById: Map, @@ -81,6 +96,37 @@ export default async function ContributionsPage() { resolveNames(payload, allRows), ]); + const isModerator = viewer + ? await hasPermission(payload, viewer, "contribution-entries:moderate") + : false; + let moderationEntries: ModerationEntry[] = []; + if (isModerator) { + const granted = await payload.find({ + collection: "contribution-entries", + where: { status: { equals: "granted" } }, + sort: "-createdAt", + limit: 25, + depth: 0, + overrideAccess: true, + }); + const ids = granted.docs.map((doc) => + typeof doc.user === "number" ? doc.user : (doc.user?.id as number), + ); + const nameById = await resolveUserNames(payload, ids); + moderationEntries = granted.docs.map((doc) => { + const userId = typeof doc.user === "number" ? doc.user : (doc.user?.id as number); + return { + id: doc.id, + userId, + userName: nameById.get(userId) ?? `User #${userId}`, + type: doc.type, + points: doc.points, + summary: doc.summary, + grantedAt: doc.grantedAt ?? doc.createdAt, + }; + }); + } + const monthDisplay = toDisplayRows(monthRows, monthNames, currentUserId); const allDisplay = toDisplayRows(allRows, allNames, currentUserId); @@ -152,6 +198,8 @@ export default async function ContributionsPage() { emptyLabel="No contribution XP has been earned yet." /> + + {isModerator && } ); } diff --git a/src/components/frontend/contributions/ContributionModeration.tsx b/src/components/frontend/contributions/ContributionModeration.tsx new file mode 100644 index 00000000..19e29b47 --- /dev/null +++ b/src/components/frontend/contributions/ContributionModeration.tsx @@ -0,0 +1,252 @@ +"use client"; + +import * as React from "react"; +import { useRouter } from "next/navigation"; +import { toast } from "sonner"; +import { Loader2Icon, ShieldAlertIcon, SparklesIcon, Undo2Icon } from "lucide-react"; + +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Textarea } from "@/components/ui/textarea"; +import { + RecipientPicker, + type RecipientSelection, +} from "@/components/frontend/account/RecipientPicker"; +import { ClientDate } from "@/components/frontend/ClientDate"; +import { + grantManualContribution, + revokeContribution, +} from "@/app/(frontend)/contributions/actions"; +import { CONTRIBUTION_RULES, type ContributionType } from "@/lib/contributions/rules"; + +export interface ModerationEntry { + id: number; + userId: number; + userName: string; + type: ContributionType; + points: number; + summary: string; + grantedAt: string; +} + +const MIN_REASON = 3; +const MAX_MANUAL_POINTS = 1000; + +/** + * Staff moderation surface for contribution XP: grant a manual award, or + * revoke a granted entry with a reason the earner is notified about. Gated on + * `contribution-entries:moderate`; the server actions re-check that permission. + */ +export function ContributionModeration({ entries }: { entries: ModerationEntry[] }) { + const router = useRouter(); + + const [grantOpen, setGrantOpen] = React.useState(false); + const [recipients, setRecipients] = React.useState([]); + const [grantPoints, setGrantPoints] = React.useState("10"); + const [grantReason, setGrantReason] = React.useState(""); + const [granting, setGranting] = React.useState(false); + + const [revokeEntry, setRevokeEntry] = React.useState(null); + const [revokeReason, setRevokeReason] = React.useState(""); + const [revoking, setRevoking] = React.useState(false); + + async function handleGrant() { + const recipient = recipients[0]; + const points = Math.floor(Number(grantPoints)); + const summary = grantReason.trim(); + if (!recipient) return toast.error("Pick a recipient."); + if (!Number.isFinite(points) || points < 1 || points > MAX_MANUAL_POINTS) { + return toast.error(`Points must be between 1 and ${MAX_MANUAL_POINTS}.`); + } + if (summary.length < MIN_REASON) return toast.error("A reason is required."); + + setGranting(true); + const res = await grantManualContribution({ userId: recipient.id, points, summary }); + setGranting(false); + if (!res.success) return toast.error(res.error ?? "Failed to grant XP."); + + toast.success(`Granted ${points} XP to ${recipient.displayName || recipient.username}.`); + setGrantOpen(false); + setRecipients([]); + setGrantPoints("10"); + setGrantReason(""); + router.refresh(); + } + + async function handleRevoke() { + if (!revokeEntry) return; + const reason = revokeReason.trim(); + if (reason.length < MIN_REASON) return toast.error("A reason is required."); + + setRevoking(true); + const res = await revokeContribution({ entryId: revokeEntry.id, reason }); + setRevoking(false); + if (!res.success) return toast.error(res.error ?? "Failed to revoke XP."); + + toast.success(`Revoked ${revokeEntry.points} XP from ${revokeEntry.userName}.`); + setRevokeEntry(null); + setRevokeReason(""); + router.refresh(); + } + + return ( +
+
+

+ + Moderation +

+ +
+ + {entries.length === 0 ? ( +

+ No granted contributions on record. +

+ ) : ( +
+
    + {entries.map((entry) => ( +
  • +
    +

    + {entry.userName} + ยท {entry.summary} +

    +

    + {CONTRIBUTION_RULES[entry.type]?.label ?? entry.type} +

    +
    + + +{entry.points} + + + + + +
  • + ))} +
+
+ )} + + !granting && setGrantOpen(open)}> + + + Grant XP + + Award contribution XP for help that has no automatic rule. The member is notified. + + + +
+
+ + setRecipients([user])} + onRemove={() => setRecipients([])} + maxSelections={1} + disabled={granting} + /> +
+
+ + setGrantPoints(e.target.value)} + disabled={granting} + /> +
+
+ +