Give finished Rules a print path, folded launch counts, and a two-day follow-up.
Export is PDF, RULE.md, and Print on US Letter, with every shared term, no member names, and a takeaway that points at Ask an organizer. Finished Rules keep type and place so the team can read folded counts without a database, Umami can sit beside the app with no cookies, and the person who holds the pen gets working PDF and RULE.md links 48 hours later.
This commit is contained in:
1 parent
0efc907633
commit
d9c475a967
74 files changed
+2401
-630
No files matched your search
@@ -33,6 +33,18 @@ describe("buildPublishPayload", () => {
|
||||
expect(JSON.stringify(r)).not.toContain("setupTraits");
|
||||
});
|
||||
|
||||
it("stores place and the main group type on the document for launch counts", () => {
|
||||
const r = buildPublishPayload({
|
||||
title: "Oak Park Commons",
|
||||
communityLocation: "Boulder",
|
||||
selectedOrganizationTypeIds: ["mutualAid"],
|
||||
});
|
||||
expect(r.ok).toBe(true);
|
||||
if (!r.ok) return;
|
||||
expect(r.document.communityLocation).toBe("Boulder");
|
||||
expect(r.document.orgType).toBe("mutualAid");
|
||||
});
|
||||
|
||||
it("returns title and fallback Overview section when no sections", () => {
|
||||
const r = buildPublishPayload({ title: "Oak Park Commons" });
|
||||
expect(r.ok).toBe(true);
|
||||
|
||||
@@ -12,6 +12,7 @@ describe("stripCopiedRuleDocument", () => {
|
||||
communityAvatarUrl: "https://example.test/a.png",
|
||||
communityAvatarFileName: "a.png",
|
||||
communityLocation: "Boulder",
|
||||
orgType: "mutualAid",
|
||||
communitySaveEmail: "a@example.com",
|
||||
sections: [
|
||||
{
|
||||
@@ -25,6 +26,7 @@ describe("stripCopiedRuleDocument", () => {
|
||||
expect(out.communityAvatarUrl).toBeUndefined();
|
||||
expect(out.communityAvatarFileName).toBeUndefined();
|
||||
expect(out.communityLocation).toBeUndefined();
|
||||
expect(out.orgType).toBeUndefined();
|
||||
expect(out.communitySaveEmail).toBeUndefined();
|
||||
expect(out.sections).toEqual([
|
||||
{
|
||||
|
||||
@@ -337,9 +337,7 @@ describe("useCompletedRuleShareExport", () => {
|
||||
const anchorUnknown = clickSpy.mock.instances.at(-1) as unknown;
|
||||
expect(anchorUnknown).toBeInstanceOf(HTMLAnchorElement);
|
||||
const anchorEl = anchorUnknown as HTMLAnchorElement;
|
||||
expect(anchorEl.getAttribute("download")).toBe(
|
||||
"garden-norms-community-rule.pdf",
|
||||
);
|
||||
expect(anchorEl.getAttribute("download")).toBe("Garden norms Rule.pdf");
|
||||
expect(anchorEl.getAttribute("href")).toBe("blob:unit-test");
|
||||
expect(setBanner).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { finishedAtIso } from "../../lib/create/lastPublishedRule";
|
||||
|
||||
describe("finishedAtIso", () => {
|
||||
it("normalizes strings and dates", () => {
|
||||
expect(finishedAtIso("2026-11-08T12:00:00.000Z")).toBe(
|
||||
"2026-11-08T12:00:00.000Z",
|
||||
);
|
||||
expect(finishedAtIso(new Date("2026-11-08T12:00:00.000Z"))).toBe(
|
||||
"2026-11-08T12:00:00.000Z",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns undefined for empty or invalid values", () => {
|
||||
expect(finishedAtIso("")).toBeUndefined();
|
||||
expect(finishedAtIso("not-a-date")).toBeUndefined();
|
||||
expect(finishedAtIso(null)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,16 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
buildPrintableRuleHtmlDocument,
|
||||
buildPublicRuleUrl,
|
||||
buildStoredRulePdfBlob,
|
||||
exportFilenameBase,
|
||||
sectionsToCsv,
|
||||
sectionsToMarkdown,
|
||||
sectionsToPdfBlob,
|
||||
exportStoredRuleAsMarkdown,
|
||||
} from "../../../lib/create/ruleExport";
|
||||
import type { CommunityRuleSection } from "../../../app/components/type/CommunityRule/CommunityRule.types";
|
||||
import {
|
||||
RULE_MD_FILENAME,
|
||||
exportPdfFilename,
|
||||
} from "../../../lib/create/ruleExportModel";
|
||||
import exportCopy from "../../../messages/en/create/export.json";
|
||||
import sharedTerms from "../../../messages/en/create/sharedTerms.json";
|
||||
|
||||
async function readBlobAsArrayBuffer(blob: Blob): Promise<ArrayBuffer> {
|
||||
if (typeof blob.arrayBuffer === "function") {
|
||||
@@ -22,16 +24,25 @@ async function readBlobAsArrayBuffer(blob: Blob): Promise<ArrayBuffer> {
|
||||
});
|
||||
}
|
||||
|
||||
describe("ruleExport", () => {
|
||||
it("buildPublicRuleUrl encodes id and trims origin slash", () => {
|
||||
expect(buildPublicRuleUrl("https://example.com/", "abc/xyz")).toBe(
|
||||
"https://example.com/rules/abc%2Fxyz",
|
||||
);
|
||||
expect(buildPublicRuleUrl("https://example.com", "r1")).toBe(
|
||||
"https://example.com/rules/r1",
|
||||
);
|
||||
});
|
||||
const origin = "https://communityrule.info";
|
||||
|
||||
const source = {
|
||||
id: "id-1",
|
||||
title: "Garden Norms",
|
||||
summary: "We share tools.",
|
||||
document: {
|
||||
sections: [
|
||||
{
|
||||
categoryName: "Values",
|
||||
entries: [{ title: "Solidarity", body: "Be kind.\n\nShare tools." }],
|
||||
},
|
||||
],
|
||||
stakeholders: [{ name: "Maya Chen", email: "maya@example.com" }],
|
||||
},
|
||||
finishedAt: "2026-11-08T12:00:00.000Z",
|
||||
};
|
||||
|
||||
describe("ruleExport", () => {
|
||||
it("exportFilenameBase slugifies title", () => {
|
||||
expect(
|
||||
exportFilenameBase({
|
||||
@@ -52,179 +63,84 @@ describe("ruleExport", () => {
|
||||
).toBe("rule-full-uui");
|
||||
});
|
||||
|
||||
it("sectionsToMarkdown renders title, summary, and sections", () => {
|
||||
const sections: CommunityRuleSection[] = [
|
||||
{
|
||||
categoryName: "Values",
|
||||
entries: [
|
||||
{
|
||||
title: "Solidarity",
|
||||
body: "First paragraph.\n\nSecond paragraph.",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
const md = sectionsToMarkdown(
|
||||
"My Rule",
|
||||
"Short summary.",
|
||||
sections,
|
||||
);
|
||||
expect(md).toContain("# My Rule");
|
||||
expect(md).toContain("Short summary.");
|
||||
it("PDF filename is {Group} Rule.pdf", () => {
|
||||
expect(exportPdfFilename("Garden Norms")).toBe("Garden Norms Rule.pdf");
|
||||
expect(RULE_MD_FILENAME).toBe("RULE.md");
|
||||
});
|
||||
|
||||
it("RULE.md has front matter, shared terms, takeaway, and no member names", () => {
|
||||
const md = exportStoredRuleAsMarkdown(source, origin);
|
||||
expect(md).toContain("title: Garden Norms");
|
||||
expect(md).toContain("summary: We share tools.");
|
||||
expect(md).toContain("finished: 2026-11-08");
|
||||
expect(md).toContain("# Garden Norms");
|
||||
expect(md).toContain("## Values");
|
||||
expect(md).toContain("### Solidarity");
|
||||
expect(md).toContain("First paragraph.");
|
||||
expect(md).toContain("Second paragraph.");
|
||||
expect(md).toContain("## Shared terms");
|
||||
expect(md).toContain("**active members**");
|
||||
expect(md).toContain(sharedTerms.terms[0]?.meaning ?? "good standing");
|
||||
expect(md).toContain(exportCopy.takeaway);
|
||||
expect(md).toContain("https://communityrule.info/#ask-organizer");
|
||||
expect(md).not.toContain("Maya Chen");
|
||||
expect(md).not.toContain("maya@example.com");
|
||||
expect(md).not.toContain("whenNoCardCoversIt");
|
||||
expect(md).not.toContain("setBy");
|
||||
});
|
||||
|
||||
it("sectionsToCsv includes header row, title metadata, sections, and quotes commas", () => {
|
||||
const sections: CommunityRuleSection[] = [
|
||||
{
|
||||
categoryName: "Values",
|
||||
entries: [
|
||||
{
|
||||
title: "Solidarity",
|
||||
body: "One, two",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
const csv = sectionsToCsv("My Rule", "Sum, mary", sections);
|
||||
expect(csv).toContain("Section,Entry,Block label,Content");
|
||||
expect(csv).toContain('"Sum, mary"');
|
||||
expect(csv).toContain('"One, two"');
|
||||
expect(csv).toContain(",Title,,My Rule");
|
||||
});
|
||||
|
||||
it("sectionsToMarkdown, sectionsToCsv, and printable HTML include imageUrl and fileUrl blocks", () => {
|
||||
const sections: CommunityRuleSection[] = [
|
||||
{
|
||||
categoryName: "Values",
|
||||
entries: [
|
||||
{
|
||||
title: "Entry",
|
||||
body: "",
|
||||
blocks: [
|
||||
{
|
||||
label: "Photo",
|
||||
body: "Caption",
|
||||
imageUrl: "https://cdn.example.com/pic.jpg",
|
||||
},
|
||||
{
|
||||
label: "Handbook",
|
||||
body: "Download",
|
||||
fileUrl: "https://cdn.example.com/guidance.pdf",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
const md = sectionsToMarkdown("Rule", null, sections);
|
||||
expect(md).toContain("");
|
||||
expect(md).toContain("[Download](https://cdn.example.com/guidance.pdf)");
|
||||
|
||||
const csv = sectionsToCsv("Rule", null, sections);
|
||||
expect(csv).toContain("Caption\nhttps://cdn.example.com/pic.jpg");
|
||||
expect(csv).toContain("Download\nhttps://cdn.example.com/guidance.pdf");
|
||||
|
||||
const html = buildPrintableRuleHtmlDocument("Rule", null, sections);
|
||||
expect(html).toContain('src="https://cdn.example.com/pic.jpg"');
|
||||
expect(html).toContain("Caption");
|
||||
expect(html).toContain('href="https://cdn.example.com/guidance.pdf"');
|
||||
expect(html).toContain("Download");
|
||||
});
|
||||
|
||||
it("sectionsToPdfBlob embeds image and file URLs as text for labeled blocks", async () => {
|
||||
const sections: CommunityRuleSection[] = [
|
||||
{
|
||||
categoryName: "Values",
|
||||
entries: [
|
||||
{
|
||||
title: "Entry",
|
||||
body: "",
|
||||
blocks: [
|
||||
{
|
||||
label: "Photo",
|
||||
body: "Caption",
|
||||
imageUrl: "https://cdn.example.com/pic.jpg",
|
||||
},
|
||||
{
|
||||
label: "Handbook",
|
||||
body: "Download",
|
||||
fileUrl: "https://cdn.example.com/guidance.pdf",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
const blob = sectionsToPdfBlob("Rule", null, sections);
|
||||
const buf = new Uint8Array(await readBlobAsArrayBuffer(blob));
|
||||
const raw = new TextDecoder("latin1").decode(buf);
|
||||
expect(raw).toContain("https://cdn.example.com/pic.jpg");
|
||||
expect(raw).toContain("https://cdn.example.com/guidance.pdf");
|
||||
it("print HTML is US Letter, credits CommunityRule, and omits names", () => {
|
||||
const html = buildPrintableRuleHtmlDocument(source, origin);
|
||||
expect(html).toContain("@page { size: letter;");
|
||||
expect(html).toContain("Garden Norms");
|
||||
expect(html).toContain(exportCopy.credit);
|
||||
expect(html).toContain(exportCopy.takeaway);
|
||||
expect(html).toContain("https://communityrule.info/#ask-organizer");
|
||||
expect(html).toContain("Shared terms");
|
||||
expect(html).not.toContain("Maya Chen");
|
||||
expect(html).not.toContain("maya@example.com");
|
||||
expect(html).not.toContain("<script>");
|
||||
});
|
||||
|
||||
it("buildPrintableRuleHtmlDocument escapes HTML in user content", () => {
|
||||
const sections: CommunityRuleSection[] = [
|
||||
{
|
||||
categoryName: 'Values <x>',
|
||||
entries: [{ title: "Entry", body: "<script>bad()</script>" }],
|
||||
},
|
||||
];
|
||||
const html = buildPrintableRuleHtmlDocument(
|
||||
'Title <t>',
|
||||
null,
|
||||
sections,
|
||||
{
|
||||
id: "id-1",
|
||||
title: "Title <t>",
|
||||
summary: null,
|
||||
document: {
|
||||
sections: [
|
||||
{
|
||||
categoryName: "Values <x>",
|
||||
entries: [{ title: "Entry", body: "<script>bad()</script>" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
origin,
|
||||
);
|
||||
expect(html).toContain("<script>");
|
||||
expect(html).not.toContain("<script>bad()");
|
||||
expect(html).toContain("Values <x>");
|
||||
});
|
||||
|
||||
it("buildStoredRulePdfBlob produces application/pdf with PDF magic bytes", async () => {
|
||||
const blob = buildStoredRulePdfBlob({
|
||||
id: "id-1",
|
||||
title: "Garden Norms",
|
||||
summary: "Summary here.",
|
||||
document: {
|
||||
sections: [
|
||||
{
|
||||
categoryName: "Values",
|
||||
entries: [{ title: "Solidarity", body: "Be kind.\n\nShare tools." }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
it("buildStoredRulePdfBlob produces application/pdf with takeaway and no names", async () => {
|
||||
const blob = buildStoredRulePdfBlob(source, origin);
|
||||
expect(blob.type).toBe("application/pdf");
|
||||
expect(blob.size).toBeGreaterThan(500);
|
||||
const buf = new Uint8Array(await readBlobAsArrayBuffer(blob));
|
||||
expect(String.fromCharCode(...buf.subarray(0, 5))).toBe("%PDF-");
|
||||
const raw = new TextDecoder("latin1").decode(buf);
|
||||
expect(raw).toContain("Garden Norms");
|
||||
expect(raw).toContain("Tell us what this Rule changed");
|
||||
expect(raw).not.toContain("Maya Chen");
|
||||
expect(raw).not.toContain("maya@example.com");
|
||||
});
|
||||
|
||||
it("buildStoredRulePdfBlob throws exportEmptyDocument when sections empty", () => {
|
||||
expect(() =>
|
||||
buildStoredRulePdfBlob({
|
||||
id: "id-1",
|
||||
title: "T",
|
||||
document: {},
|
||||
}),
|
||||
).toThrowError("exportEmptyDocument");
|
||||
});
|
||||
|
||||
it("export pdf attachment filename matches csv/md convention", () => {
|
||||
const rule = {
|
||||
id: "id-1",
|
||||
title: "Garden norms",
|
||||
document: {
|
||||
sections: [
|
||||
{ categoryName: "X", entries: [{ title: "t", body: "b" }] },
|
||||
],
|
||||
},
|
||||
};
|
||||
expect(`${exportFilenameBase(rule)}-community-rule.pdf`).toBe(
|
||||
"garden-norms-community-rule.pdf",
|
||||
it("exports an empty document without throwing", () => {
|
||||
const md = exportStoredRuleAsMarkdown(
|
||||
{ id: "id-1", title: "T", document: {} },
|
||||
origin,
|
||||
);
|
||||
expect(md).toContain("# T");
|
||||
expect(md).toContain("## Shared terms");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const isDatabaseConfiguredMock = vi.fn();
|
||||
const getOpsPruneTokenMock = vi.fn();
|
||||
const getRuleAdminEmailsMock = vi.fn();
|
||||
const getSessionUserMock = vi.fn();
|
||||
const isRuleAdminEmailMock = vi.fn();
|
||||
const findManyMock = vi.fn();
|
||||
|
||||
vi.mock("../../lib/server/env", () => ({
|
||||
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
||||
getOpsPruneToken: () => getOpsPruneTokenMock(),
|
||||
getRuleAdminEmails: () => getRuleAdminEmailsMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
publishedRule: {
|
||||
findMany: (...args: unknown[]) => findManyMock(...args),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/session", () => ({
|
||||
getSessionUser: () => getSessionUserMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/ruleAdmins", () => ({
|
||||
isRuleAdminEmail: (...args: unknown[]) => isRuleAdminEmailMock(...args),
|
||||
}));
|
||||
|
||||
import { GET } from "../../app/api/ops/rule-counts/route";
|
||||
|
||||
function get(auth?: string) {
|
||||
return new NextRequest("https://x.test/api/ops/rule-counts", {
|
||||
headers: auth ? { authorization: auth } : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
isDatabaseConfiguredMock.mockReset();
|
||||
getOpsPruneTokenMock.mockReset();
|
||||
getRuleAdminEmailsMock.mockReset();
|
||||
getSessionUserMock.mockReset();
|
||||
isRuleAdminEmailMock.mockReset();
|
||||
findManyMock.mockReset();
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getOpsPruneTokenMock.mockReturnValue("secret");
|
||||
getRuleAdminEmailsMock.mockReturnValue(["ops@example.org"]);
|
||||
getSessionUserMock.mockResolvedValue(null);
|
||||
isRuleAdminEmailMock.mockReturnValue(false);
|
||||
findManyMock.mockResolvedValue([
|
||||
{ orgType: "mutualAid", communityLocation: "Boulder" },
|
||||
{ orgType: "mutualAid", communityLocation: "Boulder" },
|
||||
{ orgType: "mutualAid", communityLocation: "Boulder" },
|
||||
{ orgType: "mutualAid", communityLocation: "Boulder" },
|
||||
{ orgType: "mutualAid", communityLocation: "Boulder" },
|
||||
]);
|
||||
});
|
||||
|
||||
describe("GET /api/ops/rule-counts", () => {
|
||||
it("returns 404 when neither admins nor an ops token are configured", async () => {
|
||||
getRuleAdminEmailsMock.mockReturnValue([]);
|
||||
getOpsPruneTokenMock.mockReturnValue(null);
|
||||
const res = await GET(get("Bearer secret"), undefined);
|
||||
expect(res.status).toBe(404);
|
||||
expect(findManyMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns folded counts for a matching bearer token", async () => {
|
||||
const res = await GET(get("Bearer secret"), undefined);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as {
|
||||
finished: number;
|
||||
cells: Array<{ folded: boolean; count: number }>;
|
||||
};
|
||||
expect(body.finished).toBe(5);
|
||||
expect(body.cells[0]).toMatchObject({ folded: false, count: 5 });
|
||||
});
|
||||
|
||||
it("returns 401 when the session is not a named admin", async () => {
|
||||
const res = await GET(get(), undefined);
|
||||
expect(res.status).toBe(401);
|
||||
expect(findManyMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,8 @@ describe("buildPublicSitemap", () => {
|
||||
expect(urls.some((url) => url.includes("/profile"))).toBe(false);
|
||||
expect(urls.some((url) => url.includes("/create"))).toBe(false);
|
||||
expect(urls.some((url) => url.includes("/monitor"))).toBe(false);
|
||||
expect(urls.some((url) => url.includes("/rule-counts"))).toBe(false);
|
||||
expect(urls.some((url) => url.includes("/kit"))).toBe(false);
|
||||
expect(urls.some((url) => url.includes("/api/"))).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -28,6 +28,31 @@ describe("publishRule", () => {
|
||||
expect(result).toEqual({ ok: true, id: "r1", title: "T" });
|
||||
});
|
||||
|
||||
it("passes createdAt when the API includes it", async () => {
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
rule: {
|
||||
id: "r1",
|
||||
title: "T",
|
||||
createdAt: "2026-11-08T00:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: { "Content-Type": "application/json" },
|
||||
},
|
||||
),
|
||||
);
|
||||
const result = await publishRule(input);
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
id: "r1",
|
||||
title: "T",
|
||||
createdAt: "2026-11-08T00:00:00.000Z",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not throw when body is empty (e.g. connection reset)", async () => {
|
||||
globalThis.fetch = vi.fn().mockResolvedValue(
|
||||
new Response("", {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
publishedRuleAnalyticsFromDocument,
|
||||
publishedRuleAnalyticsFromState,
|
||||
} from "../../lib/create/publishedRuleAnalytics";
|
||||
|
||||
describe("publishedRuleAnalyticsFromDocument", () => {
|
||||
it("reads place and a canonical group type", () => {
|
||||
expect(
|
||||
publishedRuleAnalyticsFromDocument({
|
||||
communityLocation: " Boulder ",
|
||||
orgType: "mutualAid",
|
||||
}),
|
||||
).toEqual({ communityLocation: "Boulder", orgType: "mutualAid" });
|
||||
});
|
||||
|
||||
it("drops unknown types and empty place", () => {
|
||||
expect(
|
||||
publishedRuleAnalyticsFromDocument({
|
||||
communityLocation: " ",
|
||||
orgType: "not-a-kind",
|
||||
}),
|
||||
).toEqual({ communityLocation: null, orgType: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("publishedRuleAnalyticsFromState", () => {
|
||||
it("takes place from the description field and the main group type", () => {
|
||||
expect(
|
||||
publishedRuleAnalyticsFromState({
|
||||
communityLocation: "Denver",
|
||||
selectedOrganizationTypeIds: ["mutualAid", "nonprofit"],
|
||||
}),
|
||||
).toEqual({ communityLocation: "Denver", orgType: "mutualAid" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ruleExportToken,
|
||||
ruleExportTokenMatches,
|
||||
} from "../../lib/server/ruleExportToken";
|
||||
|
||||
describe("ruleExportToken", () => {
|
||||
it("accepts the matching token and rejects another rule or token", () => {
|
||||
const pepper = "test-pepper-16chars";
|
||||
const token = ruleExportToken("rule-1", pepper);
|
||||
expect(ruleExportTokenMatches("rule-1", token, pepper)).toBe(true);
|
||||
expect(ruleExportTokenMatches("rule-2", token, pepper)).toBe(false);
|
||||
expect(ruleExportTokenMatches("rule-1", `${token}x`, pepper)).toBe(false);
|
||||
expect(ruleExportTokenMatches("rule-1", "", pepper)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const getSessionPepperMock = vi.fn();
|
||||
const sendFollowUpMock = vi.fn();
|
||||
const findManyMock = vi.fn();
|
||||
const updateMock = vi.fn();
|
||||
const originFromHostMock = vi.fn();
|
||||
|
||||
vi.mock("../../lib/server/env", () => ({
|
||||
getSessionPepper: () => getSessionPepperMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/mail", () => ({
|
||||
sendRuleFollowUpEmail: (...args: unknown[]) => sendFollowUpMock(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/siteMetadata", () => ({
|
||||
originFromHost: () => originFromHostMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/logger", () => ({
|
||||
logger: { info: vi.fn(), error: vi.fn() },
|
||||
}));
|
||||
|
||||
import { sendDueRuleFollowUpEmails } from "../../lib/server/ruleFollowUp";
|
||||
|
||||
const db = {
|
||||
publishedRule: {
|
||||
findMany: (...args: unknown[]) => findManyMock(...args),
|
||||
update: (...args: unknown[]) => updateMock(...args),
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
getSessionPepperMock.mockReset();
|
||||
sendFollowUpMock.mockReset();
|
||||
findManyMock.mockReset();
|
||||
updateMock.mockReset();
|
||||
originFromHostMock.mockReset();
|
||||
getSessionPepperMock.mockReturnValue("test-pepper-16chars");
|
||||
originFromHostMock.mockReturnValue("https://staging.communityrule.info");
|
||||
sendFollowUpMock.mockResolvedValue(undefined);
|
||||
updateMock.mockResolvedValue({});
|
||||
});
|
||||
|
||||
describe("sendDueRuleFollowUpEmails", () => {
|
||||
it("sends once to the pen-holder and records sentAt", async () => {
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{
|
||||
id: "rule-1",
|
||||
title: "Garden Norms",
|
||||
user: { email: "pen@example.com" },
|
||||
},
|
||||
]);
|
||||
|
||||
const now = new Date("2026-11-10T12:00:00.000Z");
|
||||
const result = await sendDueRuleFollowUpEmails(db as never, now);
|
||||
|
||||
expect(result).toEqual({ sent: 1, failed: 0, skipped: 0 });
|
||||
expect(sendFollowUpMock).toHaveBeenCalledTimes(1);
|
||||
expect(sendFollowUpMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
to: "pen@example.com",
|
||||
communityName: "Garden Norms",
|
||||
origin: "https://staging.communityrule.info",
|
||||
pdfUrl: expect.stringContaining("/export/pdf?t="),
|
||||
markdownUrl: expect.stringContaining("/export/md?t="),
|
||||
}),
|
||||
);
|
||||
expect(updateMock).toHaveBeenCalledWith({
|
||||
where: { id: "rule-1" },
|
||||
data: { followUpEmailSentAt: now },
|
||||
});
|
||||
});
|
||||
|
||||
it("skips rows with no mailbox and does not mark them sent", async () => {
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{ id: "rule-2", title: "Guest", user: { email: "" } },
|
||||
]);
|
||||
const result = await sendDueRuleFollowUpEmails(db as never);
|
||||
expect(result.skipped).toBe(1);
|
||||
expect(sendFollowUpMock).not.toHaveBeenCalled();
|
||||
expect(updateMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaves sentAt unset when mail fails so the hourly job can retry", async () => {
|
||||
findManyMock.mockResolvedValueOnce([
|
||||
{
|
||||
id: "rule-3",
|
||||
title: "Retry",
|
||||
user: { email: "pen@example.com" },
|
||||
},
|
||||
]);
|
||||
sendFollowUpMock.mockRejectedValueOnce(new Error("smtp down"));
|
||||
const result = await sendDueRuleFollowUpEmails(db as never);
|
||||
expect(result.failed).toBe(1);
|
||||
expect(updateMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildRuleFollowUpMail } from "../../lib/server/ruleFollowUpMail";
|
||||
|
||||
describe("buildRuleFollowUpMail", () => {
|
||||
const mail = buildRuleFollowUpMail({
|
||||
to: "pen@example.com",
|
||||
origin: "https://communityrule.info",
|
||||
communityName: "Juniper Street Food Share",
|
||||
pdfUrl: "https://communityrule.info/api/rules/r1/export/pdf?t=tok",
|
||||
markdownUrl: "https://communityrule.info/api/rules/r1/export/md?t=tok",
|
||||
});
|
||||
|
||||
it("uses the drawn subject, PDF button, RULE.md link, and kit pointer", () => {
|
||||
expect(mail.subject).toBe("Juniper Street Food Share’s Rule, printed");
|
||||
expect(mail.previewText).toContain("ready to print");
|
||||
expect(mail.text).toContain("Download the PDF");
|
||||
expect(mail.text).toContain(
|
||||
"https://communityrule.info/api/rules/r1/export/pdf?t=tok",
|
||||
);
|
||||
expect(mail.text).toContain("RULE.md");
|
||||
expect(mail.text).toContain("communityrule.info/kit");
|
||||
expect(mail.html).toContain("Download the PDF");
|
||||
expect(mail.html).toContain("RULE.md");
|
||||
expect(mail.html).toContain("/kit");
|
||||
expect(mail.html).not.toMatch(/tracking pixel|1x1/i);
|
||||
});
|
||||
|
||||
it("does not invent a first name", () => {
|
||||
expect(mail.html).not.toContain("Hi Maya");
|
||||
expect(mail.text).not.toContain("Hi Maya");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { aggregateRuleLaunchCounts } from "../../lib/server/ruleLaunchCounts";
|
||||
|
||||
describe("aggregateRuleLaunchCounts", () => {
|
||||
it("folds cells under five and reports Rules finished", () => {
|
||||
const rows = [
|
||||
...Array.from({ length: 5 }, () => ({
|
||||
orgType: "mutualAid",
|
||||
place: "Boulder",
|
||||
})),
|
||||
...Array.from({ length: 5 }, () => ({
|
||||
orgType: "mutualAid",
|
||||
place: "boulder",
|
||||
})),
|
||||
{ orgType: "nonprofit", place: "Denver" },
|
||||
{ orgType: "workersCoop", place: "Oakland" },
|
||||
];
|
||||
const counts = aggregateRuleLaunchCounts(rows);
|
||||
expect(counts.finished).toBe(12);
|
||||
expect(counts.cells).toEqual([
|
||||
{
|
||||
orgType: "mutualAid",
|
||||
place: "Boulder",
|
||||
count: 10,
|
||||
folded: false,
|
||||
},
|
||||
{
|
||||
orgType: null,
|
||||
place: null,
|
||||
count: 2,
|
||||
folded: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns no cells when nothing is finished", () => {
|
||||
expect(aggregateRuleLaunchCounts([])).toEqual({ finished: 0, cells: [] });
|
||||
});
|
||||
});
|
||||
@@ -108,6 +108,8 @@ describe("PATCH /api/rules/[id]", () => {
|
||||
data: expect.objectContaining({
|
||||
title: "Updated",
|
||||
summary: "Context",
|
||||
orgType: null,
|
||||
communityLocation: null,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ruleExportToken } from "../../lib/server/ruleExportToken";
|
||||
|
||||
const isDatabaseConfiguredMock = vi.fn();
|
||||
const getSessionPepperMock = vi.fn();
|
||||
const findUniqueMock = vi.fn();
|
||||
const getSessionUserMock = vi.fn();
|
||||
const isRuleAdminEmailMock = vi.fn();
|
||||
|
||||
vi.mock("../../lib/server/env", () => ({
|
||||
isDatabaseConfigured: () => isDatabaseConfiguredMock(),
|
||||
getSessionPepper: () => getSessionPepperMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/db", () => ({
|
||||
prisma: {
|
||||
publishedRule: {
|
||||
findUnique: (...args: unknown[]) => findUniqueMock(...args),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/session", () => ({
|
||||
getSessionUser: () => getSessionUserMock(),
|
||||
}));
|
||||
|
||||
vi.mock("../../lib/server/ruleAdmins", () => ({
|
||||
isRuleAdminEmail: (...args: unknown[]) => isRuleAdminEmailMock(...args),
|
||||
}));
|
||||
|
||||
import { GET } from "../../app/api/rules/[id]/export/[format]/route";
|
||||
|
||||
const PEPPER = "test-pepper-16chars";
|
||||
|
||||
function makeContext(id: string, format: string) {
|
||||
return { params: Promise.resolve({ id, format }) };
|
||||
}
|
||||
|
||||
function row() {
|
||||
return {
|
||||
id: "rule-1",
|
||||
title: "Garden Norms",
|
||||
summary: "We share tools.",
|
||||
document: {
|
||||
sections: [
|
||||
{
|
||||
categoryName: "Values",
|
||||
entries: [{ title: "Solidarity", body: "Be kind." }],
|
||||
},
|
||||
],
|
||||
},
|
||||
createdAt: new Date("2026-11-08T00:00:00.000Z"),
|
||||
userId: "user-1",
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
isDatabaseConfiguredMock.mockReset();
|
||||
getSessionPepperMock.mockReset();
|
||||
findUniqueMock.mockReset();
|
||||
getSessionUserMock.mockReset();
|
||||
isRuleAdminEmailMock.mockReset();
|
||||
isDatabaseConfiguredMock.mockReturnValue(true);
|
||||
getSessionPepperMock.mockReturnValue(PEPPER);
|
||||
getSessionUserMock.mockResolvedValue(null);
|
||||
isRuleAdminEmailMock.mockReturnValue(false);
|
||||
findUniqueMock.mockResolvedValue(row());
|
||||
});
|
||||
|
||||
describe("GET /api/rules/[id]/export/[format]", () => {
|
||||
it("returns 404 for an unknown format", async () => {
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1/export/csv"),
|
||||
makeContext("rule-1", "csv"),
|
||||
);
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
it("returns 401 without a token or session", async () => {
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1/export/pdf"),
|
||||
makeContext("rule-1", "pdf"),
|
||||
);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns a PDF attachment when the export token matches", async () => {
|
||||
const token = ruleExportToken("rule-1", PEPPER);
|
||||
const res = await GET(
|
||||
new NextRequest(
|
||||
`https://x.test/api/rules/rule-1/export/pdf?t=${token}`,
|
||||
),
|
||||
makeContext("rule-1", "pdf"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toBe("application/pdf");
|
||||
expect(res.headers.get("content-disposition")).toContain(
|
||||
"Garden Norms Rule.pdf",
|
||||
);
|
||||
const buf = Buffer.from(await res.arrayBuffer());
|
||||
expect(buf.subarray(0, 5).toString()).toBe("%PDF-");
|
||||
});
|
||||
|
||||
it("returns RULE.md for the owner without a token", async () => {
|
||||
getSessionUserMock.mockResolvedValue({
|
||||
id: "user-1",
|
||||
email: "owner@example.com",
|
||||
});
|
||||
const res = await GET(
|
||||
new NextRequest("https://x.test/api/rules/rule-1/export/md"),
|
||||
makeContext("rule-1", "md"),
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toContain("text/markdown");
|
||||
const text = await res.text();
|
||||
expect(text).toContain("# Garden Norms");
|
||||
expect(text).toContain("## Shared terms");
|
||||
});
|
||||
});
|
||||
@@ -114,6 +114,40 @@ describe("POST /api/rules", () => {
|
||||
expect(sendInviteMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stores place and group type from the published document", async () => {
|
||||
publishedRuleCreateMock.mockResolvedValueOnce({
|
||||
id: "rule-counts",
|
||||
title: "T",
|
||||
summary: null,
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
});
|
||||
|
||||
const res = await POST(
|
||||
new NextRequest("https://x.test/api/rules", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
title: "T",
|
||||
summary: null,
|
||||
document: {
|
||||
orgType: "mutualAid",
|
||||
communityLocation: "Boulder",
|
||||
},
|
||||
}),
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(publishedRuleCreateMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
orgType: "mutualAid",
|
||||
communityLocation: "Boulder",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("uses a transaction and sends stakeholder invites", async () => {
|
||||
const created = {
|
||||
id: "rule-new",
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { RULE_VISIBILITY } from "../../lib/ruleVisibility";
|
||||
import {
|
||||
ASK_ORGANIZER_HASH,
|
||||
askOrganizerUrl,
|
||||
buildShareRuleUrl,
|
||||
formatShareUrlDisplay,
|
||||
isShareSlug,
|
||||
ruleExportMarkdownUrl,
|
||||
ruleExportPdfUrl,
|
||||
shareCopyUrl,
|
||||
shareRulePath,
|
||||
} from "../../lib/sharePaths";
|
||||
@@ -43,4 +47,17 @@ describe("sharePaths", () => {
|
||||
}),
|
||||
).toBe("https://communityrule.info/rules/rule-1");
|
||||
});
|
||||
|
||||
it("builds Ask an organizer and export URLs", () => {
|
||||
expect(ASK_ORGANIZER_HASH).toBe("ask-organizer");
|
||||
expect(askOrganizerUrl("https://communityrule.info/")).toBe(
|
||||
"https://communityrule.info/#ask-organizer",
|
||||
);
|
||||
expect(
|
||||
ruleExportPdfUrl("https://communityrule.info", "rule/1", "tok"),
|
||||
).toBe("https://communityrule.info/api/rules/rule%2F1/export/pdf?t=tok");
|
||||
expect(
|
||||
ruleExportMarkdownUrl("https://communityrule.info", "id", "tok"),
|
||||
).toBe("https://communityrule.info/api/rules/id/export/md?t=tok");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { umamiTracker } from "../../lib/umami";
|
||||
|
||||
const KEYS = ["NEXT_PUBLIC_UMAMI_SRC", "NEXT_PUBLIC_UMAMI_WEBSITE_ID"] as const;
|
||||
const ORIGINAL = Object.fromEntries(
|
||||
KEYS.map((key) => [key, process.env[key]]),
|
||||
) as Record<(typeof KEYS)[number], string | undefined>;
|
||||
|
||||
afterEach(() => {
|
||||
for (const key of KEYS) {
|
||||
const original = ORIGINAL[key];
|
||||
if (original === undefined) delete process.env[key];
|
||||
else process.env[key] = original;
|
||||
}
|
||||
});
|
||||
|
||||
describe("umamiTracker", () => {
|
||||
it("is off when either env var is missing", () => {
|
||||
delete process.env.NEXT_PUBLIC_UMAMI_SRC;
|
||||
delete process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID;
|
||||
expect(umamiTracker()).toBeNull();
|
||||
process.env.NEXT_PUBLIC_UMAMI_SRC = "https://analytics.example.com/script.js";
|
||||
expect(umamiTracker()).toBeNull();
|
||||
});
|
||||
|
||||
it("returns the script URL and website id", () => {
|
||||
process.env.NEXT_PUBLIC_UMAMI_SRC =
|
||||
"https://analytics.example.com/script.js";
|
||||
process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID = "site-1";
|
||||
expect(umamiTracker()).toEqual({
|
||||
src: "https://analytics.example.com/script.js",
|
||||
websiteId: "site-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a non-http script URL", () => {
|
||||
process.env.NEXT_PUBLIC_UMAMI_SRC = "javascript:alert(1)";
|
||||
process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID = "site-1";
|
||||
expect(umamiTracker()).toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user