⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat(project): move a project to another workspace (#1525)
Rojenson Lugodbdc755e4a14
diff --git a/apps/api/src/activity/controllers/create-activities.ts b/apps/api/src/activity/controllers/create-activities.tsnew file mode 100644index 000000000..137c7d86b--- /dev/null+++ b/apps/api/src/activity/controllers/create-activities.ts@@ -0,0 +1,22 @@+import db from "../../database";+import { activityTable } from "../../database/schema";++type NewActivity = typeof activityTable.$inferInsert;++// Postgres caps a statement at 65535 bind parameters and each row binds a+// handful of columns, so a batch that scales with a project's task count has+// to be chunked rather than sent as one statement.+const INSERT_CHUNK_SIZE = 500;++async function createActivities(+ activities: NewActivity[],+ database: Pick<typeof db, "insert"> = db,+) {+ for (let index = 0; index < activities.length; index += INSERT_CHUNK_SIZE) {+ await database+ .insert(activityTable)+ .values(activities.slice(index, index + INSERT_CHUNK_SIZE));+ }+}++export default createActivities;diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 48f65c271..c1402c22f 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -816,6 +816,7 @@ export function createApp() {const userId = c.get("userId");+ let workspaceId: string | undefined;if (projectId) {const [project] = await db.select({ workspaceId: schema.projectTable.workspaceId })@@ -828,6 +829,7 @@ export function createApp() {}await validateWorkspaceAccess(userId, project.workspaceId);+ workspaceId = project.workspaceId;}const windowId = c.req.query("windowId");@@ -836,8 +838,14 @@ export function createApp() {return {onOpen(_evt, ws) {- if (projectId) {- conn = addConnection(projectId, ws, userId, initiatorId);+ if (projectId && workspaceId) {+ conn = addConnection(+ projectId,+ ws,+ userId,+ initiatorId,+ workspaceId,+ );}},onMessage: handleWebSocketMessage,diff --git a/apps/api/src/project/controllers/move-project.ts b/apps/api/src/project/controllers/move-project.tsnew file mode 100644index 000000000..04fa46f94--- /dev/null+++ b/apps/api/src/project/controllers/move-project.ts@@ -0,0 +1,251 @@+import {+ and,+ eq,+ inArray,+ isNotNull,+ max,+ ne,+ notInArray,+ sql,+} from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import createActivities from "../../activity/controllers/create-activities";+import db from "../../database";+import {+ assetTable,+ labelTable,+ projectTable,+ taskRelationTable,+ taskTable,+ userNotificationWorkspaceProjectTable,+ workspaceUserTable,+} from "../../database/schema";+import { publishEvent } from "../../events";+import { closeProjectConnections } from "../../ws";++async function moveProject(+ id: string,+ sourceWorkspaceId: string,+ targetWorkspaceId: string,+ currentUserId: string,+) {+ if (sourceWorkspaceId === targetWorkspaceId) {+ throw new HTTPException(400, {+ message: "Project already belongs to this workspace",+ });+ }++ const { movedProject, unassignedTasks } = await db.transaction(async (tx) => {+ // Use a stable order for both workspaces before locking the project row.+ // This also keeps source reorders from updating a project after it moves.+ for (const workspaceId of [sourceWorkspaceId, targetWorkspaceId].sort()) {+ await tx.execute(+ sql`SELECT pg_advisory_xact_lock(1524, hashtext(${workspaceId}))`,+ );+ }+ // Locked for the life of the transaction: the request was authorized+ // against the source workspace, so a concurrent move would invalidate that+ // basis while this one is still deciding what side data to rewrite.+ const [existingProject] = await tx+ .select()+ .from(projectTable)+ .where(+ and(+ eq(projectTable.id, id),+ eq(projectTable.workspaceId, sourceWorkspaceId),+ ),+ )+ .for("update");++ if (!existingProject) {+ throw new HTTPException(404, {+ message:+ "Project doesn't exist or doesn't belong to the specified workspace",+ });+ }++ // The key doubles as the ticket-id prefix (KAN-12), and short-id lookup+ // resolves it per workspace with a limit of 1. Two projects sharing a key+ // in one workspace would make those ids ambiguous, so the move is refused+ // rather than silently renaming a project out from under its ticket ids.+ // Compared case-insensitively, since the lookup is. Archived projects+ // count: their tasks still resolve by short id.+ const [keyConflict] = await tx+ .select({ name: projectTable.name })+ .from(projectTable)+ .where(+ and(+ eq(projectTable.workspaceId, targetWorkspaceId),+ ne(projectTable.id, id),+ sql`lower(${projectTable.slug}) = lower(${existingProject.slug})`,+ ),+ )+ .limit(1);++ if (keyConflict) {+ throw new HTTPException(409, {+ message: `The target workspace already has a project using the key "${existingProject.slug}" (${keyConflict.name}). Change this project's key before moving it.`,+ });+ }++ const linked = await tx.execute(sql`+ SELECT 1 FROM ${taskRelationTable} relation+ JOIN ${taskTable} source ON source.id = relation.source_task_id+ JOIN ${taskTable} target ON target.id = relation.target_task_id+ WHERE (source.project_id = ${id} AND target.project_id <> ${id})+ OR (target.project_id = ${id} AND source.project_id <> ${id})+ LIMIT 1+ `);+ if (linked.rows.length)+ throw new HTTPException(409, {+ message:+ "Remove task relationships to other projects before moving this project.",+ });++ // These rows point at both the project and a notification rule via+ // composite foreign keys carrying workspace_id. Updating the project's+ // workspace cascades into them and then violates the rule-side key,+ // since the rule stays behind in the source workspace.+ await tx+ .delete(userNotificationWorkspaceProjectTable)+ .where(+ and(+ eq(userNotificationWorkspaceProjectTable.projectId, id),+ eq(+ userNotificationWorkspaceProjectTable.workspaceId,+ sourceWorkspaceId,+ ),+ ),+ );++ const tasks = await tx+ .select({+ id: taskTable.id,+ userId: taskTable.userId,+ })+ .from(taskTable)+ .where(eq(taskTable.projectId, id));++ let unassigned: typeof tasks = [];+ const assigneeIds = [+ ...new Set(+ tasks+ .map((task) => task.userId)+ .filter((userId): userId is string => Boolean(userId)),+ ),+ ];++ if (assigneeIds.length > 0) {+ const targetMembers = await tx+ .select({ userId: workspaceUserTable.userId })+ .from(workspaceUserTable)+ .where(+ and(+ eq(workspaceUserTable.workspaceId, targetWorkspaceId),+ inArray(workspaceUserTable.userId, assigneeIds),+ ),+ );++ const memberIds = new Set(targetMembers.map((member) => member.userId));+ // Kept as rows rather than a count: each one needs an activity row+ // afterwards, keyed by task id.+ unassigned = tasks.filter(+ (task) => task.userId && !memberIds.has(task.userId),+ );++ if (unassigned.length > 0) {+ // Predicated on the assignees rather than the task ids: the member set+ // is bounded by workspace size, while the task list isn't, and Postgres+ // caps a statement at 65535 bind parameters.+ await tx+ .update(taskTable)+ .set({ userId: null })+ .where(+ and(+ eq(taskTable.projectId, id),+ isNotNull(taskTable.userId),+ memberIds.size > 0+ ? notInArray(taskTable.userId, [...memberIds])+ : undefined,+ ),+ );+ }+ }++ // The source position means nothing in the target's ordering, and keeping+ // it would collide with whichever project already holds that slot. Append+ // instead, matching where `createProject` puts a new project.+ const [{ maxPosition } = { maxPosition: null }] = await tx+ .select({ maxPosition: max(projectTable.position) })+ .from(projectTable)+ .where(eq(projectTable.workspaceId, targetWorkspaceId));++ const [movedProject] = await tx+ .update(projectTable)+ .set({+ workspaceId: targetWorkspaceId,+ position: maxPosition === null ? 0 : maxPosition + 1,+ })+ .where(+ and(+ eq(projectTable.id, id),+ eq(projectTable.workspaceId, sourceWorkspaceId),+ ),+ )+ .returning();++ if (!movedProject) {+ throw new HTTPException(409, {+ message: "Project was moved to another workspace, please try again",+ });+ }++ // Assets and task labels denormalize the project's workspace.+ await tx+ .update(assetTable)+ .set({ workspaceId: targetWorkspaceId })+ .where(eq(assetTable.projectId, id));++ // Subquery rather than a materialized id list: this one scales with the+ // project's total task count.+ await tx+ .update(labelTable)+ .set({ workspaceId: targetWorkspaceId })+ .where(+ inArray(+ labelTable.taskId,+ tx+ .select({ id: taskTable.id })+ .from(taskTable)+ .where(eq(taskTable.projectId, id)),+ ),+ );++ // Keep history atomic with the move while bounding each insert's size.+ await createActivities(+ unassigned.map((task) => ({+ taskId: task.id,+ type: "unassigned",+ userId: currentUserId,+ content: null,+ eventData: {},+ })),+ tx,+ );++ return { movedProject, unassignedTasks: unassigned };+ });++ await closeProjectConnections(id);++ if (unassignedTasks.length > 0) {+ await publishEvent("task.bulk_unassigned", {+ projectId: id,+ userId: currentUserId,+ });+ }++ return { ...movedProject, unassignedTaskCount: unassignedTasks.length };+}++export default moveProject;diff --git a/apps/api/src/project/index.ts b/apps/api/src/project/index.tsindex 1595d2dc6..6ed8746e7 100644--- a/apps/api/src/project/index.ts+++ b/apps/api/src/project/index.ts@@ -1,3 +1,5 @@+import { HTTPException } from "hono/http-exception";+import { requireWorkspaceEntitlement } from "../billing/controllers/require-entitlement";import { requireEntitlement } from "../billing/require-entitlement-middleware";import {apiRouter,@@ -11,25 +13,64 @@ import {hasWorkspacePermission,requireWorkspacePermission,} from "../utils/require-workspace-permission";+import { validateWorkspaceAccess } from "../utils/validate-workspace-access";import { workspaceAccess } from "../utils/workspace-access-middleware";import archiveProjectCtrl from "./controllers/archive-project";import createProjectCtrl from "./controllers/create-project";import deleteProjectCtrl from "./controllers/delete-project";import getProjectCtrl from "./controllers/get-project";import getProjectsCtrl from "./controllers/get-projects";+import moveProjectCtrl from "./controllers/move-project";import reorderProjectsCtrl from "./controllers/reorder-projects";import unarchiveProjectCtrl from "./controllers/unarchive-project";import updateProjectCtrl from "./controllers/update-project";-import { projectListSchema, projectSchema } from "./response";+import {+ movedProjectSchema,+ projectListSchema,+ projectSchema,+} from "./response";import {createProjectBody,listProjectsQuery,+ moveProjectBody,projectParam,reorderProjectsBody,updateProjectBody,workspaceIdQuery,} from "./schema";+const moveProjectRoute = createRoute({+ method: "put",+ path: "/{id}/move",+ operationId: "moveProject",+ tags: ["Projects"],+ summary: "Move a project to another workspace",+ description:+ "Move a project and its tasks. Requires update and delete permission in the source and create permission in the destination. Remove cross-project task relationships before moving.",+ middleware: [+ workspaceAccess.fromProject(),+ requireWorkspacePermission({ project: ["update", "delete"] }),+ ] as const,+ request: {+ params: projectParam,+ body: {+ required: true,+ content: { "application/json": { schema: moveProjectBody } },+ },+ },+ responses: {+ 200: jsonResponse("Project moved", movedProjectSchema),+ 400: errorResponse("Invalid destination or same workspace"),+ 401: errorResponse("Unauthorized"),+ 402: errorResponse("Destination workspace plan has expired"),+ 403: errorResponse("Missing workspace access or permission"),+ 404: errorResponse("Project not found in the source workspace"),+ 409: errorResponse(+ "Project key conflict or cross-project task relationships",+ ),+ },+});+const listProjectsRoute = createRoute({method: "get",operationId: "listProjects",@@ -223,6 +264,32 @@ const unarchiveProjectRoute = createRoute({});const project = apiRouter<BaseVariables & { workspaceId: string }>()+ .openapi(moveProjectRoute, async (c) => {+ const { id } = c.req.valid("param");+ const { workspaceId: targetWorkspaceId } = c.req.valid("json");+ const sourceWorkspaceId = c.get("workspaceId");+ const userId = c.get("userId");+ await validateWorkspaceAccess(+ userId,+ targetWorkspaceId,+ c.get("apiKey")?.id,+ );+ if (+ !(await hasWorkspacePermission(+ c,+ { project: ["create"] },+ targetWorkspaceId,+ ))+ )+ throw new HTTPException(403, {+ message: "Insufficient permissions in the target workspace",+ });+ await requireWorkspaceEntitlement(targetWorkspaceId);+ return c.json(+ await moveProjectCtrl(id, sourceWorkspaceId, targetWorkspaceId, userId),+ 200,+ );+ }).openapi(listProjectsRoute, async (c) => {const workspaceId = c.get("workspaceId");const { includeArchived } = c.req.valid("query");diff --git a/apps/api/src/project/response.ts b/apps/api/src/project/response.tsindex b1dea62a1..01ee1372a 100644--- a/apps/api/src/project/response.ts+++ b/apps/api/src/project/response.ts@@ -55,3 +55,7 @@ export const projectListItemSchema = projectSchema.openapi("ProjectListItem");export const projectListSchema = z.array(projectListItemSchema);++export const movedProjectSchema = projectSchema+ .extend({ unassignedTaskCount: z.number() })+ .openapi("MovedProject");diff --git a/apps/api/src/project/schema.ts b/apps/api/src/project/schema.tsindex 9d0fff622..2422f1776 100644--- a/apps/api/src/project/schema.ts+++ b/apps/api/src/project/schema.ts@@ -33,3 +33,5 @@ export const reorderProjectsBody = z.object({.array(z.object({ id: z.string(), position: z.number().int().min(0) })).min(1),});++export const moveProjectBody = z.object({ workspaceId: z.string().min(1) });diff --git a/apps/api/src/task-relation/controllers/create-task-relation.ts b/apps/api/src/task-relation/controllers/create-task-relation.tsindex c9050c190..fec1a15a7 100644--- a/apps/api/src/task-relation/controllers/create-task-relation.ts+++ b/apps/api/src/task-relation/controllers/create-task-relation.ts@@ -1,4 +1,4 @@-import { and, eq, or } from "drizzle-orm";+import { and, eq, inArray, or } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";import {@@ -27,86 +27,106 @@ async function createTaskRelation({});}- const [sourceTask] = await db- .select({- id: taskTable.id,- projectId: taskTable.projectId,- workspaceId: projectTable.workspaceId,- })- .from(taskTable)- .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))- .where(- and(- eq(taskTable.id, sourceTaskId),- eq(projectTable.workspaceId, workspaceId),- ),- )- .limit(1);+ const { relation, sourceTask } = await db.transaction(async (tx) => {+ // Serialize relation creation with project moves before validating either+ // workspace. A move must see this relation or this request must see the move.+ await tx+ .select({ id: projectTable.id })+ .from(projectTable)+ .where(+ inArray(+ projectTable.id,+ tx+ .select({ projectId: taskTable.projectId })+ .from(taskTable)+ .where(inArray(taskTable.id, [sourceTaskId, targetTaskId])),+ ),+ )+ .orderBy(projectTable.id)+ .for("share");+ const [sourceTask] = await tx+ .select({+ id: taskTable.id,+ projectId: taskTable.projectId,+ workspaceId: projectTable.workspaceId,+ })+ .from(taskTable)+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))+ .where(+ and(+ eq(taskTable.id, sourceTaskId),+ eq(projectTable.workspaceId, workspaceId),+ ),+ )+ .limit(1);- if (!sourceTask) {- throw new HTTPException(404, { message: "Source task not found" });- }+ if (!sourceTask) {+ throw new HTTPException(404, { message: "Source task not found" });+ }- const [targetTask] = await db- .select({- id: taskTable.id,- projectId: taskTable.projectId,- workspaceId: projectTable.workspaceId,- })- .from(taskTable)- .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))- .where(- and(- eq(taskTable.id, targetTaskId),- eq(projectTable.workspaceId, workspaceId),- ),- )- .limit(1);+ const [targetTask] = await tx+ .select({+ id: taskTable.id,+ projectId: taskTable.projectId,+ workspaceId: projectTable.workspaceId,+ })+ .from(taskTable)+ .innerJoin(projectTable, eq(taskTable.projectId, projectTable.id))+ .where(+ and(+ eq(taskTable.id, targetTaskId),+ eq(projectTable.workspaceId, workspaceId),+ ),+ )+ .limit(1);- if (!targetTask) {- throw new HTTPException(404, { message: "Target task not found" });- }+ if (!targetTask) {+ throw new HTTPException(404, { message: "Target task not found" });+ }- const existing = await db- .select({ id: taskRelationTable.id })- .from(taskRelationTable)- .where(- and(- eq(taskRelationTable.relationType, relationType),- or(- and(- eq(taskRelationTable.sourceTaskId, sourceTaskId),- eq(taskRelationTable.targetTaskId, targetTaskId),- ),- and(- eq(taskRelationTable.sourceTaskId, targetTaskId),- eq(taskRelationTable.targetTaskId, sourceTaskId),+ const existing = await tx+ .select({ id: taskRelationTable.id })+ .from(taskRelationTable)+ .where(+ and(+ eq(taskRelationTable.relationType, relationType),+ or(+ and(+ eq(taskRelationTable.sourceTaskId, sourceTaskId),+ eq(taskRelationTable.targetTaskId, targetTaskId),+ ),+ and(+ eq(taskRelationTable.sourceTaskId, targetTaskId),+ eq(taskRelationTable.targetTaskId, sourceTaskId),+ ),),),- ),- )- .limit(1);+ )+ .limit(1);- if (existing.length > 0) {- throw new HTTPException(409, {- message: "This relation already exists",- });- }+ if (existing.length > 0) {+ throw new HTTPException(409, {+ message: "This relation already exists",+ });+ }- const [relation] = await db- .insert(taskRelationTable)- .values({- sourceTaskId,- targetTaskId,- relationType,- })- .returning();+ const [relation] = await tx+ .insert(taskRelationTable)+ .values({+ sourceTaskId,+ targetTaskId,+ relationType,+ })+ .returning();- if (!relation) {- throw new HTTPException(500, {- message: "Failed to create task relation",- });- }+ if (!relation) {+ throw new HTTPException(500, {+ message: "Failed to create task relation",+ });+ }++ return { relation, sourceTask };+ });await publishEvent("task-relation.created", {...relation,diff --git a/apps/api/src/utils/require-workspace-permission.ts b/apps/api/src/utils/require-workspace-permission.tsindex 7d89fddb4..6a2fac767 100644--- a/apps/api/src/utils/require-workspace-permission.ts+++ b/apps/api/src/utils/require-workspace-permission.ts@@ -87,8 +87,12 @@ function satisfies(export async function hasWorkspacePermission(c: Context,permissions: PermissionMap,+ // Checks a workspace other than the one the request authorized against.+ // Needed when a single request touches two workspaces (e.g. moving a+ // project), since the access middleware only resolves one.+ workspaceIdOverride?: string,) {- const workspaceId = c.get("workspaceId");+ const workspaceId = workspaceIdOverride ?? c.get("workspaceId");if (!workspaceId) return false;const apiKey = c.get("apiKey") asdiff --git a/apps/api/src/ws/broadcast-adapter.ts b/apps/api/src/ws/broadcast-adapter.tsindex eb21ccf9c..da5ab0bc4 100644--- a/apps/api/src/ws/broadcast-adapter.ts+++ b/apps/api/src/ws/broadcast-adapter.ts@@ -30,7 +30,9 @@ export type BroadcastAdapter = {publishToUser(msg: UserBroadcast): Promise<void>;/** Subscribe to messages for delivery to local connections */- subscribe(handler: (msg: BroadcastMessage) => void): Promise<void>;+ subscribe(+ handler: (msg: BroadcastMessage) => void | Promise<void>,+ ): Promise<void>;subscribeToUser(handler: (msg: UserBroadcast) => void): Promise<void>;diff --git a/apps/api/src/ws/in-memory-broadcast-adapter.ts b/apps/api/src/ws/in-memory-broadcast-adapter.tsindex bd0aad5e2..452fe5b36 100644--- a/apps/api/src/ws/in-memory-broadcast-adapter.ts+++ b/apps/api/src/ws/in-memory-broadcast-adapter.ts@@ -5,19 +5,21 @@ import type {} from "./broadcast-adapter";export class InMemoryBroadcastAdapter implements BroadcastAdapter {- private handler?: (msg: BroadcastMessage) => void;+ private handler?: (msg: BroadcastMessage) => void | Promise<void>;private userHandler?: (msg: UserBroadcast) => void;async publish(msg: BroadcastMessage): Promise<void> {// Deliver directly in the same process- this.handler?.(msg);+ await this.handler?.(msg);}async publishToUser(msg: UserBroadcast): Promise<void> {this.userHandler?.(msg);}- async subscribe(handler: (msg: BroadcastMessage) => void): Promise<void> {+ async subscribe(+ handler: (msg: BroadcastMessage) => void | Promise<void>,+ ): Promise<void> {this.handler = handler;}diff --git a/apps/api/src/ws/index.ts b/apps/api/src/ws/index.tsindex d9d1ddeea..399a84a36 100644--- a/apps/api/src/ws/index.ts+++ b/apps/api/src/ws/index.ts@@ -1,5 +1,8 @@import { randomUUID } from "node:crypto";+import { eq } from "drizzle-orm";import type { WSContext } from "hono/ws";+import db from "../database";+import { projectTable } from "../database/schema";import { subscribeToEvent } from "../events";import { isRedisConfigured } from "../redis";import type {@@ -18,6 +21,7 @@ type ProjectConnection = {ws: WSContext;userId: string;initiatorId: string;+ workspaceId: string;};type UserConnection = {@@ -113,7 +117,7 @@ export async function initializeWebSocketAdapter() {try {await nextAdapter.subscribe((msg: BroadcastMessage) => {- deliverToLocalConnections(+ return deliverToLocalConnections(msg.projectId,msg.message,msg.excludeInitiatorId,@@ -158,26 +162,96 @@ export async function shutdownWebSocketAdapter() {adapter = null;}-function deliverToLocalConnections(+function closeLocalProjectConnections(projectId: string) {+ const timeout = projectBroadcastTimeouts.get(projectId);+ if (timeout) clearTimeout(timeout);+ projectBroadcastTimeouts.delete(projectId);+ projectBroadcastQueues.delete(projectId);+ const connections = projectConnections.get(projectId);+ projectConnections.delete(projectId);+ for (const conn of connections ?? []) {+ try {+ conn.ws.send(JSON.stringify({ type: "PROJECT_MOVED", projectId }));+ } catch {+ /* The socket may already be closed. */+ }+ try {+ conn.ws.close(1008, "Project workspace changed");+ } catch {+ /* Already closed. */+ }+ }+}++export async function closeProjectConnections(projectId: string) {+ closeLocalProjectConnections(projectId);+ try {+ await adapter?.publish({+ projectId,+ message: { type: "PROJECT_MOVED", projectId },+ });+ } catch (error) {+ // Delivery also checks the workspace, so missed Redis notifications cannot+ // leave old connections receiving future project updates.+ console.error("Failed to publish project move:", error);+ }+}++const workspaceLookups = new Map<string, Promise<string | null>>();+function currentProjectWorkspace(projectId: string) {+ let pending = workspaceLookups.get(projectId);+ if (!pending) {+ pending = db+ .select({ workspaceId: projectTable.workspaceId })+ .from(projectTable)+ .where(eq(projectTable.id, projectId))+ .limit(1)+ .then(([project]) => project?.workspaceId ?? null)+ .finally(() => workspaceLookups.delete(projectId));+ workspaceLookups.set(projectId, pending);+ }+ return pending;+}++async function deliverToLocalConnections(projectId: string,message: ProjectBroadcastMessage,excludeInitiatorId?: string,) {+ if (message.type === "PROJECT_MOVED") {+ closeLocalProjectConnections(projectId);+ return;+ }const connections = projectConnections.get(projectId);if (!connections) return;-+ const recipients = [...connections];+ let workspaceId: string | null;+ try {+ workspaceId = await currentProjectWorkspace(projectId);+ } catch (error) {+ console.error("Failed to validate project broadcast access:", error);+ workspaceId = null;+ }const payload = JSON.stringify(message);- for (const conn of connections) {+ for (const conn of recipients) {+ // A move may have closed these connections while the lookup was in flight.+ if (!projectConnections.get(projectId)?.has(conn)) continue;+ if (conn.workspaceId !== workspaceId) {+ removeConnection(projectId, conn);+ try {+ conn.ws.close(1008, "Project workspace changed");+ } catch {+ /* Already closed. */+ }+ continue;+ }if (excludeInitiatorId && conn.initiatorId === excludeInitiatorId) continue;try {conn.ws.send(payload);} catch {- connections.delete(conn);+ removeConnection(projectId, conn);}}- if (connections.size === 0) {- projectConnections.delete(projectId);- }}export function addConnection(@@ -185,11 +259,12 @@ export function addConnection(ws: WSContext,userId: string,initiatorId: string,+ workspaceId: string,) {if (!projectConnections.has(projectId)) {projectConnections.set(projectId, new Set());}- const conn: ProjectConnection = { ws, userId, initiatorId };+ const conn: ProjectConnection = { ws, userId, initiatorId, workspaceId };projectConnections.get(projectId)?.add(conn);return conn;}@@ -334,6 +409,24 @@ subscribeToEvent<{);});+// Project-scoped rather than per task: a project move can unassign every task+// in the project at once, so clients refetch the board once instead of+// receiving one message per task.+subscribeToEvent<{+ projectId: string;+ userId: string;+ initiatorId?: string;+}>("task.bulk_unassigned", async (data) => {+ const { projectId, initiatorId } = data;+ if (!projectId) return;++ broadcastToProject(+ projectId,+ { type: "TASK_UPDATED", projectId, taskId: "" },+ initiatorId,+ );+});+subscribeToEvent<{ notificationId: string; userId: string }>("notification.created",async (data) => {diff --git a/apps/api/src/ws/redis-broadcast-adapter.ts b/apps/api/src/ws/redis-broadcast-adapter.tsindex 9ee438202..67c7d916e 100644--- a/apps/api/src/ws/redis-broadcast-adapter.ts+++ b/apps/api/src/ws/redis-broadcast-adapter.ts@@ -56,7 +56,9 @@ export class RedisBroadcastAdapter implements BroadcastAdapter {);}- async subscribe(handler: (msg: BroadcastMessage) => void): Promise<void> {+ async subscribe(+ handler: (msg: BroadcastMessage) => void | Promise<void>,+ ): Promise<void> {if (this.subscribed) return;this.subscribed = true;@@ -74,7 +76,9 @@ export class RedisBroadcastAdapter implements BroadcastAdapter {console.error("Invalid broadcast message:", parsed.issues);return;}- handler(parsed.output);+ void Promise.resolve(handler(parsed.output)).catch((error) => {+ console.error("Failed to deliver project broadcast:", error);+ });} catch (err) {console.error("Failed to parse broadcast message:", err);}diff --git a/apps/docs/openapi.json b/apps/docs/openapi.jsonindex fe60d4328..c025064ae 100644--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@ -599,7 +599,7 @@"idToken"]},- "ProjectListItem": {+ "MovedProject": {"allOf": [{"$ref": "#/components/schemas/Project"@@ -607,64 +607,16 @@{"type": "object","properties": {- "statistics": {- "$ref": "#/components/schemas/ProjectStatistics"- },- "archivedTasks": {- "type": "array",- "items": {- "$ref": "#/components/schemas/BoardTask"- },- "description": "Always empty."- },- "plannedTasks": {- "type": "array",- "items": {- "$ref": "#/components/schemas/BoardTask"- },- "description": "Always empty."- },- "columns": {- "type": "array",- "items": {- "$ref": "#/components/schemas/BoardColumn"- },- "description": "Always empty."+ "unassignedTaskCount": {+ "type": "number"}},"required": [- "statistics",- "archivedTasks",- "plannedTasks",- "columns"+ "unassignedTaskCount"]}]},- "ProjectStatistics": {- "type": "object",- "properties": {- "completionPercentage": {- "type": "number"- },- "totalTasks": {- "type": "number"- },- "dueDate": {- "type": [- "string",- "null"- ],- "format": "date-time",- "description": "The soonest due date among the project's open tasks."- }- },- "required": [- "completionPercentage",- "totalTasks",- "dueDate"- ]- },"Project": {"type": "object","properties": {@@ -735,6 +687,72 @@"lastTaskNumber"]},+ "ProjectListItem": {+ "allOf": [+ {+ "$ref": "#/components/schemas/Project"+ },+ {+ "type": "object",+ "properties": {+ "statistics": {+ "$ref": "#/components/schemas/ProjectStatistics"+ },+ "archivedTasks": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/BoardTask"+ },+ "description": "Always empty."+ },+ "plannedTasks": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/BoardTask"+ },+ "description": "Always empty."+ },+ "columns": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/BoardColumn"+ },+ "description": "Always empty."+ }+ },+ "required": [+ "statistics",+ "archivedTasks",+ "plannedTasks",+ "columns"+ ]+ }+ ]+ },+ "ProjectStatistics": {+ "type": "object",+ "properties": {+ "completionPercentage": {+ "type": "number"+ },+ "totalTasks": {+ "type": "number"+ },+ "dueDate": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time",+ "description": "The soonest due date among the project's open tasks."+ }+ },+ "required": [+ "completionPercentage",+ "totalTasks",+ "dueDate"+ ]+ },"TaskDescriptionMatches": {"type": "object","properties": {@@ -6370,6 +6388,117 @@}}},+ "/project/{id}/move": {+ "put": {+ "operationId": "moveProject",+ "tags": [+ "Projects"+ ],+ "summary": "Move a project to another workspace",+ "description": "Move a project and its tasks. Requires update and delete permission in the source and create permission in the destination. Remove cross-project task relationships before moving.",+ "parameters": [+ {+ "schema": {+ "type": "string"+ },+ "required": true,+ "name": "id",+ "in": "path"+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "workspaceId": {+ "type": "string",+ "minLength": 1+ }+ },+ "required": [+ "workspaceId"+ ]+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Project moved",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MovedProject"+ }+ }+ }+ },+ "400": {+ "description": "Invalid destination or same workspace",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "401": {+ "description": "Unauthorized",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "402": {+ "description": "Destination workspace plan has expired",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "403": {+ "description": "Missing workspace access or permission",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "404": {+ "description": "Project not found in the source workspace",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },+ "409": {+ "description": "Project key conflict or cross-project task relationships",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ },"/project": {"get": {"operationId": "listProjects",diff --git a/apps/web/src/fetchers/project/move-project.ts b/apps/web/src/fetchers/project/move-project.tsnew file mode 100644index 000000000..57bd8a66b--- /dev/null+++ b/apps/web/src/fetchers/project/move-project.ts@@ -0,0 +1,25 @@+import { client } from "@kaneo/libs";+import type { InferRequestType } from "hono/client";++export type MoveProjectRequest = InferRequestType<+ (typeof client)["project"][":id"]["move"]["$put"]+>["json"] &+ InferRequestType<(typeof client)["project"][":id"]["move"]["$put"]>["param"];++async function moveProject({ id, workspaceId }: MoveProjectRequest) {+ const response = await client.project[":id"].move.$put({+ param: { id },+ json: { workspaceId },+ });++ if (!response.ok) {+ const error = await response.text();+ throw new Error(error);+ }++ const data = await response.json();++ return data;+}++export default moveProject;diff --git a/apps/web/src/hooks/mutations/project/use-move-project.ts b/apps/web/src/hooks/mutations/project/use-move-project.tsnew file mode 100644index 000000000..aec9fe177--- /dev/null+++ b/apps/web/src/hooks/mutations/project/use-move-project.ts@@ -0,0 +1,21 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import moveProject from "@/fetchers/project/move-project";++function useMoveProject() {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: moveProject,+ // `["projects"]` prefix-matches both the source and target listings.+ // `["tasks", id]` backs the project store, which still carries the old+ // workspace id that other views build links from.+ onSuccess: async (_data, { id }) => {+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ["projects"] }),+ queryClient.invalidateQueries({ queryKey: ["tasks", id] }),+ ]);+ },+ });+}++export default useMoveProject;diff --git a/apps/web/src/hooks/queries/workspace/use-workspaces-with-permission.ts b/apps/web/src/hooks/queries/workspace/use-workspaces-with-permission.tsnew file mode 100644index 000000000..23dd95376--- /dev/null+++ b/apps/web/src/hooks/queries/workspace/use-workspaces-with-permission.ts@@ -0,0 +1,53 @@+import { useQuery } from "@tanstack/react-query";+import { useMemo } from "react";+import { authClient } from "@/lib/auth-client";++// `useWorkspacePermission` can only answer for the active workspace — it pins+// `organizationId` to it. This asks the same server endpoint about a set of+// other workspaces instead, which is what the project move needs: both the+// source workspace the project actually lives in and the candidate targets.+//+// Pass a module-level constant for `permissions` so its identity is stable.+// Several actions on the same workspace belong in one call: the endpoint+// requires all of them, and asking separately doubles the round-trips.+export function useWorkspacesWithPermission(+ workspaceIds: string[],+ permissions: Record<string, string[]>,+) {+ const ids = useMemo(() => [...workspaceIds].sort(), [workspaceIds]);+ const permissionKey = useMemo(+ () => JSON.stringify(permissions),+ [permissions],+ );++ const { data, isPending, isError } = useQuery({+ queryKey: ["workspace-capabilities", "by-permission", permissionKey, ids],+ enabled: ids.length > 0,+ staleTime: 5 * 60 * 1000,+ queryFn: async () => {+ // Deliberately not caught per workspace: swallowing a failed check as+ // "no permission" is indistinguishable from a real denial, so a+ // transient error would silently hide the action instead of retrying.+ const results = await Promise.all(+ ids.map(async (organizationId) => {+ const res = await authClient.organization.hasPermission({+ organizationId,+ permissions,+ });+ if (res.error) throw new Error(res.error.message);+ return res.data?.success === true ? organizationId : null;+ }),+ );+ return results.filter((id): id is string => id !== null);+ },+ });++ const allowed = useMemo(() => new Set(data ?? []), [data]);++ return {+ allowed,+ // False while disabled, so callers don't read an empty set as "loading".+ isPending: ids.length > 0 && isPending,+ isError,+ };+}diff --git a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsxindex 5f3abec8d..12e93fede 100644--- a/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx+++ b/apps/web/src/hooks/use-project-websocket-lifecycle.test.tsx@@ -105,6 +105,24 @@ describe("project WebSocket lifecycle", () => {expect(vi.getTimerCount()).toBe(0);});+ it("refreshes project and task caches when the workspace changes", () => {+ renderHook(() => useProjectWebSocket("project-a"));+ act(() =>+ TestSocket.instances[0].onmessage?.({+ data: JSON.stringify({ type: "PROJECT_MOVED", projectId: "project-a" }),+ }),+ );+ for (const queryKey of [+ ["projects"],+ ["project", "project-a"],+ ["tasks", "project-a"],+ ["task"],+ ["task-relations"],+ ]) {+ expect(client.invalidateQueries).toHaveBeenCalledWith({ queryKey });+ }+ });+it("preserves bounded exponential reconnects and active message invalidation", () => {const { unmount } = renderHook(() => useProjectWebSocket("project-a"));for (let retry = 0; retry < 5; retry++) {diff --git a/apps/web/src/hooks/use-project-websocket.ts b/apps/web/src/hooks/use-project-websocket.tsindex 88667cfbd..6fd803d5a 100644--- a/apps/web/src/hooks/use-project-websocket.ts+++ b/apps/web/src/hooks/use-project-websocket.ts@@ -62,6 +62,18 @@ export function useProjectWebSocket(projectId: string) {if (disposed || activeSocket !== ws) return;try {const message = JSON.parse(event.data);+ if (message.type === "PROJECT_MOVED") {+ for (const queryKey of [+ ["projects"],+ ["project", projectId],+ ["tasks", projectId],+ ["task"],+ ["task-relations"],+ ]) {+ queryClient.invalidateQueries({ queryKey });+ }+ return;+ }if (message.type === "TASK_UPDATED" ||message.type === "TASK_CREATED" ||diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/general.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/general.tsxindex bed836552..b4e1a1125 100644--- a/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/general.tsx+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/settings/projects/$projectId/general.tsx@@ -35,12 +35,22 @@ import {PopoverContent,PopoverTrigger,} from "@/components/ui/popover";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";import { Separator } from "@/components/ui/separator";import icons from "@/constants/project-icons";import useDeleteProject from "@/hooks/mutations/project/use-delete-project";+import useMoveProject from "@/hooks/mutations/project/use-move-project";import useUpdateProject from "@/hooks/mutations/project/use-update-project";import { useGetTasks } from "@/hooks/queries/task/use-get-tasks";import useActiveWorkspace from "@/hooks/queries/workspace/use-active-workspace";+import useGetWorkspaces from "@/hooks/queries/workspace/use-get-workspaces";+import { useWorkspacesWithPermission } from "@/hooks/queries/workspace/use-workspaces-with-permission";import { useWorkspacePermission } from "@/hooks/use-workspace-permission";import { cn } from "@/lib/cn";import { toast } from "@/lib/toast";@@ -52,6 +62,11 @@ export const Route = createFileRoute(component: RouteComponent,});+// Module-level so their identity stays stable across renders.+const PROJECT_CREATE = { project: ["create"] };+// Asked as one check: the endpoint requires both in the source workspace.+const PROJECT_UPDATE_AND_DELETE = { project: ["update", "delete"] };+type ProjectFormValues = {name: string;slug: string;@@ -104,16 +119,26 @@ function RouteComponent() {const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null);const isSavingRef = useRef(false);const queuedSaveRef = useRef<ProjectFormValues | null>(null);+ // The save currently in flight, so a caller that lands mid-save can await the+ // real write instead of the queue hand-off returning immediately.+ const inFlightSaveRef = useRef<Promise<boolean> | null>(null);const lastSavedRef = useRef<NormalizedProjectValues | null>(null);const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);const [iconPopoverOpen, setIconPopoverOpen] = useState(false);const [iconSearch, setIconSearch] = useState("");+ // Deliberately outside `projectForm`: the form auto-saves on every change,+ // and the target workspace must only be applied from the confirm dialog.+ const [targetWorkspaceId, setTargetWorkspaceId] = useState("");+ const [isMoveModalOpen, setIsMoveModalOpen] = useState(false);const { data: workspace } = useActiveWorkspace();const { projectId: rawProjectId } = useParams({ strict: false });const projectId = rawProjectId ?? "";const { data: fetchedProject } = useGetTasks(projectId);const { project, setProject } = useProjectStore();+ // The store is populated asynchronously from `useGetTasks`, so during a route+ // transition it can still hold the previously viewed project.+ const isCurrentProject = project?.id === projectId;useEffect(() => {if (fetchedProject) {@@ -124,6 +149,49 @@ function RouteComponent() {const { mutateAsync: updateProject } = useUpdateProject();const { mutateAsync: deleteProject, isPending: isDeleting } =useDeleteProject();+ const { mutateAsync: moveProject, isPending: isMoving } = useMoveProject();+ const { data: workspaces } = useGetWorkspaces();+ // Filtered against the project's own workspace rather than the active one:+ // this route has no `workspaceId` param, so `useActiveWorkspace` falls back+ // to the last-active organization, which can differ from where the project+ // actually lives (deep link, bookmark, back after a workspace switch).+ const moveCandidates = useMemo(+ () => (workspaces ?? []).filter((item) => item.id !== project?.workspaceId),+ [workspaces, project?.workspaceId],+ );+ // The endpoint also requires `project:create` in the target, so a workspace+ // the user can't create in would only fail server-side after they picked it.+ const moveCandidateIds = useMemo(+ () => moveCandidates.map((item) => item.id),+ [moveCandidates],+ );+ const { allowed: canCreateIn, isError: moveTargetsFailed } =+ useWorkspacesWithPermission(moveCandidateIds, PROJECT_CREATE);+ const moveTargets = useMemo(+ () => moveCandidates.filter((item) => canCreateIn.has(item.id)),+ [moveCandidates, canCreateIn],+ );+ // The API authorizes the move against the project's own workspace, which+ // isn't necessarily the active one `useWorkspacePermission` answers for. It+ // requires `delete` there on top of `update`, since a move takes the project+ // out of that workspace.+ const sourceWorkspaceIds = useMemo(+ () => (project?.workspaceId ? [project.workspaceId] : []),+ [project?.workspaceId],+ );+ const { allowed: canMoveOutOfSource } = useWorkspacesWithPermission(+ sourceWorkspaceIds,+ PROJECT_UPDATE_AND_DELETE,+ );+ const canMoveFromSource = Boolean(+ project?.workspaceId && canMoveOutOfSource.has(project.workspaceId),+ );+ // Kept visible when the target lookup failed: an empty list would otherwise+ // read as "you have nowhere to move this", which is a different answer.+ const canShowMove =+ canMoveFromSource &&+ isCurrentProject &&+ (moveTargets.length > 0 || moveTargetsFailed);const { canManageProjects, canDeleteProjects } = useWorkspacePermission();const canEdit = canManageProjects();const canDelete = canDeleteProjects();@@ -160,8 +228,8 @@ function RouteComponent() {}, [project, projectForm]);const saveProject = useCallback(- async (data: ProjectFormValues) => {- if (!project?.id) return;+ async (data: ProjectFormValues): Promise<boolean> => {+ if (!project?.id) return false;const normalizedData = normalizeProjectValues(data);const nameChanged = lastSavedRef.current?.name !== normalizedData.name;@@ -172,56 +240,81 @@ function RouteComponent() {const hasChanges =nameChanged || slugChanged || descriptionChanged || iconChanged;- if (!hasChanges) return;+ if (!hasChanges) return true;if (isSavingRef.current) {queuedSaveRef.current = data;- return;+ // The in-flight save drains the queue before it resolves, so its+ // outcome covers this data too. Reporting success here instead would+ // tell the caller the edit is persisted while it is still queued.+ return inFlightSaveRef.current ?? false;}isSavingRef.current = true;+ const runSave = async (): Promise<boolean> => {+ let succeeded = false;++ try {+ const updatePayload = {+ id: project.id,+ name: nameChanged ? normalizedData.name : project.name,+ slug: slugChanged ? normalizedData.slug : project.slug,+ description: descriptionChanged+ ? normalizedData.description+ : (project.description ?? ""),+ icon: iconChanged+ ? normalizedData.icon+ : (project.icon ?? "Layout"),+ isPublic: !!project.isPublic,+ };++ await updateProject(updatePayload);++ projectForm.reset(normalizedData, { keepDirty: false });+ lastSavedRef.current = normalizedData;+ queuedSaveRef.current = null;++ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ["projects"] }),+ queryClient.invalidateQueries({+ queryKey: ["projects", workspace?.id],+ }),+ queryClient.invalidateQueries({+ queryKey: ["projects", workspace?.id, project.id],+ }),+ ]);+ toast.success(t("settings:projectGeneral.toastUpdated"));+ succeeded = true;+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : t("settings:projectGeneral.toastUpdateError"),+ );+ } finally {+ isSavingRef.current = false;++ if (queuedSaveRef.current) {+ const queuedData = queuedSaveRef.current;+ queuedSaveRef.current = null;+ // The queue holds newer values than this save wrote, so its+ // outcome is the one that describes the form's current state.+ succeeded = await saveProject(queuedData);+ }+ }++ return succeeded;+ };++ const pendingSave = runSave();+ inFlightSaveRef.current = pendingSave;+try {- const updatePayload = {- id: project.id,- name: nameChanged ? normalizedData.name : project.name,- slug: slugChanged ? normalizedData.slug : project.slug,- description: descriptionChanged- ? normalizedData.description- : (project.description ?? ""),- icon: iconChanged ? normalizedData.icon : (project.icon ?? "Layout"),- isPublic: !!project.isPublic,- };-- await updateProject(updatePayload);-- projectForm.reset(normalizedData, { keepDirty: false });- lastSavedRef.current = normalizedData;- queuedSaveRef.current = null;-- await Promise.all([- queryClient.invalidateQueries({ queryKey: ["projects"] }),- queryClient.invalidateQueries({- queryKey: ["projects", workspace?.id],- }),- queryClient.invalidateQueries({- queryKey: ["projects", workspace?.id, project.id],- }),- ]);- toast.success(t("settings:projectGeneral.toastUpdated"));- } catch (error) {- toast.error(- error instanceof Error- ? error.message- : t("settings:projectGeneral.toastUpdateError"),- );+ return await pendingSave;} finally {- isSavingRef.current = false;-- if (queuedSaveRef.current) {- const queuedData = queuedSaveRef.current;- queuedSaveRef.current = null;- await saveProject(queuedData);+ if (inFlightSaveRef.current === pendingSave) {+ inFlightSaveRef.current = null;}}},@@ -271,35 +364,92 @@ function RouteComponent() {return () => subscription.unsubscribe();}, [projectForm, debouncedSave, canEdit]);+ // Reads through the refs so its identity stays stable: the unmount effect+ // below depends on it while keeping an empty dependency array.+ // Resolves false when the pending edits were not persisted: either they are+ // invalid, or the update they triggered failed.+ const flushPendingSave = useCallback(async () => {+ if (debounceTimeoutRef.current) {+ clearTimeout(debounceTimeoutRef.current);+ debounceTimeoutRef.current = null;+ }++ const latest = projectFormRef.current.getValues() as ProjectFormValues;+ const normalized = normalizeProjectValues(latest);+ const last = lastSavedRef.current;+ const hasPendingChanges =+ !last ||+ last.name !== normalized.name ||+ last.slug !== normalized.slug ||+ last.description !== normalized.description ||+ last.icon !== normalized.icon;+ if (!hasPendingChanges) return true;++ const isValid = await projectFormRef.current.trigger();+ if (!isValid) return false;++ return saveProjectRef.current(latest);+ }, []);+useEffect(() => {return () => {- if (debounceTimeoutRef.current) {- clearTimeout(debounceTimeoutRef.current);- debounceTimeoutRef.current = null;- }// Flush pending edits if the user navigates away before the debounce fires.- void (async () => {- const latest = projectFormRef.current.getValues() as ProjectFormValues;- const normalized = normalizeProjectValues(latest);- const last = lastSavedRef.current;- const hasPendingChanges =- !last ||- last.name !== normalized.name ||- last.slug !== normalized.slug ||- last.description !== normalized.description ||- last.icon !== normalized.icon;- if (!hasPendingChanges) return;-- const isValid = await projectFormRef.current.trigger();- if (isValid) {- await saveProjectRef.current(latest);- }- })();+ void flushPendingSave();};- }, []);+ }, [flushPendingSave]);++ const handleMoveProject = useCallback(async () => {+ if (!isCurrentProject || !project?.id || !targetWorkspaceId) return;++ // The key doubles as the ticket-id prefix, and the server checks it for+ // collisions in the target. Moving on a debounced edit would check the+ // stale key and then persist the new one after navigation.+ const flushed = await flushPendingSave();+ // The dialog has already closed, so say why nothing happened. `trigger()`+ // has surfaced the offending field errors in the form itself.+ if (!flushed) {+ toast.error(t("settings:projectGeneral.toastMoveError"));+ return;+ }++ try {+ const moved = await moveProject({+ id: project.id,+ workspaceId: targetWorkspaceId,+ });++ toast.success(+ moved.unassignedTaskCount > 0+ ? t("settings:projectGeneral.toastMovedWithUnassigned", {+ taskCount: moved.unassignedTaskCount,+ })+ : t("settings:projectGeneral.toastMoved"),+ );++ // The current URL still carries the old workspace id.+ navigate({+ to: "/dashboard/workspace/$workspaceId/project/$projectId",+ params: { workspaceId: targetWorkspaceId, projectId: project.id },+ });+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : t("settings:projectGeneral.toastMoveError"),+ );+ }+ }, [+ isCurrentProject,+ project?.id,+ targetWorkspaceId,+ flushPendingSave,+ moveProject,+ navigate,+ t,+ ]);const handleDeleteProject = useCallback(async () => {- if (!project?.id) return;+ if (!isCurrentProject || !project?.id) return;try {await deleteProject({ id: project.id });@@ -318,7 +468,15 @@ function RouteComponent() {: t("settings:projectGeneral.toastDeleteError"),);}- }, [project?.id, deleteProject, queryClient, navigate, workspace?.id, t]);+ }, [+ isCurrentProject,+ project?.id,+ deleteProject,+ queryClient,+ navigate,+ workspace?.id,+ t,+ ]);return (<>@@ -550,6 +708,67 @@ function RouteComponent() {</div>{project && <TasksImportExport project={project} />}</div>++ {canShowMove && (+ <>+ <Separator />+ <div className="flex items-center justify-between">+ <div className="space-y-0.5">+ <p className="text-sm font-medium">+ {t("settings:projectGeneral.moveProject")}+ </p>+ <p className="text-xs text-muted-foreground">+ {t("settings:projectGeneral.moveProjectDescription")}+ </p>+ </div>+ {moveTargetsFailed ? (+ <p className="text-xs text-destructive">+ {t("settings:projectGeneral.moveTargetsError")}+ </p>+ ) : (+ <div className="flex items-center gap-2">+ <Select+ value={targetWorkspaceId}+ onValueChange={(value) =>+ setTargetWorkspaceId(value ?? "")+ }+ >+ <SelectTrigger className="w-48 h-8 text-sm">+ <SelectValue+ placeholder={t(+ "settings:projectGeneral.moveProjectPlaceholder",+ )}+ >+ {moveTargets.find(+ (item) => item.id === targetWorkspaceId,+ )?.name ??+ t(+ "settings:projectGeneral.moveProjectPlaceholder",+ )}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {moveTargets.map((item) => (+ <SelectItem key={item.id} value={item.id}>+ {item.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Button+ variant="outline"+ size="sm"+ type="button"+ disabled={!targetWorkspaceId || !project || isMoving}+ onClick={() => setIsMoveModalOpen(true)}+ >+ {t("settings:projectGeneral.moveProjectAction")}+ </Button>+ </div>+ )}+ </div>+ </>+ )}</div></div>@@ -580,7 +799,7 @@ function RouteComponent() {className="text-destructive hover:text-destructive transition-colors"type="button"onClick={() => setIsDeleteModalOpen(true)}- disabled={!project}+ disabled={!project || !isCurrentProject}>{t("settings:projectGeneral.deleteProject")}</Button>@@ -589,6 +808,40 @@ function RouteComponent() {</div>)}+ <AlertDialog open={isMoveModalOpen} onOpenChange={setIsMoveModalOpen}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {t("settings:projectGeneral.moveModalTitle")}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {t("settings:projectGeneral.moveModalDescription", {+ name: project?.name ?? "",+ workspace:+ moveTargets.find((item) => item.id === targetWorkspaceId)+ ?.name ?? "",+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogClose render={<Button variant="outline" size="sm" />}>+ {t("common:actions.cancel")}+ </AlertDialogClose>+ <AlertDialogClose+ render={+ <Button+ size="sm"+ disabled={isMoving}+ onClick={handleMoveProject}+ />+ }+ >+ {t("settings:projectGeneral.moveModalConfirm")}+ </AlertDialogClose>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+<AlertDialogopen={isDeleteModalOpen}onOpenChange={setIsDeleteModalOpen}diff --git a/i18n/az-AZ.json b/i18n/az-AZ.jsonindex 9a2b50ed0..03055aba5 100644--- a/i18n/az-AZ.json+++ b/i18n/az-AZ.json@@ -942,7 +942,18 @@"iconRequired": "Nişan tələb olunur"},"importExportTasks": "İdxal/ixrac",- "importExportTasksDescription": "Tapşırıqları idxal və ixrac edin."+ "importExportTasksDescription": "Tapşırıqları idxal və ixrac edin.",+ "moveModalConfirm": "Move Project",+ "moveModalDescription": "This will move the project \"{{name}}\" and all of its tasks to \"{{workspace}}\". Tasks assigned to people who aren't members of that workspace will be unassigned, and notification subscriptions for this project will be cleared.",+ "moveModalTitle": "Move Project?",+ "moveProject": "Move to workspace",+ "moveProjectAction": "Move",+ "moveProjectDescription": "Move this project, with all of its tasks, to another workspace.",+ "moveProjectPlaceholder": "Select workspace",+ "moveTargetsError": "Couldn't check which workspaces you can move this project to. Reload to try again.",+ "toastMoved": "Project moved successfully",+ "toastMovedWithUnassigned": "Project moved successfully. {{taskCount}} task(s) were unassigned.",+ "toastMoveError": "Failed to move project"},"projectIntegrations": {"pageTitle": "Layihə inteqrasiyaları",diff --git a/i18n/de-DE.json b/i18n/de-DE.jsonindex 32732bf01..6156dc047 100644--- a/i18n/de-DE.json+++ b/i18n/de-DE.json@@ -787,7 +787,18 @@"iconRequired": "Symbol ist erforderlich"},"importExportTasks": "Import/Export",- "importExportTasksDescription": "Importieren und Exportieren von Aufgaben."+ "importExportTasksDescription": "Importieren und Exportieren von Aufgaben.",+ "moveModalConfirm": "Projekt verschieben",+ "moveModalDescription": "Dadurch werden das Projekt \"{{name}}\" und alle zugehörigen Aufgaben nach \"{{workspace}}\" verschoben. Bei Aufgaben, die Personen zugewiesen sind, die kein Mitglied dieses Workspaces sind, wird die Zuweisung aufgehoben, und Benachrichtigungs-Abonnements für dieses Projekt werden entfernt.",+ "moveModalTitle": "Projekt verschieben?",+ "moveProject": "In Workspace verschieben",+ "moveProjectAction": "Verschieben",+ "moveProjectDescription": "Verschiebe dieses Projekt mit allen zugehörigen Aufgaben in einen anderen Workspace.",+ "moveProjectPlaceholder": "Workspace auswählen",+ "toastMoved": "Projekt erfolgreich verschoben",+ "toastMovedWithUnassigned": "Projekt erfolgreich verschoben. Bei {{taskCount}} Aufgabe(n) wurde die Zuweisung aufgehoben.",+ "toastMoveError": "Projekt konnte nicht verschoben werden",+ "moveTargetsError": "Es konnte nicht geprüft werden, in welche Workspaces du dieses Projekt verschieben kannst. Lade die Seite neu, um es erneut zu versuchen."},"projectIntegrations": {"pageTitle": "Projektintegrationen",diff --git a/i18n/el-GR.json b/i18n/el-GR.jsonindex be4b4d980..c1a019779 100644--- a/i18n/el-GR.json+++ b/i18n/el-GR.json@@ -707,7 +707,18 @@"iconRequired": "Το εικονίδιο είναι υποχρεωτικό"},"importExportTasks": "Εισαγωγή/Εξαγωγή",- "importExportTasksDescription": "Εισαγωγή/Εξαγωγή Εργασιών"+ "importExportTasksDescription": "Εισαγωγή/Εξαγωγή Εργασιών",+ "moveModalConfirm": "Μετακίνηση έργου",+ "moveModalDescription": "Αυτό θα μετακινήσει το έργο \"{{name}}\" και όλες τις εργασίες του στο \"{{workspace}}\". Οι εργασίες που έχουν ανατεθεί σε άτομα που δεν είναι μέλη αυτού του χώρου εργασίας θα αποδεσμευτούν και οι συνδρομές ειδοποιήσεων για αυτό το έργο θα διαγραφούν.",+ "moveModalTitle": "Μετακίνηση έργου;",+ "moveProject": "Μετακίνηση σε χώρο εργασίας",+ "moveProjectAction": "Μετακίνηση",+ "moveProjectDescription": "Μετακινήστε αυτό το έργο, μαζί με όλες τις εργασίες του, σε άλλο χώρο εργασίας.",+ "moveProjectPlaceholder": "Επιλέξτε χώρο εργασίας",+ "toastMoved": "Το έργο μετακινήθηκε με επιτυχία",+ "toastMovedWithUnassigned": "Το έργο μετακινήθηκε με επιτυχία. Αφαιρέθηκε η ανάθεση από {{taskCount}} εργασίες.",+ "toastMoveError": "Αποτυχία μετακίνησης του έργου",+ "moveTargetsError": "Δεν ήταν δυνατός ο έλεγχος των χώρων εργασίας στους οποίους μπορείτε να μετακινήσετε αυτό το έργο. Ανανεώστε τη σελίδα για να δοκιμάσετε ξανά."},"projectIntegrations": {"pageTitle": "Ενσωματώσεις έργου",diff --git a/i18n/en-US.json b/i18n/en-US.jsonindex 81d0b4839..5672ea913 100644--- a/i18n/en-US.json+++ b/i18n/en-US.json@@ -1022,7 +1022,18 @@"iconRequired": "Icon is required"},"importExportTasks": "Import/Export",- "importExportTasksDescription": "Import and export tasks."+ "importExportTasksDescription": "Import and export tasks.",+ "moveProject": "Move to workspace",+ "moveProjectDescription": "Move this project, with all of its tasks, to another workspace.",+ "moveProjectPlaceholder": "Select workspace",+ "moveTargetsError": "Couldn't check which workspaces you can move this project to. Reload to try again.",+ "moveProjectAction": "Move",+ "moveModalTitle": "Move Project?",+ "moveModalDescription": "This will move the project \"{{name}}\" and all of its tasks to \"{{workspace}}\". Tasks assigned to people who aren't members of that workspace will be unassigned, and notification subscriptions for this project will be cleared.",+ "moveModalConfirm": "Move Project",+ "toastMoved": "Project moved successfully",+ "toastMovedWithUnassigned": "Project moved successfully. {{taskCount}} task(s) were unassigned.",+ "toastMoveError": "Failed to move project"},"projectIntegrations": {"pageTitle": "Project Integrations",diff --git a/i18n/es-ES.json b/i18n/es-ES.jsonindex 08a63e7c2..3a0324bc8 100644--- a/i18n/es-ES.json+++ b/i18n/es-ES.json@@ -604,7 +604,18 @@"iconRequired": "El icono es obligatorio"},"importExportTasks": "Importar/Exportar",- "importExportTasksDescription": "Importar/Exportar Tareas"+ "importExportTasksDescription": "Importar/Exportar Tareas",+ "moveModalConfirm": "Mover proyecto",+ "moveModalDescription": "Esto moverá el proyecto \"{{name}}\" y todas sus tareas a \"{{workspace}}\". Las tareas asignadas a personas que no son miembros de ese espacio de trabajo quedarán sin asignar, y se eliminarán las suscripciones de notificaciones de este proyecto.",+ "moveModalTitle": "¿Mover proyecto?",+ "moveProject": "Mover a otro espacio de trabajo",+ "moveProjectAction": "Mover",+ "moveProjectDescription": "Mueve este proyecto, con todas sus tareas, a otro espacio de trabajo.",+ "moveProjectPlaceholder": "Selecciona un espacio de trabajo",+ "toastMoved": "Proyecto movido correctamente",+ "toastMovedWithUnassigned": "Proyecto movido correctamente. {{taskCount}} tarea(s) quedaron sin asignar.",+ "toastMoveError": "No se pudo mover el proyecto",+ "moveTargetsError": "No se pudo comprobar a qué espacios de trabajo puedes mover este proyecto. Vuelve a cargar la página para intentarlo de nuevo."},"projectIntegrations": {"pageTitle": "Integraciones del Proyecto",diff --git a/i18n/fr-FR.json b/i18n/fr-FR.jsonindex 42b2d8c4c..65b9ce5f2 100644--- a/i18n/fr-FR.json+++ b/i18n/fr-FR.json@@ -707,7 +707,18 @@"iconRequired": "L'icône est requise"},"importExportTasks": "Importation/Exportation",- "importExportTasksDescription": "Importation/Exportation des Tâches"+ "importExportTasksDescription": "Importation/Exportation des Tâches",+ "moveModalConfirm": "Déplacer le projet",+ "moveModalDescription": "Cette action déplacera le projet \"{{name}}\" et toutes ses tâches vers \"{{workspace}}\". Les tâches assignées à des personnes qui ne sont pas membres de cet espace de travail seront désassignées, et les abonnements aux notifications de ce projet seront supprimés.",+ "moveModalTitle": "Déplacer le projet ?",+ "moveProject": "Déplacer vers un espace de travail",+ "moveProjectAction": "Déplacer",+ "moveProjectDescription": "Déplacez ce projet, avec toutes ses tâches, vers un autre espace de travail.",+ "moveProjectPlaceholder": "Sélectionner un espace de travail",+ "toastMoved": "Projet déplacé avec succès",+ "toastMovedWithUnassigned": "Projet déplacé avec succès. {{taskCount}} tâche(s) ont été désassignées.",+ "toastMoveError": "Échec du déplacement du projet",+ "moveTargetsError": "Impossible de vérifier vers quels espaces de travail vous pouvez déplacer ce projet. Rechargez la page pour réessayer."},"projectIntegrations": {"pageTitle": "Intégrations du projet",diff --git a/i18n/hi-IN.json b/i18n/hi-IN.jsonindex 77d16c9ff..fef994b0b 100644--- a/i18n/hi-IN.json+++ b/i18n/hi-IN.json@@ -942,7 +942,18 @@"iconRequired": "आइकन आवश्यक है"},"importExportTasks": "आयात/निर्यात",- "importExportTasksDescription": "कार्यों को आयात और निर्यात करें।"+ "importExportTasksDescription": "कार्यों को आयात और निर्यात करें।",+ "moveModalConfirm": "प्रोजेक्ट ले जाएँ",+ "moveModalDescription": "इससे प्रोजेक्ट \"{{name}}\" और उसके सभी कार्य \"{{workspace}}\" में चले जाएँगे। जो कार्य उन लोगों को सौंपे गए हैं जो उस वर्कस्पेस के सदस्य नहीं हैं, उनका असाइनमेंट हटा दिया जाएगा, और इस प्रोजेक्ट की सूचना सदस्यताएँ हटा दी जाएँगी।",+ "moveModalTitle": "प्रोजेक्ट ले जाएँ?",+ "moveProject": "वर्कस्पेस में ले जाएँ",+ "moveProjectAction": "ले जाएँ",+ "moveProjectDescription": "इस प्रोजेक्ट को उसके सभी कार्यों सहित किसी अन्य वर्कस्पेस में ले जाएँ।",+ "moveProjectPlaceholder": "वर्कस्पेस चुनें",+ "toastMoved": "प्रोजेक्ट सफलतापूर्वक ले जाया गया",+ "toastMovedWithUnassigned": "प्रोजेक्ट सफलतापूर्वक ले जाया गया। {{taskCount}} कार्य का असाइनमेंट हटा दिया गया।",+ "toastMoveError": "प्रोजेक्ट ले जाने में विफल",+ "moveTargetsError": "यह जाँचा नहीं जा सका कि आप इस प्रोजेक्ट को किन वर्कस्पेस में ले जा सकते हैं। पुनः प्रयास करने के लिए पेज रीलोड करें।"},"projectIntegrations": {"pageTitle": "प्रोजेक्ट एकीकरण",diff --git a/i18n/id-ID.json b/i18n/id-ID.jsonindex f1f6b0f8d..bf264756a 100644--- a/i18n/id-ID.json+++ b/i18n/id-ID.json@@ -707,7 +707,18 @@"iconRequired": "Ikon wajib diisi"},"importExportTasks": "Impor/Ekspor",- "importExportTasksDescription": "Impor dan ekspor tugas."+ "importExportTasksDescription": "Impor dan ekspor tugas.",+ "moveModalConfirm": "Pindahkan proyek",+ "moveModalDescription": "Tindakan ini akan memindahkan proyek \"{{name}}\" beserta semua tugasnya ke \"{{workspace}}\". Tugas yang ditugaskan kepada orang yang bukan anggota ruang kerja tersebut akan dilepas penugasannya, dan langganan notifikasi untuk proyek ini akan dihapus.",+ "moveModalTitle": "Pindahkan proyek?",+ "moveProject": "Pindahkan ke ruang kerja",+ "moveProjectAction": "Pindahkan",+ "moveProjectDescription": "Pindahkan proyek ini, beserta semua tugasnya, ke ruang kerja lain.",+ "moveProjectPlaceholder": "Pilih ruang kerja",+ "toastMoved": "Proyek berhasil dipindahkan",+ "toastMovedWithUnassigned": "Proyek berhasil dipindahkan. {{taskCount}} tugas dilepas penugasannya.",+ "toastMoveError": "Gagal memindahkan proyek",+ "moveTargetsError": "Tidak dapat memeriksa ruang kerja mana saja yang dapat menjadi tujuan pemindahan proyek ini. Muat ulang halaman untuk mencoba lagi."},"projectIntegrations": {"pageTitle": "Integrasi Proyek",diff --git a/i18n/it-IT.json b/i18n/it-IT.jsonindex df6682ff3..869a9c5dc 100644--- a/i18n/it-IT.json+++ b/i18n/it-IT.json@@ -943,7 +943,18 @@"iconRequired": "L'icona è obbligatoria"},"importExportTasks": "Importa/Esporta",- "importExportTasksDescription": "Importa ed esporta attività."+ "importExportTasksDescription": "Importa ed esporta attività.",+ "moveModalConfirm": "Sposta progetto",+ "moveModalDescription": "Questa azione sposterà il progetto \"{{name}}\" e tutte le sue attività in \"{{workspace}}\". Le attività assegnate a persone che non sono membri di quel workspace resteranno senza assegnatario e le iscrizioni alle notifiche per questo progetto verranno eliminate.",+ "moveModalTitle": "Spostare il progetto?",+ "moveProject": "Sposta in un altro workspace",+ "moveProjectAction": "Sposta",+ "moveProjectDescription": "Sposta questo progetto, con tutte le sue attività, in un altro workspace.",+ "moveProjectPlaceholder": "Seleziona workspace",+ "toastMoved": "Progetto spostato con successo",+ "toastMovedWithUnassigned": "Progetto spostato con successo. {{taskCount}} attività sono rimaste senza assegnatario.",+ "toastMoveError": "Impossibile spostare il progetto",+ "moveTargetsError": "Non è stato possibile verificare in quali spazi di lavoro puoi spostare questo progetto. Ricarica la pagina per riprovare."},"projectIntegrations": {"pageTitle": "Integrazioni Progetto",diff --git a/i18n/ja-JP.json b/i18n/ja-JP.jsonindex 444a2f2af..1ffcf22ed 100644--- a/i18n/ja-JP.json+++ b/i18n/ja-JP.json@@ -941,7 +941,18 @@"iconRequired": "アイコンは必須です"},"importExportTasks": "インポート/エクスポート",- "importExportTasksDescription": "タスクのインポートとエクスポートを行います。"+ "importExportTasksDescription": "タスクのインポートとエクスポートを行います。",+ "moveModalConfirm": "Move Project",+ "moveModalDescription": "This will move the project \"{{name}}\" and all of its tasks to \"{{workspace}}\". Tasks assigned to people who aren't members of that workspace will be unassigned, and notification subscriptions for this project will be cleared.",+ "moveModalTitle": "Move Project?",+ "moveProject": "Move to workspace",+ "moveProjectAction": "Move",+ "moveProjectDescription": "Move this project, with all of its tasks, to another workspace.",+ "moveProjectPlaceholder": "Select workspace",+ "moveTargetsError": "Couldn't check which workspaces you can move this project to. Reload to try again.",+ "toastMoved": "Project moved successfully",+ "toastMovedWithUnassigned": "Project moved successfully. {{taskCount}} task(s) were unassigned.",+ "toastMoveError": "Failed to move project"},"projectIntegrations": {"pageTitle": "プロジェクト連携",diff --git a/i18n/ko-KR.json b/i18n/ko-KR.jsonindex 1ab5a309b..99372dac8 100644--- a/i18n/ko-KR.json+++ b/i18n/ko-KR.json@@ -707,7 +707,18 @@"iconRequired": "아이콘은 필수입니다"},"importExportTasks": "가져오기/내보내기",- "importExportTasksDescription": "작업을 가져오고 내보냅니다."+ "importExportTasksDescription": "작업을 가져오고 내보냅니다.",+ "moveModalConfirm": "프로젝트 이동",+ "moveModalDescription": "프로젝트 \"{{name}}\"과(와) 모든 작업이 \"{{workspace}}\"(으)로 이동됩니다. 해당 워크스페이스의 멤버가 아닌 사람에게 할당된 작업은 할당이 해제되며, 이 프로젝트의 알림 구독도 삭제됩니다.",+ "moveModalTitle": "프로젝트를 이동할까요?",+ "moveProject": "워크스페이스로 이동",+ "moveProjectAction": "이동",+ "moveProjectDescription": "이 프로젝트를 모든 작업과 함께 다른 워크스페이스로 이동합니다.",+ "moveProjectPlaceholder": "워크스페이스 선택",+ "toastMoved": "프로젝트를 이동했습니다",+ "toastMovedWithUnassigned": "프로젝트를 이동했습니다. {{taskCount}}개 작업의 할당이 해제되었습니다.",+ "toastMoveError": "프로젝트를 이동하지 못했습니다",+ "moveTargetsError": "이 프로젝트를 옮길 수 있는 워크스페이스를 확인하지 못했습니다. 페이지를 새로고침해 다시 시도하세요."},"projectIntegrations": {"pageTitle": "프로젝트 연동",diff --git a/i18n/mk-MK.json b/i18n/mk-MK.jsonindex 244a1b893..66136e7f8 100644--- a/i18n/mk-MK.json+++ b/i18n/mk-MK.json@@ -707,7 +707,18 @@"iconRequired": "Иконата е задолжителна"},"importExportTasks": "Импортирање/Експортирање",- "importExportTasksDescription": "Импортирање/Експортирање на задачи"+ "importExportTasksDescription": "Импортирање/Експортирање на задачи",+ "moveModalConfirm": "Премести проект",+ "moveModalDescription": "Ова ќе го премести проектот \"{{name}}\" и сите негови задачи во \"{{workspace}}\". Задачите доделени на луѓе што не се членови на тој работен простор ќе останат недоделени, а претплатите на известувања за овој проект ќе бидат отстранети.",+ "moveModalTitle": "Премести проект?",+ "moveProject": "Премести во работен простор",+ "moveProjectAction": "Премести",+ "moveProjectDescription": "Премести го овој проект, заедно со сите негови задачи, во друг работен простор.",+ "moveProjectPlaceholder": "Избери работен простор",+ "toastMoved": "Проектот е успешно преместен",+ "toastMovedWithUnassigned": "Проектот е успешно преместен. {{taskCount}} задачи останаа недоделени.",+ "toastMoveError": "Неуспешно преместување на проектот",+ "moveTargetsError": "Не можеше да се провери во кои работни простори може да го преместите овој проект. Освежете ја страницата за да се обидете повторно."},"projectIntegrations": {"pageTitle": "Интеграции на проект",diff --git a/i18n/nl-NL.json b/i18n/nl-NL.jsonindex 5711b60d8..d5526b3c8 100644--- a/i18n/nl-NL.json+++ b/i18n/nl-NL.json@@ -604,7 +604,18 @@"iconRequired": "Icoon is verplicht"},"importExportTasks": "Importeren/Exporteren",- "importExportTasksDescription": "Importeren/Exporteren taken"+ "importExportTasksDescription": "Importeren/Exporteren taken",+ "moveModalConfirm": "Project verplaatsen",+ "moveModalDescription": "Hiermee worden het project \"{{name}}\" en al zijn taken verplaatst naar \"{{workspace}}\". Taken die zijn toegewezen aan personen die geen lid zijn van die werkruimte worden niet langer toegewezen, en meldingsabonnementen voor dit project worden verwijderd.",+ "moveModalTitle": "Project verplaatsen?",+ "moveProject": "Naar werkruimte verplaatsen",+ "moveProjectAction": "Verplaatsen",+ "moveProjectDescription": "Verplaats dit project, met al zijn taken, naar een andere werkruimte.",+ "moveProjectPlaceholder": "Selecteer werkruimte",+ "toastMoved": "Project succesvol verplaatst",+ "toastMovedWithUnassigned": "Project succesvol verplaatst. {{taskCount}} taak/taken zijn niet langer toegewezen.",+ "toastMoveError": "Verplaatsen van project mislukt",+ "moveTargetsError": "Kon niet controleren naar welke workspaces je dit project kunt verplaatsen. Herlaad de pagina om het opnieuw te proberen."},"projectIntegrations": {"pageTitle": "Projectintegraties",diff --git a/i18n/pl-PL.json b/i18n/pl-PL.jsonindex f7acd459a..721138f58 100644--- a/i18n/pl-PL.json+++ b/i18n/pl-PL.json@@ -1406,7 +1406,18 @@"keyMax": "Klucz może mieć maksymalnie 8 znaków","keyRequired": "Klucz jest wymagany","nameRequired": "Nazwa projektu jest wymagana"- }+ },+ "moveModalConfirm": "Move Project",+ "moveModalDescription": "This will move the project \"{{name}}\" and all of its tasks to \"{{workspace}}\". Tasks assigned to people who aren't members of that workspace will be unassigned, and notification subscriptions for this project will be cleared.",+ "moveModalTitle": "Move Project?",+ "moveProject": "Move to workspace",+ "moveProjectAction": "Move",+ "moveProjectDescription": "Move this project, with all of its tasks, to another workspace.",+ "moveProjectPlaceholder": "Select workspace",+ "moveTargetsError": "Couldn't check which workspaces you can move this project to. Reload to try again.",+ "toastMoved": "Project moved successfully",+ "toastMovedWithUnassigned": "Project moved successfully. {{taskCount}} task(s) were unassigned.",+ "toastMoveError": "Failed to move project"},"projectIntegrations": {"discordSectionSubtitle": "Wysyłaj aktualizacje zadań projektu na kanał Discord za pomocą webhooka.",diff --git a/i18n/pt-BR.json b/i18n/pt-BR.jsonindex f94b34940..e155315d5 100644--- a/i18n/pt-BR.json+++ b/i18n/pt-BR.json@@ -943,7 +943,18 @@"iconRequired": "O ícone é obrigatório"},"importExportTasks": "Importar/Exportar",- "importExportTasksDescription": "Importe e exporte tarefas."+ "importExportTasksDescription": "Importe e exporte tarefas.",+ "moveModalConfirm": "Mover projeto",+ "moveModalDescription": "Isso moverá o projeto \"{{name}}\" e todas as suas tarefas para \"{{workspace}}\". As tarefas atribuídas a pessoas que não são membros desse espaço de trabalho ficarão sem responsável, e as inscrições de notificação deste projeto serão removidas.",+ "moveModalTitle": "Mover projeto?",+ "moveProject": "Mover para outro espaço de trabalho",+ "moveProjectAction": "Mover",+ "moveProjectDescription": "Mova este projeto, com todas as suas tarefas, para outro espaço de trabalho.",+ "moveProjectPlaceholder": "Selecione um espaço de trabalho",+ "toastMoved": "Projeto movido com sucesso",+ "toastMovedWithUnassigned": "Projeto movido com sucesso. {{taskCount}} tarefa(s) ficaram sem responsável.",+ "toastMoveError": "Falha ao mover o projeto",+ "moveTargetsError": "Não foi possível verificar para quais workspaces você pode mover este projeto. Recarregue a página para tentar novamente."},"projectIntegrations": {"pageTitle": "Integrações do projeto",diff --git a/i18n/ru-RU.json b/i18n/ru-RU.jsonindex 451141be3..ddbf8353b 100644--- a/i18n/ru-RU.json+++ b/i18n/ru-RU.json@@ -707,7 +707,18 @@"iconRequired": "Иконка обязательна"},"importExportTasks": "Импорт/Экспорт",- "importExportTasksDescription": "Импортируйте и экспортируйте задачи."+ "importExportTasksDescription": "Импортируйте и экспортируйте задачи.",+ "moveModalConfirm": "Переместить проект",+ "moveModalDescription": "Проект «{{name}}» и все его задачи будут перемещены в «{{workspace}}». С задач, назначенных пользователям, которые не состоят в этой рабочей области, назначение будет снято, а подписки на уведомления по этому проекту будут удалены.",+ "moveModalTitle": "Переместить проект?",+ "moveProject": "Переместить в другую рабочую область",+ "moveProjectAction": "Переместить",+ "moveProjectDescription": "Переместите этот проект вместе со всеми задачами в другую рабочую область.",+ "moveProjectPlaceholder": "Выберите рабочую область",+ "toastMoved": "Проект успешно перемещён",+ "toastMovedWithUnassigned": "Проект успешно перемещён. С {{taskCount}} задач(и) снято назначение.",+ "toastMoveError": "Не удалось переместить проект",+ "moveTargetsError": "Не удалось проверить, в какие рабочие пространства можно переместить этот проект. Обновите страницу, чтобы повторить попытку."},"projectIntegrations": {"pageTitle": "Интеграции проекта",diff --git a/i18n/schema.json b/i18n/schema.jsonindex a93343dee..0ab120235 100644--- a/i18n/schema.json+++ b/i18n/schema.json@@ -3949,6 +3949,39 @@},"importExportTasksDescription": {"type": "string"+ },+ "moveProject": {+ "type": "string"+ },+ "moveProjectDescription": {+ "type": "string"+ },+ "moveProjectPlaceholder": {+ "type": "string"+ },+ "moveTargetsError": {+ "type": "string"+ },+ "moveProjectAction": {+ "type": "string"+ },+ "moveModalTitle": {+ "type": "string"+ },+ "moveModalDescription": {+ "type": "string"+ },+ "moveModalConfirm": {+ "type": "string"+ },+ "toastMoved": {+ "type": "string"+ },+ "toastMovedWithUnassigned": {+ "type": "string"+ },+ "toastMoveError": {+ "type": "string"}},"required": [@@ -3983,7 +4016,18 @@"toastDeleteError","validation","importExportTasks",- "importExportTasksDescription"+ "importExportTasksDescription",+ "moveProject",+ "moveProjectDescription",+ "moveProjectPlaceholder",+ "moveTargetsError",+ "moveProjectAction",+ "moveModalTitle",+ "moveModalDescription",+ "moveModalConfirm",+ "toastMoved",+ "toastMovedWithUnassigned",+ "toastMoveError"]},"projectIntegrations": {diff --git a/i18n/tr-TR.json b/i18n/tr-TR.jsonindex 696a8d027..c8461e639 100644--- a/i18n/tr-TR.json+++ b/i18n/tr-TR.json@@ -707,7 +707,18 @@"iconRequired": "Simge gereklidir"},"importExportTasks": "İçe/Dışa Aktar",- "importExportTasksDescription": "Talepleri içe ve dışa aktarın."+ "importExportTasksDescription": "Talepleri içe ve dışa aktarın.",+ "moveModalConfirm": "Projeyi taşı",+ "moveModalDescription": "Bu işlem \"{{name}}\" projesini ve tüm görevlerini \"{{workspace}}\" alanına taşır. O çalışma alanının üyesi olmayan kişilere atanmış görevlerin ataması kaldırılır ve bu projeye ait bildirim abonelikleri silinir.",+ "moveModalTitle": "Proje taşınsın mı?",+ "moveProject": "Çalışma alanına taşı",+ "moveProjectAction": "Taşı",+ "moveProjectDescription": "Bu projeyi tüm görevleriyle birlikte başka bir çalışma alanına taşıyın.",+ "moveProjectPlaceholder": "Çalışma alanı seçin",+ "toastMoved": "Proje başarıyla taşındı",+ "toastMovedWithUnassigned": "Proje başarıyla taşındı. {{taskCount}} görevin ataması kaldırıldı.",+ "toastMoveError": "Proje taşınamadı",+ "moveTargetsError": "Bu projeyi hangi çalışma alanlarına taşıyabileceğiniz kontrol edilemedi. Yeniden denemek için sayfayı yenileyin."},"projectIntegrations": {"pageTitle": "Proje Entegrasyonları",diff --git a/i18n/uk-UA.json b/i18n/uk-UA.jsonindex 16ea44c2d..4ee7b6639 100644--- a/i18n/uk-UA.json+++ b/i18n/uk-UA.json@@ -707,7 +707,18 @@"iconRequired": "Іконка є обов'язковою"},"importExportTasks": "Імпорт/Експорт",- "importExportTasksDescription": "Імпортуйте та експортуйте завдання."+ "importExportTasksDescription": "Імпортуйте та експортуйте завдання.",+ "moveModalConfirm": "Перемістити проєкт",+ "moveModalDescription": "Проєкт «{{name}}» і всі його завдання буде переміщено до «{{workspace}}». Із завдань, призначених людям, які не є учасниками цього робочого простору, буде знято призначення, а підписки на сповіщення для цього проєкту буде видалено.",+ "moveModalTitle": "Перемістити проєкт?",+ "moveProject": "Перемістити до робочого простору",+ "moveProjectAction": "Перемістити",+ "moveProjectDescription": "Перемістіть цей проєкт разом з усіма його завданнями до іншого робочого простору.",+ "moveProjectPlaceholder": "Виберіть робочий простір",+ "toastMoved": "Проєкт успішно переміщено",+ "toastMovedWithUnassigned": "Проєкт успішно переміщено. Із {{taskCount}} завдань знято призначення.",+ "toastMoveError": "Не вдалося перемістити проєкт",+ "moveTargetsError": "Не вдалося перевірити, до яких робочих просторів можна перемістити цей проєкт. Перезавантажте сторінку, щоб спробувати ще раз."},"projectIntegrations": {"pageTitle": "Інтеґрації проєкту",diff --git a/i18n/vi-VN.json b/i18n/vi-VN.jsonindex b6e2ef6e1..73562f867 100644--- a/i18n/vi-VN.json+++ b/i18n/vi-VN.json@@ -941,7 +941,18 @@"iconRequired": "Cần có biểu tượng"},"importExportTasks": "Nhập/Xuất",- "importExportTasksDescription": "Nhập và xuất công việc."+ "importExportTasksDescription": "Nhập và xuất công việc.",+ "moveModalConfirm": "Chuyển dự án",+ "moveModalDescription": "Thao tác này sẽ chuyển dự án \"{{name}}\" và tất cả công việc của nó sang \"{{workspace}}\". Những công việc được giao cho người không phải là thành viên của không gian làm việc đó sẽ bị hủy phân công, và các đăng ký thông báo cho dự án này sẽ bị xóa.",+ "moveModalTitle": "Chuyển dự án?",+ "moveProject": "Chuyển đến không gian làm việc",+ "moveProjectAction": "Chuyển",+ "moveProjectDescription": "Chuyển dự án này, cùng với tất cả công việc của nó, sang không gian làm việc khác.",+ "moveProjectPlaceholder": "Chọn không gian làm việc",+ "toastMoved": "Đã chuyển dự án thành công",+ "toastMovedWithUnassigned": "Đã chuyển dự án thành công. {{taskCount}} công việc đã bị hủy phân công.",+ "toastMoveError": "Không thể chuyển dự án",+ "moveTargetsError": "Không thể kiểm tra những không gian làm việc mà bạn có thể chuyển dự án này đến. Hãy tải lại trang để thử lại."},"projectIntegrations": {"pageTitle": "Tích hợp dự án",diff --git a/i18n/zh-CN.json b/i18n/zh-CN.jsonindex 316e7541d..d4416d550 100644--- a/i18n/zh-CN.json+++ b/i18n/zh-CN.json@@ -941,7 +941,18 @@"iconRequired": "图标不能为空"},"importExportTasks": "导入/导出",- "importExportTasksDescription": "导入和导出任务。"+ "importExportTasksDescription": "导入和导出任务。",+ "moveModalConfirm": "移动项目",+ "moveModalDescription": "这将把项目 \"{{name}}\" 及其所有任务移动到 \"{{workspace}}\"。分配给非该工作区成员的任务将被取消分配,此项目的通知订阅也会被清除。",+ "moveModalTitle": "移动项目?",+ "moveProject": "移动到其他工作区",+ "moveProjectAction": "移动",+ "moveProjectDescription": "将此项目及其所有任务移动到其他工作区。",+ "moveProjectPlaceholder": "选择工作区",+ "toastMoved": "项目移动成功",+ "toastMovedWithUnassigned": "项目移动成功。已取消分配 {{taskCount}} 个任务。",+ "toastMoveError": "移动项目失败",+ "moveTargetsError": "无法检查你可以将此项目移动到哪些工作区。请重新加载页面后重试。"},"projectIntegrations": {"pageTitle": "项目集成",diff --git a/tests/api-integration/project-move.test.ts b/tests/api-integration/project-move.test.tsnew file mode 100644index 000000000..a902bd422--- /dev/null+++ b/tests/api-integration/project-move.test.ts@@ -0,0 +1,701 @@+import { randomUUID } from "node:crypto";+import { eq, sql } from "drizzle-orm";+import type { WSContext } from "hono/ws";+import { beforeEach, describe, expect, it, vi } from "vitest";+import db, { schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import createTaskRelation from "../../apps/api/src/task-relation/controllers/create-task-relation";+import { addConnection, removeConnection } from "../../apps/api/src/ws";+import { mockAuthenticatedSession } from "./helpers/auth";+import { resetTestDatabase } from "./helpers/database";+import {+ createProjectFixture,+ createWorkspaceMember,+} from "./helpers/fixtures";++async function addMember(workspaceId: string, userId: string, role = "member") {+ await db.insert(schema.workspaceUserTable).values({+ workspaceId,+ userId,+ role,+ joinedAt: new Date(),+ });+}++async function createTargetWorkspace() {+ const [workspace] = await db+ .insert(schema.workspaceTable)+ .values({+ id: `workspace-${randomUUID()}`,+ createdAt: new Date(),+ name: "Target Workspace",+ slug: `workspace-${randomUUID()}`,+ })+ .returning();++ return workspace;+}++// Activity rows are written by an event subscriber that the request doesn't+// await, so give the emitter a moment to drain before asserting.+async function waitForActivities(taskId: string, timeoutMs = 2000) {+ const deadline = Date.now() + timeoutMs;++ while (Date.now() < deadline) {+ const rows = await db+ .select()+ .from(schema.activityTable)+ .where(eq(schema.activityTable.taskId, taskId));++ if (rows.length > 0) return rows;+ await new Promise((resolve) => setTimeout(resolve, 25));+ }++ return [];+}++function moveRequest(workspaceId: string) {+ return {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ workspaceId }),+ };+}++describe("API integration: moving a project between workspaces", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ });++ it("rejects a move into a workspace the caller doesn't belong to", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const target = await createTargetWorkspace();+ const { project } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });++ mockAuthenticatedSession(owner.user);+ const { app } = createApp();++ const response = await app.request(+ `/api/project/${project.id}/move`,+ moveRequest(target.id),+ );++ expect(response.status).toBe(403);++ const [unchanged] = await db+ .select()+ .from(schema.projectTable)+ .where(eq(schema.projectTable.id, project.id));+ expect(unchanged.workspaceId).toBe(owner.workspace.id);+ });++ it("rejects a move when the caller can't create projects in the target", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const target = await createTargetWorkspace();+ // `viewer` grants only project:read in the target workspace.+ await addMember(target.id, owner.user.id, "viewer");+ const { project } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });++ mockAuthenticatedSession(owner.user);+ const { app } = createApp();++ const response = await app.request(+ `/api/project/${project.id}/move`,+ moveRequest(target.id),+ );++ expect(response.status).toBe(403);+ });++ it("rejects a move when the target workspace already uses the project's key", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const target = await createTargetWorkspace();+ await addMember(target.id, owner.user.id, "owner");++ const { project } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ slug: "kan",+ });+ // Different case on purpose: short-id lookup matches keys+ // case-insensitively, so "KAN" and "kan" collide just the same.+ await createProjectFixture({+ workspaceId: target.id,+ name: "Incumbent",+ slug: "KAN",+ });++ mockAuthenticatedSession(owner.user);+ const { app } = createApp();++ const response = await app.request(+ `/api/project/${project.id}/move`,+ moveRequest(target.id),+ );++ expect(response.status).toBe(409);+ expect(await response.text()).toContain("Incumbent");++ const [unchanged] = await db+ .select()+ .from(schema.projectTable)+ .where(eq(schema.projectTable.id, project.id));+ expect(unchanged.workspaceId).toBe(owner.workspace.id);+ });++ it("allows a move when only the source workspace uses that key", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const target = await createTargetWorkspace();+ await addMember(target.id, owner.user.id, "owner");++ // A same-key project left behind in the source must not block the move —+ // only the target workspace's keys matter.+ const { project } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ slug: "kan",+ });+ await createProjectFixture({+ workspaceId: owner.workspace.id,+ name: "Sibling",+ slug: "kan",+ });++ mockAuthenticatedSession(owner.user);+ const { app } = createApp();++ const response = await app.request(+ `/api/project/${project.id}/move`,+ moveRequest(target.id),+ );++ expect(response.status).toBe(200);++ const [moved] = await db+ .select()+ .from(schema.projectTable)+ .where(eq(schema.projectTable.id, project.id));+ expect(moved.workspaceId).toBe(target.id);+ });++ it("appends the moved project to the end of the target's ordering", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const target = await createTargetWorkspace();+ await addMember(target.id, owner.user.id, "owner");++ // Position 0 in the source, which is already taken in the target: keeping+ // it would leave two projects sharing a slot.+ const { project } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });+ const { project: firstInTarget } = await createProjectFixture({+ workspaceId: target.id,+ name: "First",+ });+ const { project: secondInTarget } = await createProjectFixture({+ workspaceId: target.id,+ name: "Second",+ });+ await db+ .update(schema.projectTable)+ .set({ position: 1 })+ .where(eq(schema.projectTable.id, secondInTarget.id));++ mockAuthenticatedSession(owner.user);+ const { app } = createApp();++ const response = await app.request(+ `/api/project/${project.id}/move`,+ moveRequest(target.id),+ );++ expect(response.status).toBe(200);++ const [moved] = await db+ .select()+ .from(schema.projectTable)+ .where(eq(schema.projectTable.id, project.id));+ expect(moved.position).toBe(2);++ const positions = await db+ .select({+ id: schema.projectTable.id,+ position: schema.projectTable.position,+ })+ .from(schema.projectTable)+ .where(eq(schema.projectTable.workspaceId, target.id));++ expect(+ [...positions].sort((a, b) => a.position - b.position).map((p) => p.id),+ ).toEqual([firstInTarget.id, secondInTarget.id, project.id]);+ expect(new Set(positions.map((p) => p.position)).size).toBe(3);+ });++ it("rejects a move out of a workspace where the caller can't delete projects", async () => {+ const mover = await createWorkspaceMember({ role: "project-editor" });+ const target = await createTargetWorkspace();+ // Full rights in the target, so a 403 here can only come from the source.+ await addMember(target.id, mover.user.id, "owner");+ // A custom role is the only way to hold `update` without `delete`: every+ // built-in role that grants one grants the other.+ await db.insert(schema.workspaceRoleTable).values({+ workspaceId: mover.workspace.id,+ role: "project-editor",+ permission: JSON.stringify({+ project: ["create", "read", "update"],+ }),+ });++ const { project } = await createProjectFixture({+ workspaceId: mover.workspace.id,+ });++ mockAuthenticatedSession(mover.user);+ const { app } = createApp();++ const response = await app.request(+ `/api/project/${project.id}/move`,+ moveRequest(target.id),+ );++ expect(response.status).toBe(403);++ const [unchanged] = await db+ .select()+ .from(schema.projectTable)+ .where(eq(schema.projectTable.id, project.id));+ expect(unchanged.workspaceId).toBe(mover.workspace.id);+ });++ it("rejects a move into the workspace the project is already in", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const { project } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });++ mockAuthenticatedSession(owner.user);+ const { app } = createApp();++ const response = await app.request(+ `/api/project/${project.id}/move`,+ moveRequest(owner.workspace.id),+ );++ expect(response.status).toBe(400);+ });++ it("moves the project and rewrites workspace-scoped side data", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const target = await createTargetWorkspace();+ await addMember(target.id, owner.user.id, "owner");++ const { project, columns } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });++ const [task] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Ship it",+ columnId: columns.todo.id,+ number: 1,+ userId: owner.user.id,+ })+ .returning();++ const [label] = await db+ .insert(schema.labelTable)+ .values({+ name: "bug",+ color: "#ff0000",+ taskId: task.id,+ workspaceId: owner.workspace.id,+ })+ .returning();++ const [asset] = await db+ .insert(schema.assetTable)+ .values({+ workspaceId: owner.workspace.id,+ projectId: project.id,+ taskId: task.id,+ objectKey: `object-${randomUUID()}`,+ filename: "screenshot.png",+ mimeType: "image/png",+ size: 1234,+ })+ .returning();++ // A notification rule referencing the project through the composite+ // (workspaceId, projectId) foreign key. Left in place, the workspace+ // update would cascade into it and break the rule-side key.+ const [rule] = await db+ .insert(schema.userNotificationWorkspaceRuleTable)+ .values({+ userId: owner.user.id,+ workspaceId: owner.workspace.id,+ projectMode: "selected",+ })+ .returning();++ await db.insert(schema.userNotificationWorkspaceProjectTable).values({+ workspaceId: owner.workspace.id,+ workspaceRuleId: rule.id,+ projectId: project.id,+ });++ mockAuthenticatedSession(owner.user);+ const { app } = createApp();++ const response = await app.request(+ `/api/project/${project.id}/move`,+ moveRequest(target.id),+ );++ expect(response.status).toBe(200);+ const payload = (await response.json()) as {+ workspaceId: string;+ unassignedTaskCount: number;+ };+ expect(payload.workspaceId).toBe(target.id);+ expect(payload.unassignedTaskCount).toBe(0);++ const [movedProject] = await db+ .select()+ .from(schema.projectTable)+ .where(eq(schema.projectTable.id, project.id));+ expect(movedProject.workspaceId).toBe(target.id);++ const [movedLabel] = await db+ .select()+ .from(schema.labelTable)+ .where(eq(schema.labelTable.id, label.id));+ expect(movedLabel.workspaceId).toBe(target.id);++ const [movedAsset] = await db+ .select()+ .from(schema.assetTable)+ .where(eq(schema.assetTable.id, asset.id));+ expect(movedAsset.workspaceId).toBe(target.id);++ const notificationProjects = await db+ .select()+ .from(schema.userNotificationWorkspaceProjectTable)+ .where(+ eq(schema.userNotificationWorkspaceProjectTable.projectId, project.id),+ );+ expect(notificationProjects).toHaveLength(0);++ // The task and its column survive the move.+ const [movedTask] = await db+ .select()+ .from(schema.taskTable)+ .where(eq(schema.taskTable.id, task.id));+ expect(movedTask.columnId).toBe(columns.todo.id);++ const sourceListing = await app.request(+ `/api/project?workspaceId=${owner.workspace.id}`,+ );+ expect(sourceListing.status).toBe(200);+ const sourceProjects = (await sourceListing.json()) as { id: string }[];+ expect(sourceProjects.map((item) => item.id)).not.toContain(project.id);+ });++ it("unassigns tasks whose assignee isn't a member of the target workspace", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const outsider = await createWorkspaceMember({ role: "member" });+ const target = await createTargetWorkspace();+ await addMember(target.id, owner.user.id, "owner");+ // `outsider.user` is deliberately never added to the target workspace.+ await addMember(owner.workspace.id, outsider.user.id, "member");++ const { project, columns } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });++ const [keptTask] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Stays assigned",+ columnId: columns.todo.id,+ number: 1,+ userId: owner.user.id,+ })+ .returning();++ const [droppedTask] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Loses its assignee",+ columnId: columns.todo.id,+ number: 2,+ userId: outsider.user.id,+ })+ .returning();++ mockAuthenticatedSession(owner.user);+ const { app } = createApp();++ const response = await app.request(+ `/api/project/${project.id}/move`,+ moveRequest(target.id),+ );++ expect(response.status).toBe(200);+ const payload = (await response.json()) as { unassignedTaskCount: number };+ expect(payload.unassignedTaskCount).toBe(1);++ const [kept] = await db+ .select()+ .from(schema.taskTable)+ .where(eq(schema.taskTable.id, keptTask.id));+ expect(kept.userId).toBe(owner.user.id);++ const [dropped] = await db+ .select()+ .from(schema.taskTable)+ .where(eq(schema.taskTable.id, droppedTask.id));+ expect(dropped.userId).toBeNull();++ // Losing an assignee has to land on the task's timeline, the same way a+ // manual or bulk unassignment does — otherwise there's no record of which+ // tasks a move touched.+ const activities = await waitForActivities(droppedTask.id);+ expect(activities).toHaveLength(1);+ expect(activities[0].type).toBe("unassigned");+ expect(activities[0].userId).toBe(owner.user.id);++ const keptActivities = await db+ .select()+ .from(schema.activityTable)+ .where(eq(schema.activityTable.taskId, keptTask.id));+ expect(keptActivities).toHaveLength(0);+ });++ // The unassignment is predicated on the target's member set rather than a+ // list of task ids, so an empty member set drops that term entirely — the+ // remaining predicate still has to stay scoped to this project.+ it("unassigns every task when no assignee is a member of the target", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const outsider = await createWorkspaceMember({ role: "member" });+ const target = await createTargetWorkspace();+ await addMember(target.id, owner.user.id, "owner");+ await addMember(owner.workspace.id, outsider.user.id, "member");++ const { project, columns } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });+ const other = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });++ const [movedTask] = await db+ .insert(schema.taskTable)+ .values({+ projectId: project.id,+ title: "Loses its assignee",+ columnId: columns.todo.id,+ number: 1,+ userId: outsider.user.id,+ })+ .returning();++ const [untouchedTask] = await db+ .insert(schema.taskTable)+ .values({+ projectId: other.project.id,+ title: "Belongs to another project",+ columnId: other.columns.todo.id,+ number: 1,+ userId: outsider.user.id,+ })+ .returning();++ mockAuthenticatedSession(owner.user);+ const { app } = createApp();++ const response = await app.request(+ `/api/project/${project.id}/move`,+ moveRequest(target.id),+ );++ expect(response.status).toBe(200);+ const payload = (await response.json()) as { unassignedTaskCount: number };+ expect(payload.unassignedTaskCount).toBe(1);++ const [moved] = await db+ .select()+ .from(schema.taskTable)+ .where(eq(schema.taskTable.id, movedTask.id));+ expect(moved.userId).toBeNull();++ const [untouched] = await db+ .select()+ .from(schema.taskTable)+ .where(eq(schema.taskTable.id, untouchedTask.id));+ expect(untouched.userId).toBe(outsider.user.id);+ });+});++describe("project move task relationships", () => {+ beforeEach(resetTestDatabase);+ it.each(["incoming", "outgoing", "internal"])(+ "protects %s relationships",+ async (direction) => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const target = await createTargetWorkspace();+ await addMember(target.id, owner.user.id, "owner");+ const { project } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });+ const { project: other } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });+ const tasks = await db+ .insert(schema.taskTable)+ .values([+ { title: "Moving", projectId: project.id, number: 1 },+ {+ title: "Related",+ projectId: direction === "internal" ? project.id : other.id,+ number: 2,+ },+ ])+ .returning();+ const [relation] = await db+ .insert(schema.taskRelationTable)+ .values({+ sourceTaskId: tasks[direction === "incoming" ? 1 : 0].id,+ targetTaskId: tasks[direction === "incoming" ? 0 : 1].id,+ relationType: "blocks",+ })+ .returning();+ mockAuthenticatedSession(owner.user);+ const { app } = createApp();+ const response = await app.request(+ `/api/project/${project.id}/move`,+ moveRequest(target.id),+ );+ expect(response.status).toBe(direction === "internal" ? 200 : 409);+ const [after] = await db+ .select()+ .from(schema.projectTable)+ .where(eq(schema.projectTable.id, project.id));+ expect(after.workspaceId).toBe(+ direction === "internal" ? target.id : owner.workspace.id,+ );+ expect(+ await db+ .select()+ .from(schema.taskRelationTable)+ .where(eq(schema.taskRelationTable.id, relation.id)),+ ).toHaveLength(1);+ },+ );+});++describe("project move concurrency and realtime access", () => {+ beforeEach(resetTestDatabase);+ it("closes old project sockets even when there are no tasks to unassign", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const target = await createTargetWorkspace();+ await addMember(target.id, owner.user.id, "owner");+ const { project } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });+ const socket = { send: vi.fn(), close: vi.fn() };+ const conn = addConnection(+ project.id,+ socket as unknown as WSContext,+ owner.user.id,+ "window",+ owner.workspace.id,+ );+ try {+ mockAuthenticatedSession(owner.user);+ const { app } = createApp();+ const response = await app.request(+ `/api/project/${project.id}/move`,+ moveRequest(target.id),+ );+ expect(response.status).toBe(200);+ expect(socket.close).toHaveBeenCalledWith(+ 1008,+ "Project workspace changed",+ );+ expect(socket.send).toHaveBeenCalledWith(+ JSON.stringify({ type: "PROJECT_MOVED", projectId: project.id }),+ );+ } finally {+ removeConnection(project.id, conn);+ }+ });++ it("relation creation waits for a moving project and rechecks the workspace", async () => {+ const owner = await createWorkspaceMember({ role: "owner" });+ const target = await createTargetWorkspace();+ const { project } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });+ const { project: other } = await createProjectFixture({+ workspaceId: owner.workspace.id,+ });+ const tasks = await db+ .insert(schema.taskTable)+ .values([+ { title: "Moving", projectId: project.id, number: 1 },+ { title: "Staying", projectId: other.id, number: 1 },+ ])+ .returning();+ let locked!: () => void;+ let release!: () => void;+ const ready = new Promise<void>((resolve) => {+ locked = resolve;+ });+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const move = db.transaction(async (tx) => {+ await tx+ .select()+ .from(schema.projectTable)+ .where(eq(schema.projectTable.id, project.id))+ .for("update");+ locked();+ await gate;+ await tx+ .update(schema.projectTable)+ .set({ workspaceId: target.id })+ .where(eq(schema.projectTable.id, project.id));+ });+ await ready;+ const relation = createTaskRelation({+ sourceTaskId: tasks[0].id,+ targetTaskId: tasks[1].id,+ relationType: "blocks",+ userId: owner.user.id,+ workspaceId: owner.workspace.id,+ }).then(+ () => null,+ (error: unknown) => error,+ );+ try {+ await vi.waitFor(async () => {+ const waiting = await db.execute(+ sql`SELECT 1 FROM pg_stat_activity WHERE datname = current_database() AND wait_event_type = 'Lock' AND query LIKE '%for share%'`,+ );+ expect(waiting.rows.length).toBeGreaterThan(0);+ });+ } finally {+ release();+ }+ await move;+ expect(await relation).toMatchObject({ status: 404 });+ expect(await db.select().from(schema.taskRelationTable)).toHaveLength(0);+ });+});diff --git a/tests/api/ws/broadcast.test.ts b/tests/api/ws/broadcast.test.tsindex 710eb5034..6e5810d06 100644--- a/tests/api/ws/broadcast.test.ts+++ b/tests/api/ws/broadcast.test.ts@@ -38,7 +38,7 @@ describe("broadcastToProject", () => {it("delivers messages to connected clients after batch timeout", async () => {const ws = makeFakeWs();- const conn = addConnection("proj-1", ws, "user-1", "init-1");+ const conn = addConnection("proj-1", ws, "user-1", "init-1", "workspace");broadcastToProject("proj-1", {type: "TASK_CREATED",@@ -73,8 +73,20 @@ describe("broadcastToProject", () => {it("excludes connections matching excludeInitiatorId", async () => {const ws1 = makeFakeWs();const ws2 = makeFakeWs();- const conn1 = addConnection("proj-1", ws1, "user-1", "init-excluded");- const conn2 = addConnection("proj-1", ws2, "user-2", "init-other");+ const conn1 = addConnection(+ "proj-1",+ ws1,+ "user-1",+ "init-excluded",+ "workspace",+ );+ const conn2 = addConnection(+ "proj-1",+ ws2,+ "user-2",+ "init-other",+ "workspace",+ );broadcastToProject("proj-1",@@ -101,7 +113,7 @@ describe("broadcastToProject", () => {it("deduplicates messages with the same key in a batch window", async () => {const ws = makeFakeWs();- const conn = addConnection("proj-1", ws, "user-1", "init-1");+ const conn = addConnection("proj-1", ws, "user-1", "init-1", "workspace");// Send two messages with the same type+taskId; they should be deduplicatedbroadcastToProject("proj-1", {@@ -134,7 +146,7 @@ describe("broadcastToProject", () => {it("does not deliver to connections on a different project", async () => {const ws = makeFakeWs();- const conn = addConnection("proj-2", ws, "user-1", "init-1");+ const conn = addConnection("proj-2", ws, "user-1", "init-1", "workspace");broadcastToProject("proj-1", {type: "TASK_CREATED",@@ -166,3 +178,13 @@ describe("broadcastToProject", () => {warnSpy.mockRestore();});});++vi.mock("../../../apps/api/src/database", () => ({+ default: {+ select: () => ({+ from: () => ({+ where: () => ({ limit: async () => [{ workspaceId: "workspace" }] }),+ }),+ }),+ },+}));diff --git a/tests/api/ws/connections.test.ts b/tests/api/ws/connections.test.tsindex 2a5af7b3f..f612f5c70 100644--- a/tests/api/ws/connections.test.ts+++ b/tests/api/ws/connections.test.ts@@ -38,7 +38,13 @@ afterEach(() => {});function trackAdd(projectId: string, userId: string, initiatorId: string) {- const conn = addConnection(projectId, makeFakeWs(), userId, initiatorId);+ const conn = addConnection(+ projectId,+ makeFakeWs(),+ userId,+ initiatorId,+ "workspace",+ );tracked.push({ projectId, conn });return conn;}@@ -46,13 +52,14 @@ function trackAdd(projectId: string, userId: string, initiatorId: string) {describe("addConnection / removeConnection", () => {it("returns a ProjectConnection object with the provided values", () => {const ws = makeFakeWs();- const conn = addConnection("proj-1", ws, "user-1", "init-1");+ const conn = addConnection("proj-1", ws, "user-1", "init-1", "workspace");tracked.push({ projectId: "proj-1", conn });expect(conn).toEqual({ws,userId: "user-1",initiatorId: "init-1",+ workspaceId: "workspace",});});diff --git a/tests/api/ws/label-deletion-backpressure.test.ts b/tests/api/ws/label-deletion-backpressure.test.tsindex e35955486..98998ffb8 100644--- a/tests/api/ws/label-deletion-backpressure.test.ts+++ b/tests/api/ws/label-deletion-backpressure.test.ts@@ -44,6 +44,7 @@ describe("awaited label deletion broadcasts", () => {observer as unknown as WSContext,"observer","other",+ "workspace",),],[@@ -53,6 +54,7 @@ describe("awaited label deletion broadcasts", () => {initiator as unknown as WSContext,"initiator","self",+ "workspace",),],[@@ -62,6 +64,7 @@ describe("awaited label deletion broadcasts", () => {foreign as unknown as WSContext,"foreign","another",+ "workspace",),],] as const;@@ -118,3 +121,13 @@ describe("awaited label deletion broadcasts", () => {expect(completed).toBe(true);});});++vi.mock("../../../apps/api/src/database", () => ({+ default: {+ select: () => ({+ from: () => ({+ where: () => ({ limit: async () => [{ workspaceId: "workspace" }] }),+ }),+ }),+ },+}));diff --git a/tests/api/ws/project-move.test.ts b/tests/api/ws/project-move.test.tsnew file mode 100644index 000000000..f5c43fda6--- /dev/null+++ b/tests/api/ws/project-move.test.ts@@ -0,0 +1,145 @@+import type { WSContext } from "hono/ws";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ addConnection,+ broadcastToProject,+ closeProjectConnections,+ initializeWebSocketAdapter,+ removeConnection,+ shutdownWebSocketAdapter,+} from "../../../apps/api/src/ws";++const m = vi.hoisted(() => ({+ lookup: vi.fn(),+ redis: false,+ publish: vi.fn(),+ on: vi.fn(),+}));+vi.mock("../../../apps/api/src/database", () => ({+ default: {+ select: () => ({ from: () => ({ where: () => ({ limit: m.lookup }) }) }),+ },+}));+vi.mock("../../../apps/api/src/events", () => ({ subscribeToEvent: vi.fn() }));+vi.mock("../../../apps/api/src/redis", () => ({+ isRedisConfigured: () => m.redis,+ getRedisPub: () => ({ publish: m.publish }),+ getRedisSub: () => ({+ on: m.on,+ off: vi.fn(),+ psubscribe: vi.fn(),+ punsubscribe: vi.fn(),+ }),+ closeRedis: vi.fn(),+}));+const tracked: Array<[string, ReturnType<typeof addConnection>]> = [];+function connect(projectId = "project", workspaceId = "old") {+ const ws = { send: vi.fn(), close: vi.fn() };+ tracked.push([+ projectId,+ addConnection(+ projectId,+ ws as unknown as WSContext,+ "user",+ "window",+ workspaceId,+ ),+ ]);+ return ws;+}+const update = {+ type: "TASK_UPDATED",+ projectId: "project",+ taskId: "private-task",+};+beforeEach(() => {+ m.redis = false;+ m.lookup.mockResolvedValue([{ workspaceId: "old" }]);+ m.publish.mockResolvedValue(1);+});+afterEach(async () => {+ await shutdownWebSocketAdapter();+ for (const [id, conn] of tracked.splice(0)) removeConnection(id, conn);+ vi.clearAllMocks();+ vi.useRealTimers();+});+describe("project move revocation", () => {+ it("closes local connections and discards queued updates without touching another project", async () => {+ vi.useFakeTimers();+ await initializeWebSocketAdapter();+ const old = connect();+ const other = connect("other");+ broadcastToProject("project", update);+ await closeProjectConnections("project");+ await vi.advanceTimersByTimeAsync(100);+ expect(old.close).toHaveBeenCalledWith(1008, "Project workspace changed");+ expect(old.send.mock.calls.map(([data]) => JSON.parse(data).type)).toEqual([+ "PROJECT_MOVED",+ ]);+ expect(other.close).not.toHaveBeenCalled();+ });+ it("rejects stale workspace connections even when revocation was missed", async () => {+ vi.useFakeTimers();+ await initializeWebSocketAdapter();+ const old = connect();+ const current = connect("project", "new");+ m.lookup.mockResolvedValue([{ workspaceId: "new" }]);+ broadcastToProject("project", update);+ await vi.advanceTimersByTimeAsync(100);+ expect(old.send).not.toHaveBeenCalled();+ expect(old.close).toHaveBeenCalled();+ expect(current.send).toHaveBeenCalledWith(JSON.stringify(update));+ });+ it("fails closed when workspace lookup fails", async () => {+ vi.useFakeTimers();+ await initializeWebSocketAdapter();+ const old = connect();+ m.lookup.mockRejectedValueOnce(new Error("Database unavailable"));+ broadcastToProject("project", update);+ await vi.advanceTimersByTimeAsync(100);+ expect(old.send).not.toHaveBeenCalled();+ expect(old.close).toHaveBeenCalled();+ });+ it("does not send an in-flight update after local revocation", async () => {+ vi.useFakeTimers();+ await initializeWebSocketAdapter();+ const old = connect();+ let finish!: (value: Array<{ workspaceId: string }>) => void;+ m.lookup.mockReturnValueOnce(+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ broadcastToProject("project", update);+ await vi.advanceTimersByTimeAsync(100);+ await closeProjectConnections("project");+ finish([{ workspaceId: "old" }]);+ await vi.advanceTimersByTimeAsync(0);+ expect(old.send.mock.calls.map(([data]) => JSON.parse(data).type)).toEqual([+ "PROJECT_MOVED",+ ]);+ });+ it("revokes sockets when a move arrives through Redis", async () => {+ m.redis = true;+ await initializeWebSocketAdapter();+ const old = connect();+ const handler = m.on.mock.calls[0][1];+ handler(+ "kaneo:ws:*:broadcast",+ "kaneo:ws:project:broadcast",+ JSON.stringify({+ projectId: "project",+ message: { type: "PROJECT_MOVED", projectId: "project" },+ }),+ );+ expect(old.close).toHaveBeenCalled();+ });+ it("closes local sockets even if Redis publication fails", async () => {+ m.redis = true;+ await initializeWebSocketAdapter();+ const old = connect();+ m.publish.mockRejectedValueOnce(new Error("Redis unavailable"));+ await expect(closeProjectConnections("project")).resolves.toBeUndefined();+ expect(old.close).toHaveBeenCalled();+ });+});