fix(api-v1): handle agent.organizationId FK path and nullable isArchived in ACL helpers

This commit is contained in:
charles-gauthereau
2026-05-25 15:01:25 +02:00
parent 68fb74f441
commit 96cc9822d0
+21 -5
View File
@@ -1,6 +1,6 @@
import { db } from "@/db";
import * as drizzleDb from "@/db";
import { eq, inArray, and } from "drizzle-orm";
import { eq, inArray, and, or, isNull } from "drizzle-orm";
export async function getAccessibleAgentIds(userId: string): Promise<string[]> {
const memberships = await db.query.member.findMany({
@@ -11,20 +11,36 @@ export async function getAccessibleAgentIds(userId: string): Promise<string[]> {
if (memberships.length === 0) return [];
const orgIds = memberships.map((m) => m.organizationId);
const isActiveAgent = or(
eq(drizzleDb.schemas.agent.isArchived, false),
isNull(drizzleDb.schemas.agent.isArchived)
);
// Path 1: via organizationAgent junction table
const orgAgents = await db.query.organizationAgent.findMany({
where: inArray(drizzleDb.schemas.organizationAgent.organizationId, orgIds),
columns: { agentId: true },
});
const junctionAgentIds = orgAgents.map((oa) => oa.agentId);
if (orgAgents.length === 0) return [];
// Path 2: via agent.organizationId direct FK
const directAgents = await db.query.agent.findMany({
where: and(
inArray(drizzleDb.schemas.agent.organizationId, orgIds),
isActiveAgent
),
columns: { id: true },
});
const directAgentIds = directAgents.map((a) => a.id);
const agentIds = orgAgents.map((oa) => oa.agentId);
const allAgentIds = [...new Set([...junctionAgentIds, ...directAgentIds])];
if (allAgentIds.length === 0) return [];
// Filter junction-path agents by active status
const agents = await db.query.agent.findMany({
where: and(
inArray(drizzleDb.schemas.agent.id, agentIds),
eq(drizzleDb.schemas.agent.isArchived, false)
inArray(drizzleDb.schemas.agent.id, allAgentIds),
isActiveAgent
),
columns: { id: true },
});