diff --git a/client/src/api/departments.ts b/client/src/api/departments.ts index 64918d81..6fca2cf9 100644 --- a/client/src/api/departments.ts +++ b/client/src/api/departments.ts @@ -19,6 +19,11 @@ export type DepartmentListResponse = { tree: DepartmentTreeNode[]; }; +type DepartmentMutationResponse = { + department: DepartmentItem; + outcome?: "already_archived" | "archived"; +}; + export async function fetchDepartments(params: { includeArchived?: boolean } = {}) { const search = new URLSearchParams(); if (params.includeArchived != null) { @@ -30,23 +35,24 @@ export async function fetchDepartments(params: { includeArchived?: boolean } = { } export async function createDepartment(payload: { name: string; parentId?: string | null }) { - return apiRequestData("/api/departments", { + const response = await apiRequestData("/api/departments", { method: "POST", body: JSON.stringify(payload), }); + return response.department; } export async function updateDepartment(departmentId: string, payload: { name?: string; parentId?: string | null }) { - return apiRequestData(`/api/departments/${departmentId}`, { + const response = await apiRequestData(`/api/departments/${departmentId}`, { method: "PATCH", body: JSON.stringify(payload), }); + return response.department; } export async function archiveDepartment(departmentId: string) { - return apiRequestData(`/api/departments/${departmentId}/archive`, { + return apiRequestData(`/api/departments/${departmentId}/archive`, { method: "POST", body: JSON.stringify({}), }); } - diff --git a/client/src/api/employees.ts b/client/src/api/employees.ts index 165fed59..c1713566 100644 --- a/client/src/api/employees.ts +++ b/client/src/api/employees.ts @@ -101,12 +101,14 @@ export async function fetchEmployees(params: { page: number; pageSize: number; status?: EmployeeStatus; + departmentId?: string; q?: string; }) { const search = new URLSearchParams(); search.set("page", String(params.page)); search.set("pageSize", String(params.pageSize)); if (params.status) search.set("status", params.status); + if (params.departmentId) search.set("departmentId", params.departmentId); if (params.q) search.set("q", params.q); return apiRequestData(`/api/employees?${search.toString()}`); diff --git a/client/src/pages/DepartmentsPage.tsx b/client/src/pages/DepartmentsPage.tsx index 4e7aefea..8d43a243 100644 --- a/client/src/pages/DepartmentsPage.tsx +++ b/client/src/pages/DepartmentsPage.tsx @@ -7,10 +7,21 @@ import { archiveDepartment, createDepartment, fetchDepartments, + updateDepartment, type DepartmentItem, + type DepartmentTreeNode, } from "../api/departments"; +import { StatusBadge } from "../components/common/StatusBadge"; import { PageHeader } from "../components/common/PageHeader"; import { Button } from "../components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "../components/ui/dialog"; import { Input } from "../components/ui/input"; import { Label } from "../components/ui/label"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../components/ui/table"; @@ -18,6 +29,73 @@ import { toast } from "sonner"; import { TableSkeleton } from "../components/common/TableSkeleton"; import { ConfirmDialog } from "../components/common/ConfirmDialog"; +function mapDepartmentErrorMessage(error: unknown, fallback: string) { + if (!isApiError(error)) { + return error instanceof Error ? error.message : fallback; + } + + if (error.code === "VALID_001") { + if (error.details?.parentId === "not_found") { + return `${error.code}: 上级部门不存在。`; + } + if (error.details?.parentId === "archived") { + return `${error.code}: 上级部门已归档,无法继续使用。`; + } + if (error.details?.parentId === "self_not_allowed") { + return `${error.code}: 上级部门不能选择自身。`; + } + if (error.details?.parentId === "cycle_not_allowed") { + return `${error.code}: 上级部门不能形成循环层级。`; + } + if (error.details?.status === "archived") { + return `${error.code}: 已归档部门不可编辑。`; + } + if (error.details?.department === "has_children") { + return `${error.code}: 当前部门存在下级节点,无法归档。`; + } + if (error.details?.department === "has_active_employees") { + return `${error.code}: 当前部门仍有在职员工,无法归档。`; + } + } + + return `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`; +} + +function flattenDepartmentTree(nodes: DepartmentTreeNode[], depth = 0): Array<{ id: string; label: string }> { + const items: Array<{ id: string; label: string }> = []; + for (const node of nodes) { + items.push({ id: node.id, label: `${" ".repeat(depth)}${node.name}` }); + items.push(...flattenDepartmentTree(node.children, depth + 1)); + } + return items; +} + +function DepartmentTreeView({ nodes, depth = 0 }: { nodes: DepartmentTreeNode[]; depth?: number }) { + if (!nodes.length) { + return null; + } + + return ( +
+ {nodes.map((node) => ( +
+
+
+
{node.name}
+
{node.id}
+
+ {node.archivedAt ? : null} +
+ {node.children.length ? : null} +
+ ))} +
+ ); +} + export function DepartmentsPage() { const queryClient = useQueryClient(); const [searchParams, setSearchParams] = useSearchParams(); @@ -29,6 +107,9 @@ export function DepartmentsPage() { const [parentId, setParentId] = useState(""); const [error, setError] = useState(""); const [confirmArchive, setConfirmArchive] = useState<{ id: string; name: string } | null>(null); + const [editDepartment, setEditDepartment] = useState(null); + const [editName, setEditName] = useState(""); + const [editParentId, setEditParentId] = useState(""); const listQuery = useQuery({ queryKey: ["departments", includeArchived], @@ -36,6 +117,7 @@ export function DepartmentsPage() { }); const departments = listQuery.data?.items ?? []; + const departmentTree = listQuery.data?.tree ?? []; const departmentById = useMemo(() => { const map = new Map(); @@ -45,6 +127,11 @@ export function DepartmentsPage() { return map; }, [departments]); + const departmentOptions = useMemo( + () => flattenDepartmentTree(departmentTree).filter((item) => !departmentById.get(item.id)?.archivedAt), + [departmentById, departmentTree], + ); + const createMutation = useMutation({ mutationFn: () => createDepartment({ @@ -59,9 +146,32 @@ export function DepartmentsPage() { toast.success("部门已创建"); }, onError: (err) => { - const msg = isApiError(err) - ? `${err.code}: ${mapApiErrorMessage(err.code, err.details, err.message)}` - : err instanceof Error ? err.message : "创建部门失败"; + const msg = mapDepartmentErrorMessage(err, "创建部门失败"); + setError(msg); + toast.error(msg); + }, + }); + + const editMutation = useMutation({ + mutationFn: () => { + if (!editDepartment) { + throw new Error("未选择待编辑部门"); + } + return updateDepartment(editDepartment.id, { + name: editName.trim(), + parentId: editParentId ? editParentId : null, + }); + }, + onSuccess: async () => { + await queryClient.invalidateQueries({ queryKey: ["departments"] }); + setEditDepartment(null); + setEditName(""); + setEditParentId(""); + setError(""); + toast.success("部门已更新"); + }, + onError: (err) => { + const msg = mapDepartmentErrorMessage(err, "更新部门失败"); setError(msg); toast.error(msg); }, @@ -75,9 +185,7 @@ export function DepartmentsPage() { toast.success("已归档"); }, onError: (err) => { - const msg = isApiError(err) - ? `${err.code}: ${mapApiErrorMessage(err.code, err.details, err.message)}` - : err instanceof Error ? err.message : "归档部门失败"; + const msg = mapDepartmentErrorMessage(err, "归档部门失败"); setError(msg); toast.error(msg); }, @@ -140,13 +248,11 @@ export function DepartmentsPage() { onChange={(event) => setParentId(event.target.value)} > - {departments - .filter((item) => !item.archivedAt) - .map((item) => ( - - ))} + {departmentOptions.map((item) => ( + + ))} @@ -163,6 +269,18 @@ export function DepartmentsPage() { +
+

部门树形视图

+ {listQuery.isLoading ? : null} + {!listQuery.isLoading && !listQuery.isError ? ( + departmentTree.length ? ( + + ) : ( +

暂无部门层级

+ ) + ) : null} +
+

部门列表

@@ -207,16 +325,30 @@ export function DepartmentsPage() { {!item.archivedAt ? ( - +
+ + +
) : ( 已归档 )} @@ -247,7 +379,75 @@ export function DepartmentsPage() { }} onOpenChange={(open) => { if (!open) setConfirmArchive(null); }} /> + + { + if (!open) { + setEditDepartment(null); + setEditName(""); + setEditParentId(""); + } + }} + > + + + 编辑部门 + 修改部门名称或上级部门,保存后列表和树形视图会同步刷新。 + + +
+
+ + setEditName(event.target.value)} + /> +
+ +
+ + +
+
+ + + + + +
+
); } - diff --git a/client/src/pages/PeoplePage.tsx b/client/src/pages/PeoplePage.tsx index 182b2ee5..686cca06 100644 --- a/client/src/pages/PeoplePage.tsx +++ b/client/src/pages/PeoplePage.tsx @@ -7,6 +7,7 @@ import { startEmployeeOffboarding, startEmployeeOnboarding, } from "../api/employees"; +import { fetchDepartments } from "../api/departments"; import { isApiError } from "../api/types"; import { mapApiErrorMessage } from "../api/errorMessages"; import { PageHeader } from "../components/common/PageHeader"; @@ -19,10 +20,24 @@ import { toast } from "sonner"; export function PeoplePage() { const queryClient = useQueryClient(); const [q, setQ] = useState(""); + const [status, setStatus] = useState<"" | "active" | "archived">(""); + const [departmentId, setDepartmentId] = useState(""); + + const departmentsQuery = useQuery({ + queryKey: ["departments", "people-page", "active"], + queryFn: () => fetchDepartments({ includeArchived: false }), + }); const employeesQuery = useQuery({ - queryKey: ["employees", "people-page", q], - queryFn: () => fetchEmployees({ page: 1, pageSize: 100, q: q || undefined }), + queryKey: ["employees", "people-page", q, status, departmentId], + queryFn: () => + fetchEmployees({ + page: 1, + pageSize: 100, + q: q || undefined, + status: status || undefined, + departmentId: departmentId || undefined, + }), }); const onboardingMutation = useMutation({ @@ -74,6 +89,7 @@ export function PeoplePage() { }); const items = employeesQuery.data?.items ?? []; + const departments = departmentsQuery.data?.items ?? []; return (
@@ -90,10 +106,48 @@ export function PeoplePage() { />
- setQ(event.target.value)} /> +
+ setQ(event.target.value)} + /> + + +
+ {employeesQuery.isError ? ( +

+ {isApiError(employeesQuery.error) + ? `${employeesQuery.error.code}: ${mapApiErrorMessage( + employeesQuery.error.code, + employeesQuery.error.details, + employeesQuery.error.message, + )}` + : "加载人员列表失败"} +

+ ) : null} @@ -104,32 +158,42 @@ export function PeoplePage() { - {items.map((item) => ( - - -
{item.name}
-
{item.employeeNo} · {item.email}
-
- {item.roleCodes.join(" / ") || "-"} - - -
- - - - -
+ {items.length ? ( + items.map((item) => ( + + +
{item.name}
+
+ {item.employeeNo} · {item.email} +
+
+ {item.roleCodes.join(" / ") || "-"} + + +
+ + + + +
+
+
+ )) + ) : ( + + + 暂无匹配员工 - ))} + )}
diff --git a/issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv b/issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv index 0494af6d..02724aeb 100644 --- a/issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv +++ b/issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv @@ -2,4 +2,4 @@ ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regr R37-0,R37治理合同补建与范围冻结,为 AGENTS 多 agent 规则更新补建治理合同并锁定本轮仅做治理文档与提交准备,新 CSV 校验通过 且范围明确为 AGENTS agent modes 固化与提交留痕 不承接业务代码改动,python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv,none,DONE,DONE,DONE,issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv,[],"本轮仅治理协作规则与提交流程;不修改 server/src 或 client/src 业务代码。" R37-1,Agent modes 治理规则固化与 review 修订落地,将 3 常驻加 2 按需模式固化到 AGENTS 并落实 qa 写权限 Test_Method 语义和 backend post-check 三处修订,AGENTS.md 包含 Agent modes 段落 且三处修订与现有 issues/README 和 docs/mcp-tools 边界一致,1) git diff --check 2) 核对 AGENTS.md 中 mode:qa 允许写 issues/*.csv 与 scripts/ 3) 核对回滚说明已移入 Notes 约束 4) 核对 backend post-check 已改为按变更类型执行,manual,DONE,DONE,DONE,AGENTS.md,"[""R37-0""]","若后续证明规则过严或过松,回滚方式为还原本次 Agent modes 段落并保留 CSV 审计记录。" R37-2,治理变更提交与审计留痕,提交 AGENTS 与治理 CSV 变更并使用中文 commit message 引用本 Issue ID,生成 1 个仅包含治理变更的 commit 且 git log 最新提交可见 Issue ID,"1) git diff --stat 确认仅含 AGENTS.md 与 issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv 2) git commit -m ""R37: 固化 Agent modes 治理规则"" 3) git log -1 --oneline",manual,DONE,DONE,DONE,AGENTS.md|issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv,"[""R37-1""]","commit 仅承载治理变更;若提交前发现额外文件改动则先停止并重新确认范围。" -R37-3,下个真实迭代按新模式试跑并复盘,在后续一个同时涉及 backend frontend qa 的真实迭代中按新 Agent modes 跑一次并记录阻塞点,至少完成 1 次真实试跑 并能说明 handoff QA 回填 reviewer 触发条件是否顺畅,"1) 选择一个同时涉及 server/ 与 client/ 的真实 issue 组 2) 按 Agent modes 执行 3) 在 Notes 或后续治理 issue 中记录问题与修订建议",manual,TODO,TODO,TODO,TBD,"[""R37-2""]","待下个真实迭代落地;若涉及 Prisma 迁移 权限变更 状态机调整,执行 issue 的 Notes 必须包含回滚路径。" +R37-3,下个真实迭代按新模式试跑并复盘,在后续一个同时涉及 backend frontend qa 的真实迭代中按新 Agent modes 跑一次并记录阻塞点,至少完成 1 次真实试跑 并能说明 handoff QA 回填 reviewer 触发条件是否顺畅,"1) 选择一个同时涉及 server/ 与 client/ 的真实 issue 组 2) 按 Agent modes 执行 3) 在 Notes 或后续治理 issue 中记录问题与修订建议",manual,DONE,DONE,DONE,TBD,"[""R37-2""]","已用 R38 员工管理试跑完成一次真实迭代。结论: Files 派工整体清晰 backend 侧唯一摩擦点是 /employees 复用 usersRoutes 需要显式 allowDepartmentFilter;QA 回填顺畅 命令式验证和合同状态映射明确;reviewer 触发条件当前无需细化 本轮未触及权限模型 状态机 workflow 或迁移。" diff --git a/issues/2026-03-28_13-00-03-r38-people-management-filters-department-tree.csv b/issues/2026-03-28_13-00-03-r38-people-management-filters-department-tree.csv new file mode 100644 index 00000000..6325cfb2 --- /dev/null +++ b/issues/2026-03-28_13-00-03-r38-people-management-filters-department-tree.csv @@ -0,0 +1,5 @@ +ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes +R38-0,R38执行合同建档与范围冻结,为员工管理试跑需求创建独立合同并锁定本轮只做员工筛选 部门树形视图与部门编辑 UI,CSV 校验通过 且明确本轮不承接档案扩展 汇报链接口 导出 考勤与批量操作,python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-28_13-00-03-r38-people-management-filters-department-tree.csv,none,DONE,DONE,DONE,issues/2026-03-28_13-00-03-r38-people-management-filters-department-tree.csv,[],本轮不处理 /people 路由与 /employees 后端权限口径不一致问题 仅记录不顺手修复 +R38-1,员工列表新增部门与账号状态筛选,为人员管理页补齐部门筛选与账号状态筛选并保持现有搜索组合生效,PeoplePage 支持按 departmentId 与 active archived 筛选且与关键字搜索同时生效 后端 /employees 查询兼容旧调用且不扩大 /users 语义,"业务流程: 管理员进入人员管理页 输入关键字 选择某部门 再切换账号状态 确认列表只显示匹配员工 清空筛选后恢复。验证命令: cd server && node --check src/routes/users.js && cd ../client && npm run typecheck && npm run build",manual,DONE,DONE,DONE,server/src/routes/users.js|server/src/routes/employees.js|server/tests/unit/routes/users.list.test.js|client/src/api/employees.ts|client/src/pages/PeoplePage.tsx,"[""R38-0""]","后端仅在 /employees 基座允许 departmentId 生效 不变更 /users 的既有筛选语义。已验证: node --check src/routes/users.js 通过;npm test -- tests/unit/routes/users.list.test.js 3/3 通过;client typecheck/build 通过。" +R38-2,部门树形视图与编辑弹窗,在部门管理页新增树形视图并接通编辑部门 UI 复用现有 departments tree 与 PATCH 接口,DepartmentsPage 同时展示树形视图与列表 未归档部门可通过编辑弹窗更新名称或父级 保存后树与列表同步刷新 归档部门无编辑入口,"业务流程: 管理员进入部门管理页 确认树形结构展示父子关系 打开未归档部门编辑弹窗 修改名称或上级后保存成功 列表与树同时更新 尝试把部门设置为自己的父级时前端展示后端错误。验证命令: cd server && node --check src/routes/departments.js && cd ../client && npm run typecheck && npm run build",manual,DONE,DONE,DONE,client/src/api/departments.ts|client/src/pages/DepartmentsPage.tsx,"[""R38-0""]","编辑弹窗仅包含 name 和 parentId 上级选项只展示未归档部门 且前端排除当前部门自身。已验证: node --check src/routes/departments.js 通过;client typecheck/build 通过;写接口响应在前端 API 层统一解包。" +R38-3,试跑回归与R37-3复盘,按新 Agent modes 完成员工管理试跑验证 状态回填 与 R37-3 复盘记录,单项验证与最小回归通过 R38 状态正确回填 且 R37-3 Notes 同步记录 handoff QA 回填与 reviewer 触发条件结论,"业务流程: 依次验证员工筛选 部门树视图 部门编辑 归档保护与错误提示 记录 backend frontend qa handoff 是否顺畅。验证命令: cd server && node --check src/routes/users.js && node --check src/routes/departments.js && cd ../client && npm run typecheck && npm run build",manual,DONE,DONE,DONE,issues/2026-03-28_13-00-03-r38-people-management-filters-department-tree.csv|issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv|server/src/routes/users.js|client/src/pages/PeoplePage.tsx|client/src/pages/DepartmentsPage.tsx,"[""R38-1"",""R38-2""]","试跑结论: backend Files 边界清晰 server/src/routes/users.js 与 employees.js 的共享/挂载关系是唯一摩擦点 但可控;QA 回填顺畅 当前命令式验证可直接映射到 Review1/Regression;本轮不需启用 reviewer 因为未触及权限模型 状态机 workflow 或迁移。" diff --git a/server/src/routes/employees.js b/server/src/routes/employees.js index 04aab5cf..c7b07885 100644 --- a/server/src/routes/employees.js +++ b/server/src/routes/employees.js @@ -281,7 +281,7 @@ async function buildEmployeeProfile(prisma, employeeId) { } async function employeesRoutes(fastify) { - await usersRoutes(fastify, { basePath: "/employees" }); + await usersRoutes(fastify, { basePath: "/employees", allowDepartmentFilter: true }); fastify.get("/employees/:id/profile", { preHandler: fastify.authenticate }, async (request, reply) => { await ensureFeatureEnabled(fastify, request); diff --git a/server/src/routes/users.js b/server/src/routes/users.js index 492c1d4f..1031b0a0 100644 --- a/server/src/routes/users.js +++ b/server/src/routes/users.js @@ -32,6 +32,9 @@ const listQuerySchema = z.object({ status: z.enum(["active", "archived"]).optional(), q: z.string().max(100).optional(), }); +const listQueryWithDepartmentSchema = listQuerySchema.extend({ + departmentId: z.string().uuid().optional(), +}); const createBodySchema = z.object({ employeeNo: z.string().min(1).max(50), @@ -86,8 +89,10 @@ function parseUserId(params) { return parsed.data; } -function parseListQuery(query) { - const parsed = listQuerySchema.safeParse(query ?? {}); +function parseListQuery(query, options = {}) { + const allowDepartmentFilter = options.allowDepartmentFilter === true; + const schema = allowDepartmentFilter ? listQueryWithDepartmentSchema : listQuerySchema; + const parsed = schema.safeParse(query ?? {}); if (!parsed.success) { throw new AppError({ code: "VALID_001", @@ -102,6 +107,7 @@ function parseListQuery(query) { pageSize: parsed.data.pageSize ?? 20, status: parsed.data.status, q: parsed.data.q?.trim() ?? "", + departmentId: allowDepartmentFilter ? parsed.data.departmentId : undefined, }; } @@ -232,6 +238,7 @@ async function usersRoutes(fastify, opts = {}) { typeof opts.basePath === "string" && opts.basePath.trim() ? opts.basePath.trim() : "/users"; const basePath = basePathRaw.startsWith("/") ? basePathRaw : `/${basePathRaw}`; const routeBasePath = basePath.endsWith("/") ? basePath.slice(0, -1) : basePath; + const allowDepartmentFilter = opts.allowDepartmentFilter === true; fastify.get( routeBasePath, @@ -239,12 +246,13 @@ async function usersRoutes(fastify, opts = {}) { preHandler: fastify.requirePermission("system.users"), }, async (request, reply) => { - const query = parseListQuery(request.query); + const query = parseListQuery(request.query, { allowDepartmentFilter }); const skip = (query.page - 1) * query.pageSize; const q = query.q; const where = { ...(query.status ? { status: query.status } : {}), + ...(query.departmentId ? { department_id: query.departmentId } : {}), ...(q ? { OR: [ diff --git a/server/tests/unit/routes/users.list.test.js b/server/tests/unit/routes/users.list.test.js new file mode 100644 index 00000000..de6a70ab --- /dev/null +++ b/server/tests/unit/routes/users.list.test.js @@ -0,0 +1,129 @@ +const Fastify = require("fastify"); + +const usersRoutes = require("../../../src/routes/users"); + +function buildEmployeeRow(overrides = {}) { + const now = new Date("2026-03-28T10:00:00.000Z"); + return { + id: "11111111-1111-4111-8111-111111111111", + employee_no: "E001", + name: "Alice", + phone: "13800000000", + email: "alice@example.com", + status: "active", + department_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + title: "员工", + created_at: now, + updated_at: now, + roles: [{ role_code: "employee" }], + ...overrides, + }; +} + +async function buildApp(routeOptions = {}) { + const app = Fastify(); + const findMany = vi.fn().mockResolvedValue([buildEmployeeRow()]); + const count = vi.fn().mockResolvedValue(1); + + app.decorate("prisma", { + employee: { + findMany, + count, + }, + }); + app.decorate("requirePermission", () => async (request) => { + request.employee = { + id: "actor-1", + department_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + permissionCodes: ["system.users"], + }; + }); + app.decorate("authenticate", async (request) => { + request.employee = { + id: "actor-1", + department_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + permissionCodes: ["system.users"], + }; + }); + app.decorate("hasPermission", () => true); + app.decorate("config", {}); + + await app.register(usersRoutes, { prefix: "/api", ...routeOptions }); + return { app, findMany, count }; +} + +describe("usersRoutes list query", () => { + it("supports departmentId filter for /employees when enabled", async () => { + const departmentId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + const { app, findMany, count } = await buildApp({ + basePath: "/employees", + allowDepartmentFilter: true, + }); + + const response = await app.inject({ + method: "GET", + url: `/api/employees?page=1&pageSize=20&departmentId=${departmentId}`, + }); + + expect(response.statusCode).toBe(200); + expect(findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ + department_id: departmentId, + }), + }), + ); + expect(count).toHaveBeenCalledWith({ + where: expect.objectContaining({ + department_id: departmentId, + }), + }); + + await app.close(); + }); + + it("combines q + status + departmentId for /employees", async () => { + const departmentId = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; + const { app, findMany } = await buildApp({ + basePath: "/employees", + allowDepartmentFilter: true, + }); + + const response = await app.inject({ + method: "GET", + url: `/api/employees?status=active&q=alice&departmentId=${departmentId}`, + }); + + expect(response.statusCode).toBe(200); + expect(findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: expect.objectContaining({ + status: "active", + department_id: departmentId, + OR: expect.arrayContaining([ + expect.objectContaining({ name: expect.any(Object) }), + expect.objectContaining({ employee_no: expect.any(Object) }), + ]), + }), + }), + ); + + await app.close(); + }); + + it("does not apply departmentId filter for /users", async () => { + const departmentId = "dddddddd-dddd-4ddd-8ddd-dddddddddddd"; + const { app, findMany } = await buildApp(); + + const response = await app.inject({ + method: "GET", + url: `/api/users?departmentId=${departmentId}`, + }); + + expect(response.statusCode).toBe(200); + const where = findMany.mock.calls[0][0].where; + expect(where.department_id).toBeUndefined(); + + await app.close(); + }); +});