Let anyone finish a Rule without an account or email #119

Merged
an.di merged 2 commits from adilallo/fix/CR-380-guest-finish-without-account into main 2026-11-25 01:20:21 +00:00
16 changed files with 583 additions and 268 deletions

No files matched your search

+20 -59
View File
@@ -73,10 +73,6 @@ import {
CREATE_FLOW_COPIED_QUERY, CREATE_FLOW_COPIED_QUERY,
CREATE_FLOW_COPIED_VALUE, CREATE_FLOW_COPIED_VALUE,
} from "../../../lib/create/invitePaths"; } from "../../../lib/create/invitePaths";
import {
clearPendingKeepRuleLogin,
hasPendingKeepRuleLogin,
} from "../../../lib/create/pendingKeepRuleLogin";
import { runCompletedStepExit } from "./utils/runCompletedStepExit"; import { runCompletedStepExit } from "./utils/runCompletedStepExit";
import messages from "../../../messages/en/index"; import messages from "../../../messages/en/index";
import { import {
@@ -144,8 +140,8 @@ function CreateFlowSessionShell({ children }: { children: ReactNode }) {
const sessionResolved = sessionUser !== undefined; const sessionResolved = sessionUser !== undefined;
// Mirror in-progress draft to localStorage for ALL visitors once we know who // Mirror in-progress draft to localStorage for ALL visitors once we know who
// they are. Refresh-survival is the same UX for guest and signed-in users. // they are. Refresh-survival is the same UX for guest and signed-in users.
// Save & Exit: guests open the save-progress login modal; signed-in users // Save and exit is only for signed-in users (progress is already saved).
// PUT the server draft (`useCreateFlowExit`). // Guests keep Exit; Save your progress stays the optional community-save step.
const enableLocalDraftMirroring = sessionResolved; const enableLocalDraftMirroring = sessionResolved;
return ( return (
@@ -364,24 +360,7 @@ function CreateFlowLayoutContent({
if (!sessionResolved) return; if (!sessionResolved) return;
// Completed is post-publish. Guests still need Save & Exit → keep-this-rule
// login (the document is live but unclaimed). Signed-in users just leave.
if (currentStep === "completed") { if (currentStep === "completed") {
if (sessionUser === null) {
openLogin({
variant: "keepRule",
nextPath: CREATE_ROUTES.completed,
backdropVariant: "blurredYellow",
onDismiss: () => {
runCompletedStepExit({
clearState,
clearAnonymousCreateFlowStorage,
router,
});
},
});
return;
}
runCompletedStepExit({ runCompletedStepExit({
clearState, clearState,
clearAnonymousCreateFlowStorage, clearAnonymousCreateFlowStorage,
@@ -506,10 +485,13 @@ function CreateFlowLayoutContent({
* Still merge {@link methodSectionsPinsFromPublishedHydratePatch}: selections * Still merge {@link methodSectionsPinsFromPublishedHydratePatch}: selections
* may already match draft state while compact CardStack pins stayed false * may already match draft state while compact CardStack pins stayed false
* (pins are normally set only on facet **Confirm**). * (pins are normally set only on facet **Confirm**).
*
* An empty id with that same content is a finished edit. Writing the id
* back would make the next Finish update the old Rule.
*/ */
if ( if (
titleOk && titleOk &&
editingId === last.id && (editingId === last.id || editingId.length === 0) &&
sectionsClear && sectionsClear &&
!isPublishedRuleHydratePatchIncomplete(state, patch) !isPublishedRuleHydratePatchIncomplete(state, patch)
) { ) {
@@ -580,26 +562,6 @@ function CreateFlowLayoutContent({
setCompletedCopiedReady(Boolean(last?.copiedFromTitle)); setCompletedCopiedReady(Boolean(last?.copiedFromTitle));
}, [currentStep]); }, [currentStep]);
useEffect(() => {
if (currentStep !== "completed") return;
if (!sessionResolved) return;
if (sessionUser !== null) {
clearPendingKeepRuleLogin();
return;
}
if (!hasPendingKeepRuleLogin()) return;
const timeoutId = window.setTimeout(() => {
if (!hasPendingKeepRuleLogin()) return;
clearPendingKeepRuleLogin();
openLogin({
variant: "keepRule",
nextPath: CREATE_ROUTES.completed,
backdropVariant: "blurredYellow",
});
}, 0);
return () => window.clearTimeout(timeoutId);
}, [currentStep, sessionResolved, sessionUser, openLogin]);
const handleCommunitySaveMagicLinkSubmit = useCallback(async ( const handleCommunitySaveMagicLinkSubmit = useCallback(async (
formEl?: HTMLFormElement | null, formEl?: HTMLFormElement | null,
) => { ) => {
@@ -705,7 +667,7 @@ function CreateFlowLayoutContent({
const mainResponsiveLayout = `${mainMaxMdCross} ${mainMaxMdJustify} md:flex-row md:justify-center`; const mainResponsiveLayout = `${mainMaxMdCross} ${mainMaxMdJustify} md:flex-row md:justify-center`;
const saveDraftOnExit = const saveDraftOnExit =
shouldOfferCreateFlowSaveAndExit(currentStep, sessionUser) || shouldOfferCreateFlowSaveAndExit(currentStep, sessionUser) ||
isCreateTemplatesPickerRoute; (isCreateTemplatesPickerRoute && Boolean(sessionUser));
const proportionBarProgress = getProportionBarProgressForCreateFlowStep( const proportionBarProgress = getProportionBarProgressForCreateFlowStep(
currentStep, currentStep,
@@ -1275,6 +1237,18 @@ function CreateFlowLayoutContent({
disabled={isPublishing || !sessionResolved} disabled={isPublishing || !sessionResolved}
className={CREATE_FLOW_FOOTER_BUTTON_CLASS} className={CREATE_FLOW_FOOTER_BUTTON_CLASS}
onClick={() => { onClick={() => {
if (!sessionResolved) return;
if (sessionUser === null) {
openLogin({
variant: "invite",
nextPath:
createFlowStepPathWithSyncDraft(
"confirm-stakeholders",
),
backdropVariant: "blurredYellow",
});
return;
}
void handleFinalize({ skipInvites: false }); void handleFinalize({ skipInvites: false });
}} }}
> >
@@ -1293,8 +1267,7 @@ function CreateFlowLayoutContent({
isPublishing || isPublishing ||
(isEditRuleStep && !sessionResolved) || (isEditRuleStep && !sessionResolved) ||
(currentStep === "final-review" && (currentStep === "final-review" &&
(!sessionResolved || isFinalReviewContinueBlocked(state))
isFinalReviewContinueBlocked(state)))
} }
className={CREATE_FLOW_FOOTER_BUTTON_CLASS} className={CREATE_FLOW_FOOTER_BUTTON_CLASS}
onClick={() => { onClick={() => {
@@ -1304,18 +1277,6 @@ function CreateFlowLayoutContent({
} }
if (currentStep === "final-review") { if (currentStep === "final-review") {
if (isFinalReviewContinueBlocked(state)) return; if (isFinalReviewContinueBlocked(state)) return;
if (!sessionResolved) return;
if (sessionUser === null) {
openLogin({
variant: "invite",
nextPath:
createFlowStepPathWithSyncDraft(
"confirm-stakeholders",
),
backdropVariant: "blurredYellow",
});
return;
}
goToNextStep(); goToNextStep();
return; return;
} }
@@ -38,9 +38,9 @@ interface CreateFlowProviderProps {
* `create-flow-anonymous` in localStorage so refresh / dev-restart never wipes * `create-flow-anonymous` in localStorage so refresh / dev-restart never wipes
* progress. When false, in-memory only (e.g. unit tests, pre-session-resolve). * progress. When false, in-memory only (e.g. unit tests, pre-session-resolve).
* *
* Signed-in users additionally get an explicit "Save & Exit" that PUTs to the * Signed-in users additionally get an explicit "Save and exit" that PUTs to
* server (`useCreateFlowExit`); the server draft is the cross-device snapshot, * the server (`useCreateFlowExit`); the server draft is the cross-device
* localStorage is the on-every-keystroke buffer. * snapshot, localStorage is the on-every-keystroke buffer.
*/ */
enableLocalDraftMirroring?: boolean; enableLocalDraftMirroring?: boolean;
} }
@@ -8,16 +8,7 @@ import {
type ChangeEvent, type ChangeEvent,
type RefObject, type RefObject,
} from "react"; } from "react";
import { fetchAuthSession } from "../../../../lib/create/api"; import { COMMUNITY_AVATAR_ACCEPT } from "../../../../lib/create/createFlowUploadValidation";
import {
COMMUNITY_AVATAR_ACCEPT,
messageKeyForCreateFlowUploadReason,
validateCreateFlowUploadFile,
} from "../../../../lib/create/createFlowUploadValidation";
import {
clearPendingCommunityAvatarFile,
storePendingCommunityAvatarFile,
} from "../../../../lib/create/pendingCommunityAvatarUpload";
import { import {
createFlowUploadFailureMessageKey, createFlowUploadFailureMessageKey,
uploadCreateFlowFile, uploadCreateFlowFile,
@@ -30,8 +21,9 @@ function hasCommunityAvatarUrl(url: string | undefined): boolean {
} }
/** /**
* Pick and store a community logo for the create flow. Signed-in users upload * Pick and store a community logo for the create flow. Guests and signed-in
* immediately; guests keep the file in IndexedDB until they sign in. * users upload immediately (`POST /api/uploads` accepts `communityAvatar`
* without a session).
* *
* @example * @example
* const avatar = useCommunityAvatarUpload(); * const avatar = useCommunityAvatarUpload();
@@ -52,22 +44,11 @@ export function useCommunityAvatarUpload(): {
const tUpload = useTranslation("create.upload"); const tUpload = useTranslation("create.upload");
const { markCreateFlowInteraction, state, updateState } = useCreateFlow(); const { markCreateFlowInteraction, state, updateState } = useCreateFlow();
const fileInputRef = useRef<HTMLInputElement | null>(null); const fileInputRef = useRef<HTMLInputElement | null>(null);
const [signedIn, setSignedIn] = useState<boolean | null>(null);
const [localPreviewUrl, setLocalPreviewUrl] = useState<string | null>(null); const [localPreviewUrl, setLocalPreviewUrl] = useState<string | null>(null);
const [localFileName, setLocalFileName] = useState<string | null>(null); const [localFileName, setLocalFileName] = useState<string | null>(null);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null); const [errorMessage, setErrorMessage] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
void fetchAuthSession().then(({ user }) => {
if (!cancelled) setSignedIn(Boolean(user));
});
return () => {
cancelled = true;
};
}, []);
useEffect( useEffect(
() => () => { () => () => {
if (localPreviewUrl) URL.revokeObjectURL(localPreviewUrl); if (localPreviewUrl) URL.revokeObjectURL(localPreviewUrl);
@@ -104,61 +85,25 @@ export function useCommunityAvatarUpload(): {
if (!file) return; if (!file) return;
markCreateFlowInteraction(); markCreateFlowInteraction();
setErrorMessage(null); setErrorMessage(null);
setBusy(true);
if (signedIn === true) {
setBusy(true);
try {
const { url } = await uploadCreateFlowFile(file, "communityAvatar");
setLocalPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev);
return null;
});
setLocalFileName(file.name);
updateState({
communityAvatarUrl: url,
communityAvatarFileName: file.name,
});
} catch (err) {
setErrorMessage(resolveUploadError(err));
} finally {
setBusy(false);
}
return;
}
const validated = await validateCreateFlowUploadFile(
file,
"communityAvatar",
);
if (validated.ok === false) {
setErrorMessage(
validated.reason === "tooLarge"
? u.fileTooLarge
: tUpload(messageKeyForCreateFlowUploadReason(validated.reason)),
);
return;
}
try { try {
await storePendingCommunityAvatarFile(file); const { url } = await uploadCreateFlowFile(file, "communityAvatar");
setLocalPreviewUrl((prev) => { setLocalPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev); if (prev) URL.revokeObjectURL(prev);
return URL.createObjectURL(file); return null;
}); });
setLocalFileName(file.name); setLocalFileName(file.name);
updateState({ communityAvatarFileName: file.name }); updateState({
} catch { communityAvatarUrl: url,
await clearPendingCommunityAvatarFile().catch(() => undefined); communityAvatarFileName: file.name,
setErrorMessage(tUpload("errors.generic")); });
} catch (err) {
setErrorMessage(resolveUploadError(err));
} finally {
setBusy(false);
} }
}, },
[ [markCreateFlowInteraction, resolveUploadError, updateState],
markCreateFlowInteraction,
resolveUploadError,
signedIn,
tUpload,
u.fileTooLarge,
updateState,
],
); );
const handlePickFile = useCallback(() => { const handlePickFile = useCallback(() => {
+30 -35
View File
@@ -9,7 +9,6 @@ import {
updatePublishedRule, updatePublishedRule,
} from "../../../../lib/create/api"; } from "../../../../lib/create/api";
import { writeLastPublishedRule } from "../../../../lib/create/lastPublishedRule"; import { writeLastPublishedRule } from "../../../../lib/create/lastPublishedRule";
import { writePendingKeepRuleLogin } from "../../../../lib/create/pendingKeepRuleLogin";
import messages from "../../../../messages/en/index"; import messages from "../../../../messages/en/index";
import type { CreateFlowState } from "../types"; import type { CreateFlowState } from "../types";
import { import {
@@ -133,29 +132,14 @@ export function useCreateFlowFinalize({
? state.editingPublishedRuleId.trim() ? state.editingPublishedRuleId.trim()
: ""; : "";
if (editingId.length > 0 && sessionUser === null) {
setIsPublishing(false);
writeLastPublishedRule({
id: editingId,
title,
summary: summary ?? null,
document: ruleDocument,
});
updateState({ editingPublishedRuleId: undefined });
writePendingKeepRuleLogin();
onGuestPublished?.({ skippedInvites: false });
router.push(createFlowStepPath("completed"));
return;
}
if (editingId.length > 0) { if (editingId.length > 0) {
const updateResult = await updatePublishedRule(editingId, { const updateResult = await updatePublishedRule(editingId, {
title, title,
summary: summary ?? null, summary: summary ?? null,
document: ruleDocument, document: ruleDocument,
}); });
setIsPublishing(false);
if (updateResult.ok === true) { if (updateResult.ok === true) {
setIsPublishing(false);
writeLastPublishedRule({ writeLastPublishedRule({
id: editingId, id: editingId,
title, title,
@@ -163,28 +147,39 @@ export function useCreateFlowFinalize({
document: ruleDocument, document: ruleDocument,
}); });
updateState({ editingPublishedRuleId: undefined }); updateState({ editingPublishedRuleId: undefined });
void deleteServerDraftAfterPublish(); if (sessionUser === null) {
onGuestPublished?.({ skippedInvites: false });
} else {
void deleteServerDraftAfterPublish();
}
router.push(createFlowStepPath("completed")); router.push(createFlowStepPath("completed"));
return; return;
} }
if (updateResult.status === 401) { // A leftover id must not block a new Rule. This browser cannot update
openLogin({ // that id, so publish a new one instead of pretending the edit saved.
variant: sessionUser === null ? "keepRule" : "default", const guestCannotUpdate =
nextPath: sessionUser === null &&
sessionUser === null (updateResult.status === 401 ||
? createFlowStepPath("completed") updateResult.status === 403 ||
: loginReturnPath, updateResult.status === 404);
backdropVariant: "blurredYellow", if (!guestCannotUpdate) {
}); setIsPublishing(false);
if (updateResult.status === 401) {
openLogin({
variant: "default",
nextPath: loginReturnPath,
backdropVariant: "blurredYellow",
});
return;
}
showFailedBanner(
updateResult.error.trim() !== ""
? updateResult.error
: messages.create.reviewAndComplete.publish.genericPublishFailed,
false,
);
return; return;
} }
showFailedBanner(
updateResult.error.trim() !== ""
? updateResult.error
: messages.create.reviewAndComplete.publish.genericPublishFailed,
false,
);
return;
} }
const isGuest = sessionUser === null; const isGuest = sessionUser === null;
@@ -214,8 +209,8 @@ export function useCreateFlowFinalize({
? { finishedAt: publishResult.createdAt } ? { finishedAt: publishResult.createdAt }
: {}), : {}),
}); });
updateState({ editingPublishedRuleId: undefined });
if (isGuest) { if (isGuest) {
writePendingKeepRuleLogin();
onGuestPublished?.({ skippedInvites: skippedGuestInvites }); onGuestPublished?.({ skippedInvites: skippedGuestInvites });
} else { } else {
void deleteServerDraftAfterPublish(); void deleteServerDraftAfterPublish();
@@ -13,20 +13,17 @@ import { useCreateFlow } from "../../context/CreateFlowContext";
import { CreateFlowHeaderLockup } from "../../components/CreateFlowHeaderLockup"; import { CreateFlowHeaderLockup } from "../../components/CreateFlowHeaderLockup";
import { CreateFlowStepShell } from "../../components/CreateFlowStepShell"; import { CreateFlowStepShell } from "../../components/CreateFlowStepShell";
import { CREATE_FLOW_MD_UP_COLUMN_MAX_CLASS } from "../../components/createFlowLayoutTokens"; import { CREATE_FLOW_MD_UP_COLUMN_MAX_CLASS } from "../../components/createFlowLayoutTokens";
import { fetchAuthSession } from "../../../../../lib/create/api";
import { import {
createFlowUploadFailureMessageKey, createFlowUploadFailureMessageKey,
uploadCreateFlowFile, uploadCreateFlowFile,
} from "../../../../../lib/create/uploadToServer"; } from "../../../../../lib/create/uploadToServer";
import { import {
COMMUNITY_AVATAR_ACCEPT, COMMUNITY_AVATAR_ACCEPT,
messageKeyForCreateFlowUploadReason,
validateCreateFlowUploadFile, validateCreateFlowUploadFile,
} from "../../../../../lib/create/createFlowUploadValidation"; } from "../../../../../lib/create/createFlowUploadValidation";
import { import {
clearPendingCommunityAvatarFile, clearPendingCommunityAvatarFile,
readPendingCommunityAvatarFile, readPendingCommunityAvatarFile,
storePendingCommunityAvatarFile,
} from "../../../../../lib/create/pendingCommunityAvatarUpload"; } from "../../../../../lib/create/pendingCommunityAvatarUpload";
function hasCommunityAvatarUrl(url: string | undefined): boolean { function hasCommunityAvatarUrl(url: string | undefined): boolean {
@@ -41,22 +38,11 @@ export function CommunityUploadScreen() {
const tUpload = useTranslation("create.upload"); const tUpload = useTranslation("create.upload");
const fileInputRef = useRef<HTMLInputElement | null>(null); const fileInputRef = useRef<HTMLInputElement | null>(null);
const [signedIn, setSignedIn] = useState<boolean | null>(null);
const [localPreviewUrl, setLocalPreviewUrl] = useState<string | null>(null); const [localPreviewUrl, setLocalPreviewUrl] = useState<string | null>(null);
const [localFileName, setLocalFileName] = useState<string | null>(null); const [localFileName, setLocalFileName] = useState<string | null>(null);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null); const [errorMessage, setErrorMessage] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
void fetchAuthSession().then(({ user }) => {
if (!cancelled) setSignedIn(Boolean(user));
});
return () => {
cancelled = true;
};
}, []);
useEffect( useEffect(
() => () => { () => () => {
if (localPreviewUrl) URL.revokeObjectURL(localPreviewUrl); if (localPreviewUrl) URL.revokeObjectURL(localPreviewUrl);
@@ -133,60 +119,25 @@ export function CommunityUploadScreen() {
if (!file) return; if (!file) return;
markCreateFlowInteraction(); markCreateFlowInteraction();
setErrorMessage(null); setErrorMessage(null);
setBusy(true);
if (signedIn === true) {
setBusy(true);
try {
const { url } = await uploadCreateFlowFile(file, "communityAvatar");
setLocalPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev);
return null;
});
setLocalFileName(file.name);
updateState({
communityAvatarUrl: url,
communityAvatarFileName: file.name,
});
} catch (err) {
setErrorMessage(resolveUploadError(err));
} finally {
setBusy(false);
}
return;
}
const validated = await validateCreateFlowUploadFile(
file,
"communityAvatar",
);
if (validated.ok === false) {
setErrorMessage(
validated.reason === "tooLarge"
? u.fileTooLarge
: tUpload(messageKeyForCreateFlowUploadReason(validated.reason)),
);
return;
}
try { try {
await storePendingCommunityAvatarFile(file); const { url } = await uploadCreateFlowFile(file, "communityAvatar");
setLocalPreviewUrl((prev) => { setLocalPreviewUrl((prev) => {
if (prev) URL.revokeObjectURL(prev); if (prev) URL.revokeObjectURL(prev);
return URL.createObjectURL(file); return null;
}); });
setLocalFileName(file.name); setLocalFileName(file.name);
updateState({ communityAvatarFileName: file.name }); updateState({
} catch { communityAvatarUrl: url,
setErrorMessage(tUpload("errors.generic")); communityAvatarFileName: file.name,
});
} catch (err) {
setErrorMessage(resolveUploadError(err));
} finally {
setBusy(false);
} }
}, },
[ [markCreateFlowInteraction, resolveUploadError, updateState],
markCreateFlowInteraction,
resolveUploadError,
signedIn,
tUpload,
u.fileTooLarge,
updateState,
],
); );
const handlePickFile = useCallback(() => { const handlePickFile = useCallback(() => {
+1 -1
View File
@@ -299,7 +299,7 @@ export interface CreateFlowContextValue {
* *
* Current consumer: {@link SignedInDraftHydration} — when a signed-in user * Current consumer: {@link SignedInDraftHydration} — when a signed-in user
* has already started editing, we skip replaying their server draft on top * has already started editing, we skip replaying their server draft on top
* of in-progress local state. Save & Exit visibility is * of in-progress local state. Save and exit visibility is
* `shouldOfferCreateFlowSaveAndExit` in `utils/flowSteps.ts`, not this flag. * `shouldOfferCreateFlowSaveAndExit` in `utils/flowSteps.ts`, not this flag.
*/ */
interactionTouched: boolean; interactionTouched: boolean;
+7 -6
View File
@@ -189,23 +189,24 @@ export function getStepIndex(step: CreateFlowStep | null | undefined): number {
return FLOW_STEP_ORDER.indexOf(step); return FLOW_STEP_ORDER.indexOf(step);
} }
/** First wizard step that offers Save and exit (after the community is ready to keep). */ /** First wizard step that offers Save and exit once progress can actually be saved. */
const SAVE_EXIT_FROM_STEP_INDEX = getStepIndex("community-save"); const SAVE_EXIT_FROM_STEP_INDEX = getStepIndex("community-save");
/** /**
* Top-nav Save and exit (vs Exit). Guests and signed-in users share this from * Top-nav Save and exit (vs Exit). The header stays Exit until Save your
* `community-save` onward and on `edit-rule`. On completed, guests still * progress is done — a signed-in session. Guests (and session-in-flight)
* get Save and exit (claim/login); signed-in users get Exit (already owned). * keep Exit, including on completed and edit-rule.
* *
* @param sessionUser `null` is a guest. `undefined` (session in flight) is * @param sessionUser `null` is a guest. `undefined` (session in flight) is
* not a guest — completed stays Exit until the session resolves. * treated like a guest so the label does not flash Save and exit.
*/ */
export function shouldOfferCreateFlowSaveAndExit( export function shouldOfferCreateFlowSaveAndExit(
currentStep: CreateFlowStep | null | undefined, currentStep: CreateFlowStep | null | undefined,
sessionUser?: { id: string } | null, sessionUser?: { id: string } | null,
): boolean { ): boolean {
if (currentStep == null) return false; if (currentStep == null) return false;
if (currentStep === "completed") return sessionUser === null; if (!sessionUser) return false;
if (currentStep === "completed") return false;
if (currentStep === "edit-rule") return true; if (currentStep === "edit-rule") return true;
return getStepIndex(currentStep) >= SAVE_EXIT_FROM_STEP_INDEX; return getStepIndex(currentStep) >= SAVE_EXIT_FROM_STEP_INDEX;
} }
+14 -8
View File
@@ -8,6 +8,7 @@ import {
notFound, notFound,
unauthorized, unauthorized,
} from "../../../../lib/server/responses"; } from "../../../../lib/server/responses";
import { browserHoldsClaimForHash } from "../../../../lib/server/guestRuleClaim";
import { getReadablePublishedRule } from "../../../../lib/server/publishedRules"; import { getReadablePublishedRule } from "../../../../lib/server/publishedRules";
import { getSessionUser } from "../../../../lib/server/session"; import { getSessionUser } from "../../../../lib/server/session";
import { apiRoute } from "../../../../lib/server/apiRoute"; import { apiRoute } from "../../../../lib/server/apiRoute";
@@ -54,20 +55,25 @@ export const PATCH = apiRoute<RouteContext>(
} }
const user = await getSessionUser(); const user = await getSessionUser();
if (!user) {
return unauthorized();
}
const { id } = await context.params; const { id } = await context.params;
const row = await prisma.publishedRule.findUnique({ const row = await prisma.publishedRule.findUnique({
where: { id }, where: { id },
select: { id: true, userId: true }, select: { id: true, userId: true, claimTokenHash: true },
}); });
// This browser published the Rule and nobody has claimed it yet.
const claimUpdate =
row != null &&
row.userId == null &&
(await browserHoldsClaimForHash(row.claimTokenHash));
if (!row) { if (!row) {
return notFound(); return user ? notFound() : unauthorized();
} }
if (row.userId !== user.id) { if (!user && !claimUpdate) {
return unauthorized();
}
if (user && row.userId !== user.id && !claimUpdate) {
return forbidden("You do not have permission to update this rule"); return forbidden("You do not have permission to update this rule");
} }
@@ -95,7 +101,7 @@ export const PATCH = apiRoute<RouteContext>(
await linkUploadsToRule({ await linkUploadsToRule({
ruleId: row.id, ruleId: row.id,
document, document,
userId: user.id, userId: user?.id ?? null,
}); });
return NextResponse.json({ ok: true }); return NextResponse.json({ ok: true });
+5 -5
View File
@@ -62,7 +62,7 @@ The step persists **`stakeholderEmails`** on `CreateFlowState` (validated on `PU
### Fresh start vs continue draft (signed-in + sync) ### Fresh start vs continue draft (signed-in + sync)
**Established pattern:** **Create rule** in the header, on Home, and on Profile resumes the draft in the browser. It never wipes that draft or `DELETE`s `/api/drafts/me`. Starting over is the confirmed Delete on a Profile Draft card (or a later template-replace confirm). Both guests and signed-in people can **publish** (guests get an unlisted public `/rules/{id}` with no owner). Both see **Save & Exit** from `community-structure` onward (and `edit-rule`). On **`/create/completed`**, guests still get **Save & Exit** (keep-this-rule magic-link modal); signed-in users get **Exit**. Wizard guests open the save-progress magic-link modal; signed-in users may **PUT** `/api/drafts/me` when `NEXT_PUBLIC_ENABLE_BACKEND_SYNC=true`. **Established pattern:** **Create rule** in the header, on Home, and on Profile resumes the draft in the browser. It never wipes that draft or `DELETE`s `/api/drafts/me`. Starting over is the confirmed Delete on a Profile Draft card (or a later template-replace confirm). Both guests and signed-in people can **publish** (guests get an unlisted public `/rules/{id}` with no owner). The header reads **Exit** until Save your progress is done (a signed-in session); signed-in users see **Save and exit** from `community-save` onward and on `edit-rule`. Completed is **Exit** for everyone. No screen from the first step to the finished Rule requires a login or an email. Login is asked only when someone chooses it: Save your progress, Send invitations, Share, or Log in. Signed-in users may **PUT** `/api/drafts/me` when `NEXT_PUBLIC_ENABLE_BACKEND_SYNC=true`.
- **Create rule entry:** call [`createRuleEntryPath`](../app/(app)/create/utils/createRuleEntry.ts) and `router.push` that path. Do **not** call `prepareFreshCreateFlowEntry`. - **Create rule entry:** call [`createRuleEntryPath`](../app/(app)/create/utils/createRuleEntry.ts) and `router.push` that path. Do **not** call `prepareFreshCreateFlowEntry`.
- **Continue saved draft** (profile): do **not** call `prepareFreshCreateFlowEntry`. Write the server draft Profile already loaded into `create-flow-anonymous` and the core-value details key (see [`ProfilePageClient`](../app/(app)/profile/ProfilePageClient.tsx) `handleContinueDraft`), then navigate to **`/create/{savedStep}`**. The wizard reads that snapshot on mount, including when backend sync is off. Do not clear those keys and wait for a second fetch. - **Continue saved draft** (profile): do **not** call `prepareFreshCreateFlowEntry`. Write the server draft Profile already loaded into `create-flow-anonymous` and the core-value details key (see [`ProfilePageClient`](../app/(app)/profile/ProfilePageClient.tsx) `handleContinueDraft`), then navigate to **`/create/{savedStep}`**. The wizard reads that snapshot on mount, including when backend sync is off. Do not clear those keys and wait for a second fetch.
@@ -77,13 +77,13 @@ Call sites for **`createRuleEntryPath`**: [`Top.container.tsx`](../app/component
| Path | Purpose | | Path | Purpose |
| --- | --- | | --- | --- |
| `/create/review-template/[slug]` | Template preview in the create shell; uses the same layout/footer chrome as other create pages but **is not** part of `FLOW_STEP_ORDER` **or** the three Figma stages above. | | `/create/review-template/[slug]` | Template preview in the create shell; uses the same layout/footer chrome as other create pages but **is not** part of `FLOW_STEP_ORDER` **or** the three Figma stages above. |
| `/create/templates` | In-flow template catalog after review **Create from template**. Same create chrome (Back, Save & Exit); cards link to `/create/review-template/[slug]?fromFlow=1`. Marketing `/templates` stays the public catalog. | | `/create/templates` | In-flow template catalog after review **Create from template**. Same create chrome (Back, Exit until Save your progress is done); cards link to `/create/review-template/[slug]?fromFlow=1`. Marketing `/templates` stays the public catalog. |
From that page, **Customize** opens a dialog for name, optional logo, description (“What does your community do?”), and optional city or region. Continue prefills the template’s cards and values (via [`buildTemplateCustomizePrefill`](../lib/create/applyTemplatePrefill.ts) plus catalog copy from [`templatePresetDetailsFromPrefill`](../lib/create/applyTemplatePrefill.ts)), pins `pendingTemplateAction: { slug, mode: "customize" }`, and routes to **`/create/core-values`**. Size, kind, scale, maturity, and setup questions are skipped. The decks show the template’s cards first, then the rest of the deck, with no RECOMMENDED tag, no seven-card cut, and no engine call (`templateDeck` in [`deckRecommend.ts`](../lib/create/deckRecommend.ts)). Confirm on each deck walks communication → membership → decisions → conflict → final review. Back from values returns to template review; Back from named final review returns to the conflict deck. From that page, **Customize** opens a dialog for name, optional logo, description (“What does your community do?”), and optional city or region. Continue prefills the template’s cards and values (via [`buildTemplateCustomizePrefill`](../lib/create/applyTemplatePrefill.ts) plus catalog copy from [`templatePresetDetailsFromPrefill`](../lib/create/applyTemplatePrefill.ts)), pins `pendingTemplateAction: { slug, mode: "customize" }`, and routes to **`/create/core-values`**. Size, kind, scale, maturity, and setup questions are skipped. The decks show the template’s cards first, then the rest of the deck, with no RECOMMENDED tag, no seven-card cut, and no engine call (`templateDeck` in [`deckRecommend.ts`](../lib/create/deckRecommend.ts)). Confirm on each deck walks communication → membership → decisions → conflict → final review. Back from values returns to template review; Back from named final review returns to the conflict deck.
**Exit on template preview.** Direct catalog / marketing entry (`/create/review-template/[slug]` without `?fromFlow=1`) has nothing to save — top-nav **Exit** clears client state and goes home, with no save-progress modal and no leave confirm. In-flow (`?fromFlow=1`) still has community progress, so Exit keeps the usual save / leave-confirm path. **Exit on template preview.** Direct catalog / marketing entry (`/create/review-template/[slug]` without `?fromFlow=1`) has nothing to save — top-nav **Exit** clears client state and goes home, with no save-progress modal and no leave confirm. In-flow (`?fromFlow=1`) still has community progress, so Exit keeps the usual save / leave-confirm path.
**Use without changes** skips the dialog, seeds the template’s cards (chip ids from [`templateChips.json`](../data/templates/templateChips.json) plus `state.sections` titles), pins `pendingTemplateAction: { slug, mode: "useWithoutChanges" }`, and routes to **`/create/final-review`**. Direct catalog entry clears leftover identity so the Rule card can collect name, photo, and description. In-flow keeps the community answers already given. Continue on final review waits for a name, then opens **Invite your members**. Finishing there runs **`handleFinalize → publishRule`**. Guests can publish without signing in (`POST /api/rules` with `userId` null); stakeholder invites are sent only when a session exists. Every card that reads the group’s share uses three quarters (`LAUNCH_SUPERMAJORITY_SHARE`); final review does not ask for a share. **Use without changes** skips the dialog, seeds the template’s cards (chip ids from [`templateChips.json`](../data/templates/templateChips.json) plus `state.sections` titles), pins `pendingTemplateAction: { slug, mode: "useWithoutChanges" }`, and routes to **`/create/final-review`**. Direct catalog entry clears leftover identity so the Rule card can collect name, photo, and description. In-flow keeps the community answers already given. Continue on final review waits for a name, then opens **Invite your members** with no login. **Finish without inviting** publishes and shows the finished Rule. **Send invitations** while logged out opens **Log in to invite your members** and returns here after the link is followed. Guests can publish without signing in (`POST /api/rules` with `userId` null); stakeholder invites are sent only when a session exists. Every card that reads the group’s share uses three quarters (`LAUNCH_SUPERMAJORITY_SHARE`); final review does not ask for a share.
**The pin stays for the rest of the wizard** so decks skip the engine, final review shows Has Name Field, and Back knows the path. If a leftover pin lands on `/create/review`, [`CommunityReviewScreen`](../app/(app)/create/screens/review/CommunityReviewScreen.tsx) `replace`s to `core-values` (Customize) or `final-review` (Use without changes). **The pin stays for the rest of the wizard** so decks skip the engine, final review shows Has Name Field, and Back knows the path. If a leftover pin lands on `/create/review`, [`CommunityReviewScreen`](../app/(app)/create/screens/review/CommunityReviewScreen.tsx) `replace`s to `core-values` (Customize) or `final-review` (Use without changes).
@@ -111,8 +111,8 @@ Only one `?fromFlow=1` marker exists on template-review URLs. In-flow catalog cl
| Mode | Where progress lives | Save & Exit / publish | | Mode | Where progress lives | Save & Exit / publish |
| --- | --- | --- | | --- | --- | --- |
| **Anonymous** | `localStorage` key **`create-flow-anonymous`** | **Save & Exit** (from `community-structure` onward, plus `edit-rule`) opens the save-progress magic-link modal; after verify, optional **PUT** `/api/drafts/me` when `NEXT_PUBLIC_ENABLE_BACKEND_SYNC=true` (see Tickets 4–5 in [guides/backend-linear-tickets.md](guides/backend-linear-tickets.md)). **Publish** `POST`s `/api/rules` without a session (`userId` null) and sets httpOnly **`cr_rule_claim`**. Landing on **`/create/completed`** opens a **keep-this-rule** magic-link modal (no draft transfer); the top nav stays **Save & Exit** so they can reopen it (**Continue without saving** from that control leaves the flow). After Publish, skip on the auto-opened modal stays on completed. **Edit** shows when a last-published rule is in session storage. The public URL works; the row is omitted from `GET /api/rules` until claimed. Signing in on the same browser attaches `userId` (profile, edit, invites). | | **Anonymous** | `localStorage` key **`create-flow-anonymous`** | Header is **Exit**. **Save your progress** (`community-save`) is optional (**Skip for now** never comes back as a required step). **Publish** `POST`s `/api/rules` without a session (`userId` null) and sets httpOnly **`cr_rule_claim`**. Finishing changes to a Rule this browser published `PATCH`es that Rule while it is still unclaimed. If that update is refused, Finish publishes a new Rule. Completed is **Exit** with no login or email prompt; Print, PDF, and RULE.md work from that Rule. Signing in later on the same browser attaches `userId` (profile, invites, and later edits). **Send invitations** opens the invite login and returns to Invite your members after the link is followed. |
| **Signed-in** | In-memory React state in **`CreateFlowContext`** | **Save & Exit** from the **`community-structure`** step onward (and `edit-rule`) may **PUT** `/api/drafts/me` when sync is on. **Completed** is **Exit**. **Publish** stores the rule with **`userId`**. **Sign out** is on profile, not in the create top nav. | | **Signed-in** | In-memory React state in **`CreateFlowContext`** | **Save and exit** from **`community-save`** onward (and `edit-rule`) may **PUT** `/api/drafts/me` when sync is on. **Completed** is **Exit**. **Publish** stores the rule with **`userId`**. **Sign out** is on profile, not in the create top nav. |
Details and edge cases (conflict confirm, banners, `?syncDraft=1`) match **Ticket 4**, **Ticket 5**, and [`docs/guides/backend-roadmap.md`](guides/backend-roadmap.md) §12. Details and edge cases (conflict confirm, banners, `?syncDraft=1`) match **Ticket 4**, **Ticket 5**, and [`docs/guides/backend-roadmap.md`](guides/backend-roadmap.md) §12.
@@ -1,6 +1,6 @@
{ {
"title": "Write your community’s Rule", "title": "Write your community’s Rule",
"description": "Work through it together or on your own. Nothing is shared until you invite people, and you don’t need an account to start.", "description": "Work through it together or on your own. Nothing is shared until you invite people, and you don’t need an account to write or finish it.",
"steps": { "steps": {
"0": { "0": {
"title": "Tell us about your community" "title": "Tell us about your community"
@@ -0,0 +1,244 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom/vitest";
import CreateFlowLayoutClient from "../../app/(app)/create/CreateFlowLayoutClient";
import { CREATE_FLOW_ANONYMOUS_KEY } from "../../app/(app)/create/utils/anonymousDraftStorage";
import {
CREATE_FLOW_SYNC_DRAFT_QUERY,
CREATE_FLOW_SYNC_DRAFT_VALUE,
} from "../../app/(app)/create/utils/createFlowPaths";
import {
fetchAuthSession,
publishRule,
requestMagicLink,
} from "../../lib/create/api";
import { CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY } from "../../lib/create/pendingKeepRuleLogin";
import type { CreateFlowState } from "../../app/(app)/create/types";
import {
cleanup,
renderWithProviders as render,
screen,
waitFor,
} from "../utils/test-utils";
const nav = vi.hoisted(() => ({
pathname: "/create/final-review",
push: vi.fn(),
replace: vi.fn(),
}));
vi.mock("next/navigation", () => ({
useRouter: () => ({
push: nav.push,
replace: nav.replace,
prefetch: vi.fn(),
back: vi.fn(),
}),
usePathname: () => nav.pathname,
useSearchParams: () => new URLSearchParams(),
}));
vi.mock("../../lib/create/api", async (importOriginal) => {
const actual = await importOriginal<typeof import("../../lib/create/api")>();
return {
...actual,
fetchAuthSession: vi.fn(async () => ({ user: null })),
publishRule: vi.fn(async () => ({
ok: true as const,
id: "guest-rule-1",
title: "Oak Park Commons",
})),
requestMagicLink: vi.fn(async () => ({ ok: true as const })),
};
});
const readyToContinue: CreateFlowState = {
title: "Oak Park Commons",
selectedCommunicationMethodIds: ["signal"],
selectedMembershipMethodIds: ["open-admission"],
selectedDecisionApproachIds: ["lazy-consensus"],
selectedConflictManagementIds: ["conflict-ladder"],
communicationMethodDetailsById: {
signal: {
corePrinciple: "We talk in the open.",
logisticsAdmin: "Post in Signal.",
codeOfConduct: "No pile-ons.",
},
},
membershipMethodDetailsById: {
"open-admission": {
eligibility: "Anyone who shares the work.",
joiningProcess: "Show up.",
expectations: "Keep the keys.",
},
},
decisionApproachDetailsById: {
"lazy-consensus": {
corePrinciple: "Silence is assent.",
applicableScope: [],
selectedApplicableScope: [],
stepByStepInstructions: "Post the proposal.",
objectionsDeadlocks: "A named block stops it.",
},
},
conflictManagementDetailsById: {
"conflict-ladder": {
corePrinciple: "Start small.",
applicableScope: [],
selectedApplicableScope: [],
processProtocol: "Talk, then mediate.",
restorationFallbacks: "A panel if that fails.",
},
},
};
function seedDraft(state: CreateFlowState = readyToContinue) {
window.localStorage.setItem(CREATE_FLOW_ANONYMOUS_KEY, JSON.stringify(state));
}
function renderFlow() {
return render(
<CreateFlowLayoutClient>
<div>step</div>
</CreateFlowLayoutClient>,
);
}
describe("guest finish without an account", () => {
beforeEach(() => {
nav.pathname = "/create/final-review";
nav.push.mockReset();
nav.replace.mockReset();
vi.mocked(fetchAuthSession).mockResolvedValue({ user: null });
vi.mocked(publishRule).mockResolvedValue({
ok: true,
id: "guest-rule-1",
title: "Oak Park Commons",
});
vi.mocked(requestMagicLink).mockResolvedValue({ ok: true });
window.localStorage.clear();
sessionStorage.clear();
});
afterEach(() => {
cleanup();
window.localStorage.clear();
sessionStorage.clear();
});
it("keeps Exit on final review and continues to Invite your members without login", async () => {
const user = userEvent.setup();
seedDraft();
renderFlow();
expect(
await screen.findByRole("button", { name: "Exit" }),
).toBeInTheDocument();
expect(
screen.queryByRole("button", { name: "Save and exit" }),
).not.toBeInTheDocument();
const continueButton = await screen.findByRole("button", {
name: "Continue",
});
await waitFor(() => {
expect(continueButton).toBeEnabled();
});
await user.click(continueButton);
expect(
screen.queryByRole("heading", {
name: "Log in to invite your members",
}),
).not.toBeInTheDocument();
expect(nav.push).toHaveBeenCalledWith("/create/confirm-stakeholders");
});
it("opens the invite login from Send invitations and does not publish", async () => {
const user = userEvent.setup();
nav.pathname = "/create/confirm-stakeholders";
seedDraft();
renderFlow();
const sendInvitations = await screen.findByRole("button", {
name: "Send invitations",
});
await waitFor(() => {
expect(sendInvitations).toBeEnabled();
});
await user.click(sendInvitations);
expect(
await screen.findByRole("heading", {
name: "Log in to invite your members",
}),
).toBeInTheDocument();
expect(publishRule).not.toHaveBeenCalled();
expect(nav.push).not.toHaveBeenCalled();
});
it("finishes without inviting and does not ask for an email", async () => {
const user = userEvent.setup();
nav.pathname = "/create/confirm-stakeholders";
seedDraft();
renderFlow();
const finishWithoutInviting = await screen.findByRole("button", {
name: "Finish without inviting",
});
await waitFor(() => {
expect(finishWithoutInviting).toBeEnabled();
});
await user.click(finishWithoutInviting);
await waitFor(() => {
expect(publishRule).toHaveBeenCalled();
});
expect(
screen.queryByRole("heading", {
name: "Log in to invite your members",
}),
).not.toBeInTheDocument();
expect(
screen.queryByRole("heading", {
name: "Log in to keep this rule on your profile",
}),
).not.toBeInTheDocument();
expect(
sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY),
).toBeNull();
expect(nav.push).toHaveBeenCalledWith(
expect.stringMatching(/^\/create\/completed/),
);
});
it("asks the invite login to return to Invite your members after the link", async () => {
const user = userEvent.setup();
nav.pathname = "/create/confirm-stakeholders";
seedDraft();
renderFlow();
const sendInvitations = await screen.findByRole("button", {
name: "Send invitations",
});
await waitFor(() => {
expect(sendInvitations).toBeEnabled();
});
await user.click(sendInvitations);
expect(
await screen.findByRole("heading", {
name: "Log in to invite your members",
}),
).toBeInTheDocument();
const email = screen.getByRole("textbox", { name: /email address/i });
await user.type(email, "maya@example.org");
await user.click(screen.getByRole("button", { name: "Send login link" }));
expect(requestMagicLink).toHaveBeenCalledWith(
"maya@example.org",
`/create/confirm-stakeholders?${CREATE_FLOW_SYNC_DRAFT_QUERY}=${CREATE_FLOW_SYNC_DRAFT_VALUE}`,
expect.anything(),
);
});
});
+1 -1
View File
@@ -17,7 +17,7 @@ describe("InformationalScreen", () => {
render(<InformationalScreen />); render(<InformationalScreen />);
expect( expect(
screen.getByText( screen.getByText(
/Work through it together or on your own/i, /you don’t need an account to write or finish it/i,
), ),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
+47 -5
View File
@@ -12,7 +12,10 @@ import {
readPendingCommunityAvatarFile, readPendingCommunityAvatarFile,
storePendingCommunityAvatarFile, storePendingCommunityAvatarFile,
} from "../../lib/create/pendingCommunityAvatarUpload"; } from "../../lib/create/pendingCommunityAvatarUpload";
import { fetchAuthSession } from "../../lib/create/api"; import {
CreateFlowUploadValidationError,
uploadCreateFlowFile,
} from "../../lib/create/uploadToServer";
import messages from "../../messages/en/index"; import messages from "../../messages/en/index";
vi.mock("../../lib/create/pendingCommunityAvatarUpload", () => ({ vi.mock("../../lib/create/pendingCommunityAvatarUpload", () => ({
@@ -21,9 +24,14 @@ vi.mock("../../lib/create/pendingCommunityAvatarUpload", () => ({
clearPendingCommunityAvatarFile: vi.fn().mockResolvedValue(undefined), clearPendingCommunityAvatarFile: vi.fn().mockResolvedValue(undefined),
})); }));
vi.mock("../../lib/create/api", () => ({ vi.mock("../../lib/create/uploadToServer", async (importOriginal) => {
fetchAuthSession: vi.fn().mockResolvedValue({ user: null }), const actual =
})); await importOriginal<typeof import("../../lib/create/uploadToServer")>();
return {
...actual,
uploadCreateFlowFile: vi.fn(),
};
});
const pngBytes = Uint8Array.from( const pngBytes = Uint8Array.from(
Buffer.from( Buffer.from(
@@ -46,7 +54,7 @@ describe("CommunityUploadScreen", () => {
vi.mocked(readPendingCommunityAvatarFile).mockResolvedValue(null); vi.mocked(readPendingCommunityAvatarFile).mockResolvedValue(null);
vi.mocked(storePendingCommunityAvatarFile).mockResolvedValue(undefined); vi.mocked(storePendingCommunityAvatarFile).mockResolvedValue(undefined);
vi.mocked(clearPendingCommunityAvatarFile).mockResolvedValue(undefined); vi.mocked(clearPendingCommunityAvatarFile).mockResolvedValue(undefined);
vi.mocked(fetchAuthSession).mockResolvedValue({ user: null }); vi.mocked(uploadCreateFlowFile).mockReset();
Object.defineProperty(URL, "createObjectURL", { Object.defineProperty(URL, "createObjectURL", {
value: vi.fn(() => "blob:pending-avatar"), value: vi.fn(() => "blob:pending-avatar"),
writable: true, writable: true,
@@ -98,7 +106,35 @@ describe("CommunityUploadScreen", () => {
expect(screen.getByText("avatar.png")).toBeInTheDocument(); expect(screen.getByText("avatar.png")).toBeInTheDocument();
}); });
it("uploads a guest logo without signing in", async () => {
vi.mocked(uploadCreateFlowFile).mockResolvedValue({
url: "/api/uploads/guest-logo",
id: "11111111-1111-4111-8111-111111111111",
mimeType: "image/png",
byteLength: pngBytes.byteLength,
});
render(<CommunityUploadScreen />);
await screen.findByRole("heading", { name: copy.title });
fireEvent.change(fileInput(), {
target: {
files: [new File([pngBytes], "logo.png", { type: "image/png" })],
},
});
expect(await screen.findByText("logo.png")).toBeInTheDocument();
expect(uploadCreateFlowFile).toHaveBeenCalledWith(
expect.any(File),
"communityAvatar",
);
expect(storePendingCommunityAvatarFile).not.toHaveBeenCalled();
});
it("rejects an empty file with a clear error and does not stage it", async () => { it("rejects an empty file with a clear error and does not stage it", async () => {
vi.mocked(uploadCreateFlowFile).mockRejectedValue(
new CreateFlowUploadValidationError("empty"),
);
render(<CommunityUploadScreen />); render(<CommunityUploadScreen />);
await screen.findByRole("heading", { name: copy.title }); await screen.findByRole("heading", { name: copy.title });
@@ -113,6 +149,9 @@ describe("CommunityUploadScreen", () => {
}); });
it("rejects a text file renamed as PNG", async () => { it("rejects a text file renamed as PNG", async () => {
vi.mocked(uploadCreateFlowFile).mockRejectedValue(
new CreateFlowUploadValidationError("invalidType"),
);
render(<CommunityUploadScreen />); render(<CommunityUploadScreen />);
await screen.findByRole("heading", { name: copy.title }); await screen.findByRole("heading", { name: copy.title });
@@ -129,6 +168,9 @@ describe("CommunityUploadScreen", () => {
}); });
it("rejects SVG uploads", async () => { it("rejects SVG uploads", async () => {
vi.mocked(uploadCreateFlowFile).mockRejectedValue(
new CreateFlowUploadValidationError("svg"),
);
render(<CommunityUploadScreen />); render(<CommunityUploadScreen />);
await screen.findByRole("heading", { name: copy.title }); await screen.findByRole("heading", { name: copy.title });
+21 -7
View File
@@ -259,24 +259,38 @@ describe("flowSteps", () => {
expect(parseReviewReturnSearchParam(null)).toBeNull(); expect(parseReviewReturnSearchParam(null)).toBeNull();
}); });
it("offers Save and exit from community-save through final-review and on edit-rule", () => { it("offers Save and exit from community-save only after Save your progress", () => {
expect(shouldOfferCreateFlowSaveAndExit("informational")).toBe(false); expect(shouldOfferCreateFlowSaveAndExit("informational")).toBe(false);
expect(shouldOfferCreateFlowSaveAndExit("community-name")).toBe(false); expect(shouldOfferCreateFlowSaveAndExit("community-name")).toBe(false);
expect(shouldOfferCreateFlowSaveAndExit("community-structure")).toBe(false); expect(shouldOfferCreateFlowSaveAndExit("community-structure")).toBe(false);
expect(shouldOfferCreateFlowSaveAndExit("setup-questions")).toBe(false); expect(shouldOfferCreateFlowSaveAndExit("setup-questions")).toBe(false);
expect(shouldOfferCreateFlowSaveAndExit("community-upload")).toBe(false); expect(shouldOfferCreateFlowSaveAndExit("community-upload")).toBe(false);
expect(shouldOfferCreateFlowSaveAndExit("community-save")).toBe(true); expect(shouldOfferCreateFlowSaveAndExit("community-save")).toBe(false);
expect(shouldOfferCreateFlowSaveAndExit("review")).toBe(true); expect(shouldOfferCreateFlowSaveAndExit("community-save", null)).toBe(
expect(shouldOfferCreateFlowSaveAndExit("final-review")).toBe(true); false,
expect(shouldOfferCreateFlowSaveAndExit("edit-rule")).toBe(true); );
expect(shouldOfferCreateFlowSaveAndExit("final-review", null)).toBe(false);
expect(shouldOfferCreateFlowSaveAndExit("edit-rule", null)).toBe(false);
expect(
shouldOfferCreateFlowSaveAndExit("community-save", { id: "user-1" }),
).toBe(true);
expect(
shouldOfferCreateFlowSaveAndExit("review", { id: "user-1" }),
).toBe(true);
expect(
shouldOfferCreateFlowSaveAndExit("final-review", { id: "user-1" }),
).toBe(true);
expect(
shouldOfferCreateFlowSaveAndExit("edit-rule", { id: "user-1" }),
).toBe(true);
}); });
it("offers Save & Exit on completed only for guests", () => { it("keeps Exit on completed for guests and signed-in users", () => {
expect(shouldOfferCreateFlowSaveAndExit("completed")).toBe(false); expect(shouldOfferCreateFlowSaveAndExit("completed")).toBe(false);
expect( expect(
shouldOfferCreateFlowSaveAndExit("completed", { id: "user-1" }), shouldOfferCreateFlowSaveAndExit("completed", { id: "user-1" }),
).toBe(false); ).toBe(false);
expect(shouldOfferCreateFlowSaveAndExit("completed", null)).toBe(true); expect(shouldOfferCreateFlowSaveAndExit("completed", null)).toBe(false);
expect(shouldOfferCreateFlowSaveAndExit(null)).toBe(false); expect(shouldOfferCreateFlowSaveAndExit(null)).toBe(false);
}); });
+100 -5
View File
@@ -109,6 +109,9 @@ describe("useCreateFlowFinalize", () => {
sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY), sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY),
).toBeNull(); ).toBeNull();
expect(deleteServerDraft).toHaveBeenCalledTimes(1); expect(deleteServerDraft).toHaveBeenCalledTimes(1);
expect(updateState).toHaveBeenCalledWith({
editingPublishedRuleId: undefined,
});
}); });
it("retries clearing the server draft when the first delete fails", async () => { it("retries clearing the server draft when the first delete fails", async () => {
@@ -192,7 +195,7 @@ describe("useCreateFlowFinalize", () => {
}); });
expect(onGuestPublished).toHaveBeenCalledWith({ skippedInvites: true }); expect(onGuestPublished).toHaveBeenCalledWith({ skippedInvites: true });
expect(openLogin).not.toHaveBeenCalled(); expect(openLogin).not.toHaveBeenCalled();
expect(sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY)).toBe("1"); expect(sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY)).toBeNull();
expect(router.push).toHaveBeenCalledWith( expect(router.push).toHaveBeenCalledWith(
`/create/completed?${CREATE_FLOW_COMPLETED_CELEBRATE_QUERY}=${CREATE_FLOW_COMPLETED_CELEBRATE_VALUE}`, `/create/completed?${CREATE_FLOW_COMPLETED_CELEBRATE_QUERY}=${CREATE_FLOW_COMPLETED_CELEBRATE_VALUE}`,
); );
@@ -304,7 +307,7 @@ describe("useCreateFlowFinalize", () => {
}); });
expect(onGuestPublished).toHaveBeenCalledWith({ skippedInvites: false }); expect(onGuestPublished).toHaveBeenCalledWith({ skippedInvites: false });
expect(openLogin).not.toHaveBeenCalled(); expect(openLogin).not.toHaveBeenCalled();
expect(sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY)).toBe("1"); expect(sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY)).toBeNull();
expect(router.push).toHaveBeenCalledWith( expect(router.push).toHaveBeenCalledWith(
`/create/completed?${CREATE_FLOW_COMPLETED_CELEBRATE_QUERY}=${CREATE_FLOW_COMPLETED_CELEBRATE_VALUE}`, `/create/completed?${CREATE_FLOW_COMPLETED_CELEBRATE_QUERY}=${CREATE_FLOW_COMPLETED_CELEBRATE_VALUE}`,
); );
@@ -450,7 +453,9 @@ describe("useCreateFlowFinalize", () => {
}); });
}); });
it("does not PATCH when a guest publishes an already-published rule", async () => { it("PATCHes when a guest finishes an edit of a rule this browser published", async () => {
vi.mocked(updatePublishedRule).mockResolvedValue({ ok: true });
const { result } = renderHook(() => const { result } = renderHook(() =>
useCreateFlowFinalize({ useCreateFlowFinalize({
state: { state: {
@@ -470,8 +475,16 @@ describe("useCreateFlowFinalize", () => {
await result.current.finalize(); await result.current.finalize();
}); });
expect(updatePublishedRule).not.toHaveBeenCalled(); expect(updatePublishedRule).toHaveBeenCalledWith(
"guest-rule-1",
expect.objectContaining({
title: "Published title",
summary: "Published summary",
document: {},
}),
);
expect(publishRule).not.toHaveBeenCalled(); expect(publishRule).not.toHaveBeenCalled();
expect(deleteServerDraft).not.toHaveBeenCalled();
expect(openLogin).not.toHaveBeenCalled(); expect(openLogin).not.toHaveBeenCalled();
expect(onGuestPublished).toHaveBeenCalledWith({ skippedInvites: false }); expect(onGuestPublished).toHaveBeenCalledWith({ skippedInvites: false });
expect(writeLastPublishedRule).toHaveBeenCalledWith({ expect(writeLastPublishedRule).toHaveBeenCalledWith({
@@ -480,10 +493,92 @@ describe("useCreateFlowFinalize", () => {
summary: "Published summary", summary: "Published summary",
document: {}, document: {},
}); });
expect(sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY)).toBe("1"); expect(updateState).toHaveBeenCalledWith({
editingPublishedRuleId: undefined,
});
expect(sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY)).toBeNull();
expect(router.push).toHaveBeenCalledWith("/create/completed"); expect(router.push).toHaveBeenCalledWith("/create/completed");
}); });
it("publishes a new rule when a guest cannot update the leftover id", async () => {
vi.mocked(updatePublishedRule).mockResolvedValue({
ok: false,
error: "Unauthorized",
status: 401,
});
vi.mocked(publishRule).mockResolvedValue({
ok: true,
id: "new-guest-rule",
title: "Published title",
});
const { result } = renderHook(() =>
useCreateFlowFinalize({
state: {
...emptyState,
editingPublishedRuleId: "stale-rule",
},
router,
openLogin,
updateState,
loginReturnPath: "/create/final-review?syncDraft=1",
sessionUser: null,
onGuestPublished,
}),
);
await act(async () => {
await result.current.finalize();
});
expect(updatePublishedRule).toHaveBeenCalledWith(
"stale-rule",
expect.anything(),
);
expect(publishRule).toHaveBeenCalled();
expect(openLogin).not.toHaveBeenCalled();
expect(writeLastPublishedRule).toHaveBeenCalledWith(
expect.objectContaining({ id: "new-guest-rule" }),
);
expect(updateState).toHaveBeenCalledWith({
editingPublishedRuleId: undefined,
});
expect(router.push).toHaveBeenCalledWith(
`/create/completed?${CREATE_FLOW_COMPLETED_CELEBRATE_QUERY}=${CREATE_FLOW_COMPLETED_CELEBRATE_VALUE}`,
);
});
it("does not publish a second rule when a guest update fails on the server", async () => {
vi.mocked(updatePublishedRule).mockResolvedValue({
ok: false,
error: "Database unavailable",
status: 500,
});
const { result } = renderHook(() =>
useCreateFlowFinalize({
state: {
...emptyState,
editingPublishedRuleId: "guest-rule-1",
},
router,
openLogin,
updateState,
loginReturnPath: "/create/final-review?syncDraft=1",
sessionUser: null,
onGuestPublished,
}),
);
await act(async () => {
await result.current.finalize();
});
expect(publishRule).not.toHaveBeenCalled();
expect(router.push).not.toHaveBeenCalled();
expect(result.current.publishBannerMessage).toBe("Database unavailable");
});
it("opens keepRule login when a guest publish is unauthorized", async () => { it("opens keepRule login when a guest publish is unauthorized", async () => {
vi.mocked(publishRule).mockResolvedValue({ vi.mocked(publishRule).mockResolvedValue({
ok: false, ok: false,
+61
View File
@@ -5,6 +5,7 @@ const isDatabaseConfiguredMock = vi.fn();
const findUniqueMock = vi.fn(); const findUniqueMock = vi.fn();
const updateMock = vi.fn(); const updateMock = vi.fn();
const getSessionUserMock = vi.fn(); const getSessionUserMock = vi.fn();
const browserHoldsClaimForHashMock = vi.fn();
vi.mock("../../lib/server/env", () => ({ vi.mock("../../lib/server/env", () => ({
isDatabaseConfigured: () => isDatabaseConfiguredMock(), isDatabaseConfigured: () => isDatabaseConfiguredMock(),
@@ -23,22 +24,37 @@ vi.mock("../../lib/server/session", () => ({
getSessionUser: () => getSessionUserMock(), getSessionUser: () => getSessionUserMock(),
})); }));
vi.mock("../../lib/server/guestRuleClaim", () => ({
browserHoldsClaimForHash: (...args: unknown[]) =>
browserHoldsClaimForHashMock(...args),
}));
vi.mock("../../lib/server/uploads/linkUploads", () => ({ vi.mock("../../lib/server/uploads/linkUploads", () => ({
linkUploadsToRule: vi.fn().mockResolvedValue(undefined), linkUploadsToRule: vi.fn().mockResolvedValue(undefined),
})); }));
import { PATCH } from "../../app/api/rules/[id]/route"; import { PATCH } from "../../app/api/rules/[id]/route";
import { linkUploadsToRule } from "../../lib/server/uploads/linkUploads";
function makeContext(id: string) { function makeContext(id: string) {
return { params: Promise.resolve({ id }) }; return { params: Promise.resolve({ id }) };
} }
const patchBody = {
title: "Updated",
summary: "Context",
document: { sections: [], coreValues: [] },
};
beforeEach(() => { beforeEach(() => {
isDatabaseConfiguredMock.mockReset(); isDatabaseConfiguredMock.mockReset();
findUniqueMock.mockReset(); findUniqueMock.mockReset();
updateMock.mockReset(); updateMock.mockReset();
getSessionUserMock.mockReset(); getSessionUserMock.mockReset();
browserHoldsClaimForHashMock.mockReset();
vi.mocked(linkUploadsToRule).mockClear();
getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" }); getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" });
browserHoldsClaimForHashMock.mockResolvedValue(false);
}); });
describe("PATCH /api/rules/[id]", () => { describe("PATCH /api/rules/[id]", () => {
@@ -114,4 +130,49 @@ describe("PATCH /api/rules/[id]", () => {
}), }),
); );
}); });
it("updates an unclaimed rule when this browser holds the claim", async () => {
isDatabaseConfiguredMock.mockReturnValue(true);
getSessionUserMock.mockResolvedValueOnce(null);
browserHoldsClaimForHashMock.mockResolvedValueOnce(true);
findUniqueMock.mockResolvedValueOnce({
id: "r1",
userId: null,
claimTokenHash: "claim-hash",
});
updateMock.mockResolvedValueOnce({});
const res = await PATCH(
new NextRequest("https://x.test/api/rules/r1", {
method: "PATCH",
body: JSON.stringify(patchBody),
}),
makeContext("r1"),
);
expect(res.status).toBe(200);
expect(browserHoldsClaimForHashMock).toHaveBeenCalledWith("claim-hash");
expect(updateMock).toHaveBeenCalled();
expect(linkUploadsToRule).toHaveBeenCalledWith(
expect.objectContaining({ ruleId: "r1", userId: null }),
);
});
it("returns 401 when a guest does not hold the claim", async () => {
isDatabaseConfiguredMock.mockReturnValue(true);
getSessionUserMock.mockResolvedValueOnce(null);
browserHoldsClaimForHashMock.mockResolvedValueOnce(false);
findUniqueMock.mockResolvedValueOnce({
id: "r1",
userId: null,
claimTokenHash: "claim-hash",
});
const res = await PATCH(
new NextRequest("https://x.test/api/rules/r1", {
method: "PATCH",
body: JSON.stringify(patchBody),
}),
makeContext("r1"),
);
expect(res.status).toBe(401);
expect(updateMock).not.toHaveBeenCalled();
});
}); });