Files
hose-use/src/domains/bill/tools.ts
T

809 lines
33 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { z } from "zod";
import { KyInstance } from "ky";
import {
searchRawBills,
getRawBillsByIds,
listEntitySchemas,
getRawBillFlow,
getRawBillRisk,
listActiveStaffCatalog,
getDepartmentTree,
getFeeTypeTree,
} from "./api.js";
import {
type RawBillItem,
type FormattedBill,
type BillPageResult,
type EntityMeta,
type BillQueryParams,
type BillFlowEntry,
type BillFlowNode,
type BillFlowTimeline,
type BillRiskReport,
type BillRiskWarning,
type BillReference,
type BillReferenceReport,
type BillRelationNode,
type BillRelationsReport,
type BillAttachment,
type BillAttachmentReport,
} from "./types.js";
import { CorpContext } from "../../core/config/manager.js";
import { createEkbClient } from "../../core/auth/ekb.js";
// ── 通用内置字段中文 Label 字典 ───────────────────────────────────────────────
const COMMON_FIELD_LABELS: Record<string, string> = {
code: "单据编号",
name: "单据名称",
stage: "业务阶段",
state: "审批状态",
title: "单据标题",
amount: "单据金额",
expenseMoney: "报销金额",
payMoney: "支付金额",
apportionMoney: "分摊金额",
submitDate: "提交时间",
submitterId: "提交人ID",
ownerId: "归属人ID",
description: "事由说明",
detailType: "明细类型",
entityType: "实体类型",
settleStatus: "结算状态",
settleTime: "结算时间",
billingStatus: "开票状态",
voucherStatus: "凭证状态",
voucherCreateTime: "凭证生成时间",
writtenOffAmount: "已核销金额",
unwrittenOffAmount: "未核销金额",
linkType: "关联类型",
linkId: "关联审批流ID",
detailId: "明细ID",
detailNo: "明细序号",
feeTypeId: "费用类型ID",
attachments: "附件列表",
invoiceForm: "发票表单",
submitCount: "提交次数",
rejectionNum: "驳回次数",
reviewStatus: "审核状态",
preApprovedNodeName: "上一审批节点",
preNodeApprovedTime: "节点审批通过时间",
accountPropertyMoney: "核算属性金额",
accountPropertyDate: "核算属性日期",
flowSpecificationId: "流程规范ID",
feeDetailSpecificationId: "费用明细规范ID",
printState: "打印状态",
printCount: "打印次数",
onlyOwnerPrint: "仅提交人可打印",
ownerAndApproverPrintNodeFlag: "节点打印控制标识",
};
// ── 字段元数据内存缓存 ─────────────────────────────────────────────────────────
const schemaCache = new Map<string, { timestamp: number; dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }>();
const CACHE_TTL_MS = 10 * 60 * 1000; // 10 分钟缓存
type ReferenceCatalog = {
timestamp: number;
staff: Map<string, Record<string, unknown>>;
departments: Map<string, { item: Record<string, unknown>; path: string }>;
feeTypes: Map<string, Record<string, unknown>>;
};
const referenceCatalogCache = new Map<string, ReferenceCatalog>();
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;
}
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<string, unknown>).id;
return typeof id === "string" && id.trim() ? id.trim() : undefined;
}
function referenceObject(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" ? value as Record<string, unknown> : undefined;
}
function flattenDepartments(items: Record<string, unknown>[], parentPath = "", output = new Map<string, { item: Record<string, unknown>; path: string }>()): Map<string, { item: Record<string, unknown>; 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<string, unknown> => Boolean(child && typeof child === "object"))
: [];
flattenDepartments(children, path, output);
}
return output;
}
function flattenFeeTypes(items: Record<string, unknown>[], output = new Map<string, Record<string, unknown>>()): Map<string, Record<string, unknown>> {
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<string, unknown> => Boolean(child && typeof child === "object"))
: [];
flattenFeeTypes(children, output);
}
return output;
}
async function getReferenceCatalog(client: KyInstance, corpId: string): Promise<ReferenceCatalog> {
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<string, Record<string, unknown>>();
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<string, unknown>,
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<string>()): Set<string> {
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<string, unknown>)) {
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<BillReferenceReport | undefined> {
const raw = await getRawBillFlow(client, corpId, target);
if (!raw || !raw.flowId || typeof raw.flowId !== "object") return undefined;
const flow = raw.flowId as Record<string, unknown>;
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
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 },
};
}
function relationAmount(value: Record<string, unknown>): string | undefined {
for (const key of ["amount", "money", "expenseMoney", "loanMoney", "requisitionMoney", "payMoney", "writtenOffAmount"]) {
const candidate = value[key];
if (typeof candidate === "number" || typeof candidate === "string") return String(candidate);
if (candidate && typeof candidate === "object") {
const money = candidate as Record<string, unknown>;
if (money.standard !== undefined) return `${money.standardSymbol || "¥"}${money.standard} ${money.standardStrCode || "CNY"}`.trim();
}
}
return undefined;
}
function relationNode(relation: string, value: unknown): BillRelationNode | undefined {
if (!value || typeof value !== "object") return undefined;
const object = value as Record<string, unknown>;
const children: BillRelationNode[] = [];
for (const [key, nested] of Object.entries(object)) {
if (key === "id" || key === "code" || key === "title" || key === "name") continue;
if (Array.isArray(nested)) {
for (const item of nested) {
const arrayChild = relationNode(key, item);
if (arrayChild) children.push(arrayChild);
}
} else if (nested && typeof nested === "object") {
const child = relationNode(key, nested);
if (child) children.push(child);
}
}
const id = typeof object.id === "string" ? object.id : undefined;
const code = typeof object.code === "string" ? object.code : undefined;
const title = typeof object.title === "string" ? object.title : typeof object.name === "string" ? object.name : undefined;
if (!id && !code && !title && children.length === 0) return undefined;
return { relation, id, code, title, amount: relationAmount(object), children, raw: object };
}
export async function getBillRelations(
client: KyInstance,
corpId: string,
target: string,
): Promise<BillRelationsReport | undefined> {
const raw = await getRawBillFlow(client, corpId, target);
if (!raw || !raw.flowId || typeof raw.flowId !== "object") return undefined;
const flow = raw.flowId as Record<string, unknown>;
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
const relations: BillRelationNode[] = [];
const seen = new Set<string>();
const relationPattern = /(link|loan|requisition|contract|pre.?apply|advance)/i;
for (const [key, value] of Object.entries(form)) {
if (!relationPattern.test(key)) continue;
const values = Array.isArray(value) ? value : [value];
for (const candidate of values) {
const node = relationNode(key, candidate);
if (!node) continue;
const dedupeKey = `${node.relation}:${node.id || node.code || node.title || JSON.stringify(node.raw)}`;
if (seen.has(dedupeKey)) continue;
seen.add(dedupeKey);
relations.push(node);
}
}
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,
relations,
raw: { form },
};
}
function attachmentFromValue(sourceField: string, value: unknown): BillAttachment | undefined {
if (!value || typeof value !== "object") return undefined;
const object = value as Record<string, unknown>;
const nestedFile = object.fileId && typeof object.fileId === "object" ? object.fileId as Record<string, unknown> : undefined;
const fileId = typeof object.fileId === "string" ? object.fileId : typeof nestedFile?.id === "string" ? nestedFile.id : undefined;
const key = typeof object.key === "string" ? object.key : typeof nestedFile?.key === "string" ? nestedFile.key : undefined;
const fileName = typeof object.fileName === "string" ? object.fileName : typeof object.name === "string" ? object.name : undefined;
const url = typeof object.url === "string" ? object.url : typeof nestedFile?.url === "string" ? nestedFile.url : undefined;
const thumbUrl = typeof object.thumbUrl === "string" ? object.thumbUrl : typeof nestedFile?.thumbUrl === "string" ? nestedFile.thumbUrl : undefined;
if (!fileId && !key && !fileName && !url) return undefined;
return { fileId, key, fileName, url, thumbUrl, sourceField, raw: object };
}
function collectAttachments(sourceField: string, value: unknown, output: BillAttachment[]): void {
if (Array.isArray(value)) {
for (const item of value) collectAttachments(sourceField, item, output);
return;
}
if (!value || typeof value !== "object") return;
const object = value as Record<string, unknown>;
const looksLikeAttachment = sourceField.toLowerCase().includes("attachment") || "fileId" in object || "fileName" in object || "thumbUrl" in object;
if (looksLikeAttachment) {
const attachment = attachmentFromValue(sourceField, value);
if (attachment) output.push(attachment);
}
for (const [key, nested] of Object.entries(object)) {
if (key === "fileId" || key === "fileName" || key === "url" || key === "thumbUrl" || key === "key") continue;
if (nested && typeof nested === "object") collectAttachments(sourceField === "form" ? key : `${sourceField}.${key}`, nested, output);
}
}
export async function getBillAttachments(
client: KyInstance,
corpId: string,
target: string,
): Promise<BillAttachmentReport | undefined> {
const raw = await getRawBillFlow(client, corpId, target);
if (!raw || !raw.flowId || typeof raw.flowId !== "object") return undefined;
const flow = raw.flowId as Record<string, unknown>;
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
const attachments: BillAttachment[] = [];
collectAttachments("form", form, attachments);
const deduped = [...new Map(attachments.map((item) => [`${item.fileId || ""}|${item.key || ""}|${item.fileName || ""}`, item])).values()];
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,
attachments: deduped,
raw: { form },
};
}
// ── 格式化单据数据 ─────────────────────────────────────────────────────────────
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);
const bareKey = k.replace(/^E_[^_]+_/, "").replace(/^E_/, "");
let readableKey = meta ? meta.label : (COMMON_FIELD_LABELS[k] || COMMON_FIELD_LABELS[bareKey] || bareKey);
// 格式化字段值
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));
}
function flowPerson(value: unknown): { id?: string; name?: string; code?: string } | undefined {
if (typeof value === "string") return { id: value };
if (!value || typeof value !== "object") return undefined;
const person = value as Record<string, unknown>;
return {
id: typeof person.id === "string" ? person.id : undefined,
name: typeof person.name === "string" ? person.name : undefined,
code: typeof person.code === "string" ? person.code : undefined,
};
}
function unwrapValue(value: unknown): Record<string, unknown> {
if (!value || typeof value !== "object") return {};
const object = value as Record<string, unknown>;
return object.value && typeof object.value === "object" ? object.value as Record<string, unknown> : object;
}
export async function getBillFlow(
client: KyInstance,
corpId: string,
target: string
): Promise<BillFlowTimeline | undefined> {
const raw = await getRawBillFlow(client, corpId, target);
if (!raw) return undefined;
const flow = raw.flowId && typeof raw.flowId === "object" ? raw.flowId as Record<string, unknown> : {};
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
const nodeState = raw.nodeState && typeof raw.nodeState === "object" ? raw.nodeState as Record<string, unknown> : {};
const logs = Array.isArray(flow.logs) ? flow.logs : [];
const history: BillFlowEntry[] = logs.map((value) => {
const log = value && typeof value === "object" ? value as Record<string, unknown> : {};
const attributes = log.attributes && typeof log.attributes === "object" ? log.attributes as Record<string, unknown> : {};
const nextOperators = Array.isArray(log.nextOperatorIds)
? log.nextOperatorIds.map(flowPerson).filter((person): person is NonNullable<typeof person> => Boolean(person))
: [];
return {
id: typeof log.id === "string" ? log.id : undefined,
time: typeof log.time === "number" ? log.time : undefined,
state: typeof log.state === "string" ? log.state : undefined,
action: typeof log.action === "string" ? log.action : undefined,
nodeName: typeof attributes.nodeName === "string" ? attributes.nodeName : typeof attributes.nextName === "string" ? attributes.nextName : undefined,
comment: typeof attributes.comment === "string" && attributes.comment ? attributes.comment : undefined,
automatic: attributes.isEbotNode === true || attributes.isAuto === true || !log.operatorId,
operator: flowPerson(log.operatorId),
nextOperators,
};
});
const plan = flow.plan && typeof flow.plan === "object" ? flow.plan as Record<string, unknown> : {};
const nextNodeId = typeof plan.nextNodeId === "string" ? plan.nextNodeId : undefined;
const currentNode = typeof raw.nodeName === "string" ? raw.nodeName : typeof nodeState.nodeName === "string" ? nodeState.nodeName : undefined;
const nodes = Array.isArray(plan.nodes) ? plan.nodes : [];
const pending: BillFlowNode[] = nodes.map((value) => {
const node = value && typeof value === "object" ? value as Record<string, unknown> : {};
const approvers = Array.isArray(node.counterSigners)
? node.counterSigners.map(flowPerson).filter((person): person is NonNullable<typeof person> => Boolean(person))
: [];
const approver = flowPerson(node.approverId);
return {
id: typeof node.id === "string" ? node.id : undefined,
name: typeof node.name === "string" ? node.name : undefined,
type: typeof node.type === "string" ? node.type : undefined,
state: typeof node.id === "string" && node.id === nextNodeId || typeof node.name === "string" && node.name === currentNode ? "current" : "planned",
approver,
approvers,
};
});
const lastAttributes = logs.at(-1) && typeof logs.at(-1) === "object" && (logs.at(-1) as Record<string, unknown>).attributes && typeof (logs.at(-1) as Record<string, unknown>).attributes === "object"
? (logs.at(-1) as Record<string, unknown>).attributes as Record<string, unknown>
: {};
return {
backlogId: typeof raw.id === "string" ? raw.id : target,
flowId: typeof flow.id === "string" ? flow.id : undefined,
billCode: typeof form.code === "string" ? form.code : undefined,
title: typeof form.title === "string" ? form.title : undefined,
state: typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : undefined,
currentNode: currentNode ?? (typeof lastAttributes.nextName === "string" ? lastAttributes.nextName : undefined),
history,
pending,
raw,
};
}
export async function getBillRisk(
client: KyInstance,
corpId: string,
target: string
): Promise<BillRiskReport | undefined> {
const rawFlow = await getRawBillFlow(client, corpId, target);
if (!rawFlow || !rawFlow.flowId || typeof rawFlow.flowId !== "object") return undefined;
const flow = rawFlow.flowId as Record<string, unknown>;
const flowId = typeof flow.id === "string" ? flow.id : undefined;
if (!flowId) return undefined;
const form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
const submitter = form.submitterId && typeof form.submitterId === "object" ? form.submitterId as Record<string, unknown> : {};
const submitterId = typeof submitter.id === "string" ? submitter.id : undefined;
const rawRisk = await getRawBillRisk(client, corpId, flowId, submitterId);
const coalition = unwrapValue(rawRisk.coalition);
const rawWarnings = Array.isArray(coalition.riskWarning) ? coalition.riskWarning : [];
const warnings: BillRiskWarning[] = rawWarnings.map((value) => {
const item = value && typeof value === "object" ? value as Record<string, unknown> : {};
return {
riskLevel: typeof item.riskLevel === "string" ? item.riskLevel : undefined,
type: typeof item.type === "string" ? item.type : undefined,
title: typeof item.title === "string" ? item.title : undefined,
controlName: typeof item.controlName === "string" ? item.controlName : undefined,
messages: Array.isArray(item.messages) ? item.messages.filter((message): message is string => typeof message === "string") : [],
raw: item,
};
});
const invoice = unwrapValue(rawRisk.invoice);
const budget = unwrapValue(rawRisk.budget);
return {
flowId,
budgetExceeded: budget.value === true,
budget,
credit: unwrapValue(rawRisk.staff),
rules: unwrapValue(rawRisk.rules),
notes: unwrapValue(rawRisk.notes),
warnings,
invoiceWarnings: Array.isArray(invoice.items) ? invoice.items.filter((item): item is Record<string, unknown> => Boolean(item && typeof item === "object")) : [],
raw: rawRisk,
};
}
// ── 业务操作:多条件搜索与分页单据 ─────────────────────────────────────────────
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,
})),
})),
};
},
},
];