Files
hose-use/src/domains/bill/bill.test.ts
T
giteaandClaude 4b4a7049a0 feat(bill): 支持未提交草稿查询与 flowId 直读
- bill list --state=draft/草稿 改走 flows/my 草稿列表,修复草稿不在
  invoice/search 台账索引中导致 --state=draft 返回空的问题
- 新增 --template/--title/--staff/--page 过滤与分页;服务端 RQL 结合
  客户端兜底匹配,模板版本化 ID 自动剥离哈希
- bill get 新增 flowId 直读通道,工作流/他人创建的草稿无需 flows/my 可见
- 补充域层与 CLI 单测、bill 文档、Skill 与 OpenAPI 参数说明

Fixes #153

Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-18 16:06:34 +08:00

1034 lines
42 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 { describe, it, expect } from "bun:test";
import {
formatSingleBill,
formatFlowAsBill,
searchAndFormatDraftBills,
getBillByCodeOrId,
getBillReferences,
getBillRelations,
getBillAttachments,
getBillRisk,
getBillFlow,
approveBill,
rejectBill,
transferBill,
addNodeBill,
commentBill,
resolveBillStaffIds,
parseDateFilter,
parseSinceDuration,
normalizeSearchFields,
buildServerBillFilterBy,
searchAndFormatBills,
traceBillFlowDetail,
} from "./tools.js";
import { RawBillItemSchema, EntitySchema } from "./types.js";
describe("Bill Domain", () => {
it("validates EntitySchema", () => {
const rawEntity = {
id: "ae1037940b1c304017c0",
code: "FEE_DETAIL",
name: "费用明细",
type: "EXPENSE",
active: true,
fields: [
{
name: "E_ae1037940b1c304017c0_payMoney",
type: "money",
label: "支付金额",
optional: false,
formula: false,
},
],
};
const parsed = EntitySchema.parse(rawEntity);
expect(parsed.id).toBe("ae1037940b1c304017c0");
expect(parsed.fields[0].label).toBe("支付金额");
});
it("validates RawBillItemSchema and formats fields with dictionary", () => {
const rawBill = {
id: "ID01TRzg7HMLcb",
code: "n0GMIM0dkQmKbS",
name: "项目&100",
corporationId: "ID01ofWoOC1wiX",
ownerId: "ID01ofWoOC1wiX:ID01ojZ2n2e0PR",
createTime: 1781682826000,
updateTime: 1781682870000,
form: {
E_test_code: "n0GMIM0dkQmKbS",
E_test_title: "测试单据标题",
E_test_stage: "expense",
E_test_state: "paid",
E_test_amount: {
standard: "100.00",
standardUnit: "元",
standardSymbol: "¥",
standardStrCode: "CNY",
},
E_test_submitterId: "staff-123",
E_test_customField: "VIP客户",
},
};
const parsed = RawBillItemSchema.parse(rawBill);
expect(parsed.id).toBe("ID01TRzg7HMLcb");
const dict = new Map<string, { label: string; type: string }>();
dict.set("E_test_customField", { label: "客户等级", type: "text" });
const formatted = formatSingleBill(parsed, dict);
expect(formatted.billId).toBe("ID01TRzg7HMLcb");
expect(formatted.billCode).toBe("n0GMIM0dkQmKbS");
expect(formatted.title).toBe("测试单据标题");
expect(formatted.stage).toBe("expense");
expect(formatted.state).toBe("paid");
expect(formatted.amount).toBe("¥100.00 CNY");
expect(formatted.details["客户等级"]).toBe("VIP客户");
});
it("resolves approval references from staff, department and fee type catalogs", async () => {
const responses = [
{
id: "backlog-1",
state: "APPROVING",
flowId: {
id: "flow-1",
form: {
code: "S26000001",
title: "团建申请",
submitterId: "corp:staff-1",
expenseDepartment: "corp:dept-2",
details: { feeTypeId: "fee-1" },
},
},
},
];
const client = {
post: async () => new Response(JSON.stringify({ items: responses })),
get: async (path: string) => {
if (path.includes("staffs/actives")) {
return new Response(JSON.stringify({ items: [{ id: "corp:staff-1", userId: "staff-1", name: "张三", code: "1001" }] }));
}
if (path.includes("departments/tree")) {
return new Response(JSON.stringify({ items: [{ id: "corp", name: "总公司", children: [{ id: "corp:dept-2", name: "研发部", children: [] }] }] }));
}
return new Response(JSON.stringify({ items: [{ id: "fee-1", name: "差旅费", code: "COST01", children: [] }] }));
},
} as any;
const result = await getBillReferences(client, "corp", "S26000001");
expect(result?.submitter?.name).toBe("张三");
expect(result?.department?.path).toBe("总公司/研发部");
expect(result?.feeTypes[0]?.name).toBe("差旅费");
expect(result?.unresolved).toEqual([]);
});
it("extracts linked loan and requisition nodes as a relation tree", async () => {
const client = {
post: async () => new Response(JSON.stringify({ value: {
id: "backlog-2",
flowId: {
id: "flow-2",
form: {
code: "E26000001",
title: "费用报销",
expenseLink: { id: "loan-1", code: "J26000001", title: "员工借款", loanMoney: { standard: "500" } },
linkRequisitionInfo: { id: "req-1", code: "Q26000001", title: "出差申请" },
},
},
} })),
} as any;
const result = await getBillRelations(client, "corp-relations", "E26000001");
expect(result?.relations.map((item) => item.id)).toEqual(["loan-1", "req-1"]);
expect(result?.relations[0]?.amount).toContain("500");
});
it("normalizes nested bill attachments and removes duplicates", async () => {
const client = {
post: async () => new Response(JSON.stringify({ value: {
id: "backlog-3",
flowId: {
form: {
code: "E26000002",
title: "带附件报销",
attachments: [
{ fileId: "file-1", key: "receipt.pdf", fileName: "receipt.pdf" },
{ fileId: "file-1", key: "receipt.pdf", fileName: "receipt.pdf" },
],
},
},
} })),
} as any;
const result = await getBillAttachments(client, "corp-files", "E26000002");
expect(result?.attachments).toHaveLength(1);
expect(result?.attachments[0]?.fileId).toBe("file-1");
expect(result?.attachments[0]?.fileName).toBe("receipt.pdf");
});
it("enriches attachment metadata with file-service download URLs", async () => {
const client = {
post: async (path: string) => {
if (path.includes("attachment/attachments/ids")) {
return new Response(JSON.stringify({
items: [{ id: "file-2", key: "receipt-key", name: "receipt.pdf", url: "https://files.example/receipt.pdf", thumbUrl: "https://files.example/thumb" }],
}));
}
if (path.includes("backlogs/search")) {
return new Response(JSON.stringify({ items: [{ id: "backlog-4", flowId: { form: { code: "E26000003", title: "附件元数据", attachments: [{ fileId: "file-2" }] } } }] }));
}
return new Response(JSON.stringify({ value: { id: "backlog-4", flowId: { form: { code: "E26000003", title: "附件元数据", attachments: [{ fileId: "file-2" }] } } } }));
},
} as any;
const result = await getBillAttachments(client, "corp-files", "E26000003");
expect(result?.attachments[0]).toMatchObject({
fileId: "file-2",
fileName: "receipt.pdf",
key: "receipt-key",
url: "https://files.example/receipt.pdf",
thumbUrl: "https://files.example/thumb",
});
});
it("normalizes risk warnings, budget state and invoice warnings", async () => {
const client = {
post: async (path: string) => {
if (path.includes("backlogs/search")) {
return new Response(JSON.stringify({ items: [{ id: "backlog-risk", flowId: { id: "flow-risk", form: { code: "S26000004", submitterId: { id: "staff-1" } } } }] }));
}
return new Response(JSON.stringify({ value: { id: "backlog-risk", flowId: { id: "flow-risk", form: { code: "S26000004", submitterId: { id: "staff-1" } } } } }));
},
get: async (path: string) => {
if (path.includes("coalition")) return new Response(JSON.stringify({ riskWarning: [{ riskLevel: "WARNING", controlName: "重复报销", messages: ["命中测试规则"] }] }));
if (path.includes("budget/report")) return new Response(JSON.stringify({ value: true, status: "OVER" }));
if (path.includes("invoice/riskWarning")) return new Response(JSON.stringify({ items: [{ type: "invoice", message: "发票抬头不一致" }] }));
return new Response(JSON.stringify({}));
},
} as any;
const result = await getBillRisk(client, "corp-risk", "S26000004");
expect(result?.flowId).toBe("flow-risk");
expect(result?.budgetExceeded).toBe(true);
expect(result?.warnings[0]?.controlName).toBe("重复报销");
expect(result?.invoiceWarnings).toHaveLength(1);
});
it("calculates approval-node dwell time and automatic skip markers", async () => {
const client = {
post: async (path: string) => {
if (path.includes("backlogs/search")) {
return new Response(JSON.stringify({ items: [{ id: "backlog-flow", flowId: { id: "flow-flow", form: { code: "S26000005", title: "流程时长" } } }] }));
}
return new Response(JSON.stringify({ value: { id: "backlog-flow", state: "APPROVING", nodeName: "财务审批", flowId: { id: "flow-flow", form: { code: "S26000005", title: "流程时长" }, logs: [
{ id: "log-1", time: 1000, operatorId: "staff-1", attributes: { nodeName: "提交" } },
{ id: "log-2", time: 2500, operatorId: null, state: "SKIPPED", attributes: { nodeName: "自动校验", isAuto: true, isSkip: true } },
], plan: { nodes: [] } } } }));
},
} as any;
const result = await getBillFlow(client, "corp-flow", "S26000005");
expect(result?.history[0]?.durationMs).toBe(1500);
expect(result?.history[1]?.automatic).toBe(true);
expect(result?.history[1]?.skipped).toBe(true);
});
it("translates flow actions, states, Ebot operators and print reminders", async () => {
const client = {
post: async (path: string) => {
if (path.includes("backlogs/search")) {
return new Response(JSON.stringify({ items: [{ id: "backlog-i18n", flowId: { id: "flow-i18n", form: { code: "B26000001" } } }] }));
}
return new Response(JSON.stringify({ value: {
id: "backlog-i18n",
state: "APPROVING",
flowId: {
id: "flow-i18n",
state: "APPROVING",
form: { code: "B26000001" },
logs: [
{ action: "freeflow.submit", state: "SUBMITTED", operatorId: "staff-1", attributes: { nodeName: "提交" } },
{ action: "freeflow.autoAgree", state: "APPROVED", operatorId: "ebot", attributes: { isEbotNode: true } },
{ action: "freeflow.print", state: "COMPLETED", attributes: { isAuto: true } },
],
plan: { nodes: [{ id: "node-next", name: "财务审批", type: "APPROVAL" }] },
},
} }));
},
} as any;
const result = await getBillFlow(client, "corp-i18n", "B26000001");
expect(result?.state).toBe("审批中");
expect(result?.history.map((entry) => entry.action)).toEqual(["提交送审", "自动同意", "打印单据"]);
expect(result?.history[1]?.operator?.name).toBe("Ebot (智能审批)");
expect(result?.history[2]?.nodeName).toBe("打印提醒");
expect(result?.history[0]?.rawAction).toBe("freeflow.submit");
expect(result?.history[0]?.rawState).toBe("SUBMITTED");
});
it("builds the captured approve, reject, transfer, add-node and comment payloads", async () => {
const calls: Array<{ path: string; options: any }> = [];
const client = {
post: async (path: string, options: any) => {
calls.push({ path, options });
if (path.includes("backlogs/search")) {
return new Response(JSON.stringify({ items: [{ id: "backlog-action", flowId: { id: "flow-action", form: { code: "E26000007" } } }] }));
}
if (path.includes("backlogs/id")) {
return new Response(JSON.stringify({ value: {
id: "backlog-action",
nodeId: "FLOW:node-action",
nodeName: "直接领导审批",
state: "APPROVING",
flowId: { id: "flow-action", form: { code: "E26000007" }, plan: { nodes: [] } },
} }));
}
return new Response(null, { status: 204 });
},
} as any;
await approveBill(client, "corp-action", "E26000007", { comment: "同意" });
const approveCall = calls.at(-1);
expect(approveCall?.path).toBe("api/flow/v2/backlogs/$backlog-action");
expect(approveCall?.options.json).toMatchObject({
node: { flowId: "flow-action", id: "FLOW:node-action", name: "freeflow.agree" },
comment: "同意",
name: "freeflow.agree",
});
await rejectBill(client, "corp-action", "E26000007", { comment: "金额 < 不符" });
expect(calls.at(-1)?.path).toBe("api/flow/v2/backlogs/approveListWithNode");
expect(calls.at(-1)?.options.json.data[0]).toMatchObject({
id: "backlog-action",
comment: "<p>金额 &lt; 不符</p>",
name: "freeflow.reject",
});
await transferBill(client, "corp-action", "E26000007", { approverIds: ["staff-2"] });
expect(calls.at(-1)?.options.json).toMatchObject({
approverId: ["staff-2"],
type: "SHIFT_NODE",
name: "freeflow.addnode",
});
await addNodeBill(client, "corp-action", "E26000007", { approverIds: ["staff-3"], comment: "请协助", addNodeType: "AFT_ADD_NODE" });
expect(calls.at(-1)?.options.json).toMatchObject({
approverId: ["staff-3"],
type: "AFT_ADD_NODE",
comment: "<p>请协助</p>",
name: "freeflow.addnode",
});
await commentBill(client, "corp-action", "E26000007", { comment: "补充说明" });
expect(calls.at(-1)?.path).toBe("api/flow/v1/flows/comment/$flow-action");
expect(calls.at(-1)?.options.json).toMatchObject({
id: "flow-action",
params: { comment: "<p>补充说明</p>", participants: [], attachments: [], keepItSecret: false },
name: "freeflow.comment",
});
});
it("resolves transfer and add-node people by full ID, employee code or unique name", async () => {
const client = {
get: async () => new Response(JSON.stringify({ items: [
{ id: "corp:staff-1", userId: "user-1", code: "101", name: "谢子豪" },
{ id: "corp:staff-2", userId: "user-2", code: "111", name: "沈玥妍" },
] })),
} as any;
await expect(resolveBillStaffIds(client, "corp-action", ["111", "谢子豪"])).resolves.toEqual(["corp:staff-2", "corp:staff-1"]);
});
it("translates raw bill flow into standard markdown representation", () => {
const { translateBillFlowToMarkdown } = require("./translator.js");
const rawFlow = {
flowId: {
state: "APPROVING",
form: {
code: "S26000001",
title: "我🩷吃醋",
specificationId: "ID01MCcOgJl1td:PRESET_REQUISITION_TRIP",
submitterId: { name: "谢子豪" },
requisitionDate: 1769961600000,
submitDate: 1770284988706,
requisitionMoney: { standard: "1000.00", standardStrCode: "CNY" },
details: [
{
feeTypeId: "ID01MCcOgJl1td:hotel",
feeTypeForm: {
amount: { standard: "1000", standardStrCode: "CNY" },
feeDate: 1770220800000,
city: '[{"key":"513","label":"辽宁省/大连市/大连市区"}]',
consumptionReasons: "今日在大连见客户",
detailId: "ID01QkCjK2m47Z",
detailNo: 1,
},
},
],
},
},
};
const markdown = translateBillFlowToMarkdown(rawFlow);
expect(markdown).toContain("# 单据:S26000001");
expect(markdown).toContain("- **状态**: 审批中 (approving)");
expect(markdown).toContain("- **单据模板**: `差旅申请单`");
expect(markdown).toContain("- **标题**: `我🩷吃醋`");
expect(markdown).toContain("- **提交人**: 谢子豪");
expect(markdown).toContain("- **申请金额**: CNY 1000.00");
expect(markdown).toContain("### 费用明细(共 1 条)");
expect(markdown).toContain("- **城市**: 辽宁省/大连市/大连市区");
expect(markdown).toContain("- **消费事由**: `今日在大连见客户`");
});
it("modular translator formatting functions format scalar and complex types properly", () => {
const {
formatAmountValue,
formatDateValue,
formatPersonValue,
formatDepartmentValue,
formatReferenceOrObject,
formatApportionSplits,
formatInlineAttachments,
formatInlineInvoices,
} = require("./translator.js");
// Amount
expect(formatAmountValue({ standard: "350", standardStrCode: "CNY" })).toBe("CNY 350.00");
expect(formatAmountValue(12.5)).toBe("CNY 12.50");
expect(formatAmountValue("¥100")).toBe("CNY 100.00");
// Date
expect(formatDateValue(1788364800000)).toMatch(/2026-09-03/);
expect(formatDateValue(1788364800000, true)).toMatch(/2026-09-03 \d{2}:\d{2}/);
// Person
const staffMap = new Map([["staff-1", { name: "张三", code: "ZS01" }]]);
expect(formatPersonValue("staff-1", staffMap)).toBe("张三(ZS01)");
expect(formatPersonValue({ name: "李四", code: "LS02" })).toBe("李四(LS02)");
// Department
const deptMap = new Map([["dept-1", { path: "总公司/财务部" }]]);
expect(formatDepartmentValue("dept-1", deptMap)).toBe("总公司/财务部");
expect(formatDepartmentValue({ fullPath: "总公司/研发部" })).toBe("总公司/研发部");
// Reference & Objects (Supplier, Bank, Dimension)
const dimMap = new Map([
["ID_dim_1", { name: "钰泰半导体股份有限公司", code: "ETA" }],
["ID_biz_1", { name: "费用", code: "CODE2" }],
]);
expect(formatReferenceOrObject("ID_dim_1", dimMap)).toBe("钰泰半导体股份有限公司(code=ETA)");
expect(formatReferenceOrObject("ID_biz_1", dimMap)).toBe("费用(code=CODE2)");
expect(formatReferenceOrObject({
supplierName: "上海戴维迪",
account: "03365200040008552",
bank: "农业银行",
})).toBe("供应商名称=上海戴维迪;账号=03365200040008552;银行=农业银行");
// Apportion splits
const apportions = [
{
apportionForm: {
apportionPercent: "100.00",
apportionMoney: { standard: "350", standardStrCode: "CNY" },
expenseDepartment: "dept-1",
},
},
];
expect(formatApportionSplits(apportions, deptMap)).toBe("分摊比例=100.00%;分摊金额=CNY 350.00;报销部门=总公司/财务部");
// Inline attachments
const attachments = [
{ fileName: "协议书.pdf", fileId: "file-01" },
{ fileName: "账单.pdf", fileId: "file-02" },
];
const attLines = formatInlineAttachments(attachments);
expect(attLines[0]).toBe("- **附件Attachment**:");
expect(attLines[1]).toBe(" 1. `协议书.pdf` (fileId=\"file-01\")");
expect(attLines[2]).toBe(" 2. `账单.pdf` (fileId=\"file-02\")");
// Inline invoices
const invoices = [
{
invoiceCode: "26312000005586052981",
fileInfo: { fileName: "发票原件.pdf", fileId: "inv-01" },
buyer: "钰泰半导体",
seller: "上海戴维迪",
approveAmount: { standard: "350.00" },
taxAmount: { standard: "19.81" },
},
];
const invLines = formatInlineInvoices(invoices);
expect(invLines[0]).toBe("- **发票列表**(1):");
expect(invLines.join("\n")).toContain("发票号码: 26312000005586052981");
expect(invLines.join("\n")).toContain("原始文件名: 发票原件.pdf");
expect(invLines.join("\n")).toContain("购方: 钰泰半导体");
expect(invLines.join("\n")).toContain("销方: 上海戴维迪");
expect(invLines.join("\n")).toContain("价税合计: CNY 350.00");
});
it("translates full bill preserving relative attachment and invoice positions", () => {
const { translateBillFlowToMarkdown } = require("./translator.js");
const complexFlow = {
flowId: {
state: "APPROVING",
form: {
code: "B26002288",
title: "方镕霖的8月图文快印的对公付款",
specificationId: "ID_PAYMENT",
submitDate: 1788415807829,
description: "戴维迪图文快印8月月结费用,¥350.00",
法人实体: "dim_eta",
expenseDepartment: "dept_admin",
u_提交人部门: "dept_admin",
u_经常交易供应商: "上海戴维迪图文制作有限公司",
payMoney: { standard: "350.00", standardStrCode: "CNY" },
expenseMoney: { standard: "350.00", standardStrCode: "CNY" },
u_本单税额: { standard: "19.81", standardStrCode: "CNY" },
details: [
{
feeTypeId: "fee_print",
feeTypeForm: {
amount: { standard: "350.00", standardStrCode: "CNY" },
feeDate: 1788364800000,
consumptionReasons: "8月图文快印",
detailId: "DETAIL_01",
detailNo: 1,
u_业务类型: "dim_biz_fee",
attachments: [
{ fileName: "18-1-服务框架协议书.pdf", fileId: "ID01TvInwhsEwf" },
{ fileName: "钰泰账单.pdf", fileId: "ID01VWUmNcRryf" },
],
invoiceForm: {
invoices: [
{
invoiceCode: "26312000005586052981",
buyer: "钰泰半导体股份有限公司",
seller: "上海戴维迪图文制作有限公司",
approveAmount: { standard: "350.00", standardStrCode: "CNY" },
taxAmount: { standard: "19.81", standardStrCode: "CNY" },
},
],
},
apportions: [
{
apportionForm: {
apportionPercent: "100.00",
apportionMoney: { standard: "350.00", standardStrCode: "CNY" },
expenseDepartment: "dept_admin",
},
},
],
},
},
],
},
},
};
const options = {
dimensionItemMap: new Map([
["dim_eta", { name: "钰泰半导体股份有限公司", code: "ETA" }],
["dim_biz_fee", { name: "费用", code: "CODE2" }],
]),
departmentMap: new Map([
["dept_admin", { path: "钰泰半导体/行政中心/人事行政部" }],
]),
feeTypeMap: new Map([
["fee_print", { name: "图文快印费", path: "办公费/图文快印费" }],
]),
};
const md = translateBillFlowToMarkdown(complexFlow, options);
// 验证顶层关键字段不再丢失
expect(md).toContain("- **单号**: `B26002288`");
expect(md).toContain("- **法人实体**: 钰泰半导体股份有限公司(code=ETA)");
expect(md).toContain("- **费用承担部门**: 钰泰半导体/行政中心/人事行政部");
expect(md).toContain("- **提交人部门**: 钰泰半导体/行政中心/人事行政部");
expect(md).toContain("- **事由**: `戴维迪图文快印8月月结费用,¥350.00`");
expect(md).toContain("- **经常交易供应商**: 上海戴维迪图文制作有限公司");
expect(md).toContain("- **本单税额**: CNY 19.81");
expect(md).toContain("- **支付金额**: CNY 350.00");
// 验证明细 1 内部原位挂载发票列表与附件列表
expect(md).toContain("#### 明细 1");
expect(md).toContain("- **费用类型**: 办公费/图文快印费(name=图文快印费)");
expect(md).toContain("- **发票列表**(1):");
expect(md).toContain("发票号码: 26312000005586052981");
expect(md).toContain("购方: 钰泰半导体股份有限公司");
expect(md).toContain("销方: 上海戴维迪图文制作有限公司");
expect(md).toContain("- **业务类型**: 费用(code=CODE2)");
expect(md).toContain("- **费用归属分摊**: 分摊比例=100.00%;分摊金额=CNY 350.00;报销部门=钰泰半导体/行政中心/人事行政部");
expect(md).toContain("- **附件Attachment**:");
expect(md).toContain("1. `18-1-服务框架协议书.pdf` (fileId=\"ID01TvInwhsEwf\")");
expect(md).toContain("2. `钰泰账单.pdf` (fileId=\"ID01VWUmNcRryf\")");
});
describe("Server-Side Filter & Date Helpers", () => {
it("parses relative since durations accurately", () => {
expect(parseSinceDuration("1h")).toBe(3600 * 1000);
expect(parseSinceDuration("7d")).toBe(7 * 86400 * 1000);
expect(parseSinceDuration("30d")).toBe(30 * 86400 * 1000);
expect(parseSinceDuration("2w")).toBe(14 * 86400 * 1000);
expect(parseSinceDuration("invalid")).toBeUndefined();
expect(parseSinceDuration(undefined)).toBeUndefined();
});
it("parses date filter strings and end-of-day offsets", () => {
expect(parseDateFilter("1788220800000")).toBe(1788220800000);
expect(parseDateFilter(1788220800000)).toBe(1788220800000);
const startMs = parseDateFilter("2026-09-01");
expect(typeof startMs).toBe("number");
const endMs = parseDateFilter("2026-09-01", true);
expect(typeof endMs).toBe("number");
expect((endMs ?? 0) > (startMs ?? 0)).toBe(true);
});
it("builds WAF-safe server filterBy expressions with .in() pattern", () => {
const empty = buildServerBillFilterBy({});
expect(empty).toBe("(active.in(true))");
const codeFilter = buildServerBillFilterBy({ code: "n140LKxUbHkGUU" });
expect(codeFilter).toContain('(code.in("n140LKxUbHkGUU"))');
expect(codeFilter).toContain("(active.in(true))");
const keywordFilter = buildServerBillFilterBy({ keyword: "打车" });
expect(keywordFilter).toContain('INSTR(name, "打车") > 0');
expect(keywordFilter).toContain('INSTR(code, "打车") > 0');
expect(keywordFilter).toContain('INSTR(form, "打车") > 0');
const timeFilter = buildServerBillFilterBy({ since: "7d" });
expect(timeFilter).toContain("createTime >");
const inactiveFilter = buildServerBillFilterBy({ active: false });
expect(inactiveFilter).toBe("(active.in(false))");
});
it("normalizes searchFields parameter correctly", () => {
expect(normalizeSearchFields()).toEqual(["name", "code", "form"]);
expect(normalizeSearchFields(undefined)).toEqual(["name", "code", "form"]);
expect(normalizeSearchFields("")).toEqual(["name", "code", "form"]);
expect(normalizeSearchFields("name,code")).toEqual(["name", "code"]);
expect(normalizeSearchFields(" name , code , form ")).toEqual(["name", "code", "form"]);
expect(normalizeSearchFields(["name", "form"])).toEqual(["name", "form"]);
expect(normalizeSearchFields([" ", "code"])).toEqual(["code"]);
expect(normalizeSearchFields([])).toEqual(["name", "code", "form"]);
});
it("builds multi-field composite OR and single-field RQL based on searchFields", () => {
// Default: name, code, form composite OR
const defaultFilter = buildServerBillFilterBy({ keyword: "差旅" });
expect(defaultFilter).toContain(
'((INSTR(name, "差旅") > 0) || (INSTR(code, "差旅") > 0) || (INSTR(form, "差旅") > 0))'
);
// Single field: direct INSTR without outer ||
const singleFieldFilter = buildServerBillFilterBy({
keyword: "差旅",
searchFields: "name",
});
expect(singleFieldFilter).toContain('(INSTR(name, "差旅") > 0)');
expect(singleFieldFilter).not.toContain("||");
// Multiple explicit fields array: composite OR
const multiArrayFilter = buildServerBillFilterBy({
keyword: "差旅",
searchFields: ["code", "form"],
});
expect(multiArrayFilter).toContain(
'((INSTR(code, "差旅") > 0) || (INSTR(form, "差旅") > 0))'
);
expect(multiArrayFilter).not.toContain("INSTR(name,");
// Multiple comma-separated string fields: composite OR
const multiStringFilter = buildServerBillFilterBy({
keyword: "差旅",
searchFields: "name,code",
});
expect(multiStringFilter).toContain(
'((INSTR(name, "差旅") > 0) || (INSTR(code, "差旅") > 0))'
);
expect(multiStringFilter).not.toContain("INSTR(form,");
});
it("filters bills in memory accurately based on searchFields", async () => {
const mockRawBills = [
{
id: "bill-1",
code: "CODE-TAXI",
name: "办公用品采购",
form: {},
createTime: 1000,
updateTime: 1000,
},
{
id: "bill-2",
code: "CODE-OFFICE",
name: "打车报销",
form: {},
createTime: 2000,
updateTime: 2000,
},
{
id: "bill-3",
code: "CODE-MEAL",
name: "餐饮费用",
form: { description: "打车去餐厅" },
createTime: 3000,
updateTime: 3000,
},
];
const client = {
get: async (path: string) => {
if (path.includes("entities")) {
return new Response(JSON.stringify({ items: [] }));
}
return new Response(JSON.stringify({}));
},
post: async () => new Response(JSON.stringify({ count: 3, items: mockRawBills })),
} as any;
// 1. Search only 'name': only bill-2 matches
const resName = await searchAndFormatBills(client, "test-corp", {
keyword: "打车",
searchFields: "name",
});
expect(resName.items.map((b) => b.billId)).toEqual(["bill-2"]);
// 2. Search only 'code': only bill-1 matches (CODE-TAXI)
const resCode = await searchAndFormatBills(client, "test-corp", {
keyword: "TAXI",
searchFields: "code",
});
expect(resCode.items.map((b) => b.billId)).toEqual(["bill-1"]);
// 3. Search 'form': only bill-3 matches
const resForm = await searchAndFormatBills(client, "test-corp", {
keyword: "餐厅",
searchFields: "form",
});
expect(resForm.items.map((b) => b.billId)).toEqual(["bill-3"]);
// 4. Search default (name, code, form): bill-2 and bill-3 match '打车'
const resDefault = await searchAndFormatBills(client, "test-corp", {
keyword: "打车",
});
expect(resDefault.items.map((b) => b.billId)).toEqual(["bill-2", "bill-3"]);
});
});
describe("Bill Draft Listing", () => {
const draftItems = [
{
flow: {
id: "flow-draft-1",
state: "draft",
formType: "payment",
createTime: 1781682826000,
updateTime: 1781682870000,
},
form: {
code: "FK26000001",
title: "付款草稿",
specificationId: { id: "spec-pay", name: "对公付款单" },
submitterId: { id: "staff-1", name: "张三", code: "1001" },
payMoney: { standard: "1200.00", standardSymbol: "¥", standardStrCode: "CNY" },
},
},
{
flow: {
id: "flow-draft-2",
state: "draft",
formType: "expense",
createTime: 1781682926000,
updateTime: 1781682970000,
},
form: {
code: "BX26000002",
title: "报销草稿",
specificationId: { id: "spec-exp", name: "报销单" },
submitterId: { id: "staff-2", name: "李四", code: "1002" },
expenseMoney: { standard: "88.00", standardSymbol: "¥", standardStrCode: "CNY" },
},
},
];
it("formats flows/my items that carry top-level form separately from flow", () => {
const bill = formatFlowAsBill(draftItems[0]!, new Map());
expect(bill.billId).toBe("flow-draft-1");
expect(bill.billCode).toBe("FK26000001");
expect(bill.billName).toBe("付款草稿");
expect(bill.state).toBe("draft");
expect(bill.stage).toBe("payment");
expect(bill.amount).toContain("1200.00");
expect(bill.submitterId).toContain("张三");
expect(bill.createTime).not.toBe("");
});
it("queries flows/my for drafts and applies server plus client filters", async () => {
const posts: Array<{ url: string; payload: any }> = [];
const client = {
post: async (url: string, payload: any) => {
posts.push({ url, payload });
if (url.includes("datalink/entity/search")) {
return new Response(JSON.stringify({ items: [] }));
}
if (url.endsWith("/flows/my")) {
return new Response(JSON.stringify({ count: 2, items: draftItems }));
}
return new Response(JSON.stringify({}));
},
} as any;
const result = await searchAndFormatDraftBills(client, "corp-draft-list", {
title: "付款",
templateId: "spec-pay",
submitterIds: ["staff-1"],
start: 20,
count: 10,
since: "7d",
});
expect(result.total).toBe(2);
expect(result.returned).toBe(1);
expect(result.items[0]?.billId).toBe("flow-draft-1");
expect(result.items[0]?.billCode).toBe("FK26000001");
const draftRequest = posts.find((post) => post.url.endsWith("/flows/my"));
expect(draftRequest).toBeDefined();
const filterBy = draftRequest!.payload.json.filterBy as string;
expect(filterBy).toContain('(state.in("draft"))');
expect(filterBy).toContain('INSTR(form.title, "付款")');
expect(filterBy).toContain('INSTR(form.specificationId, "spec-pay")');
expect(filterBy).toContain('INSTR(form.submitterId, "staff-1")');
expect(filterBy).toContain("createTime >");
expect(draftRequest!.payload.json.limit).toEqual({ start: 20, count: 10 });
expect(draftRequest!.payload.json.orderBy).toEqual([{ value: "createTime", order: "DESC" }]);
expect(draftRequest!.payload.searchParams).toMatchObject({
corpId: "corp-draft-list",
type: "home5",
delegatedFilter: "DELEGATE_TO_ME",
});
});
it("supports the compact flows/my shape: specification field and submitDate as createTime", async () => {
const client = {
post: async (url: string) => {
if (url.includes("datalink/entity/search")) {
return new Response(JSON.stringify({ items: [] }));
}
if (url.endsWith("/flows/my")) {
return new Response(JSON.stringify({
count: 1,
items: [{
flow: { id: "flow-compact", state: "draft" },
form: {
code: "BX26000009",
title: "紧凑草稿",
type: "expense",
specification: { id: "spec-exp:0123456789abcdef0123456789abcdef", name: "报销单" },
submitterId: { id: "staff-1", name: "张三", code: "1001" },
amount: { standard: "5.00", standardSymbol: "¥", standardStrCode: "CNY" },
submitDate: 1794989105307,
},
}],
}));
}
return new Response(JSON.stringify({}));
},
} as any;
const result = await searchAndFormatDraftBills(client, "corp-draft-compact", {
templateId: "spec-exp",
});
expect(result.returned).toBe(1);
expect(result.items[0]).toMatchObject({
billId: "flow-compact",
billCode: "BX26000009",
stage: "expense",
state: "draft",
});
expect(result.items[0]?.createTime).not.toBe("");
expect(result.items[0]?.amount).toContain("5.00");
});
it("reads a workflow-created draft by flowId even when flows/my is empty", async () => {
const posts: string[] = [];
const client = {
post: async (url: string) => {
posts.push(url);
if (url.includes("datalink/entity/search")) {
return new Response(JSON.stringify({ items: [] }));
}
if (url.includes("flows/flowId/")) {
return new Response(JSON.stringify({
value: {
id: "ID01DRAFTFLOW",
state: "draft",
form: {
code: "FD26000001",
title: "工作流付款草稿",
specificationId: { id: "spec-pay", name: "对公付款单" },
payMoney: { standard: "66.00", standardSymbol: "¥", standardStrCode: "CNY" },
},
},
}));
}
if (url.includes("flows/my") || url.includes("flows/approved")) {
return new Response(JSON.stringify({ items: [] }));
}
return new Response(JSON.stringify({ items: [] }));
},
} as any;
const bills = await getBillByCodeOrId(client, "corp-draft-flow", "ID01DRAFTFLOW");
expect(posts.some((url) => url.includes("flows/flowId/$ID01DRAFTFLOW"))).toBe(true);
expect(bills).toHaveLength(1);
expect(bills[0]?.billId).toBe("ID01DRAFTFLOW");
expect(bills[0]?.billCode).toBe("FD26000001");
expect(bills[0]?.state).toBe("draft");
expect(bills[0]?.amount).toContain("66.00");
});
});
describe("traceBillFlowDetail 全域穿透诊断与待办根因分析", () => {
it("待审批状态:精准解析提报人、金额、当前节点与待办审批人,判定可审批", async () => {
const mockRawFlow = {
id: "backlog-101",
state: "APPROVING",
flowId: {
id: "flow-101",
state: "APPROVING",
form: {
code: "BX-20261014-001",
title: "差旅费用报销单",
expenseMoney: { amount: "1280.50" },
submitDate: 1781682826000,
submitterId: { id: "staff-1", name: "张三", code: "ZS01" },
expenseDepartment: { name: "研发部" },
specificationId: { id: "spec-bx", name: "日常报销单" },
},
plan: {
nextNodeId: "node-2",
nodes: [
{ id: "node-1", name: "提单", state: "PROCESSED" },
{ id: "node-2", name: "直属主管审批", state: "APPROVING", approverId: { id: "staff-2", name: "李主管", code: "LZ01" } },
],
},
logs: [
{
action: "SUBMIT",
time: 1781682826000,
operatorId: { id: "staff-1", name: "张三" },
attributes: { nodeName: "提单", comment: "请领导审批" },
},
],
},
};
const client = {
post: async (path: string) => {
if (path.includes("backlogs/search")) {
return new Response(JSON.stringify({ items: [mockRawFlow] }));
}
if (path.includes("backlogs/id")) {
return new Response(JSON.stringify({ value: mockRawFlow }));
}
return new Response(JSON.stringify({ items: [] }));
},
} as any;
const report = await traceBillFlowDetail(client, "test-corp", "BX-20261014-001");
expect(report.found).toBe(true);
expect(report.billCode).toBe("BX-20261014-001");
expect(report.amount).toBe("¥ 1280.50");
expect(report.submitter?.name).toBe("张三");
expect(report.department).toBe("研发部");
expect(report.state).toBe("审批中");
expect(report.currentNode?.name).toBe("直属主管审批");
expect(report.pendingApprovers).toHaveLength(1);
expect(report.pendingApprovers[0].name).toBe("李主管");
expect(report.diagnostic.stage).toBe("APPROVING");
expect(report.diagnostic.canApprove).toBeNull();
expect(report.diagnostic.summary).toContain("待办审批人: 李主管");
expect(report.timeline).toHaveLength(1);
expect(report.timeline[0].action).toBe("SUBMIT");
});
it("待出纳打款节点 (PAYING):精准识别并诊断 400 根因与排障建议", async () => {
const mockRawFlow = {
id: "backlog-paying-01",
state: "APPROVING",
nodeName: "出纳打款",
flowId: {
id: "flow-paying-01",
state: "PAYING",
form: {
code: "ZJ-20261014-999",
title: "对公转账调拨",
payMoney: "50000.00",
specificationId: { id: "spec-zj", name: "资金调拨单" },
},
plan: {
nodes: [
{ id: "n1", name: "财务复核", state: "PROCESSED" },
{ id: "n2", name: "出纳打款", state: "APPROVING" },
],
},
logs: [
{
action: "AGREE",
time: 1781683000000,
operatorId: { id: "ebot_system", name: "ebot" },
attributes: { isEbotNode: true, nodeName: "智能审核", comment: "风控核验通过" },
},
],
},
};
const client = {
post: async () => new Response(JSON.stringify({ value: mockRawFlow })),
} as any;
const report = await traceBillFlowDetail(client, "test-corp", "ZJ-20261014-999");
expect(report.found).toBe(true);
expect(report.diagnostic.stage).toBe("PAYING");
expect(report.diagnostic.canApprove).toBe(false);
expect(report.diagnostic.stageLabel).toBe("待支付 / 出纳打款");
expect(report.diagnostic.summary).toContain("出纳打款");
expect(report.diagnostic.advice).toContain("400");
expect(report.timeline[0].operator?.name).toBe("Ebot (智能审批)");
expect(report.timeline[0].automatic).toBe(true);
});
for (const nodeName of ["出纳审批", "支付复核", "普通审批"]) {
it(`uses actual state instead of the display name: ${nodeName}`, async () => {
const raw = { id: "backlog", state: "APPROVING", nodeName, flowId: { id: "flow", state: "APPROVING", form: {}, plan: { nextNodeId: "node", nodes: [{ id: "node", name: nodeName, type: "APPROVAL", approverId: "staff" }] } } };
const client = { post: async () => new Response(JSON.stringify({ value: raw })) } as any;
const result = await traceBillFlowDetail(client, "corp", "ID01-record");
expect(result.diagnostic.stage).toBe("APPROVING");
expect(result.diagnostic.canApprove).toBeNull();
expect(result.diagnostic.advice).toContain("实际待办");
});
}
it("单据不存在时返回友好未找到诊断报告", async () => {
const client = {
post: async () => new Response(JSON.stringify({ items: [] })),
} as any;
const report = await traceBillFlowDetail(client, "test-corp", "NOT-EXIST-999");
expect(report.found).toBe(false);
expect(report.target).toBe("NOT-EXIST-999");
expect(report.diagnostic.canApprove).toBe(false);
expect(report.diagnostic.stage).toBe("UNKNOWN");
expect(report.diagnostic.advice).toContain("请核对单号是否准确");
});
});
});