mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-10 12:37:55 +01:00
Add archived company member removal
This commit is contained in:
1 parent
b9a80dcf22
commit
63b4dc7c5e
13 files changed
+715
-23
No files matched your search
@@ -5,6 +5,7 @@ import {
|
||||
companies,
|
||||
companyMemberships,
|
||||
createDb,
|
||||
issues,
|
||||
principalPermissionGrants,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
@@ -51,6 +52,7 @@ describeEmbeddedPostgres("access service", () => {
|
||||
}, 20_000);
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(issues);
|
||||
await db.delete(principalPermissionGrants);
|
||||
await db.delete(companyMemberships);
|
||||
await db.delete(companies);
|
||||
@@ -96,4 +98,80 @@ describeEmbeddedPostgres("access service", () => {
|
||||
.then((rows) => rows[0]!);
|
||||
expect(unchanged.status).toBe("active");
|
||||
});
|
||||
|
||||
it("archives members, clears grants, and reassigns open issues without deleting history", async () => {
|
||||
const { company, owner } = await createCompanyWithOwner(db);
|
||||
const member = await db
|
||||
.insert(companyMemberships)
|
||||
.values({
|
||||
companyId: company.id,
|
||||
principalType: "user",
|
||||
principalId: `member-${randomUUID()}`,
|
||||
status: "active",
|
||||
membershipRole: "operator",
|
||||
})
|
||||
.returning()
|
||||
.then((rows) => rows[0]!);
|
||||
await db.insert(principalPermissionGrants).values({
|
||||
companyId: company.id,
|
||||
principalType: "user",
|
||||
principalId: member.principalId,
|
||||
permissionKey: "tasks:assign",
|
||||
grantedByUserId: owner.principalId,
|
||||
});
|
||||
const openIssue = await db
|
||||
.insert(issues)
|
||||
.values({
|
||||
companyId: company.id,
|
||||
title: "Open assigned issue",
|
||||
status: "in_progress",
|
||||
assigneeUserId: member.principalId,
|
||||
})
|
||||
.returning()
|
||||
.then((rows) => rows[0]!);
|
||||
const doneIssue = await db
|
||||
.insert(issues)
|
||||
.values({
|
||||
companyId: company.id,
|
||||
title: "Historical assigned issue",
|
||||
status: "done",
|
||||
assigneeUserId: member.principalId,
|
||||
})
|
||||
.returning()
|
||||
.then((rows) => rows[0]!);
|
||||
|
||||
const access = accessService(db);
|
||||
const result = await access.archiveMember(company.id, member.id, {
|
||||
reassignment: { assigneeUserId: owner.principalId },
|
||||
});
|
||||
|
||||
expect(result?.reassignedIssueCount).toBe(1);
|
||||
const archived = await db
|
||||
.select()
|
||||
.from(companyMemberships)
|
||||
.where(eq(companyMemberships.id, member.id))
|
||||
.then((rows) => rows[0]!);
|
||||
expect(archived.status).toBe("archived");
|
||||
|
||||
const remainingGrants = await db
|
||||
.select()
|
||||
.from(principalPermissionGrants)
|
||||
.where(eq(principalPermissionGrants.principalId, member.principalId));
|
||||
expect(remainingGrants).toHaveLength(0);
|
||||
|
||||
const reassignedIssue = await db
|
||||
.select()
|
||||
.from(issues)
|
||||
.where(eq(issues.id, openIssue.id))
|
||||
.then((rows) => rows[0]!);
|
||||
expect(reassignedIssue.assigneeUserId).toBe(owner.principalId);
|
||||
expect(reassignedIssue.status).toBe("todo");
|
||||
|
||||
const historicalIssue = await db
|
||||
.select()
|
||||
.from(issues)
|
||||
.where(eq(issues.id, doneIssue.id))
|
||||
.then((rows) => rows[0]!);
|
||||
expect(historicalIssue.assigneeUserId).toBe(member.principalId);
|
||||
});
|
||||
});
|
||||
@@ -9,7 +9,7 @@ import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Router } from "express";
|
||||
import type { Request } from "express";
|
||||
import { and, desc, eq, gt, inArray, isNotNull, isNull, lte, sql } from "drizzle-orm";
|
||||
import { and, desc, eq, gt, inArray, isNotNull, isNull, lte, ne, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
assets,
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
searchAdminUsersQuerySchema,
|
||||
updateCompanyMemberWithPermissionsSchema,
|
||||
updateCompanyMemberSchema,
|
||||
archiveCompanyMemberSchema,
|
||||
updateMemberPermissionsSchema,
|
||||
updateUserCompanyAccessSchema,
|
||||
PERMISSION_KEYS
|
||||
@@ -994,7 +995,11 @@ async function loadCompanyAccessSummary(
|
||||
};
|
||||
}
|
||||
|
||||
async function loadCompanyMemberRecords(db: Db, companyId: string) {
|
||||
async function loadCompanyMemberRecords(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
options: { includeArchived?: boolean } = {},
|
||||
) {
|
||||
const members = await db
|
||||
.select()
|
||||
.from(companyMemberships)
|
||||
@@ -1002,6 +1007,7 @@ async function loadCompanyMemberRecords(db: Db, companyId: string) {
|
||||
and(
|
||||
eq(companyMemberships.companyId, companyId),
|
||||
eq(companyMemberships.principalType, "user"),
|
||||
options.includeArchived ? undefined : ne(companyMemberships.status, "archived"),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(companyMemberships.updatedAt));
|
||||
@@ -3834,6 +3840,44 @@ export function accessRoutes(
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/companies/:companyId/members/:memberId/archive",
|
||||
validate(archiveCompanyMemberSchema),
|
||||
async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const memberId = req.params.memberId as string;
|
||||
await assertCompanyPermission(req, companyId, "users:manage_permissions");
|
||||
|
||||
const result = await access.archiveMember(companyId, memberId, {
|
||||
reassignment: req.body.reassignment ?? null,
|
||||
});
|
||||
if (!result) throw notFound("Member not found");
|
||||
|
||||
await logActivity(db, {
|
||||
companyId,
|
||||
actorType: "user",
|
||||
actorId: req.actor.userId ?? "board",
|
||||
action: "company_member.archived",
|
||||
entityType: "company_membership",
|
||||
entityId: memberId,
|
||||
details: {
|
||||
principalId: result.member.principalId,
|
||||
reassignedIssueCount: result.reassignedIssueCount,
|
||||
reassignment: req.body.reassignment ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
const member = (await loadCompanyMemberRecords(db, companyId, { includeArchived: true })).find(
|
||||
(entry) => entry.id === memberId,
|
||||
);
|
||||
if (!member) throw notFound("Member not found");
|
||||
res.json({
|
||||
member,
|
||||
reassignedIssueCount: result.reassignedIssueCount,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
router.patch(
|
||||
"/companies/:companyId/members/:memberId/permissions",
|
||||
validate(updateMemberPermissionsSchema),
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { and, eq, inArray, ne, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
agents,
|
||||
companyMemberships,
|
||||
instanceUserRoles,
|
||||
issues,
|
||||
principalPermissionGrants,
|
||||
} from "@paperclipai/db";
|
||||
import type { PermissionKey, PrincipalType } from "@paperclipai/shared";
|
||||
@@ -14,6 +16,13 @@ type GrantInput = {
|
||||
scope?: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
type MemberArchiveInput = {
|
||||
reassignment?: {
|
||||
assigneeAgentId?: string | null;
|
||||
assigneeUserId?: string | null;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export function accessService(db: Db) {
|
||||
async function isInstanceAdmin(userId: string | null | undefined): Promise<boolean> {
|
||||
if (!userId) return false;
|
||||
@@ -239,6 +248,176 @@ export function accessService(db: Db) {
|
||||
});
|
||||
}
|
||||
|
||||
async function assertCanRemoveActiveOwner(
|
||||
companyId: string,
|
||||
principalType: PrincipalType,
|
||||
status: string,
|
||||
membershipRole: string | null,
|
||||
tx: Pick<Db, "select">,
|
||||
) {
|
||||
if (
|
||||
principalType !== "user" ||
|
||||
status !== "active" ||
|
||||
membershipRole !== "owner"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const activeOwnerCount = await tx
|
||||
.select({ id: companyMemberships.id })
|
||||
.from(companyMemberships)
|
||||
.where(
|
||||
and(
|
||||
eq(companyMemberships.companyId, companyId),
|
||||
eq(companyMemberships.principalType, "user"),
|
||||
eq(companyMemberships.status, "active"),
|
||||
eq(companyMemberships.membershipRole, "owner"),
|
||||
),
|
||||
)
|
||||
.then((rows) => rows.length);
|
||||
if (activeOwnerCount <= 1) {
|
||||
throw conflict("Cannot remove the last active owner");
|
||||
}
|
||||
}
|
||||
|
||||
async function assertAssignableArchiveTarget(
|
||||
companyId: string,
|
||||
input: MemberArchiveInput["reassignment"],
|
||||
tx: Pick<Db, "select">,
|
||||
) {
|
||||
if (!input?.assigneeAgentId && !input?.assigneeUserId) return;
|
||||
if (input.assigneeAgentId && input.assigneeUserId) {
|
||||
throw conflict("Choose either an agent or user reassignment target");
|
||||
}
|
||||
if (input.assigneeUserId) {
|
||||
const membership = await tx
|
||||
.select({ id: companyMemberships.id })
|
||||
.from(companyMemberships)
|
||||
.where(
|
||||
and(
|
||||
eq(companyMemberships.companyId, companyId),
|
||||
eq(companyMemberships.principalType, "user"),
|
||||
eq(companyMemberships.principalId, input.assigneeUserId),
|
||||
eq(companyMemberships.status, "active"),
|
||||
),
|
||||
)
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!membership) {
|
||||
throw conflict("Replacement user must be an active company member");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const agent = await tx
|
||||
.select({
|
||||
id: agents.id,
|
||||
companyId: agents.companyId,
|
||||
status: agents.status,
|
||||
})
|
||||
.from(agents)
|
||||
.where(eq(agents.id, input.assigneeAgentId!))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!agent || agent.companyId !== companyId) {
|
||||
throw conflict("Replacement agent must belong to the same company");
|
||||
}
|
||||
if (agent.status === "pending_approval" || agent.status === "terminated") {
|
||||
throw conflict("Replacement agent must be assignable");
|
||||
}
|
||||
}
|
||||
|
||||
async function archiveMember(companyId: string, memberId: string, input: MemberArchiveInput = {}) {
|
||||
return db.transaction(async (tx) => {
|
||||
await tx.execute(sql`
|
||||
select ${companyMemberships.id}
|
||||
from ${companyMemberships}
|
||||
where ${companyMemberships.companyId} = ${companyId}
|
||||
and ${companyMemberships.principalType} = 'user'
|
||||
and ${companyMemberships.status} = 'active'
|
||||
and ${companyMemberships.membershipRole} = 'owner'
|
||||
for update
|
||||
`);
|
||||
|
||||
const existing = await tx
|
||||
.select()
|
||||
.from(companyMemberships)
|
||||
.where(and(eq(companyMemberships.companyId, companyId), eq(companyMemberships.id, memberId)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!existing) return null;
|
||||
if (existing.principalType !== "user") {
|
||||
throw conflict("Only human company members can be archived");
|
||||
}
|
||||
if (existing.status === "archived") {
|
||||
return { member: existing, reassignedIssueCount: 0 };
|
||||
}
|
||||
if (input.reassignment?.assigneeUserId === existing.principalId) {
|
||||
throw conflict("Replacement user cannot be the archived member");
|
||||
}
|
||||
|
||||
await assertCanRemoveActiveOwner(
|
||||
companyId,
|
||||
existing.principalType,
|
||||
existing.status,
|
||||
existing.membershipRole,
|
||||
tx,
|
||||
);
|
||||
await assertAssignableArchiveTarget(companyId, input.reassignment, tx);
|
||||
|
||||
const now = new Date();
|
||||
const assignmentPatch = {
|
||||
assigneeAgentId: input.reassignment?.assigneeAgentId ?? null,
|
||||
assigneeUserId: input.reassignment?.assigneeUserId ?? null,
|
||||
updatedAt: now,
|
||||
};
|
||||
const assignedOpenIssueWhere = and(
|
||||
eq(issues.companyId, companyId),
|
||||
eq(issues.assigneeUserId, existing.principalId),
|
||||
sql`${issues.status} not in ('done', 'cancelled')`,
|
||||
);
|
||||
const resetInProgress = await tx
|
||||
.update(issues)
|
||||
.set({
|
||||
...assignmentPatch,
|
||||
status: "todo",
|
||||
startedAt: null,
|
||||
checkoutRunId: null,
|
||||
executionRunId: null,
|
||||
executionLockedAt: null,
|
||||
})
|
||||
.where(and(assignedOpenIssueWhere, eq(issues.status, "in_progress")))
|
||||
.returning({ id: issues.id });
|
||||
const reassigned = await tx
|
||||
.update(issues)
|
||||
.set(assignmentPatch)
|
||||
.where(and(assignedOpenIssueWhere, ne(issues.status, "in_progress")))
|
||||
.returning({ id: issues.id });
|
||||
|
||||
await tx
|
||||
.delete(principalPermissionGrants)
|
||||
.where(
|
||||
and(
|
||||
eq(principalPermissionGrants.companyId, companyId),
|
||||
eq(principalPermissionGrants.principalType, existing.principalType),
|
||||
eq(principalPermissionGrants.principalId, existing.principalId),
|
||||
),
|
||||
);
|
||||
|
||||
const archived = await tx
|
||||
.update(companyMemberships)
|
||||
.set({
|
||||
status: "archived",
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(eq(companyMemberships.id, existing.id))
|
||||
.returning()
|
||||
.then((rows) => rows[0] ?? existing);
|
||||
|
||||
return {
|
||||
member: archived,
|
||||
reassignedIssueCount: resetInProgress.length + reassigned.length,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function promoteInstanceAdmin(userId: string) {
|
||||
const existing = await db
|
||||
.select()
|
||||
@@ -278,13 +457,61 @@ export function accessService(db: Db) {
|
||||
const target = new Set(companyIds);
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
const toDelete = existing.filter((row) => !target.has(row.companyId)).map((row) => row.id);
|
||||
if (toDelete.length > 0) {
|
||||
await tx.delete(companyMemberships).where(inArray(companyMemberships.id, toDelete));
|
||||
const toArchive = existing.filter((row) => !target.has(row.companyId) && row.status !== "archived");
|
||||
const activeOwnerArchives = toArchive.filter(
|
||||
(row) => row.status === "active" && row.membershipRole === "owner",
|
||||
);
|
||||
if (activeOwnerArchives.length > 0) {
|
||||
const activeOwnerRows = await tx
|
||||
.select({ companyId: companyMemberships.companyId, id: companyMemberships.id })
|
||||
.from(companyMemberships)
|
||||
.where(
|
||||
and(
|
||||
eq(companyMemberships.principalType, "user"),
|
||||
eq(companyMemberships.status, "active"),
|
||||
eq(companyMemberships.membershipRole, "owner"),
|
||||
inArray(companyMemberships.companyId, activeOwnerArchives.map((row) => row.companyId)),
|
||||
),
|
||||
);
|
||||
for (const row of activeOwnerArchives) {
|
||||
const remainingOwners =
|
||||
activeOwnerRows.filter((owner) => owner.companyId === row.companyId).length - 1;
|
||||
if (remainingOwners <= 0) {
|
||||
throw conflict("Cannot remove the last active owner");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (toArchive.length > 0) {
|
||||
await tx
|
||||
.update(companyMemberships)
|
||||
.set({ status: "archived", updatedAt: new Date() })
|
||||
.where(inArray(companyMemberships.id, toArchive.map((row) => row.id)));
|
||||
await tx
|
||||
.delete(principalPermissionGrants)
|
||||
.where(
|
||||
and(
|
||||
eq(principalPermissionGrants.principalType, "user"),
|
||||
eq(principalPermissionGrants.principalId, userId),
|
||||
inArray(principalPermissionGrants.companyId, toArchive.map((row) => row.companyId)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
for (const companyId of target) {
|
||||
if (existingByCompany.has(companyId)) continue;
|
||||
const existingMembership = existingByCompany.get(companyId);
|
||||
if (existingMembership) {
|
||||
if (existingMembership.status !== "active") {
|
||||
await tx
|
||||
.update(companyMemberships)
|
||||
.set({
|
||||
status: "active",
|
||||
membershipRole: existingMembership.membershipRole ?? "operator",
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(companyMemberships.id, existingMembership.id));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
await tx.insert(companyMemberships).values({
|
||||
companyId,
|
||||
principalType: "user",
|
||||
@@ -535,6 +762,7 @@ export function accessService(db: Db) {
|
||||
listMembers,
|
||||
listActiveUserMemberships,
|
||||
copyActiveUserMemberships,
|
||||
archiveMember,
|
||||
setMemberPermissions,
|
||||
updateMemberAndPermissions,
|
||||
promoteInstanceAdmin,
|
||||
|
||||
Reference in new issue
Block a user