1460 lines
60 KiB
TypeScript
1460 lines
60 KiB
TypeScript
import { z } from "zod";
|
||
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 {
|
||
searchRawBills,
|
||
getRawBillsByIds,
|
||
listEntitySchemas,
|
||
getRawBillFlow,
|
||
getRawBillRisk,
|
||
listActiveStaffCatalog,
|
||
getDepartmentTree,
|
||
getFeeTypeTree,
|
||
resolveAttachmentFiles,
|
||
approveBillAction,
|
||
rejectBillAction,
|
||
transferBillAction,
|
||
addNodeBillAction,
|
||
commentBillAction,
|
||
getInvoiceValidationDetail,
|
||
getDatalinkCard,
|
||
type BillActionOptions,
|
||
type BillActionTarget,
|
||
} from "./api.js";
|
||
import {
|
||
formatBillFlowOperator,
|
||
translateBillFlowAction,
|
||
translateBillFlowState,
|
||
type TranslatorOptions,
|
||
} from "./translator.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";
|
||
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 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 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 Error(`未找到单据附件: ${target}`);
|
||
|
||
const selected = fileId
|
||
? report.attachments.filter((item) => item.fileId === fileId)
|
||
: report.attachments;
|
||
if (fileId && selected.length === 0) {
|
||
throw new Error(`单据 ${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 Error(`附件下载失败 (${response.status}): ${sourceName}`);
|
||
}
|
||
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 检索
|
||
}
|
||
}
|
||
|
||
// 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;
|
||
});
|
||
|
||
if (matched.length > 0) {
|
||
return matched.map((it) => formatSingleBill(it, dictionary));
|
||
}
|
||
|
||
// 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 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 Error(`未找到单据流程 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 Error(`未找到单据或审批任务: ${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 Error(`员工关键词 [${value}] 匹配到多人,请改用员工 ID 或工号`);
|
||
throw new Error(`未找到员工 [${value}]`);
|
||
}
|
||
const id = typeof matches[0]?.id === "string" ? matches[0].id : undefined;
|
||
if (!id) throw new Error(`员工 [${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 Error(`当前账号不是该节点的合法待办人,不能执行 ${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 Error("驳回原因不能为空");
|
||
return runBillAction(client, corpId, target, "reject", options);
|
||
}
|
||
|
||
export function transferBill(client: KyInstance, corpId: string, target: string, options: BillActionOptions = {}) {
|
||
if (!options.approverIds?.length) throw new Error("转交审批至少需要一个 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 Error("加签审批至少需要一个 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 Error("评论内容不能为空");
|
||
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 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,
|
||
})),
|
||
})),
|
||
};
|
||
},
|
||
},
|
||
];
|
||
|
||
export async function getTranslatorContext(
|
||
client: KyInstance,
|
||
corpId: string,
|
||
rawFlow?: Record<string, unknown>
|
||
): 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 = Array.from(invoiceIds).map(async (id) => {
|
||
const detail = await getInvoiceValidationDetail(client, corpId, id);
|
||
if (detail) invoiceDetailMap.set(id, detail);
|
||
});
|
||
|
||
// 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 {
|
||
translateBillFlowToMarkdown,
|
||
formatBillFlowOperator,
|
||
translateBillFlowAction,
|
||
translateBillFlowState,
|
||
formatAmountValue,
|
||
formatDateValue,
|
||
formatPersonValue,
|
||
formatDepartmentValue,
|
||
formatReferenceOrObject,
|
||
formatApportionSplits,
|
||
formatInlineInvoices,
|
||
formatInlineAttachments,
|
||
formatDynamicField,
|
||
type TranslatorOptions,
|
||
} from "./translator.js";
|