1
0
Fork 0

feat(contributions): add staff moderation panel to grant and revoke XP

This commit is contained in:
Jason Fraley 2026-10-13 14:46:10 -04:00
parent 87dc4deadb
commit 49bc918c67
2 changed files with 306 additions and 6 deletions

View file

@ -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<ReturnType<typeof getPayload>>;
async function resolveNames(
async function resolveUserNames(
payload: Payload,
rows: LeaderboardRow[],
ids: number[],
): Promise<Map<number, string>> {
const ids = [...new Set(rows.map((row) => row.userId))];
const unique = [...new Set(ids)];
const nameById = new Map<number, string>();
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<Map<number, string>> {
return resolveUserNames(
payload,
rows.map((row) => row.userId),
);
}
function toDisplayRows(
rows: LeaderboardRow[],
nameById: Map<number, string>,
@ -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."
/>
</section>
{isModerator && <ContributionModeration entries={moderationEntries} />}
</div>
);
}

View file

@ -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<RecipientSelection[]>([]);
const [grantPoints, setGrantPoints] = React.useState("10");
const [grantReason, setGrantReason] = React.useState("");
const [granting, setGranting] = React.useState(false);
const [revokeEntry, setRevokeEntry] = React.useState<ModerationEntry | null>(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 (
<section className="flex flex-col gap-3">
<div className="flex items-center justify-between gap-3">
<h2 className="flex items-center gap-2 text-sm font-semibold uppercase tracking-wider text-muted-foreground">
<ShieldAlertIcon className="size-4" />
Moderation
</h2>
<Button size="sm" variant="outline" onClick={() => setGrantOpen(true)}>
<SparklesIcon className="size-4" />
Grant XP
</Button>
</div>
{entries.length === 0 ? (
<p className="rounded-lg border border-border px-4 py-3 text-sm italic text-muted-foreground">
No granted contributions on record.
</p>
) : (
<div className="overflow-hidden rounded-lg border border-border">
<ul className="divide-y divide-border/50">
{entries.map((entry) => (
<li key={entry.id} className="flex items-center gap-3 px-4 py-2.5">
<div className="min-w-0 flex-1">
<p className="truncate text-sm">
<span className="font-medium">{entry.userName}</span>
<span className="text-muted-foreground"> · {entry.summary}</span>
</p>
<p className="text-[11px] text-muted-foreground">
{CONTRIBUTION_RULES[entry.type]?.label ?? entry.type}
</p>
</div>
<span className="shrink-0 font-mono text-sm tabular-nums text-emerald-400">
+{entry.points}
</span>
<span className="hidden shrink-0 text-xs text-muted-foreground sm:block">
<ClientDate date={entry.grantedAt} options={{ month: "short", day: "numeric" }} />
</span>
<Button
size="sm"
variant="ghost"
className="shrink-0 text-rose-400 hover:text-rose-300"
onClick={() => {
setRevokeEntry(entry);
setRevokeReason("");
}}
>
<Undo2Icon className="size-4" />
Revoke
</Button>
</li>
))}
</ul>
</div>
)}
<Dialog open={grantOpen} onOpenChange={(open) => !granting && setGrantOpen(open)}>
<DialogContent>
<DialogHeader>
<DialogTitle>Grant XP</DialogTitle>
<DialogDescription>
Award contribution XP for help that has no automatic rule. The member is notified.
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<Label>Recipient</Label>
<RecipientPicker
selectedUsers={recipients}
onSelect={(user) => setRecipients([user])}
onRemove={() => setRecipients([])}
maxSelections={1}
disabled={granting}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="grant-points">XP</Label>
<Input
id="grant-points"
type="number"
min={1}
max={MAX_MANUAL_POINTS}
value={grantPoints}
onChange={(e) => setGrantPoints(e.target.value)}
disabled={granting}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="grant-reason">Reason</Label>
<Textarea
id="grant-reason"
rows={3}
placeholder="What did they do?"
value={grantReason}
onChange={(e) => setGrantReason(e.target.value)}
disabled={granting}
/>
</div>
</div>
<DialogFooter>
<Button variant="ghost" onClick={() => setGrantOpen(false)} disabled={granting}>
Cancel
</Button>
<Button onClick={handleGrant} disabled={granting}>
{granting && <Loader2Icon className="size-4 animate-spin" />}
Grant XP
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog
open={revokeEntry != null}
onOpenChange={(open) => !revoking && !open && setRevokeEntry(null)}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Revoke XP</DialogTitle>
<DialogDescription>
{revokeEntry
? `Pull back ${revokeEntry.points} XP from ${revokeEntry.userName}. The reason is sent to them.`
: ""}
</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-1.5">
<Label htmlFor="revoke-reason">Reason</Label>
<Textarea
id="revoke-reason"
rows={3}
placeholder="Why is this grant being pulled back?"
value={revokeReason}
onChange={(e) => setRevokeReason(e.target.value)}
disabled={revoking}
/>
</div>
<DialogFooter>
<Button variant="ghost" onClick={() => setRevokeEntry(null)} disabled={revoking}>
Cancel
</Button>
<Button variant="destructive" onClick={handleRevoke} disabled={revoking}>
{revoking && <Loader2Icon className="size-4 animate-spin" />}
Revoke XP
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</section>
);
}