diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index 1e40f33..8d368f2 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -49,6 +49,7 @@ metadata: | 单据附件 / 发票原件标准列表 | `hose-use bill attachments <单号|ID>` | [references/bill.md](references/bill.md) | | 单据附件下载 | `hose-use bill download <单号|ID> --output-dir <目录>` | [references/bill.md](references/bill.md) | | 系统/自定义档案维度与档案项 | `hose-use dimension list`, `hose-use dimension items <维度>` | [references/dimension.md](references/dimension.md) | +| 费用类型全生命周期与表单规格 (增删查改/停启用/移动/字段) | `hose-use feetype list`, `hose-use feetype create`, `hose-use feetype get ` | [references/feetype.md](references/feetype.md) | | 企业角色、角色组与角色成员 | `hose-use role list`, `hose-use role groups`, `hose-use role members <角色>` | [references/role.md](references/role.md) | | 角色权限只读快照 | `hose-use permission get` | [references/role.md](references/role.md) | | 单据 Web 详情直达链接生成 | `hose-use bill link <单号|ID>` | [references/bill.md](references/bill.md) | @@ -113,6 +114,13 @@ hose-use bill attachments S26000001 # 查看附件和发票 hose-use bill download S26000001 --output-dir ./downloads # 下载附件到本地目录 hose-use dimension list # 查看系统与自定义档案维度 hose-use dimension items 项目 # 查看项目、成本中心等档案项 +hose-use feetype list # 树形层级查看企业费用类型 +hose-use feetype get 交通费 --specs # 查看费用类型详情与报账/申请字段 +hose-use feetype create --name="市内打车" --parent="交通费" # 在指定父级下新建费用类型 +hose-use feetype update 市内打车 --desc="滴滴企业版" # 修改费用类型属性 +hose-use feetype disable 市内打车 # 停用费用类型 (软删除) +hose-use feetype enable 市内打车 # 重新启用费用类型 +hose-use feetype move 市内打车 --parent="差旅费用" # 移动费用类型到新父级 hose-use role list # 查看企业角色定义 hose-use role groups # 查看角色组及其角色 hose-use role members 财务主管 # 查看指定角色成员 diff --git a/skills/hose-use/references/feetype.md b/skills/hose-use/references/feetype.md new file mode 100644 index 0000000..9370f9c --- /dev/null +++ b/skills/hose-use/references/feetype.md @@ -0,0 +1,33 @@ +# 费用类型与表单字段规格管理 (feetype) + +费用类型 (FeeType) 是合思/易快报费控系统的底层核心业务实体,涵盖企业报销科目树、单据表单字段规则规格以及申请/报账控件配置。 + +## 常用命令 + +```bash +# 1. 列表与树形层级 +hose-use feetype list # 树形层级展示当前企业所有活跃费用类型 +hose-use feetype list --all # 包含已停用的全量费用类型 +hose-use feetype list --keyword="差旅" # 模糊搜索名称、编码或路径 +hose-use feetype list --flat # 以平铺表格格式展示 +hose-use feetype list --json # JSON 结构化输出 (Agent 推荐) + +# 2. 单项详情与字段规格 +hose-use feetype get 交通费 # 查看费用类型基本配置、层级与父子节点 +hose-use feetype get 交通费 --specs # 同时输出报账字段与申请字段配置摘要 +hose-use feetype fields 交通费 # 查看完整的报账与申请字段表格 (字段名、类型、必填、可编辑) + +# 3. 创建与修改 (增改) +hose-use feetype create --name="市内打车费" --parent="交通费" # 在指定父级下创建,自动继承父级字段规则 +hose-use feetype create --name="公杂费" --code="COST88" # 自定义编码并建在顶级 +hose-use feetype update 市内打车费 --desc="包含出租车与网约车" # 修改描述或属性 +hose-use feetype update 市内打车费 --color="#4caf50" # 修改标识颜色 + +# 4. 停用与启用 (删查) +hose-use feetype disable 市内打车费 # 停用费用类型 (软删除,用户端隐藏) +hose-use feetype enable 市内打车费 # 重新启用费用类型 (支持 --recursive 级联启用) + +# 5. 调整层级结构 +hose-use feetype move 市内打车费 --parent="差旅费用" # 移动至差旅费用之下 +hose-use feetype move 市内打车费 --parent=root # 移至企业顶级根节点 +``` diff --git a/src/cli/commands/feetype.test.ts b/src/cli/commands/feetype.test.ts new file mode 100644 index 0000000..437979e --- /dev/null +++ b/src/cli/commands/feetype.test.ts @@ -0,0 +1,425 @@ +import { describe, it, expect, spyOn } from "bun:test"; +import { handleFeeTypeCommand } from "./feetype.js"; +import * as feetypeTools from "../../domains/feetype/tools.js"; +import type { CliRuntime } from "../types.js"; +import type { CorpConfig } from "../../core/config/types.js"; +import { FeeTypeNode } from "../../domains/feetype/types.js"; + +describe("CLI - feetype 费用类型管理命令", () => { + const dummyRuntimeNoCorp: CliRuntime = { + corpContext: { + listCorps: () => [], + getCurrent: () => null, + switchCorp: () => false, + resolve: () => null, + } as any, + selectedCorp: null, + jsonMode: false, + }; + + const mockCorp: CorpConfig = { + id: "corp_test", + name: "测试科技企业", + source: "account", + baseUrl: "https://app.ekuaibao.com", + credentials: { + accessToken: "mock-token", + corpId: "corp_test", + staffId: "mock-staff", + }, + }; + + const dummyRuntimeWithCorp: CliRuntime = { + corpContext: { + listCorps: () => [mockCorp], + getCurrent: () => mockCorp, + switchCorp: () => true, + resolve: () => mockCorp, + } as any, + selectedCorp: mockCorp, + jsonMode: false, + }; + + const mockTree = [ + { + feeType: { + id: "ft_travel", + name: "差旅费用", + code: "COST19", + active: true, + parentId: "", + order: 1000, + color: "#90caf9", + icon: "https://images.ekuaibao.com/feetype/sf_100.png", + description: "员工差旅相关费用", + }, + children: [ + { + feeType: { + id: "ft_flight", + name: "飞机票", + code: "COST54", + active: true, + parentId: "ft_travel", + order: 1001, + color: "#90caf9", + icon: "", + description: "", + }, + children: [], + }, + ], + }, + { + feeType: { + id: "ft_disabled", + name: "已停用费用", + code: "COST99", + active: false, + parentId: "", + order: 2000, + color: "#ccc", + icon: "", + description: "", + }, + children: [], + }, + ] as unknown as FeeTypeNode[]; + + it("未选中企业时抛出友好错误", async () => { + expect( + handleFeeTypeCommand( + { + area: "feetype", + action: "list", + args: [], + options: {}, + raw: ["feetype", "list"], + }, + dummyRuntimeNoCorp + ) + ).rejects.toThrow("未指定或未找到有效企业"); + }); + + it("feetype list 默认以树形层级展示活跃费用类型", async () => { + const spy = spyOn(feetypeTools, "listFeeTypes").mockResolvedValue({ + total: 3, + items: mockTree, + rawTree: mockTree, + }); + + const res = await handleFeeTypeCommand( + { + area: "feetype", + action: "list", + args: [], + options: {}, + raw: ["feetype", "list"], + }, + dummyRuntimeWithCorp + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("费用类型列表"); + expect(res.stdout).toContain("差旅费用"); + expect(res.stdout).toContain("飞机票"); + expect(res.stdout).toContain("COST19"); + expect(res.stdout).toContain("🟢 启用"); + + spy.mockRestore(); + }); + + it("feetype list --json 支持结构化输出", async () => { + const spy = spyOn(feetypeTools, "listFeeTypes").mockResolvedValue({ + total: 2, + items: mockTree, + rawTree: mockTree, + }); + + const jsonRuntime = { ...dummyRuntimeWithCorp, jsonMode: true }; + const res = await handleFeeTypeCommand( + { + area: "feetype", + action: "list", + args: [], + options: { json: true }, + raw: ["feetype", "list", "--json"], + }, + jsonRuntime + ); + + expect(res.exitCode).toBe(0); + const parsed = JSON.parse(res.stdout); + expect(parsed.corpId).toBe("corp_test"); + expect(parsed.total).toBe(2); + expect(parsed.items.length).toBe(2); + + spy.mockRestore(); + }); + + it("feetype get 查询单个费用类型详情及字段规格", async () => { + const mockDetail = { + feeType: { + id: "ft_travel", + name: "差旅费用", + code: "COST19", + active: true, + parentId: "", + path: "差旅费用", + parentName: "顶级 (根节点)", + childrenCount: 1, + color: "#90caf9", + icon: "https://images.ekuaibao.com/feetype/sf_100.png", + description: "差旅综合报销", + }, + specifications: { + expenseComponents: [ + { field: "amount", cnLabel: "报销金额", type: "money", optional: false }, + ], + requisitionComponents: [ + { field: "amount", cnLabel: "预计金额", type: "money", optional: true }, + ], + }, + }; + + const spy = spyOn(feetypeTools, "getFeeTypeDetail").mockResolvedValue(mockDetail as any); + + const res = await handleFeeTypeCommand( + { + area: "feetype", + action: "get", + args: ["差旅费用"], + options: { specs: true }, + raw: ["feetype", "get", "差旅费用", "--specs"], + }, + dummyRuntimeWithCorp + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("差旅费用"); + expect(res.stdout).toContain("COST19"); + expect(res.stdout).toContain("报销金额 (amount) - money [必填]"); + expect(res.stdout).toContain("预计金额 (amount) - money [选填]"); + + spy.mockRestore(); + }); + + it("feetype create 创建费用类型并展示卡片", async () => { + const mockCreated = { + id: "ft_hotel", + name: "酒店住宿", + code: "COST66", + active: true, + parentId: "ft_travel", + path: "差旅费用 / 酒店住宿", + parentName: "差旅费用", + childrenCount: 0, + color: "#90caf9", + icon: "", + description: "出差酒店", + }; + + const spy = spyOn(feetypeTools, "createFeeType").mockResolvedValue(mockCreated as any); + + const res = await handleFeeTypeCommand( + { + area: "feetype", + action: "create", + args: [], + options: { + name: "酒店住宿", + parent: "差旅费用", + }, + raw: ["feetype", "create", "--name=酒店住宿", "--parent=差旅费用"], + }, + dummyRuntimeWithCorp + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("费用类型创建成功"); + expect(res.stdout).toContain("酒店住宿"); + expect(res.stdout).toContain("COST66"); + expect(res.stdout).toContain("差旅费用 / 酒店住宿"); + + spy.mockRestore(); + }); + + it("feetype update 修改费用类型属性", async () => { + const mockUpdated = { + id: "ft_hotel", + name: "酒店住宿(改)", + code: "COST66", + active: true, + parentId: "ft_travel", + path: "差旅费用 / 酒店住宿(改)", + parentName: "差旅费用", + childrenCount: 0, + color: "#90caf9", + icon: "", + description: "新说明", + }; + + const spy = spyOn(feetypeTools, "updateFeeTypeInfo").mockResolvedValue(mockUpdated as any); + + const res = await handleFeeTypeCommand( + { + area: "feetype", + action: "update", + args: ["酒店住宿"], + options: { desc: "新说明" }, + raw: ["feetype", "update", "酒店住宿", "--desc=新说明"], + }, + dummyRuntimeWithCorp + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("费用类型修改成功"); + expect(res.stdout).toContain("新说明"); + + spy.mockRestore(); + }); + + it("feetype disable 停用费用类型", async () => { + const spy = spyOn(feetypeTools, "disableFeeTypeItem").mockResolvedValue({ + success: true, + item: { + id: "ft_hotel", + name: "酒店住宿", + code: "COST66", + active: false, + } as any, + }); + + const res = await handleFeeTypeCommand( + { + area: "feetype", + action: "disable", + args: ["酒店住宿"], + options: { yes: true }, + raw: ["feetype", "disable", "酒店住宿", "--yes"], + }, + dummyRuntimeWithCorp + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("已成功停用"); + expect(res.stdout).toContain("酒店住宿"); + + spy.mockRestore(); + }); + + it("feetype enable 重新启用费用类型", async () => { + const spy = spyOn(feetypeTools, "enableFeeTypeItem").mockResolvedValue({ + success: true, + item: { + id: "ft_hotel", + name: "酒店住宿", + code: "COST66", + active: true, + } as any, + }); + + const res = await handleFeeTypeCommand( + { + area: "feetype", + action: "enable", + args: ["酒店住宿"], + options: {}, + raw: ["feetype", "enable", "酒店住宿"], + }, + dummyRuntimeWithCorp + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("已成功启用"); + expect(res.stdout).toContain("酒店住宿"); + + spy.mockRestore(); + }); + + it("feetype move 移动费用类型父级节点", async () => { + const spy = spyOn(feetypeTools, "moveFeeTypeItem").mockResolvedValue({ + success: true, + item: { + id: "ft_hotel", + name: "酒店住宿", + code: "COST66", + active: true, + path: "办公费 / 酒店住宿", + } as any, + parentName: "办公费", + }); + + const res = await handleFeeTypeCommand( + { + area: "feetype", + action: "move", + args: ["酒店住宿"], + options: { parent: "办公费" }, + raw: ["feetype", "move", "酒店住宿", "--parent=办公费"], + }, + dummyRuntimeWithCorp + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("费用类型移动成功"); + expect(res.stdout).toContain("新所属父级 : 办公费"); + + spy.mockRestore(); + }); + + it("feetype fields 打印报账与申请字段表格", async () => { + const spy = spyOn(feetypeTools, "getFeeTypeFieldsList").mockResolvedValue({ + feeType: { + id: "ft_travel", + name: "差旅费用", + code: "COST19", + } as any, + expenseFields: [ + { + field: "amount", + label: "金额", + type: "money", + required: true, + editable: true, + hidden: false, + }, + ], + requisitionFields: [], + }); + + const res = await handleFeeTypeCommand( + { + area: "feetype", + action: "fields", + args: ["差旅费用"], + options: {}, + raw: ["feetype", "fields", "差旅费用"], + }, + dummyRuntimeWithCorp + ); + + expect(res.exitCode).toBe(0); + expect(res.stdout).toContain("费用类型字段配置"); + expect(res.stdout).toContain("报账字段列表"); + expect(res.stdout).toContain("amount"); + expect(res.stdout).toContain("🔴 必填"); + + spy.mockRestore(); + }); + + it("未知 feetype 子命令时抛出支持说明", async () => { + expect( + handleFeeTypeCommand( + { + area: "feetype", + action: "invalidCmd", + args: [], + options: {}, + raw: ["feetype", "invalidCmd"], + }, + dummyRuntimeWithCorp + ) + ).rejects.toThrow("未知 feetype 子命令"); + }); +}); diff --git a/src/cli/commands/feetype.ts b/src/cli/commands/feetype.ts new file mode 100644 index 0000000..42e79f1 --- /dev/null +++ b/src/cli/commands/feetype.ts @@ -0,0 +1,516 @@ +import { CliParsedArgs, CliResult, CliRuntime } from "../types.js"; +import { printJson, printTable } from "../printer.js"; +import { booleanOption, stringOption } from "../parser.js"; +import { createEkbClient } from "../../core/auth/ekb.js"; +import { + createFeeType, + disableFeeTypeItem, + enableFeeTypeItem, + findFeeType, + FlatFeeTypeItem, + flattenFeeTypeTree, + getFeeTypeDetail, + getFeeTypeFieldsList, + listFeeTypes, + moveFeeTypeItem, + updateFeeTypeInfo, +} from "../../domains/feetype/tools.js"; +import { FeeTypeNode } from "../../domains/feetype/types.js"; + +/** + * 递归渲染树形层级格式 + */ +function renderTreeRows( + nodes: FeeTypeNode[], + depth = 0, + prefix = "", + isLast = true, + acc: (string | number)[][] = [] +): (string | number)[][] { + for (let i = 0; i < nodes.length; i++) { + const node = nodes[i]; + const item = node.feeType; + if (!item) continue; + + const currentIsLast = i === nodes.length - 1; + const branch = depth === 0 ? "" : isLast ? "└─ " : "├─ "; + const indent = depth === 0 ? "" : prefix + branch; + const nextPrefix = depth === 0 ? "" : prefix + (isLast ? " " : "│ "); + + const children = Array.isArray(node.children) ? node.children : []; + acc.push([ + acc.length + 1, + `${indent}${item.name}`, + item.code || "-", + item.id, + item.active ? "🟢 启用" : "🔴 停用", + children.length ? `${children.length} 项` : "-", + ]); + + if (children.length > 0) { + renderTreeRows(children, depth + 1, nextPrefix, currentIsLast, acc); + } + } + return acc; +} + +export async function handleFeeTypeCommand( + parsed: CliParsedArgs, + runtime: CliRuntime +): Promise { + const corp = runtime.selectedCorp; + if (!corp) { + throw new Error( + "未指定或未找到有效企业。请通过 --corp= 指定企业,或运行 hose-use auth login 登录。" + ); + } + + const client = await createEkbClient(corp); + const corpId = corp.corpId || corp.id; + const action = (parsed.action?.toLowerCase() || "list").trim(); + + // ── 1. 列表 / 树形展示 (list / tree) ────────────────────────────────────────── + if (["list", "tree", "all", "search"].includes(action)) { + const includeAll = + action === "all" || + booleanOption(parsed.options, ["all", "a", "include-disabled"]) || + false; + const isFlat = + booleanOption(parsed.options, ["flat", "flatten", "table"]) || false; + const keyword = + stringOption(parsed.options, ["keyword", "q", "query"]) || parsed.args[0]; + + const result = await listFeeTypes(client, corpId, { + all: includeAll, + flat: isFlat, + keyword, + }); + + if (runtime.jsonMode) { + return { + stdout: printJson( + { + corpId, + corpName: corp.name, + total: result.total, + includeDisabled: includeAll, + keyword: keyword || null, + items: result.items, + }, + runtime.outputOptions + ), + stderr: "", + exitCode: 0, + }; + } + + let rows: (string | number)[][] = []; + if (!isFlat && !keyword) { + rows = renderTreeRows(result.rawTree); + } else { + const flatItems = (result.items as FlatFeeTypeItem[]) || []; + rows = flatItems.map((item, idx) => [ + idx + 1, + item.path || item.name, + item.code || "-", + item.id, + item.active ? "🟢 启用" : "🔴 停用", + item.childrenCount ? `${item.childrenCount} 项` : "-", + ]); + } + + const title = `====== 费用类型列表 (企业: ${corp.name} | 共 ${result.total} 个${ + includeAll ? ",含停用" : "" + }${keyword ? `,过滤: "${keyword}"` : ""}) ======`; + const tableStr = rows.length + ? printTable(["#", "名称 / 层级路径", "编码", "ID", "状态", "子节点"], rows) + : "暂无匹配的费用类型"; + + return { + stdout: `${title}\n${tableStr}\n`, + stderr: "", + exitCode: 0, + }; + } + + // ── 2. 单条详情 (get / show / detail) ───────────────────────────────────────── + if (["get", "show", "detail", "info"].includes(action)) { + const target = + parsed.args[0] || stringOption(parsed.options, ["id", "code", "name"]); + if (!target) { + throw new Error("请提供费用类型 ID、编码或名称: hose-use feetype get "); + } + + const includeSpecs = booleanOption(parsed.options, ["specs", "spec", "fields"]); + const detail = await getFeeTypeDetail(client, corpId, target, { includeSpecs }); + + if (runtime.jsonMode) { + return { + stdout: printJson( + { + corpId, + corpName: corp.name, + ...detail, + }, + runtime.outputOptions + ), + stderr: "", + exitCode: 0, + }; + } + + const ft = detail.feeType; + const lines = [ + `====== 费用类型详情 (${ft.name}) ======`, + ` 名称 : ${ft.name}${ft.enName ? ` (${ft.enName})` : ""}`, + ` 编码 : ${ft.code}`, + ` ID : ${ft.id}`, + ` 当前状态 : ${ft.active ? "🟢 启用中" : "🔴 已停用"}`, + ` 层级全路径 : ${ft.path || ft.name}`, + ` 父级节点 : ${ft.parentName || "顶级 (根节点)"} (${ft.parentId || "-"})`, + ` 子类型数量 : ${ft.childrenCount || 0} 项`, + ` 标识颜色 : ${ft.color || "-"}`, + ` 图标链接 : ${ft.icon || "-"}`, + ` 说明描述 : ${ft.description || "-"}`, + ]; + + if (includeSpecs && detail.specifications) { + const exp = detail.specifications.expenseComponents || []; + const req = detail.specifications.requisitionComponents || []; + lines.push(""); + lines.push(` ── 报账字段列表 (${exp.length} 项) ──`); + for (const c of exp) { + const reqStr = c.optional === false ? "[必填]" : "[选填]"; + lines.push(` • ${c.cnLabel || c.label} (${c.field || "-"}) - ${c.type || "text"} ${reqStr}`); + } + lines.push(""); + lines.push(` ── 申请字段列表 (${req.length} 项) ──`); + for (const c of req) { + const reqStr = c.optional === false ? "[必填]" : "[选填]"; + lines.push(` • ${c.cnLabel || c.label} (${c.field || "-"}) - ${c.type || "text"} ${reqStr}`); + } + } + + return { + stdout: `${lines.join("\n")}\n`, + stderr: "", + exitCode: 0, + }; + } + + // ── 3. 新建费用类型 (create / add) ────────────────────────────────────────── + if (["create", "add", "new"].includes(action)) { + const name = + stringOption(parsed.options, ["name", "title"]) || parsed.args[0]; + if (!name?.trim()) { + throw new Error( + "请提供费用类型名称: hose-use feetype create --name=\"费用名称\" [--code=...] [--parent=...]" + ); + } + + const code = stringOption(parsed.options, ["code"]); + const parent = stringOption(parsed.options, ["parent", "parent-id", "parentId"]); + const enName = stringOption(parsed.options, ["en-name", "enName"]); + const description = stringOption(parsed.options, ["desc", "description"]); + const color = stringOption(parsed.options, ["color"]); + const icon = stringOption(parsed.options, ["icon"]); + + const created = await createFeeType(client, corpId, { + name: name.trim(), + code, + parentId: parent, + enName, + description, + color, + icon, + }); + + if (runtime.jsonMode) { + return { + stdout: printJson( + { + success: true, + action: "create", + corpId, + feeType: created, + }, + runtime.outputOptions + ), + stderr: "", + exitCode: 0, + }; + } + + return { + stdout: [ + `🎉 费用类型创建成功!`, + ` 名称 : ${created.name}`, + ` 编码 : ${created.code}`, + ` ID : ${created.id}`, + ` 层级路径 : ${created.path}`, + ` 所属父级 : ${created.parentName || "顶级 (根节点)"}`, + ].join("\n") + "\n", + stderr: "", + exitCode: 0, + }; + } + + // ── 4. 更新费用类型 (update / edit / modify) ───────────────────────────────── + if (["update", "edit", "modify", "set"].includes(action)) { + const target = + parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]); + if (!target?.trim()) { + throw new Error( + "请指定待修改的费用类型: hose-use feetype update [--name=...] [--code=...] [--desc=...]" + ); + } + + const name = stringOption(parsed.options, ["name"]); + const code = stringOption(parsed.options, ["code"]); + const enName = stringOption(parsed.options, ["en-name", "enName"]); + const description = stringOption(parsed.options, ["desc", "description"]); + const color = stringOption(parsed.options, ["color"]); + const icon = stringOption(parsed.options, ["icon"]); + + if ( + name === undefined && + code === undefined && + enName === undefined && + description === undefined && + color === undefined && + icon === undefined + ) { + throw new Error("请至少提供一个待更新的属性参数 (例如 --name, --code, --desc, --color)"); + } + + const updated = await updateFeeTypeInfo(client, corpId, target, { + name, + code, + enName, + description, + color, + icon, + }); + + if (runtime.jsonMode) { + return { + stdout: printJson( + { + success: true, + action: "update", + corpId, + feeType: updated, + }, + runtime.outputOptions + ), + stderr: "", + exitCode: 0, + }; + } + + return { + stdout: [ + `✅ 费用类型修改成功!`, + ` 名称 : ${updated.name}`, + ` 编码 : ${updated.code}`, + ` ID : ${updated.id}`, + ` 说明描述 : ${updated.description || "-"}`, + ].join("\n") + "\n", + stderr: "", + exitCode: 0, + }; + } + + // ── 5. 停用费用类型 (disable / block / stop) ───────────────────────────────── + if (["disable", "block", "stop"].includes(action)) { + const target = + parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]); + if (!target?.trim()) { + throw new Error("请指定待停用的费用类型: hose-use feetype disable "); + } + + const res = await disableFeeTypeItem(client, corpId, target); + + if (runtime.jsonMode) { + return { + stdout: printJson( + { + success: res.success, + action: "disable", + corpId, + feeType: res.item, + }, + runtime.outputOptions + ), + stderr: "", + exitCode: 0, + }; + } + + return { + stdout: `🔴 费用类型 [${res.item.name}] (${res.item.code}) 已成功停用。\n`, + stderr: "", + exitCode: 0, + }; + } + + // ── 6. 启用费用类型 (enable / restore / start) ─────────────────────────────── + if (["enable", "restore", "start"].includes(action)) { + const target = + parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]); + if (!target?.trim()) { + throw new Error("请指定待启用的费用类型: hose-use feetype enable "); + } + + const recursive = + booleanOption(parsed.options, ["recursive", "r"]) !== false; + + const res = await enableFeeTypeItem(client, corpId, target, { recursive }); + + if (runtime.jsonMode) { + return { + stdout: printJson( + { + success: res.success, + action: "enable", + corpId, + feeType: res.item, + }, + runtime.outputOptions + ), + stderr: "", + exitCode: 0, + }; + } + + return { + stdout: `🟢 费用类型 [${res.item.name}] (${res.item.code}) 已成功启用。\n`, + stderr: "", + exitCode: 0, + }; + } + + // ── 7. 移动费用类型层级 (move) ─────────────────────────────────────────────── + if (["move"].includes(action)) { + const target = + parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]); + const parentTarget = + stringOption(parsed.options, ["parent", "to"]) || parsed.args[1]; + + if (!target?.trim()) { + throw new Error("请指定待移动的费用类型: hose-use feetype move --parent=<新父级|root>"); + } + if (parentTarget === undefined) { + throw new Error("请指定目标父级: --parent=<目标父级ID|编码|名称> 或 --parent=root (移至顶级)"); + } + + const res = await moveFeeTypeItem(client, corpId, target, parentTarget); + + if (runtime.jsonMode) { + return { + stdout: printJson( + { + success: res.success, + action: "move", + corpId, + feeType: res.item, + parentName: res.parentName, + }, + runtime.outputOptions + ), + stderr: "", + exitCode: 0, + }; + } + + return { + stdout: [ + `🚚 费用类型移动成功!`, + ` 名称 : ${res.item.name} (${res.item.code})`, + ` 新所属父级 : ${res.parentName}`, + ` 更新后路径 : ${res.item.path}`, + ].join("\n") + "\n", + stderr: "", + exitCode: 0, + }; + } + + // ── 8. 查看表单字段配置 (fields / specs) ───────────────────────────────────── + if (["fields", "specs", "schema"].includes(action)) { + const target = + parsed.args[0] || stringOption(parsed.options, ["id", "code", "target"]); + if (!target?.trim()) { + throw new Error("请指定费用类型: hose-use feetype fields "); + } + + const res = await getFeeTypeFieldsList(client, corpId, target); + + if (runtime.jsonMode) { + return { + stdout: printJson( + { + corpId, + feeType: res.feeType, + expenseFields: res.expenseFields, + requisitionFields: res.requisitionFields, + }, + runtime.outputOptions + ), + stderr: "", + exitCode: 0, + }; + } + + const expRows = res.expenseFields.map((f, i) => [ + i + 1, + f.label, + f.field, + f.type, + f.required ? "🔴 必填" : "⚪ 选填", + f.editable ? "是" : "只读", + f.hidden ? "是" : "否", + ]); + + const reqRows = res.requisitionFields.map((f, i) => [ + i + 1, + f.label, + f.field, + f.type, + f.required ? "🔴 必填" : "⚪ 选填", + f.editable ? "是" : "只读", + f.hidden ? "是" : "否", + ]); + + const outLines = [ + `====== 费用类型字段配置 (${res.feeType.name} | ${res.feeType.code}) ======`, + "", + `── 报账字段列表 (${res.expenseFields.length} 个) ──`, + expRows.length + ? printTable(["#", "字段显示名称", "字段属性名", "控件类型", "必填", "可编辑", "隐藏"], expRows) + : "暂无自定义报账字段", + "", + `── 申请字段列表 (${res.requisitionFields.length} 个) ──`, + reqRows.length + ? printTable(["#", "字段显示名称", "字段属性名", "控件类型", "必填", "可编辑", "隐藏"], reqRows) + : "暂无自定义申请字段", + ]; + + return { + stdout: `${outLines.join("\n")}\n`, + stderr: "", + exitCode: 0, + }; + } + + throw new Error( + `未知 feetype 子命令: "${action}"。\n支持的子命令:\n` + + ` • hose-use feetype list [--all] [--flat] [--keyword=...] (查看费用类型树)\n` + + ` • hose-use feetype get [--specs] (获取详情与字段配置)\n` + + ` • hose-use feetype create --name=... [--code=...] [--parent=...] (新建费用类型)\n` + + ` • hose-use feetype update [--name=...] [--desc=...] (修改属性)\n` + + ` • hose-use feetype disable (停用)\n` + + ` • hose-use feetype enable (启用)\n` + + ` • hose-use feetype move --parent=<新父级|root> (移动父级)\n` + + ` • hose-use feetype fields (查看报账与申请字段清单)` + ); +} diff --git a/src/cli/printer.ts b/src/cli/printer.ts index dd8534c..dd3b7a9 100644 --- a/src/cli/printer.ts +++ b/src/cli/printer.ts @@ -132,6 +132,7 @@ export function printHelp(): string { platform 自建应用与数据模型 (开放平台业务对象、字段与底层记录: list, get, entities, schema, records, permissions, imports) datalink platform 的同义入口,面向 DataLink 业务对象查询 dimension 系统/自定义档案维度 (list, items <维度>) + feetype 费用类型管理与字段规格配置 (list, get, create, update, disable, enable, move, fields) role 角色定义与成员 (list, groups, members <角色>) permission 权限模型快照 (get) rule 本地 AI 审批规约管理 (scopes, scope <索引号|场景>, list, get, add, delete) @@ -197,6 +198,13 @@ export function printHelp(): string { hose-use bill download S26000001 --output-dir ./downloads # 下载单据附件到本地目录 hose-use dimension list # 查看系统与自定义档案维度 hose-use dimension items 项目 # 查看项目档案项 + hose-use feetype list # 查看费用类型树与层级关系 + hose-use feetype get 交通费 --specs # 查看费用类型详情与报账/申请字段 + hose-use feetype create --name="打车费" --parent="交通费" # 在指定父级下创建费用类型 + hose-use feetype update 打车费 --desc="滴滴打车" # 修改费用类型属性 + hose-use feetype disable 打车费 # 停用费用类型 + hose-use feetype enable 打车费 # 重新启用费用类型 + hose-use feetype move 打车费 --parent="差旅费用" # 移动费用类型到新的父级 hose-use role list # 查看企业角色定义 hose-use role groups # 查看角色组及其角色 hose-use role members 财务主管 # 查看指定角色成员 diff --git a/src/cli/runner.ts b/src/cli/runner.ts index 6734305..39dfd9d 100644 --- a/src/cli/runner.ts +++ b/src/cli/runner.ts @@ -28,6 +28,7 @@ import { handleApprovalCommand } from "./commands/approval.js"; import { handleContextCommand } from "./commands/context.js"; import { handleKeysCommand } from "./commands/keys.js"; import { handleStoreCommand } from "./commands/store.js"; +import { handleFeeTypeCommand } from "./commands/feetype.js"; import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js"; const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]); @@ -193,6 +194,14 @@ async function dispatchCli( case "archive": case "archives": return await handleDimensionCommand(parsed, runtime); + case "feetype": + case "feetypes": + case "fee-type": + case "fee-types": + case "expense-type": + case "expense-types": + case "costtype": + return await handleFeeTypeCommand(parsed, runtime); case "role": case "roles": return await handleRoleCommand(parsed, runtime); diff --git a/src/core/embedded-skill.test.ts b/src/core/embedded-skill.test.ts index 1c2e6da..14b743e 100644 --- a/src/core/embedded-skill.test.ts +++ b/src/core/embedded-skill.test.ts @@ -30,6 +30,8 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => { expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toBeDefined(); expect(EMBEDDED_SKILL_FILES["references/approval.md"]).toContain("hose-aipro"); + expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toBeDefined(); + expect(EMBEDDED_SKILL_FILES["references/feetype.md"]).toContain("feetype"); }); test("installSkillFiles 递归保留层级结构并落盘到目标目录", () => { @@ -37,13 +39,14 @@ describe("embedded-skill - 多文件内嵌 Skill 体系", () => { try { const res = installSkillFiles(tmp); expect(res.targetDir).toBe(tmp); - expect(res.files.length).toBe(12); + expect(res.files.length).toBe(13); 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", "approval.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", "feetype.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); diff --git a/src/core/embedded-skill.ts b/src/core/embedded-skill.ts index e2b420d..260dc74 100644 --- a/src/core/embedded-skill.ts +++ b/src/core/embedded-skill.ts @@ -14,6 +14,7 @@ import refMessage from "../../skills/hose-use/references/message.md" with { type import refDimension from "../../skills/hose-use/references/dimension.md" with { type: "text" }; import refRole from "../../skills/hose-use/references/role.md" with { type: "text" }; import refApproval from "../../skills/hose-use/references/approval.md" with { type: "text" }; +import refFeeType from "../../skills/hose-use/references/feetype.md" with { type: "text" }; export const EMBEDDED_SKILL_FILES: Record = { "SKILL.md": skillMain, @@ -21,6 +22,7 @@ export const EMBEDDED_SKILL_FILES: Record = { "references/auth.md": refAuth, "references/approval.md": refApproval, "references/bill.md": refBill, + "references/feetype.md": refFeeType, "references/contact.md": refContact, "references/task.md": refTask, "references/message.md": refMessage, diff --git a/src/core/errors.ts b/src/core/errors.ts index 6aa4b59..bc13e69 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -20,3 +20,10 @@ export class AuthenticationError extends EkbError { super(message, "AUTH_FAILED", 401); } } + +export class BusinessError extends EkbError { + constructor(message: string, code = "BUSINESS_ERROR", status = 400) { + super(message, code, status); + this.name = "BusinessError"; + } +} diff --git a/src/domains/README.domains.md b/src/domains/README.domains.md index 64b416b..3a8a87b 100644 --- a/src/domains/README.domains.md +++ b/src/domains/README.domains.md @@ -10,6 +10,7 @@ | `datalink/` | 自建应用下的业务对象、字段、记录、权限与导入状态 | [README.datalink.md](./datalink/README.datalink.md) | | `bill/` | 费控单据、报销单、发票与 DataLink 实体字典 | [README.bill.md](./bill/README.bill.md) | | `store/` | 企业应用中心/应用商店与 OpenAPI 密钥凭证 | [README.store.md](./store/README.store.md) | +| `feetype/` | 企业费用类型全生命周期管理与字段规格配置 | [README.feetype.md](./feetype/README.feetype.md) | ## 分层规则 diff --git a/src/domains/feetype/README.feetype.md b/src/domains/feetype/README.feetype.md new file mode 100644 index 0000000..25b1d7c --- /dev/null +++ b/src/domains/feetype/README.feetype.md @@ -0,0 +1,68 @@ +# FeeType (费用类型) 域说明 + +费用类型域负责合思/易快报企业费用类型的全生命周期管理,涵盖: +- 费用类型树与平铺目录查询(活跃 / 包含停用) +- 费用类型增删查改(新建、属性修改、软停用、级联启用、移动层级) +- 费用类型表单字段规格解析(报账字段与申请字段元数据) + +## 架构职责 + +```text +CLI (feetype.ts) / MCP (feetypeTools in server.ts) + │ + ▼ +domains/feetype/tools.ts (业务编排:树展开、路径计算、字段规格继承、增删查改封装) + │ + ▼ +domains/feetype/api.ts (HTTP 传输层:直连 /api/v1/form/feeTypes 与 /api/form/v2/specifications) + │ + ▼ +core/auth/ekb.ts (企业身份认证与凭证管理) +``` + +## 接口路由映射 + +| 操作 | HTTP 方法与路径 | 说明 | +|---|---|---| +| 获取活跃树 | `GET /api/v1/form/feeTypes/tree/active` | 获取用户端可见的活跃费用类型树 | +| 获取全量树 | `GET /api/v1/form/feeTypes/tree` | 包含已停用的全量费用类型树 | +| 获取单项详情 | `GET /api/v1/form/feeTypes/$id` | 精准获取持久化配置 | +| 获取表单规格 | `GET /api/form/v2/specifications/feeType/[id]` | 获取报账与申请字段定义 | +| 获取默认模板 | `GET /api/form/v2/specifications/default/$type` | 获取 expense / requisition 预置字段 | +| 新建费用类型 | `POST /api/v1/form/feeTypes` | 批量/单个创建,支持字段规则继承 | +| 更新费用类型 | `PUT /api/v1/form/feeTypes/$id` | 更新名称、编码、英文名、图标、颜色 | +| 停用费用类型 | `PUT /api/v1/form/feeTypes/[ids]/disable` | 软删除停用 | +| 启用费用类型 | `PUT /api/v1/form/feeTypes/$id/restore` | 重新启用(可级联) | +| 移动父级节点 | `PUT /api/v1/form/feeTypes/[ids]/parent` | 调整层级关系 | + +## CLI 命令速查 + +```bash +# 查看费用类型树 +hose-use feetype list +hose-use feetype list --all +hose-use feetype list --keyword="差旅" +hose-use feetype list --flat + +# 查看单个费用类型详情 +hose-use feetype get 交通费 +hose-use feetype get 交通费 --specs + +# 创建费用类型 +hose-use feetype create --name="办公杂费" +hose-use feetype create --name="市内打车" --parent="交通费" + +# 修改费用类型 +hose-use feetype update 市内打车 --desc="滴滴企业版" + +# 停用与启用 +hose-use feetype disable 市内打车 +hose-use feetype enable 市内打车 + +# 移动层级 +hose-use feetype move 市内打车 --parent="差旅费用" +hose-use feetype move 市内打车 --parent=root + +# 查看表单字段配置 +hose-use feetype fields 交通费 +``` diff --git a/src/domains/feetype/api.ts b/src/domains/feetype/api.ts new file mode 100644 index 0000000..3d4ee99 --- /dev/null +++ b/src/domains/feetype/api.ts @@ -0,0 +1,294 @@ +import type { KyInstance } from "ky"; +import { + FeeTypeDetailResponseSchema, + FeeTypeSpecificationResponseSchema, + FeeTypeTreeResponseSchema, + FeeTypeCreateResultSchema, + DefaultSpecResponseSchema, + FeeTypeNode, + FeeTypeItem, + FeeTypeSpecificationItem, + FeeTypeCreateResult, + FeeTypeComponent, +} from "./types.js"; +import { BusinessError } from "../../core/errors.js"; + +/** + * 获取活跃费用类型树 (GET api/v1/form/feeTypes/tree/active) + */ +export async function getActiveFeeTypeTree( + client: KyInstance, + corpId: string +): Promise { + try { + const raw = await client + .get("api/v1/form/feeTypes/tree/active", { + searchParams: { corpId }, + }) + .json(); + const parsed = FeeTypeTreeResponseSchema.safeParse(raw); + if (parsed.success) return parsed.data.items; + if (Array.isArray(raw)) { + return raw.filter((item): item is FeeTypeNode => Boolean(item && typeof item === "object")); + } + return []; + } catch (err: any) { + throw new BusinessError( + `获取活跃费用类型树失败: ${err.message || String(err)}`, + "GET_ACTIVE_FEETYPE_FAILED" + ); + } +} + +/** + * 获取全量费用类型树 (含已停用) (GET api/v1/form/feeTypes/tree) + */ +export async function getFullFeeTypeTree( + client: KyInstance, + corpId: string +): Promise { + try { + const raw = await client + .get("api/v1/form/feeTypes/tree", { + searchParams: { + corpId, + join: "id,feetypeTemplate,/form/v2/specifications/feeType", + join$2: "children.id,feetypeTemplate,/form/v2/specifications/feeType", + }, + }) + .json(); + const parsed = FeeTypeTreeResponseSchema.safeParse(raw); + if (parsed.success) return parsed.data.items; + if (Array.isArray(raw)) { + return raw.filter((item): item is FeeTypeNode => Boolean(item && typeof item === "object")); + } + return []; + } catch (err: any) { + throw new BusinessError( + `获取全量费用类型树失败: ${err.message || String(err)}`, + "GET_FULL_FEETYPE_FAILED" + ); + } +} + +/** + * 获取单条费用类型详情 (GET api/v1/form/feeTypes/$id) + */ +export async function getFeeTypeById( + client: KyInstance, + corpId: string, + id: string +): Promise { + try { + const raw = await client + .get(`api/v1/form/feeTypes/$${id}`, { + searchParams: { corpId }, + }) + .json(); + const parsed = FeeTypeDetailResponseSchema.safeParse(raw); + if (parsed.success) return parsed.data.value; + if (raw && typeof raw === "object" && "value" in raw) { + return (raw as any).value as FeeTypeItem; + } + return raw as FeeTypeItem; + } catch (err: any) { + throw new BusinessError( + `获取费用类型 [${id}] 详情失败: ${err.message || String(err)}`, + "GET_FEETYPE_DETAIL_FAILED" + ); + } +} + +/** + * 获取费用类型的表单字段规格定义 (GET api/form/v2/specifications/feeType/[id]) + */ +export async function getFeeTypeSpecification( + client: KyInstance, + corpId: string, + id: string +): Promise { + try { + const raw = await client + .get(`api/form/v2/specifications/feeType/[${id}]`, { + searchParams: { id, corpId }, + }) + .json(); + const parsed = FeeTypeSpecificationResponseSchema.safeParse(raw); + if (parsed.success && parsed.data.items.length > 0) { + return parsed.data.items[0]; + } + if (raw && typeof raw === "object" && Array.isArray((raw as any).items)) { + return (raw as any).items[0]; + } + return undefined; + } catch (err: any) { + throw new BusinessError( + `获取费用类型 [${id}] 字段规格失败: ${err.message || String(err)}`, + "GET_FEETYPE_SPEC_FAILED" + ); + } +} + +/** + * 获取默认报账字段模板 (GET api/form/v2/specifications/default/$feeType_expense) + */ +export async function getDefaultExpenseSpec( + client: KyInstance, + corpId: string +): Promise { + try { + const raw = await client + .get("api/form/v2/specifications/default/$feeType_expense", { + searchParams: { type: "feeType_expense", corpId }, + }) + .json(); + const parsed = DefaultSpecResponseSchema.safeParse(raw); + return parsed.success ? (parsed.data.components ?? []) : []; + } catch { + return []; + } +} + +/** + * 获取默认申请字段模板 (GET api/form/v2/specifications/default/$feeType_requisition) + */ +export async function getDefaultRequisitionSpec( + client: KyInstance, + corpId: string +): Promise { + try { + const raw = await client + .get("api/form/v2/specifications/default/$feeType_requisition", { + searchParams: { type: "feeType_requisition", corpId }, + }) + .json(); + const parsed = DefaultSpecResponseSchema.safeParse(raw); + return parsed.success ? (parsed.data.components ?? []) : []; + } catch { + return []; + } +} + +/** + * 批量创建费用类型 (POST api/v1/form/feeTypes) + */ +export async function createFeeTypes( + client: KyInstance, + corpId: string, + items: Record[] +): Promise { + try { + const raw = await client + .post("api/v1/form/feeTypes", { + searchParams: { corpId }, + json: { data: items }, + }) + .json(); + const parsed = FeeTypeCreateResultSchema.safeParse(raw); + if (parsed.success) return parsed.data; + return raw as FeeTypeCreateResult; + } catch (err: any) { + throw new BusinessError( + `创建费用类型失败: ${err.message || String(err)}`, + "CREATE_FEETYPE_FAILED" + ); + } +} + +/** + * 更新费用类型基本信息 (PUT api/v1/form/feeTypes/$id) + */ +export async function updateFeeType( + client: KyInstance, + corpId: string, + id: string, + body: Record +): Promise { + try { + const raw = await client + .put(`api/v1/form/feeTypes/$${id}`, { + searchParams: { corpId }, + json: body, + }) + .json(); + const parsed = FeeTypeDetailResponseSchema.safeParse(raw); + if (parsed.success) return parsed.data.value; + if (raw && typeof raw === "object" && "value" in raw) { + return (raw as any).value as FeeTypeItem; + } + return raw as FeeTypeItem; + } catch (err: any) { + throw new BusinessError( + `更新费用类型 [${id}] 失败: ${err.message || String(err)}`, + "UPDATE_FEETYPE_FAILED" + ); + } +} + +/** + * 批量停用费用类型 (PUT api/v1/form/feeTypes/[ids]/disable) + */ +export async function disableFeeTypes( + client: KyInstance, + corpId: string, + ids: string[] +): Promise { + try { + const idsParam = `[${ids.join(",")}]`; + const res = await client.put(`api/v1/form/feeTypes/${idsParam}/disable`, { + searchParams: { corpId }, + }); + return res.status === 200 || res.status === 204; + } catch (err: any) { + throw new BusinessError( + `停用费用类型 [${ids.join(", ")}] 失败: ${err.message || String(err)}`, + "DISABLE_FEETYPE_FAILED" + ); + } +} + +/** + * 启用已停用的费用类型 (PUT api/v1/form/feeTypes/$id/restore) + */ +export async function restoreFeeType( + client: KyInstance, + corpId: string, + id: string, + recursive = true +): Promise { + try { + const res = await client.put(`api/v1/form/feeTypes/$${id}/restore`, { + searchParams: { corpId, recursive: String(recursive) }, + }); + return res.status === 200 || res.status === 204; + } catch (err: any) { + throw new BusinessError( + `启用费用类型 [${id}] 失败: ${err.message || String(err)}`, + "RESTORE_FEETYPE_FAILED" + ); + } +} + +/** + * 移动费用类型父级 (PUT api/v1/form/feeTypes/[ids]/parent) + */ +export async function moveFeeTypes( + client: KyInstance, + corpId: string, + ids: string[], + parentId: string +): Promise { + try { + const idsParam = `[${ids.join(",")}]`; + const res = await client.put(`api/v1/form/feeTypes/${idsParam}/parent`, { + searchParams: { corpId }, + json: { parentId: parentId || "" }, + }); + return res.status === 200 || res.status === 204; + } catch (err: any) { + throw new BusinessError( + `移动费用类型 [${ids.join(", ")}] 失败: ${err.message || String(err)}`, + "MOVE_FEETYPE_FAILED" + ); + } +} diff --git a/src/domains/feetype/feetype.test.ts b/src/domains/feetype/feetype.test.ts new file mode 100644 index 0000000..6af0416 --- /dev/null +++ b/src/domains/feetype/feetype.test.ts @@ -0,0 +1,74 @@ +import { describe, it, expect } from "bun:test"; +import { flattenFeeTypeTree } from "./tools.js"; +import { FeeTypeNode } from "./types.js"; + +describe("domains/feetype > tools & helpers", () => { + const sampleTree = [ + { + feeType: { + id: "node_1", + name: "差旅费", + code: "COST01", + active: true, + parentId: "", + }, + children: [ + { + feeType: { + id: "node_1_1", + name: "机票", + code: "COST01_1", + active: true, + parentId: "node_1", + }, + children: [ + { + feeType: { + id: "node_1_1_1", + name: "退改签", + code: "COST01_1_1", + active: true, + parentId: "node_1_1", + }, + children: [], + }, + ], + }, + ], + }, + { + feeType: { + id: "node_2", + name: "办公费", + code: "COST02", + active: false, + parentId: "", + }, + children: [], + }, + ] as unknown as FeeTypeNode[]; + + it("flattenFeeTypeTree 正确递归展开全路径与父级关系", () => { + const flat = flattenFeeTypeTree(sampleTree); + expect(flat.length).toBe(4); + + expect(flat[0].name).toBe("差旅费"); + expect(flat[0].path).toBe("差旅费"); + expect(flat[0].childrenCount).toBe(1); + + expect(flat[1].name).toBe("机票"); + expect(flat[1].path).toBe("差旅费 / 机票"); + expect(flat[1].parentName).toBe("差旅费"); + expect(flat[1].childrenCount).toBe(1); + + expect(flat[2].name).toBe("退改签"); + expect(flat[2].path).toBe("差旅费 / 机票 / 退改签"); + expect(flat[2].parentName).toBe("机票"); + expect(flat[2].childrenCount).toBe(0); + + expect(flat[3].name).toBe("办公费"); + expect(flat[3].path).toBe("办公费"); + expect(flat[3].parentName).toBe(""); + expect(flat[3].active).toBe(false); + }); +}); diff --git a/src/domains/feetype/tools.ts b/src/domains/feetype/tools.ts new file mode 100644 index 0000000..6684f05 --- /dev/null +++ b/src/domains/feetype/tools.ts @@ -0,0 +1,548 @@ +import type { KyInstance } from "ky"; +import { z } from "zod"; +import { + FeeTypeComponent, + FeeTypeCreateInput, + FeeTypeItem, + FeeTypeNode, + FeeTypeQueryOptions, + FeeTypeUpdateInput, + FeeTypeView, +} from "./types.js"; +import { + createFeeTypes, + disableFeeTypes, + getActiveFeeTypeTree, + getDefaultExpenseSpec, + getDefaultRequisitionSpec, + getFeeTypeById, + getFeeTypeSpecification, + getFullFeeTypeTree, + moveFeeTypes, + restoreFeeType, + updateFeeType, +} from "./api.js"; +import { BusinessError } from "../../core/errors.js"; + +// ── 树遍历与平铺辅助 ───────────────────────────────────────────────────────── + +export interface FlatFeeTypeItem extends FeeTypeItem { + path: string; + parentName: string; + childrenCount: number; +} + +export function flattenFeeTypeTree( + nodes: FeeTypeNode[], + parentPath = "", + parentName = "" +): FlatFeeTypeItem[] { + const result: FlatFeeTypeItem[] = []; + + for (const node of nodes) { + const item = node.feeType; + if (!item || !item.id) continue; + + const currentPath = parentPath ? `${parentPath} / ${item.name}` : item.name; + const children = Array.isArray(node.children) ? node.children : []; + + result.push({ + ...item, + path: currentPath, + parentName, + childrenCount: children.length, + }); + + if (children.length > 0) { + result.push(...flattenFeeTypeTree(children, currentPath, item.name)); + } + } + + return result; +} + +/** + * 清理组件字段 (参照易快报前端规范:删除内部状态与只读引用) + */ +function cleanComponents(list: FeeTypeComponent[]): Record[] { + return list.map((item) => { + const copy = { ...item } as Record; + delete copy.id; + delete copy.dataType; + delete copy.showValue; + delete copy.status; + delete copy.entityInfo; + delete copy.isLinkageFilter; + return copy; + }); +} + +// ── 核心业务编排 ───────────────────────────────────────────────────────────── + +/** + * 模糊或精准解析单个费用类型节点 (支持按 ID, Code, Name 查找) + */ +export async function findFeeType( + client: KyInstance, + corpId: string, + target: string, + options: { all?: boolean } = {} +): Promise { + const clean = target.trim(); + if (!clean) return undefined; + + const tree = options.all + ? await getFullFeeTypeTree(client, corpId) + : await getActiveFeeTypeTree(client, corpId); + const flat = flattenFeeTypeTree(tree); + + // 1. 精确 ID 匹配 + const byId = flat.find((item) => item.id === clean); + if (byId) return byId; + + // 2. 精确 Code 匹配 (不区分大小写) + const byCode = flat.find((item) => item.code.toLowerCase() === clean.toLowerCase()); + if (byCode) return byCode; + + // 3. 精确 Name 匹配 + const byName = flat.find((item) => item.name === clean); + if (byName) return byName; + + // 4. 包含匹配 (Name / Spell / EnName) + const byPartial = flat.find( + (item) => + item.name.includes(clean) || + (item.enName && item.enName.toLowerCase().includes(clean.toLowerCase())) + ); + return byPartial; +} + +/** + * 查询费用类型列表 (树形或平铺) + */ +export async function listFeeTypes( + client: KyInstance, + corpId: string, + options: FeeTypeQueryOptions = {} +): Promise<{ + total: number; + items: FlatFeeTypeItem[] | FeeTypeNode[]; + rawTree: FeeTypeNode[]; +}> { + const rawTree = options.all + ? await getFullFeeTypeTree(client, corpId) + : await getActiveFeeTypeTree(client, corpId); + + let flat = flattenFeeTypeTree(rawTree); + + if (options.keyword?.trim()) { + const kw = options.keyword.trim().toLowerCase(); + flat = flat.filter( + (item) => + item.name.toLowerCase().includes(kw) || + item.code.toLowerCase().includes(kw) || + (item.enName && item.enName.toLowerCase().includes(kw)) || + item.path.toLowerCase().includes(kw) + ); + } + + return { + total: flat.length, + items: options.flat ? flat : (options.keyword ? flat : rawTree), + rawTree, + }; +} + +/** + * 获取费用类型详细信息 (含字段规格) + */ +export async function getFeeTypeDetail( + client: KyInstance, + corpId: string, + target: string, + options: { includeSpecs?: boolean } = {} +): Promise<{ + feeType: FlatFeeTypeItem; + specifications?: { + expenseComponents: FeeTypeComponent[]; + requisitionComponents: FeeTypeComponent[]; + }; +}> { + const found = await findFeeType(client, corpId, target, { all: true }); + if (!found) { + throw new BusinessError( + `未找到匹配的费用类型: "${target}" (可尝试按编码或全称检索)`, + "FEETYPE_NOT_FOUND" + ); + } + + // 获取最新的精确持久化属性 + const fresh = await getFeeTypeById(client, corpId, found.id); + const resultItem: FlatFeeTypeItem = { + ...fresh, + path: found.path, + parentName: found.parentName, + childrenCount: found.childrenCount, + }; + + if (!options.includeSpecs) { + return { feeType: resultItem }; + } + + const spec = await getFeeTypeSpecification(client, corpId, found.id); + return { + feeType: resultItem, + specifications: { + expenseComponents: spec?.expenseComponents ?? [], + requisitionComponents: spec?.requisitionComponents ?? [], + }, + }; +} + +/** + * 创建费用类型 (支持自动/指定编码、父级继承与字段规格适配) + */ +export async function createFeeType( + client: KyInstance, + corpId: string, + input: FeeTypeCreateInput +): Promise { + const name = input.name.trim(); + if (!name) { + throw new BusinessError("费用类型名称不能为空", "INVALID_FEETYPE_NAME"); + } + + let resolvedParentId = ""; + let inheritedExpenseComponents: Record[] = []; + let inheritedRequisitionComponents: Record[] = []; + + if (input.parentId?.trim()) { + const parent = await findFeeType(client, corpId, input.parentId.trim(), { all: true }); + if (!parent) { + throw new BusinessError( + `指定的父级费用类型 "${input.parentId}" 不存在`, + "PARENT_FEETYPE_NOT_FOUND" + ); + } + resolvedParentId = parent.id; + // 继承父级费用类型的字段设置 + const parentSpec = await getFeeTypeSpecification(client, corpId, parent.id); + if (parentSpec) { + inheritedExpenseComponents = cleanComponents(parentSpec.expenseComponents ?? []); + inheritedRequisitionComponents = cleanComponents(parentSpec.requisitionComponents ?? []); + } + } + + // 若无父级或父级无规格,加载系统预置默认字段规格 + if (!inheritedExpenseComponents.length) { + const defaultExp = await getDefaultExpenseSpec(client, corpId); + inheritedExpenseComponents = cleanComponents(defaultExp); + } + if (!inheritedRequisitionComponents.length) { + const defaultReq = await getDefaultRequisitionSpec(client, corpId); + inheritedRequisitionComponents = cleanComponents(defaultReq); + } + + // 确定唯一编码 + let code = input.code?.trim(); + if (!code) { + const allTree = await getFullFeeTypeTree(client, corpId); + const flat = flattenFeeTypeTree(allTree); + const existingCodes = new Set(flat.map((item) => item.code.toUpperCase())); + let seq = flat.length + 1; + code = `COST${seq}`; + while (existingCodes.has(code)) { + seq++; + code = `COST${seq}`; + } + } + + const payloadItem = { + type: "ALL", + name, + enName: input.enName?.trim() || "", + code, + parentId: resolvedParentId, + description: input.description?.trim() || "", + color: input.color || "#90caf9", + icon: input.icon || "https://images.ekuaibao.com/feetype/sf_100.png", + expenseComponents: input.expenseComponents?.length + ? input.expenseComponents + : inheritedExpenseComponents, + requisitionComponents: input.requisitionComponents?.length + ? input.requisitionComponents + : inheritedRequisitionComponents, + }; + + const createRes = await createFeeTypes(client, corpId, [payloadItem]); + if (createRes.value?.errorMsgs?.length) { + throw new BusinessError( + `创建费用类型失败: ${createRes.value.errorMsgs.join("; ")}`, + "CREATE_FEETYPE_REJECTED" + ); + } + + const newId = createRes.value?.ids?.[0]; + if (!newId) { + throw new BusinessError("创建接口未返回新增的费用类型 ID", "CREATE_FEETYPE_NO_ID"); + } + + const created = await getFeeTypeDetail(client, corpId, newId); + return created.feeType; +} + +/** + * 修改费用类型属性 (名称、编码、英文名、图标、颜色、描述) + */ +export async function updateFeeTypeInfo( + client: KyInstance, + corpId: string, + target: string, + patch: FeeTypeUpdateInput +): Promise { + const found = await findFeeType(client, corpId, target, { all: true }); + if (!found) { + throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND"); + } + + const current = await getFeeTypeById(client, corpId, found.id); + const updatedBody: Record = { + id: found.id, + type: "FEETYPE", + name: patch.name !== undefined ? patch.name.trim() : current.name, + code: patch.code !== undefined ? patch.code.trim() : current.code, + enName: patch.enName !== undefined ? patch.enName.trim() : (current.enName || ""), + description: patch.description !== undefined ? patch.description.trim() : (current.description || ""), + color: patch.color !== undefined ? patch.color.trim() : (current.color || "#90caf9"), + icon: patch.icon !== undefined ? patch.icon.trim() : (current.icon || "https://images.ekuaibao.com/feetype/sf_100.png"), + }; + + await updateFeeType(client, corpId, found.id, updatedBody); + const fresh = await getFeeTypeDetail(client, corpId, found.id); + return fresh.feeType; +} + +/** + * 停用费用类型 (软删除) + */ +export async function disableFeeTypeItem( + client: KyInstance, + corpId: string, + target: string +): Promise<{ success: boolean; item: FlatFeeTypeItem }> { + const found = await findFeeType(client, corpId, target, { all: true }); + if (!found) { + throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND"); + } + + if (!found.active) { + return { success: true, item: found }; + } + + const ok = await disableFeeTypes(client, corpId, [found.id]); + const fresh = await getFeeTypeDetail(client, corpId, found.id); + return { success: ok, item: fresh.feeType }; +} + +/** + * 启用费用类型 (可级联恢复) + */ +export async function enableFeeTypeItem( + client: KyInstance, + corpId: string, + target: string, + options: { recursive?: boolean } = { recursive: true } +): Promise<{ success: boolean; item: FlatFeeTypeItem }> { + const found = await findFeeType(client, corpId, target, { all: true }); + if (!found) { + throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND"); + } + + if (found.active) { + return { success: true, item: found }; + } + + const ok = await restoreFeeType(client, corpId, found.id, options.recursive ?? true); + const fresh = await getFeeTypeDetail(client, corpId, found.id); + return { success: ok, item: fresh.feeType }; +} + +/** + * 移动费用类型父级节点 + */ +export async function moveFeeTypeItem( + client: KyInstance, + corpId: string, + target: string, + parentTarget?: string +): Promise<{ success: boolean; item: FlatFeeTypeItem; parentName: string }> { + const found = await findFeeType(client, corpId, target, { all: true }); + if (!found) { + throw new BusinessError(`未找到费用类型: "${target}"`, "FEETYPE_NOT_FOUND"); + } + + let newParentId = ""; + let newParentName = "根节点 (顶级)"; + + if (parentTarget && parentTarget !== "root" && parentTarget !== "0") { + const parent = await findFeeType(client, corpId, parentTarget, { all: true }); + if (!parent) { + throw new BusinessError( + `目标父级费用类型 "${parentTarget}" 不存在`, + "PARENT_FEETYPE_NOT_FOUND" + ); + } + if (parent.id === found.id) { + throw new BusinessError("不能将费用类型移动到其自身之下", "INVALID_MOVE_TARGET"); + } + newParentId = parent.id; + newParentName = parent.name; + } + + const ok = await moveFeeTypes(client, corpId, [found.id], newParentId); + const fresh = await getFeeTypeDetail(client, corpId, found.id); + return { success: ok, item: fresh.feeType, parentName: newParentName }; +} + +/** + * 获取费用类型的表单字段明细清单 (报账与申请字段) + */ +export async function getFeeTypeFieldsList( + client: KyInstance, + corpId: string, + target: string +): Promise<{ + feeType: FlatFeeTypeItem; + expenseFields: { + field: string; + label: string; + type: string; + required: boolean; + editable: boolean; + hidden: boolean; + }[]; + requisitionFields: { + field: string; + label: string; + type: string; + required: boolean; + editable: boolean; + hidden: boolean; + }[]; +}> { + const detail = await getFeeTypeDetail(client, corpId, target, { includeSpecs: true }); + + const mapComponent = (c: FeeTypeComponent) => ({ + field: c.field || "-", + label: c.cnLabel || c.label || "-", + type: c.type || "text", + required: !c.optional, + editable: c.editable !== false, + hidden: Boolean(c.hide), + }); + + return { + feeType: detail.feeType, + expenseFields: (detail.specifications?.expenseComponents ?? []).map(mapComponent), + requisitionFields: (detail.specifications?.requisitionComponents ?? []).map(mapComponent), + }; +} + +// ── MCP Tool Definitions ───────────────────────────────────────────────────── + +export const feetypeTools = [ + { + name: "feetype_list", + description: "查询企业费用类型树或平铺列表 (可按关键词筛选、包含已停用)", + parameters: z.object({ + corpId: z.string().describe("企业 ID"), + keyword: z.string().optional().describe("搜索关键词 (名称/编码/全路径)"), + all: z.boolean().optional().default(false).describe("是否包含已停用的费用类型"), + flat: z.boolean().optional().default(false).describe("是否以平铺列表格式返回"), + }), + handler: async (client: KyInstance, args: any) => { + return listFeeTypes(client, args.corpId, { + keyword: args.keyword, + all: args.all, + flat: args.flat, + }); + }, + }, + { + name: "feetype_get", + description: "获取单个费用类型的详细配置与字段规格", + parameters: z.object({ + corpId: z.string().describe("企业 ID"), + target: z.string().describe("费用类型 ID、编码或名称"), + includeSpecs: z.boolean().optional().default(false).describe("是否包含报账与申请字段规格定义"), + }), + handler: async (client: KyInstance, args: any) => { + return getFeeTypeDetail(client, args.corpId, args.target, { + includeSpecs: args.includeSpecs, + }); + }, + }, + { + name: "feetype_create", + description: "新建费用类型 (支持指定父级节点、编码自增与继承字段规则)", + parameters: z.object({ + corpId: z.string().describe("企业 ID"), + name: z.string().describe("费用类型名称"), + code: z.string().optional().describe("费用编码 (不提供则系统自增生成)"), + parentId: z.string().optional().describe("父级费用类型 ID、编码或名称 (不提供则建为顶级)"), + enName: z.string().optional().describe("英文名称"), + description: z.string().optional().describe("描述信息"), + color: z.string().optional().describe("标识颜色 (如 #90caf9)"), + }), + handler: async (client: KyInstance, args: any) => { + return createFeeType(client, args.corpId, args); + }, + }, + { + name: "feetype_update", + description: "修改费用类型属性 (名称、编码、英文名、颜色、图标或描述)", + parameters: z.object({ + corpId: z.string().describe("企业 ID"), + target: z.string().describe("费用类型 ID、编码或名称"), + name: z.string().optional().describe("新名称"), + code: z.string().optional().describe("新编码"), + enName: z.string().optional().describe("新英文名"), + description: z.string().optional().describe("新描述"), + color: z.string().optional().describe("新颜色"), + }), + handler: async (client: KyInstance, args: any) => { + return updateFeeTypeInfo(client, args.corpId, args.target, args); + }, + }, + { + name: "feetype_toggle", + description: "停用或启用费用类型", + parameters: z.object({ + corpId: z.string().describe("企业 ID"), + target: z.string().describe("费用类型 ID、编码或名称"), + action: z.enum(["disable", "enable"]).describe("执行动作: disable 停用, enable 启用"), + recursive: z.boolean().optional().default(true).describe("启用时是否递归启用子节点"), + }), + handler: async (client: KyInstance, args: any) => { + if (args.action === "disable") { + return disableFeeTypeItem(client, args.corpId, args.target); + } else { + return enableFeeTypeItem(client, args.corpId, args.target, { + recursive: args.recursive, + }); + } + }, + }, + { + name: "feetype_move", + description: "移动费用类型至新的父级节点 (传入 root 移至根目录)", + parameters: z.object({ + corpId: z.string().describe("企业 ID"), + target: z.string().describe("待移动的费用类型 ID、编码或名称"), + parent: z.string().describe("目标父级费用类型 ID、编码或名称 (传入 'root' 为移至顶级)"), + }), + handler: async (client: KyInstance, args: any) => { + return moveFeeTypeItem(client, args.corpId, args.target, args.parent); + }, + }, +]; diff --git a/src/domains/feetype/types.ts b/src/domains/feetype/types.ts new file mode 100644 index 0000000..da2e066 --- /dev/null +++ b/src/domains/feetype/types.ts @@ -0,0 +1,169 @@ +import { z } from "zod"; + +// ── 费用类型基础实体 ───────────────────────────────────────────────────────── + +export const FeeTypeItemSchema = z + .object({ + id: z.string(), + name: z.string(), + code: z.string(), + enName: z.string().nullish().default(""), + parentId: z.string().nullish().default(""), + active: z.boolean().default(true), + order: z.number().nullish().default(1000000), + color: z.string().nullish().default("#90caf9"), + icon: z.string().nullish().default(""), + description: z.string().nullish().default(""), + corporationId: z.string().optional(), + expenseSpecificationId: z.string().nullish(), + requisitionSpecificationId: z.string().nullish(), + receiptSpecificationId: z.string().nullish(), + showPoint: z.boolean().nullish().default(false), + createTime: z.number().nullish(), + updateTime: z.number().nullish(), + permissions: z + .array( + z.object({ + name: z.string(), + auth: z.boolean(), + }) + ) + .nullish() + .default([]), + }) + .passthrough(); + +export type FeeTypeItem = z.infer; + +// ── 树节点模型 ───────────────────────────────────────────────────────────── + +export interface FeeTypeNode { + feeType: FeeTypeItem; + children: FeeTypeNode[]; +} + +export const FeeTypeNodeSchema: z.ZodType = z.lazy(() => + z.object({ + feeType: FeeTypeItemSchema, + children: z.array(FeeTypeNodeSchema).default([]), + }) +); + +export const FeeTypeTreeResponseSchema = z.object({ + items: z.array(FeeTypeNodeSchema).default([]), +}); + +export type FeeTypeTreeResponse = z.infer; + +export const FeeTypeDetailResponseSchema = z.object({ + value: FeeTypeItemSchema, +}); + +export type FeeTypeDetailResponse = z.infer; + +export const FeeTypeCreateResultSchema = z.object({ + value: z + .object({ + ids: z.array(z.string()).default([]), + names: z.record(z.string(), z.string()).optional(), + errorMsgs: z.array(z.string()).nullish().default([]), + }) + .default({ ids: [], errorMsgs: [] }), +}); + +export type FeeTypeCreateResult = z.infer; + +// ── 字段配置与规格模型 ─────────────────────────────────────────────────────── + +export const FeeTypeComponentSchema = z + .object({ + field: z.string().optional(), + label: z.string().optional(), + cnLabel: z.string().nullish(), + enLabel: z.string().nullish(), + type: z.string().optional(), + placeholder: z.string().nullish(), + readonly: z.boolean().nullish().default(false), + editable: z.boolean().nullish().default(true), + optional: z.boolean().nullish().default(true), + hide: z.boolean().nullish().default(false), + showInDetails: z.boolean().nullish().default(false), + defaultField: z.boolean().nullish().default(false), + defaultValue: z.record(z.string(), z.any()).nullish(), + }) + .passthrough(); + +export type FeeTypeComponent = z.infer; + +export const FeeTypeSpecificationItemSchema = z + .object({ + id: z.string(), + expenseComponents: z.array(FeeTypeComponentSchema).nullish().default([]), + requisitionComponents: z.array(FeeTypeComponentSchema).nullish().default([]), + receiptComponents: z.array(FeeTypeComponentSchema).nullish().default([]), + expenseRules: z.array(z.any()).nullish().default([]), + requisitionRules: z.array(z.any()).nullish().default([]), + receiptRules: z.array(z.any()).nullish().default([]), + }) + .passthrough(); + +export type FeeTypeSpecificationItem = z.infer; + +export const FeeTypeSpecificationResponseSchema = z.object({ + items: z.array(FeeTypeSpecificationItemSchema).default([]), +}); + +export type FeeTypeSpecificationResponse = z.infer; + +export const DefaultSpecResponseSchema = z + .object({ + components: z.array(FeeTypeComponentSchema).nullish().default([]), + }) + .passthrough(); + +export type DefaultSpecResponse = z.infer; + +// ── 业务输入参数 ──────────────────────────────────────────────────────────── + +export interface FeeTypeCreateInput { + name: string; + code?: string; + enName?: string; + parentId?: string; + description?: string; + color?: string; + icon?: string; + expenseComponents?: Record[]; + requisitionComponents?: Record[]; +} + +export interface FeeTypeUpdateInput { + name?: string; + code?: string; + enName?: string; + description?: string; + color?: string; + icon?: string; + order?: number; +} + +export interface FeeTypeQueryOptions { + all?: boolean; + keyword?: string; + flat?: boolean; +} + +export interface FeeTypeView { + id: string; + name: string; + code: string; + enName: string; + active: boolean; + parentId: string; + parentName?: string; + path: string; + description: string; + color: string; + icon: string; + childrenCount: number; +} diff --git a/src/server.ts b/src/server.ts index a3ee66d..929c9fd 100644 --- a/src/server.ts +++ b/src/server.ts @@ -12,6 +12,7 @@ import { authTools } from "./core/auth/tools.js"; import { platformTools } from "./domains/platform/tools.js"; import { datalinkTools } from "./domains/datalink/tools.js"; import { billTools } from "./domains/bill/tools.js"; +import { feetypeTools } from "./domains/feetype/tools.js"; import { runCli } from "./cli/runner.js"; import { redactSensitiveText } from "./cli/printer.js"; import { VERSION } from "./version.js"; @@ -186,7 +187,7 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean } } ); - const fineGrainedTools = [...authTools, ...platformTools, ...datalinkTools, ...billTools]; + const fineGrainedTools = [...authTools, ...platformTools, ...datalinkTools, ...billTools, ...feetypeTools]; // 注册工具列表 server.setRequestHandler("tools/list", async () => {