From 7f65e0371b410b3204904380c5be50c8306e6565 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Tue, 13 Oct 2026 14:37:53 -0400 Subject: [PATCH] test(contributions): cover journal publish XP, substance gate, and cap --- tests/int/journal-contributions.int.spec.ts | 236 ++++++++++++++++++++ 1 file changed, 236 insertions(+) create mode 100644 tests/int/journal-contributions.int.spec.ts diff --git a/tests/int/journal-contributions.int.spec.ts b/tests/int/journal-contributions.int.spec.ts new file mode 100644 index 00000000..e4ca587f --- /dev/null +++ b/tests/int/journal-contributions.int.spec.ts @@ -0,0 +1,236 @@ +/** + * Publishing a journal entry earns contribution XP: a substantive publish + * grants 5 XP (immediate), drafts and short entries do not, editing a published + * entry never double-counts, the rolling daily cap applies, and deleting an + * entry pulls the XP back. + */ +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 { journalBodyLength } from "@/lib/journals/excerpt"; +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[] = []; + let user: User; + + const makeUser = async (label: string): Promise => { + 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 => { + 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 (title: string, body: Journal["body"], status: "draft" | "published") => { + const result = await createJournal({ title, body, status, occurredAt: null, mission: null }); + if (result.data != null) journalIds.push(result.data); + return result; + }; + + beforeAll(async () => { + payload = await getPayload({ config: await config }); + user = await makeUser("author"); + 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 5 XP when a substantive entry is published on create", async () => { + authSpy.mockResolvedValue({ user }); + const before = await bucketFor(user.id); + const result = await publish("A long field report", journalBody("x".repeat(250)), "published"); + expect(result.success).toBe(true); + expect(await bucketFor(user.id)).toBe(before + 5); + }); + + it("does not grant for a draft", async () => { + authSpy.mockResolvedValue({ user }); + const before = await bucketFor(user.id); + const result = await publish("A private draft", journalBody("x".repeat(250)), "draft"); + expect(result.success).toBe(true); + expect(await bucketFor(user.id)).toBe(before); + }); + + it("does not grant for a published entry below the substance threshold", async () => { + authSpy.mockResolvedValue({ user }); + const before = await bucketFor(user.id); + const result = await publish("One word", journalBody("A".repeat(50)), "published"); + expect(result.success).toBe(true); + expect(await bucketFor(user.id)).toBe(before); + }); + + it("grants on draft -> published and does not double-count on a later edit", async () => { + authSpy.mockResolvedValue({ user }); + const created = await publish("Published later", journalBody("x".repeat(250)), "draft"); + expect(created.success).toBe(true); + const id = created.data as number; + const before = await bucketFor(user.id); + + await updateJournal(id, { + title: "Published later", + body: journalBody("x".repeat(250)), + status: "published", + occurredAt: null, + mission: null, + }); + expect(await bucketFor(user.id)).toBe(before + 5); + + // 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(user.id)).toBe(before + 5); + + const entries = await payload.count({ + collection: "contribution-entries", + where: { + and: [ + { sourceCollection: { equals: "journals" } }, + { sourceId: { equals: id } }, + ], + }, + overrideAccess: true, + }); + expect(entries.totalDocs).toBe(1); + }); + + it("pulls the XP back when the entry is deleted", async () => { + authSpy.mockResolvedValue({ user }); + const created = await publish("Delete me", journalBody("x".repeat(250)), "published"); + expect(created.success).toBe(true); + const id = created.data as number; + const before = await bucketFor(user.id); + + const result = await deleteJournal(id); + expect(result.success).toBe(true); + expect(await bucketFor(user.id)).toBe(before - 5); + + const revoked = await payload.find({ + collection: "contribution-entries", + where: { + and: [ + { sourceCollection: { equals: "journals" } }, + { sourceId: { equals: id } }, + ], + }, + depth: 0, + overrideAccess: true, + }); + expect(revoked.docs[0]?.status).toBe("revoked"); + expect(revoked.docs[0]?.revokedReason).toContain("deleted"); + }); + + it("caps journal XP at 25 per rolling day", async () => { + const capUser = await makeUser("cap"); + let granted = 0; + for (let i = 0; i < 6; i += 1) { + const result = await recordContribution(payload, { + userId: capUser.id, + type: "journal-publish", + sourceCollection: "journals", + sourceId: 9_000_000 + i, + summary: `cap probe ${i}`, + }); + if (result.status === "granted") granted += 1; + } + expect(granted).toBe(5); + expect(await bucketFor(capUser.id)).toBe(25); + }); +}); + +describe("journalBodyLength", () => { + it("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); + }); +});