Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat: show subtask progress on cards and list rows

Tinb359dde75596
diff --git a/apps/api/src/column/controllers/update-column.ts b/apps/api/src/column/controllers/update-column.ts
index 420203a4b..6c93c5e39 100644
--- a/apps/api/src/column/controllers/update-column.ts
+++ b/apps/api/src/column/controllers/update-column.ts
@@ -2,6 +2,8 @@ import { eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { columnTable } from "../../database/schema";
+import { publishEvent } from "../../events";
+import { getProjectSubtaskParentProjects } from "../../task/get-subtask-parent-projects";
async function updateColumn(
id: string,
@@ -35,6 +37,19 @@ async function updateColumn(
throw new HTTPException(500, { message: "Failed to update column" });
}
+ if (existing.isFinal !== updated.isFinal) {
+ const parents = await getProjectSubtaskParentProjects(
+ updated.projectId,
+ updated.slug,
+ );
+ await publishEvent("subtask-parents.refresh", {
+ projects: [
+ { projectId: updated.projectId },
+ ...parents.filter((p) => p.projectId !== updated.projectId),
+ ],
+ });
+ }
+
return updated;
}
diff --git a/apps/api/src/project/controllers/delete-project.ts b/apps/api/src/project/controllers/delete-project.ts
index 96dcc2cda..68c69c549 100644
--- a/apps/api/src/project/controllers/delete-project.ts
+++ b/apps/api/src/project/controllers/delete-project.ts
@@ -2,12 +2,16 @@ import { eq } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import { projectTable } from "../../database/schema";
+import { publishEvent } from "../../events";
import { deleteS3Object } from "../../storage/s3";
+import { getProjectSubtaskParentProjects } from "../../task/get-subtask-parent-projects";
import getProject from "./get-project";
async function deleteProject(id: string, workspaceId: string) {
const existingProject = await getProject(id, workspaceId);
+ const parents = await getProjectSubtaskParentProjects(id);
+
const [deletedProject] = await db
.delete(projectTable)
.where(eq(projectTable.id, id))
@@ -19,6 +23,9 @@ async function deleteProject(id: string, workspaceId: string) {
});
}
+ await publishEvent("subtask-parents.refresh", {
+ projects: parents.filter((parent) => parent.projectId !== id),
+ });
if (deletedProject.backgroundObjectKey) {
deleteS3Object(deletedProject.backgroundObjectKey).catch(() => {});
}
diff --git a/apps/api/src/project/controllers/get-public-project.ts b/apps/api/src/project/controllers/get-public-project.ts
index 63b2d6637..c675b0c41 100644
--- a/apps/api/src/project/controllers/get-public-project.ts
+++ b/apps/api/src/project/controllers/get-public-project.ts
@@ -28,7 +28,7 @@ export async function getPublicProject(
});
}
- const result = await getTasks(id, options);
+ const result = await getTasks(id, { ...options, publicOnly: true });
if (!result.data) {
throw new HTTPException(404, {
diff --git a/apps/api/src/task-relation/controllers/get-task-relations.ts b/apps/api/src/task-relation/controllers/get-task-relations.ts
index c7042fd91..9b1712196 100644
--- a/apps/api/src/task-relation/controllers/get-task-relations.ts
+++ b/apps/api/src/task-relation/controllers/get-task-relations.ts
@@ -6,6 +6,7 @@ import {
taskTable,
userTable,
} from "../../database/schema";
+import { taskIsCompleted } from "../../task/task-is-completed";
async function getTaskRelations(taskId: string, workspaceId: string) {
const relations = await db
@@ -36,6 +37,7 @@ async function getTaskRelations(taskId: string, workspaceId: string) {
id: string;
title: string;
status: string;
+ isCompleted: boolean;
priority: string | null;
number: number | null;
projectId: string;
@@ -50,6 +52,7 @@ async function getTaskRelations(taskId: string, workspaceId: string) {
id: taskTable.id,
title: taskTable.title,
status: taskTable.status,
+ isCompleted: taskIsCompleted,
priority: taskTable.priority,
number: taskTable.number,
projectId: taskTable.projectId,
diff --git a/apps/api/src/task-relation/response.ts b/apps/api/src/task-relation/response.ts
index 51205b47a..0efcc77db 100644
--- a/apps/api/src/task-relation/response.ts
+++ b/apps/api/src/task-relation/response.ts
@@ -8,6 +8,9 @@ const relatedTaskSchema = z
id: z.string(),
title: z.string(),
status: z.string(),
+ isCompleted: z.boolean().openapi({
+ description: "Whether the task is in a final column of its own project.",
+ }),
priority: z.string().nullable(),
number: z.number().nullable(),
projectId: z.string(),
diff --git a/apps/api/src/task/controllers/bulk-update-tasks.ts b/apps/api/src/task/controllers/bulk-update-tasks.ts
index e12b27342..71661f663 100644
--- a/apps/api/src/task/controllers/bulk-update-tasks.ts
+++ b/apps/api/src/task/controllers/bulk-update-tasks.ts
@@ -13,6 +13,7 @@ import { publishEvent } from "../../events";
import { removeLabelFromGitea } from "../../plugins/gitea/utils/sync-label-to-gitea";
import { removeLabelFromGitHub } from "../../plugins/github/utils/sync-label-to-github";
import { assertAssignableUser } from "../../utils/assert-assignable-user";
+import { getSubtaskParentProjects } from "../get-subtask-parent-projects";
import {
assertValidPriority,
assertValidTaskStatus,
@@ -124,6 +125,11 @@ async function bulkUpdateTasks({
updatedCount += result.rowCount ?? projectTaskIds.length;
+ const parentProjects = await getSubtaskParentProjects(projectTaskIds);
+ await publishEvent("subtask-parents.refresh", {
+ projects: parentProjects,
+ });
+
for (const task of projectTasks) {
await publishEvent("task.status_changed", {
taskId: task.id,
@@ -134,6 +140,7 @@ async function bulkUpdateTasks({
title: task.title,
assigneeId: task.userId,
type: "status_changed",
+ skipSubtaskParentRefresh: true,
});
}
@@ -215,6 +222,8 @@ async function bulkUpdateTasks({
}
case "delete": {
+ // Relations cascade away with the children, so capture parents first.
+ const parentProjects = await getSubtaskParentProjects(foundIds);
const result = await db
.delete(taskTable)
.where(inArray(taskTable.id, foundIds));
@@ -229,6 +238,9 @@ async function bulkUpdateTasks({
title: task.title,
});
}
+ await publishEvent("subtask-parents.refresh", {
+ projects: parentProjects,
+ });
break;
}
diff --git a/apps/api/src/task/controllers/get-tasks.ts b/apps/api/src/task/controllers/get-tasks.ts
index 8f364db4c..9b52542d0 100644
--- a/apps/api/src/task/controllers/get-tasks.ts
+++ b/apps/api/src/task/controllers/get-tasks.ts
@@ -19,7 +19,6 @@ import {
taskTable,
userTable,
} from "../../database/schema";
-
import { boundedTaskRead, type TaskReadDatabase } from "../bounded-read";
import {
boardDescription,
@@ -27,8 +26,10 @@ import {
descriptionDeferred,
projectDescriptionDeferred,
} from "../description-pages";
+import { getSubtaskCounts } from "../get-subtask-counts";
export type GetTasksOptions = {
+ publicOnly?: boolean;
assigneeId?: string;
dueAfter?: string;
dueBefore?: string;
@@ -172,6 +173,13 @@ async function getTasksPage(
const taskIds = paginatedTasks.map((task) => task.id);
+ const subtaskCounts = await getSubtaskCounts(
+ db,
+ taskIds,
+ project.workspaceId,
+ options.publicOnly ?? false,
+ );
+
const labelsData =
taskIds.length > 0
? await db
@@ -307,6 +315,7 @@ async function getTasksPage(
.filter((task) => task.status === column.slug)
.map((task) => ({
...task,
+ subtaskCounts: subtaskCounts.get(task.id) ?? { completed: 0, total: 0 },
labels: taskLabelsMap.get(task.id) || [],
externalLinks: taskExternalLinksMap.get(task.id) || [],
})),
@@ -316,6 +325,7 @@ async function getTasksPage(
.filter((task) => task.status === "archived")
.map((task) => ({
...task,
+ subtaskCounts: subtaskCounts.get(task.id) ?? { completed: 0, total: 0 },
labels: taskLabelsMap.get(task.id) || [],
externalLinks: taskExternalLinksMap.get(task.id) || [],
}));
@@ -324,6 +334,7 @@ async function getTasksPage(
.filter((task) => task.status === "planned")
.map((task) => ({
...task,
+ subtaskCounts: subtaskCounts.get(task.id) ?? { completed: 0, total: 0 },
labels: taskLabelsMap.get(task.id) || [],
externalLinks: taskExternalLinksMap.get(task.id) || [],
}));
diff --git a/apps/api/src/task/get-subtask-counts.ts b/apps/api/src/task/get-subtask-counts.ts
new file mode 100644
index 000000000..ba06eaabe
--- /dev/null
+++ b/apps/api/src/task/get-subtask-counts.ts
@@ -0,0 +1,42 @@
+import { and, eq, inArray, sql } from "drizzle-orm";
+import { projectTable, taskRelationTable, taskTable } from "../database/schema";
+import type { TaskReadDatabase } from "./bounded-read";
+import { taskIsCompleted } from "./task-is-completed";
+
+/** Load direct-child progress for the entire page, independent of board filters. */
+export async function getSubtaskCounts(
+ db: TaskReadDatabase,
+ taskIds: string[],
+ workspaceId: string,
+ publicOnly: boolean,
+) {
+ if (taskIds.length === 0) {
+ return new Map<string, { completed: number; total: number }>();
+ }
+
+ const rows = await db
+ .select({
+ taskId: taskRelationTable.sourceTaskId,
+ total: sql<number>`count(distinct ${taskTable.id})`.mapWith(Number),
+ completed:
+ sql<number>`count(distinct ${taskTable.id}) filter (where ${taskIsCompleted})`.mapWith(
+ Number,
+ ),
+ })
+ .from(taskRelationTable)
+ .innerJoin(taskTable, eq(taskRelationTable.targetTaskId, taskTable.id))
+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))
+ .where(
+ and(
+ inArray(taskRelationTable.sourceTaskId, taskIds),
+ eq(taskRelationTable.relationType, "subtask"),
+ eq(projectTable.workspaceId, workspaceId),
+ publicOnly ? eq(projectTable.isPublic, true) : undefined,
+ ),
+ )
+ .groupBy(taskRelationTable.sourceTaskId);
+
+ return new Map(
+ rows.map(({ taskId, completed, total }) => [taskId, { completed, total }]),
+ );
+}
diff --git a/apps/api/src/task/get-subtask-parent-projects.ts b/apps/api/src/task/get-subtask-parent-projects.ts
new file mode 100644
index 000000000..4aac371c9
--- /dev/null
+++ b/apps/api/src/task/get-subtask-parent-projects.ts
@@ -0,0 +1,47 @@
+import { and, eq, inArray } from "drizzle-orm";
+import { alias } from "drizzle-orm/pg-core";
+import db from "../database";
+import { taskRelationTable, taskTable } from "../database/schema";
+
+/** Find boards whose counters depend on a child, including other projects. */
+export async function getSubtaskParentProjects(taskIds: string[]) {
+ if (taskIds.length === 0) return [];
+ return db
+ .selectDistinct({ projectId: taskTable.projectId })
+ .from(taskRelationTable)
+ .innerJoin(taskTable, eq(taskRelationTable.sourceTaskId, taskTable.id))
+ .where(
+ and(
+ inArray(taskRelationTable.targetTaskId, taskIds),
+ eq(taskRelationTable.relationType, "subtask"),
+ ),
+ );
+}
+
+/** Deleted relations are gone by broadcast time; their source task still exists. */
+export async function getRelationSourceProject(sourceTaskId: string) {
+ return db
+ .select({ projectId: taskTable.projectId })
+ .from(taskTable)
+ .where(eq(taskTable.id, sourceTaskId));
+}
+
+/** Find affected parent boards before a project cascade or column change. */
+export async function getProjectSubtaskParentProjects(
+ projectId: string,
+ status?: string,
+) {
+ const child = alias(taskTable, "child");
+ return db
+ .selectDistinct({ projectId: taskTable.projectId })
+ .from(taskRelationTable)
+ .innerJoin(taskTable, eq(taskRelationTable.sourceTaskId, taskTable.id))
+ .innerJoin(child, eq(taskRelationTable.targetTaskId, child.id))
+ .where(
+ and(
+ eq(child.projectId, projectId),
+ status === undefined ? undefined : eq(child.status, status),
+ eq(taskRelationTable.relationType, "subtask"),
+ ),
+ );
+}
diff --git a/apps/api/src/task/response.ts b/apps/api/src/task/response.ts
index ecd0c4cad..839318660 100644
--- a/apps/api/src/task/response.ts
+++ b/apps/api/src/task/response.ts
@@ -85,6 +85,15 @@ export const boardTaskSchema = z
assigneeId: z.string().nullable(),
assigneeImage: z.string().nullable(),
projectId: z.string(),
+ subtaskCounts: z
+ .object({
+ completed: z.number().int().nonnegative(),
+ total: z.number().int().nonnegative(),
+ })
+ .openapi({
+ description:
+ "Direct subtasks in the workspace; completed means a final column in the child project. Public boards count only children in public projects.",
+ }),
labels: z.array(taskLabelSchema),
externalLinks: z.array(taskExternalLinkSchema),
})
diff --git a/apps/api/src/task/task-is-completed.ts b/apps/api/src/task/task-is-completed.ts
new file mode 100644
index 000000000..647cfd23f
--- /dev/null
+++ b/apps/api/src/task/task-is-completed.ts
@@ -0,0 +1,10 @@
+import { sql } from "drizzle-orm";
+import { columnTable, taskTable } from "../database/schema";
+
+// Completion belongs to the task's workflow, even when its parent is elsewhere.
+export const taskIsCompleted = sql<boolean>`exists (
+ select 1 from ${columnTable}
+ where ${columnTable.projectId} = ${taskTable.projectId}
+ and ${columnTable.slug} = ${taskTable.status}
+ and ${columnTable.isFinal} = true
+)`;
diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.ts
index 252859154..414db106c 100644
--- a/apps/api/src/ws/index.ts
+++ b/apps/api/src/ws/index.ts
@@ -5,6 +5,10 @@ import db from "../database";
import { projectTable } from "../database/schema";
import { subscribeToEvent } from "../events";
import { isRedisConfigured } from "../redis";
+import {
+ getRelationSourceProject,
+ getSubtaskParentProjects,
+} from "../task/get-subtask-parent-projects";
import type {
BroadcastAdapter,
BroadcastMessage,
@@ -330,6 +334,7 @@ export function broadcastToProject(
}
type TaskEvent = {
+ skipSubtaskParentRefresh?: boolean;
id: string | undefined;
projectId: string;
userId: string;
@@ -339,6 +344,29 @@ type TaskEvent = {
targetTaskId: string | undefined;
};
+// Include the initiating window: its local mutation refreshes the child project,
+// while it may be displaying a different parent board. Never send child data.
+function refreshParentBoards(
+ projects: { projectId: string }[],
+ currentProjectId = "",
+) {
+ for (const { projectId } of projects) {
+ if (projectId === currentProjectId) continue;
+ broadcastToProject(projectId, {
+ type: "TASK_RELATION_UPDATED",
+ projectId,
+ taskId: "",
+ });
+ }
+}
+
+subscribeToEvent<{ projects: { projectId: string }[] }>(
+ "subtask-parents.refresh",
+ async ({ projects }) => {
+ refreshParentBoards(projects);
+ },
+);
+
const taskUpdateEvents = [
"task.created",
"task.updated",
@@ -386,6 +414,7 @@ subscribeToEvent<{
{ type: "TASK_MOVED", projectId: fromProjectId, taskId },
initiatorId,
);
+ refreshParentBoards(await getSubtaskParentProjects([taskId]), fromProjectId);
});
subscribeToEvent<{
@@ -505,5 +534,13 @@ for (const eventName of taskUpdateEvents) {
},
initiatorId,
);
+ if (eventName === "task.status_changed" && !data.skipSubtaskParentRefresh) {
+ refreshParentBoards(await getSubtaskParentProjects([taskId]), projectId);
+ } else if (eventName === "task-relation.deleted" && data.sourceTaskId) {
+ refreshParentBoards(
+ await getRelationSourceProject(data.sourceTaskId),
+ projectId,
+ );
+ }
});
}
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index a7e3a72aa..56f26f480 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -182,6 +182,24 @@
"projectId": {
"type": "string"
},
+ "subtaskCounts": {
+ "type": "object",
+ "properties": {
+ "completed": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "total": {
+ "type": "integer",
+ "minimum": 0
+ }
+ },
+ "required": [
+ "completed",
+ "total"
+ ],
+ "description": "Direct subtasks in the workspace; completed means a final column in the child project. Public boards count only children in public projects."
+ },
"labels": {
"type": "array",
"items": {
@@ -211,6 +229,7 @@
"assigneeId",
"assigneeImage",
"projectId",
+ "subtaskCounts",
"labels",
"externalLinks"
]
@@ -3042,6 +3061,10 @@
"status": {
"type": "string"
},
+ "isCompleted": {
+ "type": "boolean",
+ "description": "Whether the task is in a final column of its own project."
+ },
"priority": {
"type": [
"string",
@@ -3074,6 +3097,7 @@
"id",
"title",
"status",
+ "isCompleted",
"priority",
"number",
"projectId",
diff --git a/apps/web/src/components/backlog-list-view/backlog-task-row.tsx b/apps/web/src/components/backlog-list-view/backlog-task-row.tsx
index cd555bc8e..27583119b 100644
--- a/apps/web/src/components/backlog-list-view/backlog-task-row.tsx
+++ b/apps/web/src/components/backlog-list-view/backlog-task-row.tsx
@@ -10,6 +10,7 @@ import {
} from "lucide-react";
import { type CSSProperties, memo, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
+import { TaskProgressBadges } from "@/components/task/task-progress-badges";
import {
AlertDialog,
AlertDialogClose,
@@ -205,11 +206,10 @@ const BacklogTaskRow = memo(function BacklogTaskRow({
<span className="text-sm text-foreground truncate">
{task.title}
</span>
- {showLabels && (
- <div className="flex items-center gap-1">
- <TaskLabels labels={task.labels ?? []} />
- </div>
- )}
+ <div className="flex items-center gap-1">
+ <TaskProgressBadges task={task} />
+ {showLabels && <TaskLabels labels={task.labels ?? []} />}
+ </div>
</div>
</div>
diff --git a/apps/web/src/components/kanban-board/task-card.tsx b/apps/web/src/components/kanban-board/task-card.tsx
index d7620dc5f..9f653b9a5 100644
--- a/apps/web/src/components/kanban-board/task-card.tsx
+++ b/apps/web/src/components/kanban-board/task-card.tsx
@@ -9,10 +9,10 @@ import {
GitMerge,
GitPullRequest,
SlidersHorizontal,
- SquareCheck,
} from "lucide-react";
import { type CSSProperties, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
+import { TaskProgressBadges } from "@/components/task/task-progress-badges";
import {
AlertDialog,
AlertDialogClose,
@@ -34,7 +34,6 @@ import { useDeleteTask } from "@/hooks/mutations/task/use-delete-task";
import useGetCustomFieldValuesByProject from "@/hooks/queries/custom-field/use-get-custom-field-values-by-project";
import useActiveWorkspace from "@/hooks/queries/workspace/use-active-workspace";
import { useGetActiveWorkspaceUsers } from "@/hooks/queries/workspace-users/use-get-active-workspace-users";
-import { cn } from "@/lib/cn";
import {
dueDateStatusColors,
getDueDateStatus,
@@ -42,7 +41,6 @@ import {
} from "@/lib/due-date-status";
import { getExternalWebUrl, openExternalWebUrl } from "@/lib/external-url";
import { getInitials } from "@/lib/get-initials";
-import { getTaskItemStats } from "@/lib/get-task-item-stats";
import { getPriorityIcon } from "@/lib/priority";
import { toast } from "@/lib/toast";
import useBulkSelectionStore from "@/store/bulk-selection";
@@ -78,19 +76,11 @@ function TaskCard({ task, disableDragDrop = false }: TaskCardProps) {
showDueDates,
showLabels,
showTaskNumbers,
- showTaskItemCounts,
} = useUserPreferencesStore();
const [isDeleteTaskModalOpen, setIsDeleteTaskModalOpen] = useState(false);
const { toggleSelection, isSelected, isFocused } = useBulkSelectionStore();
const isTaskSelected = isSelected(task.id);
const isTaskFocused = isFocused(task.id);
- const taskItemStats = useMemo(
- () =>
- showTaskItemCounts && !task.descriptionDeferred
- ? getTaskItemStats(task.description)
- : null,
- [task.description, task.descriptionDeferred, showTaskItemCounts],
- );
const pullRequests = useMemo(() => {
return (task.externalLinks ?? []).filter(
@@ -295,7 +285,7 @@ function TaskCard({ task, disableDragDrop = false }: TaskCardProps) {
</div>
)}
- <div className="flex items-center gap-1.5">
+ <div className="flex flex-wrap items-center gap-1.5">
{showPriority && (
<span className="inline-flex items-center gap-1 rounded border border-border/70 bg-muted/55 px-2 py-1 text-[10px] font-medium text-muted-foreground h-5.5">
{getPriorityIcon(task.priority ?? "")}
@@ -367,20 +357,7 @@ function TaskCard({ task, disableDragDrop = false }: TaskCardProps) {
</HoverCard>
)}
- {taskItemStats && taskItemStats.total > 0 && (
- <span
- className={cn(
- "flex items-center gap-1 text-[10px] px-2 py-1 rounded bg-muted/50 text-muted-foreground h-5.5",
- {
- "bg-success/10 text-success-foreground":
- taskItemStats.completed === taskItemStats.total,
- },
- )}
- >
- <SquareCheck className="h-[12px] w-[12px]" />
- {taskItemStats.completed}/{taskItemStats.total}
- </span>
- )}
+ <TaskProgressBadges task={task} />
{showDueDates && task.dueDate && (
<div
diff --git a/apps/web/src/components/list-view/task-row.test.tsx b/apps/web/src/components/list-view/task-row.test.tsx
index 2e266c6cd..8974b418e 100644
--- a/apps/web/src/components/list-view/task-row.test.tsx
+++ b/apps/web/src/components/list-view/task-row.test.tsx
@@ -1,6 +1,9 @@
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type Task from "@/types/task";
+import BacklogTaskRow from "../backlog-list-view/backlog-task-row";
+import { PublicTaskCard } from "../public-project/task-card";
+import { PublicTaskRow } from "../public-project/task-row";
import TaskRow from "./task-row";
const useExternalLinks = vi.fn((_taskId: string) => ({ data: [] }));
@@ -52,7 +55,14 @@ vi.mock("@/store/bulk-selection", () => ({
}));
vi.mock("@/store/project", () => ({
- default: () => ({ project: { id: "project-1", slug: "kan" } }),
+ default: (
+ selector?: (state: {
+ project: { id: string; slug: string; columns: never[] };
+ }) => unknown,
+ ) => {
+ const state = { project: { id: "project-1", slug: "kan", columns: [] } };
+ return selector ? selector(state) : state;
+ },
}));
vi.mock("@/store/user-preferences", () => ({
@@ -85,6 +95,7 @@ const task: Task = {
assigneeName: null,
projectId: "project-1",
labels: [{ id: "label-1", name: "Bug", color: "red" }],
+ subtaskCounts: { completed: 2, total: 5 },
externalLinks: [
{
id: "link-1",
@@ -100,12 +111,54 @@ const task: Task = {
};
describe("TaskRow", () => {
+ it.each([PublicTaskCard, PublicTaskRow])(
+ "renders public progress without nesting interactive controls",
+ (Component) => {
+ const onTaskClick = vi.fn();
+ const { container } = render(
+ <Component
+ task={{ ...task, externalLinks: [] }}
+ projectSlug="kan"
+ onTaskClick={onTaskClick}
+ />,
+ );
+ expect(screen.getByTitle("tasks:subtasks.progress")).toHaveTextContent(
+ "2/5",
+ );
+ expect(container.querySelector("button button")).toBeNull();
+ expect(screen.getAllByRole("button")).toHaveLength(1);
+ expect(useExternalLinks).not.toHaveBeenCalled();
+ expect(useGetLabelsByTask).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(["planned", "archived"])(
+ "renders progress for %s backlog parents without per-row requests",
+ (status) => {
+ render(<BacklogTaskRow task={{ ...task, status }} />);
+
+ expect(
+ screen.getByRole("button", { name: "tasks:subtasks.progress" }),
+ ).toHaveTextContent("2/5");
+ expect(useExternalLinks).not.toHaveBeenCalled();
+ expect(useGetLabelsByTask).not.toHaveBeenCalled();
+ },
+ );
+
it("renders labels and pull requests from the task payload without per-row requests", () => {
render(<TaskRow task={task} projectSlug="kan" />);
expect(screen.getByText("Bug")).toBeVisible();
expect(screen.getByText("#42")).toBeVisible();
+ expect(
+ screen.getByRole("button", { name: "tasks:subtasks.progress" }),
+ ).toHaveTextContent("2/5");
expect(useExternalLinks).not.toHaveBeenCalled();
expect(useGetLabelsByTask).not.toHaveBeenCalled();
});
});
+
+vi.mock(
+ "@/hooks/queries/custom-field/use-get-custom-field-values-by-project",
+ () => ({ default: () => ({ data: [] }) }),
+);
diff --git a/apps/web/src/components/list-view/task-row.tsx b/apps/web/src/components/list-view/task-row.tsx
index 4ee0a2e8a..801e76daf 100644
--- a/apps/web/src/components/list-view/task-row.tsx
+++ b/apps/web/src/components/list-view/task-row.tsx
@@ -11,6 +11,7 @@ import {
} from "lucide-react";
import { type CSSProperties, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
+import { TaskProgressBadges } from "@/components/task/task-progress-badges";
import {
AlertDialog,
AlertDialogClose,
@@ -217,6 +218,7 @@ function TaskRow({ task, projectSlug }: TaskRowProps) {
{task.title}
</span>
<div className="flex items-center gap-1">
+ <TaskProgressBadges task={task} />
{showLabels && <TaskLabels labels={task.labels ?? []} />}
{pullRequests.length === 1 && (
diff --git a/apps/web/src/components/public-project/task-card.tsx b/apps/web/src/components/public-project/task-card.tsx
index fc9e89d18..c1410ad0f 100644
--- a/apps/web/src/components/public-project/task-card.tsx
+++ b/apps/web/src/components/public-project/task-card.tsx
@@ -1,5 +1,6 @@
import { Calendar, CalendarClock, CalendarX } from "lucide-react";
import { useRef } from "react";
+import { TaskProgressBadges } from "@/components/task/task-progress-badges";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
dueDateStatusColors,
@@ -122,7 +123,8 @@ export function PublicTaskCard({
</div>
)}
- <div className="flex items-center gap-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <TaskProgressBadges task={task} asText />
{task.priority && (
<span className="inline-flex items-center gap-1.5 px-2 py-1 rounded border border-border bg-sidebar text-[10px] font-medium text-muted-foreground">
{getPriorityIcon(task.priority ?? "")}
diff --git a/apps/web/src/components/public-project/task-row.tsx b/apps/web/src/components/public-project/task-row.tsx
index 7dd6c02d3..6adb57785 100644
--- a/apps/web/src/components/public-project/task-row.tsx
+++ b/apps/web/src/components/public-project/task-row.tsx
@@ -1,5 +1,6 @@
import { Calendar, CalendarClock, CalendarX } from "lucide-react";
import { useTranslation } from "react-i18next";
+import { TaskProgressBadges } from "@/components/task/task-progress-badges";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
dueDateStatusColors,
@@ -58,7 +59,8 @@ export function PublicTaskRow({
</div>
</div>
- <div className="flex items-center gap-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <TaskProgressBadges task={task} asText />
{task.assigneeName && (
<div className="flex items-center gap-1.5">
<Avatar className="h-5 w-5">
diff --git a/apps/web/src/components/task/task-progress-badges.test.tsx b/apps/web/src/components/task/task-progress-badges.test.tsx
new file mode 100644
index 000000000..c7f853f19
--- /dev/null
+++ b/apps/web/src/components/task/task-progress-badges.test.tsx
@@ -0,0 +1,118 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import { TaskProgressBadges } from "./task-progress-badges";
+
+const preferences = vi.hoisted(() => ({ showTaskItemCounts: true }));
+vi.mock("@/store/user-preferences", () => ({
+ useUserPreferencesStore: () => preferences,
+}));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, values: { completed: number; total: number }) =>
+ `${values.completed} of ${values.total} ${key.includes("subtasks") ? "subtasks" : "checklist items"} completed`,
+ }),
+}));
+
+afterEach(cleanup);
+
+beforeEach(() => {
+ preferences.showTaskItemCounts = true;
+});
+
+describe("TaskProgressBadges", () => {
+ it("keeps checklist and subtask completion independent", () => {
+ render(
+ <TaskProgressBadges
+ task={{
+ description: "- [x] One\n- [ ] Two\n- [ ] Three",
+ subtaskCounts: { completed: 2, total: 2 },
+ }}
+ />,
+ );
+ const subtasks = screen.getByRole("button", {
+ name: "2 of 2 subtasks completed",
+ });
+ const checklist = screen.getByRole("button", {
+ name: "1 of 3 checklist items completed",
+ });
+ expect(subtasks).toHaveTextContent("2/2");
+ expect(subtasks).toHaveClass("text-success-foreground");
+ expect(checklist).toHaveTextContent("1/3");
+ expect(checklist).not.toHaveClass("text-success-foreground");
+ });
+
+ it("shows subtasks when description checklist counts are disabled", () => {
+ preferences.showTaskItemCounts = false;
+ render(
+ <TaskProgressBadges
+ task={{
+ description: "- [ ] One",
+ subtaskCounts: { completed: 0, total: 3 },
+ }}
+ />,
+ );
+ expect(
+ screen.getByRole("button", { name: "0 of 3 subtasks completed" }),
+ ).toBeVisible();
+ expect(screen.getAllByRole("button")).toHaveLength(1);
+ });
+
+ it("hides absent and empty counters", () => {
+ const { rerender } = render(
+ <TaskProgressBadges task={{ description: null }} />,
+ );
+ expect(screen.queryByRole("button")).not.toBeInTheDocument();
+ rerender(
+ <TaskProgressBadges
+ task={{
+ description: "Plain text",
+ subtaskCounts: { completed: 0, total: 0 },
+ }}
+ />,
+ );
+ expect(screen.queryByRole("button")).not.toBeInTheDocument();
+ });
+
+ it("provides a tooltip and preserves the card's open action", async () => {
+ const open = vi.fn();
+ render(
+ <TooltipProvider delay={0}>
+ {/* biome-ignore lint/a11y/noStaticElementInteractions: reproduces the task card click boundary */}
+ <div onClick={open} role="presentation">
+ <TaskProgressBadges
+ task={{
+ description: null,
+ subtaskCounts: { completed: 2, total: 5 },
+ }}
+ />
+ </div>
+ </TooltipProvider>,
+ );
+ const badge = screen.getByRole("button", {
+ name: "2 of 5 subtasks completed",
+ });
+ fireEvent.mouseEnter(badge);
+ expect(await screen.findByText("2 of 5 subtasks completed")).toBeVisible();
+ fireEvent.click(badge);
+ expect(open).toHaveBeenCalledOnce();
+ });
+});
+
+it.each([
+ { description: "- [x] Truncated", descriptionDeferred: true },
+ { description: "- [x] One\n".repeat(10000), descriptionDeferred: false },
+])(
+ "does not show partial checklist counts for bounded descriptions",
+ (task) => {
+ render(
+ <TaskProgressBadges
+ task={{ ...task, subtaskCounts: { completed: 1, total: 2 } }}
+ />,
+ );
+ expect(screen.getAllByRole("button")).toHaveLength(1);
+ expect(
+ screen.getByRole("button", { name: "1 of 2 subtasks completed" }),
+ ).toBeVisible();
+ },
+);
diff --git a/apps/web/src/components/task/task-progress-badges.tsx b/apps/web/src/components/task/task-progress-badges.tsx
new file mode 100644
index 000000000..3cbae3aab
--- /dev/null
+++ b/apps/web/src/components/task/task-progress-badges.tsx
@@ -0,0 +1,82 @@
+import { ListTree, SquareCheck } from "lucide-react";
+import { useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { Tooltip, TooltipPopup, TooltipTrigger } from "@/components/ui/tooltip";
+import { cn } from "@/lib/cn";
+import { getTaskItemStats } from "@/lib/get-task-item-stats";
+import { useUserPreferencesStore } from "@/store/user-preferences";
+import type Task from "@/types/task";
+
+export function TaskProgressBadges({
+ task,
+ asText = false,
+}: {
+ task: Pick<Task, "description" | "descriptionDeferred" | "subtaskCounts">;
+ asText?: boolean;
+}) {
+ const { t } = useTranslation();
+ const { showTaskItemCounts } = useUserPreferencesStore();
+ const checklist = useMemo(
+ () =>
+ showTaskItemCounts && !task.descriptionDeferred
+ ? getTaskItemStats(task.description)
+ : null,
+ [task.description, task.descriptionDeferred, showTaskItemCounts],
+ );
+ const counters = [
+ {
+ kind: "subtasks",
+ counts: task.subtaskCounts,
+ Icon: ListTree,
+ label: t("tasks:subtasks.progress", {
+ completed: task.subtaskCounts?.completed ?? 0,
+ total: task.subtaskCounts?.total ?? 0,
+ }),
+ },
+ {
+ kind: "checklist",
+ counts: showTaskItemCounts ? checklist : undefined,
+ Icon: SquareCheck,
+ label: t("tasks:checklistProgress", {
+ completed: checklist?.completed ?? 0,
+ total: checklist?.total ?? 0,
+ }),
+ },
+ ];
+
+ return counters.map(({ kind, counts, Icon, label }) => {
+ if (!counts || counts.total === 0) return null;
+ const className = cn(
+ "inline-flex h-5.5 shrink-0 cursor-inherit items-center gap-1 rounded border border-border/70 bg-muted/50 px-2 py-1 text-[10px] font-medium tabular-nums text-muted-foreground",
+ counts.completed === counts.total &&
+ "border-success/20 bg-success/10 text-success-foreground",
+ );
+ const content = (
+ <>
+ <Icon className="size-3" aria-hidden="true" />
+ {counts.completed}/{counts.total}
+ </>
+ );
+
+ // Public cards are buttons already; their badges must remain plain text.
+ if (asText) {
+ return (
+ <span key={kind} className={className} title={label}>
+ <span className="sr-only">{label}</span>
+ <span aria-hidden="true" className="inline-flex items-center gap-1">
+ {content}
+ </span>
+ </span>
+ );
+ }
+
+ return (
+ <Tooltip key={kind}>
+ <TooltipTrigger aria-label={label} className={className}>
+ {content}
+ </TooltipTrigger>
+ <TooltipPopup>{label}</TooltipPopup>
+ </Tooltip>
+ );
+ });
+}
diff --git a/apps/web/src/components/task/task-subtasks.test.tsx b/apps/web/src/components/task/task-subtasks.test.tsx
index 221d8ed54..b45296f21 100644
--- a/apps/web/src/components/task/task-subtasks.test.tsx
+++ b/apps/web/src/components/task/task-subtasks.test.tsx
@@ -5,7 +5,10 @@ import {
screen,
waitFor,
} from "@testing-library/react";
+import type { ComponentProps } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type SubtaskRow from "./subtask-row";
+import { TaskProgressBadges } from "./task-progress-badges";
import TaskSubtasks from "./task-subtasks";
const mocks = vi.hoisted(() => ({
@@ -14,9 +17,16 @@ const mocks = vi.hoisted(() => ({
createTask: vi.fn(),
createRelation: vi.fn(),
getColumns: vi.fn(),
+ getRelations: vi.fn(),
+ fetchColumns: vi.fn(),
+ updateStatus: vi.fn(),
+ navigate: vi.fn(),
+ toastError: vi.fn(),
}));
-vi.mock("@tanstack/react-router", () => ({ useNavigate: () => vi.fn() }));
+vi.mock("@tanstack/react-router", () => ({
+ useNavigate: () => mocks.navigate,
+}));
vi.mock("framer-motion", () => ({
AnimatePresence: ({ children }: { children: unknown }) => children,
}));
@@ -33,13 +43,13 @@ vi.mock("@/hooks/mutations/task/use-delete-task", () => ({
useDeleteTask: () => ({ mutateAsync: vi.fn() }),
}));
vi.mock("@/hooks/mutations/task/use-update-task-status", () => ({
- useUpdateTaskStatus: () => ({ mutateAsync: vi.fn() }),
+ useUpdateTaskStatus: () => ({ mutateAsync: mocks.updateStatus }),
}));
vi.mock("@/hooks/queries/column/use-get-columns", () => ({
useGetColumns: () => mocks.getColumns(),
}));
vi.mock("@/hooks/queries/task-relation/use-get-task-relations", () => ({
- default: () => ({ data: [] }),
+ default: () => mocks.getRelations(),
}));
vi.mock("@/hooks/queries/workspace/use-active-workspace", () => ({
default: () => ({ data: { id: "workspace-1" } }),
@@ -56,9 +66,12 @@ vi.mock("@/hooks/use-workspace-permission", () => ({
canUpdateTasks: mocks.canUpdateTasks,
}),
}));
-vi.mock("@/lib/toast", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
+vi.mock("@/lib/toast", () => ({
+ toast: { error: mocks.toastError, success: vi.fn() },
+}));
beforeEach(() => {
+ mocks.getRelations.mockReturnValue({ data: [] });
mocks.canCreateTasks.mockReturnValue(true);
mocks.canUpdateTasks.mockReturnValue(true);
mocks.getColumns.mockReturnValue({
@@ -178,3 +191,121 @@ describe("TaskSubtasks", () => {
).not.toBeInTheDocument();
});
});
+
+vi.mock("@/fetchers/column/get-columns", () => ({
+ default: (projectId: string) => mocks.fetchColumns(projectId),
+}));
+vi.mock("./subtask-row", () => ({
+ default: ({
+ isCompleted,
+ onToggleComplete,
+ onNavigate,
+ }: ComponentProps<typeof SubtaskRow>) => (
+ <>
+ <button
+ type="button"
+ aria-label="Toggle child"
+ aria-pressed={isCompleted}
+ onClick={onToggleComplete}
+ >
+ Toggle
+ </button>
+ <button type="button" onClick={onNavigate}>
+ Open child
+ </button>
+ </>
+ ),
+}));
+function renderCrossProjectChild(isCompleted: boolean) {
+ mocks.getRelations.mockReturnValue({
+ data: [
+ {
+ id: "relation",
+ relationType: "subtask",
+ sourceTaskId: "parent",
+ targetTaskId: "child",
+ targetTask: {
+ id: "child",
+ projectId: "child-project",
+ title: "Child",
+ status: isCompleted ? "shipped" : "queued",
+ isCompleted,
+ },
+ },
+ ],
+ });
+ return render(
+ <>
+ <TaskProgressBadges
+ task={{
+ description: null,
+ subtaskCounts: { completed: isCompleted ? 1 : 0, total: 1 },
+ }}
+ asText
+ />
+ <TaskSubtasks
+ taskId="parent"
+ projectId="parent-project"
+ workspaceId="workspace-1"
+ parentStatus="to-do"
+ />
+ </>,
+ );
+}
+describe("cross-project subtask progress", () => {
+ it.each([true, false])(
+ "agrees with the board for completion=%s in a different workflow",
+ (completed) => {
+ renderCrossProjectChild(completed);
+ expect(screen.getAllByText(completed ? "1/1" : "0/1")).toHaveLength(2);
+ expect(
+ screen.getByRole("button", { name: "Toggle child" }),
+ ).toHaveAttribute("aria-pressed", String(completed));
+ },
+ );
+ it.each([true, false])(
+ "toggles completion=%s using the child's columns",
+ async (completed) => {
+ mocks.fetchColumns.mockResolvedValue([
+ { slug: "queued", isFinal: false },
+ { slug: "shipped", isFinal: true },
+ ]);
+ renderCrossProjectChild(completed);
+ fireEvent.click(screen.getByRole("button", { name: "Toggle child" }));
+ await waitFor(() =>
+ expect(mocks.updateStatus).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: "child",
+ projectId: "child-project",
+ status: completed ? "queued" : "shipped",
+ }),
+ ),
+ );
+ expect(mocks.fetchColumns).toHaveBeenCalledWith("child-project");
+ },
+ );
+ it("does not invent a status when the workflow has no final column", async () => {
+ mocks.fetchColumns.mockResolvedValue([{ slug: "queued", isFinal: false }]);
+ renderCrossProjectChild(false);
+ fireEvent.click(screen.getByRole("button", { name: "Toggle child" }));
+ await waitFor(() =>
+ expect(mocks.toastError).toHaveBeenCalledWith(
+ "tasks:subtasks.noCompletionColumn",
+ ),
+ );
+ expect(mocks.updateStatus).not.toHaveBeenCalled();
+ });
+ it("opens the child in its own project", () => {
+ renderCrossProjectChild(true);
+ fireEvent.click(screen.getByRole("button", { name: "Open child" }));
+ expect(mocks.navigate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: {
+ workspaceId: "workspace-1",
+ projectId: "child-project",
+ taskId: "child",
+ },
+ }),
+ );
+ });
+});
diff --git a/apps/web/src/components/task/task-subtasks.tsx b/apps/web/src/components/task/task-subtasks.tsx
index 59ba4c13c..b57e69ba1 100644
--- a/apps/web/src/components/task/task-subtasks.tsx
+++ b/apps/web/src/components/task/task-subtasks.tsx
@@ -20,6 +20,7 @@ import {
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Input } from "@/components/ui/input";
+import getColumns from "@/fetchers/column/get-columns";
import useCreateTask from "@/hooks/mutations/task/use-create-task";
import { useDeleteTask } from "@/hooks/mutations/task/use-delete-task";
import { useUpdateTaskStatus } from "@/hooks/mutations/task/use-update-task-status";
@@ -72,17 +73,9 @@ export default function TaskSubtasks({
const canEdit = canUpdateTasks();
const canCreate = canCreateTasks();
- // Map the completion checkbox to the project's actual column slugs (the API
- // validates status against columns). A subtask counts as completed when its
- // status is a final column.
- const doneSlug = columns.find((c) => c.isFinal)?.slug ?? "done";
const todoSlug = columns.find((c) => !c.isFinal)?.slug;
const canCreateSubtask =
parentStatus === "planned" || (!isLoadingColumns && Boolean(todoSlug));
- const isCompleted = (status: string) =>
- columns.length > 0
- ? (columns.find((c) => c.slug === status)?.isFinal ?? false)
- : status === "done";
const subtasks = relations
.filter(
@@ -94,9 +87,7 @@ export default function TaskSubtasks({
item.task !== null,
);
- const completedCount = subtasks.filter((s) =>
- isCompleted(s.task.status),
- ).length;
+ const completedCount = subtasks.filter((s) => s.task.isCompleted).length;
const totalCount = subtasks.length;
const hasSelection = selectedIds.size > 0;
@@ -145,10 +136,23 @@ export default function TaskSubtasks({
const handleToggleComplete = async (taskObj: Task) => {
try {
- await updateTaskStatus({
- ...taskObj,
- status: isCompleted(taskObj.status) ? (todoSlug ?? "to-do") : doneSlug,
+ // Fetch at activation so a cached workflow cannot send a stale status.
+ const taskColumns = await queryClient.fetchQuery({
+ queryKey: ["columns", taskObj.projectId],
+ queryFn: () => getColumns(taskObj.projectId),
+ staleTime: 0,
});
+ const completed = taskColumns.some(
+ (column) => column.slug === taskObj.status && column.isFinal,
+ );
+ const nextColumn = taskColumns.find(
+ (column) => column.isFinal !== completed,
+ );
+ if (!nextColumn) {
+ toast.error(t("tasks:subtasks.noCompletionColumn"));
+ return;
+ }
+ await updateTaskStatus({ ...taskObj, status: nextColumn.slug });
} catch (error) {
toast.error(
error instanceof Error
@@ -224,7 +228,7 @@ export default function TaskSubtasks({
to: "/dashboard/workspace/$workspaceId/project/$projectId/task/$taskId",
params: {
workspaceId,
- projectId,
+ projectId: subtasks[focusedIndex].task.projectId,
taskId: subtasks[focusedIndex].task.id,
},
});
@@ -254,7 +258,6 @@ export default function TaskSubtasks({
clearSelection,
navigate,
workspaceId,
- projectId,
toggleSelection,
]);
@@ -373,11 +376,11 @@ export default function TaskSubtasks({
key={subtask.task.id}
task={taskObj}
tasks={getTargetTasks(taskObj)}
- projectId={projectId}
+ projectId={subtask.task.projectId}
workspaceId={workspace?.id ?? workspaceId}
isSelected={isSelected}
isFocused={focusedIndex === index}
- isCompleted={isCompleted(subtask.task.status)}
+ isCompleted={subtask.task.isCompleted}
canEdit={canEdit}
selectionRadius={getSelectionRadius(index, isSelected)}
assignee={getAssignee(subtask.task.userId)}
@@ -387,7 +390,7 @@ export default function TaskSubtasks({
to: "/dashboard/workspace/$workspaceId/project/$projectId/task/$taskId",
params: {
workspaceId,
- projectId,
+ projectId: subtask.task.projectId,
taskId: subtask.task.id,
},
})
diff --git a/apps/web/src/hooks/mutations/task-relation/invalidate-relation-task-project.test.ts b/apps/web/src/hooks/mutations/task-relation/invalidate-relation-task-project.test.ts
new file mode 100644
index 000000000..51f994ac5
--- /dev/null
+++ b/apps/web/src/hooks/mutations/task-relation/invalidate-relation-task-project.test.ts
@@ -0,0 +1,29 @@
+import { QueryClient } from "@tanstack/react-query";
+import { describe, expect, it } from "vitest";
+import { invalidateRelationTaskProject } from "./invalidate-relation-task-project";
+
+describe("invalidateRelationTaskProject", () => {
+ it.each(["columns", "plannedTasks", "archivedTasks"])(
+ "refreshes the parent in %s without invalidating unrelated boards",
+ async (location) => {
+ const client = new QueryClient();
+ const parent = { id: "parent" };
+ client.setQueryData(["tasks", "parent-project"], {
+ columns: location === "columns" ? [{ tasks: [parent] }] : [],
+ plannedTasks: location === "plannedTasks" ? [parent] : [],
+ archivedTasks: location === "archivedTasks" ? [parent] : [],
+ });
+ client.setQueryData(["tasks", "unrelated-project"], {
+ columns: [{ tasks: [{ id: "other" }] }],
+ });
+ await invalidateRelationTaskProject(client, "parent");
+ expect(
+ client.getQueryState(["tasks", "parent-project"])?.isInvalidated,
+ ).toBe(true);
+ expect(
+ client.getQueryState(["tasks", "unrelated-project"])?.isInvalidated,
+ ).toBe(false);
+ client.clear();
+ },
+ );
+});
diff --git a/apps/web/src/hooks/mutations/task-relation/invalidate-relation-task-project.ts b/apps/web/src/hooks/mutations/task-relation/invalidate-relation-task-project.ts
new file mode 100644
index 000000000..442bc56c1
--- /dev/null
+++ b/apps/web/src/hooks/mutations/task-relation/invalidate-relation-task-project.ts
@@ -0,0 +1,22 @@
+import type { QueryClient } from "@tanstack/react-query";
+import type { ProjectWithTasks } from "@/types/project";
+
+/** Refresh only cached boards that contain the relation's parent task. */
+export function invalidateRelationTaskProject(
+ queryClient: QueryClient,
+ taskId: string,
+) {
+ return queryClient.invalidateQueries({
+ queryKey: ["tasks"],
+ predicate: ({ state }) => {
+ const project = state.data as ProjectWithTasks | undefined;
+ return Boolean(
+ project?.columns.some((column) =>
+ column.tasks.some((task) => task.id === taskId),
+ ) ||
+ project?.plannedTasks?.some((task) => task.id === taskId) ||
+ project?.archivedTasks?.some((task) => task.id === taskId),
+ );
+ },
+ });
+}
diff --git a/apps/web/src/hooks/mutations/task-relation/use-create-task-relation.ts b/apps/web/src/hooks/mutations/task-relation/use-create-task-relation.ts
index 703a2fd91..87aa20cde 100644
--- a/apps/web/src/hooks/mutations/task-relation/use-create-task-relation.ts
+++ b/apps/web/src/hooks/mutations/task-relation/use-create-task-relation.ts
@@ -1,12 +1,15 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import createTaskRelation from "@/fetchers/task-relation/create-task-relation";
+import { invalidateRelationTaskProject } from "./invalidate-relation-task-project";
+
function useCreateTaskRelation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: createTaskRelation,
onSuccess: (_, variables) => {
+ void invalidateRelationTaskProject(queryClient, variables.sourceTaskId);
queryClient.invalidateQueries({
queryKey: ["task-relations", variables.sourceTaskId],
});
diff --git a/apps/web/src/hooks/mutations/task-relation/use-delete-task-relation.ts b/apps/web/src/hooks/mutations/task-relation/use-delete-task-relation.ts
index 8f59ac4f8..cab450d2a 100644
--- a/apps/web/src/hooks/mutations/task-relation/use-delete-task-relation.ts
+++ b/apps/web/src/hooks/mutations/task-relation/use-delete-task-relation.ts
@@ -1,12 +1,15 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import deleteTaskRelation from "@/fetchers/task-relation/delete-task-relation";
+import { invalidateRelationTaskProject } from "./invalidate-relation-task-project";
+
function useDeleteTaskRelation(taskId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: deleteTaskRelation,
- onSuccess: () => {
+ onSuccess: (relation) => {
+ void invalidateRelationTaskProject(queryClient, relation.sourceTaskId);
queryClient.invalidateQueries({
queryKey: ["task-relations", taskId],
});
diff --git a/apps/web/src/hooks/queries/project/use-get-public-project.ts b/apps/web/src/hooks/queries/project/use-get-public-project.ts
index 182c06a79..3327c4f3a 100644
--- a/apps/web/src/hooks/queries/project/use-get-public-project.ts
+++ b/apps/web/src/hooks/queries/project/use-get-public-project.ts
@@ -5,6 +5,7 @@ function useGetPublicProject(id: string) {
return useQuery({
queryKey: ["public-project", id],
queryFn: ({ signal }) => getPublicProject({ id }, signal),
+ refetchOnMount: true,
});
}
diff --git a/apps/web/src/hooks/queries/task/use-get-tasks.test.tsx b/apps/web/src/hooks/queries/task/use-get-tasks.test.tsx
new file mode 100644
index 000000000..9d25b2373
--- /dev/null
+++ b/apps/web/src/hooks/queries/task/use-get-tasks.test.tsx
@@ -0,0 +1,86 @@
+import { QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, renderHook, waitFor } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import queryClient from "@/query-client";
+import useGetPublicProject from "../project/use-get-public-project";
+import { useGetTasks } from "./use-get-tasks";
+
+const getTasks = vi.hoisted(() => vi.fn());
+const getPublicProject = vi.hoisted(() => vi.fn());
+vi.mock("@/fetchers/task/get-tasks", () => ({ default: getTasks }));
+vi.mock("@/fetchers/project/get-public-project", () => ({
+ default: getPublicProject,
+}));
+
+function Wrapper({ children }: { children: ReactNode }) {
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+}
+
+afterEach(() => {
+ cleanup();
+ queryClient.clear();
+ getTasks.mockReset();
+ getPublicProject.mockReset();
+});
+
+describe("useGetTasks", () => {
+ it("refreshes a cached public board when revisited", async () => {
+ queryClient.setQueryData(["public-project", "public-parent"], {
+ columns: [{ tasks: [{ subtaskCounts: { completed: 0, total: 1 } }] }],
+ });
+ const updated = {
+ columns: [{ tasks: [{ subtaskCounts: { completed: 1, total: 1 } }] }],
+ };
+ getPublicProject.mockResolvedValue(updated);
+ const { result } = renderHook(() => useGetPublicProject("public-parent"), {
+ wrapper: Wrapper,
+ });
+ await waitFor(() => expect(result.current.data).toEqual(updated));
+ expect(getPublicProject).toHaveBeenCalledWith(
+ { id: "public-parent" },
+ expect.any(AbortSignal),
+ );
+ });
+
+ it("refreshes cached parent progress on return without a parent socket", async () => {
+ const parent = {
+ id: "parent-project",
+ columns: [
+ {
+ tasks: [{ id: "parent", subtaskCounts: { completed: 0, total: 1 } }],
+ },
+ ],
+ };
+ getTasks.mockResolvedValue(parent);
+ const firstVisit = renderHook(() => useGetTasks("parent-project"), {
+ wrapper: Wrapper,
+ });
+ await waitFor(() => expect(firstVisit.result.current.data).toEqual(parent));
+ firstVisit.unmount();
+
+ // Deleting the child project changes the server while the parent is inactive.
+ // No socket event or local invalidation reaches this cached board.
+ const updatedParent = {
+ ...parent,
+ columns: [
+ {
+ tasks: [{ id: "parent", subtaskCounts: { completed: 0, total: 0 } }],
+ },
+ ],
+ };
+ getTasks.mockResolvedValue(updatedParent);
+ expect(queryClient.getQueryData(["tasks", "parent-project"])).toEqual(
+ parent,
+ );
+ const returnVisit = renderHook(() => useGetTasks("parent-project"), {
+ wrapper: Wrapper,
+ });
+ await waitFor(() =>
+ expect(returnVisit.result.current.data).toEqual(updatedParent),
+ );
+ expect(getTasks).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/web/src/hooks/queries/task/use-get-tasks.ts b/apps/web/src/hooks/queries/task/use-get-tasks.ts
index 370cd2453..4861dc978 100644
--- a/apps/web/src/hooks/queries/task/use-get-tasks.ts
+++ b/apps/web/src/hooks/queries/task/use-get-tasks.ts
@@ -6,6 +6,7 @@ export function useGetTasks(projectId: string) {
return useQuery({
queryKey: ["tasks", projectId],
queryFn: ({ signal }) => getTasks(projectId, signal),
+ refetchOnMount: true,
refetchInterval: (query) =>
isUnauthorizedError(query.state.error) ? false : 30000,
enabled: !!projectId,
diff --git a/apps/web/src/types/task/index.ts b/apps/web/src/types/task/index.ts
index b8797a0e7..2bcdaa526 100644
--- a/apps/web/src/types/task/index.ts
+++ b/apps/web/src/types/task/index.ts
@@ -39,6 +39,7 @@ type Task = {
assigneeImage?: string | null;
projectId: string;
columnId?: string | null;
+ subtaskCounts?: { completed: number; total: number };
labels?: TaskLabel[];
externalLinks?: TaskExternalLink[];
customFieldValues?: TaskCustomFieldValue[];
diff --git a/i18n/az-AZ.json b/i18n/az-AZ.json
index 07efcea7b..9873b66f8 100644
--- a/i18n/az-AZ.json
+++ b/i18n/az-AZ.json
@@ -2096,7 +2096,9 @@
"deleteDialogTitle": "Tapşırıq silinsin?",
"deleteDialogDescription": "Bu, tapşırığı və bütün məlumatlarını həmişəlik siləcək. Bu əməliyyatı geri qaytara bilməzsiniz.",
"deleteAction": "Tapşırığı sil",
- "completeAria": "Alt tapşırığı tamamlanmış kimi işarələ"
+ "completeAria": "Alt tapşırığı tamamlanmış kimi işarələ",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask.",
+ "progress": "{{completed}} of {{total}} subtasks completed"
},
"properties": {
"title": "Xüsusiyyətlər",
@@ -2370,6 +2372,7 @@
"success": "Task duplicated successfully",
"titleSuffix": "{{title}} (copy)"
},
+ "checklistProgress": "{{completed}} of {{total}} checklist items completed",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/de-DE.json b/i18n/de-DE.json
index d7231587a..639d3f59e 100644
--- a/i18n/de-DE.json
+++ b/i18n/de-DE.json
@@ -2096,7 +2096,9 @@
"deleteDialogTitle": "Aufgabe löschen?",
"deleteDialogDescription": "Dadurch wird die Aufgabe und alle zugehörigen Daten dauerhaft entfernt. Diese Aktion kann nicht rückgängig gemacht werden.",
"deleteAction": "Aufgabe löschen",
- "completeAria": "Teilaufgabe als erledigt markieren"
+ "completeAria": "Teilaufgabe als erledigt markieren",
+ "progress": "{{completed}} von {{total}} Unteraufgaben abgeschlossen",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "Eigenschaften",
@@ -2370,6 +2372,7 @@
"descriptionRetry": "Erneut versuchen",
"descriptionLoading": "Beschreibung wird geladen…",
"descriptionLoadError": "Die Beschreibung konnte nicht geladen werden. Versuche es erneut, um die aktuelle Version zu laden.",
+ "checklistProgress": "{{completed}} von {{total}} Checklistenpunkten abgeschlossen",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/el-GR.json b/i18n/el-GR.json
index d9ac6574c..dcd3f909a 100644
--- a/i18n/el-GR.json
+++ b/i18n/el-GR.json
@@ -2096,7 +2096,9 @@
"deleteDialogTitle": "Διαγραφή εργασίας;",
"deleteDialogDescription": "Αυτό θα αφαιρέσει οριστικά την εργασία και όλα τα δεδομένα της. Δεν μπορείτε να αναιρέσετε αυτήν την ενέργεια.",
"deleteAction": "Διαγραφή εργασίας",
- "completeAria": "Επισήμανση υποεργασίας ως ολοκληρωμένης"
+ "completeAria": "Επισήμανση υποεργασίας ως ολοκληρωμένης",
+ "progress": "Ολοκληρώθηκαν {{completed}} από {{total}} υποεργασίες",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "Ιδιότητες",
@@ -2370,6 +2372,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "Ολοκληρώθηκαν {{completed}} από {{total}} στοιχεία λίστας ελέγχου",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/en-US.json b/i18n/en-US.json
index 972c57260..a8e785f90 100644
--- a/i18n/en-US.json
+++ b/i18n/en-US.json
@@ -1919,6 +1919,7 @@
}
},
"tasks": {
+ "checklistProgress": "{{completed}} of {{total}} checklist items completed",
"title": "Tasks",
"status": {
"label": "Status",
@@ -2086,6 +2087,8 @@
}
},
"subtasks": {
+ "progress": "{{completed}} of {{total}} subtasks completed",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask.",
"title": "Sub-tasks",
"inputPlaceholder": "Subtask title...",
"addAction": "Add",
diff --git a/i18n/es-ES.json b/i18n/es-ES.json
index d42b3db5e..5af0df757 100644
--- a/i18n/es-ES.json
+++ b/i18n/es-ES.json
@@ -2103,7 +2103,9 @@
"deleteDialogTitle": "¿Eliminar tarea?",
"deleteDialogDescription": "Esto eliminará permanentemente la tarea y sus datos. Esta acción no puede deshacerse.",
"deleteAction": "Eliminar tarea",
- "completeAria": "Marcar subtarea como completada"
+ "completeAria": "Marcar subtarea como completada",
+ "progress": "{{completed}} de {{total}} subtareas completadas",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "Propiedades",
@@ -2378,6 +2380,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "{{completed}} de {{total}} elementos de la lista completados",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/fr-FR.json b/i18n/fr-FR.json
index 364e23327..a83eb959f 100644
--- a/i18n/fr-FR.json
+++ b/i18n/fr-FR.json
@@ -2103,7 +2103,9 @@
"deleteDialogTitle": "Supprimer la tâche ?",
"deleteDialogDescription": "Cela supprimera définitivement la tâche et toutes ses données. Vous ne pouvez pas annuler cette action.",
"deleteAction": "Supprimer la tâche",
- "completeAria": "Marquer la sous-tâche comme terminée"
+ "completeAria": "Marquer la sous-tâche comme terminée",
+ "progress": "{{completed}} sous-tâches terminées sur {{total}}",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "Propriétés",
@@ -2378,6 +2380,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "{{completed}} éléments de la liste terminés sur {{total}}",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/hi-IN.json b/i18n/hi-IN.json
index 9e596a734..930acfff3 100644
--- a/i18n/hi-IN.json
+++ b/i18n/hi-IN.json
@@ -2096,7 +2096,9 @@
"deleteDialogTitle": "कार्य हटाएँ?",
"deleteDialogDescription": "यह कार्य और इसका सभी डेटा स्थायी रूप से हटा दिया जाएगा। यह कार्रवाई पूर्ववत नहीं की जा सकती।",
"deleteAction": "कार्य हटाएँ",
- "completeAria": "उप-कार्य को पूर्ण चिह्नित करें"
+ "completeAria": "उप-कार्य को पूर्ण चिह्नित करें",
+ "progress": "{{total}} में से {{completed}} उपकार्य पूरे हुए",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "गुण",
@@ -2370,6 +2372,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "चेकलिस्ट के {{total}} में से {{completed}} आइटम पूरे हुए",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/id-ID.json b/i18n/id-ID.json
index 8729e8462..2da5fd468 100644
--- a/i18n/id-ID.json
+++ b/i18n/id-ID.json
@@ -2089,7 +2089,9 @@
"deleteDialogTitle": "Hapus Tugas?",
"deleteDialogDescription": "Ini akan menghapus tugas dan semua datanya secara permanen. Anda tidak dapat membatalkan tindakan ini.",
"deleteAction": "Hapus Tugas",
- "completeAria": "Tandai subtugas selesai"
+ "completeAria": "Tandai subtugas selesai",
+ "progress": "{{completed}} dari {{total}} subtugas selesai",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "Properti",
@@ -2362,6 +2364,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "{{completed}} dari {{total}} item daftar periksa selesai",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/it-IT.json b/i18n/it-IT.json
index 06a91bf68..078137cc0 100644
--- a/i18n/it-IT.json
+++ b/i18n/it-IT.json
@@ -2103,7 +2103,9 @@
"deleteDialogTitle": "Eliminare l'Attività?",
"deleteDialogDescription": "Questo rimuoverà permanentemente l'attività e tutti i suoi dati. Non puoi annullare questa azione.",
"deleteAction": "Elimina Attività",
- "completeAria": "Segna sotto-attività come completata"
+ "completeAria": "Segna sotto-attività come completata",
+ "progress": "{{completed}} di {{total}} sottoattività completate",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "Proprietà",
@@ -2378,6 +2380,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "{{completed}} di {{total}} elementi della checklist completati",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/ja-JP.json b/i18n/ja-JP.json
index 05eace695..90f4c521a 100644
--- a/i18n/ja-JP.json
+++ b/i18n/ja-JP.json
@@ -2089,7 +2089,9 @@
"deleteDialogTitle": "タスクを削除しますか?",
"deleteDialogDescription": "これにより、タスクとそのすべてのデータが完全に削除されます。この操作は取り消せません。",
"deleteAction": "タスクを削除",
- "completeAria": "サブタスクを完了にする"
+ "completeAria": "サブタスクを完了にする",
+ "progress": "サブタスク {{total}} 件中 {{completed}} 件完了",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "プロパティ",
@@ -2362,6 +2364,7 @@
"success": "Task duplicated successfully",
"titleSuffix": "{{title}} (copy)"
},
+ "checklistProgress": "チェックリスト {{total}} 項目中 {{completed}} 項目完了",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/ko-KR.json b/i18n/ko-KR.json
index 0ba6c5d2c..485fb5a86 100644
--- a/i18n/ko-KR.json
+++ b/i18n/ko-KR.json
@@ -2089,7 +2089,9 @@
"deleteDialogTitle": "작업을 삭제하시겠습니까?",
"deleteDialogDescription": "작업과 모든 데이터가 영구적으로 제거됩니다. 이 작업은 취소할 수 없습니다.",
"deleteAction": "작업 삭제",
- "completeAria": "하위 작업을 완료로 표시"
+ "completeAria": "하위 작업을 완료로 표시",
+ "progress": "하위 작업 {{total}}개 중 {{completed}}개 완료",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "속성",
@@ -2362,6 +2364,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "체크리스트 항목 {{total}}개 중 {{completed}}개 완료",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/mk-MK.json b/i18n/mk-MK.json
index 5c4eca955..d32122dff 100644
--- a/i18n/mk-MK.json
+++ b/i18n/mk-MK.json
@@ -2096,7 +2096,9 @@
"deleteDialogTitle": "Избриши задача?",
"deleteDialogDescription": "Ова трајно ќе ја отстрани задачата и сите нејзини податоци. Не можеш да ја вратиш оваа акција.",
"deleteAction": "Избриши задача",
- "completeAria": "Означи ја подзадачата како завршена"
+ "completeAria": "Означи ја подзадачата како завршена",
+ "progress": "Завршени се {{completed}} од {{total}} подзадачи",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "Својства",
@@ -2370,6 +2372,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "Завршени се {{completed}} од {{total}} ставки од списокот",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/nl-NL.json b/i18n/nl-NL.json
index 1e12e6f98..a4e8f7417 100644
--- a/i18n/nl-NL.json
+++ b/i18n/nl-NL.json
@@ -2096,7 +2096,9 @@
"deleteDialogTitle": "Taak verwijderen?",
"deleteDialogDescription": "Dit zal de taak en alle data permanent verwijderen. Dit kan niet ongedaan worden gemaakt.",
"deleteAction": "Taak verwijderen",
- "completeAria": "Markeer subtaak als voltooid"
+ "completeAria": "Markeer subtaak als voltooid",
+ "progress": "{{completed}} van {{total}} subtaken voltooid",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "Eigenschappen",
@@ -2370,6 +2372,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "{{completed}} van {{total}} checklistitems voltooid",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/pl-PL.json b/i18n/pl-PL.json
index 8806bd7b3..8003c6a09 100644
--- a/i18n/pl-PL.json
+++ b/i18n/pl-PL.json
@@ -2548,7 +2548,9 @@
"deleteSuccess": "Zadanie usunięto pomyślnie",
"empty": "Brak podzadań",
"inputPlaceholder": "Tytuł podzadania...",
- "title": "Podzadania"
+ "title": "Podzadania",
+ "progress": "Ukończone podzadania: {{completed}} z {{total}}",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"update": {
"error": "Nie udało się zaktualizować zadania",
@@ -2568,6 +2570,7 @@
"success": "Task duplicated successfully",
"titleSuffix": "{{title}} (copy)"
},
+ "checklistProgress": "Ukończone elementy listy kontrolnej: {{completed}} z {{total}}",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/pt-BR.json b/i18n/pt-BR.json
index 32b76462a..56f694e44 100644
--- a/i18n/pt-BR.json
+++ b/i18n/pt-BR.json
@@ -2103,7 +2103,9 @@
"deleteDialogTitle": "Excluir tarefa?",
"deleteDialogDescription": "Isso removerá permanentemente a tarefa e todos os seus dados. Você não pode desfazer esta ação.",
"deleteAction": "Excluir tarefa",
- "completeAria": "Marcar subtarefa como concluída"
+ "completeAria": "Marcar subtarefa como concluída",
+ "progress": "{{completed}} de {{total}} subtarefas concluídas",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "Propriedades",
@@ -2378,6 +2380,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "{{completed}} de {{total}} itens da lista concluídos",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/ru-RU.json b/i18n/ru-RU.json
index d7f24a5b9..f86e9b201 100644
--- a/i18n/ru-RU.json
+++ b/i18n/ru-RU.json
@@ -2118,7 +2118,9 @@
"deleteDialogTitle": "Удалить задачу?",
"deleteDialogDescription": "Задача и все её данные будут безвозвратно удалены. Это действие нельзя отменить.",
"deleteAction": "Удалить задачу",
- "completeAria": "Отметить подзадачу выполненной"
+ "completeAria": "Отметить подзадачу выполненной",
+ "progress": "Выполнено подзадач: {{completed}} из {{total}}",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "Свойства",
@@ -2442,6 +2444,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "Выполнено пунктов списка: {{completed}} из {{total}}",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/schema.json b/i18n/schema.json
index 3da74af09..c2f0082c2 100644
--- a/i18n/schema.json
+++ b/i18n/schema.json
@@ -7755,6 +7755,9 @@
"type": "object",
"additionalProperties": false,
"properties": {
+ "checklistProgress": {
+ "type": "string"
+ },
"title": {
"type": "string"
},
@@ -8406,6 +8409,12 @@
"type": "object",
"additionalProperties": false,
"properties": {
+ "progress": {
+ "type": "string"
+ },
+ "noCompletionColumn": {
+ "type": "string"
+ },
"title": {
"type": "string"
},
@@ -8441,6 +8450,8 @@
}
},
"required": [
+ "progress",
+ "noCompletionColumn",
"title",
"inputPlaceholder",
"addAction",
@@ -9748,6 +9759,7 @@
}
},
"required": [
+ "checklistProgress",
"title",
"status",
"priority",
diff --git a/i18n/tr-TR.json b/i18n/tr-TR.json
index c9595bc0b..8586f0583 100644
--- a/i18n/tr-TR.json
+++ b/i18n/tr-TR.json
@@ -2096,7 +2096,9 @@
"deleteDialogTitle": "Talep Silinsin mi?",
"deleteDialogDescription": "Bu, talebi ve tüm verilerini kalıcı olarak kaldıracak. Bu işlemi geri alamazsınız.",
"deleteAction": "Talebi Sil",
- "completeAria": "Alt talebi tamamlandı olarak işaretle"
+ "completeAria": "Alt talebi tamamlandı olarak işaretle",
+ "progress": "{{total}} alt görevin {{completed}} tanesi tamamlandı",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "Özellikler",
@@ -2370,6 +2372,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "{{total}} kontrol listesi öğesinin {{completed}} tanesi tamamlandı",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/uk-UA.json b/i18n/uk-UA.json
index a322aa3be..7df706193 100644
--- a/i18n/uk-UA.json
+++ b/i18n/uk-UA.json
@@ -2110,7 +2110,9 @@
"deleteDialogTitle": "Видалити завдання?",
"deleteDialogDescription": "Це назавжди видалить завдання та всі його дані. Цю дію неможливо скасувати.",
"deleteAction": "Видалити завдання",
- "completeAria": "Позначити підзавдання виконаним"
+ "completeAria": "Позначити підзавдання виконаним",
+ "progress": "Виконано підзавдань: {{completed}} із {{total}}",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "Властивості",
@@ -2386,6 +2388,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "Виконано пунктів списку: {{completed}} із {{total}}",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/vi-VN.json b/i18n/vi-VN.json
index 2cb9ce8b9..d2b1cdf2f 100644
--- a/i18n/vi-VN.json
+++ b/i18n/vi-VN.json
@@ -2089,7 +2089,9 @@
"deleteDialogTitle": "Xóa công việc?",
"deleteDialogDescription": "Thao tác này sẽ xóa vĩnh viễn công việc và toàn bộ dữ liệu của nó. Bạn không thể hoàn tác hành động này.",
"deleteAction": "Xóa công việc",
- "completeAria": "Đánh dấu hoàn thành công việc con"
+ "completeAria": "Đánh dấu hoàn thành công việc con",
+ "progress": "Đã hoàn thành {{completed}} trên {{total}} công việc con",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "Thuộc tính",
@@ -2362,6 +2364,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "Đã hoàn thành {{completed}} trên {{total}} mục trong danh sách kiểm tra",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/i18n/zh-CN.json b/i18n/zh-CN.json
index 9bda63fbd..d6bab2e26 100644
--- a/i18n/zh-CN.json
+++ b/i18n/zh-CN.json
@@ -2089,7 +2089,9 @@
"deleteDialogTitle": "删除任务?",
"deleteDialogDescription": "这将永久删除任务及其所有数据,此操作不可撤销。",
"deleteAction": "删除任务",
- "completeAria": "将子任务标记为完成"
+ "completeAria": "将子任务标记为完成",
+ "progress": "已完成 {{completed}}/{{total}} 个子任务",
+ "noCompletionColumn": "This project has no matching column for completing or reopening this subtask."
},
"properties": {
"title": "属性",
@@ -2362,6 +2364,7 @@
"descriptionRetry": "Retry",
"descriptionLoading": "Loading description…",
"descriptionLoadError": "The description could not be loaded. Retry to load the current version.",
+ "checklistProgress": "已完成 {{completed}}/{{total}} 个清单项",
"customFields": {
"ariaLabel": "Custom fields"
}
diff --git a/tests/api-integration/subtask-counts.test.ts b/tests/api-integration/subtask-counts.test.ts
new file mode 100644
index 000000000..85abd13ab
--- /dev/null
+++ b/tests/api-integration/subtask-counts.test.ts
@@ -0,0 +1,521 @@
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import updateColumn from "../../apps/api/src/column/controllers/update-column";
+import db, { schema } from "../../apps/api/src/database";
+import { eventContext } from "../../apps/api/src/events";
+import { createApp } from "../../apps/api/src/index";
+import deleteProject from "../../apps/api/src/project/controllers/delete-project";
+import { getPublicProject } from "../../apps/api/src/project/controllers/get-public-project";
+import deleteTask from "../../apps/api/src/task/controllers/delete-task";
+import getTasks from "../../apps/api/src/task/controllers/get-tasks";
+import moveTask from "../../apps/api/src/task/controllers/move-task";
+import updateTaskStatus from "../../apps/api/src/task/controllers/update-task-status";
+import * as subtaskParents from "../../apps/api/src/task/get-subtask-parent-projects";
+import getTaskRelations from "../../apps/api/src/task-relation/controllers/get-task-relations";
+import {
+ addConnection,
+ initializeWebSocketAdapter,
+ removeConnection,
+ shutdownWebSocketAdapter,
+} from "../../apps/api/src/ws";
+import { mockAuthenticatedSession } from "./helpers/auth";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+
+async function addTask(projectId: string, status = "to-do") {
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId,
+ title: "Task",
+ status,
+ number: null,
+ })
+ .returning();
+ return task;
+}
+
+async function relate(
+ sourceTaskId: string,
+ targetTaskId: string,
+ relationType = "subtask",
+) {
+ const [relation] = await db
+ .insert(schema.taskRelationTable)
+ .values({
+ sourceTaskId,
+ targetTaskId,
+ relationType,
+ })
+ .returning();
+ return relation;
+}
+
+async function countsFor(projectId: string, taskId: string) {
+ const { data } = await getTasks(projectId);
+ return [
+ ...data.columns.flatMap((c) => c.tasks),
+ ...data.plannedTasks,
+ ...data.archivedTasks,
+ ].find((task) => task.id === taskId)?.subtaskCounts;
+}
+
+describe("API integration: subtask counters", () => {
+ beforeEach(resetTestDatabase);
+
+ it("counts direct children across filters and pagination, excluding other relations and incoming parents", async () => {
+ const member = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const parent = await addTask(project.id);
+ const child = await addTask(project.id, "done");
+ const grandchild = await addTask(project.id, "done");
+ const other = await addTask(project.id, "in-progress");
+ await relate(parent.id, child.id);
+ await relate(child.id, grandchild.id);
+ await relate(parent.id, other.id, "blocks");
+ await relate(other.id, parent.id);
+ await db
+ .update(schema.taskTable)
+ .set({ description: "- [x] Checklist\n- [ ] Checklist" })
+ .where(eq(schema.taskTable.id, parent.id));
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+ const response = await app.request(
+ `/api/task/tasks/${project.id}?status=to-do&limit=1&page=1`,
+ );
+ expect(response.status).toBe(200);
+ const body = await response.json();
+ const tasks = body.data.columns.flatMap(
+ (column: { tasks: unknown[] }) => column.tasks,
+ );
+ expect(tasks).toHaveLength(1);
+ expect(tasks[0]).toMatchObject({
+ id: parent.id,
+ subtaskCounts: { completed: 1, total: 1 },
+ });
+ });
+
+ it("uses the child's final columns across projects and includes planned and archived children", async () => {
+ const member = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const other = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ await db
+ .update(schema.columnTable)
+ .set({ isFinal: false })
+ .where(eq(schema.columnTable.id, other.columns.done.id));
+ await db.insert(schema.columnTable).values({
+ projectId: other.project.id,
+ name: "Shipped",
+ slug: "shipped",
+ isFinal: true,
+ });
+ const parent = await addTask(project.id, "planned");
+ for (const status of ["shipped", "done", "planned", "archived"]) {
+ const child = await addTask(other.project.id, status);
+ await relate(parent.id, child.id);
+ }
+ expect(await countsFor(project.id, parent.id)).toEqual({
+ completed: 1,
+ total: 4,
+ });
+ const relations = await getTaskRelations(parent.id, member.workspace.id);
+ expect(
+ relations.filter((relation) => relation.targetTask?.isCompleted),
+ ).toHaveLength(1);
+ expect(
+ relations.find((relation) => relation.targetTask?.isCompleted)?.targetTask
+ ?.status,
+ ).toBe("shipped");
+ await db
+ .update(schema.taskTable)
+ .set({ status: "archived" })
+ .where(eq(schema.taskTable.id, parent.id));
+ expect(await countsFor(project.id, parent.id)).toEqual({
+ completed: 1,
+ total: 4,
+ });
+ });
+
+ it("returns zero for empty tasks and reflects completion, reopening, unlinking, and deletion", async () => {
+ const member = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ expect(
+ (await getTasks(project.id)).data.columns.every(
+ (c) => c.tasks.length === 0,
+ ),
+ ).toBe(true);
+ const parent = await addTask(project.id);
+ const child = await addTask(project.id);
+ expect(await countsFor(project.id, parent.id)).toEqual({
+ completed: 0,
+ total: 0,
+ });
+ const relation = await relate(parent.id, child.id);
+ expect(await countsFor(project.id, parent.id)).toEqual({
+ completed: 0,
+ total: 1,
+ });
+ await updateTaskStatus({
+ id: child.id,
+ status: "done",
+ currentUserId: member.user.id,
+ });
+ expect(await countsFor(project.id, parent.id)).toEqual({
+ completed: 1,
+ total: 1,
+ });
+ await updateTaskStatus({
+ id: child.id,
+ status: "to-do",
+ currentUserId: member.user.id,
+ });
+ expect(await countsFor(project.id, parent.id)).toEqual({
+ completed: 0,
+ total: 1,
+ });
+ await db
+ .delete(schema.taskRelationTable)
+ .where(eq(schema.taskRelationTable.id, relation.id));
+ expect(await countsFor(project.id, parent.id)).toEqual({
+ completed: 0,
+ total: 0,
+ });
+ await relate(parent.id, child.id);
+ await deleteTask(child.id, member.user.id);
+ expect(await countsFor(project.id, parent.id)).toEqual({
+ completed: 0,
+ total: 0,
+ });
+ });
+
+ it("excludes cross-workspace relations and private-project counts on public boards", async () => {
+ const member = await createWorkspaceMember();
+ const stranger = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const privateProject = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const foreignProject = await createProjectFixture({
+ workspaceId: stranger.workspace.id,
+ });
+ await db
+ .update(schema.projectTable)
+ .set({ isPublic: true })
+ .where(eq(schema.projectTable.id, project.id));
+ const parent = await addTask(project.id);
+ const publicChild = await addTask(project.id, "done");
+ const privateChild = await addTask(privateProject.project.id, "done");
+ const foreignChild = await addTask(foreignProject.project.id, "done");
+ await relate(parent.id, publicChild.id);
+ await relate(parent.id, privateChild.id);
+ // Simulate a legacy malformed relation; it must not cross the workspace boundary.
+ await relate(parent.id, foreignChild.id);
+ expect(await countsFor(project.id, parent.id)).toEqual({
+ completed: 2,
+ total: 2,
+ });
+ const publicBoard = await getPublicProject(project.id);
+ expect(
+ publicBoard.columns
+ .flatMap((c) => c.tasks)
+ .find((t) => t.id === parent.id)?.subtaskCounts,
+ ).toEqual({ completed: 1, total: 1 });
+ });
+ it("refreshes a parent board when a child in another project is completed or deleted", async () => {
+ const member = await createWorkspaceMember();
+ const parentProject = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const childProject = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const parent = await addTask(parentProject.project.id);
+ const child = await addTask(childProject.project.id);
+ await relate(parent.id, child.id);
+ await initializeWebSocketAdapter();
+ const send = vi.fn();
+ const connection = addConnection(
+ parentProject.project.id,
+ { send } as never,
+ member.user.id,
+ "other-window",
+ member.workspace.id,
+ );
+ try {
+ await eventContext.run({ initiatorId: "other-window" }, () =>
+ updateTaskStatus({
+ id: child.id,
+ status: "done",
+ currentUserId: member.user.id,
+ }),
+ );
+ await vi.waitFor(() => expect(send).toHaveBeenCalled());
+ expect(JSON.parse(send.mock.calls[0][0])).toEqual({
+ type: "TASK_RELATION_UPDATED",
+ projectId: parentProject.project.id,
+ taskId: "",
+ });
+ send.mockClear();
+ await eventContext.run({ initiatorId: "other-window" }, () =>
+ deleteTask(child.id, member.user.id),
+ );
+ await vi.waitFor(() => expect(send).toHaveBeenCalled());
+ expect(JSON.parse(send.mock.calls[0][0])).toEqual({
+ type: "TASK_RELATION_UPDATED",
+ projectId: parentProject.project.id,
+ taskId: "",
+ });
+ } finally {
+ removeConnection(parentProject.project.id, connection);
+ await shutdownWebSocketAdapter();
+ }
+ });
+ it("refreshes parent boards when a child's column is marked final or reopened", async () => {
+ const member = await createWorkspaceMember();
+ const parentProject = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const childProject = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const parent = await addTask(parentProject.project.id);
+ const child = await addTask(childProject.project.id, "done");
+ await relate(parent.id, child.id);
+ await initializeWebSocketAdapter();
+ const send = vi.fn();
+ const connection = addConnection(
+ parentProject.project.id,
+ { send } as never,
+ member.user.id,
+ "same-window",
+ member.workspace.id,
+ );
+ try {
+ for (const isFinal of [false, true]) {
+ send.mockClear();
+ await eventContext.run({ initiatorId: "same-window" }, () =>
+ updateColumn(childProject.columns.done.id, { isFinal }),
+ );
+ await vi.waitFor(() => expect(send).toHaveBeenCalled());
+ expect(JSON.parse(send.mock.calls[0][0])).toEqual({
+ type: "TASK_RELATION_UPDATED",
+ projectId: parentProject.project.id,
+ taskId: "",
+ });
+ expect(await countsFor(parentProject.project.id, parent.id)).toEqual({
+ completed: isFinal ? 1 : 0,
+ total: 1,
+ });
+ }
+ } finally {
+ removeConnection(parentProject.project.id, connection);
+ await shutdownWebSocketAdapter();
+ }
+ });
+
+ it.each(["delete", "updateStatus"])(
+ "batches parent refreshes when the bulk API performs %s",
+ async (operation) => {
+ const member = await createWorkspaceMember({ role: "owner" });
+ const parentProject = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const childProject = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const parent = await addTask(parentProject.project.id);
+ const child = await addTask(childProject.project.id);
+ const secondChild = await addTask(childProject.project.id);
+ await relate(parent.id, child.id);
+ await relate(parent.id, secondChild.id);
+ await initializeWebSocketAdapter();
+ const send = vi.fn();
+ const connection = addConnection(
+ parentProject.project.id,
+ { send } as never,
+ member.user.id,
+ "other-window",
+ member.workspace.id,
+ );
+ const parentLookup = vi.spyOn(subtaskParents, "getSubtaskParentProjects");
+ try {
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+ const response = await app.request("/api/task/bulk", {
+ method: "PATCH",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ taskIds: [child.id, secondChild.id],
+ operation,
+ value: operation === "updateStatus" ? "done" : undefined,
+ }),
+ });
+ expect(response.status).toBe(200);
+ await vi.waitFor(() => expect(send).toHaveBeenCalled());
+ expect(JSON.parse(send.mock.calls[0][0])).toEqual({
+ type: "TASK_RELATION_UPDATED",
+ projectId: parentProject.project.id,
+ taskId: "",
+ });
+ expect(await countsFor(parentProject.project.id, parent.id)).toEqual({
+ completed: operation === "updateStatus" ? 2 : 0,
+ total: operation === "updateStatus" ? 2 : 0,
+ });
+ expect(parentLookup).toHaveBeenCalledTimes(1);
+ expect(parentLookup.mock.calls[0][0].toSorted()).toEqual(
+ [child.id, secondChild.id].toSorted(),
+ );
+ } finally {
+ parentLookup.mockRestore();
+ removeConnection(parentProject.project.id, connection);
+ await shutdownWebSocketAdapter();
+ }
+ },
+ );
+ it("refreshes surviving parent boards when a child project is deleted", async () => {
+ const member = await createWorkspaceMember();
+ const parentProject = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const childProject = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const parent = await addTask(parentProject.project.id);
+ const child = await addTask(childProject.project.id, "done");
+ await relate(parent.id, child.id);
+ expect(await countsFor(parentProject.project.id, parent.id)).toEqual({
+ completed: 1,
+ total: 1,
+ });
+ await initializeWebSocketAdapter();
+ const send = vi.fn();
+ const connection = addConnection(
+ parentProject.project.id,
+ { send } as never,
+ member.user.id,
+ "same-window",
+ member.workspace.id,
+ );
+ try {
+ await eventContext.run({ initiatorId: "same-window" }, () =>
+ deleteProject(childProject.project.id, member.workspace.id),
+ );
+ await vi.waitFor(() => expect(send).toHaveBeenCalled());
+ expect(JSON.parse(send.mock.calls[0][0])).toEqual({
+ type: "TASK_RELATION_UPDATED",
+ projectId: parentProject.project.id,
+ taskId: "",
+ });
+ expect(await countsFor(parentProject.project.id, parent.id)).toEqual({
+ completed: 0,
+ total: 0,
+ });
+ } finally {
+ removeConnection(parentProject.project.id, connection);
+ await shutdownWebSocketAdapter();
+ }
+ });
+});
+
+describe("subtask counter mutation paths", () => {
+ beforeEach(resetTestDatabase);
+ it("refreshes a parent after moving a child into a nonfinal workflow", async () => {
+ const member = await createWorkspaceMember();
+ const parentProject = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const source = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const destination = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ await db
+ .update(schema.columnTable)
+ .set({ isFinal: false })
+ .where(eq(schema.columnTable.id, destination.columns.done.id));
+ const parent = await addTask(parentProject.project.id);
+ const child = await addTask(source.project.id, "done");
+ await relate(parent.id, child.id);
+ expect(await countsFor(parentProject.project.id, parent.id)).toEqual({
+ completed: 1,
+ total: 1,
+ });
+ await initializeWebSocketAdapter();
+ const send = vi.fn();
+ const connection = addConnection(
+ parentProject.project.id,
+ { send } as never,
+ member.user.id,
+ "same-window",
+ member.workspace.id,
+ );
+ try {
+ await eventContext.run({ initiatorId: "same-window" }, () =>
+ moveTask({
+ taskId: child.id,
+ destinationProjectId: destination.project.id,
+ currentUserId: member.user.id,
+ }),
+ );
+ await vi.waitFor(() => expect(send).toHaveBeenCalled());
+ expect(JSON.parse(send.mock.calls[0][0])).toEqual({
+ type: "TASK_RELATION_UPDATED",
+ projectId: parentProject.project.id,
+ taskId: "",
+ });
+ expect(await countsFor(parentProject.project.id, parent.id)).toEqual({
+ completed: 0,
+ total: 1,
+ });
+ } finally {
+ removeConnection(parentProject.project.id, connection);
+ await shutdownWebSocketAdapter();
+ }
+ });
+ it("refreshes same-project parents in other windows after child deletion", async () => {
+ const member = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const parent = await addTask(project.id);
+ const child = await addTask(project.id, "done");
+ await relate(parent.id, child.id);
+ await initializeWebSocketAdapter();
+ const send = vi.fn();
+ const connection = addConnection(
+ project.id,
+ { send } as never,
+ member.user.id,
+ "viewer",
+ member.workspace.id,
+ );
+ try {
+ await eventContext.run({ initiatorId: "editor" }, () =>
+ deleteTask(child.id, member.user.id),
+ );
+ await vi.waitFor(() => expect(send).toHaveBeenCalled());
+ expect(await countsFor(project.id, parent.id)).toEqual({
+ completed: 0,
+ total: 0,
+ });
+ } finally {
+ removeConnection(project.id, connection);
+ await shutdownWebSocketAdapter();
+ }
+ });
+});
diff --git a/tests/api/project/delete-project.test.ts b/tests/api/project/delete-project.test.ts
index 6e2ef3585..f71d73ac3 100644
--- a/tests/api/project/delete-project.test.ts
+++ b/tests/api/project/delete-project.test.ts
@@ -4,6 +4,8 @@ const mocks = vi.hoisted(() => ({
findFirst: vi.fn(),
delete: vi.fn(),
deleteS3Object: vi.fn(),
+ publishEvent: vi.fn(),
+ getProjectSubtaskParentProjects: vi.fn(),
}));
vi.mock("../../../apps/api/src/database", () => ({
@@ -17,6 +19,14 @@ vi.mock("../../../apps/api/src/storage/s3", () => ({
deleteS3Object: mocks.deleteS3Object,
}));
+vi.mock("../../../apps/api/src/events", () => ({
+ publishEvent: mocks.publishEvent,
+}));
+
+vi.mock("../../../apps/api/src/task/get-subtask-parent-projects", () => ({
+ getProjectSubtaskParentProjects: mocks.getProjectSubtaskParentProjects,
+}));
+
import deleteProject from "../../../apps/api/src/project/controllers/delete-project";
function mockDeletedProject(backgroundObjectKey: string | null) {
@@ -36,6 +46,10 @@ describe("deleteProject", () => {
tasks: [],
});
mocks.deleteS3Object.mockResolvedValue(undefined);
+ mocks.getProjectSubtaskParentProjects.mockResolvedValue([
+ { projectId: "parent-project" },
+ ]);
+ mocks.publishEvent.mockResolvedValue(undefined);
});
it("deletes the background object after deleting its project", async () => {
@@ -45,6 +59,9 @@ describe("deleteProject", () => {
await deleteProject("project-1", "workspace-1");
+ expect(mocks.publishEvent).toHaveBeenCalledWith("subtask-parents.refresh", {
+ projects: [{ projectId: "parent-project" }],
+ });
expect(mocks.deleteS3Object).toHaveBeenCalledWith(
"workspace/ws/project/project-1/backgrounds/background-v1",
);