Merge pull request 'Keep finished Rules and drafts from overwriting each other' (#114) from adilallo/fix/CR-339-finish-drafts into main
Reviewed-on: #114
This commit was merged in pull request #114.
This commit is contained in:
commit
014d231781
76 files changed
+2204
-427
No files matched your search
@@ -64,6 +64,11 @@ import {
|
|||||||
} from "../../../lib/create/publishedDocumentToCreateFlowState";
|
} from "../../../lib/create/publishedDocumentToCreateFlowState";
|
||||||
import { METHOD_FACET_API_SECTION_IDS } from "../../../lib/create/customRuleFacets";
|
import { METHOD_FACET_API_SECTION_IDS } from "../../../lib/create/customRuleFacets";
|
||||||
import { readLastPublishedRule } from "../../../lib/create/lastPublishedRule";
|
import { readLastPublishedRule } from "../../../lib/create/lastPublishedRule";
|
||||||
|
import {
|
||||||
|
createFlowStateForEditingPublishedRule,
|
||||||
|
publishedRuleEditWouldReplaceDraft,
|
||||||
|
} from "../../../lib/create/beginEditingPublishedRule";
|
||||||
|
import { useAsyncConfirm } from "../../hooks/useAsyncConfirm";
|
||||||
import {
|
import {
|
||||||
CREATE_FLOW_COPIED_QUERY,
|
CREATE_FLOW_COPIED_QUERY,
|
||||||
CREATE_FLOW_COPIED_VALUE,
|
CREATE_FLOW_COPIED_VALUE,
|
||||||
@@ -225,6 +230,7 @@ function CreateFlowLayoutContent({
|
|||||||
} | null>(null);
|
} | null>(null);
|
||||||
const [shareModalOpen, setShareModalOpen] = useState(false);
|
const [shareModalOpen, setShareModalOpen] = useState(false);
|
||||||
const [leaveConfirmOpen, setLeaveConfirmOpen] = useState(false);
|
const [leaveConfirmOpen, setLeaveConfirmOpen] = useState(false);
|
||||||
|
const { requestConfirm, confirmDialog } = useAsyncConfirm();
|
||||||
const [completedHasPublishedRule, setCompletedHasPublishedRule] =
|
const [completedHasPublishedRule, setCompletedHasPublishedRule] =
|
||||||
useState(false);
|
useState(false);
|
||||||
const [completedCopiedReady, setCompletedCopiedReady] = useState(false);
|
const [completedCopiedReady, setCompletedCopiedReady] = useState(false);
|
||||||
@@ -330,6 +336,8 @@ function CreateFlowLayoutContent({
|
|||||||
replaceState,
|
replaceState,
|
||||||
router,
|
router,
|
||||||
fromCreateWizard,
|
fromCreateWizard,
|
||||||
|
signedIn: Boolean(sessionUser),
|
||||||
|
requestConfirm,
|
||||||
markCreateFlowInteraction,
|
markCreateFlowInteraction,
|
||||||
});
|
});
|
||||||
const isCreateTemplatesPickerRoute =
|
const isCreateTemplatesPickerRoute =
|
||||||
@@ -889,20 +897,31 @@ function CreateFlowLayoutContent({
|
|||||||
backdropVariant="blurredYellow"
|
backdropVariant="blurredYellow"
|
||||||
ariaLabel={messages.create.topNav.leaveConfirmTitle}
|
ariaLabel={messages.create.topNav.leaveConfirmTitle}
|
||||||
/>
|
/>
|
||||||
|
{confirmDialog}
|
||||||
<TemplateCustomizeDialog
|
<TemplateCustomizeDialog
|
||||||
isOpen={customizeDialog !== null}
|
isOpen={customizeDialog !== null}
|
||||||
templateTitle={customizeDialog?.templateTitle ?? ""}
|
templateTitle={customizeDialog?.templateTitle ?? ""}
|
||||||
valuesCount={customizeDialog?.valuesCount ?? 0}
|
valuesCount={customizeDialog?.valuesCount ?? 0}
|
||||||
cardsCount={customizeDialog?.cardsCount ?? 0}
|
cardsCount={customizeDialog?.cardsCount ?? 0}
|
||||||
initialTitle={typeof state.title === "string" ? state.title : ""}
|
initialTitle={
|
||||||
|
fromCreateWizard && state.templateReviewEntryFromCreateFlow === true
|
||||||
|
? typeof state.title === "string"
|
||||||
|
? state.title
|
||||||
|
: ""
|
||||||
|
: ""
|
||||||
|
}
|
||||||
initialDescription={
|
initialDescription={
|
||||||
typeof state.communityContext === "string"
|
fromCreateWizard && state.templateReviewEntryFromCreateFlow === true
|
||||||
? state.communityContext
|
? typeof state.communityContext === "string"
|
||||||
|
? state.communityContext
|
||||||
|
: ""
|
||||||
: ""
|
: ""
|
||||||
}
|
}
|
||||||
initialLocation={
|
initialLocation={
|
||||||
typeof state.communityLocation === "string"
|
fromCreateWizard && state.templateReviewEntryFromCreateFlow === true
|
||||||
? state.communityLocation
|
? typeof state.communityLocation === "string"
|
||||||
|
? state.communityLocation
|
||||||
|
: ""
|
||||||
: ""
|
: ""
|
||||||
}
|
}
|
||||||
onClose={closeCustomizeDialog}
|
onClose={closeCustomizeDialog}
|
||||||
@@ -926,13 +945,24 @@ function CreateFlowLayoutContent({
|
|||||||
onEdit={
|
onEdit={
|
||||||
isCompletedStep
|
isCompletedStep
|
||||||
? () => {
|
? () => {
|
||||||
const last = readLastPublishedRule();
|
void (async () => {
|
||||||
if (!last) return;
|
const last = readLastPublishedRule();
|
||||||
updateState({
|
if (!last) return;
|
||||||
editingPublishedRuleId: last.id,
|
if (publishedRuleEditWouldReplaceDraft(state, last)) {
|
||||||
sections: [],
|
const agreed = await requestConfirm({
|
||||||
});
|
title: messages.create.topNav.editReplaceDraftTitle,
|
||||||
router.push(createFlowStepPath("final-review"));
|
description:
|
||||||
|
messages.create.topNav.editReplaceDraftDescription,
|
||||||
|
proceedText:
|
||||||
|
messages.create.topNav.editReplaceDraftProceed,
|
||||||
|
cancelText:
|
||||||
|
messages.create.topNav.editReplaceDraftCancel,
|
||||||
|
});
|
||||||
|
if (!agreed) return;
|
||||||
|
}
|
||||||
|
replaceState(createFlowStateForEditingPublishedRule(last));
|
||||||
|
router.push(createFlowStepPath("final-review"));
|
||||||
|
})();
|
||||||
}
|
}
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,7 +21,11 @@ import {
|
|||||||
isCreateFlowTemplatesPickerPath,
|
isCreateFlowTemplatesPickerPath,
|
||||||
parseCreateFlowScreenFromPathname,
|
parseCreateFlowScreenFromPathname,
|
||||||
} from "./utils/flowSteps";
|
} from "./utils/flowSteps";
|
||||||
import { hasFreshEntryPending } from "./utils/prepareFreshCreateFlowEntry";
|
import {
|
||||||
|
hasFreshEntryPending,
|
||||||
|
hasTemplateApplyLatch,
|
||||||
|
clearTemplateApplyLatch,
|
||||||
|
} from "./utils/prepareFreshCreateFlowEntry";
|
||||||
|
|
||||||
import { isBackendSyncEnabled } from "../../../lib/create/backendSyncEnabled";
|
import { isBackendSyncEnabled } from "../../../lib/create/backendSyncEnabled";
|
||||||
|
|
||||||
@@ -94,6 +98,12 @@ export function SignedInDraftHydration({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (hasTemplateApplyLatch()) {
|
||||||
|
finishedUserIdRef.current = userId;
|
||||||
|
clearTemplateApplyLatch();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Local draft wins over server: no fetch, no replaceState. The provider
|
// Local draft wins over server: no fetch, no replaceState. The provider
|
||||||
// already hydrated from localStorage at mount, so the user sees their
|
// already hydrated from localStorage at mount, so the user sees their
|
||||||
// unsaved keystrokes immediately.
|
// unsaved keystrokes immediately.
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ import type {
|
|||||||
import {
|
import {
|
||||||
clearAnonymousCreateFlowStorage,
|
clearAnonymousCreateFlowStorage,
|
||||||
clearLegacyCreateFlowKeysOnce,
|
clearLegacyCreateFlowKeysOnce,
|
||||||
hasTransferPendingFlag,
|
|
||||||
readAnonymousCreateFlowState,
|
readAnonymousCreateFlowState,
|
||||||
writeAnonymousCreateFlowState,
|
writeAnonymousCreateFlowState,
|
||||||
} from "../utils/anonymousDraftStorage";
|
} from "../utils/anonymousDraftStorage";
|
||||||
@@ -65,6 +64,7 @@ export function CreateFlowProvider({
|
|||||||
const [currentStep] = useState<CreateFlowStep | null>(initialStep);
|
const [currentStep] = useState<CreateFlowStep | null>(initialStep);
|
||||||
const prevPersistRef = useRef(enableLocalDraftMirroring);
|
const prevPersistRef = useRef(enableLocalDraftMirroring);
|
||||||
const persistWriteSkipRef = useRef(true);
|
const persistWriteSkipRef = useRef(true);
|
||||||
|
const coreValueWriteSkipRef = useRef(true);
|
||||||
const initialHydrateDoneRef = useRef(false);
|
const initialHydrateDoneRef = useRef(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -115,13 +115,6 @@ export function CreateFlowProvider({
|
|||||||
const wasOff = !prevPersistRef.current;
|
const wasOff = !prevPersistRef.current;
|
||||||
prevPersistRef.current = true;
|
prevPersistRef.current = true;
|
||||||
if (!wasOff) return;
|
if (!wasOff) return;
|
||||||
if (hasTransferPendingFlag()) return;
|
|
||||||
if (
|
|
||||||
typeof window !== "undefined" &&
|
|
||||||
new URLSearchParams(window.location.search).get("syncDraft") === "1"
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const from = readAnonymousCreateFlowState();
|
const from = readAnonymousCreateFlowState();
|
||||||
if (Object.keys(from).length === 0) return;
|
if (Object.keys(from).length === 0) return;
|
||||||
// eslint-disable-next-line react-hooks/set-state-in-effect -- hydrate local draft when mirroring turns on
|
// eslint-disable-next-line react-hooks/set-state-in-effect -- hydrate local draft when mirroring turns on
|
||||||
@@ -160,8 +153,16 @@ export function CreateFlowProvider({
|
|||||||
|
|
||||||
/** Meaning/signals for core values: survives refresh for signed-in users; merged with anonymous draft when both exist. */
|
/** Meaning/signals for core values: survives refresh for signed-in users; merged with anonymous draft when both exist. */
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (!enableLocalDraftMirroring) {
|
||||||
|
coreValueWriteSkipRef.current = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (coreValueWriteSkipRef.current) {
|
||||||
|
coreValueWriteSkipRef.current = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
writeCoreValueDetailsToLocalStorage(state.coreValueDetailsByChipId);
|
writeCoreValueDetailsToLocalStorage(state.coreValueDetailsByChipId);
|
||||||
}, [state.coreValueDetailsByChipId]);
|
}, [state.coreValueDetailsByChipId, enableLocalDraftMirroring]);
|
||||||
|
|
||||||
const markCreateFlowInteraction = useCallback(() => {
|
const markCreateFlowInteraction = useCallback(() => {
|
||||||
setInteractionTouched(true);
|
setInteractionTouched(true);
|
||||||
|
|||||||
@@ -3,7 +3,11 @@
|
|||||||
import { useCallback, useState } from "react";
|
import { useCallback, useState } from "react";
|
||||||
import { buildPublishPayload } from "../../../../lib/create/buildPublishPayload";
|
import { buildPublishPayload } from "../../../../lib/create/buildPublishPayload";
|
||||||
import { stateWithPendingCommunityAvatar } from "../../../../lib/create/flushPendingCommunityAvatar";
|
import { stateWithPendingCommunityAvatar } from "../../../../lib/create/flushPendingCommunityAvatar";
|
||||||
import { publishRule, updatePublishedRule } from "../../../../lib/create/api";
|
import {
|
||||||
|
deleteServerDraft,
|
||||||
|
publishRule,
|
||||||
|
updatePublishedRule,
|
||||||
|
} from "../../../../lib/create/api";
|
||||||
import { writeLastPublishedRule } from "../../../../lib/create/lastPublishedRule";
|
import { writeLastPublishedRule } from "../../../../lib/create/lastPublishedRule";
|
||||||
import { writePendingKeepRuleLogin } from "../../../../lib/create/pendingKeepRuleLogin";
|
import { writePendingKeepRuleLogin } from "../../../../lib/create/pendingKeepRuleLogin";
|
||||||
import messages from "../../../../messages/en/index";
|
import messages from "../../../../messages/en/index";
|
||||||
@@ -14,6 +18,15 @@ import {
|
|||||||
} from "../utils/flowSteps";
|
} from "../utils/flowSteps";
|
||||||
import { createFlowStepPath } from "../utils/createFlowPaths";
|
import { createFlowStepPath } from "../utils/createFlowPaths";
|
||||||
|
|
||||||
|
const DRAFT_DELETE_ATTEMPTS = 3;
|
||||||
|
|
||||||
|
/** The rule is saved. Keep trying until the source draft is actually gone. */
|
||||||
|
async function deleteServerDraftAfterPublish(): Promise<void> {
|
||||||
|
for (let attempt = 0; attempt < DRAFT_DELETE_ATTEMPTS; attempt += 1) {
|
||||||
|
if (await deleteServerDraft()) return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type AppRouterLike = { push: (_href: string) => void };
|
type AppRouterLike = { push: (_href: string) => void };
|
||||||
|
|
||||||
type OpenLogin = (args: {
|
type OpenLogin = (args: {
|
||||||
@@ -150,6 +163,7 @@ export function useCreateFlowFinalize({
|
|||||||
document: ruleDocument,
|
document: ruleDocument,
|
||||||
});
|
});
|
||||||
updateState({ editingPublishedRuleId: undefined });
|
updateState({ editingPublishedRuleId: undefined });
|
||||||
|
void deleteServerDraftAfterPublish();
|
||||||
router.push(createFlowStepPath("completed"));
|
router.push(createFlowStepPath("completed"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -203,6 +217,8 @@ export function useCreateFlowFinalize({
|
|||||||
if (isGuest) {
|
if (isGuest) {
|
||||||
writePendingKeepRuleLogin();
|
writePendingKeepRuleLogin();
|
||||||
onGuestPublished?.({ skippedInvites: skippedGuestInvites });
|
onGuestPublished?.({ skippedInvites: skippedGuestInvites });
|
||||||
|
} else {
|
||||||
|
void deleteServerDraftAfterPublish();
|
||||||
}
|
}
|
||||||
router.push(
|
router.push(
|
||||||
createFlowStepPath("completed", {
|
createFlowStepPath("completed", {
|
||||||
|
|||||||
@@ -68,6 +68,14 @@ export function useCreateFlowNavigation(
|
|||||||
|
|
||||||
const validStep = parseCreateFlowScreenFromPathname(pathname ?? null);
|
const validStep = parseCreateFlowScreenFromPathname(pathname ?? null);
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
if (!validStep || validStep === "completed" || validStep === "edit-rule") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (state.currentStep === validStep) return;
|
||||||
|
updateState({ currentStep: validStep });
|
||||||
|
}, [validStep, state.currentStep, updateState]);
|
||||||
|
|
||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
if (!pathname?.includes("/create/review-template/")) return;
|
if (!pathname?.includes("/create/review-template/")) return;
|
||||||
if (
|
if (
|
||||||
|
|||||||
@@ -2,19 +2,25 @@
|
|||||||
|
|
||||||
import { useCallback, useMemo, useState } from "react";
|
import { useCallback, useMemo, useState } from "react";
|
||||||
import {
|
import {
|
||||||
buildTemplateCustomizePrefill,
|
buildAppliedTemplateCreateFlowState,
|
||||||
templatePresetDetailsFromPrefill,
|
sectionsFromTemplateBody,
|
||||||
} from "../../../../lib/create/applyTemplatePrefill";
|
} from "../../../../lib/create/applyTemplatePrefill";
|
||||||
|
import { fetchDraftFromServer } from "../../../../lib/create/api";
|
||||||
|
import { createFlowStateHasKeys } from "../../../../lib/create/draftHydrationUtils";
|
||||||
import { loadTemplateReviewBySlug } from "../../../../lib/create/loadTemplateReviewBySlug";
|
import { loadTemplateReviewBySlug } from "../../../../lib/create/loadTemplateReviewBySlug";
|
||||||
import { methodSectionsPinsForHydratedSelections } from "../../../../lib/create/publishedDocumentToCreateFlowState";
|
|
||||||
import { stripCustomRuleSelectionFields } from "../../../../lib/create/stripCustomRuleSelectionFields";
|
|
||||||
import { templateChipCounts } from "../../../../lib/create/templatePath";
|
import { templateChipCounts } from "../../../../lib/create/templatePath";
|
||||||
import messages from "../../../../messages/en/index";
|
import messages from "../../../../messages/en/index";
|
||||||
|
import type { AsyncConfirmOptions } from "../../../hooks/useAsyncConfirm";
|
||||||
import type {
|
import type {
|
||||||
CreateFlowContextValue,
|
CreateFlowContextValue,
|
||||||
CreateFlowState,
|
CreateFlowState,
|
||||||
} from "../types";
|
} from "../types";
|
||||||
|
import { hasBrowserCreateFlowDraft } from "../utils/createRuleEntry";
|
||||||
import { createFlowStepPath } from "../utils/createFlowPaths";
|
import { createFlowStepPath } from "../utils/createFlowPaths";
|
||||||
|
import {
|
||||||
|
latchTemplateApply,
|
||||||
|
prepareFreshCreateFlowEntrySync,
|
||||||
|
} from "../utils/prepareFreshCreateFlowEntry";
|
||||||
|
|
||||||
type AppRouterLike = { push: (_href: string) => void };
|
type AppRouterLike = { push: (_href: string) => void };
|
||||||
type UpdateState = CreateFlowContextValue["updateState"];
|
type UpdateState = CreateFlowContextValue["updateState"];
|
||||||
@@ -61,13 +67,27 @@ export type UseTemplateReviewActionsResult = {
|
|||||||
confirmCustomizeDialog: (_fields: TemplateCustomizeFields) => void;
|
confirmCustomizeDialog: (_fields: TemplateCustomizeFields) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
function sectionsFromTemplateBody(
|
const TEMPLATE_NAV_KEYS = new Set([
|
||||||
body: unknown,
|
"templateReviewEntryFromCreateFlow",
|
||||||
): Record<string, unknown>[] | null {
|
"templateReviewBackSlug",
|
||||||
if (!body || typeof body !== "object" || Array.isArray(body)) return null;
|
"pendingTemplateAction",
|
||||||
const sectionsRaw = (body as { sections?: unknown }).sections;
|
"currentStep",
|
||||||
if (!Array.isArray(sectionsRaw) || sectionsRaw.length === 0) return null;
|
"methodSectionsPinCommitted",
|
||||||
return sectionsRaw as Record<string, unknown>[];
|
]);
|
||||||
|
|
||||||
|
function createFlowStateLooksLikeProgress(state: CreateFlowState): boolean {
|
||||||
|
return Object.keys(state).some((key) => !TEMPLATE_NAV_KEYS.has(key));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function hasDraftToReplace(
|
||||||
|
state: CreateFlowState,
|
||||||
|
signedIn: boolean,
|
||||||
|
): Promise<boolean> {
|
||||||
|
if (createFlowStateLooksLikeProgress(state)) return true;
|
||||||
|
if (hasBrowserCreateFlowDraft()) return true;
|
||||||
|
if (!signedIn) return false;
|
||||||
|
const server = await fetchDraftFromServer();
|
||||||
|
return server != null && createFlowStateHasKeys(server);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -86,10 +106,11 @@ function sectionsFromTemplateBody(
|
|||||||
export function useTemplateReviewActions({
|
export function useTemplateReviewActions({
|
||||||
pathname,
|
pathname,
|
||||||
state,
|
state,
|
||||||
updateState,
|
|
||||||
replaceState,
|
replaceState,
|
||||||
router,
|
router,
|
||||||
fromCreateWizard = false,
|
fromCreateWizard = false,
|
||||||
|
signedIn = false,
|
||||||
|
requestConfirm,
|
||||||
markCreateFlowInteraction,
|
markCreateFlowInteraction,
|
||||||
}: {
|
}: {
|
||||||
pathname: string | null | undefined;
|
pathname: string | null | undefined;
|
||||||
@@ -103,6 +124,8 @@ export function useTemplateReviewActions({
|
|||||||
* draft title must not count as “community steps already done”.
|
* draft title must not count as “community steps already done”.
|
||||||
*/
|
*/
|
||||||
fromCreateWizard?: boolean;
|
fromCreateWizard?: boolean;
|
||||||
|
signedIn?: boolean;
|
||||||
|
requestConfirm?: (_opts: AsyncConfirmOptions) => Promise<boolean>;
|
||||||
markCreateFlowInteraction: () => void;
|
markCreateFlowInteraction: () => void;
|
||||||
}): UseTemplateReviewActionsResult {
|
}): UseTemplateReviewActionsResult {
|
||||||
const [isApplyingTemplate, setIsApplyingTemplate] = useState(false);
|
const [isApplyingTemplate, setIsApplyingTemplate] = useState(false);
|
||||||
@@ -121,10 +144,26 @@ export function useTemplateReviewActions({
|
|||||||
pathname?.includes("/create/review-template/"),
|
pathname?.includes("/create/review-template/"),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const keepInFlowIdentity =
|
||||||
|
fromCreateWizard && state.templateReviewEntryFromCreateFlow === true;
|
||||||
|
|
||||||
|
const confirmReplaceDraft = useCallback(async (): Promise<boolean> => {
|
||||||
|
if (!requestConfirm) return true;
|
||||||
|
if (!(await hasDraftToReplace(state, signedIn))) return true;
|
||||||
|
const copy = messages.create.templateReview.replaceDraft;
|
||||||
|
return requestConfirm({
|
||||||
|
title: copy.title,
|
||||||
|
description: copy.description,
|
||||||
|
proceedText: copy.proceed,
|
||||||
|
cancelText: copy.cancel,
|
||||||
|
});
|
||||||
|
}, [requestConfirm, signedIn, state]);
|
||||||
|
|
||||||
const handleCustomize = useCallback(async () => {
|
const handleCustomize = useCallback(async () => {
|
||||||
if (!templateReviewSlug) return;
|
if (!templateReviewSlug) return;
|
||||||
markCreateFlowInteraction();
|
markCreateFlowInteraction();
|
||||||
setTemplateReviewApplyError(null);
|
setTemplateReviewApplyError(null);
|
||||||
|
if (!(await confirmReplaceDraft())) return;
|
||||||
setIsApplyingTemplate(true);
|
setIsApplyingTemplate(true);
|
||||||
const loaded = await loadTemplateReviewBySlug(templateReviewSlug);
|
const loaded = await loadTemplateReviewBySlug(templateReviewSlug);
|
||||||
setIsApplyingTemplate(false);
|
setIsApplyingTemplate(false);
|
||||||
@@ -140,7 +179,11 @@ export function useTemplateReviewActions({
|
|||||||
valuesCount: counts?.values ?? 0,
|
valuesCount: counts?.values ?? 0,
|
||||||
cardsCount: counts?.cards ?? 0,
|
cardsCount: counts?.cards ?? 0,
|
||||||
});
|
});
|
||||||
}, [markCreateFlowInteraction, templateReviewSlug]);
|
}, [
|
||||||
|
confirmReplaceDraft,
|
||||||
|
markCreateFlowInteraction,
|
||||||
|
templateReviewSlug,
|
||||||
|
]);
|
||||||
|
|
||||||
const closeCustomizeDialog = useCallback(() => {
|
const closeCustomizeDialog = useCallback(() => {
|
||||||
setCustomizeDialog(null);
|
setCustomizeDialog(null);
|
||||||
@@ -150,44 +193,29 @@ export function useTemplateReviewActions({
|
|||||||
(fields: TemplateCustomizeFields) => {
|
(fields: TemplateCustomizeFields) => {
|
||||||
if (!customizeDialog) return;
|
if (!customizeDialog) return;
|
||||||
markCreateFlowInteraction();
|
markCreateFlowInteraction();
|
||||||
const prefill = buildTemplateCustomizePrefill(
|
prepareFreshCreateFlowEntrySync({ signedIn });
|
||||||
customizeDialog.body,
|
latchTemplateApply();
|
||||||
customizeDialog.slug,
|
replaceState(() =>
|
||||||
);
|
buildAppliedTemplateCreateFlowState({
|
||||||
const details = templatePresetDetailsFromPrefill(prefill);
|
|
||||||
const pinPatch = methodSectionsPinsForHydratedSelections(prefill);
|
|
||||||
const title = fields.title.trim();
|
|
||||||
const communityContext = fields.communityContext.trim();
|
|
||||||
const communityLocation = fields.communityLocation.trim();
|
|
||||||
updateState({
|
|
||||||
...prefill,
|
|
||||||
...details,
|
|
||||||
title: title.length > 0 ? title : undefined,
|
|
||||||
communityContext:
|
|
||||||
communityContext.length > 0 ? communityContext : undefined,
|
|
||||||
summary: communityContext.length > 0 ? communityContext : undefined,
|
|
||||||
communityLocation:
|
|
||||||
communityLocation.length > 0 ? communityLocation : undefined,
|
|
||||||
methodSectionsPinCommitted: {
|
|
||||||
...state.methodSectionsPinCommitted,
|
|
||||||
...pinPatch,
|
|
||||||
},
|
|
||||||
templateReviewBackSlug: customizeDialog.slug,
|
|
||||||
setupTraits: undefined,
|
|
||||||
pendingTemplateAction: {
|
|
||||||
slug: customizeDialog.slug,
|
slug: customizeDialog.slug,
|
||||||
|
body: customizeDialog.body,
|
||||||
mode: "customize",
|
mode: "customize",
|
||||||
},
|
identity: {
|
||||||
});
|
title: fields.title,
|
||||||
|
communityContext: fields.communityContext,
|
||||||
|
communityLocation: fields.communityLocation,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
setCustomizeDialog(null);
|
setCustomizeDialog(null);
|
||||||
router.push(createFlowStepPath("core-values"));
|
router.push(createFlowStepPath("core-values"));
|
||||||
},
|
},
|
||||||
[
|
[
|
||||||
customizeDialog,
|
customizeDialog,
|
||||||
markCreateFlowInteraction,
|
markCreateFlowInteraction,
|
||||||
|
replaceState,
|
||||||
router,
|
router,
|
||||||
state.methodSectionsPinCommitted,
|
signedIn,
|
||||||
updateState,
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -195,6 +223,7 @@ export function useTemplateReviewActions({
|
|||||||
if (!templateReviewSlug) return;
|
if (!templateReviewSlug) return;
|
||||||
markCreateFlowInteraction();
|
markCreateFlowInteraction();
|
||||||
setTemplateReviewApplyError(null);
|
setTemplateReviewApplyError(null);
|
||||||
|
if (!(await confirmReplaceDraft())) return;
|
||||||
setIsApplyingTemplate(true);
|
setIsApplyingTemplate(true);
|
||||||
const loaded = await loadTemplateReviewBySlug(templateReviewSlug);
|
const loaded = await loadTemplateReviewBySlug(templateReviewSlug);
|
||||||
setIsApplyingTemplate(false);
|
setIsApplyingTemplate(false);
|
||||||
@@ -211,63 +240,33 @@ export function useTemplateReviewActions({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
replaceState((prev) => {
|
prepareFreshCreateFlowEntrySync({ signedIn });
|
||||||
const base = stripCustomRuleSelectionFields(prev);
|
latchTemplateApply();
|
||||||
const customizePrefill = buildTemplateCustomizePrefill(
|
replaceState(() =>
|
||||||
template.body,
|
buildAppliedTemplateCreateFlowState({
|
||||||
templateReviewSlug ?? undefined,
|
slug: templateReviewSlug,
|
||||||
);
|
body: template.body,
|
||||||
const details = templatePresetDetailsFromPrefill(customizePrefill);
|
mode: "useWithoutChanges",
|
||||||
const hasValuesSeed =
|
identity: keepInFlowIdentity
|
||||||
customizePrefill.selectedCoreValueIds !== undefined;
|
? {
|
||||||
|
title: state.title,
|
||||||
const sectionsWithoutValues = hasValuesSeed
|
communityContext: state.communityContext,
|
||||||
? sections.filter((s) => {
|
communityLocation: state.communityLocation,
|
||||||
const name = (s as { categoryName?: unknown }).categoryName;
|
}
|
||||||
if (typeof name !== "string") return true;
|
: undefined,
|
||||||
const key = name.toLowerCase().replace(/[^a-z]+/g, "");
|
}),
|
||||||
return key !== "values" && key !== "corevalues";
|
);
|
||||||
})
|
|
||||||
: sections;
|
|
||||||
|
|
||||||
const pinPatch =
|
|
||||||
methodSectionsPinsForHydratedSelections(customizePrefill);
|
|
||||||
|
|
||||||
const seeded: CreateFlowState = {
|
|
||||||
...base,
|
|
||||||
...customizePrefill,
|
|
||||||
...details,
|
|
||||||
sections: sectionsWithoutValues,
|
|
||||||
methodSectionsPinCommitted: pinPatch,
|
|
||||||
templateReviewBackSlug: templateReviewSlug,
|
|
||||||
setupTraits: undefined,
|
|
||||||
pendingTemplateAction: {
|
|
||||||
slug: templateReviewSlug,
|
|
||||||
mode: "useWithoutChanges",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
if (fromCreateWizard) {
|
|
||||||
return seeded;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
...seeded,
|
|
||||||
title: undefined,
|
|
||||||
communityContext: undefined,
|
|
||||||
communityLocation: undefined,
|
|
||||||
communityAvatarUrl: undefined,
|
|
||||||
communityAvatarFileName: undefined,
|
|
||||||
currentStep: undefined,
|
|
||||||
templateReviewEntryFromCreateFlow: undefined,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
router.push(createFlowStepPath("final-review"));
|
router.push(createFlowStepPath("final-review"));
|
||||||
}, [
|
}, [
|
||||||
fromCreateWizard,
|
confirmReplaceDraft,
|
||||||
|
keepInFlowIdentity,
|
||||||
markCreateFlowInteraction,
|
markCreateFlowInteraction,
|
||||||
replaceState,
|
replaceState,
|
||||||
router,
|
router,
|
||||||
|
state.communityContext,
|
||||||
|
state.communityLocation,
|
||||||
|
signedIn,
|
||||||
|
state.title,
|
||||||
templateReviewSlug,
|
templateReviewSlug,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,10 @@ import {
|
|||||||
type FinalReviewCategoryRowDetailed,
|
type FinalReviewCategoryRowDetailed,
|
||||||
} from "../../../../../lib/create/buildFinalReviewCategories";
|
} from "../../../../../lib/create/buildFinalReviewCategories";
|
||||||
import { communityInitialsFromTitle } from "../../../../../lib/create/communityInitials";
|
import { communityInitialsFromTitle } from "../../../../../lib/create/communityInitials";
|
||||||
import { finalReviewChipHasWarning } from "../../../../../lib/create/finalReviewChipWarnings";
|
import {
|
||||||
|
finalReviewChipHasWarning,
|
||||||
|
finalReviewMissingWordsLabels,
|
||||||
|
} from "../../../../../lib/create/finalReviewChipWarnings";
|
||||||
import { applyFinalReviewChipEditPatch } from "../../../../../lib/create/applyFinalReviewChipEditPatch";
|
import { applyFinalReviewChipEditPatch } from "../../../../../lib/create/applyFinalReviewChipEditPatch";
|
||||||
import type {
|
import type {
|
||||||
TemplateChipDetail,
|
TemplateChipDetail,
|
||||||
@@ -234,6 +237,11 @@ export function FinalReviewScreen({
|
|||||||
|
|
||||||
const descriptionEmptyHint = t("communityContextEditModal.emptyHint");
|
const descriptionEmptyHint = t("communityContextEditModal.emptyHint");
|
||||||
|
|
||||||
|
const missingWordsLabels = useMemo(
|
||||||
|
() => finalReviewMissingWordsLabels(state),
|
||||||
|
[state],
|
||||||
|
);
|
||||||
|
|
||||||
const templatePath = isTemplateCreatePath(state);
|
const templatePath = isTemplateCreatePath(state);
|
||||||
const avatarUpload = useCommunityAvatarUpload();
|
const avatarUpload = useCommunityAvatarUpload();
|
||||||
const serverAvatarUrl = useCommunityAvatarDisplayUrl(state.communityAvatarUrl);
|
const serverAvatarUrl = useCommunityAvatarDisplayUrl(state.communityAvatarUrl);
|
||||||
@@ -277,6 +285,19 @@ export function FinalReviewScreen({
|
|||||||
: t("description")
|
: t("description")
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
|
{missingWordsLabels.length > 0 ? (
|
||||||
|
<Alert
|
||||||
|
type="banner"
|
||||||
|
status="warning"
|
||||||
|
size="m"
|
||||||
|
title={t("missingWordsWarning.title")}
|
||||||
|
description={t("missingWordsWarning.description").replace(
|
||||||
|
"{labels}",
|
||||||
|
missingWordsLabels.join(", "),
|
||||||
|
)}
|
||||||
|
hasTrailingIcon={false}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
{bindingArbitrationNeedsSeparateYes(state) ? (
|
{bindingArbitrationNeedsSeparateYes(state) ? (
|
||||||
<Alert
|
<Alert
|
||||||
type="banner"
|
type="banner"
|
||||||
|
|||||||
@@ -84,6 +84,16 @@ export function hasTransferPendingFlag(): boolean {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Drop the transfer flag without touching the stored draft. */
|
||||||
|
export function clearTransferPendingFlag(): void {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
try {
|
||||||
|
window.localStorage.removeItem(CREATE_FLOW_TRANSFER_PENDING_KEY);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** One-time cleanup of pre–anonymous-draft keys. */
|
/** One-time cleanup of pre–anonymous-draft keys. */
|
||||||
export function clearLegacyCreateFlowKeysOnce(): void {
|
export function clearLegacyCreateFlowKeysOnce(): void {
|
||||||
if (typeof window === "undefined") return;
|
if (typeof window === "undefined") return;
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { clearPendingKeepRuleLogin } from "../../../../lib/create/pendingKeepRuleLogin";
|
||||||
|
import { clearLastPublishedRule } from "../../../../lib/create/lastPublishedRule";
|
||||||
|
import { clearCreateFlowPersistedDrafts } from "./clearCreateFlowPersistedDrafts";
|
||||||
|
|
||||||
|
const LEGACY_LIVE_KEY = "create-flow-state";
|
||||||
|
const LEGACY_DRAFT_KEY = "create-flow-draft";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drop every Rule the browser is holding: the anonymous draft, last finished
|
||||||
|
* Rule, keep-this-rule prompt, and leftover pre-anonymous keys. Does not
|
||||||
|
* `DELETE /api/drafts/me`. Call after Log out and Delete account.
|
||||||
|
*/
|
||||||
|
export function clearBrowserRuleData(): void {
|
||||||
|
clearCreateFlowPersistedDrafts();
|
||||||
|
clearLastPublishedRule();
|
||||||
|
clearPendingKeepRuleLogin();
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
try {
|
||||||
|
window.localStorage.removeItem(LEGACY_LIVE_KEY);
|
||||||
|
window.localStorage.removeItem(LEGACY_DRAFT_KEY);
|
||||||
|
} catch {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import {
|
|||||||
buildFinalReviewCategoryRowsDetailed,
|
buildFinalReviewCategoryRowsDetailed,
|
||||||
type FinalReviewCategoryNames,
|
type FinalReviewCategoryNames,
|
||||||
} from "../../../../lib/create/buildFinalReviewCategories";
|
} from "../../../../lib/create/buildFinalReviewCategories";
|
||||||
|
import { finalReviewChipBlocksContinue } from "../../../../lib/create/finalReviewChipWarnings";
|
||||||
import type { TemplateFacetGroupKey } from "../../../../lib/create/templateReviewMapping";
|
import type { TemplateFacetGroupKey } from "../../../../lib/create/templateReviewMapping";
|
||||||
import type { CreateFlowState, CreateFlowStep } from "../types";
|
import type { CreateFlowState, CreateFlowStep } from "../types";
|
||||||
|
|
||||||
@@ -75,8 +76,9 @@ const FINAL_REVIEW_REQUIRED_GROUPS: readonly TemplateFacetGroupKey[] = [
|
|||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Continue on final review waits for a community name and at least one card
|
* Continue on final review waits for a community name, at least one card on
|
||||||
* on each of the four questions. Skipped values do not block.
|
* each of the four questions, every picked card's words, and every picked
|
||||||
|
* value's meaning. Skipped values and missing signals do not block.
|
||||||
*/
|
*/
|
||||||
export function isFinalReviewContinueBlocked(state: CreateFlowState): boolean {
|
export function isFinalReviewContinueBlocked(state: CreateFlowState): boolean {
|
||||||
const title = typeof state.title === "string" ? state.title.trim() : "";
|
const title = typeof state.title === "string" ? state.title.trim() : "";
|
||||||
@@ -85,10 +87,16 @@ export function isFinalReviewContinueBlocked(state: CreateFlowState): boolean {
|
|||||||
state,
|
state,
|
||||||
FINAL_REVIEW_BLOCK_NAMES,
|
FINAL_REVIEW_BLOCK_NAMES,
|
||||||
);
|
);
|
||||||
return FINAL_REVIEW_REQUIRED_GROUPS.some((groupKey) => {
|
const missingRequiredCard = FINAL_REVIEW_REQUIRED_GROUPS.some((groupKey) => {
|
||||||
const row = rows.find((candidate) => candidate.groupKey === groupKey);
|
const row = rows.find((candidate) => candidate.groupKey === groupKey);
|
||||||
return !row || row.entries.length === 0;
|
return !row || row.entries.length === 0;
|
||||||
});
|
});
|
||||||
|
if (missingRequiredCard) return true;
|
||||||
|
return rows.some((row) =>
|
||||||
|
row.entries.some((entry) =>
|
||||||
|
finalReviewChipBlocksContinue(state, entry.groupKey, entry.overrideKey),
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { createFlowStateHasKeys } from "../../../../lib/create/draftHydrationUtils";
|
||||||
|
import type { CreateFlowStep } from "../types";
|
||||||
|
import { readAnonymousCreateFlowState } from "./anonymousDraftStorage";
|
||||||
|
import { CREATE_ROUTES, createFlowStepPath } from "./createFlowPaths";
|
||||||
|
import { readCoreValueDetailsFromLocalStorage } from "./coreValueDetailsLocalStorage";
|
||||||
|
import { isValidStep } from "./flowSteps";
|
||||||
|
|
||||||
|
const NON_RESUME_STEPS = new Set<CreateFlowStep>(["completed", "edit-rule"]);
|
||||||
|
|
||||||
|
export function hasBrowserCreateFlowDraft(): boolean {
|
||||||
|
if (createFlowStateHasKeys(readAnonymousCreateFlowState())) return true;
|
||||||
|
return Object.keys(readCoreValueDetailsFromLocalStorage()).length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Path for header / Home / Profile **Create rule**. Never clears the browser
|
||||||
|
* draft or `DELETE`s `/api/drafts/me` — resume where the draft was left.
|
||||||
|
*/
|
||||||
|
export function createRuleEntryPath(): string {
|
||||||
|
const local = readAnonymousCreateFlowState();
|
||||||
|
const step = local.currentStep;
|
||||||
|
if (isValidStep(step) && !NON_RESUME_STEPS.has(step)) {
|
||||||
|
return createFlowStepPath(step);
|
||||||
|
}
|
||||||
|
return CREATE_ROUTES.createFirstStep;
|
||||||
|
}
|
||||||
@@ -247,6 +247,15 @@ export function isValidStep(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Resume a saved draft on the screen it was left on. */
|
||||||
|
export function resumeCreateFlowStep(
|
||||||
|
state: { currentStep?: CreateFlowStep } | null | undefined,
|
||||||
|
): CreateFlowStep {
|
||||||
|
const step = state?.currentStep;
|
||||||
|
if (step && isValidStep(step)) return step;
|
||||||
|
return FIRST_STEP;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parses `/create/{screenId}` (and optional trailing segments) from pathname.
|
* Parses `/create/{screenId}` (and optional trailing segments) from pathname.
|
||||||
* Returns null for non-wizard paths (e.g. `/create/review-template/...`).
|
* Returns null for non-wizard paths (e.g. `/create/review-template/...`).
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ import { isBackendSyncEnabled } from "../../../../lib/create/backendSyncEnabled"
|
|||||||
*/
|
*/
|
||||||
export const FRESH_ENTRY_PENDING_KEY = "create:fresh-entry-pending";
|
export const FRESH_ENTRY_PENDING_KEY = "create:fresh-entry-pending";
|
||||||
|
|
||||||
|
/** Set when a template is applied so server-draft hydration cannot replace it. */
|
||||||
|
export const TEMPLATE_APPLY_LATCH_KEY = "create:template-apply-latch";
|
||||||
|
|
||||||
export type PrepareFreshCreateFlowEntryOptions = {
|
export type PrepareFreshCreateFlowEntryOptions = {
|
||||||
/**
|
/**
|
||||||
* When `true`, and backend sync is on, also `DELETE /api/drafts/me`.
|
* When `true`, and backend sync is on, also `DELETE /api/drafts/me`.
|
||||||
@@ -28,6 +31,33 @@ export function hasFreshEntryPending(): boolean {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function latchTemplateApply(): void {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
try {
|
||||||
|
window.sessionStorage.setItem(TEMPLATE_APPLY_LATCH_KEY, "1");
|
||||||
|
} catch {
|
||||||
|
/* ignore — sessionStorage may be unavailable */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasTemplateApplyLatch(): boolean {
|
||||||
|
if (typeof window === "undefined") return false;
|
||||||
|
try {
|
||||||
|
return window.sessionStorage.getItem(TEMPLATE_APPLY_LATCH_KEY) === "1";
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearTemplateApplyLatch(): void {
|
||||||
|
if (typeof window === "undefined") return;
|
||||||
|
try {
|
||||||
|
window.sessionStorage.removeItem(TEMPLATE_APPLY_LATCH_KEY);
|
||||||
|
} catch {
|
||||||
|
/* ignore */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function setFreshEntryPending(): void {
|
function setFreshEntryPending(): void {
|
||||||
if (typeof window === "undefined") return;
|
if (typeof window === "undefined") return;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import type { CreateFlowState } from "../types";
|
||||||
|
import { forgetFlushedCommunityAvatarUrl } from "../../../../lib/create/flushPendingCommunityAvatar";
|
||||||
|
import { clearPendingCommunityAvatarFile } from "../../../../lib/create/pendingCommunityAvatarUpload";
|
||||||
|
import {
|
||||||
|
clearTransferPendingFlag,
|
||||||
|
writeAnonymousCreateFlowState,
|
||||||
|
} from "./anonymousDraftStorage";
|
||||||
|
import { writeCoreValueDetailsToLocalStorage } from "./coreValueDetailsLocalStorage";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Profile already has the server draft. Write that snapshot into the browser
|
||||||
|
* before opening the wizard so the create flow can mount it immediately,
|
||||||
|
* including when backend sync is off and hydration will not refetch.
|
||||||
|
*/
|
||||||
|
export function seedContinuedDraftLocalStorage(state: CreateFlowState): void {
|
||||||
|
writeAnonymousCreateFlowState(state);
|
||||||
|
writeCoreValueDetailsToLocalStorage(state.coreValueDetailsByChipId);
|
||||||
|
clearTransferPendingFlag();
|
||||||
|
forgetFlushedCommunityAvatarUrl();
|
||||||
|
void clearPendingCommunityAvatarFile();
|
||||||
|
}
|
||||||
@@ -23,7 +23,9 @@ import {
|
|||||||
downloadStoredRuleAsPdf,
|
downloadStoredRuleAsPdf,
|
||||||
} from "../../../lib/create/ruleExport";
|
} from "../../../lib/create/ruleExport";
|
||||||
import {
|
import {
|
||||||
|
clearLastPublishedRule,
|
||||||
finishedAtIso,
|
finishedAtIso,
|
||||||
|
readLastPublishedRule,
|
||||||
writeLastPublishedRule,
|
writeLastPublishedRule,
|
||||||
type StoredLastPublishedRule,
|
type StoredLastPublishedRule,
|
||||||
} from "../../../lib/create/lastPublishedRule";
|
} from "../../../lib/create/lastPublishedRule";
|
||||||
@@ -31,28 +33,19 @@ import {
|
|||||||
CREATE_FLOW_MANAGE_STAKEHOLDERS_QUERY,
|
CREATE_FLOW_MANAGE_STAKEHOLDERS_QUERY,
|
||||||
CREATE_FLOW_MANAGE_STAKEHOLDERS_VALUE,
|
CREATE_FLOW_MANAGE_STAKEHOLDERS_VALUE,
|
||||||
CREATE_FLOW_REVIEW_RETURN_QUERY_KEY,
|
CREATE_FLOW_REVIEW_RETURN_QUERY_KEY,
|
||||||
FIRST_STEP,
|
resumeCreateFlowStep,
|
||||||
isValidStep,
|
|
||||||
} from "../create/utils/flowSteps";
|
} from "../create/utils/flowSteps";
|
||||||
import type { CreateFlowStep } from "../create/types";
|
|
||||||
import { clearAnonymousCreateFlowStorage } from "../create/utils/anonymousDraftStorage";
|
import { clearAnonymousCreateFlowStorage } from "../create/utils/anonymousDraftStorage";
|
||||||
import { clearCoreValueDetailsLocalStorage } from "../create/utils/coreValueDetailsLocalStorage";
|
import { clearBrowserRuleData } from "../create/utils/clearBrowserRuleData";
|
||||||
import { prepareFreshCreateFlowEntrySync } from "../create/utils/prepareFreshCreateFlowEntry";
|
import { createRuleEntryPath } from "../create/utils/createRuleEntry";
|
||||||
import { createFlowStepPath } from "../create/utils/createFlowPaths";
|
import { createFlowStepPath } from "../create/utils/createFlowPaths";
|
||||||
|
import { seedContinuedDraftLocalStorage } from "../create/utils/seedContinuedDraftLocalStorage";
|
||||||
import { useMediaQuery } from "../../hooks/useMediaQuery";
|
import { useMediaQuery } from "../../hooks/useMediaQuery";
|
||||||
import {
|
import {
|
||||||
ProfilePageSignedOutView,
|
ProfilePageSignedOutView,
|
||||||
ProfilePageView,
|
ProfilePageView,
|
||||||
} from "./_components/ProfilePage.view";
|
} from "./_components/ProfilePage.view";
|
||||||
|
|
||||||
function resolveContinueStepState(
|
|
||||||
state: { currentStep?: CreateFlowStep } & Record<string, unknown>,
|
|
||||||
): CreateFlowStep {
|
|
||||||
const s = state.currentStep;
|
|
||||||
if (s && isValidStep(s)) return s;
|
|
||||||
return FIRST_STEP;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function ProfilePageClient() {
|
export default function ProfilePageClient() {
|
||||||
const t = useTranslation("pages.profile");
|
const t = useTranslation("pages.profile");
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -203,6 +196,7 @@ export default function ProfilePageClient() {
|
|||||||
const handleSignOut = useCallback(async () => {
|
const handleSignOut = useCallback(async () => {
|
||||||
setActionError(null);
|
setActionError(null);
|
||||||
await logout();
|
await logout();
|
||||||
|
clearBrowserRuleData();
|
||||||
setUser(null);
|
setUser(null);
|
||||||
setRules([]);
|
setRules([]);
|
||||||
setDraft(null);
|
setDraft(null);
|
||||||
@@ -228,6 +222,8 @@ export default function ProfilePageClient() {
|
|||||||
const res = await deletePublishedRule(id);
|
const res = await deletePublishedRule(id);
|
||||||
setRuleDeleteBusy(false);
|
setRuleDeleteBusy(false);
|
||||||
if (res.ok === true) {
|
if (res.ok === true) {
|
||||||
|
const stored = readLastPublishedRule();
|
||||||
|
if (stored?.id === id) clearLastPublishedRule();
|
||||||
setRuleDeleteTargetId(null);
|
setRuleDeleteTargetId(null);
|
||||||
void load();
|
void load();
|
||||||
return;
|
return;
|
||||||
@@ -297,15 +293,13 @@ export default function ProfilePageClient() {
|
|||||||
|
|
||||||
const handleContinueDraft = useCallback(() => {
|
const handleContinueDraft = useCallback(() => {
|
||||||
if (draft == null || !draft.hasDraft) return;
|
if (draft == null || !draft.hasDraft) return;
|
||||||
const step = resolveContinueStepState(draft.state);
|
const step = resumeCreateFlowStep(draft.state);
|
||||||
clearAnonymousCreateFlowStorage();
|
seedContinuedDraftLocalStorage(draft.state);
|
||||||
clearCoreValueDetailsLocalStorage();
|
router.push(createFlowStepPath(step));
|
||||||
router.push(`/create/${step}`);
|
|
||||||
}, [draft, router]);
|
}, [draft, router]);
|
||||||
|
|
||||||
const handleStartNewCustomRule = useCallback(() => {
|
const handleStartNewCustomRule = useCallback(() => {
|
||||||
prepareFreshCreateFlowEntrySync({ signedIn: true });
|
router.push(createRuleEntryPath());
|
||||||
router.push("/create/informational");
|
|
||||||
}, [router]);
|
}, [router]);
|
||||||
|
|
||||||
const handleRequestDeleteDraft = useCallback(() => {
|
const handleRequestDeleteDraft = useCallback(() => {
|
||||||
@@ -392,6 +386,7 @@ export default function ProfilePageClient() {
|
|||||||
const res = await deleteAccount();
|
const res = await deleteAccount();
|
||||||
setAccountDeleteBusy(false);
|
setAccountDeleteBusy(false);
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
|
clearBrowserRuleData();
|
||||||
setAccountDeleteOpen(false);
|
setAccountDeleteOpen(false);
|
||||||
setUser(null);
|
setUser(null);
|
||||||
setRules([]);
|
setRules([]);
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import Alert from "../../../components/modals/Alert";
|
|||||||
import HeaderLockup from "../../../components/type/HeaderLockup";
|
import HeaderLockup from "../../../components/type/HeaderLockup";
|
||||||
import { useTranslation } from "../../../contexts/MessagesContext";
|
import { useTranslation } from "../../../contexts/MessagesContext";
|
||||||
import type { CreateFlowState } from "../../create/types";
|
import type { CreateFlowState } from "../../create/types";
|
||||||
|
import { createCompletedPath } from "../../create/utils/createFlowPaths";
|
||||||
import type {
|
import type {
|
||||||
MyPublishedRule,
|
MyPublishedRule,
|
||||||
ServerDraftForProfile,
|
ServerDraftForProfile,
|
||||||
@@ -257,7 +258,7 @@ export function ProfilePageView({
|
|||||||
id: "create-template",
|
id: "create-template",
|
||||||
title: t("optionCreateTemplate"),
|
title: t("optionCreateTemplate"),
|
||||||
description: "",
|
description: "",
|
||||||
href: "/templates?fromFlow=1",
|
href: "/templates",
|
||||||
leadingIcon: "content_copy",
|
leadingIcon: "content_copy",
|
||||||
showDescription: false,
|
showDescription: false,
|
||||||
},
|
},
|
||||||
@@ -355,7 +356,7 @@ export function ProfilePageView({
|
|||||||
createLabel={t("emptyCardCreate")}
|
createLabel={t("emptyCardCreate")}
|
||||||
browseLabel={t("emptyCardBrowse")}
|
browseLabel={t("emptyCardBrowse")}
|
||||||
onCreate={onStartNewCustomRule}
|
onCreate={onStartNewCustomRule}
|
||||||
browseHref="/templates?fromFlow=1"
|
browseHref="/templates"
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex flex-col gap-3">
|
<div className="flex flex-col gap-3">
|
||||||
@@ -399,6 +400,8 @@ export function ProfilePageView({
|
|||||||
description={rule.summary ?? undefined}
|
description={rule.summary ?? undefined}
|
||||||
expanded
|
expanded
|
||||||
size={ruleCardSize}
|
size={ruleCardSize}
|
||||||
|
href={createCompletedPath({ ruleId: rule.id })}
|
||||||
|
ariaLabel={rule.title}
|
||||||
hasBottomLinks
|
hasBottomLinks
|
||||||
bottomStatusLabel={t("finishedBadge")}
|
bottomStatusLabel={t("finishedBadge")}
|
||||||
bottomLinks={[
|
bottomLinks={[
|
||||||
@@ -422,7 +425,7 @@ export function ProfilePageView({
|
|||||||
rule.title,
|
rule.title,
|
||||||
)}
|
)}
|
||||||
backgroundColor="bg-[var(--color-surface-invert-brand-teal)]"
|
backgroundColor="bg-[var(--color-surface-invert-brand-teal)]"
|
||||||
className={ownedRuleCardShellClass}
|
className={ruleCardShellClass}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -449,7 +452,8 @@ export function ProfilePageView({
|
|||||||
description={rule.summary ?? undefined}
|
description={rule.summary ?? undefined}
|
||||||
expanded
|
expanded
|
||||||
size={ruleCardSize}
|
size={ruleCardSize}
|
||||||
href={`/invite/${encodeURIComponent(rule.id)}`}
|
href={`/rules/${encodeURIComponent(rule.id)}`}
|
||||||
|
ariaLabel={rule.title}
|
||||||
communityInitials={communityInitialsFromTitle(
|
communityInitials={communityInitialsFromTitle(
|
||||||
rule.title,
|
rule.title,
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { useSearchParams } from "next/navigation";
|
|||||||
import HeaderLockup from "../../components/type/HeaderLockup";
|
import HeaderLockup from "../../components/type/HeaderLockup";
|
||||||
import { GovernanceTemplateGrid } from "../../components/sections/GovernanceTemplateGrid";
|
import { GovernanceTemplateGrid } from "../../components/sections/GovernanceTemplateGrid";
|
||||||
import type { TemplateGridCardEntry } from "../../../lib/templates/templateGridPresentation";
|
import type { TemplateGridCardEntry } from "../../../lib/templates/templateGridPresentation";
|
||||||
import { prepareFreshCreateFlowEntrySync } from "../../(app)/create/utils/prepareFreshCreateFlowEntry";
|
|
||||||
import { buildTemplateReviewHref } from "../../(app)/create/utils/flowSteps";
|
import { buildTemplateReviewHref } from "../../(app)/create/utils/flowSteps";
|
||||||
import { useTranslation } from "../../contexts/MessagesContext";
|
import { useTranslation } from "../../contexts/MessagesContext";
|
||||||
|
|
||||||
@@ -62,8 +61,7 @@ export default function TemplatesPageClient({
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* - `fromFlow=1` — skip `prepareFreshCreateFlowEntry` on template click
|
* - `fromFlow=1` — in-wizard catalog; community answers stay until apply.
|
||||||
* (draft preserved). Used by profile “Create from template”.
|
|
||||||
* Templates carry no recommendation; the grid stays in curated order.
|
* Templates carry no recommendation; the grid stays in curated order.
|
||||||
*/
|
*/
|
||||||
function TemplatesGridWithSearchParams({
|
function TemplatesGridWithSearchParams({
|
||||||
@@ -91,13 +89,6 @@ function TemplatesGrid({
|
|||||||
hrefForTemplate={(slug) =>
|
hrefForTemplate={(slug) =>
|
||||||
buildTemplateReviewHref(slug, { fromCreateWizard: fromFlow })
|
buildTemplateReviewHref(slug, { fromCreateWizard: fromFlow })
|
||||||
}
|
}
|
||||||
onTemplateClick={() => {
|
|
||||||
if (!fromFlow) {
|
|
||||||
// Marketing /templates has no session in hand; DELETE is
|
|
||||||
// best-effort and the sentinel blocks stale-draft hydration.
|
|
||||||
prepareFreshCreateFlowEntrySync({ signedIn: true });
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { NextResponse } from "next/server";
|
import { NextResponse } from "next/server";
|
||||||
import { isDatabaseConfigured } from "../../../../lib/server/env";
|
import { isDatabaseConfigured } from "../../../../lib/server/env";
|
||||||
import { dbUnavailable } from "../../../../lib/server/responses";
|
import { dbUnavailable } from "../../../../lib/server/responses";
|
||||||
|
import { clearGuestRuleClaimCookie } from "../../../../lib/server/guestRuleClaim";
|
||||||
import { destroySessionFromRequest } from "../../../../lib/server/session";
|
import { destroySessionFromRequest } from "../../../../lib/server/session";
|
||||||
import { apiRoute } from "../../../../lib/server/apiRoute";
|
import { apiRoute } from "../../../../lib/server/apiRoute";
|
||||||
|
|
||||||
@@ -10,5 +11,6 @@ export const POST = apiRoute("auth.logout", async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await destroySessionFromRequest();
|
await destroySessionFromRequest();
|
||||||
|
await clearGuestRuleClaimCookie();
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
});
|
});
|
||||||
@@ -11,7 +11,7 @@ import { apiRoute } from "../../../../lib/server/apiRoute";
|
|||||||
import { putDraftBodySchema } from "../../../../lib/server/validation/createFlowSchemas";
|
import { putDraftBodySchema } from "../../../../lib/server/validation/createFlowSchemas";
|
||||||
import { readLimitedJson } from "../../../../lib/server/validation/requestBody";
|
import { readLimitedJson } from "../../../../lib/server/validation/requestBody";
|
||||||
import { jsonFromZodError } from "../../../../lib/server/validation/zodHttp";
|
import { jsonFromZodError } from "../../../../lib/server/validation/zodHttp";
|
||||||
import { deleteUploadsForDraft } from "../../../../lib/server/uploads/deleteUploadedFiles";
|
import { deleteRuleDraftForUser } from "../../../../lib/server/ruleDrafts";
|
||||||
import { linkUploadsToDraft } from "../../../../lib/server/uploads/linkUploads";
|
import { linkUploadsToDraft } from "../../../../lib/server/uploads/linkUploads";
|
||||||
|
|
||||||
export const GET = apiRoute("drafts.me.get", async () => {
|
export const GET = apiRoute("drafts.me.get", async () => {
|
||||||
@@ -92,14 +92,7 @@ export const DELETE = apiRoute("drafts.me.delete", async () => {
|
|||||||
|
|
||||||
// Idempotent: missing draft is a no-op so callers can fire-and-forget after
|
// Idempotent: missing draft is a no-op so callers can fire-and-forget after
|
||||||
// publish / exit without worrying about prior state.
|
// publish / exit without worrying about prior state.
|
||||||
const draft = await prisma.ruleDraft.findUnique({
|
await deleteRuleDraftForUser(user.id);
|
||||||
where: { userId: user.id },
|
|
||||||
select: { id: true },
|
|
||||||
});
|
|
||||||
if (draft) {
|
|
||||||
await deleteUploadsForDraft(draft.id);
|
|
||||||
}
|
|
||||||
await prisma.ruleDraft.deleteMany({ where: { userId: user.id } });
|
|
||||||
|
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
});
|
});
|
||||||
@@ -35,10 +35,36 @@ import {
|
|||||||
import { readLimitedJson } from "../../../lib/server/validation/requestBody";
|
import { readLimitedJson } from "../../../lib/server/validation/requestBody";
|
||||||
import { jsonFromZodError } from "../../../lib/server/validation/zodHttp";
|
import { jsonFromZodError } from "../../../lib/server/validation/zodHttp";
|
||||||
import { publishedRuleAnalyticsColumns } from "../../../lib/server/publishedRulePersist";
|
import { publishedRuleAnalyticsColumns } from "../../../lib/server/publishedRulePersist";
|
||||||
|
import { deleteRuleDraftForUser } from "../../../lib/server/ruleDrafts";
|
||||||
|
|
||||||
/** One anonymous publish per IP per minute (in-memory limiter). */
|
/** One anonymous publish per IP per minute (in-memory limiter). */
|
||||||
const ANONYMOUS_PUBLISH_IP_MIN_INTERVAL_MS = 60_000;
|
const ANONYMOUS_PUBLISH_IP_MIN_INTERVAL_MS = 60_000;
|
||||||
|
|
||||||
|
const DRAFT_DELETE_ATTEMPTS = 3;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The rule is already saved. Retry clearing the source draft so Profile does
|
||||||
|
* not keep showing it as in progress. A leftover draft is logged, not a
|
||||||
|
* failed publish.
|
||||||
|
*/
|
||||||
|
async function deleteDraftAfterPublish(
|
||||||
|
userId: string,
|
||||||
|
requestId: string,
|
||||||
|
): Promise<void> {
|
||||||
|
let lastError: unknown;
|
||||||
|
for (let attempt = 0; attempt < DRAFT_DELETE_ATTEMPTS; attempt += 1) {
|
||||||
|
try {
|
||||||
|
await deleteRuleDraftForUser(userId);
|
||||||
|
return;
|
||||||
|
} catch (err) {
|
||||||
|
lastError = err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
logRouteError("rules.publish", requestId, lastError, {
|
||||||
|
phase: "deleteRuleDraftForUser",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function clientIp(request: NextRequest): string {
|
function clientIp(request: NextRequest): string {
|
||||||
return (
|
return (
|
||||||
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??
|
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ??
|
||||||
@@ -170,6 +196,7 @@ export const POST = apiRoute(
|
|||||||
document,
|
document,
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
});
|
});
|
||||||
|
await deleteDraftAfterPublish(user.id, requestId);
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
rule: {
|
rule: {
|
||||||
@@ -261,6 +288,7 @@ export const POST = apiRoute(
|
|||||||
document,
|
document,
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
});
|
});
|
||||||
|
await deleteDraftAfterPublish(user.id, requestId);
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
rule: {
|
rule: {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
internalError,
|
internalError,
|
||||||
unauthorized,
|
unauthorized,
|
||||||
} from "../../../../lib/server/responses";
|
} from "../../../../lib/server/responses";
|
||||||
|
import { clearGuestRuleClaimCookie } from "../../../../lib/server/guestRuleClaim";
|
||||||
import {
|
import {
|
||||||
clearSessionCookie,
|
clearSessionCookie,
|
||||||
getSessionUser,
|
getSessionUser,
|
||||||
@@ -37,6 +38,7 @@ export const DELETE = apiRoute("user.me.delete", async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await clearSessionCookie();
|
await clearSessionCookie();
|
||||||
|
await clearGuestRuleClaimCookie();
|
||||||
|
|
||||||
return NextResponse.json({ ok: true });
|
return NextResponse.json({ ok: true });
|
||||||
});
|
});
|
||||||
@@ -36,6 +36,7 @@ const RuleContainer = memo<RuleProps>(
|
|||||||
className = "",
|
className = "",
|
||||||
onClick,
|
onClick,
|
||||||
href,
|
href,
|
||||||
|
ariaLabel: ariaLabelProp,
|
||||||
expanded = false,
|
expanded = false,
|
||||||
size: sizeProp,
|
size: sizeProp,
|
||||||
categories,
|
categories,
|
||||||
@@ -67,7 +68,11 @@ const RuleContainer = memo<RuleProps>(
|
|||||||
const size = sizeProp ?? "L";
|
const size = sizeProp ?? "L";
|
||||||
const isInteractive = interactive ?? !hasBottomLinks;
|
const isInteractive = interactive ?? !hasBottomLinks;
|
||||||
const t = useTranslation("ruleCard");
|
const t = useTranslation("ruleCard");
|
||||||
const cardAriaLabel = t("ariaLabel")?.replace("{title}", title) || title;
|
const trimmedAriaLabel = ariaLabelProp?.trim() ?? "";
|
||||||
|
const cardAriaLabel =
|
||||||
|
trimmedAriaLabel.length > 0
|
||||||
|
? trimmedAriaLabel
|
||||||
|
: t("ariaLabel")?.replace("{title}", title) || title;
|
||||||
const recommendedLabel = t("recommendedLabel");
|
const recommendedLabel = t("recommendedLabel");
|
||||||
|
|
||||||
const handleClick = () => {
|
const handleClick = () => {
|
||||||
@@ -111,7 +116,7 @@ const RuleContainer = memo<RuleProps>(
|
|||||||
icon={icon}
|
icon={icon}
|
||||||
backgroundColor={backgroundColor}
|
backgroundColor={backgroundColor}
|
||||||
className={className}
|
className={className}
|
||||||
href={isInteractive && !hasBottomLinks ? href : undefined}
|
href={href}
|
||||||
onClick={isInteractive && !hasBottomLinks ? handleClick : undefined}
|
onClick={isInteractive && !hasBottomLinks ? handleClick : undefined}
|
||||||
onKeyDown={
|
onKeyDown={
|
||||||
isInteractive && !hasBottomLinks && !href ? handleKeyDown : undefined
|
isInteractive && !hasBottomLinks && !href ? handleKeyDown : undefined
|
||||||
|
|||||||
@@ -56,9 +56,16 @@ export interface RuleProps {
|
|||||||
onClick?: () => void;
|
onClick?: () => void;
|
||||||
/**
|
/**
|
||||||
* When set, the card is a real link (focusable, Enter, open in a new tab)
|
* When set, the card is a real link (focusable, Enter, open in a new tab)
|
||||||
* instead of a click-only `role="button"` surface.
|
* instead of a click-only `role="button"` surface. Combined with
|
||||||
|
* {@link hasBottomLinks}, the link is a stretched overlay so Invite /
|
||||||
|
* Duplicate / Delete stay separate controls.
|
||||||
*/
|
*/
|
||||||
href?: string;
|
href?: string;
|
||||||
|
/**
|
||||||
|
* Accessible name for the card or its overlay link. Defaults to the
|
||||||
|
* `ruleCard` “Learn more about {title}…” string.
|
||||||
|
*/
|
||||||
|
ariaLabel?: string;
|
||||||
expanded?: boolean;
|
expanded?: boolean;
|
||||||
size?: RuleSizeValue;
|
size?: RuleSizeValue;
|
||||||
categories?: Category[];
|
categories?: Category[];
|
||||||
|
|||||||
@@ -298,6 +298,7 @@ export function RuleView({
|
|||||||
<NavigationLink
|
<NavigationLink
|
||||||
key={link.id}
|
key={link.id}
|
||||||
{...shared}
|
{...shared}
|
||||||
|
className={`${shared.className} pointer-events-auto relative z-10`}
|
||||||
href={link.href}
|
href={link.href}
|
||||||
onClick={(e) => e.stopPropagation()}
|
onClick={(e) => e.stopPropagation()}
|
||||||
/>
|
/>
|
||||||
@@ -307,6 +308,7 @@ export function RuleView({
|
|||||||
<NavigationLink
|
<NavigationLink
|
||||||
key={link.id}
|
key={link.id}
|
||||||
{...shared}
|
{...shared}
|
||||||
|
className={`${shared.className} pointer-events-auto relative z-10`}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
link.onClick?.();
|
link.onClick?.();
|
||||||
@@ -319,7 +321,8 @@ export function RuleView({
|
|||||||
const surfaceStyle = surfaceColor
|
const surfaceStyle = surfaceColor
|
||||||
? { backgroundColor: surfaceColor }
|
? { backgroundColor: surfaceColor }
|
||||||
: undefined;
|
: undefined;
|
||||||
const isLinkCard = Boolean(href) && interactiveCard;
|
const isLinkCard = Boolean(href) && interactiveCard && !hasBottomLinks;
|
||||||
|
const overlayHref = hasBottomLinks && href ? href : undefined;
|
||||||
|
|
||||||
const hasCategories = Boolean(categories && categories.length > 0);
|
const hasCategories = Boolean(categories && categories.length > 0);
|
||||||
const expandedDescriptionFrameClass = [
|
const expandedDescriptionFrameClass = [
|
||||||
@@ -610,6 +613,27 @@ export function RuleView({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (overlayHref) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`${cardClassName} cursor-pointer`}
|
||||||
|
style={surfaceStyle}
|
||||||
|
role="article"
|
||||||
|
>
|
||||||
|
<NextLink
|
||||||
|
href={overlayHref}
|
||||||
|
className="absolute inset-0 z-0 rounded-[inherit]"
|
||||||
|
aria-label={ariaLabel}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
className={`relative z-[1] flex w-full flex-col items-start pointer-events-none ${cardGap}`}
|
||||||
|
>
|
||||||
|
{cardBody}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={cardClassName}
|
className={cardClassName}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import type { Category, RuleProps } from "../Rule";
|
|||||||
import { getAssetPath } from "../../../../lib/assetUtils";
|
import { getAssetPath } from "../../../../lib/assetUtils";
|
||||||
import type { RuleTemplateDto } from "../../../../lib/create/fetchTemplates";
|
import type { RuleTemplateDto } from "../../../../lib/create/fetchTemplates";
|
||||||
import {
|
import {
|
||||||
templateBodyToReviewData,
|
templateReviewDataForSlug,
|
||||||
templateSummaryFromBody,
|
templateSummaryFromBody,
|
||||||
} from "../../../../lib/create/templateReviewMapping";
|
} from "../../../../lib/create/templateReviewMapping";
|
||||||
import {
|
import {
|
||||||
@@ -26,9 +26,9 @@ export interface TemplateReviewCardProps {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Expanded Rule for template review: surfaces + icon from Figma catalog (21764-16435);
|
* Expanded Rule for template review: surfaces + icon from Figma catalog (21764-16435);
|
||||||
* tag rows from API `body`. Chip clicks open a read-only detail modal per
|
* tag rows from the remade catalog chips. Chip clicks open a read-only detail
|
||||||
* facet group (values / communication / membership / decision-making / conflict
|
* modal per facet group (values / communication / membership / decision-making /
|
||||||
* management) so reviewers can see what each chip means without editing.
|
* conflict management) so reviewers can see what each chip means without editing.
|
||||||
*/
|
*/
|
||||||
export function TemplateReviewCard({
|
export function TemplateReviewCard({
|
||||||
template,
|
template,
|
||||||
@@ -38,8 +38,8 @@ export function TemplateReviewCard({
|
|||||||
const catalog = getGovernanceTemplateCatalogEntry(template.slug);
|
const catalog = getGovernanceTemplateCatalogEntry(template.slug);
|
||||||
const pres = catalog ?? TEMPLATE_GRID_FALLBACK_PRESENTATION;
|
const pres = catalog ?? TEMPLATE_GRID_FALLBACK_PRESENTATION;
|
||||||
const { categories: rawCategories, chipDetailsByChipId } = useMemo(
|
const { categories: rawCategories, chipDetailsByChipId } = useMemo(
|
||||||
() => templateBodyToReviewData(template.body),
|
() => templateReviewDataForSlug(template.slug, template.body),
|
||||||
[template.body],
|
[template.slug, template.body],
|
||||||
);
|
);
|
||||||
const summary = templateSummaryFromBody(template.description, template.body);
|
const summary = templateSummaryFromBody(template.description, template.body);
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { buildCreateFlowDraftPayload } from "../../../../lib/create/buildCreateF
|
|||||||
import { MAGIC_LINK_TTL_MINUTES } from "../../../../lib/privacyRetention";
|
import { MAGIC_LINK_TTL_MINUTES } from "../../../../lib/privacyRetention";
|
||||||
import { safeInternalPath } from "../../../../lib/safeInternalPath";
|
import { safeInternalPath } from "../../../../lib/safeInternalPath";
|
||||||
import {
|
import {
|
||||||
|
clearTransferPendingFlag,
|
||||||
readAnonymousCreateFlowState,
|
readAnonymousCreateFlowState,
|
||||||
setTransferPendingFlag,
|
setTransferPendingFlag,
|
||||||
} from "../../../(app)/create/utils/anonymousDraftStorage";
|
} from "../../../(app)/create/utils/anonymousDraftStorage";
|
||||||
@@ -212,6 +213,7 @@ export default function LoginForm({
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isExpiredLinkError(errorParam)) {
|
if (isExpiredLinkError(errorParam)) {
|
||||||
setLinkExpired(true);
|
setLinkExpired(true);
|
||||||
|
clearTransferPendingFlag();
|
||||||
}
|
}
|
||||||
}, [errorParam]);
|
}, [errorParam]);
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import AvatarContainer from "../../asset/AvatarContainer";
|
|||||||
import Avatar from "../../asset/Avatar";
|
import Avatar from "../../asset/Avatar";
|
||||||
import { getAssetPath, ASSETS } from "../../../../lib/assetUtils";
|
import { getAssetPath, ASSETS } from "../../../../lib/assetUtils";
|
||||||
import { PRODUCTION_SITE_ORIGIN, websiteJsonLd } from "../../../../lib/siteMetadata";
|
import { PRODUCTION_SITE_ORIGIN, websiteJsonLd } from "../../../../lib/siteMetadata";
|
||||||
import { prepareFreshCreateFlowEntrySync } from "../../../(app)/create/utils/prepareFreshCreateFlowEntry";
|
import { createRuleEntryPath } from "../../../(app)/create/utils/createRuleEntry";
|
||||||
import { TopView } from "./Top.view";
|
import { TopView } from "./Top.view";
|
||||||
import type { TopProps } from "./Top.types";
|
import type { TopProps } from "./Top.types";
|
||||||
|
|
||||||
@@ -59,16 +59,12 @@ const TopContainer = memo<TopProps>(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* `Top` is hidden on `/create` routes by ConditionalNavigationClient, so
|
* `Top` is hidden on `/create` routes by ConditionalNavigationClient, so
|
||||||
* this button is always clicked from outside the wizard. Clears anonymous
|
* this button is always clicked from outside the wizard. Resume the draft
|
||||||
* `localStorage` synchronously and, when backend sync is on, fires the
|
* in the browser instead of wiping it.
|
||||||
* server `DELETE /api/drafts/me` in the background. `SignedInDraftHydration`
|
|
||||||
* reads the `create:fresh-entry-pending` sentinel and waits before fetching
|
|
||||||
* (see {@link prepareFreshCreateFlowEntrySync}).
|
|
||||||
*/
|
*/
|
||||||
const handleCreateRuleClick = useCallback(() => {
|
const handleCreateRuleClick = useCallback(() => {
|
||||||
prepareFreshCreateFlowEntrySync({ signedIn: loggedIn });
|
router.push(createRuleEntryPath());
|
||||||
router.push("/create/informational");
|
}, [router]);
|
||||||
}, [loggedIn, router]);
|
|
||||||
|
|
||||||
const schemaData = websiteJsonLd(siteOrigin);
|
const schemaData = websiteJsonLd(siteOrigin);
|
||||||
|
|
||||||
|
|||||||
@@ -4,11 +4,10 @@
|
|||||||
* Figma: "Section / Hero Banner" (18477:15473)
|
* Figma: "Section / Hero Banner" (18477:15473)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { memo, useCallback, useEffect, useMemo, useState } from "react";
|
import { memo, useCallback, useMemo } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useMessages, useTranslation } from "../../../contexts/MessagesContext";
|
import { useMessages, useTranslation } from "../../../contexts/MessagesContext";
|
||||||
import { fetchAuthSession } from "../../../../lib/create/api";
|
import { createRuleEntryPath } from "../../../(app)/create/utils/createRuleEntry";
|
||||||
import { prepareFreshCreateFlowEntrySync } from "../../../(app)/create/utils/prepareFreshCreateFlowEntry";
|
|
||||||
import type { Category } from "../../cards/Rule";
|
import type { Category } from "../../cards/Rule";
|
||||||
import type { ChipOption } from "../../controls/MultiSelect/MultiSelect.types";
|
import type { ChipOption } from "../../controls/MultiSelect/MultiSelect.types";
|
||||||
import HeroBannerView from "./HeroBanner.view";
|
import HeroBannerView from "./HeroBanner.view";
|
||||||
@@ -28,26 +27,10 @@ const HeroBannerContainer = memo<HeroBannerProps>(
|
|||||||
const messages = useMessages();
|
const messages = useMessages();
|
||||||
const tHome = useTranslation("pages.home.heroBanner");
|
const tHome = useTranslation("pages.home.heroBanner");
|
||||||
const tHero = useTranslation("heroBanner");
|
const tHero = useTranslation("heroBanner");
|
||||||
const [signedIn, setSignedIn] = useState(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
let cancelled = false;
|
|
||||||
void fetchAuthSession()
|
|
||||||
.then(({ user }) => {
|
|
||||||
if (!cancelled) setSignedIn(Boolean(user));
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
/* guest fallback */
|
|
||||||
});
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const handleCreateRule = useCallback(() => {
|
const handleCreateRule = useCallback(() => {
|
||||||
prepareFreshCreateFlowEntrySync({ signedIn });
|
router.push(createRuleEntryPath());
|
||||||
router.push("/create/informational");
|
}, [router]);
|
||||||
}, [router, signedIn]);
|
|
||||||
|
|
||||||
const ruleCategories = useMemo<Category[]>(() => {
|
const ruleCategories = useMemo<Category[]>(() => {
|
||||||
const groups = messages.heroBanner.ruleCard.categories;
|
const groups = messages.heroBanner.ruleCard.categories;
|
||||||
|
|||||||
@@ -7,7 +7,6 @@
|
|||||||
import { memo, useEffect, useState } from "react";
|
import { memo, useEffect, useState } from "react";
|
||||||
import { useTranslation } from "../../../contexts/MessagesContext";
|
import { useTranslation } from "../../../contexts/MessagesContext";
|
||||||
import { logger } from "../../../../lib/logger";
|
import { logger } from "../../../../lib/logger";
|
||||||
import { prepareFreshCreateFlowEntrySync } from "../../../(app)/create/utils/prepareFreshCreateFlowEntry";
|
|
||||||
import { buildTemplateReviewHref } from "../../../(app)/create/utils/flowSteps";
|
import { buildTemplateReviewHref } from "../../../(app)/create/utils/flowSteps";
|
||||||
import {
|
import {
|
||||||
fetchTemplates,
|
fetchTemplates,
|
||||||
@@ -96,10 +95,6 @@ const RuleStackContainer = memo<RuleStackProps>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
logger.debug(`${slug} template clicked`);
|
logger.debug(`${slug} template clicked`);
|
||||||
// Marketing home “Popular templates”: same fresh start as Top “Create rule”.
|
|
||||||
// `signedIn: true` because this surface has no session in hand; DELETE is
|
|
||||||
// best-effort and the sentinel blocks stale-draft hydration.
|
|
||||||
prepareFreshCreateFlowEntrySync({ signedIn: true });
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -4,38 +4,21 @@
|
|||||||
* Figma: "Section / Your Turn" (24239:1397)
|
* Figma: "Section / Your Turn" (24239:1397)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { memo, useCallback, useEffect, useState } from "react";
|
import { memo, useCallback, useState } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useMessages } from "../../../contexts/MessagesContext";
|
import { useMessages } from "../../../contexts/MessagesContext";
|
||||||
import { fetchAuthSession } from "../../../../lib/create/api";
|
import { createRuleEntryPath } from "../../../(app)/create/utils/createRuleEntry";
|
||||||
import { prepareFreshCreateFlowEntrySync } from "../../../(app)/create/utils/prepareFreshCreateFlowEntry";
|
|
||||||
import AskOrganizerInquiryModal from "../../modals/AskOrganizerInquiry";
|
import AskOrganizerInquiryModal from "../../modals/AskOrganizerInquiry";
|
||||||
import YourTurnView from "./YourTurn.view";
|
import YourTurnView from "./YourTurn.view";
|
||||||
|
|
||||||
const YourTurnContainer = memo(() => {
|
const YourTurnContainer = memo(() => {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const copy = useMessages().pages.about.yourTurn;
|
const copy = useMessages().pages.about.yourTurn;
|
||||||
const [signedIn, setSignedIn] = useState(false);
|
|
||||||
const [inquiryOpen, setInquiryOpen] = useState(false);
|
const [inquiryOpen, setInquiryOpen] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
let cancelled = false;
|
|
||||||
void fetchAuthSession()
|
|
||||||
.then(({ user }) => {
|
|
||||||
if (!cancelled) setSignedIn(Boolean(user));
|
|
||||||
})
|
|
||||||
.catch(() => {
|
|
||||||
/* guest fallback */
|
|
||||||
});
|
|
||||||
return () => {
|
|
||||||
cancelled = true;
|
|
||||||
};
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const onCreateRule = useCallback(() => {
|
const onCreateRule = useCallback(() => {
|
||||||
prepareFreshCreateFlowEntrySync({ signedIn });
|
router.push(createRuleEntryPath());
|
||||||
router.push("/create/informational");
|
}, [router]);
|
||||||
}, [router, signedIn]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
|||||||
+12
-12
@@ -44,7 +44,7 @@ Order is defined in code by [`FLOW_STEP_ORDER`](../app/(app)/create/utils/flowSt
|
|||||||
| 16 | Review and complete | `confirm-stakeholders` | `/create/confirm-stakeholders` |
|
| 16 | Review and complete | `confirm-stakeholders` | `/create/confirm-stakeholders` |
|
||||||
| 17 | Review and complete | `completed` | `/create/completed` |
|
| 17 | Review and complete | `completed` | `/create/completed` |
|
||||||
|
|
||||||
**Primary entry:** marketing header **Create rule** and profile **Create new custom Rule** both run **`prepareFreshCreateFlowEntry`** then navigate to **`/create`**, which redirects to **`/create/informational`** (see [`Top.container.tsx`](../app/components/navigation/Top/Top.container.tsx) and [`ProfilePageClient.tsx`](../app/(app)/profile/ProfilePageClient.tsx)).
|
**Primary entry:** marketing header **Create rule** and profile **Create new custom Rule** both call [`createRuleEntryPath`](../app/(app)/create/utils/createRuleEntry.ts) and resume the browser draft at its last step. They do **not** clear storage or `DELETE /api/drafts/me` (see [`Top.container.tsx`](../app/components/navigation/Top/Top.container.tsx) and [`ProfilePageClient.tsx`](../app/(app)/profile/ProfilePageClient.tsx)).
|
||||||
|
|
||||||
Active step for chrome and navigation is resolved from the pathname via [`parseCreateFlowScreenFromPathname`](../app/(app)/create/utils/flowSteps.ts) inside [`useCreateFlowNavigation`](../app/(app)/create/hooks/useCreateFlowNavigation.ts).
|
Active step for chrome and navigation is resolved from the pathname via [`parseCreateFlowScreenFromPathname`](../app/(app)/create/utils/flowSteps.ts) inside [`useCreateFlowNavigation`](../app/(app)/create/hooks/useCreateFlowNavigation.ts).
|
||||||
|
|
||||||
@@ -62,13 +62,13 @@ 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:** anonymous and signed-in users should see the **same** wizard when starting a **new** rule from marketing or profile: empty state at the first step, with no surprise reload of old work. Both 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). 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`.
|
||||||
|
|
||||||
- **New rule entry** (always a clean slate): call [`prepareFreshCreateFlowEntry`](../app/(app)/create/utils/prepareFreshCreateFlowEntry.ts) **before** `router.push` into `/create` or `/create/review-template/...`. It clears **`create-flow-anonymous`** and the core-value-details `localStorage` key; when sync is on, it **`DELETE`s `/api/drafts/me`** so [`SignedInDraftHydration`](../app/(app)/create/SignedInDraftHydration.tsx) does not rehydrate a stale server draft after local storage was wiped.
|
- **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`. Clear the same `localStorage` keys **only** (see [`ProfilePageClient`](../app/(app)/profile/ProfilePageClient.tsx) `handleContinueDraft`) so the client mirror is empty, then navigate to **`/create/{savedStep}`**. Hydration loads the server draft; the URL may be corrected to `currentStep` when it differs from the path.
|
- **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.
|
||||||
- **Local-only wipe** without touching the server: [`clearCreateFlowPersistedDrafts`](../app/(app)/create/utils/clearCreateFlowPersistedDrafts.ts) (same two `localStorage` keys). Prefer **`prepareFreshCreateFlowEntry`** for any user-facing “start new rule” navigation so signed-in + sync stays aligned with anonymous.
|
- **Confirmed wipe:** [`prepareFreshCreateFlowEntry`](../app/(app)/create/utils/prepareFreshCreateFlowEntry.ts) still clears **`create-flow-anonymous`** and, when sync is on, **`DELETE`s `/api/drafts/me`**. Use it only after the person agrees to start over, including when they confirm replacing a draft with a template.
|
||||||
|
|
||||||
Call sites for **`prepareFreshCreateFlowEntry`**: [`Top.container.tsx`](../app/components/navigation/Top/Top.container.tsx) (Create rule), profile **Create new custom Rule** ([`ProfilePageClient.tsx`](../app/(app)/profile/ProfilePageClient.tsx)), home **Popular templates** ([`RuleStack.container.tsx`](../app/components/sections/RuleStack/RuleStack.container.tsx)), and **direct** `/templates` template picks ([`TemplatesPageClient.tsx`](../app/(marketing)/templates/TemplatesPageClient.tsx)) when **`fromFlow` is absent**.
|
Call sites for **`createRuleEntryPath`**: [`Top.container.tsx`](../app/components/navigation/Top/Top.container.tsx) (Create rule), Home hero, About, and profile **Create new custom Rule** ([`ProfilePageClient.tsx`](../app/(app)/profile/ProfilePageClient.tsx)). Template catalog clicks do **not** wipe a draft; **Use without changes** / **Customize** ask first, then apply from an empty seed.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -91,17 +91,17 @@ From that page, **Customize** opens a dialog for name, optional logo, descriptio
|
|||||||
- **Use without changes (direct)** — home Popular templates, `/templates` without `fromFlow`, or a pasted review-template URL. Identity is collected on the final-review Rule card. Back returns to template review.
|
- **Use without changes (direct)** — home Popular templates, `/templates` without `fromFlow`, or a pasted review-template URL. Identity is collected on the final-review Rule card. Back returns to template review.
|
||||||
- **Use without changes (in-flow)** — `/create/review` → `/create/templates` → template. Community identity is already collected. Back still returns to template review.
|
- **Use without changes (in-flow)** — `/create/review` → `/create/templates` → template. Community identity is already collected. Back still returns to template review.
|
||||||
|
|
||||||
**Direct entry vs in-flow template pick.** The same `/create/review-template/[slug]` URL is reached from two different origins. We disambiguate at the *click site*, not on the review-template page. **Direct** picks call [`prepareFreshCreateFlowEntry`](../app/(app)/create/utils/prepareFreshCreateFlowEntry.ts) **before** navigation (local + server draft when sync is on — see **Fresh start vs continue draft** above). **In-flow** picks skip that call so the user’s community-stage state survives the detour. Because `CreateFlowProvider` reads `localStorage` in its `useState` initializer, clearing **before** `push` means a direct entry mounts without stale anonymous keys; signed-in users also avoid a stale server draft overwriting the empty mirror.
|
**Direct entry vs in-flow template pick.** The same `/create/review-template/[slug]` URL is reached from two different origins. **Direct** picks (home Popular templates, `/templates`) do not wipe a draft on click. **Use without changes** and **Customize** ask before replacing a draft, then seed from the template with no leftover logo or setup answers. **In-flow** picks (`/create/templates?fromFlow=1`) keep the community name, description, and place already given. A hydration latch stops a saved server draft from overwriting the template after apply.
|
||||||
|
|
||||||
| Origin | Click-site behavior | URL the user lands on |
|
| Origin | Click-site behavior | URL the user lands on |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Home marketing "Popular templates" ([`RuleStack.container.tsx`](../app/components/sections/RuleStack/RuleStack.container.tsx)) | always `await prepareFreshCreateFlowEntry()` then navigate | `/create/review-template/[slug]` |
|
| Home marketing "Popular templates" ([`RuleStack.container.tsx`](../app/components/sections/RuleStack/RuleStack.container.tsx)) | navigate only; apply asks before replacing a draft | `/create/review-template/[slug]` |
|
||||||
| `/templates` index ([`TemplatesPageClient.tsx`](../app/(marketing)/templates/TemplatesPageClient.tsx)) visited directly / via pasted URL | `fromFlow` absent → `await prepareFreshCreateFlowEntry()` then navigate | `/create/review-template/[slug]` |
|
| `/templates` index ([`TemplatesPageClient.tsx`](../app/(marketing)/templates/TemplatesPageClient.tsx)) visited directly / via pasted URL | `fromFlow` absent → navigate only | `/create/review-template/[slug]` |
|
||||||
| In-flow: `/create/review` footer "Create from template" → `/create/templates` → template click | no fresh-entry prep; cards are `?fromFlow=1` links | `/create/review-template/[slug]?fromFlow=1` |
|
| In-flow: `/create/review` footer "Create from template" → `/create/templates` → template click | no fresh-entry prep; cards are `?fromFlow=1` links | `/create/review-template/[slug]?fromFlow=1` |
|
||||||
|
|
||||||
Only one `?fromFlow=1` marker exists on template-review URLs. In-flow catalog clicks on `/create/templates` always include it so **Use without changes** can keep in-flow identity instead of clearing it. Profile still uses marketing `/templates?fromFlow=1`. Templates on `/templates` and `/create/templates` show in curated order with no RECOMMENDED tag; facet scoring is unused.
|
Only one `?fromFlow=1` marker exists on template-review URLs. In-flow catalog clicks on `/create/templates` always include it so **Use without changes** can keep in-flow identity instead of clearing it. Profile **Create from template** uses marketing `/templates` without that marker, so a saved draft is not treated as this community’s name. Templates on `/templates` and `/create/templates` show in curated order with no RECOMMENDED tag; facet scoring is unused.
|
||||||
|
|
||||||
**Resume from profile** remains explicit-only: **Continue** clears local mirrors then opens `/create/{step}` so [`SignedInDraftHydration`](../app/(app)/create/SignedInDraftHydration.tsx) can load `/api/drafts/me` when the client buffer is empty. There is no automatic “pick template from marketing → silently merge server draft” path.
|
**Resume from profile** remains explicit-only: **Continue** writes the loaded server draft into the browser, then opens `/create/{step}`. There is no automatic “pick template from marketing → silently merge server draft” path.
|
||||||
|
|
||||||
**Final-review Rule category chips** are derived from `CreateFlowState` via [`buildFinalReviewCategoriesFromState`](../lib/create/buildFinalReviewCategories.ts): for the Customize / plain custom-rule path it resolves `selected{Communication,Membership,DecisionApproach,ConflictManagement}MethodIds` against the curated method presets in `messages/en/create/customRule/*.json`, and `buildCoreValuesForDocument` supplies the `Values` row from `coreValuesChipsSnapshot` + `selectedCoreValueIds`. For the Use-without-changes path the template body lives in `state.sections`; the helper renders `categoryName` + entry titles directly, and preset ids from the chip file keep chips editable. The demo chips shipped in `finalReview.json` remain the fallback only when nothing in state resolves to any chip (e.g. direct navigation for development).
|
**Final-review Rule category chips** are derived from `CreateFlowState` via [`buildFinalReviewCategoriesFromState`](../lib/create/buildFinalReviewCategories.ts): for the Customize / plain custom-rule path it resolves `selected{Communication,Membership,DecisionApproach,ConflictManagement}MethodIds` against the curated method presets in `messages/en/create/customRule/*.json`, and `buildCoreValuesForDocument` supplies the `Values` row from `coreValuesChipsSnapshot` + `selectedCoreValueIds`. For the Use-without-changes path the template body lives in `state.sections`; the helper renders `categoryName` + entry titles directly, and preset ids from the chip file keep chips editable. The demo chips shipped in `finalReview.json` remain the fallback only when nothing in state resolves to any chip (e.g. direct navigation for development).
|
||||||
|
|
||||||
@@ -120,7 +120,7 @@ Details and edge cases (conflict confirm, banners, `?syncDraft=1`) match **Ticke
|
|||||||
|
|
||||||
## Known implementation gaps
|
## Known implementation gaps
|
||||||
|
|
||||||
- **Profile + drafts (CR-86):** The profile page lists the server draft. **Continue** clears anonymous `localStorage` (and core-value details) then deep-links to `/create/{currentStep}` so hydration loads the server draft. **Create new custom Rule** and marketing **Create rule** use **`prepareFreshCreateFlowEntry`** (local + `DELETE /api/drafts/me` when sync is on) before opening the wizard so signed-in behavior matches a fresh anonymous start. `SignedInDraftHydration` may `router.replace` to the saved step when it applies a server draft so the URL matches hydrated state. Remaining edge cases (e.g. template review routes) are handled when they surface in QA.
|
- **Profile + drafts (CR-86):** The profile page lists the server draft. **Continue** clears anonymous `localStorage` (and core-value details) then deep-links to `/create/{currentStep}` so hydration loads the server draft. **Create new custom Rule** and marketing **Create rule** resume the browser draft via **`createRuleEntryPath`** and do not delete the server draft. `SignedInDraftHydration` may `router.replace` to the saved step when it applies a server draft so the URL matches hydrated state. Remaining edge cases (e.g. template review routes) are handled when they surface in QA.
|
||||||
- **Inner “text/select shells”:** deferred until Create Community is stable; screens use **`CreateFlowStepShell`** only for Stage 1.
|
- **Inner “text/select shells”:** deferred until Create Community is stable; screens use **`CreateFlowStepShell`** only for Stage 1.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
+8
-7
@@ -164,19 +164,20 @@ async function errorBodyMessage(res: Response): Promise<string> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Wipe the signed-in user's saved draft. Fire-and-forget: any non-2xx (including
|
* Wipe the signed-in user's saved draft.
|
||||||
* the sync-flag-off `503` and the unauthenticated `401`) is swallowed because
|
* Returns true when the server confirms the draft is gone.
|
||||||
* callers only invoke this on already-published / explicitly-discarded flows
|
* Callers that only need a best-effort wipe can ignore a false result
|
||||||
* where a leftover server draft is acceptable.
|
* (`503` when sync is off, `401` when signed out, or a network error).
|
||||||
*/
|
*/
|
||||||
export async function deleteServerDraft(): Promise<void> {
|
export async function deleteServerDraft(): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
await fetch("/api/drafts/me", {
|
const res = await fetch("/api/drafts/me", {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
});
|
});
|
||||||
|
return res.ok;
|
||||||
} catch {
|
} catch {
|
||||||
/* ignore — server draft cleanup is best-effort */
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
decisionApproachPresetFor,
|
decisionApproachPresetFor,
|
||||||
membershipPresetFor,
|
membershipPresetFor,
|
||||||
} from "./finalReviewChipPresets";
|
} from "./finalReviewChipPresets";
|
||||||
|
import { methodSectionsPinsForHydratedSelections } from "./publishedDocumentToCreateFlowState";
|
||||||
import {
|
import {
|
||||||
templateChipsForSlug,
|
templateChipsForSlug,
|
||||||
type TemplateChipSet,
|
type TemplateChipSet,
|
||||||
@@ -223,3 +224,72 @@ export function templatePresetDetailsFromPrefill(
|
|||||||
coreValueDetailsByChipId,
|
coreValueDetailsByChipId,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function sectionsFromTemplateBody(
|
||||||
|
body: unknown,
|
||||||
|
): Record<string, unknown>[] | null {
|
||||||
|
if (!body || typeof body !== "object" || Array.isArray(body)) return null;
|
||||||
|
const sectionsRaw = (body as { sections?: unknown }).sections;
|
||||||
|
if (!Array.isArray(sectionsRaw) || sectionsRaw.length === 0) return null;
|
||||||
|
return sectionsRaw as Record<string, unknown>[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TemplateApplyIdentity = {
|
||||||
|
title?: string;
|
||||||
|
communityContext?: string;
|
||||||
|
communityLocation?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fresh wizard state for a template. Does not spread a previous draft, so a
|
||||||
|
* leftover logo, setup answers, or another community's cards cannot ride along.
|
||||||
|
*/
|
||||||
|
export function buildAppliedTemplateCreateFlowState(args: {
|
||||||
|
slug: string;
|
||||||
|
body: unknown;
|
||||||
|
mode: "customize" | "useWithoutChanges";
|
||||||
|
identity?: TemplateApplyIdentity;
|
||||||
|
}): CreateFlowState {
|
||||||
|
const prefill = buildTemplateCustomizePrefill(args.body, args.slug);
|
||||||
|
const details = templatePresetDetailsFromPrefill(prefill);
|
||||||
|
const pinPatch = methodSectionsPinsForHydratedSelections(prefill);
|
||||||
|
const title = args.identity?.title?.trim();
|
||||||
|
const communityContext = args.identity?.communityContext?.trim();
|
||||||
|
const communityLocation = args.identity?.communityLocation?.trim();
|
||||||
|
|
||||||
|
const seeded: CreateFlowState = {
|
||||||
|
...prefill,
|
||||||
|
...details,
|
||||||
|
methodSectionsPinCommitted: pinPatch,
|
||||||
|
templateReviewBackSlug: args.slug,
|
||||||
|
pendingTemplateAction: {
|
||||||
|
slug: args.slug,
|
||||||
|
mode: args.mode,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
if (title) seeded.title = title;
|
||||||
|
if (communityContext) {
|
||||||
|
seeded.communityContext = communityContext;
|
||||||
|
seeded.summary = communityContext;
|
||||||
|
}
|
||||||
|
if (communityLocation) seeded.communityLocation = communityLocation;
|
||||||
|
if (args.identity) seeded.templateReviewEntryFromCreateFlow = true;
|
||||||
|
|
||||||
|
if (args.mode === "useWithoutChanges") {
|
||||||
|
const sections = sectionsFromTemplateBody(args.body);
|
||||||
|
if (sections) {
|
||||||
|
const hasValuesSeed = seeded.selectedCoreValueIds !== undefined;
|
||||||
|
seeded.sections = hasValuesSeed
|
||||||
|
? sections.filter((section) => {
|
||||||
|
const name = (section as { categoryName?: unknown }).categoryName;
|
||||||
|
if (typeof name !== "string") return true;
|
||||||
|
const key = name.toLowerCase().replace(/[^a-z]+/g, "");
|
||||||
|
return key !== "values" && key !== "corevalues";
|
||||||
|
})
|
||||||
|
: sections;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return seeded;
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
import type { CreateFlowState } from "../../app/(app)/create/types";
|
||||||
|
import { createFlowStateHasKeys } from "./draftHydrationUtils";
|
||||||
|
import {
|
||||||
|
CUSTOM_RULE_FACETS,
|
||||||
|
PUBLISHED_CUSTOM_RULE_SELECTION_KEYS,
|
||||||
|
} from "./customRuleFacets";
|
||||||
|
import type { StoredLastPublishedRule } from "./lastPublishedRule";
|
||||||
|
import {
|
||||||
|
createFlowStateFromPublishedRule,
|
||||||
|
methodSectionsPinsFromPublishedHydratePatch,
|
||||||
|
} from "./publishedDocumentToCreateFlowState";
|
||||||
|
|
||||||
|
function sortedIds(value: unknown): string {
|
||||||
|
if (!Array.isArray(value)) return "";
|
||||||
|
return value
|
||||||
|
.filter((id): id is string => typeof id === "string")
|
||||||
|
.map((id) => id.trim())
|
||||||
|
.filter((id) => id.length > 0)
|
||||||
|
.sort()
|
||||||
|
.join(",");
|
||||||
|
}
|
||||||
|
|
||||||
|
function trimmedText(value: unknown): string {
|
||||||
|
return typeof value === "string" ? value.trim() : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function canonical(value: unknown): unknown {
|
||||||
|
if (Array.isArray(value)) return value.map(canonical);
|
||||||
|
if (value && typeof value === "object") {
|
||||||
|
const record = value as Record<string, unknown>;
|
||||||
|
const out: Record<string, unknown> = {};
|
||||||
|
for (const key of Object.keys(record).sort()) {
|
||||||
|
const child = record[key];
|
||||||
|
if (child === undefined) continue;
|
||||||
|
out[key] = canonical(child);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Missing and empty objects are the same: the author has not written that copy. */
|
||||||
|
function sameCopy(a: unknown, b: unknown): boolean {
|
||||||
|
const normalize = (value: unknown): unknown => {
|
||||||
|
if (value == null) return null;
|
||||||
|
if (
|
||||||
|
typeof value === "object" &&
|
||||||
|
!Array.isArray(value) &&
|
||||||
|
Object.keys(value as object).length === 0
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
JSON.stringify(canonical(normalize(a))) ===
|
||||||
|
JSON.stringify(canonical(normalize(b)))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createFlowStateMatchesPublishedRule(
|
||||||
|
state: CreateFlowState,
|
||||||
|
last: StoredLastPublishedRule,
|
||||||
|
): boolean {
|
||||||
|
const patch = createFlowStateFromPublishedRule(last);
|
||||||
|
const title = typeof state.title === "string" ? state.title.trim() : "";
|
||||||
|
const patchTitle = typeof patch.title === "string" ? patch.title.trim() : "";
|
||||||
|
if (title !== patchTitle) return false;
|
||||||
|
if (
|
||||||
|
trimmedText(state.communityContext) !== trimmedText(patch.communityContext)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (trimmedText(state.summary) !== trimmedText(patch.summary)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (const key of PUBLISHED_CUSTOM_RULE_SELECTION_KEYS) {
|
||||||
|
if (sortedIds(state[key]) !== sortedIds(patch[key])) return false;
|
||||||
|
}
|
||||||
|
for (const row of CUSTOM_RULE_FACETS) {
|
||||||
|
if (
|
||||||
|
!sameCopy(
|
||||||
|
state[row.detailOverridesStateKey],
|
||||||
|
patch[row.detailOverridesStateKey],
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!sameCopy(
|
||||||
|
state.customMethodCardFieldBlocksById,
|
||||||
|
patch.customMethodCardFieldBlocksById,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!sameCopy(state.customMethodCardMetaById, patch.customMethodCardMetaById)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when Edit would drop a different in-progress draft to load this
|
||||||
|
* finished Rule. Empty state and a draft that already is this Rule do not
|
||||||
|
* need a confirm.
|
||||||
|
*/
|
||||||
|
export function publishedRuleEditWouldReplaceDraft(
|
||||||
|
state: CreateFlowState,
|
||||||
|
last: StoredLastPublishedRule,
|
||||||
|
): boolean {
|
||||||
|
if (!createFlowStateHasKeys(state)) return false;
|
||||||
|
const editingId =
|
||||||
|
typeof state.editingPublishedRuleId === "string"
|
||||||
|
? state.editingPublishedRuleId.trim()
|
||||||
|
: "";
|
||||||
|
if (editingId.length > 0 && editingId !== last.id) return true;
|
||||||
|
return !createFlowStateMatchesPublishedRule(state, last);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Full wizard state for editing a finished Rule — not a merge onto another draft. */
|
||||||
|
export function createFlowStateForEditingPublishedRule(
|
||||||
|
last: StoredLastPublishedRule,
|
||||||
|
): CreateFlowState {
|
||||||
|
const patch = createFlowStateFromPublishedRule(last);
|
||||||
|
return {
|
||||||
|
...patch,
|
||||||
|
methodSectionsPinCommitted:
|
||||||
|
methodSectionsPinsFromPublishedHydratePatch(patch),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -8,11 +8,10 @@ import type {
|
|||||||
import type { CommunityRuleSection } from "../../app/components/type/CommunityRule/CommunityRule.types";
|
import type { CommunityRuleSection } from "../../app/components/type/CommunityRule/CommunityRule.types";
|
||||||
import { resolveMethodPresetIdFromLabel } from "./buildFinalReviewCategories";
|
import { resolveMethodPresetIdFromLabel } from "./buildFinalReviewCategories";
|
||||||
import {
|
import {
|
||||||
communicationPresetFor,
|
emptyCommunicationDetails,
|
||||||
conflictManagementPresetFor,
|
emptyConflictManagementDetails,
|
||||||
decisionApproachPresetFor,
|
emptyDecisionApproachDetails,
|
||||||
membershipPresetFor,
|
emptyMembershipDetails,
|
||||||
mergeCoreValueDetailWithPresets,
|
|
||||||
publishedMethodDisplayLabel,
|
publishedMethodDisplayLabel,
|
||||||
} from "./finalReviewChipPresets";
|
} from "./finalReviewChipPresets";
|
||||||
import { isDocumentEntry } from "./documentEntryGuards";
|
import { isDocumentEntry } from "./documentEntryGuards";
|
||||||
@@ -61,12 +60,12 @@ export function buildCoreValuesForDocument(state: CreateFlowState): Array<{
|
|||||||
return snap
|
return snap
|
||||||
.filter((r) => selected.has(r.id))
|
.filter((r) => selected.has(r.id))
|
||||||
.map((r) => {
|
.map((r) => {
|
||||||
const merged = mergeCoreValueDetailWithPresets(r.id, r.label, details[r.id]);
|
const saved = details[r.id];
|
||||||
return {
|
return {
|
||||||
chipId: r.id,
|
chipId: r.id,
|
||||||
label: r.label,
|
label: r.label,
|
||||||
meaning: merged.meaning,
|
meaning: typeof saved?.meaning === "string" ? saved.meaning : "",
|
||||||
signals: merged.signals,
|
signals: typeof saved?.signals === "string" ? saved.signals : "",
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -278,10 +277,8 @@ function publishedRowSupportText(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Merge `selected*MethodIds` with any saved `{group}MethodDetailsById`
|
* Merge `selected*MethodIds` with any saved `{group}MethodDetailsById`
|
||||||
* overrides authored on the final-review screen. Preset defaults from the
|
* overrides authored on the final-review screen. Blank parts stay blank —
|
||||||
* shipped `messages/en/create/customRule/*.json` seed any sub-fields the
|
* library presets are not filled in for text the pen holder never wrote.
|
||||||
* user didn't edit so consumers of `document.methodSelections` always see
|
|
||||||
* a complete payload per method.
|
|
||||||
*/
|
*/
|
||||||
export function buildMethodSelectionsForDocument(
|
export function buildMethodSelectionsForDocument(
|
||||||
state: CreateFlowState,
|
state: CreateFlowState,
|
||||||
@@ -297,7 +294,6 @@ export function buildMethodSelectionsForDocument(
|
|||||||
);
|
);
|
||||||
if (commIds.length > 0) {
|
if (commIds.length > 0) {
|
||||||
out.communication = commIds.map((id) => {
|
out.communication = commIds.map((id) => {
|
||||||
const preset = communicationPresetFor(id);
|
|
||||||
const override = state.communicationMethodDetailsById?.[id];
|
const override = state.communicationMethodDetailsById?.[id];
|
||||||
const supportText = publishedRowSupportText(
|
const supportText = publishedRowSupportText(
|
||||||
id,
|
id,
|
||||||
@@ -310,7 +306,7 @@ export function buildMethodSelectionsForDocument(
|
|||||||
id,
|
id,
|
||||||
state.customMethodCardMetaById,
|
state.customMethodCardMetaById,
|
||||||
),
|
),
|
||||||
sections: override ? { ...preset, ...override } : preset,
|
sections: override ?? emptyCommunicationDetails(),
|
||||||
...(supportText ? { supportText } : {}),
|
...(supportText ? { supportText } : {}),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
@@ -322,7 +318,6 @@ export function buildMethodSelectionsForDocument(
|
|||||||
);
|
);
|
||||||
if (memIds.length > 0) {
|
if (memIds.length > 0) {
|
||||||
out.membership = memIds.map((id) => {
|
out.membership = memIds.map((id) => {
|
||||||
const preset = membershipPresetFor(id);
|
|
||||||
const override = state.membershipMethodDetailsById?.[id];
|
const override = state.membershipMethodDetailsById?.[id];
|
||||||
const supportText = publishedRowSupportText(
|
const supportText = publishedRowSupportText(
|
||||||
id,
|
id,
|
||||||
@@ -335,7 +330,7 @@ export function buildMethodSelectionsForDocument(
|
|||||||
id,
|
id,
|
||||||
state.customMethodCardMetaById,
|
state.customMethodCardMetaById,
|
||||||
),
|
),
|
||||||
sections: override ? { ...preset, ...override } : preset,
|
sections: override ?? emptyMembershipDetails(),
|
||||||
...(supportText ? { supportText } : {}),
|
...(supportText ? { supportText } : {}),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
@@ -347,13 +342,11 @@ export function buildMethodSelectionsForDocument(
|
|||||||
);
|
);
|
||||||
if (daIds.length > 0) {
|
if (daIds.length > 0) {
|
||||||
out.decisionApproaches = daIds.map((id) => {
|
out.decisionApproaches = daIds.map((id) => {
|
||||||
const preset = decisionApproachPresetFor(id);
|
|
||||||
const override = state.decisionApproachDetailsById?.[id];
|
const override = state.decisionApproachDetailsById?.[id];
|
||||||
const supportText = publishedRowSupportText(
|
const supportText = publishedRowSupportText(
|
||||||
id,
|
id,
|
||||||
state.customMethodCardMetaById,
|
state.customMethodCardMetaById,
|
||||||
);
|
);
|
||||||
const merged = override ? { ...preset, ...override } : preset;
|
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
label: publishedMethodDisplayLabel(
|
label: publishedMethodDisplayLabel(
|
||||||
@@ -362,7 +355,7 @@ export function buildMethodSelectionsForDocument(
|
|||||||
state.customMethodCardMetaById,
|
state.customMethodCardMetaById,
|
||||||
),
|
),
|
||||||
sections: withoutUnpublishedDecisionConsensus(
|
sections: withoutUnpublishedDecisionConsensus(
|
||||||
{ ...merged },
|
{ ...(override ?? emptyDecisionApproachDetails()) },
|
||||||
state.customMethodCardFieldBlocksById?.[id],
|
state.customMethodCardFieldBlocksById?.[id],
|
||||||
) as DecisionApproachDetailEntry,
|
) as DecisionApproachDetailEntry,
|
||||||
...(supportText ? { supportText } : {}),
|
...(supportText ? { supportText } : {}),
|
||||||
@@ -376,7 +369,6 @@ export function buildMethodSelectionsForDocument(
|
|||||||
);
|
);
|
||||||
if (cmIds.length > 0) {
|
if (cmIds.length > 0) {
|
||||||
out.conflictManagement = cmIds.map((id) => {
|
out.conflictManagement = cmIds.map((id) => {
|
||||||
const preset = conflictManagementPresetFor(id);
|
|
||||||
const override = state.conflictManagementDetailsById?.[id];
|
const override = state.conflictManagementDetailsById?.[id];
|
||||||
const supportText = publishedRowSupportText(
|
const supportText = publishedRowSupportText(
|
||||||
id,
|
id,
|
||||||
@@ -389,7 +381,7 @@ export function buildMethodSelectionsForDocument(
|
|||||||
id,
|
id,
|
||||||
state.customMethodCardMetaById,
|
state.customMethodCardMetaById,
|
||||||
),
|
),
|
||||||
sections: override ? { ...preset, ...override } : preset,
|
sections: override ?? emptyConflictManagementDetails(),
|
||||||
...(supportText ? { supportText } : {}),
|
...(supportText ? { supportText } : {}),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -15,9 +15,8 @@ import type {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Catalog copy for method/value sections. Generate draft inserts these into
|
* Catalog copy for method/value sections. Generate draft inserts these into
|
||||||
* empty creation-modal fields. Publish still merges them onto saved overrides
|
* empty creation-modal fields. Publish keeps blank parts blank — it does not
|
||||||
* so every method carries a complete section payload when the author only
|
* fill library text the pen holder never wrote.
|
||||||
* edited a subset of fields.
|
|
||||||
*/
|
*/
|
||||||
type CustomRuleMethodRow = {
|
type CustomRuleMethodRow = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -145,6 +144,16 @@ export function emptyDecisionApproachTextFields(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function emptyDecisionApproachDetails(): DecisionApproachDetailEntry {
|
||||||
|
return {
|
||||||
|
corePrinciple: "",
|
||||||
|
applicableScope: [],
|
||||||
|
selectedApplicableScope: [],
|
||||||
|
stepByStepInstructions: "",
|
||||||
|
objectionsDeadlocks: "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function conflictManagementPresetFor(
|
export function conflictManagementPresetFor(
|
||||||
id: string,
|
id: string,
|
||||||
): ConflictManagementDetailEntry {
|
): ConflictManagementDetailEntry {
|
||||||
@@ -233,8 +242,8 @@ export function coreValuePresetForLabel(label: string): CoreValueDetailEntry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Published / display copy: saved draft wins when non-empty; otherwise preset
|
* Generate draft and legacy placeholder replacement: saved copy wins when
|
||||||
* by chip id (numeric presets), then by label match in `coreValues.json`.
|
* non-empty; otherwise preset by chip id, then by label match.
|
||||||
*/
|
*/
|
||||||
export function mergeCoreValueDetailWithPresets(
|
export function mergeCoreValueDetailWithPresets(
|
||||||
chipId: string,
|
chipId: string,
|
||||||
|
|||||||
@@ -5,12 +5,34 @@ import type {
|
|||||||
DecisionApproachDetailEntry,
|
DecisionApproachDetailEntry,
|
||||||
MembershipMethodDetailEntry,
|
MembershipMethodDetailEntry,
|
||||||
} from "../../app/(app)/create/types";
|
} from "../../app/(app)/create/types";
|
||||||
|
import {
|
||||||
|
buildFinalReviewCategoryRowsDetailed,
|
||||||
|
type FinalReviewCategoryNames,
|
||||||
|
} from "./buildFinalReviewCategories";
|
||||||
|
import type { CustomMethodCardFieldBlock } from "./customMethodCardFieldBlocks";
|
||||||
|
import { facetBlockHasContent } from "./methodCardWizardPrefill";
|
||||||
import type { TemplateFacetGroupKey } from "./templateReviewMapping";
|
import type { TemplateFacetGroupKey } from "./templateReviewMapping";
|
||||||
|
import { usesWizardFieldBlocksModalBody } from "./usesWizardFieldBlocksModalBody";
|
||||||
|
|
||||||
|
const LABEL_NAMES: FinalReviewCategoryNames = {
|
||||||
|
values: "values",
|
||||||
|
communication: "communication",
|
||||||
|
membership: "membership",
|
||||||
|
decisions: "decisions",
|
||||||
|
conflict: "conflict",
|
||||||
|
};
|
||||||
|
|
||||||
function missingText(...values: readonly (string | undefined)[]): boolean {
|
function missingText(...values: readonly (string | undefined)[]): boolean {
|
||||||
return values.some((value) => (value ?? "").trim().length === 0);
|
return values.some((value) => (value ?? "").trim().length === 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function customFieldBlocksHaveWords(
|
||||||
|
blocks: readonly CustomMethodCardFieldBlock[] | undefined,
|
||||||
|
): boolean {
|
||||||
|
if (!blocks || blocks.length === 0) return false;
|
||||||
|
return blocks.every(facetBlockHasContent);
|
||||||
|
}
|
||||||
|
|
||||||
function communicationMissingWords(
|
function communicationMissingWords(
|
||||||
saved: CommunicationMethodDetailEntry | undefined,
|
saved: CommunicationMethodDetailEntry | undefined,
|
||||||
): boolean {
|
): boolean {
|
||||||
@@ -55,21 +77,30 @@ function conflictMissingWords(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
function methodUsesCustomFieldBlocks(
|
||||||
* A review chip shows a warning when its value is missing meaning or signals,
|
|
||||||
* or a card is missing its words.
|
|
||||||
*/
|
|
||||||
export function finalReviewChipHasWarning(
|
|
||||||
state: CreateFlowState,
|
state: CreateFlowState,
|
||||||
groupKey: TemplateFacetGroupKey | null,
|
overrideKey: string,
|
||||||
overrideKey: string | null,
|
|
||||||
): boolean {
|
): boolean {
|
||||||
if (!groupKey || !overrideKey) return true;
|
return usesWizardFieldBlocksModalBody({
|
||||||
|
methodId: overrideKey,
|
||||||
|
meta: state.customMethodCardMetaById,
|
||||||
|
fieldBlocksById: state.customMethodCardFieldBlocksById,
|
||||||
|
modalEditUnlocked: true,
|
||||||
|
draftFieldBlocks: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function methodCardMissingWords(
|
||||||
|
state: CreateFlowState,
|
||||||
|
groupKey: Exclude<TemplateFacetGroupKey, "coreValues">,
|
||||||
|
overrideKey: string,
|
||||||
|
): boolean {
|
||||||
|
if (methodUsesCustomFieldBlocks(state, overrideKey)) {
|
||||||
|
return !customFieldBlocksHaveWords(
|
||||||
|
state.customMethodCardFieldBlocksById?.[overrideKey],
|
||||||
|
);
|
||||||
|
}
|
||||||
switch (groupKey) {
|
switch (groupKey) {
|
||||||
case "coreValues": {
|
|
||||||
const saved = state.coreValueDetailsByChipId?.[overrideKey];
|
|
||||||
return missingText(saved?.meaning, saved?.signals);
|
|
||||||
}
|
|
||||||
case "communication":
|
case "communication":
|
||||||
return communicationMissingWords(
|
return communicationMissingWords(
|
||||||
state.communicationMethodDetailsById?.[overrideKey],
|
state.communicationMethodDetailsById?.[overrideKey],
|
||||||
@@ -88,3 +119,84 @@ export function finalReviewChipHasWarning(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function valueHasMeaning(
|
||||||
|
state: CreateFlowState,
|
||||||
|
overrideKey: string,
|
||||||
|
): boolean {
|
||||||
|
const saved = state.coreValueDetailsByChipId?.[overrideKey];
|
||||||
|
if ((saved?.meaning ?? "").trim().length > 0) return true;
|
||||||
|
const blocks = state.customMethodCardFieldBlocksById?.[overrideKey];
|
||||||
|
if (!blocks || blocks.length === 0) return false;
|
||||||
|
return blocks.some(
|
||||||
|
(block) =>
|
||||||
|
block.kind === "text" &&
|
||||||
|
block.id !== "facet-signals" &&
|
||||||
|
facetBlockHasContent(block),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function valueHasSignals(
|
||||||
|
state: CreateFlowState,
|
||||||
|
overrideKey: string,
|
||||||
|
): boolean {
|
||||||
|
const saved = state.coreValueDetailsByChipId?.[overrideKey];
|
||||||
|
if ((saved?.signals ?? "").trim().length > 0) return true;
|
||||||
|
const blocks = state.customMethodCardFieldBlocksById?.[overrideKey];
|
||||||
|
if (!blocks || blocks.length === 0) return false;
|
||||||
|
const signalsBlock = blocks.find(
|
||||||
|
(block) => block.kind === "text" && block.id === "facet-signals",
|
||||||
|
);
|
||||||
|
if (!signalsBlock) return true;
|
||||||
|
return facetBlockHasContent(signalsBlock);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A review chip shows a warning when its value is missing meaning or signals,
|
||||||
|
* or a card is missing its words. Custom field text counts as those words.
|
||||||
|
*/
|
||||||
|
export function finalReviewChipHasWarning(
|
||||||
|
state: CreateFlowState,
|
||||||
|
groupKey: TemplateFacetGroupKey | null,
|
||||||
|
overrideKey: string | null,
|
||||||
|
): boolean {
|
||||||
|
if (!groupKey || !overrideKey) return true;
|
||||||
|
if (groupKey === "coreValues") {
|
||||||
|
return !valueHasMeaning(state, overrideKey) || !valueHasSignals(state, overrideKey);
|
||||||
|
}
|
||||||
|
return methodCardMissingWords(state, groupKey, overrideKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Continue waits for every picked card's words and every picked value's
|
||||||
|
* meaning. Missing signals stay a warning only.
|
||||||
|
*/
|
||||||
|
export function finalReviewChipBlocksContinue(
|
||||||
|
state: CreateFlowState,
|
||||||
|
groupKey: TemplateFacetGroupKey | null,
|
||||||
|
overrideKey: string | null,
|
||||||
|
): boolean {
|
||||||
|
if (!groupKey || !overrideKey) return false;
|
||||||
|
if (groupKey === "coreValues") {
|
||||||
|
return !valueHasMeaning(state, overrideKey);
|
||||||
|
}
|
||||||
|
return methodCardMissingWords(state, groupKey, overrideKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Chip labels that still need words before Continue. */
|
||||||
|
export function finalReviewMissingWordsLabels(
|
||||||
|
state: CreateFlowState,
|
||||||
|
): string[] {
|
||||||
|
const rows = buildFinalReviewCategoryRowsDetailed(state, LABEL_NAMES);
|
||||||
|
const labels: string[] = [];
|
||||||
|
for (const row of rows) {
|
||||||
|
for (const entry of row.entries) {
|
||||||
|
if (
|
||||||
|
finalReviewChipBlocksContinue(state, entry.groupKey, entry.overrideKey)
|
||||||
|
) {
|
||||||
|
labels.push(entry.label);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return labels;
|
||||||
|
}
|
||||||
@@ -2,8 +2,8 @@ import type { CopiedNameHit } from "./copiedRuleDocument";
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Bridges final-review → completed without query strings, and re-opens a rule
|
* Bridges final-review → completed without query strings, and re-opens a rule
|
||||||
* from profile (`/create/completed?ruleId=…`) after GET /api/rules/[id]. Profile
|
* from profile (`/create/completed?ruleId=…`) after GET /api/rules/[id].
|
||||||
* "Manage" links here; stakeholder "View" uses `/invite/[id]`.
|
* Stakeholder cards on Profile open the reader page at `/rules/[id]`.
|
||||||
*/
|
*/
|
||||||
export const CREATE_FLOW_LAST_PUBLISHED_KEY = "createFlow.lastPublished";
|
export const CREATE_FLOW_LAST_PUBLISHED_KEY = "createFlow.lastPublished";
|
||||||
|
|
||||||
@@ -35,6 +35,11 @@ export function writeLastPublishedRule(data: StoredLastPublishedRule): void {
|
|||||||
sessionStorage.setItem(CREATE_FLOW_LAST_PUBLISHED_KEY, JSON.stringify(data));
|
sessionStorage.setItem(CREATE_FLOW_LAST_PUBLISHED_KEY, JSON.stringify(data));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function clearLastPublishedRule(): void {
|
||||||
|
if (typeof sessionStorage === "undefined") return;
|
||||||
|
sessionStorage.removeItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
export function readLastPublishedRule(): StoredLastPublishedRule | null {
|
export function readLastPublishedRule(): StoredLastPublishedRule | null {
|
||||||
if (typeof sessionStorage === "undefined") return null;
|
if (typeof sessionStorage === "undefined") return null;
|
||||||
const raw = sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
|
const raw = sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
|
||||||
|
|||||||
@@ -233,7 +233,7 @@ export function facetDetailsToWizardFieldBlocks(
|
|||||||
return mapFacetPrefillToWizardFieldBlocks(prefill);
|
return mapFacetPrefillToWizardFieldBlocks(prefill);
|
||||||
}
|
}
|
||||||
|
|
||||||
function facetBlockHasContent(block: CustomMethodCardFieldBlock): boolean {
|
export function facetBlockHasContent(block: CustomMethodCardFieldBlock): boolean {
|
||||||
switch (block.kind) {
|
switch (block.kind) {
|
||||||
case "text":
|
case "text":
|
||||||
return hasTrimmedText(block.placeholderText);
|
return hasTrimmedText(block.placeholderText);
|
||||||
|
|||||||
@@ -4,13 +4,6 @@ import type { PublishedMethodSelections } from "./buildPublishPayload";
|
|||||||
import { parseDocumentSectionsForDisplay } from "./buildPublishPayload";
|
import { parseDocumentSectionsForDisplay } from "./buildPublishPayload";
|
||||||
import { resolveMethodPresetIdFromLabel } from "./buildFinalReviewCategories";
|
import { resolveMethodPresetIdFromLabel } from "./buildFinalReviewCategories";
|
||||||
import { resolveCoreValueChipIdFromLabel } from "./finalReviewChipPresets";
|
import { resolveCoreValueChipIdFromLabel } from "./finalReviewChipPresets";
|
||||||
import {
|
|
||||||
communicationPresetFor,
|
|
||||||
conflictManagementPresetFor,
|
|
||||||
decisionApproachPresetFor,
|
|
||||||
membershipPresetFor,
|
|
||||||
mergeCoreValueDetailWithPresets,
|
|
||||||
} from "./finalReviewChipPresets";
|
|
||||||
import { templateCategoryToGroupKey } from "./templateReviewMapping";
|
import { templateCategoryToGroupKey } from "./templateReviewMapping";
|
||||||
import type { TemplateFacetGroupKey } from "./templateReviewMapping";
|
import type { TemplateFacetGroupKey } from "./templateReviewMapping";
|
||||||
import { RULE_SECTION_CATEGORY } from "./ruleSectionsFromMethodSelections";
|
import { RULE_SECTION_CATEGORY } from "./ruleSectionsFromMethodSelections";
|
||||||
@@ -110,26 +103,9 @@ function sectionsRecordFromBlocks(
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
function presetForMethod(
|
|
||||||
groupKey: Exclude<TemplateFacetGroupKey, "coreValues">,
|
|
||||||
id: string,
|
|
||||||
): Record<string, unknown> {
|
|
||||||
switch (groupKey) {
|
|
||||||
case "communication":
|
|
||||||
return { ...communicationPresetFor(id) } as Record<string, unknown>;
|
|
||||||
case "membership":
|
|
||||||
return { ...membershipPresetFor(id) } as Record<string, unknown>;
|
|
||||||
case "decisionApproaches":
|
|
||||||
return { ...decisionApproachPresetFor(id) } as Record<string, unknown>;
|
|
||||||
case "conflictManagement":
|
|
||||||
return { ...conflictManagementPresetFor(id) } as Record<string, unknown>;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function sectionsRecordFromEntry(
|
function sectionsRecordFromEntry(
|
||||||
entry: CommunityRuleSection["entries"][number],
|
entry: CommunityRuleSection["entries"][number],
|
||||||
groupKey: Exclude<TemplateFacetGroupKey, "coreValues">,
|
groupKey: Exclude<TemplateFacetGroupKey, "coreValues">,
|
||||||
presetId: string,
|
|
||||||
): Record<string, unknown> {
|
): Record<string, unknown> {
|
||||||
const labelByKey = LABELS_BY_GROUP[groupKey];
|
const labelByKey = LABELS_BY_GROUP[groupKey];
|
||||||
const consensusKey =
|
const consensusKey =
|
||||||
@@ -140,16 +116,16 @@ function sectionsRecordFromEntry(
|
|||||||
consensusLevelKey: consensusKey,
|
consensusLevelKey: consensusKey,
|
||||||
});
|
});
|
||||||
if (Object.keys(fromBlocks).length > 0) {
|
if (Object.keys(fromBlocks).length > 0) {
|
||||||
return { ...presetForMethod(groupKey, presetId), ...fromBlocks };
|
return fromBlocks;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const body = (entry.body ?? "").trim();
|
const body = (entry.body ?? "").trim();
|
||||||
if (body.length === 0) {
|
if (body.length === 0) {
|
||||||
return presetForMethod(groupKey, presetId);
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
return { ...presetForMethod(groupKey, presetId), corePrinciple: body };
|
return { corePrinciple: body };
|
||||||
}
|
}
|
||||||
|
|
||||||
function coreValuesFromValuesSection(
|
function coreValuesFromValuesSection(
|
||||||
@@ -169,18 +145,14 @@ function coreValuesFromValuesSection(
|
|||||||
const parts = body.length > 0 ? body.split(/\n\n+/) : [];
|
const parts = body.length > 0 ? body.split(/\n\n+/) : [];
|
||||||
const meaning = (parts[0] ?? "").trim();
|
const meaning = (parts[0] ?? "").trim();
|
||||||
const signals = parts.slice(1).join("\n\n").trim();
|
const signals = parts.slice(1).join("\n\n").trim();
|
||||||
const merged = mergeCoreValueDetailWithPresets("", label, {
|
|
||||||
meaning,
|
|
||||||
signals,
|
|
||||||
});
|
|
||||||
const chipId =
|
const chipId =
|
||||||
resolveCoreValueChipIdFromLabel(label) ??
|
resolveCoreValueChipIdFromLabel(label) ??
|
||||||
`hydrated-${label.toLowerCase()}`;
|
`hydrated-${label.toLowerCase()}`;
|
||||||
out.push({
|
out.push({
|
||||||
chipId,
|
chipId,
|
||||||
label,
|
label,
|
||||||
meaning: merged.meaning,
|
meaning,
|
||||||
signals: merged.signals,
|
signals,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,7 +185,7 @@ function methodSelectionsFromDisplaySections(
|
|||||||
rows.push({
|
rows.push({
|
||||||
id,
|
id,
|
||||||
label,
|
label,
|
||||||
sections: sectionsRecordFromEntry(entry, groupKey, id),
|
sections: sectionsRecordFromEntry(entry, groupKey),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (rows.length > 0) {
|
if (rows.length > 0) {
|
||||||
|
|||||||
@@ -80,7 +80,6 @@ const CM_LABELS: Record<string, string> = {
|
|||||||
function needsPlaceholderPresetEnrichment(entry: CommunityRuleEntry): boolean {
|
function needsPlaceholderPresetEnrichment(entry: CommunityRuleEntry): boolean {
|
||||||
if (entry.blocks && entry.blocks.length > 0) return false;
|
if (entry.blocks && entry.blocks.length > 0) return false;
|
||||||
const b = (entry.body ?? "").trim();
|
const b = (entry.body ?? "").trim();
|
||||||
if (b.length === 0) return true;
|
|
||||||
return b === TEMPLATE_COMPOSITION_SUGGESTED_BODY;
|
return b === TEMPLATE_COMPOSITION_SUGGESTED_BODY;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,15 +195,12 @@ function sectionFromStoredCoreValues(
|
|||||||
for (const row of raw) {
|
for (const row of raw) {
|
||||||
if (!row || typeof row !== "object") continue;
|
if (!row || typeof row !== "object") continue;
|
||||||
const o = row as Record<string, unknown>;
|
const o = row as Record<string, unknown>;
|
||||||
const chipId = typeof o.chipId === "string" ? o.chipId : "";
|
|
||||||
const label = nonEmptyTrimmed(o.label);
|
const label = nonEmptyTrimmed(o.label);
|
||||||
if (!label) continue;
|
if (!label) continue;
|
||||||
const merged = mergeCoreValueDetailWithPresets(chipId, label, {
|
const meaning =
|
||||||
meaning: typeof o.meaning === "string" ? o.meaning : "",
|
typeof o.meaning === "string" ? o.meaning.trim() : "";
|
||||||
signals: typeof o.signals === "string" ? o.signals : "",
|
const signals =
|
||||||
});
|
typeof o.signals === "string" ? o.signals.trim() : "";
|
||||||
const meaning = (merged.meaning ?? "").trim();
|
|
||||||
const signals = (merged.signals ?? "").trim();
|
|
||||||
const bodyParts: string[] = [];
|
const bodyParts: string[] = [];
|
||||||
if (meaning.length > 0) bodyParts.push(meaning);
|
if (meaning.length > 0) bodyParts.push(meaning);
|
||||||
if (signals.length > 0) bodyParts.push(signals);
|
if (signals.length > 0) bodyParts.push(signals);
|
||||||
|
|||||||
@@ -221,8 +221,7 @@ export function communityRuleEntryFromMethodChip(
|
|||||||
const blocks = [...presetBlocks, ...wizardBlocks];
|
const blocks = [...presetBlocks, ...wizardBlocks];
|
||||||
const description = nonEmptyTrimmed(options?.supportText);
|
const description = nonEmptyTrimmed(options?.supportText);
|
||||||
if (blocks.length === 0) {
|
if (blocks.length === 0) {
|
||||||
if (!description) return null;
|
return { title, body: description ?? "" };
|
||||||
return { title, body: description };
|
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
title,
|
title,
|
||||||
@@ -387,8 +386,8 @@ export function sectionFromConflict(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Swap template `sections` method rows for fully-resolved entries built from
|
* Swap template `sections` method rows for entries built from
|
||||||
* `methodSelections` (preset + overrides).
|
* `methodSelections`.
|
||||||
*/
|
*/
|
||||||
export function replaceMethodSectionsWithMethodSelections(
|
export function replaceMethodSectionsWithMethodSelections(
|
||||||
sections: CommunityRuleSection[],
|
sections: CommunityRuleSection[],
|
||||||
|
|||||||
@@ -1,9 +1,14 @@
|
|||||||
import type { Category } from "../../app/components/cards/Rule";
|
import type { Category } from "../../app/components/cards/Rule";
|
||||||
import type { ChipOption } from "../../app/components/controls/MultiSelect/MultiSelect.types";
|
import type { ChipOption } from "../../app/components/controls/MultiSelect/MultiSelect.types";
|
||||||
import type { CommunityRuleSection } from "../../app/components/type/CommunityRule/CommunityRule.types";
|
import type { CommunityRuleSection } from "../../app/components/type/CommunityRule/CommunityRule.types";
|
||||||
|
import coreValuesMessages from "../../messages/en/create/customRule/coreValues.json";
|
||||||
import type { TemplateFacetGroupKey } from "./customRuleFacets";
|
import type { TemplateFacetGroupKey } from "./customRuleFacets";
|
||||||
import { templateCategoryToFacetGroupKey } from "./customRuleFacets";
|
import {
|
||||||
|
readMethodPresetsForFacetGroup,
|
||||||
|
templateCategoryToFacetGroupKey,
|
||||||
|
} from "./customRuleFacets";
|
||||||
import { isDocumentEntry } from "./documentEntryGuards";
|
import { isDocumentEntry } from "./documentEntryGuards";
|
||||||
|
import { templateChipsForSlug, type TemplateChipSet } from "./templatePath";
|
||||||
|
|
||||||
export type { TemplateFacetGroupKey } from "./customRuleFacets";
|
export type { TemplateFacetGroupKey } from "./customRuleFacets";
|
||||||
|
|
||||||
@@ -91,6 +96,134 @@ export function templateBodyToCategories(body: unknown): Category[] {
|
|||||||
return templateBodyToReviewData(body).categories;
|
return templateBodyToReviewData(body).categories;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ReviewData = ReturnType<typeof templateBodyToReviewData>;
|
||||||
|
|
||||||
|
const CHIP_REVIEW_GROUPS: readonly {
|
||||||
|
groupKey: TemplateFacetGroupKey;
|
||||||
|
categoryName: string;
|
||||||
|
idsOf: (_chips: TemplateChipSet) => readonly string[];
|
||||||
|
}[] = [
|
||||||
|
{
|
||||||
|
groupKey: "coreValues",
|
||||||
|
categoryName: "Values",
|
||||||
|
idsOf: (chips) => chips.coreValues,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
groupKey: "communication",
|
||||||
|
categoryName: "Communication",
|
||||||
|
idsOf: (chips) => chips.communication,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
groupKey: "membership",
|
||||||
|
categoryName: "Membership",
|
||||||
|
idsOf: (chips) => chips.membership,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
groupKey: "decisionApproaches",
|
||||||
|
categoryName: "Decision-making",
|
||||||
|
idsOf: (chips) => chips.decisionApproaches,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
groupKey: "conflictManagement",
|
||||||
|
categoryName: "Conflict management",
|
||||||
|
idsOf: (chips) => chips.conflictManagement,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function coreValueLabelById(id: string): string | null {
|
||||||
|
const values = (coreValuesMessages as { values?: unknown }).values;
|
||||||
|
if (!Array.isArray(values)) return null;
|
||||||
|
for (const raw of values) {
|
||||||
|
if (!raw || typeof raw !== "object") continue;
|
||||||
|
const row = raw as { id?: unknown; label?: unknown };
|
||||||
|
if (row.id === id && typeof row.label === "string" && row.label.trim()) {
|
||||||
|
return row.label;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Same order as `coreValuesChipsSnapshot` / final review: catalog list, then leftovers. */
|
||||||
|
function orderedCoreValueIds(ids: readonly string[]): string[] {
|
||||||
|
const wanted = new Set(ids);
|
||||||
|
const out: string[] = [];
|
||||||
|
const values = (coreValuesMessages as { values?: unknown }).values;
|
||||||
|
if (Array.isArray(values)) {
|
||||||
|
for (const raw of values) {
|
||||||
|
if (!raw || typeof raw !== "object") continue;
|
||||||
|
const id = (raw as { id?: unknown }).id;
|
||||||
|
if (typeof id === "string" && wanted.delete(id)) out.push(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const id of ids) {
|
||||||
|
if (wanted.has(id)) out.push(id);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function methodLabelById(
|
||||||
|
groupKey: Exclude<TemplateFacetGroupKey, "coreValues">,
|
||||||
|
id: string,
|
||||||
|
): string | null {
|
||||||
|
const row = readMethodPresetsForFacetGroup(groupKey).find(
|
||||||
|
(method) => method.id === id,
|
||||||
|
);
|
||||||
|
return row?.label ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function templateChipsToReviewData(slug: string): ReviewData | null {
|
||||||
|
const chips = templateChipsForSlug(slug);
|
||||||
|
if (!chips) return null;
|
||||||
|
|
||||||
|
const categories: Category[] = [];
|
||||||
|
const chipDetailsByChipId: ReviewData["chipDetailsByChipId"] = {};
|
||||||
|
|
||||||
|
for (const group of CHIP_REVIEW_GROUPS) {
|
||||||
|
const chipOptions: ChipOption[] = [];
|
||||||
|
const ids =
|
||||||
|
group.groupKey === "coreValues"
|
||||||
|
? orderedCoreValueIds(group.idsOf(chips))
|
||||||
|
: group.idsOf(chips);
|
||||||
|
for (const id of ids) {
|
||||||
|
const chipLabel =
|
||||||
|
group.groupKey === "coreValues"
|
||||||
|
? coreValueLabelById(id)
|
||||||
|
: methodLabelById(group.groupKey, id);
|
||||||
|
if (!chipLabel) continue;
|
||||||
|
chipDetailsByChipId[id] = {
|
||||||
|
chipId: id,
|
||||||
|
chipLabel,
|
||||||
|
categoryName: group.categoryName,
|
||||||
|
groupKey: group.groupKey,
|
||||||
|
body: "",
|
||||||
|
};
|
||||||
|
chipOptions.push({
|
||||||
|
id,
|
||||||
|
label: chipLabel,
|
||||||
|
state: "unselected",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (chipOptions.length === 0) continue;
|
||||||
|
categories.push({
|
||||||
|
name: group.categoryName,
|
||||||
|
chipOptions,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { categories, chipDetailsByChipId };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detail-page chips. Prefer the remade catalog ids in templateChips.json so
|
||||||
|
* the list matches final review; fall back to API body titles for unknown slugs.
|
||||||
|
*/
|
||||||
|
export function templateReviewDataForSlug(
|
||||||
|
slug: string,
|
||||||
|
body: unknown,
|
||||||
|
): ReviewData {
|
||||||
|
return templateChipsToReviewData(slug) ?? templateBodyToReviewData(body);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Summary line under tag rows: prefer API description; else first entry bodies (short).
|
* Summary line under tag rows: prefer API description; else first entry bodies (short).
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ export async function issueGuestRuleClaimCookie(token: string): Promise<void> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function clearGuestRuleClaimCookie(): Promise<void> {
|
export async function clearGuestRuleClaimCookie(): Promise<void> {
|
||||||
const store = await cookies();
|
const store = await cookies();
|
||||||
store.set(GUEST_RULE_CLAIM_COOKIE_NAME, "", {
|
store.set(GUEST_RULE_CLAIM_COOKIE_NAME, "", {
|
||||||
...cookieOptions(),
|
...cookieOptions(),
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { prisma } from "./db";
|
||||||
|
import { deleteUploadsForDraft } from "./uploads/deleteUploadedFiles";
|
||||||
|
|
||||||
|
/** Remove the signed-in user's in-progress draft and any files still tied to it. */
|
||||||
|
export async function deleteRuleDraftForUser(userId: string): Promise<void> {
|
||||||
|
const draft = await prisma.ruleDraft.findUnique({
|
||||||
|
where: { userId },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
if (draft) {
|
||||||
|
await deleteUploadsForDraft(draft.id);
|
||||||
|
}
|
||||||
|
await prisma.ruleDraft.deleteMany({ where: { userId } });
|
||||||
|
}
|
||||||
@@ -30,6 +30,10 @@
|
|||||||
"title": "Binding arbitration needs each member’s own yes",
|
"title": "Binding arbitration needs each member’s own yes",
|
||||||
"description": "Open admission and membership by token do not record that yes. Each member still has to agree separately before binding arbitration applies to them."
|
"description": "Open admission and membership by token do not record that yes. Each member still has to agree separately before binding arbitration applies to them."
|
||||||
},
|
},
|
||||||
|
"missingWordsWarning": {
|
||||||
|
"title": "Add words before you finish",
|
||||||
|
"description": "These still need words: {labels}."
|
||||||
|
},
|
||||||
"categories": [
|
"categories": [
|
||||||
{
|
{
|
||||||
"name": "Values",
|
"name": "Values",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"intro": {
|
"intro": {
|
||||||
"title": "CommunityRule Template",
|
"title": "CommunityRule Template",
|
||||||
"description": "These templates can get you started with a proven approach to governance and decision-making. As useful as these templates are, they are not one size fit all solutions though. We recommend that you use them as a starting place for your community to adapt and customize according to your group's specific needs."
|
"description": "These templates can get you started with a proven approach to governance and decision-making. As useful as these templates are, they are not one size fits all solutions though. We recommend that you use them as a starting place for your community to adapt and customize according to your group's specific needs."
|
||||||
},
|
},
|
||||||
"footer": {
|
"footer": {
|
||||||
"useWithoutChanges": "Use without changes",
|
"useWithoutChanges": "Use without changes",
|
||||||
@@ -12,6 +12,12 @@
|
|||||||
"notFound": "This template was not found.",
|
"notFound": "This template was not found.",
|
||||||
"applyFailed": "Something went wrong. Please try again."
|
"applyFailed": "Something went wrong. Please try again."
|
||||||
},
|
},
|
||||||
|
"replaceDraft": {
|
||||||
|
"title": "Replace the draft in progress?",
|
||||||
|
"description": "Starting this template replaces the draft you have been working on.",
|
||||||
|
"proceed": "Use this template",
|
||||||
|
"cancel": "Keep my draft"
|
||||||
|
},
|
||||||
"loading": "Loading template…",
|
"loading": "Loading template…",
|
||||||
"chipDetailModal": {
|
"chipDetailModal": {
|
||||||
"closeButton": "Close",
|
"closeButton": "Close",
|
||||||
|
|||||||
@@ -19,6 +19,10 @@
|
|||||||
"leaveConfirmProceed": "Leave anyway",
|
"leaveConfirmProceed": "Leave anyway",
|
||||||
"leaveConfirmSaveProgress": "Save my progress",
|
"leaveConfirmSaveProgress": "Save my progress",
|
||||||
"leaveConfirmCancel": "Stay",
|
"leaveConfirmCancel": "Stay",
|
||||||
|
"editReplaceDraftTitle": "Replace the draft in progress?",
|
||||||
|
"editReplaceDraftDescription": "Edit opens this finished Rule. The draft you have been working on will be replaced in this browser.",
|
||||||
|
"editReplaceDraftProceed": "Edit this Rule",
|
||||||
|
"editReplaceDraftCancel": "Keep my draft",
|
||||||
"draftSaveBannerTitle": "Couldn't save draft",
|
"draftSaveBannerTitle": "Couldn't save draft",
|
||||||
"postLoginSaveFailedWithReason": "Could not save your draft to your account. Your progress is still stored on this device.\n\n{reason}",
|
"postLoginSaveFailedWithReason": "Could not save your draft to your account. Your progress is still stored on this device.\n\n{reason}",
|
||||||
"offlineTitle": "You're offline",
|
"offlineTitle": "You're offline",
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
import { useSearchParams } from "next/navigation";
|
import { useSearchParams } from "next/navigation";
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
import { renderWithProviders as render, screen } from "../utils/test-utils";
|
import {
|
||||||
|
renderWithProviders as render,
|
||||||
|
screen,
|
||||||
|
waitFor,
|
||||||
|
} from "../utils/test-utils";
|
||||||
import "@testing-library/jest-dom/vitest";
|
import "@testing-library/jest-dom/vitest";
|
||||||
import { CompletedScreen } from "../../app/(app)/create/screens/completed/CompletedScreen";
|
import { CompletedScreen } from "../../app/(app)/create/screens/completed/CompletedScreen";
|
||||||
import { CREATE_FLOW_LAST_PUBLISHED_KEY } from "../../lib/create/lastPublishedRule";
|
import { CREATE_FLOW_LAST_PUBLISHED_KEY } from "../../lib/create/lastPublishedRule";
|
||||||
@@ -8,6 +12,14 @@ import {
|
|||||||
CREATE_FLOW_COMPLETED_CELEBRATE_QUERY,
|
CREATE_FLOW_COMPLETED_CELEBRATE_QUERY,
|
||||||
CREATE_FLOW_COMPLETED_CELEBRATE_VALUE,
|
CREATE_FLOW_COMPLETED_CELEBRATE_VALUE,
|
||||||
} from "../../app/(app)/create/utils/flowSteps";
|
} from "../../app/(app)/create/utils/flowSteps";
|
||||||
|
import { testRouter } from "../mocks/navigation";
|
||||||
|
|
||||||
|
const fetchPublishedRuleDetail = vi.hoisted(() => vi.fn());
|
||||||
|
|
||||||
|
vi.mock("../../lib/create/api", () => ({
|
||||||
|
fetchPublishedRuleDetail: (...args: unknown[]) =>
|
||||||
|
fetchPublishedRuleDetail(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
const storedRuleFixture = {
|
const storedRuleFixture = {
|
||||||
id: "rule-fixture-1",
|
id: "rule-fixture-1",
|
||||||
@@ -48,6 +60,8 @@ function mockSearchParams(record?: Record<string, string>) {
|
|||||||
describe("CompletedScreen", () => {
|
describe("CompletedScreen", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
sessionStorage.removeItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
|
sessionStorage.removeItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
|
||||||
|
fetchPublishedRuleDetail.mockReset();
|
||||||
|
testRouter.replace.mockReset();
|
||||||
mockSearchParams();
|
mockSearchParams();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -165,4 +179,52 @@ describe("CompletedScreen", () => {
|
|||||||
),
|
),
|
||||||
).toBe(true);
|
).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("loads an owned Rule from ?ruleId= and stores it", async () => {
|
||||||
|
fetchPublishedRuleDetail.mockResolvedValue({
|
||||||
|
viewerIsOwner: true,
|
||||||
|
rule: {
|
||||||
|
id: "rule-owned",
|
||||||
|
title: "QA Tenants Union",
|
||||||
|
summary: "How we share the building.",
|
||||||
|
document: storedRuleFixture.document,
|
||||||
|
createdAt: "2026-11-01T00:00:00.000Z",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
mockSearchParams({ ruleId: "rule-owned" });
|
||||||
|
render(<CompletedScreen />);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
await screen.findByRole("heading", { name: "QA Tenants Union" }),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(testRouter.replace).toHaveBeenCalledWith("/create/completed");
|
||||||
|
});
|
||||||
|
const stored = JSON.parse(
|
||||||
|
sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY) ?? "null",
|
||||||
|
);
|
||||||
|
expect(stored).toMatchObject({
|
||||||
|
id: "rule-owned",
|
||||||
|
title: "QA Tenants Union",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sends a non-owner ?ruleId= load to the reader page", async () => {
|
||||||
|
fetchPublishedRuleDetail.mockResolvedValue({
|
||||||
|
viewerIsOwner: false,
|
||||||
|
rule: {
|
||||||
|
id: "rule-other",
|
||||||
|
title: "Someone else's Rule",
|
||||||
|
summary: null,
|
||||||
|
document: storedRuleFixture.document,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
mockSearchParams({ ruleId: "rule-other" });
|
||||||
|
render(<CompletedScreen />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(testRouter.replace).toHaveBeenCalledWith("/rules/rule-other");
|
||||||
|
});
|
||||||
|
expect(sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).toBeNull();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -241,6 +241,14 @@ describe("FinalReviewScreen — prefilled selections", () => {
|
|||||||
expect(
|
expect(
|
||||||
screen.getByRole("button", { name: "Signal, missing words" }),
|
screen.getByRole("button", { name: "Signal, missing words" }),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.getByText("Add words before you finish"),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.getByText(
|
||||||
|
/These still need words: Accessibility, Signal, Open admission/,
|
||||||
|
),
|
||||||
|
).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("warns when binding arbitration sits next to a join that records no yes", async () => {
|
it("warns when binding arbitration sits next to a join that records no yes", async () => {
|
||||||
|
|||||||
@@ -45,7 +45,11 @@ vi.mock("../../app/(app)/create/utils/anonymousDraftStorage", async (importOrigi
|
|||||||
|
|
||||||
import { EMAIL_MAX_LEN } from "../../lib/create/isValidCreateFlowSaveEmail";
|
import { EMAIL_MAX_LEN } from "../../lib/create/isValidCreateFlowSaveEmail";
|
||||||
import { requestMagicLink } from "../../lib/create/api";
|
import { requestMagicLink } from "../../lib/create/api";
|
||||||
import { setTransferPendingFlag } from "../../app/(app)/create/utils/anonymousDraftStorage";
|
import {
|
||||||
|
CREATE_FLOW_ANONYMOUS_KEY,
|
||||||
|
CREATE_FLOW_TRANSFER_PENDING_KEY,
|
||||||
|
setTransferPendingFlag,
|
||||||
|
} from "../../app/(app)/create/utils/anonymousDraftStorage";
|
||||||
|
|
||||||
function renderLoginForm() {
|
function renderLoginForm() {
|
||||||
return renderWithProviders(
|
return renderWithProviders(
|
||||||
@@ -62,6 +66,7 @@ describe("LoginForm", () => {
|
|||||||
navMock.replace.mockReset();
|
navMock.replace.mockReset();
|
||||||
navMock.pathname = "/";
|
navMock.pathname = "/";
|
||||||
navMock.searchParams = new URLSearchParams();
|
navMock.searchParams = new URLSearchParams();
|
||||||
|
window.localStorage.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("renders title, email field, and submit control", () => {
|
it("renders title, email field, and submit control", () => {
|
||||||
@@ -368,6 +373,34 @@ describe("LoginForm", () => {
|
|||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("clears the transfer flag on an expired link and keeps the browser draft", () => {
|
||||||
|
window.localStorage.setItem(
|
||||||
|
CREATE_FLOW_ANONYMOUS_KEY,
|
||||||
|
JSON.stringify({ title: "Garden coop" }),
|
||||||
|
);
|
||||||
|
window.localStorage.setItem(CREATE_FLOW_TRANSFER_PENDING_KEY, "1");
|
||||||
|
navMock.searchParams = new URLSearchParams("error=expired_link");
|
||||||
|
renderLoginForm();
|
||||||
|
expect(window.localStorage.getItem(CREATE_FLOW_TRANSFER_PENDING_KEY)).toBeNull();
|
||||||
|
expect(window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toContain(
|
||||||
|
"Garden coop",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clears the transfer flag on an already-used link and keeps the browser draft", () => {
|
||||||
|
window.localStorage.setItem(
|
||||||
|
CREATE_FLOW_ANONYMOUS_KEY,
|
||||||
|
JSON.stringify({ title: "Garden coop" }),
|
||||||
|
);
|
||||||
|
window.localStorage.setItem(CREATE_FLOW_TRANSFER_PENDING_KEY, "1");
|
||||||
|
navMock.searchParams = new URLSearchParams("error=invalid_link");
|
||||||
|
renderLoginForm();
|
||||||
|
expect(window.localStorage.getItem(CREATE_FLOW_TRANSFER_PENDING_KEY)).toBeNull();
|
||||||
|
expect(window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toContain(
|
||||||
|
"Garden coop",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
it("shows URL-driven error for invalid_link", () => {
|
it("shows URL-driven error for invalid_link", () => {
|
||||||
navMock.searchParams = new URLSearchParams("error=invalid_link");
|
navMock.searchParams = new URLSearchParams("error=invalid_link");
|
||||||
renderLoginForm();
|
renderLoginForm();
|
||||||
|
|||||||
@@ -67,16 +67,13 @@ describe('Top "Create rule" button', () => {
|
|||||||
window.localStorage.clear();
|
window.localStorage.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
it("keeps the browser draft and resumes the step it was left on", async () => {
|
||||||
* Guards against localStorage stickiness on the marketing homepage: hitting
|
|
||||||
* the top-nav "Create rule" from anywhere outside `/create` must wipe the
|
|
||||||
* in-flight anonymous draft so the wizard always starts fresh. See
|
|
||||||
* handleCreateRuleClick in Top.container.tsx for the contract.
|
|
||||||
*/
|
|
||||||
it("clears anonymous draft + core-value-details localStorage before routing to /create/informational", async () => {
|
|
||||||
window.localStorage.setItem(
|
window.localStorage.setItem(
|
||||||
CREATE_FLOW_ANONYMOUS_KEY,
|
CREATE_FLOW_ANONYMOUS_KEY,
|
||||||
JSON.stringify({ title: "Stale community" }),
|
JSON.stringify({
|
||||||
|
title: "Stale community",
|
||||||
|
currentStep: "community-name",
|
||||||
|
}),
|
||||||
);
|
);
|
||||||
window.localStorage.setItem(
|
window.localStorage.setItem(
|
||||||
CORE_VALUE_DETAILS_STORAGE_KEY,
|
CORE_VALUE_DETAILS_STORAGE_KEY,
|
||||||
@@ -91,12 +88,14 @@ describe('Top "Create rule" button', () => {
|
|||||||
await userEvent.click(btn);
|
await userEvent.click(btn);
|
||||||
|
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(pushMock).toHaveBeenCalledWith("/create/informational");
|
expect(pushMock).toHaveBeenCalledWith("/create/community-name");
|
||||||
});
|
});
|
||||||
expect(window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toBeNull();
|
expect(window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toContain(
|
||||||
|
"Stale community",
|
||||||
|
);
|
||||||
expect(
|
expect(
|
||||||
window.localStorage.getItem(CORE_VALUE_DETAILS_STORAGE_KEY),
|
window.localStorage.getItem(CORE_VALUE_DETAILS_STORAGE_KEY),
|
||||||
).toBeNull();
|
).not.toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("pads the standard header to hug Create rule", () => {
|
it("pads the standard header to hug Create rule", () => {
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
import { describe, it, expect } from "vitest";
|
import { afterEach, describe, it, expect } from "vitest";
|
||||||
import { act, render, screen } from "@testing-library/react";
|
import { act, render, screen, waitFor } from "@testing-library/react";
|
||||||
import "@testing-library/jest-dom/vitest";
|
import "@testing-library/jest-dom/vitest";
|
||||||
import {
|
import {
|
||||||
CreateFlowProvider,
|
CreateFlowProvider,
|
||||||
useCreateFlow,
|
useCreateFlow,
|
||||||
} from "../../app/(app)/create/context/CreateFlowContext";
|
} from "../../app/(app)/create/context/CreateFlowContext";
|
||||||
|
import {
|
||||||
|
CREATE_FLOW_ANONYMOUS_KEY,
|
||||||
|
CREATE_FLOW_TRANSFER_PENDING_KEY,
|
||||||
|
} from "../../app/(app)/create/utils/anonymousDraftStorage";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Harness: mounts a consumer that renders the state we want to assert on and
|
* Harness: mounts a consumer that renders the state we want to assert on and
|
||||||
@@ -46,6 +50,15 @@ function Harness() {
|
|||||||
<div data-testid="pin-method">
|
<div data-testid="pin-method">
|
||||||
{state.methodSectionsPinCommitted?.communication ? "yes" : "no"}
|
{state.methodSectionsPinCommitted?.communication ? "yes" : "no"}
|
||||||
</div>
|
</div>
|
||||||
|
<div data-testid="size">
|
||||||
|
{(state.selectedCommunitySizeIds ?? []).join(",")}
|
||||||
|
</div>
|
||||||
|
<div data-testid="kind">
|
||||||
|
{(state.selectedOrganizationTypeIds ?? []).join(",")}
|
||||||
|
</div>
|
||||||
|
<div data-testid="maturity">
|
||||||
|
{(state.selectedMaturityIds ?? []).join(",")}
|
||||||
|
</div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -129,3 +142,56 @@ describe("CreateFlowContext — resetCustomRuleSelections", () => {
|
|||||||
expect(screen.getByTestId("core").textContent).toBe("");
|
expect(screen.getByTestId("core").textContent).toBe("");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("CreateFlowContext — draft hydration after Save your progress", () => {
|
||||||
|
afterEach(() => {
|
||||||
|
window.localStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("loads the stored draft when mirroring turns on, even with the transfer flag", async () => {
|
||||||
|
window.localStorage.setItem(
|
||||||
|
CREATE_FLOW_ANONYMOUS_KEY,
|
||||||
|
JSON.stringify({
|
||||||
|
title: "Juniper Street Tenants",
|
||||||
|
selectedCommunitySizeIds: ["thirteenToOneHundred"],
|
||||||
|
selectedOrganizationTypeIds: ["housing"],
|
||||||
|
selectedMaturityIds: ["forming"],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
window.localStorage.setItem(CREATE_FLOW_TRANSFER_PENDING_KEY, "1");
|
||||||
|
|
||||||
|
const { rerender } = render(
|
||||||
|
<CreateFlowProvider enableLocalDraftMirroring={false}>
|
||||||
|
<Harness />
|
||||||
|
</CreateFlowProvider>,
|
||||||
|
);
|
||||||
|
rerender(
|
||||||
|
<CreateFlowProvider enableLocalDraftMirroring>
|
||||||
|
<Harness />
|
||||||
|
</CreateFlowProvider>,
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByTestId("title").textContent).toBe(
|
||||||
|
"Juniper Street Tenants",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
expect(screen.getByTestId("size").textContent).toBe("thirteenToOneHundred");
|
||||||
|
expect(screen.getByTestId("kind").textContent).toBe("housing");
|
||||||
|
expect(screen.getByTestId("maturity").textContent).toBe("forming");
|
||||||
|
|
||||||
|
act(() => {
|
||||||
|
getUpdateState()({ title: "Juniper Street Tenants Union" });
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
const stored = JSON.parse(
|
||||||
|
window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY) ?? "{}",
|
||||||
|
) as Record<string, unknown>;
|
||||||
|
expect(stored.title).toBe("Juniper Street Tenants Union");
|
||||||
|
expect(stored.selectedCommunitySizeIds).toEqual(["thirteenToOneHundred"]);
|
||||||
|
expect(stored.selectedOrganizationTypeIds).toEqual(["housing"]);
|
||||||
|
expect(stored.selectedMaturityIds).toEqual(["forming"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -121,7 +121,7 @@ describe("ProfilePageView", () => {
|
|||||||
expect(screen.getByText(copy.emptyCardBody)).toBeInTheDocument();
|
expect(screen.getByText(copy.emptyCardBody)).toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.getByRole("link", { name: copy.emptyCardBrowse }),
|
screen.getByRole("link", { name: copy.emptyCardBrowse }),
|
||||||
).toHaveAttribute("href", "/templates?fromFlow=1");
|
).toHaveAttribute("href", "/templates");
|
||||||
|
|
||||||
await user.click(
|
await user.click(
|
||||||
screen.getByRole("button", { name: copy.emptyCardCreate }),
|
screen.getByRole("button", { name: copy.emptyCardCreate }),
|
||||||
@@ -224,6 +224,11 @@ describe("ProfilePageView", () => {
|
|||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
screen.getByRole("heading", {
|
||||||
|
name: copy.welcomeTitle.replace("{{name}}", "dani@example.com"),
|
||||||
|
}),
|
||||||
|
).toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.getByText(copy.welcomeBodyFirstRule),
|
screen.getByText(copy.welcomeBodyFirstRule),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
@@ -242,6 +247,9 @@ describe("ProfilePageView", () => {
|
|||||||
expect(
|
expect(
|
||||||
screen.getByRole("button", { name: copy.deleteRule }),
|
screen.getByRole("button", { name: copy.deleteRule }),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.getByRole("link", { name: "Garden coop" }),
|
||||||
|
).toHaveAttribute("href", "/create/completed?ruleId=rule-1");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("lists invited Rules under Rules you belong to, not Your Rules", () => {
|
test("lists invited Rules under Rules you belong to, not Your Rules", () => {
|
||||||
@@ -274,8 +282,8 @@ describe("ProfilePageView", () => {
|
|||||||
screen.getByRole("heading", { name: copy.rulesYouBelongToHeading }),
|
screen.getByRole("heading", { name: copy.rulesYouBelongToHeading }),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
expect(
|
expect(
|
||||||
screen.getByRole("link", { name: /Hawthorn Row Seed Library/ }),
|
screen.getByRole("link", { name: "Hawthorn Row Seed Library" }),
|
||||||
).toHaveAttribute("href", "/invite/rule-invited");
|
).toHaveAttribute("href", "/rules/rule-invited");
|
||||||
expect(
|
expect(
|
||||||
screen.queryByRole("button", { name: copy.viewPublic }),
|
screen.queryByRole("button", { name: copy.viewPublic }),
|
||||||
).not.toBeInTheDocument();
|
).not.toBeInTheDocument();
|
||||||
@@ -340,5 +348,11 @@ describe("ProfilePageView", () => {
|
|||||||
expect(
|
expect(
|
||||||
screen.getByRole("button", { name: copy.continueDraft }),
|
screen.getByRole("button", { name: copy.continueDraft }),
|
||||||
).toBeInTheDocument();
|
).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.getByRole("button", { name: copy.deleteRule }),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(
|
||||||
|
screen.queryByRole("button", { name: copy.inviteMembers }),
|
||||||
|
).not.toBeInTheDocument();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -94,6 +94,25 @@ describe("Rule Component", () => {
|
|||||||
expect(handleClick).toHaveBeenCalledTimes(1);
|
expect(handleClick).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps bottom links and names the overlay link with ariaLabel", () => {
|
||||||
|
const onInvite = vi.fn();
|
||||||
|
render(
|
||||||
|
<Rule
|
||||||
|
{...defaultProps}
|
||||||
|
href="/create/completed?ruleId=rule-1"
|
||||||
|
ariaLabel="Garden coop"
|
||||||
|
hasBottomLinks
|
||||||
|
bottomLinks={[{ id: "invite", label: "Invite your members", onClick: onInvite }]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
screen.getByRole("link", { name: "Garden coop" }),
|
||||||
|
).toHaveAttribute("href", "/create/completed?ruleId=rule-1");
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Invite your members" }));
|
||||||
|
expect(onInvite).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
it("applies hover effects correctly", () => {
|
it("applies hover effects correctly", () => {
|
||||||
render(<Rule {...defaultProps} />);
|
render(<Rule {...defaultProps} />);
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
CREATE_FLOW_ANONYMOUS_KEY,
|
CREATE_FLOW_ANONYMOUS_KEY,
|
||||||
CREATE_FLOW_TRANSFER_PENDING_KEY,
|
CREATE_FLOW_TRANSFER_PENDING_KEY,
|
||||||
clearAnonymousCreateFlowStorage,
|
clearAnonymousCreateFlowStorage,
|
||||||
|
clearTransferPendingFlag,
|
||||||
} from "../../app/(app)/create/utils/anonymousDraftStorage";
|
} from "../../app/(app)/create/utils/anonymousDraftStorage";
|
||||||
|
|
||||||
describe("clearAnonymousCreateFlowStorage", () => {
|
describe("clearAnonymousCreateFlowStorage", () => {
|
||||||
@@ -41,3 +42,19 @@ describe("clearAnonymousCreateFlowStorage", () => {
|
|||||||
expect(forgetFlushedCommunityAvatarUrl).not.toHaveBeenCalled();
|
expect(forgetFlushedCommunityAvatarUrl).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("clearTransferPendingFlag", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
localStorage.clear();
|
||||||
|
localStorage.setItem(CREATE_FLOW_ANONYMOUS_KEY, "{\"title\":\"Garden\"}");
|
||||||
|
localStorage.setItem(CREATE_FLOW_TRANSFER_PENDING_KEY, "1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes the flag and leaves the stored draft", () => {
|
||||||
|
clearTransferPendingFlag();
|
||||||
|
expect(localStorage.getItem(CREATE_FLOW_TRANSFER_PENDING_KEY)).toBeNull();
|
||||||
|
expect(localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toBe(
|
||||||
|
"{\"title\":\"Garden\"}",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import {
|
import {
|
||||||
|
buildAppliedTemplateCreateFlowState,
|
||||||
buildCoreValuesPrefillFromTemplateBody,
|
buildCoreValuesPrefillFromTemplateBody,
|
||||||
buildTemplateCustomizePrefill,
|
buildTemplateCustomizePrefill,
|
||||||
templatePresetDetailsFromPrefill,
|
templatePresetDetailsFromPrefill,
|
||||||
@@ -224,6 +225,31 @@ describe("buildTemplateCustomizePrefill from templateChips.json", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("buildAppliedTemplateCreateFlowState", () => {
|
||||||
|
it("starts from the template and drops leftover draft identity", () => {
|
||||||
|
const seeded = buildAppliedTemplateCreateFlowState({
|
||||||
|
slug: "mutual-aid-mondays",
|
||||||
|
body: {
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
categoryName: "Communication",
|
||||||
|
entries: [{ title: "Signal" }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
mode: "useWithoutChanges",
|
||||||
|
});
|
||||||
|
expect(seeded.title).toBeUndefined();
|
||||||
|
expect(seeded.communityAvatarUrl).toBeUndefined();
|
||||||
|
expect(seeded.setupTraits).toBeUndefined();
|
||||||
|
expect(seeded.selectedCommunicationMethodIds).toEqual(["signal"]);
|
||||||
|
expect(seeded.pendingTemplateAction).toEqual({
|
||||||
|
slug: "mutual-aid-mondays",
|
||||||
|
mode: "useWithoutChanges",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("templatePresetDetailsFromPrefill", () => {
|
describe("templatePresetDetailsFromPrefill", () => {
|
||||||
it("fills catalog copy for each prefilled chip", () => {
|
it("fills catalog copy for each prefilled chip", () => {
|
||||||
const details = templatePresetDetailsFromPrefill({
|
const details = templatePresetDetailsFromPrefill({
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import {
|
||||||
|
createFlowStateForEditingPublishedRule,
|
||||||
|
createFlowStateMatchesPublishedRule,
|
||||||
|
publishedRuleEditWouldReplaceDraft,
|
||||||
|
} from "../../lib/create/beginEditingPublishedRule";
|
||||||
|
import type { StoredLastPublishedRule } from "../../lib/create/lastPublishedRule";
|
||||||
|
import type { CreateFlowState } from "../../app/(app)/create/types";
|
||||||
|
|
||||||
|
const published: StoredLastPublishedRule = {
|
||||||
|
id: "rule-qa",
|
||||||
|
title: "QA Tenants Union",
|
||||||
|
summary: "How we share the building.",
|
||||||
|
document: {
|
||||||
|
coreValues: [
|
||||||
|
{
|
||||||
|
chipId: "accountability",
|
||||||
|
label: "Accountability",
|
||||||
|
meaning: "We say what we will do.",
|
||||||
|
signals: "",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
methodSelections: {
|
||||||
|
communication: [
|
||||||
|
{
|
||||||
|
id: "signal",
|
||||||
|
label: "Signal",
|
||||||
|
sections: {
|
||||||
|
corePrinciple: "We write it down.",
|
||||||
|
logisticsAdmin: "A shared thread.",
|
||||||
|
codeOfConduct: "No pile-ons.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("publishedRuleEditWouldReplaceDraft", () => {
|
||||||
|
it("is false when there is no draft", () => {
|
||||||
|
expect(publishedRuleEditWouldReplaceDraft({}, published)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is false when the draft is already this finished Rule", () => {
|
||||||
|
const state = createFlowStateForEditingPublishedRule(published);
|
||||||
|
expect(publishedRuleEditWouldReplaceDraft(state, published)).toBe(false);
|
||||||
|
expect(createFlowStateMatchesPublishedRule(state, published)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is true when the draft is a different community", () => {
|
||||||
|
const state: CreateFlowState = {
|
||||||
|
title: "The CommunityRule Project",
|
||||||
|
selectedCoreValueIds: ["solidarity"],
|
||||||
|
selectedCommunicationMethodIds: ["loomio"],
|
||||||
|
};
|
||||||
|
expect(publishedRuleEditWouldReplaceDraft(state, published)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is true when the draft is already marked as an edit of another Rule", () => {
|
||||||
|
const state: CreateFlowState = {
|
||||||
|
...createFlowStateForEditingPublishedRule(published),
|
||||||
|
editingPublishedRuleId: "some-other-rule",
|
||||||
|
};
|
||||||
|
expect(publishedRuleEditWouldReplaceDraft(state, published)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is true when the same cards have different description, details, or field blocks", () => {
|
||||||
|
const loaded = createFlowStateForEditingPublishedRule(published);
|
||||||
|
|
||||||
|
const rewrittenContext: CreateFlowState = {
|
||||||
|
...loaded,
|
||||||
|
communityContext: "A different description.",
|
||||||
|
summary: "A different description.",
|
||||||
|
};
|
||||||
|
expect(
|
||||||
|
createFlowStateMatchesPublishedRule(rewrittenContext, published),
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
publishedRuleEditWouldReplaceDraft(rewrittenContext, published),
|
||||||
|
).toBe(true);
|
||||||
|
|
||||||
|
const rewrittenMeaning: CreateFlowState = {
|
||||||
|
...loaded,
|
||||||
|
coreValueDetailsByChipId: {
|
||||||
|
accountability: {
|
||||||
|
meaning: "We changed what this means.",
|
||||||
|
signals: "",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
expect(
|
||||||
|
publishedRuleEditWouldReplaceDraft(rewrittenMeaning, published),
|
||||||
|
).toBe(true);
|
||||||
|
|
||||||
|
const rewrittenMethod: CreateFlowState = {
|
||||||
|
...loaded,
|
||||||
|
communicationMethodDetailsById: {
|
||||||
|
signal: {
|
||||||
|
corePrinciple: "We say it out loud.",
|
||||||
|
logisticsAdmin: "A shared thread.",
|
||||||
|
codeOfConduct: "No pile-ons.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
expect(publishedRuleEditWouldReplaceDraft(rewrittenMethod, published)).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
|
||||||
|
const rewrittenBlocks: CreateFlowState = {
|
||||||
|
...loaded,
|
||||||
|
customMethodCardFieldBlocksById: {
|
||||||
|
signal: [
|
||||||
|
{
|
||||||
|
kind: "text",
|
||||||
|
id: "notes",
|
||||||
|
blockTitle: "Notes",
|
||||||
|
placeholderText: "What changed",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
expect(publishedRuleEditWouldReplaceDraft(rewrittenBlocks, published)).toBe(
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("createFlowStateForEditingPublishedRule", () => {
|
||||||
|
it("loads the finished Rule's own name and cards, not leftover draft fields", () => {
|
||||||
|
const state = createFlowStateForEditingPublishedRule(published);
|
||||||
|
expect(state.title).toBe("QA Tenants Union");
|
||||||
|
expect(state.editingPublishedRuleId).toBe("rule-qa");
|
||||||
|
expect(state.selectedCommunicationMethodIds).toEqual(["signal"]);
|
||||||
|
expect(state.selectedOrganizationTypeIds).toBeUndefined();
|
||||||
|
expect(state.communityAvatarUrl).toBeUndefined();
|
||||||
|
expect(state.sections).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,7 +4,6 @@ import {
|
|||||||
parseDocumentSectionsForDisplay,
|
parseDocumentSectionsForDisplay,
|
||||||
parseSectionsFromCreateFlowState,
|
parseSectionsFromCreateFlowState,
|
||||||
} from "../../lib/create/buildPublishPayload";
|
} from "../../lib/create/buildPublishPayload";
|
||||||
import { mergeCoreValueDetailWithPresets } from "../../lib/create/finalReviewChipPresets";
|
|
||||||
import type { CreateFlowState } from "../../app/(app)/create/types";
|
import type { CreateFlowState } from "../../app/(app)/create/types";
|
||||||
|
|
||||||
describe("buildPublishPayload", () => {
|
describe("buildPublishPayload", () => {
|
||||||
@@ -144,15 +143,9 @@ describe("buildPublishPayload", () => {
|
|||||||
});
|
});
|
||||||
expect(r.ok).toBe(true);
|
expect(r.ok).toBe(true);
|
||||||
if (!r.ok) return;
|
if (!r.ok) return;
|
||||||
const preset2 = mergeCoreValueDetailWithPresets("2", "Beta", undefined);
|
|
||||||
expect(r.document.coreValues).toEqual([
|
expect(r.document.coreValues).toEqual([
|
||||||
{ chipId: "1", label: "Alpha", meaning: "m1", signals: "s1" },
|
{ chipId: "1", label: "Alpha", meaning: "m1", signals: "s1" },
|
||||||
{
|
{ chipId: "2", label: "Beta", meaning: "", signals: "" },
|
||||||
chipId: "2",
|
|
||||||
label: "Beta",
|
|
||||||
meaning: preset2.meaning,
|
|
||||||
signals: preset2.signals,
|
|
||||||
},
|
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -188,11 +181,12 @@ describe("buildPublishPayload — methodSelections", () => {
|
|||||||
expect(ms?.communication?.length).toBe(1);
|
expect(ms?.communication?.length).toBe(1);
|
||||||
expect(ms?.communication?.[0]?.id).toBe("slack");
|
expect(ms?.communication?.[0]?.id).toBe("slack");
|
||||||
const first = ms?.communication?.[0];
|
const first = ms?.communication?.[0];
|
||||||
expect(first?.sections.corePrinciple.length).toBeGreaterThan(10);
|
expect(first?.sections.corePrinciple).toBe("");
|
||||||
const entries =
|
const entries =
|
||||||
(r.document.sections as Array<{ entries: Array<{ blocks?: unknown[] }> }>)[0]
|
(r.document.sections as Array<{
|
||||||
?.entries;
|
entries: Array<{ title: string; body: string; blocks?: unknown[] }>;
|
||||||
expect(entries?.[0]?.blocks?.length).toBeGreaterThanOrEqual(1);
|
}>)[0]?.entries;
|
||||||
|
expect(entries?.[0]).toEqual({ title: "Slack", body: "" });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("uses customMethodCardMetaById label when preset id is unknown", () => {
|
it("uses customMethodCardMetaById label when preset id is unknown", () => {
|
||||||
@@ -251,7 +245,7 @@ describe("buildPublishPayload — methodSelections", () => {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("emits preset-only sections when a method is selected without an override", () => {
|
it("keeps blank card parts blank when a method is selected without an override", () => {
|
||||||
const r = buildPublishPayload({
|
const r = buildPublishPayload({
|
||||||
title: "T",
|
title: "T",
|
||||||
selectedCommunicationMethodIds: ["signal"],
|
selectedCommunicationMethodIds: ["signal"],
|
||||||
@@ -270,9 +264,7 @@ describe("buildPublishPayload — methodSelections", () => {
|
|||||||
};
|
};
|
||||||
expect(entry.id).toBe("signal");
|
expect(entry.id).toBe("signal");
|
||||||
expect(entry.label).toBe("Signal");
|
expect(entry.label).toBe("Signal");
|
||||||
// Preset corePrinciple is non-empty for `signal` in the shipped messages
|
expect(entry.sections.corePrinciple).toBe("");
|
||||||
// file — proves we read presets when no override is present.
|
|
||||||
expect(entry.sections.corePrinciple.length).toBeGreaterThan(0);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not seed 75% consensus on a custom decision-making card", () => {
|
it("does not seed 75% consensus on a custom decision-making card", () => {
|
||||||
@@ -311,7 +303,7 @@ describe("buildPublishPayload — methodSelections", () => {
|
|||||||
expect(ms.decisionApproaches?.[0]?.sections.consensusLevel).toBeUndefined();
|
expect(ms.decisionApproaches?.[0]?.sections.consensusLevel).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("keeps catalog decision consensus in methodSelections", () => {
|
it("does not fill catalog decision consensus when the card has no words", () => {
|
||||||
const r = buildPublishPayload({
|
const r = buildPublishPayload({
|
||||||
title: "T",
|
title: "T",
|
||||||
selectedDecisionApproachIds: ["lazy-consensus"],
|
selectedDecisionApproachIds: ["lazy-consensus"],
|
||||||
@@ -321,7 +313,7 @@ describe("buildPublishPayload — methodSelections", () => {
|
|||||||
const ms = r.document.methodSelections as {
|
const ms = r.document.methodSelections as {
|
||||||
decisionApproaches?: Array<{ sections: { consensusLevel?: number } }>;
|
decisionApproaches?: Array<{ sections: { consensusLevel?: number } }>;
|
||||||
};
|
};
|
||||||
expect(ms.decisionApproaches?.[0]?.sections.consensusLevel).toBe(100);
|
expect(ms.decisionApproaches?.[0]?.sections.consensusLevel).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("merges override on top of preset for the selected method", () => {
|
it("merges override on top of preset for the selected method", () => {
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { CREATE_FLOW_ANONYMOUS_KEY } from "../../app/(app)/create/utils/anonymousDraftStorage";
|
||||||
|
import { clearBrowserRuleData } from "../../app/(app)/create/utils/clearBrowserRuleData";
|
||||||
|
import { CORE_VALUE_DETAILS_STORAGE_KEY } from "../../app/(app)/create/utils/coreValueDetailsLocalStorage";
|
||||||
|
import { CREATE_FLOW_LAST_PUBLISHED_KEY } from "../../lib/create/lastPublishedRule";
|
||||||
|
import { CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY } from "../../lib/create/pendingKeepRuleLogin";
|
||||||
|
|
||||||
|
const deleteServerDraft = vi.fn();
|
||||||
|
|
||||||
|
vi.mock("../../lib/create/api", () => ({
|
||||||
|
deleteServerDraft: (...args: unknown[]) => deleteServerDraft(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe("clearBrowserRuleData", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
deleteServerDraft.mockReset();
|
||||||
|
window.localStorage.clear();
|
||||||
|
window.sessionStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
window.localStorage.clear();
|
||||||
|
window.sessionStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clears local draft keys and lastPublished without deleting the server draft", () => {
|
||||||
|
window.localStorage.setItem(
|
||||||
|
CREATE_FLOW_ANONYMOUS_KEY,
|
||||||
|
JSON.stringify({ title: "Stale" }),
|
||||||
|
);
|
||||||
|
window.localStorage.setItem(
|
||||||
|
CORE_VALUE_DETAILS_STORAGE_KEY,
|
||||||
|
JSON.stringify({ v1: { meaning: "x" } }),
|
||||||
|
);
|
||||||
|
window.localStorage.setItem("create-flow-state", "{}");
|
||||||
|
window.localStorage.setItem("create-flow-draft", "{}");
|
||||||
|
window.sessionStorage.setItem(
|
||||||
|
CREATE_FLOW_LAST_PUBLISHED_KEY,
|
||||||
|
JSON.stringify({ id: "rule-1", title: "Garden", document: {} }),
|
||||||
|
);
|
||||||
|
window.sessionStorage.setItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY, "1");
|
||||||
|
|
||||||
|
clearBrowserRuleData();
|
||||||
|
|
||||||
|
expect(window.localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY)).toBeNull();
|
||||||
|
expect(window.localStorage.getItem(CORE_VALUE_DETAILS_STORAGE_KEY)).toBeNull();
|
||||||
|
expect(window.localStorage.getItem("create-flow-state")).toBeNull();
|
||||||
|
expect(window.localStorage.getItem("create-flow-draft")).toBeNull();
|
||||||
|
expect(window.sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).toBeNull();
|
||||||
|
expect(
|
||||||
|
window.sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY),
|
||||||
|
).toBeNull();
|
||||||
|
expect(deleteServerDraft).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||||
|
import { CREATE_FLOW_ANONYMOUS_KEY } from "../../app/(app)/create/utils/anonymousDraftStorage";
|
||||||
|
import { CORE_VALUE_DETAILS_STORAGE_KEY } from "../../app/(app)/create/utils/coreValueDetailsLocalStorage";
|
||||||
|
import {
|
||||||
|
createRuleEntryPath,
|
||||||
|
hasBrowserCreateFlowDraft,
|
||||||
|
} from "../../app/(app)/create/utils/createRuleEntry";
|
||||||
|
|
||||||
|
describe("createRuleEntryPath", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
window.localStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
window.localStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("opens the first step when there is no draft", () => {
|
||||||
|
expect(hasBrowserCreateFlowDraft()).toBe(false);
|
||||||
|
expect(createRuleEntryPath()).toBe("/create/informational");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("resumes the stored step", () => {
|
||||||
|
window.localStorage.setItem(
|
||||||
|
CREATE_FLOW_ANONYMOUS_KEY,
|
||||||
|
JSON.stringify({
|
||||||
|
title: "Garden coop",
|
||||||
|
currentStep: "community-size",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(hasBrowserCreateFlowDraft()).toBe(true);
|
||||||
|
expect(createRuleEntryPath()).toBe("/create/community-size");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not resume a finished Rule screen", () => {
|
||||||
|
window.localStorage.setItem(
|
||||||
|
CREATE_FLOW_ANONYMOUS_KEY,
|
||||||
|
JSON.stringify({
|
||||||
|
title: "Garden coop",
|
||||||
|
currentStep: "completed",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(createRuleEntryPath()).toBe("/create/informational");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("treats leftover core-value details as a draft", () => {
|
||||||
|
window.localStorage.setItem(
|
||||||
|
CORE_VALUE_DETAILS_STORAGE_KEY,
|
||||||
|
JSON.stringify({ "1": { meaning: "m", signals: "s" } }),
|
||||||
|
);
|
||||||
|
expect(hasBrowserCreateFlowDraft()).toBe(true);
|
||||||
|
expect(createRuleEntryPath()).toBe("/create/informational");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
import { describe, it, expect } from "vitest";
|
import { describe, it, expect } from "vitest";
|
||||||
import { isFinalReviewContinueBlocked } from "../../app/(app)/create/utils/createFlowFooterLabels";
|
import { isFinalReviewContinueBlocked } from "../../app/(app)/create/utils/createFlowFooterLabels";
|
||||||
import { communityInitialsFromTitle } from "../../lib/create/communityInitials";
|
import { communityInitialsFromTitle } from "../../lib/create/communityInitials";
|
||||||
import { finalReviewChipHasWarning } from "../../lib/create/finalReviewChipWarnings";
|
import {
|
||||||
|
finalReviewChipBlocksContinue,
|
||||||
|
finalReviewChipHasWarning,
|
||||||
|
finalReviewMissingWordsLabels,
|
||||||
|
} from "../../lib/create/finalReviewChipWarnings";
|
||||||
import type { CreateFlowState } from "../../app/(app)/create/types";
|
import type { CreateFlowState } from "../../app/(app)/create/types";
|
||||||
|
|
||||||
const completeCards: CreateFlowState = {
|
const completeCards: CreateFlowState = {
|
||||||
@@ -12,11 +16,47 @@ const completeCards: CreateFlowState = {
|
|||||||
selectedConflictManagementIds: ["conflict-ladder"],
|
selectedConflictManagementIds: ["conflict-ladder"],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const completeCardsWithWords: CreateFlowState = {
|
||||||
|
...completeCards,
|
||||||
|
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.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
describe("isFinalReviewContinueBlocked", () => {
|
describe("isFinalReviewContinueBlocked", () => {
|
||||||
it("blocks when the community name is empty", () => {
|
it("blocks when the community name is empty", () => {
|
||||||
expect(
|
expect(
|
||||||
isFinalReviewContinueBlocked({
|
isFinalReviewContinueBlocked({
|
||||||
...completeCards,
|
...completeCardsWithWords,
|
||||||
title: " ",
|
title: " ",
|
||||||
}),
|
}),
|
||||||
).toBe(true);
|
).toBe(true);
|
||||||
@@ -25,14 +65,45 @@ describe("isFinalReviewContinueBlocked", () => {
|
|||||||
it("blocks when any of the four questions has no card", () => {
|
it("blocks when any of the four questions has no card", () => {
|
||||||
expect(
|
expect(
|
||||||
isFinalReviewContinueBlocked({
|
isFinalReviewContinueBlocked({
|
||||||
...completeCards,
|
...completeCardsWithWords,
|
||||||
selectedMembershipMethodIds: [],
|
selectedMembershipMethodIds: [],
|
||||||
}),
|
}),
|
||||||
).toBe(true);
|
).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not block when values are empty and the four questions have cards", () => {
|
it("blocks when a picked card is missing its words", () => {
|
||||||
expect(isFinalReviewContinueBlocked(completeCards)).toBe(false);
|
expect(isFinalReviewContinueBlocked(completeCards)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not block when values are empty and every card has its words", () => {
|
||||||
|
expect(isFinalReviewContinueBlocked(completeCardsWithWords)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("blocks when a picked value is missing its meaning", () => {
|
||||||
|
expect(
|
||||||
|
isFinalReviewContinueBlocked({
|
||||||
|
...completeCardsWithWords,
|
||||||
|
selectedCoreValueIds: ["1"],
|
||||||
|
coreValuesChipsSnapshot: [
|
||||||
|
{ id: "1", label: "Care", state: "selected" },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not block when a value has meaning but no signals", () => {
|
||||||
|
expect(
|
||||||
|
isFinalReviewContinueBlocked({
|
||||||
|
...completeCardsWithWords,
|
||||||
|
selectedCoreValueIds: ["1"],
|
||||||
|
coreValuesChipsSnapshot: [
|
||||||
|
{ id: "1", label: "Care", state: "selected" },
|
||||||
|
],
|
||||||
|
coreValueDetailsByChipId: {
|
||||||
|
"1": { meaning: "We look after each other.", signals: "" },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -70,6 +141,83 @@ describe("finalReviewChipHasWarning", () => {
|
|||||||
),
|
),
|
||||||
).toBe(false);
|
).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("clears the warning when a custom card's fields have text", () => {
|
||||||
|
const customId = "00000000-0000-4000-8000-000000000190";
|
||||||
|
expect(
|
||||||
|
finalReviewChipHasWarning(
|
||||||
|
{
|
||||||
|
customMethodCardMetaById: {
|
||||||
|
[customId]: { label: "S13 comms card", supportText: "" },
|
||||||
|
},
|
||||||
|
customMethodCardFieldBlocksById: {
|
||||||
|
[customId]: [
|
||||||
|
{
|
||||||
|
kind: "text",
|
||||||
|
id: "b1",
|
||||||
|
blockTitle: "How we talk",
|
||||||
|
placeholderText: "Post in the hall.",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"communication",
|
||||||
|
customId,
|
||||||
|
),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("finalReviewChipBlocksContinue", () => {
|
||||||
|
it("does not block a value that has meaning but no signals", () => {
|
||||||
|
expect(
|
||||||
|
finalReviewChipBlocksContinue(
|
||||||
|
{
|
||||||
|
coreValueDetailsByChipId: {
|
||||||
|
"1": { meaning: "Care", signals: "" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"coreValues",
|
||||||
|
"1",
|
||||||
|
),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("blocks a custom card until its fields have text", () => {
|
||||||
|
const customId = "00000000-0000-4000-8000-000000000191";
|
||||||
|
expect(
|
||||||
|
finalReviewChipBlocksContinue(
|
||||||
|
{
|
||||||
|
customMethodCardMetaById: {
|
||||||
|
[customId]: { label: "S13 comms card", supportText: "" },
|
||||||
|
},
|
||||||
|
customMethodCardFieldBlocksById: {
|
||||||
|
[customId]: [
|
||||||
|
{
|
||||||
|
kind: "text",
|
||||||
|
id: "b1",
|
||||||
|
blockTitle: "How we talk",
|
||||||
|
placeholderText: "",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"communication",
|
||||||
|
customId,
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("finalReviewMissingWordsLabels", () => {
|
||||||
|
it("names the cards that still need words", () => {
|
||||||
|
expect(finalReviewMissingWordsLabels(completeCards)).toEqual([
|
||||||
|
"Signal",
|
||||||
|
"Open admission",
|
||||||
|
"Lazy consensus",
|
||||||
|
"Conflict ladder",
|
||||||
|
]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("communityInitialsFromTitle", () => {
|
describe("communityInitialsFromTitle", () => {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
getNextStep,
|
getNextStep,
|
||||||
getPreviousStep,
|
getPreviousStep,
|
||||||
isValidStep,
|
isValidStep,
|
||||||
|
resumeCreateFlowStep,
|
||||||
getStepIndex,
|
getStepIndex,
|
||||||
parseReviewReturnSearchParam,
|
parseReviewReturnSearchParam,
|
||||||
parseCreateFlowScreenFromPathname,
|
parseCreateFlowScreenFromPathname,
|
||||||
@@ -46,6 +47,14 @@ describe("flowSteps", () => {
|
|||||||
expect(getPreviousStep(null)).toBeNull();
|
expect(getPreviousStep(null)).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("resumeCreateFlowStep opens the screen the draft was left on", () => {
|
||||||
|
expect(resumeCreateFlowStep({ currentStep: "core-values" })).toBe(
|
||||||
|
"core-values",
|
||||||
|
);
|
||||||
|
expect(resumeCreateFlowStep({})).toBe("informational");
|
||||||
|
expect(resumeCreateFlowStep(null)).toBe("informational");
|
||||||
|
});
|
||||||
|
|
||||||
it("isValidStep allows branch-only edit-rule URL segment", () => {
|
it("isValidStep allows branch-only edit-rule URL segment", () => {
|
||||||
expect(isValidStep("edit-rule")).toBe(true);
|
expect(isValidStep("edit-rule")).toBe(true);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ vi.mock("../../lib/logger", () => ({
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
claimGuestRulesForUser,
|
claimGuestRulesForUser,
|
||||||
|
clearGuestRuleClaimCookie,
|
||||||
issueGuestRuleClaimCookie,
|
issueGuestRuleClaimCookie,
|
||||||
} from "../../lib/server/guestRuleClaim";
|
} from "../../lib/server/guestRuleClaim";
|
||||||
|
|
||||||
@@ -76,6 +77,21 @@ describe("issueGuestRuleClaimCookie", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("clearGuestRuleClaimCookie", () => {
|
||||||
|
it("expires the claim cookie", async () => {
|
||||||
|
await clearGuestRuleClaimCookie();
|
||||||
|
expect(cookieSetMock).toHaveBeenCalledWith(
|
||||||
|
"cr_rule_claim",
|
||||||
|
"",
|
||||||
|
expect.objectContaining({
|
||||||
|
httpOnly: true,
|
||||||
|
path: "/",
|
||||||
|
maxAge: 0,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("claimGuestRulesForUser", () => {
|
describe("claimGuestRulesForUser", () => {
|
||||||
it("returns 0 when the cookie is empty", async () => {
|
it("returns 0 when the cookie is empty", async () => {
|
||||||
cookieGetMock.mockReturnValue(undefined);
|
cookieGetMock.mockReturnValue(undefined);
|
||||||
|
|||||||
@@ -2,7 +2,11 @@ import { renderHook, act } from "@testing-library/react";
|
|||||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||||
import type { CreateFlowState } from "../../../app/(app)/create/types";
|
import type { CreateFlowState } from "../../../app/(app)/create/types";
|
||||||
import { useCreateFlowFinalize } from "../../../app/(app)/create/hooks/useCreateFlowFinalize";
|
import { useCreateFlowFinalize } from "../../../app/(app)/create/hooks/useCreateFlowFinalize";
|
||||||
import { publishRule, updatePublishedRule } from "../../../lib/create/api";
|
import {
|
||||||
|
deleteServerDraft,
|
||||||
|
publishRule,
|
||||||
|
updatePublishedRule,
|
||||||
|
} from "../../../lib/create/api";
|
||||||
import { buildPublishPayload } from "../../../lib/create/buildPublishPayload";
|
import { buildPublishPayload } from "../../../lib/create/buildPublishPayload";
|
||||||
import { stateWithPendingCommunityAvatar } from "../../../lib/create/flushPendingCommunityAvatar";
|
import { stateWithPendingCommunityAvatar } from "../../../lib/create/flushPendingCommunityAvatar";
|
||||||
import messages from "../../../messages/en/index";
|
import messages from "../../../messages/en/index";
|
||||||
@@ -25,6 +29,7 @@ vi.mock("../../../lib/create/buildPublishPayload", () => ({
|
|||||||
vi.mock("../../../lib/create/api", () => ({
|
vi.mock("../../../lib/create/api", () => ({
|
||||||
publishRule: vi.fn(),
|
publishRule: vi.fn(),
|
||||||
updatePublishedRule: vi.fn(),
|
updatePublishedRule: vi.fn(),
|
||||||
|
deleteServerDraft: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
vi.mock("../../../lib/create/flushPendingCommunityAvatar", () => ({
|
vi.mock("../../../lib/create/flushPendingCommunityAvatar", () => ({
|
||||||
@@ -50,6 +55,8 @@ describe("useCreateFlowFinalize", () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.mocked(publishRule).mockReset();
|
vi.mocked(publishRule).mockReset();
|
||||||
vi.mocked(updatePublishedRule).mockReset();
|
vi.mocked(updatePublishedRule).mockReset();
|
||||||
|
vi.mocked(deleteServerDraft).mockReset();
|
||||||
|
vi.mocked(deleteServerDraft).mockResolvedValue(true);
|
||||||
vi.mocked(writeLastPublishedRule).mockReset();
|
vi.mocked(writeLastPublishedRule).mockReset();
|
||||||
vi.mocked(stateWithPendingCommunityAvatar).mockReset();
|
vi.mocked(stateWithPendingCommunityAvatar).mockReset();
|
||||||
vi.mocked(stateWithPendingCommunityAvatar).mockImplementation(
|
vi.mocked(stateWithPendingCommunityAvatar).mockImplementation(
|
||||||
@@ -101,6 +108,35 @@ describe("useCreateFlowFinalize", () => {
|
|||||||
expect(
|
expect(
|
||||||
sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY),
|
sessionStorage.getItem(CREATE_FLOW_PENDING_KEEP_RULE_LOGIN_KEY),
|
||||||
).toBeNull();
|
).toBeNull();
|
||||||
|
expect(deleteServerDraft).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("retries clearing the server draft when the first delete fails", async () => {
|
||||||
|
vi.mocked(publishRule).mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
id: "new-rule-id",
|
||||||
|
title: "Published title",
|
||||||
|
});
|
||||||
|
vi.mocked(deleteServerDraft)
|
||||||
|
.mockResolvedValueOnce(false)
|
||||||
|
.mockResolvedValueOnce(true);
|
||||||
|
|
||||||
|
const { result } = renderHook(() =>
|
||||||
|
useCreateFlowFinalize({
|
||||||
|
state: emptyState,
|
||||||
|
router,
|
||||||
|
openLogin,
|
||||||
|
updateState,
|
||||||
|
loginReturnPath: "/create/final-review",
|
||||||
|
sessionUser: signedIn,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.finalize();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(deleteServerDraft).toHaveBeenCalledTimes(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not publish while the session is unresolved", async () => {
|
it("does not publish while the session is unresolved", async () => {
|
||||||
@@ -408,6 +444,7 @@ describe("useCreateFlowFinalize", () => {
|
|||||||
summary: "Published summary",
|
summary: "Published summary",
|
||||||
document: {},
|
document: {},
|
||||||
});
|
});
|
||||||
|
expect(deleteServerDraft).toHaveBeenCalledTimes(1);
|
||||||
expect(updateState).toHaveBeenCalledWith({
|
expect(updateState).toHaveBeenCalledWith({
|
||||||
editingPublishedRuleId: undefined,
|
editingPublishedRuleId: undefined,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -35,10 +35,15 @@ describe("useTemplateReviewActions", () => {
|
|||||||
const router = { push: vi.fn() };
|
const router = { push: vi.fn() };
|
||||||
const updateState = vi.fn();
|
const updateState = vi.fn();
|
||||||
const markCreateFlowInteraction = vi.fn();
|
const markCreateFlowInteraction = vi.fn();
|
||||||
|
const requestConfirm = vi.fn();
|
||||||
let applied: CreateFlowState | undefined;
|
let applied: CreateFlowState | undefined;
|
||||||
const replaceState = vi.fn(
|
const replaceState = vi.fn(
|
||||||
(updater: (_prev: CreateFlowState) => CreateFlowState) => {
|
(updater: (_prev: CreateFlowState) => CreateFlowState) => {
|
||||||
applied = updater({});
|
applied = updater({
|
||||||
|
title: "Juniper Street Tenants",
|
||||||
|
communityAvatarUrl: "/old.png",
|
||||||
|
setupTraits: { employer: true },
|
||||||
|
});
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -48,8 +53,12 @@ describe("useTemplateReviewActions", () => {
|
|||||||
router.push.mockReset();
|
router.push.mockReset();
|
||||||
updateState.mockReset();
|
updateState.mockReset();
|
||||||
markCreateFlowInteraction.mockReset();
|
markCreateFlowInteraction.mockReset();
|
||||||
|
requestConfirm.mockReset();
|
||||||
|
requestConfirm.mockResolvedValue(true);
|
||||||
replaceState.mockClear();
|
replaceState.mockClear();
|
||||||
applied = undefined;
|
applied = undefined;
|
||||||
|
window.sessionStorage.clear();
|
||||||
|
window.localStorage.clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
function renderActions(
|
function renderActions(
|
||||||
@@ -64,6 +73,7 @@ describe("useTemplateReviewActions", () => {
|
|||||||
replaceState,
|
replaceState,
|
||||||
router,
|
router,
|
||||||
fromCreateWizard,
|
fromCreateWizard,
|
||||||
|
requestConfirm,
|
||||||
markCreateFlowInteraction,
|
markCreateFlowInteraction,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -86,9 +96,10 @@ describe("useTemplateReviewActions", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("Customize Continue prefills cards, drops setup answers, and walks the decks", async () => {
|
it("Customize Continue prefills cards, drops leftover identity, and walks the decks", async () => {
|
||||||
const { result } = renderActions({
|
const { result } = renderActions({
|
||||||
setupTraits: { employer: true },
|
setupTraits: { employer: true },
|
||||||
|
communityAvatarUrl: "/old.png",
|
||||||
});
|
});
|
||||||
|
|
||||||
await act(async () => {
|
await act(async () => {
|
||||||
@@ -103,32 +114,19 @@ describe("useTemplateReviewActions", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
expect(router.push).toHaveBeenCalledWith("/create/core-values");
|
expect(router.push).toHaveBeenCalledWith("/create/core-values");
|
||||||
expect(updateState).toHaveBeenCalledWith(
|
expect(applied?.title).toBe("Neighborhood");
|
||||||
expect.objectContaining({
|
expect(applied?.communityContext).toBe("We meet weekly");
|
||||||
title: "Neighborhood",
|
expect(applied?.communityLocation).toBe("Oakland");
|
||||||
communityContext: "We meet weekly",
|
expect(applied?.communityAvatarUrl).toBeUndefined();
|
||||||
communityLocation: "Oakland",
|
expect(applied?.setupTraits).toBeUndefined();
|
||||||
setupTraits: undefined,
|
expect(applied?.pendingTemplateAction).toEqual({
|
||||||
pendingTemplateAction: {
|
slug: "mutual-aid-mondays",
|
||||||
slug: "mutual-aid-mondays",
|
mode: "customize",
|
||||||
mode: "customize",
|
});
|
||||||
},
|
expect(applied?.templateReviewBackSlug).toBe("mutual-aid-mondays");
|
||||||
templateReviewBackSlug: "mutual-aid-mondays",
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("direct Use without changes goes to final review and clears leftover identity", async () => {
|
it("direct Use without changes goes to final review and clears leftover identity", async () => {
|
||||||
replaceState.mockImplementation(
|
|
||||||
(updater: (_prev: CreateFlowState) => CreateFlowState) => {
|
|
||||||
applied = updater({
|
|
||||||
title: "Neighborhood",
|
|
||||||
communityContext: "Stale description",
|
|
||||||
currentStep: "confirm-stakeholders",
|
|
||||||
setupTraits: { employer: true, network: false },
|
|
||||||
});
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const { result } = renderActions({ title: "Neighborhood" });
|
const { result } = renderActions({ title: "Neighborhood" });
|
||||||
|
|
||||||
await act(async () => {
|
await act(async () => {
|
||||||
@@ -138,8 +136,9 @@ describe("useTemplateReviewActions", () => {
|
|||||||
expect(router.push).toHaveBeenCalledWith("/create/final-review");
|
expect(router.push).toHaveBeenCalledWith("/create/final-review");
|
||||||
expect(applied?.title).toBeUndefined();
|
expect(applied?.title).toBeUndefined();
|
||||||
expect(applied?.communityContext).toBeUndefined();
|
expect(applied?.communityContext).toBeUndefined();
|
||||||
expect(applied?.currentStep).toBeUndefined();
|
expect(applied?.communityAvatarUrl).toBeUndefined();
|
||||||
expect(applied?.setupTraits).toBeUndefined();
|
expect(applied?.setupTraits).toBeUndefined();
|
||||||
|
expect(applied?.currentStep).toBeUndefined();
|
||||||
expect(applied?.pendingTemplateAction).toEqual({
|
expect(applied?.pendingTemplateAction).toEqual({
|
||||||
slug: "mutual-aid-mondays",
|
slug: "mutual-aid-mondays",
|
||||||
mode: "useWithoutChanges",
|
mode: "useWithoutChanges",
|
||||||
@@ -147,18 +146,12 @@ describe("useTemplateReviewActions", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("in-flow Use without changes keeps the community name and pins the template path", async () => {
|
it("in-flow Use without changes keeps the community name and pins the template path", async () => {
|
||||||
replaceState.mockImplementation(
|
|
||||||
(updater: (_prev: CreateFlowState) => CreateFlowState) => {
|
|
||||||
applied = updater({
|
|
||||||
title: "Neighborhood",
|
|
||||||
communityContext: "We meet weekly",
|
|
||||||
templateReviewEntryFromCreateFlow: true,
|
|
||||||
setupTraits: { employer: true },
|
|
||||||
});
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const { result } = renderActions(
|
const { result } = renderActions(
|
||||||
{ title: "Neighborhood", templateReviewEntryFromCreateFlow: true },
|
{
|
||||||
|
title: "Neighborhood",
|
||||||
|
communityContext: "We meet weekly",
|
||||||
|
templateReviewEntryFromCreateFlow: true,
|
||||||
|
},
|
||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -176,4 +169,21 @@ describe("useTemplateReviewActions", () => {
|
|||||||
});
|
});
|
||||||
expect(applied?.templateReviewBackSlug).toBe("mutual-aid-mondays");
|
expect(applied?.templateReviewBackSlug).toBe("mutual-aid-mondays");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("asks before replacing a draft in progress", async () => {
|
||||||
|
requestConfirm.mockResolvedValueOnce(false);
|
||||||
|
const { result } = renderActions({ title: "Juniper Street Tenants" });
|
||||||
|
|
||||||
|
await act(async () => {
|
||||||
|
await result.current.handleUseWithoutChanges();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(requestConfirm).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
title: "Replace the draft in progress?",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(router.push).not.toHaveBeenCalled();
|
||||||
|
expect(replaceState).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
import { finishedAtIso } from "../../lib/create/lastPublishedRule";
|
import {
|
||||||
|
CREATE_FLOW_LAST_PUBLISHED_KEY,
|
||||||
|
clearLastPublishedRule,
|
||||||
|
finishedAtIso,
|
||||||
|
writeLastPublishedRule,
|
||||||
|
} from "../../lib/create/lastPublishedRule";
|
||||||
|
|
||||||
describe("finishedAtIso", () => {
|
describe("finishedAtIso", () => {
|
||||||
it("normalizes strings and dates", () => {
|
it("normalizes strings and dates", () => {
|
||||||
@@ -17,3 +22,25 @@ describe("finishedAtIso", () => {
|
|||||||
expect(finishedAtIso(null)).toBeUndefined();
|
expect(finishedAtIso(null)).toBeUndefined();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("clearLastPublishedRule", () => {
|
||||||
|
afterEach(() => {
|
||||||
|
sessionStorage.removeItem(CREATE_FLOW_LAST_PUBLISHED_KEY);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes the stored finished Rule", () => {
|
||||||
|
writeLastPublishedRule({
|
||||||
|
id: "rule-1",
|
||||||
|
title: "Garden coop",
|
||||||
|
document: { sections: [] },
|
||||||
|
});
|
||||||
|
expect(sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).not.toBeNull();
|
||||||
|
clearLastPublishedRule();
|
||||||
|
expect(sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does nothing when the key is already missing", () => {
|
||||||
|
expect(() => clearLastPublishedRule()).not.toThrow();
|
||||||
|
expect(sessionStorage.getItem(CREATE_FLOW_LAST_PUBLISHED_KEY)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
import {
|
import {
|
||||||
FRESH_ENTRY_PENDING_KEY,
|
FRESH_ENTRY_PENDING_KEY,
|
||||||
|
TEMPLATE_APPLY_LATCH_KEY,
|
||||||
|
clearTemplateApplyLatch,
|
||||||
hasFreshEntryPending,
|
hasFreshEntryPending,
|
||||||
|
hasTemplateApplyLatch,
|
||||||
|
latchTemplateApply,
|
||||||
prepareFreshCreateFlowEntry,
|
prepareFreshCreateFlowEntry,
|
||||||
prepareFreshCreateFlowEntrySync,
|
prepareFreshCreateFlowEntrySync,
|
||||||
} from "../../app/(app)/create/utils/prepareFreshCreateFlowEntry";
|
} from "../../app/(app)/create/utils/prepareFreshCreateFlowEntry";
|
||||||
@@ -66,6 +70,25 @@ describe("prepareFreshCreateFlowEntrySync", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("template apply latch", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
window.sessionStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
window.sessionStorage.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sets, reads, and clears the session flag", () => {
|
||||||
|
expect(hasTemplateApplyLatch()).toBe(false);
|
||||||
|
latchTemplateApply();
|
||||||
|
expect(window.sessionStorage.getItem(TEMPLATE_APPLY_LATCH_KEY)).toBe("1");
|
||||||
|
expect(hasTemplateApplyLatch()).toBe(true);
|
||||||
|
clearTemplateApplyLatch();
|
||||||
|
expect(hasTemplateApplyLatch()).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("prepareFreshCreateFlowEntry", () => {
|
describe("prepareFreshCreateFlowEntry", () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
deleteServerDraft.mockReset();
|
deleteServerDraft.mockReset();
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ describe("parsePublishedDocumentForCommunityRuleDisplay", () => {
|
|||||||
expect(out[0].entries[0].body).toBe("x\n\ny");
|
expect(out[0].entries[0].body).toBe("x\n\ny");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("enriches empty core value copy from presets (label match)", () => {
|
it("keeps empty core value copy blank instead of filling library text", () => {
|
||||||
const doc = {
|
const doc = {
|
||||||
sections: [],
|
sections: [],
|
||||||
coreValues: [
|
coreValues: [
|
||||||
@@ -89,7 +89,8 @@ describe("parsePublishedDocumentForCommunityRuleDisplay", () => {
|
|||||||
],
|
],
|
||||||
};
|
};
|
||||||
const out = parsePublishedDocumentForCommunityRuleDisplay(doc);
|
const out = parsePublishedDocumentForCommunityRuleDisplay(doc);
|
||||||
expect(out[0].entries[0].body).toMatch(/well-being is bound up/);
|
expect(out[0].entries[0].title).toBe("Interdependence");
|
||||||
|
expect(out[0].entries[0].body).toBe("");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("replaces template placeholder bodies with preset copy, Values first", () => {
|
it("replaces template placeholder bodies with preset copy, Values first", () => {
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const findUniqueMock = vi.fn();
|
||||||
|
const deleteManyMock = vi.fn();
|
||||||
|
const deleteUploadsForDraftMock = vi.fn();
|
||||||
|
|
||||||
|
vi.mock("../../lib/server/db", () => ({
|
||||||
|
prisma: {
|
||||||
|
ruleDraft: {
|
||||||
|
findUnique: (...args: unknown[]) => findUniqueMock(...args),
|
||||||
|
deleteMany: (...args: unknown[]) => deleteManyMock(...args),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../../lib/server/uploads/deleteUploadedFiles", () => ({
|
||||||
|
deleteUploadsForDraft: (...args: unknown[]) =>
|
||||||
|
deleteUploadsForDraftMock(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { deleteRuleDraftForUser } from "../../lib/server/ruleDrafts";
|
||||||
|
|
||||||
|
describe("deleteRuleDraftForUser", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
findUniqueMock.mockReset();
|
||||||
|
deleteManyMock.mockReset();
|
||||||
|
deleteUploadsForDraftMock.mockReset();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes the draft and files still tied to it", async () => {
|
||||||
|
findUniqueMock.mockResolvedValueOnce({ id: "draft-1" });
|
||||||
|
deleteUploadsForDraftMock.mockResolvedValueOnce(undefined);
|
||||||
|
deleteManyMock.mockResolvedValueOnce({ count: 1 });
|
||||||
|
|
||||||
|
await deleteRuleDraftForUser("user-1");
|
||||||
|
|
||||||
|
expect(findUniqueMock).toHaveBeenCalledWith({
|
||||||
|
where: { userId: "user-1" },
|
||||||
|
select: { id: true },
|
||||||
|
});
|
||||||
|
expect(deleteUploadsForDraftMock).toHaveBeenCalledWith("draft-1");
|
||||||
|
expect(deleteManyMock).toHaveBeenCalledWith({
|
||||||
|
where: { userId: "user-1" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("still deletes when there is no draft row", async () => {
|
||||||
|
findUniqueMock.mockResolvedValueOnce(null);
|
||||||
|
deleteManyMock.mockResolvedValueOnce({ count: 0 });
|
||||||
|
|
||||||
|
await deleteRuleDraftForUser("user-1");
|
||||||
|
|
||||||
|
expect(deleteUploadsForDraftMock).not.toHaveBeenCalled();
|
||||||
|
expect(deleteManyMock).toHaveBeenCalledWith({
|
||||||
|
where: { userId: "user-1" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -61,6 +61,37 @@ describe("inviteRuleCountsLabel", () => {
|
|||||||
}),
|
}),
|
||||||
).toBe("3 VALUES AND 2 CARDS");
|
).toBe("3 VALUES AND 2 CARDS");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("counts titled cards that still have no words", () => {
|
||||||
|
expect(
|
||||||
|
inviteRuleCountsLabel({
|
||||||
|
methodSelections: {
|
||||||
|
communication: [
|
||||||
|
{
|
||||||
|
id: "signal",
|
||||||
|
label: "Signal",
|
||||||
|
sections: {
|
||||||
|
corePrinciple: "",
|
||||||
|
logisticsAdmin: "",
|
||||||
|
codeOfConduct: "",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
membership: [
|
||||||
|
{
|
||||||
|
id: "open-admission",
|
||||||
|
label: "Open admission",
|
||||||
|
sections: {
|
||||||
|
eligibility: "",
|
||||||
|
joiningProcess: "",
|
||||||
|
expectations: "",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
).toBe("0 VALUES AND 2 CARDS");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("inviteRuleCountsSpoken", () => {
|
describe("inviteRuleCountsSpoken", () => {
|
||||||
|
|||||||
@@ -45,6 +45,16 @@ describe("withoutUnpublishedDecisionConsensus", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("communityRuleEntryFromMethodChip", () => {
|
describe("communityRuleEntryFromMethodChip", () => {
|
||||||
|
it("keeps a titled card when there are no words yet", () => {
|
||||||
|
expect(
|
||||||
|
communityRuleEntryFromMethodChip(
|
||||||
|
"Signal",
|
||||||
|
{ corePrinciple: "" },
|
||||||
|
{ corePrinciple: "Core Principle" },
|
||||||
|
),
|
||||||
|
).toEqual({ title: "Signal", body: "" });
|
||||||
|
});
|
||||||
|
|
||||||
it("publishes supportText as body when there are no labeled blocks", () => {
|
it("publishes supportText as body when there are no labeled blocks", () => {
|
||||||
expect(
|
expect(
|
||||||
communityRuleEntryFromMethodChip(
|
communityRuleEntryFromMethodChip(
|
||||||
|
|||||||
@@ -48,6 +48,12 @@ vi.mock("../../lib/server/uploads/linkUploads", () => ({
|
|||||||
linkUploadsToRule: vi.fn().mockResolvedValue(undefined),
|
linkUploadsToRule: vi.fn().mockResolvedValue(undefined),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
const deleteRuleDraftForUserMock = vi.fn();
|
||||||
|
vi.mock("../../lib/server/ruleDrafts", () => ({
|
||||||
|
deleteRuleDraftForUser: (...args: unknown[]) =>
|
||||||
|
deleteRuleDraftForUserMock(...args),
|
||||||
|
}));
|
||||||
|
|
||||||
vi.mock("../../lib/server/db", () => ({
|
vi.mock("../../lib/server/db", () => ({
|
||||||
prisma: {
|
prisma: {
|
||||||
$transaction: (fn: (tx: unknown) => Promise<unknown>) =>
|
$transaction: (fn: (tx: unknown) => Promise<unknown>) =>
|
||||||
@@ -72,6 +78,8 @@ beforeEach(() => {
|
|||||||
sendInviteMock.mockReset();
|
sendInviteMock.mockReset();
|
||||||
rateLimitKeyMock.mockReset();
|
rateLimitKeyMock.mockReset();
|
||||||
issueGuestRuleClaimCookieMock.mockReset();
|
issueGuestRuleClaimCookieMock.mockReset();
|
||||||
|
deleteRuleDraftForUserMock.mockReset();
|
||||||
|
deleteRuleDraftForUserMock.mockResolvedValue(undefined);
|
||||||
rateLimitKeyMock.mockReturnValue({ ok: true as const });
|
rateLimitKeyMock.mockReturnValue({ ok: true as const });
|
||||||
getSessionUserMock.mockResolvedValue({
|
getSessionUserMock.mockResolvedValue({
|
||||||
id: "user-1",
|
id: "user-1",
|
||||||
@@ -112,6 +120,61 @@ describe("POST /api/rules", () => {
|
|||||||
).toBeUndefined();
|
).toBeUndefined();
|
||||||
expect(issueGuestRuleClaimCookieMock).not.toHaveBeenCalled();
|
expect(issueGuestRuleClaimCookieMock).not.toHaveBeenCalled();
|
||||||
expect(sendInviteMock).not.toHaveBeenCalled();
|
expect(sendInviteMock).not.toHaveBeenCalled();
|
||||||
|
expect(deleteRuleDraftForUserMock).toHaveBeenCalledWith("user-1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("retries draft deletion after publish and still returns the rule", async () => {
|
||||||
|
publishedRuleCreateMock.mockResolvedValueOnce({
|
||||||
|
id: "rule-solo",
|
||||||
|
title: "T",
|
||||||
|
summary: null,
|
||||||
|
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||||
|
});
|
||||||
|
deleteRuleDraftForUserMock
|
||||||
|
.mockRejectedValueOnce(new Error("draft delete failed"))
|
||||||
|
.mockResolvedValueOnce(undefined);
|
||||||
|
|
||||||
|
const res = await POST(
|
||||||
|
new NextRequest("https://x.test/api/rules", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
title: "T",
|
||||||
|
summary: null,
|
||||||
|
document: {},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
undefined,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(deleteRuleDraftForUserMock).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("publishes when draft deletion keeps failing", async () => {
|
||||||
|
publishedRuleCreateMock.mockResolvedValueOnce({
|
||||||
|
id: "rule-solo",
|
||||||
|
title: "T",
|
||||||
|
summary: null,
|
||||||
|
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||||
|
});
|
||||||
|
deleteRuleDraftForUserMock.mockRejectedValue(
|
||||||
|
new Error("draft delete failed"),
|
||||||
|
);
|
||||||
|
|
||||||
|
const res = await POST(
|
||||||
|
new NextRequest("https://x.test/api/rules", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
title: "T",
|
||||||
|
summary: null,
|
||||||
|
document: {},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
undefined,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(deleteRuleDraftForUserMock).toHaveBeenCalledTimes(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("stores place and group type from the published document", async () => {
|
it("stores place and group type from the published document", async () => {
|
||||||
@@ -196,6 +259,7 @@ describe("POST /api/rules", () => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
expect(publishedRuleCreateMock).not.toHaveBeenCalled();
|
expect(publishedRuleCreateMock).not.toHaveBeenCalled();
|
||||||
|
expect(deleteRuleDraftForUserMock).toHaveBeenCalledWith("user-1");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("rolls back publish when mail fails", async () => {
|
it("rolls back publish when mail fails", async () => {
|
||||||
@@ -238,6 +302,7 @@ describe("POST /api/rules", () => {
|
|||||||
expect(publishedRuleDeleteMock).toHaveBeenCalledWith({
|
expect(publishedRuleDeleteMock).toHaveBeenCalledWith({
|
||||||
where: { id: "rule-new" },
|
where: { id: "rule-new" },
|
||||||
});
|
});
|
||||||
|
expect(deleteRuleDraftForUserMock).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("keeps the rule when a later invite send fails after one succeeded", async () => {
|
it("keeps the rule when a later invite send fails after one succeeded", async () => {
|
||||||
@@ -248,12 +313,7 @@ describe("POST /api/rules", () => {
|
|||||||
createdAt: new Date("2026-01-02T00:00:00.000Z"),
|
createdAt: new Date("2026-01-02T00:00:00.000Z"),
|
||||||
};
|
};
|
||||||
transactionMock.mockImplementation(
|
transactionMock.mockImplementation(
|
||||||
async (
|
async (fn: (tx: { publishedRule: { create: typeof vi.fn }; ruleStakeholder: { create: typeof vi.fn } }) => Promise<unknown>) => {
|
||||||
fn: (tx: {
|
|
||||||
publishedRule: { create: typeof vi.fn };
|
|
||||||
ruleStakeholder: { create: typeof vi.fn };
|
|
||||||
}) => Promise<unknown>,
|
|
||||||
) => {
|
|
||||||
const tx = {
|
const tx = {
|
||||||
publishedRule: {
|
publishedRule: {
|
||||||
create: vi.fn().mockResolvedValue(created),
|
create: vi.fn().mockResolvedValue(created),
|
||||||
@@ -329,6 +389,7 @@ describe("POST /api/rules", () => {
|
|||||||
expect(sendInviteMock).not.toHaveBeenCalled();
|
expect(sendInviteMock).not.toHaveBeenCalled();
|
||||||
const body = (await res.json()) as { rule: { id: string } };
|
const body = (await res.json()) as { rule: { id: string } };
|
||||||
expect(body.rule.id).toBe("rule-guest");
|
expect(body.rule.id).toBe("rule-guest");
|
||||||
|
expect(deleteRuleDraftForUserMock).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("rate-limits anonymous publish by IP", async () => {
|
it("rate-limits anonymous publish by IP", async () => {
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
const clearPendingCommunityAvatarFile = vi.fn();
|
||||||
|
const forgetFlushedCommunityAvatarUrl = vi.fn();
|
||||||
|
|
||||||
|
vi.mock("../../lib/create/pendingCommunityAvatarUpload", () => ({
|
||||||
|
clearPendingCommunityAvatarFile: () => clearPendingCommunityAvatarFile(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("../../lib/create/flushPendingCommunityAvatar", () => ({
|
||||||
|
forgetFlushedCommunityAvatarUrl: () => forgetFlushedCommunityAvatarUrl(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import {
|
||||||
|
CREATE_FLOW_ANONYMOUS_KEY,
|
||||||
|
CREATE_FLOW_TRANSFER_PENDING_KEY,
|
||||||
|
} from "../../app/(app)/create/utils/anonymousDraftStorage";
|
||||||
|
import { CORE_VALUE_DETAILS_STORAGE_KEY } from "../../app/(app)/create/utils/coreValueDetailsLocalStorage";
|
||||||
|
import { seedContinuedDraftLocalStorage } from "../../app/(app)/create/utils/seedContinuedDraftLocalStorage";
|
||||||
|
import type { CreateFlowState } from "../../app/(app)/create/types";
|
||||||
|
|
||||||
|
describe("seedContinuedDraftLocalStorage", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
localStorage.clear();
|
||||||
|
clearPendingCommunityAvatarFile.mockReset();
|
||||||
|
forgetFlushedCommunityAvatarUrl.mockReset();
|
||||||
|
localStorage.setItem(
|
||||||
|
CREATE_FLOW_ANONYMOUS_KEY,
|
||||||
|
JSON.stringify({ title: "Stale" }),
|
||||||
|
);
|
||||||
|
localStorage.setItem(
|
||||||
|
CORE_VALUE_DETAILS_STORAGE_KEY,
|
||||||
|
JSON.stringify({ old: { meaning: "old", signals: "" } }),
|
||||||
|
);
|
||||||
|
localStorage.setItem(CREATE_FLOW_TRANSFER_PENDING_KEY, "1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("writes the server draft over the browser mirror", () => {
|
||||||
|
const state: CreateFlowState = {
|
||||||
|
title: "Garden",
|
||||||
|
currentStep: "core-values",
|
||||||
|
coreValueDetailsByChipId: {
|
||||||
|
solidarity: { meaning: "We show up.", signals: "" },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
seedContinuedDraftLocalStorage(state);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
JSON.parse(localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY) ?? "{}"),
|
||||||
|
).toEqual(state);
|
||||||
|
expect(
|
||||||
|
JSON.parse(localStorage.getItem(CORE_VALUE_DETAILS_STORAGE_KEY) ?? "{}"),
|
||||||
|
).toEqual(state.coreValueDetailsByChipId);
|
||||||
|
expect(localStorage.getItem(CREATE_FLOW_TRANSFER_PENDING_KEY)).toBeNull();
|
||||||
|
expect(clearPendingCommunityAvatarFile).toHaveBeenCalledTimes(1);
|
||||||
|
expect(forgetFlushedCommunityAvatarUrl).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clears core-value details when the continued draft has none", () => {
|
||||||
|
seedContinuedDraftLocalStorage({ title: "Garden" });
|
||||||
|
|
||||||
|
expect(localStorage.getItem(CORE_VALUE_DETAILS_STORAGE_KEY)).toBeNull();
|
||||||
|
expect(
|
||||||
|
JSON.parse(localStorage.getItem(CREATE_FLOW_ANONYMOUS_KEY) ?? "{}"),
|
||||||
|
).toEqual({
|
||||||
|
title: "Garden",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,10 +1,15 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { buildAppliedTemplateCreateFlowState } from "../../lib/create/applyTemplatePrefill";
|
||||||
|
import { buildFinalReviewCategoriesFromState } from "../../lib/create/buildFinalReviewCategories";
|
||||||
import {
|
import {
|
||||||
templateBodyToCategories,
|
templateBodyToCategories,
|
||||||
templateBodyToReviewData,
|
templateBodyToReviewData,
|
||||||
templateCategoryToGroupKey,
|
templateCategoryToGroupKey,
|
||||||
|
templateReviewDataForSlug,
|
||||||
templateSummaryFromBody,
|
templateSummaryFromBody,
|
||||||
} from "../../lib/create/templateReviewMapping";
|
} from "../../lib/create/templateReviewMapping";
|
||||||
|
import templateChipsFile from "../../data/templates/templateChips.json";
|
||||||
|
import templateReviewMessages from "../../messages/en/create/templateReview.json";
|
||||||
|
|
||||||
describe("templateReviewMapping", () => {
|
describe("templateReviewMapping", () => {
|
||||||
it("maps body sections to Rule categories", () => {
|
it("maps body sections to Rule categories", () => {
|
||||||
@@ -117,3 +122,113 @@ describe("templateReviewMapping", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const FINAL_REVIEW_NAMES = {
|
||||||
|
values: "Values",
|
||||||
|
communication: "Communication",
|
||||||
|
membership: "Membership",
|
||||||
|
decisions: "Decision-making",
|
||||||
|
conflict: "Conflict management",
|
||||||
|
};
|
||||||
|
|
||||||
|
const STALE_CONSENSUS_BODY = {
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
categoryName: "Values",
|
||||||
|
entries: [{ title: "Community Care", body: "" }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
categoryName: "Communication",
|
||||||
|
entries: [
|
||||||
|
{ title: "In-Person Meetings", body: "" },
|
||||||
|
{ title: "Loomio", body: "" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
categoryName: "Membership",
|
||||||
|
entries: [{ title: "Peer Sponsorship", body: "" }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
categoryName: "Decision-making",
|
||||||
|
entries: [
|
||||||
|
{ title: "Consensus or Vote-Based Approval", body: "" },
|
||||||
|
{ title: "Consensus Decision-Making", body: "" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
categoryName: "Conflict management",
|
||||||
|
entries: [{ title: "Facilitated Negotiation", body: "" }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("templateReviewDataForSlug", () => {
|
||||||
|
it("lists remade catalog names for consensus, not API body titles", () => {
|
||||||
|
const { categories } = templateReviewDataForSlug(
|
||||||
|
"consensus",
|
||||||
|
STALE_CONSENSUS_BODY,
|
||||||
|
);
|
||||||
|
const labels = categories.flatMap((row) =>
|
||||||
|
row.chipOptions.map((chip) => chip.label),
|
||||||
|
);
|
||||||
|
expect(labels).toContain("How we run meetings");
|
||||||
|
expect(labels).toContain("In-person meetings");
|
||||||
|
expect(labels).toContain("Conflict ladder");
|
||||||
|
expect(labels).toContain("Community care");
|
||||||
|
expect(labels).toContain("Decision speeds");
|
||||||
|
expect(labels).not.toContain("In-Person Meetings");
|
||||||
|
expect(labels).not.toContain("Community Care");
|
||||||
|
expect(labels).not.toContain("Peer Sponsorship");
|
||||||
|
expect(labels).not.toContain("Facilitated Negotiation");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("matches Use without changes final-review labels", () => {
|
||||||
|
const slugs = Object.keys(
|
||||||
|
(templateChipsFile as { templates: Record<string, unknown> }).templates,
|
||||||
|
);
|
||||||
|
for (const slug of slugs) {
|
||||||
|
const detail = templateReviewDataForSlug(slug, STALE_CONSENSUS_BODY);
|
||||||
|
const seeded = buildAppliedTemplateCreateFlowState({
|
||||||
|
slug,
|
||||||
|
body: STALE_CONSENSUS_BODY,
|
||||||
|
mode: "useWithoutChanges",
|
||||||
|
});
|
||||||
|
const review = buildFinalReviewCategoriesFromState(
|
||||||
|
seeded,
|
||||||
|
FINAL_REVIEW_NAMES,
|
||||||
|
);
|
||||||
|
const detailByName = new Map(
|
||||||
|
detail.categories.map((row) => [
|
||||||
|
row.name,
|
||||||
|
row.chipOptions.map((chip) => chip.label),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
for (const row of review) {
|
||||||
|
if (row.chips.length === 0) continue;
|
||||||
|
expect(detailByName.get(row.name), slug).toEqual(row.chips);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to body titles when the slug is not in the catalog", () => {
|
||||||
|
const cats = templateReviewDataForSlug("unknown-template", {
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
categoryName: "Values",
|
||||||
|
entries: [{ title: "Solidarity", body: "Long body" }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}).categories;
|
||||||
|
expect(cats[0].chipOptions.map((chip) => chip.label)).toEqual([
|
||||||
|
"Solidarity",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("template review intro", () => {
|
||||||
|
it("reads one size fits all", () => {
|
||||||
|
expect(templateReviewMessages.intro.description).toContain(
|
||||||
|
"one size fits all",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -26,6 +26,10 @@ vi.mock("../../lib/server/uploads/deleteUploadedFiles", () => ({
|
|||||||
deleteUploadsForUser: vi.fn().mockResolvedValue(undefined),
|
deleteUploadsForUser: vi.fn().mockResolvedValue(undefined),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
vi.mock("../../lib/server/guestRuleClaim", () => ({
|
||||||
|
clearGuestRuleClaimCookie: vi.fn().mockResolvedValue(undefined),
|
||||||
|
}));
|
||||||
|
|
||||||
import { DELETE } from "../../app/api/user/me/route";
|
import { DELETE } from "../../app/api/user/me/route";
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
|
|||||||
Reference in new issue
Block a user