feat(journals): member-authored journal entries with author-owned publishing
- New Journals collection (Chronicle group): title, Lexical body, status draft/published, optional in-world date and mission link; authors read, edit, and delete their own entries at any status while every logged-in user reads published ones; journals:* staff permissions bypass ownership and gate the admin page (registered in the permission registry) - /journals list with compose dialog and /journals/[id] reader reusing the Chronicle typography; edit/delete controls for authors and staff; drafts carry the DraftBadge and stay invisible to everyone but their author - Server actions create/update/delete with ownership checks, publish-time journal:created and journal:deleted feed events (journals added to the GameEventLogs target collection enum via migration) - Sidebar entry under Chronicle, command palette destination, admin panel icon; excerpt extractor as a pure module (src/lib/journals/excerpt.ts) - Access-control integration spec covers draft privacy, publish visibility, non-author write blocking, and staff override (5 tests)
This commit is contained in:
parent
3604c1d146
commit
8a7d79c369
23 changed files with 82310 additions and 2 deletions
146
src/app/(frontend)/journals/[id]/page.tsx
Normal file
146
src/app/(frontend)/journals/[id]/page.tsx
Normal file
|
|
@ -0,0 +1,146 @@
|
||||||
|
import config from "@payload-config";
|
||||||
|
import { getPayload } from "payload";
|
||||||
|
import { headers as nextHeaders } from "next/headers";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { RichText } from "@payloadcms/richtext-lexical/react";
|
||||||
|
import { ArrowLeftIcon } from "lucide-react";
|
||||||
|
import type { Journal, Mission, User } from "@/payload-types";
|
||||||
|
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 { DraftBadge } from "@/components/frontend/story/DraftBadge";
|
||||||
|
import { JournalDetailControls } from "@/components/frontend/journals/JournalDetailControls";
|
||||||
|
import type { JournalDraft, MissionOption } from "@/components/frontend/journals/JournalFormDialog";
|
||||||
|
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function JournalDetailPage({
|
||||||
|
params,
|
||||||
|
}: {
|
||||||
|
params: Promise<{ id: string }>;
|
||||||
|
}) {
|
||||||
|
const { id } = await params;
|
||||||
|
const journalId = Number(id);
|
||||||
|
if (!Number.isInteger(journalId) || journalId <= 0) notFound();
|
||||||
|
|
||||||
|
const payloadConfig = await config;
|
||||||
|
const payload = await getPayload({ config: payloadConfig });
|
||||||
|
const headers = await nextHeaders();
|
||||||
|
const { user } = await payload.auth({ headers, canSetHeaders: false });
|
||||||
|
|
||||||
|
if (!isPayloadUser(user)) return null;
|
||||||
|
|
||||||
|
// Read access is enforced by the collection: drafts of other authors throw
|
||||||
|
// here and fall through to notFound().
|
||||||
|
let journal: Journal | null = null;
|
||||||
|
try {
|
||||||
|
journal = (await payload.findByID({
|
||||||
|
collection: "journals",
|
||||||
|
id: journalId,
|
||||||
|
depth: 1,
|
||||||
|
overrideAccess: false,
|
||||||
|
user,
|
||||||
|
})) as Journal;
|
||||||
|
} catch {
|
||||||
|
journal = null;
|
||||||
|
}
|
||||||
|
if (!journal) notFound();
|
||||||
|
|
||||||
|
const authorId =
|
||||||
|
typeof journal.author === "number" ? journal.author : journal.author?.id ?? null;
|
||||||
|
const isAuthor = authorId !== null && authorId === user.id;
|
||||||
|
const [canUpdate, canDelete] = await Promise.all([
|
||||||
|
hasPermission(payload, user, "journals:update"),
|
||||||
|
hasPermission(payload, user, "journals:delete"),
|
||||||
|
]);
|
||||||
|
const canEdit = canUpdate || isAuthor;
|
||||||
|
const canDeleteEntry = canDelete || isAuthor;
|
||||||
|
|
||||||
|
const mission =
|
||||||
|
journal.mission && typeof journal.mission !== "number" ? (journal.mission as Mission) : null;
|
||||||
|
const dateSource = journal.occurredAt ?? journal.createdAt;
|
||||||
|
const isDraft = journal.status !== "published";
|
||||||
|
|
||||||
|
const missionsResult = await payload.find({
|
||||||
|
collection: "missions",
|
||||||
|
limit: 200,
|
||||||
|
depth: 0,
|
||||||
|
sort: "-id",
|
||||||
|
select: { name: true, codeName: true },
|
||||||
|
overrideAccess: false,
|
||||||
|
user,
|
||||||
|
});
|
||||||
|
const missionOptions: MissionOption[] = (missionsResult.docs as Mission[]).map((m) => ({
|
||||||
|
id: m.id,
|
||||||
|
label: m.codeName ? `${m.codeName} · ${m.name}` : m.name,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const draft: JournalDraft = {
|
||||||
|
id: journal.id,
|
||||||
|
title: journal.title,
|
||||||
|
status: journal.status,
|
||||||
|
occurredAt: journal.occurredAt ? journal.occurredAt.slice(0, 10) : "",
|
||||||
|
missionId: mission?.id ?? null,
|
||||||
|
body: JSON.parse(JSON.stringify(journal.body)) as Record<string, unknown>,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-3xl px-4 py-10">
|
||||||
|
<Link
|
||||||
|
href="/journals"
|
||||||
|
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
|
||||||
|
>
|
||||||
|
<ArrowLeftIcon className="size-4" />
|
||||||
|
All journals
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<header className="mt-4 flex flex-wrap items-start justify-between gap-4">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{isDraft && <DraftBadge />}
|
||||||
|
{mission && (
|
||||||
|
<span className="rounded border border-border px-2 py-0.5 text-xs text-muted-foreground">
|
||||||
|
{mission.codeName ? `${mission.codeName} · ${mission.name}` : mission.name}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<h1 className="mt-2 font-serif text-3xl font-bold leading-tight">{journal.title}</h1>
|
||||||
|
<div className="mt-2 flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
|
||||||
|
<span>{authorName(journal.author)}</span>
|
||||||
|
{dateSource && (
|
||||||
|
<>
|
||||||
|
<span className="text-border">|</span>
|
||||||
|
<span>{DATE_FORMAT.format(new Date(dateSource))}</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<JournalDetailControls
|
||||||
|
draft={draft}
|
||||||
|
missions={missionOptions}
|
||||||
|
canEdit={canEdit}
|
||||||
|
canDelete={canDeleteEntry}
|
||||||
|
/>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<article className={cn("mt-8", BEAT_BODY_CLASSES)}>
|
||||||
|
<RichText data={journal.body} />
|
||||||
|
</article>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
186
src/app/(frontend)/journals/actions.ts
Normal file
186
src/app/(frontend)/journals/actions.ts
Normal file
|
|
@ -0,0 +1,186 @@
|
||||||
|
"use server";
|
||||||
|
|
||||||
|
import config from "@payload-config";
|
||||||
|
import { getPayload } from "payload";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
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 type { Journal } from "@/payload-types";
|
||||||
|
|
||||||
|
export interface ActionResult<T = undefined> {
|
||||||
|
success: boolean;
|
||||||
|
error?: string;
|
||||||
|
data?: T;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function authenticate() {
|
||||||
|
const payloadConfig = await config;
|
||||||
|
const payload = await getPayload({ config: payloadConfig });
|
||||||
|
const { headers } = await import("next/headers");
|
||||||
|
const hdrs = await headers();
|
||||||
|
const { user } = await payload.auth({ headers: hdrs, canSetHeaders: false });
|
||||||
|
|
||||||
|
if (!isPayloadUser(user)) {
|
||||||
|
throw new Error("Unauthorized");
|
||||||
|
}
|
||||||
|
|
||||||
|
return { payload, user };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface JournalInput {
|
||||||
|
title: string;
|
||||||
|
body: unknown;
|
||||||
|
status: "draft" | "published";
|
||||||
|
occurredAt?: string | null;
|
||||||
|
mission?: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function validate(input: JournalInput): string | null {
|
||||||
|
if (!input.title || input.title.trim().length === 0) return "Title is required.";
|
||||||
|
if (input.title.trim().length > 200) return "Title must be 200 characters or fewer.";
|
||||||
|
if (input.status !== "draft" && input.status !== "published") return "Invalid status.";
|
||||||
|
const root = (input.body as { root?: { children?: unknown[] } } | null)?.root;
|
||||||
|
if (!root || !Array.isArray(root.children) || root.children.length === 0) {
|
||||||
|
return "Entry body is required.";
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const toNullableId = (value: number | null | undefined): number | null =>
|
||||||
|
typeof value === "number" ? value : null;
|
||||||
|
|
||||||
|
export async function createJournal(input: JournalInput): Promise<ActionResult<number>> {
|
||||||
|
try {
|
||||||
|
const { payload, user } = await authenticate();
|
||||||
|
const error = validate(input);
|
||||||
|
if (error) return { success: false, error };
|
||||||
|
|
||||||
|
const doc = await payload.create({
|
||||||
|
collection: "journals",
|
||||||
|
data: {
|
||||||
|
title: input.title.trim(),
|
||||||
|
author: user.id,
|
||||||
|
status: input.status,
|
||||||
|
occurredAt: input.occurredAt ?? null,
|
||||||
|
mission: toNullableId(input.mission),
|
||||||
|
body: input.body as Journal["body"],
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (input.status === "published") {
|
||||||
|
const who = user.displayName || user.username || "Someone";
|
||||||
|
await emitGameEvent(payload, {
|
||||||
|
type: EventTypes.JournalCreated,
|
||||||
|
message: `${who} published a journal entry: "${doc.title}"`,
|
||||||
|
actor: user.id,
|
||||||
|
targetCollection: "journals",
|
||||||
|
targetId: doc.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
revalidatePath("/journals");
|
||||||
|
return { success: true, data: doc.id };
|
||||||
|
} catch (e) {
|
||||||
|
const message = e instanceof Error ? e.message : "Unknown error";
|
||||||
|
return { success: false, error: message === "Unauthorized" ? "You must be logged in." : message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authors edit their own entries; journals:update staff may edit any entry.
|
||||||
|
* Publishing (draft -> published) emits the journal:created feed event so
|
||||||
|
* drafts stay silent until their author publishes them.
|
||||||
|
*/
|
||||||
|
export async function updateJournal(
|
||||||
|
id: number,
|
||||||
|
input: JournalInput,
|
||||||
|
): Promise<ActionResult<number>> {
|
||||||
|
try {
|
||||||
|
const { payload, user } = await authenticate();
|
||||||
|
const error = validate(input);
|
||||||
|
if (error) return { success: false, error };
|
||||||
|
|
||||||
|
const existing = await payload.findByID({
|
||||||
|
collection: "journals",
|
||||||
|
id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
const authorId = typeof existing.author === "number" ? existing.author : existing.author?.id;
|
||||||
|
const isStaff = await hasPermission(payload, user, "journals:update");
|
||||||
|
if (!isStaff && authorId !== user.id) {
|
||||||
|
return { success: false, error: "You can only edit your own journal entries." };
|
||||||
|
}
|
||||||
|
|
||||||
|
await payload.update({
|
||||||
|
collection: "journals",
|
||||||
|
id,
|
||||||
|
data: {
|
||||||
|
title: input.title.trim(),
|
||||||
|
status: input.status,
|
||||||
|
occurredAt: input.occurredAt ?? null,
|
||||||
|
mission: toNullableId(input.mission),
|
||||||
|
body: input.body as Journal["body"],
|
||||||
|
},
|
||||||
|
overrideAccess: true,
|
||||||
|
depth: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (existing.status === "draft" && input.status === "published") {
|
||||||
|
const who = user.displayName || user.username || "Someone";
|
||||||
|
await emitGameEvent(payload, {
|
||||||
|
type: EventTypes.JournalCreated,
|
||||||
|
message: `${who} published a journal entry: "${input.title.trim()}"`,
|
||||||
|
actor: user.id,
|
||||||
|
targetCollection: "journals",
|
||||||
|
targetId: id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
revalidatePath("/journals");
|
||||||
|
revalidatePath(`/journals/${id}`);
|
||||||
|
return { success: true, data: id };
|
||||||
|
} catch (e) {
|
||||||
|
const message = e instanceof Error ? e.message : "Unknown error";
|
||||||
|
return { success: false, error: message === "Unauthorized" ? "You must be logged in." : message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteJournal(id: number): Promise<ActionResult> {
|
||||||
|
try {
|
||||||
|
const { payload, user } = await authenticate();
|
||||||
|
|
||||||
|
const existing = await payload.findByID({
|
||||||
|
collection: "journals",
|
||||||
|
id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
const authorId = typeof existing.author === "number" ? existing.author : existing.author?.id;
|
||||||
|
const isStaff = await hasPermission(payload, user, "journals:delete");
|
||||||
|
if (!isStaff && authorId !== user.id) {
|
||||||
|
return { success: false, error: "You can only delete your own journal entries." };
|
||||||
|
}
|
||||||
|
|
||||||
|
await payload.delete({ collection: "journals", id, overrideAccess: true });
|
||||||
|
|
||||||
|
const who = user.displayName || user.username || "Someone";
|
||||||
|
await emitGameEvent(payload, {
|
||||||
|
type: EventTypes.JournalDeleted,
|
||||||
|
message: `${who} removed the journal entry "${existing.title}"`,
|
||||||
|
actor: user.id,
|
||||||
|
targetCollection: "journals",
|
||||||
|
targetId: id,
|
||||||
|
});
|
||||||
|
|
||||||
|
revalidatePath("/journals");
|
||||||
|
return { success: true };
|
||||||
|
} catch (e) {
|
||||||
|
const message = e instanceof Error ? e.message : "Unknown error";
|
||||||
|
return { success: false, error: message === "Unauthorized" ? "You must be logged in." : message };
|
||||||
|
}
|
||||||
|
}
|
||||||
87
src/app/(frontend)/journals/page.tsx
Normal file
87
src/app/(frontend)/journals/page.tsx
Normal file
|
|
@ -0,0 +1,87 @@
|
||||||
|
import config from "@payload-config";
|
||||||
|
import { getPayload } from "payload";
|
||||||
|
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 { JournalsList, type JournalCard } from "@/components/frontend/journals/JournalsList";
|
||||||
|
import type { MissionOption } from "@/components/frontend/journals/JournalFormDialog";
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
function authorName(author: number | User): string {
|
||||||
|
if (typeof author === "number") return "Unknown operator";
|
||||||
|
return author.displayName || author.username || "Unknown operator";
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function JournalsPage() {
|
||||||
|
const payloadConfig = await config;
|
||||||
|
const payload = await getPayload({ config: payloadConfig });
|
||||||
|
const headers = await nextHeaders();
|
||||||
|
const { user } = await payload.auth({ headers, canSetHeaders: false });
|
||||||
|
|
||||||
|
if (!isPayloadUser(user)) return null;
|
||||||
|
|
||||||
|
// The collection's read access already limits non-staff to published docs
|
||||||
|
// plus their own drafts; the explicit filter keeps authors' drafts first-
|
||||||
|
// class in their list without needing a staff permission.
|
||||||
|
const journalsResult = await payload.find({
|
||||||
|
collection: "journals",
|
||||||
|
where: {
|
||||||
|
or: [{ status: { equals: "published" } }, { author: { equals: user.id } }],
|
||||||
|
},
|
||||||
|
sort: "-createdAt",
|
||||||
|
limit: 100,
|
||||||
|
depth: 1,
|
||||||
|
overrideAccess: false,
|
||||||
|
user,
|
||||||
|
});
|
||||||
|
|
||||||
|
const missionsResult = await payload.find({
|
||||||
|
collection: "missions",
|
||||||
|
limit: 200,
|
||||||
|
depth: 0,
|
||||||
|
sort: "-id",
|
||||||
|
select: { name: true, codeName: true },
|
||||||
|
overrideAccess: false,
|
||||||
|
user,
|
||||||
|
});
|
||||||
|
|
||||||
|
const cards: JournalCard[] = (journalsResult.docs as Journal[]).map((journal) => {
|
||||||
|
const mission =
|
||||||
|
journal.mission && typeof journal.mission !== "number" ? (journal.mission as Mission) : null;
|
||||||
|
const dateSource = journal.occurredAt ?? journal.createdAt;
|
||||||
|
return {
|
||||||
|
id: journal.id,
|
||||||
|
title: journal.title,
|
||||||
|
status: journal.status,
|
||||||
|
authorName: authorName(journal.author),
|
||||||
|
dateLabel: dateSource ? DATE_FORMAT.format(new Date(dateSource)) : null,
|
||||||
|
missionLabel: mission ? missionLabel(mission) : null,
|
||||||
|
excerpt: extractExcerpt(journal.body),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const missionOptions: MissionOption[] = (missionsResult.docs as Mission[]).map((mission) => ({
|
||||||
|
id: mission.id,
|
||||||
|
label: missionLabel(mission),
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-6xl px-4 py-10">
|
||||||
|
<JournalsList journals={cards} missions={missionOptions} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -40,6 +40,7 @@ const TARGET_COLLECTIONS = [
|
||||||
{ label: "Voice Scripts", value: "voice-scripts" },
|
{ label: "Voice Scripts", value: "voice-scripts" },
|
||||||
{ label: "Voice Submissions", value: "voice-submissions" },
|
{ label: "Voice Submissions", value: "voice-submissions" },
|
||||||
{ label: "Chronicle Entries", value: "story-beats" },
|
{ label: "Chronicle Entries", value: "story-beats" },
|
||||||
|
{ label: "Journals", value: "journals" },
|
||||||
{ label: "Chronicle Entry States", value: "story-beat-states" },
|
{ label: "Chronicle Entry States", value: "story-beat-states" },
|
||||||
{ label: "Custom Minefields", value: "custom-minefields" },
|
{ label: "Custom Minefields", value: "custom-minefields" },
|
||||||
{ label: "Custom Minefield Scores", value: "custom-minefield-scores" },
|
{ label: "Custom Minefield Scores", value: "custom-minefield-scores" },
|
||||||
|
|
|
||||||
108
src/collections/story/Journals.ts
Normal file
108
src/collections/story/Journals.ts
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
import type { CollectionConfig, Where } from "payload";
|
||||||
|
import { FixedToolbarFeature, lexicalEditor } from "@payloadcms/richtext-lexical";
|
||||||
|
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Member-authored journal entries. Authors publish their own work directly
|
||||||
|
* (no staff review): authors can read/edit/delete their own entries at any
|
||||||
|
* status; every logged-in user reads published entries; staff with
|
||||||
|
* journals:read see everything through the admin panel.
|
||||||
|
*/
|
||||||
|
export const Journals: CollectionConfig = {
|
||||||
|
slug: "journals",
|
||||||
|
labels: {
|
||||||
|
singular: "Journal Entry",
|
||||||
|
plural: "Journals",
|
||||||
|
},
|
||||||
|
admin: {
|
||||||
|
group: "Chronicle",
|
||||||
|
useAsTitle: "title",
|
||||||
|
defaultColumns: ["title", "author", "status", "occurredAt", "createdAt"],
|
||||||
|
listSearchableFields: ["title", "body"],
|
||||||
|
description:
|
||||||
|
"Member-written journals. Drafts are visible to their author and staff only; published entries are readable by any logged-in user on /journals.",
|
||||||
|
},
|
||||||
|
access: {
|
||||||
|
read: async ({ req }): Promise<boolean | Where> => {
|
||||||
|
if (!req.user) return false;
|
||||||
|
if (await hasPermission(req.payload, req.user, "journals:read")) return true;
|
||||||
|
return {
|
||||||
|
or: [{ author: { equals: req.user.id } }, { status: { equals: "published" } }],
|
||||||
|
};
|
||||||
|
},
|
||||||
|
create: ({ req }) => Boolean(req.user),
|
||||||
|
update: async ({ req }): Promise<boolean | Where> => {
|
||||||
|
if (!req.user) return false;
|
||||||
|
if (await hasPermission(req.payload, req.user, "journals:update")) return true;
|
||||||
|
return { author: { equals: req.user.id } };
|
||||||
|
},
|
||||||
|
delete: async ({ req }): Promise<boolean | Where> => {
|
||||||
|
if (!req.user) return false;
|
||||||
|
if (await hasPermission(req.payload, req.user, "journals:delete")) return true;
|
||||||
|
return { author: { equals: req.user.id } };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
name: "title",
|
||||||
|
type: "text",
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "author",
|
||||||
|
type: "relationship",
|
||||||
|
relationTo: "users",
|
||||||
|
required: true,
|
||||||
|
defaultValue: ({ user }) => user?.id,
|
||||||
|
// Ownership is not transferable by authors; only journals:update staff
|
||||||
|
// may reassign an entry (Payload silently strips the field otherwise).
|
||||||
|
access: {
|
||||||
|
update: async ({ req }) =>
|
||||||
|
Boolean(req.user) && (await hasPermission(req.payload, req.user!, "journals:update")),
|
||||||
|
},
|
||||||
|
admin: {
|
||||||
|
description: "Owning member. Authors can always edit their own entries.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "status",
|
||||||
|
type: "select",
|
||||||
|
required: true,
|
||||||
|
defaultValue: "draft",
|
||||||
|
index: true,
|
||||||
|
options: [
|
||||||
|
{ label: "Draft", value: "draft" },
|
||||||
|
{ label: "Published", value: "published" },
|
||||||
|
],
|
||||||
|
admin: {
|
||||||
|
description: "Authors publish directly; no staff review is required.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "occurredAt",
|
||||||
|
type: "date",
|
||||||
|
admin: {
|
||||||
|
description: "Optional in-world date shown with the entry. Does not affect list order.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "mission",
|
||||||
|
type: "relationship",
|
||||||
|
relationTo: "missions",
|
||||||
|
admin: {
|
||||||
|
description: "Optional mission this entry relates to. Entries may stand alone.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "body",
|
||||||
|
type: "richText",
|
||||||
|
required: true,
|
||||||
|
editor: lexicalEditor({
|
||||||
|
features: ({ defaultFeatures }) => [...defaultFeatures, FixedToolbarFeature()],
|
||||||
|
}),
|
||||||
|
admin: {
|
||||||
|
description: "Rich text body of the entry, rendered on /journals with the Lexical renderer.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
@ -207,6 +207,7 @@ export const collectionIcons: Record<string, LucideIcon> = {
|
||||||
// Story (Chronicle)
|
// Story (Chronicle)
|
||||||
"story-beat-states": BookmarkCheck,
|
"story-beat-states": BookmarkCheck,
|
||||||
"story-beats": ScrollText,
|
"story-beats": ScrollText,
|
||||||
|
journals: NotebookText,
|
||||||
"story-voiceovers": Mic,
|
"story-voiceovers": Mic,
|
||||||
|
|
||||||
// Server
|
// Server
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,7 @@ import {
|
||||||
Search,
|
Search,
|
||||||
Award,
|
Award,
|
||||||
Mic,
|
Mic,
|
||||||
|
NotebookText,
|
||||||
PlaneTakeoff,
|
PlaneTakeoff,
|
||||||
Radio,
|
Radio,
|
||||||
Bomb,
|
Bomb,
|
||||||
|
|
@ -380,6 +381,13 @@ export const navigationCommands: NavigationCommand[] = [
|
||||||
href: "/story",
|
href: "/story",
|
||||||
keywords: ["lore", "narrative", "story", "history", "beats"],
|
keywords: ["lore", "narrative", "story", "history", "beats"],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "nav:journals",
|
||||||
|
label: "Journals",
|
||||||
|
icon: NotebookText,
|
||||||
|
href: "/journals",
|
||||||
|
keywords: ["writing", "member stories", "after action", "memories", "diary"],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: "nav:surveys",
|
id: "nav:surveys",
|
||||||
label: "Surveys",
|
label: "Surveys",
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ import {
|
||||||
LifeBuoy,
|
LifeBuoy,
|
||||||
Medal,
|
Medal,
|
||||||
Map,
|
Map,
|
||||||
|
NotebookText,
|
||||||
Package,
|
Package,
|
||||||
Radar,
|
Radar,
|
||||||
ScrollText,
|
ScrollText,
|
||||||
|
|
@ -203,6 +204,11 @@ export const sidebarData = {
|
||||||
url: "/story",
|
url: "/story",
|
||||||
icon: ScrollText,
|
icon: ScrollText,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: "Journals",
|
||||||
|
url: "/journals",
|
||||||
|
icon: NotebookText,
|
||||||
|
},
|
||||||
],
|
],
|
||||||
navSurveys: [
|
navSurveys: [
|
||||||
{
|
{
|
||||||
|
|
|
||||||
108
src/components/frontend/journals/JournalDetailControls.tsx
Normal file
108
src/components/frontend/journals/JournalDetailControls.tsx
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as React from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Loader2Icon, PencilIcon, Trash2Icon } from "lucide-react";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
AlertDialog,
|
||||||
|
AlertDialogAction,
|
||||||
|
AlertDialogCancel,
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogDescription,
|
||||||
|
AlertDialogFooter,
|
||||||
|
AlertDialogHeader,
|
||||||
|
AlertDialogTitle,
|
||||||
|
AlertDialogTrigger,
|
||||||
|
} from "@/components/ui/alert-dialog";
|
||||||
|
import { deleteJournal } from "@/app/(frontend)/journals/actions";
|
||||||
|
import { JournalFormDialog, type MissionOption } from "./JournalFormDialog";
|
||||||
|
import type { JournalDraft } from "./JournalFormDialog";
|
||||||
|
|
||||||
|
interface JournalDetailControlsProps {
|
||||||
|
draft: JournalDraft;
|
||||||
|
missions: MissionOption[];
|
||||||
|
canEdit: boolean;
|
||||||
|
canDelete: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Author/staff controls on the /journals/[id] reader page. */
|
||||||
|
export function JournalDetailControls({
|
||||||
|
draft,
|
||||||
|
missions,
|
||||||
|
canEdit,
|
||||||
|
canDelete,
|
||||||
|
}: JournalDetailControlsProps) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [editing, setEditing] = React.useState(false);
|
||||||
|
const [deleting, setDeleting] = React.useState(false);
|
||||||
|
|
||||||
|
if (!canEdit && !canDelete) return null;
|
||||||
|
|
||||||
|
const handleDelete = async () => {
|
||||||
|
if (typeof draft.id !== "number") return;
|
||||||
|
setDeleting(true);
|
||||||
|
const result = await deleteJournal(draft.id);
|
||||||
|
setDeleting(false);
|
||||||
|
if (!result.success) {
|
||||||
|
toast.error(result.error ?? "Failed to delete entry");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
toast.success("Entry deleted");
|
||||||
|
router.push("/journals");
|
||||||
|
router.refresh();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{canEdit && (
|
||||||
|
<>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => setEditing(true)}>
|
||||||
|
<PencilIcon className="mr-2 size-3.5" />
|
||||||
|
Edit
|
||||||
|
</Button>
|
||||||
|
<JournalFormDialog
|
||||||
|
open={editing}
|
||||||
|
onOpenChange={setEditing}
|
||||||
|
missions={missions}
|
||||||
|
draft={draft}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{canDelete && (
|
||||||
|
<AlertDialog>
|
||||||
|
<AlertDialogTrigger asChild>
|
||||||
|
<Button variant="outline" size="sm" className="text-destructive hover:text-destructive">
|
||||||
|
<Trash2Icon className="mr-2 size-3.5" />
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
|
</AlertDialogTrigger>
|
||||||
|
<AlertDialogContent>
|
||||||
|
<AlertDialogHeader>
|
||||||
|
<AlertDialogTitle>Delete this journal entry?</AlertDialogTitle>
|
||||||
|
<AlertDialogDescription>
|
||||||
|
"{draft.title}" will be permanently removed. This cannot be undone.
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</AlertDialogHeader>
|
||||||
|
<AlertDialogFooter>
|
||||||
|
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||||
|
<AlertDialogAction
|
||||||
|
onClick={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
void handleDelete();
|
||||||
|
}}
|
||||||
|
disabled={deleting}
|
||||||
|
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||||
|
>
|
||||||
|
{deleting && <Loader2Icon className="mr-2 size-4 animate-spin" />}
|
||||||
|
Delete
|
||||||
|
</AlertDialogAction>
|
||||||
|
</AlertDialogFooter>
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialog>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
203
src/components/frontend/journals/JournalFormDialog.tsx
Normal file
203
src/components/frontend/journals/JournalFormDialog.tsx
Normal file
|
|
@ -0,0 +1,203 @@
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as React from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Loader2Icon } 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 {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import {
|
||||||
|
LexicalRichTextEditor,
|
||||||
|
type LexicalJson,
|
||||||
|
} from "@/components/frontend/intelligence/LexicalRichTextEditor";
|
||||||
|
import { createJournal, updateJournal } from "@/app/(frontend)/journals/actions";
|
||||||
|
|
||||||
|
export interface MissionOption {
|
||||||
|
id: number;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface JournalDraft {
|
||||||
|
id?: number;
|
||||||
|
title: string;
|
||||||
|
status: "draft" | "published";
|
||||||
|
/** yyyy-MM-dd or "" */
|
||||||
|
occurredAt: string;
|
||||||
|
missionId: number | null;
|
||||||
|
body: LexicalJson | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const EMPTY_JOURNAL_DRAFT: JournalDraft = {
|
||||||
|
title: "",
|
||||||
|
status: "draft",
|
||||||
|
occurredAt: "",
|
||||||
|
missionId: null,
|
||||||
|
body: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
interface JournalFormDialogProps {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
missions: MissionOption[];
|
||||||
|
draft: JournalDraft;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Compose/edit dialog shared by the /journals list and the entry reader. */
|
||||||
|
export function JournalFormDialog({
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
missions,
|
||||||
|
draft,
|
||||||
|
}: JournalFormDialogProps) {
|
||||||
|
const router = useRouter();
|
||||||
|
const isEdit = typeof draft.id === "number";
|
||||||
|
|
||||||
|
const [title, setTitle] = React.useState(draft.title);
|
||||||
|
const [status, setStatus] = React.useState<"draft" | "published">(draft.status);
|
||||||
|
const [occurredAt, setOccurredAt] = React.useState(draft.occurredAt);
|
||||||
|
const [missionId, setMissionId] = React.useState<string>(
|
||||||
|
draft.missionId === null ? "none" : String(draft.missionId),
|
||||||
|
);
|
||||||
|
const [body, setBody] = React.useState<LexicalJson | null>(draft.body);
|
||||||
|
const [saving, setSaving] = React.useState(false);
|
||||||
|
|
||||||
|
// Re-seed the form whenever a different entry (or a fresh compose) opens.
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
setTitle(draft.title);
|
||||||
|
setStatus(draft.status);
|
||||||
|
setOccurredAt(draft.occurredAt);
|
||||||
|
setMissionId(draft.missionId === null ? "none" : String(draft.missionId));
|
||||||
|
setBody(draft.body);
|
||||||
|
}, [open, draft]);
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
setSaving(true);
|
||||||
|
const input = {
|
||||||
|
title,
|
||||||
|
status,
|
||||||
|
occurredAt: occurredAt ? new Date(occurredAt).toISOString() : null,
|
||||||
|
mission: missionId === "none" ? null : Number(missionId),
|
||||||
|
body,
|
||||||
|
};
|
||||||
|
const result = isEdit
|
||||||
|
? await updateJournal(draft.id as number, input)
|
||||||
|
: await createJournal(input);
|
||||||
|
setSaving(false);
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
toast.error(result.error ?? "Failed to save entry");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
toast.success(isEdit ? "Entry updated" : "Entry saved");
|
||||||
|
onOpenChange(false);
|
||||||
|
router.refresh();
|
||||||
|
if (!isEdit && result.data) {
|
||||||
|
router.push(`/journals/${result.data}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{isEdit ? "Edit journal entry" : "Write a journal entry"}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Drafts are private to you. Publishing makes the entry readable by every operator on
|
||||||
|
Journals.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-4">
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<Label htmlFor="journal-title">Title</Label>
|
||||||
|
<Input
|
||||||
|
id="journal-title"
|
||||||
|
value={title}
|
||||||
|
onChange={(e) => setTitle(e.target.value)}
|
||||||
|
placeholder="After-action reflections, deployment diaries..."
|
||||||
|
maxLength={200}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-4 sm:grid-cols-3">
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<Label>Status</Label>
|
||||||
|
<Select value={status} onValueChange={(v) => setStatus(v as "draft" | "published")}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="draft">Draft (private)</SelectItem>
|
||||||
|
<SelectItem value="published">Published</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<Label htmlFor="journal-date">In-world date</Label>
|
||||||
|
<Input
|
||||||
|
id="journal-date"
|
||||||
|
type="date"
|
||||||
|
value={occurredAt}
|
||||||
|
onChange={(e) => setOccurredAt(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<Label>Related mission</Label>
|
||||||
|
<Select value={missionId} onValueChange={setMissionId}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="None" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="none">None</SelectItem>
|
||||||
|
{missions.map((m) => (
|
||||||
|
<SelectItem key={m.id} value={String(m.id)}>
|
||||||
|
{m.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1.5">
|
||||||
|
<Label>Entry</Label>
|
||||||
|
<LexicalRichTextEditor
|
||||||
|
key={`${draft.id ?? "new"}-${open ? "open" : "closed"}`}
|
||||||
|
value={body}
|
||||||
|
onChange={setBody}
|
||||||
|
placeholder="Write your entry here..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button onClick={handleSubmit} disabled={saving || !title.trim()}>
|
||||||
|
{saving && <Loader2Icon className="mr-2 size-4 animate-spin" />}
|
||||||
|
{isEdit ? "Save changes" : "Save entry"}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
107
src/components/frontend/journals/JournalsList.tsx
Normal file
107
src/components/frontend/journals/JournalsList.tsx
Normal file
|
|
@ -0,0 +1,107 @@
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as React from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { NotebookTextIcon, PenLineIcon } from "lucide-react";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Card, CardContent } from "@/components/ui/card";
|
||||||
|
import { DraftBadge } from "@/components/frontend/story/DraftBadge";
|
||||||
|
import {
|
||||||
|
EMPTY_JOURNAL_DRAFT,
|
||||||
|
JournalFormDialog,
|
||||||
|
type MissionOption,
|
||||||
|
} from "./JournalFormDialog";
|
||||||
|
|
||||||
|
export interface JournalCard {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
status: "draft" | "published";
|
||||||
|
authorName: string;
|
||||||
|
dateLabel: string | null;
|
||||||
|
missionLabel: string | null;
|
||||||
|
excerpt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface JournalsListProps {
|
||||||
|
journals: JournalCard[];
|
||||||
|
missions: MissionOption[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function JournalsList({ journals, missions }: JournalsListProps) {
|
||||||
|
const [composing, setComposing] = React.useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-6">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<p className="text-xs uppercase tracking-[0.3em] text-muted-foreground">
|
||||||
|
Member Journals
|
||||||
|
</p>
|
||||||
|
<h1 className="mt-1 font-serif text-3xl font-bold">Journals</h1>
|
||||||
|
<p className="mt-1 max-w-xl text-sm text-muted-foreground">
|
||||||
|
First-person accounts from the unit: after-action notes, deployment diaries, and
|
||||||
|
everything in between. Write your own at any time; publish when you are happy with it.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button onClick={() => setComposing(true)}>
|
||||||
|
<PenLineIcon className="mr-2 size-4" />
|
||||||
|
Write entry
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{journals.length === 0 ? (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="flex flex-col items-center gap-3 py-12 text-center">
|
||||||
|
<NotebookTextIcon className="size-8 text-muted-foreground" />
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
No journal entries yet. Be the first to write one.
|
||||||
|
</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||||
|
{journals.map((journal) => (
|
||||||
|
<Link key={journal.id} href={`/journals/${journal.id}`} className="group">
|
||||||
|
<Card className="h-full transition-colors group-hover:border-primary/50">
|
||||||
|
<CardContent className="flex h-full flex-col gap-2 p-5">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
{journal.status === "draft" && <DraftBadge />}
|
||||||
|
{journal.missionLabel && (
|
||||||
|
<Badge variant="secondary" className="max-w-[60%] truncate text-[10px]">
|
||||||
|
{journal.missionLabel}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<h2 className="font-serif text-lg font-semibold leading-snug line-clamp-2">
|
||||||
|
{journal.title}
|
||||||
|
</h2>
|
||||||
|
{journal.excerpt && (
|
||||||
|
<p className="text-sm text-muted-foreground line-clamp-3">{journal.excerpt}</p>
|
||||||
|
)}
|
||||||
|
<div className="mt-auto flex items-center gap-2 pt-2 text-xs text-muted-foreground">
|
||||||
|
<span className="truncate">{journal.authorName}</span>
|
||||||
|
{journal.dateLabel && (
|
||||||
|
<>
|
||||||
|
<span className="text-border">|</span>
|
||||||
|
<span className="shrink-0">{journal.dateLabel}</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<JournalFormDialog
|
||||||
|
open={composing}
|
||||||
|
onOpenChange={setComposing}
|
||||||
|
missions={missions}
|
||||||
|
draft={EMPTY_JOURNAL_DRAFT}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
36
src/lib/journals/excerpt.ts
Normal file
36
src/lib/journals/excerpt.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
/**
|
||||||
|
* Plain-text excerpt extraction from Lexical document JSON. Pure module so
|
||||||
|
* list pages and tests can use it without React or Payload.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface LexicalNodeLike {
|
||||||
|
type?: string;
|
||||||
|
text?: string;
|
||||||
|
children?: LexicalNodeLike[];
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
for (const child of node.children ?? []) {
|
||||||
|
if (collectText(child, parts, limit)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flattens the first `maxLength` characters of visible text out of a Lexical
|
||||||
|
* editor state. 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()}…`;
|
||||||
|
}
|
||||||
40419
src/migrations/20261012_181310_add_journals_collection.json
Normal file
40419
src/migrations/20261012_181310_add_journals_collection.json
Normal file
File diff suppressed because it is too large
Load diff
65
src/migrations/20261012_181310_add_journals_collection.ts
Normal file
65
src/migrations/20261012_181310_add_journals_collection.ts
Normal file
File diff suppressed because one or more lines are too long
40420
src/migrations/20261012_182016_add_journals_event_target.json
Normal file
40420
src/migrations/20261012_182016_add_journals_event_target.json
Normal file
File diff suppressed because it is too large
Load diff
14
src/migrations/20261012_182016_add_journals_event_target.ts
Normal file
14
src/migrations/20261012_182016_add_journals_event_target.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
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_game_event_logs_target_collection" ADD VALUE 'journals' BEFORE 'story-beat-states';`)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||||
|
await db.execute(sql`
|
||||||
|
ALTER TABLE "game_event_logs" ALTER COLUMN "target_collection" SET DATA TYPE text;
|
||||||
|
DROP TYPE "public"."enum_game_event_logs_target_collection";
|
||||||
|
CREATE TYPE "public"."enum_game_event_logs_target_collection" AS ENUM('game-structures', 'game-vehicles', 'game-npcs', 'npc-staffing', 'structures', 'resources', 'assets', 'vehicles', 'factions', 'missions', 'campaigns', 'users', 'technologies', 'maps', 'shipments', 'bank-accounts', 'bank-transactions', 'ledger-entries', 'locker-storages', 'loadouts', 'market-listings', 'market-negotiations', 'market-state', 'evaluations', 'tickets', 'wiki-pages', 'wiki-revisions', 'wiki-templates', 'form-submissions', 'mission-map-markers', 'contribution-entries', 'game-servers', 'assignment-transfers', 'voice-scripts', 'voice-submissions', 'story-beats', 'story-beat-states', 'custom-minefields', 'custom-minefield-scores', 'custom-radio-tests', 'custom-radio-test-scores', 'ribbon-submissions', 'promotion-nominations', 'leadership-transfers', 'player-flags', 'reinforcement-pools');
|
||||||
|
ALTER TABLE "game_event_logs" ALTER COLUMN "target_collection" SET DATA TYPE "public"."enum_game_event_logs_target_collection" USING "target_collection"::"public"."enum_game_event_logs_target_collection";`)
|
||||||
|
}
|
||||||
|
|
@ -129,6 +129,8 @@ import * as migration_20261012_015000_seed_call_for_fire_versus_registry from '.
|
||||||
import * as migration_20261012_030000_update_call_for_fire_versus_wording from './20261012_030000_update_call_for_fire_versus_wording';
|
import * as migration_20261012_030000_update_call_for_fire_versus_wording from './20261012_030000_update_call_for_fire_versus_wording';
|
||||||
import * as migration_20261012_134242_add_discord_presence_global from './20261012_134242_add_discord_presence_global';
|
import * as migration_20261012_134242_add_discord_presence_global from './20261012_134242_add_discord_presence_global';
|
||||||
import * as migration_20261012_173511_add_sidebar_order_preference from './20261012_173511_add_sidebar_order_preference';
|
import * as migration_20261012_173511_add_sidebar_order_preference from './20261012_173511_add_sidebar_order_preference';
|
||||||
|
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';
|
||||||
|
|
||||||
export const migrations = [
|
export const migrations = [
|
||||||
{
|
{
|
||||||
|
|
@ -784,6 +786,16 @@ export const migrations = [
|
||||||
{
|
{
|
||||||
up: migration_20261012_173511_add_sidebar_order_preference.up,
|
up: migration_20261012_173511_add_sidebar_order_preference.up,
|
||||||
down: migration_20261012_173511_add_sidebar_order_preference.down,
|
down: migration_20261012_173511_add_sidebar_order_preference.down,
|
||||||
name: '20261012_173511_add_sidebar_order_preference'
|
name: '20261012_173511_add_sidebar_order_preference',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
up: migration_20261012_181310_add_journals_collection.up,
|
||||||
|
down: migration_20261012_181310_add_journals_collection.down,
|
||||||
|
name: '20261012_181310_add_journals_collection',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
up: migration_20261012_182016_add_journals_event_target.up,
|
||||||
|
down: migration_20261012_182016_add_journals_event_target.down,
|
||||||
|
name: '20261012_182016_add_journals_event_target'
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
|
||||||
|
|
@ -135,6 +135,7 @@ export interface Config {
|
||||||
'story-beats': StoryBeat;
|
'story-beats': StoryBeat;
|
||||||
'story-beat-states': StoryBeatState;
|
'story-beat-states': StoryBeatState;
|
||||||
'story-voiceovers': StoryVoiceover;
|
'story-voiceovers': StoryVoiceover;
|
||||||
|
journals: Journal;
|
||||||
'mission-files': MissionFile;
|
'mission-files': MissionFile;
|
||||||
'mod-lists': ModList;
|
'mod-lists': ModList;
|
||||||
'game-servers': GameServer;
|
'game-servers': GameServer;
|
||||||
|
|
@ -240,6 +241,7 @@ export interface Config {
|
||||||
'story-beats': StoryBeatsSelect<false> | StoryBeatsSelect<true>;
|
'story-beats': StoryBeatsSelect<false> | StoryBeatsSelect<true>;
|
||||||
'story-beat-states': StoryBeatStatesSelect<false> | StoryBeatStatesSelect<true>;
|
'story-beat-states': StoryBeatStatesSelect<false> | StoryBeatStatesSelect<true>;
|
||||||
'story-voiceovers': StoryVoiceoversSelect<false> | StoryVoiceoversSelect<true>;
|
'story-voiceovers': StoryVoiceoversSelect<false> | StoryVoiceoversSelect<true>;
|
||||||
|
journals: JournalsSelect<false> | JournalsSelect<true>;
|
||||||
'mission-files': MissionFilesSelect<false> | MissionFilesSelect<true>;
|
'mission-files': MissionFilesSelect<false> | MissionFilesSelect<true>;
|
||||||
'mod-lists': ModListsSelect<false> | ModListsSelect<true>;
|
'mod-lists': ModListsSelect<false> | ModListsSelect<true>;
|
||||||
'game-servers': GameServersSelect<false> | GameServersSelect<true>;
|
'game-servers': GameServersSelect<false> | GameServersSelect<true>;
|
||||||
|
|
@ -640,6 +642,11 @@ export interface Role {
|
||||||
| 'awards:update'
|
| 'awards:update'
|
||||||
| 'awards:delete'
|
| 'awards:delete'
|
||||||
| 'admin:awards:manage'
|
| 'admin:awards:manage'
|
||||||
|
| 'journals:create'
|
||||||
|
| 'journals:read'
|
||||||
|
| 'journals:update'
|
||||||
|
| 'journals:delete'
|
||||||
|
| 'admin:journals:manage'
|
||||||
| 'qualifications:create'
|
| 'qualifications:create'
|
||||||
| 'qualifications:read'
|
| 'qualifications:read'
|
||||||
| 'qualifications:update'
|
| 'qualifications:update'
|
||||||
|
|
@ -2751,6 +2758,11 @@ export interface GameEventLog {
|
||||||
| 'awards:update'
|
| 'awards:update'
|
||||||
| 'awards:delete'
|
| 'awards:delete'
|
||||||
| 'admin:awards:manage'
|
| 'admin:awards:manage'
|
||||||
|
| 'journals:create'
|
||||||
|
| 'journals:read'
|
||||||
|
| 'journals:update'
|
||||||
|
| 'journals:delete'
|
||||||
|
| 'admin:journals:manage'
|
||||||
| 'qualifications:create'
|
| 'qualifications:create'
|
||||||
| 'qualifications:read'
|
| 'qualifications:read'
|
||||||
| 'qualifications:update'
|
| 'qualifications:update'
|
||||||
|
|
@ -3142,6 +3154,7 @@ export interface GameEventLog {
|
||||||
| 'voice-scripts'
|
| 'voice-scripts'
|
||||||
| 'voice-submissions'
|
| 'voice-submissions'
|
||||||
| 'story-beats'
|
| 'story-beats'
|
||||||
|
| 'journals'
|
||||||
| 'story-beat-states'
|
| 'story-beat-states'
|
||||||
| 'custom-minefields'
|
| 'custom-minefields'
|
||||||
| 'custom-minefield-scores'
|
| 'custom-minefield-scores'
|
||||||
|
|
@ -5462,6 +5475,52 @@ export interface StoryBeatState {
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* Member-written journals. Drafts are visible to their author and staff only; published entries are readable by any logged-in user on /journals.
|
||||||
|
*
|
||||||
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
|
* via the `definition` "journals".
|
||||||
|
*/
|
||||||
|
export interface Journal {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
/**
|
||||||
|
* Owning member. Authors can always edit their own entries.
|
||||||
|
*/
|
||||||
|
author: number | User;
|
||||||
|
/**
|
||||||
|
* Authors publish directly; no staff review is required.
|
||||||
|
*/
|
||||||
|
status: 'draft' | 'published';
|
||||||
|
/**
|
||||||
|
* Optional in-world date shown with the entry. Does not affect list order.
|
||||||
|
*/
|
||||||
|
occurredAt?: string | null;
|
||||||
|
/**
|
||||||
|
* Optional mission this entry relates to. Entries may stand alone.
|
||||||
|
*/
|
||||||
|
mission?: (number | null) | Mission;
|
||||||
|
/**
|
||||||
|
* Rich text body of the entry, rendered on /journals with the Lexical renderer.
|
||||||
|
*/
|
||||||
|
body: {
|
||||||
|
root: {
|
||||||
|
type: string;
|
||||||
|
children: {
|
||||||
|
type: any;
|
||||||
|
version: number;
|
||||||
|
[k: string]: unknown;
|
||||||
|
}[];
|
||||||
|
direction: ('ltr' | 'rtl') | null;
|
||||||
|
format: 'left' | 'start' | 'center' | 'right' | 'end' | 'justify' | '';
|
||||||
|
indent: number;
|
||||||
|
version: number;
|
||||||
|
};
|
||||||
|
[k: string]: unknown;
|
||||||
|
};
|
||||||
|
updatedAt: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* This interface was referenced by `Config`'s JSON-Schema
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
* via the `definition` "game-servers".
|
* via the `definition` "game-servers".
|
||||||
|
|
@ -7637,6 +7696,24 @@ export interface PayloadMcpApiKey {
|
||||||
*/
|
*/
|
||||||
delete?: boolean | null;
|
delete?: boolean | null;
|
||||||
};
|
};
|
||||||
|
journals?: {
|
||||||
|
/**
|
||||||
|
* Allow clients to find journals.
|
||||||
|
*/
|
||||||
|
find?: boolean | null;
|
||||||
|
/**
|
||||||
|
* Allow clients to create journals.
|
||||||
|
*/
|
||||||
|
create?: boolean | null;
|
||||||
|
/**
|
||||||
|
* Allow clients to update journals.
|
||||||
|
*/
|
||||||
|
update?: boolean | null;
|
||||||
|
/**
|
||||||
|
* Allow clients to delete journals.
|
||||||
|
*/
|
||||||
|
delete?: boolean | null;
|
||||||
|
};
|
||||||
missionFiles?: {
|
missionFiles?: {
|
||||||
/**
|
/**
|
||||||
* Allow clients to find mission-files.
|
* Allow clients to find mission-files.
|
||||||
|
|
@ -8296,6 +8373,10 @@ export interface PayloadLockedDocument {
|
||||||
relationTo: 'story-voiceovers';
|
relationTo: 'story-voiceovers';
|
||||||
value: number | StoryVoiceover;
|
value: number | StoryVoiceover;
|
||||||
} | null)
|
} | null)
|
||||||
|
| ({
|
||||||
|
relationTo: 'journals';
|
||||||
|
value: number | Journal;
|
||||||
|
} | null)
|
||||||
| ({
|
| ({
|
||||||
relationTo: 'mission-files';
|
relationTo: 'mission-files';
|
||||||
value: number | MissionFile;
|
value: number | MissionFile;
|
||||||
|
|
@ -10479,6 +10560,20 @@ export interface StoryVoiceoversSelect<T extends boolean = true> {
|
||||||
focalX?: T;
|
focalX?: T;
|
||||||
focalY?: T;
|
focalY?: T;
|
||||||
}
|
}
|
||||||
|
/**
|
||||||
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
|
* via the `definition` "journals_select".
|
||||||
|
*/
|
||||||
|
export interface JournalsSelect<T extends boolean = true> {
|
||||||
|
title?: T;
|
||||||
|
author?: T;
|
||||||
|
status?: T;
|
||||||
|
occurredAt?: T;
|
||||||
|
mission?: T;
|
||||||
|
body?: T;
|
||||||
|
updatedAt?: T;
|
||||||
|
createdAt?: T;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* This interface was referenced by `Config`'s JSON-Schema
|
* This interface was referenced by `Config`'s JSON-Schema
|
||||||
* via the `definition` "mission-files_select".
|
* via the `definition` "mission-files_select".
|
||||||
|
|
@ -11602,6 +11697,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
|
||||||
update?: T;
|
update?: T;
|
||||||
delete?: T;
|
delete?: T;
|
||||||
};
|
};
|
||||||
|
journals?:
|
||||||
|
| T
|
||||||
|
| {
|
||||||
|
find?: T;
|
||||||
|
create?: T;
|
||||||
|
update?: T;
|
||||||
|
delete?: T;
|
||||||
|
};
|
||||||
missionFiles?:
|
missionFiles?:
|
||||||
| T
|
| T
|
||||||
| {
|
| {
|
||||||
|
|
|
||||||
|
|
@ -83,6 +83,7 @@ import { Sprints } from "@/collections/projects/Sprints";
|
||||||
import { Releases } from "@/collections/projects/Releases";
|
import { Releases } from "@/collections/projects/Releases";
|
||||||
import { Labels } from "@/collections/projects/Labels";
|
import { Labels } from "@/collections/projects/Labels";
|
||||||
import { StoryBeats } from "@/collections/story/StoryBeats";
|
import { StoryBeats } from "@/collections/story/StoryBeats";
|
||||||
|
import { Journals } from "@/collections/story/Journals";
|
||||||
import { StoryBeatStates } from "@/collections/story/StoryBeatStates";
|
import { StoryBeatStates } from "@/collections/story/StoryBeatStates";
|
||||||
import { Voiceovers } from "@/collections/story/Voiceovers";
|
import { Voiceovers } from "@/collections/story/Voiceovers";
|
||||||
import { Shims } from "@/collections/Shims";
|
import { Shims } from "@/collections/Shims";
|
||||||
|
|
@ -361,6 +362,7 @@ const collections = [
|
||||||
StoryBeats,
|
StoryBeats,
|
||||||
StoryBeatStates,
|
StoryBeatStates,
|
||||||
Voiceovers,
|
Voiceovers,
|
||||||
|
Journals,
|
||||||
|
|
||||||
// Server
|
// Server
|
||||||
MissionFiles,
|
MissionFiles,
|
||||||
|
|
|
||||||
|
|
@ -102,6 +102,16 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
|
||||||
{ value: "admin:awards:manage", label: "Manage Admin Page" },
|
{ value: "admin:awards:manage", label: "Manage Admin Page" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
group: "Journals",
|
||||||
|
permissions: [
|
||||||
|
{ value: "journals:create", label: "Create" },
|
||||||
|
{ value: "journals:read", label: "Read (staff: all entries incl. drafts)" },
|
||||||
|
{ value: "journals:update", label: "Update (staff: any entry)" },
|
||||||
|
{ value: "journals:delete", label: "Delete (staff: any entry)" },
|
||||||
|
{ value: "admin:journals:manage", label: "Manage Admin Page" },
|
||||||
|
],
|
||||||
|
},
|
||||||
{
|
{
|
||||||
group: "Qualifications",
|
group: "Qualifications",
|
||||||
permissions: [
|
permissions: [
|
||||||
|
|
@ -846,6 +856,11 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
|
||||||
"awards:update",
|
"awards:update",
|
||||||
"awards:delete",
|
"awards:delete",
|
||||||
"admin:awards:manage",
|
"admin:awards:manage",
|
||||||
|
"journals:create",
|
||||||
|
"journals:read",
|
||||||
|
"journals:update",
|
||||||
|
"journals:delete",
|
||||||
|
"admin:journals:manage",
|
||||||
"qualifications:create",
|
"qualifications:create",
|
||||||
"qualifications:read",
|
"qualifications:read",
|
||||||
"qualifications:update",
|
"qualifications:update",
|
||||||
|
|
|
||||||
|
|
@ -55,7 +55,8 @@ interface GameEventInput {
|
||||||
| "reinforcement-pools"
|
| "reinforcement-pools"
|
||||||
| "form-submissions"
|
| "form-submissions"
|
||||||
| "mission-map-markers"
|
| "mission-map-markers"
|
||||||
| "contribution-entries";
|
| "contribution-entries"
|
||||||
|
| "journals";
|
||||||
targetId?: number;
|
targetId?: number;
|
||||||
data?: Record<string, unknown>;
|
data?: Record<string, unknown>;
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -208,6 +208,11 @@ export const EventTypes = {
|
||||||
StoryBeatRead: "story:beat-read",
|
StoryBeatRead: "story:beat-read",
|
||||||
StoryBeatReact: "story:beat-react",
|
StoryBeatReact: "story:beat-react",
|
||||||
|
|
||||||
|
// Journals
|
||||||
|
JournalCreated: "journal:created",
|
||||||
|
JournalUpdated: "journal:updated",
|
||||||
|
JournalDeleted: "journal:deleted",
|
||||||
|
|
||||||
// Projects
|
// Projects
|
||||||
ProjectCreate: "project:create",
|
ProjectCreate: "project:create",
|
||||||
ProjectUpdate: "project:update",
|
ProjectUpdate: "project:update",
|
||||||
|
|
|
||||||
255
tests/int/journals-access.int.spec.ts
Normal file
255
tests/int/journals-access.int.spec.ts
Normal file
|
|
@ -0,0 +1,255 @@
|
||||||
|
/**
|
||||||
|
* Journals access rules: authors own their entries (drafts private), every
|
||||||
|
* logged-in user reads published entries, staff permissions bypass ownership.
|
||||||
|
*/
|
||||||
|
import { getPayload, Payload } from "payload";
|
||||||
|
import config from "@/payload.config";
|
||||||
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import type { Journal, Role, User } from "@/payload-types";
|
||||||
|
import type { Permission } from "@/permissions";
|
||||||
|
|
||||||
|
let payload: Payload;
|
||||||
|
|
||||||
|
const RUN = `jn-${Date.now().toString(36)}`;
|
||||||
|
const TIMEOUT = 30_000;
|
||||||
|
|
||||||
|
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("Journals access control", () => {
|
||||||
|
const roleIds: number[] = [];
|
||||||
|
const userIds: number[] = [];
|
||||||
|
const journalIds: number[] = [];
|
||||||
|
|
||||||
|
let authorUser: User;
|
||||||
|
let readerUser: User;
|
||||||
|
let staffUser: 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;
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
payload = await getPayload({ config });
|
||||||
|
const plainRole = await makeRole("plain", []);
|
||||||
|
const staffRole = await makeRole("staff", [
|
||||||
|
"journals:read",
|
||||||
|
"journals:update",
|
||||||
|
"journals:delete",
|
||||||
|
]);
|
||||||
|
authorUser = await makeUser("author", plainRole.id);
|
||||||
|
readerUser = await makeUser("reader", plainRole.id);
|
||||||
|
staffUser = await makeUser("staff", staffRole.id);
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
for (const id of journalIds) {
|
||||||
|
await payload.delete({ collection: "journals", id, overrideAccess: true }).catch(() => {});
|
||||||
|
}
|
||||||
|
for (const id of userIds) {
|
||||||
|
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
|
||||||
|
}
|
||||||
|
for (const id of roleIds) {
|
||||||
|
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
|
||||||
|
}
|
||||||
|
}, TIMEOUT);
|
||||||
|
|
||||||
|
const createDraft = async (author: User): Promise<Journal> => {
|
||||||
|
const doc = (await payload.create({
|
||||||
|
collection: "journals",
|
||||||
|
data: {
|
||||||
|
title: `${RUN} draft`,
|
||||||
|
author: author.id,
|
||||||
|
status: "draft" as const,
|
||||||
|
body: journalBody("Field notes body."),
|
||||||
|
},
|
||||||
|
overrideAccess: false,
|
||||||
|
user: author,
|
||||||
|
depth: 0,
|
||||||
|
})) as unknown as Journal;
|
||||||
|
journalIds.push(doc.id);
|
||||||
|
return doc;
|
||||||
|
};
|
||||||
|
|
||||||
|
it(
|
||||||
|
"lets any logged-in member create an entry, owned by them, defaulting to draft",
|
||||||
|
async () => {
|
||||||
|
const doc = await createDraft(authorUser);
|
||||||
|
expect(doc.status).toBe("draft");
|
||||||
|
expect(typeof doc.author === "number" ? doc.author : doc.author.id).toBe(authorUser.id);
|
||||||
|
},
|
||||||
|
TIMEOUT,
|
||||||
|
);
|
||||||
|
|
||||||
|
it(
|
||||||
|
"keeps drafts invisible to other members but visible to the author and staff",
|
||||||
|
async () => {
|
||||||
|
const doc = await createDraft(authorUser);
|
||||||
|
|
||||||
|
const asReader = await payload.find({
|
||||||
|
collection: "journals",
|
||||||
|
where: { id: { equals: doc.id } },
|
||||||
|
user: readerUser,
|
||||||
|
overrideAccess: false,
|
||||||
|
});
|
||||||
|
expect(asReader.totalDocs).toBe(0);
|
||||||
|
|
||||||
|
const asAuthor = await payload.find({
|
||||||
|
collection: "journals",
|
||||||
|
where: { id: { equals: doc.id } },
|
||||||
|
user: authorUser,
|
||||||
|
overrideAccess: false,
|
||||||
|
});
|
||||||
|
expect(asAuthor.totalDocs).toBe(1);
|
||||||
|
|
||||||
|
const asStaff = await payload.find({
|
||||||
|
collection: "journals",
|
||||||
|
where: { id: { equals: doc.id } },
|
||||||
|
user: staffUser,
|
||||||
|
overrideAccess: false,
|
||||||
|
});
|
||||||
|
expect(asStaff.totalDocs).toBe(1);
|
||||||
|
},
|
||||||
|
TIMEOUT,
|
||||||
|
);
|
||||||
|
|
||||||
|
it(
|
||||||
|
"opens published entries to every logged-in member",
|
||||||
|
async () => {
|
||||||
|
const doc = await createDraft(authorUser);
|
||||||
|
await payload.update({
|
||||||
|
collection: "journals",
|
||||||
|
id: doc.id,
|
||||||
|
data: { status: "published" },
|
||||||
|
user: authorUser,
|
||||||
|
overrideAccess: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const asReader = await payload.findByID({
|
||||||
|
collection: "journals",
|
||||||
|
id: doc.id,
|
||||||
|
user: readerUser,
|
||||||
|
overrideAccess: false,
|
||||||
|
});
|
||||||
|
expect(asReader.title).toBe(`${RUN} draft`);
|
||||||
|
},
|
||||||
|
TIMEOUT,
|
||||||
|
);
|
||||||
|
|
||||||
|
it(
|
||||||
|
"blocks non-authors from updating or deleting, allows the author",
|
||||||
|
async () => {
|
||||||
|
const doc = await createDraft(authorUser);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
payload.update({
|
||||||
|
collection: "journals",
|
||||||
|
id: doc.id,
|
||||||
|
data: { title: "hijacked" },
|
||||||
|
user: readerUser,
|
||||||
|
overrideAccess: false,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow();
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
payload.delete({
|
||||||
|
collection: "journals",
|
||||||
|
id: doc.id,
|
||||||
|
user: readerUser,
|
||||||
|
overrideAccess: false,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow();
|
||||||
|
|
||||||
|
const updated = (await payload.update({
|
||||||
|
collection: "journals",
|
||||||
|
id: doc.id,
|
||||||
|
data: { title: `${RUN} edited` },
|
||||||
|
user: authorUser,
|
||||||
|
overrideAccess: false,
|
||||||
|
depth: 0,
|
||||||
|
})) as unknown as Journal;
|
||||||
|
expect(updated.title).toBe(`${RUN} edited`);
|
||||||
|
|
||||||
|
await payload.delete({
|
||||||
|
collection: "journals",
|
||||||
|
id: doc.id,
|
||||||
|
user: authorUser,
|
||||||
|
overrideAccess: false,
|
||||||
|
});
|
||||||
|
const gone = await payload.find({
|
||||||
|
collection: "journals",
|
||||||
|
where: { id: { equals: doc.id } },
|
||||||
|
user: staffUser,
|
||||||
|
overrideAccess: false,
|
||||||
|
});
|
||||||
|
expect(gone.totalDocs).toBe(0);
|
||||||
|
},
|
||||||
|
TIMEOUT,
|
||||||
|
);
|
||||||
|
|
||||||
|
it(
|
||||||
|
"lets journals:update staff edit another member's entry",
|
||||||
|
async () => {
|
||||||
|
const doc = await createDraft(authorUser);
|
||||||
|
const updated = (await payload.update({
|
||||||
|
collection: "journals",
|
||||||
|
id: doc.id,
|
||||||
|
data: { title: `${RUN} staff edit` },
|
||||||
|
user: staffUser,
|
||||||
|
overrideAccess: false,
|
||||||
|
depth: 0,
|
||||||
|
})) as unknown as Journal;
|
||||||
|
expect(updated.title).toBe(`${RUN} staff edit`);
|
||||||
|
},
|
||||||
|
TIMEOUT,
|
||||||
|
);
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue