"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"; /** * Earliest allowed in-universe date for journal entries (unit founding, * 2156-03-19). Stored as a UTC-midnight epoch so it compares cleanly against * the ISO `occurredAt` the client sends. */ const MIN_OCCURRENCE_DATE = Date.parse("2156-03-19T00:00:00.000Z"); /** * Days the in-game clock runs ahead of real time. The latest allowed in-world * journal date is exactly this many days from the real "now", so the picker * never lets an author write about the in-game future. */ const MAX_OCCURRENCE_OFFSET_DAYS = 47_326; /** Latest allowed in-world date as an instant: real now + the game's offset. */ function maxOccurrenceInstant(): number { return Date.now() + MAX_OCCURRENCE_OFFSET_DAYS * 86_400_000; } export interface ActionResult { 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."; } if (input.occurredAt) { const occurred = Date.parse(input.occurredAt); if (!Number.isNaN(occurred)) { if (occurred < MIN_OCCURRENCE_DATE) { return "The in-world date cannot be before March 19, 2156."; } if (occurred > maxOccurrenceInstant()) { return "The in-world date cannot be after the current in-game date."; } } } return null; } const toNullableId = (value: number | null | undefined): number | null => typeof value === "number" ? value : null; export async function createJournal(input: JournalInput): Promise> { 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> { 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 { 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 }; } }