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

1888 lines
76 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 { KyInstance } from "ky";
import { existsSync } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import { basename, extname, join, resolve } from "node:path";
import { getGlobalCache } from "../../core/cache/index.js";
import {
BusinessError,
EkbApiError,
NotFoundError,
PermissionError,
ValidationError,
} from "../../core/errors.js";
import {
searchRawBills,
getRawBillsByIds,
listEntitySchemas,
getRawBillFlow,
getRawBillRisk,
listActiveStaffCatalog,
getDepartmentTree,
getFeeTypeTree,
resolveAttachmentFiles,
approveBillAction,
rejectBillAction,
transferBillAction,
addNodeBillAction,
commentBillAction,
getInvoiceValidationDetail,
getDatalinkCard,
getFormSpecification,
type BillActionOptions,
type BillActionTarget,
} from "./api.js";
import {
formatBillFlowOperator,
translateBillFlowAction,
translateBillFlowState,
type TranslatorOptions,
} from "./translator.js";
import {
type RawBillItem,
type RawBillSearchResponse,
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,
type BillFlowTimelineItem,
type BillFlowTraceDiagnostic,
type FormSpecification,
type FormSpecificationComponent,
type FormPriorityItem,
} from "./types.js";
import { resolveDimension } from "../dimension/tools.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 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>>;
};
export async function getFieldDictionary(
client: KyInstance,
corpId: string,
forceRefresh = false
): Promise<{ dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }> {
const cache = getGlobalCache();
const rawEntities = await cache.withCache(
`bill:entities:${corpId}`,
() => listEntitySchemas(client, corpId, { start: 0, count: 100 }),
{ namespace: "bills", ttlMs: CACHE_TTL_MS, forceRefresh }
);
const dictionary = new Map<string, { label: string; type: string }>();
for (const entity of rawEntities) {
for (const field of entity.fields) {
if (field.name && field.label) {
dictionary.set(field.name, { label: field.label, type: field.type });
}
}
}
return { dictionary, entities: rawEntities };
}
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 cache = getGlobalCache();
const raw = await cache.withCache(
`bill:ref_raw:${corpId}`,
async () => {
const [staffs, departments, feeTypes] = await Promise.all([
listActiveStaffCatalog(client, corpId),
getDepartmentTree(client, corpId),
getFeeTypeTree(client, corpId),
]);
return { staffs, departments, feeTypes };
},
{ namespace: "bills", ttlMs: CACHE_TTL_MS }
);
const staff = new Map<string, Record<string, unknown>>();
for (const item of raw.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);
}
}
return {
timestamp: Date.now(),
staff,
departments: flattenDepartments(raw.departments),
feeTypes: flattenFeeTypes(raw.feeTypes),
};
}
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 submitterObject = referenceObject(form.submitterId);
const submitterLegalEntity = submitterObject?.defaultDepartment && typeof submitterObject.defaultDepartment === "object"
? referenceObject(submitterObject.defaultDepartment)?.form && typeof referenceObject(submitterObject.defaultDepartment)?.form === "object"
? (referenceObject(submitterObject.defaultDepartment)?.form as Record<string, unknown>).legalEntity
: undefined
: undefined;
const legalEntityId = referenceId(legalEntityValue) || referenceId(submitterLegalEntity);
const legalEntityCatalog = legalEntityId ? await resolveDimension(client, corpId, "FRST") : undefined;
const legalEntityItem = legalEntityCatalog?.items.find((item) => item.id === legalEntityId || item.id.endsWith(`:${legalEntityId}`));
const legalEntity = toReference(legalEntityValue || submitterLegalEntity || legalEntityId, "legalEntity", legalEntityItem ? "catalog" : "joined", legalEntityItem as unknown as Record<string, unknown> | undefined);
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));
const dimensions: BillReference[] = [];
const dimensionTargets: Array<[RegExp, string]> = [[/project|项目/i, "DA001"], [/cost.?center|成本中心/i, "costCenter"]];
for (const [keyPattern, dimensionCode] of dimensionTargets) {
for (const [key, value] of Object.entries(form)) {
if (!keyPattern.test(key)) continue;
const id = referenceId(value);
if (!id) continue;
const resolved = await resolveDimension(client, corpId, dimensionCode);
const item = resolved?.items.find((entry) => entry.id === id || entry.id.endsWith(`:${id}`));
const reference = toReference(value, "dimension", item ? "catalog" : "raw", item as unknown as Record<string, unknown> | undefined);
if (reference) dimensions.push(reference);
if (!reference?.name) unresolved.push(id);
}
}
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,
dimensions,
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);
let billId: string | undefined;
let billCode: string | undefined;
let title: string | undefined;
let form: Record<string, unknown> = {};
if (raw?.flowId && typeof raw.flowId === "object") {
billId = typeof raw.id === "string" ? raw.id : undefined;
const flow = raw.flowId as Record<string, unknown>;
form = flow.form && typeof flow.form === "object" ? flow.form as Record<string, unknown> : {};
billCode = typeof form.code === "string" ? form.code : undefined;
title = typeof form.title === "string" ? form.title : undefined;
} else {
const search = await searchRawBills(client, corpId, { count: 100 });
const item = search.items.find((candidate) => candidate.id === target || candidate.code === target);
if (!item) return undefined;
billId = item.id;
billCode = item.code;
title = item.form?.title as string | undefined;
form = item.form || {};
}
const attachments: BillAttachment[] = [];
collectAttachments("form", form, attachments);
const deduped = [...new Map(attachments.map((item) => [`${item.fileId || ""}|${item.key || ""}|${item.fileName || ""}`, item])).values()];
const fileIds = deduped
.map((item) => item.fileId)
.filter((fileId): fileId is string => Boolean(fileId));
let resolved: Awaited<ReturnType<typeof resolveAttachmentFiles>> = [];
try {
resolved = await resolveAttachmentFiles(client, corpId, fileIds);
} catch {
// 附件元数据接口不可用时,仍返回审批详情中已经拿到的原始字段。
}
const resolvedById = new Map(resolved.map((item) => [item.id, item]));
const enriched = deduped.map((item) => {
const metadata = item.fileId ? resolvedById.get(item.fileId) : undefined;
if (!metadata) return item;
return {
...item,
key: item.key ?? metadata.key,
fileName: item.fileName ?? metadata.name,
url: item.url ?? metadata.url,
thumbUrl: item.thumbUrl ?? metadata.thumbUrl,
raw: { ...item.raw, resolved: metadata },
};
});
return {
target,
billId,
billCode,
title,
attachments: enriched,
raw: { form },
};
}
export interface DownloadedBillAttachment {
fileId?: string;
fileName?: string;
key?: string;
path: string;
bytes: number;
}
function safeAttachmentName(value: string): string {
const cleaned = basename(value)
.replace(/[\\/?%*:|"<>]/g, "_")
.replace(/^\.+/, "_")
.trim();
return cleaned || "attachment";
}
function uniqueAttachmentPath(outputDir: string, fileName: string, fileId: string | undefined, used: Set<string>): string {
const extension = extname(fileName);
const stem = extension ? fileName.slice(0, -extension.length) : fileName;
let index = 0;
while (true) {
const suffix = index === 0 ? "" : fileId ? `-${fileId}${index > 1 ? `-${index}` : ""}` : `-copy${index > 1 ? `-${index}` : ""}`;
const candidate = join(outputDir, `${stem}${suffix}${extension}`);
if (!used.has(candidate) && !existsSync(candidate)) {
used.add(candidate);
return candidate;
}
index++;
}
}
export async function downloadBillAttachments(
client: KyInstance,
corpId: string,
target: string,
outputDir: string,
fileId?: string,
): Promise<{
target: string;
outputDir: string;
requestedFileId?: string;
downloaded: DownloadedBillAttachment[];
skipped: number;
report: BillAttachmentReport;
}> {
const report = await getBillAttachments(client, corpId, target);
if (!report) throw new NotFoundError(`未找到单据附件: ${target}`);
const selected = fileId
? report.attachments.filter((item) => item.fileId === fileId)
: report.attachments;
if (fileId && selected.length === 0) {
throw new NotFoundError(`单据 ${target} 中未找到附件 fileId: ${fileId}`);
}
const destination = resolve(outputDir);
await mkdir(destination, { recursive: true });
const usedPaths = new Set<string>();
const downloaded: DownloadedBillAttachment[] = [];
let skipped = 0;
for (const attachment of selected) {
if (!attachment.url) {
skipped++;
continue;
}
const sourceName = attachment.fileName || attachment.key || attachment.fileId || "attachment";
const path = uniqueAttachmentPath(destination, safeAttachmentName(sourceName), attachment.fileId, usedPaths);
const response = await fetch(attachment.url);
if (!response.ok) {
throw new EkbApiError(`附件下载失败 (${response.status}): ${sourceName}`, "ATTACHMENT_DOWNLOAD_FAILED", response.status);
}
const content = new Uint8Array(await response.arrayBuffer());
await writeFile(path, content);
downloaded.push({
fileId: attachment.fileId,
fileName: attachment.fileName,
key: attachment.key,
path,
bytes: content.byteLength,
});
}
return {
target,
outputDir: destination,
requestedFileId: fileId,
downloaded,
skipped,
report,
};
}
// ── 格式化单据数据 ─────────────────────────────────────────────────────────────
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,
};
}
export function formatFlowAsBill(
raw: Record<string, unknown>,
dictionary: Map<string, { label: string; type: string }>
): FormattedBill {
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 billCode = (typeof form.code === "string" && form.code.trim()) || (typeof flow.id === "string" ? flow.id : String(raw.id || ""));
const title = (typeof form.title === "string" && form.title.trim()) || (typeof flow.title === "string" ? flow.title : undefined);
const billName = title || (flow.formType === "requisition" ? "差旅申请单" : "审批单据");
const stage = typeof flow.formType === "string" ? flow.formType : "flow";
const state = raw.nodeName
? `${raw.state || flow.state || "APPROVING"} (${raw.nodeName})`
: (typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : "APPROVING");
let amountStr: string | undefined;
for (const key of ["requisitionMoney", "amount", "expenseMoney", "payMoney"]) {
const val = form[key];
if (val && typeof val === "object" && (val as any).standard !== undefined) {
const money = val as any;
amountStr = `${money.standardSymbol || "¥"}${money.standard} ${money.standardStrCode || "CNY"}`.trim();
break;
}
}
let submitterId: string | undefined;
const submitter = form.submitterId as Record<string, unknown> | undefined;
if (submitter && typeof submitter === "object") {
const name = submitter.name || "";
const code = submitter.code ? ` (${submitter.code})` : "";
const dept = (submitter.defaultDepartment as Record<string, unknown>)?.name;
submitterId = `${name}${code}${dept ? ` - ${dept}` : ""}`.trim();
} else if (typeof form.submitterId === "string") {
submitterId = form.submitterId;
}
let submitDateStr: string | undefined;
if (typeof form.submitDate === "number" && form.submitDate > 1000000000000) {
submitDateStr = new Date(form.submitDate).toLocaleString("zh-CN");
}
const createTimeNum = typeof flow.createTime === "number" ? flow.createTime : typeof raw.createTime === "number" ? raw.createTime : 0;
const updateTimeNum = typeof flow.updateTime === "number" ? flow.updateTime : typeof raw.updateTime === "number" ? raw.updateTime : 0;
const createTimeStr = createTimeNum > 0 ? new Date(createTimeNum).toLocaleString("zh-CN") : "";
const updateTimeStr = updateTimeNum > 0 ? new Date(updateTimeNum).toLocaleString("zh-CN") : "";
const readableDetails: Record<string, any> = {};
if (raw.nodeName) readableDetails["当前节点"] = raw.nodeName;
if (raw.id) readableDetails["任务 ID"] = raw.id;
if (flow.id) readableDetails["流程 ID"] = flow.id;
if (flow.formType) readableDetails["表单类型"] = flow.formType;
const detailsArray = Array.isArray(form.details) ? form.details : [];
if (detailsArray.length > 0) {
readableDetails["费用明细条数"] = `${detailsArray.length} 笔`;
detailsArray.forEach((item, idx) => {
const feeForm = (item.feeTypeForm && typeof item.feeTypeForm === "object" ? item.feeTypeForm : {}) as Record<string, unknown>;
const feeTypeId = typeof item.feeTypeId === "string" ? item.feeTypeId.split(":").at(-1) || item.feeTypeId : "费用";
let rowMoney = "";
if (feeForm.amount && typeof feeForm.amount === "object") {
const m = feeForm.amount as any;
rowMoney = `${m.standardSymbol || "¥"}${m.standard} ${m.standardStrCode || "CNY"}`.trim();
}
let cityStr = "";
if (typeof feeForm.city === "string") {
try {
const parsedCity = JSON.parse(feeForm.city);
if (Array.isArray(parsedCity) && parsedCity[0]?.label) {
cityStr = parsedCity[0].label;
} else {
cityStr = feeForm.city;
}
} catch {
cityStr = feeForm.city;
}
}
let dateStr = "";
if (typeof feeForm.feeDate === "number" && feeForm.feeDate > 1000000000000) {
dateStr = new Date(feeForm.feeDate).toLocaleDateString("zh-CN");
}
const reason = feeForm.consumptionReasons || feeForm.reason || "";
const attachments = Array.isArray(feeForm.attachments) ? feeForm.attachments.length : 0;
const summaryParts = [
`[${feeTypeId}]`,
cityStr,
rowMoney,
dateStr,
reason ? `事由: ${reason}` : "",
`附件: ${attachments} 个`,
].filter(Boolean);
readableDetails[`明细 #${idx + 1}`] = summaryParts.join(" | ");
if (reason) readableDetails[`明细 #${idx + 1} 事由`] = reason;
if (cityStr) readableDetails[`明细 #${idx + 1} 城市`] = cityStr;
});
}
for (const [k, v] of Object.entries(form)) {
if (["code", "title", "details", "submitterId", "submitDate", "requisitionMoney", "amount", "expenseMoney", "logs", "flowPlanId"].includes(k)) continue;
if (v === null || v === undefined || v === "") continue;
const meta = dictionary.get(k);
const bareKey = k.replace(/^E_[^_]+_/, "").replace(/^E_/, "");
const label = meta ? meta.label : (COMMON_FIELD_LABELS[k] || COMMON_FIELD_LABELS[bareKey] || k);
if (typeof v === "object") {
readableDetails[label] = JSON.stringify(v);
} else {
readableDetails[label] = v;
}
}
return {
billId: String(flow.id || raw.id || ""),
billCode,
billName,
title,
stage,
state,
amount: amountStr,
submitterId,
submitDate: submitDateStr,
corporationId: String(flow.corporationId || raw.corporationId || ""),
ownerId: typeof flow.ownerId === "object" ? (flow.ownerId as any)?.name : typeof flow.ownerId === "string" ? flow.ownerId : undefined,
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 检索
}
}
// 1.1 如果是典型单据编号特征(如 B26010730、R2023...),优先走审批流通道检索,避免 invoice/search 接口慢超时
if (/^[A-Za-z][A-Za-z0-9_-]+$/.test(cleanQuery)) {
try {
const rawFlow = await getRawBillFlow(client, corpId, cleanQuery);
if (rawFlow) {
return [formatFlowAsBill(rawFlow, dictionary)];
}
} catch {
// 容错并继续回退到传统单据检索
}
}
// 2. 从 search 中匹配单号、flowCode、ID 或关联 LinkId(带 5s 超时与容错降级)
try {
const searchRes = await searchRawBills(client, corpId, { start: 0, count: 50, timeout: 5000 });
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;
});
if (matched.length > 0) {
return matched.map((it) => formatSingleBill(it, dictionary));
}
} catch {
// 忽略 invoice/search 超时或错误,平滑回退
}
// 3. 回退到审批流程/待办接口检索(支持申请单 Requisition、借款单、自由流待办)
try {
const rawFlow = await getRawBillFlow(client, corpId, cleanQuery);
if (rawFlow) {
return [formatFlowAsBill(rawFlow, dictionary)];
}
} catch {
// 忽略流程回退错误
}
return [];
}
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, index) => {
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 currentTime = typeof log.time === "number" ? log.time : undefined;
const nextLog = logs[index + 1] && typeof logs[index + 1] === "object" ? logs[index + 1] as Record<string, unknown> : undefined;
const nextTime = typeof nextLog?.time === "number" ? nextLog.time : undefined;
const durationMs = currentTime !== undefined && nextTime !== undefined && nextTime >= currentTime ? nextTime - currentTime : undefined;
const nextOperators = Array.isArray(log.nextOperatorIds)
? log.nextOperatorIds.map(flowPerson).filter((person): person is NonNullable<typeof person> => Boolean(person))
: [];
const operator = flowPerson(log.operatorId);
const isEbot = attributes.isEbotNode === true || `${operator?.id || ""} ${operator?.name || ""}`.toLowerCase().includes("ebot");
const labeledOperator = isEbot
? { ...(operator || { id: "ebot" }), name: "Ebot (智能审批)" }
: operator;
const rawAction = typeof log.action === "string" ? log.action : undefined;
const rawState = typeof log.state === "string" ? log.state : undefined;
return {
id: typeof log.id === "string" ? log.id : undefined,
time: currentTime,
durationMs,
state: translateBillFlowState(rawState),
rawState,
action: translateBillFlowAction(rawAction),
rawAction,
nodeName: typeof attributes.nodeName === "string" && attributes.nodeName
? attributes.nodeName
: typeof attributes.nextName === "string" && attributes.nextName
? attributes.nextName
: translateBillFlowAction(rawAction) === "打印单据" ? "打印提醒" : undefined,
comment: typeof attributes.comment === "string" && attributes.comment ? attributes.comment : undefined,
automatic: attributes.isEbotNode === true || attributes.isAuto === true || !log.operatorId,
skipped: attributes.isSkip === true || attributes.skipped === true || log.state === "SKIPPED",
operator: labeledOperator,
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 ? "当前" : "后续",
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: translateBillFlowState(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,
};
}
function resolveFlowStage(
rawState: string,
nodeType?: string
): "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN" {
const s = rawState.toUpperCase();
const n = (nodeType || "").toUpperCase();
if (s.includes("REJECT") || s === "TERMINATED") return "REJECTED";
if (s === "PAID" || s === "COMPLETED" || s === "PROCESSED") return "PAID";
if (s.includes("PAY") || ["PAYMENT", "PAY", "CASHIER"].includes(n)) return "PAYING";
if (s.includes("APPROV") || s === "PENDING" || s === "SENDING") return "APPROVING";
if (s.includes("DRAFT")) return "DRAFT";
return "UNKNOWN";
}
function buildDiagnosticReport(
stage: "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN",
rawState: string,
currentNodeName?: string,
pendingApprovers: { id?: string; name?: string; code?: string }[] = []
): {
canApprove: boolean | null;
stage: "DRAFT" | "APPROVING" | "PAYING" | "PAID" | "REJECTED" | "UNKNOWN";
stageLabel: string;
summary: string;
advice: string;
} {
const approverNames = pendingApprovers.map((p) => p.name || p.id).filter(Boolean).join("、");
switch (stage) {
case "PAYING":
return {
canApprove: false,
stage,
stageLabel: "待支付 / 出纳打款",
summary: `单据已通过全部分级审批流转,当前停留在【${currentNodeName || "出纳打款"}】环节`,
advice: "流程处于支付环节。请先核对实际待办与操作权限;无待办时调用审批接口可能返回 400。若工作流误触发支付阶段单据,请核对触发条件与流程状态。",
};
case "APPROVING":
return {
canApprove: null,
stage,
stageLabel: "审批中 (待办审批)",
summary: `单据当前停留在【${currentNodeName || "审批"}】节点${approverNames ? `,待办审批人: ${approverNames}` : ""}`,
advice: "单据处于审批阶段;所列人员来自当前节点配置。执行同意或驳回前,仍需核对当前身份的实际待办与审批权限。",
};
case "REJECTED":
return {
canApprove: false,
stage,
stageLabel: "已驳回 / 已终止",
summary: "单据已流转至驳回或终止状态",
advice: "单据已终止流转,无法执行审批同意。请联系提报人员根据驳回意见重新修改并提交新单据。",
};
case "PAID":
return {
canApprove: false,
stage,
stageLabel: "已闭环 / 已打款",
summary: "单据全流程已审批并通过出纳打款闭环",
advice: "单据已结束流转,无需任何人工或自动化操作。",
};
case "DRAFT":
return {
canApprove: false,
stage,
stageLabel: "草稿未提交",
summary: "单据尚未正式提交进入审批流",
advice: "请提报人完成单据填写后点击提交。",
};
default:
return {
canApprove: null,
stage,
stageLabel: rawState || "未知状态",
summary: `单据当前处于状态: ${rawState || "未知"}`,
advice: "请通过 Web 后台或联系管理员核对单据流转配置。",
};
}
}
/**
* 全域单据穿透诊断与待办全貌洞察
* options.skipInvoices 仅保留旧 SDK 调用兼容性;此诊断不补充加载发票详情。
*/
export async function traceBillFlowDetail(
client: KyInstance,
corpId: string,
targetQuery: string,
options?: { skipInvoices?: boolean }
): Promise<BillFlowTraceDiagnostic> {
const cleanTarget = targetQuery.trim();
if (!cleanTarget) {
throw new ValidationError("请提供要穿透查询的单号或单据 ID");
}
// 1. 尝试直接获取流程全貌
let rawFlow = await getRawBillFlow(client, corpId, cleanTarget);
// 2. 如果直接流程未命中,尝试通过传统单据索引反查
if (!rawFlow) {
try {
const bills = await getBillByCodeOrId(client, corpId, cleanTarget);
if (bills.length > 0) {
const firstBill = bills[0];
const candidateId = firstBill.billId || firstBill.billCode;
if (candidateId) {
rawFlow = await getRawBillFlow(client, corpId, candidateId);
}
}
} catch {
// 容错并继续
}
}
if (!rawFlow) {
return {
found: false,
target: cleanTarget,
pendingApprovers: [],
diagnostic: {
canApprove: false,
stage: "UNKNOWN",
stageLabel: "未找到",
summary: `在当前企业下未找到匹配 "${cleanTarget}" 的单据或流程实例`,
advice: "请核对单号是否准确,或确认当前账号是否具备该业务流程的查看权限。",
},
timeline: [],
};
}
const flow = rawFlow.flowId && typeof rawFlow.flowId === "object" ? (rawFlow.flowId as Record<string, unknown>) : {};
const form = flow.form && typeof flow.form === "object" ? (flow.form as Record<string, unknown>) : ((rawFlow.form as Record<string, unknown>) || {});
const spec = form.specificationId && typeof form.specificationId === "object" ? (form.specificationId as Record<string, unknown>) : {};
const nodeState = rawFlow.nodeState && typeof rawFlow.nodeState === "object" ? (rawFlow.nodeState as Record<string, unknown>) : {};
const plan = flow.plan && typeof flow.plan === "object" ? (flow.plan as Record<string, unknown>) : {};
const nodes = Array.isArray(plan.nodes) ? (plan.nodes as Record<string, unknown>[]) : [];
const logs = Array.isArray(flow.logs) ? (flow.logs as Record<string, unknown>[]) : [];
// 基础信息提取
const billCode = typeof form.code === "string" ? form.code : typeof rawFlow.code === "string" ? rawFlow.code : undefined;
const billId = typeof rawFlow.id === "string" ? rawFlow.id : typeof form.id === "string" ? form.id : undefined;
const flowId = typeof flow.id === "string" ? flow.id : undefined;
const backlogId = typeof rawFlow.id === "string" ? rawFlow.id : undefined;
const specificationName = typeof spec.name === "string" ? spec.name : undefined;
const specificationId = typeof spec.id === "string" ? spec.id : undefined;
const title = typeof form.title === "string" ? form.title : typeof form.name === "string" ? form.name : undefined;
// 金额提取
let amountStr: string | undefined;
const rawMoney = form.expenseMoney || form.payMoney || form.loanMoney || form.requisitionMoney || form.amount;
if (rawMoney && typeof rawMoney === "object") {
const std = (rawMoney as any).standard ?? (rawMoney as any).amount;
if (std !== undefined) amountStr = `¥ ${std}`;
} else if (typeof rawMoney === "string" || typeof rawMoney === "number") {
amountStr = `¥ ${rawMoney}`;
}
// 提交人与部门
const submitter = flowPerson(form.submitterId || flow.ownerId);
const deptObj = form.expenseDepartment || form.defaultDepartment;
const department = deptObj && typeof deptObj === "object" ? (deptObj as any).name : undefined;
const submitDate = typeof form.submitDate === "number" ? new Date(form.submitDate).toLocaleString("zh-CN", { hour12: false }) : undefined;
// 状态提取
const rawState = String(flow.state || rawFlow.state || form.state || "").toUpperCase();
const stateLabel = translateBillFlowState(rawState);
// 当前驻留节点提取
const nextNodeId = typeof plan.nextNodeId === "string" ? plan.nextNodeId : undefined;
const currentNodeName = typeof rawFlow.nodeName === "string" ? rawFlow.nodeName : typeof nodeState.nodeName === "string" ? nodeState.nodeName : undefined;
let activeNode = nodes.find((n) => (nextNodeId && n.id === nextNodeId) || (currentNodeName && n.name === currentNodeName));
if (!activeNode && nodes.length > 0) {
activeNode = nodes.find((n) => n.state === "APPROVING" || n.state === "approving" || n.status === "ACTIVE");
}
const currentNode = activeNode
? {
id: typeof activeNode.id === "string" ? activeNode.id : undefined,
name: typeof activeNode.name === "string" ? activeNode.name : currentNodeName,
type: typeof activeNode.type === "string" ? activeNode.type : undefined,
}
: currentNodeName
? { name: currentNodeName }
: undefined;
// 待办审批人提取
const pendingApprovers: { id?: string; name?: string; code?: string }[] = [];
if (activeNode) {
if (activeNode.approverId) {
const p = flowPerson(activeNode.approverId);
if (p) pendingApprovers.push(p);
}
if (Array.isArray(activeNode.counterSigners)) {
for (const signer of activeNode.counterSigners) {
const p = flowPerson(signer);
if (p) pendingApprovers.push(p);
}
}
}
// 诊断规则引擎
const stage = resolveFlowStage(rawState, currentNode?.type);
const diagnostic = buildDiagnosticReport(stage, rawState, currentNode?.name, pendingApprovers);
// 流转时间线
const timeline: BillFlowTimelineItem[] = logs.map((log, index) => {
const attrs = (log.attributes as Record<string, unknown>) || {};
const op = flowPerson(log.operatorId);
const isEbot = attrs.isEbotNode === true || `${op?.id || ""} ${op?.name || ""}`.toLowerCase().includes("ebot");
const labeledOp = isEbot ? { ...(op || { id: "ebot" }), name: "Ebot (智能审批)" } : op;
const timeNum = typeof log.time === "number" ? log.time : undefined;
return {
index: index + 1,
time: timeNum ? new Date(timeNum).toLocaleString("zh-CN", { hour12: false }) : undefined,
timestamp: timeNum,
action: translateBillFlowAction(typeof log.action === "string" ? log.action : undefined),
rawAction: typeof log.action === "string" ? log.action : undefined,
state: translateBillFlowState(typeof log.state === "string" ? log.state : undefined),
rawState: typeof log.state === "string" ? log.state : undefined,
nodeName: typeof attrs.nodeName === "string" ? attrs.nodeName : typeof attrs.nextName === "string" ? attrs.nextName : undefined,
operator: labeledOp,
comment: typeof attrs.comment === "string" ? attrs.comment.replace(/<[^>]+>/g, "").trim() : undefined,
automatic: attrs.isEbotNode === true || attrs.isAuto === true || !log.operatorId,
skipped: attrs.isSkip === true || attrs.skipped === true || log.state === "SKIPPED",
};
});
return {
found: true,
target: cleanTarget,
billCode,
billId,
flowId,
backlogId,
specificationName,
specificationId,
title,
amount: amountStr,
submitter,
department,
submitDate,
state: stateLabel,
rawState,
currentNode,
pendingApprovers,
diagnostic,
timeline,
raw: rawFlow,
};
}
function actionTarget(raw: Record<string, unknown>, fallback: string): BillActionTarget {
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 backlogId = typeof raw.id === "string" ? raw.id : fallback;
const flowId = typeof flow.id === "string" ? flow.id : undefined;
if (!flowId) throw new NotFoundError(`未找到单据流程 ID: ${fallback}`);
const plan = flow.plan && typeof flow.plan === "object" ? flow.plan as Record<string, unknown> : {};
const nodes = Array.isArray(plan.nodes) ? plan.nodes : [];
const nodeName = typeof raw.nodeName === "string" ? raw.nodeName : undefined;
const currentNode = nodes.find((value) => {
const node = value && typeof value === "object" ? value as Record<string, unknown> : {};
return typeof raw.nodeId === "string" && node.id === raw.nodeId || nodeName && node.name === nodeName;
});
return {
backlogId,
flowId,
billId: flowId,
billCode: typeof form.code === "string" ? form.code : undefined,
nodeId: typeof raw.nodeId === "string" ? raw.nodeId : currentNode && typeof currentNode === "object" && typeof (currentNode as Record<string, unknown>).id === "string" ? (currentNode as Record<string, unknown>).id as string : undefined,
nodeName,
raw,
};
}
async function resolveActionTarget(client: KyInstance, corpId: string, target: string): Promise<BillActionTarget> {
const raw = await getRawBillFlow(client, corpId, target);
if (!raw) throw new NotFoundError(`未找到单据或审批任务: ${target}`);
return actionTarget(raw, target);
}
export interface BillActionResult {
action: "approve" | "reject" | "transfer" | "add-node" | "comment";
corpId: string;
target: string;
backlogId: string;
flowId: string;
billId?: string;
billCode?: string;
nodeId?: string;
response?: unknown;
}
export async function resolveBillStaffIds(
client: KyInstance,
corpId: string,
values: string[],
): Promise<string[]> {
const catalog = await listActiveStaffCatalog(client, corpId);
const normalized = (value: string) => value.trim().toLowerCase();
const matchesFor = (value: string) => {
const target = normalized(value);
return catalog.filter((staff) => {
const id = typeof staff.id === "string" ? staff.id : "";
const userId = typeof staff.userId === "string" ? staff.userId : "";
const name = typeof staff.name === "string" ? staff.name : "";
const code = typeof staff.code === "string" ? staff.code : "";
return [id, userId, name, code].some((candidate) => {
const lowered = normalized(candidate);
return lowered === target || lowered.endsWith(`:${target}`);
});
});
};
const result: string[] = [];
for (const value of values) {
const matches = matchesFor(value);
if (matches.length !== 1) {
if (matches.length > 1) throw new ValidationError(`员工关键词 [${value}] 匹配到多人,请改用员工 ID 或工号`);
throw new NotFoundError(`未找到员工 [${value}]`);
}
const id = typeof matches[0]?.id === "string" ? matches[0].id : undefined;
if (!id) throw new BusinessError(`员工 [${value}] 缺少可用 ID`);
result.push(id);
}
return result;
}
async function runBillAction(
client: KyInstance,
corpId: string,
target: string,
action: BillActionResult["action"],
options: BillActionOptions = {},
): Promise<BillActionResult> {
const resolved = await resolveActionTarget(client, corpId, target);
if (options.currentStaffId && action !== "comment") {
const flow = resolved.raw.flowId && typeof resolved.raw.flowId === "object" ? resolved.raw.flowId as Record<string, unknown> : {};
const actions = flow.actions && typeof flow.actions === "object" ? flow.actions as Record<string, unknown> : undefined;
if (actions && Object.keys(actions).length > 0) {
const current = options.currentStaffId;
const currentTail = current.split(":").at(-1) || current;
const entry = Object.entries(actions).find(([staffId]) => {
const staffTail = staffId.split(":").at(-1) || staffId;
return staffId === current || staffId.endsWith(`:${current}`) || current.endsWith(`:${staffId}`) || staffTail === currentTail;
});
const allowed = entry?.[1];
const requiredAction = action === "approve" ? "freeflow.agree" : action === "reject" ? "freeflow.reject" : "freeflow.addnode";
if (!Array.isArray(allowed) || !allowed.includes(requiredAction)) {
throw new PermissionError(`当前账号不是该节点的合法待办人,不能执行 ${action} 动作`);
}
}
}
let response: unknown;
if (action === "approve") response = await approveBillAction(client, corpId, resolved, options);
else if (action === "reject") response = await rejectBillAction(client, corpId, resolved, options);
else if (action === "transfer") response = await transferBillAction(client, corpId, resolved, options);
else if (action === "add-node") response = await addNodeBillAction(client, corpId, resolved, options);
else response = await commentBillAction(client, corpId, resolved, options);
return {
action,
corpId,
target,
backlogId: resolved.backlogId,
flowId: resolved.flowId,
billId: resolved.billId,
billCode: resolved.billCode,
nodeId: resolved.nodeId,
response,
};
}
export function approveBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
return runBillAction(client, corpId, target, "approve", options);
}
export function rejectBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
if (!options.comment?.trim()) throw new ValidationError("驳回原因不能为空");
return runBillAction(client, corpId, target, "reject", options);
}
export function transferBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
if (!options.approverIds?.length) throw new ValidationError("转交审批至少需要一个 approverId");
return runBillAction(client, corpId, target, "transfer", options);
}
export function addNodeBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
if (!options.approverIds?.length) throw new ValidationError("加签审批至少需要一个 approverId");
return runBillAction(client, corpId, target, "add-node", options);
}
export function commentBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
if (!options.comment?.trim()) throw new ValidationError("评论内容不能为空");
return runBillAction(client, corpId, target, "comment", options);
}
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 function parseDateFilter(value: string | number | undefined, isEnd = false): number | undefined {
if (value === undefined || value === "") return undefined;
if (typeof value === "number") return value;
const trimmed = String(value).trim();
if (!trimmed) return undefined;
if (/^\d+$/.test(trimmed)) return Number(trimmed);
const parsed = Date.parse(trimmed);
if (!Number.isNaN(parsed)) {
if (isEnd && /^\d{4}-\d{2}-\d{2}$/.test(trimmed)) {
const d = new Date(parsed);
d.setHours(23, 59, 59, 999);
return d.getTime();
}
return parsed;
}
return undefined;
}
export function parseSinceDuration(since: string | undefined): number | undefined {
if (!since) return undefined;
const match = /^(\d+)([dhmyw])$/i.exec(since.trim());
if (!match) return undefined;
const count = Number(match[1]);
const unit = match[2].toLowerCase();
const MS_PER_HOUR = 3600 * 1000;
const MS_PER_DAY = 24 * MS_PER_HOUR;
switch (unit) {
case "h": return count * MS_PER_HOUR;
case "d": return count * MS_PER_DAY;
case "w": return count * 7 * MS_PER_DAY;
case "m": return count * 30 * MS_PER_DAY;
case "y": return count * 365 * MS_PER_DAY;
default: return undefined;
}
}
export function normalizeSearchFields(fields?: string[] | string): string[] {
if (!fields) return ["name", "code", "form"];
if (Array.isArray(fields)) {
const list = fields.map((f) => f.trim()).filter(Boolean);
return list.length > 0 ? list : ["name", "code", "form"];
}
const list = fields.split(",").map((f) => f.trim()).filter(Boolean);
return list.length > 0 ? list : ["name", "code", "form"];
}
export function buildServerBillFilterBy(params: BillQueryParams): string | undefined {
if (params.filterBy && params.filterBy.trim()) {
return params.filterBy.trim();
}
const parts: string[] = [];
// 1. active 软删除过滤 (使用 .in 避免 CloudWAF 误拦截)
if (params.active !== false) {
parts.push("(active.in(true))");
} else if (params.active === false) {
parts.push("(active.in(false))");
}
// 2. 时间范围过滤
let fromTime = params.from ?? parseDateFilter(params.startDate);
if (params.since) {
const duration = parseSinceDuration(params.since);
if (duration !== undefined) {
fromTime = Math.max(fromTime ?? 0, Date.now() - duration);
}
}
const toTime = params.to ?? parseDateFilter(params.endDate, true);
if (fromTime !== undefined) {
parts.push(`(createTime > ${fromTime})`);
}
if (toTime !== undefined) {
parts.push(`(createTime < ${toTime})`);
}
// 3. 单号服务端过滤 (使用 .in 避免 CloudWAF 误拦截)
if (params.code && params.code.trim()) {
parts.push(`(code.in(${JSON.stringify(params.code.trim())}))`);
}
// 4. 关键字跨字段检索 (支持通过 searchFields 指定单字段或多字段联合 RQL)
if (params.keyword && params.keyword.trim()) {
const kw = params.keyword.trim();
const fields = normalizeSearchFields(params.searchFields);
if (fields.length === 1) {
parts.push(`(INSTR(${fields[0]}, ${JSON.stringify(kw)}) > 0)`);
} else {
const fieldParts = fields.map(
(f) => `(INSTR(${f}, ${JSON.stringify(kw)}) > 0)`
);
parts.push(`(${fieldParts.join(" || ")})`);
}
}
if (parts.length === 0) return undefined;
if (parts.length === 1) return parts[0];
return `(${parts.join(" && ")})`;
}
export async function searchAndFormatBills(
client: KyInstance,
corpId: string,
params: BillQueryParams = {}
): Promise<BillPageResult> {
const { dictionary } = await getFieldDictionary(client, corpId);
const filterBy = buildServerBillFilterBy(params);
const sortDirection = (params.order || "DESC").toUpperCase() as "ASC" | "DESC";
const orderBy = params.orderBy && params.orderBy.length > 0
? params.orderBy
: [{ value: "createTime", order: sortDirection }];
let searchRes: RawBillSearchResponse;
try {
searchRes = await searchRawBills(client, corpId, {
start: params.start ?? 0,
count: params.count ?? 20,
filterBy,
orderBy,
select: params.select || "id,code,name,createTime,updateTime,form,active",
distinct: params.distinct,
join: params.join,
});
} catch (err) {
if (String(err).includes("timed out") || (err as any)?.name === "TimeoutError") {
throw new EkbApiError(
`全局单据台账检索超时。在大企业或海量单据租户中,建议指定时间范围或单号筛选:\n` +
`建议:\n` +
` - 指定时间范围:hose-use bill list --since=7d 或 --start-date=2026-09-01\n` +
` - 查看当前员工发起的单据:hose-use task submitted 或 hose-use bill list --mine\n` +
` - 查看待我审批单据:hose-use task todo\n` +
` - 按单号精确查询:hose-use bill get <单号>`,
"BILL_SEARCH_TIMEOUT",
504
);
}
throw err;
}
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();
const fields = normalizeSearchFields(params.searchFields);
filtered = filtered.filter((it) => {
if (fields.includes("name") && it.name?.toLowerCase().includes(kw)) return true;
if (fields.includes("code") && it.code?.toLowerCase().includes(kw)) return true;
if (fields.includes("form")) {
for (const v of Object.values(it.form || {})) {
if (typeof v === "string" && v.toLowerCase().includes(kw)) return true;
}
}
for (const field of fields) {
if (field !== "name" && field !== "code" && field !== "form") {
const val = (it as any)[field] ?? (it.form as any)?.[field];
if (typeof val === "string" && val.toLowerCase().includes(kw)) return true;
}
}
return false;
});
}
const formattedItems = filtered.map((it) => formatSingleBill(it, dictionary));
return {
total: searchRes.count,
returned: formattedItems.length,
items: formattedItems,
};
}
export async function getTranslatorContext(
client: KyInstance,
corpId: string,
rawFlow?: Record<string, unknown>,
options?: { skipInvoices?: boolean }
): Promise<TranslatorOptions> {
const [feeTypeTree, catalog, dimEntity, dimBiz, dimBool] = await Promise.allSettled([
getFeeTypeTree(client, corpId),
getReferenceCatalog(client, corpId),
resolveDimension(client, corpId, "法人实体"),
resolveDimension(client, corpId, "业务类型"),
resolveDimension(client, corpId, "是否"),
]);
const feeTypeMap = new Map<string, { name?: string; path?: string }>();
if (feeTypeTree.status === "fulfilled") {
const flat = flattenFeeTypes(feeTypeTree.value);
for (const [id, val] of flat.entries()) {
feeTypeMap.set(id, { name: val.name as string, path: val.path as string });
}
}
const staffMap = catalog.status === "fulfilled" ? catalog.value.staff : undefined;
const departmentMap = catalog.status === "fulfilled" ? catalog.value.departments : undefined;
const dimensionItemMap = new Map<string, { name?: string; code?: string; label?: string }>();
for (const dimRes of [dimEntity, dimBiz, dimBool]) {
if (dimRes.status === "fulfilled" && dimRes.value?.items) {
for (const item of dimRes.value.items) {
dimensionItemMap.set(item.id, { name: item.name, code: item.code });
}
}
}
const invoiceDetailMap = new Map<string, Record<string, unknown>>();
const datalinkCardMap = new Map<string, string>();
if (rawFlow) {
const flowIdObj = (rawFlow.flowId && typeof rawFlow.flowId === "object" ? rawFlow.flowId : rawFlow) as Record<string, any>;
const form = (flowIdObj.form && typeof flowIdObj.form === "object" ? flowIdObj.form : {}) as Record<string, any>;
// 1. 扫描所有发票 invoiceId
const invoiceIds = new Set<string>();
const details = Array.isArray(form.details) ? form.details : [];
for (const d of details) {
const ftf = d?.feeTypeForm || d || {};
const invs = ftf.invoiceForm?.invoices || ftf.invoices || [];
if (Array.isArray(invs)) {
for (const inv of invs) {
const id = inv.invoiceId || inv.id;
if (typeof id === "string" && id) invoiceIds.add(id);
}
}
}
const invoiceFetches = options?.skipInvoices
? []
: Array.from(invoiceIds).map(async (id) => {
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const deadline = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
controller.abort();
reject(new Error("Invoice timeout"));
}, 3000);
});
const detail = await Promise.race([
getInvoiceValidationDetail(client, corpId, id, { signal: controller.signal }),
deadline,
]);
if (detail) invoiceDetailMap.set(id, detail);
} catch {
// 单张发票详情超时或获取失败不阻断整体流程解析
} finally {
clearTimeout(timer);
}
});
// 2. 扫描数据连接/卡片 ID (例如供应商 ID01...,payeeId 等)
const cardCandidateIds = new Set<string>();
for (const [_, v] of Object.entries(form)) {
if (typeof v === "string" && v.startsWith("ID01")) {
if (!dimensionItemMap.has(v)) {
cardCandidateIds.add(v);
}
}
}
const cardFetches = Array.from(cardCandidateIds).map(async (cardId) => {
const cardVal = await getDatalinkCard(client, corpId, cardId);
const cardObj = (cardVal?.data as any)?.dataLink || (cardVal?.data as any)?.form || cardVal?.data;
if (cardObj && typeof cardObj === "object") {
const parts: string[] = [];
let suppName = "";
let suppCode = "";
let bankCard = "";
let payeeInfoStr = "";
let payeeInfoDirect = "";
for (const [fieldKey, fieldVal] of Object.entries(cardObj)) {
if (fieldKey.endsWith("_name") || fieldKey.includes("供应商名称")) {
suppName = String(fieldVal);
} else if (fieldKey.endsWith("_code") || fieldKey.includes("供应商编码")) {
suppCode = String(fieldVal);
} else if (fieldKey.includes("银行卡号") || fieldKey.includes("卡号")) {
bankCard = String(fieldVal);
} else if (fieldKey.includes("收款信息") && typeof fieldVal === "object" && fieldVal !== null) {
const pi = fieldVal as Record<string, any>;
const piParts: string[] = [];
const directParts: string[] = [];
const accountName = pi.name || pi.accountName || pi.accountOwner;
const accountNo = pi.cardNo || pi.account;
const accountType = (pi.type || pi.accountType) === "PUBLIC" ? "对公账户" : (pi.type || pi.accountType);
const accountSort = pi.sort || pi.accountCategory || pi.accountClass;
const bankName = pi.bank || pi.bankName;
const branchName = pi.branch || pi.openBankName;
if (accountName) piParts.push(`开户名=${accountName}`);
if (accountNo) piParts.push(`账号=${accountNo}`);
if (accountType) piParts.push(`账户类型=${accountType}`);
if (accountSort) piParts.push(`账户类别=${accountSort}`);
if (bankName) piParts.push(`银行=${bankName}`);
if (branchName) piParts.push(`开户网点=${branchName}`);
if (piParts.length > 0) {
payeeInfoStr = piParts.join(";");
}
if (accountNo) directParts.push(`账号=${accountNo}`);
if (bankName) directParts.push(`银行=${bankName}`);
if (accountName) directParts.push(`开户名=${accountName}`);
if (branchName) directParts.push(`开户网点=${branchName}`);
if (accountType) directParts.push(`账户类型=${accountType}`);
if (accountSort) directParts.push(`账户类别=${accountSort}`);
if (directParts.length > 0) {
payeeInfoDirect = directParts.join(";");
}
}
}
if (suppName) parts.push(`供应商名称=${suppName}`);
if (suppCode) parts.push(`供应商编码=${suppCode}`);
if (bankCard) parts.push(`银行卡号=${bankCard}`);
if (payeeInfoStr) parts.push(`收款信息=${payeeInfoStr}`);
if (parts.length > 0) {
datalinkCardMap.set(cardId, parts.join(";"));
}
if (payeeInfoDirect || payeeInfoStr) {
const valToSet = payeeInfoDirect || payeeInfoStr;
datalinkCardMap.set(`payeeInfo:${cardId}`, valToSet);
if (suppCode) datalinkCardMap.set(suppCode, valToSet);
}
}
});
await Promise.allSettled([...invoiceFetches, ...cardFetches]);
}
return {
feeTypeMap,
staffMap,
departmentMap,
dimensionItemMap,
invoiceDetailMap,
datalinkCardMap,
};
}
export function formatFormPriorityList(priorityList: FormPriorityItem[] | undefined): string {
if (!Array.isArray(priorityList) || priorityList.length === 0) return "-";
const sorted = [...priorityList].sort((a, b) => b.priority - a.priority);
return sorted.map((p) => `${p.type}(${p.priority})`).join(" > ");
}
export function hasLinkageOverridePriority(priorityList: FormPriorityItem[] | undefined): boolean {
if (!Array.isArray(priorityList) || priorityList.length === 0) return false;
const linkage = priorityList.find((p) => p.type === "LINKAGE_ASSIGNMENT");
const manual = priorityList.find((p) => p.type === "MANUALLY_FILL_IN");
if (!linkage || !manual) return false;
return linkage.priority > manual.priority;
}
export interface FormSpecificationInspection {
specification: FormSpecification;
warnings: string[];
}
export async function inspectFormSpecification(
client: KyInstance,
corpId: string,
specificationId: string
): Promise<FormSpecificationInspection | undefined> {
const spec = await getFormSpecification(client, corpId, specificationId);
if (!spec) return undefined;
const warnings: string[] = [];
const linkageSources = spec.components.filter(
(c) => c.isLinkageAssignment === true || Boolean(c.assignmentRule)
);
const overrideTargets = spec.components.filter((c) =>
hasLinkageOverridePriority(c.priorityList)
);
for (const src of linkageSources) {
if (src.isLinkageAssignment) {
warnings.push(
`字段 [${src.label || src.name}] (${src.name}, type=${src.type}) 开启了联动赋值 (isLinkageAssignment=true, assignmentRule=${src.assignmentRule || "-"})`
);
} else if (src.assignmentRule) {
warnings.push(
`字段 [${src.label || src.name}] (${src.name}, type=${src.type}) 配置了联动规则 (assignmentRule=${src.assignmentRule}, 当前 isLinkageAssignment=false)`
);
}
}
if (linkageSources.length > 0 && overrideTargets.length > 0) {
const targetNames = overrideTargets.map((t) => `${t.label || t.name}(${t.name})`).join("、");
warnings.push(
`优先级覆盖风险: 字段 [${targetNames}] 的赋值优先级中 LINKAGE_ASSIGNMENT 高于 MANUALLY_FILL_IN(如 LINKAGE_ASSIGNMENT(10) > MANUALLY_FILL_IN(5)),当关联业务对象触发联动赋值时,手动填写或工作流 API 显式传入的值将被联动值覆盖!`
);
}
return {
specification: spec,
warnings,
};
}
export {
getRawBillFlow,
getFormSpecification,
type FormSpecification,
type FormSpecificationComponent,
type FormPriorityItem,
};
export {
translateBillFlowToMarkdown,
formatBillFlowOperator,
translateBillFlowAction,
translateBillFlowState,
formatAmountValue,
formatDateValue,
formatPersonValue,
formatDepartmentValue,
formatReferenceOrObject,
formatApportionSplits,
formatInlineInvoices,
formatInlineAttachments,
formatDynamicField,
type TranslatorOptions,
} from "./translator.js";