feat(bill): 引入费控单据与费用明细检索(支持按单号精准查询与 DataLink 字典自动还原)并发布 v0.3.0
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
This commit is contained in:
1 parent
0372698ff9
commit
5cf6c9e014
19 files changed
+1141
-14
No files matched your search
@@ -0,0 +1,192 @@
|
||||
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
|
||||
import { printJson, printTable } from "../printer.js";
|
||||
import { stringOption, numberOption } from "../parser.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
import {
|
||||
searchAndFormatBills,
|
||||
getBillByCodeOrId,
|
||||
getFieldDictionary,
|
||||
} from "../../domains/bill/tools.js";
|
||||
|
||||
export async function handleBillCommand(
|
||||
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);
|
||||
const action = parsed.action?.toLowerCase();
|
||||
const corpId = corp.corpId || corp.id;
|
||||
|
||||
switch (action) {
|
||||
case "list":
|
||||
case "search":
|
||||
case undefined: {
|
||||
const code = stringOption(parsed.options, ["code", "c"]);
|
||||
const keyword = stringOption(parsed.options, ["keyword", "k", "q", "query"]);
|
||||
const stage = stringOption(parsed.options, ["stage"]);
|
||||
const state = stringOption(parsed.options, ["state", "s"]);
|
||||
const count = numberOption(parsed.options, ["count", "limit", "n"], 20);
|
||||
|
||||
const result = await searchAndFormatBills(client, corpId, {
|
||||
code,
|
||||
keyword,
|
||||
stage,
|
||||
state,
|
||||
count,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
total: result.total,
|
||||
returned: result.returned,
|
||||
items: result.items,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "单据编号 (单号)", "单据名称", "阶段", "状态", "金额", "提交时间"];
|
||||
const rows = result.items.map((b, idx) => [
|
||||
idx + 1,
|
||||
b.billCode,
|
||||
b.billName,
|
||||
b.stage || "-",
|
||||
b.state || "-",
|
||||
b.amount || "-",
|
||||
b.submitDate || b.createTime || "-",
|
||||
]);
|
||||
|
||||
const tableOutput = printTable(headers, rows);
|
||||
const title = `====== 单据与费用明细列表 (企业: ${corp.name} | 总数: ${result.total} | 本次返回: ${result.returned}) ======\n`;
|
||||
const tip = `\n提示: 运行 hose-use bill get <单号> 查看表单结构化详情与发票明细\n`;
|
||||
|
||||
return {
|
||||
stdout: title + tableOutput + tip,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
case "get":
|
||||
case "show":
|
||||
case "find": {
|
||||
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
|
||||
if (!target) {
|
||||
throw new Error("请提供要查询的单号或单据 ID: hose-use bill get <单号|ID>");
|
||||
}
|
||||
|
||||
const bills = await getBillByCodeOrId(client, corpId, target);
|
||||
|
||||
if (bills.length === 0) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ found: false, code: target, message: "未找到匹配单据" }),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[NOT FOUND] 在企业 [${corp.name}] 下未找到单号或 ID 为 [${target}] 的单据\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
count: bills.length,
|
||||
bills,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const outputs: string[] = [];
|
||||
for (let i = 0; i < bills.length; i++) {
|
||||
const b = bills[i];
|
||||
outputs.push(`\n====== 单据详情 [${i + 1}/${bills.length}] (单号: ${b.billCode}) ======`);
|
||||
outputs.push(` 单据 ID : ${b.billId}`);
|
||||
outputs.push(` 单据名称 : ${b.billName}`);
|
||||
if (b.title) outputs.push(` 单据标题 : ${b.title}`);
|
||||
if (b.stage) outputs.push(` 业务阶段 : ${b.stage}`);
|
||||
if (b.state) outputs.push(` 审批状态 : ${b.state}`);
|
||||
if (b.amount) outputs.push(` 单据金额 : ${b.amount}`);
|
||||
if (b.submitterId) outputs.push(` 提交人员 : ${b.submitterId}`);
|
||||
if (b.submitDate) outputs.push(` 提交时间 : ${b.submitDate}`);
|
||||
outputs.push(` 创建时间 : ${b.createTime}`);
|
||||
outputs.push(` 更新时间 : ${b.updateTime}`);
|
||||
outputs.push(`\n --- 结构化表单字段明细 ---`);
|
||||
|
||||
const detailEntries = Object.entries(b.details);
|
||||
if (detailEntries.length === 0) {
|
||||
outputs.push(` (无额外字段数据)`);
|
||||
} else {
|
||||
const maxKeyLen = Math.max(...detailEntries.map(([k]) => k.length), 0);
|
||||
for (const [k, v] of detailEntries) {
|
||||
const formattedVal = typeof v === "object" ? JSON.stringify(v) : String(v);
|
||||
outputs.push(` ${k.padEnd(maxKeyLen + 2)}: ${formattedVal}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: outputs.join("\n") + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
case "schema":
|
||||
case "schemas":
|
||||
case "entities": {
|
||||
const { entities } = await getFieldDictionary(client, corpId, true);
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
corpId,
|
||||
corpName: corp.name,
|
||||
totalEntities: entities.length,
|
||||
entities,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const headers = ["#", "实体 ID", "实体名称", "类型", "字段数"];
|
||||
const rows = entities.map((e, idx) => [
|
||||
idx + 1,
|
||||
e.id,
|
||||
e.name || "-",
|
||||
e.type || "-",
|
||||
e.fields.length,
|
||||
]);
|
||||
|
||||
const tableOutput = printTable(headers, rows);
|
||||
const title = `====== 单据实体与数据模型字典 (企业: ${corp.name} | 共 ${entities.length} 个实体) ======\n`;
|
||||
return {
|
||||
stdout: title + tableOutput + "\n",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`未知 bill 子命令: ${action}。支持: list, get <单号>, schema`);
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,7 @@ export function printHelp(): string {
|
||||
corps 多企业租户管理 (list, switch, current)
|
||||
config 全局运行模式 (show, mode <stateful|stateless>, set)
|
||||
workflow 工作流管理 (list, get, find, toggle)
|
||||
bill 单据与费用明细检索 (list, get <单号|ID>, schema)
|
||||
platform 自建应用管理 (list)
|
||||
skill Agent Skill 管理 (install, status, dump)
|
||||
probe 连通性诊断 (probe [corpId])
|
||||
@@ -71,6 +72,8 @@ export function printHelp(): string {
|
||||
hose-use corps switch uzU7pcWfScck00 # 切换工作企业
|
||||
hose-use workflow list # 汇总查看全部工作流
|
||||
hose-use workflow find --task=code-js2 # 搜索包含自定义脚本的工作流
|
||||
hose-use bill list # 查看当前企业单据与报销列表
|
||||
hose-use bill get n0GMIM0dkQmKbS # 根据单号精准查询单据结构化详情
|
||||
hose-use probe # 诊断当前企业鉴权连通性
|
||||
hose-use skill install # 安装 Agent 技能到用户目录
|
||||
hose-use update # 自动检查并升级到最新版本
|
||||
|
||||
@@ -12,6 +12,7 @@ import { handleProbeCommand } from "./commands/probe.js";
|
||||
import { handleMcpCommand } from "./commands/mcp.js";
|
||||
import { handleUpdateCommand } from "./commands/update.js";
|
||||
import { handleOpenApiCommand } from "./commands/openapi.js";
|
||||
import { handleBillCommand } from "./commands/bill.js";
|
||||
import type { CliResult, CliRunOptions } from "./types.js";
|
||||
|
||||
export async function runCli(
|
||||
@@ -55,6 +56,13 @@ export async function runCli(
|
||||
case "workflows":
|
||||
case "wf":
|
||||
return await handleWorkflowCommand(parsed, runtime);
|
||||
case "bill":
|
||||
case "bills":
|
||||
case "fee":
|
||||
case "fees":
|
||||
case "invoice":
|
||||
case "invoices":
|
||||
return await handleBillCommand(parsed, runtime);
|
||||
case "platform":
|
||||
case "platforms":
|
||||
case "app":
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
| 域 | 说明 | 详细文档 |
|
||||
|---|---|---|
|
||||
| `platform/` | 自建应用(DataLink Platform)与工作流(EASO/Piper) | [README.platform.md](./platform/README.platform.md) |
|
||||
| `bill/` | 费控单据、报销单、发票与 DataLink 实体字典 | [README.bill.md](./bill/README.bill.md) |
|
||||
|
||||
## 分层规则
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# Bill 域说明
|
||||
|
||||
本目录负责合思/易快报(ekuaibao)费控单据、报销单、借款单、发票与数据实体元数据字典的检索与格式化。
|
||||
|
||||
## 文件结构
|
||||
|
||||
```text
|
||||
src/domains/bill/
|
||||
├── api.ts # 传输层:调用 /api/v2/invoice/search, /api/v2/invoice, /api/v2/datalink/entity/search
|
||||
├── tools.ts # 业务编排层:DataLink 字段字典映射、单号匹配、格式化与 MCP tools
|
||||
├── types.ts # 模型层:Zod Schema 与 TypeScript 类型定义
|
||||
├── bill.test.ts # 单元测试
|
||||
└── README.bill.md # 本说明文件
|
||||
```
|
||||
|
||||
## 核心能力
|
||||
|
||||
1. **单据检索与分页 (`searchAndFormatBills`)**:
|
||||
- 跨单据池查询费用明细、报销单、借款单与发票。
|
||||
- 支持按单号(`code`)、阶段(`stage`)、状态(`state`)、关键字(`keyword`)过滤。
|
||||
2. **按单号/ID 精确查询 (`getBillByCodeOrId`)**:
|
||||
- 根据业务单号(如 `n0GMIM0dkQmKbS`)或单据 ID(如 `ID01TRzg7HMLcb`)查询单据。
|
||||
3. **DataLink 字段元数据字典 (`getFieldDictionary`)**:
|
||||
- 自动拉取企业全部实体模型定义,将混淆代码字段(如 `E_ae10..._payMoney`)还原为人类友好的中文字段名(如 `报销金额`)。
|
||||
@@ -0,0 +1,71 @@
|
||||
import { KyInstance } from "ky";
|
||||
import {
|
||||
RawBillSearchResponseSchema,
|
||||
RawBillBatchGetResponseSchema,
|
||||
EntityListResponseSchema,
|
||||
type RawBillSearchResponse,
|
||||
type RawBillItem,
|
||||
type EntityMeta,
|
||||
} from "./types.js";
|
||||
|
||||
// ── 原始单据检索 API ──────────────────────────────────────────────────────────
|
||||
|
||||
export async function searchRawBills(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: { start?: number; count?: number } = {}
|
||||
): Promise<RawBillSearchResponse> {
|
||||
const response = await client.post("api/v2/invoice/search", {
|
||||
searchParams: { corporationId: corpId, corpId },
|
||||
json: {
|
||||
limit: {
|
||||
start: options.start ?? 0,
|
||||
count: options.count ?? 50,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const json = await response.json();
|
||||
return RawBillSearchResponseSchema.parse(json);
|
||||
}
|
||||
|
||||
// ── 按 ID 列表精确拉取单据详情 API ─────────────────────────────────────────────
|
||||
|
||||
export async function getRawBillsByIds(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
ids: string[]
|
||||
): Promise<RawBillItem[]> {
|
||||
if (ids.length === 0) return [];
|
||||
|
||||
const response = await client.post("api/v2/invoice", {
|
||||
searchParams: { corporationId: corpId, corpId },
|
||||
json: { ids },
|
||||
});
|
||||
|
||||
const json = await response.json();
|
||||
const parsed = RawBillBatchGetResponseSchema.parse(json);
|
||||
return parsed.items;
|
||||
}
|
||||
|
||||
// ── 单据实体与字段元数据字典 API ───────────────────────────────────────────────
|
||||
|
||||
export async function listEntitySchemas(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: { start?: number; count?: number } = {}
|
||||
): Promise<EntityMeta[]> {
|
||||
const response = await client.post("api/v2/datalink/entity/search", {
|
||||
searchParams: { corporationId: corpId, corpId },
|
||||
json: {
|
||||
limit: {
|
||||
start: options.start ?? 0,
|
||||
count: options.count ?? 100,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const json = await response.json();
|
||||
const parsed = EntityListResponseSchema.parse(json);
|
||||
return parsed.items;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, it, expect } from "bun:test";
|
||||
import { formatSingleBill } from "./tools.js";
|
||||
import { RawBillItemSchema, EntitySchema } from "./types.js";
|
||||
|
||||
describe("Bill Domain", () => {
|
||||
it("validates EntitySchema", () => {
|
||||
const rawEntity = {
|
||||
id: "ae1037940b1c304017c0",
|
||||
code: "FEE_DETAIL",
|
||||
name: "费用明细",
|
||||
type: "EXPENSE",
|
||||
active: true,
|
||||
fields: [
|
||||
{
|
||||
name: "E_ae1037940b1c304017c0_payMoney",
|
||||
type: "money",
|
||||
label: "支付金额",
|
||||
optional: false,
|
||||
formula: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const parsed = EntitySchema.parse(rawEntity);
|
||||
expect(parsed.id).toBe("ae1037940b1c304017c0");
|
||||
expect(parsed.fields[0].label).toBe("支付金额");
|
||||
});
|
||||
|
||||
it("validates RawBillItemSchema and formats fields with dictionary", () => {
|
||||
const rawBill = {
|
||||
id: "ID01TRzg7HMLcb",
|
||||
code: "n0GMIM0dkQmKbS",
|
||||
name: "项目&100",
|
||||
corporationId: "ID01ofWoOC1wiX",
|
||||
ownerId: "ID01ofWoOC1wiX:ID01ojZ2n2e0PR",
|
||||
createTime: 1781682826000,
|
||||
updateTime: 1781682870000,
|
||||
form: {
|
||||
E_test_code: "n0GMIM0dkQmKbS",
|
||||
E_test_title: "测试单据标题",
|
||||
E_test_stage: "expense",
|
||||
E_test_state: "paid",
|
||||
E_test_amount: {
|
||||
standard: "100.00",
|
||||
standardUnit: "元",
|
||||
standardSymbol: "¥",
|
||||
standardStrCode: "CNY",
|
||||
},
|
||||
E_test_submitterId: "staff-123",
|
||||
E_test_customField: "VIP客户",
|
||||
},
|
||||
};
|
||||
|
||||
const parsed = RawBillItemSchema.parse(rawBill);
|
||||
expect(parsed.id).toBe("ID01TRzg7HMLcb");
|
||||
|
||||
const dict = new Map<string, { label: string; type: string }>();
|
||||
dict.set("E_test_customField", { label: "客户等级", type: "text" });
|
||||
|
||||
const formatted = formatSingleBill(parsed, dict);
|
||||
expect(formatted.billId).toBe("ID01TRzg7HMLcb");
|
||||
expect(formatted.billCode).toBe("n0GMIM0dkQmKbS");
|
||||
expect(formatted.title).toBe("测试单据标题");
|
||||
expect(formatted.stage).toBe("expense");
|
||||
expect(formatted.state).toBe("paid");
|
||||
expect(formatted.amount).toBe("¥100.00 CNY");
|
||||
expect(formatted.details["客户等级"]).toBe("VIP客户");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,337 @@
|
||||
import { z } from "zod";
|
||||
import { KyInstance } from "ky";
|
||||
import { searchRawBills, getRawBillsByIds, listEntitySchemas } from "./api.js";
|
||||
import {
|
||||
type RawBillItem,
|
||||
type FormattedBill,
|
||||
type BillPageResult,
|
||||
type EntityMeta,
|
||||
type BillQueryParams,
|
||||
} from "./types.js";
|
||||
import { CorpContext } from "../../core/config/manager.js";
|
||||
import { createEkbClient } from "../../core/auth/ekb.js";
|
||||
|
||||
// ── 字段元数据内存缓存 ─────────────────────────────────────────────────────────
|
||||
|
||||
const schemaCache = new Map<string, { timestamp: number; dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }>();
|
||||
const CACHE_TTL_MS = 10 * 60 * 1000; // 10 分钟缓存
|
||||
|
||||
export async function getFieldDictionary(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
forceRefresh = false
|
||||
): Promise<{ dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }> {
|
||||
const cached = schemaCache.get(corpId);
|
||||
if (!forceRefresh && cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const entities = await listEntitySchemas(client, corpId, { start: 0, count: 100 });
|
||||
const dictionary = new Map<string, { label: string; type: string }>();
|
||||
|
||||
for (const entity of entities) {
|
||||
for (const field of entity.fields) {
|
||||
if (field.name && field.label) {
|
||||
dictionary.set(field.name, { label: field.label, type: field.type });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = { timestamp: Date.now(), dictionary, entities };
|
||||
schemaCache.set(corpId, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ── 格式化单据数据 ─────────────────────────────────────────────────────────────
|
||||
|
||||
export function formatSingleBill(
|
||||
item: RawBillItem,
|
||||
dictionary: Map<string, { label: string; type: string }>
|
||||
): FormattedBill {
|
||||
const rawForm = item.form || {};
|
||||
let billCode = item.code || "";
|
||||
let billName = item.name || "";
|
||||
let title: string | undefined;
|
||||
let stage: string | undefined;
|
||||
let state: string | undefined;
|
||||
let amountStr: string | undefined;
|
||||
let submitterId: string | undefined;
|
||||
let submitDateStr: string | undefined;
|
||||
|
||||
const readableDetails: Record<string, any> = {};
|
||||
|
||||
for (const [k, v] of Object.entries(rawForm)) {
|
||||
if (v === null || v === undefined || v === "") continue;
|
||||
|
||||
// 提取核心通用业务字段
|
||||
if (k.endsWith("_code") && typeof v === "string") billCode = billCode || v;
|
||||
if (k.endsWith("_title") && typeof v === "string") title = v;
|
||||
if (k.endsWith("_stage") && typeof v === "string") stage = v;
|
||||
if (k.endsWith("_state") && typeof v === "string") state = v;
|
||||
if (k.endsWith("_submitterId") && typeof v === "string") submitterId = v;
|
||||
|
||||
// 格式化金额
|
||||
if (k.endsWith("_amount") || k.endsWith("_expenseMoney") || k.endsWith("_payMoney")) {
|
||||
if (typeof v === "object" && v !== null && (v as any).standard) {
|
||||
const money = v as any;
|
||||
const formatted = `${money.standardSymbol || "¥"}${money.standard} ${money.standardStrCode || "CNY"}`.trim();
|
||||
if (!amountStr || k.endsWith("_amount")) {
|
||||
amountStr = formatted;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 格式化提交时间
|
||||
if (k.endsWith("_submitDate") && typeof v === "number" && v > 1000000000000) {
|
||||
submitDateStr = new Date(v).toLocaleString("zh-CN");
|
||||
}
|
||||
|
||||
// 字典 Label 还原
|
||||
const meta = dictionary.get(k);
|
||||
let readableKey = meta ? meta.label : k.replace(/^E_[^_]+_/, "");
|
||||
if (readableKey.startsWith("E_")) {
|
||||
readableKey = readableKey.replace(/^E_/, "");
|
||||
}
|
||||
|
||||
// 格式化字段值
|
||||
let formattedVal = v;
|
||||
if (typeof v === "number" && v > 1000000000000 && v < 2500000000000 && !k.endsWith("_code") && !k.endsWith("_No")) {
|
||||
formattedVal = `${new Date(v).toLocaleString("zh-CN")}`;
|
||||
} else if (typeof v === "object" && v !== null && (v as any).standard) {
|
||||
const money = v as any;
|
||||
formattedVal = `${money.standardSymbol || "¥"}${money.standard} ${money.standardStrCode || "CNY"}`.trim();
|
||||
}
|
||||
|
||||
readableDetails[readableKey] = formattedVal;
|
||||
}
|
||||
|
||||
const createTimeStr = item.createTime > 0
|
||||
? new Date(item.createTime).toLocaleString("zh-CN")
|
||||
: "";
|
||||
const updateTimeStr = item.updateTime > 0
|
||||
? new Date(item.updateTime).toLocaleString("zh-CN")
|
||||
: "";
|
||||
|
||||
return {
|
||||
billId: item.id,
|
||||
billCode: billCode || item.id,
|
||||
billName: billName || item.id,
|
||||
title,
|
||||
stage,
|
||||
state,
|
||||
amount: amountStr,
|
||||
submitterId,
|
||||
submitDate: submitDateStr,
|
||||
corporationId: item.corporationId || "",
|
||||
ownerId: item.ownerId || "",
|
||||
createTime: createTimeStr,
|
||||
updateTime: updateTimeStr,
|
||||
details: readableDetails,
|
||||
};
|
||||
}
|
||||
|
||||
// ── 业务操作:按单号或 ID 精确查询单据 ─────────────────────────────────────────
|
||||
|
||||
export async function getBillByCodeOrId(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
queryCodeOrId: string
|
||||
): Promise<FormattedBill[]> {
|
||||
const cleanQuery = queryCodeOrId.trim();
|
||||
if (!cleanQuery) return [];
|
||||
|
||||
const { dictionary } = await getFieldDictionary(client, corpId);
|
||||
|
||||
// 1. 如果传入的是 ID 格式(如 ID01...),先尝试走精准 ID 批量接口
|
||||
if (cleanQuery.startsWith("ID01")) {
|
||||
try {
|
||||
const items = await getRawBillsByIds(client, corpId, [cleanQuery]);
|
||||
if (items.length > 0) {
|
||||
return items.map((it) => formatSingleBill(it, dictionary));
|
||||
}
|
||||
} catch {
|
||||
// 忽略错误,继续回退到 search 检索
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 从 search 中匹配单号、flowCode、ID 或关联 LinkId
|
||||
const searchRes = await searchRawBills(client, corpId, { start: 0, count: 50 });
|
||||
const matched = searchRes.items.filter((item) => {
|
||||
if (item.id === cleanQuery) return true;
|
||||
if (item.code === cleanQuery) return true;
|
||||
for (const [k, v] of Object.entries(item.form || {})) {
|
||||
if (typeof v === "string" && v.trim() === cleanQuery) {
|
||||
if (k.endsWith("_code") || k.endsWith("_flowCode") || k.endsWith("_linkId") || k.endsWith("_detailId")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
return matched.map((it) => formatSingleBill(it, dictionary));
|
||||
}
|
||||
|
||||
// ── 业务操作:多条件搜索与分页单据 ─────────────────────────────────────────────
|
||||
|
||||
export async function searchAndFormatBills(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
params: BillQueryParams = {}
|
||||
): Promise<BillPageResult> {
|
||||
const { dictionary } = await getFieldDictionary(client, corpId);
|
||||
const searchRes = await searchRawBills(client, corpId, {
|
||||
start: params.start ?? 0,
|
||||
count: params.count ?? 50,
|
||||
});
|
||||
|
||||
let filtered = searchRes.items;
|
||||
|
||||
// 客户端辅助精确过滤
|
||||
if (params.code) {
|
||||
const target = params.code.trim();
|
||||
filtered = filtered.filter((it) => {
|
||||
if (it.code === target) return true;
|
||||
for (const [k, v] of Object.entries(it.form || {})) {
|
||||
if (k.endsWith("_code") && v === target) return true;
|
||||
if (k.endsWith("_flowCode") && v === target) return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
if (params.id) {
|
||||
const target = params.id.trim();
|
||||
filtered = filtered.filter((it) => it.id === target);
|
||||
}
|
||||
|
||||
if (params.stage) {
|
||||
const target = params.stage.trim().toLowerCase();
|
||||
filtered = filtered.filter((it) => {
|
||||
for (const [k, v] of Object.entries(it.form || {})) {
|
||||
if (k.endsWith("_stage") && String(v).toLowerCase() === target) return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
if (params.state) {
|
||||
const target = params.state.trim().toLowerCase();
|
||||
filtered = filtered.filter((it) => {
|
||||
for (const [k, v] of Object.entries(it.form || {})) {
|
||||
if (k.endsWith("_state") && String(v).toLowerCase() === target) return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
if (params.keyword) {
|
||||
const kw = params.keyword.trim().toLowerCase();
|
||||
filtered = filtered.filter((it) => {
|
||||
if (it.name?.toLowerCase().includes(kw)) return true;
|
||||
if (it.code?.toLowerCase().includes(kw)) return true;
|
||||
for (const v of Object.values(it.form || {})) {
|
||||
if (typeof v === "string" && v.toLowerCase().includes(kw)) return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
const formattedItems = filtered.map((it) => formatSingleBill(it, dictionary));
|
||||
|
||||
return {
|
||||
total: searchRes.count,
|
||||
returned: formattedItems.length,
|
||||
items: formattedItems,
|
||||
};
|
||||
}
|
||||
|
||||
// ── MCP Tools 适配 ────────────────────────────────────────────────────────────
|
||||
|
||||
export const billTools = [
|
||||
{
|
||||
name: "bill_search",
|
||||
description: "检索企业名下的费用单据、报销单、借款单与发票列表(已自动将字段代码还原为可读业务名称)",
|
||||
parameters: z.object({
|
||||
code: z.string().optional().describe("按单据编号/单号过滤(如 jO1it3cIufDjNS)"),
|
||||
keyword: z.string().optional().describe("按关键字模糊搜索标题、名称或内容"),
|
||||
stage: z.string().optional().describe("按阶段过滤(如 expense 报销, loan 借款, payment 付款)"),
|
||||
state: z.string().optional().describe("按审批/支付状态过滤(如 paid 已支付, approving 审批中, draft 草稿)"),
|
||||
count: z.number().optional().default(20).describe("拉取记录数"),
|
||||
}),
|
||||
handler: async (
|
||||
{ corpContext }: { corpContext: CorpContext },
|
||||
params: { code?: string; keyword?: string; stage?: string; state?: string; count?: number }
|
||||
) => {
|
||||
const corp = corpContext.getCurrent();
|
||||
if (!corp) {
|
||||
throw new Error("未配置活跃企业上下文");
|
||||
}
|
||||
const client = await createEkbClient(corp);
|
||||
const result = await searchAndFormatBills(client, corp.corpId || corp.id, params);
|
||||
return {
|
||||
corpId: corp.corpId || corp.id,
|
||||
corpName: corp.name,
|
||||
...result,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bill_get",
|
||||
description: "根据单据编号(单号)或单据 ID 精确查询单据详细信息与格式化表单明细",
|
||||
parameters: z.object({
|
||||
code: z.string().describe("单据编号(如 jO1it3cIufDjNS)或 单据 ID(如 ID01V0zDDjZNHp)"),
|
||||
}),
|
||||
handler: async (
|
||||
{ corpContext }: { corpContext: CorpContext },
|
||||
params: { code: string }
|
||||
) => {
|
||||
const corp = corpContext.getCurrent();
|
||||
if (!corp) {
|
||||
throw new Error("未配置活跃企业上下文");
|
||||
}
|
||||
const client = await createEkbClient(corp);
|
||||
const bills = await getBillByCodeOrId(client, corp.corpId || corp.id, params.code);
|
||||
if (bills.length === 0) {
|
||||
return {
|
||||
found: false,
|
||||
message: `未找到单号或 ID 为 [${params.code}] 的单据`,
|
||||
code: params.code,
|
||||
};
|
||||
}
|
||||
return {
|
||||
found: true,
|
||||
count: bills.length,
|
||||
bills,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bill_schema",
|
||||
description: "获取企业全部单据实体的数据模型、表单定义与中文字段 Label 字典",
|
||||
parameters: z.object({}),
|
||||
handler: async ({ corpContext }: { corpContext: CorpContext }) => {
|
||||
const corp = corpContext.getCurrent();
|
||||
if (!corp) {
|
||||
throw new Error("未配置活跃企业上下文");
|
||||
}
|
||||
const client = await createEkbClient(corp);
|
||||
const { entities } = await getFieldDictionary(client, corp.corpId || corp.id, true);
|
||||
return {
|
||||
corpId: corp.corpId || corp.id,
|
||||
totalEntities: entities.length,
|
||||
entities: entities.map((e) => ({
|
||||
id: e.id,
|
||||
name: e.name,
|
||||
type: e.type,
|
||||
fieldCount: e.fields.length,
|
||||
fields: e.fields.map((f) => ({
|
||||
name: f.name,
|
||||
label: f.label,
|
||||
type: f.type,
|
||||
})),
|
||||
})),
|
||||
};
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,105 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// ── 字段元数据(DataLink Field Meta)──────────────────────────────────────────
|
||||
|
||||
export const FieldMetaSchema = z.object({
|
||||
name: z.string(),
|
||||
type: z.string().default("text"),
|
||||
label: z.string().default(""),
|
||||
regex: z.string().optional().default(""),
|
||||
source: z.string().optional().default("dataLink"),
|
||||
formula: z.boolean().optional().default(false),
|
||||
optional: z.boolean().optional().default(true),
|
||||
calculation: z.record(z.string(), z.any()).optional(),
|
||||
});
|
||||
|
||||
export const EntitySchema = z.object({
|
||||
id: z.string(),
|
||||
code: z.string().optional().default(""),
|
||||
name: z.string().default(""),
|
||||
type: z.string().default(""),
|
||||
active: z.boolean().default(true),
|
||||
fields: z.array(FieldMetaSchema).default([]),
|
||||
});
|
||||
|
||||
export const EntityListResponseSchema = z.object({
|
||||
items: z.array(EntitySchema).default([]),
|
||||
});
|
||||
|
||||
// ── 原始单据条目(Raw Bill Item from /api/v2/invoice/search)─────────────────────
|
||||
|
||||
export const RawBillMoneySchema = z.object({
|
||||
standard: z.string().or(z.number()).transform((v) => String(v)),
|
||||
standardUnit: z.string().optional().default("元"),
|
||||
standardScale: z.number().optional().default(2),
|
||||
standardSymbol: z.string().optional().default("¥"),
|
||||
standardNumCode: z.string().optional().default("156"),
|
||||
standardStrCode: z.string().optional().default("CNY"),
|
||||
});
|
||||
|
||||
export const RawBillItemSchema = z.object({
|
||||
id: z.string(),
|
||||
code: z.string().default(""),
|
||||
name: z.string().default(""),
|
||||
entityId: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true),
|
||||
ownerId: z.string().optional().default(""),
|
||||
corporationId: z.string().optional().default(""),
|
||||
createTime: z.number().default(0),
|
||||
updateTime: z.number().default(0),
|
||||
form: z.record(z.string(), z.any()).default({}),
|
||||
});
|
||||
|
||||
export const RawBillSearchResponseSchema = z.object({
|
||||
count: z.number().default(0),
|
||||
items: z.array(RawBillItemSchema).default([]),
|
||||
});
|
||||
|
||||
export const RawBillBatchGetResponseSchema = z.object({
|
||||
items: z.array(RawBillItemSchema).default([]),
|
||||
});
|
||||
|
||||
// ── 格式化后的单据输出(Formatted Bill)───────────────────────────────────────
|
||||
|
||||
export const FormattedBillSchema = z.object({
|
||||
billId: z.string(),
|
||||
billCode: z.string(),
|
||||
billName: z.string(),
|
||||
title: z.string().optional(),
|
||||
stage: z.string().optional(),
|
||||
state: z.string().optional(),
|
||||
amount: z.string().optional(),
|
||||
submitterId: z.string().optional(),
|
||||
submitDate: z.string().optional(),
|
||||
corporationId: z.string(),
|
||||
ownerId: z.string().optional(),
|
||||
createTime: z.string(),
|
||||
updateTime: z.string(),
|
||||
details: z.record(z.string(), z.any()),
|
||||
});
|
||||
|
||||
export const BillPageResultSchema = z.object({
|
||||
total: z.number(),
|
||||
returned: z.number(),
|
||||
items: z.array(FormattedBillSchema),
|
||||
});
|
||||
|
||||
// ── 类型导出 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export type FieldMeta = z.infer<typeof FieldMetaSchema>;
|
||||
export type EntityMeta = z.infer<typeof EntitySchema>;
|
||||
export type RawBillMoney = z.infer<typeof RawBillMoneySchema>;
|
||||
export type RawBillItem = z.infer<typeof RawBillItemSchema>;
|
||||
export type RawBillSearchResponse = z.infer<typeof RawBillSearchResponseSchema>;
|
||||
export type FormattedBill = z.infer<typeof FormattedBillSchema>;
|
||||
export type BillPageResult = z.infer<typeof BillPageResultSchema>;
|
||||
|
||||
export interface BillQueryParams {
|
||||
code?: string;
|
||||
id?: string;
|
||||
keyword?: string;
|
||||
stage?: string;
|
||||
state?: string;
|
||||
start?: number;
|
||||
count?: number;
|
||||
}
|
||||
+24
-2
@@ -12,6 +12,7 @@ import { getEasoClient } from "./core/auth/easo.js";
|
||||
import { AuthenticationError, EkbError, NotLoggedInError } from "./core/errors.js";
|
||||
import { authTools } from "./core/auth/tools.js";
|
||||
import { platformTools } from "./domains/platform/tools.js";
|
||||
import { billTools } from "./domains/bill/tools.js";
|
||||
|
||||
function formatError(error: unknown): {
|
||||
content: Array<{ type: "text"; text: string }>;
|
||||
@@ -70,7 +71,7 @@ async function main() {
|
||||
);
|
||||
|
||||
// 聚合所有工具
|
||||
const allTools = [...authTools, ...platformTools];
|
||||
const allTools = [...authTools, ...platformTools, ...billTools];
|
||||
|
||||
// 注册工具列表
|
||||
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
||||
@@ -109,7 +110,28 @@ async function main() {
|
||||
};
|
||||
}
|
||||
|
||||
// 2. 检查 Domain 业务工具(需要当前企业上下文)
|
||||
// 2. 检查 Bill 工具
|
||||
const billTool = billTools.find((t) => t.name === name);
|
||||
if (billTool) {
|
||||
const parsed = billTool.parameters.safeParse(args || {});
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
content: [{ type: "text", text: `参数错误: ${parsed.error.message}` }],
|
||||
isError: true,
|
||||
};
|
||||
}
|
||||
const result = await billTool.handler({ corpContext }, parsed.data as never);
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: typeof result === "string" ? result : JSON.stringify(result, null, 2),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// 3. 检查 Domain 业务工具(需要当前企业上下文)
|
||||
const currentCorp = corpContext.getCurrent();
|
||||
if (!currentCorp) {
|
||||
return {
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
export const VERSION = "0.2.2";
|
||||
export const VERSION = "0.3.0";
|
||||
Reference in new issue
Block a user