import { describe, it, expect } from "bun:test"; import { formatSingleBill, getBillReferences, getBillRelations, getBillAttachments, getBillRisk, getBillFlow, approveBill, rejectBill, transferBill, addNodeBill, commentBill, resolveBillStaffIds, parseDateFilter, parseSinceDuration, normalizeSearchFields, buildServerBillFilterBy, searchAndFormatBills, } 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(); 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: "

金额 < 不符

", 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: "

请协助

", 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: "

补充说明

", 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"]); }); }); });