1
0
Fork 0
polaris-task-force/tests/int/journal-contributions.int.spec.ts

267 lines
9.2 KiB
TypeScript

/**
* 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();
});
});