Keep a continued draft on screen, ask before Edit drops rewritten copy, and retry clearing the draft after publish.
This commit is contained in:
1 parent
54a4871ad1
commit
7c08766092
11 files changed
+361
-41
No files matched your search
@@ -18,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: {
|
||||||
@@ -154,7 +163,7 @@ export function useCreateFlowFinalize({
|
|||||||
document: ruleDocument,
|
document: ruleDocument,
|
||||||
});
|
});
|
||||||
updateState({ editingPublishedRuleId: undefined });
|
updateState({ editingPublishedRuleId: undefined });
|
||||||
void deleteServerDraft();
|
void deleteServerDraftAfterPublish();
|
||||||
router.push(createFlowStepPath("completed"));
|
router.push(createFlowStepPath("completed"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -209,7 +218,7 @@ export function useCreateFlowFinalize({
|
|||||||
writePendingKeepRuleLogin();
|
writePendingKeepRuleLogin();
|
||||||
onGuestPublished?.({ skippedInvites: skippedGuestInvites });
|
onGuestPublished?.({ skippedInvites: skippedGuestInvites });
|
||||||
} else {
|
} else {
|
||||||
void deleteServerDraft();
|
void deleteServerDraftAfterPublish();
|
||||||
}
|
}
|
||||||
router.push(
|
router.push(
|
||||||
createFlowStepPath("completed", {
|
createFlowStepPath("completed", {
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -37,9 +37,9 @@ import {
|
|||||||
} from "../create/utils/flowSteps";
|
} from "../create/utils/flowSteps";
|
||||||
import { clearAnonymousCreateFlowStorage } from "../create/utils/anonymousDraftStorage";
|
import { clearAnonymousCreateFlowStorage } from "../create/utils/anonymousDraftStorage";
|
||||||
import { clearBrowserRuleData } from "../create/utils/clearBrowserRuleData";
|
import { clearBrowserRuleData } from "../create/utils/clearBrowserRuleData";
|
||||||
import { clearCoreValueDetailsLocalStorage } from "../create/utils/coreValueDetailsLocalStorage";
|
|
||||||
import { createRuleEntryPath } from "../create/utils/createRuleEntry";
|
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,
|
||||||
@@ -294,9 +294,8 @@ export default function ProfilePageClient() {
|
|||||||
const handleContinueDraft = useCallback(() => {
|
const handleContinueDraft = useCallback(() => {
|
||||||
if (draft == null || !draft.hasDraft) return;
|
if (draft == null || !draft.hasDraft) return;
|
||||||
const step = resumeCreateFlowStep(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(() => {
|
||||||
|
|||||||
+27
-14
@@ -40,6 +40,31 @@ 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() ??
|
||||||
@@ -171,13 +196,7 @@ export const POST = apiRoute(
|
|||||||
document,
|
document,
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
});
|
});
|
||||||
try {
|
await deleteDraftAfterPublish(user.id, requestId);
|
||||||
await deleteRuleDraftForUser(user.id);
|
|
||||||
} catch (err) {
|
|
||||||
logRouteError("rules.publish", requestId, err, {
|
|
||||||
phase: "deleteRuleDraftForUser",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
rule: {
|
rule: {
|
||||||
@@ -269,13 +288,7 @@ export const POST = apiRoute(
|
|||||||
document,
|
document,
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
});
|
});
|
||||||
try {
|
await deleteDraftAfterPublish(user.id, requestId);
|
||||||
await deleteRuleDraftForUser(user.id);
|
|
||||||
} catch (err) {
|
|
||||||
logRouteError("rules.publish", requestId, err, {
|
|
||||||
phase: "deleteRuleDraftForUser",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
rule: {
|
rule: {
|
||||||
|
|||||||
+2
-2
@@ -65,7 +65,7 @@ The step persists **`stakeholderEmails`** on `CreateFlowState` (validated on `PU
|
|||||||
**Established pattern:** **Create rule** in the header, on Home, and on Profile resumes the draft in the browser. It never wipes that draft or `DELETE`s `/api/drafts/me`. Starting over is the confirmed Delete on a Profile Draft card (or a later template-replace confirm). Both guests and signed-in people can **publish** (guests get an unlisted public `/rules/{id}` with no owner). Both see **Save & Exit** from `community-structure` onward (and `edit-rule`). On **`/create/completed`**, guests still get **Save & Exit** (keep-this-rule magic-link modal); signed-in users get **Exit**. Wizard guests open the save-progress magic-link modal; signed-in users may **PUT** `/api/drafts/me` when `NEXT_PUBLIC_ENABLE_BACKEND_SYNC=true`.
|
**Established pattern:** **Create rule** in the header, on Home, and on Profile resumes the draft in the browser. It never wipes that draft or `DELETE`s `/api/drafts/me`. Starting over is the confirmed Delete on a Profile Draft card (or a later template-replace confirm). Both guests and signed-in people can **publish** (guests get an unlisted public `/rules/{id}` with no owner). 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`.
|
||||||
|
|
||||||
- **Create rule entry:** call [`createRuleEntryPath`](../app/(app)/create/utils/createRuleEntry.ts) and `router.push` that path. Do **not** call `prepareFreshCreateFlowEntry`.
|
- **Create rule entry:** call [`createRuleEntryPath`](../app/(app)/create/utils/createRuleEntry.ts) and `router.push` that path. Do **not** call `prepareFreshCreateFlowEntry`.
|
||||||
- **Continue saved draft** (profile): do **not** call `prepareFreshCreateFlowEntry`. 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.
|
||||||
- **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.
|
- **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 **`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.
|
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.
|
||||||
@@ -101,7 +101,7 @@ From that page, **Customize** opens a dialog for name, optional logo, descriptio
|
|||||||
|
|
||||||
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.
|
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).
|
||||||
|
|
||||||
|
|||||||
+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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import type { CreateFlowState } from "../../app/(app)/create/types";
|
import type { CreateFlowState } from "../../app/(app)/create/types";
|
||||||
import { createFlowStateHasKeys } from "./draftHydrationUtils";
|
import { createFlowStateHasKeys } from "./draftHydrationUtils";
|
||||||
import { PUBLISHED_CUSTOM_RULE_SELECTION_KEYS } from "./customRuleFacets";
|
import {
|
||||||
|
CUSTOM_RULE_FACETS,
|
||||||
|
PUBLISHED_CUSTOM_RULE_SELECTION_KEYS,
|
||||||
|
} from "./customRuleFacets";
|
||||||
import type { StoredLastPublishedRule } from "./lastPublishedRule";
|
import type { StoredLastPublishedRule } from "./lastPublishedRule";
|
||||||
import {
|
import {
|
||||||
createFlowStateFromPublishedRule,
|
createFlowStateFromPublishedRule,
|
||||||
@@ -17,19 +20,86 @@ function sortedIds(value: unknown): string {
|
|||||||
.join(",");
|
.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(
|
export function createFlowStateMatchesPublishedRule(
|
||||||
state: CreateFlowState,
|
state: CreateFlowState,
|
||||||
last: StoredLastPublishedRule,
|
last: StoredLastPublishedRule,
|
||||||
): boolean {
|
): boolean {
|
||||||
const patch = createFlowStateFromPublishedRule(last);
|
const patch = createFlowStateFromPublishedRule(last);
|
||||||
const title =
|
const title = typeof state.title === "string" ? state.title.trim() : "";
|
||||||
typeof state.title === "string" ? state.title.trim() : "";
|
const patchTitle = typeof patch.title === "string" ? patch.title.trim() : "";
|
||||||
const patchTitle =
|
|
||||||
typeof patch.title === "string" ? patch.title.trim() : "";
|
|
||||||
if (title !== patchTitle) return false;
|
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) {
|
for (const key of PUBLISHED_CUSTOM_RULE_SELECTION_KEYS) {
|
||||||
if (sortedIds(state[key]) !== sortedIds(patch[key])) return false;
|
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;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -63,6 +63,66 @@ describe("publishedRuleEditWouldReplaceDraft", () => {
|
|||||||
};
|
};
|
||||||
expect(publishedRuleEditWouldReplaceDraft(state, published)).toBe(true);
|
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", () => {
|
describe("createFlowStateForEditingPublishedRule", () => {
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ describe("useCreateFlowFinalize", () => {
|
|||||||
vi.mocked(publishRule).mockReset();
|
vi.mocked(publishRule).mockReset();
|
||||||
vi.mocked(updatePublishedRule).mockReset();
|
vi.mocked(updatePublishedRule).mockReset();
|
||||||
vi.mocked(deleteServerDraft).mockReset();
|
vi.mocked(deleteServerDraft).mockReset();
|
||||||
vi.mocked(deleteServerDraft).mockResolvedValue(undefined);
|
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(
|
||||||
@@ -111,6 +111,34 @@ describe("useCreateFlowFinalize", () => {
|
|||||||
expect(deleteServerDraft).toHaveBeenCalledTimes(1);
|
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 () => {
|
||||||
const { result } = renderHook(() =>
|
const { result } = renderHook(() =>
|
||||||
useCreateFlowFinalize({
|
useCreateFlowFinalize({
|
||||||
|
|||||||
@@ -123,6 +123,60 @@ describe("POST /api/rules", () => {
|
|||||||
expect(deleteRuleDraftForUserMock).toHaveBeenCalledWith("user-1");
|
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 () => {
|
||||||
publishedRuleCreateMock.mockResolvedValueOnce({
|
publishedRuleCreateMock.mockResolvedValueOnce({
|
||||||
id: "rule-counts",
|
id: "rule-counts",
|
||||||
@@ -259,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),
|
||||||
|
|||||||
@@ -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",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user