Compare commits
17 commits
2cc7629690
...
8f91bfedbd
| Author | SHA1 | Date | |
|---|---|---|---|
| 8f91bfedbd | |||
| 0830719561 | |||
| 75817ed3fe | |||
| e96fdb7f58 | |||
| f481efb108 | |||
| 076de5d60c | |||
| 88d674cff6 | |||
| 283cd3f4b2 | |||
| 3cc97bf791 | |||
| 420bc06f84 | |||
| 0a955035a1 | |||
| f1634fb335 | |||
| c323d0d853 | |||
| 49bc918c67 | |||
| 87dc4deadb | |||
| 7f65e0371b | |||
| 9409f31dcf |
25 changed files with 41771 additions and 43 deletions
21
CHANGELOG.md
21
CHANGELOG.md
|
|
@ -1,5 +1,26 @@
|
|||
# Changelog
|
||||
|
||||
# v0.9.2
|
||||
|
||||
Journals now earn contribution XP, alongside a few journal, editor, and navigation fixes.
|
||||
|
||||
### Features
|
||||
|
||||
- **Journal XP.** Publishing a journal entry now earns contribution XP, just like wiki pages, surveys, and planning markers. One entry a day counts, and the composer shows when an entry qualifies.
|
||||
|
||||
### Improvements
|
||||
|
||||
- **Editor spacing.** Paragraphs in the rich text editor now have proper spacing, so a draft reads much like the published entry.
|
||||
- **Nav label.** The contributions leaderboard is now listed as Contributions in the sidebar.
|
||||
|
||||
### Fixes
|
||||
|
||||
- In-world journal dates now show the day you picked instead of the day before.
|
||||
- Journal cards in the list now summarize the opening line instead of running every paragraph together.
|
||||
- Various bug fixes and improvements.
|
||||
|
||||
---
|
||||
|
||||
# v0.9.1
|
||||
|
||||
Journals stay within the campaign timeline, and a live in-universe clock now ticks under the sidebar logo.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "polaris-task-force",
|
||||
"version": "0.9.1",
|
||||
"version": "0.9.2",
|
||||
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
|||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { BEAT_BODY_CLASSES } from "@/lib/story/richtextClasses";
|
||||
import { formatJournalDate } from "@/lib/journals/dates";
|
||||
import { DraftBadge } from "@/components/frontend/story/DraftBadge";
|
||||
import { JournalDetailControls } from "@/components/frontend/journals/JournalDetailControls";
|
||||
import type { JournalDraft, MissionOption } from "@/components/frontend/journals/JournalFormDialog";
|
||||
|
|
@ -18,12 +19,6 @@ export const metadata = {
|
|||
title: "Journal Entry",
|
||||
};
|
||||
|
||||
const DATE_FORMAT = new Intl.DateTimeFormat("en-US", {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
|
||||
function authorName(author: number | User): string {
|
||||
if (typeof author === "number") return "Unknown operator";
|
||||
return author.displayName || author.username || "Unknown operator";
|
||||
|
|
@ -127,7 +122,7 @@ export default async function JournalDetailPage({
|
|||
{dateSource && (
|
||||
<>
|
||||
<span className="text-border">|</span>
|
||||
<span>{DATE_FORMAT.format(new Date(dateSource))}</span>
|
||||
<span>{formatJournalDate(dateSource)}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -7,6 +7,9 @@ import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
|||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { emitGameEvent } from "@/utils/event-log/emit";
|
||||
import { EventTypes } from "@/utils/event-log/eventTypes";
|
||||
import { recordContribution, revokeEntriesForSource } from "@/lib/contributions";
|
||||
import { journalBodyLength } from "@/lib/journals/excerpt";
|
||||
import { JOURNAL_XP_MIN_CHARS } from "@/lib/journals/xp";
|
||||
import type { Journal } from "@/payload-types";
|
||||
|
||||
/**
|
||||
|
|
@ -110,6 +113,18 @@ export async function createJournal(input: JournalInput): Promise<ActionResult<n
|
|||
targetCollection: "journals",
|
||||
targetId: doc.id,
|
||||
});
|
||||
if (journalBodyLength(input.body) >= JOURNAL_XP_MIN_CHARS) {
|
||||
await recordContribution(payload, {
|
||||
userId: user.id,
|
||||
type: "journal-publish",
|
||||
sourceCollection: "journals",
|
||||
sourceId: doc.id,
|
||||
summary: `Published a journal entry: "${doc.title}"`,
|
||||
link: `/journals/${doc.id}`,
|
||||
actorId: user.id,
|
||||
actorName: who,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
revalidatePath("/journals");
|
||||
|
|
@ -169,6 +184,18 @@ export async function updateJournal(
|
|||
targetCollection: "journals",
|
||||
targetId: id,
|
||||
});
|
||||
if (journalBodyLength(input.body) >= JOURNAL_XP_MIN_CHARS) {
|
||||
await recordContribution(payload, {
|
||||
userId: user.id,
|
||||
type: "journal-publish",
|
||||
sourceCollection: "journals",
|
||||
sourceId: id,
|
||||
summary: `Published a journal entry: "${input.title.trim()}"`,
|
||||
link: `/journals/${id}`,
|
||||
actorId: user.id,
|
||||
actorName: who,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
revalidatePath("/journals");
|
||||
|
|
@ -198,6 +225,15 @@ export async function deleteJournal(id: number): Promise<ActionResult> {
|
|||
|
||||
await payload.delete({ collection: "journals", id, overrideAccess: true });
|
||||
|
||||
// Deleting an entry (e.g. spam) pulls back any XP it earned.
|
||||
await revokeEntriesForSource(
|
||||
payload,
|
||||
"journals",
|
||||
id,
|
||||
`The journal entry "${existing.title}" was deleted.`,
|
||||
Number(user.id),
|
||||
);
|
||||
|
||||
const who = user.displayName || user.username || "Someone";
|
||||
await emitGameEvent(payload, {
|
||||
type: EventTypes.JournalDeleted,
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { headers as nextHeaders } from "next/headers";
|
|||
import type { Journal, Mission, User } from "@/payload-types";
|
||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||
import { extractExcerpt } from "@/lib/journals/excerpt";
|
||||
import { formatJournalDate } from "@/lib/journals/dates";
|
||||
import { JournalsList, type JournalCard } from "@/components/frontend/journals/JournalsList";
|
||||
import type { MissionOption } from "@/components/frontend/journals/JournalFormDialog";
|
||||
|
||||
|
|
@ -11,12 +12,6 @@ export const metadata = {
|
|||
title: "Journals",
|
||||
};
|
||||
|
||||
const DATE_FORMAT = new Intl.DateTimeFormat("en-US", {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
|
||||
function missionLabel(mission: Mission): string {
|
||||
return mission.codeName ? `${mission.codeName} · ${mission.name}` : mission.name;
|
||||
}
|
||||
|
|
@ -70,7 +65,7 @@ export default async function JournalsPage() {
|
|||
title: journal.title,
|
||||
status: journal.status,
|
||||
authorName: authorName(journal.author),
|
||||
dateLabel: dateSource ? DATE_FORMAT.format(new Date(dateSource)) : null,
|
||||
dateLabel: formatJournalDate(dateSource),
|
||||
missionLabel: mission ? missionLabel(mission) : null,
|
||||
excerpt: extractExcerpt(journal.body),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -312,6 +312,106 @@
|
|||
}
|
||||
}
|
||||
|
||||
/* "This will earn XP" hint: the sparkles pop in, the copy wipes in from the
|
||||
left, then a gold shimmer sweeps across the copy itself (clipped to the
|
||||
glyphs). The motion is skipped when the user asks for reduced motion; the
|
||||
hint itself still shows, just without animating. Reused wherever a surface
|
||||
grants contribution XP (see components/frontend/contributions/XpHint.tsx). */
|
||||
@keyframes xp-hint-icon-in {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: scale(0.4);
|
||||
}
|
||||
60% {
|
||||
opacity: 1;
|
||||
transform: scale(1.15);
|
||||
}
|
||||
100% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes xp-hint-text-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
clip-path: inset(0 100% 0 0);
|
||||
}
|
||||
60% {
|
||||
opacity: 1;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
clip-path: inset(0 0 0 0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes xp-hint-shimmer {
|
||||
from {
|
||||
background-position: 100% center;
|
||||
}
|
||||
to {
|
||||
background-position: 0% center;
|
||||
}
|
||||
}
|
||||
|
||||
.xp-hint-icon {
|
||||
animation: xp-hint-icon-in 0.4s ease-out both;
|
||||
}
|
||||
|
||||
.xp-hint-text {
|
||||
background-image: linear-gradient(
|
||||
100deg,
|
||||
#fbbf24 0%,
|
||||
#fbbf24 42%,
|
||||
#fff7d6 50%,
|
||||
#fbbf24 58%,
|
||||
#fbbf24 100%
|
||||
);
|
||||
background-size: 250% 100%;
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
color: transparent;
|
||||
animation:
|
||||
xp-hint-text-in 0.45s ease-out 0.5s both,
|
||||
xp-hint-shimmer 2s ease-in-out 1s both;
|
||||
}
|
||||
|
||||
/* The XP amount sits a touch brighter than the copy and carries a soft glow. */
|
||||
.xp-hint-amount {
|
||||
color: #fde68a;
|
||||
text-shadow:
|
||||
0 0 12px rgb(251 191 36 / 0.8),
|
||||
0 0 24px rgb(251 191 36 / 0.4);
|
||||
}
|
||||
|
||||
/* Added when the hint stops applying; it fades up and away before unmounting. */
|
||||
.xp-hint-leaving {
|
||||
transition:
|
||||
opacity 0.25s ease-in,
|
||||
transform 0.25s ease-in;
|
||||
opacity: 0;
|
||||
transform: translateY(-0.25rem);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.xp-hint-icon {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.xp-hint-text {
|
||||
animation: none;
|
||||
background-image: none;
|
||||
-webkit-background-clip: border-box;
|
||||
background-clip: border-box;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.xp-hint-leaving {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
.locker-search-highlight {
|
||||
animation: locker-search-pulse 1.1s ease-in-out infinite;
|
||||
box-shadow: 0 0 0 3px rgb(251 191 36 / 0.9);
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ const SOURCE_LABELS: Record<string, string> = {
|
|||
"wiki-pages": "Wiki Page",
|
||||
"mission-map-markers": "Planning Marker",
|
||||
"form-submissions": "Survey Submission",
|
||||
journals: "Journal Entry",
|
||||
manual: "Manual",
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -292,10 +292,10 @@ export const navigationCommands: NavigationCommand[] = [
|
|||
},
|
||||
{
|
||||
id: "nav:contributions",
|
||||
label: "Leaderboard",
|
||||
label: "Contributions",
|
||||
icon: Trophy,
|
||||
href: "/contributions",
|
||||
keywords: ["contributions", "rankings", "top", "scoreboard", "standings"],
|
||||
keywords: ["contributions", "leaderboard", "rankings", "top", "scoreboard", "standings"],
|
||||
},
|
||||
{
|
||||
id: "nav:voiceover",
|
||||
|
|
|
|||
|
|
@ -183,7 +183,7 @@ export const sidebarData = {
|
|||
icon: Award,
|
||||
},
|
||||
{
|
||||
title: "Leaderboard",
|
||||
title: "Contributions",
|
||||
url: "/contributions",
|
||||
icon: Trophy,
|
||||
},
|
||||
|
|
|
|||
252
src/components/frontend/contributions/ContributionModeration.tsx
Normal file
252
src/components/frontend/contributions/ContributionModeration.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
64
src/components/frontend/contributions/XpHint.tsx
Normal file
64
src/components/frontend/contributions/XpHint.tsx
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { SparklesIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface XpHintProps {
|
||||
/** Whether the hint applies; turning it off fades it out and away. */
|
||||
visible: boolean;
|
||||
/** XP the action will grant. */
|
||||
points: number;
|
||||
/** Optional trailing context, e.g. "from this journal entry". */
|
||||
context?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** Fade-out duration before the hint unmounts (kept in step with the CSS). */
|
||||
const EXIT_MS = 250;
|
||||
|
||||
/**
|
||||
* Small gold "you'll earn N XP" hint. The sparkles pop in, the copy wipes in
|
||||
* from the left, then a gold shimmer sweeps across the copy itself (clipped to
|
||||
* the glyphs). When `visible` turns false the hint fades out before it
|
||||
* unmounts. The animation is skipped under `prefers-reduced-motion`.
|
||||
*/
|
||||
export function XpHint({ visible, points, context, className }: XpHintProps) {
|
||||
const [mounted, setMounted] = React.useState(visible);
|
||||
const [leaving, setLeaving] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (visible) {
|
||||
setMounted(true);
|
||||
setLeaving(false);
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
setLeaving(true);
|
||||
const timer = window.setTimeout(() => {
|
||||
setMounted(false);
|
||||
setLeaving(false);
|
||||
}, EXIT_MS);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [visible, mounted]);
|
||||
|
||||
if (!mounted) return null;
|
||||
|
||||
return (
|
||||
<p
|
||||
className={cn(
|
||||
"flex items-center gap-1.5 text-xs text-amber-400",
|
||||
leaving && "xp-hint-leaving",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<SparklesIcon className="xp-hint-icon size-3.5 shrink-0" />
|
||||
<span className="xp-hint-text">
|
||||
{`Nice - you'll earn `}
|
||||
<strong className="xp-hint-amount font-semibold">{`${points} XP`}</strong>
|
||||
{context ? ` ${context}!` : "!"}
|
||||
</span>
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
|
@ -34,22 +34,23 @@ const EDITOR_NODES = [
|
|||
|
||||
const EDITOR_THEME: EditorThemeClasses = {
|
||||
heading: {
|
||||
h2: "text-lg font-semibold",
|
||||
h3: "text-base font-semibold",
|
||||
h4: "text-sm font-semibold",
|
||||
h2: "mt-4 mb-2 text-lg font-semibold",
|
||||
h3: "mt-3 mb-2 text-base font-semibold",
|
||||
h4: "mt-2 mb-1 text-sm font-semibold",
|
||||
},
|
||||
hr: "my-3 border-border",
|
||||
hr: "my-4 border-border",
|
||||
link: "text-primary underline underline-offset-2",
|
||||
list: {
|
||||
checklist: "pl-6",
|
||||
listitem: "pl-1",
|
||||
listitem: "mb-1 pl-1",
|
||||
listitemChecked: "text-muted-foreground line-through",
|
||||
listitemUnchecked: "",
|
||||
nested: { list: "pl-6", listitem: "pl-1" },
|
||||
ol: "list-decimal pl-6",
|
||||
ul: "list-disc pl-6",
|
||||
ol: "mb-4 list-decimal pl-6",
|
||||
ul: "mb-4 list-disc pl-6",
|
||||
},
|
||||
quote: "border-l-2 border-border pl-3 italic text-muted-foreground",
|
||||
paragraph: "mb-4 last:mb-0",
|
||||
quote: "mb-4 border-l-2 border-border pl-3 italic text-muted-foreground",
|
||||
text: {
|
||||
bold: "font-semibold",
|
||||
code: "rounded-sm bg-muted px-1 font-mono text-xs",
|
||||
|
|
|
|||
|
|
@ -28,6 +28,9 @@ import {
|
|||
type LexicalJson,
|
||||
} from "@/components/frontend/intelligence/LexicalRichTextEditor";
|
||||
import { createJournal, updateJournal } from "@/app/(frontend)/journals/actions";
|
||||
import { XpHint } from "@/components/frontend/contributions/XpHint";
|
||||
import { journalBodyLength } from "@/lib/journals/excerpt";
|
||||
import { JOURNAL_XP_MIN_CHARS, JOURNAL_XP_POINTS } from "@/lib/journals/xp";
|
||||
|
||||
/**
|
||||
* Days the in-game clock runs ahead of real time. The in-world date picker is
|
||||
|
|
@ -143,6 +146,9 @@ export function JournalFormDialog({
|
|||
: "";
|
||||
const dateSubtitle = occurredAt ? `${formatInWorldDate(occurredAt)}${sinceAwakening}` : null;
|
||||
|
||||
// Live body length, so the composer can hint once the entry will earn XP.
|
||||
const bodyLength = journalBodyLength(body);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setSaving(true);
|
||||
const input = {
|
||||
|
|
@ -245,6 +251,11 @@ export function JournalFormDialog({
|
|||
onChange={setBody}
|
||||
placeholder="Write your entry here..."
|
||||
/>
|
||||
<XpHint
|
||||
visible={bodyLength >= JOURNAL_XP_MIN_CHARS}
|
||||
points={JOURNAL_XP_POINTS}
|
||||
context="from this journal entry"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@
|
|||
|
||||
|
||||
Crowdsourced contribution XP: users earn XP for helping build the app (wiki pages, mission
|
||||
planning markers, surveys, manual awards). The XP feeds the existing virtual profile total
|
||||
planning markers, surveys, journal entries, manual awards). The XP feeds the existing virtual
|
||||
profile total
|
||||
(`Profiles.progression.xp`), so it shows up in the sidebar `XPDisplay`, the profile page, and the
|
||||
level ladder with no extra wiring.
|
||||
|
||||
|
|
@ -33,6 +34,7 @@ snapshotted onto each entry, so editing a value rebalances future earnings only.
|
|||
| `wiki-page-edit` | 5 | instant | 30 XP/day cap; min 200-char normalized content delta |
|
||||
| `mission-map-marker` | 2 | queued | first 10 per user per mission |
|
||||
| `survey-completion` | 5 | instant | one per submission (idempotency) |
|
||||
| `journal-publish` | 5 | instant | 25 XP/day cap; min 200-char body; one per entry |
|
||||
| `manual` | grantor-set | instant | reason required, no self-grants below superuser |
|
||||
|
||||
## Service (`src/lib/contributions/`)
|
||||
|
|
@ -64,6 +66,8 @@ update, event, and notification flows through these functions.
|
|||
|
||||
- **Wiki**: `createWikiPage` / `updateWikiPage` award on success (Documentation excluded; edits need
|
||||
a substantive delta, deduped by content hash); `deleteWikiPage` revokes the page's entries.
|
||||
- **Journals**: `createJournal` / `updateJournal` award `journal-publish` when an entry is published
|
||||
with a body of at least 200 chars; `deleteJournal` revokes the entry's XP.
|
||||
- **Surveys**: `formBuilderConfig.ts` `form-submissions` `afterChange` awards `survey-completion`.
|
||||
- **Missions**: `classification.planningMapDelegates` + `afterChange` sweep + `beforeDelete` expire.
|
||||
- **Moderation**: `src/app/(frontend)/contributions/actions.ts` (`grantManualContribution`,
|
||||
|
|
@ -101,4 +105,4 @@ the ledger plus the public event log.
|
|||
schema migration; the `contribution-entries` table and profile column do (migration
|
||||
`20261009_201920_add_contribution_entries`).
|
||||
- The Missions `afterChange` sweep must stay loop-safe: it writes entries/profiles, never missions.
|
||||
- Tests: `tests/int/contributions.int.spec.ts`.
|
||||
- Tests: `tests/int/contributions.int.spec.ts`, `tests/int/journal-contributions.int.spec.ts`.
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ export const CONTRIBUTION_TYPES = [
|
|||
"wiki-page-edit",
|
||||
"mission-map-marker",
|
||||
"survey-completion",
|
||||
"journal-publish",
|
||||
"manual",
|
||||
] as const;
|
||||
|
||||
|
|
@ -29,6 +30,7 @@ export const CONTRIBUTION_SOURCE_COLLECTIONS = [
|
|||
"wiki-pages",
|
||||
"mission-map-markers",
|
||||
"form-submissions",
|
||||
"journals",
|
||||
"manual",
|
||||
] as const;
|
||||
|
||||
|
|
@ -93,6 +95,17 @@ export const CONTRIBUTION_RULES: Record<ContributionType, ContributionRule> = {
|
|||
maxPerMission: null,
|
||||
minEditDeltaChars: null,
|
||||
},
|
||||
"journal-publish": {
|
||||
type: "journal-publish",
|
||||
label: "Journal entry published",
|
||||
points: 25,
|
||||
mode: "instant",
|
||||
// A 25 XP daily cap means one qualifying entry per day earns.
|
||||
description: "Published a journal entry to the Chronicle with a substantive body (one per day).",
|
||||
dailyCap: 25,
|
||||
maxPerMission: null,
|
||||
minEditDeltaChars: null,
|
||||
},
|
||||
manual: {
|
||||
type: "manual",
|
||||
label: "Manual award",
|
||||
|
|
|
|||
20
src/lib/journals/dates.ts
Normal file
20
src/lib/journals/dates.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
/**
|
||||
* Journal date display. `occurredAt` is an in-world *calendar day* stored as UTC
|
||||
* midnight, and the `createdAt` fallback is a UTC instant; both are rendered in
|
||||
* UTC so a machine behind UTC never shows the previous day. Pure and
|
||||
* deterministic (independent of the server/browser timezone).
|
||||
*/
|
||||
|
||||
const UTC_DATE_FORMAT = new Intl.DateTimeFormat("en-US", {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
|
||||
export function formatJournalDate(value: string | Date | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return null;
|
||||
return UTC_DATE_FORMAT.format(date);
|
||||
}
|
||||
|
|
@ -9,28 +9,56 @@ interface LexicalNodeLike {
|
|||
children?: LexicalNodeLike[];
|
||||
}
|
||||
|
||||
/** Block-level nodes that separate one another in the flattened text. */
|
||||
const BLOCK_NODE_TYPES = new Set(["paragraph", "heading", "listitem", "quote"]);
|
||||
|
||||
function collectText(node: LexicalNodeLike, parts: string[], limit: number): boolean {
|
||||
if (node.type === "text" && typeof node.text === "string") {
|
||||
parts.push(node.text);
|
||||
return parts.join("").length >= limit;
|
||||
}
|
||||
if (node.type === "linebreak") {
|
||||
parts.push(" ");
|
||||
return false;
|
||||
}
|
||||
for (const child of node.children ?? []) {
|
||||
if (collectText(child, parts, limit)) return true;
|
||||
}
|
||||
// A line break between blocks, so the first one can be found reliably.
|
||||
if (node.type && BLOCK_NODE_TYPES.has(node.type)) {
|
||||
parts.push("\n");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flattens the first `maxLength` characters of visible text out of a Lexical
|
||||
* editor state. Returns "" for empty/invalid input.
|
||||
* Flatten a Lexical body into a one-line card summary: the text up to the first
|
||||
* block break or `maxLength` characters, whichever comes first, with an
|
||||
* ellipsis when anything was left out. Returns "" for empty/invalid input.
|
||||
*/
|
||||
export function extractExcerpt(body: unknown, maxLength = 180): string {
|
||||
const root = (body as { root?: LexicalNodeLike } | null)?.root;
|
||||
if (!root || !Array.isArray(root.children)) return "";
|
||||
|
||||
const parts: string[] = [];
|
||||
collectText(root, parts, maxLength);
|
||||
const text = parts.join("").replace(/\s+/g, " ").trim();
|
||||
if (text.length <= maxLength) return text;
|
||||
return `${text.slice(0, maxLength - 1).trimEnd()}…`;
|
||||
collectText(root, parts, Number.MAX_SAFE_INTEGER);
|
||||
const full = parts.join("").trim();
|
||||
|
||||
const firstBreak = full.indexOf("\n");
|
||||
const cut = firstBreak >= 0 && firstBreak < maxLength ? firstBreak : maxLength;
|
||||
const text = full.slice(0, cut).replace(/\s+/g, " ").trim();
|
||||
if (full.length <= cut) return text;
|
||||
return `${text}…`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Total visible-text length of a Lexical body (whitespace collapsed), with no
|
||||
* truncation. Used to gate contribution XP so one-word entries do not earn.
|
||||
*/
|
||||
export function journalBodyLength(body: unknown): number {
|
||||
const root = (body as { root?: LexicalNodeLike } | null)?.root;
|
||||
if (!root || !Array.isArray(root.children)) return 0;
|
||||
const parts: string[] = [];
|
||||
collectText(root, parts, Number.MAX_SAFE_INTEGER);
|
||||
return parts.join("").replace(/\s+/g, " ").trim().length;
|
||||
}
|
||||
|
|
|
|||
11
src/lib/journals/xp.ts
Normal file
11
src/lib/journals/xp.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import { CONTRIBUTION_RULES } from "@/lib/contributions/rules";
|
||||
|
||||
/**
|
||||
* Minimum visible body length (chars) for a published journal entry to earn
|
||||
* contribution XP; shorter entries still publish, they just do not count.
|
||||
* Shared by the publish action and the composer's XP hint so they never drift.
|
||||
*/
|
||||
export const JOURNAL_XP_MIN_CHARS = 200;
|
||||
|
||||
/** XP earned for publishing a qualifying journal entry (from the rule table). */
|
||||
export const JOURNAL_XP_POINTS = CONTRIBUTION_RULES["journal-publish"].points ?? 0;
|
||||
40660
src/migrations/20261013_183041_add_journal_contribution_type.json
Normal file
40660
src/migrations/20261013_183041_add_journal_contribution_type.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,19 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TYPE "public"."enum_contribution_entries_type" ADD VALUE 'journal-publish' BEFORE 'manual';
|
||||
ALTER TYPE "public"."enum_contribution_entries_source_collection" ADD VALUE 'journals' BEFORE 'manual';`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "contribution_entries" ALTER COLUMN "type" SET DATA TYPE text;
|
||||
DROP TYPE "public"."enum_contribution_entries_type";
|
||||
CREATE TYPE "public"."enum_contribution_entries_type" AS ENUM('wiki-page-create', 'wiki-page-edit', 'mission-map-marker', 'survey-completion', 'manual');
|
||||
ALTER TABLE "contribution_entries" ALTER COLUMN "type" SET DATA TYPE "public"."enum_contribution_entries_type" USING "type"::"public"."enum_contribution_entries_type";
|
||||
ALTER TABLE "contribution_entries" ALTER COLUMN "source_collection" SET DATA TYPE text;
|
||||
DROP TYPE "public"."enum_contribution_entries_source_collection";
|
||||
CREATE TYPE "public"."enum_contribution_entries_source_collection" AS ENUM('wiki-pages', 'mission-map-markers', 'form-submissions', 'manual');
|
||||
ALTER TABLE "contribution_entries" ALTER COLUMN "source_collection" SET DATA TYPE "public"."enum_contribution_entries_source_collection" USING "source_collection"::"public"."enum_contribution_entries_source_collection";`)
|
||||
}
|
||||
|
|
@ -132,6 +132,7 @@ import * as migration_20261012_173511_add_sidebar_order_preference from './20261
|
|||
import * as migration_20261012_181310_add_journals_collection from './20261012_181310_add_journals_collection';
|
||||
import * as migration_20261012_182016_add_journals_event_target from './20261012_182016_add_journals_event_target';
|
||||
import * as migration_20261012_185409_add_award_rules_automation from './20261012_185409_add_award_rules_automation';
|
||||
import * as migration_20261013_183041_add_journal_contribution_type from './20261013_183041_add_journal_contribution_type';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -802,6 +803,11 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261012_185409_add_award_rules_automation.up,
|
||||
down: migration_20261012_185409_add_award_rules_automation.down,
|
||||
name: '20261012_185409_add_award_rules_automation'
|
||||
name: '20261012_185409_add_award_rules_automation',
|
||||
},
|
||||
{
|
||||
up: migration_20261013_183041_add_journal_contribution_type.up,
|
||||
down: migration_20261013_183041_add_journal_contribution_type.down,
|
||||
name: '20261013_183041_add_journal_contribution_type'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -3729,10 +3729,16 @@ export interface Experience {
|
|||
export interface ContributionEntry {
|
||||
id: number;
|
||||
user: number | User;
|
||||
type: 'wiki-page-create' | 'wiki-page-edit' | 'mission-map-marker' | 'survey-completion' | 'manual';
|
||||
type:
|
||||
| 'wiki-page-create'
|
||||
| 'wiki-page-edit'
|
||||
| 'mission-map-marker'
|
||||
| 'survey-completion'
|
||||
| 'journal-publish'
|
||||
| 'manual';
|
||||
status: 'queued' | 'granted' | 'revoked' | 'expired';
|
||||
points: number;
|
||||
sourceCollection: 'wiki-pages' | 'mission-map-markers' | 'form-submissions' | 'manual';
|
||||
sourceCollection: 'wiki-pages' | 'mission-map-markers' | 'form-submissions' | 'journals' | 'manual';
|
||||
/**
|
||||
* Id of the source document (polymorphic).
|
||||
*/
|
||||
|
|
|
|||
170
tests/int/contributions-moderation.int.spec.ts
Normal file
170
tests/int/contributions-moderation.int.spec.ts
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
/**
|
||||
* Contribution moderation actions: a moderator can grant manual XP and revoke a
|
||||
* grant with a reason (the reason is stored and shown to the earner), and both
|
||||
* are gated on `contribution-entries:moderate`.
|
||||
*/
|
||||
import { getPayload, type Payload } from "payload";
|
||||
import config from "@/payload.config";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi, type MockInstance } from "vitest";
|
||||
|
||||
import type { Role, User } from "@/payload-types";
|
||||
import type { Permission } from "@/permissions";
|
||||
import {
|
||||
grantManualContribution,
|
||||
revokeContribution,
|
||||
} from "@/app/(frontend)/contributions/actions";
|
||||
|
||||
vi.mock("next/headers", () => ({ headers: async () => new Headers() }));
|
||||
vi.mock("next/cache", () => ({ revalidatePath: () => {} }));
|
||||
|
||||
const RUN = `cmod-${Date.now().toString(36)}`;
|
||||
const TIMEOUT = 30_000;
|
||||
|
||||
let payload: Payload;
|
||||
let authSpy: MockInstance;
|
||||
|
||||
describe("Contribution moderation actions", () => {
|
||||
const roleIds: number[] = [];
|
||||
const userIds: number[] = [];
|
||||
let moderator: User;
|
||||
let plain: User;
|
||||
let target: User;
|
||||
|
||||
const makeRole = async (label: string, permissions: Permission[]): Promise<Role> => {
|
||||
const role = (await payload.create({
|
||||
collection: "roles",
|
||||
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, permissions },
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as Role;
|
||||
roleIds.push(role.id);
|
||||
return role;
|
||||
};
|
||||
|
||||
const makeUser = async (label: string, roleId: number): Promise<User> => {
|
||||
const user = (await payload.create({
|
||||
collection: "users",
|
||||
data: {
|
||||
username: `${RUN}-${label}`,
|
||||
discordUsername: `${RUN}-${label}`,
|
||||
displayName: label.toUpperCase(),
|
||||
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
||||
password: "Test123",
|
||||
roleDocs: [roleId],
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as User;
|
||||
userIds.push(user.id);
|
||||
return user;
|
||||
};
|
||||
|
||||
const bucketFor = async (userId: number): Promise<number> => {
|
||||
const res = await payload.find({
|
||||
collection: "profiles",
|
||||
where: { user: { equals: userId } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
select: { progression: { contributions: { xpEarned: true } } },
|
||||
});
|
||||
return res.docs[0]?.progression?.contributions?.xpEarned ?? 0;
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({ config: await config });
|
||||
const modRole = await makeRole("mod", ["contribution-entries:moderate"]);
|
||||
const plainRole = await makeRole("plain", []);
|
||||
moderator = await makeUser("mod", modRole.id);
|
||||
plain = await makeUser("plain", plainRole.id);
|
||||
target = await makeUser("target", plainRole.id);
|
||||
authSpy = vi.spyOn(payload, "auth");
|
||||
}, TIMEOUT);
|
||||
|
||||
afterAll(async () => {
|
||||
authSpy?.mockRestore();
|
||||
for (const id of userIds) {
|
||||
await payload
|
||||
.delete({
|
||||
collection: "contribution-entries",
|
||||
where: { user: { equals: id } },
|
||||
overrideAccess: true,
|
||||
})
|
||||
.catch(() => {});
|
||||
const profiles = await payload
|
||||
.find({ collection: "profiles", where: { user: { equals: id } }, depth: 0, overrideAccess: true })
|
||||
.catch(() => null);
|
||||
for (const profile of profiles?.docs ?? []) {
|
||||
await payload.delete({ collection: "profiles", id: profile.id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of roleIds) {
|
||||
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
}, TIMEOUT);
|
||||
|
||||
it("lets a moderator grant manual XP", async () => {
|
||||
authSpy.mockResolvedValue({ user: moderator });
|
||||
const before = await bucketFor(target.id);
|
||||
const res = await grantManualContribution({
|
||||
userId: target.id,
|
||||
points: 12,
|
||||
summary: "Helped organize the unit event",
|
||||
});
|
||||
expect(res.success).toBe(true);
|
||||
expect(await bucketFor(target.id)).toBe(before + 12);
|
||||
});
|
||||
|
||||
it("requires a reason to grant", async () => {
|
||||
authSpy.mockResolvedValue({ user: moderator });
|
||||
const res = await grantManualContribution({ userId: target.id, points: 5, summary: "x" });
|
||||
expect(res.success).toBe(false);
|
||||
});
|
||||
|
||||
it("blocks a non-moderator from granting", async () => {
|
||||
authSpy.mockResolvedValue({ user: plain });
|
||||
const res = await grantManualContribution({ userId: target.id, points: 5, summary: "nope" });
|
||||
expect(res.success).toBe(false);
|
||||
expect(res.error).toMatch(/not allowed/i);
|
||||
});
|
||||
|
||||
it("revokes a grant with a reason and pulls the XP back", async () => {
|
||||
authSpy.mockResolvedValue({ user: moderator });
|
||||
const grant = await grantManualContribution({
|
||||
userId: target.id,
|
||||
points: 8,
|
||||
summary: "To be revoked",
|
||||
});
|
||||
expect(grant.success).toBe(true);
|
||||
const entryId = grant.data!.entryId;
|
||||
const before = await bucketFor(target.id);
|
||||
|
||||
const res = await revokeContribution({ entryId, reason: "Spam entry" });
|
||||
expect(res.success).toBe(true);
|
||||
expect(await bucketFor(target.id)).toBe(before - 8);
|
||||
|
||||
const entry = await payload.findByID({
|
||||
collection: "contribution-entries",
|
||||
id: entryId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
expect(entry.status).toBe("revoked");
|
||||
expect(entry.revokedReason).toBe("Spam entry");
|
||||
});
|
||||
|
||||
it("requires a reason to revoke", async () => {
|
||||
authSpy.mockResolvedValue({ user: moderator });
|
||||
const res = await revokeContribution({ entryId: 1, reason: "" });
|
||||
expect(res.success).toBe(false);
|
||||
expect(res.error).toMatch(/reason/i);
|
||||
});
|
||||
|
||||
it("blocks a non-moderator from revoking", async () => {
|
||||
authSpy.mockResolvedValue({ user: plain });
|
||||
const res = await revokeContribution({ entryId: 1, reason: "trying" });
|
||||
expect(res.success).toBe(false);
|
||||
expect(res.error).toMatch(/not allowed/i);
|
||||
});
|
||||
});
|
||||
267
tests/int/journal-contributions.int.spec.ts
Normal file
267
tests/int/journal-contributions.int.spec.ts
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
/**
|
||||
* Publishing a journal entry earns contribution XP: a substantive publish
|
||||
* grants 25 XP (immediate), drafts and short entries do not, editing a published
|
||||
* entry never double-counts, only one entry a day earns, and deleting an entry
|
||||
* pulls the XP back. Each grant test uses a fresh author because the rule's
|
||||
* 25 XP daily cap allows a single entry per day.
|
||||
*/
|
||||
import { getPayload, type Payload } from "payload";
|
||||
import config from "@/payload.config";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi, type MockInstance } from "vitest";
|
||||
|
||||
import type { Journal, User } from "@/payload-types";
|
||||
import { createJournal, deleteJournal, updateJournal } from "@/app/(frontend)/journals/actions";
|
||||
import { extractExcerpt, journalBodyLength } from "@/lib/journals/excerpt";
|
||||
import { formatJournalDate } from "@/lib/journals/dates";
|
||||
import { recordContribution } from "@/lib/contributions";
|
||||
|
||||
// The actions read next/headers and call next/cache outside a request scope.
|
||||
vi.mock("next/headers", () => ({ headers: async () => new Headers() }));
|
||||
vi.mock("next/cache", () => ({ revalidatePath: () => {} }));
|
||||
|
||||
const RUN = `jx-${Date.now().toString(36)}`;
|
||||
const TIMEOUT = 30_000;
|
||||
|
||||
let payload: Payload;
|
||||
let authSpy: MockInstance;
|
||||
|
||||
function journalBody(text: string): Journal["body"] {
|
||||
return {
|
||||
root: {
|
||||
type: "root",
|
||||
format: "",
|
||||
indent: 0,
|
||||
version: 1,
|
||||
direction: null,
|
||||
children: [
|
||||
{
|
||||
type: "paragraph",
|
||||
format: "",
|
||||
indent: 0,
|
||||
version: 1,
|
||||
direction: null,
|
||||
textFormat: 0,
|
||||
textStyle: "",
|
||||
children: [
|
||||
{ type: "text", format: 0, version: 1, mode: "normal", style: "", text, detail: 0 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
} as Journal["body"];
|
||||
}
|
||||
|
||||
describe("Journal contribution XP", () => {
|
||||
const userIds: number[] = [];
|
||||
const journalIds: number[] = [];
|
||||
|
||||
const makeUser = async (label: string): Promise<User> => {
|
||||
const created = (await payload.create({
|
||||
collection: "users",
|
||||
data: {
|
||||
username: `${RUN}-${label}`,
|
||||
discordUsername: `${RUN}-${label}`,
|
||||
displayName: label.toUpperCase(),
|
||||
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
||||
password: "Test123",
|
||||
roles: ["user"],
|
||||
},
|
||||
overrideAccess: true,
|
||||
depth: 0,
|
||||
})) as unknown as User;
|
||||
userIds.push(created.id);
|
||||
return created;
|
||||
};
|
||||
|
||||
const bucketFor = async (userId: number): Promise<number> => {
|
||||
const res = await payload.find({
|
||||
collection: "profiles",
|
||||
where: { user: { equals: userId } },
|
||||
limit: 1,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
select: { progression: { contributions: { xpEarned: true } } },
|
||||
});
|
||||
return res.docs[0]?.progression?.contributions?.xpEarned ?? 0;
|
||||
};
|
||||
|
||||
const publish = async (
|
||||
author: User,
|
||||
title: string,
|
||||
body: Journal["body"],
|
||||
status: "draft" | "published",
|
||||
) => {
|
||||
authSpy.mockResolvedValue({ user: author });
|
||||
const result = await createJournal({ title, body, status, occurredAt: null, mission: null });
|
||||
if (result.data != null) journalIds.push(result.data);
|
||||
return result;
|
||||
};
|
||||
|
||||
const entriesForJournal = (journalId: number) =>
|
||||
payload.find({
|
||||
collection: "contribution-entries",
|
||||
where: {
|
||||
and: [
|
||||
{ sourceCollection: { equals: "journals" } },
|
||||
{ sourceId: { equals: journalId } },
|
||||
],
|
||||
},
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
payload = await getPayload({ config: await config });
|
||||
authSpy = vi.spyOn(payload, "auth");
|
||||
}, TIMEOUT);
|
||||
|
||||
afterAll(async () => {
|
||||
authSpy?.mockRestore();
|
||||
for (const id of journalIds) {
|
||||
await payload.delete({ collection: "journals", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
for (const id of userIds) {
|
||||
await payload
|
||||
.delete({
|
||||
collection: "contribution-entries",
|
||||
where: { user: { equals: id } },
|
||||
overrideAccess: true,
|
||||
})
|
||||
.catch(() => {});
|
||||
const profiles = await payload
|
||||
.find({ collection: "profiles", where: { user: { equals: id } }, depth: 0, overrideAccess: true })
|
||||
.catch(() => null);
|
||||
for (const profile of profiles?.docs ?? []) {
|
||||
await payload.delete({ collection: "profiles", id: profile.id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
||||
}
|
||||
}, TIMEOUT);
|
||||
|
||||
it("grants 25 XP when a substantive entry is published on create", async () => {
|
||||
const author = await makeUser("publish");
|
||||
const before = await bucketFor(author.id);
|
||||
const result = await publish(author, "A long field report", journalBody("x".repeat(250)), "published");
|
||||
expect(result.success).toBe(true);
|
||||
expect(await bucketFor(author.id)).toBe(before + 25);
|
||||
});
|
||||
|
||||
it("does not grant for a draft", async () => {
|
||||
const author = await makeUser("draft");
|
||||
const before = await bucketFor(author.id);
|
||||
const result = await publish(author, "A private draft", journalBody("x".repeat(250)), "draft");
|
||||
expect(result.success).toBe(true);
|
||||
expect(await bucketFor(author.id)).toBe(before);
|
||||
});
|
||||
|
||||
it("does not grant for a published entry below the substance threshold", async () => {
|
||||
const author = await makeUser("short");
|
||||
const before = await bucketFor(author.id);
|
||||
const result = await publish(author, "One word", journalBody("A".repeat(50)), "published");
|
||||
expect(result.success).toBe(true);
|
||||
expect(await bucketFor(author.id)).toBe(before);
|
||||
});
|
||||
|
||||
it("grants on draft -> published and does not double-count on a later edit", async () => {
|
||||
const author = await makeUser("later");
|
||||
const created = await publish(author, "Published later", journalBody("x".repeat(250)), "draft");
|
||||
expect(created.success).toBe(true);
|
||||
const id = created.data as number;
|
||||
const before = await bucketFor(author.id);
|
||||
|
||||
authSpy.mockResolvedValue({ user: author });
|
||||
await updateJournal(id, {
|
||||
title: "Published later",
|
||||
body: journalBody("x".repeat(250)),
|
||||
status: "published",
|
||||
occurredAt: null,
|
||||
mission: null,
|
||||
});
|
||||
expect(await bucketFor(author.id)).toBe(before + 25);
|
||||
|
||||
// A subsequent edit of the already-published entry must not mint again.
|
||||
await updateJournal(id, {
|
||||
title: "Published later, revised",
|
||||
body: journalBody("y".repeat(300)),
|
||||
status: "published",
|
||||
occurredAt: null,
|
||||
mission: null,
|
||||
});
|
||||
expect(await bucketFor(author.id)).toBe(before + 25);
|
||||
|
||||
const entries = await entriesForJournal(id);
|
||||
expect(entries.totalDocs).toBe(1);
|
||||
});
|
||||
|
||||
it("pulls the XP back when the entry is deleted", async () => {
|
||||
const author = await makeUser("delete");
|
||||
const created = await publish(author, "Delete me", journalBody("x".repeat(250)), "published");
|
||||
expect(created.success).toBe(true);
|
||||
const id = created.data as number;
|
||||
const before = await bucketFor(author.id);
|
||||
|
||||
authSpy.mockResolvedValue({ user: author });
|
||||
const result = await deleteJournal(id);
|
||||
expect(result.success).toBe(true);
|
||||
expect(await bucketFor(author.id)).toBe(before - 25);
|
||||
|
||||
const revoked = await entriesForJournal(id);
|
||||
expect(revoked.docs[0]?.status).toBe("revoked");
|
||||
expect(revoked.docs[0]?.revokedReason).toContain("deleted");
|
||||
});
|
||||
|
||||
it("allows a single journal entry per rolling day", async () => {
|
||||
const author = await makeUser("cap");
|
||||
let granted = 0;
|
||||
for (let i = 0; i < 2; i += 1) {
|
||||
const result = await recordContribution(payload, {
|
||||
userId: author.id,
|
||||
type: "journal-publish",
|
||||
sourceCollection: "journals",
|
||||
sourceId: 9_000_000 + i,
|
||||
summary: `cap probe ${i}`,
|
||||
});
|
||||
if (result.status === "granted") granted += 1;
|
||||
}
|
||||
expect(granted).toBe(1);
|
||||
expect(await bucketFor(author.id)).toBe(25);
|
||||
});
|
||||
});
|
||||
|
||||
describe("journal text helpers", () => {
|
||||
it("journalBodyLength counts visible text and treats empty/whitespace bodies as zero", () => {
|
||||
expect(journalBodyLength(journalBody("hello world"))).toBe(11);
|
||||
expect(journalBodyLength(journalBody(" "))).toBe(0);
|
||||
expect(journalBodyLength(null)).toBe(0);
|
||||
expect(journalBodyLength({ root: { children: [] } })).toBe(0);
|
||||
});
|
||||
|
||||
it("extractExcerpt stops at the first block break with an ellipsis", () => {
|
||||
const twoParagraphs = {
|
||||
root: {
|
||||
type: "root",
|
||||
children: [
|
||||
{ type: "paragraph", children: [{ type: "text", text: "First para." }] },
|
||||
{ type: "paragraph", children: [{ type: "text", text: "Second para." }] },
|
||||
],
|
||||
},
|
||||
};
|
||||
expect(extractExcerpt(twoParagraphs)).toBe("First para.…");
|
||||
expect(extractExcerpt(journalBody("hello world"))).toBe("hello world");
|
||||
expect(extractExcerpt(null)).toBe("");
|
||||
});
|
||||
|
||||
it("extractExcerpt truncates a long single block at the limit", () => {
|
||||
const out = extractExcerpt(journalBody("x".repeat(300)), 180);
|
||||
expect(out).toBe(`${"x".repeat(180)}…`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatJournalDate", () => {
|
||||
it("renders the calendar day in UTC regardless of the runner timezone", () => {
|
||||
expect(formatJournalDate("2156-05-10T00:00:00.000Z")).toBe("May 10, 2156");
|
||||
expect(formatJournalDate(null)).toBeNull();
|
||||
expect(formatJournalDate(undefined)).toBeNull();
|
||||
expect(formatJournalDate("not-a-date")).toBeNull();
|
||||
});
|
||||
});
|
||||
Loading…
Reference in a new issue