diff --git a/app/(app)/create/CreateFlowLayoutClient.tsx b/app/(app)/create/CreateFlowLayoutClient.tsx index 9ef3388..5b73d0f 100644 --- a/app/(app)/create/CreateFlowLayoutClient.tsx +++ b/app/(app)/create/CreateFlowLayoutClient.tsx @@ -73,10 +73,6 @@ import { CREATE_FLOW_COPIED_QUERY, CREATE_FLOW_COPIED_VALUE, } from "../../../lib/create/invitePaths"; -import { - clearPendingKeepRuleLogin, - hasPendingKeepRuleLogin, -} from "../../../lib/create/pendingKeepRuleLogin"; import { runCompletedStepExit } from "./utils/runCompletedStepExit"; import messages from "../../../messages/en/index"; import { @@ -144,8 +140,8 @@ function CreateFlowSessionShell({ children }: { children: ReactNode }) { const sessionResolved = sessionUser !== undefined; // 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. - // Save & Exit: guests open the save-progress login modal; signed-in users - // PUT the server draft (`useCreateFlowExit`). + // Save and exit is only for signed-in users (progress is already saved). + // Guests keep Exit; Save your progress stays the optional community-save step. const enableLocalDraftMirroring = sessionResolved; return ( @@ -364,24 +360,7 @@ function CreateFlowLayoutContent({ 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 (sessionUser === null) { - openLogin({ - variant: "keepRule", - nextPath: CREATE_ROUTES.completed, - backdropVariant: "blurredYellow", - onDismiss: () => { - runCompletedStepExit({ - clearState, - clearAnonymousCreateFlowStorage, - router, - }); - }, - }); - return; - } runCompletedStepExit({ clearState, clearAnonymousCreateFlowStorage, @@ -506,10 +485,13 @@ function CreateFlowLayoutContent({ * Still merge {@link methodSectionsPinsFromPublishedHydratePatch}: selections * may already match draft state while compact CardStack pins stayed false * (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 ( titleOk && - editingId === last.id && + (editingId === last.id || editingId.length === 0) && sectionsClear && !isPublishedRuleHydratePatchIncomplete(state, patch) ) { @@ -580,26 +562,6 @@ function CreateFlowLayoutContent({ setCompletedCopiedReady(Boolean(last?.copiedFromTitle)); }, [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 ( formEl?: HTMLFormElement | null, ) => { @@ -705,7 +667,7 @@ function CreateFlowLayoutContent({ const mainResponsiveLayout = `${mainMaxMdCross} ${mainMaxMdJustify} md:flex-row md:justify-center`; const saveDraftOnExit = shouldOfferCreateFlowSaveAndExit(currentStep, sessionUser) || - isCreateTemplatesPickerRoute; + (isCreateTemplatesPickerRoute && Boolean(sessionUser)); const proportionBarProgress = getProportionBarProgressForCreateFlowStep( currentStep, @@ -1275,6 +1237,18 @@ function CreateFlowLayoutContent({ disabled={isPublishing || !sessionResolved} className={CREATE_FLOW_FOOTER_BUTTON_CLASS} onClick={() => { + if (!sessionResolved) return; + if (sessionUser === null) { + openLogin({ + variant: "invite", + nextPath: + createFlowStepPathWithSyncDraft( + "confirm-stakeholders", + ), + backdropVariant: "blurredYellow", + }); + return; + } void handleFinalize({ skipInvites: false }); }} > @@ -1293,8 +1267,7 @@ function CreateFlowLayoutContent({ isPublishing || (isEditRuleStep && !sessionResolved) || (currentStep === "final-review" && - (!sessionResolved || - isFinalReviewContinueBlocked(state))) + isFinalReviewContinueBlocked(state)) } className={CREATE_FLOW_FOOTER_BUTTON_CLASS} onClick={() => { @@ -1304,18 +1277,6 @@ function CreateFlowLayoutContent({ } if (currentStep === "final-review") { if (isFinalReviewContinueBlocked(state)) return; - if (!sessionResolved) return; - if (sessionUser === null) { - openLogin({ - variant: "invite", - nextPath: - createFlowStepPathWithSyncDraft( - "confirm-stakeholders", - ), - backdropVariant: "blurredYellow", - }); - return; - } goToNextStep(); return; } diff --git a/app/(app)/create/context/CreateFlowContext.tsx b/app/(app)/create/context/CreateFlowContext.tsx index 17af270..73ff4d2 100644 --- a/app/(app)/create/context/CreateFlowContext.tsx +++ b/app/(app)/create/context/CreateFlowContext.tsx @@ -38,9 +38,9 @@ interface CreateFlowProviderProps { * `create-flow-anonymous` in localStorage so refresh / dev-restart never wipes * 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 - * server (`useCreateFlowExit`); the server draft is the cross-device snapshot, - * localStorage is the on-every-keystroke buffer. + * Signed-in users additionally get an explicit "Save and exit" that PUTs to + * the server (`useCreateFlowExit`); the server draft is the cross-device + * snapshot, localStorage is the on-every-keystroke buffer. */ enableLocalDraftMirroring?: boolean; } diff --git a/app/(app)/create/hooks/useCommunityAvatarUpload.ts b/app/(app)/create/hooks/useCommunityAvatarUpload.ts index 8121ef7..cbdcbf4 100644 --- a/app/(app)/create/hooks/useCommunityAvatarUpload.ts +++ b/app/(app)/create/hooks/useCommunityAvatarUpload.ts @@ -8,16 +8,7 @@ import { type ChangeEvent, type RefObject, } from "react"; -import { fetchAuthSession } from "../../../../lib/create/api"; -import { - COMMUNITY_AVATAR_ACCEPT, - messageKeyForCreateFlowUploadReason, - validateCreateFlowUploadFile, -} from "../../../../lib/create/createFlowUploadValidation"; -import { - clearPendingCommunityAvatarFile, - storePendingCommunityAvatarFile, -} from "../../../../lib/create/pendingCommunityAvatarUpload"; +import { COMMUNITY_AVATAR_ACCEPT } from "../../../../lib/create/createFlowUploadValidation"; import { createFlowUploadFailureMessageKey, 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 - * immediately; guests keep the file in IndexedDB until they sign in. + * Pick and store a community logo for the create flow. Guests and signed-in + * users upload immediately (`POST /api/uploads` accepts `communityAvatar` + * without a session). * * @example * const avatar = useCommunityAvatarUpload(); @@ -52,22 +44,11 @@ export function useCommunityAvatarUpload(): { const tUpload = useTranslation("create.upload"); const { markCreateFlowInteraction, state, updateState } = useCreateFlow(); const fileInputRef = useRef(null); - const [signedIn, setSignedIn] = useState(null); const [localPreviewUrl, setLocalPreviewUrl] = useState(null); const [localFileName, setLocalFileName] = useState(null); const [busy, setBusy] = useState(false); const [errorMessage, setErrorMessage] = useState(null); - useEffect(() => { - let cancelled = false; - void fetchAuthSession().then(({ user }) => { - if (!cancelled) setSignedIn(Boolean(user)); - }); - return () => { - cancelled = true; - }; - }, []); - useEffect( () => () => { if (localPreviewUrl) URL.revokeObjectURL(localPreviewUrl); @@ -104,61 +85,25 @@ export function useCommunityAvatarUpload(): { if (!file) return; markCreateFlowInteraction(); setErrorMessage(null); - - 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; - } + setBusy(true); try { - await storePendingCommunityAvatarFile(file); + const { url } = await uploadCreateFlowFile(file, "communityAvatar"); setLocalPreviewUrl((prev) => { if (prev) URL.revokeObjectURL(prev); - return URL.createObjectURL(file); + return null; }); setLocalFileName(file.name); - updateState({ communityAvatarFileName: file.name }); - } catch { - await clearPendingCommunityAvatarFile().catch(() => undefined); - setErrorMessage(tUpload("errors.generic")); + updateState({ + communityAvatarUrl: url, + communityAvatarFileName: file.name, + }); + } catch (err) { + setErrorMessage(resolveUploadError(err)); + } finally { + setBusy(false); } }, - [ - markCreateFlowInteraction, - resolveUploadError, - signedIn, - tUpload, - u.fileTooLarge, - updateState, - ], + [markCreateFlowInteraction, resolveUploadError, updateState], ); const handlePickFile = useCallback(() => { diff --git a/app/(app)/create/hooks/useCreateFlowFinalize.ts b/app/(app)/create/hooks/useCreateFlowFinalize.ts index c9691b6..64b476f 100644 --- a/app/(app)/create/hooks/useCreateFlowFinalize.ts +++ b/app/(app)/create/hooks/useCreateFlowFinalize.ts @@ -9,7 +9,6 @@ import { updatePublishedRule, } from "../../../../lib/create/api"; import { writeLastPublishedRule } from "../../../../lib/create/lastPublishedRule"; -import { writePendingKeepRuleLogin } from "../../../../lib/create/pendingKeepRuleLogin"; import messages from "../../../../messages/en/index"; import type { CreateFlowState } from "../types"; import { @@ -133,29 +132,14 @@ export function useCreateFlowFinalize({ ? 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) { const updateResult = await updatePublishedRule(editingId, { title, summary: summary ?? null, document: ruleDocument, }); - setIsPublishing(false); if (updateResult.ok === true) { + setIsPublishing(false); writeLastPublishedRule({ id: editingId, title, @@ -163,28 +147,39 @@ export function useCreateFlowFinalize({ document: ruleDocument, }); updateState({ editingPublishedRuleId: undefined }); - void deleteServerDraftAfterPublish(); + if (sessionUser === null) { + onGuestPublished?.({ skippedInvites: false }); + } else { + void deleteServerDraftAfterPublish(); + } router.push(createFlowStepPath("completed")); return; } - if (updateResult.status === 401) { - openLogin({ - variant: sessionUser === null ? "keepRule" : "default", - nextPath: - sessionUser === null - ? createFlowStepPath("completed") - : loginReturnPath, - backdropVariant: "blurredYellow", - }); + // A leftover id must not block a new Rule. This browser cannot update + // that id, so publish a new one instead of pretending the edit saved. + const guestCannotUpdate = + sessionUser === null && + (updateResult.status === 401 || + updateResult.status === 403 || + updateResult.status === 404); + 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; } - showFailedBanner( - updateResult.error.trim() !== "" - ? updateResult.error - : messages.create.reviewAndComplete.publish.genericPublishFailed, - false, - ); - return; } const isGuest = sessionUser === null; @@ -214,8 +209,8 @@ export function useCreateFlowFinalize({ ? { finishedAt: publishResult.createdAt } : {}), }); + updateState({ editingPublishedRuleId: undefined }); if (isGuest) { - writePendingKeepRuleLogin(); onGuestPublished?.({ skippedInvites: skippedGuestInvites }); } else { void deleteServerDraftAfterPublish(); diff --git a/app/(app)/create/screens/upload/CommunityUploadScreen.tsx b/app/(app)/create/screens/upload/CommunityUploadScreen.tsx index abe9340..9d59ded 100644 --- a/app/(app)/create/screens/upload/CommunityUploadScreen.tsx +++ b/app/(app)/create/screens/upload/CommunityUploadScreen.tsx @@ -13,20 +13,17 @@ import { useCreateFlow } from "../../context/CreateFlowContext"; import { CreateFlowHeaderLockup } from "../../components/CreateFlowHeaderLockup"; import { CreateFlowStepShell } from "../../components/CreateFlowStepShell"; import { CREATE_FLOW_MD_UP_COLUMN_MAX_CLASS } from "../../components/createFlowLayoutTokens"; -import { fetchAuthSession } from "../../../../../lib/create/api"; import { createFlowUploadFailureMessageKey, uploadCreateFlowFile, } from "../../../../../lib/create/uploadToServer"; import { COMMUNITY_AVATAR_ACCEPT, - messageKeyForCreateFlowUploadReason, validateCreateFlowUploadFile, } from "../../../../../lib/create/createFlowUploadValidation"; import { clearPendingCommunityAvatarFile, readPendingCommunityAvatarFile, - storePendingCommunityAvatarFile, } from "../../../../../lib/create/pendingCommunityAvatarUpload"; function hasCommunityAvatarUrl(url: string | undefined): boolean { @@ -41,22 +38,11 @@ export function CommunityUploadScreen() { const tUpload = useTranslation("create.upload"); const fileInputRef = useRef(null); - const [signedIn, setSignedIn] = useState(null); const [localPreviewUrl, setLocalPreviewUrl] = useState(null); const [localFileName, setLocalFileName] = useState(null); const [busy, setBusy] = useState(false); const [errorMessage, setErrorMessage] = useState(null); - useEffect(() => { - let cancelled = false; - void fetchAuthSession().then(({ user }) => { - if (!cancelled) setSignedIn(Boolean(user)); - }); - return () => { - cancelled = true; - }; - }, []); - useEffect( () => () => { if (localPreviewUrl) URL.revokeObjectURL(localPreviewUrl); @@ -133,60 +119,25 @@ export function CommunityUploadScreen() { if (!file) return; markCreateFlowInteraction(); setErrorMessage(null); - - 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; - } + setBusy(true); try { - await storePendingCommunityAvatarFile(file); + const { url } = await uploadCreateFlowFile(file, "communityAvatar"); setLocalPreviewUrl((prev) => { if (prev) URL.revokeObjectURL(prev); - return URL.createObjectURL(file); + return null; }); setLocalFileName(file.name); - updateState({ communityAvatarFileName: file.name }); - } catch { - setErrorMessage(tUpload("errors.generic")); + updateState({ + communityAvatarUrl: url, + communityAvatarFileName: file.name, + }); + } catch (err) { + setErrorMessage(resolveUploadError(err)); + } finally { + setBusy(false); } }, - [ - markCreateFlowInteraction, - resolveUploadError, - signedIn, - tUpload, - u.fileTooLarge, - updateState, - ], + [markCreateFlowInteraction, resolveUploadError, updateState], ); const handlePickFile = useCallback(() => { diff --git a/app/(app)/create/types.ts b/app/(app)/create/types.ts index f5a5c5f..fda865b 100644 --- a/app/(app)/create/types.ts +++ b/app/(app)/create/types.ts @@ -299,7 +299,7 @@ export interface CreateFlowContextValue { * * Current consumer: {@link SignedInDraftHydration} — when a signed-in user * 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. */ interactionTouched: boolean; diff --git a/app/(app)/create/utils/flowSteps.ts b/app/(app)/create/utils/flowSteps.ts index c6bd232..91db7a3 100644 --- a/app/(app)/create/utils/flowSteps.ts +++ b/app/(app)/create/utils/flowSteps.ts @@ -189,23 +189,24 @@ export function getStepIndex(step: CreateFlowStep | null | undefined): number { 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"); /** - * Top-nav Save and exit (vs Exit). Guests and signed-in users share this from - * `community-save` onward and on `edit-rule`. On completed, guests still - * get Save and exit (claim/login); signed-in users get Exit (already owned). + * Top-nav Save and exit (vs Exit). The header stays Exit until Save your + * progress is done — a signed-in session. Guests (and session-in-flight) + * keep Exit, including on completed and edit-rule. * * @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( currentStep: CreateFlowStep | null | undefined, sessionUser?: { id: string } | null, ): boolean { 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; return getStepIndex(currentStep) >= SAVE_EXIT_FROM_STEP_INDEX; } diff --git a/app/api/rules/[id]/route.ts b/app/api/rules/[id]/route.ts index 36a3403..68ff74a 100644 --- a/app/api/rules/[id]/route.ts +++ b/app/api/rules/[id]/route.ts @@ -8,6 +8,7 @@ import { notFound, unauthorized, } from "../../../../lib/server/responses"; +import { browserHoldsClaimForHash } from "../../../../lib/server/guestRuleClaim"; import { getReadablePublishedRule } from "../../../../lib/server/publishedRules"; import { getSessionUser } from "../../../../lib/server/session"; import { apiRoute } from "../../../../lib/server/apiRoute"; @@ -54,20 +55,25 @@ export const PATCH = apiRoute( } const user = await getSessionUser(); - if (!user) { - return unauthorized(); - } - const { id } = await context.params; const row = await prisma.publishedRule.findUnique({ 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) { - 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"); } @@ -95,7 +101,7 @@ export const PATCH = apiRoute( await linkUploadsToRule({ ruleId: row.id, document, - userId: user.id, + userId: user?.id ?? null, }); return NextResponse.json({ ok: true }); diff --git a/docs/create-flow.md b/docs/create-flow.md index bba8f07..9da20ec 100644 --- a/docs/create-flow.md +++ b/docs/create-flow.md @@ -62,7 +62,7 @@ The step persists **`stakeholderEmails`** on `CreateFlowState` (validated on `PU ### 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`. - **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 | | --- | --- | | `/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. **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). @@ -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 | | --- | --- | --- | -| **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). | -| **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. | +| **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 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. diff --git a/messages/en/create/community/informational.json b/messages/en/create/community/informational.json index 597cbba..f7d08f2 100644 --- a/messages/en/create/community/informational.json +++ b/messages/en/create/community/informational.json @@ -1,6 +1,6 @@ { "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": { "0": { "title": "Tell us about your community" diff --git a/tests/components/CreateFlowGuestFinish.test.tsx b/tests/components/CreateFlowGuestFinish.test.tsx new file mode 100644 index 0000000..208243d --- /dev/null +++ b/tests/components/CreateFlowGuestFinish.test.tsx @@ -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(); + 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( + +
step
+
, + ); +} + +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(), + ); + }); +}); diff --git a/tests/components/InformationalPage.test.tsx b/tests/components/InformationalPage.test.tsx index 80ba076..9da113d 100644 --- a/tests/components/InformationalPage.test.tsx +++ b/tests/components/InformationalPage.test.tsx @@ -17,7 +17,7 @@ describe("InformationalScreen", () => { render(); expect( screen.getByText( - /Work through it together or on your own/i, + /you don’t need an account to write or finish it/i, ), ).toBeInTheDocument(); }); diff --git a/tests/components/UploadPage.test.tsx b/tests/components/UploadPage.test.tsx index 5027a64..3209a0b 100644 --- a/tests/components/UploadPage.test.tsx +++ b/tests/components/UploadPage.test.tsx @@ -12,7 +12,10 @@ import { readPendingCommunityAvatarFile, storePendingCommunityAvatarFile, } from "../../lib/create/pendingCommunityAvatarUpload"; -import { fetchAuthSession } from "../../lib/create/api"; +import { + CreateFlowUploadValidationError, + uploadCreateFlowFile, +} from "../../lib/create/uploadToServer"; import messages from "../../messages/en/index"; vi.mock("../../lib/create/pendingCommunityAvatarUpload", () => ({ @@ -21,9 +24,14 @@ vi.mock("../../lib/create/pendingCommunityAvatarUpload", () => ({ clearPendingCommunityAvatarFile: vi.fn().mockResolvedValue(undefined), })); -vi.mock("../../lib/create/api", () => ({ - fetchAuthSession: vi.fn().mockResolvedValue({ user: null }), -})); +vi.mock("../../lib/create/uploadToServer", async (importOriginal) => { + const actual = + await importOriginal(); + return { + ...actual, + uploadCreateFlowFile: vi.fn(), + }; +}); const pngBytes = Uint8Array.from( Buffer.from( @@ -46,7 +54,7 @@ describe("CommunityUploadScreen", () => { vi.mocked(readPendingCommunityAvatarFile).mockResolvedValue(null); vi.mocked(storePendingCommunityAvatarFile).mockResolvedValue(undefined); vi.mocked(clearPendingCommunityAvatarFile).mockResolvedValue(undefined); - vi.mocked(fetchAuthSession).mockResolvedValue({ user: null }); + vi.mocked(uploadCreateFlowFile).mockReset(); Object.defineProperty(URL, "createObjectURL", { value: vi.fn(() => "blob:pending-avatar"), writable: true, @@ -98,7 +106,35 @@ describe("CommunityUploadScreen", () => { 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(); + 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 () => { + vi.mocked(uploadCreateFlowFile).mockRejectedValue( + new CreateFlowUploadValidationError("empty"), + ); render(); await screen.findByRole("heading", { name: copy.title }); @@ -113,6 +149,9 @@ describe("CommunityUploadScreen", () => { }); it("rejects a text file renamed as PNG", async () => { + vi.mocked(uploadCreateFlowFile).mockRejectedValue( + new CreateFlowUploadValidationError("invalidType"), + ); render(); await screen.findByRole("heading", { name: copy.title }); @@ -129,6 +168,9 @@ describe("CommunityUploadScreen", () => { }); it("rejects SVG uploads", async () => { + vi.mocked(uploadCreateFlowFile).mockRejectedValue( + new CreateFlowUploadValidationError("svg"), + ); render(); await screen.findByRole("heading", { name: copy.title }); diff --git a/tests/unit/flowSteps.test.ts b/tests/unit/flowSteps.test.ts index 80f3925..5ca0898 100644 --- a/tests/unit/flowSteps.test.ts +++ b/tests/unit/flowSteps.test.ts @@ -259,24 +259,38 @@ describe("flowSteps", () => { 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("community-name")).toBe(false); expect(shouldOfferCreateFlowSaveAndExit("community-structure")).toBe(false); expect(shouldOfferCreateFlowSaveAndExit("setup-questions")).toBe(false); expect(shouldOfferCreateFlowSaveAndExit("community-upload")).toBe(false); - expect(shouldOfferCreateFlowSaveAndExit("community-save")).toBe(true); - expect(shouldOfferCreateFlowSaveAndExit("review")).toBe(true); - expect(shouldOfferCreateFlowSaveAndExit("final-review")).toBe(true); - expect(shouldOfferCreateFlowSaveAndExit("edit-rule")).toBe(true); + expect(shouldOfferCreateFlowSaveAndExit("community-save")).toBe(false); + expect(shouldOfferCreateFlowSaveAndExit("community-save", null)).toBe( + false, + ); + 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", { id: "user-1" }), ).toBe(false); - expect(shouldOfferCreateFlowSaveAndExit("completed", null)).toBe(true); + expect(shouldOfferCreateFlowSaveAndExit("completed", null)).toBe(false); expect(shouldOfferCreateFlowSaveAndExit(null)).toBe(false); }); diff --git a/tests/unit/hooks/useCreateFlowFinalize.test.tsx b/tests/unit/hooks/useCreateFlowFinalize.test.tsx index 2f2bf3d..b95fb6c 100644 --- a/tests/unit/hooks/useCreateFlowFinalize.test.tsx +++ b/tests/unit/hooks/useCreateFlowFinalize.test.tsx @@ -109,6 +109,9 @@ describe("useCreateFlowFinalize", () => { sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY), ).toBeNull(); expect(deleteServerDraft).toHaveBeenCalledTimes(1); + expect(updateState).toHaveBeenCalledWith({ + editingPublishedRuleId: undefined, + }); }); it("retries clearing the server draft when the first delete fails", async () => { @@ -192,7 +195,7 @@ describe("useCreateFlowFinalize", () => { }); expect(onGuestPublished).toHaveBeenCalledWith({ skippedInvites: true }); 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( `/create/completed?${CREATE_FLOW_COMPLETED_CELEBRATE_QUERY}=${CREATE_FLOW_COMPLETED_CELEBRATE_VALUE}`, ); @@ -304,7 +307,7 @@ describe("useCreateFlowFinalize", () => { }); expect(onGuestPublished).toHaveBeenCalledWith({ skippedInvites: false }); 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( `/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(() => useCreateFlowFinalize({ state: { @@ -470,8 +475,16 @@ describe("useCreateFlowFinalize", () => { 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(deleteServerDraft).not.toHaveBeenCalled(); expect(openLogin).not.toHaveBeenCalled(); expect(onGuestPublished).toHaveBeenCalledWith({ skippedInvites: false }); expect(writeLastPublishedRule).toHaveBeenCalledWith({ @@ -480,10 +493,92 @@ describe("useCreateFlowFinalize", () => { summary: "Published summary", 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"); }); + 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 () => { vi.mocked(publishRule).mockResolvedValue({ ok: false, diff --git a/tests/unit/rulesByIdPatchRoute.test.ts b/tests/unit/rulesByIdPatchRoute.test.ts index ac543d2..91e7e8e 100644 --- a/tests/unit/rulesByIdPatchRoute.test.ts +++ b/tests/unit/rulesByIdPatchRoute.test.ts @@ -5,6 +5,7 @@ const isDatabaseConfiguredMock = vi.fn(); const findUniqueMock = vi.fn(); const updateMock = vi.fn(); const getSessionUserMock = vi.fn(); +const browserHoldsClaimForHashMock = vi.fn(); vi.mock("../../lib/server/env", () => ({ isDatabaseConfigured: () => isDatabaseConfiguredMock(), @@ -23,22 +24,37 @@ vi.mock("../../lib/server/session", () => ({ getSessionUser: () => getSessionUserMock(), })); +vi.mock("../../lib/server/guestRuleClaim", () => ({ + browserHoldsClaimForHash: (...args: unknown[]) => + browserHoldsClaimForHashMock(...args), +})); + vi.mock("../../lib/server/uploads/linkUploads", () => ({ linkUploadsToRule: vi.fn().mockResolvedValue(undefined), })); import { PATCH } from "../../app/api/rules/[id]/route"; +import { linkUploadsToRule } from "../../lib/server/uploads/linkUploads"; function makeContext(id: string) { return { params: Promise.resolve({ id }) }; } +const patchBody = { + title: "Updated", + summary: "Context", + document: { sections: [], coreValues: [] }, +}; + beforeEach(() => { isDatabaseConfiguredMock.mockReset(); findUniqueMock.mockReset(); updateMock.mockReset(); getSessionUserMock.mockReset(); + browserHoldsClaimForHashMock.mockReset(); + vi.mocked(linkUploadsToRule).mockClear(); getSessionUserMock.mockResolvedValue({ id: "user-1", email: "a@b.c" }); + browserHoldsClaimForHashMock.mockResolvedValue(false); }); 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(); + }); });