Merge pull request #28 from yunyingk/feat/issue-2-roles
feat: add role definitions and member CLI
This commit is contained in:
12 files changed
+200
-1
No files matched your search
@@ -40,6 +40,7 @@ metadata:
|
||||
| 单据预算状态 / 超预算与占用信息 | `hose bill budget <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据附件 / 发票原件标准列表 | `hose bill attachments <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 系统/自定义档案维度与档案项 | `hose dimension list`, `hose dimension items <维度>` | [references/dimension.md](references/dimension.md) |
|
||||
| 企业角色、角色组与角色成员 | `hose role list`, `hose role groups`, `hose role members <角色>` | [references/role.md](references/role.md) |
|
||||
| 单据 Web 详情直达链接生成 | `hose bill link <单号|ID>` | [references/bill.md](references/bill.md) |
|
||||
| 单据实体模型与字段元数据查询 | `hose bill schema` | [references/bill.md](references/bill.md) |
|
||||
| 企业通讯录检索 / 员工档案 / 防爆保护 | `hose contact search`, `hose contact list`, `hose contact get` | [references/contact.md](references/contact.md) |
|
||||
@@ -83,6 +84,9 @@ hose bill budget S26000001 # 查看单据预算超限
|
||||
hose bill attachments S26000001 # 查看附件和发票原件列表
|
||||
hose dimension list # 查看系统与自定义档案维度
|
||||
hose dimension items 项目 # 查看项目、成本中心等档案项
|
||||
hose role list # 查看企业角色定义
|
||||
hose role groups # 查看角色组及其角色
|
||||
hose role members 财务主管 # 查看指定角色成员
|
||||
hose bill schema # 查询单据实体元数据字典
|
||||
|
||||
# 4. 待办与消息
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# 角色与角色组
|
||||
|
||||
角色页对应的只读 CLI:
|
||||
|
||||
```bash
|
||||
hose role list
|
||||
hose role list --keyword=财务
|
||||
hose role groups
|
||||
hose role members 财务主管
|
||||
hose role members CODE15 --json
|
||||
```
|
||||
|
||||
接口来自系统配置 → 角色页面:角色定义列表、角色组及指定角色成员。成员查询支持角色 ID、编码或名称。
|
||||
@@ -0,0 +1,40 @@
|
||||
import { numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import { getRoleGroups, getRoleMembers, searchRoles } from "../../domains/role/tools.js";
|
||||
|
||||
export async function handleRoleCommand(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const corp = runtime.selectedCorp;
|
||||
if (!corp) throw new Error("未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose auth login 登录。");
|
||||
const client = await createEkbClient(corp), corpId = corp.corpId || corp.id;
|
||||
const action = parsed.action?.toLowerCase() || "list";
|
||||
if (["list", "search"].includes(action)) {
|
||||
const keyword = stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0];
|
||||
const roles = await searchRoles(client, corpId, { keyword });
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], roles.length) || roles.length;
|
||||
const items = roles.slice(0, count);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, corpName: corp.name, count: items.length, roles: items }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = items.map((role) => [role.name, role.code || "-", role.id, role.scope.name || "-", role.roleGroupId || "-"]);
|
||||
return { stdout: `====== 企业角色 (共 ${items.length} 个) ======\n${rows.length ? printTable(["名称", "编码", "ID", "角色类型", "角色组 ID"], rows) : "暂无匹配角色"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
if (["groups", "group"].includes(action)) {
|
||||
const groups = await getRoleGroups(client, corpId);
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, corpName: corp.name, count: groups.length, groups }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = groups.map((group) => [group.name, group.id, group.roleDefs.length, group.roleDefs.map((role) => role.name).join(", ") || "-"]);
|
||||
return { stdout: `====== 角色组 (共 ${groups.length} 个) ======\n${rows.length ? printTable(["名称", "ID", "角色数", "角色"], rows) : "暂无角色组"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
if (["members", "member", "staffs", "staff"].includes(action)) {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["role", "id", "code", "name"]);
|
||||
if (!target) throw new Error("请提供角色 ID、编码或名称: hose role members <角色>");
|
||||
const report = await getRoleMembers(client, corpId, target);
|
||||
if (!report) {
|
||||
if (runtime.jsonMode) return { stdout: printJson({ found: false, target }, runtime.outputOptions), stderr: "", exitCode: 1 };
|
||||
return { stdout: "", stderr: `[NOT FOUND] 未找到角色: ${target}\n`, exitCode: 1 };
|
||||
}
|
||||
if (runtime.jsonMode) return { stdout: printJson({ corpId, corpName: corp.name, ...report, count: report.members.length }, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
const rows = report.members.map((member) => [member.name, member.code || "-", member.id, member.email || "-", member.cellphone || "-"]);
|
||||
return { stdout: `====== 角色成员 (角色: ${report.role.name} | 共 ${rows.length} 人) ======\n${rows.length ? printTable(["姓名", "工号", "staffId", "邮箱", "手机号"], rows) : "暂无成员"}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
throw new Error(`未知 role 子命令: ${action}。支持: list, groups, members <角色 ID|编码|名称>`);
|
||||
}
|
||||
@@ -125,6 +125,7 @@ export function printHelp(): string {
|
||||
message 消息中心与通知管理 (list, count, read, read-all)
|
||||
platform 自建应用管理 (list)
|
||||
dimension 系统/自定义档案维度 (list, items <维度>)
|
||||
role 角色定义与成员 (list, groups, members <角色>)
|
||||
skill Agent Skill 管理 (install, status, dump)
|
||||
probe 连通性诊断 (probe [corpId])
|
||||
update 版本自更新与发布记录 (update, update check, update --changelog)
|
||||
@@ -169,6 +170,9 @@ export function printHelp(): string {
|
||||
hose-use bill attachments S26000001 # 查看单据附件和发票原件标准列表
|
||||
hose-use dimension list # 查看系统与自定义档案维度
|
||||
hose-use dimension items 项目 # 查看项目档案项
|
||||
hose-use role list # 查看企业角色定义
|
||||
hose-use role groups # 查看角色组及其角色
|
||||
hose-use role members 财务主管 # 查看指定角色成员
|
||||
hose-use bill link CL20260901001 # 获取单据 Web 详情直达免密跳转链接
|
||||
hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆
|
||||
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
|
||||
|
||||
@@ -19,6 +19,7 @@ import { handleHttpCommand } from "./commands/http.js";
|
||||
import { handleTaskCommand } from "./commands/task.js";
|
||||
import { handleMessageCommand } from "./commands/message.js";
|
||||
import { handleDimensionCommand } from "./commands/dimension.js";
|
||||
import { handleRoleCommand } from "./commands/role.js";
|
||||
import type { CliResult, CliRunOptions } from "./types.js";
|
||||
|
||||
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
|
||||
@@ -147,6 +148,9 @@ async function dispatchCli(
|
||||
case "archive":
|
||||
case "archives":
|
||||
return await handleDimensionCommand(parsed, runtime);
|
||||
case "role":
|
||||
case "roles":
|
||||
return await handleRoleCommand(parsed, runtime);
|
||||
case "message":
|
||||
case "messages":
|
||||
case "notify":
|
||||
|
||||
@@ -34,12 +34,13 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => {
|
||||
try {
|
||||
const res = installSkillFiles(tmp);
|
||||
expect(res.targetDir).toBe(tmp);
|
||||
expect(res.files.length).toBe(10);
|
||||
expect(res.files.length).toBe(11);
|
||||
expect(existsSync(join(tmp, "SKILL.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "agents", "openai.yaml"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "auth.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "bill.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "contact.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "role.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "workflow.md"))).toBe(true);
|
||||
expect(existsSync(join(tmp, "references", "service.md"))).toBe(true);
|
||||
} finally {
|
||||
|
||||
@@ -12,6 +12,7 @@ import refContact from "../../skills/hose-use/references/contact.md" with { type
|
||||
import refTask from "../../skills/hose-use/references/task.md" with { type: "text" };
|
||||
import refMessage from "../../skills/hose-use/references/message.md" with { type: "text" };
|
||||
import refDimension from "../../skills/hose-use/references/dimension.md" with { type: "text" };
|
||||
import refRole from "../../skills/hose-use/references/role.md" with { type: "text" };
|
||||
|
||||
export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
"SKILL.md": skillMain,
|
||||
@@ -22,6 +23,7 @@ export const EMBEDDED_SKILL_FILES: Record<string, string> = {
|
||||
"references/task.md": refTask,
|
||||
"references/message.md": refMessage,
|
||||
"references/dimension.md": refDimension,
|
||||
"references/role.md": refRole,
|
||||
"references/workflow.md": refWorkflow,
|
||||
"references/service.md": refService,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# Role Domain
|
||||
|
||||
角色域提供企业角色定义、角色组和角色成员的只读查询。
|
||||
|
||||
- `GET /api/v1/organization/roles?start=0&count=2999&corpId=...`:角色定义列表
|
||||
- `GET /api/v1/organization/roleGroups?corpId=...`:角色组及其角色定义
|
||||
- `GET /api/v1/organization/staffs/byRole?roleDefId=...&corpId=...`:指定角色的员工成员
|
||||
|
||||
CLI 入口为 `hose role list`、`hose role groups` 和 `hose role members <角色 ID|编码|名称>`。
|
||||
@@ -0,0 +1,22 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { RoleGroupSchema, RoleMemberSchema, RoleSchema, type Role, type RoleGroup, type RoleMember } from "./types.js";
|
||||
|
||||
export async function listRoles(client: KyInstance, corpId: string, start = 0, count = 2999): Promise<Role[]> {
|
||||
const response = await client.get("api/v1/organization/roles", { searchParams: { start: String(start), count: String(count), corpId } });
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return z.array(RoleSchema).parse(json.items ?? []);
|
||||
}
|
||||
|
||||
export async function listRoleGroups(client: KyInstance, corpId: string): Promise<RoleGroup[]> {
|
||||
const response = await client.get("api/v1/organization/roleGroups", { searchParams: { corpId } });
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
return z.array(RoleGroupSchema).parse(json.items ?? []);
|
||||
}
|
||||
|
||||
export async function listRoleMembers(client: KyInstance, corpId: string, roleDefId: string): Promise<RoleMember[]> {
|
||||
const response = await client.get("api/v1/organization/staffs/byRole", { searchParams: { roleDefId, corpId } });
|
||||
const json = (await response.json()) as { items?: unknown[] };
|
||||
const items = (json.items ?? []).map((item: any) => item?.staff ?? item);
|
||||
return z.array(RoleMemberSchema).parse(items);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { getRoleMembers, getRoleGroups, searchRoles } from "./tools.js";
|
||||
|
||||
describe("Role Domain - 角色定义与成员", () => {
|
||||
it("loads and filters roles", async () => {
|
||||
const client = { get: async (path: string) => new Response(JSON.stringify(path.includes("roleGroups")
|
||||
? { items: [{ id: "group-1", name: "未分组", roleDefs: [{ id: "role-1", name: "财务主管", code: "FIN" }] }] }
|
||||
: { items: [{ id: "role-1", name: "财务主管", code: "FIN", roleGroupId: "group-1", scope: { name: "普通角色", properties: {} } }] })) } as any;
|
||||
const roles = await searchRoles(client, "corp-1", { keyword: "财务" });
|
||||
expect(roles).toHaveLength(1); expect(roles[0]?.id).toBe("role-1");
|
||||
expect((await getRoleGroups(client, "corp-1"))[0]?.name).toBe("未分组");
|
||||
});
|
||||
|
||||
it("resolves a role and loads its members", async () => {
|
||||
const client = { get: async (path: string) => new Response(JSON.stringify(path.includes("staffs/byRole")
|
||||
? { items: [{ id: "staff-1", name: "张三", code: "1001", departments: [] }] }
|
||||
: path.includes("roleGroups") ? { items: [] }
|
||||
: { items: [{ id: "role-1", name: "财务主管", code: "FIN", scope: { name: "普通角色", properties: {} } }] })) } as any;
|
||||
const report = await getRoleMembers(client, "corp-2", "FIN");
|
||||
expect(report?.role.name).toBe("财务主管"); expect(report?.members[0]?.name).toBe("张三");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { z } from "zod";
|
||||
import type { KyInstance } from "ky";
|
||||
import { listRoleGroups, listRoleMembers, listRoles } from "./api.js";
|
||||
import type { Role, RoleGroup, RoleMemberReport, RoleQuery } from "./types.js";
|
||||
|
||||
const cache = new Map<string, { timestamp: number; roles: Role[]; groups: RoleGroup[] }>();
|
||||
const CACHE_TTL_MS = 10 * 60 * 1000;
|
||||
async function getCatalog(client: KyInstance, corpId: string): Promise<{ roles: Role[]; groups: RoleGroup[] }> {
|
||||
const existing = cache.get(corpId);
|
||||
if (existing && Date.now() - existing.timestamp < CACHE_TTL_MS) return existing;
|
||||
const [roles, groups] = await Promise.all([listRoles(client, corpId), listRoleGroups(client, corpId)]);
|
||||
const result = { timestamp: Date.now(), roles, groups }; cache.set(corpId, result); return result;
|
||||
}
|
||||
|
||||
export async function searchRoles(client: KyInstance, corpId: string, query: RoleQuery = {}): Promise<Role[]> {
|
||||
const { roles } = await getCatalog(client, corpId);
|
||||
const keyword = (query.keyword || query.id || query.code || query.name || "").trim().toLowerCase();
|
||||
if (!keyword) return roles;
|
||||
return roles.filter((role) => [role.id, role.name, role.code, role.purposeName, role.scope.name].some((value) => value.toLowerCase().includes(keyword)));
|
||||
}
|
||||
export async function getRoleGroups(client: KyInstance, corpId: string): Promise<RoleGroup[]> { return (await getCatalog(client, corpId)).groups; }
|
||||
export async function resolveRole(client: KyInstance, corpId: string, target: string): Promise<Role | undefined> {
|
||||
const matches = await searchRoles(client, corpId, { keyword: target });
|
||||
return matches.find((role) => role.id === target || role.code === target || role.name === target) || matches[0];
|
||||
}
|
||||
export async function getRoleMembers(client: KyInstance, corpId: string, target: string): Promise<RoleMemberReport | undefined> {
|
||||
const role = await resolveRole(client, corpId, target); if (!role) return undefined;
|
||||
return { role, members: await listRoleMembers(client, corpId, role.id) };
|
||||
}
|
||||
|
||||
export const roleTools = [{
|
||||
name: "role_list", description: "列出当前企业角色定义与角色组",
|
||||
parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }),
|
||||
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
|
||||
const corp = corpContext.getCurrent(); if (!corp) throw new Error("未配置活跃企业上下文");
|
||||
const client = await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp));
|
||||
const roles = await searchRoles(client, corp.corpId || corp.id, { keyword: params.keyword });
|
||||
return { count: roles.length, roles: roles.slice(0, params.count ?? 100) };
|
||||
},
|
||||
}];
|
||||
@@ -0,0 +1,38 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const RoleScopeSchema = z.object({
|
||||
name: z.string().optional().default(""),
|
||||
enName: z.string().nullable().optional().default(""),
|
||||
properties: z.record(z.string(), z.string()).optional().default({}),
|
||||
});
|
||||
|
||||
export const RoleSchema = z.object({
|
||||
id: z.string(), name: z.string().default(""), code: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true), corporationId: z.string().optional().default(""),
|
||||
roleGroupId: z.string().optional().default(""), scope: RoleScopeSchema.optional().default({ name: "", enName: "", properties: {} }),
|
||||
sourceType: z.string().optional().default(""), sourceTypeValue: z.string().nullable().optional(),
|
||||
purposeType: z.string().optional().default(""), purposeName: z.string().optional().default(""),
|
||||
locked: z.boolean().optional().default(false), containSubDept: z.boolean().optional().default(false),
|
||||
applicableToSubDepartments: z.boolean().optional().default(false),
|
||||
});
|
||||
|
||||
export const RoleGroupSchema = z.object({
|
||||
id: z.string(), name: z.string().default(""), code: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true), corporationId: z.string().optional().default(""),
|
||||
roleDefs: z.array(RoleSchema).optional().default([]),
|
||||
});
|
||||
|
||||
export const RoleMemberSchema = z.object({
|
||||
id: z.string(), userId: z.string().optional().default(""), name: z.string().default(""),
|
||||
code: z.string().optional().default(""), enName: z.string().nullable().optional(),
|
||||
email: z.string().nullable().optional(), cellphone: z.string().nullable().optional(),
|
||||
active: z.boolean().optional().default(true), departments: z.array(z.string()).optional().default([]),
|
||||
defaultDepartment: z.string().nullable().optional(), external: z.boolean().optional().default(false),
|
||||
admin: z.boolean().optional().default(false),
|
||||
});
|
||||
|
||||
export type Role = z.infer<typeof RoleSchema>;
|
||||
export type RoleGroup = z.infer<typeof RoleGroupSchema>;
|
||||
export type RoleMember = z.infer<typeof RoleMemberSchema>;
|
||||
export interface RoleQuery { keyword?: string; id?: string; code?: string; name?: string; }
|
||||
export interface RoleMemberReport { role: Role; members: RoleMember[]; }
|
||||
Reference in new issue
Block a user