Admin hybrid delete/retire of a quest definition (Delete Task) (#262)

Co-authored-by: dev_agent <17+dev_agent@code.cubecraftcreations.com>
Co-committed-by: dev_agent <17+dev_agent@code.cubecraftcreations.com>
This commit was merged in pull request #262.
This commit is contained in:
2026-09-26 12:47:34 -04:00
committed by approver_agent
parent b1c14ed7d9
commit 02f4d8c8aa
11 changed files with 822 additions and 45 deletions
+23
View File
@@ -147,6 +147,29 @@ export async function updateDefinition(
return readJson<QuestDefinition>(await sendJson(`${DEFINITIONS_PATH}/${id}`, "PATCH", body));
}
/** `DELETE /quest-definitions/{id}`: exactly one of `deleted` / `retired` is true. */
export interface DefinitionDeleteResult {
definition_id: number;
deleted: boolean;
retired: boolean;
/** The retired (now inactive) definition; null when it was deleted. */
definition: QuestDefinition | null;
}
/**
* Delete a task if it has no completion history; otherwise the API retires
* (deactivates) it. Retirement preserves the definition row, schedule rule,
* assignees, windows and ALL durable completion history. Like any
* deactivation it regenerates, so future UNCOMPLETED instances are cleared
* (rolling, regenerable rows) and not recreated while inactive; durable
* history lives only in the append-only `completion_events`.
*/
export async function deleteDefinition(id: number): Promise<DefinitionDeleteResult> {
return readJson<DefinitionDeleteResult>(
await apiFetch(`${DEFINITIONS_PATH}/${id}`, { method: "DELETE" }),
);
}
export const OCCURRENCES_PREVIEW_PATH = `${DEFINITIONS_PATH}/occurrences-preview`;
export interface OccurrencesPreviewOptions {
+20
View File
@@ -569,6 +569,26 @@
color: #fff;
}
.defs-save--danger {
background: var(--nq-a-danger);
}
.defs-delete {
display: block;
width: 100%;
margin-top: 10px;
padding: 11px 0;
border: 1px solid var(--nq-a-danger-bg);
border-radius: var(--nq-a-density-radius);
background: var(--nq-a-surface);
color: var(--nq-a-danger-strong);
font-family: inherit;
font-size: 13px;
font-weight: 700;
cursor: pointer;
}
.defs-delete:disabled,
.defs-cancel:disabled,
.defs-save:disabled {
opacity: 0.6;
+86 -3
View File
@@ -121,6 +121,8 @@ function fakeApi(initial: QuestDefinition[]) {
const calls: Call[] = [];
let nextWrite: Response | null = null;
let preview: PreviewHandler = async () => jsonResponse({ dates: [] });
// Definitions with completion history: the API retires these on DELETE.
const withHistory = new Set<number>();
const fetchMock = vi.fn(async (input: RequestInfo | URL, init: RequestInit = {}) => {
const path = new URL(String(input), "http://localhost").pathname;
const method = init.method ?? "GET";
@@ -187,6 +189,16 @@ function fakeApi(initial: QuestDefinition[]) {
);
return jsonResponse(definitions.find((d) => d.id === id));
}
if (method === "DELETE" && match) {
const id = Number(match[1]);
if (withHistory.has(id)) {
definitions = definitions.map((d) => (d.id === id ? { ...d, is_active: false } : d));
const retired = definitions.find((d) => d.id === id);
return jsonResponse({ definition_id: id, deleted: false, retired: true, definition: retired });
}
definitions = definitions.filter((d) => d.id !== id);
return jsonResponse({ definition_id: id, deleted: true, retired: false, definition: null });
}
return jsonResponse({ detail: "unexpected" }, 500);
});
return {
@@ -203,6 +215,9 @@ function fakeApi(initial: QuestDefinition[]) {
failNextWrite: (response: Response) => {
nextWrite = response;
},
markHistory: (id: number) => {
withHistory.add(id);
},
};
}
@@ -578,14 +593,15 @@ describe("DefinitionsTab", () => {
fireEvent.click(screen.getByTestId("definition-10"));
const s = sheet();
const title = within(s).getByRole("textbox", { name: "Title" });
const save = within(s).getByRole("button", { name: "Save changes" });
// The edit sheet's last focusable control is its Delete button.
const last = within(s).getByRole("button", { name: "Delete task" });
save.focus();
last.focus();
fireEvent.keyDown(s, { key: "Tab" });
expect(document.activeElement).toBe(title);
fireEvent.keyDown(s, { key: "Tab", shiftKey: true });
expect(document.activeElement).toBe(save);
expect(document.activeElement).toBe(last);
});
it("Escape does not close the sheet while saving", async () => {
@@ -694,6 +710,73 @@ describe("DefinitionsTab", () => {
);
});
it("the Delete control is only offered for an existing task", async () => {
await renderReady();
fireEvent.click(screen.getByRole("button", { name: "New" }));
expect(within(sheet()).queryByRole("button", { name: "Delete task" })).toBeNull();
fireEvent.click(within(sheet()).getByRole("button", { name: "Cancel" }));
fireEvent.click(screen.getByTestId("definition-10"));
expect(within(sheet()).getByRole("button", { name: "Delete task" })).toBeTruthy();
});
it("Delete asks first, explaining delete-vs-retire; Go back writes nothing", async () => {
await renderReady();
fireEvent.click(screen.getByTestId("definition-10"));
fireEvent.click(within(sheet()).getByRole("button", { name: "Delete task" }));
const confirm = screen.getByTestId("delete-confirm");
expect(confirm.textContent).toContain("If it has no completion history it is deleted");
expect(confirm.textContent).toContain("otherwise it is retired");
expect(api.writes()).toHaveLength(0);
fireEvent.click(within(confirm).getByRole("button", { name: "Go back" }));
expect(screen.queryByTestId("delete-confirm")).toBeNull();
expect(api.writes()).toHaveLength(0);
});
it("confirming Delete on a task without history removes its row", async () => {
await renderReady();
fireEvent.click(screen.getByTestId("definition-10"));
fireEvent.click(within(sheet()).getByRole("button", { name: "Delete task" }));
fireEvent.click(
within(screen.getByTestId("delete-confirm")).getByRole("button", { name: "Delete task" }),
);
await waitFor(() => expect(screen.queryByTestId("definition-10")).toBeNull());
expect(screen.queryByRole("dialog")).toBeNull();
expect(api.writes()).toEqual([
{ method: "DELETE", path: "/api/v1/admin/quest-definitions/10", body: null },
]);
expect(screen.getByTestId("definition-11")).toBeTruthy();
});
it("confirming Delete on a task with history shows it retired (inactive)", async () => {
await renderReady();
api.markHistory(10);
fireEvent.click(screen.getByTestId("definition-10"));
fireEvent.click(within(sheet()).getByRole("button", { name: "Delete task" }));
fireEvent.click(
within(screen.getByTestId("delete-confirm")).getByRole("button", { name: "Delete task" }),
);
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
const row = screen.getByTestId("definition-10");
expect(row.className).toContain("defs-row--inactive");
expect(meta(row)).toContain("· inactive");
expect(api.writes().map((c) => c.method)).toEqual(["DELETE"]);
});
it("a failed Delete shows the API's detail and keeps the sheet open", async () => {
await renderReady();
api.failNextWrite(jsonResponse({ detail: "Quest definition not found" }, 404));
fireEvent.click(screen.getByTestId("definition-10"));
fireEvent.click(within(sheet()).getByRole("button", { name: "Delete task" }));
fireEvent.click(
within(screen.getByTestId("delete-confirm")).getByRole("button", { name: "Delete task" }),
);
expect((await screen.findByTestId("sheet-error")).textContent).toBe(
"Quest definition not found",
);
expect(screen.getByRole("dialog")).toBeTruthy();
expect(screen.getByTestId("definition-10")).toBeTruthy();
});
it("scroll column carries the 92px bottom padding", async () => {
await renderReady();
expect(screen.getByTestId("definitions-scroll").style.paddingBottom).toBe("92px");
+92 -10
View File
@@ -13,12 +13,14 @@ import { ApiForbiddenError } from "../api/client";
import {
ApiRequestError,
createDefinition,
deleteDefinition,
fetchChildren,
fetchDefinitions,
previewOccurrences,
updateDefinition,
type AdminChild,
type DefinitionCreateBody,
type DefinitionDeleteResult,
type DefinitionEditBody,
type DefinitionRule,
type QuestDefinition,
@@ -273,6 +275,12 @@ function saveErrorMessage(error: unknown): string {
return "The task could not be saved. Check your connection and try again.";
}
function deleteErrorMessage(error: unknown): string {
if (error instanceof ApiForbiddenError) return error.message;
if (error instanceof ApiRequestError && error.detail) return error.detail;
return "The task could not be deleted. Check your connection and try again.";
}
function toggle<T>(list: T[], value: T): T[] {
return list.includes(value) ? list.filter((item) => item !== value) : [...list, value];
}
@@ -449,11 +457,13 @@ function EditSheet({
activeChildren,
onCancel,
onSaved,
onDeleted,
}: {
target: "new" | QuestDefinition;
activeChildren: AdminChild[];
onCancel: () => void;
onSaved: () => void;
onDeleted: (result: DefinitionDeleteResult) => void;
}) {
const [draft, setDraft] = useState<Draft>(() =>
target === "new" ? newDraft(activeChildren) : draftFrom(target, activeChildren),
@@ -473,6 +483,7 @@ function EditSheet({
const [pickerOpen, setPickerOpen] = useState(false);
const [saving, setSaving] = useState(false);
const [confirming, setConfirming] = useState(false);
const [confirmingDelete, setConfirmingDelete] = useState(false);
const [error, setError] = useState<string | null>(null);
// A ref, not state: two taps in one frame must not both see `saving === false`.
const inFlight = useRef(false);
@@ -490,8 +501,8 @@ function EditSheet({
}, []);
useEffect(() => {
if (confirming) confirmRef.current?.focus();
}, [confirming]);
if (confirming || confirmingDelete) confirmRef.current?.focus();
}, [confirming, confirmingDelete]);
function onKeyDown(event: ReactKeyboardEvent<HTMLDivElement>) {
if (event.key === "Escape") {
@@ -559,6 +570,21 @@ function EditSheet({
}
}
async function remove() {
if (target === "new" || inFlight.current) return;
setConfirmingDelete(false);
inFlight.current = true;
setSaving(true);
setError(null);
try {
onDeleted(await deleteDefinition(target.id));
} catch (err) {
setError(deleteErrorMessage(err));
inFlight.current = false;
setSaving(false);
}
}
return (
<div className="defs-sheet-layer">
<div
@@ -906,15 +932,56 @@ function EditSheet({
</button>
</div>
</div>
) : (
<div className="defs-sheet-footer">
<button type="button" className="defs-cancel" onClick={onCancel} disabled={saving}>
Cancel
</button>
<button type="button" className="defs-save" onClick={() => save()} disabled={saving}>
{saving ? "Saving…" : "Save changes"}
</button>
) : confirmingDelete ? (
<div
className="defs-confirm"
role="group"
aria-labelledby="defs-delete-confirm-text"
data-testid="delete-confirm"
ref={confirmRef}
tabIndex={-1}
>
<p id="defs-delete-confirm-text">
Delete this task? If it has no completion history it is deleted; otherwise it is
retired (deactivated) and its history is kept.
</p>
<div className="defs-sheet-footer">
<button
type="button"
className="defs-cancel"
onClick={() => setConfirmingDelete(false)}
>
Go back
</button>
<button type="button" className="defs-save defs-save--danger" onClick={remove}>
Delete task
</button>
</div>
</div>
) : (
<>
<div className="defs-sheet-footer">
<button type="button" className="defs-cancel" onClick={onCancel} disabled={saving}>
Cancel
</button>
<button type="button" className="defs-save" onClick={() => save()} disabled={saving}>
{saving ? "Saving…" : "Save changes"}
</button>
</div>
{target !== "new" ? (
<button
type="button"
className="defs-delete"
disabled={saving}
onClick={() => {
setError(null);
setConfirmingDelete(true);
}}
>
Delete task
</button>
) : null}
</>
)}
</div>
</div>
@@ -1038,6 +1105,21 @@ export default function DefinitionsTab() {
setSheet(null);
setAttempt((n) => n + 1);
}}
onDeleted={(result) => {
setSheet(null);
setState((current) =>
current.kind !== "ready"
? current
: {
...current,
definitions: result.definition
? current.definitions.map((d) =>
d.id === result.definition_id ? result.definition! : d,
)
: current.definitions.filter((d) => d.id !== result.definition_id),
},
);
}}
/>
) : null}
</div>