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
@@ -50,8 +50,14 @@ NEXT_PUBLIC_ENABLE_BACKEND_SYNC=
|
||||
# SITE_INDEXING=false
|
||||
|
||||
# Named admins who may open a private Rule. Comma-separated emails. Every such read is logged.
|
||||
# The same list can open /rule-counts (finished Rules by group type and place).
|
||||
# RULE_ADMIN_EMAILS=ops@example.org
|
||||
|
||||
# Optional Umami (self-hosted beside the app). Unset: no tracker script.
|
||||
# Cookie-free / no-cookies is an Umami server setting.
|
||||
# NEXT_PUBLIC_UMAMI_SRC=https://analytics.example.com/script.js
|
||||
# NEXT_PUBLIC_UMAMI_WEBSITE_ID=
|
||||
|
||||
# Writable directory for `POST /api/uploads` (community photo + custom-method attachments).
|
||||
# In production (e.g. Cloudron localstorage mount), set to the mounted path. Local dev example:
|
||||
# UPLOAD_ROOT="/absolute/path/to/community-rule/var/uploads"
|
||||
@@ -4,7 +4,7 @@
|
||||
"title": "Community Rule",
|
||||
"author": "MEDLab",
|
||||
"description": "Community governance and rule-building app",
|
||||
"version": "0.1.14",
|
||||
"version": "0.1.15",
|
||||
"httpPort": 3000,
|
||||
"healthCheckPath": "/api/health",
|
||||
"memoryLimit": 805306368,
|
||||
@@ -17,6 +17,10 @@
|
||||
"prune-expired": {
|
||||
"schedule": "20 7 * * *",
|
||||
"command": "gosu node:node node /app/prune-expired.bundle.cjs"
|
||||
},
|
||||
"follow-up-mail": {
|
||||
"schedule": "15 * * * *",
|
||||
"command": "gosu node:node node /app/follow-up-mail.bundle.cjs"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -38,6 +38,10 @@ RUN ./node_modules/.bin/esbuild scripts/prune-sessions.ts \
|
||||
--bundle --platform=node --format=cjs \
|
||||
--outfile=prune-expired.bundle.cjs \
|
||||
--external:@prisma/client
|
||||
RUN ./node_modules/.bin/esbuild scripts/send-rule-follow-up.ts \
|
||||
--bundle --platform=node --format=cjs \
|
||||
--outfile=follow-up-mail.bundle.cjs \
|
||||
--external:@prisma/client
|
||||
|
||||
FROM base AS runner
|
||||
# openssl: Prisma engines. gosu: privilege drop in start.sh after chown.
|
||||
@@ -53,6 +57,7 @@ COPY --from=builder --chown=node:node /app/.next/standalone ./
|
||||
COPY --from=builder --chown=node:node /app/.next/static ./.next/static
|
||||
COPY --from=builder --chown=node:node /app/prisma ./prisma
|
||||
COPY --from=builder --chown=node:node /app/prune-expired.bundle.cjs ./prune-expired.bundle.cjs
|
||||
COPY --from=builder --chown=node:node /app/follow-up-mail.bundle.cjs ./follow-up-mail.bundle.cjs
|
||||
# Facet/template seed JSON — NOT under /app/data (localstorage mount overlays that).
|
||||
COPY --from=builder --chown=node:node /app/data ./seed-data
|
||||
ENV SEED_DATA_DIR=/app/seed-data
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import type { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import messages from "../../../messages/en/index";
|
||||
import communityStructure from "../../../messages/en/create/community/communityStructure.json";
|
||||
import { routeMetadata } from "../../../lib/siteMetadata";
|
||||
import { getRuleAdminEmails, isDatabaseConfigured } from "../../../lib/server/env";
|
||||
import { prisma } from "../../../lib/server/db";
|
||||
import { isRuleAdminEmail } from "../../../lib/server/ruleAdmins";
|
||||
import { aggregateRuleLaunchCounts } from "../../../lib/server/ruleLaunchCounts";
|
||||
import { getSessionUser } from "../../../lib/server/session";
|
||||
|
||||
export const metadata: Metadata = routeMetadata("/rule-counts", {
|
||||
title: messages.metadata.ruleCounts.title,
|
||||
robots: { index: false, follow: false },
|
||||
});
|
||||
|
||||
const ORG_LABELS = Object.fromEntries(
|
||||
communityStructure.organizationTypes.map((row) => [row.id, row.label]),
|
||||
);
|
||||
|
||||
function typeLabel(orgType: string | null, folded: boolean, copy: typeof messages.pages.ruleCounts): string {
|
||||
if (folded) return copy.folded;
|
||||
if (!orgType) return copy.notGiven;
|
||||
return ORG_LABELS[orgType] ?? orgType;
|
||||
}
|
||||
|
||||
function placeLabel(place: string | null, folded: boolean, copy: typeof messages.pages.ruleCounts): string {
|
||||
if (folded) return copy.folded;
|
||||
if (!place) return copy.notGiven;
|
||||
return place;
|
||||
}
|
||||
|
||||
export default async function RuleCountsPage() {
|
||||
if (getRuleAdminEmails().length === 0) notFound();
|
||||
|
||||
const copy = messages.pages.ruleCounts;
|
||||
const user = await getSessionUser();
|
||||
if (!user) {
|
||||
return (
|
||||
<section className="mx-auto flex w-full max-w-md flex-col gap-4 px-6 py-16">
|
||||
<h1 className="x-large-heading text-[var(--color-content-default-primary)]">
|
||||
{copy.title}
|
||||
</h1>
|
||||
<p className="medium-paragraph">{copy.signIn}</p>
|
||||
<Link href="/login?next=/rule-counts" className="medium-label underline">
|
||||
{copy.signInButton}
|
||||
</Link>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
if (!isRuleAdminEmail(user.email)) {
|
||||
return (
|
||||
<section className="mx-auto flex w-full max-w-md flex-col gap-4 px-6 py-16">
|
||||
<h1 className="x-large-heading text-[var(--color-content-default-primary)]">
|
||||
{copy.title}
|
||||
</h1>
|
||||
<p className="medium-paragraph">{copy.forbidden}</p>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const rows = isDatabaseConfigured()
|
||||
? await prisma.publishedRule.findMany({
|
||||
select: { orgType: true, communityLocation: true },
|
||||
})
|
||||
: [];
|
||||
const counts = aggregateRuleLaunchCounts(
|
||||
rows.map((row) => ({
|
||||
orgType: row.orgType,
|
||||
place: row.communityLocation,
|
||||
})),
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="mx-auto flex w-full max-w-4xl flex-col gap-6 px-6 py-12">
|
||||
<h1 className="x-large-heading text-[var(--color-content-default-primary)]">
|
||||
{copy.title}
|
||||
</h1>
|
||||
<p className="medium-paragraph">{copy.intro}</p>
|
||||
<p className="large-label">
|
||||
{copy.finished}: {counts.finished}
|
||||
</p>
|
||||
{counts.cells.length === 0 ? (
|
||||
<p className="medium-paragraph">{copy.empty}</p>
|
||||
) : (
|
||||
<table className="w-full border-collapse text-left">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="medium-label py-2">{copy.columns.type}</th>
|
||||
<th className="medium-label py-2">{copy.columns.place}</th>
|
||||
<th className="medium-label py-2">{copy.columns.count}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{counts.cells.map((cell) => (
|
||||
<tr
|
||||
key={`${cell.folded ? "folded" : "open"}:${cell.orgType ?? ""}:${cell.place ?? ""}`}
|
||||
>
|
||||
<td className="small-paragraph py-2">
|
||||
{typeLabel(cell.orgType, cell.folded, copy)}
|
||||
</td>
|
||||
<td className="small-paragraph py-2">
|
||||
{placeLabel(cell.place, cell.folded, copy)}
|
||||
</td>
|
||||
<td className="small-paragraph py-2">{cell.count}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -15,11 +15,10 @@ import {
|
||||
} from "../../../../lib/create/shareChannels";
|
||||
import {
|
||||
buildPublicRuleUrl,
|
||||
downloadStoredRuleAsMarkdown,
|
||||
downloadStoredRuleAsPdf,
|
||||
downloadTextFile,
|
||||
exportFilenameBase,
|
||||
exportStoredRuleAsCsv,
|
||||
exportStoredRuleAsMarkdown,
|
||||
printStoredRule,
|
||||
type RuleExportFormat,
|
||||
} from "../../../../lib/create/ruleExport";
|
||||
|
||||
export type CompletedFlowActionBanner = {
|
||||
@@ -101,7 +100,7 @@ export function useCompletedRuleShareExport({
|
||||
sharePublishedRuleViaSignal: () => Promise<void>;
|
||||
sharePublishedRuleViaSlack: () => Promise<void>;
|
||||
sharePublishedRuleViaDiscord: () => Promise<void>;
|
||||
onSelectExportFormat: (_format: "pdf" | "csv" | "markdown") => void;
|
||||
onSelectExportFormat: (_format: RuleExportFormat) => void;
|
||||
} {
|
||||
const t = useTranslation("create.reviewAndComplete.completed");
|
||||
|
||||
@@ -318,7 +317,7 @@ export function useCompletedRuleShareExport({
|
||||
]);
|
||||
|
||||
const onSelectExportFormat = useCallback(
|
||||
(format: "pdf" | "csv" | "markdown") => {
|
||||
(format: RuleExportFormat) => {
|
||||
if (typeof window === "undefined") return;
|
||||
const rule = readLastPublishedRule();
|
||||
if (!rule) {
|
||||
@@ -331,34 +330,29 @@ export function useCompletedRuleShareExport({
|
||||
return;
|
||||
}
|
||||
|
||||
const base = exportFilenameBase(rule);
|
||||
const origin = window.location.origin;
|
||||
try {
|
||||
if (format === "pdf") {
|
||||
downloadStoredRuleAsPdf(rule);
|
||||
} else if (format === "csv") {
|
||||
const csv = exportStoredRuleAsCsv(rule);
|
||||
downloadTextFile(
|
||||
`${base}-community-rule.csv`,
|
||||
csv,
|
||||
"text/csv;charset=utf-8",
|
||||
);
|
||||
downloadStoredRuleAsPdf(rule, origin);
|
||||
} else if (format === "print") {
|
||||
const opened = printStoredRule(rule, origin);
|
||||
if (!opened) {
|
||||
setActionBanner({
|
||||
key: "completedPrintBlocked",
|
||||
status: "warning",
|
||||
title: t("printBlockedTitle"),
|
||||
description: t("printBlockedDescription"),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const md = exportStoredRuleAsMarkdown(rule);
|
||||
downloadTextFile(
|
||||
`${base}-community-rule.md`,
|
||||
md,
|
||||
"text/markdown;charset=utf-8",
|
||||
);
|
||||
downloadStoredRuleAsMarkdown(rule, origin);
|
||||
}
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error && e.message === "exportEmptyDocument";
|
||||
} catch {
|
||||
setActionBanner({
|
||||
key: "completedExportFailed",
|
||||
status: "danger",
|
||||
title: msg ? t("exportEmptyDocumentTitle") : t("exportFailedTitle"),
|
||||
description: msg
|
||||
? t("exportEmptyDocumentDescription")
|
||||
: t("exportFailedDescription"),
|
||||
title: t("exportFailedTitle"),
|
||||
description: t("exportFailedDescription"),
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
@@ -196,6 +196,9 @@ export function useCreateFlowFinalize({
|
||||
title,
|
||||
summary: summary ?? null,
|
||||
document: ruleDocument,
|
||||
...(publishResult.createdAt
|
||||
? { finishedAt: publishResult.createdAt }
|
||||
: {}),
|
||||
});
|
||||
if (isGuest) {
|
||||
writePendingKeepRuleLogin();
|
||||
|
||||
@@ -4,16 +4,17 @@ import { useState, useEffect } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import CommunityRule from "../../../../components/type/CommunityRule";
|
||||
import type { CommunityRuleSection } from "../../../../components/type/CommunityRule/CommunityRule.types";
|
||||
import Link from "next/link";
|
||||
import Alert from "../../../../components/modals/Alert";
|
||||
import AskOrganizerInquiryModal from "../../../../components/modals/AskOrganizerInquiry";
|
||||
import InlineTextButton from "../../../../components/buttons/InlineTextButton";
|
||||
import { useMessages } from "../../../../contexts/MessagesContext";
|
||||
import { fetchPublishedRuleDetail } from "../../../../../lib/create/api";
|
||||
import { parsePublishedDocumentForCommunityRuleDisplay } from "../../../../../lib/create/publishedDocumentToDisplaySections";
|
||||
import {
|
||||
finishedAtIso,
|
||||
readLastPublishedRule,
|
||||
writeLastPublishedRule,
|
||||
} from "../../../../../lib/create/lastPublishedRule";
|
||||
import { ASK_ORGANIZER_HASH } from "../../../../../lib/sharePaths";
|
||||
import { useCreateFlowMdUp } from "../../hooks/useCreateFlowMdUp";
|
||||
import { CreateFlowHeaderLockup } from "../../components/CreateFlowHeaderLockup";
|
||||
import {
|
||||
@@ -99,7 +100,6 @@ export function CompletedScreen() {
|
||||
/** Latch: toast copy should survive `router.replace` after we strip `?celebrate=1`. */
|
||||
const [showCelebrateToast] = useState(celebrateInUrl);
|
||||
const [showCopiedReady] = useState(copiedInUrl);
|
||||
const [askOrganizerOpen, setAskOrganizerOpen] = useState(false);
|
||||
const [headerTitle, setHeaderTitle] = useState(initial.headerTitle);
|
||||
const [headerDescription, setHeaderDescription] = useState<
|
||||
string | undefined
|
||||
@@ -124,11 +124,13 @@ export function CompletedScreen() {
|
||||
return;
|
||||
}
|
||||
const doc = detail.rule.document as Record<string, unknown>;
|
||||
const finishedAt = finishedAtIso(detail.rule.createdAt);
|
||||
writeLastPublishedRule({
|
||||
id: detail.rule.id,
|
||||
title: detail.rule.title,
|
||||
summary: detail.rule.summary,
|
||||
document: doc,
|
||||
...(finishedAt ? { finishedAt } : {}),
|
||||
});
|
||||
const parsed = parsePublishedDocumentForCommunityRuleDisplay(doc);
|
||||
if (parsed.length === 0) {
|
||||
@@ -210,13 +212,17 @@ export function CompletedScreen() {
|
||||
/>
|
||||
{headerTitle && !surfaceCopied ? (
|
||||
<p className="mt-[var(--space-400)] max-w-[640px] text-small-paragraph text-[var(--color-content-invert-secondary)]">
|
||||
{completed.askOrganizerLead}{" "}
|
||||
<InlineTextButton
|
||||
className="text-small-paragraph text-[var(--color-content-invert-primary)]"
|
||||
onClick={() => setAskOrganizerOpen(true)}
|
||||
{completed.askOrganizerLead ? (
|
||||
<>
|
||||
{completed.askOrganizerLead}{" "}
|
||||
</>
|
||||
) : null}
|
||||
<Link
|
||||
href={`/#${ASK_ORGANIZER_HASH}`}
|
||||
className="text-small-paragraph text-[var(--color-content-invert-primary)] underline"
|
||||
>
|
||||
{completed.askOrganizerLink}
|
||||
</InlineTextButton>
|
||||
</Link>
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
@@ -261,10 +267,6 @@ export function CompletedScreen() {
|
||||
</div>
|
||||
</div>
|
||||
{toast}
|
||||
<AskOrganizerInquiryModal
|
||||
isOpen={askOrganizerOpen}
|
||||
onClose={() => setAskOrganizerOpen(false)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -12,7 +12,10 @@ import { communityPossessive } from "../../../../lib/create/ruleInviteCardMeta";
|
||||
import { CREATE_FLOW_COPIED_QUERY, CREATE_FLOW_COPIED_VALUE } from "../../../../lib/create/invitePaths";
|
||||
import { formatInviteLastChanged } from "../../../../lib/create/inviteLastChanged";
|
||||
import { writeLastPublishedRule } from "../../../../lib/create/lastPublishedRule";
|
||||
import { downloadStoredRuleAsPdf } from "../../../../lib/create/ruleExport";
|
||||
import {
|
||||
downloadStoredRuleAsPdf,
|
||||
printStoredRule,
|
||||
} from "../../../../lib/create/ruleExport";
|
||||
import { createCompletedPath } from "../../create/utils/createFlowPaths";
|
||||
import { CreateFlowHeaderLockup } from "../../create/components/CreateFlowHeaderLockup";
|
||||
import { useCreateFlowMdUp } from "../../create/hooks/useCreateFlowMdUp";
|
||||
@@ -79,18 +82,34 @@ export function InvitedRuleView({
|
||||
|
||||
const handlePdf = useCallback(() => {
|
||||
try {
|
||||
downloadStoredRuleAsPdf({
|
||||
id: ruleId,
|
||||
title,
|
||||
summary,
|
||||
document,
|
||||
});
|
||||
downloadStoredRuleAsPdf(
|
||||
{
|
||||
id: ruleId,
|
||||
title,
|
||||
summary,
|
||||
document,
|
||||
},
|
||||
window.location.origin,
|
||||
);
|
||||
setExportError(false);
|
||||
} catch {
|
||||
setExportError(true);
|
||||
}
|
||||
}, [document, ruleId, summary, title]);
|
||||
|
||||
const handlePrint = useCallback(() => {
|
||||
const opened = printStoredRule(
|
||||
{
|
||||
id: ruleId,
|
||||
title,
|
||||
summary,
|
||||
document,
|
||||
},
|
||||
window.location.origin,
|
||||
);
|
||||
setExportError(!opened);
|
||||
}, [document, ruleId, summary, title]);
|
||||
|
||||
const handleCopy = useCallback(
|
||||
async (communityName: string) => {
|
||||
setCopyBusy(true);
|
||||
@@ -194,7 +213,7 @@ export function InvitedRuleView({
|
||||
size="xsmall"
|
||||
type="button"
|
||||
className={outlineButtonClass}
|
||||
onClick={() => window.print()}
|
||||
onClick={handlePrint}
|
||||
>
|
||||
{t("print")}
|
||||
</Button>
|
||||
|
||||
@@ -19,12 +19,11 @@ import {
|
||||
type PublishedRuleDetailForClient,
|
||||
} from "../../../lib/create/api";
|
||||
import {
|
||||
downloadStoredRuleAsMarkdown,
|
||||
downloadStoredRuleAsPdf,
|
||||
downloadTextFile,
|
||||
exportFilenameBase,
|
||||
exportStoredRuleAsMarkdown,
|
||||
} from "../../../lib/create/ruleExport";
|
||||
import {
|
||||
finishedAtIso,
|
||||
writeLastPublishedRule,
|
||||
type StoredLastPublishedRule,
|
||||
} from "../../../lib/create/lastPublishedRule";
|
||||
@@ -255,11 +254,13 @@ export default function ProfilePageClient() {
|
||||
setActionError(t("actionError"));
|
||||
return;
|
||||
}
|
||||
const finishedAt = finishedAtIso(detail.rule.createdAt);
|
||||
writeLastPublishedRule({
|
||||
id: detail.rule.id,
|
||||
title: detail.rule.title,
|
||||
summary: detail.rule.summary,
|
||||
document: detail.rule.document as Record<string, unknown>,
|
||||
...(finishedAt ? { finishedAt } : {}),
|
||||
});
|
||||
router.push(
|
||||
createFlowStepPath("confirm-stakeholders", {
|
||||
@@ -334,11 +335,13 @@ export default function ProfilePageClient() {
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const finishedAt = finishedAtIso(rule.createdAt);
|
||||
return {
|
||||
id: rule.id,
|
||||
title: rule.title,
|
||||
summary: rule.summary,
|
||||
document: rule.document as Record<string, unknown>,
|
||||
...(finishedAt ? { finishedAt } : {}),
|
||||
};
|
||||
},
|
||||
[],
|
||||
@@ -354,7 +357,7 @@ export default function ProfilePageClient() {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
downloadStoredRuleAsPdf(stored);
|
||||
downloadStoredRuleAsPdf(stored, window.location.origin);
|
||||
} catch {
|
||||
setActionError(t("actionError"));
|
||||
}
|
||||
@@ -372,12 +375,7 @@ export default function ProfilePageClient() {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const markdown = exportStoredRuleAsMarkdown(stored);
|
||||
downloadTextFile(
|
||||
`${exportFilenameBase(stored)}-community-rule.md`,
|
||||
markdown,
|
||||
"text/markdown;charset=utf-8",
|
||||
);
|
||||
downloadStoredRuleAsMarkdown(stored, window.location.origin);
|
||||
} catch {
|
||||
setActionError(t("actionError"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
/** Office-hours pointer used in the 48-hour follow-up email. */
|
||||
export default function KitPage() {
|
||||
redirect("/workshops");
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { apiRoute } from "../../../../lib/server/apiRoute";
|
||||
import { prisma } from "../../../../lib/server/db";
|
||||
import {
|
||||
getOpsPruneToken,
|
||||
getRuleAdminEmails,
|
||||
isDatabaseConfigured,
|
||||
} from "../../../../lib/server/env";
|
||||
import {
|
||||
dbUnavailable,
|
||||
notFound,
|
||||
unauthorized,
|
||||
} from "../../../../lib/server/responses";
|
||||
import { isRuleAdminEmail } from "../../../../lib/server/ruleAdmins";
|
||||
import { aggregateRuleLaunchCounts } from "../../../../lib/server/ruleLaunchCounts";
|
||||
import { getSessionUser } from "../../../../lib/server/session";
|
||||
|
||||
export const GET = apiRoute("ops.ruleCounts", async (request: NextRequest) => {
|
||||
if (getRuleAdminEmails().length === 0 && !getOpsPruneToken()) {
|
||||
return notFound();
|
||||
}
|
||||
if (!isDatabaseConfigured()) return dbUnavailable();
|
||||
|
||||
const header = request.headers.get("authorization") ?? "";
|
||||
const opsToken = getOpsPruneToken();
|
||||
const bearerOk = Boolean(opsToken) && header === `Bearer ${opsToken}`;
|
||||
if (!bearerOk) {
|
||||
const user = await getSessionUser();
|
||||
if (!user || !isRuleAdminEmail(user.email)) return unauthorized();
|
||||
}
|
||||
|
||||
const rows = await prisma.publishedRule.findMany({
|
||||
select: { orgType: true, communityLocation: true },
|
||||
});
|
||||
const counts = aggregateRuleLaunchCounts(
|
||||
rows.map((row) => ({
|
||||
orgType: row.orgType,
|
||||
place: row.communityLocation,
|
||||
})),
|
||||
);
|
||||
return NextResponse.json(counts);
|
||||
});
|
||||
@@ -0,0 +1,112 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { apiRoute } from "../../../../../../lib/server/apiRoute";
|
||||
import { prisma } from "../../../../../../lib/server/db";
|
||||
import {
|
||||
getSessionPepper,
|
||||
isDatabaseConfigured,
|
||||
} from "../../../../../../lib/server/env";
|
||||
import { getPublicOrigin } from "../../../../../../lib/server/publicOrigin";
|
||||
import {
|
||||
dbUnavailable,
|
||||
forbidden,
|
||||
notFound,
|
||||
unauthorized,
|
||||
} from "../../../../../../lib/server/responses";
|
||||
import { isRuleAdminEmail } from "../../../../../../lib/server/ruleAdmins";
|
||||
import { ruleExportTokenMatches } from "../../../../../../lib/server/ruleExportToken";
|
||||
import { getSessionUser } from "../../../../../../lib/server/session";
|
||||
import {
|
||||
RULE_MD_FILENAME,
|
||||
buildStoredRulePdfBytes,
|
||||
exportPdfFilename,
|
||||
exportStoredRuleAsMarkdown,
|
||||
} from "../../../../../../lib/create/ruleExport";
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string; format: string }> };
|
||||
|
||||
function attachmentDisposition(filename: string): string {
|
||||
const ascii = filename.replace(/[^\x20-\x7E]/g, "_").replace(/"/g, "");
|
||||
const encoded = encodeURIComponent(filename);
|
||||
return `attachment; filename="${ascii}"; filename*=UTF-8''${encoded}`;
|
||||
}
|
||||
|
||||
function documentRecord(value: unknown): Record<string, unknown> | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
export const GET = apiRoute<RouteContext>(
|
||||
"rules.export",
|
||||
async (request: NextRequest, context) => {
|
||||
if (!isDatabaseConfigured()) return dbUnavailable();
|
||||
|
||||
const { id, format } = await context.params;
|
||||
if (format !== "pdf" && format !== "md") return notFound();
|
||||
|
||||
const row = await prisma.publishedRule.findUnique({
|
||||
where: { id },
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
summary: true,
|
||||
document: true,
|
||||
createdAt: true,
|
||||
userId: true,
|
||||
},
|
||||
});
|
||||
if (!row) return notFound();
|
||||
|
||||
const token = request.nextUrl.searchParams.get("t") ?? "";
|
||||
let tokenOk = false;
|
||||
if (token.length > 0) {
|
||||
try {
|
||||
tokenOk = ruleExportTokenMatches(row.id, token, getSessionPepper());
|
||||
} catch {
|
||||
tokenOk = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!tokenOk) {
|
||||
const user = await getSessionUser();
|
||||
if (!user) return unauthorized();
|
||||
const isOwner = row.userId === user.id;
|
||||
if (!isOwner && !isRuleAdminEmail(user.email)) {
|
||||
return forbidden("You do not have permission to export this rule");
|
||||
}
|
||||
}
|
||||
|
||||
const document = documentRecord(row.document);
|
||||
if (!document) return notFound();
|
||||
|
||||
const origin = getPublicOrigin(request);
|
||||
const source = {
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
summary: row.summary,
|
||||
document,
|
||||
finishedAt: row.createdAt,
|
||||
};
|
||||
|
||||
if (format === "pdf") {
|
||||
const bytes = buildStoredRulePdfBytes(source, origin);
|
||||
return new NextResponse(Buffer.from(bytes), {
|
||||
headers: {
|
||||
"Content-Type": "application/pdf",
|
||||
"Content-Disposition": attachmentDisposition(
|
||||
exportPdfFilename(row.title),
|
||||
),
|
||||
"Cache-Control": "private, no-store",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const markdown = exportStoredRuleAsMarkdown(source, origin);
|
||||
return new NextResponse(markdown, {
|
||||
headers: {
|
||||
"Content-Type": "text/markdown; charset=utf-8",
|
||||
"Content-Disposition": attachmentDisposition(RULE_MD_FILENAME),
|
||||
"Cache-Control": "private, no-store",
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -16,6 +16,7 @@ import { linkUploadsToRule } from "../../../../lib/server/uploads/linkUploads";
|
||||
import { publishRuleBodySchema } from "../../../../lib/server/validation/createFlowSchemas";
|
||||
import { readLimitedJson } from "../../../../lib/server/validation/requestBody";
|
||||
import { jsonFromZodError } from "../../../../lib/server/validation/zodHttp";
|
||||
import { publishedRuleAnalyticsColumns } from "../../../../lib/server/publishedRulePersist";
|
||||
|
||||
type RouteContext = { params: Promise<{ id: string }> };
|
||||
|
||||
@@ -88,6 +89,7 @@ export const PATCH = apiRoute<RouteContext>(
|
||||
title,
|
||||
summary,
|
||||
document: document as Prisma.InputJsonValue,
|
||||
...publishedRuleAnalyticsColumns(document),
|
||||
},
|
||||
});
|
||||
await linkUploadsToRule({
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
} from "../../../lib/server/validation/createFlowSchemas";
|
||||
import { readLimitedJson } from "../../../lib/server/validation/requestBody";
|
||||
import { jsonFromZodError } from "../../../lib/server/validation/zodHttp";
|
||||
import { publishedRuleAnalyticsColumns } from "../../../lib/server/publishedRulePersist";
|
||||
|
||||
/** One anonymous publish per IP per minute (in-memory limiter). */
|
||||
const ANONYMOUS_PUBLISH_IP_MIN_INTERVAL_MS = 60_000;
|
||||
@@ -113,6 +114,7 @@ export const POST = apiRoute(
|
||||
summary,
|
||||
document: document as Prisma.InputJsonValue,
|
||||
claimTokenHash,
|
||||
...publishedRuleAnalyticsColumns(document),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -160,6 +162,7 @@ export const POST = apiRoute(
|
||||
title,
|
||||
summary,
|
||||
document: document as Prisma.InputJsonValue,
|
||||
...publishedRuleAnalyticsColumns(document),
|
||||
},
|
||||
});
|
||||
await linkUploadsToRule({
|
||||
@@ -196,6 +199,7 @@ export const POST = apiRoute(
|
||||
title,
|
||||
summary,
|
||||
document: document as Prisma.InputJsonValue,
|
||||
...publishedRuleAnalyticsColumns(document),
|
||||
},
|
||||
});
|
||||
const toSend: { email: string; token: string }[] = [];
|
||||
|
||||
@@ -18,6 +18,7 @@ import Numeric2CircleIcon from "./numeric-2-circle.svg";
|
||||
import Numeric3CircleIcon from "./numeric-3-circle.svg";
|
||||
import NumberIcon from "./number.svg";
|
||||
import PictureAsPdfIcon from "./picture_as_pdf.svg";
|
||||
import PrintIcon from "./print.svg";
|
||||
import TagsIcon from "./tags.svg";
|
||||
import TextBlockIcon from "./text_block.svg";
|
||||
import WarningIcon from "./warning.svg";
|
||||
@@ -39,6 +40,7 @@ export const ICON_NAME_OPTIONS = [
|
||||
"numeric_3_circle",
|
||||
"number",
|
||||
"picture_as_pdf",
|
||||
"print",
|
||||
"tags",
|
||||
"text_block",
|
||||
"warning",
|
||||
@@ -68,6 +70,7 @@ const iconMap: Record<IconName, SvgComponent> = {
|
||||
numeric_3_circle: Numeric3CircleIcon,
|
||||
number: NumberIcon,
|
||||
picture_as_pdf: PictureAsPdfIcon,
|
||||
print: PrintIcon,
|
||||
tags: TagsIcon,
|
||||
text_block: TextBlockIcon,
|
||||
warning: WarningIcon,
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path
|
||||
d="M18 7H6V3H18V7ZM18 12.5C18.2833 12.5 18.5208 12.4042 18.7125 12.2125C18.9042 12.0208 19 11.7833 19 11.5C19 11.2167 18.9042 10.9792 18.7125 10.7875C18.5208 10.5958 18.2833 10.5 18 10.5C17.7167 10.5 17.4792 10.5958 17.2875 10.7875C17.0958 10.9792 17 11.2167 17 11.5C17 11.7833 17.0958 12.0208 17.2875 12.2125C17.4792 12.4042 17.7167 12.5 18 12.5ZM16 19V15H8V19H16ZM18 21H6V17H2V11C2 10.1667 2.29167 9.45833 2.875 8.875C3.45833 8.29167 4.16667 8 5 8H19C19.8333 8 20.5417 8.29167 21.125 8.875C21.7083 9.45833 22 10.1667 22 11V17H18V21Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 680 B |
@@ -88,18 +88,18 @@ const CreateFlowTopNavContainer = memo<CreateFlowTopNavProps>(
|
||||
leadingIcon: "picture_as_pdf",
|
||||
onClick: () => onSelectExportFormat("pdf"),
|
||||
},
|
||||
{
|
||||
id: "export-csv",
|
||||
label: tPopover("downloadCsv"),
|
||||
leadingIcon: "csv",
|
||||
onClick: () => onSelectExportFormat("csv"),
|
||||
},
|
||||
{
|
||||
id: "export-markdown",
|
||||
label: tPopover("downloadMarkdown"),
|
||||
leadingIcon: "markdown_copy",
|
||||
onClick: () => onSelectExportFormat("markdown"),
|
||||
},
|
||||
{
|
||||
id: "export-print",
|
||||
label: tPopover("print"),
|
||||
leadingIcon: "print",
|
||||
onClick: () => onSelectExportFormat("print"),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -233,8 +233,8 @@ const CreateFlowTopNavContainer = memo<CreateFlowTopNavProps>(
|
||||
actionMenuItems={actionMenuItems}
|
||||
exportPopoverMenuAriaLabel={tPopover("menuAriaLabel")}
|
||||
exportPopoverPdfLabel={tPopover("downloadPdf")}
|
||||
exportPopoverCsvLabel={tPopover("downloadCsv")}
|
||||
exportPopoverMarkdownLabel={tPopover("downloadMarkdown")}
|
||||
exportPopoverPrintLabel={tPopover("print")}
|
||||
moreOptionsAriaLabel={t("moreOptionsAriaLabel")}
|
||||
actionsMenuAriaLabel={t("actionsMenuAriaLabel")}
|
||||
shareLabel={t("share")}
|
||||
|
||||
@@ -55,7 +55,7 @@ export interface CreateFlowTopNavProps {
|
||||
/**
|
||||
* Callback when user picks an export format from the Export menu.
|
||||
*/
|
||||
onSelectExportFormat?: (_format: "pdf" | "csv" | "markdown") => void;
|
||||
onSelectExportFormat?: (_format: "pdf" | "markdown" | "print") => void;
|
||||
/**
|
||||
* Callback when Edit button is clicked
|
||||
*/
|
||||
@@ -106,8 +106,8 @@ export type CreateFlowTopNavViewProps = CreateFlowTopNavProps & {
|
||||
actionMenuItems: CreateFlowTopNavActionMenuItem[];
|
||||
exportPopoverMenuAriaLabel: string;
|
||||
exportPopoverPdfLabel: string;
|
||||
exportPopoverCsvLabel: string;
|
||||
exportPopoverMarkdownLabel: string;
|
||||
exportPopoverPrintLabel: string;
|
||||
moreOptionsAriaLabel: string;
|
||||
actionsMenuAriaLabel: string;
|
||||
shareLabel: string;
|
||||
|
||||
@@ -61,8 +61,8 @@ export function CreateFlowTopNavView({
|
||||
actionMenuItems,
|
||||
exportPopoverMenuAriaLabel,
|
||||
exportPopoverPdfLabel,
|
||||
exportPopoverCsvLabel,
|
||||
exportPopoverMarkdownLabel,
|
||||
exportPopoverPrintLabel,
|
||||
moreOptionsAriaLabel,
|
||||
actionsMenuAriaLabel,
|
||||
shareLabel,
|
||||
@@ -145,19 +145,19 @@ export function CreateFlowTopNavView({
|
||||
/>
|
||||
<ListItem
|
||||
showDivider
|
||||
leadingIcon="csv"
|
||||
label={exportPopoverCsvLabel}
|
||||
leadingIcon="markdown_copy"
|
||||
label={exportPopoverMarkdownLabel}
|
||||
onClick={() => {
|
||||
onSelectExportFormat("csv");
|
||||
onSelectExportFormat("markdown");
|
||||
setExportMenuOpen(false);
|
||||
}}
|
||||
/>
|
||||
<ListItem
|
||||
showDivider={false}
|
||||
leadingIcon="markdown_copy"
|
||||
label={exportPopoverMarkdownLabel}
|
||||
leadingIcon="print"
|
||||
label={exportPopoverPrintLabel}
|
||||
onClick={() => {
|
||||
onSelectExportFormat("markdown");
|
||||
onSelectExportFormat("print");
|
||||
setExportMenuOpen(false);
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -210,6 +210,9 @@ const Footer = memo(({ siteOrigin = PRODUCTION_SITE_ORIGIN }: { siteOrigin?: str
|
||||
lg:gap-10
|
||||
lg:text-small-paragraph"
|
||||
>
|
||||
<Link href={t("takeawayHref")} className={legalLinkClass}>
|
||||
{t("takeaway")}
|
||||
</Link>
|
||||
<Link href={t("legal.privacyPolicyHref")} className={legalLinkClass}>
|
||||
{t("legal.privacyPolicy")}
|
||||
</Link>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import ContentLockup from "../../type/ContentLockup";
|
||||
import Button from "../../buttons/Button";
|
||||
import { ASK_ORGANIZER_HASH } from "../../../../lib/sharePaths";
|
||||
import type { AskOrganizerViewProps } from "./AskOrganizer.types";
|
||||
|
||||
function AskOrganizerView({
|
||||
@@ -28,6 +29,7 @@ function AskOrganizerView({
|
||||
|
||||
return (
|
||||
<section
|
||||
id={ASK_ORGANIZER_HASH}
|
||||
className={`${sectionPadding} ${className}`}
|
||||
aria-labelledby={labelledBy}
|
||||
aria-label={labelledBy ? undefined : ctaAriaLabel}
|
||||
|
||||
+23
-6
@@ -2,6 +2,7 @@ import { Inter, Bricolage_Grotesque } from "next/font/google";
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import type { ReactNode } from "react";
|
||||
import { headers } from "next/headers";
|
||||
import Script from "next/script";
|
||||
import messages from "../messages/en/index";
|
||||
import { ASSETS, getAssetPath } from "../lib/assetUtils";
|
||||
import {
|
||||
@@ -9,6 +10,7 @@ import {
|
||||
originFromHost,
|
||||
resolveRequestHost,
|
||||
} from "../lib/siteMetadata";
|
||||
import { umamiTracker } from "../lib/umami";
|
||||
import "./globals.css";
|
||||
|
||||
// Session chrome (`ConditionalNavigation`) lives in `(marketing)`, `(app)`, and
|
||||
@@ -124,7 +126,7 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
}
|
||||
|
||||
export default function RootLayout({ children }: { children: ReactNode }) {
|
||||
// Load messages for the default locale (single locale setup)
|
||||
const umami = umamiTracker();
|
||||
|
||||
return (
|
||||
<html lang="en" className="font-sans">
|
||||
@@ -148,11 +150,26 @@ export default function RootLayout({ children }: { children: ReactNode }) {
|
||||
type="image/png"
|
||||
/>
|
||||
</head>
|
||||
<body className={`${inter.variable} ${bricolageGrotesque.variable}`}>
|
||||
<div className="mx-auto flex min-h-screen w-full max-w-[1920px] flex-col">
|
||||
{children}
|
||||
</div>
|
||||
</body>
|
||||
{umami ? (
|
||||
<body className={`${inter.variable} ${bricolageGrotesque.variable}`}>
|
||||
<Script
|
||||
src={umami.src}
|
||||
strategy="afterInteractive"
|
||||
data-website-id={umami.websiteId}
|
||||
data-do-not-track="true"
|
||||
data-exclude-search="true"
|
||||
/>
|
||||
<div className="mx-auto flex min-h-screen w-full max-w-[1920px] flex-col">
|
||||
{children}
|
||||
</div>
|
||||
</body>
|
||||
) : (
|
||||
<body className={`${inter.variable} ${bricolageGrotesque.variable}`}>
|
||||
<div className="mx-auto flex min-h-screen w-full max-w-[1920px] flex-col">
|
||||
{children}
|
||||
</div>
|
||||
</body>
|
||||
)}
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -85,6 +85,10 @@ per-app in the manifest and provisioned at install time.
|
||||
(`start.sh` chowns `/app/data` for the `node` user). When unset, upload
|
||||
routes return `server_misconfigured`. See [CONTRIBUTING.md](../../CONTRIBUTING.md)
|
||||
API table.
|
||||
- `NEXT_PUBLIC_UMAMI_SRC` / `NEXT_PUBLIC_UMAMI_WEBSITE_ID` — optional
|
||||
Umami tracker. Unset until the companion Umami app is installed.
|
||||
Cookie-free mode is set on Umami, not here. See
|
||||
[ops-runbook.md](ops-runbook.md) §9.3.
|
||||
|
||||
## 4. Platform settings
|
||||
|
||||
|
||||
@@ -248,6 +248,9 @@ persist across image updates unless changed:
|
||||
| `UPLOAD_ROOT` | `/app/data/uploads` on Cloudron — required for file uploads. |
|
||||
| `OPS_PRUNE_TOKEN` | Bearer token for `POST /api/ops/prune`. Unset hides the route. Optional; the daily scheduler runs the prune inside the container without it. |
|
||||
| `WORKSHOP_INQUIRY_PURGE_TOKEN` | Bearer token for `POST /api/workshop-inquiries/purge`. Unset hides that route. |
|
||||
| `RULE_ADMIN_EMAILS` | Named admins. Comma-separated. Can open private Rules and `/rule-counts`. |
|
||||
| `NEXT_PUBLIC_UMAMI_SRC` | Umami script URL. Unset: no tracker. Pair with `NEXT_PUBLIC_UMAMI_WEBSITE_ID`. |
|
||||
| `NEXT_PUBLIC_UMAMI_WEBSITE_ID` | Umami website id for this hostname. |
|
||||
|
||||
Full detail: [`ops-backend-deploy.md` §3](ops-backend-deploy.md#3-environment-variables).
|
||||
|
||||
@@ -320,6 +323,27 @@ node --env-file=.env --import tsx scripts/prune-sessions.ts
|
||||
If the scheduler addon is missing after an image update, add the same
|
||||
command under the app **Cron** tab (`20 7 * * *`, UTC).
|
||||
|
||||
The same scheduler addon also runs **`follow-up-mail`** at **15 minutes
|
||||
past every hour**. It sends one print follow-up to the address that holds
|
||||
the pen, 48 hours after the Rule was finished, with PDF and RULE.md
|
||||
links. Guest Rules with no account are skipped until claimed, and only
|
||||
Rules finished in the last seven days are considered so a first run after
|
||||
deploy does not mail every historic Rule.
|
||||
|
||||
Manual run:
|
||||
|
||||
```bash
|
||||
cloudron exec --app staging.communityrule.info -- \
|
||||
node /app/follow-up-mail.bundle.cjs
|
||||
|
||||
# local
|
||||
node --env-file=.env --import tsx scripts/send-rule-follow-up.ts
|
||||
```
|
||||
|
||||
Named admins can read finished-Rule counts (folded under five) at
|
||||
`/rule-counts`, or `GET /api/ops/rule-counts` with the same session or
|
||||
`Authorization: Bearer $OPS_PRUNE_TOKEN`.
|
||||
|
||||
### 9.2 Logs
|
||||
|
||||
App logs (stdout) and Cloudron request logs are deleted after **14
|
||||
@@ -336,7 +360,28 @@ host for longer than 14 days.
|
||||
|
||||
Sign-in mail failures log a request id, not the email address.
|
||||
|
||||
### 9.3 Backups
|
||||
### 9.3 Umami (site counts)
|
||||
|
||||
Umami is a **second Cloudron app**, not this image. Install the Umami
|
||||
Cloudron package (or Docker) on a hostname such as
|
||||
`analytics.communityrule.info`. Create a website for this app’s public
|
||||
origin. In Umami → website settings, **turn off cookies** (tracker
|
||||
collects aggregate page views only).
|
||||
|
||||
Then on this CommunityRule app:
|
||||
|
||||
```bash
|
||||
cloudron env set --app staging.communityrule.info \
|
||||
NEXT_PUBLIC_UMAMI_SRC=https://analytics.communityrule.info/script.js
|
||||
cloudron env set --app staging.communityrule.info \
|
||||
NEXT_PUBLIC_UMAMI_WEBSITE_ID=<website-id>
|
||||
```
|
||||
|
||||
Unset both to ship no tracker. The snippet sets `data-do-not-track` and
|
||||
`data-exclude-search` so query strings (share and export tokens) are not
|
||||
sent to Umami.
|
||||
|
||||
### 9.4 Backups
|
||||
|
||||
Set the Cloudron backup site to **`30 daily`** (*Backups* → *Schedule &
|
||||
Retention*). Confirm this on staging and production. Cloudron also keeps
|
||||
|
||||
@@ -37,8 +37,10 @@ until the 12-month delete.
|
||||
## Analytics
|
||||
|
||||
**Umami**, self-hosted beside the app, with no cookies and aggregate
|
||||
counts only. Name it in the policy. The counter itself ships with the
|
||||
counts-by-group work, not this pass.
|
||||
counts only. Name it in the policy. The app loads the tracker only when
|
||||
`NEXT_PUBLIC_UMAMI_SRC` and `NEXT_PUBLIC_UMAMI_WEBSITE_ID` are set.
|
||||
Cookie-free mode is configured on the Umami app, not in this repo.
|
||||
See [`docs/guides/ops-runbook.md`](guides/ops-runbook.md) §9.3.
|
||||
|
||||
## Product copy the build already matches
|
||||
|
||||
|
||||
+11
-3
@@ -213,7 +213,7 @@ export async function publishRule(input: {
|
||||
document: Record<string, unknown>;
|
||||
stakeholderEmails?: string[];
|
||||
}): Promise<
|
||||
| { ok: true; id: string; title: string }
|
||||
| { ok: true; id: string; title: string; createdAt?: string }
|
||||
| { ok: false; error: string; status?: number }
|
||||
> {
|
||||
try {
|
||||
@@ -232,7 +232,7 @@ export async function publishRule(input: {
|
||||
});
|
||||
const data = (await safeParseJsonResponse(res)) as {
|
||||
error?: string | { message?: string };
|
||||
rule?: { id: string; title: string };
|
||||
rule?: { id: string; title: string; createdAt?: string };
|
||||
} | null;
|
||||
const rule = data && typeof data === "object" ? data.rule : undefined;
|
||||
if (!res.ok || !rule) {
|
||||
@@ -248,7 +248,14 @@ export async function publishRule(input: {
|
||||
status: res.status,
|
||||
};
|
||||
}
|
||||
return { ok: true, id: rule.id, title: rule.title };
|
||||
return {
|
||||
ok: true,
|
||||
id: rule.id,
|
||||
title: rule.title,
|
||||
...(typeof rule.createdAt === "string" && rule.createdAt.length > 0
|
||||
? { createdAt: rule.createdAt }
|
||||
: {}),
|
||||
};
|
||||
} catch {
|
||||
return {
|
||||
ok: false as const,
|
||||
@@ -344,6 +351,7 @@ export type PublishedRuleDetailForClient = {
|
||||
title: string;
|
||||
summary: string | null;
|
||||
document: unknown;
|
||||
createdAt?: string;
|
||||
};
|
||||
|
||||
export type FetchPublishedRuleDetailResult = {
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
replaceMethodSectionsWithMethodSelections,
|
||||
withoutUnpublishedDecisionConsensus,
|
||||
} from "./ruleSectionsFromMethodSelections";
|
||||
import { publishedRuleAnalyticsFromState } from "./publishedRuleAnalytics";
|
||||
import { LAUNCH_SUPERMAJORITY_SHARE } from "./sharedTermsSection";
|
||||
import { templateCategoryToGroupKey } from "./templateReviewMapping";
|
||||
|
||||
@@ -191,6 +192,14 @@ export function buildPublishPayload(
|
||||
document.customMethodCardFieldBlocksById = fieldBlocks;
|
||||
}
|
||||
|
||||
const analytics = publishedRuleAnalyticsFromState(state);
|
||||
if (analytics.communityLocation) {
|
||||
document.communityLocation = analytics.communityLocation;
|
||||
}
|
||||
if (analytics.orgType) {
|
||||
document.orgType = analytics.orgType;
|
||||
}
|
||||
|
||||
if (summary !== undefined) {
|
||||
return { ok: true, title, summary, document };
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ const IDENTITY_KEYS = [
|
||||
"communityAvatarFileName",
|
||||
"communityContext",
|
||||
"communityLocation",
|
||||
"orgType",
|
||||
"communitySaveEmail",
|
||||
"title",
|
||||
] as const;
|
||||
|
||||
@@ -12,11 +12,24 @@ export type StoredLastPublishedRule = {
|
||||
title: string;
|
||||
summary?: string | null;
|
||||
document: Record<string, unknown>;
|
||||
/** ISO date the Rule was finished, for RULE.md front matter. */
|
||||
finishedAt?: string;
|
||||
/** Present after Make a copy; drives the copy-ready banner and lavender surface. */
|
||||
copiedFromTitle?: string;
|
||||
copiedNameHit?: CopiedNameHit | null;
|
||||
};
|
||||
|
||||
export function finishedAtIso(value: unknown): string | undefined {
|
||||
if (typeof value === "string" && value.trim().length > 0) {
|
||||
const date = new Date(value);
|
||||
if (!Number.isNaN(date.getTime())) return date.toISOString();
|
||||
}
|
||||
if (value instanceof Date && !Number.isNaN(value.getTime())) {
|
||||
return value.toISOString();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function writeLastPublishedRule(data: StoredLastPublishedRule): void {
|
||||
if (typeof sessionStorage === "undefined") return;
|
||||
sessionStorage.setItem(CREATE_FLOW_LAST_PUBLISHED_KEY, JSON.stringify(data));
|
||||
@@ -44,6 +57,10 @@ export function readLastPublishedRule(): StoredLastPublishedRule | null {
|
||||
} else {
|
||||
summary = undefined;
|
||||
}
|
||||
let finishedAt: string | undefined;
|
||||
if (typeof o.finishedAt === "string" && o.finishedAt.trim().length > 0) {
|
||||
finishedAt = o.finishedAt;
|
||||
}
|
||||
let copiedFromTitle: string | undefined;
|
||||
if (
|
||||
typeof o.copiedFromTitle === "string" &&
|
||||
@@ -69,6 +86,7 @@ export function readLastPublishedRule(): StoredLastPublishedRule | null {
|
||||
title: o.title,
|
||||
summary,
|
||||
document: doc as Record<string, unknown>,
|
||||
...(finishedAt ? { finishedAt } : {}),
|
||||
...(copiedFromTitle ? { copiedFromTitle } : {}),
|
||||
...(copiedNameHit ? { copiedNameHit } : {}),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { CreateFlowState } from "../../app/(app)/create/types";
|
||||
import { KINDS, type Kind } from "./deckTypes";
|
||||
import { groupAnswersFromCreateFlowState } from "./groupAnswers";
|
||||
|
||||
const LOCATION_MAX = 200;
|
||||
|
||||
function isKind(value: string): value is Kind {
|
||||
return (KINDS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
function trimmedLocation(raw: unknown): string | undefined {
|
||||
if (typeof raw !== "string") return undefined;
|
||||
const trimmed = raw.trim().replace(/\s+/g, " ");
|
||||
if (trimmed.length === 0) return undefined;
|
||||
return trimmed.slice(0, LOCATION_MAX);
|
||||
}
|
||||
|
||||
/** Place and main group type stored on a finished Rule for launch counts. */
|
||||
export function publishedRuleAnalyticsFromState(state: CreateFlowState): {
|
||||
communityLocation?: string;
|
||||
orgType?: Kind;
|
||||
} {
|
||||
const communityLocation = trimmedLocation(state.communityLocation);
|
||||
const orgType = groupAnswersFromCreateFlowState(state).mainKind ?? undefined;
|
||||
return {
|
||||
...(communityLocation ? { communityLocation } : {}),
|
||||
...(orgType ? { orgType } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function publishedRuleAnalyticsFromDocument(document: unknown): {
|
||||
communityLocation: string | null;
|
||||
orgType: string | null;
|
||||
} {
|
||||
if (!document || typeof document !== "object" || Array.isArray(document)) {
|
||||
return { communityLocation: null, orgType: null };
|
||||
}
|
||||
const row = document as Record<string, unknown>;
|
||||
const communityLocation = trimmedLocation(row.communityLocation) ?? null;
|
||||
const orgTypeRaw =
|
||||
typeof row.orgType === "string" ? row.orgType.trim() : "";
|
||||
const orgType = isKind(orgTypeRaw) ? orgTypeRaw : null;
|
||||
return { communityLocation, orgType };
|
||||
}
|
||||
+200
-357
@@ -1,12 +1,15 @@
|
||||
import { jsPDF } from "jspdf";
|
||||
|
||||
import type {
|
||||
CommunityRuleEntry,
|
||||
CommunityRuleLabeledBlock,
|
||||
CommunityRuleSection,
|
||||
} from "../../app/components/type/CommunityRule/CommunityRule.types";
|
||||
import exportCopy from "../../messages/en/create/export.json";
|
||||
import type { StoredLastPublishedRule } from "./lastPublishedRule";
|
||||
import { parsePublishedDocumentForCommunityRuleDisplay } from "./publishedDocumentToDisplaySections";
|
||||
import {
|
||||
RULE_MD_FILENAME,
|
||||
buildRuleExportDocument,
|
||||
exportPdfFilename,
|
||||
yamlQuote,
|
||||
type RuleExportDocument,
|
||||
type RuleExportLine,
|
||||
type RuleExportSource,
|
||||
} from "./ruleExportModel";
|
||||
import { ruleExportDocumentToPdfBytes } from "./ruleExportPdf";
|
||||
|
||||
export {
|
||||
buildPublicRuleUrl,
|
||||
@@ -14,6 +17,159 @@ export {
|
||||
formatShareUrlDisplay,
|
||||
shareCopyUrl,
|
||||
} from "../sharePaths";
|
||||
export {
|
||||
RULE_MD_FILENAME,
|
||||
exportPdfFilename,
|
||||
type RuleExportSource,
|
||||
} from "./ruleExportModel";
|
||||
|
||||
export type RuleExportFormat = "pdf" | "markdown" | "print";
|
||||
|
||||
function lineMarkdown(line: RuleExportLine): string {
|
||||
if (line.lead) return `**${line.lead}** ${line.body}`;
|
||||
return line.body;
|
||||
}
|
||||
|
||||
export function ruleExportDocumentToMarkdown(doc: RuleExportDocument): string {
|
||||
const front: string[] = ["---", `title: ${yamlQuote(doc.title)}`];
|
||||
if (doc.summary.length > 0) {
|
||||
front.push(`summary: ${yamlQuote(doc.summary)}`);
|
||||
}
|
||||
if (doc.finishedOn) {
|
||||
front.push(`finished: ${doc.finishedOn}`);
|
||||
}
|
||||
front.push("---", "", `# ${doc.title}`, "");
|
||||
if (doc.summary.length > 0) {
|
||||
front.push(doc.summary, "");
|
||||
}
|
||||
for (const section of doc.sections) {
|
||||
front.push(`## ${section.title}`, "");
|
||||
for (const card of section.cards) {
|
||||
front.push(`### ${card.title}`, "");
|
||||
for (const line of card.lines) {
|
||||
front.push(lineMarkdown(line), "");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (doc.terms.length > 0) {
|
||||
front.push(`## ${exportCopy.sharedTermsHeading}`, "");
|
||||
for (const term of doc.terms) {
|
||||
front.push(`**${term.term}**`, `: ${term.meaning}`, "");
|
||||
}
|
||||
}
|
||||
front.push(`${doc.takeaway}: ${doc.takeawayUrl}`, "");
|
||||
return `${front.join("\n").trimEnd()}\n`;
|
||||
}
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function lineHtml(line: RuleExportLine): string {
|
||||
if (line.lead) {
|
||||
return `<p><span class="lead">${escapeHtml(line.lead)}</span> ${escapeHtml(line.body)}</p>`;
|
||||
}
|
||||
return `<p>${escapeHtml(line.body)}</p>`;
|
||||
}
|
||||
|
||||
export function ruleExportDocumentToPrintHtml(doc: RuleExportDocument): string {
|
||||
const photo = doc.photoUrl
|
||||
? `<img class="photo" src="${escapeHtml(doc.photoUrl)}" alt="" />`
|
||||
: `<div class="photo initials">${escapeHtml(doc.initials)}</div>`;
|
||||
const summary =
|
||||
doc.summary.length > 0
|
||||
? `<p class="summary">${escapeHtml(doc.summary)}</p>`
|
||||
: "";
|
||||
const sections = doc.sections
|
||||
.map((section) => {
|
||||
const cards = section.cards
|
||||
.map(
|
||||
(card) =>
|
||||
`<article class="card"><h3>${escapeHtml(card.title)}</h3>${card.lines
|
||||
.map(lineHtml)
|
||||
.join("")}</article>`,
|
||||
)
|
||||
.join("");
|
||||
return `<section><h2>${escapeHtml(section.title)}</h2>${cards}</section>`;
|
||||
})
|
||||
.join("");
|
||||
const terms = doc.terms
|
||||
.map(
|
||||
(term) =>
|
||||
`<p class="term"><i>${escapeHtml(term.term)}</i> ${escapeHtml(term.meaning)}</p>`,
|
||||
)
|
||||
.join("");
|
||||
const termsBlock =
|
||||
doc.terms.length > 0
|
||||
? `<section class="terms"><h2>${escapeHtml(exportCopy.sharedTermsHeading)}</h2><div class="term-columns">${terms}</div></section>`
|
||||
: "";
|
||||
const styles = `
|
||||
@page { size: letter; margin: 12.7mm 16.9mm 12mm; }
|
||||
html, body { margin: 0; padding: 0; background: #fff; color: #141414; }
|
||||
body { font-family: Inter, system-ui, sans-serif; font-size: 12pt; line-height: 1.35; }
|
||||
h1, h2, h3 { font-family: "Bricolage Grotesque", Inter, system-ui, sans-serif; font-weight: 700; margin: 0; }
|
||||
.header { display: flex; gap: 24px; align-items: center; padding-bottom: 12px; }
|
||||
.photo { width: 72px; height: 72px; border-radius: 9999px; object-fit: cover; flex-shrink: 0; }
|
||||
.photo.initials { border: 2px solid #141414; display: flex; align-items: center; justify-content: center; font-size: 24px; font-weight: 500; }
|
||||
.group { min-width: 0; flex: 1; }
|
||||
h1 { font-size: 32px; line-height: 40px; }
|
||||
.summary { font-size: 16px; line-height: 24px; margin: 8px 0 0; font-weight: 400; }
|
||||
section { border-top: 1px solid #141414; padding-top: 16px; margin-top: 20px; }
|
||||
h2 { font-size: 24px; line-height: 32px; margin-bottom: 12px; }
|
||||
.card { margin: 0 0 12px; }
|
||||
h3 { font-size: 16px; line-height: 22px; margin-bottom: 8px; }
|
||||
p { margin: 0 0 8px; font-size: 14px; line-height: 20px; }
|
||||
.lead { font-weight: 500; }
|
||||
.terms h2 { margin-bottom: 16px; }
|
||||
.term-columns { column-count: 2; column-gap: 32px; }
|
||||
.term { font-size: 12px; line-height: 16px; break-inside: avoid; margin: 0 0 12px; }
|
||||
.term i { font-style: italic; }
|
||||
.takeaway { margin-top: 24px; font-size: 12px; }
|
||||
.takeaway a { color: #141414; }
|
||||
.footer { display: flex; justify-content: space-between; color: #464646; font-size: 12px; margin-top: 24px; }
|
||||
@media print {
|
||||
.footer { position: running(pageFooter); }
|
||||
@page { @bottom-center { content: none; } }
|
||||
}
|
||||
`.replace(/\n/g, "");
|
||||
|
||||
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><title>${escapeHtml(doc.title)}</title><style>${styles}</style></head><body><header class="header">${photo}<div class="group"><h1>${escapeHtml(doc.title)}</h1>${summary}</div></header>${sections}${termsBlock}<p class="takeaway">${escapeHtml(doc.takeaway)} <a href="${escapeHtml(doc.takeawayUrl)}">${escapeHtml(doc.takeawayUrl)}</a></p><div class="footer"><span>${escapeHtml(doc.credit)}</span></div></body></html>`;
|
||||
}
|
||||
|
||||
export function exportStoredRuleAsMarkdown(
|
||||
rule: RuleExportSource,
|
||||
origin: string,
|
||||
): string {
|
||||
return ruleExportDocumentToMarkdown(buildRuleExportDocument(rule, origin));
|
||||
}
|
||||
|
||||
export function buildPrintableRuleHtmlDocument(
|
||||
rule: RuleExportSource,
|
||||
origin: string,
|
||||
): string {
|
||||
return ruleExportDocumentToPrintHtml(buildRuleExportDocument(rule, origin));
|
||||
}
|
||||
|
||||
export function buildStoredRulePdfBytes(
|
||||
rule: RuleExportSource,
|
||||
origin: string,
|
||||
): Uint8Array {
|
||||
return ruleExportDocumentToPdfBytes(buildRuleExportDocument(rule, origin));
|
||||
}
|
||||
|
||||
export function buildStoredRulePdfBlob(
|
||||
rule: RuleExportSource,
|
||||
origin: string,
|
||||
): Blob {
|
||||
const bytes = buildStoredRulePdfBytes(rule, origin);
|
||||
const copy = new Uint8Array(bytes.byteLength);
|
||||
copy.set(bytes);
|
||||
return new Blob([copy.buffer], { type: "application/pdf" });
|
||||
}
|
||||
|
||||
/** Safe filename fragment from rule title, with stable fallback. */
|
||||
export function exportFilenameBase(rule: StoredLastPublishedRule): string {
|
||||
@@ -26,346 +182,8 @@ export function exportFilenameBase(rule: StoredLastPublishedRule): string {
|
||||
return fromTitle.length > 0 ? fromTitle : `rule-${rule.id.slice(0, 8)}`;
|
||||
}
|
||||
|
||||
function labeledBlockMedia(b: CommunityRuleLabeledBlock): {
|
||||
img?: string;
|
||||
file?: string;
|
||||
bodyTrim: string;
|
||||
} {
|
||||
const imgRaw = b.imageUrl?.trim();
|
||||
const fileRaw = b.fileUrl?.trim();
|
||||
return {
|
||||
img: imgRaw && imgRaw.length > 0 ? imgRaw : undefined,
|
||||
file: fileRaw && fileRaw.length > 0 ? fileRaw : undefined,
|
||||
bodyTrim: b.body.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function entryToMarkdown(entry: CommunityRuleEntry): string {
|
||||
const lines: string[] = [`### ${entry.title}`, ""];
|
||||
if (entry.blocks && entry.blocks.length > 0) {
|
||||
for (const b of entry.blocks) {
|
||||
lines.push(`#### ${b.label}`, "");
|
||||
const { img, file, bodyTrim } = labeledBlockMedia(b);
|
||||
if (img) {
|
||||
lines.push(``, "");
|
||||
} else if (file) {
|
||||
lines.push(`[${bodyTrim || "file"}](${file})`, "");
|
||||
} else {
|
||||
lines.push(b.body, "");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const body = (entry.body ?? "").trim();
|
||||
if (body.length > 0) {
|
||||
const paras = body.split(/\n\s*\n/);
|
||||
for (const p of paras) {
|
||||
const t = p.trim();
|
||||
if (t.length > 0) lines.push(t, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines.join("\n").trimEnd();
|
||||
}
|
||||
|
||||
export function sectionsToMarkdown(
|
||||
title: string,
|
||||
summary: string | null | undefined,
|
||||
sections: CommunityRuleSection[],
|
||||
): string {
|
||||
const parts: string[] = [`# ${title}`, ""];
|
||||
const sum = typeof summary === "string" ? summary.trim() : "";
|
||||
if (sum.length > 0) {
|
||||
parts.push(sum, "");
|
||||
}
|
||||
for (const sec of sections) {
|
||||
parts.push(`## ${sec.categoryName}`, "");
|
||||
for (const ent of sec.entries) {
|
||||
parts.push(entryToMarkdown(ent), "");
|
||||
}
|
||||
}
|
||||
return `${parts.join("\n").trimEnd()}\n`;
|
||||
}
|
||||
|
||||
function escapeCsvCell(value: string): string {
|
||||
if (/[",\r\n]/.test(value)) {
|
||||
return `"${value.replace(/"/g, '""')}"`;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Tabular snapshot of parsed rule content (RFC 4180-style; UTF-8 with BOM when downloaded). */
|
||||
export function sectionsToCsv(
|
||||
title: string,
|
||||
summary: string | null | undefined,
|
||||
sections: CommunityRuleSection[],
|
||||
): string {
|
||||
const rows: string[][] = [
|
||||
["Section", "Entry", "Block label", "Content"],
|
||||
["", "Title", "", title],
|
||||
];
|
||||
const sum = typeof summary === "string" ? summary.trim() : "";
|
||||
if (sum.length > 0) {
|
||||
rows.push(["", "Summary", "", sum]);
|
||||
}
|
||||
for (const sec of sections) {
|
||||
for (const ent of sec.entries) {
|
||||
if (ent.blocks && ent.blocks.length > 0) {
|
||||
for (const b of ent.blocks) {
|
||||
const { img, file, bodyTrim } = labeledBlockMedia(b);
|
||||
const content = img
|
||||
? bodyTrim.length > 0
|
||||
? `${bodyTrim}\n${img}`
|
||||
: img
|
||||
: file
|
||||
? bodyTrim.length > 0
|
||||
? `${bodyTrim}\n${file}`
|
||||
: file
|
||||
: b.body;
|
||||
rows.push([sec.categoryName, ent.title, b.label, content]);
|
||||
}
|
||||
} else {
|
||||
rows.push([sec.categoryName, ent.title, "", ent.body ?? ""]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return `${rows.map((r) => r.map(escapeCsvCell).join(",")).join("\n")}\n`;
|
||||
}
|
||||
|
||||
export function exportStoredRuleAsMarkdown(rule: StoredLastPublishedRule): string {
|
||||
const sections = parsePublishedDocumentForCommunityRuleDisplay(rule.document);
|
||||
if (sections.length === 0) {
|
||||
throw new Error("exportEmptyDocument");
|
||||
}
|
||||
return sectionsToMarkdown(rule.title, rule.summary, sections);
|
||||
}
|
||||
|
||||
export function exportStoredRuleAsCsv(rule: StoredLastPublishedRule): string {
|
||||
const sections = parsePublishedDocumentForCommunityRuleDisplay(rule.document);
|
||||
if (sections.length === 0) {
|
||||
throw new Error("exportEmptyDocument");
|
||||
}
|
||||
return `\uFEFF${sectionsToCsv(rule.title, rule.summary, sections)}`;
|
||||
}
|
||||
|
||||
function escapeHtml(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function paragraphsHtml(text: string): string {
|
||||
const paras = text
|
||||
.trim()
|
||||
.split(/\n\s*\n/)
|
||||
.filter((p) => p.trim().length > 0);
|
||||
if (paras.length === 0) return "";
|
||||
return paras
|
||||
.map((p) => `<p>${escapeHtml(p.trim()).replace(/\n/g, "<br />")}</p>`)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function entryToPrintHtml(entry: CommunityRuleEntry): string {
|
||||
let inner = "";
|
||||
if (entry.blocks && entry.blocks.length > 0) {
|
||||
for (const b of entry.blocks) {
|
||||
inner += `<h4 class="block-label">${escapeHtml(b.label)}</h4>`;
|
||||
const { img, file, bodyTrim } = labeledBlockMedia(b);
|
||||
if (img) {
|
||||
inner += `<p><img src="${escapeHtml(img)}" alt="${escapeHtml(bodyTrim || b.label)}" /></p>`;
|
||||
if (bodyTrim.length > 0) {
|
||||
inner += paragraphsHtml(b.body);
|
||||
}
|
||||
} else if (file) {
|
||||
inner += `<p><a href="${escapeHtml(file)}">${escapeHtml(bodyTrim || file)}</a></p>`;
|
||||
} else {
|
||||
inner += paragraphsHtml(b.body);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
inner += paragraphsHtml(entry.body ?? "");
|
||||
}
|
||||
return `<article class="entry"><h3>${escapeHtml(entry.title)}</h3>${inner}</article>`;
|
||||
}
|
||||
|
||||
/** Full HTML document for static preview or tests; PDF export uses {@link sectionsToPdfBlob}. */
|
||||
export function buildPrintableRuleHtmlDocument(
|
||||
title: string,
|
||||
summary: string | null | undefined,
|
||||
sections: CommunityRuleSection[],
|
||||
): string {
|
||||
const sum = typeof summary === "string" ? summary.trim() : "";
|
||||
const summaryBlock =
|
||||
sum.length > 0 ? `<div class="summary">${paragraphsHtml(sum)}</div>` : "";
|
||||
const body = sections
|
||||
.map(
|
||||
(sec) =>
|
||||
`<section><h2>${escapeHtml(sec.categoryName)}</h2>${sec.entries.map(entryToPrintHtml).join("\n")}</section>`,
|
||||
)
|
||||
.join("\n");
|
||||
const styles = `body{font-family:system-ui,sans-serif;line-height:1.5;margin:2rem auto;max-width:48rem;padding:0 1rem;color:#111;background:#fff}h1{font-size:1.75rem;margin-bottom:.5rem}h2{font-size:1.25rem;margin-top:1.5rem;margin-bottom:.75rem;border-bottom:1px solid #ccc}h3{font-size:1.05rem;margin-top:1rem}h4.block-label{font-size:.95rem;font-weight:600;margin-top:.75rem;margin-bottom:.25rem}p{margin:0 0 .75rem}.summary{color:#333;margin-bottom:1.25rem}@media print{body{margin:0;max-width:none}h2,h3{break-after:avoid}}`;
|
||||
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><title>${escapeHtml(title)}</title><style>${styles}</style></head><body><h1>${escapeHtml(title)}</h1>${summaryBlock}${body}</body></html>`;
|
||||
}
|
||||
|
||||
function splitDisplayParagraphs(text: string): string[] {
|
||||
return text
|
||||
.trim()
|
||||
.split(/\n\s*\n/)
|
||||
.filter((p) => p.trim().length > 0)
|
||||
.map((p) => p.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* Same section structure as {@link buildPrintableRuleHtmlDocument}; renders a
|
||||
* simple multi-page PDF (Helvetica, headings + wrapped body text).
|
||||
*/
|
||||
export function sectionsToPdfBlob(
|
||||
title: string,
|
||||
summary: string | null | undefined,
|
||||
sections: CommunityRuleSection[],
|
||||
): Blob {
|
||||
const doc = new jsPDF({ unit: "mm", format: "a4" });
|
||||
const margin = 20;
|
||||
const pageW = doc.internal.pageSize.getWidth();
|
||||
const pageH = doc.internal.pageSize.getHeight();
|
||||
const maxW = pageW - 2 * margin;
|
||||
let y = margin;
|
||||
|
||||
function ensureSpace(h: number): void {
|
||||
if (y + h > pageH - margin) {
|
||||
doc.addPage();
|
||||
y = margin;
|
||||
}
|
||||
}
|
||||
|
||||
function writeBlockBodyParagraphs(body: string): void {
|
||||
for (const p of splitDisplayParagraphs(body)) {
|
||||
doc.setFont("helvetica", "normal");
|
||||
doc.setFontSize(11);
|
||||
const lines = doc.splitTextToSize(p, maxW);
|
||||
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: maxW });
|
||||
ensureSpace(dim.h + 1);
|
||||
doc.text(lines, margin, y);
|
||||
y += dim.h + 2;
|
||||
}
|
||||
}
|
||||
|
||||
/** Plain URL line(s); italic for images so captions vs URL read distinctly in print. */
|
||||
function writeMediaUrlLines(url: string, fontStyle: "normal" | "italic"): void {
|
||||
doc.setFont("helvetica", fontStyle);
|
||||
doc.setFontSize(10);
|
||||
const urlLines = doc.splitTextToSize(url, maxW);
|
||||
const urlDim = doc.getTextDimensions(urlLines.join("\n"), { maxWidth: maxW });
|
||||
ensureSpace(urlDim.h + 1);
|
||||
doc.text(urlLines, margin, y);
|
||||
y += urlDim.h + 2;
|
||||
}
|
||||
|
||||
doc.setFont("helvetica", "bold");
|
||||
doc.setFontSize(16);
|
||||
{
|
||||
const lines = doc.splitTextToSize(title, maxW);
|
||||
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: maxW });
|
||||
ensureSpace(dim.h + 4);
|
||||
doc.text(lines, margin, y);
|
||||
y += dim.h + 6;
|
||||
}
|
||||
|
||||
const sum = typeof summary === "string" ? summary.trim() : "";
|
||||
if (sum.length > 0) {
|
||||
for (const p of splitDisplayParagraphs(sum)) {
|
||||
doc.setFont("helvetica", "normal");
|
||||
doc.setFontSize(11);
|
||||
const lines = doc.splitTextToSize(p, maxW);
|
||||
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: maxW });
|
||||
ensureSpace(dim.h + 2);
|
||||
doc.text(lines, margin, y);
|
||||
y += dim.h + 3;
|
||||
}
|
||||
y += 2;
|
||||
}
|
||||
|
||||
for (const sec of sections) {
|
||||
doc.setFont("helvetica", "bold");
|
||||
doc.setFontSize(13);
|
||||
{
|
||||
const lines = doc.splitTextToSize(sec.categoryName, maxW);
|
||||
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: maxW });
|
||||
ensureSpace(dim.h + 3);
|
||||
doc.text(lines, margin, y);
|
||||
y += dim.h + 5;
|
||||
}
|
||||
|
||||
for (const ent of sec.entries) {
|
||||
doc.setFont("helvetica", "bold");
|
||||
doc.setFontSize(11);
|
||||
{
|
||||
const lines = doc.splitTextToSize(ent.title, maxW);
|
||||
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: maxW });
|
||||
ensureSpace(dim.h + 2);
|
||||
doc.text(lines, margin, y);
|
||||
y += dim.h + 3;
|
||||
}
|
||||
|
||||
if (ent.blocks && ent.blocks.length > 0) {
|
||||
for (const b of ent.blocks) {
|
||||
doc.setFont("helvetica", "bold");
|
||||
doc.setFontSize(10);
|
||||
{
|
||||
const lines = doc.splitTextToSize(b.label, maxW);
|
||||
const dim = doc.getTextDimensions(lines.join("\n"), {
|
||||
maxWidth: maxW,
|
||||
});
|
||||
ensureSpace(dim.h + 1);
|
||||
doc.text(lines, margin, y);
|
||||
y += dim.h + 2;
|
||||
}
|
||||
const { img, file } = labeledBlockMedia(b);
|
||||
if (img) {
|
||||
writeBlockBodyParagraphs(b.body);
|
||||
writeMediaUrlLines(img, "italic");
|
||||
} else if (file) {
|
||||
writeBlockBodyParagraphs(b.body);
|
||||
writeMediaUrlLines(file, "normal");
|
||||
} else {
|
||||
writeBlockBodyParagraphs(b.body);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (const p of splitDisplayParagraphs(ent.body ?? "")) {
|
||||
doc.setFont("helvetica", "normal");
|
||||
doc.setFontSize(11);
|
||||
const lines = doc.splitTextToSize(p, maxW);
|
||||
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: maxW });
|
||||
ensureSpace(dim.h + 1);
|
||||
doc.text(lines, margin, y);
|
||||
y += dim.h + 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ab = doc.output("arraybuffer") as ArrayBuffer;
|
||||
return new Blob([ab], { type: "application/pdf" });
|
||||
}
|
||||
|
||||
export function buildStoredRulePdfBlob(rule: StoredLastPublishedRule): Blob {
|
||||
const sections = parsePublishedDocumentForCommunityRuleDisplay(rule.document);
|
||||
if (sections.length === 0) {
|
||||
throw new Error("exportEmptyDocument");
|
||||
}
|
||||
return sectionsToPdfBlob(rule.title, rule.summary, sections);
|
||||
}
|
||||
|
||||
export function downloadStoredRuleAsPdf(rule: StoredLastPublishedRule): void {
|
||||
if (typeof document === "undefined") return;
|
||||
const blob = buildStoredRulePdfBlob(rule);
|
||||
const base = exportFilenameBase(rule);
|
||||
downloadBlob(`${base}-community-rule.pdf`, blob);
|
||||
}
|
||||
|
||||
export function downloadBlob(filename: string, blob: Blob): void {
|
||||
if (typeof document === "undefined") return;
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
@@ -382,14 +200,39 @@ export function downloadTextFile(
|
||||
contents: string,
|
||||
mime: string,
|
||||
): void {
|
||||
const blob = new Blob([contents], { type: mime });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
a.rel = "noopener";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
downloadBlob(filename, new Blob([contents], { type: mime }));
|
||||
}
|
||||
|
||||
export function downloadStoredRuleAsPdf(
|
||||
rule: RuleExportSource,
|
||||
origin: string,
|
||||
): void {
|
||||
downloadBlob(exportPdfFilename(rule.title), buildStoredRulePdfBlob(rule, origin));
|
||||
}
|
||||
|
||||
export function downloadStoredRuleAsMarkdown(
|
||||
rule: RuleExportSource,
|
||||
origin: string,
|
||||
): void {
|
||||
downloadTextFile(
|
||||
RULE_MD_FILENAME,
|
||||
exportStoredRuleAsMarkdown(rule, origin),
|
||||
"text/markdown;charset=utf-8",
|
||||
);
|
||||
}
|
||||
|
||||
export function printStoredRule(
|
||||
rule: RuleExportSource,
|
||||
origin: string,
|
||||
): boolean {
|
||||
if (typeof window === "undefined") return false;
|
||||
const html = buildPrintableRuleHtmlDocument(rule, origin);
|
||||
const popup = window.open("", "_blank");
|
||||
if (!popup) return false;
|
||||
popup.document.open();
|
||||
popup.document.write(html);
|
||||
popup.document.close();
|
||||
popup.focus();
|
||||
popup.print();
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import type { CommunityRuleEntry } from "../../app/components/type/CommunityRule/CommunityRule.types";
|
||||
import exportCopy from "../../messages/en/create/export.json";
|
||||
import { communityInviteInitials } from "./ruleInviteCardMeta";
|
||||
import { parsePublishedDocumentForCommunityRuleDisplay } from "./publishedDocumentToDisplaySections";
|
||||
import { RULE_SECTION_CATEGORY } from "./ruleSectionsFromMethodSelections";
|
||||
import { sharedTermsSection } from "./sharedTermsSection";
|
||||
import { askOrganizerUrl } from "../sharePaths";
|
||||
|
||||
export type RuleExportSource = {
|
||||
id: string;
|
||||
title: string;
|
||||
summary?: string | null;
|
||||
document: Record<string, unknown>;
|
||||
finishedAt?: string | Date | null;
|
||||
};
|
||||
|
||||
export type RuleExportLine = {
|
||||
lead?: string;
|
||||
body: string;
|
||||
};
|
||||
|
||||
export type RuleExportCard = {
|
||||
title: string;
|
||||
lines: RuleExportLine[];
|
||||
};
|
||||
|
||||
export type RuleExportSection = {
|
||||
title: string;
|
||||
cards: RuleExportCard[];
|
||||
};
|
||||
|
||||
export type RuleExportTerm = {
|
||||
term: string;
|
||||
meaning: string;
|
||||
};
|
||||
|
||||
export type RuleExportDocument = {
|
||||
title: string;
|
||||
summary: string;
|
||||
initials: string;
|
||||
photoUrl?: string;
|
||||
finishedOn?: string;
|
||||
sections: RuleExportSection[];
|
||||
terms: RuleExportTerm[];
|
||||
takeaway: string;
|
||||
takeawayUrl: string;
|
||||
credit: string;
|
||||
};
|
||||
|
||||
function leadIn(label: string): string {
|
||||
const trimmed = label.trim();
|
||||
if (trimmed.length === 0) return "";
|
||||
return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;
|
||||
}
|
||||
|
||||
function splitParagraphs(text: string): string[] {
|
||||
return text
|
||||
.trim()
|
||||
.split(/\n\s*\n/)
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
}
|
||||
|
||||
function valueLines(body: string): RuleExportLine[] {
|
||||
const parts = splitParagraphs(body);
|
||||
if (parts.length === 0) return [];
|
||||
if (parts.length === 1) {
|
||||
const only = parts[0];
|
||||
return only ? [{ body: only }] : [];
|
||||
}
|
||||
const meaning = parts[0] ?? "";
|
||||
const signals = parts.slice(1).join(" ");
|
||||
const lines: RuleExportLine[] = [];
|
||||
if (meaning.length > 0) lines.push({ body: meaning });
|
||||
if (signals.length > 0) {
|
||||
lines.push({ lead: exportCopy.signalsLead, body: signals });
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function entryLines(
|
||||
entry: CommunityRuleEntry,
|
||||
valuesSection: boolean,
|
||||
): RuleExportLine[] {
|
||||
if (valuesSection) {
|
||||
return valueLines(entry.body ?? "");
|
||||
}
|
||||
const lines: RuleExportLine[] = [];
|
||||
const intro = (entry.body ?? "").trim();
|
||||
if (intro.length > 0) {
|
||||
for (const paragraph of splitParagraphs(intro)) {
|
||||
lines.push({ body: paragraph });
|
||||
}
|
||||
}
|
||||
for (const block of entry.blocks ?? []) {
|
||||
const body = block.body.trim();
|
||||
if (body.length === 0) continue;
|
||||
const lead = leadIn(block.label);
|
||||
if (lead.length > 0) {
|
||||
lines.push({ lead, body });
|
||||
} else {
|
||||
lines.push({ body });
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function photoUrlFromDocument(document: Record<string, unknown>): string | undefined {
|
||||
const raw = document.communityAvatarUrl;
|
||||
if (typeof raw !== "string") return undefined;
|
||||
const trimmed = raw.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function finishedOn(value: string | Date | null | undefined): string | undefined {
|
||||
if (value == null) return undefined;
|
||||
const date = typeof value === "string" ? new Date(value) : value;
|
||||
if (Number.isNaN(date.getTime())) return undefined;
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function buildRuleExportDocument(
|
||||
rule: RuleExportSource,
|
||||
origin: string,
|
||||
): RuleExportDocument {
|
||||
const title = rule.title.trim();
|
||||
const summary =
|
||||
typeof rule.summary === "string" ? rule.summary.trim() : "";
|
||||
const display = parsePublishedDocumentForCommunityRuleDisplay(rule.document);
|
||||
const sharedTitle = sharedTermsSection().categoryName;
|
||||
const sections: RuleExportSection[] = [];
|
||||
for (const section of display) {
|
||||
if (section.categoryName === sharedTitle) continue;
|
||||
const valuesSection =
|
||||
section.categoryName === RULE_SECTION_CATEGORY.values;
|
||||
const cards: RuleExportCard[] = [];
|
||||
for (const entry of section.entries) {
|
||||
const lines = entryLines(entry, valuesSection);
|
||||
if (lines.length === 0 && entry.title.trim().length === 0) continue;
|
||||
cards.push({ title: entry.title.trim(), lines });
|
||||
}
|
||||
if (cards.length === 0) continue;
|
||||
sections.push({ title: section.categoryName, cards });
|
||||
}
|
||||
const terms: RuleExportTerm[] = sharedTermsSection().entries.map((entry) => ({
|
||||
term: entry.title,
|
||||
meaning: (entry.body ?? "").trim(),
|
||||
}));
|
||||
return {
|
||||
title: title.length > 0 ? title : "Rule",
|
||||
summary,
|
||||
initials: communityInviteInitials(title.length > 0 ? title : "Rule"),
|
||||
photoUrl: photoUrlFromDocument(rule.document),
|
||||
finishedOn: finishedOn(rule.finishedAt),
|
||||
sections,
|
||||
terms,
|
||||
takeaway: exportCopy.takeaway,
|
||||
takeawayUrl: askOrganizerUrl(origin),
|
||||
credit: exportCopy.credit,
|
||||
};
|
||||
}
|
||||
|
||||
export function yamlQuote(value: string): string {
|
||||
if (value.length === 0) return '""';
|
||||
if (/[:#\n"'\\]/.test(value) || value !== value.trim()) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function exportPdfFilename(title: string): string {
|
||||
const cleaned = title
|
||||
.trim()
|
||||
.replace(/[\\/:*?"<>|]/g, "")
|
||||
.replace(/\s+/g, " ");
|
||||
const base = cleaned.length > 0 ? cleaned : "Rule";
|
||||
return `${base} Rule.pdf`;
|
||||
}
|
||||
|
||||
export const RULE_MD_FILENAME = exportCopy.ruleMdFilename;
|
||||
@@ -0,0 +1,228 @@
|
||||
import { jsPDF } from "jspdf";
|
||||
|
||||
import exportCopy from "../../messages/en/create/export.json";
|
||||
import type {
|
||||
RuleExportCard,
|
||||
RuleExportDocument,
|
||||
RuleExportLine,
|
||||
RuleExportTerm,
|
||||
} from "./ruleExportModel";
|
||||
|
||||
const PAGE_W = 215.9;
|
||||
const PAGE_H = 279.4;
|
||||
const MARGIN_X = 16.9;
|
||||
const MARGIN_TOP = 12.7;
|
||||
const FOOTER_Y = PAGE_H - 9.5;
|
||||
const CONTENT_BOTTOM = PAGE_H - 16;
|
||||
const COL_GAP = 8.5;
|
||||
const COL_W = (PAGE_W - 2 * MARGIN_X - COL_GAP) / 2;
|
||||
|
||||
function lineText(line: RuleExportLine): string {
|
||||
return line.lead ? `${line.lead} ${line.body}` : line.body;
|
||||
}
|
||||
|
||||
export function ruleExportDocumentToPdfBytes(docModel: RuleExportDocument): Uint8Array {
|
||||
const doc = new jsPDF({ unit: "mm", format: "letter" });
|
||||
const maxW = PAGE_W - 2 * MARGIN_X;
|
||||
let y = MARGIN_TOP;
|
||||
|
||||
function addPage(): void {
|
||||
doc.addPage();
|
||||
y = MARGIN_TOP;
|
||||
}
|
||||
|
||||
function ensureSpace(height: number): void {
|
||||
if (y + height > CONTENT_BOTTOM) addPage();
|
||||
}
|
||||
|
||||
function writeWrapped(
|
||||
text: string,
|
||||
opts: {
|
||||
size: number;
|
||||
style: "normal" | "bold" | "italic";
|
||||
width?: number;
|
||||
x?: number;
|
||||
gap?: number;
|
||||
},
|
||||
): void {
|
||||
const width = opts.width ?? maxW;
|
||||
const x = opts.x ?? MARGIN_X;
|
||||
doc.setFont("helvetica", opts.style);
|
||||
doc.setFontSize(opts.size);
|
||||
const lines = doc.splitTextToSize(text, width) as string[];
|
||||
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: width });
|
||||
ensureSpace(dim.h + 0.4);
|
||||
doc.text(lines, x, y);
|
||||
y += dim.h + (opts.gap ?? 1.6);
|
||||
}
|
||||
|
||||
function writeCard(card: RuleExportCard): void {
|
||||
writeWrapped(card.title, { size: 11, style: "bold", gap: 1.4 });
|
||||
for (const line of card.lines) {
|
||||
writeWrapped(lineText(line), { size: 9.5, style: "normal", gap: 2 });
|
||||
}
|
||||
y += 1;
|
||||
}
|
||||
|
||||
function termHeight(term: RuleExportTerm, width: number): number {
|
||||
doc.setFont("helvetica", "italic");
|
||||
doc.setFontSize(9);
|
||||
const termLines = doc.splitTextToSize(
|
||||
`${term.term} ${term.meaning}`,
|
||||
width,
|
||||
) as string[];
|
||||
const dim = doc.getTextDimensions(termLines.join("\n"), { maxWidth: width });
|
||||
return dim.h + 2.2;
|
||||
}
|
||||
|
||||
function writeTermAt(
|
||||
term: RuleExportTerm,
|
||||
x: number,
|
||||
top: number,
|
||||
width: number,
|
||||
): number {
|
||||
const text = `${term.term} ${term.meaning}`;
|
||||
doc.setFont("helvetica", "italic");
|
||||
doc.setFontSize(9);
|
||||
const lines = doc.splitTextToSize(text, width) as string[];
|
||||
const dim = doc.getTextDimensions(lines.join("\n"), { maxWidth: width });
|
||||
doc.text(lines, x, top);
|
||||
return dim.h + 2.2;
|
||||
}
|
||||
|
||||
function writeTerms(terms: RuleExportTerm[]): void {
|
||||
let index = 0;
|
||||
while (index < terms.length) {
|
||||
if (y > CONTENT_BOTTOM - 10) addPage();
|
||||
const colTop = y;
|
||||
const left: RuleExportTerm[] = [];
|
||||
let leftH = 0;
|
||||
while (index < terms.length) {
|
||||
const next = terms[index];
|
||||
if (!next) break;
|
||||
const height = termHeight(next, COL_W);
|
||||
if (leftH > 0 && colTop + leftH + height > CONTENT_BOTTOM) break;
|
||||
if (leftH === 0 && colTop + height > CONTENT_BOTTOM) {
|
||||
addPage();
|
||||
break;
|
||||
}
|
||||
left.push(next);
|
||||
leftH += height;
|
||||
index += 1;
|
||||
}
|
||||
if (left.length === 0) {
|
||||
const overflow = terms[index];
|
||||
if (!overflow) break;
|
||||
left.push(overflow);
|
||||
index += 1;
|
||||
}
|
||||
const right: RuleExportTerm[] = [];
|
||||
let rightH = 0;
|
||||
while (index < terms.length) {
|
||||
const next = terms[index];
|
||||
if (!next) break;
|
||||
const height = termHeight(next, COL_W);
|
||||
if (right.length > 0 && colTop + rightH + height > CONTENT_BOTTOM) {
|
||||
break;
|
||||
}
|
||||
if (right.length === 0 && colTop + height > CONTENT_BOTTOM) break;
|
||||
right.push(next);
|
||||
rightH += height;
|
||||
index += 1;
|
||||
}
|
||||
let leftY = colTop;
|
||||
for (const term of left) {
|
||||
leftY += writeTermAt(term, MARGIN_X, leftY, COL_W);
|
||||
}
|
||||
let rightY = colTop;
|
||||
for (const term of right) {
|
||||
rightY += writeTermAt(
|
||||
term,
|
||||
MARGIN_X + COL_W + COL_GAP,
|
||||
rightY,
|
||||
COL_W,
|
||||
);
|
||||
}
|
||||
y = Math.max(leftY, rightY);
|
||||
}
|
||||
}
|
||||
|
||||
doc.setTextColor(0, 0, 0);
|
||||
doc.setDrawColor(20, 20, 20);
|
||||
doc.setLineWidth(0.5);
|
||||
doc.circle(MARGIN_X + 9.5, y + 9.5, 9.5, "S");
|
||||
doc.setFont("helvetica", "bold");
|
||||
doc.setFontSize(11);
|
||||
doc.text(docModel.initials, MARGIN_X + 9.5, y + 11.2, { align: "center" });
|
||||
|
||||
const headerX = MARGIN_X + 25.4;
|
||||
const headerW = maxW - 25.4;
|
||||
const titleY = y;
|
||||
doc.setFont("helvetica", "bold");
|
||||
doc.setFontSize(16);
|
||||
const titleLines = doc.splitTextToSize(docModel.title, headerW) as string[];
|
||||
const titleDim = doc.getTextDimensions(titleLines.join("\n"), {
|
||||
maxWidth: headerW,
|
||||
});
|
||||
doc.text(titleLines, headerX, y + 6);
|
||||
let headerBottom = titleY + Math.max(19, titleDim.h + 4);
|
||||
if (docModel.summary.length > 0) {
|
||||
doc.setFont("helvetica", "normal");
|
||||
doc.setFontSize(10);
|
||||
const sumLines = doc.splitTextToSize(docModel.summary, headerW) as string[];
|
||||
const sumDim = doc.getTextDimensions(sumLines.join("\n"), {
|
||||
maxWidth: headerW,
|
||||
});
|
||||
doc.text(sumLines, headerX, titleY + titleDim.h + 8);
|
||||
headerBottom = titleY + titleDim.h + sumDim.h + 10;
|
||||
}
|
||||
y = Math.max(headerBottom, y + 22);
|
||||
|
||||
for (const section of docModel.sections) {
|
||||
doc.setDrawColor(20, 20, 20);
|
||||
doc.setLineWidth(0.25);
|
||||
ensureSpace(14);
|
||||
doc.line(MARGIN_X, y, PAGE_W - MARGIN_X, y);
|
||||
y += 5;
|
||||
writeWrapped(section.title, { size: 14, style: "bold", gap: 3 });
|
||||
for (const card of section.cards) {
|
||||
writeCard(card);
|
||||
}
|
||||
}
|
||||
|
||||
if (docModel.terms.length > 0) {
|
||||
doc.setDrawColor(20, 20, 20);
|
||||
doc.setLineWidth(0.25);
|
||||
ensureSpace(16);
|
||||
doc.line(MARGIN_X, y, PAGE_W - MARGIN_X, y);
|
||||
y += 5;
|
||||
writeWrapped(exportCopy.sharedTermsHeading, {
|
||||
size: 14,
|
||||
style: "bold",
|
||||
gap: 4,
|
||||
});
|
||||
writeTerms(docModel.terms);
|
||||
}
|
||||
|
||||
ensureSpace(8);
|
||||
y += 4;
|
||||
writeWrapped(`${docModel.takeaway} ${docModel.takeawayUrl}`, {
|
||||
size: 8,
|
||||
style: "normal",
|
||||
gap: 2,
|
||||
});
|
||||
|
||||
const pageCount = doc.getNumberOfPages();
|
||||
for (let i = 1; i <= pageCount; i += 1) {
|
||||
doc.setPage(i);
|
||||
doc.setFont("helvetica", "normal");
|
||||
doc.setFontSize(8);
|
||||
doc.setTextColor(70, 70, 70);
|
||||
doc.text(docModel.credit, MARGIN_X, FOOTER_Y);
|
||||
doc.text(String(i), PAGE_W - MARGIN_X, FOOTER_Y, { align: "right" });
|
||||
doc.setTextColor(0, 0, 0);
|
||||
}
|
||||
|
||||
const ab = doc.output("arraybuffer") as ArrayBuffer;
|
||||
return new Uint8Array(ab);
|
||||
}
|
||||
@@ -12,6 +12,10 @@ import {
|
||||
stakeholderInviteReplyTo,
|
||||
type RuleStakeholderInviteMailInput,
|
||||
} from "./ruleStakeholderInviteMail";
|
||||
import {
|
||||
buildRuleFollowUpMail,
|
||||
type RuleFollowUpMailInput,
|
||||
} from "./ruleFollowUpMail";
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value
|
||||
@@ -115,6 +119,20 @@ export async function sendRuleStakeholderInviteEmail(
|
||||
});
|
||||
}
|
||||
|
||||
/** 48-hour print follow-up to the address that holds the pen. */
|
||||
export async function sendRuleFollowUpEmail(
|
||||
input: RuleFollowUpMailInput,
|
||||
): Promise<void> {
|
||||
const { subject, text, html } = buildRuleFollowUpMail(input);
|
||||
await sendHtmlMail({
|
||||
to: input.to,
|
||||
subject,
|
||||
text,
|
||||
html,
|
||||
devLog: `[dev] Rule follow-up mail for ${input.to}`,
|
||||
});
|
||||
}
|
||||
|
||||
/** Notify support/organizers when a visitor submits the Ask an organizer form. */
|
||||
export async function sendOrganizerInquiryNotification(params: {
|
||||
/** Destination inbox (e.g. from ORGANIZER_INQUIRY_TO). */
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { publishedRuleAnalyticsFromDocument } from "../create/publishedRuleAnalytics";
|
||||
|
||||
export function publishedRuleAnalyticsColumns(document: unknown): {
|
||||
communityLocation: string | null;
|
||||
orgType: string | null;
|
||||
} {
|
||||
return publishedRuleAnalyticsFromDocument(document);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { createHmac, timingSafeEqual } from "crypto";
|
||||
|
||||
export function ruleExportToken(ruleId: string, pepper: string): string {
|
||||
return createHmac("sha256", pepper)
|
||||
.update(`rule-export:${ruleId}`)
|
||||
.digest("base64url");
|
||||
}
|
||||
|
||||
export function ruleExportTokenMatches(
|
||||
ruleId: string,
|
||||
token: string,
|
||||
pepper: string,
|
||||
): boolean {
|
||||
if (token.length === 0) return false;
|
||||
const expected = Buffer.from(ruleExportToken(ruleId, pepper));
|
||||
const actual = Buffer.from(token);
|
||||
if (expected.length !== actual.length) return false;
|
||||
return timingSafeEqual(expected, actual);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { PrismaClient } from "@prisma/client";
|
||||
import { logger } from "../logger";
|
||||
import { originFromHost } from "../siteMetadata";
|
||||
import { ruleExportMarkdownUrl, ruleExportPdfUrl } from "../sharePaths";
|
||||
import { getSessionPepper } from "./env";
|
||||
import { sendRuleFollowUpEmail } from "./mail";
|
||||
import { ruleExportToken } from "./ruleExportToken";
|
||||
|
||||
export const RULE_FOLLOW_UP_AFTER_MS = 48 * 60 * 60 * 1000;
|
||||
export const RULE_FOLLOW_UP_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export type RuleFollowUpResult = {
|
||||
sent: number;
|
||||
failed: number;
|
||||
skipped: number;
|
||||
};
|
||||
|
||||
export async function sendDueRuleFollowUpEmails(
|
||||
db: PrismaClient,
|
||||
now = new Date(),
|
||||
): Promise<RuleFollowUpResult> {
|
||||
const result: RuleFollowUpResult = { sent: 0, failed: 0, skipped: 0 };
|
||||
|
||||
let pepper: string;
|
||||
try {
|
||||
pepper = getSessionPepper();
|
||||
} catch (err) {
|
||||
logger.error({
|
||||
scope: "ruleFollowUp",
|
||||
message: err instanceof Error ? err.message : "SESSION_SECRET missing",
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
const origin = originFromHost(null);
|
||||
const dueBy = new Date(now.getTime() - RULE_FOLLOW_UP_AFTER_MS);
|
||||
const notBefore = new Date(now.getTime() - RULE_FOLLOW_UP_MAX_AGE_MS);
|
||||
|
||||
const rows = await db.publishedRule.findMany({
|
||||
where: {
|
||||
followUpEmailSentAt: null,
|
||||
userId: { not: null },
|
||||
createdAt: { lte: dueBy, gte: notBefore },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
user: { select: { email: true } },
|
||||
},
|
||||
});
|
||||
|
||||
for (const row of rows) {
|
||||
const email = row.user?.email?.trim().toLowerCase() ?? "";
|
||||
if (!email.includes("@")) {
|
||||
result.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const token = ruleExportToken(row.id, pepper);
|
||||
try {
|
||||
await sendRuleFollowUpEmail({
|
||||
to: email,
|
||||
origin,
|
||||
communityName: row.title,
|
||||
pdfUrl: ruleExportPdfUrl(origin, row.id, token),
|
||||
markdownUrl: ruleExportMarkdownUrl(origin, row.id, token),
|
||||
});
|
||||
await db.publishedRule.update({
|
||||
where: { id: row.id },
|
||||
data: { followUpEmailSentAt: now },
|
||||
});
|
||||
result.sent += 1;
|
||||
} catch (err) {
|
||||
result.failed += 1;
|
||||
logger.error({
|
||||
scope: "ruleFollowUp",
|
||||
message: err instanceof Error ? err.message : "send failed",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
logger.info({
|
||||
scope: "ruleFollowUp",
|
||||
sent: result.sent,
|
||||
failed: result.failed,
|
||||
skipped: result.skipped,
|
||||
});
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { ASSETS, getAssetPath } from "../assetUtils";
|
||||
import { communityPossessive } from "../create/ruleInviteCardMeta";
|
||||
import { RULE_MD_FILENAME } from "../create/ruleExportModel";
|
||||
|
||||
export const RULE_FOLLOW_UP_LOGO_PATH = getAssetPath(ASSETS.LOGO_MARK);
|
||||
|
||||
export type RuleFollowUpMailInput = {
|
||||
to: string;
|
||||
origin: string;
|
||||
communityName: string;
|
||||
pdfUrl: string;
|
||||
markdownUrl: string;
|
||||
};
|
||||
|
||||
export type RuleFollowUpMailContent = {
|
||||
subject: string;
|
||||
previewText: string;
|
||||
text: string;
|
||||
html: string;
|
||||
};
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function originHost(origin: string): string {
|
||||
try {
|
||||
return new URL(origin).host;
|
||||
} catch {
|
||||
return origin.replace(/^https?:\/\//, "").replace(/\/$/, "");
|
||||
}
|
||||
}
|
||||
|
||||
export function buildRuleFollowUpMail(
|
||||
input: RuleFollowUpMailInput,
|
||||
): RuleFollowUpMailContent {
|
||||
const communityName = input.communityName.trim() || "A community";
|
||||
const possessive = communityPossessive(communityName);
|
||||
const origin = input.origin.replace(/\/$/, "");
|
||||
const kitUrl = `${origin}/kit`;
|
||||
const host = originHost(origin);
|
||||
const subject = `${possessive} Rule, printed`;
|
||||
const previewText = `Here is ${possessive} Rule as a PDF, ready to print.`;
|
||||
const intro = `Here is ${possessive} Rule as a PDF, ready to print or drop into your onboarding doc.`;
|
||||
const putIt =
|
||||
"Put it where members will see it, on the wall where you meet or at the top of the doc new members read.";
|
||||
const fixNow =
|
||||
"If anything in it already feels wrong, that is normal, and it is easier to fix now than in a year.";
|
||||
const officeHours = `Bring it to office hours if you want a second read. No signup, and the next one is listed at ${host}/kit.`;
|
||||
const signOff = "CommunityRule";
|
||||
const why = `Sent because you finished a Rule at ${host}.`;
|
||||
const madeBy =
|
||||
"CommunityRule is made by the Media Economies Design Lab at the University of Colorado Boulder.";
|
||||
const privacyUrl = `${origin}/privacy`;
|
||||
const aboutUrl = `${origin}/about`;
|
||||
const logoUrl = `${origin}${RULE_FOLLOW_UP_LOGO_PATH}`;
|
||||
|
||||
const text = [
|
||||
"Your Rule is ready to print",
|
||||
"",
|
||||
intro,
|
||||
"",
|
||||
"Download the PDF",
|
||||
input.pdfUrl,
|
||||
"",
|
||||
`Or download ${RULE_MD_FILENAME} for a wiki or a repository.`,
|
||||
input.markdownUrl,
|
||||
"",
|
||||
putIt,
|
||||
"",
|
||||
fixNow,
|
||||
"",
|
||||
officeHours,
|
||||
kitUrl,
|
||||
"",
|
||||
signOff,
|
||||
"",
|
||||
why,
|
||||
"",
|
||||
madeBy,
|
||||
`Privacy ${privacyUrl}`,
|
||||
].join("\n");
|
||||
|
||||
const html = followUpHtml({
|
||||
subject,
|
||||
previewText,
|
||||
intro,
|
||||
pdfUrl: input.pdfUrl,
|
||||
markdownUrl: input.markdownUrl,
|
||||
putIt,
|
||||
fixNow,
|
||||
officeHours,
|
||||
kitUrl,
|
||||
signOff,
|
||||
why,
|
||||
madeBy,
|
||||
privacyUrl,
|
||||
aboutUrl,
|
||||
logoUrl,
|
||||
kitHostPath: `${host}/kit`,
|
||||
});
|
||||
|
||||
return { subject, previewText, text, html };
|
||||
}
|
||||
|
||||
function followUpHtml(opts: {
|
||||
subject: string;
|
||||
previewText: string;
|
||||
intro: string;
|
||||
pdfUrl: string;
|
||||
markdownUrl: string;
|
||||
putIt: string;
|
||||
fixNow: string;
|
||||
officeHours: string;
|
||||
kitUrl: string;
|
||||
signOff: string;
|
||||
why: string;
|
||||
madeBy: string;
|
||||
privacyUrl: string;
|
||||
aboutUrl: string;
|
||||
logoUrl: string;
|
||||
kitHostPath: string;
|
||||
}): string {
|
||||
const pdfHref = escapeHtml(opts.pdfUrl);
|
||||
const mdHref = escapeHtml(opts.markdownUrl);
|
||||
const kitHref = escapeHtml(opts.kitUrl);
|
||||
const kitHostPath = escapeHtml(opts.kitHostPath);
|
||||
const officeLead = "Bring it to office hours if you want a second read. No signup, and the next one is listed at ";
|
||||
const officeHtml = opts.officeHours.startsWith(officeLead)
|
||||
? `${escapeHtml(officeLead)}<a href="${kitHref}" style="color:#000000;text-decoration:underline;">${kitHostPath}</a>.`
|
||||
: escapeHtml(opts.officeHours);
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>${escapeHtml(opts.subject)}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:0;background:#e4e4e4;">
|
||||
<div style="display:none;max-height:0;overflow:hidden;mso-hide:all;">${escapeHtml(
|
||||
opts.previewText,
|
||||
)}</div>
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#e4e4e4;">
|
||||
<tr>
|
||||
<td align="center">
|
||||
<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="width:600px;max-width:600px;background:#ffffff;">
|
||||
<tr>
|
||||
<td style="background:#000000;padding:24px 32px;">
|
||||
<table role="presentation" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td style="font-family:'Bricolage Grotesque',Arial,sans-serif;font-size:22px;line-height:27px;color:#ffffff;padding-right:6px;">CommunityRule</td>
|
||||
<td>
|
||||
<img src="${escapeHtml(opts.logoUrl)}" width="27" height="27" alt="" style="display:block;border:0;width:27px;height:27px;" />
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding:40px 32px 56px;">
|
||||
<h1 style="margin:0 0 16px;font-family:'Bricolage Grotesque',Arial,sans-serif;font-size:36px;line-height:44px;font-weight:700;color:#000000;">Your Rule is ready to print</h1>
|
||||
<p style="margin:0 0 32px;font-family:Inter,Arial,sans-serif;font-size:18px;line-height:24px;color:#303030;">${escapeHtml(opts.intro)}</p>
|
||||
<p style="margin:0 0 16px;">
|
||||
<a href="${pdfHref}" style="display:inline-block;background:#141414;color:#ffffff;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:20px;font-weight:500;text-decoration:none;border-radius:9999px;padding:12px 16px;">Download the PDF</a>
|
||||
</p>
|
||||
<p style="margin:0 0 32px;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">
|
||||
Or download <a href="${mdHref}" style="color:#000000;text-decoration:underline;">${RULE_MD_FILENAME}</a> for a wiki or a repository.
|
||||
</p>
|
||||
<div style="height:1px;background:#e4e4e4;margin:0 0 32px;"></div>
|
||||
<p style="margin:0 0 20px;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:24px;color:#303030;">${escapeHtml(opts.putIt)}</p>
|
||||
<p style="margin:0 0 20px;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:24px;color:#303030;">${escapeHtml(opts.fixNow)}</p>
|
||||
<p style="margin:0 0 20px;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:24px;color:#303030;">${officeHtml}</p>
|
||||
<p style="margin:0 0 32px;font-family:Inter,Arial,sans-serif;font-size:16px;line-height:24px;color:#000000;">${escapeHtml(opts.signOff)}</p>
|
||||
<div style="border-top:1px solid #e4e4e4;padding-top:24px;">
|
||||
<p style="margin:0 0 12px;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">${escapeHtml(opts.why)}</p>
|
||||
<p style="margin:0 0 12px;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">${escapeHtml(opts.madeBy)}</p>
|
||||
<p style="margin:0;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:20px;color:#464646;">
|
||||
<a href="${escapeHtml(opts.privacyUrl)}" style="color:#464646;text-decoration:underline;">Privacy</a>
|
||||
|
||||
<a href="${escapeHtml(opts.aboutUrl)}" style="color:#464646;text-decoration:underline;">About CommunityRule</a>
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
export const RULE_COUNT_FOLD_THRESHOLD = 5;
|
||||
|
||||
export type RuleCountRow = {
|
||||
orgType: string | null;
|
||||
place: string | null;
|
||||
};
|
||||
|
||||
export type RuleCountCell = {
|
||||
orgType: string | null;
|
||||
place: string | null;
|
||||
count: number;
|
||||
folded: boolean;
|
||||
};
|
||||
|
||||
export type RuleLaunchCounts = {
|
||||
finished: number;
|
||||
cells: RuleCountCell[];
|
||||
};
|
||||
|
||||
function normalizePlace(raw: string | null): string {
|
||||
return (raw ?? "").trim().replace(/\s+/g, " ").toLowerCase();
|
||||
}
|
||||
|
||||
function cellKey(orgType: string | null, placeKey: string): string {
|
||||
return `${orgType ?? ""}\u0000${placeKey}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finished-Rule counts by group type and place. Any cell under five is folded
|
||||
* so a single group cannot be picked out.
|
||||
*/
|
||||
export function aggregateRuleLaunchCounts(rows: RuleCountRow[]): RuleLaunchCounts {
|
||||
const grouped = new Map<
|
||||
string,
|
||||
{ orgType: string | null; place: string | null; count: number }
|
||||
>();
|
||||
for (const row of rows) {
|
||||
const orgType = row.orgType && row.orgType.trim().length > 0 ? row.orgType : null;
|
||||
const placeRaw = row.place && row.place.trim().length > 0 ? row.place.trim() : null;
|
||||
const key = cellKey(orgType, normalizePlace(placeRaw));
|
||||
const existing = grouped.get(key);
|
||||
if (existing) {
|
||||
existing.count += 1;
|
||||
} else {
|
||||
grouped.set(key, { orgType, place: placeRaw, count: 1 });
|
||||
}
|
||||
}
|
||||
|
||||
const shown: RuleCountCell[] = [];
|
||||
let foldedCount = 0;
|
||||
for (const cell of grouped.values()) {
|
||||
if (cell.count < RULE_COUNT_FOLD_THRESHOLD) {
|
||||
foldedCount += cell.count;
|
||||
continue;
|
||||
}
|
||||
shown.push({ ...cell, folded: false });
|
||||
}
|
||||
shown.sort((a, b) => b.count - a.count || (a.orgType ?? "").localeCompare(b.orgType ?? ""));
|
||||
if (foldedCount > 0) {
|
||||
shown.push({
|
||||
orgType: null,
|
||||
place: null,
|
||||
count: foldedCount,
|
||||
folded: true,
|
||||
});
|
||||
}
|
||||
return { finished: rows.length, cells: shown };
|
||||
}
|
||||
@@ -19,6 +19,38 @@ export function buildPublicRuleUrl(origin: string, ruleId: string): string {
|
||||
return `${base}${publishedRulePath(ruleId)}`;
|
||||
}
|
||||
|
||||
export const ASK_ORGANIZER_HASH = "ask-organizer";
|
||||
|
||||
/** Home Ask an organizer section. Exports link here; they do not embed the form. */
|
||||
export function askOrganizerUrl(origin: string): string {
|
||||
const base = origin.replace(/\/$/, "");
|
||||
return `${base}/#${ASK_ORGANIZER_HASH}`;
|
||||
}
|
||||
|
||||
export function ruleExportPdfPath(ruleId: string, token: string): string {
|
||||
return `/api/rules/${encodeURIComponent(ruleId)}/export/pdf?t=${encodeURIComponent(token)}`;
|
||||
}
|
||||
|
||||
export function ruleExportMarkdownPath(ruleId: string, token: string): string {
|
||||
return `/api/rules/${encodeURIComponent(ruleId)}/export/md?t=${encodeURIComponent(token)}`;
|
||||
}
|
||||
|
||||
export function ruleExportPdfUrl(
|
||||
origin: string,
|
||||
ruleId: string,
|
||||
token: string,
|
||||
): string {
|
||||
return `${origin.replace(/\/$/, "")}${ruleExportPdfPath(ruleId, token)}`;
|
||||
}
|
||||
|
||||
export function ruleExportMarkdownUrl(
|
||||
origin: string,
|
||||
ruleId: string,
|
||||
token: string,
|
||||
): string {
|
||||
return `${origin.replace(/\/$/, "")}${ruleExportMarkdownPath(ruleId, token)}`;
|
||||
}
|
||||
|
||||
export function buildShareRuleUrl(origin: string, shareSlug: string): string {
|
||||
const base = origin.replace(/\/$/, "");
|
||||
return `${base}${shareRulePath(shareSlug)}`;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Optional Umami tracker. Unset env vars mean no script ships.
|
||||
* Cookie-free mode is an Umami server setting, not this snippet.
|
||||
*/
|
||||
export function umamiTracker(): { src: string; websiteId: string } | null {
|
||||
const src = process.env.NEXT_PUBLIC_UMAMI_SRC?.trim() ?? "";
|
||||
const websiteId = process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID?.trim() ?? "";
|
||||
if (!src || !websiteId) return null;
|
||||
try {
|
||||
const url = new URL(src);
|
||||
if (url.protocol !== "https:" && url.protocol !== "http:") return null;
|
||||
return { src: url.href, websiteId };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,8 @@
|
||||
"termsOfService": "Terms of Service",
|
||||
"termsOfServiceHref": "/terms"
|
||||
},
|
||||
"takeaway": "Tell us what this Rule changed",
|
||||
"takeawayHref": "/#ask-organizer",
|
||||
"license": {
|
||||
"_comment": "Replaces Figma's '© All right reserved'. Covers user-facing content (guides, template copy, marketing) per README — not GPL-3.0 application source. Published user-authored rules are a separate grant.",
|
||||
"label": "Content licensed under CC BY-SA 4.0",
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"_comment": "Print, PDF and RULE.md copy. Figma Print / Notes for the build (25035:48180) and Print / Rule pages 1–4.",
|
||||
"takeaway": "Tell us what this Rule changed",
|
||||
"credit": "Written with CommunityRule. communityrule.info",
|
||||
"signalsLead": "Signals of violation.",
|
||||
"sharedTermsHeading": "Shared terms",
|
||||
"ruleMdFilename": "RULE.md"
|
||||
}
|
||||
@@ -5,8 +5,8 @@
|
||||
"copyReadyToastDescription": "It started from {possessive} Rule. Read it through and change what does not fit before you invite your members.",
|
||||
"copyNameHitTitle": "One line names {name}",
|
||||
"copyNameHitDescription": "It is in {entry} under {category}.",
|
||||
"askOrganizerLead": "Has your Rule changed how your community works?",
|
||||
"askOrganizerLink": "Tell an organizer what changed.",
|
||||
"askOrganizerLead": "",
|
||||
"askOrganizerLink": "Tell us what this Rule changed",
|
||||
"shareNoRuleTitle": "Nothing to share yet",
|
||||
"shareNoRuleDescription": "Open this page from your profile after you finish, or finish a rule first.",
|
||||
"shareLinkCopiedTitle": "Link copied",
|
||||
@@ -21,6 +21,8 @@
|
||||
"exportFailedDescription": "Something went wrong. Refresh the page and try again.",
|
||||
"exportEmptyDocumentTitle": "Could not export",
|
||||
"exportEmptyDocumentDescription": "Your rule document is not available to export yet.",
|
||||
"printBlockedTitle": "Could not open print",
|
||||
"printBlockedDescription": "Allow pop-ups for this site, then choose Print again.",
|
||||
"guestInvitesSkippedTitle": "Stakeholder invites were not sent",
|
||||
"guestInvitesSkippedDescription": "Log in to invite people by email. Until then, share the public link to this CommunityRule.",
|
||||
"guestClaimHintTitle": "Log in to keep this rule on your profile",
|
||||
|
||||
@@ -21,6 +21,7 @@ import learn from "./pages/learn.json";
|
||||
import about from "./pages/about.json";
|
||||
import workshops from "./pages/workshops.json";
|
||||
import workshopInquiries from "./pages/workshopInquiries.json";
|
||||
import ruleCounts from "./pages/ruleCounts.json";
|
||||
import useCases from "./pages/useCases.json";
|
||||
import useCasesDetail from "./pages/useCasesDetail.json";
|
||||
import useCasesCompletedRules from "./pages/useCasesCompletedRules.json";
|
||||
@@ -69,6 +70,7 @@ import createConfirmStakeholders from "./create/reviewAndComplete/confirmStakeho
|
||||
import createFinalReview from "./create/reviewAndComplete/finalReview.json";
|
||||
import createCompleted from "./create/reviewAndComplete/completed.json";
|
||||
import createPublish from "./create/reviewAndComplete/publish.json";
|
||||
import createExport from "./create/export.json";
|
||||
|
||||
// create – cross-cutting (chrome + layout-shell strings)
|
||||
import createFooter from "./create/footer.json";
|
||||
@@ -104,6 +106,7 @@ export default {
|
||||
about,
|
||||
workshops,
|
||||
workshopInquiries,
|
||||
ruleCounts,
|
||||
useCases,
|
||||
useCasesDetail,
|
||||
useCasesCompletedRules,
|
||||
@@ -149,6 +152,7 @@ export default {
|
||||
publish: createPublish,
|
||||
},
|
||||
footer: createFooter,
|
||||
export: createExport,
|
||||
topNav: createTopNav,
|
||||
draftHydration: createDraftHydration,
|
||||
templateReview: createTemplateReview,
|
||||
|
||||
@@ -27,6 +27,9 @@
|
||||
"workshopInquiries": {
|
||||
"title": "Workshop inquiries"
|
||||
},
|
||||
"ruleCounts": {
|
||||
"title": "Finished Rule counts"
|
||||
},
|
||||
"learn": {
|
||||
"title": "Learn",
|
||||
"description": "See how groups use CommunityRule, who it is for, and practical guides for organizing together."
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"menuAriaLabel": "Export format",
|
||||
"downloadPdf": "Download PDF",
|
||||
"downloadCsv": "Download CSV",
|
||||
"downloadMarkdown": "Download Markdown"
|
||||
"downloadPdf": "PDF",
|
||||
"downloadMarkdown": "RULE.md",
|
||||
"print": "Print"
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
{
|
||||
"heading": "What we collect",
|
||||
"paragraphs": [
|
||||
"Your email, to log you in, change your email, or invite a stakeholder. In-progress drafts in your browser and, after you save, on our servers. Files you attach to a Rule. Messages you send through the organizer form, which go to MEDLab by email. Page performance metrics (URL, timing, and browser), which are written to our server logs and are not tied to your account. If you finish a Rule without logging in, a claim cookie on this browser so a later login can attach that Rule to your account.",
|
||||
"Your email, to log you in, change your email, or invite a stakeholder. In-progress drafts in your browser and, after you save, on our servers. Files you attach to a Rule. Messages you send through the organizer form, which go to MEDLab by email. Page performance metrics (URL, timing, and browser), which are written to our server logs and are not tied to your account. If you finish a Rule without logging in, a claim cookie on this browser so a later login can attach that Rule to your account. We count page views with Umami, self-hosted beside this app. It sets no cookies and stores aggregate counts only.",
|
||||
"We do not sell this information or use it for advertising. As a public university project, some records may be subject to the Colorado Open Records Act."
|
||||
]
|
||||
},
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"_comment": "Operator view of finished-Rule counts by group type and place. Named admins only.",
|
||||
"title": "Finished Rule counts",
|
||||
"intro": "Counts of finished Rules by group type and place. Cells with fewer than five Rules are folded together so no single group can be picked out.",
|
||||
"signIn": "Sign in with a named admin account to read these counts.",
|
||||
"signInButton": "Log in",
|
||||
"forbidden": "This page is for named admins.",
|
||||
"empty": "No finished Rules yet.",
|
||||
"finished": "Rules finished",
|
||||
"folded": "Fewer than five",
|
||||
"notGiven": "Not given",
|
||||
"columns": {
|
||||
"type": "Group type",
|
||||
"place": "Place",
|
||||
"count": "Finished"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "PublishedRule" ADD COLUMN "communityLocation" TEXT;
|
||||
ALTER TABLE "PublishedRule" ADD COLUMN "orgType" TEXT;
|
||||
ALTER TABLE "PublishedRule" ADD COLUMN "followUpEmailSentAt" TIMESTAMP(3);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "PublishedRule_orgType_communityLocation_idx" ON "PublishedRule"("orgType", "communityLocation");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "PublishedRule_followUpEmailSentAt_createdAt_idx" ON "PublishedRule"("followUpEmailSentAt", "createdAt");
|
||||
@@ -94,12 +94,20 @@ model PublishedRule {
|
||||
visibility RuleVisibility @default(private)
|
||||
/// Rotating public path `/r/{shareSlug}`. Null while private. Replaced when a link is turned back on.
|
||||
shareSlug String? @unique
|
||||
/// Optional city or region from the description step. Used for launch counts.
|
||||
communityLocation String?
|
||||
/// Canonical group type id (`workersCoop`, `mutualAid`, …). Used for launch counts.
|
||||
orgType String?
|
||||
/// Set when the 48-hour print follow-up has been sent to the pen-holder.
|
||||
followUpEmailSentAt DateTime?
|
||||
|
||||
stakeholders RuleStakeholder[]
|
||||
uploads Upload[]
|
||||
|
||||
@@index([userId])
|
||||
@@index([visibility, updatedAt])
|
||||
@@index([orgType, communityLocation])
|
||||
@@index([followUpEmailSentAt, createdAt])
|
||||
}
|
||||
|
||||
/// File written under UPLOAD_ROOT. Readers follow the linked Rule or draft.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Send the 48-hour print follow-up to pen-holders whose Rule is due.
|
||||
*
|
||||
* Usage (from repo root):
|
||||
* node --env-file=.env --import tsx scripts/send-rule-follow-up.ts
|
||||
*
|
||||
* Cloudron runs the bundled copy hourly. Does not import Next request
|
||||
* helpers.
|
||||
*/
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import { sendDueRuleFollowUpEmails } from "../lib/server/ruleFollowUp";
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
const result = await sendDueRuleFollowUpEmails(prisma);
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
scope: "ruleFollowUp",
|
||||
now: new Date().toISOString(),
|
||||
...result,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(() => prisma.$disconnect());
|
||||
@@ -92,11 +92,8 @@ describe("CompletedScreen", () => {
|
||||
);
|
||||
render(<CompletedScreen />);
|
||||
expect(
|
||||
screen.getByText("Has your Rule changed how your community works?"),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Tell an organizer what changed." }),
|
||||
).toBeInTheDocument();
|
||||
screen.getByRole("link", { name: "Tell us what this Rule changed" }),
|
||||
).toHaveAttribute("href", "/#ask-organizer");
|
||||
});
|
||||
|
||||
it("renders header and document from sessionStorage", () => {
|
||||
|
||||
@@ -73,9 +73,9 @@ describe("CreateFlowTopNav (behavioral tests)", () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Download Markdown", "markdown"],
|
||||
["Download PDF", "pdf"],
|
||||
["Download CSV", "csv"],
|
||||
["RULE.md", "markdown"],
|
||||
["PDF", "pdf"],
|
||||
["Print", "print"],
|
||||
] as const)(
|
||||
"opens export menu and calls onSelectExportFormat for %s",
|
||||
async (menuLabel, expectedFormat) => {
|
||||
@@ -245,14 +245,17 @@ describe("CreateFlowTopNav (viewport < sm2 / 440px)", () => {
|
||||
|
||||
expect(screen.getByRole("menuitem", { name: "Share" })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("menuitem", { name: "Download PDF" }),
|
||||
screen.getByRole("menuitem", { name: "PDF" }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("menuitem", { name: "Download CSV" }),
|
||||
screen.getByRole("menuitem", { name: "RULE.md" }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("menuitem", { name: "Download Markdown" }),
|
||||
screen.getByRole("menuitem", { name: "Print" }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole("menuitem", { name: "Download CSV" }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("menuitem", { name: "Edit" })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("menuitem", { name: "Save and exit" }),
|
||||
|
||||
@@ -110,6 +110,13 @@ describe("Footer (behavioral tests)", () => {
|
||||
expect(screen.queryByText(/all right reserved/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders the takeaway line to Ask an organizer", () => {
|
||||
render(<Footer />);
|
||||
expect(
|
||||
screen.getAllByRole("link", { name: "Tell us what this Rule changed" })[0],
|
||||
).toHaveAttribute("href", "/#ask-organizer");
|
||||
});
|
||||
|
||||
it("renders legal links to privacy and terms pages", () => {
|
||||
render(<Footer />);
|
||||
expect(
|
||||
|
||||
@@ -22,6 +22,14 @@ vi.mock("../../app/components/sections/ContentBanner", () => ({
|
||||
}));
|
||||
|
||||
describe("legal document pages", () => {
|
||||
test("privacy copy names Umami and cookieless counts", () => {
|
||||
const collect = messages.pages.privacy.sections.find(
|
||||
(section) => section.heading === "What we collect",
|
||||
);
|
||||
expect(collect?.paragraphs.join(" ")).toMatch(/Umami/);
|
||||
expect(collect?.paragraphs.join(" ")).toMatch(/sets no cookies/);
|
||||
});
|
||||
|
||||
test("privacy page covers hosting, recommendations, and campus privacy", () => {
|
||||
render(<PrivacyPage />);
|
||||
const page = messages.pages.privacy;
|
||||
|
||||
@@ -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