From 60866efa2ec9b66bc297df8b355e551568542bc0 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sat, 5 Sep 2026 19:59:15 +0800 Subject: [PATCH] feat(bill): resolve referenced IDs for approval details --- skills/hose-use/SKILL.md | 2 + skills/hose-use/references/bill.md | 11 ++ src/cli/commands/bill.ts | 31 ++++- src/cli/printer.ts | 3 +- src/domains/bill/README.bill.md | 7 +- src/domains/bill/api.ts | 37 +++++- src/domains/bill/bill.test.ts | 39 ++++++- src/domains/bill/tools.ts | 174 ++++++++++++++++++++++++++++- src/domains/bill/types.ts | 23 ++++ 9 files changed, 320 insertions(+), 7 deletions(-) diff --git a/skills/hose-use/SKILL.md b/skills/hose-use/SKILL.md index db8ae23..b6bac2e 100644 --- a/skills/hose-use/SKILL.md +++ b/skills/hose-use/SKILL.md @@ -35,6 +35,7 @@ metadata: | 报销单据检索 / 费用明细下钻 / 中文字典 | `hose bill list`, `hose bill get <单号|ID>` | [references/bill.md](references/bill.md) | | 单据审批历史 / 当前节点 / 后续流程 | `hose bill flow <单号|ID>` | [references/bill.md](references/bill.md) | | 单据风控预警 / 预算状态 / 发票风险 | `hose bill risk <单号|ID>` | [references/bill.md](references/bill.md) | +| 单据引用 ID 二级解析(人员/部门/费用类型) | `hose bill refs <单号|ID>` | [references/bill.md](references/bill.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) | @@ -72,6 +73,7 @@ hose bill list # 查看最新单据与报 hose bill link CL20260901001 # 生成官方 Web 详情直达免密跳转链接 hose bill list --json -o /tmp/bills.json # 导出全量单据报文至本地磁盘 hose bill get n0GMIM0dkQmKbS # 精准查询单据详情 (中文字段映射) +hose bill refs S26000001 # 解析提交人、归属人、部门、法人实体与费用类型 hose bill schema # 查询单据实体元数据字典 # 4. 待办与消息 diff --git a/skills/hose-use/references/bill.md b/skills/hose-use/references/bill.md index 67c070b..15c6f69 100644 --- a/skills/hose-use/references/bill.md +++ b/skills/hose-use/references/bill.md @@ -61,6 +61,17 @@ hose-use bill risk CL20260903001 `bill risk` 聚合审批页“审查”面板的风控预警、信用规则、预算状态与发票风险接口;默认只输出摘要,`--json` 保留结构化原始结果。 +### 单据引用 ID 二级解析 (`bill refs`) + +读取审批详情并联动组织架构、部门树和费用类型目录,将底层 ID 转为姓名、工号、部门全路径或费用类型名称,同时保留原始 ID: + +```bash +hose bill refs S26000001 +hose bill refs S26000001 --json +``` + +JSON 输出包含 `submitter`、`owner`、`department`、`legalEntity`、`feeTypes` 和 `unresolved`。目录在当前进程内按企业缓存 10 分钟,避免对同一企业重复拉取。 + ## 4. 单据实体元数据字典 (`bill schema`) 用于探查当前企业所有单据实体、字段类型与扩展属性定义: diff --git a/src/cli/commands/bill.ts b/src/cli/commands/bill.ts index 4cd23f8..0b3dc66 100644 --- a/src/cli/commands/bill.ts +++ b/src/cli/commands/bill.ts @@ -7,6 +7,7 @@ import { getBillByCodeOrId, getBillFlow, getBillRisk, + getBillReferences, getFieldDictionary, } from "../../domains/bill/tools.js"; @@ -268,6 +269,34 @@ export async function handleBillCommand( return { stdout: output, stderr: "", exitCode: 0 }; } + case "refs": + case "references": + case "resolve": { + const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]); + if (!target) throw new Error("请提供要解析引用的单号或单据 ID: hose bill refs <单号|ID>"); + const report = await getBillReferences(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 }, runtime.outputOptions), stderr: "", exitCode: 0 }; + } + const person = (value: typeof report.submitter) => value ? `${value.name || "未解析"}${value.code ? ` (${value.code})` : ""} [${value.id}]` : "-"; + const output = [ + `====== 单据引用解析 (单号: ${report.billCode || target}) ======`, + `标题: ${report.title || "-"}`, + `提交人: ${person(report.submitter)}`, + `归属人: ${person(report.owner)}`, + `费用承担部门: ${report.department?.path || report.department?.name || "-"}${report.department?.id ? ` [${report.department.id}]` : ""}`, + `法人实体: ${report.legalEntity ? `${report.legalEntity.name || "未解析"}${report.legalEntity.id ? ` [${report.legalEntity.id}]` : ""}` : "-"}`, + `费用类型: ${report.feeTypes.length ? report.feeTypes.map((item) => `${item.name || "未解析"}${item.code ? ` (${item.code})` : ""} [${item.id}]`).join("、") : "-"}`, + report.unresolved.length ? `未解析 ID: ${report.unresolved.join("、")}` : "引用均已解析", + "", + ].join("\n"); + return { stdout: output, stderr: "", exitCode: 0 }; + } + case "link": case "url": { const target = parsed.args[0] || stringOption(parsed.options, ["code", "id", "c"]); @@ -330,6 +359,6 @@ export async function handleBillCommand( } default: - throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号>, flow <单号>, risk <单号>, schema, link <单号>`); + throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号>, refs <单号>, flow <单号>, risk <单号>, schema, link <单号>`); } } diff --git a/src/cli/printer.ts b/src/cli/printer.ts index 76b3f2f..75ddc38 100644 --- a/src/cli/printer.ts +++ b/src/cli/printer.ts @@ -119,7 +119,7 @@ export function printHelp(): string { corps 多企业租户管理 (list, switch, current) config 全局运行模式与路径诊断 (show, paths, mode , set) workflow 工作流管理 (list, get, find, toggle) - bill 单据与费用明细检索 (list, get <单号|ID>, flow <单号|ID>, risk <单号|ID>, schema, link <单号|ID>) + bill 单据与费用明细检索 (list, get <单号|ID>, refs <单号|ID>, flow <单号|ID>, risk <单号|ID>, schema, link <单号|ID>) contact 企业通讯录与人员检索 (list, search <关键词>, get ) task 待办中心与审批任务 (todo, approved, records, submitted, cc) message 消息中心与通知管理 (list, count, read, read-all) @@ -162,6 +162,7 @@ export function printHelp(): string { hose-use bill list # 查看当前企业单据与报销列表 hose-use bill flow S26000001 # 查看单据审批历史与后续节点 hose-use bill risk S26000001 # 查看风控预警、预算与发票风险 + hose-use bill refs S26000001 # 二级解析提交人、部门、法人实体与费用类型引用 hose-use bill link CL20260901001 # 获取单据 Web 详情直达免密跳转链接 hose-use bill list --json -o /tmp/bills.json # 导出单据报文到本地磁盘并防爆 hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情 diff --git a/src/domains/bill/README.bill.md b/src/domains/bill/README.bill.md index 6ee654a..ba9c0cd 100644 --- a/src/domains/bill/README.bill.md +++ b/src/domains/bill/README.bill.md @@ -1,12 +1,12 @@ # Bill 域说明 -本目录负责合思/易快报(ekuaibao)费控单据、报销单、借款单、发票与数据实体元数据字典的检索与格式化。 +本目录负责合思/易快报(ekuaibao)费控单据、报销单、借款单、发票、关联引用与数据实体元数据字典的检索与格式化。 ## 文件结构 ```text src/domains/bill/ -├── api.ts # 传输层:调用 /api/v2/invoice/search, /api/v2/invoice, /api/v2/datalink/entity/search +├── api.ts # 传输层:调用单据、审批详情、组织架构和费用类型目录 API ├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与 MCP tools ├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义 ├── bill.test.ts # 单元测试 @@ -22,3 +22,6 @@ src/domains/bill/ - 根据业务单号(如 `n0GMIM0dkQmKbS`)或单据 ID(如 `ID01TRzg7HMLcb`)查询单据。 3. **DataLink 字段元数据字典 (`getFieldDictionary`)**: - 自动拉取企业全部实体模型定义,将混淆代码字段(如 `E_ae10..._payMoney`)还原为人类友好的中文字段名(如 `报销金额`)。 +4. **关联引用二级解析 (`getBillReferences`)**: + - 通过审批详情、组织架构和费用类型目录批量解析提交人、归属人、费用承担部门与费用类型; + - 保留原始 ID,并在 JSON 中提供 `name`、`code`、部门 `path` 与未解析 ID;目录在进程内按企业缓存 10 分钟。 diff --git a/src/domains/bill/api.ts b/src/domains/bill/api.ts index 498e50e..5ceb099 100644 --- a/src/domains/bill/api.ts +++ b/src/domains/bill/api.ts @@ -17,7 +17,42 @@ function flowLookupSelect(): string { } function flowDetailSelect(): string { - return "flowId(form(code,title,submitDate,submitterId),logs(operatorId,nextOperatorId,`...`),plan(`...`),`...`),`...`"; + return "flowId(form(`...`),logs(operatorId,nextOperatorId,`...`),plan(`...`),`...`),`...`"; +} + +export async function listActiveStaffCatalog( + client: KyInstance, + corpId: string +): Promise[]> { + const response = await client.get("api/v1/organization/staffs/actives", { + searchParams: { start: "0", count: "2999", corpId }, + }); + const json = (await response.json()) as { items?: unknown[] }; + return Array.isArray(json.items) ? json.items.filter((item): item is Record => Boolean(item && typeof item === "object")) : []; +} + +export async function getDepartmentTree( + client: KyInstance, + corpId: string +): Promise[]> { + const response = await client.get("api/v1/organization/departments/tree/actives", { + searchParams: { corpId }, + }); + const json = (await response.json()) as { items?: unknown[] } | unknown[]; + if (Array.isArray(json)) return json.filter((item): item is Record => Boolean(item && typeof item === "object")); + return Array.isArray(json.items) ? json.items.filter((item): item is Record => Boolean(item && typeof item === "object")) : []; +} + +export async function getFeeTypeTree( + client: KyInstance, + corpId: string +): Promise[]> { + const response = await client.get("api/v1/form/feeTypes/tree/active", { + searchParams: { corpId }, + }); + const json = (await response.json()) as { items?: unknown[] } | unknown[]; + if (Array.isArray(json)) return json.filter((item): item is Record => Boolean(item && typeof item === "object")); + return Array.isArray(json.items) ? json.items.filter((item): item is Record => Boolean(item && typeof item === "object")) : []; } export async function getRawBillFlow( diff --git a/src/domains/bill/bill.test.ts b/src/domains/bill/bill.test.ts index d10a7e4..6740e48 100644 --- a/src/domains/bill/bill.test.ts +++ b/src/domains/bill/bill.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "bun:test"; -import { formatSingleBill } from "./tools.js"; +import { formatSingleBill, getBillReferences } from "./tools.js"; import { RawBillItemSchema, EntitySchema } from "./types.js"; describe("Bill Domain", () => { @@ -66,4 +66,41 @@ describe("Bill Domain", () => { expect(formatted.amount).toBe("¥100.00 CNY"); expect(formatted.details["客户等级"]).toBe("VIP客户"); }); + + it("resolves approval references from staff, department and fee type catalogs", async () => { + const responses = [ + { + id: "backlog-1", + state: "APPROVING", + flowId: { + id: "flow-1", + form: { + code: "S26000001", + title: "团建申请", + submitterId: "corp:staff-1", + expenseDepartment: "corp:dept-2", + details: { feeTypeId: "fee-1" }, + }, + }, + }, + ]; + const client = { + post: async () => new Response(JSON.stringify({ items: responses })), + get: async (path: string) => { + if (path.includes("staffs/actives")) { + return new Response(JSON.stringify({ items: [{ id: "corp:staff-1", userId: "staff-1", name: "张三", code: "1001" }] })); + } + if (path.includes("departments/tree")) { + return new Response(JSON.stringify({ items: [{ id: "corp", name: "总公司", children: [{ id: "corp:dept-2", name: "研发部", children: [] }] }] })); + } + return new Response(JSON.stringify({ items: [{ id: "fee-1", name: "差旅费", code: "COST01", children: [] }] })); + }, + } as any; + + const result = await getBillReferences(client, "corp", "S26000001"); + expect(result?.submitter?.name).toBe("张三"); + expect(result?.department?.path).toBe("总公司/研发部"); + expect(result?.feeTypes[0]?.name).toBe("差旅费"); + expect(result?.unresolved).toEqual([]); + }); }); diff --git a/src/domains/bill/tools.ts b/src/domains/bill/tools.ts index 8448bf6..6189627 100644 --- a/src/domains/bill/tools.ts +++ b/src/domains/bill/tools.ts @@ -1,6 +1,15 @@ import { z } from "zod"; import { KyInstance } from "ky"; -import { searchRawBills, getRawBillsByIds, listEntitySchemas, getRawBillFlow, getRawBillRisk } from "./api.js"; +import { + searchRawBills, + getRawBillsByIds, + listEntitySchemas, + getRawBillFlow, + getRawBillRisk, + listActiveStaffCatalog, + getDepartmentTree, + getFeeTypeTree, +} from "./api.js"; import { type RawBillItem, type FormattedBill, @@ -12,6 +21,8 @@ import { type BillFlowTimeline, type BillRiskReport, type BillRiskWarning, + type BillReference, + type BillReferenceReport, } from "./types.js"; import { CorpContext } from "../../core/config/manager.js"; import { createEkbClient } from "../../core/auth/ekb.js"; @@ -68,6 +79,15 @@ const COMMON_FIELD_LABELS: Record = { const schemaCache = new Map; entities: EntityMeta[] }>(); const CACHE_TTL_MS = 10 * 60 * 1000; // 10 分钟缓存 +type ReferenceCatalog = { + timestamp: number; + staff: Map>; + departments: Map; path: string }>; + feeTypes: Map>; +}; + +const referenceCatalogCache = new Map(); + export async function getFieldDictionary( client: KyInstance, corpId: string, @@ -94,6 +114,158 @@ export async function getFieldDictionary( return result; } +function referenceId(value: unknown): string | undefined { + if (typeof value === "string" && value.trim()) return value.trim(); + if (!value || typeof value !== "object") return undefined; + const id = (value as Record).id; + return typeof id === "string" && id.trim() ? id.trim() : undefined; +} + +function referenceObject(value: unknown): Record | undefined { + return value && typeof value === "object" ? value as Record : undefined; +} + +function flattenDepartments(items: Record[], parentPath = "", output = new Map; path: string }>()): Map; path: string }> { + for (const item of items) { + const name = typeof item.name === "string" ? item.name : ""; + const path = name ? (parentPath ? `${parentPath}/${name}` : name) : parentPath; + const id = typeof item.id === "string" ? item.id : undefined; + if (id) output.set(id, { item, path }); + const children = Array.isArray(item.children) + ? item.children.filter((child): child is Record => Boolean(child && typeof child === "object")) + : []; + flattenDepartments(children, path, output); + } + return output; +} + +function flattenFeeTypes(items: Record[], output = new Map>()): Map> { + for (const item of items) { + const feeType = referenceObject(item.feeType) ?? item; + const id = typeof feeType.id === "string" ? feeType.id : undefined; + if (id) output.set(id, feeType); + const children = Array.isArray(item.children) + ? item.children.filter((child): child is Record => Boolean(child && typeof child === "object")) + : []; + flattenFeeTypes(children, output); + } + return output; +} + +async function getReferenceCatalog(client: KyInstance, corpId: string): Promise { + const cached = referenceCatalogCache.get(corpId); + if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) return cached; + const [staffs, departments, feeTypes] = await Promise.all([ + listActiveStaffCatalog(client, corpId), + getDepartmentTree(client, corpId), + getFeeTypeTree(client, corpId), + ]); + const staff = new Map>(); + for (const item of staffs) { + if (typeof item.id === "string") { + staff.set(item.id, item); + const userId = typeof item.userId === "string" ? item.userId : undefined; + if (userId) staff.set(userId, item); + } + } + const result = { + timestamp: Date.now(), + staff, + departments: flattenDepartments(departments), + feeTypes: flattenFeeTypes(feeTypes), + }; + referenceCatalogCache.set(corpId, result); + return result; +} + +function toReference( + value: unknown, + kind: BillReference["kind"], + source: BillReference["source"], + catalog?: Record, + path?: string, +): BillReference | undefined { + const id = referenceId(value); + if (!id) return undefined; + const object = referenceObject(value); + const sourceObject = object ?? catalog; + return { + id, + name: typeof sourceObject?.name === "string" ? sourceObject.name : undefined, + code: typeof sourceObject?.code === "string" ? sourceObject.code : undefined, + path, + kind, + source, + }; +} + +function collectFeeTypeIds(value: unknown, output = new Set()): Set { + if (Array.isArray(value)) { + for (const item of value) collectFeeTypeIds(item, output); + return output; + } + if (!value || typeof value !== "object") return output; + for (const [key, nested] of Object.entries(value as Record)) { + if (key === "feeTypeId" || key.endsWith("_feeTypeId")) { + const id = referenceId(nested); + if (id) output.add(id); + } + collectFeeTypeIds(nested, output); + } + return output; +} + +export async function getBillReferences( + client: KyInstance, + corpId: string, + target: string, +): Promise { + const raw = await getRawBillFlow(client, corpId, target); + if (!raw || !raw.flowId || typeof raw.flowId !== "object") return undefined; + const flow = raw.flowId as Record; + const form = flow.form && typeof flow.form === "object" ? flow.form as Record : {}; + const catalog = await getReferenceCatalog(client, corpId); + const unresolved: string[] = []; + const resolveStaff = (value: unknown, fallbackKind: BillReference["kind"]): BillReference | undefined => { + const id = referenceId(value); + if (!id) return undefined; + const found = catalog.staff.get(id) ?? catalog.staff.get(id.split(":").at(-1) ?? id); + const reference = toReference(value, fallbackKind, found ? "catalog" : "raw", found); + if (!reference?.name) unresolved.push(id); + return reference; + }; + const departmentValue = form.expenseDepartment; + const departmentId = referenceId(departmentValue); + const departmentFound = departmentId ? catalog.departments.get(departmentId) ?? catalog.departments.get(departmentId.split(":").at(-1) ?? departmentId) : undefined; + const department = toReference(departmentValue, "department", departmentFound ? "catalog" : "raw", departmentFound?.item, departmentFound?.path); + if (departmentId && !department?.name) unresolved.push(departmentId); + + const legalEntityValue = form.legalEntity; + const legalEntity = toReference(legalEntityValue, "legalEntity", "joined"); + if (referenceId(legalEntityValue) && !legalEntity?.name) unresolved.push(referenceId(legalEntityValue)!); + + const feeTypes = [...collectFeeTypeIds(form)].map((id) => { + const found = catalog.feeTypes.get(id) ?? catalog.feeTypes.get(id.split(":").at(-1) ?? id); + const reference = toReference(id, "feeType", found ? "catalog" : "raw", found); + if (!reference?.name) unresolved.push(id); + return reference; + }).filter((item): item is BillReference => Boolean(item)); + + return { + target, + billId: typeof raw.id === "string" ? raw.id : undefined, + billCode: typeof form.code === "string" ? form.code : undefined, + title: typeof form.title === "string" ? form.title : undefined, + submitter: resolveStaff(form.submitterId, "staff"), + owner: resolveStaff(form.ownerId, "staff"), + department, + legalEntity, + feeTypes, + unresolved: [...new Set(unresolved)], + raw: { form }, + }; +} + // ── 格式化单据数据 ───────────────────────────────────────────────────────────── export function formatSingleBill( diff --git a/src/domains/bill/types.ts b/src/domains/bill/types.ts index c7a4c9c..55145f7 100644 --- a/src/domains/bill/types.ts +++ b/src/domains/bill/types.ts @@ -156,3 +156,26 @@ export interface BillRiskReport { invoiceWarnings: Record[]; raw: Record; } + +export interface BillReference { + id: string; + name?: string; + code?: string; + path?: string; + kind: "staff" | "department" | "feeType" | "legalEntity" | "unknown"; + source: "joined" | "catalog" | "raw"; +} + +export interface BillReferenceReport { + target: string; + billId?: string; + billCode?: string; + title?: string; + submitter?: BillReference; + owner?: BillReference; + department?: BillReference; + legalEntity?: BillReference; + feeTypes: BillReference[]; + unresolved: string[]; + raw: Record; +}