Skip to content

armgit / kaneo

Public Imported from GitHub
0

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

fix(import): deduplicate assignees and preserve indexed ID lookups

Tinb24ba961d34d
diff --git a/apps/api/src/task/resolve-import-assignees.ts b/apps/api/src/task/resolve-import-assignees.ts
index 6507b797b..bd3fe213c 100644
--- a/apps/api/src/task/resolve-import-assignees.ts
+++ b/apps/api/src/task/resolve-import-assignees.ts
@@ -1,4 +1,4 @@
-import { and, eq, inArray, isNotNull, or, sql } from "drizzle-orm";
+import { and, eq, exists, inArray, or, sql } from "drizzle-orm";
import db, { schema } from "../database";
import { instanceAdminRoleSql } from "../utils/instance-admin-role";
@@ -9,47 +9,59 @@ export async function resolveImportAssignees(
const resolved = new Map<string, string>();
if (references.length === 0) return resolved;
- const users = await db
+ // Membership is a predicate: duplicate membership rows still mean one user.
+ const eligible = or(
+ exists(
+ db
+ .select({ id: schema.workspaceUserTable.id })
+ .from(schema.workspaceUserTable)
+ .where(
+ and(
+ eq(schema.workspaceUserTable.userId, schema.userTable.id),
+ eq(schema.workspaceUserTable.workspaceId, workspaceId),
+ ),
+ ),
+ ),
+ instanceAdminRoleSql(schema.userTable.role),
+ );
+ const idUsers = await db
+ .select({ id: schema.userTable.id })
+ .from(schema.userTable)
+ .where(and(inArray(schema.userTable.id, references), eligible));
+ for (const user of idUsers) resolved.set(user.id, user.id);
+
+ // Keep existing ID imports on the indexed path, including missing IDs.
+ const emails = [
+ ...new Set(
+ references
+ .filter(
+ (reference) => !resolved.has(reference) && reference.includes("@"),
+ )
+ .map((reference) => reference.toLowerCase()),
+ ),
+ ];
+ if (emails.length === 0) return resolved;
+
+ const emailUsers = await db
.select({ id: schema.userTable.id, email: schema.userTable.email })
.from(schema.userTable)
- .leftJoin(
- schema.workspaceUserTable,
- and(
- eq(schema.workspaceUserTable.userId, schema.userTable.id),
- eq(schema.workspaceUserTable.workspaceId, workspaceId),
- ),
- )
.where(
- and(
- or(
- inArray(schema.userTable.id, references),
- inArray(
- sql`lower(${schema.userTable.email})`,
- references.map((reference) => reference.toLowerCase()),
- ),
- ),
- or(
- isNotNull(schema.workspaceUserTable.userId),
- instanceAdminRoleSql(schema.userTable.role),
- ),
- ),
+ and(inArray(sql`lower(${schema.userTable.email})`, emails), eligible),
);
-
- const ids = new Set(users.map((user) => user.id));
- const byEmail = new Map<string, string[]>();
- for (const user of users) {
+ const byEmail = new Map<string, Set<string>>();
+ for (const user of emailUsers) {
const email = user.email.toLowerCase();
- byEmail.set(email, [...(byEmail.get(email) ?? []), user.id]);
+ const matches = byEmail.get(email) ?? new Set<string>();
+ matches.add(user.id);
+ byEmail.set(email, matches);
}
for (const reference of references) {
- // Existing exports use IDs; retain their meaning even if an ID resembles an email.
- if (ids.has(reference)) {
- resolved.set(reference, reference);
- continue;
- }
+ // IDs keep precedence even when they resemble another user's email.
+ if (resolved.has(reference)) continue;
const matches = byEmail.get(reference.toLowerCase());
- const match = matches?.[0];
- if (matches?.length === 1 && match) resolved.set(reference, match);
+ if (matches?.size !== 1) continue;
+ const [id] = matches;
+ if (id) resolved.set(reference, id);
}
return resolved;
}
diff --git a/tests/api-integration/task-import-assignees.test.ts b/tests/api-integration/task-import-assignees.test.ts
index 6710113cd..89eebc621 100644
--- a/tests/api-integration/task-import-assignees.test.ts
+++ b/tests/api-integration/task-import-assignees.test.ts
@@ -1,6 +1,7 @@
import { eq } from "drizzle-orm";
-import { beforeEach, describe, expect, it } from "vite-plus/test";
-import db, { schema } from "../../apps/api/src/database";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import db, { getDatabasePool, schema } from "../../apps/api/src/database";
+import { resolveImportAssignees } from "../../apps/api/src/task/resolve-import-assignees";
import { createApp } from "../../apps/api/src/index";
import { mockAuthenticatedSession } from "./helpers/auth";
import { resetTestDatabase } from "./helpers/database";
@@ -55,6 +56,78 @@ describe("JSON import assignees", () => {
expect(tasks.some((task) => task.userId === user.email)).toBe(false);
});
+ it("resolves an email when the same user has duplicate workspace memberships", async () => {
+ const { user, workspace, importUsers } = await fixture();
+ await db.insert(schema.workspaceUserTable).values({
+ userId: user.id,
+ workspaceId: workspace.id,
+ role: "owner",
+ joinedAt: new Date(),
+ });
+ const result = await importUsers([
+ user.email,
+ ` ${user.email.toUpperCase()} `,
+ ]);
+ expect(result.results.successful).toBe(2);
+ expect(result.results.failed).toBe(0);
+ expect(
+ result.results.tasks.map(
+ (entry: { task: { userId: string } }) => entry.task.userId,
+ ),
+ ).toEqual([user.id, user.id]);
+ });
+
+ it("prefers an actual user ID over another eligible user's matching email", async () => {
+ const { user, workspace, importUsers } = await fixture();
+ const [idHolder] = await db
+ .insert(schema.userTable)
+ .values({
+ id: user.email,
+ email: `${user.id}@id-holder.example.com`,
+ emailVerified: true,
+ name: "ID Holder",
+ })
+ .returning();
+ await db.insert(schema.workspaceUserTable).values({
+ userId: idHolder.id,
+ workspaceId: workspace.id,
+ role: "member",
+ joinedAt: new Date(),
+ });
+ const result = await importUsers([idHolder.id, user.id]);
+ expect(result.results.successful).toBe(2);
+ expect(result.results.failed).toBe(0);
+ expect(
+ result.results.tasks.map(
+ (entry: { task: { userId: string } }) => entry.task.userId,
+ ),
+ ).toEqual([idHolder.id, user.id]);
+ });
+
+ it("keeps indexed ID-only imports free of email scans", async () => {
+ const { user, workspace } = await fixture();
+ const queries = vi.spyOn(getDatabasePool(), "query");
+ try {
+ const resolved = await resolveImportAssignees(
+ [user.id, "missing-user-id"],
+ workspace.id,
+ );
+ expect(resolved.get(user.id)).toBe(user.id);
+ expect(resolved.has("missing-user-id")).toBe(false);
+ expect(queries).toHaveBeenCalledTimes(1);
+ const statement = queries.mock.calls[0]?.[0];
+ const text =
+ typeof statement === "string"
+ ? statement
+ : statement && typeof statement === "object" && "text" in statement
+ ? statement.text
+ : "";
+ expect(text).not.toMatch(/lower\s*\(/i);
+ } finally {
+ queries.mockRestore();
+ }
+ });
+
it("rejects another workspace's users without revealing whether the email exists", async () => {
const { importUsers } = await fixture();
const outsider = await createWorkspaceMember();